Merge main into feat/print-template-browser-folders

This commit is contained in:
dotCooCoo committed 2026-11-05 17:21:16 -08:00
commit f9475fffe2
297 files changed
+23014 -1673

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
name: CI (Windows)
# The Windows leg of the gate: clippy and the tests of the crates with Windows-only code, on pull
# requests and pushes to main that touch that code, and on pull requests labelled `full-ci`.
# The Linux gate (ci.yml) still runs everything else on every pull request.
#
# Not the full `cargo xtask ci`: on a cold windows-latest runner that is well over an hour, and
# its wasm, layers, assets and parity steps don't differ by platform. What does is the
# `cfg(windows)` code (title bar theme, monitor profiles, file handling) and its tests.
on:
push:
branches: [main]
pull_request:
# `labeled`: adding `full-ci` starts it. Other labels skip (see concurrency and the scope job).
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# Its own group, so the Windows leg never cancels the Linux gate. A newer push to a PR branch
# cancels its older run; a label other than `full-ci` gets a group of its own, so it cancels nothing.
concurrency:
group: ci-windows-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ github.event.action == 'labeled' && github.event.label.name != 'full-ci' && format('-label-{0}', github.run_id) || '' }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
windows-scope:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
uses: storytold/craft-common-actions/.github/workflows/changed-paths.yml@main
with:
label: full-ci
# The crates and files with `cfg(windows)` code, and what decides how they build: their
# manifests and the lockfile (a dependency bump can break only Windows).
paths: |
.github/workflows/ci-windows.yml
apps/lightcraft/*
apps/lightcraft-cli/src/bench_cull.rs
apps/lightcraft-cli/tests/it/cli.rs
apps/lightcraft-cli/Cargo.toml
crates/wincolor/*
crates/ui-egui/src/theme.rs
crates/ui-egui/src/panels/left/local.rs
crates/ui-egui/src/menus/files.rs
crates/ui-egui/src/dialogs/settings/performance.rs
crates/catalog/src/safe_file.rs
crates/catalog/Cargo.toml
crates/engine/src/originals.rs
crates/engine/src/import/scan.rs
crates/engine/src/walk.rs
crates/engine/src/doc_path.rs
crates/engine/src/rename/*
crates/engine/src/cmd/geocode.rs
crates/engine/src/tests/sync.rs
crates/engine/src/tests/import.rs
crates/engine/Cargo.toml
crates/ui-egui/Cargo.toml
Cargo.toml
Cargo.lock
rust-toolchain.toml
.cargo/*
gate-windows:
needs: windows-scope
if: needs.windows-scope.outputs.matched == 'true'
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-latest"]'
# Same craft-fonts commit as ci.yml and release.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
targets: ""
tools: ""
timeout-minutes: 90
windows-command: |
pkgs=(-p lightcraft-wincolor -p lightcraft-catalog -p lightcraft-engine -p lightcraft-ui-egui -p lightcraft -p lightcraft-cli)
cargo clippy "${pkgs[@]}" --all-targets --keep-going -- -D warnings
cargo test "${pkgs[@]}" --lib --bins --tests --no-fail-fast
+3
View File
@@ -24,6 +24,9 @@ jobs:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
timeout-minutes: 90
# A green run takes about 40 min. A hung test is stopped at 80 min, so the log lists the
# processes still running and the leg fails as timed out instead of being cancelled at 90.
gate-timeout-minutes: 80
# xtask ci runs cargo test: the demo scene cache is per process, so nextest is slower here.
tools: ""
packages: >-
+22 -9
View File
@@ -14,7 +14,7 @@ LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructi
4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row
tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut).
When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` /
`docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
`docs/target-app-parity.md` when a listed gap closes (add a row to each doc's revision history; the header line keeps only `Last reviewed`, `Target` and the `Changes` link, never a `Last updated` date or a change note, which every PR would edit and conflict on); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
path the tracker cites still exists, and `cargo xtask parity --write` refreshes its summary.
5. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's.
@@ -38,9 +38,10 @@ of it.
"unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]`
+ `.expect("why it can't fail")`.
- **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed
allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new
unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe
fallback where possible, and a line here naming it.
allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile
Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every
other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper
crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it.
- **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or
arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative
casts to `usize`; cap allocations sized by input; slice strings only at char boundaries.
@@ -49,10 +50,15 @@ of it.
- **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped
panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native.
- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix.
- Enforced by clippy: root `clippy.toml` allows unwrap/expect/panic in tests only; indexing is not denied. Every production crate
root (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Not `[workspace.lints]`: those would also hit
integration tests, examples and benches. New crates start with the attribute.
- Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace
denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with
`[lints] workspace = true`, and `sysmem` repeats those denies in its local lint table. Every production crate root
(`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include
`[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include
the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots`
(part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib`
web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception).
## Non-negotiables
- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…).
@@ -61,7 +67,7 @@ of it.
- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec.
- **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, wasm).
- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment.
## Assets: icons, images, fonts (ABSOLUTE RULE — never violate)
@@ -123,6 +129,12 @@ of it.
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG.
- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`.
- **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it
passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with
`#[ignore = "flaky: #<issue>"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its
own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that
hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under
nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do.
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
@@ -154,4 +166,5 @@ evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the work
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- `ci.yml` is the Linux gate, on every pull request. `ci-windows.yml` adds a Windows leg (clippy and tests of the crates with `cfg(windows)` code) when a pull request changes the paths it lists; add the `full-ci` label to run it on any other pull request. When you add `cfg(windows)` code in a new file, add the file to its `paths` in a CI PR.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
+16 -6
View File
@@ -14,7 +14,7 @@ LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructi
4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row
tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut).
When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` /
`docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
`docs/target-app-parity.md` when a listed gap closes (add a row to each doc's revision history; the header line keeps only `Last reviewed`, `Target` and the `Changes` link, never a `Last updated` date or a change note, which every PR would edit and conflict on); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
path the tracker cites still exists and that `docs/gaps.md` lists each gap once, and `cargo xtask parity --write`
refreshes its summary.
5. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's.
@@ -39,9 +39,10 @@ of it.
"unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]`
+ `.expect("why it can't fail")`.
- **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed
allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new
unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe
fallback where possible, and a line here naming it.
allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile
Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every
other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper
crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it.
- **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or
arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative
casts to `usize`; cap allocations sized by input; slice strings only at char boundaries.
@@ -56,7 +57,9 @@ of it.
(`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include
`[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include
the attribute before modules or other crate items; crate-level `//!` documentation may precede it.
the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots`
(part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib`
web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception).
## Non-negotiables
- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…).
@@ -70,7 +73,7 @@ of it.
- **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages'
tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR
tests, layers, assets, roots, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR
(`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see
the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`).
- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment.
@@ -137,6 +140,12 @@ of it.
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG.
- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`.
- **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it
passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with
`#[ignore = "flaky: #<issue>"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its
own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that
hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under
nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do.
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
@@ -153,4 +162,5 @@ evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the work
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- `ci.yml` is the Linux gate, on every pull request. `ci-windows.yml` adds a Windows leg (clippy and tests of the crates with `cfg(windows)` code) when a pull request changes the paths it lists; add the `full-ci` label to run it on any other pull request. When you add `cfg(windows)` code in a new file, add the file to its `paths` in a CI PR.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
Generated
+22 -14
View File
@@ -1246,7 +1246,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=a231e517c3b371e1bf0ee8af71ed807424a9a05d#a231e517c3b371e1bf0ee8af71ed807424a9a05d"
dependencies = [
"chrono",
"dunce",
@@ -2139,6 +2139,16 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "fs4"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5"
dependencies = [
"rustix 1.1.5",
"windows-sys 0.61.2",
]
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -3589,12 +3599,14 @@ dependencies = [
"lightcraft-sysmem",
"lightcraft-testkit",
"lightcraft-ui-egui",
"lightcraft-wincolor",
"log",
"muda",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"pollster 1.0.1",
"raw-window-handle",
"rfd",
"serde_json",
"winit",
@@ -3732,6 +3744,7 @@ dependencies = [
"ab_glyph",
"chrono",
"craft-docpath",
"fs4",
"harfrust 0.13.3",
"jxl-oxide",
"libc",
@@ -4080,6 +4093,14 @@ dependencies = [
"web-sys",
]
[[package]]
name = "lightcraft-wincolor"
version = "0.18.0"
dependencies = [
"lightcraft-testkit",
"windows-sys 0.61.2",
]
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
@@ -8184,7 +8205,6 @@ dependencies = [
"nix",
"typed-path 0.13.0",
"windows-sys 0.61.2",
"zopfli",
]
[[package]]
@@ -8199,18 +8219,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.5.3"
+4 -1
View File
@@ -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 = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
# internal
lightcraft-denoise-core = { path = "crates/denoise-core" }
@@ -23,6 +23,7 @@ lightcraft-denoise = { path = "crates/denoise", default-features = false }
lightcraft-geom = { path = "crates/geom" }
lightcraft-faces = { path = "crates/faces" }
lightcraft-sysmem = { path = "crates/sysmem" }
lightcraft-wincolor = { path = "crates/wincolor" }
lightcraft-color = { path = "crates/color" }
lightcraft-raster = { path = "crates/raster" }
lightcraft-tiff = { path = "crates/tiff" }
@@ -58,6 +59,8 @@ log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
rayon = "1"
# free/total space of a drive (engine's low-disk alert); MIT OR Apache-2.0, pure Rust (rustix / windows-sys)
fs4 = { version = "1.1", default-features = false }
winapi-util = "0.1" # lightcraft-catalog reads a file's volume serial number and file index with it on Windows
proptest = "1"
bytemuck = { version = "1", features = ["derive"] }
+2 -2
View File
@@ -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;
- **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. 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 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);
- **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), 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)) |
| 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)) |
| 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 | ✅ |
+10 -9
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~14 points and ~340–600 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Canon CRW decoded clean-room, 6 bodies verified, 557 models verified; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; the lens profile database priority links its tracking issue #329; Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 85% of Adobe's models decode, 39% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
> **Last reviewed:** 2026-10-10 · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 · **Changes:** [revision history](#revision-history)
One-page summary of how close LightCraft is to Adobe Lightroom. Agents: read this, then pick work
from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are in
@@ -14,25 +14,25 @@ from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are
|---|---:|---|
| **Feature breadth** (checklist) | **81.6%** of 532 rows (P0 98.0%, P1 95.2%, P2 50.0%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount |
| **Feature breadth** (weighted by use) | **~77%** | estimated |
| **Ready for real work** (full target) | **~61%** (56–66%) | estimated: weighted sum over the dimensions |
| **Ready for real work** (full target) | **~62%** (57–67%) | estimated: weighted sum over the dimensions |
| **Mainstream practitioner** | **~51%** (46–56%) | estimated |
| **Essentials user** | **~65%** (60–70%) | estimated |
| Remaining to **beta** | **~340–600 h** (Opus 5.5 agent hours, ~60% parallel) | estimated |
| Remaining to **full parity** | **~1,000–1,800 h** (~70% parallel) | estimated |
| Remaining to **full parity** | **~980–1,750 h** (~70% parallel) | estimated |
Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%):
| Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates |
|---|---:|---:|---|
| Full target (ready for real work) | **~61%** | **1,000–1,800 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem |
| Mainstream practitioner | **~51%** | **450–840 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability |
| Full target (ready for real work) | **~62%** | **980–1,750 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem |
| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability |
| Essentials user | **~65%** | **160–300 h** (~50% parallelizes) | default raw look for popular cameras; launch stability; basic-slider feel; opening CR3 / HEIC files people send |
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), compressed ORF and HE NEF
open as previews, rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
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
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 blocking gaps (compressed ORF and HE NEF open as previews; Canon,
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
(import, cull, develop, save and reopen, batch looks, export) work end to end on macOS
([docs/roadmap.md](docs/roadmap.md#alpha-gate)). The three readiness numbers and their weights and discounts are in
@@ -107,13 +107,14 @@ 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 and HE NEF (28–55 h)
6. ~~Compressed ORF~~ (done 2026-11-04) 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-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
+585
View File
@@ -0,0 +1,585 @@
//! `lightcraft-cli bench-cull FOLDER`: time what culling a shoot costs, headless, on real files.
//!
//! What a wedding photographer does most is open a folder of a few thousand raws, look at each
//! one, rate it and move on. This times the engine side of each step on the files themselves (the
//! desktop app's own frame timings come from `ui.inspect` → `perf.loupeSteps`, see
//! `tools/cull-bench.py`):
//!
//! - browse: reading the folder into the Local view (`library.browse`, the whole folder);
//! - grid thumbnails: the camera JPEG at 512 px for the first screen, on as many threads as the
//! app renders with;
//! - camera preview at loupe sizes (1280, 2560) and at full size (the 100 % view), one at a time;
//! - LightCraft's render of the loupe (2560 px) from a cold source;
//! - rating: `photo.rate` on many photos in a row, journal included;
//! - import: adding N files in place to a fresh library, and copying M of them into it (`--n 0`:
//! no import).
//!
//! `--files K` reads only the first K files (by name) of the folder, as browsing reads them: a
//! sample of a folder on a network share, where reading thousands of raws takes hours.
//!
//! Each number is printed as `name: X ms wall` (median, with p95 and n), the format
//! `cargo xtask bench` parses, and the lot as one JSON object with `--json FILE`. Nothing is
//! written next to the photos: every library is made in a new folder of the run's own under
//! `--work` (default: a folder in the system temp directory; nothing already there is deleted),
//! XMP auto-write stays off, and the source folder is only read.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
use lightcraft_engine::Session;
use lightcraft_engine::catalog::PhotoId;
use serde_json::{Value, json};
const USAGE: &str = "lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]";
/// Threads the app renders thumbnails with (`Renderer::default`: cores − 1, at most 6).
fn render_threads() -> usize {
std::thread::available_parallelism().map(|n| n.get().saturating_sub(1)).unwrap_or(2).clamp(2, 6)
}
/// Median, p95 and count of `ms` (milliseconds).
fn stats(ms: &[f64]) -> Value {
if ms.is_empty() {
return Value::Null;
}
let mut v = ms.to_vec();
v.sort_by(f64::total_cmp);
let at = |q: f64| v.get(((v.len() - 1) as f64 * q).round() as usize).copied().unwrap_or(0.0);
json!({"p50": round(at(0.5)), "p95": round(at(0.95)), "max": round(at(1.0)), "n": v.len()})
}
fn round(x: f64) -> f64 {
(x * 10.0).round() / 10.0
}
fn ms_since(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1000.0
}
/// Print one result line the way `xtask bench` parses it (`name: X ms wall`).
fn line(name: &str, s: &Value) {
if let Some(p50) = s.get("p50").and_then(Value::as_f64) {
println!("{name}: {p50:.1} ms wall (p95 {} ms, n {})", s["p95"], s["n"]);
}
}
/// A new, empty folder `name` in this run's own folder; never deletes anything already there.
fn fresh_dir(root: &Path, name: &str) -> Result<PathBuf, String> {
let d = root.join(name);
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
Ok(d)
}
/// A folder of this run's own under `work`, which must not exist yet: a run never deletes or
/// reuses what is already under `--work`.
fn run_dir(work: &Path) -> Result<PathBuf, String> {
std::fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?;
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
static RUNS: AtomicUsize = AtomicUsize::new(0);
let n = RUNS.fetch_add(1, Ordering::Relaxed);
let d = work.join(format!("bench-cull-run-{}-{stamp}-{n}", std::process::id()));
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
Ok(d)
}
/// `take` items of `v` after the first `skip` (photos the stages before have read, so cold in the
/// file cache), or, when `v` has no more than `skip`, its first `take`: a small folder is measured
/// on photos already read rather than not at all.
fn sample_after<T>(v: &[T], skip: usize, take: usize) -> &[T] {
let from = if v.len() > skip { skip } else { 0 };
let rest = v.get(from..).unwrap_or_default();
rest.get(..take.min(rest.len())).unwrap_or_default()
}
/// Whether `path` names a file in `folder` (the source folder, which a run only reads), checked
/// twice: where its own entry sits (the folder holding it, the final link not followed: writing the
/// results replaces that entry, so a link to a file elsewhere that sits in the source folder, maybe
/// standing for a photo, would be replaced; CodeRabbit on #3080), and where it resolves to: a file
/// that is there by itself (a link to a photo there is the photo), a link that points nowhere yet
/// by where writing through it would create the file, and anything else by its nearest folder that
/// exists (a `--work` folder may not be there yet).
fn inside_source(path: &Path, folder: &Path) -> bool {
let Ok(folder) = std::fs::canonicalize(folder) else { return false };
entry_inside(path, &folder) || resolves_inside(path, &folder, 0)
}
/// Whether the folder holding `path`'s own entry (its nearest folder that exists, resolved) is in
/// `folder` (already resolved). The entry itself is not followed.
fn entry_inside(path: &Path, folder: &Path) -> bool {
let mut p = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
loop {
if let Ok(c) = std::fs::canonicalize(p) {
return c.starts_with(folder);
}
match p.parent() {
Some(up) if !up.as_os_str().is_empty() => p = up,
Some(_) => p = Path::new("."),
None => return false,
}
}
}
/// [`inside_source`] for a `folder` already resolved; `hops`: links followed so far (a loop of
/// links counts as inside: refused).
fn resolves_inside(path: &Path, folder: &Path, hops: u32) -> bool {
if let Ok(c) = std::fs::canonicalize(path) {
return c.starts_with(folder);
}
if let Ok(target) = std::fs::read_link(path) {
if hops >= 40 {
return true;
}
let target = path.parent().map_or_else(|| target.clone(), |dir| dir.join(&target));
return resolves_inside(&target, folder, hops + 1);
}
entry_inside(path, folder)
}
/// Refuse `--json` or `--work` in the folder being measured: nothing is written next to the photos,
/// the results and the run's libraries included. Checked before anything is made.
fn check_outputs(folder: &Path, json: Option<&Path>, work: &Path) -> Result<(), String> {
// a `..` after a folder not made yet can't be resolved now, and the run makes that folder:
// `--json NEW/../FOLDER/r.json` would pass the checks below and land in the source folder
// (CodeRabbit on #3544)
for (name, p) in [("--json", json), ("--work", Some(work))] {
if let Some(p) = p.filter(|p| p.components().any(|c| c == std::path::Component::ParentDir)) {
return Err(format!("{}: {name} must not contain \"..\"; give the folder without it", p.display()));
}
}
if let Some(j) = json.filter(|j| inside_source(j, folder)) {
return Err(format!("{}: --json must not be in the folder being measured", j.display()));
}
if inside_source(&work.join("run"), folder) {
return Err(format!("{}: --work must not be in the folder being measured", work.display()));
}
Ok(())
}
fn library(dir: &Path) -> Result<Session, String> {
let mut s = Session::new().with_fs().with_system_clock();
s.open_library(dir, false).map_err(|e| format!("{}: {e}", dir.display()))?;
// nothing is ever written next to the photos
s.execute("library.xmpPreferences", &json!({"autoWrite": false})).map_err(|e| e.to_string())?;
Ok(s)
}
pub fn run(args: &[String]) -> Result<(), String> {
let mut folder = None;
let mut n = 2000usize;
let mut copy = 200usize;
let mut work = None;
let mut json_out = None;
let mut files = None;
let mut i = 0;
while i < args.len() {
let value = |i: usize| args.get(i + 1).cloned().ok_or_else(|| format!("{} needs a value\n{USAGE}", args[i]));
match args[i].as_str() {
"--n" => {
n = value(i)?.parse().map_err(|_| "--n needs a number".to_string())?;
i += 1;
}
"--copy" => {
copy = value(i)?.parse().map_err(|_| "--copy needs a number".to_string())?;
i += 1;
}
"--files" => {
files = Some(value(i)?.parse::<usize>().map_err(|_| "--files needs a number".to_string())?);
i += 1;
}
"--work" => {
work = Some(PathBuf::from(value(i)?));
i += 1;
}
"--json" => {
json_out = Some(PathBuf::from(value(i)?));
i += 1;
}
"-h" | "--help" => {
println!("{USAGE}");
return Ok(());
}
a if a.starts_with("--") => return Err(format!("unknown option {a}\n{USAGE}")),
// (a second folder would replace the first and be timed in its place: CodeRabbit on #3583)
a if folder.is_some() => return Err(format!("{a}: one FOLDER only\n{USAGE}")),
a => folder = Some(PathBuf::from(a)),
}
i += 1;
}
let folder = folder.ok_or_else(|| USAGE.to_string())?;
if !folder.is_dir() {
return Err(format!("{}: not a folder", folder.display()));
}
let work = work.unwrap_or_else(|| std::env::temp_dir().join(format!("lightcraft-bench-cull-{}", std::process::id())));
check_outputs(&folder, json_out.as_deref(), &work)?;
let work = run_dir(&work)?;
let mut out = json!({"folder": folder.display().to_string(), "threads": render_threads()});
// --- browse: the whole folder into the Local view -------------------------------------------
let mut s = library(&fresh_dir(&work, "lib-browse")?)?;
// `--files K`: only the first K files by name, read as browsing reads them (a sample of a slow
// network folder)
let t = Instant::now();
let (photos, ids): (u64, Vec<PhotoId>) = match files {
None => {
let r = s.execute("library.browse", &json!({"path": folder.display().to_string()})).map_err(|e| e.to_string())?;
(r["photos"].as_u64().unwrap_or(0), s.visible_cloned())
}
Some(k) => {
let mut list: Vec<String> = std::fs::read_dir(&folder)
.map_err(|e| format!("{}: {e}", folder.display()))?
.flatten()
.map(|e| e.path())
.filter(|p| p.is_file() && lightcraft_engine::import::is_supported(p))
.map(|p| p.display().to_string())
.collect();
list.sort();
list.truncate(k);
let r = s.execute("library.import", &json!({"paths": list, "mode": "add", "local": true})).map_err(|e| e.to_string())?;
let ids: Vec<PhotoId> = r["imported"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(PhotoId).collect();
(ids.len() as u64, ids)
}
};
let browse_ms = ms_since(t);
let what = if files.is_some() { "first files" } else { "whole folder" };
println!("browse {photos} photos ({what}): {browse_ms:.1} ms wall");
out["browse"] = json!({"ms": round(browse_ms), "photos": photos, "perPhotoMs": round(browse_ms / photos.max(1) as f64)});
let paths: Vec<String> = ids
.iter()
.filter_map(|id| match &s.catalog.photo(*id)?.source {
lightcraft_engine::catalog::Source::File { path } => Some(path.clone()),
_ => None,
})
.collect();
if paths.is_empty() {
return Err(format!("{}: no photos", folder.display()));
}
let loader = s.media.preview_loader.clone().ok_or("no preview loader")?;
// --- grid thumbnails: the first screen, in parallel ------------------------------------------
let screen: Vec<String> = paths.iter().take(48).cloned().collect();
let next = Arc::new(AtomicUsize::new(0));
let t = Instant::now();
let per: Vec<(f64, f64)> = std::thread::scope(|sc| {
let workers: Vec<_> = (0..render_threads())
.map(|_| {
let (next, loader, screen) = (next.clone(), loader.clone(), &screen);
sc.spawn(move || {
let mut done = Vec::new();
while let Some(p) = screen.get(next.fetch_add(1, Ordering::Relaxed)) {
let a = Instant::now();
let _ = loader(p, 512);
done.push((ms_since(a), ms_since(t)));
}
done
})
})
.collect();
workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect()
});
let first = per.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
let all = per.iter().map(|p| p.1).fold(0.0, f64::max);
let each = stats(&per.iter().map(|p| p.0).collect::<Vec<_>>());
println!("grid: first thumbnail: {first:.1} ms wall");
println!("grid: {} thumbnails: {all:.1} ms wall", per.len());
line("grid: one 512 px thumbnail", &each);
out["thumbs"] = json!({"firstMs": round(first), "allMs": round(all), "count": per.len(), "each": each});
// --- camera previews at loupe sizes, one at a time (what a step costs without look-ahead) -----
let sample = sample_after(&paths, 48, 20);
for edge in [1280usize, 2560, usize::MAX] {
let ms: Vec<f64> = sample
.iter()
.map(|p| {
let a = Instant::now();
let _ = loader(p, edge);
ms_since(a)
})
.collect();
let name = if edge == usize::MAX { "camera preview full size (100 %)".to_string() } else { format!("camera preview {edge} px") };
let st = stats(&ms);
line(&name, &st);
out[if edge == usize::MAX { "cameraFull".to_string() } else { format!("camera{edge}") }] = st;
}
// --- LightCraft's loupe render (2560 px) from a cold source --------------------------------
let ms: Vec<f64> = sample_after(&ids, 80, 5)
.iter()
.filter_map(|id| {
let job = s.loupe_job(*id, 2560, 1708, true)?;
let a = Instant::now();
let r = job.run();
let t = ms_since(a);
r.rendered.is_ok().then_some(t)
})
.collect();
let st = stats(&ms);
line("loupe render 2560 px (cold)", &st);
out["loupeRender"] = st;
// --- rating: a culling pass of keypresses ---------------------------------------------------
let ms: Vec<f64> = ids
.iter()
.take(50)
.enumerate()
.filter_map(|(k, id)| {
// the key acts on the selected photo, as in the loupe
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).ok()?;
let a = Instant::now();
s.execute("photo.rate", &json!({"rating": (k % 5) + 1})).ok()?;
Some(ms_since(a))
})
.collect();
let st = stats(&ms);
line("rate one photo (journal written)", &st);
out["rate"] = st;
drop(s);
// --- import: add in place, then copy ----------------------------------------------------------
if n == 0 {
return finish(out, json_out);
}
let add: Vec<String> = paths.iter().take(n).cloned().collect();
let mut s = library(&fresh_dir(&work, "lib-add")?)?;
let t = Instant::now();
let r = s.execute("library.import", &json!({"paths": add, "mode": "add"})).map_err(|e| e.to_string())?;
let add_ms = ms_since(t);
let added = r["imported"].as_array().map(Vec::len).unwrap_or(0);
println!("import {added} photos in place: {add_ms:.1} ms wall");
out["importAdd"] = json!({"ms": round(add_ms), "photos": added, "perPhotoMs": round(add_ms / added.max(1) as f64)});
drop(s);
if copy > 0 {
let some: Vec<String> = paths.iter().take(copy).cloned().collect();
let lib = fresh_dir(&work, "lib-copy")?;
let mut s = library(&lib)?;
let t = Instant::now();
let r = s
.execute("library.import", &json!({"paths": some, "mode": "copy", "destination": lib.join("Originals").display().to_string()}))
.map_err(|e| e.to_string())?;
let copy_ms = ms_since(t);
let copied = r["imported"].as_array().map(Vec::len).unwrap_or(0);
println!("import {copied} photos by copying: {copy_ms:.1} ms wall");
out["importCopy"] = json!({"ms": round(copy_ms), "photos": copied, "perPhotoMs": round(copy_ms / copied.max(1) as f64)});
drop(s);
let _ = std::fs::remove_dir_all(&lib);
}
finish(out, json_out)
}
fn finish(out: Value, json_out: Option<PathBuf>) -> Result<(), String> {
if let Some(p) = json_out {
write_replacing(&p, serde_json::to_string_pretty(&out).unwrap_or_default().as_bytes())?;
}
println!("{}", serde_json::to_string(&out).unwrap_or_default());
Ok(())
}
/// Write `bytes` to `path` through a new file next to it, renamed over `path`: an existing `path`
/// is replaced as a name, never written into. A hard link there shares its data with another file
/// (maybe a photo in the source folder, which [`inside_source`] can't tell), and writing into it
/// would overwrite that file too (CodeRabbit on #3077). The temporary file is removed on error.
fn write_replacing(path: &Path, bytes: &[u8]) -> Result<(), String> {
use std::io::Write;
let err = |e: std::io::Error| format!("{}: {e}", path.display());
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
let name = path.file_name().ok_or_else(|| format!("{}: not a file name", path.display()))?;
static TEMPS: AtomicUsize = AtomicUsize::new(0);
let n = TEMPS.fetch_add(1, Ordering::Relaxed);
let mut tmp_name = std::ffi::OsString::from(".");
tmp_name.push(name);
tmp_name.push(format!(".{}-{n}.tmp", std::process::id()));
let tmp = dir.join(tmp_name);
let written =
std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|()| f.sync_all()));
if let Err(e) = written.and_then(|()| std::fs::rename(&tmp, path)) {
let _ = std::fs::remove_file(&tmp);
return Err(err(e));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_second_folder_is_an_error() {
let e = run(&["a".to_string(), "b".to_string()]).unwrap_err();
assert!(e.starts_with("b: one FOLDER only"), "{e}");
}
/// `--work` may hold anything: a run makes a new folder of its own there and never deletes
/// what is already in it (it used to remove `lib-browse`, `lib-add` and `lib-copy` there).
#[test]
fn a_run_never_deletes_what_is_under_work() {
// a folder this test owns (made new), so the cleanup below removes nothing else
let work = run_dir(&std::env::temp_dir()).unwrap();
let keep = work.join("lib-browse").join("keep.txt");
std::fs::create_dir_all(keep.parent().unwrap()).unwrap();
std::fs::write(&keep, b"mine").unwrap();
let a = run_dir(&work).unwrap();
let b = run_dir(&work).unwrap();
assert_ne!(a, b);
fresh_dir(&a, "lib-browse").unwrap();
assert!(fresh_dir(&a, "lib-browse").is_err(), "an existing folder is never reused");
assert_eq!(std::fs::read(&keep).unwrap(), b"mine");
let _ = std::fs::remove_dir_all(&work);
}
/// A folder too small for the disjoint samples is measured on the photos it has (CodeRabbit on #3077).
#[test]
fn a_small_folder_is_sampled_from_its_start() {
let v: Vec<u32> = (0..100).collect();
assert_eq!(sample_after(&v, 48, 20), &v[48..68]);
assert_eq!(sample_after(&v, 90, 20), &v[90..100]);
assert_eq!(sample_after(&v[..3], 48, 20), &v[..3]);
assert_eq!(sample_after(&v[..48], 48, 5), &v[..5]);
assert!(sample_after::<u32>(&[], 48, 20).is_empty());
}
/// A file link at `at` to `target`.
#[cfg(unix)]
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(target, at)
}
/// A file link at `at` to `target` (Windows: needs Developer Mode or the right to make links).
#[cfg(windows)]
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
std::os::windows::fs::symlink_file(target, at)
}
#[cfg(not(any(unix, windows)))]
fn link(_: &Path, _: &Path) -> std::io::Result<()> {
Err(std::io::Error::other("no file links here"))
}
/// `--json` naming a link (made elsewhere) to a file in the source folder is refused: writing
/// the results would follow it and overwrite a photo (CodeRabbit on #3080). So is a link that
/// points to a file not made yet in the source folder, and a loop of links.
#[test]
fn a_json_link_into_the_source_folder_is_refused() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let photo = src.join("a.jpg");
std::fs::write(&photo, b"photo").unwrap();
let to_photo = work.join("report.json");
if let Err(e) = link(&photo, &to_photo) {
let _ = std::fs::remove_dir_all(&work);
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
return;
}
assert!(inside_source(&to_photo, &src), "a link to a photo in the source folder");
let e = check_outputs(&src, Some(&to_photo), &work.join("elsewhere")).unwrap_err();
assert!(e.contains("--json"), "{e}");
let to_new = work.join("new.json");
link(&src.join("not-yet.json"), &to_new).unwrap();
assert!(inside_source(&to_new, &src), "a link to a file not made yet in the source folder");
let (x, y) = (work.join("x.json"), work.join("y.json"));
link(&y, &x).unwrap();
link(&x, &y).unwrap();
assert!(inside_source(&x, &src), "a loop of links");
let to_elsewhere = work.join("fine.json");
link(&work.join("out.json"), &to_elsewhere).unwrap();
assert!(!inside_source(&to_elsewhere, &src), "a link to a file outside is fine");
assert_eq!(std::fs::read(&photo).unwrap(), b"photo");
let _ = std::fs::remove_dir_all(&work);
}
/// `--json` naming a link that sits in the source folder and points to a file outside it is
/// refused: writing the results would replace the link itself, an entry of the source folder
/// (CodeRabbit on #3080). The link stays as it was.
#[test]
fn a_json_link_in_the_source_folder_to_a_file_outside_is_refused() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let outside = work.join("out.json");
std::fs::write(&outside, b"outside").unwrap();
let in_src = src.join("a.jpg");
if let Err(e) = link(&outside, &in_src) {
let _ = std::fs::remove_dir_all(&work);
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
return;
}
assert!(inside_source(&in_src, &src), "a link in the source folder, wherever it points");
let e = check_outputs(&src, Some(&in_src), &work.join("elsewhere")).unwrap_err();
assert!(e.contains("--json"), "{e}");
assert!(std::fs::symlink_metadata(&in_src).unwrap().file_type().is_symlink(), "the link stays");
assert_eq!(std::fs::read_link(&in_src).unwrap(), outside);
assert_eq!(std::fs::read(&outside).unwrap(), b"outside");
// a new file in the source folder (nothing there yet) is refused too
assert!(check_outputs(&src, Some(&src.join("new.json")), &work.join("elsewhere")).is_err());
let _ = std::fs::remove_dir_all(&work);
}
/// `--json` naming a hard link (made elsewhere) to a photo in the source folder passes
/// [`inside_source`] (a hard link has no target to resolve), so the results replace the link
/// instead of writing into it: the photo keeps its bytes (CodeRabbit on #3077).
#[test]
fn a_json_hard_link_to_a_photo_leaves_the_photo_alone() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let photo = src.join("a.jpg");
std::fs::write(&photo, b"photo").unwrap();
let report = work.join("report.json");
if let Err(e) = std::fs::hard_link(&photo, &report) {
let _ = std::fs::remove_dir_all(&work);
lightcraft_testkit::skip!(System, "can't make a hard link here ({e})");
return;
}
finish(json!({"browse": 1}), Some(report.clone())).unwrap();
assert_eq!(std::fs::read(&photo).unwrap(), b"photo", "the photo is unchanged");
let written: Value = serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap();
assert_eq!(written["browse"], 1);
let left: Vec<_> = std::fs::read_dir(&work).unwrap().flatten().map(|e| e.file_name()).collect();
assert_eq!(left.len(), 2, "no temporary file is left: {left:?}");
// a folder that isn't there: an error, nothing panics
assert!(write_replacing(&work.join("missing").join("r.json"), b"x").is_err());
let _ = std::fs::remove_dir_all(&work);
}
/// `--json` naming a file in the source folder is refused (CodeRabbit on #3077); elsewhere it is fine.
#[test]
fn the_results_never_go_in_the_source_folder() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let sub = fresh_dir(&src, "sub").unwrap();
assert!(inside_source(&src.join("a.png"), &src));
assert!(inside_source(&sub.join("x.json"), &src));
assert!(inside_source(&src.join("sub").join("..").join("a.png"), &src));
assert!(!inside_source(&work.join("out.json"), &src));
let _ = std::fs::remove_dir_all(&work);
}
/// `--work` in the source folder is refused before anything is made there, also when it doesn't
/// exist yet (CodeRabbit on #3077); elsewhere it is fine.
#[test]
fn the_work_folder_never_goes_in_the_source_folder() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let inside = src.join("out").join("deeper");
let e = check_outputs(&src, None, &inside).unwrap_err();
assert!(e.contains("--work"), "{e}");
assert!(check_outputs(&src, None, &src).is_err(), "the source folder itself");
assert!(!src.join("out").exists(), "nothing was made in the source folder");
assert!(check_outputs(&src, None, &work.join("elsewhere")).is_ok());
assert!(check_outputs(&src, Some(&src.join("r.json")), &work.join("elsewhere")).is_err());
let _ = std::fs::remove_dir_all(&work);
}
/// A `..` in `--json` or `--work` is refused: after a folder the run hasn't made yet it can't be
/// resolved now, and would lead into the source folder once the run makes it (CodeRabbit on #3544).
#[test]
fn a_dot_dot_in_the_outputs_is_refused() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let sneaky = work.join("new").join("..").join("src").join("r.json");
let e = check_outputs(&src, Some(&sneaky), &work.join("elsewhere")).unwrap_err();
assert!(e.contains("--json") && e.contains(".."), "{e}");
let e = check_outputs(&src, None, &work.join("new").join("..").join("src")).unwrap_err();
assert!(e.contains("--work"), "{e}");
assert!(!work.join("new").exists(), "nothing was made");
let _ = std::fs::remove_dir_all(&work);
}
}
+9
View File
@@ -11,11 +11,13 @@
//! lightcraft-cli commands [--json]
//! lightcraft-cli controls [--json]
//! lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
//! lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
//! ```
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod alloc_release;
mod bench_cull;
use std::io::Write;
use std::path::Path;
@@ -110,6 +112,12 @@ USAGE:
model, written as <model>.json to DIR (default: the profiles folder LightCraft reads,
<config>/camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then
take their colour from the profile and only their tone from their own JPEG.
lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
Time what culling a shoot costs on its own files: reading the folder (browse), the first
screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render,
rating, and importing N files in place (default 2000) and copying M (default 200). Libraries
are made in a new folder under DIR (default: the temp folder); nothing is written next to the
photos. --files K reads only the first K files by name (a sample of a slow network folder).
lightcraft-cli --version | --help
";
@@ -176,6 +184,7 @@ fn main() -> ExitCode {
Some("controls") => controls(&args[1..]),
Some("denoise-serve") => denoise_serve(&args[1..]),
Some("calibrate") => calibrate(&args[1..]),
Some("bench-cull") => bench_cull::run(&args[1..]),
Some("--version" | "-V" | "version") => {
println!("lightcraft-cli {}", env!("CARGO_PKG_VERSION"));
Ok(())
+69
View File
@@ -101,6 +101,75 @@ fn gradient_png(path: &std::path::Path) {
std::fs::write(path, png).unwrap();
}
/// PERF-CULL-5: `bench-cull` times a folder end to end and writes nothing next to the photos.
#[test]
fn bench_cull_times_a_folder_and_leaves_it_untouched() {
let dir = tmp("bench-cull-src");
std::fs::create_dir_all(&dir).unwrap();
for (seed, name) in ["a.png", "b.png", "c.png"].iter().enumerate() {
// three different pictures (the same bytes would import as one photo)
let img = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, (seed * 80) as u8, 255]);
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
std::fs::write(dir.join(name), png).unwrap();
}
// every file's name and bytes: nothing added, and no photo written into (CodeRabbit on #3577)
let listing = |d: &std::path::Path| {
let mut v: Vec<(String, Vec<u8>)> = std::fs::read_dir(d)
.unwrap()
.map(|e| e.unwrap())
.map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read(e.path()).unwrap()))
.collect();
v.sort();
v
};
let before = listing(&dir);
let work = tmp("bench-cull-work");
let json_out = tmp("bench-cull.json");
let r = Command::new(binary())
.arg("bench-cull")
.arg(&dir)
.args(["--n", "3", "--copy", "1", "--work"])
.arg(&work)
.arg("--json")
.arg(&json_out)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&r.stdout);
assert!(r.status.success(), "{stdout}{}", String::from_utf8_lossy(&r.stderr));
assert!(stdout.contains("browse 3 photos") && stdout.contains("ms wall"), "{stdout}");
let v: Value = serde_json::from_str(&std::fs::read_to_string(&json_out).unwrap()).unwrap();
assert_eq!(v["browse"]["photos"], 3);
assert_eq!(v["importAdd"]["photos"], 3);
assert_eq!(v["importCopy"]["photos"], 1);
assert_eq!(v["rate"]["n"], 3);
// a folder smaller than the samples is measured on the photos it has, not reported empty
for stage in ["camera1280", "camera2560", "cameraFull", "loupeRender"] {
assert_eq!(v[stage]["n"], 3, "{stage}: {}", v[stage]);
}
assert_eq!(listing(&dir), before, "nothing written next to the photos");
// results asked for in the source folder: refused, the photo untouched
let photo = std::fs::read(dir.join("a.png")).unwrap();
let r = Command::new(binary())
.arg("bench-cull")
.arg(&dir)
.args(["--n", "0", "--work"])
.arg(&work)
.arg("--json")
.arg(dir.join("a.png"))
.output()
.unwrap();
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("--json"), "{}", String::from_utf8_lossy(&r.stderr));
assert_eq!(std::fs::read(dir.join("a.png")).unwrap(), photo);
assert_eq!(listing(&dir), before);
// a sample of the folder, no import
let r = Command::new(binary()).arg("bench-cull").arg(&dir).args(["--files", "2", "--n", "0", "--work"]).arg(&work).output().unwrap();
let stdout = String::from_utf8_lossy(&r.stdout);
assert!(r.status.success() && stdout.contains("browse 2 photos (first files)") && !stdout.contains("import"), "{stdout}");
// a bad folder is an error, not a panic
let r = Command::new(binary()).args(["bench-cull", "/no/such/folder"]).output().unwrap();
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("not a folder"));
}
#[test]
fn calibrate_reads_raf_inputs_and_reports_bad_files() {
let input = tmp("invalid.RAF");
+4
View File
@@ -32,10 +32,14 @@ js-sys = { workspace = true }
web-sys = { workspace = true, features = [
"Blob",
"BlobPropertyBag",
"CustomEvent",
"CustomEventInit",
"CssStyleDeclaration",
"DedicatedWorkerGlobalScope",
"Document",
"DomStringList",
"Element",
"Event",
"EventTarget",
"File",
"FileList",
+632
View File
@@ -0,0 +1,632 @@
//! The bridge to a host page (issue #2270): a same-origin page embeds LightCraft in an `<iframe>`
//! (`?host=parent`) or in its own document (`data-host="page"` on the canvas). The protocol is
//! the one PdfCraft, GridCraft and DeckCraft speak, with `lightcraft:` message types:
//!
//! - `lightcraft:ready` (to the parent): `{ version }`, the app is listening.
//! - `lightcraft:failed` (to the parent): `{ error }`, the app couldn't start, or it refused a
//! `lightcraft:open` (a file larger than a library backup can hold, [`crate::backup::MAX_BYTES`]).
//! - `lightcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
//! `Uint8Array`. The photo is added to the library, as one dropped on the window is; `name`
//! gives the format (its extension), `photo.jpg` when missing.
//! - `lightcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
//! file LightCraft would otherwise download: exports and the library backup (the preset, keyword
//! and curve file dialogs have no web implementation yet). The parent stores it and reports
//! failures itself.
//! - `lightcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
//! On the web every change is written to browser storage a moment after it is made, so `dirty`
//! means "closing the page right now would lose something": a write still queued or running,
//! or changes that storage refused (quota).
//! - `lightcraft:cmd` (from the parent): `{ id, params }`, params a JSON string (`{}` when
//! missing, empty or `null`; anything but a JSON object is refused unrun, see [`crate::automation::params`]).
//! Runs the command by id, like `lightcraft.command(..)` from the page itself, and answers with
//! `lightcraft:response` `{ ok, value }` (the JSON result, or the error text).
//! Responses carry no request id (none of the sibling bridges' do): they come back in the order
//! the commands were sent, one per `cmd` that had an id; a `cmd` without one gets no response.
//!
//! Only the parent window on the page's own origin is heard or answered. A page whose origin is
//! opaque (`"null"`: a sandboxed iframe, a `data:` page) gets no bridge at all, since every other
//! opaque-origin window would then pass as the parent. A parent on another origin gets no bridge
//! either: its `location` cannot be read, and exports keep downloading. There is no `docClosed`: LightCraft has a
//! library, not documents that close.
//!
//! ## `data-host="page"` — the page's own document
//!
//! A page can also run LightCraft in its own document, no iframe: the canvas opts in with
//! `data-host="page"`, and the same messages travel as DOM `CustomEvent`s on the canvas instead
//! of `postMessage` — outward with the message's fields as the event's `detail`, inward as
//! `lightcraft:open` and `lightcraft:cmd` events the page dispatches on the canvas. Events don't
//! bubble, so two editors on one page can't hear each other, and the canvas is the only target
//! the bridge listens on.
//!
//! The message layer (what a message means, what is sent back) is plain Rust, tested natively;
//! [`Bridge`] (wasm32 only) moves it over `postMessage`, or over DOM events in page mode.
/// A message from the parent page, once understood.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Incoming {
/// `lightcraft:open`: add this photo to the library.
Open { name: String, bytes: Vec<u8> },
/// `lightcraft:cmd`: run this command (params as JSON text).
Cmd { id: String, params: String },
/// `lightcraft:open` with a file too large to keep: tell the parent why (`lightcraft:failed`).
Refused(String),
}
/// The fields of a message from the parent, as read off the event (each may be missing).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Raw {
pub kind: Option<String>,
pub name: Option<String>,
pub bytes: Option<Vec<u8>>,
pub id: Option<String>,
pub params: Option<String>,
/// The size of `bytes` when it was too large to copy (`bytes` is then `None`).
pub oversize: Option<u64>,
}
/// Why a photo of `len` bytes sent with `lightcraft:open` is refused, or `None` when it fits: one
/// larger than a library backup can hold ([`crate::backup::MAX_BYTES`]) is never copied in.
pub fn open_size_error(len: u64) -> Option<String> {
let max = crate::backup::MAX_BYTES;
(len > max).then(|| format!("the file is too large to open ({} MB; the limit is {} MB)", len >> 20, max >> 20))
}
/// The name a photo sent without one is stored under (its extension picks the decoder).
pub const DEFAULT_OPEN_NAME: &str = "photo.jpg";
impl Incoming {
/// What the parent asked for; `None` for a message type that isn't ours, an `open` without
/// bytes or a `cmd` without an id (dropped, the page's other messages are none of our business).
pub fn parse(raw: Raw) -> Option<Incoming> {
match raw.kind.as_deref() {
Some("lightcraft:open") => {
if let Some(error) = raw.oversize.and_then(open_size_error) {
return Some(Incoming::Refused(error));
}
let name = raw.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| DEFAULT_OPEN_NAME.to_string());
Some(Incoming::Open { name, bytes: raw.bytes? })
}
Some("lightcraft:cmd") => {
let id = raw.id.filter(|i| !i.trim().is_empty())?;
Some(Incoming::Cmd { id, params: raw.params.filter(|p| !p.trim().is_empty()).unwrap_or_else(|| "{}".to_string()) })
}
_ => None,
}
}
}
/// A field of a message to the parent.
#[derive(Clone, Debug, PartialEq)]
pub enum Field {
Str(String),
Bool(bool),
}
/// A message to the parent, without bytes (`lightcraft:save` carries a transferred buffer and is
/// built by the bridge itself).
#[derive(Clone, Debug, PartialEq)]
pub enum Outgoing {
Ready,
Failed(String),
Dirty(bool),
/// How a `lightcraft:cmd` ended: the JSON result, or the error text.
Response {
ok: bool,
value: String,
},
}
impl Outgoing {
/// The message's fields, `type` first.
pub fn fields(&self) -> Vec<(&'static str, Field)> {
match self {
Outgoing::Ready => vec![("type", Field::Str("lightcraft:ready".into())), ("version", Field::Str(env!("CARGO_PKG_VERSION").into()))],
Outgoing::Failed(error) => vec![("type", Field::Str("lightcraft:failed".into())), ("error", Field::Str(error.clone()))],
Outgoing::Dirty(dirty) => vec![("type", Field::Str("lightcraft:dirty".into())), ("dirty", Field::Bool(*dirty))],
Outgoing::Response { ok, value } => {
vec![("type", Field::Str("lightcraft:response".into())), ("ok", Field::Bool(*ok)), ("value", Field::Str(value.clone()))]
}
}
}
}
/// The unsaved-changes state as the parent last heard it: `lightcraft:dirty` goes out only when
/// it changes (not every frame), and a message that couldn't be sent is sent again next time.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DirtyReport {
reported: Option<bool>,
}
impl DirtyReport {
/// `Some(message)` when `dirty` differs from what the parent knows; call [`DirtyReport::sent`]
/// once it went out.
pub fn change(&self, dirty: bool) -> Option<Outgoing> {
(self.reported != Some(dirty)).then_some(Outgoing::Dirty(dirty))
}
pub fn sent(&mut self, dirty: bool) {
self.reported = Some(dirty);
}
/// Record `dirty` before the send. A page host can report another state while the event is
/// still dispatching, and that later report wins. Returns the message to send and the state
/// to put back if this send fails and nothing else recorded one.
pub fn prepare(&mut self, dirty: bool) -> (Option<Outgoing>, Option<bool>) {
let previous = self.reported;
let message = self.change(dirty);
if message.is_some() {
self.sent(dirty);
}
(message, previous)
}
/// Forget a send that failed, unless a nested report already recorded a different state.
pub fn restore_if_unchanged(&mut self, dirty: bool, previous: Option<bool>) {
if self.reported == Some(dirty) {
self.reported = previous;
}
}
}
/// Whether a page origin can tell the parent apart from any other window: an opaque origin
/// (`"null"`, as a sandboxed iframe or a `data:` page has) cannot, so such a page gets no bridge.
pub fn origin_is_usable(origin: &str) -> bool {
let o = origin.trim();
!o.is_empty() && o != "null"
}
/// The name a saved file is handed over under: the file name of the path the export chose.
pub fn save_name(path: &str) -> String {
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string())
}
/// The one `data-host` value that opts a page into page host mode: the exact string `"page"`.
pub const PAGE_HOST: &str = "page";
/// How a host page reaches the app. The modes behave the same; they differ only in how an event
/// goes out ([`Bridge::post`] and `save`, wasm32) and how one comes in ([`Bridge::listen`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
/// `?host=parent`: the page framed LightCraft in an `<iframe>`; `postMessage`.
Parent,
/// `data-host="page"`: the page runs LightCraft in its own document; DOM `CustomEvent`s.
Page,
}
/// The mode the page asked for. `?host=parent` wins when the page asks for both, the same order
/// as the other apps. Page mode is the exact `data-host="page"` ([`PAGE_HOST`]). `None` with
/// neither, so that URL stays the normal app with downloads.
pub fn transport_for(data_host: Option<&str>, query: &str) -> Option<Mode> {
if host_parent_requested(query) {
Some(Mode::Parent)
} else if data_host == Some(PAGE_HOST) {
Some(Mode::Page)
} else {
None
}
}
/// The message type. A page-mode `CustomEvent` is named `lightcraft:open` or `lightcraft:cmd`
/// and its `detail` is only the fields, so the event name is the type. A parent `postMessage`
/// carries `type` in the object and has no event name.
pub fn incoming_kind(event_name: Option<&str>, detail_type: Option<String>) -> Option<String> {
event_name.map(str::to_string).or(detail_type)
}
/// Does the query ask for the parent bridge? The same reading of `?host=parent` the URL options
/// always used: the first `host` parameter whose value is exactly `parent`.
pub fn host_parent_requested(query: &str) -> bool {
query.trim_start_matches('?').split('&').find_map(|p| {
let (k, v) = p.split_once('=').unwrap_or((p, ""));
(k == "host").then_some(v == "parent")
}) == Some(true)
}
#[cfg(target_arch = "wasm32")]
pub use bridge::Bridge;
#[cfg(target_arch = "wasm32")]
mod bridge {
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::JsCast as _;
use wasm_bindgen::JsValue;
use wasm_bindgen::closure::Closure;
use super::{DirtyReport, Field, Incoming, Mode, Outgoing, Raw, open_size_error, origin_is_usable, save_name};
/// How an event goes to the host page, per mode ([`Mode`]).
#[derive(Clone)]
enum Transport {
/// `?host=parent`: `postMessage` between same-origin windows.
Parent { parent: web_sys::Window, origin: String },
/// `data-host="page"`: DOM `CustomEvent`s on the editor's own canvas.
Page { canvas: web_sys::HtmlCanvasElement },
}
impl Transport {
/// Hand an event to the host. Parent mode: a `postMessage` whose `type` field is `event`
/// (the same message as before, transferring `transfer` when given). Page mode: a
/// non-bubbling `CustomEvent` of that name on the canvas, whose `detail` holds the
/// fields; nothing is transferred there, the buffer just rides inside `detail`.
fn send(&self, event: &str, fields: &[(&str, JsValue)], transfer: Option<&js_sys::ArrayBuffer>) -> Result<(), String> {
match self {
Transport::Parent { parent, origin } => {
let mut all = Vec::with_capacity(fields.len() + 1);
all.push(("type", JsValue::from_str(event)));
all.extend_from_slice(fields);
let message = message(&all).ok_or_else(|| "couldn't build the message".to_string())?;
let sent = match transfer {
Some(buffer) => parent.post_message_with_transfer(&message, origin, &js_sys::Array::of1(buffer)),
None => parent.post_message(&message, origin),
};
sent.map_err(|e| js_error(&e, "couldn't post the message"))
}
Transport::Page { canvas } => {
let detail = message(fields).ok_or_else(|| "couldn't build the event detail".to_string())?;
let init = web_sys::CustomEventInit::new();
init.set_bubbles(false);
init.set_detail(&detail);
let custom =
web_sys::CustomEvent::new_with_event_init_dict(event, &init).map_err(|e| js_error(&e, "couldn't create the event"))?;
canvas.dispatch_event(&custom).map_err(|e| js_error(&e, "couldn't dispatch the event"))?;
Ok(())
}
}
}
}
/// The host page's end of the bridge (cheap to clone; one per page).
#[derive(Clone)]
pub struct Bridge {
transport: Transport,
/// What the host sent since the last frame, oldest first.
incoming: Rc<RefCell<Vec<Incoming>>>,
dirty: Rc<RefCell<DirtyReport>>,
}
impl Bridge {
/// The parent bridge for `?host=parent`. `None` when the page isn't framed, its origin is
/// opaque, or the parent is on another origin (exports then keep downloading).
pub fn new() -> Option<Self> {
let window = web_sys::window()?;
let parent = window.parent().ok().flatten()?;
if js_sys::Object::is(&parent, &window) {
return None;
}
// the document's own origin (`window.origin`), not the URL's: a sandboxed iframe keeps
// its URL but runs with the opaque origin "null"
let origin = window.origin();
if !origin_is_usable(&origin) {
return None;
}
// Reading another origin's location throws, so this is `None` for a cross-origin parent.
if parent.location().origin().ok().as_deref() != Some(origin.as_str()) {
return None;
}
Some(Self { transport: Transport::Parent { parent, origin }, incoming: Rc::default(), dirty: Rc::default() })
}
/// The page bridge for `data-host="page"`: the host page runs LightCraft in its own
/// document and hears the app's DOM `CustomEvent`s on this canvas.
pub fn for_page(canvas: &web_sys::HtmlCanvasElement) -> Self {
Self { transport: Transport::Page { canvas: canvas.clone() }, incoming: Rc::default(), dirty: Rc::default() }
}
/// The bridge for the mode the page opted into (`host::transport_for`): page mode needs
/// its canvas, and parent mode falls back to `None` as [`Bridge::new`] always did.
pub fn for_mode(mode: Mode, canvas: Option<&web_sys::HtmlCanvasElement>) -> Option<Self> {
match mode {
Mode::Page => canvas.map(Self::for_page),
Mode::Parent => Self::new(),
}
}
/// Hear the host from now on; a message wakes the app for the next frame.
pub fn listen(&self, ctx: egui::Context) {
match &self.transport {
Transport::Parent { parent, origin } => {
let parent = parent.clone();
let origin = origin.clone();
let incoming = self.incoming.clone();
let on_message = Closure::<dyn Fn(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) {
return;
}
deliver(&incoming, &ctx, &event.data(), None);
});
if web_sys::window().is_some_and(|w| w.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok()) {
// the listener lives as long as the page
on_message.forget();
}
}
Transport::Page { canvas } => {
// non-bubbling events: the page dispatches on the canvas, the canvas listens
for kind in ["lightcraft:open", "lightcraft:cmd"] {
let incoming = self.incoming.clone();
let ctx = ctx.clone();
let event_type = kind.to_string();
// `Fn`, not `FnMut`: a page event is dispatched synchronously, and a host
// that answers one event with another would re-enter an `FnMut` listener.
let on_custom = Closure::<dyn Fn(web_sys::Event)>::new(move |event: web_sys::Event| {
let Some(custom) = event.dyn_ref::<web_sys::CustomEvent>() else { return };
deliver(&incoming, &ctx, &custom.detail(), Some(event_type.as_str()));
});
if canvas.add_event_listener_with_callback(kind, on_custom.as_ref().unchecked_ref()).is_ok() {
// the listener lives as long as the page
on_custom.forget();
}
}
}
}
}
/// What the parent sent since the last frame, oldest first.
pub fn take_incoming(&self) -> Vec<Incoming> {
std::mem::take(&mut *self.incoming.borrow_mut())
}
/// Post a message; false if it couldn't be sent.
pub fn post(&self, m: &Outgoing) -> bool {
let fields = m.fields();
// every message names its type first (tested natively); the rest go to the transport
let Some((_, Field::Str(event))) = fields.first() else { return false };
let event = event.clone();
let rest: Vec<(&str, JsValue)> = fields.into_iter().skip(1).map(|(k, v)| (k, field(&v))).collect();
self.transport.send(&event, &rest, None).is_ok()
}
/// Tell the parent whether closing now would lose something, when that changed.
/// The new state is recorded before the send: page mode dispatches synchronously, and a
/// host that reports another state from that event wins. A failed send is forgotten
/// only when nothing else recorded one, so the next frame retries it.
pub fn report_dirty(&self, dirty: bool) {
let (message, previous) = self.dirty.borrow_mut().prepare(dirty);
if let Some(m) = message
&& !self.post(&m)
{
self.dirty.borrow_mut().restore_if_unchanged(dirty, previous);
}
}
/// Hand a file to the parent instead of downloading it (`lightcraft:save`).
pub fn save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
let name = save_name(path);
let buffer = js_sys::Uint8Array::from(bytes).buffer();
self.transfer(&name, buffer)
}
/// [`Bridge::save`] for a blob built outside the wasm heap (the library backup).
pub async fn save_blob(&self, name: String, blob: web_sys::Blob) -> Result<(), String> {
let buffer = wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await.map_err(|e| format!("{e:?}"))?;
self.transfer(&name, buffer.unchecked_into::<js_sys::ArrayBuffer>())
}
fn transfer(&self, name: &str, buffer: js_sys::ArrayBuffer) -> Result<(), String> {
self.transport.send("lightcraft:save", &[("name", name.into()), ("bytes", buffer.clone().into())], Some(&buffer))?;
log::info!("handed {name} to the page");
Ok(())
}
}
/// A message from the host (the `data` of a window message, or the `detail` of a page-mode
/// `CustomEvent`), read with the same field code both transports share, and pushed for the
/// next frame.
fn deliver(incoming: &Rc<RefCell<Vec<Incoming>>>, ctx: &egui::Context, data: &JsValue, event_type: Option<&str>) {
// moved, not cloned: an accepted photo can be hundreds of MB
let (bytes, oversize) = match bytes(data) {
Some(Ok(b)) => (Some(b), None),
Some(Err(len)) => (None, Some(len)),
None => (None, None),
};
let raw = Raw {
kind: super::incoming_kind(event_type, string(data, "type")),
name: string(data, "name"),
bytes,
id: string(data, "id"),
params: string(data, "params"),
oversize,
};
if let Some(m) = Incoming::parse(raw) {
incoming.borrow_mut().push(m);
ctx.request_repaint();
}
}
fn field(v: &Field) -> JsValue {
match v {
Field::Str(s) => s.as_str().into(),
Field::Bool(b) => (*b).into(),
}
}
fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> {
let m = js_sys::Object::new();
for (key, value) in fields {
js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?;
}
Some(m)
}
fn string(data: &JsValue, key: &str) -> Option<String> {
js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string()
}
/// `bytes` as an `ArrayBuffer` or `Uint8Array`.
/// `bytes` as an `ArrayBuffer` or `Uint8Array`, copied only when within the size cap
/// ([`open_size_error`]); `Err(len)` for an oversize one, never copied into the app's memory.
fn bytes(data: &JsValue) -> Option<Result<Vec<u8>, u64>> {
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
let array = if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
array.clone()
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
js_sys::Uint8Array::new(&bytes)
} else {
return None;
};
let len = u64::from(array.byte_length());
Some(if open_size_error(len).is_some() { Err(len) } else { Ok(array.to_vec()) })
}
/// A `JsValue` error as a string, after `what` went wrong.
fn js_error(e: &JsValue, what: &str) -> String {
format!("{what}: {}", e.as_string().unwrap_or_else(|| format!("{e:?}")))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn raw(kind: &str) -> Raw {
Raw { kind: Some(kind.into()), ..Default::default() }
}
#[test]
fn open_needs_bytes_and_names_a_nameless_photo() {
let mut m = raw("lightcraft:open");
assert_eq!(Incoming::parse(m.clone()), None, "no bytes, nothing to add");
m.bytes = Some(vec![1, 2, 3]);
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Open { name: DEFAULT_OPEN_NAME.into(), bytes: vec![1, 2, 3] }));
m.name = Some(" ".into());
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Open { name: DEFAULT_OPEN_NAME.into(), bytes: vec![1, 2, 3] }));
m.name = Some("IMG_0001.CR2".into());
assert_eq!(Incoming::parse(m), Some(Incoming::Open { name: "IMG_0001.CR2".into(), bytes: vec![1, 2, 3] }));
}
#[test]
fn cmd_needs_an_id_and_defaults_its_params() {
let mut m = raw("lightcraft:cmd");
assert_eq!(Incoming::parse(m.clone()), None);
m.id = Some("library.info".into());
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Cmd { id: "library.info".into(), params: "{}".into() }));
m.params = Some(r#"{"rating": 5}"#.into());
assert_eq!(Incoming::parse(m), Some(Incoming::Cmd { id: "library.info".into(), params: r#"{"rating": 5}"#.into() }));
}
#[test]
fn an_oversize_open_is_refused_not_copied() {
let max = crate::backup::MAX_BYTES;
assert!(open_size_error(max).is_none());
assert!(open_size_error(max + 1).is_some_and(|e| e.contains("too large")));
let m = Raw { name: Some("big.tif".into()), oversize: Some(max + 1), ..raw("lightcraft:open") };
assert!(matches!(Incoming::parse(m), Some(Incoming::Refused(e)) if e.contains("too large")));
}
#[test]
fn other_pages_messages_are_not_ours() {
for kind in ["deckcraft:open", "lightcraft:save", "lightcraft:ready", ""] {
let m = Raw { bytes: Some(vec![1]), id: Some("x".into()), ..raw(kind) };
assert_eq!(Incoming::parse(m), None, "{kind:?}");
}
assert_eq!(Incoming::parse(Raw::default()), None);
}
#[test]
fn outgoing_messages_name_their_type_first() {
let ready = Outgoing::Ready.fields();
assert_eq!(ready[0], ("type", Field::Str("lightcraft:ready".into())));
assert_eq!(ready[1].0, "version");
assert_eq!(Outgoing::Failed("boom".into()).fields()[1], ("error", Field::Str("boom".into())));
assert_eq!(Outgoing::Dirty(true).fields(), vec![("type", Field::Str("lightcraft:dirty".into())), ("dirty", Field::Bool(true))]);
let r = Outgoing::Response { ok: false, value: "no such command".into() }.fields();
assert_eq!(r[1], ("ok", Field::Bool(false)));
assert_eq!(r[2], ("value", Field::Str("no such command".into())));
}
/// The parent hears `dirty` when it changes, not every frame, and again if a send failed.
#[test]
fn dirty_is_reported_on_change_only() {
let mut d = DirtyReport::default();
assert_eq!(d.change(false), Some(Outgoing::Dirty(false)), "the first state is news");
d.sent(false);
assert_eq!(d.change(false), None);
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
// not marked sent (the post failed): still owed
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
d.sent(true);
assert_eq!(d.change(true), None);
assert_eq!(d.change(false), Some(Outgoing::Dirty(false)));
}
/// A failed send is retried. A report that lands during the send (page mode dispatches
/// synchronously) is the one that stays.
#[test]
fn a_failed_dirty_send_is_retried_unless_a_later_report_landed() {
let mut d = DirtyReport::default();
let (message, previous) = d.prepare(true);
assert_eq!(message, Some(Outgoing::Dirty(true)));
d.restore_if_unchanged(true, previous);
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
let (message, previous) = d.prepare(true);
assert!(message.is_some());
let (later, _) = d.prepare(false);
assert_eq!(later, Some(Outgoing::Dirty(false)));
d.restore_if_unchanged(true, previous);
assert_eq!(d.change(false), None);
}
/// A canvas event is named for its type; the detail does not have to repeat it.
#[test]
fn a_page_event_is_named_for_its_type() {
assert_eq!(incoming_kind(Some("lightcraft:open"), None).as_deref(), Some("lightcraft:open"));
assert_eq!(incoming_kind(Some("lightcraft:cmd"), Some("lightcraft:open".into())).as_deref(), Some("lightcraft:cmd"));
assert_eq!(incoming_kind(None, Some("lightcraft:open".into())).as_deref(), Some("lightcraft:open"));
assert_eq!(incoming_kind(None, None), None);
}
/// A sandboxed iframe or a `data:` page has the opaque origin `"null"`, which any other such
/// window shares: no bridge there, so the origin check keeps meaning something.
#[test]
fn an_opaque_origin_gets_no_bridge() {
assert!(origin_is_usable("https://photos.example"));
assert!(origin_is_usable("http://localhost:8080"));
assert!(!origin_is_usable("null"));
assert!(!origin_is_usable(" null "));
assert!(!origin_is_usable(""));
}
#[test]
fn saved_files_are_handed_over_by_file_name() {
assert_eq!(save_name("exports/2026/IMG_0001.jpg"), "IMG_0001.jpg");
assert_eq!(save_name("IMG_0001.jpg"), "IMG_0001.jpg");
assert_eq!(save_name("lightcraft-library-backup-2026-10-19.zip"), "lightcraft-library-backup-2026-10-19.zip");
}
/// Page mode is opt-in by the exact attribute value, parent mode by the query, and parent
/// mode wins when a page asks for both.
#[test]
fn page_mode_is_opt_in_and_parent_mode_wins_when_both_are_set() {
assert_eq!(transport_for(Some("page"), ""), Some(Mode::Page));
assert_eq!(transport_for(Some("page"), "?host=parent"), Some(Mode::Parent), "parent mode wins");
// only the exact value opts in; anything else falls back to the query, or to standalone
for not_page in ["Page", " page", "page ", "parent", "host"] {
assert_eq!(transport_for(Some(not_page), "?host=parent"), Some(Mode::Parent), "{not_page:?}");
assert_eq!(transport_for(Some(not_page), ""), None, "{not_page:?}");
}
assert_eq!(transport_for(None, ""), None);
assert_eq!(transport_for(None, "?store=idb"), None);
assert_eq!(transport_for(None, "?host="), None);
assert_eq!(transport_for(None, "?host=Parent"), None);
assert_eq!(transport_for(None, "?xhost=parent"), None);
}
/// The query is read the way the URL options always read it: the first `host` parameter wins,
/// and only a value of exactly `parent` counts.
#[test]
fn the_query_asks_for_the_parent_bridge() {
assert!(host_parent_requested("?host=parent"));
assert!(host_parent_requested("host=parent"));
assert!(host_parent_requested("?host=parent&store=idb"));
assert!(host_parent_requested("?store=idb&host=parent"));
assert!(!host_parent_requested(""));
assert!(!host_parent_requested("?"));
assert!(!host_parent_requested("?host"));
assert!(!host_parent_requested("?host="));
assert!(host_parent_requested("?host=parent&host=id"), "the first host parameter wins");
assert!(!host_parent_requested("?host=id&host=parent"));
assert!(!host_parent_requested("?hosts=parent"));
}
}
+5
View File
@@ -14,6 +14,10 @@
//! console (see [`bench`]) on the generated demo photos in an unsaved library (it implies `?store=memory`, so it never edits
//! the library in browser storage); `?store=idb` forces the IndexedDB backend, `?store=memory` disables
//! persistence and `?workers=0` renders on the main thread.
//! `?host=parent` speaks to a same-origin page framing LightCraft (see [`host`]): it hands
//! photos in, receives what would be downloaded and hears about unsaved changes. A page can also
//! host LightCraft in its own document, no iframe: `data-host="page"` on the canvas opts in, and
//! the same messages travel as DOM `CustomEvent`s on the canvas.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -25,6 +29,7 @@ pub mod bench;
#[cfg(any(test, target_arch = "wasm32"))]
mod drop_gate;
pub mod files;
pub mod host;
pub mod store;
pub mod wire;
+7 -3
View File
@@ -149,10 +149,14 @@ pub fn download_blob(name: &str, blob: &web_sys::Blob) -> Result<(), String> {
Ok(())
}
/// Where a finished backup goes: the browser's downloads ([`download_blob`]), or the page framing
/// LightCraft (`?host=parent`). Awaited, so the backup counts as done only once it is handed over.
pub type Deliver = Box<dyn FnOnce(String, web_sys::Blob) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>>>>>;
/// File ▸ Back Up Library…: a zip of the library files (as the app has them, saved or not) and
/// every original in storage, built entry by entry into the browser's memory (outside the wasm
/// heap) and downloaded. `names`: content hash → the photo's file name.
pub async fn backup(files: Files, backend: Backend, names: HashMap<String, String>) -> Result<(usize, f64), String> {
/// heap) and handed to `deliver`. `names`: content hash → the photo's file name.
pub async fn backup(files: Files, backend: Backend, names: HashMap<String, String>, deliver: Deliver) -> Result<(usize, f64), String> {
let parts = js_sys::Array::new();
let mut zip = ZipWriter::default();
let mut bytes = 0f64;
@@ -190,7 +194,7 @@ pub async fn backup(files: Files, backend: Backend, names: HashMap<String, Strin
opts.set_type("application/zip");
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(|e| format!("{e:?}"))?;
let day: String = String::from(js_sys::Date::new_0().to_iso_string()).chars().take(10).collect();
download_blob(&format!("lightcraft-library-backup-{day}.zip"), &blob)?;
deliver(format!("lightcraft-library-backup-{day}.zip"), blob).await?;
Ok((originals, bytes + tail.len() as f64))
}
+7 -7
View File
@@ -12,7 +12,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use lightcraft_engine::files::{load_bytes_with, probe_bytes};
use lightcraft_engine::files::{load_bytes_decoded, probe_bytes};
use lightcraft_engine::media::{FileLoader, FileProbe};
/// Prefix of the catalog paths of files kept in browser storage.
@@ -146,9 +146,9 @@ impl Originals {
let s = self.clone();
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
// whether it decodes in a worker or inline when workers are unavailable)
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, _dcp: Option<&lightcraft_engine::media::DcpProfile>| {
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, with: lightcraft_engine::media::RawDecode<'_>| {
let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?;
load_bytes_with(&bytes, max_edge, None)
load_bytes_decoded(&bytes, max_edge, lightcraft_engine::media::RawDecode { dcp: None, outliers: with.outliers })
});
let s = self.clone();
let probe: FileProbe = Arc::new(move |path: &str| {
@@ -285,15 +285,15 @@ mod tests {
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
};
assert_ne!(
load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
load_bytes_with(&dng, 64, None).unwrap().0.data,
lightcraft_engine::files::load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
lightcraft_engine::files::load_bytes_with(&dng, 64, None).unwrap().0.data,
"the profile changes a raw's colour where it is applied"
);
let store = Originals::default();
store.insert("h1", Arc::from(dng));
let (loader, _) = store.hooks();
let with = loader("web/h1/a.dng", 64, Some(&profile)).unwrap();
let without = loader("web/h1/a.dng", 64, None).unwrap();
let with = loader("web/h1/a.dng", 64, lightcraft_engine::media::RawDecode { dcp: Some(&profile), outliers: false }).unwrap();
let without = loader("web/h1/a.dng", 64, Default::default()).unwrap();
assert_eq!(with.0.data, without.0.data, "the web loader leaves it out");
}
+176 -20
View File
@@ -2,14 +2,14 @@
//! `<canvas id="lightcraft_canvas">`, wires the file picker and drag-and-drop, and turns exports
//! into downloads.
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use lightcraft_engine::Session;
use lightcraft_engine::catalog::Source;
use lightcraft_engine::library::LibraryStores;
use lightcraft_ui_egui::{LightcraftApp, Services, UiState};
use lightcraft_ui_egui::{LightcraftApp, Services, UiState, WriteFn};
use serde_json::json;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
@@ -18,6 +18,7 @@ use crate::backend::Backend;
use crate::backup::{ACTIVE_LIBRARY, DEFAULT_LIBRARY_DIR, valid_library_dir};
use crate::bench::Bench;
use crate::files::{Files, FlushOp, LIBRARY_FILES};
use crate::host::{Incoming, Outgoing};
use crate::safety::{self, notice};
use crate::store::{Originals, content_hash, download_name, storage_key};
use crate::wire::ThumbIndex;
@@ -68,13 +69,15 @@ pub(crate) fn request_repaint() {
});
}
/// URL options (`?bench&store=idb&workers=2&reset`).
/// URL options (`?bench&store=idb&workers=2&reset&host=parent`).
struct Options {
bench: bool,
/// "opfs" (default: OPFS, falling back to IndexedDB), "idb" or "memory".
store: String,
workers: Option<usize>,
reset: bool,
/// The raw query string, for the host mode ([`crate::host::transport_for`]).
query: String,
}
impl Options {
@@ -98,6 +101,7 @@ impl Options {
store: if bench { "memory".into() } else { get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()) },
workers: get("workers").and_then(|v| v.parse().ok()).map(|n: usize| n.min(crate::workers::MAX_WORKERS)),
reset: get("reset").is_some(),
query: q,
}
}
}
@@ -171,12 +175,75 @@ fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
Ok(())
}
/// Keep egui's hidden text field content-box, so host page CSS cannot misplace typed text:
/// eframe (0.36 web) types through a hidden `<input type="text">` it inserts as the canvas's
/// next sibling, and a host page's global `* { box-sizing: border-box }` reaches it and leaves it
/// no content box, so the next key lands before text just committed by an input method or a
/// paste-like insert. Inline style beats any host stylesheet rule without `!important`, so the
/// property is set on the element itself, in every host mode, and retried on the next animation
/// frames while eframe hasn't inserted the field yet.
fn fix_text_field_box_sizing() {
/// How many animation frames the fix may wait for eframe to insert its hidden text field.
const MAX_FRAMES: u32 = 120;
/// True when the field was found and set: the canvas's next sibling, or an
/// `input[type=text]` in the canvas's parent.
fn fix_once() -> bool {
let Some(doc) = window().and_then(|w| w.document()) else { return false };
let Some(canvas) = doc.get_element_by_id("lightcraft_canvas") else { return false };
let input = canvas.next_element_sibling().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()).or_else(|| {
canvas
.parent_element()
.and_then(|p| p.query_selector("input[type=text]").ok())
.flatten()
.and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok())
});
input.is_some_and(|i| i.style().set_property("box-sizing", "content-box").is_ok())
}
// the closure reschedules itself until the field is fixed or the frames run out; done, it is
// left parked in its slot (dropping it from inside itself would free its own state, and the
// slot holds the only reference) — a one-off leak, like the forgotten listeners
let tries = Rc::new(Cell::new(MAX_FRAMES));
let slot: Rc<RefCell<Option<Closure<dyn FnMut()>>>> = Rc::default();
let own = Rc::clone(&slot);
*slot.borrow_mut() = Some(Closure::new(move || {
if fix_once() || tries.get() <= 1 {
return; // done: stop rescheduling
}
tries.set(tries.get() - 1);
let again = own.borrow_mut().take();
if let Some(again) = again {
let _ = window().and_then(|w| w.request_animation_frame(again.as_ref().unchecked_ref()).ok());
// put the same closure back, now that the frame it was handed to has its own reference
*own.borrow_mut() = Some(again);
}
}));
let first = slot.borrow_mut().take();
if let Some(first) = first {
let _ = window().and_then(|w| w.request_animation_frame(first.as_ref().unchecked_ref()).ok());
*slot.borrow_mut() = Some(first);
}
}
/// Build the browser host's `Services`: library backup/restore through browser storage and a
/// download, asynchronous file picking, downloads for writes, and PNG encoding. Desktop-only
/// services (native pickers, reveal, model folders) stay unset.
fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen: Rc<Cell<bool>>, ctx: egui::Context) -> Services {
let (backup_backend, backup_files) = (backend.clone(), files);
fn services(
originals: Originals,
backend: Option<Backend>,
files: Files,
frozen: Rc<Cell<bool>>,
ctx: egui::Context,
bridge: Option<crate::host::Bridge>,
) -> Services {
let (backup_backend, backup_files, backup_bridge) = (backend.clone(), files, bridge.clone());
let restore_backend = backend.clone();
// what would be downloaded goes to the page framing LightCraft instead, when there is one
let write: WriteFn = match bridge {
Some(bridge) => Box::new(move |path: &str, bytes: &[u8]| bridge.save(path, bytes)),
None => Box::new(download),
};
Services {
local_places: None,
picker: None,
@@ -197,9 +264,18 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
})
.collect();
let files = backup_files.clone();
notice("Backing up the library… (the download starts when it's ready)");
// awaited by `backup`: "backed up" is said only once the page has the file
let deliver: safety::Deliver = match backup_bridge.clone() {
Some(bridge) => Box::new(move |name: String, blob: web_sys::Blob| Box::pin(async move { bridge.save_blob(name, blob).await })),
None => Box::new(|name: String, blob: web_sys::Blob| Box::pin(async move { safety::download_blob(&name, &blob) })),
};
notice(if backup_bridge.is_some() {
"Backing up the library… (handed to the page when it's ready)"
} else {
"Backing up the library… (the download starts when it's ready)"
});
wasm_bindgen_futures::spawn_local(async move {
match safety::backup(files, b, names).await {
match safety::backup(files, b, names, deliver).await {
Ok((n, bytes)) => notice(format!(
"Library backed up: {n} original{} ({:.1} MB). Keep the file somewhere safe.",
if n == 1 { "" } else { "s" },
@@ -237,7 +313,7 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
save_slideshow_template: None,
pick_print_templates: None,
save_print_template: None,
write: Some(Box::new(download)),
write: Some(write),
// the browser download path has no meaningful create-new file write; the control channel
// (and therefore screenshot paths) is not available on the web
write_new: None,
@@ -289,7 +365,8 @@ async fn flush(files: Files, backend: Backend, dir: String, flushing: Rc<Cell<bo
}
}
flushing.set(false);
// the page title drops its unsaved • now, even when nothing else wakes the page
// the page title drops its unsaved • now, and the page framing LightCraft hears `dirty: false`,
// even when nothing else wakes the page
request_repaint();
}
@@ -301,12 +378,14 @@ struct Boot {
index: ThumbIndex,
/// The library folder in storage (`library`, or a restored backup's).
lib_dir: String,
/// The page framing LightCraft (`?host=parent`), when there is one.
bridge: Option<crate::host::Bridge>,
/// Library files that exist but couldn't be read (#1507): the library isn't opened and
/// nothing is saved, so the stored copy stays as it was.
load_error: Option<String>,
}
async fn boot(opts: Options) -> Boot {
async fn boot(opts: Options, bridge: Option<crate::host::Bridge>) -> Boot {
let t0 = perf_now();
let backend = if opts.store == "memory" {
None
@@ -403,7 +482,7 @@ async fn boot(opts: Options) -> Boot {
index.len(),
index.total() as f64 / 1e6
);
Boot { opts, backend, files, index, lib_dir, load_error }
Boot { opts, backend, files, index, lib_dir, bridge, load_error }
}
struct WebApp {
@@ -424,6 +503,7 @@ struct WebApp {
title: String,
last_save: f64,
ui_written: Vec<u8>,
bridge: Option<crate::host::Bridge>,
}
/// The browser host's drop queues, taken only through the shared gate: a prompt or blocking
@@ -458,7 +538,7 @@ impl WebApp {
/// browser storage (a read failure starts an empty session and a blocking `LibraryProblem`),
/// load the stored UI state, start render workers and the optional benchmark.
fn new(cc: &eframe::CreationContext<'_>, boot: Boot, chinese_font: Vec<u8>) -> Self {
let Boot { opts, backend, files, index, lib_dir, load_error } = boot;
let Boot { opts, backend, files, index, lib_dir, bridge, load_error } = boot;
let originals = Originals::default();
let t = perf_now();
let mut session = Session::new();
@@ -513,13 +593,16 @@ impl WebApp {
session.media.preview_capacity = 3;
// nothing is saved while the stored library couldn't be read
let frozen = Rc::new(Cell::new(read_failed));
let mut app = LightcraftApp::new(session, services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone()))
.with_chinese_font(chinese_font);
let services = services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone(), bridge.clone());
let mut app = LightcraftApp::new(session, services).with_chinese_font(chinese_font);
let ui_written = files.get("ui.json").unwrap_or_default();
// an arrangement from an older docking version starts again from the default
let mut saved = serde_json::from_slice::<serde_json::Value>(&ui_written).unwrap_or_default();
if let Some(fields) = saved.as_object_mut() {
lightcraft_ui_egui::docking::drop_outdated(fields);
// a stored ui.json means an installation that has been run: due What's New, never
// the first-run tour (the same migration the desktop settings loader runs)
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
}
if let Ok(ui) = serde_json::from_value::<UiState>(saved) {
app.ui = ui;
@@ -547,6 +630,13 @@ impl WebApp {
}
log::info!("lightcraft: {n} render workers");
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
if let Some(b) = &bridge {
// hear the page from now on, and tell it the app is listening
b.listen(cc.egui_ctx.clone());
if !b.post(&Outgoing::Ready) {
log::warn!("lightcraft: the page framing LightCraft could not be told the app is ready");
}
}
let origin = lightcraft_ui_egui::monotonic_ms();
WebApp {
app,
@@ -563,9 +653,49 @@ impl WebApp {
title: String::new(),
last_save: 0.0,
ui_written,
bridge,
}
}
/// What the page framing LightCraft sent since the last frame: photos to add (as if dropped
/// on the window) and commands to run, each answered with `lightcraft:response`.
fn run_host(&mut self, ctx: &egui::Context) {
let Some(bridge) = self.bridge.clone() else { return };
for m in bridge.take_incoming() {
match m {
Incoming::Open { name, bytes } => {
wasm_bindgen_futures::spawn_local(store_file(self.originals.clone(), self.backend.clone(), name, bytes, ctx.clone()));
}
Incoming::Refused(error) => {
if !bridge.post(&Outgoing::Failed(error)) {
log::warn!("lightcraft: a refused open could not be reported to the page");
}
}
Incoming::Cmd { id, params } => {
let r = match crate::automation::params(&params) {
Err(e) => Err(format!("{id}: {e}")),
Ok(_) if id == "web.stats" => Ok(self.web_stats()),
Ok(params) => self.app.run(&id, params),
};
let response = match r {
Ok(v) => Outgoing::Response { ok: true, value: v.to_string() },
Err(e) => Outgoing::Response { ok: false, value: e },
};
if !bridge.post(&response) {
log::warn!("lightcraft: the answer to {id} could not reach the page");
}
}
}
}
}
/// Whether closing the page now would lose something: a write to browser storage still
/// queued or running, or changes storage refused (quota). The page framing LightCraft hears
/// when this changes (`lightcraft:dirty`), so it can ask before closing a window with edits.
fn dirty_for_host(&self) -> bool {
self.files.is_dirty() || self.flushing.get() || self.app.session.unsaved().is_some()
}
/// Consume the drops the raw-input hook queued once (never re-read `raw.dropped_files` in a
/// hidden logic tick), and add originals whose bytes have arrived.
fn import_dropped(&mut self, ctx: &egui::Context) {
@@ -742,6 +872,7 @@ impl eframe::App for WebApp {
self.app.ui.toast = Some((text, now + NOTICE_SECS, None));
}
self.run_inbox();
self.run_host(ctx);
self.load_originals(ctx);
if let Some(w) = &self.workers {
// `library.preferences ▸ cacheMb` is read by the session; the worker index prunes on
@@ -750,6 +881,9 @@ impl eframe::App for WebApp {
}
self.app.logic(ctx);
self.save();
if let Some(b) = &self.bridge {
b.report_dirty(self.dirty_for_host());
}
}
/// Pass the browser's raw input to the app hook before egui processes it, so prompt barriers
@@ -837,6 +971,21 @@ pub fn start(chinese_font: Vec<u8>) {
log::warn!("lightcraft: no Simplified Chinese font supplied; Chinese-only glyphs will show as boxes");
}
let opts = Options::from_url();
// `?host=parent`: a same-origin page framing LightCraft hands photos in, stores what would
// be downloaded and hears about unsaved changes (see `host`). `data-host="page"` on the
// canvas opts a page in instead: it runs LightCraft in its own document and talks over DOM
// `CustomEvent`s on the canvas. `?host=parent` wins when a page asks for both.
let canvas = window()
.and_then(|w| w.document())
.and_then(|d| d.get_element_by_id("lightcraft_canvas"))
.and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok());
let mode = crate::host::transport_for(canvas.as_ref().and_then(|c| c.get_attribute("data-host")).as_deref(), &opts.query);
let bridge = mode.and_then(|m| crate::host::Bridge::for_mode(m, canvas.as_ref()));
if mode == Some(crate::host::Mode::Parent) && bridge.is_none() {
log::warn!(
"lightcraft: ?host=parent, but this page is not framed, has an opaque origin, or its parent is on another origin; exports keep downloading"
);
}
wasm_bindgen_futures::spawn_local(async move {
// one tab per library: two would each keep their own copy and overwrite each other's saves
if opts.store != "memory" && safety::acquire_tab_lock().await == Some(false) {
@@ -844,17 +993,19 @@ pub fn start(chinese_font: Vec<u8>) {
"LightCraft is already open in another tab or window of this browser.\n\n\
Switch to that tab, or close it and reload this page. (Two tabs would overwrite each other's changes.)",
);
if let Some(b) = &bridge {
b.post(&Outgoing::Failed("LightCraft is already open in another tab or window of this browser".into()));
}
return;
}
let Some(canvas) = window()
.and_then(|w| w.document())
.and_then(|d| d.get_element_by_id("lightcraft_canvas"))
.and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok())
else {
let Some(canvas) = canvas else {
log::error!("missing <canvas id=\"lightcraft_canvas\">");
if let Some(b) = &bridge {
b.post(&Outgoing::Failed("the page has no <canvas id=\"lightcraft_canvas\">".into()));
}
return;
};
let boot = boot(opts).await;
let boot = boot(opts, bridge.clone()).await;
let runner = eframe::WebRunner::new();
let r = runner.start(canvas, eframe::WebOptions::default(), Box::new(move |cc| Ok(Box::new(WebApp::new(cc, boot, chinese_font))))).await;
match r {
@@ -862,10 +1013,15 @@ pub fn start(chinese_font: Vec<u8>) {
if let Some(el) = window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id("lightcraft_loading")) {
el.remove();
}
// the runner just started: egui's hidden text field exists from now on
fix_text_field_box_sizing();
}
Err(e) => {
log::error!("LightCraft failed to start: {e:?}");
set_status(&format!("LightCraft failed to start: {e:?}"));
if let Some(b) = &bridge {
b.post(&Outgoing::Failed(format!("{e:?}")));
}
}
}
});
+22 -4
View File
@@ -33,6 +33,9 @@ pub struct WireJob {
pub origin: Source,
/// Decode the source at most this long.
pub max_edge: usize,
/// Resize an already decoded source exactly as the engine's cached-source path does.
#[serde(default)]
pub fit_edge: Option<usize>,
pub raw: bool,
#[serde(default)]
pub relative_wb: bool,
@@ -67,7 +70,8 @@ impl WireJob {
/// `view`: the slot name, for jobs that keep a stage cache.
pub fn from_job(job: &RenderJob, thumb_cached: bool, view: &str) -> WireJob {
let max_edge = match &job.source {
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } | SourceRef::Fit { max_edge, .. } => *max_edge,
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } => *max_edge,
SourceRef::Fit { from, .. } => from.image.width.max(from.image.height),
SourceRef::Loaded(img) => img.image.width.max(img.image.height),
SourceRef::Smart { .. } => 2560,
};
@@ -77,6 +81,10 @@ impl WireJob {
level: job.level,
origin: job.origin.clone(),
max_edge,
fit_edge: match &job.source {
SourceRef::Fit { max_edge, .. } => Some(*max_edge),
_ => None,
},
raw: job.info.raw,
relative_wb: job.info.relative_wb,
legacy_relative_wb: job.info.legacy_relative_wb,
@@ -114,6 +122,7 @@ impl WireJob {
RenderRequest {
max_w: self.max_w,
max_h: self.max_h,
exact_size: false,
quality: if self.draft { Quality::Draft } else { Quality::Full },
apply_crop: self.apply_crop,
overlay: lightcraft_engine::pipeline::Overlay::from_parts(self.overlay.0, self.overlay.1),
@@ -129,7 +138,9 @@ impl WireJob {
/// Identifies the decoded source this job needs.
fn source_key(&self) -> String {
match &self.origin {
Source::File { path } => format!("{}:{:?}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge),
Source::File { path } => {
format!("{}:{:?}:{}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge, self.settings.removes_hot_pixels())
}
Source::Demo { scene } => format!("{}:{:?}:{}:demo:{scene}", self.cache_generation, self.source_identity, self.max_edge),
}
}
@@ -181,8 +192,10 @@ impl WorkerCore {
None => {
let src = match (&job.origin, original) {
(Source::File { .. }, Some(bytes)) => {
let (image, info) = lightcraft_engine::files::load_bytes(bytes, job.max_edge)?;
DecodedSource::new(Arc::new(image), Some(info))
let outliers = job.settings.removes_hot_pixels();
let with = lightcraft_engine::media::RawDecode { dcp: None, outliers };
let (image, info) = lightcraft_engine::files::load_bytes_decoded(bytes, job.max_edge, with)?;
DecodedSource { outliers, ..DecodedSource::new(Arc::new(image), Some(info)) }
}
(Source::File { path }, None) => return Err(format!("{path}: original not found in browser storage")),
(origin @ Source::Demo { .. }, _) => self.media.origin_ref(origin, job.max_edge).load_source()?,
@@ -192,6 +205,10 @@ impl WorkerCore {
src
}
};
let src = match job.fit_edge {
Some(max_edge) => SourceRef::Fit { from: Box::new(src), max_edge }.load_source()?,
None => src,
};
let info = src.info_or(job.info());
let mut rendered = match &job.stages {
Some(view) => {
@@ -468,6 +485,7 @@ mod tests {
level: SourceLevel::Thumb,
origin,
max_edge: 512,
fit_edge: None,
raw: false,
relative_wb: false,
legacy_relative_wb: false,
+3
View File
@@ -58,3 +58,6 @@ lightcraft-testkit = { workspace = true }
[target.'cfg(windows)'.dependencies]
craft-update = { workspace = true }
# the colour profile of the monitor showing the window (`win_screen_profile`)
lightcraft-wincolor = { workspace = true }
raw-window-handle = "0.6"
+1 -29
View File
@@ -18,8 +18,6 @@ use std::time::Duration;
const POLL: Duration = Duration::from_secs(3);
/// A wait before trying again when colord isn't there (not installed, no system bus).
const RETRY: Duration = Duration::from_secs(30);
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
const MAX_PROFILE: u64 = 16 << 20;
const SERVICE: &str = "org.freedesktop.ColorManager";
const DEVICE: &str = "org.freedesktop.ColorManager.Device";
@@ -72,7 +70,7 @@ fn read(conn: &zbus::blocking::Connection) -> Option<Vec<u8>> {
}
}
let file = pick(&files)?;
load(std::path::Path::new(file))
crate::profile_file::load(std::path::Path::new(file))
}
/// The profile to use for these displays' profile files: the one they share, `None` with none or
@@ -83,15 +81,6 @@ fn pick(files: &[String]) -> Option<&str> {
named.all(|f| f == first).then_some(first)
}
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
fn load(path: &std::path::Path) -> Option<Vec<u8>> {
use std::io::Read as _;
let file = std::fs::File::open(path).ok()?;
let mut bytes = Vec::new();
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -105,21 +94,4 @@ mod tests {
assert_eq!(pick(&s(&["/a.icc", "/b.icc"])), None, "which one the window is on isn't known");
assert_eq!(pick(&s(&[""])), None);
}
#[test]
fn profile_files_are_read_with_a_size_cap() {
let dir = std::env::temp_dir().join(format!("colord-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let small = dir.join("small.icc");
std::fs::write(&small, b"acsp").unwrap();
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
let empty = dir.join("empty.icc");
std::fs::write(&empty, b"").unwrap();
assert_eq!(load(&empty), None);
assert_eq!(load(&dir.join("missing.icc")), None);
let big = dir.join("big.icc");
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
assert_eq!(load(&big), None);
std::fs::remove_dir_all(&dir).unwrap();
}
}
+5
View File
@@ -35,8 +35,12 @@ mod hdr_display;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
#[cfg(any(target_os = "linux", windows))]
mod profile_file;
#[cfg(target_os = "macos")]
mod screen_profile;
#[cfg(windows)]
mod win_screen_profile;
mod window_gpu;
use dialog_filter::FileDialogExt as _;
@@ -371,6 +375,7 @@ fn main() -> eframe::Result {
app.notices.extend(launch_notices);
app.notices.extend(window_notice);
app.gpu_notice = true;
app.disk_space_notice = true;
// an empty library opens where Import is offered (a grid, with the sidebar); before
// the snapshot below, so this alone isn't written to the settings file
if problem.is_none() && files.is_empty() {
+5
View File
@@ -67,6 +67,11 @@ fn decode_saved_ui(bytes: &[u8]) -> Result<(UiState, bool), String> {
if recovered {
fields.remove("docking");
}
// A settings file from before the startup dialog existed has no `seenVersion` key: the file
// is there, so this is an installation that has been run, due What's New — never the
// first-run tour. Shared with the browser's loader, which runs the same migration on its
// stored `ui.json` (`startup::migrate_legacy_seen_version` carries the full story).
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
let ui = serde_json::from_value(saved).map_err(|error| error.to_string())?;
Ok((ui, recovered))
}
+87
View File
@@ -0,0 +1,87 @@
//! Reading a display's ICC profile file for the screen-profile services (`colord` on Linux,
//! `win_screen_profile` on Windows).
use std::path::{Path, PathBuf};
use std::time::SystemTime;
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
pub const MAX_PROFILE: u64 = 16 << 20;
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
pub fn load(path: &Path) -> Option<Vec<u8>> {
use std::io::Read as _;
let file = std::fs::File::open(path).ok()?;
let mut bytes = Vec::new();
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
}
/// A profile file read again only when it changes: the services are asked about once a second, and
/// calibration software rewrites its profile under the same name.
#[cfg_attr(not(windows), allow(dead_code))]
#[derive(Default)]
pub struct Cached {
/// The file last read: its path, length and modification time.
stamp: Option<(PathBuf, u64, Option<SystemTime>)>,
bytes: Option<Vec<u8>>,
}
#[cfg_attr(not(windows), allow(dead_code))]
impl Cached {
/// The bytes of profile file `path`, read again when it isn't the file read last time or has
/// changed since (see [`load`]).
pub fn read(&mut self, path: &Path) -> Option<Vec<u8>> {
let stamp = std::fs::metadata(path).ok().map(|m| (path.to_path_buf(), m.len(), m.modified().ok()));
if stamp.is_none() || stamp != self.stamp {
self.bytes = stamp.as_ref().and_then(|_| load(path));
self.stamp = stamp;
}
self.bytes.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn profile_files_are_read_with_a_size_cap() {
let dir = std::env::temp_dir().join(format!("profile-file-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let small = dir.join("small.icc");
std::fs::write(&small, b"acsp").unwrap();
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
let empty = dir.join("empty.icc");
std::fs::write(&empty, b"").unwrap();
assert_eq!(load(&empty), None);
assert_eq!(load(&dir.join("missing.icc")), None);
let big = dir.join("big.icc");
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
assert_eq!(load(&big), None);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_cached_profile_is_read_again_when_the_file_changes() {
let dir = std::env::temp_dir().join(format!("profile-cache-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (a, b) = (dir.join("a.icc"), dir.join("b.icc"));
std::fs::write(&a, b"first").unwrap();
std::fs::write(&b, b"other").unwrap();
let mut cache = Cached::default();
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
// another monitor's profile
assert_eq!(cache.read(&b).as_deref(), Some(&b"other"[..]));
// rewritten under the same name (a different length, so the change shows whatever the
// file system's time resolution)
std::fs::write(&b, b"calibrated").unwrap();
assert_eq!(cache.read(&b).as_deref(), Some(&b"calibrated"[..]));
// gone: nothing, then read again once it is back
std::fs::remove_file(&b).unwrap();
assert_eq!(cache.read(&b), None);
std::fs::write(&b, b"back").unwrap();
assert_eq!(cache.read(&b).as_deref(), Some(&b"back"[..]));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+5 -1
View File
@@ -144,7 +144,11 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
// Linux: the profile the desktop assigns in colord, read off the UI thread
#[cfg(target_os = "linux")]
screen_profile: Some(colord::service()),
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
// Windows: the profile it uses for the window's monitor, unless it colour-manages the
// desktop itself (HDR, Auto Color Management)
#[cfg(windows)]
screen_profile: win_screen_profile::service(cc),
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
screen_profile: None,
pick_display_profile: Some(Box::new(|| {
let mut d = file_dialog()
+36
View File
@@ -223,6 +223,42 @@ fn memory_session_leaves_a_damaged_ui_json_alone() {
let _ = std::fs::remove_dir_all(&d);
}
/// A settings file from before the startup dialog existed (no `seenVersion`) belongs to an
/// installation that has been run: its first launch after the update shows What's New, never
/// the first-run tour. A file this version saved before the dialog was presented carries an
/// explicit `null` and is not migrated; only a missing file stays a first run as well.
#[test]
fn legacy_ui_json_shows_whats_new_not_the_first_run_tour() {
let d = dir("legacy-startup");
let path = d.join("ui.json");
std::fs::write(&path, br#"{"language":"en","settings":{"startupView":"detail"}}"#).unwrap();
let (ui, warning, keep) = load_prefs_at(&path, true);
assert!(warning.is_none() && !keep);
let ui = ui.unwrap();
assert_eq!(ui.seen_version.as_deref(), Some(lightcraft_ui_egui::startup::LEGACY_SEEN_VERSION));
assert_eq!(
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
Some(lightcraft_ui_egui::startup::StartupDialog::WhatsNew)
);
// a file that already records the running version is migrated nowhere
std::fs::write(&path, format!(r#"{{"seenVersion":"{}"}}"#, env!("CARGO_PKG_VERSION"))).unwrap();
let (ui, warning, _) = load_prefs_at(&path, true);
assert!(warning.is_none());
assert_eq!(ui.unwrap().seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION")));
// an explicit `null` is this version's "not presented yet" (the launch chooser saves while
// the tour still waits): it stays a first run, not a pre-feature file
std::fs::write(&path, br#"{"language":"en","seenVersion":null}"#).unwrap();
let (ui, warning, _) = load_prefs_at(&path, true);
assert!(warning.is_none());
let ui = ui.unwrap();
assert_eq!(ui.seen_version, None);
assert_eq!(
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
Some(lightcraft_ui_egui::startup::StartupDialog::FirstRun)
);
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn docking_survives_native_settings_file_reload() {
use lightcraft_ui_egui::docking::Panel;
+40
View File
@@ -0,0 +1,40 @@
//! The ICC profile Windows assigns to the monitor showing LightCraft's window.
//!
//! On an SDR desktop Windows passes what an app draws to the monitor unchanged, so sRGB previews
//! look oversaturated on a wide-gamut monitor and ignore a calibration. While no monitor profile is
//! chosen in Settings ▸ Display, previews are shown through the profile Windows uses for the window's
//! monitor (`Services::screen_profile`, see `lightcraft_wincolor`), followed when the window moves to
//! another monitor or the profile changes in Windows' Color Management. When Windows colour-manages
//! the desktop itself (HDR, Auto Color Management) previews stay sRGB, as Windows expects then.
use lightcraft_wincolor::MonitorColor;
/// The service the UI polls, for the window `cc` belongs to; `None` when its handle isn't a Win32 one.
pub fn service(cc: &eframe::CreationContext<'_>) -> Option<lightcraft_ui_egui::ScreenProfileFn> {
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
let RawWindowHandle::Win32(handle) = cc.window_handle().ok()?.as_raw() else { return None };
let hwnd = handle.hwnd.get();
let mut file = crate::profile_file::Cached::default();
let mut last: Option<MonitorColor> = None;
Some(Box::new(move || {
let answer = lightcraft_wincolor::monitor_color(hwnd);
if last.as_ref() != Some(&answer) {
log::info!("screen profile: {}", describe(&answer));
last = Some(answer.clone());
}
match answer {
MonitorColor::Profile(path) => file.read(&path),
MonitorColor::ManagedByWindows | MonitorColor::NoProfile | MonitorColor::Unknown => None,
}
}))
}
/// For the log: what the window's monitor answered.
fn describe(answer: &MonitorColor) -> String {
match answer {
MonitorColor::Profile(path) => format!("the monitor's profile, {}", path.display()),
MonitorColor::ManagedByWindows => "Windows colour-manages this monitor (HDR or Auto Color Management): previews are sRGB".into(),
MonitorColor::NoProfile => "no profile is assigned to the monitor: previews are sRGB".into(),
MonitorColor::Unknown => "not known for this monitor: previews are sRGB".into(),
}
}
+4
View File
@@ -68,6 +68,10 @@ sync_github_name = true
[people.ronibalthazar]
sync_github_name = true
[people.esli1283]
real_name = "Aaron Lopez"
sync_github_name = false
[people.dotCooCoo]
real_name = "Robert Lee"
sync_github_name = true
+132 -28
View File
@@ -25,6 +25,12 @@
//! - a bad record **followed by good ones** is real damage: replay stops there, the log is kept
//! as `catalog.log.damaged-<seq>`, and a fresh snapshot is written so the library stays usable.
//!
//! Segmentation grids are shared within a snapshot (issue #2154): each distinct grid is written
//! once into `Catalog.grids` and the masks of the photo's develop settings, versions, history
//! steps and import look refer to it by index, so an unchanged mask no longer repeats with every
//! history step. The table lives only in the snapshot file; log records keep the full grids
//! inline.
//!
//! **Background compaction** ([`Journal::snapshot_in_background`], when the store offers a
//! [`Store::background_writer`]): a worker thread writes the snapshot of a copy of the catalog at
//! op `N` while appends go on (durably, as always) to the same log. Once the snapshot is durable,
@@ -57,6 +63,7 @@
//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` |
//! | 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` |
//!
//! Rules:
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
@@ -81,7 +88,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 = 11;
pub const VERSION: u32 = 12;
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
#[derive(Clone, Copy, Debug)]
@@ -272,12 +279,18 @@ fn newer(what: String) -> CatalogError {
CatalogError::Newer(format!("{what}; this version reads catalog format v{VERSION} and older"))
}
/// The most `resync` spends re-validating the suffixes of one line whose whole bytes are not valid
/// UTF-8 (a real fragment ends at any byte): one line of a modest malformed log that holds a start
/// of a record in every few bytes used to re-validate the whole remaining suffix at every attempt
/// (CWE-407). Past the budget the rest of the line stays a torn tail, which the damaged path keeps
/// and reports, same state as before, minus the CPU.
const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
#[cfg(test)]
thread_local! {
/// Start markers that `resync` decoded on this thread (test builds only; see the cost test).
pub(crate) static RESYNC_CANDIDATES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Total bytes of candidate suffixes `resync` may decode per damaged line: every attempt reads
/// the rest of the line, so trying every candidate of a crafted line would make
/// [`Journal::open`] quadratic in the line length (CWE-407). The budget is far above any
/// fragment-plus-retry a failed append can leave, but caps the stall; past it the line reads as
/// damage, which is handled safely.
pub(crate) const MAX_SCAN: usize = 64 << 20;
/// A line that doesn't decode but ends with a whole record: a fragment of a failed append followed
/// by the record that retried it (the retry re-encodes the same ops with the same `seq`s). Returns
@@ -285,32 +298,70 @@ const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
/// The record's CRC must match, so damage is never mistaken for it.
fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> {
const START: &[u8] = b"{\"seq\":";
// One record per line, so a line of valid UTF-8 holds a valid suffix at every record start and
// one validation covers every candidate; only a line that is not wholly valid re-checks, and
// then up to the budget rather than the suffix length times the candidate count.
let whole = std::str::from_utf8(line).ok();
let mut spent = 0usize;
(1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| {
let text = match &whole {
Some(t) => &t[i..],
None => {
if spent >= RESYNC_BUDGET_BYTES {
return None;
}
spent = spent.saturating_add(line.len() - i);
std::str::from_utf8(&line[i..]).ok()?
}
// The retry record starts with the `{"seq":` marker, but that marker can also occur inside
// the op body (a smart-album rule value such as `{"seq":1}`); then the last occurrence is
// nested, not the record start, and decoding it rejects a valid retry. Scan every marker
// once, left to right, then try them from the end. A candidate must match the record header
// shape — `{"seq":<digits>,"crc":<digits>,"op":`, what `encode_record` writes — so a marker
// nested inside the op body (followed by `}` or `,`) or plain junk never reaches
// `decode_record`; only a real record start does. This imposes no fixed limit on how many
// nested markers a valid record may contain. Each attempt then decodes the rest of the line,
// so the scan budget bounds the total when a hostile line still holds many header-shaped
// markers, keeping the work near-linear instead of quadratic. The fragment that precedes the
// record stays to its left (`i > 0`).
let digits = |b: &[u8]| b.iter().take_while(|x| x.is_ascii_digit()).count();
let mut candidates: Vec<usize> = Vec::new();
let mut from = 0;
while let Some(i) = line[from..].windows(START.len()).position(|w| w == START) {
let pos = from + i;
let Some(after) = line.get(pos + START.len()..) else { break };
let seq_digits = digits(after);
let crc_field = after.get(seq_digits..).and_then(|rest| rest.strip_prefix(b",\"crc\":"));
let crc_digits = crc_field.map(digits).unwrap_or(0);
let op_field = crc_field.and_then(|rest| rest.get(crc_digits..)).and_then(|rest| rest.strip_prefix(b",\"op\":"));
if seq_digits > 0 && crc_digits > 0 && op_field.is_some() {
candidates.push(pos);
}
from = pos + START.len();
}
let mut scanned = 0usize;
for &i in candidates.iter().rev() {
if i == 0 {
break; // the record must follow a fragment
}
let Some(suffix) = line.get(i..) else { continue };
scanned = match scanned.checked_add(suffix.len()) {
Some(total) if total <= MAX_SCAN => total,
_ => break, // the budget is spent: stop trying further candidates
};
let rec = decode_record(text.trim_end_matches('\r'))?;
(rec.0 <= last.saturating_add(1)).then_some((i, rec))
})
let Ok(text) = std::str::from_utf8(suffix) else { continue };
#[cfg(test)]
RESYNC_CANDIDATES.with(|c| c.set(c.get() + 1));
if let Some((seq, op)) = decode_record(text.trim_end_matches('\u{0D}'))
&& seq <= last.saturating_add(1)
{
return Some((i, (seq, op)));
}
}
None
}
/// Write `catalog.snap` for the state after op `seq`, streaming the JSON into the store (no
/// whole-file string). The bytes are exactly
/// `{"format":"lightcraft-catalog","version":1,"seq":N,"catalog":<serde_json of the catalog>}\n`,
/// as before streaming. Fills in the serialise / write+sync times and the size.
/// as before streaming. Each distinct segmentation grid of the photos' settings holders (see
/// `Photo::settings_holders`) is written once (`Catalog.grids`), with the masks referring to it
/// by index, so an unchanged mask does not repeat with every history step (issue #2154). Fills
/// in the serialise / write+sync times and the size.
fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io::Result<SnapshotTiming> {
write_snapshot_owned(store, seq, catalog.clone())
}
/// The same write, taking the catalog by value: the background path hands over the copy it
/// already made, so a snapshot in flight holds one catalog, not two ([`Catalog::clone`] copies
/// the photo pointers and the small tables, and the derived indexes start empty — real work on a
/// large library).
fn write_snapshot_owned(store: &mut dyn Store, seq: u64, mut snapshot: Catalog) -> std::io::Result<SnapshotTiming> {
let t0 = web_time::Instant::now();
let mut serialize_ms = 0.0;
let bytes = store.write_atomic_with(SNAPSHOT, &mut |w| {
@@ -320,7 +371,35 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io
// 1 MiB chunks go through the store's `dyn Write`
let mut b = std::io::BufWriter::with_capacity(1 << 20, w);
write!(b, "{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":{seq},\"catalog\":")?;
serde_json::to_writer(&mut b, catalog).map_err(std::io::Error::other)?;
// The shared grids, in first-appearance order. The pool is a serialization detail:
// `snapshot` itself is never modified (log records, presets and XMP stay inline).
let mut pool: Vec<String> = Vec::new();
let mut index: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
{
let mut see = |s: &lightcraft_develop::DevelopSettings| {
s.visit_seg_masks(&mut |m| {
// borrowed lookup: a grid every history step shares is not cloned just to
// find it already indexed (only a new grid is copied, into pool and table)
if !m.data.is_empty() && !index.contains_key(m.data.as_str()) {
index.insert(m.data.clone(), pool.len() as u32);
pool.push(m.data.clone());
}
});
};
for p in snapshot.photos.values() {
for settings in p.settings_holders() {
see(settings);
}
}
}
snapshot.grids = pool;
match lightcraft_develop::with_grid_interner(index, || serde_json::to_writer(&mut b, &snapshot)) {
// no interner can be active here (snapshot writes don't nest), so `None` is a bug:
// fail the write rather than store a truncated or reference-less snapshot
Some(Ok(())) => {}
Some(Err(e)) => return Err(std::io::Error::other(e)),
None => return Err(std::io::Error::other("nested grid interner while writing a snapshot")),
}
b.write_all(b"}\n")?;
b.flush()?;
serialize_ms = ms_since(t);
@@ -607,7 +686,7 @@ impl Journal {
let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) };
let copy = catalog.clone();
let seq = self.seq;
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot(writer.as_mut(), seq, &copy));
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot_owned(writer.as_mut(), seq, copy));
let worker = match spawned {
Ok(w) => w,
Err(e) => {
@@ -792,4 +871,29 @@ mod tests_resync {
// matches, so the double `Some` is only reached with `last >= 4`
assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
}
/// A retry record whose op body holds more than eight nested `{"seq":` markers (a
/// `SetAlbumRules` with nine rule values of `{"seq":1}`) exhausts `resync`'s fixed
/// `MAX_DECODES = 8` decode budget on the nested markers, so the outer record's real
/// start is never decoded and the valid operation is truncated as damage.
#[test]
fn resync_recovers_retry_beyond_eight_nested_markers() {
let mut c = Catalog::new();
let album_id = c.alloc_album_id();
let mut rules = Vec::new();
for _ in 0..9 {
rules.push(crate::Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) });
}
let retry_op = Op::SetAlbumRules {
id: album_id,
rules: Box::new(crate::Filter { rule_set: Some(crate::RuleSet { mode: crate::Match::All, rules }), ..Default::default() }),
};
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let record = format!("{{\"seq\":5,\"crc\":{crc},\"op\":{body}}}");
let mut line = Vec::from(b"torn fragment" as &[u8]);
let fragment = line.len();
line.extend_from_slice(record.as_bytes());
assert_eq!(resync(&line, 4).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
}
}
+45
View File
@@ -289,6 +289,13 @@ pub struct Catalog {
/// What the library keeps about its folders (folder identity → record), see [`folders`].
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
folder_records: BTreeMap<String, FolderRecord>,
/// Segmentation grids shared by this snapshot's masks: each distinct grid's data once, in
/// first-appearance order, referenced by index from the masks ([`lightcraft_develop::\
/// SegMask::grid`] is a position here). A serialization detail of snapshots
/// ([`journal`]): never held in the live catalog — [`Catalog::repair`] resolves the
/// references and clears the table when a snapshot is read.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
grids: Vec<String>,
/// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog
/// changed, so what is keyed by the revision is out of date).
#[serde(skip)]
@@ -367,6 +374,25 @@ impl std::fmt::Debug for PlansMemo {
}
}
/// Resolves the shared-grid references of one settings holder (see [`Photo::settings_holders`])
/// against a snapshot's grid table: each referenced mask takes its
/// grid's data and the reference is cleared. A reference past the table (a damaged snapshot)
/// leaves the mask empty — it renders nothing, like any other damaged grid. Data present on the
/// mask itself wins over a stray reference. Returns the dangling count added to `dangling`.
fn resolve_grids(settings: &mut Arc<DevelopSettings>, grids: &[String], dangling: usize) -> usize {
let mut dangling = dangling;
Arc::make_mut(settings).visit_seg_masks_mut(&mut |m| {
if let Some(i) = m.grid.take() {
match (m.data.is_empty(), grids.get(i as usize)) {
(true, Some(data)) => m.data = data.clone(),
(true, None) => dangling += 1,
(false, _) => {}
}
}
});
dangling
}
/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can
/// follow a small edit without being worked out again from every photo.
#[derive(Clone, Debug, Default)]
@@ -1192,6 +1218,23 @@ impl Catalog {
/// wrote).
pub fn repair(&mut self) -> Vec<String> {
let mut changed = Vec::new();
// Segmentation grids shared by the snapshot this was read from (issue #2154): each
// reference takes its grid's data, and the table is not kept — a live catalog always
// stores the data inline, so masks render and serialize without the snapshot's table.
// Resolving is the normal way a snapshot in this format reads (not reported); a
// reference past the table is damage and is reported — that includes a reference into
// an empty table, which is always dangling, so the table being empty does not skip it.
let grids = std::mem::take(&mut self.grids);
let mut dangling = 0usize;
for p in self.photos.values_mut() {
let photo = Arc::make_mut(p);
for settings in photo.settings_holders_mut() {
dangling = resolve_grids(settings, &grids, dangling);
}
}
if dangling > 0 {
changed.push(format!("{dangling} segmentation grid reference(s) pointed past the shared table: cleared"));
}
for (id, p) in self.photos.iter_mut() {
if p.id != *id {
changed.push(format!("photo {} was filed as {}", p.id.0, id.0));
@@ -1488,6 +1531,8 @@ mod tests_folders;
#[cfg(test)]
mod tests_format_version;
#[cfg(test)]
mod tests_grids;
#[cfg(test)]
mod tests_index;
#[cfg(test)]
mod tests_journal;
+1
View File
@@ -238,6 +238,7 @@ impl Writer {
return Ok(());
}
self.file = None;
crate::store::check_regular_directory_entry(&self.path)?;
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
+17
View File
@@ -439,6 +439,23 @@ impl Photo {
pub fn relative_wb(&self) -> bool {
self.develops_raw() && relative_wb_camera(&self.format, &self.meta.camera)
}
/// Every settings holder of this photo that can carry segmentation grids: the develop
/// settings, the versions', the history steps' and the import look. A snapshot's shared grid
/// table ([`crate::Catalog`]'s `grids`) covers all of them, so a new holder belongs here.
pub(crate) fn settings_holders(&self) -> impl Iterator<Item = &Arc<DevelopSettings>> {
std::iter::once(&self.develop)
.chain(self.versions.iter().map(|v| &v.settings))
.chain(self.history.iter().map(|h| &h.settings))
.chain(self.import_look.iter())
}
/// [`Photo::settings_holders`] with mutable access (resolving a snapshot's grid references).
pub(crate) fn settings_holders_mut(&mut self) -> impl Iterator<Item = &mut Arc<DevelopSettings>> {
let Photo { develop, versions, history, import_look, .. } = self;
std::iter::once(develop)
.chain(versions.iter_mut().map(|v| &mut v.settings))
.chain(history.iter_mut().map(|h| &mut h.settings))
.chain(import_look.as_mut())
}
/// The develop settings import gave this photo: [`Photo::camera_defaults`], or the user's
/// default preset applied on top of them ([`Photo::import_look`]). Like the camera defaults,
/// in the photo's own rendering process.
+3 -2
View File
@@ -238,8 +238,9 @@ fn op_variants_are_versioned() {
Op::SetHistoryCursor { .. } => 8,
}
}
/// v11: `EmbeddedLens.source` (v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
const NEWEST_FIELDS: u32 = 11;
/// 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;
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");
}
+392
View File
@@ -0,0 +1,392 @@
//! Issue #2154: a snapshot keeps each distinct segmentation grid once (`Catalog.grids`) and the
//! masks of the develop settings, versions, history steps and import look refer to it by index,
//! so an unchanged mask no longer repeats with every history step. In-memory catalogs and log
//! records always hold the grids inline; older catalogs (inline everywhere) load and are upgraded.
use std::sync::Arc;
use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape, SegMask};
use crate::journal::{LOG, SNAPSHOT, VERSION};
use crate::*;
fn snapshot_version(m: &MemStore) -> u64 {
let v: serde_json::Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap();
v["version"].as_u64().unwrap()
}
fn open(m: &MemStore) -> (Journal, Catalog, LoadReport) {
Journal::open(Box::new(m.clone())).unwrap()
}
/// Develop settings with one AI mask over an object segmentation.
fn settings_with_seg(seg: SegMask, exposure: f64) -> DevelopSettings {
let mut s = DevelopSettings::default();
s.light.exposure = exposure;
s.masks.push(Mask {
id: 1,
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Object {
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
exclude: vec![],
seg: Some(seg),
detail: vec![],
edge: 0.0,
},
}],
..Default::default()
});
s
}
/// One mask (`id`) whose only component is an Object segmentation `seg`.
fn object_mask(id: u32, seg: SegMask) -> Mask {
Mask {
id,
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Object {
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
exclude: vec![],
seg: Some(seg),
detail: vec![],
edge: 0.0,
},
}],
..Default::default()
}
}
/// A catalog of one photo whose history is `steps` slider edits over the same mask, plus the
/// ops that built it (each step is one `SetDevelop` + one `PushHistory`, as the engine commits
/// an edit) and the shared grid's bytes.
fn masked_catalog(steps: usize) -> (Catalog, Vec<Op>, PhotoId, String) {
let seg = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
let blob = seg.data.clone();
let mut c = Catalog::new();
let id = c.alloc_photo_id();
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::File { path: "/p/1.jpg".into() }, "1.jpg", "JPEG", 60, 40, "2026-01-01")) };
c.apply(add.clone()).unwrap();
let mut ops = vec![add];
for i in 1..=steps {
let settings = Arc::new(settings_with_seg(seg.clone(), f64::from(i as u32) * 0.1));
let op = Op::Batch {
ops: vec![
Op::SetDevelop { id, settings: settings.clone(), label: "Exposure".into(), edited: Some(format!("t{i}")) },
Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings } },
],
};
c.apply(op.clone()).unwrap();
ops.push(op);
}
(c, ops, id, blob)
}
/// N history steps over one mask store the grid exactly once and load back identical.
#[test]
fn snapshot_deduplicates_shared_grid() {
let (live, ops, id, blob) = masked_catalog(20);
let m = MemStore::new();
let (mut j, _, report) = open(&m);
assert!(report.created);
j.append(&ops).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let body = std::str::from_utf8(&snap_bytes).unwrap();
assert_eq!(snapshot_version(&m), u64::from(VERSION));
assert_eq!(body.match_indices(&blob).count(), 1, "the grid is stored once for every step that shares it");
let v: serde_json::Value = serde_json::from_str(body).unwrap();
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 1);
let (_, loaded, report) = open(&m);
assert_eq!((report.replayed, report.upgraded_from, report.repaired.len()), (0, None, 0));
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
let p = loaded.photo(id).unwrap();
assert_eq!(p.history.len(), 20);
for h in &p.history {
let MaskShape::Object { seg: Some(seg), .. } = &h.settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), (blob.as_str(), None), "every step's grid is back inline");
}
}
/// A catalog written before the shared table (grids inline everywhere, format v9) loads as it
/// was and its upgrade rewrite deduplicates.
#[test]
fn v9_catalog_with_inline_grids_loads_and_is_upgraded() {
let (live, _, _, blob) = masked_catalog(3);
let body = live.to_snapshot();
assert!(body.contains(&blob), "a live catalog stores its grids inline");
let m = MemStore::new();
m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":2,\"catalog\":{body}}}\n").into_bytes());
let (_, loaded, report) = open(&m);
assert_eq!((report.replayed, report.upgraded_from), (0, Some(9)));
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
// rewritten in this format before anything is appended, with the grid once
assert_eq!(snapshot_version(&m), u64::from(VERSION));
let rewritten_bytes = m.get(SNAPSHOT).unwrap();
let rewritten = std::str::from_utf8(&rewritten_bytes).unwrap();
assert_eq!(rewritten.match_indices(&blob).count(), 1);
assert!(rewritten.contains("\"grids\":["), "the shared table is in the file");
}
/// The op log is not deduplicated: every record keeps the grids inline (a log never carries the
/// shared table), and replaying it rebuilds the same state.
#[test]
fn log_records_keep_their_grids_inline() {
let (live, ops, _, blob) = masked_catalog(2);
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&ops).unwrap();
drop(j); // no snapshot: the log holds the whole state
let log_bytes = m.get(LOG).unwrap();
let log = std::str::from_utf8(&log_bytes).unwrap();
assert_eq!(log.match_indices(&blob).count(), 4, "two edits, SetDevelop + PushHistory each, inline");
let (_, loaded, report) = open(&m);
assert_eq!(report.replayed, 3, "the photo and the two edits");
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
}
/// A reference that points past the shared table is cleared (the mask renders nothing, like any
/// damaged grid); a good reference resolves back to the full grid.
#[test]
fn shared_grid_references_resolve_or_are_repaired() {
let (live, _, id, blob) = masked_catalog(1);
let inline = live.to_snapshot();
// a damaged snapshot: the develop mask refers past the one-entry table
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":7", 1);
let m = MemStore::new();
m.set(
SNAPSHOT,
format!(
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"dHdv\"],{} }} }}\n",
&body[1..body.len() - 1]
)
.into_bytes(),
);
let (_, damaged, report) = open(&m);
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
let p = damaged.photo(id).unwrap();
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared, never a crash");
// the history step's inline grid is untouched
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!(seg.data, blob);
// a good reference resolves (the normal way a snapshot in this format reads, so it is not
// reported as a repair): the mask reads exactly as it was written
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
let m = MemStore::new();
m.set(
SNAPSHOT,
format!(
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"{blob}\"],{} }} }}\n",
&body[1..body.len() - 1]
)
.into_bytes(),
);
let (_, resolved, report) = open(&m);
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
assert_eq!(resolved.to_snapshot(), live.to_snapshot());
}
/// The background snapshot path shares the grids too (the interner is per thread).
#[test]
fn background_snapshot_deduplicates_shared_grid() {
let (live, ops, _, blob) = masked_catalog(5);
let mut m = MemStore::new();
m.background = true;
let (mut j, _, _) = open(&m);
j.append(&ops).unwrap();
j.snapshot_in_background(&live).unwrap();
j.wait().unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let body = std::str::from_utf8(&snap_bytes).unwrap();
assert_eq!(body.match_indices(&blob).count(), 1);
let (_, loaded, _) = open(&m);
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
}
/// A version (not only history steps) shares the grid: one photo with a snapshot version and a
/// history step over the same mask stores the grid once.
#[test]
fn versions_share_the_grid_too() {
let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]);
let blob = seg.data.clone();
let id = PhotoId(1);
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, "d.jpg", "JPEG", 60, 40, "2026-01-01")) };
let settings = Arc::new(settings_with_seg(seg, 0.5));
let versions =
Op::SetVersions { id, versions: vec![Version { name: "v".into(), created: "2026-01-01".into(), settings: settings.clone(), auto: false }] };
let history = Op::PushHistory { id, step: HistoryStep { label: "e".into(), settings } };
let mut live = Catalog::new();
for op in [&add, &versions, &history] {
live.apply(op.clone()).unwrap();
}
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&[add, versions, history]).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let body = std::str::from_utf8(&snap_bytes).unwrap();
assert_eq!(body.match_indices(&blob).count(), 1, "the version and the step share the grid");
let (_, loaded, _) = open(&m);
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
}
/// The import look (`Photo.import_look`, the settings a default preset gave the photo on import)
/// can hold AI masks, and their grids can be grids the develop settings or a history step hold.
/// Every settings holder shares the snapshot's table, so the look's masks are referenced and
/// resolved on load like the others; a grid only the look holds is in the table too.
#[test]
fn import_look_masks_share_the_table_and_resolve_on_load() {
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
let look_only = SegMask::from_logits(64, &vec![-0.5f32; 64 * 64]);
let mut look = DevelopSettings::default();
look.masks.push(object_mask(1, shared.clone()));
look.masks.push(object_mask(2, look_only.clone()));
let mut edit = DevelopSettings::default();
edit.light.exposure = 0.7;
edit.masks.push(object_mask(1, shared.clone()));
let edit = Arc::new(edit);
let id = PhotoId(1);
let mut photo = Photo::new(id, Source::File { path: "/p/2.jpg".into() }, "2.jpg", "JPEG", 60, 40, "2026-01-01");
photo.develop = edit.clone();
photo.import_look = Some(Arc::new(look));
photo.history.push(HistoryStep { label: "Exposure".into(), settings: edit });
let add = Op::AddPhoto { photo: Box::new(photo) };
let mut live = Catalog::new();
live.apply(add.clone()).unwrap();
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&[add]).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let body = std::str::from_utf8(&snap_bytes).unwrap();
assert_eq!(body.match_indices(&shared.data).count(), 1, "the grid of the look and of the edit is stored once");
assert_eq!(body.match_indices(&look_only.data).count(), 1);
let (_, loaded, report) = open(&m);
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
let p = loaded.photo(id).unwrap();
let look_masks = &p.import_look.as_ref().unwrap().masks;
assert_eq!(look_masks.len(), 2);
for (mask, want) in look_masks.iter().zip([&shared, &look_only]) {
let MaskShape::Object { seg: Some(seg), .. } = &mask.components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), (want.data.as_str(), None), "the look's grid is back inline");
}
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
let v: serde_json::Value = serde_json::from_str(body).unwrap();
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 2, "one table entry per distinct grid, the look's included");
}
/// A `grid` that arrives from a document (a command's mask JSON, a preset, a merged partial) is
/// not a reference and is never written as one: a snapshot must not resolve it to another mask's
/// grid. Here photo two's mask carries `grid: 0` with empty data, while photo one's grid is the
/// table's entry 0; before the fix the inline form wrote `"grid":0` and the load filled photo two
/// with photo one's grid.
#[test]
fn stray_grid_from_a_document_is_not_written_as_a_reference() {
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
let stray: SegMask = serde_json::from_str(r#"{"side":64,"data":"","grid":0}"#).unwrap();
assert_eq!(stray.grid, Some(0), "a document can set grid");
let mut stray_settings = DevelopSettings::default();
stray_settings.masks.push(object_mask(1, stray));
let (one, two) = (PhotoId(1), PhotoId(2));
let photo = |id: PhotoId, name: &str| Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01");
let ops = [
Op::AddPhoto { photo: Box::new(photo(one, "1.jpg")) },
Op::SetDevelop { id: one, settings: Arc::new(settings_with_seg(shared.clone(), 0.2)), label: "Exposure".into(), edited: Some("t1".into()) },
Op::AddPhoto { photo: Box::new(photo(two, "2.jpg")) },
Op::SetDevelop { id: two, settings: Arc::new(stray_settings), label: "Edit".into(), edited: Some("t2".into()) },
];
let mut live = Catalog::new();
for op in &ops {
live.apply(op.clone()).unwrap();
}
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&ops).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let (_, loaded, report) = open(&m);
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
let MaskShape::Object { seg: Some(seg), .. } = &loaded.photo(two).unwrap().develop.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the stray reference is not resolved to photo one's grid");
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
}
/// A snapshot whose shared grid table is empty (`grids: []`) but whose masks still refer into
/// it: the table being empty must not skip the repair. A reference past an empty table is
/// dangling, so it is cleared (the mask renders nothing, like any other damaged grid), the
/// repair is reported, and a mask that carries its own grid inline is left untouched.
#[test]
fn empty_shared_grid_table_clears_dangling_references() {
let (live, _, id, blob) = masked_catalog(1);
let inline = live.to_snapshot();
// a damaged snapshot: an empty table, but the develop mask still refers to entry 0
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
let m = MemStore::new();
m.set(
SNAPSHOT,
format!(
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[],{} }} }}\n",
&body[1..body.len() - 1]
)
.into_bytes(),
);
let (_, damaged, report) = open(&m);
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
let p = damaged.photo(id).unwrap();
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with an empty table");
// the history step carries its grid inline: nothing there to resolve, left as it was
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
}
/// A snapshot that omits the shared grid table entirely (no `grids` key) but whose masks still
/// refer into it: an absent table deserializes to an empty Vec, so a reference past it is
/// dangling and is cleared and reported, just like the empty-table case.
#[test]
fn omitted_shared_grid_table_clears_dangling_references() {
let (live, _, id, blob) = masked_catalog(1);
let inline = live.to_snapshot();
// a damaged snapshot: no table at all, but the develop mask still refers to entry 0
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
let m = MemStore::new();
m.set(
SNAPSHOT,
format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{{} }} }}\n", &body[1..body.len() - 1])
.into_bytes(),
);
let (_, damaged, report) = open(&m);
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
let p = damaged.photo(id).unwrap();
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with no table");
// the history step carries its grid inline: nothing there to resolve, left as it was
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
}
+206 -1
View File
@@ -4,7 +4,7 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use crate::journal::LOG;
use crate::journal::{LOG, RESYNC_CANDIDATES};
use crate::*;
/// A store whose next append writes only a prefix of its data, then fails.
@@ -224,3 +224,208 @@ fn fs_store_truncates_a_missing_file_quietly() {
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"");
let _ = std::fs::remove_dir_all(&dir);
}
/// Issue #2124: `resync` must be linear in the line length, not quadratic. A line that is nothing
/// but the start marker repeated 300k times must open fast, and a valid retry record placed after
/// it must still be recovered.
#[test]
fn resync_is_not_quadratic_in_line_length() {
let probe = MemStore::new();
// Build a valid snapshot + an initial record so `j.seq()` is non-zero and the `seq <= last + 1`
// gate in resync can be exercised.
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
let add = add_photo(&mut c);
let first = apply(&mut c, vec![add]);
j.append(&first).unwrap();
let log = probe.get(LOG).unwrap();
let base_len = log.len();
// A hostile 300k-repetition marker line (about 2.3 MB), then one valid retried record that
// continues the log (seq == j.seq() + 1, so resync's gate accepts it).
let marker = b"{\"seq\":";
let mut hostile = Vec::with_capacity(marker.len() * 300_000 + log.len() + 256);
hostile.extend_from_slice(&log[..base_len]);
for _ in 0..300_000 {
hostile.extend_from_slice(marker);
}
// Encode the retry record the same way the journal writes records, so decode_record accepts it.
let next_seq = j.seq() + 1;
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
hostile.extend_from_slice(retry.as_bytes());
probe.set(LOG, hostile);
// Count the start markers resync decodes instead of timing it: a slow worker must not fail this.
RESYNC_CANDIDATES.with(|c| c.set(0));
let (j2, _c2, report) = Journal::open(Box::new(probe.clone())).unwrap();
let candidates = RESYNC_CANDIDATES.with(|c| c.get());
assert!(candidates <= 1, "resync decoded {candidates} start markers of a hostile 2 MB line; only the last one may be decoded");
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
}
/// A retry record whose op body holds a nested `{"seq":` (a smart-album rule value such as
/// `{"seq":1}` on a `title isEmpty` rule) shadows the record's own start marker: `rposition` in
/// `resync` picks the nested occurrence, `decode_record` rejects the suffix, and `Journal::open`
/// truncates the final line instead of replaying the retry — the valid operation is lost.
#[test]
fn resync_preserves_retry_record_with_nested_start_marker() {
let probe = MemStore::new();
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
let add = add_photo(&mut c);
j.append(&apply(&mut c, vec![add])).unwrap();
let album_id = c.alloc_album_id();
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
j.append(&apply(&mut c, vec![add_album])).unwrap();
let retry_op = Op::SetAlbumRules {
id: album_id,
rules: Box::new(Filter {
rule_set: Some(RuleSet {
mode: Match::All,
rules: vec![Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }],
}),
..Default::default()
}),
};
apply(&mut c, vec![retry_op.clone()]);
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
// resync finds its real start: `seq` continues the log and the CRC matches the body.
let next_seq = j.seq() + 1;
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
// A torn fragment glued to the retry on the final line. The outer record start sits right
// after the fragment, but the last `{"seq":` byte occurrence is the nested rule value.
let mut log = probe.get(LOG).unwrap();
log.extend_from_slice(b"torn fragment without a newline");
log.extend_from_slice(retry.as_bytes());
probe.set(LOG, log);
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be truncated as torn");
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the recovered smart-album rule should be preserved");
}
/// The maintainer's regression for issue #2124, with the damaged line as the file's LAST one: a
/// torn fragment glued to a CRC-valid `SetAlbumRules` retry whose rules hold several nested
/// `{"seq":1}` values. Picking the last raw `{"seq":` occurrence as the record start (as the
/// original `rposition` scan did) lands in a nested value, rejects the whole record, and cuts the
/// final line away — losing the valid operation. `resync` must recover the retry (its real start
/// is followed by the `,"crc":` header no nested rule value has) and leave the log file whole.
#[test]
fn resync_recovers_rules_retry_with_many_nested_values_on_the_final_line() {
let probe = MemStore::new();
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
let add = add_photo(&mut c);
j.append(&apply(&mut c, vec![add])).unwrap();
let album_id = c.alloc_album_id();
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
j.append(&apply(&mut c, vec![add_album])).unwrap();
let rules =
(0..12).map(|_| Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }).collect::<Vec<_>>();
let retry_op =
Op::SetAlbumRules { id: album_id, rules: Box::new(Filter { rule_set: Some(RuleSet { mode: Match::All, rules }), ..Default::default() }) };
apply(&mut c, vec![retry_op.clone()]);
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
// resync finds its real start: `seq` continues the log and the CRC matches the body.
let next_seq = j.seq() + 1;
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}");
// The failed append's fragment glued to the retry, and nothing after: the damaged line is the
// file's last, without a closing newline.
let mut log = probe.get(LOG).unwrap();
log.extend_from_slice(b"torn fragment without a newline");
log.extend_from_slice(retry.as_bytes());
let damaged = log.clone();
probe.set(LOG, log);
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
assert_eq!(report.torn_fragments, 1, "the fragment must be reported and the retry recovered");
assert_eq!(report.torn_bytes, 0, "the retry record must not be cut away as a torn tail");
assert_eq!(j2.seq(), next_seq, "the retried SetAlbumRules must be recovered");
assert_eq!(report.replayed, 3);
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the smart-album rules must survive the reload");
// The log file is preserved: its bytes stay (plus only the newline that closes the final
// line), instead of the damaged line being truncated away.
let after = probe.get(LOG).unwrap();
assert_eq!(after.len(), damaged.len() + 1, "the log must keep the fragment and the recovered record");
assert_eq!(&after[..damaged.len()], &damaged[..]);
}
/// A crafted final line of many header-shaped markers (`{"seq":1,"crc":2,"op":`) passes the
/// record-header filter, so every marker becomes a resync candidate, and each attempt decodes the
/// whole rest of the line: trying all of them is quadratic in the line length, a stall of
/// `Journal::open` on a hostile log (CWE-407). The per-line scan budget must bound the candidate
/// decodes (counted, not timed) and open must still finish safely. A CRC-valid retry placed after
/// the junk must stay recoverable: it is the last candidate, so the scan reaches it first.
#[test]
fn resync_scan_budget_bounds_a_line_of_header_shaped_markers() {
let probe = MemStore::new();
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
let add = add_photo(&mut c);
j.append(&apply(&mut c, vec![add])).unwrap();
let good = probe.get(LOG).unwrap();
const MARKERS: usize = 5_000;
let marker: &[u8] = b"{\"seq\":1,\"crc\":2,\"op\":";
let mut hostile = good.clone();
hostile.extend_from_slice(b"torn fragment"); // so no marker sits at line position 0
for _ in 0..MARKERS {
hostile.extend_from_slice(marker);
}
let hostile_len = (hostile.len() - good.len()) as u64;
probe.set(LOG, hostile);
RESYNC_CANDIDATES.with(|count| count.set(0));
let (j2, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
assert!(
candidates < MARKERS,
"resync tried all {candidates} candidates of a hostile {hostile_len}-byte line; the scan budget must bound the work"
);
assert!(report.damaged.is_none(), "{report:?}");
assert_eq!(report.torn_fragments, 0);
assert_eq!(report.torn_bytes, hostile_len, "the hostile line must be dropped as a torn tail");
assert_eq!(j2.seq(), 1, "the records before the hostile line must survive");
assert_eq!(probe.get(LOG).unwrap().len(), good.len(), "the log must be cut back to the last good record");
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
let next_seq = j2.seq() + 1;
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let mut log = good.clone();
for _ in 0..MARKERS {
log.extend_from_slice(marker);
}
log.extend_from_slice(format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n").as_bytes());
probe.set(LOG, log);
RESYNC_CANDIDATES.with(|count| count.set(0));
let (j3, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
assert_eq!(candidates, 1, "the retry is the last candidate and must decode first");
assert_eq!(j3.seq(), next_seq, "the retried record after the junk must be recovered");
assert_eq!(report.torn_fragments, 1, "the junk before the retry is one skipped fragment");
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be cut away");
}
+207
View File
@@ -862,3 +862,210 @@ mod tests {
}
}
}
/// [`crate::decode_jpeg_srgb8_fit`]: a plain 8-bit sRGB JPEG decoded (DCT-scaled when that still
/// covers the box) and area-averaged in linear light straight into 8-bit sRGB, without the
/// float image the general path builds (for a 45 MP camera preview fitted to 2560 px that float
/// image and its conversions were half the time). `Ok(None)` for anything else.
pub(crate) fn srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result<Option<(lightcraft_raster::Rgba8, u16)>> {
// (a Samsung SEF trailer read as the file it stands for, as the general decode does: CodeRabbit on #3583)
let bytes = &*without_sef_trailer(bytes);
let Some(m) = parse_markers(bytes) else { return Ok(None) };
let plain = matches!(m.components, 1 | 3)
&& m.precision == 8
&& matches!(m.sof, 0xC0..=0xC2)
&& m.icc.is_none()
&& !m.icc_invalid
&& m.adobe_transform.is_none();
let summary = m.exif.as_deref().map(exif::summarize).unwrap_or_default();
if !plain || summary.adobe_rgb_hint || max_w == 0 || max_h == 0 {
return Ok(None);
}
let budget = DecodeOptions::default();
check_size(F, m.width as u64, m.height as u64, &budget)?;
// as in the general decode: the decoders below walk every APP1 again
if m.app1 > MAX_APP1 {
return Err(Error::Malformed(F, "too many APP1 markers".into()));
}
let scale_to = (m.width >= max_w.saturating_mul(2) || m.height >= max_h.saturating_mul(2)).then_some((max_w, max_h));
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
let raw =
if scale_to.is_some() || non_interleaved { decode_jpeg_decoder(bytes, &m, scale_to, &budget)? } else { decode_zune(bytes, &m, &budget)? };
let Buf::U8(px) = &raw.buf else { return Ok(None) };
let ch = match raw.model {
Model::Rgb => 3,
Model::Gray => 1,
Model::Cmyk => return Ok(None),
};
let (w, h) = (raw.width, raw.height);
if w == 0 || h == 0 || px.len() < w.saturating_mul(h).saturating_mul(ch) {
return Err(Error::Malformed(F, "short output".into()));
}
// the size `lightcraft_raster::resample::fit` gives: within the box, aspect kept, never larger
let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0);
let tw = ((w as f64 * s).round() as usize).clamp(1, w);
let th = ((h as f64 * s).round() as usize).clamp(1, h);
let orientation = summary.orientation.filter(|o| (1..=8).contains(o)).unwrap_or(1);
Ok(Some((area_average_srgb8(px, w, h, ch, tw, th), orientation)))
}
/// Source pixels and weights each output pixel along one axis covers: a box of the scale's width
/// (`n` source pixels onto `out`), partly covered pixels at its ends weighted by their share.
fn box_taps(n: usize, out: usize) -> Vec<(usize, Vec<f32>)> {
let scale = n as f64 / out as f64;
(0..out)
.map(|o| {
let (a, b) = (o as f64 * scale, ((o + 1) as f64 * scale).min(n as f64));
let first = (a.floor() as usize).min(n - 1);
let last = ((b.ceil() as usize).max(first + 1)).min(n);
let ws: Vec<f32> =
(first..last).map(|j| ((b.min(j as f64 + 1.0) - a.max(j as f64)).max(0.0) / (b - a).max(f64::MIN_POSITIVE)) as f32).collect();
(first, ws)
})
.collect()
}
/// `px` (`w × h`, `ch` = 1 or 3 interleaved 8-bit sRGB samples) averaged over boxes in linear
/// light into `tw × th` opaque 8-bit sRGB pixels. A copy when the size doesn't change.
fn area_average_srgb8(px: &[u8], w: usize, h: usize, ch: usize, tw: usize, th: usize) -> lightcraft_raster::Rgba8 {
use lightcraft_color::transfer::{decode_srgb8, encode_srgb8};
let mut out = lightcraft_raster::Rgba8::new(tw, th);
let sample = |x: usize, y: usize, c: usize| px.get((y * w + x) * ch + if ch == 3 { c } else { 0 }).copied().unwrap_or(0);
if (tw, th) == (w, h) {
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
*o = [sample(x, y, 0), sample(x, y, 1), sample(x, y, 2), 255];
}
});
return out;
}
let lut: [f32; 256] = std::array::from_fn(|i| decode_srgb8(i as u8));
let xs = box_taps(w, tw);
let ys = box_taps(h, th);
// one source row filtered across into linear RGB at the output width
let across = |sy: usize, buf: &mut Vec<[f32; 3]>| {
buf.clear();
let Some(src) = px.get(sy * w * ch..(sy + 1) * w * ch) else {
buf.resize(tw, [0.0; 3]);
return;
};
for (x0, wx) in &xs {
let mut a = [0f32; 3];
if let Some(span) = src.get(x0 * ch..(x0 + wx.len()) * ch) {
for (p, &k) in span.chunks_exact(ch).zip(wx) {
match p {
[r, g, b] => {
a[0] += lut[*r as usize] * k;
a[1] += lut[*g as usize] * k;
a[2] += lut[*b as usize] * k;
}
[v] => {
let l = lut[*v as usize] * k;
a = [a[0] + l, a[1] + l, a[2] + l];
}
_ => {}
}
}
}
buf.push(a);
}
};
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
let Some((y0, wy)) = ys.get(y) else { return };
let mut acc = vec![[0f32; 3]; tw];
let mut line = Vec::with_capacity(tw);
for (dy, &k) in wy.iter().enumerate() {
across(y0 + dy, &mut line);
for (a, l) in acc.iter_mut().zip(&line) {
a[0] += l[0] * k;
a[1] += l[1] * k;
a[2] += l[2] * k;
}
}
for (o, a) in row.iter_mut().zip(&acc) {
*o = [encode_srgb8(a[0]), encode_srgb8(a[1]), encode_srgb8(a[2]), 255];
}
});
out
}
#[cfg(test)]
mod srgb8_fit_tests {
use super::*;
fn jpeg(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
let data: Vec<[u8; 4]> = (0..w * h)
.map(|i| {
let [r, g, b] = f(i % w, i / w);
[r, g, b, 255]
})
.collect();
let img = lightcraft_raster::Rgba8 { width: w, height: h, data };
crate::encode_jpeg(&crate::EncodeImage::rgba8(&img), 95, crate::ChromaSubsampling::S420, &crate::EncodeMeta::default()).unwrap()
}
/// The fast path shows what the general decode shows for a plain sRGB JPEG, at the same size.
#[test]
fn matches_the_general_decode_within_a_few_levels() {
let b = jpeg(1203, 801, |x, y| [((x * 7) ^ (y * 3)) as u8, (x / 5 + y / 3) as u8, ((x * y) % 251) as u8]);
for (mw, mh) in [(300u32, 300u32), (640, 640), (1203, 801), (5000, 5000), (500, 120)] {
let (fast, o) = srgb8_fit(&b, mw, mh).unwrap().unwrap();
let slow = crate::decode(&b, DecodeOptions::fit(mw, mh)).unwrap().to_srgb8();
assert_eq!((fast.width, fast.height), (slow.width, slow.height), "box {mw}×{mh}");
assert_eq!(o, 1);
let diff: Vec<u32> =
fast.data.iter().zip(&slow.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] as i32 - b[c] as i32).unsigned_abs())).collect();
let mean = diff.iter().sum::<u32>() as f64 / diff.len() as f64;
assert!(mean < 3.0, "box {mw}×{mh}: mean difference {mean}");
}
}
/// Anything but plain 8-bit sRGB goes the general way; junk is an error or `None`, never a panic.
#[test]
fn declines_what_it_does_not_cover_and_never_panics() {
let b = jpeg(64, 48, |x, _| [x as u8, 0, 0]);
assert!(srgb8_fit(&b, 0, 10).unwrap().is_none());
assert!(srgb8_fit(b"not a jpeg", 10, 10).unwrap().is_none());
for cut in [0, 2, 20, b.len() / 2, b.len() - 3] {
let _ = srgb8_fit(&b[..cut], 32, 32);
}
// a 1-pixel-wide image into a box much smaller in one axis
let thin = jpeg(1, 300, |_, y| [y as u8, y as u8, y as u8]);
let (img, _) = srgb8_fit(&thin, 10, 10).unwrap().unwrap();
assert_eq!((img.width, img.height), (1, 10));
}
/// An incomplete ICC_PROFILE sequence (chunk 1 of 2) is "has a profile we can't read", not
/// "plain sRGB": the general decode handles it, as the doc says (CodeRabbit on #3577).
#[test]
fn an_incomplete_icc_sequence_goes_the_general_way() {
let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]);
let mut seg = vec![0xFF, 0xE2, 0, 0];
seg.extend_from_slice(b"ICC_PROFILE");
seg.extend_from_slice(&[1, 2]);
seg.extend_from_slice(&[0u8; 64]);
let len = u16::try_from(seg.len() - 2).unwrap();
seg[2..4].copy_from_slice(&len.to_be_bytes());
let mut with = b[..2].to_vec();
with.extend_from_slice(&seg);
with.extend_from_slice(&b[2..]);
assert!(parse_markers(&with).unwrap().icc_invalid);
assert!(srgb8_fit(&b, 8, 8).unwrap().is_some());
assert!(srgb8_fit(&with, 8, 8).unwrap().is_none());
}
/// The 8-bit path refuses an APP1 flood before its decoders walk it again, as the general one does.
#[test]
fn an_app1_flood_is_refused_by_the_8_bit_path_too() {
let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]);
let mut flood = b[..2].to_vec();
for _ in 0..200 {
flood.extend_from_slice(&[0xFF, 0xE1, 0x00, 0x02]);
}
flood.extend_from_slice(&b[2..]);
match srgb8_fit(&flood, 8, 8) {
Err(Error::Malformed(_, m)) => assert!(m.contains("APP1"), "{m}"),
other => panic!("unexpected: {other:?}"),
}
}
}
+15
View File
@@ -169,6 +169,21 @@ pub fn decode(bytes: &[u8], opts: DecodeOptions) -> Result<Decoded> {
std::panic::catch_unwind(|| decode_unguarded(bytes, format, &opts)).unwrap_or_else(|_| Err(Error::Malformed(format, "decoder panicked".into())))
}
/// A JPEG for display, fast: fitted within `max_w × max_h` (never enlarged) as 8-bit sRGB with its
/// EXIF orientation (1..=8, not applied), the picture `decode(bytes, DecodeOptions::fit(..))
/// .to_srgb8()` gives within a few levels, in about half the time for a large camera preview.
/// `Ok(None)` when the file is not a plain 8-bit sRGB JPEG (an ICC profile or an Adobe RGB EXIF
/// hint, CMYK, 12-bit, lossless or arithmetic coding) or its headers can't be read: use
/// [`decode`], which reports a malformed header as an error. Bad scan data is an error here, and
/// nothing is ever a panic.
pub fn decode_jpeg_srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result<Option<(lightcraft_raster::Rgba8, u16)>> {
if sniff(bytes) != Some(Format::Jpeg) {
return Ok(None);
}
std::panic::catch_unwind(|| jpeg::srgb8_fit(bytes, max_w, max_h))
.unwrap_or_else(|_| Err(Error::Malformed(Format::Jpeg, "decoder panicked".into())))
}
/// What a file's headers say about its image: enough to catalogue it without decoding pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
+4
View File
@@ -208,6 +208,10 @@ fn samsung_sef_trailer_without_eoi() {
assert_eq!(full.image.data, reference.image.data, "the same pixels as the file with its EOI");
let small = decode(&pano, DecodeOptions::fit(32, 32)).unwrap();
assert_eq!((small.source_width, small.source_height), (160, 96));
// the fast display decode too, scaled (where the trailer after the scan used to fail it)
let (fit, _) = lightcraft_codecs::decode_jpeg_srgb8_fit(&pano, 32, 32).unwrap().unwrap();
let (fit_ref, _) = lightcraft_codecs::decode_jpeg_srgb8_fit(&jpeg, 32, 32).unwrap().unwrap();
assert_eq!((fit.width, fit.height, &fit.data), (fit_ref.width, fit_ref.height, &fit_ref.data));
// an FF D9 inside the SEF data is not the image's end
let eoi_in_data = sef_file(scan, block, b"SEFH", 0x08E0, &[0xFF, 0xC0, 0, 0x11, 0xFF, 0xD9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], None);
assert_eq!(read_header(&eoi_in_data).unwrap().width, 160);
+601
View File
@@ -0,0 +1,601 @@
//! Block-matching collaborative filtering (after Dabov, Foi, Katkovnik and Egiazarian, "Image denoising by sparse 3-D
//! transform-domain collaborative filtering", 2007; the colour variant is their CBM3D), written from the paper.
//!
//! It works on the same planes as [`crate::nlm`]: four Bayer planes of unit noise (see [`crate::nlm::Stabiliser`]),
//! rotated by a Hadamard transform into a brightness plane and three colour-difference planes. Blocks of the
//! brightness plane that look alike are stacked into a group; the stack is transformed (2-D DCT of each block, Haar
//! across the stack) where the picture is sparse and the noise is not, shrunk, transformed back and put back with
//! weights. The first step shrinks by a hard threshold and gives a basic estimate; the second matches blocks on that
//! cleaner estimate and shrinks by a Wiener filter built from it. Every plane of a group follows the brightness
//! plane's matches, so the colour differences are only averaged across like brightness.
use crate::nlm::hadamard;
use std::f32::consts::FRAC_1_SQRT_2;
/// What the filter may be tuned by (the defaults are what the built-in denoiser uses).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Params {
/// Side of a block, in cells.
pub block: usize,
/// Distance, in cells, between the blocks that start a group (1 = every block; larger is faster).
pub step: usize,
/// How far, in cells, a match is looked for round a block.
pub search: usize,
/// The most blocks in a group (rounded down to a power of two).
pub group: usize,
/// How far above the noise two blocks may differ (mean square, in units of the noise variance) and still be
/// grouped, in the first step (on the noisy picture) and in the second (on the basic estimate).
pub tau1: f32,
pub tau2: f32,
/// The first step's hard-threshold level, in noise deviations, as a function of how noisy the photo is: points of
/// (the noise's deviation at mid-grey, with white = 1; the threshold), rising with the noise and joined in a straight
/// line against the logarithm of the noise (flat beyond the first and last). A quieter photo has more fine detail
/// per unit of noise to keep, a noisier one less. Fitted on real Canon raws with noise added at their ISO levels
/// (docs/denoise.md → Why block matching).
pub lambda: [(f32, f32); 6],
/// The noise's deviation as the filter takes it (1 = as measured; more cleans harder).
pub sigma: f32,
/// Whether the second (Wiener) step runs.
pub wiener: bool,
}
impl Default for Params {
/// What the built-in denoiser runs with: 4 × 4 blocks taken every 3 cells, matched within 8 cells, up to 16 to a
/// group, the fitted threshold curve, and the Wiener step on.
fn default() -> Self {
Params {
block: 4,
step: 3,
search: 8,
group: 16,
tau1: 4.0,
tau2: 1.0,
lambda: [(0.0028, 1.2), (0.0062, 1.9), (0.0094, 2.3), (0.0152, 2.65), (0.038, 3.2), (0.14, 3.5)],
sigma: 1.0,
wiener: true,
}
}
}
/// The threshold for a photo whose noise has deviation `noise` at mid-grey: `curve` read in a straight line against the
/// logarithm of the noise (the ends hold). A curve that is empty or not rising in its first coordinate gives its first
/// point's value for any noise, and a noise that is not a number is the quietest.
pub fn threshold_for(curve: &[(f32, f32)], noise: f32) -> f32 {
let Some(&(x0, y0)) = curve.first() else { return 3.0 };
if !noise.is_finite() || noise <= x0 {
return y0;
}
for pair in curve.windows(2) {
let ((xa, ya), (xb, yb)) = (pair[0], pair[1]);
if xa.is_finite() && xb.is_finite() && xa > 0.0 && xb > xa && noise <= xb {
return ya + (yb - ya) * (noise / xa).ln() / (xb / xa).ln();
}
}
curve.last().map_or(y0, |p| p.1)
}
/// The orthonormal DCT-II of a block and the window the filtered blocks are put back with.
struct Transform {
n: usize,
c: Vec<f32>,
window: Vec<f32>,
}
/// The zeroth-order modified Bessel function of the first kind (a series; the Kaiser window needs it).
fn bessel_i0(x: f32) -> f32 {
let (mut sum, mut term) = (1.0f32, 1.0f32);
for k in 1..30 {
term *= x * x / (4.0 * (k * k) as f32);
sum += term;
}
sum
}
impl Transform {
/// The transform for `n × n` blocks: the DCT-II matrix and the Kaiser window the filtered blocks are put back with.
fn new(n: usize) -> Self {
let mut c = vec![0f32; n * n];
for (k, row) in c.chunks_exact_mut(n).enumerate() {
let scale = if k == 0 { (1.0 / n as f32).sqrt() } else { (2.0 / n as f32).sqrt() };
for (i, v) in row.iter_mut().enumerate() {
*v = scale * (std::f32::consts::PI * (2 * i + 1) as f32 * k as f32 / (2 * n) as f32).cos();
}
}
// a Kaiser window (beta 2) down each side, so a block's edge counts less than its middle
let beta = 2.0f32;
let side: Vec<f32> = (0..n)
.map(|i| {
let r = if n > 1 { 2.0 * i as f32 / (n - 1) as f32 - 1.0 } else { 0.0 };
bessel_i0(beta * (1.0 - r * r).max(0.0).sqrt()) / bessel_i0(beta)
})
.collect();
let window = side.iter().flat_map(|y| side.iter().map(move |x| x * y)).collect();
Transform { n, c, window }
}
/// `blk` (`n × n`) becomes its 2-D DCT.
fn forward(&self, blk: &mut [f32], tmp: &mut [f32]) {
let n = self.n;
for (trow, crow) in tmp.chunks_exact_mut(n).zip(self.c.chunks_exact(n)) {
trow.fill(0.0);
for (&ck, brow) in crow.iter().zip(blk.chunks_exact(n)) {
for (t, &b) in trow.iter_mut().zip(brow) {
*t += ck * b;
}
}
}
for (orow, trow) in blk.chunks_exact_mut(n).zip(tmp.chunks_exact(n)) {
for (o, crow) in orow.iter_mut().zip(self.c.chunks_exact(n)) {
*o = trow.iter().zip(crow).map(|(a, b)| a * b).sum();
}
}
}
/// The inverse of [`Transform::forward`].
fn inverse(&self, blk: &mut [f32], tmp: &mut [f32]) {
let n = self.n;
tmp.fill(0.0);
for (crow, xrow) in self.c.chunks_exact(n).zip(blk.chunks_exact(n)) {
for (trow, &cki) in tmp.chunks_exact_mut(n).zip(crow) {
for (t, &x) in trow.iter_mut().zip(xrow) {
*t += cki * x;
}
}
}
for (brow, trow) in blk.chunks_exact_mut(n).zip(tmp.chunks_exact(n)) {
brow.fill(0.0);
for (&t, crow) in trow.iter().zip(self.c.chunks_exact(n)) {
for (b, &c) in brow.iter_mut().zip(crow) {
*b += t * c;
}
}
}
}
}
/// The orthonormal Haar transform of a vector whose length is a power of two.
fn haar_forward(v: &mut [f32], tmp: &mut [f32]) {
let mut len = v.len();
while len > 1 {
let half = len / 2;
for i in 0..half {
let (a, b) = (v.get(2 * i).copied().unwrap_or(0.0), v.get(2 * i + 1).copied().unwrap_or(0.0));
if let Some(x) = tmp.get_mut(i) {
*x = (a + b) * FRAC_1_SQRT_2;
}
if let Some(x) = tmp.get_mut(half + i) {
*x = (a - b) * FRAC_1_SQRT_2;
}
}
if let (Some(dst), Some(src)) = (v.get_mut(..len), tmp.get(..len)) {
dst.copy_from_slice(src);
}
len = half;
}
}
/// Undoes [`haar_forward`] in place; `tmp` is scratch of the same length.
fn haar_inverse(v: &mut [f32], tmp: &mut [f32]) {
let mut len = 2;
while len <= v.len() {
let half = len / 2;
for i in 0..half {
let (avg, det) = (v.get(i).copied().unwrap_or(0.0), v.get(half + i).copied().unwrap_or(0.0));
if let Some(x) = tmp.get_mut(2 * i) {
*x = (avg + det) * FRAC_1_SQRT_2;
}
if let Some(x) = tmp.get_mut(2 * i + 1) {
*x = (avg - det) * FRAC_1_SQRT_2;
}
}
if let (Some(dst), Some(src)) = (v.get_mut(..len), tmp.get(..len)) {
dst.copy_from_slice(src);
}
len *= 2;
}
}
/// Reusable buffers of the group transforms.
#[derive(Default)]
struct Scratch {
tmp: Vec<f32>,
col: Vec<f32>,
col_tmp: Vec<f32>,
}
/// A group (`m` blocks of `n × n`, one after the other in `buf`) to the transform domain, or back.
fn group_transform(tf: &Transform, buf: &mut [f32], m: usize, s: &mut Scratch, forward: bool) {
let nn = tf.n * tf.n;
s.tmp.resize(nn, 0.0);
if !forward {
haar_columns(buf, m, nn, s, false);
}
for blk in buf.chunks_exact_mut(nn) {
if forward {
tf.forward(blk, &mut s.tmp);
} else {
tf.inverse(blk, &mut s.tmp);
}
}
if forward {
haar_columns(buf, m, nn, s, true);
}
}
/// The Haar transform across the blocks of a group, at each of the `nn` positions of a block.
fn haar_columns(buf: &mut [f32], m: usize, nn: usize, s: &mut Scratch, forward: bool) {
if m < 2 {
return;
}
s.col.resize(m, 0.0);
s.col_tmp.resize(m, 0.0);
for k in 0..nn {
for (i, c) in s.col.iter_mut().enumerate() {
*c = buf.get(i * nn + k).copied().unwrap_or(0.0);
}
if forward {
haar_forward(&mut s.col, &mut s.col_tmp);
} else {
haar_inverse(&mut s.col, &mut s.col_tmp);
}
for (i, c) in s.col.iter().enumerate() {
if let Some(b) = buf.get_mut(i * nn + k) {
*b = *c;
}
}
}
}
/// Copy the blocks of a group out of a plane (`members` are the blocks' top-left cells).
pub(crate) fn gather(plane: &[f32], t: usize, n: usize, members: &[u32], out: &mut Vec<f32>) {
out.clear();
for &pos in members {
for j in 0..n {
let at = pos as usize + j * t;
match plane.get(at..at + n) {
Some(row) => out.extend_from_slice(row),
None => out.extend(std::iter::repeat_n(0.0, n)),
}
}
}
}
/// Where a plane's blocks start along one side: every `step` cells, and the last one too, so the edge is covered.
pub fn starts(blocks: usize, step: usize) -> Vec<usize> {
let mut v: Vec<usize> = (0..blocks).step_by(step.max(1)).collect();
if let Some(last) = blocks.checked_sub(1)
&& v.last() != Some(&last)
{
v.push(last);
}
v
}
/// Insert `(distance, block)` into a list ordered by distance, keeping at most `cap`.
fn insert(list: &mut Vec<(f32, u32)>, cap: usize, d: f32, pos: u32) {
if list.len() >= cap && list.last().is_some_and(|l| d >= l.0) {
return;
}
let at = list.partition_point(|e| e.0 <= d);
list.insert(at, (d, pos));
list.truncate(cap);
}
/// For every block that starts a group, the blocks of `plane` within `search` cells (itself first) whose mean squared
/// difference from it is at most `tau`, nearest first and at most `cap`. Blocks (of `n × n` cells) are named by their
/// top-left cell, and a block starts a group every `step` cells.
pub(crate) fn match_groups(plane: &[f32], t: usize, n: usize, step: usize, search: usize, cap: usize, tau: f32) -> Vec<Vec<u32>> {
let nb = t + 1 - n;
let refs = starts(nb, step);
let nr = refs.len();
let cap = cap.max(1);
let mut lists: Vec<Vec<(f32, u32)>> = Vec::with_capacity(nr * nr);
for &ry in &refs {
for &rx in &refs {
let mut l = Vec::with_capacity(cap + 1);
l.push((0.0, (ry * t + rx) as u32));
lists.push(l);
}
}
let norm = 1.0 / (n * n) as f32;
let r = search as isize;
let (mut d, mut hsum) = (vec![0f32; t * t], vec![0f32; t * nr]);
let valid = |v: usize, o: isize| (v as isize + o) >= 0 && ((v as isize + o) as usize) < nb;
for oy in -r..=r {
for ox in -r..=r {
if ox == 0 && oy == 0 {
continue;
}
// squared differences between the plane and itself shifted by the offset
let (x0, x1) = (0.max(-ox) as usize, (t as isize).min(t as isize - ox) as usize);
for y in 0..t {
let sy = y as isize + oy;
if sy < 0 || sy >= t as isize {
continue;
}
let (Some(a), Some(b), Some(out)) = (
plane.get(y * t + x0..y * t + x1),
plane.get(sy as usize * t + (x0 as isize + ox) as usize..sy as usize * t + (x1 as isize + ox) as usize),
d.get_mut(y * t + x0..y * t + x1),
) else {
continue;
};
for ((o, &a), &b) in out.iter_mut().zip(a).zip(b) {
*o = (a - b) * (a - b);
}
}
// block sums: along rows at the starting columns, then down at the starting rows
for y in 0..t {
for (ri, &rx) in refs.iter().enumerate() {
if !valid(rx, ox) {
continue;
}
let s: f32 = d.get(y * t + rx..y * t + rx + n).map_or(0.0, |v| v.iter().sum());
if let Some(h) = hsum.get_mut(y * nr + ri) {
*h = s;
}
}
}
for (rj, &ry) in refs.iter().enumerate() {
if !valid(ry, oy) {
continue;
}
for (ri, &rx) in refs.iter().enumerate() {
if !valid(rx, ox) {
continue;
}
let s: f32 = (0..n).map(|j| hsum.get((ry + j) * nr + ri).copied().unwrap_or(0.0)).sum::<f32>() * norm;
if s <= tau {
let other = ((ry as isize + oy) as usize * t) as isize + (rx as isize + ox);
if let Some(l) = lists.get_mut(rj * nr + ri) {
insert(l, cap, s, other as u32);
}
}
}
}
}
}
lists.into_iter().map(|l| l.into_iter().map(|(_, pos)| pos).collect()).collect()
}
/// [`match_groups`] with each group cut to a power of two, so the Haar transform across it is complete.
fn match_blocks(plane: &[f32], t: usize, p: &Params, tau: f32) -> Vec<Vec<u32>> {
let mut groups = match_groups(plane, t, p.block, p.step, p.search, p.group, tau);
for g in &mut groups {
let m = if g.is_empty() { 0 } else { 1usize << g.len().ilog2() };
g.truncate(m);
}
groups
}
/// Filter every plane of `y` over the groups: hard threshold when there is no `pilot`, Wiener shrinkage by it when
/// there is.
fn collaborate(y: &[Vec<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>], t: usize, p: &Params, lambda: f32, tf: &Transform) -> Vec<Vec<f32>> {
let n = tf.n;
let sigma = p.sigma.max(1e-3);
let lambda = lambda * sigma;
let mut s = Scratch::default();
let (mut buf, mut pbuf) = (Vec::new(), Vec::new());
let mut out = Vec::with_capacity(y.len());
for plane in y {
let mut num = vec![0f32; t * t];
let mut den = vec![0f32; t * t];
let c = out.len();
let pilot_plane = pilot.and_then(|pl| pl.get(c));
for members in groups {
let m = members.len();
gather(plane, t, n, members, &mut buf);
group_transform(tf, &mut buf, m, &mut s, true);
let weight = match pilot_plane {
None => {
let mut kept = 0usize;
for v in buf.iter_mut() {
if v.abs() < lambda {
*v = 0.0;
} else {
kept += 1;
}
}
1.0 / kept.max(1) as f32
}
Some(pl) => {
gather(pl, t, n, members, &mut pbuf);
group_transform(tf, &mut pbuf, m, &mut s, true);
let mut energy = 0f32;
for (v, &q) in buf.iter_mut().zip(&pbuf) {
let w = q * q / (q * q + sigma * sigma);
*v *= w;
energy += w * w;
}
1.0 / energy.max(1e-3)
}
};
group_transform(tf, &mut buf, m, &mut s, false);
for (&pos, blk) in members.iter().zip(buf.chunks_exact(n * n)) {
for (j, row) in blk.chunks_exact(n).enumerate() {
let at = pos as usize + j * t;
let (Some(nu), Some(de)) = (num.get_mut(at..at + n), den.get_mut(at..at + n)) else { continue };
let win = tf.window.get(j * n..(j + 1) * n).unwrap_or_default();
for (((nu, de), &v), &w) in nu.iter_mut().zip(de.iter_mut()).zip(row).zip(win) {
*nu += weight * w * v;
*de += weight * w;
}
}
}
}
// cells no block reached keep their value
out.push(num.iter().zip(&den).zip(plane).map(|((&nu, &de), &own)| if de > 0.0 { nu / de } else { own }).collect());
}
out
}
/// What a run over tiles of `t` cells uses once the parameters are made safe: shared by every device that runs the filter.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Plan {
pub params: Params,
/// The first step's hard threshold, in noise deviations (before `params.sigma` scales it).
pub lambda: f32,
}
/// The parameters as they are used for tiles of `t` cells and a photo whose noise has deviation `noise` at mid-grey
/// (white = 1; see [`Params::lambda`]), or `None` when the tiles are smaller than a block (they are then left as they
/// are).
pub fn plan(p: &Params, t: usize, noise: f32) -> Option<Plan> {
let n = p.block.clamp(2, 16);
if t < n {
return None;
}
let params = Params { block: n, search: p.search.min(t), group: p.group.clamp(1, 64), ..*p };
Some(Plan { params, lambda: threshold_for(&p.lambda, noise) })
}
/// The block-to-block DCT matrix (`n × n`, row `k` is frequency `k`) and the window (`n × n`) the filtered blocks are put
/// back with: the constants the graphics-card version is given so that both use the very same numbers.
pub fn constants(n: usize) -> (Vec<f32>, Vec<f32>) {
let tf = Transform::new(n.clamp(2, 16));
(tf.c, tf.window)
}
/// Denoise four unit-noise planes of `t × t` cells (see the module description); `noise` is the photo's noise at
/// mid-grey, which sets how hard it cleans (see [`Params::lambda`]).
pub fn filter(planes: &[Vec<f32>], t: usize, p: &Params, noise: f32) -> Vec<Vec<f32>> {
let y = hadamard(planes);
let Some(Plan { params: p, lambda }) = plan(p, t, noise) else { return hadamard(&y) };
if y.len() != 4 || y.iter().any(|pl| pl.len() != t * t) {
return hadamard(&y);
}
let tf = Transform::new(p.block);
let var = p.sigma.max(1e-3).powi(2);
let Some(brightness) = y.first() else { return hadamard(&y) };
let first = match_blocks(brightness, t, &p, p.tau1 * var);
let basic = collaborate(&y, None, &first, t, &p, lambda, &tf);
if !p.wiener {
return hadamard(&basic);
}
let Some(pilot) = basic.first() else { return hadamard(&basic) };
let second = match_blocks(pilot, t, &p, p.tau2 * var);
hadamard(&collaborate(&y, Some(&basic), &second, t, &p, lambda, &tf))
}
#[cfg(test)]
mod tests {
use super::*;
/// The DCT keeps a block's energy, and both it and the Haar transform are undone exactly by their inverses.
#[test]
fn the_dct_and_haar_transforms_invert() {
for n in [2, 4, 8] {
let tf = Transform::new(n);
let block: Vec<f32> = (0..n * n).map(|i| (i as f32 * 0.7).sin() * 3.0).collect();
let (mut b, mut tmp) = (block.clone(), vec![0f32; n * n]);
tf.forward(&mut b, &mut tmp);
let energy = |v: &[f32]| v.iter().map(|x| x * x).sum::<f32>();
assert!((energy(&b) - energy(&block)).abs() < 1e-3, "the DCT keeps energy");
tf.inverse(&mut b, &mut tmp);
assert!(b.iter().zip(&block).all(|(a, c)| (a - c).abs() < 1e-4));
}
for m in [1usize, 2, 4, 16] {
let v: Vec<f32> = (0..m).map(|i| i as f32 * 0.3 - 1.0).collect();
let (mut w, mut tmp) = (v.clone(), vec![0f32; m]);
haar_forward(&mut w, &mut tmp);
assert!((w.iter().map(|x| x * x).sum::<f32>() - v.iter().map(|x| x * x).sum::<f32>()).abs() < 1e-4);
haar_inverse(&mut w, &mut tmp);
assert!(w.iter().zip(&v).all(|(a, c)| (a - c).abs() < 1e-5));
}
}
/// Four planes of unit noise (an LCG and Box-Muller, so the tests need no dependency) round `level`.
fn noisy(t: usize, level: f32, seed: u64) -> Vec<Vec<f32>> {
let mut state = seed;
let mut uniform = move || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32
};
(0..4)
.map(|_| {
(0..t * t)
.map(|_| {
let (u, v) = (uniform(), uniform());
level + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
})
.collect()
})
.collect()
}
/// The deviation of the planes' values around `level`.
fn spread(planes: &[Vec<f32>], level: f32) -> f32 {
let all: Vec<f32> = planes.iter().flatten().copied().collect();
(all.iter().map(|v| (v - level) * (v - level)).sum::<f32>() / all.len().max(1) as f32).sqrt()
}
/// The threshold holds at the ends of the curve, passes through its points and never falls as the noise rises; a
/// noise that is not a number, an empty curve and curves out of order give a value instead of a panic.
#[test]
fn the_threshold_follows_the_noise_and_survives_odd_curves() {
let c = Params::default().lambda;
let at = |n: f32| threshold_for(&c, n);
assert_eq!((at(0.0), at(1.0)), (1.2, 3.5), "the ends hold");
assert!((at(0.0062) - 1.9).abs() < 1e-4 && (at(0.0152) - 2.65).abs() < 1e-4, "the points are on the curve");
let mut last = 0.0;
for i in 0..250 {
let v = at(0.001 * 1.04f32.powi(i));
assert!(v >= last - 1e-6, "the threshold never falls as the noise rises");
last = v;
}
assert_eq!(at(f32::NAN), 1.2, "a noise that is not a number is the quietest");
assert_eq!(threshold_for(&[], 0.1), 3.0);
// curves that are out of order, or with numbers that are not numbers, give some value and never panic
for curve in [vec![(0.0, 1.0), (f32::NAN, 2.0), (0.01, 5.0), (0.005, 4.0)], vec![(0.01, 2.0), (0.01, 3.0)], vec![(-1.0, 2.0), (0.0, 3.0)]] {
for n in [0.0, 0.003, 0.02, 1.0, f32::INFINITY] {
assert!(threshold_for(&curve, n).is_finite() || !curve.iter().all(|p| p.1.is_finite()));
}
}
}
/// Filtering a flat picture of pure noise leaves well under half of the noise's deviation.
#[test]
fn a_flat_noisy_picture_comes_out_much_quieter() {
let t = 48;
let planes = noisy(t, 5.0, 7);
let out = filter(&planes, t, &Params::default(), 0.5);
// the Hadamard transform keeps the level, so what is left of the spread is the noise that got through
assert!(spread(&out, 5.0) < 0.35 * spread(&planes, 5.0), "{} vs {}", spread(&out, 5.0), spread(&planes, 5.0));
assert!(out.iter().flatten().all(|v| v.is_finite()));
}
/// A step edge under noise stays a step: a few cells either side of it the values are still near their two levels.
#[test]
fn a_step_edge_stays_sharp() {
let t = 48;
let mut planes = noisy(t, 0.0, 9);
for pl in &mut planes {
for (i, v) in pl.iter_mut().enumerate() {
if i % t >= t / 2 {
*v += 12.0;
}
}
}
let out = filter(&planes, t, &Params::default(), 0.5);
let row = t / 2;
let at = |x: usize| out.iter().map(|pl| pl.get(row * t + x).copied().unwrap_or(0.0)).sum::<f32>() / 4.0;
assert!(at(t / 2 - 3) < 2.0 && at(t / 2 + 2) > 10.0, "{} {}", at(t / 2 - 3), at(t / 2 + 2));
}
/// Tiny and empty tiles, planes of NaN, a tuning with a zero block, step or group, and no planes at all give finite
/// values or empty planes and never a panic.
#[test]
fn odd_inputs_never_panic() {
// the sizes and values a tile or a caller could hand over
for t in [0usize, 1, 3, 4, 5, 9] {
let planes = noisy(t.max(1), 1.0, 3);
let out = filter(&planes, t, &Params::default(), 0.5);
assert!(out.iter().flatten().all(|v| v.is_finite()));
}
let planes = vec![vec![f32::NAN; 64]; 4];
let _ = filter(&planes, 8, &Params::default(), 0.5);
let wild = Params { block: 0, step: 0, search: 1000, group: 0, ..Params::default() };
assert!(filter(&noisy(16, 2.0, 1), 16, &wild, 0.5).iter().flatten().all(|v| v.is_finite()));
assert!(filter(&[], 8, &Params::default(), 0.5).iter().all(|p| p.is_empty()));
}
}
+679
View File
@@ -0,0 +1,679 @@
//! The built-in denoiser: what AI Denoise runs when no model has been installed, so it works out of the box.
//!
//! It is a [`TileRunner`] with the same contract as a model (four Bayer planes in, camera RGB at twice the plane
//! size out), written from scratch and needing no file: the noise level of the photo is measured from the photo itself
//! (Poisson-Gaussian: variance = a · signal + b; [`estimate_noise`], with a tile's own measure as the fallback), the
//! four planes are cleaned together by block-matching collaborative filtering on variance-stabilised data
//! ([`crate::bm3d`]; the non-local-means filter of [`crate::nlm`] is the fallback), which cleans harder as the noise
//! grows, and the cleaned mosaic is demosaiced with edge-directed green and colour-difference red and blue.
use crate::bayer::reflect;
use crate::licence::{Commercial, Licence};
use crate::manifest::{DenoiserManifest, Domain, Gain};
use crate::nlm::{self, Stabiliser, Tuning};
use crate::run::{Error, TileRunner};
/// Id of the built-in denoiser; no installed model may use it (the models folder is never searched for it).
pub const ID: &str = "builtin";
/// Changes when the algorithm does, so that cached pictures made by an older one are made again.
pub const VERSION: u32 = 5;
/// Side of its tile, in cells.
pub const TILE: u32 = 256;
/// Cells neighbouring tiles share.
pub const OVERLAP: u32 = 16;
/// Cells on a side of the blocks the noise level is measured over.
const BLOCK: usize = 16;
/// The smallest variance used, so that a clean tile is left alone instead of divided by zero.
const MIN_VARIANCE: f32 = 1e-10;
/// Blocks with a mean above this (white = 1) may be clipped and say nothing about the noise.
const CLIPPED: f32 = 0.9;
/// The manifest of the built-in denoiser, as the engine treats an installed model.
pub fn manifest() -> DenoiserManifest {
DenoiserManifest {
id: ID.into(),
name: "Built-in".into(),
version: VERSION.to_string(),
licence: Licence {
name: "MIT OR Apache-2.0".into(),
commercial: Commercial::Yes,
url: None,
notice: "Part of LightCraft: no download, no weights.".into(),
},
source: None,
sha256: None,
size_bytes: None,
provenance: "Block-matching collaborative filtering with a noise level measured from each photo, written for LightCraft.".into(),
domain: Domain::BayerToRgb,
tile: TILE,
overlap: OVERLAP,
gain: Gain::None,
}
}
/// The built-in denoiser as a tile runner.
#[derive(Clone, Copy, Debug, Default)]
pub struct Builtin {
/// The noise of the whole photo as `(a, b)`, variance = `a · signal + b` (see [`estimate_noise`]). Without it each
/// tile measures its own, which is rougher and can show as a change of strength between tiles.
pub noise: Option<(f32, f32)>,
pub tuning: Tuning,
}
impl Builtin {
/// The runner told the photo's noise as `(a, b)`, variance = `a · signal + b` (see [`estimate_noise`]), with the default tuning.
pub fn with_noise(noise: (f32, f32)) -> Self {
Builtin { noise: Some(noise), tuning: Tuning::default() }
}
/// The block-matching filter's parameters when this one uses it (the only filter with a graphics-card version, see
/// `lightcraft_gpu::bm3d`), else `None`.
pub fn bm3d_params(&self) -> Option<crate::bm3d::Params> {
self.tuning.bm3d
}
/// [`TileRunner::run`] with the filter stage given: it gets the four variance-stabilised planes (unit noise), their
/// side, and the photo's noise at mid-grey (which sets how strongly to clean, see [`Tuning::strength`]), and returns
/// the cleaned planes. Everything else (measuring the noise, stabilising and its inverse, demosaicing) is shared, so
/// a filter that is the same computation on another device gives the same picture.
pub fn run_with(&self, input: &[f32], filter: &dyn Fn(&[Vec<f32>], usize, f32) -> Result<Vec<Vec<f32>>, Error>) -> Result<Vec<f32>, Error> {
let t = side_of(input.len()).ok_or_else(|| Error::Input("the tile is not four square planes".into()))?;
let clean: Vec<f32> = input.iter().map(|v| if v.is_finite() { *v } else { 0.0 }).collect();
let n = t * t;
let (a, b) = match self.noise {
Some((a, b)) if a.is_finite() && b.is_finite() => (a, b),
_ => noise_model(&clean.chunks_exact(n).collect::<Vec<_>>(), t),
};
let st = Stabiliser::new(a, b);
let stabilised: Vec<Vec<f32>> = clean.chunks_exact(n).map(|p| p.iter().map(|&v| st.forward(v)).collect()).collect();
let cleaned = filter(&stabilised, t, (a * 0.18 + b).max(0.0).sqrt())?;
if cleaned.len() != 4 || cleaned.iter().any(|p| p.len() != n) {
return Err(Error::Runtime("the filter returned planes of the wrong size".into()));
}
let planes: Vec<Vec<f32>> = cleaned.iter().map(|p| p.iter().map(|&v| st.inverse(v)).collect()).collect();
Ok(demosaic(&planes, t))
}
/// The filter stage on the processor.
pub fn filter_on_cpu(&self, stabilised: &[Vec<f32>], t: usize, noise: f32) -> Vec<Vec<f32>> {
match &self.tuning.bm3d {
Some(p) => crate::bm3d::filter(stabilised, t, p, noise),
None => nlm::filter(stabilised, t, &self.tuning, noise),
}
}
}
impl TileRunner for Builtin {
/// Clean one tile, all on the processor.
fn run(&self, input: &[f32]) -> Result<Vec<f32>, Error> {
self.run_with(input, &|planes, t, noise| Ok(self.filter_on_cpu(planes, t, noise)))
}
}
/// The side of the planes of a tile of `len` values, if it is four squares.
fn side_of(len: usize) -> Option<usize> {
let per = len / 4;
let t = (per as f64).sqrt().round() as usize;
(len.is_multiple_of(4) && (8..=2048).contains(&t) && t * t == per).then_some(t)
}
/// Measure the noise of a tile: `(a, b)` with variance = `a · signal + b`. Each block of a plane gives the signal
/// (its mean) and the variance of its cells' difference from their four neighbours (which texture and edges only
/// raise), the lower part of the variances at each brightness is the noise, and a line is fitted through them.
fn noise_model(planes: &[&[f32]], t: usize) -> (f32, f32) {
let mut blocks: Vec<(f32, f32)> = Vec::new();
for p in planes {
let at = |x: usize, y: usize| p.get(y * t + x).copied().unwrap_or(0.0);
let mut by = 1;
while by + BLOCK < t {
let mut bx = 1;
while bx + BLOCK < t {
let (mut sum, mut sq) = (0f64, 0f64);
for y in by..by + BLOCK {
for x in bx..bx + BLOCK {
let c = at(x, y);
let r = c - 0.25 * (at(x - 1, y) + at(x + 1, y) + at(x, y - 1) + at(x, y + 1));
sum += f64::from(c);
sq += f64::from(r * r);
}
}
let cells = (BLOCK * BLOCK) as f64;
let mean = (sum / cells) as f32;
// a cell minus the mean of four neighbours has 1.25 times the variance of one
let variance = (sq / cells / 1.25) as f32;
if mean < CLIPPED && mean.is_finite() && variance.is_finite() {
blocks.push((mean, variance));
}
bx += BLOCK;
}
by += BLOCK;
}
}
fit_noise(blocks)
}
/// The noise of a whole mosaic as `(a, b)` (variance = `a · signal + b`), measured from the picture itself.
///
/// Each of the four colour planes (they sit at different levels in a raw, so they are never mixed) is cut into blocks.
/// A block's noise variance is read from a second-difference operator (`[1 -2 1; -2 4 -2; 1 -2 1]`, which cancels flat
/// and smoothly sloping signal and has `36 σ²` of white noise's variance); texture and edges only add to it. At each
/// brightness the quietest few blocks are the noise (a low quantile, divided by the bias of that quantile of pure
/// noise), and a line is fitted through them. A picture with no flat area still reads somewhat high, never low.
pub fn estimate_noise(mosaic: &[f32], width: usize, height: usize) -> (f32, f32) {
estimate_noise_with(mosaic, width, height, &NoiseProbe::default())
}
/// [`estimate_noise`], or `None` when the mosaic could not be measured (too small, the wrong size, or no unclipped
/// block): the runner then measures each tile's own noise instead of being told a made-up one.
pub fn measure_noise(mosaic: &[f32], width: usize, height: usize) -> Option<(f32, f32)> {
let noise = estimate_noise(mosaic, width, height);
(noise != (0.0, MIN_VARIANCE)).then_some(noise)
}
/// What [`estimate_noise_with`] may be tuned by.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NoiseProbe {
/// Cells on a side of the blocks, in a colour plane.
pub block: usize,
/// Which of a brightness's blocks (by how noisy they look, 0 = the quietest) is taken as the noise.
pub quantile: f32,
/// What that quantile of the variances of noise-only blocks is, as a fraction of their true variance.
pub correction: f32,
}
impl Default for NoiseProbe {
/// The settings the estimator was calibrated with: 12-cell blocks, the quietest 5 %, and the 0.67 bias of that quantile.
fn default() -> Self {
NoiseProbe { block: 12, quantile: 0.05, correction: 0.67 }
}
}
/// [`estimate_noise`] with its settings given.
pub fn estimate_noise_with(mosaic: &[f32], width: usize, height: usize, probe: &NoiseProbe) -> (f32, f32) {
let (pw, ph) = (width / 2, height / 2);
let b = probe.block.clamp(6, 64);
if pw < b + 2 || ph < b + 2 || width.checked_mul(height) != Some(mosaic.len()) {
return (0.0, MIN_VARIANCE);
}
let mut blocks: Vec<(f32, f32)> = Vec::new();
let mut plane = vec![0f32; pw * ph];
for c in 0..4 {
let (dx, dy) = (c % 2, c / 2);
for (y, row) in plane.chunks_exact_mut(pw).enumerate() {
for (x, v) in row.iter_mut().enumerate() {
*v = mosaic.get((2 * y + dy) * width + 2 * x + dx).copied().unwrap_or(0.0);
}
}
let at = |x: usize, y: usize| plane.get(y * pw + x).copied().unwrap_or(0.0);
let mut by = 1;
while by + b < ph {
let mut bx = 1;
while bx + b < pw {
let (mut sum, mut sq, mut top) = (0f64, 0f64, f32::MIN);
for y in by..by + b {
for x in bx..bx + b {
let m = at(x, y);
let r = 4.0 * m - 2.0 * (at(x - 1, y) + at(x + 1, y) + at(x, y - 1) + at(x, y + 1))
+ (at(x - 1, y - 1) + at(x + 1, y - 1) + at(x - 1, y + 1) + at(x + 1, y + 1));
sum += f64::from(m);
sq += f64::from(r * r);
top = top.max(m);
}
}
let cells = (b * b) as f64;
let (mean, variance) = ((sum / cells) as f32, (sq / cells / 36.0) as f32);
if top < CLIPPED && mean.is_finite() && variance.is_finite() {
blocks.push((mean, variance));
}
bx += b;
}
by += b;
}
}
fit_quiet_blocks(blocks, probe.quantile, probe.correction)
}
/// Fit `variance = a · signal + b` through the `(mean, variance)` of blocks: at each brightness (about 300 blocks of
/// each) the `quantile` of the variances, divided by `correction`, is the noise.
fn fit_quiet_blocks(mut blocks: Vec<(f32, f32)>, quantile: f32, correction: f32) -> (f32, f32) {
if blocks.is_empty() {
return (0.0, MIN_VARIANCE);
}
blocks.sort_by(|x, y| x.0.total_cmp(&y.0));
let groups = (blocks.len() / 300).clamp(1, 10);
let q = if quantile.is_finite() { quantile.clamp(0.0, 0.5) } else { 0.1 };
let correction = if correction.is_finite() && correction > 0.05 { correction } else { 1.0 };
let mut points: Vec<(f64, f64)> = Vec::new();
for g in 0..groups {
let slice = blocks.get(g * blocks.len() / groups..(g + 1) * blocks.len() / groups).unwrap_or(&[]);
if slice.is_empty() {
continue;
}
let mean = slice.iter().map(|b| f64::from(b.0)).sum::<f64>() / slice.len() as f64;
let mut variances: Vec<f32> = slice.iter().map(|b| b.1).collect();
variances.sort_by(f32::total_cmp);
let quiet = variances.get(((variances.len() as f32 * q) as usize).min(variances.len().saturating_sub(1))).copied().unwrap_or(0.0);
points.push((mean, f64::from(quiet / correction)));
}
fit_line(&points)
}
/// The noise of a whole mosaic as `(a, b)` (variance = `a · signal + b`), from blocks spread over the picture. This is
/// the first version (blocks mix the colour planes, a plain neighbour difference, the lower quarter of the blocks):
/// it reads texture as noise and reports at least about 0.003 at mid-grey whatever the noise. Kept to compare with.
pub fn estimate_noise_v1(mosaic: &[f32], width: usize, height: usize) -> (f32, f32) {
const SIDE: usize = 32;
const MOST_BLOCKS: usize = 6000;
let mut blocks: Vec<(f32, f32)> = Vec::new();
if width < SIDE + 4 || height < SIDE + 4 || width.checked_mul(height) != Some(mosaic.len()) {
return (0.0, MIN_VARIANCE);
}
let total = (width / SIDE).saturating_mul(height / SIDE);
let skip = (total / MOST_BLOCKS + 1).isqrt().max(1);
let at = |x: usize, y: usize| mosaic.get(y * width + x).copied().unwrap_or(0.0);
let mut by = 2;
while by + SIDE + 2 <= height {
let mut bx = 2;
while bx + SIDE + 2 <= width {
let (mut sum, mut sq) = (0f64, 0f64);
for y in by..by + SIDE {
for x in bx..bx + SIDE {
let c = at(x, y);
// the neighbours of the same colour, two samples away
let r = c - 0.25 * (at(x - 2, y) + at(x + 2, y) + at(x, y - 2) + at(x, y + 2));
sum += f64::from(c);
sq += f64::from(r * r);
}
}
let cells = (SIDE * SIDE) as f64;
let (mean, variance) = ((sum / cells) as f32, (sq / cells / 1.25) as f32);
if mean < CLIPPED && mean.is_finite() && variance.is_finite() {
blocks.push((mean, variance));
}
bx += SIDE * skip;
}
by += SIDE * skip;
}
fit_noise(blocks)
}
/// Fit `variance = a · signal + b` through the `(mean, variance)` of blocks: the quieter part of the variances at
/// each brightness is the noise (texture and edges only raise a block's variance), and a line is fitted through them.
fn fit_noise(mut blocks: Vec<(f32, f32)>) -> (f32, f32) {
if blocks.is_empty() {
return (0.0, MIN_VARIANCE);
}
blocks.sort_by(|x, y| x.0.total_cmp(&y.0));
let groups = (blocks.len() / 8).clamp(1, 6);
let points: Vec<(f64, f64)> = {
let mut points: Vec<(f64, f64)> = Vec::new();
for g in 0..groups {
let slice = blocks.get(g * blocks.len() / groups..(g + 1) * blocks.len() / groups).unwrap_or(&[]);
if slice.is_empty() {
continue;
}
let mean = slice.iter().map(|b| f64::from(b.0)).sum::<f64>() / slice.len() as f64;
let mut variances: Vec<f32> = slice.iter().map(|b| b.1).collect();
variances.sort_by(f32::total_cmp);
let quiet = variances.get(variances.len() / 4).copied().unwrap_or(0.0);
points.push((mean, f64::from(quiet)));
}
points
};
fit_line(&points)
}
/// The line `variance = a · signal + b` through `(signal, variance)` points, with neither `a` nor `b` negative.
fn fit_line(points: &[(f64, f64)]) -> (f32, f32) {
if points.is_empty() {
return (0.0, MIN_VARIANCE);
}
let n = points.len() as f64;
let (sx, sy) = points.iter().fold((0.0, 0.0), |s, p| (s.0 + p.0, s.1 + p.1));
let (sxx, sxy) = points.iter().fold((0.0, 0.0), |s, p| (s.0 + p.0 * p.0, s.1 + p.0 * p.1));
let det = n * sxx - sx * sx;
let (mut a, mut b) =
if points.len() >= 2 && det.abs() > 1e-12 { ((n * sxy - sx * sy) / det, (sy - (n * sxy - sx * sy) / det * sx) / n) } else { (0.0, sy / n) };
if a < 0.0 {
(a, b) = (0.0, sy / n);
} else if b < 0.0 {
(a, b) = (if sxx > 0.0 { sxy / sxx } else { 0.0 }, 0.0);
}
(a.max(0.0) as f32, (b.max(0.0) as f32).max(MIN_VARIANCE))
}
/// Demosaic four planes `[R, G1, G2, B]` of an RGGB tile into camera RGB planes `[R, G, B]` of `2t × 2t`.
pub fn demosaic(planes: &[Vec<f32>], t: usize) -> Vec<f32> {
let s = 2 * t;
let si = s as isize;
// the mosaic: R at (even, even), G1 at (odd, even), G2 at (even, odd), B at (odd, odd)
let mut m = vec![0f32; s * s];
for (p, plane) in planes.iter().enumerate() {
let (dx, dy) = (p % 2, p / 2);
for cy in 0..t {
for cx in 0..t {
if let (Some(dst), Some(v)) = (m.get_mut((2 * cy + dy) * s + 2 * cx + dx), plane.get(cy * t + cx)) {
*dst = *v;
}
}
}
}
let at = |x: isize, y: isize| m.get(reflect(y, s) * s + reflect(x, s)).copied().unwrap_or(0.0);
// green everywhere: measured where there is a green sample, else interpolated along the smoother direction
let mut g = vec![0f32; s * s];
for y in 0..si {
for x in 0..si {
let v = if (x + y) % 2 == 1 {
at(x, y)
} else {
let c = at(x, y);
let (l, r, u, d) = (at(x - 1, y), at(x + 1, y), at(x, y - 1), at(x, y + 1));
let (gh, gv) =
((l + r) / 2.0 + (2.0 * c - at(x - 2, y) - at(x + 2, y)) / 4.0, (u + d) / 2.0 + (2.0 * c - at(x, y - 2) - at(x, y + 2)) / 4.0);
let (dh, dv) =
((l - r).abs() + (2.0 * c - at(x - 2, y) - at(x + 2, y)).abs(), (u - d).abs() + (2.0 * c - at(x, y - 2) - at(x, y + 2)).abs());
let est = if dh < dv {
gh
} else if dv < dh {
gv
} else {
(gh + gv) / 2.0
};
est.clamp(l.min(r).min(u).min(d), l.max(r).max(u).max(d))
};
if let Some(dst) = g.get_mut(y as usize * s + x as usize) {
*dst = v;
}
}
}
let gat = |x: isize, y: isize| g.get(reflect(y, s) * s + reflect(x, s)).copied().unwrap_or(0.0);
// red and blue: the difference from green is smooth, so interpolate it from the nearest samples of the colour
let chroma = |px: isize, py: isize| -> Vec<f32> {
let diff = |x: isize, y: isize| at(x, y) - gat(x, y);
let mut out = vec![0f32; s * s];
for y in 0..si {
for x in 0..si {
let (col, row) = (x % 2 == px, y % 2 == py);
let d = match (col, row) {
(true, true) => diff(x, y),
(false, true) => (diff(x - 1, y) + diff(x + 1, y)) / 2.0,
(true, false) => (diff(x, y - 1) + diff(x, y + 1)) / 2.0,
(false, false) => (diff(x - 1, y - 1) + diff(x + 1, y - 1) + diff(x - 1, y + 1) + diff(x + 1, y + 1)) / 4.0,
};
if let Some(dst) = out.get_mut(y as usize * s + x as usize) {
*dst = d + gat(x, y);
}
}
}
out
};
let mut out = chroma(0, 0);
out.extend_from_slice(&g);
out.extend(chroma(1, 1));
out
}
#[cfg(test)]
mod tests {
use super::*;
/// Deterministic standard normal numbers.
struct Noise(u64);
impl Noise {
/// The next uniform number, strictly between 0 and 1.
fn uniform(&mut self) -> f32 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((self.0 >> 40) as f32 + 0.5) / (1u64 << 24) as f32
}
/// The next standard normal number (Box-Muller).
fn normal(&mut self) -> f32 {
let (u, v) = (self.uniform(), self.uniform());
(-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
}
}
/// A scene of camera RGB with an edge and a gradient, `s × s`.
fn scene(s: usize) -> [Vec<f32>; 3] {
let mut out = [vec![0f32; s * s], vec![0f32; s * s], vec![0f32; s * s]];
for y in 0..s {
for x in 0..s {
let base = 0.15 + 0.5 * x as f32 / s as f32;
let step = if y > s / 2 { 0.2 } else { 0.0 };
for (c, plane) in out.iter_mut().enumerate() {
plane[y * s + x] = base + step * (1.0 + c as f32 * 0.3) / 1.6;
}
}
}
out
}
/// The scene's RGGB mosaic with noise of variance `a · signal + b`, as the four planes a tile has.
fn mosaic_planes(truth: &[Vec<f32>; 3], t: usize, a: f32, b: f32, seed: u64) -> Vec<f32> {
let s = 2 * t;
let mut rng = Noise(seed);
let mut planes = vec![0f32; 4 * t * t];
for (p, &(dx, dy)) in [(0, 0), (1, 0), (0, 1), (1, 1)].iter().enumerate() {
let c = [0, 1, 1, 2][p];
for cy in 0..t {
for cx in 0..t {
let v = truth[c][(2 * cy + dy) * s + 2 * cx + dx];
planes[p * t * t + cy * t + cx] = v + rng.normal() * (a * v + b).sqrt();
}
}
}
planes
}
/// Mean squared error of an RGB result against the scene, away from the tile's edges.
fn error(out: &[f32], truth: &[Vec<f32>; 3], s: usize) -> f64 {
let (mut sum, mut n) = (0f64, 0f64);
for (c, plane) in truth.iter().enumerate() {
for y in 12..s - 12 {
for x in 12..s - 12 {
let d = f64::from(out[c * s * s + y * s + x] - plane[y * s + x]);
sum += d * d;
n += 1.0;
}
}
}
sum / n
}
/// A noisy tile comes out at least five times closer to the scene (squared error) than a plain demosaic of it.
#[test]
fn a_noisy_tile_comes_out_much_closer_to_the_scene_than_a_plain_demosaic() {
let (t, a, b) = (64, 0.004, 0.0004);
let truth = scene(2 * t);
let input = mosaic_planes(&truth, t, a, b, 7);
let planes: Vec<Vec<f32>> = input.chunks_exact(t * t).map(<[f32]>::to_vec).collect();
let plain = error(&demosaic(&planes, t), &truth, 2 * t);
let cleaned = error(&Builtin::default().run(&input).unwrap(), &truth, 2 * t);
assert!(cleaned < plain / 5.0, "plain {plain}, cleaned {cleaned}");
}
/// A tile with no noise is demosaiced almost exactly, and the step between two rows of its scene survives.
#[test]
fn a_noise_free_tile_is_demosaiced_without_blurring_its_edge() {
let t = 64;
let truth = scene(2 * t);
let input = mosaic_planes(&truth, t, 0.0, 0.0, 1);
let out = Builtin::default().run(&input).unwrap();
assert!(error(&out, &truth, 2 * t) < 2e-5);
// the step between rows 63 and 65 survives
let s = 2 * t;
let (above, below) = (out[s * (s / 2 - 2) + s / 2], out[s * (s / 2 + 2) + s / 2]);
assert!(below - above > 0.9 * 0.2 / 1.6, "{above} {below}");
}
/// The tile's own noise model finds the added noise within 30 % at two brightness levels.
#[test]
fn the_noise_level_is_found_from_the_tile() {
let (t, a, b) = (128, 0.004, 0.0004);
let truth = scene(2 * t);
let input = mosaic_planes(&truth, t, a, b, 3);
let planes: Vec<&[f32]> = input.chunks_exact(t * t).collect();
let (ea, eb) = noise_model(&planes, t);
for signal in [0.2f32, 0.5] {
let (want, got) = (a * signal + b, ea * signal + eb);
assert!((got / want - 1.0).abs() < 0.3, "at {signal}: {got} against {want}");
}
}
/// Black, mid-grey and fully clipped tiles give finite results that stay at their level.
#[test]
fn flat_dark_and_clipped_tiles_do_not_break_it() {
let t = 32;
for v in [0.0f32, 0.5, 1.0] {
let out = Builtin::default().run(&vec![v; 4 * t * t]).unwrap();
assert_eq!(out.len(), 3 * 4 * t * t);
assert!(out.iter().all(|x| x.is_finite() && (x - v).abs() < 1e-4), "{v}");
}
}
/// Empty tiles and tiles that are not four squares are errors; NaN and infinite values in a tile are cleaned up.
#[test]
fn bad_tiles_are_errors_and_bad_numbers_are_cleaned_up() {
assert!(Builtin::default().run(&[]).is_err());
assert!(Builtin::default().run(&[0.0; 30]).is_err());
assert!(Builtin::default().run(&vec![0.0; 4 * 9 * 10]).is_err());
let mut input = vec![0.3f32; 4 * 16 * 16];
input[5] = f32::NAN;
input[77] = f32::INFINITY;
assert!(Builtin::default().run(&input).unwrap().iter().all(|v| v.is_finite()));
}
/// The whole-mosaic estimate finds the added noise within 25 %; a mosaic that is too small or not the size it says
/// gets the minimum variance instead of a panic.
#[test]
fn the_noise_of_a_whole_mosaic_is_found_and_hostile_mosaics_are_refused() {
let (s, a, b) = (384, 0.01f32, 0.0005f32);
let truth = scene(s);
let mut rng = Noise(5);
let mosaic: Vec<f32> = (0..s * s)
.map(|i| {
let (x, y) = (i % s, i / s);
let v = truth[[0, 1, 1, 2][(y % 2) * 2 + x % 2]][i];
v + rng.normal() * (a * v + b).sqrt()
})
.collect();
let (ea, eb) = estimate_noise(&mosaic, s, s);
for signal in [0.2f32, 0.5] {
let (want, got) = (a * signal + b, ea * signal + eb);
assert!((got / want - 1.0).abs() < 0.25, "at {signal}: {got} against {want}");
}
// too small, or not the size it says: no estimate, and no panic
assert_eq!(estimate_noise(&mosaic, 10, 10).1, MIN_VARIANCE);
assert_eq!(estimate_noise(&mosaic, s, s - 1).1, MIN_VARIANCE);
assert_eq!(estimate_noise(&[], 0, 0).1, MIN_VARIANCE);
assert_eq!(measure_noise(&[], 0, 0), None, "a mosaic that cannot be measured has no noise to tell the runner");
assert_eq!(measure_noise(&mosaic, 10, 10), None);
assert!(measure_noise(&mosaic, s, s).is_some());
assert_eq!(estimate_noise(&mosaic, usize::MAX, usize::MAX).1, MIN_VARIANCE);
}
/// A 640 x 640 mosaic: a smooth slope (dark at the top, bright at the bottom), texture (fine lines, edges) over its
/// left part and flat over the rest, with noise of variance `a · signal + b` added.
fn textured_and_flat(a: f32, b: f32, flat_from: usize, seed: u64) -> Vec<f32> {
let s = 640;
let mut rng = Noise(seed);
(0..s * s)
.map(|i| {
let (x, y) = (i % s, i / s);
let slope = 0.02 + 0.6 * y as f32 / s as f32 + 0.1 * x as f32 / s as f32;
let texture = if x < flat_from {
0.04 * ((x as f32 * 1.3).sin() + (y as f32 * 0.9).sin()) + if (x / 9 + y / 7) % 2 == 0 { 0.05 } else { 0.0 }
} else {
0.0
};
let v = (slope + texture).max(0.0);
v + rng.normal() * (a * v + b).sqrt()
})
.collect()
}
/// With texture over most of the picture and a flat strip beside it, the estimate follows the strip's noise within
/// 25 % (in deviation), where the first version read the texture as several times too much.
#[test]
fn the_noise_is_read_from_the_flat_areas_and_not_from_the_texture_beside_them() {
let (a, b) = (5e-4f32, 1e-6f32);
// texture over the left 70 % and flat over the rest: the flat part is what shows the noise
let mosaic = textured_and_flat(a, b, 450, 7);
let (ea, eb) = estimate_noise(&mosaic, 640, 640);
for signal in [0.1f32, 0.2, 0.4] {
let (want, got) = ((a * signal + b).sqrt(), (ea * signal + eb).sqrt());
assert!((got / want - 1.0).abs() < 0.25, "the deviation at {signal}: {got} against {want}");
}
// the first version read the texture as noise (several times too much); this one is far closer
let old = estimate_noise_v1(&mosaic, 640, 640);
assert!(((old.0 * 0.2 + old.1) / (a * 0.2 + b)).sqrt() > 1.4, "the first version is the thing this one improves on");
}
/// A picture that is all texture is read as noisier than it is, never as meaningfully quieter.
#[test]
fn a_picture_with_no_flat_area_reads_noisier_than_it_is_never_quieter() {
let (a, b) = (5e-4f32, 1e-6f32);
let mosaic = textured_and_flat(a, b, 640, 9);
let (ea, eb) = estimate_noise(&mosaic, 640, 640);
for signal in [0.1f32, 0.3] {
assert!(ea * signal + eb >= 0.9 * (a * signal + b), "at {signal}: {} against {}", ea * signal + eb, a * signal + b);
}
}
/// Black, fully clipped and NaN mosaics, and a nonsensical probe setting, give finite numbers and no panic.
#[test]
fn a_clipped_or_all_dark_mosaic_is_measured_without_a_panic() {
for level in [0.0f32, 1.0, f32::NAN] {
let mosaic = vec![level; 200 * 200];
let (a, b) = estimate_noise(&mosaic, 200, 200);
assert!(a.is_finite() && b.is_finite() && a >= 0.0 && b > 0.0, "{level}: {a} {b}");
}
let probe = NoiseProbe { block: 0, quantile: f32::NAN, correction: -1.0 };
let (a, b) = estimate_noise_with(&vec![0.3; 200 * 200], 200, 200, &probe);
assert!(a.is_finite() && b.is_finite());
}
/// A heavily noisy tile is cleaned to under an eighth of a plain demosaic's error, whether the runner measures the
/// noise itself or is told it.
#[test]
fn a_heavily_noisy_tile_is_cleaned_far_more_than_a_plain_demosaic_and_by_the_photos_noise() {
let (t, a, b) = (64, 0.03, 0.004);
let truth = scene(2 * t);
let input = mosaic_planes(&truth, t, a, b, 9);
let planes: Vec<Vec<f32>> = input.chunks_exact(t * t).map(<[f32]>::to_vec).collect();
let plain = error(&demosaic(&planes, t), &truth, 2 * t);
let own = error(&Builtin::default().run(&input).unwrap(), &truth, 2 * t);
let told = error(&Builtin::with_noise((a, b)).run(&input).unwrap(), &truth, 2 * t);
assert!(own < plain / 8.0 && told < plain / 8.0, "plain {plain}, own {own}, told {told}");
}
/// Noise values that are not numbers fall back to the tile's own measurement; a tuning with no search, and the
/// non-local-means fallback, still give finite pictures; and the strength rises with the noise from 0 to 1.
#[test]
fn noise_values_that_are_not_numbers_fall_back_to_the_tiles_own_and_the_strength_follows_the_noise() {
let t = 32;
let input = vec![0.3f32; 4 * t * t];
for bad in [(f32::NAN, 1e-3), (0.01, f32::INFINITY), (-1.0, -1.0)] {
let out = Builtin { noise: Some(bad), tuning: Tuning::default() }.run(&input).unwrap();
assert!(out.iter().all(|v| v.is_finite()), "{bad:?}");
}
// no search at all is a plain demosaic, not a crash
let none = Builtin { noise: Some((0.01, 1e-3)), tuning: Tuning { search: 0, search2: 0, bm3d: None, ..Tuning::default() } };
assert!(none.run(&input).unwrap().iter().all(|v| v.is_finite()));
let nlm = Builtin { noise: Some((0.01, 1e-3)), tuning: Tuning { bm3d: None, ..Tuning::default() } };
assert!(nlm.run(&input).unwrap().iter().all(|v| v.is_finite()));
let tune = Tuning::default();
let ramp: Vec<f32> = [0.0, 0.02, 0.05, 0.1, 0.2].iter().map(|&n| tune.strength(n)).collect();
assert!(ramp.windows(2).all(|w| w[0] <= w[1]) && ramp[0] == 0.0 && ramp[4] == 1.0, "{ramp:?}");
}
/// The built-in denoiser's manifest passes the manifest check and carries the tile and overlap the runner uses.
#[test]
fn its_manifest_is_valid() {
let m = manifest();
crate::manifest::validate(&m).unwrap();
assert_eq!((m.tile, m.overlap), (TILE, OVERLAP));
}
}
+3
View File
@@ -4,10 +4,13 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod archive;
pub mod bayer;
pub mod bm3d;
pub mod builtin;
pub mod hash;
pub mod known;
pub mod licence;
pub mod manifest;
pub mod nlm;
pub mod product;
pub mod run;
pub mod tiles;
+416
View File
@@ -0,0 +1,416 @@
//! The built-in denoiser's filter: variance stabilisation and a non-local-means average whose weights come from all
//! four colour planes of a tile at once, so the planes are cleaned together instead of each on its own.
//!
//! Noise in a raw file has variance `a · signal + b`. The generalised Anscombe transform ([`Stabiliser`]) turns that
//! into noise of variance 1 everywhere, so one threshold fits every brightness. The four planes are then rotated
//! (a Hadamard transform, which keeps unit noise) into a brightness plane and three colour-difference planes.
//! Each cell becomes the average of the cells around it whose patch, over all four planes, looks like its own
//! within the noise, in two passes: the second finds matches on the first pass's much cleaner picture, so it can
//! look further and keep finer detail.
use crate::bayer::reflect;
/// What the filter may be tuned by (the defaults are what the built-in denoiser uses).
///
/// How strongly a photo is cleaned follows its noise, measured as the standard deviation at mid-grey (0.18, white = 1):
/// below `light` it is cleaned gently and in one pass, above `heavy` as hard as the filter goes, and in between smoothly.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tuning {
/// Search window radius, in cells, of the first pass.
pub search: usize,
/// Search window radius of the second pass, which finds matches on the first pass's cleaner picture; 0 skips it.
pub search2: usize,
/// How far above the noise two patches may differ and still be averaged in the first pass (larger blurs more),
/// for a light and for a heavily noisy photo.
pub h_light: f32,
pub h_heavy: f32,
/// The same for the second pass, which is blended in as the noise grows.
pub h2: f32,
/// Noise at mid-grey where the stronger settings start and where they are in full.
pub light: f32,
pub heavy: f32,
/// Search radius and threshold of the colour-difference planes' own pass, guided by the cleaned brightness
/// plane (colour noise is the cheapest to remove without losing texture); radius 0 skips it.
pub search_c: usize,
pub h_c: f32,
/// Patch radius (a patch is `2 · half + 1` cells on a side) of the first and of the later passes.
pub half: usize,
pub half2: usize,
/// How much looser (a multiple of the threshold) the average is that cells with few matching patches lean on in
/// the first pass; 0 turns it off.
pub loose: f32,
/// The matched weight below which they lean on it, in a heavily noisy photo (scaled down with the noise).
pub few: f32,
/// Block-matching collaborative filtering ([`crate::bm3d`]) is what cleans the planes; with `None` the non-local-means
/// averages above do (their settings apply only then).
pub bm3d: Option<crate::bm3d::Params>,
}
impl Default for Tuning {
/// The built-in denoiser's tuning: block matching on, and the non-local-means settings it falls back to when that is off.
fn default() -> Self {
Tuning {
search: 3,
search2: 5,
h_light: 0.3,
h_heavy: 0.45,
h2: 0.1,
light: 0.03,
heavy: 0.14,
search_c: 7,
h_c: 1.0,
half: 1,
half2: 1,
loose: 4.0,
few: 0.6,
bm3d: Some(crate::bm3d::Params::default()),
}
}
}
impl Tuning {
/// 0 for a lightly noisy photo up to 1 for a heavily noisy one.
pub fn strength(&self, noise: f32) -> f32 {
let span = (self.heavy - self.light).max(1e-6);
let x = ((noise - self.light) / span).clamp(0.0, 1.0);
x * x * (3.0 - 2.0 * x)
}
}
/// The generalised Anscombe transform for noise of variance `a · v + b`.
#[derive(Clone, Copy, Debug)]
pub struct Stabiliser {
a: f32,
b: f32,
}
/// Below this the noise has no signal-dependent part worth modelling.
const MIN_GAIN: f32 = 1e-6;
impl Stabiliser {
/// The transform for noise of variance `a · signal + b`; a gain or offset that is not a number counts as none.
pub fn new(a: f32, b: f32) -> Self {
Stabiliser { a: if a.is_finite() { a.max(0.0) } else { 0.0 }, b: if b.is_finite() { b.max(1e-12) } else { 1e-12 } }
}
/// A value as a signal with unit noise deviation (a plain scaling when the noise has no signal-dependent part).
pub fn forward(self, v: f32) -> f32 {
if self.a < MIN_GAIN {
return v / self.b.sqrt();
}
let x = (v + self.b / self.a) / self.a;
2.0 * (x + 0.375).max(0.0).sqrt()
}
/// The inverse, with the correction for the bias a plain inverse has on averaged data.
pub fn inverse(self, y: f32) -> f32 {
if self.a < MIN_GAIN {
return y * self.b.sqrt();
}
let x = if y >= 1.5 {
let (i1, i2) = (1.0 / y, 1.0 / (y * y));
y * y / 4.0 + 0.25 * 1.5f32.sqrt() * i1 - 11.0 / 8.0 * i2 + 5.0 / 8.0 * 1.5f32.sqrt() * i2 * i1 - 0.125
} else {
y * y / 4.0 - 0.375
};
self.a * x - self.b / self.a
}
}
/// The orthonormal 4 × 4 Hadamard transform across four planes (its own inverse).
pub fn hadamard(p: &[Vec<f32>]) -> Vec<Vec<f32>> {
let n = p.first().map_or(0, Vec::len);
let mut out = vec![vec![0f32; n]; 4];
for i in 0..n {
let g = |c: usize| p.get(c).and_then(|v| v.get(i)).copied().unwrap_or(0.0);
let (r, g1, g2, b) = (g(0), g(1), g(2), g(3));
let vals = [(r + g1 + g2 + b) / 2.0, (r - g1 + g2 - b) / 2.0, (r + g1 - g2 - b) / 2.0, (r - g1 - g2 + b) / 2.0];
for (c, v) in vals.into_iter().enumerate() {
if let Some(o) = out.get_mut(c).and_then(|o| o.get_mut(i)) {
*o = v;
}
}
}
out
}
/// A plane with `pad` cells mirrored round every edge (`t + 2 · pad` on a side).
fn padded(src: &[f32], t: usize, pad: usize) -> Vec<f32> {
let wd = t + 2 * pad;
let mut out = vec![0f32; wd * wd];
for y in 0..wd {
let sy = reflect(y as isize - pad as isize, t);
for x in 0..wd {
let sx = reflect(x as isize - pad as isize, t);
if let (Some(o), Some(v)) = (out.get_mut(y * wd + x), src.get(sy * t + sx)) {
*o = *v;
}
}
}
out
}
/// What one [`pass`] is run with.
#[derive(Clone, Copy)]
struct Pass {
/// Search window radius and patch radius, in cells.
radius: usize,
half: usize,
/// The threshold and the floor of the weights (see [`pass`]).
h: f32,
floor: f32,
/// A second, looser average (threshold `h · loose`) that cells with few matches lean on, so a cell no patch
/// resembles is not left as it was; 0 turns it off.
loose: f32,
/// Matched weight below which a cell starts to lean on that looser average.
few: f32,
}
/// One pass: every cell becomes the weighted average of the cells within `radius` whose patch (`2 · half + 1` cells
/// on a side), over all planes, is like its own. `guide` holds the planes the patches are compared on, `data` the
/// planes that are averaged (the same ones in the first pass). Weights are `exp(-(excess) / h)`, `excess` being how
/// far the mean squared difference of the patches is above `floor` (what two noisy views of one signal give).
fn pass(guide: &[Vec<f32>], data: &[Vec<f32>], t: usize, p: &Pass) -> Vec<Vec<f32>> {
let Pass { radius, half, h, floor, loose, few } = *p;
let pad = radius + half;
let wd = t + 2 * pad;
let guide: Vec<Vec<f32>> = guide.iter().map(|p| padded(p, t, pad)).collect();
let data: Vec<Vec<f32>> = data.iter().map(|p| padded(p, t, pad)).collect();
let (n, region, span) = (t * t, t + 2 * half, 2 * half + 1);
let planes = data.len().max(1);
let mut num = vec![vec![0f32; n]; planes];
let mut den = vec![0f32; n];
let mut num_l = vec![vec![0f32; n]; if loose > 0.0 { planes } else { 0 }];
let mut den_l = vec![0f32; if loose > 0.0 { n } else { 0 }];
let (mut d, mut rows) = (vec![0f32; region * region], vec![0f32; region * t]);
let norm = 1.0 / ((span * span) as f32 * guide.len().max(1) as f32);
let r = radius as isize;
for oy in -r..=r {
for ox in -r..=r {
if ox == 0 && oy == 0 {
continue;
}
let shift = oy * wd as isize + ox;
// squared differences over the planes, for the cells and the ring round them the patch reaches
for j in 0..region {
let base = (j + pad - half) * wd + pad - half;
for i in 0..region {
let pos = base + i;
let other = (pos as isize + shift) as usize;
let mut s = 0f32;
for p in &guide {
let (a, b) = (p.get(pos).copied().unwrap_or(0.0), p.get(other).copied().unwrap_or(0.0));
s += (a - b) * (a - b);
}
if let Some(v) = d.get_mut(j * region + i) {
*v = s;
}
}
}
// the sum over each cell's patch: along rows, then down columns
for j in 0..region {
for x in 0..t {
let k = j * region + x;
let s: f32 = (0..span).map(|i| d.get(k + i).copied().unwrap_or(0.0)).sum();
if let Some(v) = rows.get_mut(j * t + x) {
*v = s;
}
}
}
for y in 0..t {
for x in 0..t {
let k = y * t + x;
let patch = (0..span).map(|j| rows.get(k + j * t).copied().unwrap_or(0.0)).sum::<f32>() * norm;
let excess = (patch - floor).max(0.0);
let wide = if loose > 0.0 { loose } else { 1.0 };
// beyond this the weight is below 5e-5: not worth the exponential and the sums
if excess > 10.0 * h * wide {
continue;
}
let pos = (y + pad) * wd + x + pad;
let other = (pos as isize + shift) as usize;
if excess <= 10.0 * h {
let w = (-excess / h).exp();
if let Some(dn) = den.get_mut(k) {
*dn += w;
}
for (nu, p) in num.iter_mut().zip(&data) {
if let (Some(nu), Some(v)) = (nu.get_mut(k), p.get(other)) {
*nu += w * v;
}
}
}
if loose > 0.0 {
let w = (-excess / (h * loose)).exp();
if let Some(dn) = den_l.get_mut(k) {
*dn += w;
}
for (nu, p) in num_l.iter_mut().zip(&data) {
if let (Some(nu), Some(v)) = (nu.get_mut(k), p.get(other)) {
*nu += w * v;
}
}
}
}
}
}
}
// the cell itself counts as much as a perfect match
let mut out = vec![vec![0f32; n]; planes];
for (c, (o, (nu, p))) in out.iter_mut().zip(num.iter().zip(&data)).enumerate() {
for k in 0..n {
let own = p.get((k / t + pad) * wd + k % t + pad).copied().unwrap_or(0.0);
if let (Some(o), Some(nu), Some(dn)) = (o.get_mut(k), nu.get(k), den.get(k)) {
let tight = (nu + own) / (dn + 1.0);
*o = match (num_l.get(c).and_then(|v| v.get(k)), den_l.get(k)) {
(Some(nl), Some(dl)) => {
let loose = (nl + own) / (dl + 1.0);
let lean = if few > 0.0 { few / (dn + few) } else { 0.0 };
tight + (loose - tight) * lean
}
_ => tight,
};
}
}
}
out
}
/// Denoise four unit-noise planes of `t × t` cells (see the module description); `noise` is the photo's noise at
/// mid-grey, which sets how strongly (see [`Tuning`]).
pub fn filter(planes: &[Vec<f32>], t: usize, tune: &Tuning, noise: f32) -> Vec<Vec<f32>> {
let y = hadamard(planes);
let k = tune.strength(if noise.is_finite() { noise } else { 0.0 });
// two noisy views of one signal differ by 2 in mean square: the floor the excess is counted from
let h1 = tune.h_light + (tune.h_heavy - tune.h_light) * k;
let first = pass(&y, &y, t, &Pass { radius: tune.search, half: tune.half, h: h1, floor: 2.0, loose: tune.loose, few: tune.few * k });
if tune.search2 == 0 || k <= 0.0 {
return hadamard(&first);
}
// the first pass's picture still carries a little noise (of unknown size), so the floor is 0 and the threshold
// alone decides
let second = pass(&first, &y, t, &Pass { radius: tune.search2, half: tune.half2, h: tune.h2, floor: 0.0, loose: 0.0, few: 0.0 });
let mut blended: Vec<Vec<f32>> = first.iter().zip(&second).map(|(f, s)| f.iter().zip(s).map(|(f, s)| f + (s - f) * k).collect()).collect();
if tune.search_c > 0 {
// matches found on the cleaned brightness plane alone, so colour is only averaged across like brightness
let guide = blended.get(..1).unwrap_or_default();
let colour = pass(
guide,
y.get(1..).unwrap_or_default(),
t,
&Pass { radius: tune.search_c, half: tune.half2, h: tune.h_c, floor: 0.0, loose: 0.0, few: 0.0 },
);
for (b, c) in blended.iter_mut().skip(1).zip(&colour) {
for (b, c) in b.iter_mut().zip(c) {
*b += (c - *b) * k;
}
}
}
hadamard(&blended)
}
#[cfg(test)]
mod tests {
use super::*;
/// The transform is undone by its inverse within a little, a step of one noise deviation is a step of about 1
/// whatever the brightness, and with no signal-dependent noise it is a plain scaling.
#[test]
fn the_stabiliser_round_trips_and_gives_unit_noise() {
let s = Stabiliser::new(0.01, 0.0005);
for v in [0.0f32, 0.01, 0.1, 0.5, 0.9] {
let back = s.inverse(s.forward(v));
assert!((back - v).abs() < 0.005 + 0.03 * v, "{v} -> {back}");
}
// a step of one standard deviation is a step of about 1 whatever the brightness
for v in [0.05f32, 0.2, 0.6] {
let sigma = (0.01 * v + 0.0005).sqrt();
let step = s.forward(v + sigma) - s.forward(v);
assert!((step - 1.0).abs() < 0.15, "at {v}: {step}");
}
let flat = Stabiliser::new(0.0, 4e-4);
assert!((flat.forward(0.1) - 5.0).abs() < 1e-4 && (flat.inverse(5.0) - 0.1).abs() < 1e-6);
}
/// The Hadamard transform applied twice gives the planes back, and it keeps their energy.
#[test]
fn the_hadamard_transform_is_its_own_inverse_and_keeps_energy() {
let planes: Vec<Vec<f32>> = (0..4).map(|c| (0..9).map(|i| (c * 9 + i) as f32 * 0.37 - 3.0).collect()).collect();
let back = hadamard(&hadamard(&planes));
for (a, b) in planes.iter().flatten().zip(back.iter().flatten()) {
assert!((a - b).abs() < 1e-4);
}
let energy = |p: &[Vec<f32>]| p.iter().flatten().map(|v| v * v).sum::<f32>();
assert!((energy(&planes) - energy(&hadamard(&planes))).abs() < 1e-2);
}
/// Four planes of unit noise (an LCG and Box-Muller, so the tests need no dependency) round `level`.
fn noisy(t: usize, level: f32, seed: u64) -> Vec<Vec<f32>> {
let mut state = seed;
let mut uniform = move || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32
};
(0..4)
.map(|_| {
(0..t * t)
.map(|_| {
let (u, v) = (uniform(), uniform());
level + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
})
.collect()
})
.collect()
}
/// The deviation of the planes' values around `level`.
fn spread(planes: &[Vec<f32>], level: f32) -> f32 {
let all: Vec<f32> = planes.iter().flatten().copied().collect();
(all.iter().map(|v| (v - level) * (v - level)).sum::<f32>() / all.len().max(1) as f32).sqrt()
}
/// The colour planes' own pass leaves less noise than brightness alone would, and takes unit noise well below 0.5.
#[test]
fn the_colour_pass_cleans_colour_planes_further_than_brightness_alone_would() {
let (t, noise) = (40, 0.2);
let planes = noisy(t, 5.0, 3);
let with = filter(&planes, t, &Tuning::default(), noise);
let without = filter(&planes, t, &Tuning { search_c: 0, ..Tuning::default() }, noise);
// after the Hadamard rotation the colour differences are planes 1..4 of the mixed result, so compare it all
assert!(spread(&with, 5.0) < spread(&without, 5.0), "{} vs {}", spread(&with, 5.0), spread(&without, 5.0));
assert!(spread(&with, 5.0) < 0.5, "unit noise should drop well below 0.5: {}", spread(&with, 5.0));
}
/// A cell far from its surroundings, which no patch resembles, ends up nearer to them with the looser average than without it.
#[test]
fn a_cell_no_patch_resembles_is_not_left_as_a_speck_in_heavy_noise() {
let (t, noise) = (40, 0.2);
let mut planes = noisy(t, 5.0, 9);
// one cell far from its surroundings in every plane: nothing matches it
let at = (t / 2) * t + t / 2;
for p in &mut planes {
if let Some(v) = p.get_mut(at) {
*v += 6.0;
}
}
let with = filter(&planes, t, &Tuning::default(), noise);
let without = filter(&planes, t, &Tuning { loose: 0.0, ..Tuning::default() }, noise);
let peak = |planes: &[Vec<f32>]| planes.iter().filter_map(|p| p.get(at)).map(|v| (v - 5.0).abs()).fold(0f32, f32::max);
assert!(peak(&with) < peak(&without), "{} vs {}", peak(&with), peak(&without));
}
/// Noise of 0, NaN or next to nothing, with one cell far from the rest, still gives finite values.
#[test]
fn a_photo_with_no_measured_noise_stays_finite_even_with_an_odd_cell() {
let t = 24;
let mut planes = noisy(t, 5.0, 5);
for p in &mut planes {
if let Some(v) = p.get_mut(t * t / 2) {
*v += 50.0;
}
}
for noise in [0.0, f32::NAN, 1e-9] {
assert!(filter(&planes, t, &Tuning::default(), noise).iter().flatten().all(|v| v.is_finite()), "noise {noise}");
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
# lightcraft-denoise
L1 pure-Rust AI RAW denoise primitives and CPU inference. No weights are bundled.
L1 pure-Rust AI RAW denoise primitives and CPU inference. No weights are bundled; `lightcraft_denoise_core::builtin` is the model-free denoiser used by default.
See [user workflow and limitations](../../docs/denoise.md).
`lightcraft-denoise-core` provides metadata, Bayer helpers and cache formats,
+56 -2
View File
@@ -13,7 +13,7 @@ pub mod settings;
pub use controls::{CONTROLS, ControlSpec, Section, Track};
pub use presets::{Preset, SettingsGroup, apply_partial, extract_groups};
pub use segmask::SegMask;
pub use segmask::{SegMask, with_grid_interner};
pub use settings::*;
use serde_json::Value;
@@ -27,6 +27,7 @@ impl DevelopSettings {
s.wb.tint = as_shot_tint;
s.detail.sharpen_amount = 40.0;
s.detail.nr_color = 25.0;
s.detail.nr_outliers = true;
s
}
@@ -38,6 +39,18 @@ impl DevelopSettings {
serde_json::from_value(v.clone())
}
/// [`Self::to_json`] with Remove Hot Pixels (`detail.nr_outliers`) stated even when off, for JSON that is copied,
/// merged, scaled or compared key by key (copy / paste, presets, Auto Sync). The stored JSON leaves it out when
/// off, so settings saved before it keep their hash; a merge needs the `false`, or copying Detail would not turn
/// the box off and a preset applied at an amount would not find its base value.
pub fn to_json_for_merge(&self) -> Value {
let mut v = self.to_json();
if let Some(detail) = v.get_mut("detail").and_then(Value::as_object_mut) {
detail.insert("nr_outliers".into(), Value::Bool(self.detail.nr_outliers));
}
v
}
/// [`Self::from_json`] for settings from outside the app, such as a sidecar's `lc:settings`
/// (issue #2555): kept in range as [`Self::merged`] keeps them.
pub fn from_untrusted_json(v: &Value) -> Result<DevelopSettings, serde_json::Error> {
@@ -141,6 +154,12 @@ impl DevelopSettings {
std::borrow::Cow::Owned(d)
}
/// Whether a raw is decoded with its single outlier photosites replaced: Remove Hot Pixels is on and the Detail
/// section's eye is too (an Edit-panel section that is off contributes nothing, as in [`Self::effective`]).
pub fn removes_hot_pixels(&self) -> bool {
self.detail.nr_outliers && self.section_enabled("detail")
}
/// How much of the AI-denoised picture to mix in, 0 (none) to 1 (all of it): the Denoise amount, unless the Detail
/// section is switched off or the value is not a number.
pub fn denoise_amount(&self) -> f32 {
@@ -167,7 +186,11 @@ impl DevelopSettings {
self.curve = d;
}
Section::Color => self.wb.mode = WbMode::AsShot,
Section::Detail => self.enhance.denoise_on = None,
Section::Detail => {
self.enhance.denoise_on = None;
// not a slider: reset like them, to the general default (off)
self.detail.nr_outliers = false;
}
// the creative profile is not a control: the chosen look goes back to the default one,
// and so does the camera's own local tone mapping
Section::Profile => {
@@ -202,6 +225,37 @@ mod tests {
use super::*;
use serde_json::json;
/// Remove Hot Pixels (#1345) is on for a newly imported raw and off for everything else, and an edit saved
/// before the box existed reads as off, so it renders as it did.
#[test]
fn hot_pixel_box_is_on_for_new_raws_only() {
assert!(DevelopSettings::for_raw(5500.0, 10.0).detail.nr_outliers);
assert!(!DevelopSettings::default().detail.nr_outliers);
let mut saved = DevelopSettings::for_raw(5500.0, 10.0).to_json();
let detail = saved.get_mut("detail").and_then(|d| d.as_object_mut()).unwrap();
assert!(detail.remove("nr_outliers").is_some());
let read = DevelopSettings::from_json(&saved).unwrap();
assert!(!read.detail.nr_outliers);
assert_eq!(read.detail.nr_color, 25.0, "the rest of the saved edit is kept");
assert_ne!(read.hash64(), DevelopSettings::for_raw(5500.0, 10.0).hash64(), "cached renders are told apart");
// off is omitted: an edit saved before the box keeps its JSON, and so its hash and cached thumbnails
assert_eq!(read.to_json(), saved);
// copying Detail still carries the box when it is off
let copied = crate::extract_groups(&read, &[crate::SettingsGroup::Detail]);
assert_eq!(copied["detail"]["nr_outliers"], false);
let mut target = DevelopSettings::for_raw(5500.0, 10.0).to_json();
crate::presets::deep_merge(&mut target, &copied);
assert!(!DevelopSettings::from_json(&target).unwrap().detail.nr_outliers);
// the Detail eye switches it off for the decode too, and Reset Detail resets it like the sliders
let mut raw = DevelopSettings::for_raw(5500.0, 10.0);
assert!(raw.removes_hot_pixels());
raw.set_section_enabled("detail", false);
assert!(!raw.removes_hot_pixels());
raw.set_section_enabled("detail", true);
raw.reset_section(Section::Detail);
assert!(!raw.detail.nr_outliers && !raw.removes_hot_pixels());
}
#[test]
fn serde_roundtrip_default_and_edited() {
let mut s = DevelopSettings::default();
+312 -18
View File
@@ -1,8 +1,12 @@
//! Presets and copy/paste subsets.
//!
//! A preset is a *partial* settings object (JSON) — only the groups it includes. Applying merges it
//! into the photo's settings; `amount` (0..200 %) interpolates numeric values between the current
//! settings and the preset's. Copy/paste/sync use the same group selection ([`SettingsGroup`]).
//! A preset is a *partial* settings object (JSON) — only the settings it names. Applying it changes
//! exactly the settings it names (a leaf: a number, a flag, a name; an array is one leaf): each is
//! computed from the photo's *original* state (its import settings, when known) and the preset's
//! value, and replaces the photo's value; every other setting keeps the photo's value (issue
//! #2159). `amount` (0..200 %) moves each named number between the original and the preset's
//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the
//! current settings as before.
//!
//! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets
//! made from a photo never carry it, so the photos they change keep their own. A partial that names
@@ -126,7 +130,7 @@ impl SettingsGroup {
/// The subset of `s` covering `groups`, as a partial JSON object.
pub fn extract_groups(s: &DevelopSettings, groups: &[SettingsGroup]) -> Value {
let full = s.to_json();
let full = s.to_json_for_merge();
let mut out = Map::new();
for g in groups {
for k in g.keys() {
@@ -186,11 +190,79 @@ fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value {
/// Apply a partial settings object with an amount (1.0 = 100 %). Out-of-range values are clamped
/// through the control specs, as every merge does ([`DevelopSettings::merged`]).
pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> DevelopSettings {
let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json(), partial, amount)) };
let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json_for_merge(), partial, amount)) };
// (a white balance without a scale keeps its old meaning: `DevelopSettings::merged`)
s.merged(&patch).unwrap_or_else(|_| s.clone())
}
/// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on
/// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and
/// a preset without them leaves the photo's alone.
const REPAIR_KEYS: [&str; 3] = ["masks", "spots", "red_eye"];
/// The settings `settings` (a partial JSON object) names, applied to `current` at `amount`: each
/// named setting is computed from `original` (the photo's import state) and the preset's value,
/// and replaces the photo's value (issue #2159). Every setting the preset does not name keeps the
/// photo's current value, edits included. Pixel repairs compose on the photo's own values, as they
/// always have.
fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings: &Value, amount: f64) -> DevelopSettings {
// At 100 % the preset's own values apply as they are, and `original` is not read. The presets
// panel calls this for every visible row on every frame, so the scaling base is built below only.
if (amount - 1.0).abs() < 1e-9 {
return current.merged(settings).unwrap_or_else(|_| current.clone());
}
let cur = current.to_json();
let mut base = original.to_json();
if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) {
for k in REPAIR_KEYS {
if let Some(v) = c.get(k) {
b.insert(k.to_string(), v.clone());
}
}
}
let composed = match settings.as_object() {
Some(patch) => Value::Object(interpolate_object(base.as_object(), patch, amount)),
None => Value::Object(Map::new()),
};
// `merged` deep-merges: the named settings replace, everything else stays as `current` has it
current.merged(&composed).unwrap_or_else(|_| current.clone())
}
/// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in
/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there.
fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Value>, t: f64) -> Map<String, Value> {
let mut out = Map::new();
for (k, pv) in patch {
let bv = base.and_then(|b| b.get(k));
let v = match pv {
Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))),
_ => interpolate_leaf(bv, pv, t),
};
if let Some(v) = v {
out.insert(k.clone(), v);
}
}
out
}
/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's
/// at half amount and up, and below it take the base's value. A null in the base is the baseline
/// value the import state recorded (a cleared option, such as a free crop aspect): below half
/// amount it applies and clears the photo's value, as the amount contract promises. A null the
/// preset writes is a value like any other, so it applies at half amount and up (a preset can
/// clear an option field such as a crop aspect).
fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option<Value> {
match (base, patch) {
// integer fields (the grain seed, ids) are discrete like strings: see `scale_patch`
(Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => {
let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0));
serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number)
}
_ if t >= 0.5 => Some(patch.clone()),
_ => base.cloned(),
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Preset {
pub id: String,
@@ -209,30 +281,49 @@ impl Preset {
pub fn from_settings(id: &str, name: &str, group: &str, s: &DevelopSettings, groups: &[SettingsGroup]) -> Preset {
Preset { id: id.into(), name: name.into(), group: group.into(), settings: extract_groups(s, groups), favorite: false, builtin: false }
}
/// Apply at `amount` (1.0 = 100 %). Masks in the preset are added to the photo's own (ones it
/// already has are skipped), their effect scaled by the amount.
/// Apply at `amount` (1.0 = 100 %), with `s` as both the photo's current and its original
/// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch
/// bases. Masks in the preset are added to the photo's own (ones it already has are skipped),
/// their effect scaled by the amount.
pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings {
self.apply_on(s, s, amount)
}
/// Apply at `amount` (1.0 = 100 %), composing on `original` (the photo's import state, or the
/// photo's current settings when that is not known): each setting the preset names is computed
/// from `original` and the preset's value, `amount` moving it between the two, and replaces the
/// photo's value. Every setting the preset does not name keeps `current`'s value, and so do
/// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the
/// preset are added to the photo's own (ones it already has are skipped), their effect scaled
/// by the amount. A second preset therefore restores what the first one changed in the
/// settings it names (issue #2159), and nothing it leaves out.
pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings {
let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else {
return apply_partial(s, &self.settings, amount);
return compose_named(current, original, &self.settings, amount);
};
let mut rest = self.settings.clone();
if let Some(o) = rest.as_object_mut() {
o.remove("masks");
}
let mut out = apply_partial(s, &rest, amount);
for m in masks {
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
continue;
}
m.id = out.next_mask_id();
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
out.masks.push(m);
}
let mut out = compose_named(current, original, &rest, amount);
add_masks(&mut out, masks, amount);
out
}
}
/// The preset's masks, added to the photo's own (ones it already has are skipped), their effect
/// scaled by the amount.
fn add_masks(out: &mut DevelopSettings, masks: &[Value], amount: f64) {
for m in masks {
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
continue;
}
m.id = out.next_mask_id();
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
out.masks.push(m);
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -285,6 +376,209 @@ mod tests {
}
}
/// A preset changes only the settings it names: a setting in a group it styles but does not
/// name keeps the photo's value, and so does a whole group it leaves out.
#[test]
fn apply_on_changes_only_the_settings_it_names() {
let mut current = DevelopSettings::default();
current.light.exposure = 2.0;
current.light.blacks = -30.0;
current.effects.clarity = 30.0;
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"light": {"contrast": 12.0}}),
favorite: false,
builtin: false,
};
let out = p.apply_on(&current, &original, 1.0);
assert_eq!(out.light.contrast, 12.0);
assert_eq!(out.light.exposure, 2.0, "a setting the preset doesn't name keeps the photo's value");
assert_eq!(out.light.blacks, -30.0, "a setting in the same group, not named, keeps the photo's value");
assert_eq!(out.effects.clarity, 30.0, "a group the preset doesn't name is untouched");
}
/// A partial preset that names one colour of the mixer leaves the other colours, and the
/// unnamed settings of the colour it names, as the photo has them.
#[test]
fn apply_on_keeps_the_mixer_colours_it_does_not_name() {
let mut current = DevelopSettings::default();
current.mixer.red.sat = 20.0;
current.mixer.blue.hue = 15.0;
current.mixer.blue.sat = 5.0;
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"mixer": {"blue": {"sat": 15.0, "lum": -25.0}}}),
favorite: false,
builtin: false,
};
let out = p.apply_on(&current, &original, 1.0);
assert_eq!(out.mixer.red.sat, 20.0, "a colour the preset doesn't name");
assert_eq!(out.mixer.blue.hue, 15.0, "a setting of a named colour that the preset doesn't name");
assert_eq!((out.mixer.blue.sat, out.mixer.blue.lum), (15.0, -25.0));
}
/// The white balance is not one setting: a preset that names only the temperature keeps the
/// photo's tint.
#[test]
fn apply_on_keeps_the_white_balance_fields_it_does_not_name() {
let mut current = DevelopSettings::default();
current.wb.temp = 6000.0;
current.wb.tint = 12.0;
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"wb": {"temp": 5000.0}}),
favorite: false,
builtin: false,
};
let out = p.apply_on(&current, &original, 1.0);
assert_eq!((out.wb.temp, out.wb.tint), (5000.0, 12.0));
}
/// A preset's amount 0 changes nothing when the original is the photo's current settings (no
/// import state is recorded for the photo), and any other amount moves the named settings
/// from where the photo has them.
#[test]
fn apply_on_without_an_import_state_scales_from_the_current_settings() {
let mut current = DevelopSettings::default();
current.light.exposure = 2.0;
current.light.blacks = -30.0;
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"light": {"exposure": 0.45, "contrast": 12.0}}),
favorite: false,
builtin: false,
};
assert_eq!(p.apply_on(&current, &current, 0.0), current, "amount 0 applies nothing");
let half = p.apply_on(&current, &current, 0.5);
assert!((half.light.exposure - 1.225).abs() < 1e-9, "{}", half.light.exposure);
assert_eq!(half.light.blacks, -30.0);
}
/// An unresolved `crs:Look` reference (its profile object has no id; the importer leaves
/// `look` in it) changes nothing: the photo keeps its own profile.
#[test]
fn an_unresolved_profile_reference_keeps_the_photos_profile() {
let mut current = DevelopSettings::default();
current.profile.id = "lc.vivid".into();
current.profile.amount = 60.0;
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"profile": {"look": {"name": "Not imported", "amount": 100.0}}, "light": {"contrast": 12.0}}),
favorite: false,
builtin: false,
};
for amount in [1.0, 0.5] {
let out = p.apply_on(&current, &current, amount);
assert_eq!((out.profile.id.as_str(), out.profile.amount), ("lc.vivid", 60.0), "amount {amount}");
}
}
/// The amount interpolates between the original and the preset, not between the visible
/// values and the preset: a preset at 50 % looks the same however the photo was edited before.
#[test]
fn apply_on_scales_against_the_original() {
let mut current = DevelopSettings::default();
current.light.exposure = 2.0;
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"light": {"exposure": 0.45}}),
favorite: false,
builtin: false,
};
let out = p.apply_on(&current, &original, 0.5);
assert!((out.light.exposure - 0.225).abs() < 1e-9, "{}", out.light.exposure);
}
/// Pixel repairs are the photo's own: a preset's are patched in, and one without them never
/// restores the original's.
#[test]
fn apply_on_patches_pixel_repairs_into_the_current_ones() {
let current = DevelopSettings {
spots: serde_json::from_value(json!([{"mode": "heal", "points": [[0.5, 0.5]], "size": 0.05, "feather": 50.0, "opacity": 100.0}]))
.unwrap(),
..Default::default()
};
let original = DevelopSettings::default();
let none = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"light": {"contrast": 10.0}}),
favorite: false,
builtin: false,
};
let out = none.apply_on(&current, &original, 1.0);
assert_eq!(out.spots.len(), 1, "the photo's spot survives a preset without spots");
let clearing = Preset {
id: "q".into(),
name: "Q".into(),
group: "G".into(),
settings: json!({"light": {"contrast": 10.0}, "spots": []}),
favorite: false,
builtin: false,
};
let out = clearing.apply_on(&current, &original, 1.0);
assert_eq!(out.spots.len(), 0, "a preset that names spots replaces them, as before");
}
/// A null a preset writes into an option field (here a crop aspect: null is "free") is the
/// preset's value, so it clears the photo's aspect from half amount up, as any value of the
/// preset does; below half amount the import baseline applies, which here is null as well.
#[test]
fn a_preset_null_clears_an_option_field_from_half_amount() {
let mut current = DevelopSettings::default();
current.crop.aspect = Some((3, 2));
let original = DevelopSettings::default(); // the import state has no aspect
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"crop": {"aspect": null}}),
favorite: false,
builtin: false,
};
for amount in [1.0, 0.7, 0.5] {
assert_eq!(p.apply_on(&current, &original, amount).crop.aspect, None, "amount {amount}: the preset's null clears the aspect");
}
assert_eq!(p.apply_on(&current, &original, 0.3).crop.aspect, None, "below half amount the import baseline (no aspect) applies");
}
/// The import state has no aspect, and that null is the baseline below half amount (the amount
/// contract: a named setting moves between the import state and the preset's value); from half
/// amount the preset's aspect applies.
#[test]
fn a_null_in_the_original_is_the_baseline_below_half_amount() {
let mut current = DevelopSettings::default();
current.crop.aspect = Some((3, 2));
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"crop": {"aspect": [16, 9]}}),
favorite: false,
builtin: false,
};
assert_eq!(p.apply_on(&current, &original, 0.4).crop.aspect, None, "40 %: the import baseline (no aspect) applies");
assert_eq!(p.apply_on(&current, &original, 0.6).crop.aspect, Some((16, 9)), "60 %: the preset's aspect applies");
}
#[test]
fn deep_merge_objects() {
let mut a = json!({"x": {"a": 1, "b": 2}, "y": [1]});
+119 -4
View File
@@ -1,6 +1,9 @@
//! Model segmentations stored with a mask ([`SegMask`]), so rendering never needs the model.
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::HashMap;
use serde::{Deserialize, Serialize, Serializer};
/// Logits are stored in steps of 1/`SCALE`, clamped to ±127/`SCALE` (≈ ±15.9: a sigmoid of
/// 1 − 1.2e-7, i.e. fully in or out).
@@ -13,15 +16,26 @@ pub const MAX_SIDE: usize = 1024;
/// normalized `((x + 0.5) / side, (y + 0.5) / side)`), quantized to `i8`, deflated and base64
/// encoded. Coverage at a point is the sigmoid of the bilinearly sampled logit, so edges stay
/// smooth at any output size.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct SegMask {
pub side: u32,
/// The grid's bytes (quantized, deflated, base64), unless this is a reference into the
/// snapshot's shared grid table (`grid` is set and `data` is empty).
#[serde(default)]
pub data: String,
/// The part of the image the grid covers, normalized `[x0, y0, x1, y1]` (`None` = all of
/// it). A zoomed-in pass over one object covers just its surroundings, at a higher
/// resolution than a pass over the whole photo.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rect: Option<[f64; 4]>,
/// Index into the catalog snapshot's shared grid table (`Catalog::grids`) this mask refers
/// to instead of carrying its own `data`. A serialization detail of snapshots only: the
/// snapshot writer sets it (through the interner, into its own table), `Catalog::repair`
/// resolves it when a snapshot is read, and no other serialization writes it. A `grid` that
/// arrives from any other document (a command, a preset, XMP, a log record) is read but
/// never written back, so it cannot point a snapshot at another mask's grid.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grid: Option<u32>,
}
impl SegMask {
@@ -29,7 +43,7 @@ impl SegMask {
pub fn from_logits(side: usize, logits: &[f32]) -> SegMask {
let q: Vec<u8> = logits.iter().take(side * side).map(|l| ((l * SCALE).round().clamp(-127.0, 127.0) as i8) as u8).collect();
let z = miniz_oxide::deflate::compress_to_vec(&q, 8);
SegMask { side: side as u32, data: base64_encode(&z), rect: None }
SegMask { side: side as u32, data: base64_encode(&z), rect: None, grid: None }
}
/// From `side × side` logits over the part `rect` of the image.
@@ -55,6 +69,63 @@ impl SegMask {
}
}
// The grid table a snapshot serialization refers to: each distinct grid's data → its index.
thread_local! {
static INTERNER: RefCell<Option<HashMap<String, u32>>> = const { RefCell::new(None) };
}
/// Serializes masks as references into a shared grid table (`grid` = index, `data` omitted)
/// while `f` runs, one thread at a time (snapshot writes). Nested calls are ignored (`None`):
/// the outermost writer owns the table.
pub fn with_grid_interner<T>(map: HashMap<String, u32>, f: impl FnOnce() -> T) -> Option<T> {
INTERNER.with(|i| {
if i.borrow().is_some() {
return None;
}
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
INTERNER.with(|j| *j.borrow_mut() = None);
}
}
*i.borrow_mut() = Some(map);
let _guard = Guard;
Some(f())
})
}
impl Serialize for SegMask {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
// While a snapshot is being written with a shared grid table, a mask whose exact bytes
// are in the table refers to it by index instead of repeating the blob (issue #2154).
if !self.data.is_empty()
&& let Some(id) = INTERNER.with(|i| i.borrow().as_ref().and_then(|m| m.get(&self.data).copied()))
{
let len = if self.rect.is_some() { 3 } else { 2 };
let mut map = serializer.serialize_map(Some(len))?;
map.serialize_entry("side", &self.side)?;
map.serialize_entry("grid", &id)?;
if let Some(rect) = self.rect {
map.serialize_entry("rect", &rect)?;
}
return map.end();
}
// Without a table hit: exactly the pre-v10 derived form (field order and skips included),
// so every serialization that doesn't dedup keeps its bytes (`hash64`, cache keys). `grid`
// is never written here: a value read from some document is dropped on save, and only the
// interner above can write a reference (into the table of the snapshot being written).
let len = 2 + usize::from(self.rect.is_some());
let mut map = serializer.serialize_map(Some(len))?;
map.serialize_entry("side", &self.side)?;
map.serialize_entry("data", &self.data)?;
if let Some(rect) = self.rect {
map.serialize_entry("rect", &rect)?;
}
map.end()
}
}
/// Most zoomed-in detail patches one AI mask component keeps (the app makes one; each costs a
/// decode per render, so a hostile document can't make rendering explode).
pub const MAX_DETAIL: usize = 4;
@@ -189,7 +260,51 @@ mod tests {
assert!(m.logits().is_none(), "size mismatch");
m.side = 100_000;
assert!(m.logits().is_none(), "absurd size");
assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None }.logits().is_none());
assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None, grid: None }.logits().is_none());
assert!(SegMask { rect: Some([0.5, 0.0, 0.2, 1.0]), ..SegMask::from_logits(2, &[0.0; 4]) }.bounds().is_none());
}
/// A `grid` read from a document is never written outside the snapshot interner, with or
/// without data: the bytes stay the pre-v10 form, so `hash64` and cache keys don't depend on
/// a stray value (issue #2154).
#[test]
fn stray_grid_is_never_written_outside_the_interner() {
let empty = SegMask { side: 4, data: String::new(), rect: None, grid: None };
let stray = SegMask { grid: Some(3), ..empty.clone() };
assert_eq!(serde_json::to_string(&stray).unwrap(), "{\"side\":4,\"data\":\"\"}");
assert_eq!(serde_json::to_string(&stray).unwrap(), serde_json::to_string(&empty).unwrap());
let with_data = SegMask { grid: Some(3), ..SegMask::from_logits(4, &[1.0; 16]) };
assert!(!serde_json::to_string(&with_data).unwrap().contains("grid"), "no grid key outside the interner");
}
/// Without the snapshot interner the JSON is exactly the derived form it always was; with
/// it, a pooled grid serializes as an index and the data is left to the table (issue #2154).
#[test]
fn serialization_refs_only_under_the_interner() {
let m = SegMask::from_logits(4, &[1.0; 16]);
let plain = serde_json::to_string(&m).unwrap();
assert_eq!(plain, format!("{{\"side\":4,\"data\":\"{}\"}}", m.data), "no interner: unchanged bytes");
let with_rect = SegMask { rect: Some([0.0, 0.0, 0.5, 0.5]), ..m.clone() };
assert_eq!(serde_json::to_string(&with_rect).unwrap(), format!("{{\"side\":4,\"data\":\"{}\",\"rect\":[0.0,0.0,0.5,0.5]}}", m.data));
let mut table = std::collections::HashMap::new();
table.insert(m.data.clone(), 3u32);
let referenced = with_grid_interner(table, || serde_json::to_string(&m).unwrap()).unwrap();
assert_eq!(referenced, "{\"side\":4,\"grid\":3}", "pooled grid: an index, no data");
// a grid the table doesn't hold, and an empty-data mask, stay inline
let other = SegMask::from_logits(2, &[0.0; 4]);
let mixed = with_grid_interner(std::collections::HashMap::new(), || serde_json::to_string(&other).unwrap()).unwrap();
assert_eq!(mixed, format!("{{\"side\":2,\"data\":\"{}\"}}", other.data));
// the interner is gone afterwards: serialization is inline again
assert_eq!(serde_json::to_string(&m).unwrap(), plain);
// nested calls are ignored: the outer writer keeps its table
let outer_table = std::collections::HashMap::from([(m.data.clone(), 0u32)]);
let nested = with_grid_interner(outer_table, || {
let inner_table = std::collections::HashMap::from([(other.data.clone(), 1u32)]);
(with_grid_interner(inner_table, || serde_json::to_string(&other).unwrap()), serde_json::to_string(&m).unwrap())
})
.unwrap();
assert_eq!(nested.0, None, "the nested writer is refused");
assert_eq!(nested.1, "{\"side\":4,\"grid\":0}");
}
}
+80 -2
View File
@@ -90,12 +90,15 @@ pub enum Process {
/// camera curve keeps V2 Whites and fitted pointwise operators follow it
/// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`).
V4,
/// V4, with a raw's tone curve rolling off into white in stops past its last fitted knot, so
/// highlights the sensor recorded keep their detail when Exposure lifts them (issue #1632).
V5,
}
impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4];
pub const LATEST: Process = Process::V4;
pub const ALL: [Process; 5] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5];
pub const LATEST: Process = Process::V5;
pub const fn version(self) -> ProcessVersion {
match self {
@@ -103,6 +106,7 @@ impl Process {
Process::V2 => ProcessVersion(2),
Process::V3 => ProcessVersion(3),
Process::V4 => ProcessVersion(4),
Process::V5 => ProcessVersion(5),
}
}
}
@@ -632,6 +636,13 @@ pub struct Detail {
pub nr_color: f64,
pub nr_color_detail: f64,
pub nr_color_smoothness: f64,
/// Replace single outlier photosites (noise spikes far above all their same-colour neighbours) in the
/// raw mosaic before demosaicing, so they do not become coloured dots (#1345). On for newly imported
/// raws ([`crate::DevelopSettings::for_raw`]); off for edits saved before it existed, so they look the
/// same. Raw files only. Omitted when off, so settings saved before it keep their JSON (and hash, and with it
/// their cached thumbnails).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub nr_outliers: bool,
}
impl Default for Detail {
@@ -649,6 +660,7 @@ impl Default for Detail {
nr_color: 0.0,
nr_color_detail: 50.0,
nr_color_smoothness: 50.0,
nr_outliers: false,
}
}
}
@@ -1115,6 +1127,72 @@ impl Default for Mask {
}
}
impl DevelopSettings {
/// Calls `f` for every segmentation grid stored in these settings (the `seg` and `detail`
/// of Object and Prompt mask shapes).
pub fn visit_seg_masks(&self, f: &mut impl FnMut(&crate::SegMask)) {
for mask in &self.masks {
for component in &mask.components {
visit_shape(&component.shape, f);
}
}
}
/// [`DevelopSettings::visit_seg_masks`] with mutable access (resolving references into a
/// snapshot's grid table).
pub fn visit_seg_masks_mut(&mut self, f: &mut impl FnMut(&mut crate::SegMask)) {
for mask in &mut self.masks {
for component in &mut mask.components {
visit_shape_mut(&mut component.shape, f);
}
}
}
}
fn visit_shape(shape: &MaskShape, f: &mut impl FnMut(&crate::SegMask)) {
match shape {
MaskShape::Object { seg, detail, .. } => {
if let Some(seg) = seg {
f(seg);
}
for d in detail {
f(d);
}
}
MaskShape::Prompt { seg, detail, .. } => {
if let Some(seg) = seg {
f(seg);
}
for d in detail {
f(d);
}
}
_ => {}
}
}
fn visit_shape_mut(shape: &mut MaskShape, f: &mut impl FnMut(&mut crate::SegMask)) {
match shape {
MaskShape::Object { seg, detail, .. } => {
if let Some(seg) = seg.as_mut() {
f(seg);
}
for d in detail {
f(d);
}
}
MaskShape::Prompt { seg, detail, .. } => {
if let Some(seg) = seg.as_mut() {
f(seg);
}
for d in detail {
f(d);
}
}
_ => {}
}
}
// ---------------------------------------------------------------------------------------------
// Heal / remove / red eye
+2
View File
@@ -49,6 +49,8 @@ lightcraft-segment = { workspace = true, optional = true }
lightcraft-fetch = { workspace = true }
# capture-time parsing for face recognition (native only)
chrono = { workspace = true }
# free space of the drive holding the preview cache (the low-disk alert; pure Rust: rustix / windows-sys)
fs4 = { workspace = true }
[features]
# AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds.
+1 -1
View File
@@ -144,7 +144,7 @@ fn benchmark_load(args: &[String], n: usize, only: &str) {
}
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
let (loader, _) = lightcraft_engine::files::fs_hooks();
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, None).expect("load"))));
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, Default::default()).expect("load"))));
}
}
+6 -1
View File
@@ -169,7 +169,12 @@ pub(super) fn dro_off(own_tone: &CameraTone) -> CameraTone {
// Past its last knot a curve goes on as a shoulder whose rate comes from its last two knots
// (`CameraTone::apply`): lowering the second-last knot more than the last steepens it, and the
// extended highlights would end up above the fitted curve. Raise the second-last knot (never
// above the fitted curve) until the rate is at most the fitted curve's.
// above the fitted curve) until the rate is at most the fitted curve's. Process V5's shoulder
// (`CameraTone::apply_rolloff`) is not part of this bound or of `at_most`: V1 to V4 read the
// same curve, and a V5 bound here would change their renders. It stays below the fitted
// curve's too when the last segment's slope over the squared gap to white is at most the fitted
// curve's; a lowered curve with a nearly flat last segment can end up above it far past the last
// knot under V5 (issue #1632).
let ([a, b], last) = ([own[30], own[31]], knots[31]);
let rate = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0) / (1.0 - b[1]).max(0.01);
let floor = last[1] - rate * (1.0 - last[1]).max(0.01) * (b[0] - a[0]);
+26
View File
@@ -1285,6 +1285,30 @@ fn assert_lowered(fitted: &CameraLook, fixed: &CameraLook, what: &str) {
let x = 0.001 * 1.005f32.powi(i);
assert!(fixed.tone.apply(x) <= fitted.tone.apply(x) + 1e-5, "{what} at {x}: {} > {}", fixed.tone.apply(x), fitted.tone.apply(x));
}
// V5's shoulder stays below too whenever the lowered last segment's slope over its squared gap to
// white is at most the fitted one's (`dro_off` doesn't enforce it, so V1 to V4 keep their curve;
// issue #1632)
if v5_bounded(&fixed.tone, &fitted.tone) {
assert!(v5_below(&fixed.tone, &fitted.tone), "{what}: brighter than the fitted curve under V5");
}
}
/// Whether the last segment of `a`, over its squared gap to white, is at most `b`'s: then `a`'s V5
/// shoulder ([`CameraTone::apply_rolloff`]) is nowhere above `b`'s (issue #1632).
fn v5_bounded(a: &CameraTone, b: &CameraTone) -> bool {
let rate = |t: &CameraTone| {
let k = t.knots();
((k[31][1] - k[30][1]) / (k[31][0] - k[30][0])).max(0.0) / (1.0 - k[31][1]).powi(2)
};
rate(a) <= rate(b)
}
/// Whether `a`'s V5 curve is nowhere brighter than `b`'s, from deep shadows to far past the last knot.
fn v5_below(a: &CameraTone, b: &CameraTone) -> bool {
(0..=2400).all(|i| {
let x = 0.001 * 1.005f32.powi(i);
a.apply_rolloff(x) <= b.apply_rolloff(x) + 1e-5
})
}
/// Issue #244: Sony's Dynamic Range Optimizer lifts the camera JPEG's shadows, not the raw's. A
@@ -1423,6 +1447,8 @@ fn corpus_arw_with_dro_is_lowered_to_the_dro_off_tone() {
let fitted = fit_look(&sensor, &reference, &clipped, colour).unwrap();
if dro {
assert_lowered(&fitted, &look, name);
// the Sony DRO samples' lowered curves stay below their fitted ones under V5 as well
assert!(v5_below(&look.tone, &fitted.tone), "{name}: brighter than the fitted curve under V5");
for x in lowered {
assert!(look.tone.apply(x) < 0.95 * fitted.tone.apply(x), "{name} at {x}: {} vs {}", look.tone.apply(x), fitted.tone.apply(x));
}
+60
View File
@@ -271,6 +271,66 @@ pub(crate) fn bool_or(p: &Value, key: &str, d: bool) -> bool {
pub(crate) fn ok() -> Result<Value> {
Ok(Value::Null)
}
/// A batch-edit recipe from a command's params: `[{id, value}, …]`, each `id` a develop control a
/// recipe may name ([`check_recipe`]). Empty when absent or null. A malformed item, a control a
/// recipe may not name, or more entries than there are controls is an error, so a typo is refused
/// rather than silently ignored. An id named twice counts once, the last value winning; the list
/// comes back in id order.
pub(crate) fn recipe_param(p: &Value, cmd: &str) -> Result<Vec<(String, f64)>> {
let Some(v) = p.get("recipe").filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
let Some(items) = v.as_array() else {
return Err(bad(cmd, "`recipe` must be a list of {id, value}"));
};
let most = lightcraft_develop::controls::CONTROLS.len();
if items.len() > most {
return Err(bad(cmd, format!("a recipe has one entry per control, at most {most} (it has {})", items.len())));
}
let mut by_id = std::collections::BTreeMap::new();
for it in items {
let id = it.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "each recipe item needs an `id`"))?;
let value = it.get("value").and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("recipe `{id}` needs a numeric `value`")))?;
by_id.insert(id.to_string(), value);
}
let recipe: Vec<(String, f64)> = by_id.into_iter().collect();
check_recipe(&recipe).map_err(|e| bad(cmd, e))?;
Ok(recipe)
}
/// Whether every control of `recipe` is one a batch-edit recipe may name, else why not. The rule is
/// on the control's spec: a plain control of the shared list, writable on any photo's settings
/// (`set` takes it), outside the Geometry section and not white balance.
///
/// - Per-photo instances (`pointColor.0.hueShift`, `redEye.0.pupilSize`) are not in the list; on a
/// photo without that instance a write is dropped.
/// - Geometry controls (`crop.angle`, `geometry.*`) need the photo's own size: the slider refits the
/// crop around a new angle, which a batch write cannot do.
/// - White balance means something else on each kind of file (Kelvin on a raw with matrices,
/// relative to the as-shot white on a rendered photo or a raw without them), so one temperature
/// cannot name the same look for every photo of a batch.
pub(crate) fn check_recipe(recipe: &[(String, f64)]) -> std::result::Result<(), String> {
use lightcraft_develop::{Section, controls};
let mut scratch = lightcraft_develop::DevelopSettings::default();
for (id, value) in recipe {
let Some(spec) = controls::CONTROLS.iter().find(|c| c.id == id.as_str()) else {
return Err(format!(
"unknown recipe control `{id}` (see develop.controls; a control that belongs to one photo, such as pointColor.0.hueShift, is not one)"
));
};
if spec.section == Section::Geometry {
return Err(format!("`{id}` is a geometry control: a recipe does not crop, straighten or transform photos"));
}
if id.starts_with("wb.") {
return Err(format!(
"`{id}` is white balance: a recipe does not set it, because a temperature means something else on a raw than on a rendered photo"
));
}
if !controls::set(&mut scratch, id, *value) {
return Err(format!("recipe control `{id}` cannot be set"));
}
}
Ok(())
}
pub(crate) fn point(p: &Value, key: &str) -> Option<lightcraft_geom::Point> {
let a = p.get(key)?.as_array()?;
Some(lightcraft_geom::Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?))
+6 -3
View File
@@ -118,6 +118,9 @@ fn identify(path: &Path, c: &str, sha_known: Option<&str>) -> Result<Source> {
&& let Some(bytes) = read_capped(&sibling, MAX_MANIFEST_BYTES)
{
let m = manifest::parse(&bytes).map_err(|e| bad(c, format!("{}: {e}", sibling.display())))?;
if m.id == lightcraft_denoise::builtin::ID {
return Err(bad(c, "the id `builtin` is LightCraft's own denoiser: give the model another id in its denoise-model.json"));
}
return Ok(Source { manifest: m, entry: None, file_name });
}
Err(bad(
@@ -660,20 +663,20 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(query "denoise.models.downloadCancel", "Cancel Denoise Model Download", [], None, "{id} → {discarded} — stop a download, or delete a finished one that was not installed", always, download_cancel),
cmd!(query "denoise.models.test", "Test Denoise Model", [], None, "{id} → {ok, result} — load an installed model and check it gives sensible pictures; needs the denoise runtime", always, test),
cmd!(query "denoise.models.remove", "Remove Denoise Model", [], None, "{id} → {removed, model} — delete an installed model (its cached pictures stay until they are evicted)", always, remove),
cmd!(query "denoise.models.select", "Choose Denoise Model", [], None, "{id: installed model | null} → {model} — null switches denoise off", always, select),
cmd!(query "denoise.models.select", "Choose Denoise Model", [], None, "{id: installed model | null} → {model} — null uses the built-in denoiser", always, select),
cmd!(query "denoise.settings", "Denoise Settings", [], None, "{auto?: bool, cacheGb?: 1..10000, threads?: 1..64 | null, runOn?: auto | gpu | cpu} → the settings — `auto`: make the picture of the photos being looked at that have a Denoise amount; `cacheGb`: how much the cached pictures may take; `threads`: most tiles run at once; `runOn`: where the model runs — `auto` (the default) the graphics card where it is faster than the processor (both timed on this computer when the card is set up), `gpu` the card whenever it can run the model, `cpu` the processor. Setting `runOn` also lets the card be tried again after a set-up that failed or closed LightCraft", always, settings),
cmd!(
"denoise.toggle",
"AI Denoise",
[],
None,
"{id?: photoId, enabled?: bool} → {id, enabled, amount} — turn AI Denoise on (50% initially) or off for one raw photo, independent of selection and Auto Sync; needs an installed model to turn on",
"{id?: photoId, enabled?: bool} → {id, enabled, amount} — turn AI Denoise on (50% initially) or off for one raw photo, independent of selection and Auto Sync; uses the built-in denoiser when no model is chosen",
always,
toggle
),
cmd!(query "denoise.queue", "Denoise Photos", [], None, "{ids?: [photoId], scope?: selected | visible | withAmount, retry?: false} → {added, …status} — make the denoised pictures of raw photos that have none, in the background. `retry` tries photos that failed before", always, queue),
cmd!(query "denoise.cancel", "Cancel Denoise", [], None, "{id?, all?} → {cancelled} — stop the photo being made and/or forget the ones waiting (all of them when `id` is omitted)", always, cancel),
cmd!(query "denoise.status", "Denoise Status", [], None, "{id?} → {enabled, model, runtime, productsDir, queued, running: {photo, done, total, seconds} | null, ready, made, auto, runOn, device: {kind: gpu | cpu | pending | none, adapter?, reason?, cardMs?, cpuMs?, fellBack?, remote?: {address, state: pending | unavailable | used | idle | slower | given up, device?, remoteMs?, localMs?, reason?, failures?, lastError?}}, cache: {files, bytes, limitBytes}, generation, photo?: {state: notApplicable | noModel | ready | queued | running | failed | idle, …}}", always, status),
cmd!(query "denoise.status", "Denoise Status", [], None, "{id?} → {enabled, model, runtime, productsDir, queued, running: {photo, done, total, seconds} | null, ready, made, auto, runOn, device: {kind: gpu | cpu | pending | none, adapter?, reason?, cardMs?, cpuMs?, fellBack?, remote?: {address, state: pending | unavailable | used | idle | slower | given up, device?, remoteMs?, localMs?, reason?, failures?, lastError?}}, cache: {files, bytes, limitBytes}, generation, photo?: {state: notApplicable | ready | queued | running | failed | idle, …}}", always, status),
cmd!(query "denoise.pump", "Denoise Pump", [], None, "{pace?: pause | light | normal | full} → {active, running, queued, ready, generation, downloading} — called every frame by the app: takes in finished work and keeps one photo going", always, pump),
cmd!(query "denoise.clear", "Clear Denoise Cache", [], None, "{} → {deleted, bytes} — delete every cached denoised picture of this library (they are made again when wanted)", always, clear),
]
+183 -20
View File
@@ -33,6 +33,58 @@ fn groups_param(p: &Value, c: &str) -> Result<Option<Vec<SettingsGroup>>> {
}
}
/// The leaves of `a` that differ from `b` (same shape), as a partial JSON object: `None` when they
/// are equal. Used to store only what a batch-edit recipe names, so applying the saved preset
/// later never overrides the settings the recipe doesn't name.
fn partial_diff(a: &Value, b: &Value) -> Option<Value> {
match (a, b) {
(Value::Object(x), Value::Object(y)) => {
let mut out = serde_json::Map::new();
for (k, v) in x {
if let Some(d) = partial_diff(v, y.get(k).unwrap_or(&Value::Null)) {
out.insert(k.clone(), d);
}
}
(!out.is_empty()).then_some(Value::Object(out))
}
(x, y) => (x != y).then(|| x.clone()),
}
}
/// The settings as JSON with the HDR subtree always present: [`Hdr`] is left out while it is the default
/// (its JSON stays as it was), so a reset to a default HDR value would have nothing to compare with and
/// would be dropped from a saved preset.
fn full_json(s: &DevelopSettings) -> Value {
let mut v = s.to_json();
if let Some(obj) = v.as_object_mut() {
obj.entry("hdr").or_insert_with(|| serde_json::to_value(s.hdr).unwrap_or(Value::Null));
}
v
}
/// The partial settings a batch-edit recipe names, with the values the import would give (clamped
/// by the control specs). Each named control is compared with the same control at a value it is not
/// set to, so a control the recipe sets to its default (a reset) is stored too, and nothing else is.
/// `None` when the recipe names nothing that is stored, or a control that cannot be written.
fn recipe_partial(recipe: &[(String, f64)]) -> Option<Value> {
let (mut named, mut other) = (DevelopSettings::default(), DevelopSettings::default());
for (id, v) in recipe {
if !controls::set(&mut named, id, *v) {
return None;
}
}
for (id, _) in recipe {
let (spec, now) = (controls::find(id)?, controls::get(&named, id)?);
if !controls::set(&mut other, id, if now > spec.min { spec.min } else { spec.max }) {
return None;
}
}
partial_diff(&full_json(&named), &full_json(&other))
}
/// The longest name or group a saved recipe preset may have (characters).
const MAX_PRESET_TEXT: usize = 100;
fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) {
let p = s.catalog.photo(id);
let (w, h) = p.map(|p| (p.width.max(1) as f64, p.height.max(1) as f64)).unwrap_or((3.0, 2.0));
@@ -460,24 +512,51 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(json!({"mix": m}))
}
),
cmd!("develop.auto", "Auto Settings", ["Photo"], Some("Shift+A"), "{}", has_active, |s, _| {
let id = active(s, "develop.auto")?;
let src = s.source_now(id, SourceLevel::Thumb).map_err(|e| bad("develop.auto", e))?;
let info = s.source_info(id);
let d = s.develop_of(id).unwrap_or_default();
let a = lightcraft_pipeline::auto::auto_tone(&src, &info, &d);
edit(s, "develop.auto", "Auto", |d| {
d.light.exposure = a.exposure;
d.light.contrast = a.contrast;
d.light.highlights = a.highlights;
d.light.shadows = a.shadows;
d.light.whites = a.whites;
d.light.blacks = a.blacks;
d.color.vibrance = a.vibrance;
d.color.saturation = a.saturation;
Ok(())
})?;
Ok(serde_json::to_value(a).unwrap_or_default())
cmd!("develop.auto", "Auto Settings", ["Photo"], Some("Shift+A"), "{}", has_selection, |s, p| {
const C: &str = "develop.auto";
let ids = s.targets(p)?;
// a wrong id is a bad request, unlike a photo that can't be read just now
if let Some(id) = ids.iter().find(|id| s.catalog.photo(**id).is_none()) {
return Err(bad(C, format!("no such photo: {}", id.0)));
}
let mut first: Option<Value> = None;
let mut ops: Vec<Op> = Vec::new();
let mut failed = None;
for id in ids {
// a photo that can't be read (offline, no decoder) is left out, not the whole selection
let src = match s.source_now(id, SourceLevel::Thumb) {
Ok(src) => src,
Err(e) => {
failed.get_or_insert(e);
continue;
}
};
let info = s.source_info(id);
let d = s.develop_of(id).unwrap_or_default();
let a = lightcraft_pipeline::auto::auto_tone(&src, &info, &d);
if first.is_none() {
first = Some(serde_json::to_value(a).unwrap_or_default());
}
let mut nd = (*d).clone();
nd.light.exposure = a.exposure;
nd.light.contrast = a.contrast;
nd.light.highlights = a.highlights;
nd.light.shadows = a.shadows;
nd.light.whites = a.whites;
nd.light.blacks = a.blacks;
nd.color.vibrance = a.vibrance;
nd.color.saturation = a.saturation;
if let Some(op) = s.develop_op(id, nd, "Auto") {
ops.push(op);
}
}
if let (None, Some(e)) = (&first, failed) {
return Err(bad(C, e));
}
if !ops.is_empty() {
s.commit("Auto", Op::Batch { ops })?;
}
Ok(first.unwrap_or_default())
}),
cmd!(
"develop.wb",
@@ -1108,7 +1187,13 @@ pub fn specs() -> Vec<CommandSpec> {
let prepared = prepare_photo_for_wb_partial(&d, &preset.settings, &info);
let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb;
let base: &DevelopSettings = prepared.as_ref().unwrap_or(&d);
let mut next = preset.apply(base, amount);
// Amount is measured from the import look only when the photo has one.
// Otherwise the current settings (on the partial's WB scale) are its baseline.
let imported = s.catalog.photo(id).filter(|p| p.import_look.is_some() && amount != 1.0).map(|p| p.import_defaults());
let prepared_import =
imported.as_ref().map(|d| prepare_photo_for_wb_partial(d, &preset.settings, &info).unwrap_or_else(|| d.clone()));
let original = prepared_import.as_ref().unwrap_or(base);
let mut next = preset.apply_on(base, original, amount);
if on_kelvin_scale {
lightcraft_pipeline::local::normalize_wb(&mut next, &info);
}
@@ -1129,6 +1214,41 @@ pub fn specs() -> Vec<CommandSpec> {
s.presets.push(Preset::from_settings(&pid, name, group, &d, &groups));
Ok(json!({"id": pid}))
}),
cmd!(
"preset.saveRecipe",
"Save Import Recipe as Preset",
[],
None,
"{name (up to 100 characters), group?: default Import Recipes, recipe: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}]} → {id, name} — save a batch-edit recipe (as library.import takes it) as a user preset, so it can be reused from the Preset list; only the settings the recipe names are stored, so applying it later never overrides the rest. The preset gets an id no other preset has; saving the same recipe under the same name and group again returns the preset that already is",
always,
|s, p| {
const C: &str = "preset.saveRecipe";
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(C, "missing name"))?.to_string();
let group = str_param(p, "group").map(str::trim).filter(|g| !g.is_empty()).unwrap_or("Import Recipes").to_string();
if name.chars().count() > MAX_PRESET_TEXT || group.chars().count() > MAX_PRESET_TEXT {
return Err(bad(C, format!("a name or group is at most {MAX_PRESET_TEXT} characters")));
}
let recipe = super::recipe_param(p, C)?;
if recipe.is_empty() {
return Err(bad(C, "the recipe is empty"));
}
let settings = recipe_partial(&recipe).ok_or_else(|| bad(C, "the recipe sets nothing a preset can store"))?;
// presets get their ids as imported ones do (`user.<group>-<name>`, then -2, -3…): an id from the list's
// length repeats once a preset is deleted, and the first preset with an id is the one that gets applied
let preset = Preset { id: String::new(), name, group, settings, favorite: false, builtin: false };
let id = match s.add_presets(vec![preset.clone()]).into_iter().next() {
Some(id) => id,
// the same recipe under the same name and group is already a preset
None => s
.presets
.iter()
.find(|q| !q.builtin && q.name == preset.name && q.group == preset.group && q.settings == preset.settings)
.map(|q| q.id.clone())
.ok_or_else(|| bad(C, "the preset could not be saved"))?,
};
Ok(json!({"id": id, "name": preset.name}))
}
),
cmd!("preset.delete", "Delete Preset", [], None, "{id}", always, |s, p| {
let pid = str_param(p, "id").ok_or_else(|| bad("preset.delete", "missing id"))?;
let i = s.presets.iter().position(|x| x.id == pid).ok_or_else(|| bad("preset.delete", "unknown preset"))?;
@@ -1166,7 +1286,7 @@ pub fn specs() -> Vec<CommandSpec> {
|s, p| {
let c = "preset.update";
let id = active(s, c)?;
let current = s.develop_of(id).unwrap_or_default().to_json();
let current = s.develop_of(id).unwrap_or_default().to_json_for_merge();
let groups = groups_param(p, c)?;
let pr = user_preset(s, p, c)?;
pr.settings = match groups {
@@ -1303,3 +1423,46 @@ fn has_history_after(s: &Session) -> std::result::Result<(), String> {
Err("at the latest History step".into())
}
}
#[cfg(test)]
mod recipe_tests {
use super::*;
/// Equal settings differ nowhere, so there is nothing to store; a difference comes back with
/// its path only.
#[test]
fn partial_diff_is_the_changed_leaves_only() {
let a = json!({"light": {"exposure": 1.0, "contrast": 0.0}, "color": {"vibrance": 5.0}});
assert_eq!(partial_diff(&a, &a), None);
let b = json!({"light": {"exposure": 0.0, "contrast": 0.0}, "color": {"vibrance": 5.0}});
assert_eq!(partial_diff(&a, &b), Some(json!({"light": {"exposure": 1.0}})));
assert_eq!(partial_diff(&a, &json!({})), Some(a.clone()), "a leaf the other side lacks is a difference");
}
fn recipe(items: &[(&str, f64)]) -> Vec<(String, f64)> {
items.iter().map(|(id, v)| (id.to_string(), *v)).collect()
}
/// A recipe that names nothing, or a control `set` would drop (a per-photo instance on fresh
/// settings), stores nothing: the command answers with an error, not an empty preset.
#[test]
fn a_recipe_that_stores_nothing_is_none() {
assert_eq!(recipe_partial(&[]), None);
assert_eq!(recipe_partial(&recipe(&[("pointColor.0.hueShift", 5.0)])), None, "set returns false for it");
assert_eq!(recipe_partial(&recipe(&[("nope.nope", 5.0)])), None);
assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.5)])), Some(json!({"light": {"exposure": 0.5}})));
// a reset to the control's default is stored
assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.0)])), Some(json!({"light": {"exposure": 0.0}})));
}
/// The HDR subtree is left out of the JSON while it is the default, so a reset of a headroom to its
/// default is stored in the preset by itself and next to another adjustment.
#[test]
fn an_hdr_reset_is_stored_alone_and_next_to_another_adjustment() {
let reset = recipe_partial(&recipe(&[("hdr.maxEv", 3.0)])).expect("a reset is stored");
assert_eq!(reset.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{reset}");
let both = recipe_partial(&recipe(&[("hdr.maxEv", 3.0), ("light.exposure", 0.5)])).expect("both are stored");
assert_eq!(both.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{both}");
assert_eq!(both.pointer("/light/exposure"), Some(&json!(0.5)), "{both}");
}
}
+25
View File
@@ -14,6 +14,31 @@ impl Session {
builtin_presets().into_iter().map(|p| (p, true)).chain(self.export_presets.iter().cloned().map(|p| (p, false))).collect()
}
/// The user's export presets, renamed where they shadow a built-in: the built-ins are looked up
/// first, so a preset whose name matches one of them (in any case) could never be selected or
/// exported, and the save path refuses a built-in's name. Such a preset gets a free name of its
/// own (`<name> (mine)`, then a number when that is taken too), keeping its settings.
pub(crate) fn rename_shadowing_export_presets(&mut self) {
let builtins: Vec<String> = builtin_presets().into_iter().map(|p| p.name).collect();
// the names that may not be taken: the built-ins', and every user preset's own
let mut taken: Vec<String> = builtins.clone();
taken.extend(self.export_presets.iter().map(|p| p.name.clone()));
for preset in self.export_presets.iter_mut() {
if !builtins.iter().any(|b| b.eq_ignore_ascii_case(&preset.name)) {
continue;
}
let base = format!("{} (mine)", preset.name);
let mut name = base.clone();
let mut n = 2;
while taken.iter().any(|t| t.eq_ignore_ascii_case(&name)) {
name = format!("{base} {n}");
n += 1;
}
taken.push(name.clone());
preset.name = name;
}
}
/// `app.export` params with a named `preset` expanded: the preset's params, overridden by the
/// call's own (`preset` itself removed). Unknown preset names are an error.
pub fn export_params(&self, p: &Value) -> std::result::Result<Value, String> {
+1
View File
@@ -82,6 +82,7 @@ pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
metadata_preset,
convert_dng: bool_or(p, "dng", false),
local: bool_or(p, "local", false),
recipe: crate::cmd::recipe_param(p, "library.import")?,
};
let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
Ok(ImportRequest { paths, opts, album, album_name })
+15 -5
View File
@@ -1325,16 +1325,22 @@ pub fn specs() -> Vec<CommandSpec> {
"Review Import",
[],
None,
"{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned} — nothing is added",
"{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned, scanLimited: bool (the folder walk stopped at its scan limit: there may be more photos), skipped: {unreadable (folders that could not be listed), unsupported (files in the folders that are not a supported photo type, XMP sidecars not counted; a file named in paths is always tried)}} — nothing is added",
always,
|s, p| {
let paths = strs(p, "paths");
if paths.is_empty() {
return Err(bad("library.importPreview", "no paths"));
}
let c = crate::import::scan(s, &paths);
let dups = c.iter().filter(|c| c.duplicate.is_some()).count();
Ok(json!({"scanned": c.len(), "duplicates": dups, "candidates": c}))
let out = crate::import::scan_report(s, &paths);
let dups = out.candidates.iter().filter(|c| c.duplicate.is_some()).count();
Ok(json!({
"scanned": out.candidates.len(),
"duplicates": dups,
"candidates": out.candidates,
"scanLimited": out.truncated,
"skipped": {"unreadable": out.unreadable, "unsupported": out.unsupported},
}))
}
),
cmd!(
@@ -1342,7 +1348,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Photos",
["File"],
Some("Cmd+Shift+I"),
"{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}",
"{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}",
always,
|s, p| {
let req = import_params(s, p)?;
@@ -1367,6 +1373,8 @@ pub fn specs() -> Vec<CommandSpec> {
),
// ---- persistence
cmd!(query "library.info", "Library Info", [], None, "{}", always, |s, _| {
// the answer of a free-space read that ran on a worker (lowDiskSpace below)
s.poll_disk_space();
let photos = s.catalog.len();
let albums = s.catalog.albums().count();
let (rendered_n, rendered_bytes) = s.media.rendered.mem_usage();
@@ -1402,6 +1410,8 @@ pub fn specs() -> Vec<CommandSpec> {
"lastError": lib.last_error,
// settings files that were unreadable or damaged at open (kept, defaults used)
"settingsWarnings": lib.settings_warnings,
// the drive holding the preview cache ran low this session (warned once)
"lowDiskSpace": s.disk_space_alert_raised(),
// changes applied in memory whose write failed (retried by every save)
"unsavedOps": s.unsaved().map_or(0, |u| u.0),
"unsavedError": s.unsaved().map(|u| u.1),
+363 -50
View File
@@ -31,6 +31,20 @@ pub struct PreviewBuild {
pub what: &'static str,
/// Why the whole build failed (e.g. the smart previews folder isn't there).
pub error: std::sync::Mutex<Option<String>>,
/// Photos whose previews were there already (from an earlier build, the loupe or the photos
/// prepared ahead): counted as done, not rendered again (PERF-PREVIEW-REUSE).
pub skipped: AtomicUsize,
/// Photos left alone because another job was building them at that moment.
pub shared: AtomicUsize,
/// Started by the background preparation ([`crate::prep`]): it yields to the photo on screen,
/// and a build the user (or an import) asks for replaces it.
pub background: bool,
/// The photos in build order (ids), and where the user is among them: the next photo built
/// is the nearest one not built yet from there, in the direction of travel
/// ([`PreviewBuild::focus_on`]).
pub order: Vec<u64>,
pub focus: AtomicUsize,
pub backward: AtomicBool,
/// Test-only: the gate this build's lanes wait at before a photo's first render (see
/// [`test_gate`]). Captured by `build` on the calling thread; production builds never have one.
#[cfg(test)]
@@ -47,10 +61,38 @@ impl PreviewBuild {
"cancelled": self.cancel.load(Ordering::Relaxed),
"what": if self.what.is_empty() { "previews" } else { self.what },
"repaired": self.repaired.load(Ordering::Relaxed),
"skipped": self.skipped.load(Ordering::Relaxed),
"shared": self.shared.load(Ordering::Relaxed),
"background": self.background,
"error": self.error(),
})
}
pub fn running(&self) -> bool {
!self.finished.load(Ordering::Relaxed)
}
/// The user is at photo `id`, moving `backward` or forward: build from there on.
pub fn focus_on(&self, id: lightcraft_catalog::PhotoId, backward: bool) {
if let Some(i) = self.order.iter().position(|p| *p == id.0) {
self.focus.store(i, Ordering::Relaxed);
self.backward.store(backward, Ordering::Relaxed);
}
}
/// Index of the next photo to build in `queue` (`None`: none left): the first one still there
/// from the focus on in the direction of travel, then the rest the other way.
pub(crate) fn next_index<T>(&self, queue: &[Option<T>]) -> Option<usize> {
let n = queue.len();
let at = self.focus.load(Ordering::Relaxed).min(n.saturating_sub(1));
let there = |i: &usize| queue.get(*i).is_some_and(Option::is_some);
if self.backward.load(Ordering::Relaxed) {
(0..=at).rev().find(there).or_else(|| (at..n).find(there))
} else {
(at..n).find(there).or_else(|| (0..at).rev().find(there))
}
}
pub fn error(&self) -> Option<String> {
self.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
}
@@ -69,9 +111,93 @@ pub(crate) fn jobs_for(s: &mut Session, id: lightcraft_catalog::PhotoId, edge: O
if e >= thumb { view.into_iter().chain(grid).collect() } else { grid.into_iter().chain(view).collect() }
}
/// The previews the build of one photo would make are all there already, big enough: its view
/// render at least as large as asked for (`view_cache` of the view job) and its grid thumbnail
/// (`cache` of the thumbnail job), on disk when the cache has one: a render the loupe kept only in
/// memory (its deferred disk write skipped) is built again, and written. Only file headers are read.
pub(crate) fn already_built(jobs: &[RenderJob]) -> bool {
!jobs.is_empty()
&& jobs.iter().all(|j| {
if let Some((cache, key)) = &j.view_cache {
let want = j.request.max_w.max(j.request.max_h) as f64;
cache.stored_dims(*key).is_some_and(|(w, h)| w.max(h) as f64 >= want * 0.99)
} else if let Some((cache, key)) = &j.cache {
cache.stored_dims(*key).is_some()
} else {
false
}
})
}
/// Photos some preview build is rendering right now, by (the cache they go to, photo id): two
/// builds (a background one being replaced, and the one replacing it) never render the same photo
/// at once.
static BUILDING: std::sync::Mutex<Vec<(usize, u64)>> = std::sync::Mutex::new(Vec::new());
/// Holds a photo in [`BUILDING`] while it is rendered.
struct Building((usize, u64));
impl Building {
/// `id` of `jobs` (the cache their results go to tells sessions apart).
fn take(id: u64, jobs: &[RenderJob]) -> Option<Building> {
let cache = jobs.iter().find_map(|j| j.view_cache.as_ref().or(j.cache.as_ref())).map_or(0, |(c, _)| Arc::as_ptr(c) as usize);
let id = (cache, id);
let mut b = BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if b.contains(&id) {
return None;
}
b.push(id);
Some(Building(id))
}
/// [`Self::take`], waiting while another build renders the photo (a build asked for replacing the
/// background one may meet it on the same photo): the photo is not counted until that render is over, as
/// built when it made the previews, else rendered here. With whether it had to wait; `None` when `cancel`
/// was asked for meanwhile. (On the web, with one thread, a photo held is not waited for: `Some((None, true))`.)
fn wait(id: u64, jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option<Building>, bool)> {
if let Some(b) = Self::take(id, jobs) {
return Some((Some(b), false));
}
Self::wait_held(id, jobs, cancel)
}
/// [`Self::wait`] for a photo another build holds.
#[cfg(not(target_arch = "wasm32"))]
fn wait_held(id: u64, jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option<Building>, bool)> {
loop {
if cancel.load(Ordering::Relaxed) {
return None;
}
std::thread::sleep(std::time::Duration::from_millis(10));
if let Some(b) = Self::take(id, jobs) {
return Some((Some(b), true));
}
}
}
/// [`Self::wait`] for a photo another build holds: on the web, with one thread, it is not waited for.
#[cfg(target_arch = "wasm32")]
fn wait_held(_id: u64, _jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option<Building>, bool)> {
(!cancel.load(Ordering::Relaxed)).then_some((None, true))
}
}
/// Tests: hold `id` of `jobs` as a build rendering it would, until the returned value is dropped.
#[cfg(test)]
pub(crate) fn hold_building(id: u64, jobs: &[RenderJob]) -> Option<Box<dyn std::any::Any>> {
Building::take(id, jobs).map(|b| Box::new(b) as Box<dyn std::any::Any>)
}
impl Drop for Building {
fn drop(&mut self) {
BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).retain(|x| *x != self.0);
}
}
/// The build's row in the activity stack (`what` as in [`PreviewBuild::what`]).
fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard {
let (kind, label) = match state.what {
"" if state.background => ("previews", "Preparing photos in the background"),
"" => ("previews", "Building previews"),
"smart previews" => ("smartPreviews", "Building smart previews"),
_ => ("smartPreviews", "Discarding smart previews"),
@@ -84,7 +210,8 @@ fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard {
/// Render one photo's jobs in order. The source the first job decodes serves the ones after it
/// (the grid thumbnail is made from the view's source instead of decoding the file again).
/// `None` when `cancel` was asked for before a job started: that photo is not counted as done.
fn run_photo_cancellable(jobs: Vec<RenderJob>, cancel: Option<&AtomicBool>) -> Option<bool> {
/// `force`: the grid thumbnail is rendered too, not taken from the cache it is written to.
fn run_photo_cancellable(jobs: Vec<RenderJob>, cancel: Option<&AtomicBool>, force: bool) -> Option<bool> {
let mut decoded: Option<crate::media::DecodedSource> = None;
let mut ok = true;
for mut j in jobs {
@@ -97,7 +224,33 @@ fn run_photo_cancellable(jobs: Vec<RenderJob>, cancel: Option<&AtomicBool>) -> O
{
j.source = crate::media::SourceRef::Loaded(Box::new(src.clone()));
}
// The view render is written to the disk cache here, before the photo counts as built,
// not left to the cache's writer (which skips writes when it falls behind): a built
// preview is on disk, for this session and the next. (Taken out of the job: it would only
// queue the write, and would serve a smaller cached view.)
// A preview that isn't kept fails the photo: it is not built (a full or unwritable cache folder, or the
// cache discarded while the photo rendered).
let keep = j.view_cache.take().map(|v| (v, j.cache_generation));
// forced: the thumbnail job's cache is only written to, after the render (a job reads its cache first;
// CodeRabbit on #3577)
let rewrite = if force { j.cache.take().map(|c| (c, j.cache_generation)) } else { None };
let r = j.run();
if let (Some(((cache, key), generation)), Ok(img)) = (rewrite, r.rendered.as_ref())
&& !cache.put_at(generation, key, Arc::new(img.image.clone()))
{
log::warn!("building previews: the grid thumbnail could not be kept");
ok = false;
}
if let (Some(((cache, key), generation)), Ok(img)) = (keep, r.rendered.as_ref())
&& !cache.put_at(generation, key, Arc::new(img.image.clone()))
{
if cache.generation() == generation {
log::warn!("building previews: the view preview could not be written to the cache folder");
} else {
log::warn!("building previews: the preview cache was discarded while the photo rendered");
}
ok = false;
}
ok &= r.rendered.is_ok();
if decoded.is_none() {
decoded = r.loaded;
@@ -109,7 +262,7 @@ fn run_photo_cancellable(jobs: Vec<RenderJob>, cancel: Option<&AtomicBool>) -> O
/// [`run_photo_cancellable`] for callers that render a photo without a cancel flag.
#[cfg(test)]
pub(crate) fn run_photo(jobs: Vec<RenderJob>) -> bool {
run_photo_cancellable(jobs, None) == Some(true)
run_photo_cancellable(jobs, None, false) == Some(true)
}
/// How many photos render side by side: as many as an export batch for standard previews (each
@@ -224,34 +377,83 @@ pub(crate) mod test_gate {
pub(crate) fn take() -> Option<Arc<PreviewGate>> {
NEXT_GATE.with(|g| g.borrow_mut().take())
}
thread_local! {
/// The next build started on this thread fails to start its worker (a thread the system
/// won't give), taken by `build`.
static FAIL_SPAWN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Have the next build started on this thread fail to start its worker.
pub(crate) fn fail_next_spawn() {
FAIL_SPAWN.with(|f| f.set(true));
}
/// Whether this build's worker is to fail to start (once).
pub(crate) fn take_fail_spawn() -> bool {
FAIL_SPAWN.with(std::cell::Cell::take)
}
}
fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: &TaskGuard, lanes: usize) {
/// One photo's work in a build: its id and its render jobs ([`jobs_for`]).
type PhotoJobs = (u64, Vec<RenderJob>);
/// Build every photo of `jobs` on `lanes` threads. `force`: render even the photos whose previews
/// are there. `task`: the build's own row (`None`: another job's row shows it, e.g. the import's
/// Getting photos ready).
fn run_all(jobs: Vec<PhotoJobs>, state: &PreviewBuild, task: Option<&TaskGuard>, lanes: usize, force: bool) {
let total = jobs.len();
let queue = std::sync::Mutex::new(jobs.into_iter());
let queue = std::sync::Mutex::new(jobs.into_iter().map(Some).collect::<Vec<_>>());
let work = || {
loop {
if state.cancel.load(Ordering::Relaxed) {
break;
}
let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next();
let Some(photo_jobs) = next else { break };
// the background preparation waits while the photo on screen is being made
if state.background && crate::prep::wait_for_foreground(&state.cancel) {
break;
}
let next = {
let mut q = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
state.next_index(&q).and_then(|i| q.get_mut(i)).and_then(Option::take)
};
let Some((id, photo_jobs)) = next else { break };
// A cancel accepted while this lane waited for the queue (or for another lane's
// photo) stops before this photo's first render; a cancelled photo is not counted.
if state.cancel.load(Ordering::Relaxed) {
break;
}
#[cfg(test)]
if let Some(gate) = &state.gate {
gate.enter();
}
let outcome = crate::guard::catch("building previews", || run_photo_cancellable(photo_jobs, Some(&state.cancel))).unwrap_or(Some(false));
let Some(ok) = outcome else { break };
if !ok {
state.failed.fetch_add(1, Ordering::Relaxed);
if !force && already_built(&photo_jobs) {
state.skipped.fetch_add(1, Ordering::Relaxed);
} else if let Some((held, shared)) = Building::wait(id, &photo_jobs, &state.cancel) {
// another build was rendering this photo: what it made counts, if it made it (not
// for a forced build, which renders every photo itself)
if !force && shared && (held.is_none() || already_built(&photo_jobs)) {
state.shared.fetch_add(1, Ordering::Relaxed);
let done = state.done.fetch_add(1, Ordering::Relaxed).saturating_add(1);
if let Some(task) = task {
task.progress(done as u64, total as u64);
}
continue;
}
#[cfg(test)]
if let Some(gate) = &state.gate {
gate.enter();
}
let outcome =
crate::guard::catch("building previews", || run_photo_cancellable(photo_jobs, Some(&state.cancel), force)).unwrap_or(Some(false));
let Some(ok) = outcome else { break };
if !ok {
state.failed.fetch_add(1, Ordering::Relaxed);
}
} else {
// cancelled while another build was rendering it: not counted
break;
}
let done = state.done.fetch_add(1, Ordering::Relaxed).saturating_add(1);
task.progress(done as u64, total as u64);
if let Some(task) = task {
task.progress(done as u64, total as u64);
}
}
};
#[cfg(not(target_arch = "wasm32"))]
@@ -272,43 +474,99 @@ fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: &TaskGuard, la
state.finished.store(true, Ordering::Relaxed);
}
/// The long edge a standard preview is built at: [`STANDARD_EDGE`], or what the loupe asks for
/// on this screen when that is more ([`Session::loupe_edge`]), so the loupe finds what was built.
pub fn standard_edge(s: &Session) -> usize {
STANDARD_EDGE.max(s.loupe_edge.min(8192))
}
fn build(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.buildPreviews";
// tests: this invocation's gate, consumed here so an early error cannot attach it to a later build
#[cfg(test)]
let gate = test_gate::take();
let edge = match str_param(p, "size").unwrap_or("standard") {
"standard" => Some(p.get("edge").and_then(Value::as_u64).map_or(STANDARD_EDGE, |e| e.clamp(256, 8192) as usize)),
"standard" => Some(p.get("edge").and_then(Value::as_u64).map_or_else(|| standard_edge(s), |e| e.clamp(256, 8192) as usize)),
"full" | "1:1" => None,
other => return Err(bad(C, format!("unknown size `{other}` (standard|full)"))),
};
if s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) {
return Err(bad(C, "a preview build is already running"));
let background = p.get("background").and_then(Value::as_bool).unwrap_or(false);
let force = p.get("force").and_then(Value::as_bool).unwrap_or(false);
// (`row: false`: the job that asked shows the progress in its own row)
let row = p.get("row").and_then(Value::as_bool).unwrap_or(true);
// the background preparation gives way to a build that was asked for; nothing replaces a build
// that was asked for (it carries on, and the photos it built are skipped by the next). The
// background one is stopped only once this request is known to be good (below): a request
// with bad ids leaves it running (CodeRabbit on #3544)
let mut gives_way = None;
if let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) {
if b.background && !background {
gives_way = Some(b.cancel.clone());
} else {
return Err(bad(C, "a preview build is already running"));
}
}
// explicit ids, else the selection, else everything in view
let ids = if p.get("ids").is_some() || p.get("id").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() };
let jobs: Vec<Vec<RenderJob>> = ids.iter().map(|id| jobs_for(s, *id, edge)).filter(|j| !j.is_empty()).collect();
s.fit_disk_cache();
// explicit ids, else the selected photos (more than one: as the menu says), else everything in
// view (a single photo selected is the one open, not a choice of photos: "Visible" in the menu)
let ids = if p.get("ids").is_some() || p.get("id").is_some() || (!background && s.selection.ids.len() > 1) {
s.targets(p)?
} else {
s.visible_cloned()
};
let jobs: Vec<PhotoJobs> = ids.iter().map(|id| (id.0, jobs_for(s, *id, edge))).filter(|j| !j.1.is_empty()).collect();
// the background build stays the session's until this one has started (a worker that can't
// start leaves it running and in place: CodeRabbit on #3544)
let previous = s.preview_build.clone();
let order = jobs.iter().map(|j| j.0).collect();
#[cfg_attr(not(test), allow(unused_mut))]
let mut build_state = PreviewBuild { total: jobs.len(), background, order, ..Default::default() };
#[cfg(test)]
let state = Arc::new(PreviewBuild { total: jobs.len(), gate, ..Default::default() });
#[cfg(not(test))]
let state = Arc::new(PreviewBuild { total: jobs.len(), ..Default::default() });
{
build_state.gate = gate;
}
let state = Arc::new(build_state);
if let Some(at) = p.get("from").and_then(Value::as_u64) {
state.focus_on(lightcraft_catalog::PhotoId(at), p.get("backward").and_then(Value::as_bool).unwrap_or(false));
}
s.preview_build = Some(state.clone());
let task = task_for(s, &state);
let lanes = lanes(jobs.len(), edge.is_none());
let task = row.then(|| task_for(s, &state));
// the background preparation leaves most of the machine to the photo on screen and the user
let lanes = if background { crate::prep::background_lanes() } else { lanes(jobs.len(), edge.is_none()) };
let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32");
if wait {
run_all(jobs, &state, &task, lanes);
if let Some(cancel) = gives_way {
cancel.store(true, Ordering::Relaxed);
}
run_all(jobs, &state, task.as_ref(), lanes, force);
return Ok(state.json());
}
#[cfg(not(target_arch = "wasm32"))]
{
// the row stays while the worker runs (it is dropped with the closure, however that ends)
let st = state.clone();
std::thread::Builder::new()
.name("lc-build-previews".into())
.spawn(move || run_all(jobs, &st, &task, lanes))
.map_err(|e| bad(C, format!("could not start: {e}")))?;
#[cfg(test)]
let started = if test_gate::take_fail_spawn() {
drop(task);
Err(std::io::Error::other("no thread (test)"))
} else {
std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force))
};
#[cfg(not(test))]
let started = std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force));
if let Err(e) = started {
// never started: not left "running", which would hold every later build back, and the
// build it was to replace carries on
state.finished.store(true, Ordering::Relaxed);
s.preview_build = previous;
return Err(bad(C, format!("could not start: {e}")));
}
if let Some(cancel) = gives_way {
cancel.store(true, Ordering::Relaxed);
}
}
#[cfg(target_arch = "wasm32")]
let _ = previous;
Ok(state.json())
}
@@ -361,8 +619,8 @@ fn original_only(source: crate::media::SourceRef) -> Option<crate::media::Source
use crate::media::SourceRef;
match source {
// (a smart preview keeps the file's own colour: an imported camera profile is applied when the original is read)
SourceRef::File { path, max_edge, loader, denoise, .. } => {
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, reduced: None })
SourceRef::File { path, max_edge, loader, denoise, outliers, .. } => {
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, outliers, reduced: None })
}
SourceRef::Loaded(d) if d.info.is_some() && !d.from_proxy && !d.reduced => Some(SourceRef::Loaded(d)),
_ => None,
@@ -476,10 +734,18 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
let dir = s.media.smart_dir.clone().ok_or_else(|| bad(C, "smart previews need a library on disk"))?;
let discard = p.get("discard").and_then(Value::as_bool).unwrap_or(false);
let background = p.get("background").and_then(Value::as_bool).unwrap_or(false);
if background && s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) {
return Err(bad(C, "a preview build is already running"));
// (as Build Previews: the photos named, or the selected ones when more than one is, else
// everything in view; read first, so a request with bad ids stops nothing: CodeRabbit on #3577)
let ids = if p.get("ids").is_some() || p.get("id").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() };
// (the background preparation gives way, as to Build Previews: once this one's worker has started)
let mut gives_way = None;
if background && let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) {
if b.background {
gives_way = Some(b.cancel.clone());
} else {
return Err(bad(C, "a preview build is already running"));
}
}
let ids = if p.get("ids").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() };
let mut jobs: Vec<SmartJob> = Vec::new();
for id in ids {
let Some(ph) = s.catalog.photo(id).cloned() else { continue };
@@ -496,19 +762,35 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
if background {
let what = if discard { "discarding smart previews" } else { "smart previews" };
let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() });
s.preview_build = Some(state.clone());
let previous = s.preview_build.replace(state.clone());
let task = task_for(s, &state);
let st = state.clone();
std::thread::Builder::new()
.name("lc-smart-previews".into())
.spawn(move || {
if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) {
log::warn!("{C}: {e}");
*st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e);
}
st.finished.store(true, Ordering::Relaxed);
})
.map_err(|e| bad(C, format!("could not start: {e}")))?;
let work = move || {
if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) {
log::warn!("{C}: {e}");
*st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e);
}
st.finished.store(true, Ordering::Relaxed);
};
#[cfg(test)]
let started = if test_gate::take_fail_spawn() {
drop(work);
Err(std::io::Error::other("no thread (test)"))
} else {
std::thread::Builder::new().name("lc-smart-previews".into()).spawn(work)
};
#[cfg(not(test))]
let started = std::thread::Builder::new().name("lc-smart-previews".into()).spawn(work);
if let Err(e) = started {
// never started: not left "running", and the background build it was to replace carries on
// (CodeRabbit on #3077)
state.finished.store(true, Ordering::Relaxed);
s.preview_build = previous;
return Err(bad(C, format!("could not start: {e}")));
}
if let Some(cancel) = gives_way {
cancel.store(true, Ordering::Relaxed);
}
return Ok(state.json());
}
let r = smart_run(&dir, custom, discard, jobs, None).map_err(|e| bad(C, e))?;
@@ -647,7 +929,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Build Smart Previews",
[],
None,
"{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)",
"{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)",
always,
smart
),
@@ -674,13 +956,43 @@ pub fn specs() -> Vec<CommandSpec> {
"Build Previews",
[],
None,
"{size?: standard (2048 px, or `edge`) | full (1:1), ids?, wait?: bool} — render the grid thumbnail and loupe view of the selected photos (else all in view) into the preview cache, in the background unless `wait` → {total, done, failed, running}",
"{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}",
always,
build
),
cmd!(query "library.previewProgress", "Preview Build Progress", [], None, "{} → {total, done, failed, repaired, running, cancelled, what, error} | null", always, |s, _| {
cmd!(query "library.previewProgress", "Preview Build Progress", [], None, "{} → {total, done, failed, repaired, skipped, shared, background, running, cancelled, what, error} | null", always, |s, _| {
Ok(s.preview_build.as_ref().map_or(Value::Null, |b| b.json()))
}),
cmd!(query "prefs.backgroundPrep", "Background Preparation Settings", [], None, "{} → {app, library|null, settings (in use), own: bool (this library keeps its own), building} — what is prepared in the background per mode (culling | library: previews of every photo in view, ahead = photos ahead rendered for the loupe, eyeAhead = photos ahead whose eye focus strip is worked out, scope all|marked|onScreen; develop: ahead = photos kept decoded ready to edit, scope)", always, |s, _| {
Ok(s.prep_json())
}),
cmd!(
"prefs.setBackgroundPrep",
"Set Background Preparation",
[],
None,
"{settings?: partial {culling?, library?, develop?}, library?: bool (this library's own settings; else the app-wide ones), reset?: bool (this library goes back to the app-wide settings)} → as prefs.backgroundPrep",
always,
|s, p| {
const C: &str = "prefs.setBackgroundPrep";
let library = p.get("library").and_then(Value::as_bool).unwrap_or(false);
if p.get("reset").and_then(Value::as_bool).unwrap_or(false) {
s.clear_library_prep()?;
return Ok(s.prep_json());
}
if library && s.library.is_none() {
return Err(bad(C, "no library is open"));
}
let base = if library { s.prep.library.unwrap_or(s.prep.app) } else { s.prep.app };
let next = match p.get("settings") {
Some(patch) if patch.is_object() => base.patched(patch).map_err(|e| bad(C, e))?,
Some(_) => return Err(bad(C, "settings must be an object")),
None => base,
};
s.set_prep_settings(next, library)?;
Ok(s.prep_json())
}
),
cmd!("library.cancelPreviews", "Cancel Preview Build", [], None, "{}", always, |s, _| {
if let Some(b) = &s.preview_build {
b.cancel.store(true, Ordering::Relaxed);
@@ -730,6 +1042,7 @@ mod tests {
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source");
+15
View File
@@ -273,6 +273,21 @@ pub fn specs() -> Vec<CommandSpec> {
}
Ok(serde_json::to_value(s.memory_report()).unwrap_or_default())
}),
cmd!(query "app.hotPixelLimit", "Hot Pixel Limit", [], None, "{percent?: number} — Remove Hot Pixels leaves a raw alone when more than this share of its photosites would be replaced (0.001..100 %, default 0.2 %; real light it keeps doesn't count); returns {percent, default}", always, |s, p| {
if let Some(v) = p.get("percent").filter(|v| !v.is_null()) {
let Some(percent) = v.as_f64().filter(|x| (0.001..=100.0).contains(x)) else {
return Err(bad("app.hotPixelLimit", "percent must be a number in 0.001..100"));
};
// (the default as an `f32` from the app's settings, 0.2000000029…, is the default: its keys stay)
let default = lightcraft_raw::HOT_PIXEL_MAX_SHARE;
let share = if (percent / 100.0 / default - 1.0).abs() < 1e-6 { default } else { percent / 100.0 };
if crate::files::set_hot_pixel_limit(share) {
// decoded with the old limit, and their render keys change
s.media.clear_sources();
}
}
Ok(json!({"percent": crate::files::hot_pixel_limit() * 100.0, "default": lightcraft_raw::HOT_PIXEL_MAX_SHARE * 100.0}))
}),
cmd!(query "journal.list", "Command Journal", [], None, "{limit?}", always, |s, p| {
let lim = p.get("limit").and_then(Value::as_u64).unwrap_or(100) as usize;
let start = s.journal.len().saturating_sub(lim);
+5 -1
View File
@@ -36,6 +36,7 @@ use crate::merge::ByteReader;
use crate::model_download::Downloads;
use crate::{Selection, Session};
mod builtin;
mod gpu;
mod model;
mod products;
@@ -63,5 +64,8 @@ pub(crate) use settings::{Settings, forget_gpu_set_ups, installed_models, read_c
pub(crate) use state::State;
pub use state::{Pace, PhotoState};
#[cfg(all(test, feature = "denoise"))]
// Two stacked cfgs (not `all(test, feature = …)`): clippy only recognises a plain `cfg(test)`
// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers.
#[cfg(test)]
#[cfg(feature = "denoise")]
mod gpu_tests;
+325
View File
@@ -0,0 +1,325 @@
use super::gpu::GPU_SETUP_MARKER;
#[cfg(feature = "denoise")]
use super::gpu::{GPU_MAX_FALLBACKS, GPU_PARALLEL, GPU_SETUP_LIMIT, card_is_faster, card_tile_ms, set_up_card};
#[cfg(feature = "denoise")]
use super::model::worth_retrying;
use super::model::{Model, RunOn};
#[cfg(feature = "denoise")]
use super::state::Pace;
#[cfg(feature = "denoise")]
use super::{Arc, AtomicUsize, Mutex, Ordering, PoisonError, RunError};
use super::{OnceLock, Path, PathBuf, TileRunner, Value, json};
/// The built-in denoiser (`lightcraft_denoise::builtin`): nothing to load, so it is what runs until a model is chosen. Its
/// filter runs on the graphics card when there is one that agrees with the CPU on a check tile and is faster, else on
/// the CPU (see [`BuiltinCard`]); the rest of it always runs on the CPU.
pub(super) struct BuiltinModel {
runner: OnceLock<lightcraft_denoise::builtin::Builtin>,
#[cfg(feature = "denoise")]
card: Arc<BuiltinCard>,
/// The runner of a photo that runs on the card.
#[cfg(feature = "denoise")]
hybrid: OnceLock<CardRunner>,
}
impl BuiltinModel {
/// For a photo, with the card's state for the set-up marker `marker` (where its set-up is recorded).
pub(super) fn new(#[cfg_attr(not(feature = "denoise"), allow(unused_variables))] marker: &Path) -> Self {
BuiltinModel {
runner: OnceLock::new(),
#[cfg(feature = "denoise")]
card: builtin_card(marker),
#[cfg(feature = "denoise")]
hybrid: OnceLock::new(),
}
}
}
impl Model for BuiltinModel {
fn runner(&self, run_on: RunOn, threads: usize) -> (&dyn TileRunner, usize) {
let cpu = self.runner.get_or_init(Default::default);
#[cfg(feature = "denoise")]
{
let threads = threads.max(1);
self.card.last_threads.store(threads, Ordering::Relaxed);
if let Ok(side) = self.card.choose(run_on, threads, true)
&& let Ok(gpu) = lightcraft_gpu::bm3d::BuiltinRunner::new(side.gpu.clone(), *cpu)
{
let hybrid = self.hybrid.get_or_init(|| CardRunner { gpu, cpu: *cpu, card: self.card.clone() });
return (hybrid, threads.min(GPU_PARALLEL));
}
}
#[cfg(not(feature = "denoise"))]
let _ = run_on;
(cpu, threads)
}
/// Measure the whole photo's noise once, so every tile is cleaned by the photo's noise instead of its own. A photo
/// that cannot be measured is told nothing: each tile then measures its own.
fn prepare(&self, mosaic: &[f32], width: usize, height: usize) {
if let Some(noise) = lightcraft_denoise::builtin::measure_noise(mosaic, width, height) {
let _ = self.runner.set(lightcraft_denoise::builtin::Builtin::with_noise(noise));
}
}
fn self_test(&self, _run_on: RunOn) -> Result<Value, String> {
let side = 16;
let out = lightcraft_denoise::builtin::Builtin::with_noise((0.01, 0.001)).run(&vec![0.25; 4 * side * side]).map_err(|e| e.to_string())?;
if out.len() != 12 * side * side || out.iter().any(|v| !v.is_finite()) {
return Err("the built-in denoiser gave an unexpected result".into());
}
Ok(json!({"ok": true, "builtin": true}))
}
/// Planes, the two mosaics and the working copies of a 256-cell tile.
fn bytes_per_tile(&self) -> usize {
64 * 1024 * 1024
}
fn device(&self, run_on: RunOn) -> Value {
#[cfg(feature = "denoise")]
{
self.card.device(run_on)
}
#[cfg(not(feature = "denoise"))]
{
let _ = run_on;
json!({"kind": "cpu", "reason": "built-in"})
}
}
}
// ---------------------------------------------------------------------------------------------------------------------
// the built-in denoiser on the graphics card
/// The noise the check tile is made with and the built-in denoiser is told for it (variance = a · signal + b).
#[cfg(feature = "denoise")]
const CHECK_NOISE: (f32, f32) = (0.01, 0.001);
/// How far the card's filter may be from the CPU's on the check tile, in the noise's deviations: at most this at one place
/// (a few blocks whose match or threshold falls either side of a tie in the two devices' roundings change by up to about a
/// tenth; a broken kernel by far more), and this on average.
#[cfg(feature = "denoise")]
const BUILTIN_AGREE_WORST: f32 = 0.3;
#[cfg(feature = "denoise")]
const BUILTIN_AGREE_MEAN: f32 = 1e-3;
/// A mosaic tile (four planes of `side` cells): a ramp, edges and some texture with noise of [`CHECK_NOISE`], the same
/// every time.
#[cfg(feature = "denoise")]
fn builtin_check_tile(side: usize) -> Vec<f32> {
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut uniform = move || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32
};
let mut out = Vec::with_capacity(4 * side * side);
for plane in 0..4 {
for i in 0..side * side {
let (x, y) = (i % side, i / side);
let step = if (x / 37 + y / 29) % 2 == 0 { 0.25 } else { 0.0 };
let signal =
(0.1 + 0.4 * x as f32 / side as f32 + 0.1 * y as f32 / side as f32 + step + 0.05 * ((x as f32 + 4.0 * plane as f32) * 0.7).sin())
.clamp(0.02, 0.95);
let (u, v) = (uniform(), uniform());
let noise = (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos();
out.push((signal + noise * (CHECK_NOISE.0 * signal + CHECK_NOISE.1).sqrt()).max(0.0));
}
}
out
}
/// The card set up for the built-in denoiser: its kernels, and the check tile's time on it and on the CPU.
#[cfg(feature = "denoise")]
struct BuiltinGpu {
gpu: Arc<lightcraft_gpu::bm3d::Bm3dGpu>,
adapter: String,
/// The check tile on the card, the fastest of a few runs (ms).
card_ms: f64,
/// The check tile on the CPU, on one thread (ms).
cpu_ms: f64,
}
/// Set the card up for the built-in denoiser: kernels built, the check tile run on both and compared, both timed.
#[cfg(feature = "denoise")]
fn make_builtin_gpu(marker: &Path) -> Result<BuiltinGpu, String> {
use lightcraft_denoise::builtin::{Builtin, TILE};
let tile = TILE as usize;
let builtin = Builtin::with_noise(CHECK_NOISE);
let params = builtin.bm3d_params().ok_or("the built-in denoiser does not use the block-matching filter")?;
let input = Arc::new(builtin_check_tile(tile));
let on_card = input.clone();
let card = move || -> Result<_, String> {
let gpu = Arc::new(lightcraft_gpu::bm3d::Bm3dGpu::new(&params, tile)?);
let runner = lightcraft_gpu::bm3d::BuiltinRunner::new(gpu.clone(), builtin)?;
let agreement = runner.agreement(&on_card).map_err(|e| format!("the GPU could not run the check tile: {e}"))?;
let whole = runner.run(&on_card).map_err(|e| format!("the GPU could not run the check tile: {e}"))?;
let card_ms = card_tile_ms(&runner, &on_card);
Ok((gpu, agreement, whole, card_ms))
};
let on_cpu = || {
let started = web_time::Instant::now();
(builtin.run(&input), started.elapsed().as_secs_f64() * 1000.0)
};
let ((gpu, agreement, whole, card_ms), (want, cpu_ms)) = set_up_card(marker, GPU_SETUP_LIMIT, card, on_cpu)?;
let want = want.map_err(|e| format!("the CPU could not check the GPU: {e}"))?;
if whole.len() != want.len() || !whole.iter().all(|v| v.is_finite()) {
return Err("its picture of the check tile is not the CPU's size or has numbers that are not finite: not used".into());
}
if !(agreement.worst <= BUILTIN_AGREE_WORST && agreement.mean <= BUILTIN_AGREE_MEAN) {
return Err(format!(
"its filter's answer on the check tile is not the CPU's (off by {:.2} at most and {:.1e} on average, in noise deviations): not used",
agreement.worst, agreement.mean
));
}
let adapter = gpu.adapter();
Ok(BuiltinGpu { gpu, adapter, card_ms, cpu_ms })
}
/// What the built-in denoiser knows about the graphics card in this process: set up for the first photo that may use it,
/// and used while it keeps working. Kept by the marker of its set-up (see [`builtin_card`]) so that every photo shares it.
#[cfg(feature = "denoise")]
pub(super) struct BuiltinCard {
marker: PathBuf,
gpu: OnceLock<Result<BuiltinGpu, String>>,
/// Tiles the card got wrong (an error, numbers that are not finite) and the CPU ran.
fallbacks: AtomicUsize,
/// Tiles at once of the photo started last (0: none yet), to say where the work runs.
last_threads: AtomicUsize,
}
#[cfg(feature = "denoise")]
static BUILTIN_CARDS: Mutex<Vec<(PathBuf, Arc<BuiltinCard>)>> = Mutex::new(Vec::new());
/// The card's state for the set-up marker `marker`, made the first time it is asked for.
#[cfg(feature = "denoise")]
pub(super) fn builtin_card(marker: &Path) -> Arc<BuiltinCard> {
let mut all = BUILTIN_CARDS.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((_, c)) = all.iter().find(|(m, _)| m == marker) {
return c.clone();
}
let c = Arc::new(BuiltinCard {
marker: marker.to_path_buf(),
gpu: OnceLock::new(),
fallbacks: AtomicUsize::new(0),
last_threads: AtomicUsize::new(0),
});
all.push((marker.to_path_buf(), c.clone()));
c
}
/// Forget the card's state for the marker (and the marker): the card is tried afresh for the next photo.
#[cfg(feature = "denoise")]
pub(super) fn forget_builtin_card(marker: &Path) {
BUILTIN_CARDS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(m, _)| m != marker);
let _ = std::fs::remove_file(marker);
}
/// Where the card's set-up is recorded for the built-in denoiser whose `onnx` is its model's (made-up) path in the models
/// folder: beside it, and in the temporary folder when there is no models folder.
pub(super) fn builtin_marker(onnx: &Path) -> PathBuf {
match onnx.parent() {
Some(p) if !p.as_os_str().is_empty() => onnx.with_file_name(GPU_SETUP_MARKER),
_ => std::env::temp_dir().join(format!("lightcraft-builtin-{GPU_SETUP_MARKER}")),
}
}
#[cfg(feature = "denoise")]
impl BuiltinCard {
/// The card when it can be used now, else why not. `start` sets it up when that has not been tried yet; without it
/// nothing is started.
fn card(&self, start: bool) -> Result<&BuiltinGpu, String> {
let side = if start {
Some(self.gpu.get_or_init(|| {
let made = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| make_builtin_gpu(&self.marker)))
.unwrap_or_else(|_| Err("the GPU runner gave up".into()));
if let Err(why) = &made {
log::info!("denoise: the built-in denoiser runs on the CPU ({why})");
}
made
}))
} else {
self.gpu.get()
};
let g = match side {
None => return Err("the graphics card is not set up yet".into()),
Some(Err(why)) => return Err(why.clone()),
Some(Ok(g)) => g,
};
if let Some(why) = lightcraft_gpu::nn::broken_reason() {
return Err(format!("the graphics card stopped working ({why})"));
}
if self.fallbacks.load(Ordering::Relaxed) >= GPU_MAX_FALLBACKS {
return Err(format!("{} got {GPU_MAX_FALLBACKS} tiles wrong", g.adapter));
}
Ok(g)
}
/// The card, when a photo made `threads` tiles at a time under `run_on` runs on it; else why the CPU does.
fn choose(&self, run_on: RunOn, threads: usize, start: bool) -> Result<&BuiltinGpu, String> {
if run_on == RunOn::Cpu {
return Err("the processor is chosen in Settings".into());
}
let g = self.card(start)?;
if run_on == RunOn::Auto && !card_is_faster(g.card_ms, g.cpu_ms, threads) {
return Err(format!("it is faster than {} on this computer", g.adapter));
}
Ok(g)
}
fn fell_back(&self, why: &str) {
let n = self.fallbacks.fetch_add(1, Ordering::Relaxed) + 1;
if n == 1 {
log::warn!("denoise: a tile came back wrong from the GPU ({why}); the CPU runs it");
} else if n == GPU_MAX_FALLBACKS {
log::warn!("denoise: the GPU got {n} tiles wrong; the CPU does the rest");
}
}
/// Where the tiles run (see [`Model::device`]).
pub(super) fn device(&self, run_on: RunOn) -> Value {
if run_on != RunOn::Cpu && self.gpu.get().is_none() {
return json!({"kind": "pending"});
}
let threads = match self.last_threads.load(Ordering::Relaxed) {
0 => Pace::Full.parallel(std::thread::available_parallelism().map_or(1, |n| n.get()), None),
n => n,
};
let mut v = match self.choose(run_on, threads, false) {
Ok(g) => json!({"kind": "gpu", "adapter": g.adapter}),
// a set-up that crashed or ran out of time can be tried again (`denoise.settings {runOn}`)
Err(why) => json!({"kind": "cpu", "retry": worth_retrying(&why), "reason": why}),
};
if let (Some(Ok(g)), Some(o)) = (self.gpu.get(), v.as_object_mut()) {
o.insert("cardMs".into(), json!(g.card_ms));
o.insert("cpuMs".into(), json!(g.cpu_ms));
o.insert("fellBack".into(), json!(self.fallbacks.load(Ordering::Relaxed)));
}
v
}
}
/// The built-in denoiser for a photo that runs on the card: the filter there, and the CPU running any tile the card gets
/// wrong, so a photo is always finished.
#[cfg(feature = "denoise")]
struct CardRunner {
gpu: lightcraft_gpu::bm3d::BuiltinRunner,
cpu: lightcraft_denoise::builtin::Builtin,
card: Arc<BuiltinCard>,
}
#[cfg(feature = "denoise")]
impl TileRunner for CardRunner {
fn run(&self, input: &[f32]) -> Result<Vec<f32>, RunError> {
if self.card.card(false).is_ok() {
match self.gpu.run(input) {
Ok(out) if out.iter().all(|v| v.is_finite()) => return Ok(out),
Ok(_) => self.card.fell_back("numbers that are not finite"),
Err(e) => self.card.fell_back(&e.to_string()),
}
}
self.cpu.run(input)
}
}
#[cfg(all(test, feature = "denoise"))]
mod tests;
+156
View File
@@ -0,0 +1,156 @@
use super::*;
use crate::denoise::forget_gpu_set_ups;
/// A folder of the test's own: the card's set-up leaves its marker in it.
#[allow(clippy::unwrap_used)]
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("lc-engine-builtin-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// The built-in denoiser for one photo of `noise` `(a, b)`, its card state kept by a marker in a folder of its own.
fn builtin(name: &str) -> (BuiltinModel, PathBuf) {
let dir = folder(name);
let m = BuiltinModel::new(&dir.join(GPU_SETUP_MARKER));
let _ = m.runner.set(lightcraft_denoise::builtin::Builtin::with_noise(CHECK_NOISE));
(m, dir)
}
/// Compare a tile from the card with the CPU's picture: equal on average, and with few values far off. (The demosaic
/// chooses a direction at each pixel, so a tiny difference of the filter can change a pixel by a good deal.)
fn agree(want: &[f32], got: &[f32]) {
assert_eq!(want.len(), got.len());
let scale = want.iter().fold(1e-9f32, |m, v| m.max(v.abs()));
let mean = want.iter().zip(got).map(|(a, b)| (a - b).abs()).sum::<f32>() / want.len() as f32 / scale;
let far = want.iter().zip(got).filter(|(a, b)| (*a - *b).abs() > 0.05 * scale).count() as f32 / want.len() as f32;
assert!(mean < 1e-3 && far < 5e-3, "off by {mean:e} on average of the largest value, {far:e} of the values far off");
}
/// With the card chosen, the built-in denoiser's tile agrees with the processor's, a few tiles feed the card at once,
/// and a set-up that ended leaves no marker; where there is no card it stays on the processor.
#[test]
fn the_built_in_denoiser_on_the_card_gives_the_cpus_tile() {
use lightcraft_denoise::builtin::{Builtin, TILE};
let (m, dir) = builtin("builtin-card");
let tile = builtin_check_tile(TILE as usize);
let want = Builtin::with_noise(CHECK_NOISE).run(&tile).unwrap();
let (runner, at_once) = m.runner(RunOn::Gpu, 16);
let device = m.device(RunOn::Gpu);
eprintln!("device: {device}");
match device["kind"].as_str() {
Some("gpu") => {
assert!(at_once <= GPU_PARALLEL, "a card is fed by a few tiles at once");
agree(&want, &runner.run(&tile).unwrap());
assert!(device["cardMs"].as_f64().is_some_and(|ms| ms > 0.0) && device["cpuMs"].as_f64().is_some_and(|ms| ms > 0.0), "{device}");
}
Some("cpu") => {
lightcraft_testkit::skip!(Gpu, "the built-in denoiser stays on the CPU here: {}", device["reason"]);
assert_eq!(at_once, 16);
}
other => panic!("the first photo decides where the work runs, not {other:?}"),
}
assert!(!dir.join(GPU_SETUP_MARKER).exists(), "a set-up that ended leaves no marker");
forget_builtin_card(&dir.join(GPU_SETUP_MARKER));
let _ = std::fs::remove_dir_all(&dir);
}
/// With the processor chosen, the built-in denoiser gives the processor's tile bit for bit, uses all the threads
/// asked for and never sets the card up.
#[test]
fn with_the_processor_chosen_the_built_in_denoiser_runs_on_the_cpu_and_never_starts_the_card() {
use lightcraft_denoise::builtin::{Builtin, TILE};
let (m, dir) = builtin("builtin-cpu");
let tile = builtin_check_tile(TILE as usize);
let (runner, at_once) = m.runner(RunOn::Cpu, 16);
assert_eq!(runner.run(&tile).unwrap(), Builtin::with_noise(CHECK_NOISE).run(&tile).unwrap(), "the CPU path is the CPU runner, bit for bit");
assert_eq!(at_once, 16, "the threads asked for are the threads used");
assert_eq!(m.device(RunOn::Cpu)["kind"], "cpu");
assert_eq!(m.device(RunOn::Auto)["kind"], "pending", "the card was not even set up");
forget_builtin_card(&dir.join(GPU_SETUP_MARKER));
let _ = std::fs::remove_dir_all(&dir);
}
/// A set-up marker left behind (the app closed while it ran) keeps the card off the built-in denoiser, with a reason
/// and a retry, until choosing where denoise runs forgets it.
#[test]
fn a_set_up_marker_left_behind_keeps_the_card_off_the_built_in_denoiser_until_a_choice_is_made() {
let (m, dir) = builtin("builtin-marker");
let marker = dir.join(GPU_SETUP_MARKER);
std::fs::write(&marker, "setting up the graphics card for AI Denoise (unix time 1)\n").unwrap();
let (_, at_once) = m.runner(RunOn::Gpu, 6);
assert_eq!(at_once, 6, "no card: the threads asked for");
let device = m.device(RunOn::Gpu);
assert_eq!(device["kind"], "cpu", "{device}");
assert_eq!(device["retry"], true, "{device}");
assert!(device["reason"].as_str().unwrap().contains("closed"), "{device}");
// choosing where denoise runs forgets it (and the marker): the card is set up afresh for the next photo
forget_gpu_set_ups(&dir);
assert!(!marker.exists());
let (again, _) = builtin("builtin-marker-again");
assert_eq!(again.device(RunOn::Auto)["kind"], "pending");
let _ = std::fs::remove_dir_all(&dir);
}
/// The card's filter stays within the agreement limits of the processor's on the check tile, well inside them, and
/// gives the same answer every time.
#[test]
fn the_cards_filter_agrees_with_the_cpus_on_the_check_tile_and_gives_the_same_answer_every_time() {
use lightcraft_denoise::builtin::{Builtin, TILE};
let tile = builtin_check_tile(TILE as usize);
let b = Builtin::with_noise(CHECK_NOISE);
let params = b.bm3d_params().unwrap();
let gpu = match lightcraft_gpu::bm3d::Bm3dGpu::new(&params, TILE as usize) {
Ok(g) => Arc::new(g),
Err(why) => return lightcraft_testkit::skip!(Gpu, "no card for the built-in denoiser here: {why}"),
};
let runner = lightcraft_gpu::bm3d::BuiltinRunner::new(gpu, b).unwrap();
let a = runner.agreement(&tile).unwrap();
eprintln!("the card's filter is off by {:.3} at most and {:.1e} on average (noise deviations)", a.worst, a.mean);
assert!(a.worst <= BUILTIN_AGREE_WORST && a.mean <= BUILTIN_AGREE_MEAN, "{a:?}");
assert!(a.worst < 0.15 && a.mean < 1e-4, "a card within the limits but far from what it manages: {a:?}");
let (first, again) = (runner.run(&tile).unwrap(), runner.run(&tile).unwrap());
assert_eq!(first, again, "the card gives the same answer every time");
agree(&Builtin::with_noise(CHECK_NOISE).run(&tile).unwrap(), &first);
}
/// A tile the card cannot do (another size than it was made for) is run on the processor, and after three of them
/// the card is stopped for the built-in denoiser.
#[test]
fn a_tile_the_card_gets_wrong_is_run_on_the_processor_and_three_stop_the_card_for_the_built_in_denoiser() {
use lightcraft_denoise::builtin::Builtin;
let (m, dir) = builtin("builtin-wrong");
let (_, _) = m.runner(RunOn::Gpu, 8);
if m.device(RunOn::Gpu)["kind"] != "gpu" {
lightcraft_testkit::skip!(Gpu, "no card for the built-in denoiser here: {}", m.device(RunOn::Gpu)["reason"]);
forget_builtin_card(&dir.join(GPU_SETUP_MARKER));
let _ = std::fs::remove_dir_all(&dir);
return;
}
// a tile of another size than the card was made for is one it cannot do: the CPU runs it, and three stop the card
let small = 64;
let input = builtin_check_tile(small);
let want = Builtin::with_noise(CHECK_NOISE).run(&input).unwrap();
let (runner, _) = m.runner(RunOn::Gpu, 8);
for _ in 0..GPU_MAX_FALLBACKS {
assert_eq!(runner.run(&input).unwrap(), want, "a tile the card cannot do is the CPU's tile");
}
let device = m.device(RunOn::Gpu);
assert_eq!(device["kind"], "cpu", "{device}");
assert!(device["reason"].as_str().unwrap().contains("tiles wrong"), "{device}");
assert_eq!(device["fellBack"], GPU_MAX_FALLBACKS);
let (_, at_once) = m.runner(RunOn::Gpu, 8);
assert_eq!(at_once, 8, "the next photo runs on the CPU, even with the card chosen");
forget_builtin_card(&dir.join(GPU_SETUP_MARKER));
let _ = std::fs::remove_dir_all(&dir);
}
/// A photo whose noise cannot be measured is not told a made-up noise (which would leave it undenoised): the runner
/// keeps measuring each tile's own.
#[test]
fn a_photo_whose_noise_cannot_be_measured_leaves_the_runner_to_measure_each_tile() {
let m = BuiltinModel::new(&std::env::temp_dir().join("lc-engine-builtin-unmeasured"));
m.prepare(&[0.5; 100], 10, 10);
assert!(m.runner.get().is_none(), "nothing was measured, so nothing is set");
}
+6 -3
View File
@@ -14,7 +14,7 @@ const GPU_AGREE: f32 = 1e-3;
/// Longest the card may take to set up (build its kernels, run the check tile, time it) before the processor does the
/// work instead.
#[cfg(feature = "denoise")]
const GPU_SETUP_LIMIT: Duration = Duration::from_secs(30);
pub(super) const GPU_SETUP_LIMIT: Duration = Duration::from_secs(30);
/// Tiles the card may get wrong (an error, numbers that are not finite) before it stops being used for the model.
#[cfg(feature = "denoise")]
@@ -80,7 +80,10 @@ pub(super) fn set_up_card<T: Send + 'static, R>(
return Err(GPU_CRASHED.into());
}
let secs = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs());
// a marker that cannot be written only loses the crash guard
// the models folder may not exist yet; a marker that cannot be written only loses the crash guard
if let Some(parent) = marker.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::write(marker, format!("setting up the graphics card for AI Denoise (unix time {secs})\n"));
running.push(marker.to_path_buf());
SetUpEnded(marker.to_path_buf())
@@ -107,7 +110,7 @@ pub(super) fn set_up_card<T: Send + 'static, R>(
/// The card's time for one tile once it is warm: the fastest of up to three runs, stopping after about two seconds (a
/// slow card is slow enough to tell at once).
#[cfg(feature = "denoise")]
fn card_tile_ms(runner: &dyn TileRunner, input: &[f32]) -> f64 {
pub(super) fn card_tile_ms(runner: &dyn TileRunner, input: &[f32]) -> f64 {
if runner.run(input).is_err() {
return f64::INFINITY;
}
+20
View File
@@ -279,6 +279,26 @@ fn a_set_up_runs_beside_the_cpu_and_removes_its_marker() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_set_up_makes_the_folder_of_its_marker() {
let dir = folder("setup-folder").join("not").join("yet");
let marker = dir.join(GPU_SETUP_MARKER);
let (m, seen) = (marker.clone(), Arc::new(AtomicBool::new(false)));
let s = seen.clone();
let r = set_up_card(
&marker,
Duration::from_secs(10),
move || {
s.store(m.exists(), Ordering::Relaxed);
Ok(())
},
|| (),
);
assert_eq!(r, Ok(((), ())));
assert!(seen.load(Ordering::Relaxed), "the crash guard is written even when the models folder was missing");
let _ = std::fs::remove_dir_all(dir.ancestors().nth(2).unwrap_or(&dir));
}
#[test]
fn a_set_up_that_takes_too_long_is_given_up_on() {
let dir = folder("slowsetup");
+2
View File
@@ -51,6 +51,8 @@ pub(crate) trait Model: Send + Sync {
/// What runs a photo's tiles, and how many to run at once, when `threads` may be used and the setting is `run_on`
/// (a graphics card is kept busy by a few). The first time the card may be used it is set up and checked here.
fn runner(&self, run_on: RunOn, threads: usize) -> (&dyn TileRunner, usize);
/// Called once per photo with its whole mosaic before the tiles run, for a model that adapts to the photo.
fn prepare(&self, _mosaic: &[f32], _width: usize, _height: usize) {}
/// Check it does something sensible: the test's result, or why not. Unless `run_on` is the processor the graphics
/// card is set up and checked too, and the result says where the work will run.
fn self_test(&self, run_on: RunOn) -> Result<Value, String>;
+8
View File
@@ -1,3 +1,4 @@
use super::builtin::{BuiltinModel, builtin_marker};
use super::model::{Loader, Model, ModelSlot, RunOn, STACK};
use super::settings::EXT;
use super::{
@@ -133,6 +134,9 @@ impl Progress {
/// The loaded model, loading it first when it is not (kept for the next photo).
pub(super) fn loaded(spec: &JobSpec) -> Result<Arc<dyn Model>, MakeError> {
if spec.manifest.id == lightcraft_denoise::builtin::ID {
return Ok(Arc::new(BuiltinModel::new(&builtin_marker(&spec.onnx))));
}
if let Some(m) = spec.model.lock().unwrap_or_else(PoisonError::into_inner).clone() {
return Ok(m);
}
@@ -196,6 +200,10 @@ pub(crate) fn make_product(spec: &JobSpec, progress: Option<&Progress>) -> Resul
let (_, budget) = crate::memory::work_gate().usage();
let parallel = spec.parallel.clamp(1, 4).min((budget / scratch.max(1)).max(1));
let _held = crate::memory::work_gate().acquire(mosaic.data.len().saturating_mul(20).saturating_add(scratch.saturating_mul(parallel)));
model.prepare(&mosaic.data, mosaic.width, mosaic.height);
if cancelled() {
return Err(MakeError::Cancelled);
}
let (runner, parallel) = model.runner(spec.run_on, parallel);
let params = Params {
tile: spec.manifest.tile as usize,
+25 -17
View File
@@ -1,3 +1,5 @@
#[cfg(feature = "denoise")]
use super::builtin::{builtin_card, builtin_marker};
#[cfg(doc)]
use super::model::Model;
use super::model::STACK;
@@ -15,6 +17,11 @@ impl Session {
let loaded = self.denoise.active.as_ref().and_then(|a| a.model.lock().unwrap_or_else(PoisonError::into_inner).clone());
match loaded {
Some(m) => m.device(self.denoise.settings.run_on()),
#[cfg(feature = "denoise")]
None if self.denoise.active.as_ref().is_some_and(|a| a.id == lightcraft_denoise::builtin::ID) => {
let onnx = self.denoise.active.as_ref().map(|a| a.onnx.clone()).unwrap_or_default();
builtin_card(&builtin_marker(&onnx)).device(self.denoise.settings.run_on())
}
None => json!({"kind": "none"}),
}
}
@@ -37,23 +44,20 @@ impl Session {
let id = self.denoise.settings.model.clone()?;
installed_models(dir).into_iter().find(|i| i.manifest.id == id)
});
let found = chosen.map(|i| (i.fingerprint(), i));
let same = match (&self.denoise.active, &found) {
(None, None) => true,
(Some(a), Some((fp, _))) => a.fingerprint == *fp,
_ => false,
// no model chosen (or the one chosen is gone): the built-in denoiser
let (fingerprint, manifest, onnx) = match chosen {
Some(i) => (i.fingerprint(), i.manifest, i.onnx),
None => {
let manifest = lightcraft_denoise::builtin::manifest();
let onnx = self.denoise.models_dir.as_deref().map(|d| d.join(lightcraft_denoise::builtin::ID)).unwrap_or_default();
(format!("{}@{}", manifest.id, manifest.version), manifest, onnx)
}
};
if same {
if self.denoise.active.as_ref().is_some_and(|a| a.fingerprint == fingerprint) {
return;
}
// another model: what was made with the old one is not this one's, and what failed may work now
self.denoise.active = found.map(|(fingerprint, i)| Active {
id: i.manifest.id.clone(),
manifest: i.manifest,
onnx: i.onnx,
fingerprint,
model: Arc::new(Mutex::new(None)),
});
self.denoise.active = Some(Active { id: manifest.id.clone(), manifest, onnx, fingerprint, model: Arc::new(Mutex::new(None)) });
if let Some(r) = self.denoise.running.take() {
r.progress.cancel_now();
}
@@ -142,8 +146,8 @@ impl Session {
return PhotoState::NotApplicable;
}
if self.denoise.active.is_none() {
// the model folder has not been looked at yet (just started): not "no model" until it has been
return if self.denoise.active_seen.is_none() { PhotoState::Idle } else { PhotoState::NoModel };
// the model in use has not been looked at yet (just started)
return PhotoState::Idle;
}
if self.denoise_products_dir().is_none() {
return PhotoState::Failed {
@@ -310,8 +314,12 @@ impl Session {
/// Keep the cache within its limit: the pictures nobody asks for go first, the oldest first; `keep` (the one just
/// made) never goes. The index forgets what was deleted.
pub(crate) fn denoise_evict(&mut self, keep: Option<&Path>) {
let Some(models) = self.denoise.models_dir.clone() else { return };
self.denoise_evict_to(read_settings(&models).cache_bytes(), keep);
self.denoise_evict_to(self.denoise_cache_limit(), keep);
}
/// The cache's size limit in bytes (the default without a models folder).
pub(crate) fn denoise_cache_limit(&self) -> u64 {
self.denoise.models_dir.as_deref().map(read_settings).unwrap_or_default().cache_bytes()
}
/// [`Self::denoise_evict`] for a limit of `limit` bytes.
+5 -1
View File
@@ -1,3 +1,5 @@
#[cfg(feature = "denoise")]
use super::builtin::{builtin_marker, forget_builtin_card};
use super::gpu::GPU_SETUP_MARKER;
use super::model::RunOn;
use super::{DenoiserManifest, Deserialize, Duration, Path, PathBuf, Serialize, Value};
@@ -108,7 +110,7 @@ pub(crate) fn installed_models(dir: &Path) -> Vec<Installed> {
let p = e.path();
let Some(name) = p.file_name().and_then(|n| n.to_str()).map(str::to_string) else { continue };
let onnx = p.join("model.onnx");
if !lightcraft_denoise::licence::valid_id(&name) || !p.is_dir() || !onnx.is_file() {
if name == lightcraft_denoise::builtin::ID || !lightcraft_denoise::licence::valid_id(&name) || !p.is_dir() || !onnx.is_file() {
continue;
}
let Some(m) = read_capped(&p.join("denoise-model.json"), lightcraft_denoise::manifest::MAX_MANIFEST_BYTES)
@@ -132,4 +134,6 @@ pub(crate) fn forget_gpu_set_ups(dir: &Path) {
for i in installed_models(dir) {
let _ = std::fs::remove_file(i.onnx.with_file_name(GPU_SETUP_MARKER));
}
#[cfg(feature = "denoise")]
forget_builtin_card(&builtin_marker(&dir.join(lightcraft_denoise::builtin::ID)));
}
-2
View File
@@ -54,8 +54,6 @@ impl Pace {
pub enum PhotoState {
/// Not a photo denoise applies to (not a raw, offline, a demo).
NotApplicable,
/// No model is chosen: nothing can be made.
NoModel,
/// Its picture is made: the Amount slider works.
Ready,
Queued {
+577
View File
@@ -0,0 +1,577 @@
//! A once-per-session alert when the drive holding the library's preview cache runs low.
//!
//! The automatic preview cache budget grows with the library and has no ceiling
//! ([`crate::media::default_disk_cache_bytes`]): a large library can fill its drive. Rather than cap
//! it, the session looks at the drive's free space when the library opens and, at most every
//! [`CHECK_EVERY`] while the app runs (thumbnails and previews fill the cache); when it is under [`LOW_FREE_PERCENT`] of the drive or
//! under [`LOW_FREE_BYTES`], it hands out one [`LowDiskAlert`] ([`crate::Session::take_disk_space_alert`])
//! that the UI shows with a way to Settings ▸ Performance, where the cache can be given a limit. It is
//! not repeated until the next library open or app run. Reading the free space can fail (a network
//! share that doesn't say, the web build): then there is no alert, only a log line.
//! Natively the read runs on a worker thread and its answer is taken on a later call, so a slow
//! network share never holds up the UI thread that asks.
use std::path::Path;
/// The drive is low when less than this share of it (percent) is free…
pub const LOW_FREE_PERCENT: u64 = 10;
/// …or when less than this is free (20 GB), whichever comes first.
pub const LOW_FREE_BYTES: u64 = 20 << 30;
/// While a library is open, the free space is read at most this often (statvfs on the cache's
/// drive: cheap, but not something for every frame or every write).
pub const CHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(5 * 60);
/// A read when the library opens that hasn't answered after this long shows in the activity stack.
const SHOW_ROW_AFTER: std::time::Duration = std::time::Duration::from_millis(200);
/// A read whose thread couldn't start (the system out of threads for a moment) is tried again this
/// soon, not after [`CHECK_EVERY`].
pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(10);
/// What a read's worker answers: the drive's space and the cache's size when low (`None`: the drive
/// didn't say), or that the read couldn't start.
type Answer = Result<Option<(DiskSpace, u64)>, NotStarted>;
/// A read's thread couldn't be started.
struct NotStarted;
/// Space on one drive, in bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DiskSpace {
/// Free for this user (what can still be written).
pub available: u64,
/// The drive's size.
pub total: u64,
}
impl DiskSpace {
/// Under [`LOW_FREE_PERCENT`] of the drive free, or under [`LOW_FREE_BYTES`]. A drive that
/// reports no size isn't judged by its share.
pub fn is_low(&self) -> bool {
let under_share = self.total > 0 && u128::from(self.available) * 100 < u128::from(self.total) * u128::from(LOW_FREE_PERCENT);
under_share || self.available < LOW_FREE_BYTES
}
}
/// What the UI tells the user once: the drive's free space and size, and how big the preview
/// cache is now.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LowDiskAlert {
pub space: DiskSpace,
/// Bytes the preview cache takes on that drive.
pub cache_bytes: u64,
}
/// The free space of the drive holding `dir` (or its parent when `dir` isn't there yet). `None`
/// (logged) when it can't be read.
pub fn read(dir: &Path) -> Option<DiskSpace> {
#[cfg(not(target_arch = "wasm32"))]
{
let probe = if dir.exists() { dir } else { dir.parent().unwrap_or(dir) };
match fs4::statvfs(probe) {
Ok(s) => Some(DiskSpace { available: s.available_space(), total: s.total_space() }),
Err(e) => {
log::info!("disk space: can't read the free space of {}: {e}", probe.display());
None
}
}
}
#[cfg(target_arch = "wasm32")]
{
let _ = dir;
None
}
}
/// Reads the free space of a drive ([`read`]; a test can put a slow one in its place).
pub type Reader = std::sync::Arc<dyn Fn(&Path) -> Option<DiskSpace> + Send + Sync>;
/// The session's state of the alert (reset when a library opens).
#[derive(Default)]
pub(crate) struct DiskAlertState {
/// The alert was handed out (or is waiting to be) this session: never again until reset.
pub(crate) raised: bool,
/// The alert waiting for the UI.
pub(crate) pending: Option<LowDiskAlert>,
/// When the free space was last read.
pub(crate) checked_at: Option<web_time::Instant>,
/// The read running on a worker (natively): a network share can take its time to answer, and
/// the check runs on the UI thread. It answers with the drive's space and, when that is low,
/// the preview cache's size (counting the cache can mean reading every file's size: that too
/// stays off the UI thread).
probe: Option<std::sync::mpsc::Receiver<Answer>>,
/// The running read was started for the library open before this one: its answer is ignored,
/// and the drive is read again for the current library once it has come. Until then no second
/// read starts, so switching libraries while a drive hangs never piles up workers.
stale: bool,
/// In place of [`read`] (tests).
pub(crate) reader: Option<Reader>,
/// Tests: the read's thread that fails to start (`"disk-space"`, `"disk-space-read"`).
pub(crate) fail_spawn: Option<&'static str>,
}
/// Start a named thread; `fail` stands for a system that can't (tests).
#[cfg(not(target_arch = "wasm32"))]
fn spawn(name: &str, fail: bool, f: impl FnOnce() + Send + 'static) -> std::io::Result<()> {
if fail {
return Err(std::io::Error::other("no thread (test)"));
}
std::thread::Builder::new().name(name.into()).spawn(f).map(drop)
}
impl DiskAlertState {
/// A fresh state for a newly opened library (the reader stays; a read still running is kept,
/// marked stale).
pub(crate) fn reset(&mut self) {
let probe = self.probe.take();
let stale = probe.is_some();
*self = DiskAlertState { reader: self.reader.take(), fail_spawn: self.fail_spawn, probe, stale, ..Default::default() };
}
}
impl crate::Session {
/// Read the free space of the drive holding the preview cache, at most every [`CHECK_EVERY`]
/// (`now`: whatever the last read, as when the library opens), and raise the alert if it is low
/// ([`Session::note_disk_space`](crate::Session::note_disk_space)). Nothing once the alert was
/// raised this session, without an on-disk library, or when the space can't be read.
/// The read itself runs on a worker (natively) and its answer is taken by a later call or
/// [`Session::poll_disk_space`]: a slow drive never holds up the caller.
pub fn check_disk_space(&mut self, now: bool) {
self.poll_disk_space();
// (a read still running for an earlier library open starts this library's read when it answers)
if self.disk_alert.raised || self.disk_alert.probe.is_some() {
return;
}
let Some(dir) = self.library.as_ref().filter(|l| l.on_disk).map(crate::library::Library::thumbs_dir) else { return };
let at = web_time::Instant::now();
if !now && self.disk_alert.checked_at.is_some_and(|t| at.saturating_duration_since(t) < CHECK_EVERY) {
return;
}
self.disk_alert.checked_at = Some(at);
let reader = self.disk_alert.reader.clone();
let rendered = self.media.rendered.clone();
let read_now = move || {
let space = match reader {
Some(r) => r(&dir),
None => read(&dir),
}?;
// the cache is counted only when the alert will tell its size
let cache_bytes = if space.is_low() { rendered.disk().map_or(0, |d| d.size()) } else { 0 };
Some((space, cache_bytes))
};
#[cfg(not(target_arch = "wasm32"))]
{
// a read when the library opens that takes more than a moment (a network share slow to
// answer, or the cache counted when the drive is low) shows in the activity stack; a quick
// one, and the quiet periodic ones every few minutes, don't
let activity = now.then(|| self.activity.clone());
let fail = self.disk_alert.fail_spawn;
let (tx, rx) = std::sync::mpsc::channel();
let started = spawn("disk-space", fail == Some("disk-space"), move || {
let answer = match activity {
None => Ok(read_now()),
Some(activity) => {
let (done, answered) = std::sync::mpsc::channel();
let reading = spawn("disk-space-read", fail == Some("disk-space-read"), move || {
let _ = done.send(read_now());
});
match reading {
Err(e) => {
log::info!("disk space: can't start the free-space read: {e}");
Err(NotStarted)
}
Ok(()) => match answered.recv_timeout(SHOW_ROW_AFTER) {
Ok(answer) => Ok(answer),
Err(_) => {
let _row = activity.start("cache", "Checking free disk space", crate::activity::Cancel::No);
Ok(answered.recv().ok().flatten())
}
},
}
}
};
let _ = tx.send(answer);
});
match started {
Ok(()) => self.disk_alert.probe = Some(rx),
Err(e) => {
log::info!("disk space: can't start the free-space read: {e}");
self.retry_disk_space_soon();
}
}
}
#[cfg(target_arch = "wasm32")]
if let Some((space, cache_bytes)) = read_now() {
self.raise_disk_alert(space, cache_bytes);
}
}
/// Take the answer of the free-space read running on a worker, if it has come, and raise the
/// alert when the drive is low. An answer for an earlier library open is dropped and the drive
/// of the current one is read instead. Called by [`Session::check_disk_space`],
/// [`Session::take_disk_space_alert`] and `library.info`.
pub fn poll_disk_space(&mut self) {
let Some(rx) = self.disk_alert.probe.as_ref() else { return };
let answer = match rx.try_recv() {
Ok(answer) => answer,
Err(std::sync::mpsc::TryRecvError::Empty) => return,
// (a worker that ended without answering: tried again soon too)
Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(NotStarted),
};
self.disk_alert.probe = None;
if std::mem::take(&mut self.disk_alert.stale) {
self.check_disk_space(true);
} else {
match answer {
Ok(Some((space, cache_bytes))) => {
self.raise_disk_alert(space, cache_bytes);
}
Ok(None) => {}
Err(NotStarted) => self.retry_disk_space_soon(),
}
}
}
/// A read that couldn't start counts as made [`RETRY_AFTER`] less than [`CHECK_EVERY`] ago: the next check
/// reads the drive after [`RETRY_AFTER`] (CodeRabbit on #3577: it waited the whole five minutes).
fn retry_disk_space_soon(&mut self) {
let now = web_time::Instant::now();
self.disk_alert.checked_at = Some(now.checked_sub(CHECK_EVERY.saturating_sub(RETRY_AFTER)).unwrap_or(now));
}
/// Raise the low-disk alert for `space` when it is low and the alert wasn't raised this session
/// yet (the numbers come from [`read`], or from a test). Returns whether it was raised now.
/// Counts the preview cache here, on the caller's thread: the session's own reads count it on
/// their worker.
pub fn note_disk_space(&mut self, space: DiskSpace) -> bool {
if self.disk_alert.raised || !space.is_low() {
return false;
}
let cache_bytes = self.media.rendered.disk().map_or(0, |d| d.size());
self.raise_disk_alert(space, cache_bytes)
}
/// [`Session::note_disk_space`] with the cache's size already counted.
fn raise_disk_alert(&mut self, space: DiskSpace, cache_bytes: u64) -> bool {
if self.disk_alert.raised || !space.is_low() {
return false;
}
log::warn!("disk space: {} of {} bytes free; the preview cache takes {cache_bytes} bytes", space.available, space.total);
self.disk_alert.raised = true;
self.disk_alert.pending = Some(LowDiskAlert { space, cache_bytes });
true
}
/// The low-disk alert not shown yet, if any (handed out once per session).
pub fn take_disk_space_alert(&mut self) -> Option<LowDiskAlert> {
self.poll_disk_space();
self.disk_alert.pending.take()
}
/// Read the drive's space with `reader` instead of asking the system (tests of the app).
#[doc(hidden)]
pub fn set_disk_space_reader(&mut self, reader: Option<Reader>) {
self.disk_alert.reader = reader;
}
/// Forget when the space was last read, as if [`CHECK_EVERY`] had passed (tests of the app).
#[doc(hidden)]
pub fn forget_disk_space_check(&mut self) {
self.disk_alert.checked_at = None;
}
/// Whether a free-space read is running on its worker (its answer not taken yet).
pub fn disk_space_reading(&self) -> bool {
self.disk_alert.probe.is_some()
}
/// How long until [`Session::check_disk_space`] reads the drive again (zero when it is due, `None`
/// when it won't: the alert was raised, a read runs, or nothing has been read yet).
pub fn disk_space_next_check_in(&self) -> Option<std::time::Duration> {
let a = &self.disk_alert;
if a.raised || a.probe.is_some() {
return None;
}
Some(CHECK_EVERY.saturating_sub(a.checked_at?.elapsed()))
}
/// How long the free-space read running on its worker has run (`Duration::MAX` for one started for the
/// library before), or `None` when none runs.
pub fn disk_space_read_running_for(&self) -> Option<std::time::Duration> {
let a = &self.disk_alert;
a.probe.as_ref()?;
Some(a.checked_at.filter(|_| !a.stale).map_or(std::time::Duration::MAX, |t| t.elapsed()))
}
/// Whether the low-disk alert was raised since the library opened (`library.info` →
/// `lowDiskSpace`).
pub fn disk_space_alert_raised(&self) -> bool {
self.disk_alert.raised
}
}
#[cfg(test)]
mod tests {
use super::{DiskSpace, LOW_FREE_BYTES};
use crate::Session;
const GB: u64 = 1 << 30;
#[test]
fn plenty_of_room_on_both_counts_raises_no_alert() {
let mut s = Session::new();
assert!(!s.note_disk_space(DiskSpace { available: 200 * GB, total: 1000 * GB }), "20 % and 200 GB free");
assert!(!s.note_disk_space(DiskSpace { available: 25 * GB, total: 100 * GB }), "25 % and 25 GB free");
assert!(s.take_disk_space_alert().is_none());
assert!(!s.disk_space_alert_raised());
}
#[test]
fn under_ten_percent_free_raises_the_alert() {
let mut s = Session::new();
// 300 GB is far above 20 GB, but only 7.5 % of a 4 TB drive
let space = DiskSpace { available: 300 * GB, total: 4000 * GB };
assert!(s.note_disk_space(space));
let alert = s.take_disk_space_alert().expect("the alert is handed out");
assert_eq!(alert.space, space);
assert!(s.disk_space_alert_raised());
}
#[test]
fn under_twenty_gb_free_raises_the_alert() {
let mut s = Session::new();
// 15 % of a 100 GB drive is free, but that is under 20 GB
let space = DiskSpace { available: 15 * GB, total: 100 * GB };
assert!(space.available < LOW_FREE_BYTES);
assert!(s.note_disk_space(space));
assert_eq!(s.take_disk_space_alert().map(|a| a.space), Some(space));
}
#[test]
fn the_alert_is_raised_once_per_session() {
let mut s = Session::new();
let low = DiskSpace { available: GB, total: 500 * GB };
assert!(s.note_disk_space(low));
assert!(s.take_disk_space_alert().is_some());
assert!(s.take_disk_space_alert().is_none(), "handed out once");
assert!(!s.note_disk_space(DiskSpace { available: GB / 2, ..low }), "lower still: not again this session");
assert!(s.take_disk_space_alert().is_none());
s.check_disk_space(true);
assert!(s.take_disk_space_alert().is_none(), "a check after the alert reads nothing");
}
#[test]
fn opening_a_library_starts_a_new_session_for_the_alert() {
let dir = std::env::temp_dir().join(format!("lc-disk-alert-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
// whatever this machine's drive holds, raise it by hand
let _ = s.take_disk_space_alert();
let low = DiskSpace { available: GB, total: 500 * GB };
if !s.disk_space_alert_raised() {
assert!(s.note_disk_space(low));
}
assert!(!s.note_disk_space(low), "once per session");
s.close_library().unwrap();
s.open_library(&dir, false).unwrap();
let _ = s.take_disk_space_alert();
let raised_by_open = s.disk_space_alert_raised();
assert!(raised_by_open || s.note_disk_space(low), "a new library open may warn again");
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// A drive that takes its time to answer (a network share) doesn't hold up the library open
/// or the checks on the UI thread: the read runs on a worker and its answer is taken later.
#[test]
fn a_slow_drive_does_not_hold_up_the_check() {
use std::sync::{Arc, Mutex, mpsc};
let dir = std::env::temp_dir().join(format!("lc-disk-alert-slow-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (release, wait) = mpsc::channel::<()>();
let wait = Mutex::new(wait);
let mut s = Session::new().with_fs();
s.disk_alert.reader = Some(Arc::new(move |_: &std::path::Path| {
// answers once the test lets it (or after 10 s, so a broken test can't hang)
let _ = wait.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10));
Some(DiskSpace { available: GB, total: 500 * GB })
}));
s.open_library(&dir, false).unwrap();
assert!(s.take_disk_space_alert().is_none(), "the open didn't wait for the drive's answer");
// the read the open started shows in the activity stack once it takes more than a moment
// (CodeRabbit on #3077)
let reading = |s: &Session| s.activity.list().iter().any(|t| t.kind == "cache" && t.label == "Checking free disk space");
let until = web_time::Instant::now() + std::time::Duration::from_secs(10);
while !reading(&s) {
assert!(web_time::Instant::now() < until, "{:?}", s.activity.list());
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(s.disk_space_reading());
s.check_disk_space(true);
assert!(s.take_disk_space_alert().is_none(), "nor does a check while the read runs");
release.send(()).unwrap();
let until = std::time::Instant::now() + std::time::Duration::from_secs(10);
let alert = loop {
if let Some(a) = s.take_disk_space_alert() {
break a;
}
assert!(std::time::Instant::now() < until, "the drive's answer was never taken");
std::thread::sleep(std::time::Duration::from_millis(5));
};
assert_eq!(alert.space.available, GB);
assert!(s.disk_space_alert_raised());
assert!(!reading(&s) && !s.disk_space_reading(), "the row goes with the read");
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// A drive that hangs while the user switches libraries: the read still running is kept, no
/// second worker starts beside it, its answer (for the old library) is dropped, and the current
/// library's drive is read once it has come.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn switching_libraries_while_a_drive_hangs_starts_no_second_read() {
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
let root = std::env::temp_dir().join(format!("lc-disk-alert-switch-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (a, b) = (root.join("a"), root.join("b"));
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
let (release, wait) = mpsc::channel::<()>();
let (started_tx, started) = mpsc::channel::<std::path::PathBuf>();
let wait = Mutex::new(wait);
let started_tx = Mutex::new(started_tx);
let mut s = Session::new().with_fs();
s.disk_alert.reader = Some(Arc::new(move |dir: &std::path::Path| {
let _ = started_tx.lock().unwrap().send(dir.to_path_buf());
let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10));
Some(DiskSpace { available: GB, total: 500 * GB })
}));
s.open_library(&a, false).unwrap();
let first = started.recv_timeout(Duration::from_secs(10)).expect("the open reads the drive");
assert!(first.starts_with(&a), "{first:?}");
s.close_library().unwrap();
s.open_library(&b, false).unwrap();
s.check_disk_space(true);
assert!(started.recv_timeout(Duration::from_millis(300)).is_err(), "no second read beside the hanging one");
release.send(()).unwrap();
let until = Instant::now() + Duration::from_secs(10);
let second = loop {
assert!(s.take_disk_space_alert().is_none(), "the old library's answer is dropped");
if let Ok(dir) = started.try_recv() {
break dir;
}
assert!(Instant::now() < until, "the current library's drive was never read");
std::thread::sleep(Duration::from_millis(5));
};
assert!(second.starts_with(&b), "{second:?}");
assert!(!s.disk_space_alert_raised());
release.send(()).unwrap();
let until = Instant::now() + Duration::from_secs(10);
while s.take_disk_space_alert().is_none() {
assert!(Instant::now() < until, "the current library's answer was never taken");
std::thread::sleep(Duration::from_millis(5));
}
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&root);
}
/// When the drive is low, the preview cache is counted on the read's worker too: counting it can
/// mean reading the size of every file (a big cache on a slow share), never on the UI thread
/// that takes the answer.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_preview_cache_is_counted_off_the_ui_thread() {
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
let dir = std::env::temp_dir().join(format!("lc-disk-alert-count-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (release, wait) = mpsc::channel::<()>();
let wait = Mutex::new(wait);
let mut s = Session::new().with_fs();
s.disk_alert.reader = Some(Arc::new(move |_: &std::path::Path| {
let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10));
Some(DiskSpace { available: GB, total: 500 * GB })
}));
s.open_library(&dir, false).unwrap();
let disk = || s.media.rendered.disk().map(lightcraft_preview::DiskCache::known_size);
assert_eq!(disk(), Some(None), "an on-disk library has a preview cache, not counted yet");
release.send(()).unwrap();
// no poll here: only the worker can count the cache
let until = Instant::now() + Duration::from_secs(10);
let counted = loop {
if let Some(Some(bytes)) = disk() {
break bytes;
}
assert!(Instant::now() < until, "the worker never counted the cache");
std::thread::sleep(Duration::from_millis(5));
};
let until = Instant::now() + Duration::from_secs(10);
let alert = loop {
if let Some(a) = s.take_disk_space_alert() {
break a;
}
assert!(Instant::now() < until, "the drive's answer was never taken");
std::thread::sleep(Duration::from_millis(5));
};
assert_eq!(alert.cache_bytes, counted);
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_free_space_of_a_real_drive_is_read() {
let space = super::read(&std::env::temp_dir().join("lc-disk-alert-not-there")).expect("the temp folder's drive says its size");
assert!(space.total > 0 && space.available <= space.total, "{space:?}");
}
/// A read whose thread can't start is tried again after [`super::RETRY_AFTER`], not after the five minutes
/// of [`super::CHECK_EVERY`] (CodeRabbit on #3577); for either of its two threads.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_read_that_could_not_start_is_tried_again_soon() {
use std::time::{Duration, Instant};
for thread in ["disk-space", "disk-space-read"] {
let dir = std::env::temp_dir().join(format!("lc-disk-alert-nothread-{thread}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new().with_fs();
s.disk_alert.reader = Some(std::sync::Arc::new(|_: &std::path::Path| Some(DiskSpace { available: GB, total: 500 * GB })));
s.disk_alert.fail_spawn = Some(thread);
s.open_library(&dir, false).unwrap();
let until = Instant::now() + Duration::from_secs(10);
while s.disk_space_reading() {
assert!(Instant::now() < until, "{thread}: the read never ended");
s.poll_disk_space();
std::thread::sleep(Duration::from_millis(5));
}
let since = s.disk_alert.checked_at.expect("a check was made").elapsed();
assert!(
since + super::RETRY_AFTER + Duration::from_secs(1) >= super::CHECK_EVERY,
"{thread}: next read in {:?}",
super::CHECK_EVERY.saturating_sub(since)
);
// the thread can start again: the retry reads the drive and raises the alert
s.disk_alert.fail_spawn = None;
s.disk_alert.checked_at = s.disk_alert.checked_at.and_then(|t| t.checked_sub(super::RETRY_AFTER));
s.check_disk_space(false);
let until = Instant::now() + Duration::from_secs(10);
while s.take_disk_space_alert().is_none() {
assert!(Instant::now() < until, "{thread}: the retry never read the drive");
std::thread::sleep(Duration::from_millis(5));
}
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
}
#[test]
fn a_drive_that_reports_no_size_is_judged_by_its_free_bytes() {
assert!(!DiskSpace { available: 50 * GB, total: 0 }.is_low());
assert!(DiskSpace { available: 5 * GB, total: 0 }.is_low());
}
}
+12
View File
@@ -198,6 +198,11 @@ pub struct ExportPreset {
}
/// The built-in export presets (File → Export with Preset).
///
/// A preset sets output options (format, quality, size, colour space, sharpening, metadata), never a
/// crop. "Instagram Story / Reel" therefore applies no crop to 9:16: it sets a 1920 px long edge only, so
/// a 3:2 photo exports at 1920 × 1280. The export options have no crop-to-aspect setting; a photo's own
/// crop is the only way to change its shape before export.
pub fn builtin_presets() -> Vec<ExportPreset> {
let p = |name: &str, params: serde_json::Value| ExportPreset { name: name.into(), params };
vec![
@@ -205,6 +210,13 @@ pub fn builtin_presets() -> Vec<ExportPreset> {
p("JPEG (Large)", serde_json::json!({"format": "jpeg", "quality": 92, "longEdge": 0, "colorSpace": "srgb"})),
p("Original + Settings", serde_json::json!({"format": "original"})),
p("DNG", serde_json::json!({"format": "dng"})),
p("Instagram Feed", serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 1080, "colorSpace": "srgb", "sharpen": "screen"})),
p(
"Instagram Story / Reel",
serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 1920, "colorSpace": "srgb", "sharpen": "screen"}),
),
p("Web / Portfolio", serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 2048, "colorSpace": "srgb", "metadata": "copyright"})),
p("Full Resolution Master", serde_json::json!({"format": "jpeg", "quality": 95, "longEdge": 0, "colorSpace": "displayP3"})),
]
}
+11 -2
View File
@@ -123,12 +123,21 @@ fn prepare_guarded(
let label = p.file_name.clone();
let meta = export_metadata(p, &session.catalog, o);
let gain_map = o.hdr_output() && o.format == ExportFormat::Jpeg;
let job = session.export_job(id, w, h, o.effective_space(), o.effective_depth())?;
let mut job = session.export_job(id, w, h, o.effective_space(), o.effective_depth())?;
job.request.exact_size = true;
job.key ^= 0x86e2_fadc_0917_b435;
let weight = render_weight(full_px, long, job.level, w.saturating_mul(h));
if let Some(why) = too_big_for_memory((w, h), native_px, weight, crate::memory::total_ram()) {
return Err(format!("{label}: {why}"));
}
let hdr_job = if gain_map { Some(session.export_job(id, w, h, o.effective_space(), OutputDepth::F32Hdr)?) } else { None };
let hdr_job = if gain_map {
let mut hdr = session.export_job(id, w, h, o.effective_space(), OutputDepth::F32Hdr)?;
hdr.request.exact_size = true;
hdr.key ^= 0x86e2_fadc_0917_b435;
Some(hdr)
} else {
None
};
(Work::Render(Box::new(RenderWork { job, hdr_job, meta, opts: o.clone() })), weight)
} else {
let lightcraft_catalog::Source::File { path } = &p.source else {
+1 -1
View File
@@ -225,7 +225,7 @@ fn sharpened_pixels_are_pinned() {
let samples = src.data.iter().flat_map(|p| [p[0], p[1], p[2]].map(|v| u16::from(v) * 257)).collect();
let mut deep = DeepImage { width: src.width, height: src.height, samples: DeepSamples::U16(samples), space: OutputSpace::Srgb };
output_sharpen_deep(&mut deep, target, SharpenAmount::Standard);
let DeepSamples::U16(v) = &deep.samples else { unreachable!() };
let DeepSamples::U16(v) = &deep.samples else { panic!("expected U16 samples") };
got.push(fnv(&v.iter().flat_map(|s| s.to_le_bytes()).collect::<Vec<u8>>()));
}
assert_eq!(got, SHARPENED, "{got:#x?}");
+4 -1
View File
@@ -246,7 +246,10 @@ fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) {
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
// Two stacked cfgs (not `all(test, …)`): clippy only recognises a plain `cfg(test)`
// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers.
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
use super::*;
use lightcraft_faces::hash::sha256_hex;
+29 -1
View File
@@ -27,7 +27,7 @@ pub(crate) use colour::clipped_white;
use fs::quick_image_srgb;
pub use fs::{fs_hooks, fs_pair_loader, fs_reduced_loader};
pub(crate) use load::{DngWhite, WbScaleOf, dng_tone_curve};
pub use load::{load_bytes, load_bytes_with, load_vec, load_vec_pair, load_vec_reduced};
pub use load::{load_bytes, load_bytes_decoded, load_bytes_with, load_vec, load_vec_pair, load_vec_reduced};
#[cfg(test)]
use preview::PLAN_PREFIX;
pub(crate) use preview::decode_raw_preview;
@@ -109,5 +109,33 @@ impl CameraColourModel<'_> {
}
}
/// Remove Hot Pixels leaves a raw alone when more than this share of its photosites would be replaced (Settings ▸
/// Performance ▸ Hot pixel limit, `app.hotPixelLimit`), as `f64` bits. Process-wide, like the GPU switch.
static HOT_PIXEL_LIMIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(lightcraft_raw::HOT_PIXEL_MAX_SHARE.to_bits());
/// The share of a raw's photosites Remove Hot Pixels may replace (0..1).
pub fn hot_pixel_limit() -> f64 {
f64::from_bits(HOT_PIXEL_LIMIT.load(std::sync::atomic::Ordering::Relaxed))
}
/// Set [`hot_pixel_limit`]; false (nothing changed) unless `share` is a new value in 0..=1. Sources decoded before
/// keep the old limit: the caller forgets them ([`crate::media::MediaCache::clear_sources`]).
pub fn set_hot_pixel_limit(share: f64) -> bool {
if !(0.0..=1.0).contains(&share) {
return false;
}
HOT_PIXEL_LIMIT.swap(share.to_bits(), std::sync::atomic::Ordering::Relaxed) != share.to_bits()
}
/// What [`hot_pixel_limit`] adds to the render cache keys of `settings`: nothing at the default limit or when they
/// don't remove hot pixels, so those renders stay valid whatever the limit.
pub fn hot_pixel_key(settings: &lightcraft_develop::DevelopSettings) -> u64 {
let limit = hot_pixel_limit();
if !settings.removes_hot_pixels() || limit.to_bits() == lightcraft_raw::HOT_PIXEL_MAX_SHARE.to_bits() {
return 0;
}
limit.to_bits().wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(29)
}
#[cfg(test)]
pub(crate) mod tests;
+12 -5
View File
@@ -1,7 +1,8 @@
use super::load::{load_vec, load_vec_pair, load_vec_reduced};
use super::preview::{fit_box, fs_preview_loader, preview_orientation};
use super::probe::probe_bytes;
use super::{Arc, DcpProfile, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
use super::{Arc, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
use crate::media::RawDecode;
/// The file's first [`lightcraft_raw::PREVIEW_PREFIX`] bytes (or the whole file when it is shorter),
/// which is what every format [`lightcraft_raw::bounded_preview`] covers keeps its pointer in.
@@ -37,6 +38,12 @@ pub(super) fn raf_preview_extent(prefix: &[u8]) -> Option<u64> {
/// `adobe_rgb`: the container declares the preview Adobe RGB ([`PreviewRead::adobe_rgb`]), applied
/// as [`decode_raw_preview`] applies it. `None` when the bytes are not a decodable image.
pub(super) fn quick_image_srgb(header: &[u8], window: &[u8], adobe_rgb: bool, max_edge: usize) -> Option<lightcraft_raster::Rgba8> {
// a plain sRGB camera JPEG (nearly all of them) straight to 8-bit (PERF-CULL-3: 45 MP preview
// of an EOS R5 C fitted to 2560 px, 194 → ~110 ms); anything else takes the general decode
let edge = u32::try_from(max_edge).unwrap_or(u32::MAX);
if !adobe_rgb && let Ok(Some((image, orientation))) = lightcraft_codecs::decode_jpeg_srgb8_fit(window, edge, edge) {
return Some(image.oriented(preview_orientation(header, orientation)));
}
let decoded = if adobe_rgb && window.starts_with(&[0xff, 0xd8]) {
lightcraft_codecs::decode_jpeg_with_fallback(window, fit_box(max_edge), lightcraft_codecs::NamedSpace::AdobeRgb)
} else {
@@ -54,13 +61,13 @@ pub(super) fn quick_image_srgb(header: &[u8], window: &[u8], adobe_rgb: bool, ma
/// The filesystem-backed [`PairLoader`]: the file is read and decoded once, and developed as usual and from the photo's
/// denoised picture. It holds two pictures at once, so it counts for more at the memory gate than a plain load.
pub fn fs_pair_loader() -> PairLoader {
Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec, dcp: Option<&DcpProfile>| {
Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec, with: RawDecode<'_>| {
let len = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0);
let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 };
let gate = crate::memory::work_gate();
let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) };
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
let r = load_vec_pair(bytes, max_edge, spec, dcp);
let r = load_vec_pair(bytes, max_edge, spec, with);
crate::memory::release();
r
})
@@ -75,7 +82,7 @@ pub fn fs_pair_loader() -> PairLoader {
/// yields to them.
pub fn fs_hooks() -> (FileLoader, FileProbe) {
let loader: FileLoader =
Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, dcp)));
Arc::new(|path: &str, max_edge: usize, with: RawDecode<'_>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, with)));
let probe: FileProbe = Arc::new(|path: &str| {
use std::io::Read;
// one open, then everything from the open file: its size and modification time are not
@@ -95,7 +102,7 @@ pub fn fs_hooks() -> (FileLoader, FileProbe) {
/// The filesystem [`ReducedLoader`]: [`load_vec_reduced`] of the file, gated like [`fs_hooks`]' loader.
pub fn fs_reduced_loader() -> ReducedLoader {
Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, dcp)))
Arc::new(|path: &str, max_edge: usize, with: RawDecode<'_>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, with)))
}
/// Read `path` and `load` it, waiting on [`crate::memory::work_gate`] as [`fs_hooks`] explains.
+24 -9
View File
@@ -2,6 +2,7 @@ use super::colour::bin_factor;
use super::preview::{fit_box, load_embedded_preview};
use super::probe::preview_reason;
use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint};
use crate::media::RawDecode;
/// Decode a file into a linear Rec.2020 image no larger than `max_edge`, oriented.
///
@@ -9,26 +10,31 @@ use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_C
/// instead of each one waking the pool from outside and waiting for it (which costs more than the
/// loops themselves when the machine is busy).
pub fn load_bytes(bytes: &[u8], max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, None).map(|(img, _, info, _)| (img, info)))
load_bytes_decoded(bytes, max_edge, RawDecode::default())
}
/// [`load_bytes`] developing a raw file with an imported camera profile (`dcp`) in place of its own colour model.
pub fn load_bytes_with(bytes: &[u8], max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info)))
load_bytes_decoded(bytes, max_edge, RawDecode { dcp, outliers: false })
}
/// [`load_bytes`] decoding a raw file as `with` says.
pub fn load_bytes_decoded(bytes: &[u8], max_edge: usize, with: RawDecode<'_>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, with).map(|(img, _, info, _)| (img, info)))
}
/// [`load_bytes`] taking the file's bytes: a raw file's bytes are freed as soon as it is decoded
/// (less memory held while it is developed).
pub fn load_vec(bytes: Vec<u8>, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info)))
pub fn load_vec(bytes: Vec<u8>, max_edge: usize, with: RawDecode<'_>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false, with).map(|(img, _, info, _)| (img, info)))
}
/// [`load_vec`] for a thumbnail: a DNG that keeps reduced-resolution copies of its raw image (Lightroom's HDR and
/// panorama merges) develops the smallest that covers `max_edge` instead of the whole image. The flag says whether
/// it did: such a picture is not the full image, and an export never renders from it.
pub fn load_vec_reduced(bytes: Vec<u8>, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> {
pub fn load_vec_reduced(bytes: Vec<u8>, max_edge: usize, with: RawDecode<'_>) -> Result<(Rgb32f, SourceInfo, bool), String> {
rayon::scope(move |_| {
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true, dcp).map(|(img, _, info, reduced)| (img, info, reduced))
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true, with).map(|(img, _, info, reduced)| (img, info, reduced))
})
}
@@ -39,10 +45,10 @@ pub fn load_vec_pair(
bytes: Vec<u8>,
max_edge: usize,
spec: &DenoiseSpec,
dcp: Option<&DcpProfile>,
with: RawDecode<'_>,
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
rayon::scope(move |_| {
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, dcp).map(|(img, twin, info, _)| (img, twin, info))
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, with).map(|(img, twin, info, _)| (img, twin, info))
})
}
@@ -73,8 +79,9 @@ fn load_bytes_now(
max_edge: usize,
denoise: Option<&DenoiseSpec>,
allow_reduced: bool,
dcp: Option<&DcpProfile>,
with: RawDecode<'_>,
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo, bool), String> {
let dcp = with.dcp;
if lightcraft_raw::probe(&bytes).is_some() {
// a thumbnail (`allow_reduced`, never an export) of a DNG that keeps smaller copies of its raw image
// (Lightroom's merges) develops the smallest that covers it; a denoised photo's twin needs the full mosaic
@@ -96,6 +103,14 @@ fn load_bytes_now(
}
Err(Err(e)) => return Err(e),
};
// single outlier photosites, replaced in the mosaic before anything is developed from it (#1345)
if with.outliers {
let t = std::time::Instant::now();
let n = raw.suppress_hot_pixels_with(super::hot_pixel_limit());
if lightcraft_pipeline::profiling() {
eprintln!("[profile] raw outliers: {n} photosites replaced in {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
}
}
// Embedded lens corrections are applied by the pipeline ("Enable Profile Corrections"), not baked in
// (removed before the camera look's binned sensor proxy too, which needs an empty `OpcodeList3`).
let info = raw.info();
+19 -4
View File
@@ -33,7 +33,11 @@ pub(crate) fn decode_raw_preview(
opts: lightcraft_codecs::DecodeOptions,
covering: Option<usize>,
) -> Option<lightcraft_codecs::Decoded> {
let jpeg = stand_in_image(bytes, covering)?;
decode_stand_in(bytes, &stand_in_image(bytes, covering)?, opts)
}
/// [`decode_raw_preview`] of the stand-in `jpeg` already found in the raw file `bytes` (by [`stand_in_image`]).
fn decode_stand_in(bytes: &[u8], jpeg: &[u8], opts: lightcraft_codecs::DecodeOptions) -> Option<lightcraft_codecs::Decoded> {
// the colour space is a property of the JPEG; a TIFF stand-in (the file itself, or a Hasselblad RGB preview
// wrapped as a TIFF) and a JPEG XL preview are read by their own decoders
let is_jpeg = jpeg.starts_with(&[0xff, 0xd8]);
@@ -43,9 +47,9 @@ pub(crate) fn decode_raw_preview(
lightcraft_raw::PreviewColorSpace::Srgb => lightcraft_codecs::NamedSpace::Srgb,
lightcraft_raw::PreviewColorSpace::AdobeRgb => lightcraft_codecs::NamedSpace::AdobeRgb,
};
lightcraft_codecs::decode_jpeg_with_fallback(&jpeg, opts, space).ok()
lightcraft_codecs::decode_jpeg_with_fallback(jpeg, opts, space).ok()
}
None => lightcraft_codecs::decode(&jpeg, opts).ok(),
None => lightcraft_codecs::decode(jpeg, opts).ok(),
}
}
@@ -80,7 +84,18 @@ pub fn load_embedded_preview(bytes: &[u8], max_edge: usize) -> Option<(Rgb32f, S
/// loupe and grid show it until the raw itself has been developed ([`crate::media::QuickJob`]). The smallest
/// embedded JPEG that covers `max_edge` is decoded, not the largest.
pub fn embedded_preview_srgb(bytes: &[u8], max_edge: usize) -> Option<lightcraft_raster::Rgba8> {
let mut d = decode_raw_preview(bytes, fit_box(max_edge), Some(max_edge))?;
// a plain sRGB camera JPEG straight to 8-bit, as the quick path decodes it (PERF-CULL-3), so
// both paths give the same picture; anything else takes the general decode
let edge = u32::try_from(max_edge).unwrap_or(u32::MAX);
// (found once: the general decode below takes the same stand-in when the fast path declines)
let jpeg = stand_in_image(bytes, Some(max_edge))?;
if lightcraft_raw::embedded_preview_color_space(bytes) != Some(lightcraft_raw::PreviewColorSpace::AdobeRgb)
&& matches!(jpeg, std::borrow::Cow::Owned(_))
&& let Ok(Some((image, orientation))) = lightcraft_codecs::decode_jpeg_srgb8_fit(&jpeg, edge, edge)
{
return Some(image.oriented(preview_orientation(bytes, orientation)));
}
let mut d = decode_stand_in(bytes, &jpeg, fit_box(max_edge))?;
if d.image.width.max(d.image.height) > max_edge {
d.image = fit(&d.image, max_edge, max_edge, Filter::Box);
d.alpha = None;
+15
View File
@@ -143,6 +143,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
as_shot_wb: None,
content_hash,
xmp: lightcraft_meta::embedded(bytes).xmp,
orientation: m.orientation,
preview_only: Some(why),
..Default::default()
});
@@ -177,6 +178,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
as_shot_wb,
content_hash,
xmp: lightcraft_meta::embedded(bytes).xmp,
orientation: Some(raw.orientation),
preview_only: None,
});
}
@@ -192,6 +194,18 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
if o.swaps_axes() {
std::mem::swap(&mut w, &mut h);
}
// regions another app drew on the photo as stored: `extract` could only tell by the size the metadata states, which
// can be missing or wrong; the header's is the size as stored, so the boxes as written are turned by it (#2674)
let mut meta = meta;
if o.swaps_axes()
&& !meta.regions.is_empty()
&& let Some(xmp) = lightcraft_meta::embedded(bytes).xmp.and_then(|x| lightcraft_meta::parse_xmp(&x).ok())
&& let Some(drawn_on) = xmp.regions_drawn_on()
&& !xmp.metadata.regions.is_empty()
{
meta.regions = xmp.metadata.regions;
lightcraft_meta::upright_regions(&mut meta.regions, drawn_on, o, (header.width, header.height));
}
let format = match ext_upper(name).as_str() {
"JPG" | "JPEG" => "JPEG".to_string(),
"" => format!("{fmt:?}").to_uppercase(),
@@ -210,6 +224,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
content_hash,
embedded_lens: None,
xmp: None,
orientation: m.orientation,
preview_only: None,
})
}
+36 -4
View File
@@ -591,7 +591,7 @@ fn cached_denoise_uses_the_same_white_balance_profile_and_orientation_as_plain_r
product::write(&path, &camera_rgb, key).unwrap();
let spec = DenoiseSpec { product: path, key: key.into(), make: None };
let (ordinary, _) = load_bytes(&bytes, 2048).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, None).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, Default::default()).unwrap();
assert_eq!(plain.data, ordinary.data, "requesting a twin must not change the ordinary path");
let cached = cached.unwrap();
assert_eq!((plain.width, plain.height), (24, 32));
@@ -1255,10 +1255,10 @@ fn exports_never_develop_a_dngs_reduced_copy() {
let mean = |img: &lightcraft_raster::Rgba8| img.data.iter().map(|p| p[1] as f64).sum::<f64>() / img.data.len().max(1) as f64;
// the loaders: only the thumbnail's develops the copy, and only when it covers the size
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, None).unwrap();
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, Default::default()).unwrap();
assert!(used, "a thumbnail develops the copy");
assert!(!load_vec_reduced(bytes.clone(), 1024, None).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512, None).unwrap();
assert!(!load_vec_reduced(bytes.clone(), 1024, Default::default()).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512, Default::default()).unwrap();
assert!(g(&copy) > 4.0 * g(&full), "the fixture's copy is much brighter: {} vs {}", g(&copy), g(&full));
let dir = std::env::temp_dir().join(format!("lc-reduced-export-{}", std::process::id()));
@@ -1844,3 +1844,35 @@ fn existing_photo_settings_are_not_rewritten() {
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
/// Issue #1632: a DNG's `ProfileToneCurve` is the finish stage's camera curve, so process V5 extends
/// it past its last point (the sensor's white, scene 1.0) with the stop roll-off as well. A curve
/// that reaches white there renders as under V4 up to it and white past it; one that ends below
/// white (here 0.9) keeps what Exposure lifts past the sensor's white apart instead of reaching
/// 8-bit 255 within a stop.
#[test]
fn v5_extends_a_dng_tone_curve_past_white_in_stops() {
use lightcraft_color::transfer::linear_to_srgb;
use lightcraft_develop::{DevelopSettings, Process};
use lightcraft_pipeline::SourceInfo;
let code = |curve: &[f64], process: Process, y: f32| {
let tone = lightcraft_raw::profile::ToneCurve::from_tag(curve).and_then(|c| super::dng_tone_curve(&c));
let info = SourceInfo { raw: true, camera_tone: Some(tone.expect("a valid curve")), ..SourceInfo::default() };
let s = DevelopSettings { process: process.version(), ..DevelopSettings::default() };
let o = lightcraft_pipeline::finish::base_tone(&s, &info, 1.0).apply(y);
(linear_to_srgb(o.clamp(0.0, 1.0)) * 255.0).round()
};
let to_white = [0.0, 0.0, 0.03, 0.09, 0.18, 0.4, 0.5, 0.78, 1.0, 1.0];
for y in [0.01, 0.05, 0.18, 0.5, 0.9] {
assert_eq!(code(&to_white, Process::V5, y), code(&to_white, Process::V4, y), "{y}");
}
for y in [1.0, 2.0, 4.0] {
assert_eq!((code(&to_white, Process::V4, y), code(&to_white, Process::V5, y)), (255.0, 255.0), "{y}");
}
let below_white = [0.0, 0.0, 0.03, 0.09, 0.18, 0.4, 0.5, 0.72, 1.0, 0.9];
let at = |process, ev: f32| code(&below_white, process, ev.exp2());
assert_eq!(at(Process::V5, 0.0), at(Process::V4, 0.0));
assert_eq!(at(Process::V4, 1.0), 255.0, "V4 is frozen");
let (white, beyond) = (at(Process::V5, 0.0), at(Process::V5, 1.0));
assert!(beyond < 254.0 && beyond - white >= 3.0, "{white} then {beyond} a stop past the sensor's white");
}
+8 -3
View File
@@ -15,7 +15,8 @@
//! 6. Apply each photo's XMP sidecar (or a raw/DNG file's embedded XMP): the sidecar wins for
//! metadata and develop settings are restored (see [`crate::sidecar`]). Its capture time fills
//! in when the file has none (read before step 5, so it also files and names the copy).
//! 7. Optionally apply a preset and add keywords (the import dialog's options).
//! 7. Optionally apply a preset, then a batch-edit recipe (one more History step), and add
//! keywords (the import dialog's options).
//! 8. Commit all new photos as one undoable op. (Undoing a move removes the catalog records;
//! the files stay at the destination — undo never moves files back over a card.)
//! 9. Copy and Move rename sequences use checked platform-sized numbers: the last number is usable once, and any
@@ -46,14 +47,18 @@ pub(crate) use commit::workers;
pub use commit::{batch_size, civil, commit_prepared, system_clock};
pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults};
pub use files::{
EXTENSIONS, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_within, is_supported, launch_deadline, launch_path, launch_path_until,
EXTENSIONS, Expansion, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_report, expand_within, is_supported, launch_deadline,
launch_path, launch_path_until,
};
pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with};
#[cfg(test)]
use job::PreparedItem;
pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with};
pub(crate) use scan::scan_files;
pub use scan::{ScanInput, ScanOutput, ScanProgress, scan, scan_with};
pub use scan::{
ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan,
scan_report, scan_with,
};
#[cfg(test)]
use scan::{library_files, library_hashes};
pub use types::{
+15
View File
@@ -253,6 +253,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
}
}
let sidecar = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default());
// the photo is upright as the file's own orientation turns it, when the file states one
let sidecar = sidecar.map(|sc| crate::sidecar::SidecarData { orientation: info.orientation.or(sc.orientation), ..sc });
// a copy is catalogued under its new name
let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone());
let mut p = Photo::new(id, Source::File { path: stored }, &name, &info.format, info.width, info.height, &now);
@@ -289,6 +291,19 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
p.edited = Some(now.clone());
p.history.push(lightcraft_catalog::HistoryStep { label, settings: d });
}
// the batch-edit recipe goes on top of everything above (sidecar, camera default,
// preset): only the controls it names change, through the same specs the sliders use
if !opts.recipe.is_empty() {
let mut d = (*p.develop).clone();
for (id, v) in &opts.recipe {
// (`ImportJob::new` refused any id `set` would not write, and `set` clamps to the range)
lightcraft_develop::controls::set(&mut d, id, *v);
}
let d = std::sync::Arc::new(d);
p.develop = d.clone();
p.edited = Some(now.clone());
p.history.push(lightcraft_catalog::HistoryStep { label: "Import adjustments".into(), settings: d });
}
report.imported.push(id.0);
p.local = opts.local;
if opts.local {
+55 -10
View File
@@ -24,6 +24,11 @@ pub fn is_supported(path: &Path) -> bool {
path.extension().is_some_and(|e| EXTENSIONS.contains(&e.to_string_lossy().to_lowercase().as_str()))
}
/// An XMP sidecar (`.xmp`, any letter case): read with its photo on import, never a photo itself.
fn is_xmp_sidecar(path: &Path) -> bool {
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp"))
}
/// The web file picker's accept list, derived from [`EXTENSIONS`]. Each extension
/// is listed in both cases: browsers' `accept` matching is case-insensitive per
/// spec, but some implementations (e.g. Windows/Edge) match case-sensitively and
@@ -78,19 +83,57 @@ pub(crate) fn expand_noting(
paths: &[String],
skip: Option<&Path>,
limits: crate::walk::Limits,
mut note: Option<crate::walk::NoteFolder>,
note: Option<crate::walk::NoteFolder>,
) -> (Vec<String>, bool) {
let mut out = Vec::new();
let mut truncated = false;
let e = expand_report_noting(paths, skip, limits, note);
(e.files, e.truncated)
}
/// What expanding import sources found, and what the walks left out ([`expand_report`]), so a
/// review can say that it did not see everything.
#[derive(Clone, Debug, Default)]
pub struct Expansion {
/// Supported files, folders walked recursively and deduplicated by path, in walk order.
pub files: Vec<String>,
/// A walk stopped at a depth or entry bound: there may be more files.
pub truncated: bool,
/// Folders whose contents couldn't be listed (permissions, a folder that vanished or went offline).
pub unreadable: usize,
/// Files found inside the folders walked that are not a supported type (see [`is_supported`]),
/// not counting XMP sidecars, which the import reads with their photos. A file named directly
/// is attempted whatever its extension and is never counted here. Both counts add up over the
/// sources, so a folder named twice (or inside another source) counts twice.
pub unsupported: usize,
}
/// [`expand_within`] keeping the walks' diagnostics. A walk that stops at a bound is logged here
/// (once per folder), as it always was.
pub fn expand_report(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits) -> Expansion {
expand_report_noting(paths, skip, limits, None)
}
/// ([`expand_report`], handing the listing of every folder that is walked to `note`, as
/// [`expand_noting`] does.)
fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, mut note: Option<crate::walk::NoteFolder>) -> Expansion {
let mut out = Expansion::default();
for p in paths {
let p = Path::new(p);
if skip.is_some_and(|s| p == s) {
continue;
}
if p.is_dir() {
// XMP sidecars are read with their photos, not skipped: they are left out of the count
let mut sidecars = 0usize;
let keep = |f: &Path| {
let keep = is_supported(f);
if !keep && is_xmp_sidecar(f) {
sidecars = sidecars.saturating_add(1);
}
keep
};
let w = match note.as_mut() {
Some(note) => crate::walk::files_in_noting(p, skip, limits, is_supported, &mut **note),
None => crate::walk::files_in(p, skip, limits, is_supported),
Some(note) => crate::walk::files_in_noting(p, skip, limits, keep, &mut **note),
None => crate::walk::files_in(p, skip, limits, keep),
};
if w.truncated {
log::warn!(
@@ -101,16 +144,18 @@ pub(crate) fn expand_noting(
limits.max_depth
);
}
truncated |= w.truncated;
out.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string()));
out.truncated |= w.truncated;
out.unreadable = out.unreadable.saturating_add(w.unreadable);
out.unsupported = out.unsupported.saturating_add(w.skipped.saturating_sub(sidecars));
out.files.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string()));
} else {
// explicitly named files are attempted even with an unknown extension (sniffed)
out.push(p.to_string_lossy().to_string());
out.files.push(p.to_string_lossy().to_string());
}
}
let mut seen = std::collections::HashSet::new();
out.retain(|p| seen.insert(p.clone()));
(out, truncated)
out.files.retain(|p| seen.insert(p.clone()));
out
}
/// What a path given on the command line at launch becomes ([`launch_path`]).
+4
View File
@@ -163,6 +163,8 @@ impl ImportJob {
/// Snapshot what an import with `opts` needs from the session (no file-system calls). Takes
/// the probes a preceding scan left ([`Session::import_probes`]).
pub fn new(s: &mut Session, opts: ImportOptions) -> crate::Result<Self> {
// a recipe is checked before any file is read or placed, not when the photos are committed
crate::cmd::check_recipe(&opts.recipe).map_err(|e| crate::cmd::bad("library.import", e))?;
let mode = opts.mode;
// Only a library on disk has an `Originals/` folder. The browser build keeps the bytes of
// every added file in its own storage already, so "copy" there means "add".
@@ -528,6 +530,8 @@ impl Session {
key,
cached: Vec::new(),
embedded,
embedded_cache: None,
embedded_on_disk: false,
minimum_embedded_edge,
small: Some(Box::new(small)),
})
+206 -8
View File
@@ -1,4 +1,4 @@
use super::files::{Seen, expand, probe_all, reusable_probes};
use super::files::{Seen, expand, expand_report, is_supported, probe_all, reusable_probes};
use super::types::ImportCandidate;
use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source};
@@ -77,6 +77,12 @@ pub struct ScanProgress {
pub struct ScanOutput {
pub candidates: Vec<ImportCandidate>,
pub probes: HashMap<String, ProbeInfo>,
/// A folder walk stopped at a depth or entry bound: there may be more photos ([`Expansion`]).
pub truncated: bool,
/// Folders whose contents couldn't be listed.
pub unreadable: usize,
/// Files inside the folders that are not a supported photo type (XMP sidecars not counted).
pub unsupported: usize,
}
impl ScanInput {
@@ -98,26 +104,217 @@ impl ScanInput {
pub(crate) fn library(&self) -> std::sync::Arc<lightcraft_catalog::Catalog> {
std::sync::Arc::clone(&self.library)
}
/// The probes of earlier scans this input took from the session ([`ScanInput::new`]), to hand back with a
/// scan's output that probes nothing itself (browsing), so a later import doesn't read those files again.
pub fn take_probes(&mut self) -> HashMap<String, ProbeInfo> {
std::mem::take(&mut self.cache)
}
}
/// What browsing a folder (Local) has to read: the files of `files` the library has no photo at,
/// in the order the view will show them (see [`browse_order`]). Unlike [`scan_with`] nothing is
/// read, so the import that follows adds the photos batch by batch as it reads them, and the first
/// screen of a 3,000-raw wedding shows within a second instead of after every file was read
/// (measured on 2,933 EOS R5 C CR3s: 30.6 s to the first photo before).
pub fn browse_queue(input: &ScanInput, files: Vec<String>, sort: &lightcraft_catalog::Sort) -> Vec<String> {
browse_queue_until(input, files, sort, &std::sync::atomic::AtomicBool::new(false)).unwrap_or_default()
}
/// [`browse_queue`] that stops reading the files' times or sizes once `cancel` is set (another folder was
/// chosen): `None` then.
pub fn browse_queue_until(
input: &ScanInput,
files: Vec<String>,
sort: &lightcraft_catalog::Sort,
cancel: &std::sync::atomic::AtomicBool,
) -> Option<Vec<String>> {
let known = library_files(&input.library, &files);
let mut files: Vec<String> = files.into_iter().filter(|f| !known.contains_key(Path::new(f))).collect();
browse_order_until(&mut files, sort, cancel).then_some(files)
}
/// The files browsing `root` (Local) lists: the supported, non-hidden files in it, or below it
/// with `subfolders`, never inside the library's own folder (as [`scan_with`] skips it).
///
/// A folder that can't be listed whole (gone, no access, a network share dropping out) is an
/// error, not an empty or partial listing: the browse bookkeeping would take the files missing
/// from it for files gone. (With `subfolders` the walk skips the folders below it that it can't
/// read, as the import's scan does.)
pub fn browse_files(input: &ScanInput, root: &str, subfolders: bool) -> std::io::Result<Vec<String>> {
// one spelling for the folder, and so for its files: `lib/../outside` lists `outside`'s files as
// the catalog stores them, not as new photos under another name
let root_path = browse_path(Path::new(root))?;
let root = root_path.to_string_lossy().to_string();
// the library's folder itself, or a folder inside it: nothing to browse
if input.skip.as_deref().is_some_and(|lib| inside(&root_path, lib)) {
return Ok(Vec::new());
}
if subfolders {
// (the root itself must be there to be walked)
std::fs::read_dir(&root)?;
return Ok(expand(&[root], input.skip.as_deref()));
}
let mut v = Vec::new();
for entry in std::fs::read_dir(&root)? {
let entry = entry?;
if crate::walk::is_hidden_entry(&entry) {
continue;
}
let f = entry.path();
if f.is_file() && is_supported(&f) {
v.push(f.to_string_lossy().to_string());
}
}
v.sort();
Ok(v)
}
/// The folder `path` names, as one spelling for the view, its listing and the catalog's records:
/// absolute (`.` is the current folder), with `.` and `..` taken out the way the system reads them.
/// Windows takes `..` out by name; elsewhere `link/..` is the folder above where the link points,
/// so a link before a `..` is resolved first. Everything else keeps its spelling (a mapped drive
/// stays a drive letter, a link not followed by `..` stays the link), as the records were made.
///
/// It may read the disk (a link on a stalled network mount can block it): call it off the UI thread.
/// [`browse_spelling`] is the UI's spelling meanwhile.
pub fn browse_path(path: &Path) -> std::io::Result<PathBuf> {
normalized(path, true)
}
/// [`browse_path`] without reading the disk: `.` and `..` taken out by name. What the view shows
/// until the worker has resolved the folder; the same folder unless a link comes before a `..`
/// (not on Windows, which takes `..` out by name too).
pub fn browse_spelling(path: &Path) -> std::io::Result<PathBuf> {
normalized(path, false)
}
fn normalized(path: &Path, resolve_links: bool) -> std::io::Result<PathBuf> {
use std::path::Component;
// (no disk access: the current folder is the process's)
let path = std::path::absolute(path)?;
let mut out = PathBuf::new();
for c in path.components() {
match c {
Component::CurDir => {}
Component::ParentDir => {
// a link before `..` is left through where it points; a broken one is an error, not
// its parent folder by name (CodeRabbit on #3577)
#[cfg(not(windows))]
if resolve_links && std::fs::symlink_metadata(&out).is_ok_and(|m| m.file_type().is_symlink()) {
out = std::fs::canonicalize(&out)?;
}
#[cfg(windows)]
let _ = resolve_links;
// (above the root: still the root)
if matches!(out.components().next_back(), Some(Component::Normal(_))) {
out.pop();
}
}
c => out.push(c.as_os_str()),
}
}
Ok(out)
}
/// Whether `root` (a [`browse_path`]) is `lib` or a folder inside it: as written, or once both are
/// resolved (a symlink to the library names the same folder), as the recursive walk tells. A root
/// that can't be resolved (gone, or a network share that won't say) is compared as written when it
/// is there; one that isn't there is not inside, and listing it reports why.
fn inside(root: &Path, lib: &Path) -> bool {
let as_written = || root.starts_with(browse_path(lib).unwrap_or_else(|_| lib.to_path_buf()));
match std::fs::canonicalize(root) {
Ok(resolved) => as_written() || std::fs::canonicalize(lib).is_ok_and(|lib| resolved.starts_with(lib)),
Err(_) => root.exists() && as_written(),
}
}
/// Order `files` the way a view sorted by `sort` will show them, as far as the file system can
/// tell before the files are read: by modification time for the capture date (a camera's file
/// time is its capture time, near enough to fill the first screen first), by name, or by size.
/// New photos share one import time and have no edit time, so the import- and edit-date sorts
/// show them by name. Ties go by name in the view's direction, as the catalog breaks them
/// ([`lightcraft_catalog::Sort::order`]); new photos tie on rating too. Random keeps the given order. Files whose
/// time or size can't be read go last.
pub fn browse_order(files: &mut [String], sort: &lightcraft_catalog::Sort) {
browse_order_until(files, sort, &std::sync::atomic::AtomicBool::new(false));
}
/// [`browse_order`] that stops reading the files' times or sizes once `cancel` is set: `false` then, and
/// `files` is left as it was.
fn browse_order_until(files: &mut [String], sort: &lightcraft_catalog::Sort, cancel: &std::sync::atomic::AtomicBool) -> bool {
use lightcraft_catalog::SortKey;
use lightcraft_catalog::query::cmp_name;
use std::cmp::Ordering;
use std::sync::atomic::Ordering::Relaxed;
let asc = sort.ascending;
let name = |f: &str| Path::new(f).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let directed = |o: Ordering| if asc { o } else { o.reverse() };
// `key` per file (`None`: unreadable, last in either direction), then the name, in the view's direction
let by_key = |files: &mut [String], key: &dyn Fn(&str) -> Option<u64>| {
let mut keyed: Vec<(Option<u64>, String, String)> = Vec::with_capacity(files.len());
for f in files.iter() {
if cancel.load(Relaxed) {
return false;
}
keyed.push((key(f), name(f), f.clone()));
}
keyed.sort_by(|a, b| match (a.0, b.0) {
(Some(x), Some(y)) => directed(x.cmp(&y).then_with(|| cmp_name(&a.1, &b.1))),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => directed(cmp_name(&a.1, &b.1)),
});
for (slot, (_, _, f)) in files.iter_mut().zip(keyed) {
*slot = f;
}
true
};
match sort.key {
SortKey::CaptureDate => by_key(files, &|f| {
let t = std::fs::metadata(f).and_then(|m| m.modified()).ok()?;
// (nanoseconds since the epoch fit a u64 until 2554; earlier times count as the epoch)
Some(t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX)))
}),
SortKey::ImportDate | SortKey::EditDate | SortKey::Rating | SortKey::FileName => {
files.sort_by(|a, b| directed(cmp_name(&name(a), &name(b))));
!cancel.load(Relaxed)
}
SortKey::FileSize => by_key(files, &|f| std::fs::metadata(f).ok().map(|m| m.len())),
SortKey::Random => !cancel.load(Relaxed),
}
}
/// Find and probe what importing `paths` would add, marking duplicates (by path, or by content
/// against the library and earlier candidates). Nothing is added; the probes are kept for the
/// import that follows.
pub fn scan(s: &mut Session, paths: &[String]) -> Vec<ImportCandidate> {
scan_report(s, paths).candidates
}
/// [`scan`] keeping what the walks left out. The probes are already kept in the session for the
/// import that follows, so `probes` of the output is empty.
pub fn scan_report(s: &mut Session, paths: &[String]) -> ScanOutput {
let (input, paths) = ScanInput::new(s, paths);
let out = scan_with(input, &paths, &ScanProgress::default());
s.import_probes = out.probes;
out.candidates
let mut out = scan_with(input, &paths, &ScanProgress::default());
s.import_probes = std::mem::take(&mut out.probes);
out
}
/// [`scan`] without the session, so it can run on a worker thread. Stops early (returning what it
/// has) when `progress.cancel` is set.
pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput {
let files = expand(paths, input.skip.as_deref());
scan_files(input, files, progress)
let expansion = expand_report(paths, input.skip.as_deref(), crate::walk::Limits::default());
let mut out = scan_files(input, expansion.files, progress);
out.truncated = expansion.truncated;
out.unreadable = expansion.unreadable;
out.unsupported = expansion.unsupported;
out
}
/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]).
/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]). The walks'
/// diagnostics ([`ScanOutput::truncated`] and friends) are left empty: who expanded the paths has
/// them ([`expand_report`]).
pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &ScanProgress) -> ScanOutput {
use std::sync::atomic::Ordering::Relaxed;
let by_path = library_files(&input.library, &files);
@@ -178,5 +375,6 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &Sc
}
out.push(c);
}
ScanOutput { candidates: out, probes: kept }
// (the walks' diagnostics are [`scan_with`]'s: these files were found already)
ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0 }
}
+10
View File
@@ -67,6 +67,16 @@ pub struct ImportOptions {
pub metadata_preset: Option<String>,
/// Copy: raws are copied as DNG (Copy as DNG).
pub convert_dng: bool,
/// A batch-edit recipe: develop control id / value pairs (e.g. `light.exposure` → 0.5),
/// applied to every imported photo *after* its XMP sidecar, camera default and import preset,
/// as one more History step (`Import adjustments`). Only the named controls change; the recipe
/// is a snapshot taken when the import starts, so editing a preset afterwards cannot change it.
/// It names plain adjustments only (no white balance, geometry or crop: `cmd::check_recipe`),
/// and [`ImportJob::new`] refuses anything else.
/// Empty (the default) = no recipe. A photo the library already has keeps its own settings:
/// one skipped as a duplicate, restored from Recently Deleted, or joined from a browsed
/// folder (Local) is never touched, as the preset and keywords never are.
pub recipe: Vec<(String, f64)>,
}
/// How copies are filed in the destination. The date is the capture time, else the time of the
+44
View File
@@ -113,6 +113,12 @@ fn load(dir: &Path, downloaded: bool) -> Option<Arc<LensDb>> {
}
match LensDb::load_dir(dir) {
Ok((db, errors)) => {
let n_files = std::fs::read_dir(dir)
.map(|rd| {
rd.filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("xml"))).count()
})
.unwrap_or(0);
log::info!("lens database: {files} files, {profiles} profiles", files = n_files, profiles = db.lenses.len());
for (file, e) in errors {
log::warn!("lens database: skipped {file}: {e}");
}
@@ -335,6 +341,44 @@ mod tests {
}
}
/// The database that was found is reported: how many files it holds and how many profiles they carry, so a
/// directory that was pointed at but holds nothing (or holds profiles that never match a photo) is visible in
/// the log instead of passing unnoticed. The database is read from the environment and kept for the process,
/// so the check runs in a child process of this test binary.
#[test]
fn lens_database_summary_reports_files_and_profiles() {
let dir = std::env::temp_dir().join(format!("lc-lens-summary-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("one.xml"), DB).unwrap();
std::fs::write(dir.join("two.xml"), DB.replace("Testcam 18-55mm f/3.5-5.6", "Testcam 24-70mm f/2.8")).unwrap();
let exe = std::env::current_exe().unwrap();
let out = std::process::Command::new(exe)
.args(["--exact", "lens_profiles::tests::lens_database_summary_child", "--ignored", "--test-threads=1", "--nocapture"])
.env(ENV, &dir)
.env("LIGHTCRAFT_LOG", "trace")
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
let _ = std::fs::remove_dir_all(&dir);
assert!(out.status.success(), "the child process failed: {stderr}");
let logged: Vec<&str> = stderr.lines().filter(|l| l.starts_with("lightcraft: ")).collect();
assert!(!logged.is_empty(), "the database was read without a word in the log: {stderr}");
let summary = logged.iter().find(|l| l.contains("lens database:")).expect("the lens database summary line was not logged");
let mut counts = summary.split_whitespace().filter_map(|t| t.trim_end_matches(',').parse::<usize>().ok());
assert_eq!(counts.next(), Some(2), "expected 2 files in the lens database summary: {summary}");
assert_eq!(counts.next(), Some(2), "expected 2 profiles in the lens database summary: {summary}");
}
/// Run by [`lens_database_summary_reports_files_and_profiles`] in a child process: read the database the
/// environment points at, so its summary reaches the log the parent reads.
#[test]
#[ignore = "helper process for lens_database_summary_reports_files_and_profiles"]
fn lens_database_summary_child() {
crate::logging::install("lightcraft");
let _ = database();
}
/// A synthetic grid recorded through the profile's barrel distortion comes out of the pipeline's geometry
/// stage with straight lines.
#[test]
+2
View File
@@ -608,6 +608,7 @@ mod tests {
let _ = std::fs::remove_file(beside(&dir, LOCK));
}
#[allow(clippy::unwrap_used)]
fn scratch(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("lc-lensfun-{name}-{}", std::process::id()));
for leftover in [d.clone(), beside(&d, STAGING), beside(&d, PREVIOUS)] {
@@ -618,6 +619,7 @@ mod tests {
}
/// A local server answering `GET /db/<name>` with that file's body (404 otherwise).
#[allow(clippy::unwrap_used)]
fn serve(files: Vec<(&'static str, Vec<u8>)>) -> String {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/db", l.local_addr().unwrap());
+17 -2
View File
@@ -9,6 +9,7 @@
//! of decoded source proxies. Rendering is done by [`RenderJob`]s that are `Send` so frontends can
//! run them off the UI thread.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
// Model/cache types remain available without linking the optional inference crate.
#[cfg(not(feature = "denoise"))]
@@ -28,6 +29,7 @@ pub mod crs_masks;
pub mod demo;
pub mod denoise;
pub mod devices;
pub mod disk_space;
pub mod display;
pub mod doc_path;
mod errors;
@@ -61,6 +63,7 @@ mod model_download;
pub mod open_path;
pub mod originals;
mod pdf;
pub mod prep;
pub mod preset_import;
pub mod preset_luminar;
pub mod presets;
@@ -401,10 +404,18 @@ pub struct Session {
pub slideshow_export: Option<std::sync::Arc<slideshow_export::ExportRun>>,
/// The last (or running) Build Previews.
pub preview_build: Option<std::sync::Arc<cmd::previews::PreviewBuild>>,
/// Preparing photos in the background: settings (app-wide and this library's) and the build
/// it runs ([`prep`]).
pub prep: prep::PrepState,
/// The long edge (px) the loupe renders at on this screen, as the frontend last said
/// (0: not known). Standard previews are built at least this big, so the loupe can use them.
pub loupe_edge: usize,
/// Develop defaults applied on import (persisted in prefs.json).
pub import_defaults: import::ImportDefaults,
/// Disk budget of the library's thumbnail cache in MB (0 = default; persisted in prefs.json).
pub cache_mb: u32,
/// The once-per-session alert for a drive running low under the preview cache ([`disk_space`]).
pub(crate) disk_alert: disk_space::DiskAlertState,
/// Slideshow playback settings (`slideshow.playback`; persisted in prefs.json).
pub slideshow: slideshow::PlaybackSettings,
/// Slideshow slide layout: Layout, Options and Backdrop (`slideshow.layout`; persisted in
@@ -541,9 +552,12 @@ impl Session {
folder_changes: None,
activity: Default::default(),
preview_build: None,
prep: Default::default(),
loupe_edge: 0,
slideshow_export: None,
import_defaults: import::ImportDefaults::default(),
cache_mb: 0,
disk_alert: Default::default(),
slideshow: slideshow::PlaybackSettings::default(),
slide_layout: slide::SlideSettings::default(),
slide_overlays: slide_overlay::OverlaySettings::default(),
@@ -1007,8 +1021,9 @@ impl Session {
return Vec::new();
}
let Some(old) = self.develop_of(id) else { return Vec::new() };
let mut old_json = old.to_json();
let mut new_json = new.to_json();
// (Remove Hot Pixels, omitted when off, is stated: switching it off is a change)
let mut old_json = old.to_json_for_merge();
let mut new_json = new.to_json_for_merge();
// False is omitted from stored profile JSON. Keep it explicit for this comparison so
// switching camera local tone mapping off is a change without copying untouched values.
old_json["profile"]["camera_local_tone"] = Value::Bool(old.profile.camera_local_tone);
+46 -2
View File
@@ -258,6 +258,13 @@ impl Library {
}
}
/// [`PrefsFile`]'s `prep`, read leniently (see there).
fn lenient_prep<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Option<crate::prep::PrepSettings>, D::Error> {
use serde::Deserialize;
let value = serde_json::Value::deserialize(d)?;
Ok(serde_json::from_value(value).ok())
}
#[derive(Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct PrefsFile {
@@ -297,6 +304,11 @@ struct PrefsFile {
import: crate::import::ImportDefaults,
/// Thumbnail disk cache budget (MB, 0 = default).
cache_mb: u32,
/// This library's own background preparation settings (`None`: the app-wide ones). Read
/// leniently: a value a newer build wrote that this one doesn't know is `None`, and the rest of
/// the file is kept.
#[serde(skip_serializing_if = "Option::is_none", deserialize_with = "lenient_prep")]
prep: Option<crate::prep::PrepSettings>,
/// Folder for smart previews (default: `Smart Previews` in the library).
smart_previews_dir: Option<String>,
/// Days after which untouched Local records of unbrowsed folders are forgotten (missing =
@@ -571,6 +583,9 @@ impl Session {
self.last_export = prefs.last_export;
self.last_merge = prefs.last_merge;
self.export_presets = prefs.export_presets;
// a user preset whose name shadows a built-in one could never be selected or exported
// (the built-ins are looked up first); it gets a name of its own instead
self.rename_shadowing_export_presets();
self.print_templates = prefs.print_templates;
self.print_template_folders = prefs.print_template_folders;
crate::print::template::tidy_folders(&mut self.print_template_folders, &mut self.print_templates);
@@ -589,6 +604,7 @@ impl Session {
self.recent_keywords = prefs.recent_keywords;
self.import_defaults = prefs.import;
self.cache_mb = prefs.cache_mb;
self.prep.library = prefs.prep.map(crate::prep::PrepSettings::sanitized);
self.slideshow = prefs.slideshow.sanitized();
self.slide_layout = prefs.slide_layout.sanitized();
self.slide_overlays = prefs.slide_overlays.sanitized();
@@ -692,6 +708,9 @@ impl Session {
crate::cmd::previews::refresh_stale_smart_previews(self);
}
self.library_identity = std::sync::Arc::new(());
// a library open is a new session for the low-disk alert: look at the drive now
self.disk_alert.reset();
self.check_disk_space(true);
Ok(())
}
@@ -905,6 +924,7 @@ impl Session {
recent_keywords: self.recent_keywords.clone(),
import: self.import_defaults.clone(),
cache_mb: self.cache_mb,
prep: self.prep.library,
smart_previews_dir: self.smart_previews_dir.as_ref().map(|d| d.to_string_lossy().to_string()),
forget_local_days: Some(self.forget_local_days),
slideshow: self.slideshow.clone(),
@@ -932,9 +952,23 @@ impl Session {
new
}
/// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default).
/// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default, which
/// grows with the library: [`crate::media::default_disk_cache_bytes`]).
pub fn cache_bytes(&self) -> u64 {
if self.cache_mb == 0 { crate::media::DISK_CACHE_BYTES } else { u64::from(self.cache_mb) << 20 }
if self.cache_mb == 0 { crate::media::default_disk_cache_bytes(self.catalog.len()) } else { u64::from(self.cache_mb) << 20 }
}
/// Bring the disk cache's budget up to date with the library (photos were added since it was
/// set): cheap, nothing is read or written. Called before previews are built, so it also
/// looks at the drive's free space when that is due ([`Session::check_disk_space`]).
pub fn fit_disk_cache(&mut self) {
let want = self.cache_bytes();
if let Some(d) = self.media.rendered.disk()
&& d.budget() != want
{
d.set_budget(want);
}
self.check_disk_space(false);
}
/// Change the thumbnail disk cache budget (MB, 0 = default) in place: the cached thumbnails
@@ -996,6 +1030,16 @@ fn unlocked_warning(lock: Option<&LibraryLock>) -> Option<String> {
mod resolve_tests {
use super::*;
/// A library's background preparation value this build doesn't know reads as none (the
/// app-wide settings apply) and keeps the rest of `prefs.json`.
#[test]
fn an_unknown_background_preparation_value_keeps_the_other_prefs() {
let v = serde_json::json!({"cacheMb": 77, "prep": {"culling": {"scope": "someday"}}});
let read: PrefsFile = serde_json::from_value(v).unwrap();
assert!(read.prep.is_none());
assert_eq!(read.cache_mb, 77);
}
/// `--library <dir>/catalog.snap` failed with the OS's "File exists" (creating a folder over
/// the file); it opens the library that file belongs to.
#[test]
+122 -10
View File
@@ -937,6 +937,35 @@ pub(crate) struct ApplyPrepared<'a> {
pub(crate) undo0: usize,
}
/// The catalog's collections with each id once, in catalog order. A row repeated as it is drops quietly; a different
/// collection with an id an earlier one has is left out with a warning naming both, since two albums can't have one id
/// (#1588: one bad Lightroom record costs that record, not the import). The photos listed under the id go to the first.
fn first_of_each_collection<'a>(data: &'a CatalogImport, warnings: &mut Vec<String>) -> Vec<&'a Row> {
let mut first: HashMap<i64, &Row> = HashMap::new();
let mut rows = Vec::new();
for collection in &data.collections {
let id = number(collection, "id_local");
let Some(kept) = first.get(&id) else {
first.insert(id, collection);
rows.push(collection);
continue;
};
if *kept != collection {
let photos = if data.members.iter().any(|m| number(m, "collection") == id) {
format!("; the photos listed under that id go to “{}”", text(kept, "name"))
} else {
String::new()
};
warnings.push(format!(
"collection “{}”: not imported, it has the id of collection “{}”{photos}",
text(collection, "name"),
text(kept, "name")
));
}
}
rows
}
fn stage_collections(
s: &mut crate::Session,
data: &CatalogImport,
@@ -944,24 +973,42 @@ fn stage_collections(
ids: &HashMap<i64, PhotoId>,
ops: &mut Vec<Op>,
warnings: &mut Vec<String>,
) -> usize {
) -> crate::Result<usize> {
let rows = first_of_each_collection(data, warnings);
let mut albums = HashMap::new();
for collection in &data.collections {
// Two collections never share an album. An index that names one album for two gives the second a new one; the
// counter saturates, so a damaged one hands out an id that's taken, and that stops the import instead.
let mut assigned = HashSet::new();
for &collection in &rows {
if number(collection, "systemOnly") != 0 {
continue;
}
let collection_key = format!("{}:{}", key(&data.source), number(collection, "id_local"));
let id = index
let indexed = index
.collections
.get(&collection_key)
.copied()
.map(lightcraft_catalog::AlbumId)
.filter(|id| s.catalog.album(*id).is_some())
.unwrap_or_else(|| s.catalog.alloc_album_id());
.filter(|id| s.catalog.album(*id).is_some() && !assigned.contains(id));
let id = match indexed {
Some(id) => id,
None => {
let id = s.catalog.alloc_album_id();
if s.catalog.album(id).is_some() || assigned.contains(&id) {
return Err(error(format!(
"collection “{}”: the library has no unused album id left for it (its album numbering is exhausted or damaged)",
text(collection, "name")
)));
}
id
}
};
assigned.insert(id);
index.collections.insert(collection_key, id.0);
albums.insert(number(collection, "id_local"), id);
}
let parents: HashMap<_, _> = data.collections.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect();
let parents: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect();
let collections: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), *r)).collect();
let mut grouped_members: HashMap<i64, Vec<&Row>> = HashMap::new();
for member in &data.members {
grouped_members.entry(number(member, "collection")).or_default().push(member);
@@ -969,7 +1016,7 @@ fn stage_collections(
for members in grouped_members.values_mut() {
members.sort_by(|a, b| text(a, "positionInCollection").cmp(text(b, "positionInCollection")));
}
let mut ordered: Vec<_> = data.collections.iter().collect();
let mut ordered = rows.clone();
ordered.sort_by_key(|r| {
let mut depth = 0;
let mut at = number(r, "parent");
@@ -979,10 +1026,19 @@ fn stage_collections(
}
depth
});
// Collections whose albums are folders: a collection set, or an earlier import's album when it is a folder.
let sets: HashSet<i64> = albums
.iter()
.filter(|(lr, id)| match s.catalog.album(**id) {
Some(album) => album.folder,
None => collections.get(*lr).is_some_and(|r| text(r, "creationId").contains("group")),
})
.map(|(lr, _)| *lr)
.collect();
let mut added_folders = HashSet::new();
for collection in ordered {
let Some(id) = albums.get(&number(collection, "id_local")).copied() else { continue };
let mut album = Album::new(id, text(collection, "name"));
album.parent = albums.get(&number(collection, "parent")).copied();
album.folder = text(collection, "creationId").contains("group");
if text(collection, "creationId").contains("smart") {
warnings.push(format!("{}: smart rules preserved in archive; imported current membership", album.name));
@@ -1008,10 +1064,49 @@ fn stage_collections(
ops.push(Op::SetAlbumPhotos { id, photos });
}
} else {
let (set, moved) = collection_parent(collection, &collections, &sets);
album.parent = set.and_then(|set| albums.get(&set).copied());
// `AddAlbum` rejects a parent that isn't a folder yet, and that would roll back the whole batch: every
// album and every catalog-only photo. `collection_parent` already prevents it; this keeps a bug there
// (or a cycle `validate` missed) from doing so.
if let Some(parent) = album.parent
&& !added_folders.contains(&parent)
&& !s.catalog.album(parent).is_some_and(|a| a.folder)
{
album.parent = None;
warnings.push(format!(
"{}: its collection set could not be created first; imported at the top level (Lightroom collection {})",
album.name,
number(collection, "id_local")
));
} else if moved {
let lr_parent = number(collection, "parent");
let why = match collections.get(&lr_parent) {
None => "its parent collection isn't in the catalog".to_string(),
Some(r) => match albums.get(&lr_parent).and_then(|id| s.catalog.album(*id)) {
// a set imported earlier whose album is no longer a folder
Some(a) if text(r, "creationId").contains("group") => {
format!("its collection set “{}” is the album “{}” in this library, which isn't a folder", text(r, "name"), a.name)
}
_ => format!("Lightroom keeps it inside “{}”, which isn't a collection set", text(r, "name")),
},
};
// the set's name in this library: the user may have renamed it since an earlier import
let to = match (album.parent.and_then(|id| s.catalog.album(id)), set.and_then(|set| collections.get(&set))) {
(Some(a), _) => format!("into “{}”", a.name),
(None, Some(r)) => format!("into “{}”", text(r, "name")),
(None, None) => "at the top level".to_string(),
};
// the Lightroom id tells apart collections that share a name (#2165)
warnings.push(format!("{}: {why}; imported {to} (Lightroom collection {})", album.name, number(collection, "id_local")));
}
if album.folder {
added_folders.insert(id);
}
ops.push(Op::AddAlbum { album });
}
}
albums.len()
Ok(albums.len())
}
/// Turn the read catalog into library records in one undo step and return the import report
@@ -1240,7 +1335,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
}
by_path.entry(key(&src.path)).or_insert(photo_id);
}
let album_count = stage_collections(s, &data, index, &ids, &mut ops, &mut warnings);
let album_count = stage_collections(s, &data, index, &ids, &mut ops, &mut warnings)?;
if !ops.is_empty() {
s.commit("Import Lightroom Catalog", Op::Batch { ops })?;
}
@@ -1251,5 +1346,22 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
})
}
/// The collection set a Lightroom collection's album goes into (`None`: the top level), and whether that isn't its
/// Lightroom parent. A LightCraft album nests only in a folder, but Lightroom also keeps a print, book, slideshow or
/// web gallery (or, in an odd catalog, a collection) inside a plain or smart collection, and a parent can be
/// system-only (not imported) or gone from the catalog. Such an album joins the nearest collection set above it.
fn collection_parent(collection: &Row, collections: &HashMap<i64, &Row>, sets: &HashSet<i64>) -> (Option<i64>, bool) {
let mut at = number(collection, "parent");
let mut seen = HashSet::from([number(collection, "id_local")]);
while at != 0 && !sets.contains(&at) {
// `validate` rejects cycles and deep chains; stop at the top level if one got here anyway.
if seen.len() > 64 || !seen.insert(at) {
return (None, true);
}
at = collections.get(&at).map_or(0, |r| number(r, "parent"));
}
((at != 0).then_some(at), at != number(collection, "parent"))
}
#[cfg(test)]
mod tests;
+250 -1
View File
@@ -405,6 +405,255 @@ fn a_reimport_counts_each_trashed_match_once() {
assert_eq!(r["imported"], 0, "{r}");
assert!(ids.iter().all(|id| s.catalog.photo(*id).unwrap().deleted));
}
/// The import report's warnings about `album`.
fn warnings_naming(r: &Value, album: &str) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.starts_with(&format!("{album}:"))).map(String::from).collect()
}
fn album_named<'a>(s: &'a crate::Session, name: &str) -> &'a lightcraft_catalog::Album {
s.catalog.albums().find(|a| a.name == name).unwrap_or_else(|| panic!("no album {name}"))
}
/// A LightCraft album nests only in a folder. A collection Lightroom keeps inside a plain collection used to fail the
/// whole batch with "parent must be an existing folder", taking every album with it (#2165, #2532).
#[test]
fn a_collection_inside_a_plain_collection_joins_the_set_above_it() {
let mut s = crate::Session::new();
let mut data = sample();
data.collections.push(row(json!({"id_local":11,"parent":10,"name":"Picks","creationId":"com.adobe.ag.library.collection"})));
data.members.push(row(json!({"collection":11,"image":1,"positionInCollection":"a"})));
let r = apply(&mut s, data, false).unwrap();
assert_eq!(r["collections"], 3);
assert_eq!(s.catalog.photos().count(), 2);
let travel = album_named(&s, "Travel").id;
assert_eq!(album_named(&s, "Keepers").parent, Some(travel));
assert_eq!(album_named(&s, "Keepers").photos.len(), 2);
assert_eq!(album_named(&s, "Picks").parent, Some(travel));
assert_eq!(album_named(&s, "Picks").photos.len(), 1);
let w = warnings_naming(&r, "Picks");
assert_eq!(w.len(), 1, "{w:?}");
assert!(w[0].contains("Keepers") && w[0].contains("into “Travel”"), "{w:?}");
assert!(warnings_naming(&r, "Keepers").is_empty());
}
/// Lightroom Classic saves a print, book, slideshow or web gallery inside a collection; with no set above it, the
/// creation lands at the top level.
#[test]
fn a_creation_saved_inside_a_top_level_collection_lands_at_the_top_level() {
let mut s = crate::Session::new();
let mut data = sample();
data.collections.push(row(json!({"id_local":12,"name":"Loose","creationId":"com.adobe.ag.library.collection"})));
data.collections.push(row(json!({"id_local":13,"parent":12,"name":"Poster","creationId":"com.adobe.ag.print"})));
data.collections.push(row(json!({"id_local":14,"parent":10,"name":"Album Book","creationId":"com.adobe.ag.layout.book"})));
data.members.push(row(json!({"collection":13,"image":1,"positionInCollection":"a"})));
let r = apply(&mut s, data, false).unwrap();
assert_eq!(r["collections"], 5);
let poster = album_named(&s, "Poster");
assert_eq!((poster.parent, poster.folder, poster.photos.len()), (None, false, 1));
assert_eq!(album_named(&s, "Album Book").parent, Some(album_named(&s, "Travel").id));
let w = warnings_naming(&r, "Poster");
assert!(w.len() == 1 && w[0].contains("Loose") && w[0].contains("at the top level"), "{w:?}");
assert_eq!(warnings_naming(&r, "Album Book").len(), 1);
assert_eq!(album_named(&s, "Keepers").photos.len(), 2);
}
/// A parent that's gone from the catalog or system-only (Quick Collection, an unsaved print…) isn't imported; the
/// album lands at the top level, and the report says why it isn't where Lightroom had it.
#[test]
fn a_collection_whose_parent_is_missing_or_system_only_lands_at_the_top_level_with_a_warning() {
let mut s = crate::Session::new();
let mut data = sample();
data.collections.push(row(json!({"id_local":11,"parent":99,"name":"Orphan","creationId":"com.adobe.ag.library.collection"})));
data.collections.push(row(json!({"id_local":5,"name":"quick collection","creationId":"com.adobe.ag.library.collection","systemOnly":1})));
data.collections.push(row(json!({"id_local":12,"parent":5,"name":"Stray","creationId":"com.adobe.ag.print"})));
let r = apply(&mut s, data, false).unwrap();
assert_eq!(r["collections"], 4);
assert_eq!(album_named(&s, "Orphan").parent, None);
assert_eq!(album_named(&s, "Stray").parent, None);
assert!(s.catalog.albums().all(|a| a.name != "quick collection"));
let w = warnings_naming(&r, "Orphan");
assert!(w.len() == 1 && w[0].contains("isn't in the catalog"), "{w:?}");
let w = warnings_naming(&r, "Stray");
assert!(w.len() == 1 && w[0].contains("quick collection") && w[0].contains("at the top level"), "{w:?}");
assert_eq!(album_named(&s, "Keepers").parent, Some(album_named(&s, "Travel").id));
}
/// Imports `data` keeping `index` between imports, as a library on disk does.
fn import_indexed(s: &mut crate::Session, data: CatalogImport, index: &mut ImportIndex) -> crate::Result<Value> {
let undo0 = s.undo.len();
let missing_sources = HashSet::new();
let context =
ApplyPrepared { update_existing: false, files: Default::default(), index, archive_path: None, missing_sources: &missing_sources, undo0 };
apply_prepared(s, data, context).map(|applied| applied.report)
}
/// The sample with “Picks”, a collection Lightroom keeps inside the plain collection “Keepers”.
fn with_picks() -> CatalogImport {
let mut data = sample();
data.collections.push(row(json!({"id_local":11,"parent":10,"name":"Picks","creationId":"com.adobe.ag.library.collection"})));
data.members.push(row(json!({"collection":11,"image":1,"positionInCollection":"a"})));
data
}
/// Importing the catalog again finds the moved album where the first import put it, adds nothing twice and doesn't
/// warn again: the album is already in the library.
#[test]
fn a_relocated_collection_keeps_its_place_on_reimport_without_duplicates_or_a_second_warning() {
let mut s = crate::Session::new();
let mut index = ImportIndex::default();
let first = import_indexed(&mut s, with_picks(), &mut index).unwrap();
assert_eq!(warnings_naming(&first, "Picks").len(), 1);
let second = import_indexed(&mut s, with_picks(), &mut index).unwrap();
assert_eq!(second["collections"], 3);
assert_eq!(s.catalog.albums().count(), 3);
assert_eq!(album_named(&s, "Picks").parent, Some(album_named(&s, "Travel").id));
assert_eq!(album_named(&s, "Picks").photos.len(), 1);
assert_eq!(album_named(&s, "Keepers").photos.len(), 2);
assert!(warnings_naming(&second, "Picks").is_empty(), "{second}");
}
/// Albums the user moved after an import stay where the user put them when the catalog is imported again.
#[test]
fn an_album_the_user_moved_keeps_its_place_on_reimport() {
let mut s = crate::Session::new();
let mut index = ImportIndex::default();
import_indexed(&mut s, with_picks(), &mut index).unwrap();
for name in ["Picks", "Keepers"] {
let id = album_named(&s, name).id;
s.commit("Move Album", Op::MoveAlbum { id, parent: None }).unwrap();
}
let r = import_indexed(&mut s, with_picks(), &mut index).unwrap();
assert_eq!(s.catalog.albums().count(), 3);
assert_eq!(album_named(&s, "Picks").parent, None);
assert_eq!(album_named(&s, "Keepers").parent, None);
assert!(warnings_naming(&r, "Picks").is_empty() && warnings_naming(&r, "Keepers").is_empty(), "{r}");
}
/// A collection new since the last import goes into the set's album, and the warning names that album as the
/// library calls it now, not by its Lightroom name.
#[test]
fn a_relocation_warning_names_the_set_as_the_user_renamed_it() {
let mut s = crate::Session::new();
let mut index = ImportIndex::default();
import_indexed(&mut s, sample(), &mut index).unwrap();
let travel = album_named(&s, "Travel").id;
s.commit("Rename Album", Op::RenameAlbum { id: travel, name: "Trips".into() }).unwrap();
let r = import_indexed(&mut s, with_picks(), &mut index).unwrap();
assert_eq!(album_named(&s, "Picks").parent, Some(travel));
let w = warnings_naming(&r, "Picks");
assert!(w.len() == 1 && w[0].contains("inside “Keepers”") && w[0].ends_with("imported into “Trips” (Lightroom collection 11)"), "{w:?}");
}
/// The album an earlier import made for a Lightroom set may no longer be a folder (here: an index that names a plain
/// album). A collection in that set lands at the top level, and the warning says why without calling the set
/// something it isn't.
#[test]
fn a_set_whose_album_is_not_a_folder_puts_its_collections_at_the_top_level() {
let mut s = crate::Session::new();
let plain = s.catalog.alloc_album_id();
s.commit("New Album", Op::AddAlbum { album: Album::new(plain, "Travel picks") }).unwrap();
let mut index = ImportIndex::default();
index.collections.insert(format!("{}:9", key("test.lrcat")), plain.0);
let r = import_indexed(&mut s, sample(), &mut index).unwrap();
assert_eq!(s.catalog.albums().count(), 2);
assert!(!s.catalog.album(plain).unwrap().folder);
let keepers = album_named(&s, "Keepers");
assert_eq!((keepers.parent, keepers.photos.len()), (None, 2));
let w = warnings_naming(&r, "Keepers");
assert_eq!(w.len(), 1, "{w:?}");
assert!(w[0].contains("“Travel” is the album “Travel picks”") && w[0].contains("isn't a folder"), "{w:?}");
assert!(!w[0].contains("isn't a collection set") && w[0].ends_with("at the top level (Lightroom collection 10)"), "{w:?}");
}
/// Only the outermost set inside a plain collection moves; the sets and creations inside it keep their places.
#[test]
fn sets_nested_under_a_plain_collection_keep_their_own_nesting() {
let mut s = crate::Session::new();
let mut data = sample();
data.collections.push(row(json!({"id_local":12,"name":"Loose","creationId":"com.adobe.ag.library.collection"})));
data.collections.push(row(json!({"id_local":13,"parent":12,"name":"Outer","creationId":"com.adobe.ag.library.group"})));
data.collections.push(row(json!({"id_local":14,"parent":13,"name":"Inner","creationId":"com.adobe.ag.library.group"})));
data.collections.push(row(json!({"id_local":15,"parent":14,"name":"Poster","creationId":"com.adobe.ag.print"})));
data.members.push(row(json!({"collection":15,"image":1,"positionInCollection":"a"})));
let r = apply(&mut s, data, false).unwrap();
assert_eq!(r["collections"], 6);
let outer = album_named(&s, "Outer");
assert_eq!((outer.parent, outer.folder), (None, true));
let inner = album_named(&s, "Inner");
assert_eq!((inner.parent, inner.folder), (Some(outer.id), true));
assert_eq!(album_named(&s, "Poster").parent, Some(inner.id));
assert_eq!(album_named(&s, "Poster").photos.len(), 1);
let w = warnings_naming(&r, "Outer");
assert!(w.len() == 1 && w[0].contains("inside “Loose”") && w[0].ends_with("at the top level (Lightroom collection 13)"), "{w:?}");
assert!(warnings_naming(&r, "Inner").is_empty() && warnings_naming(&r, "Poster").is_empty(), "{r}");
}
/// The album counter saturates: one at its end hands every collection the same id. The second collection used to be
/// dropped without a word while the report counted it; the import now stops and names it.
#[test]
fn an_exhausted_album_counter_stops_the_import_naming_the_collection() {
let mut s = crate::Session::new();
s.commit("New Album", Op::AddAlbum { album: Album::new(lightcraft_catalog::AlbumId(u64::MAX - 1), "Last") }).unwrap();
let err = apply(&mut s, sample(), false).unwrap_err().to_string();
assert!(err.contains("“Keepers”") && err.contains("no unused album id"), "{err}");
assert_eq!(s.catalog.albums().count(), 1);
assert!(s.catalog.is_empty());
}
/// A collection listed twice imports once. A different collection under the same Lightroom id used to stop the import;
/// like any bad record it now costs only itself (#1588): it is left out with a warning naming both, and its photos go
/// to the first.
#[test]
fn a_collection_listed_twice_imports_once_and_a_conflicting_one_is_skipped_with_a_warning() {
let mut s = crate::Session::new();
let mut data = sample();
data.collections.push(data.collections[1].clone());
let r = apply(&mut s, data, false).unwrap();
assert_eq!(r["collections"], 2);
assert_eq!(s.catalog.albums().filter(|a| a.name == "Keepers").count(), 1);
assert_eq!(album_named(&s, "Keepers").photos.len(), 2);
assert_eq!(r["warnings"], json!([]), "an exact repeat drops quietly");
let mut s = crate::Session::new();
let mut data = sample();
// shallower than the first, so a depth-ordered pass would meet it first
data.collections.push(row(json!({"id_local":10,"parent":0,"name":"Rejects","creationId":"collection"})));
let r = apply(&mut s, data, false).unwrap();
assert_eq!(r["photos"], 2, "{r}");
assert_eq!(r["collections"], 2, "{r}");
assert!(s.catalog.albums().all(|a| a.name != "Rejects"));
let keepers = album_named(&s, "Keepers");
assert_eq!(keepers.photos.len(), 2);
assert!(keepers.parent.is_some(), "the first row's place is kept");
assert_eq!(
r["warnings"],
json!(["collection “Rejects”: not imported, it has the id of collection “Keepers”; the photos listed under that id go to “Keepers”"])
);
assert_eq!(s.undo.len(), 1);
}
/// The search for the nearest set ends on a parent loop that got past `validate` (A in B in A, a collection in
/// itself) and on a chain of plain collections deeper than 64: the album goes to the top level, flagged as moved.
#[test]
fn the_nearest_set_search_ends_on_a_parent_loop_or_a_deep_chain() {
let plain = |id: i64, parent: i64| row(json!({"id_local":id,"parent":parent,"name":format!("C{id}"),"creationId":"collection"}));
let (a, b, own) = (plain(1, 2), plain(2, 1), plain(3, 3));
let child = plain(4, 1);
let collections: HashMap<i64, &Row> = [(1, &a), (2, &b), (3, &own), (4, &child)].into_iter().collect();
let no_sets = HashSet::new();
for c in [&a, &b, &own, &child] {
assert_eq!(collection_parent(c, &collections, &no_sets), (None, true), "{c:?}");
}
// a set in the loop is still found
assert_eq!(collection_parent(&child, &collections, &HashSet::from([2])), (Some(2), true));
let chain: Vec<Row> = (100..200).map(|id| plain(id, if id == 100 { 0 } else { id - 1 })).collect();
let collections: HashMap<i64, &Row> = chain.iter().map(|r| (number(r, "id_local"), r)).collect();
assert_eq!(collection_parent(&chain[99], &collections, &no_sets), (None, true));
}
/// A damaged index that names one existing album for two collections gives the second an album of its own rather
/// than merging its photos into the first's.
#[test]
fn an_index_naming_one_album_for_two_collections_gives_the_second_its_own() {
let mut s = crate::Session::new();
let old = s.catalog.alloc_album_id();
s.commit("New Album", Op::AddAlbum { album: Album::new(old, "Old") }).unwrap();
let mut index = ImportIndex::default();
for lr in [10, 11] {
index.collections.insert(format!("{}:{lr}", key("test.lrcat")), old.0);
}
let r = import_indexed(&mut s, with_picks(), &mut index).unwrap();
assert_eq!(r["collections"], 3);
assert_eq!(s.catalog.album(old).unwrap().photos.len(), 2, "Keepers merges into the album the index names");
let picks = album_named(&s, "Picks");
assert_ne!(picks.id, old);
assert_eq!(picks.photos.len(), 1);
}
#[test]
fn preserves_existing_edits_and_rejects_invalid_structure_before_mutation() {
let mut s = crate::Session::new();
@@ -873,7 +1122,7 @@ fn record(values: &[SqlValue]) -> Vec<u8> {
body.extend(s.as_bytes());
13 + 2 * s.len() as u64
}
_ => unreachable!(),
_ => panic!("unexpected SqlValue in a test record: {value:?}"),
};
header.extend(varint(serial));
}
+6 -3
View File
@@ -35,14 +35,17 @@ mod settings_hash;
mod source;
pub use cache::DenoiseIndex;
#[cfg(test)]
pub(crate) use cache::rendered_budget;
pub use quick::{QuickJob, QuickSource, content_key, source_info};
pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_for_display};
pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_cached, fit_for_display};
#[cfg(test)]
use settings_hash::SETTINGS_HASH_ENTRIES;
use settings_hash::SettingsHashes;
pub use source::{
DISK_CACHE_BYTES, DecodedSource, DenoiseSpec, FACE_EDGE_STEP, FileLoader, FileProbe, MakeProduct, PairLoader, PreviewLoader, ProbeInfo,
RENDER_CACHE_VERSION, ReducedLoader, SourceLevel, SourceRef, THUMB_SIZES, Twin, face_edge, thumb_bucket,
DISK_CACHE_BYTES, DISK_CACHE_PER_PHOTO, DecodedSource, DenoiseSpec, FACE_EDGE_STEP, FileLoader, FileProbe, MakeProduct, PairLoader,
PreviewLoader, ProbeInfo, RENDER_CACHE_VERSION, RawDecode, ReducedLoader, SourceLevel, SourceRef, THUMB_SIZES, Twin, default_disk_cache_bytes,
face_edge, thumb_bucket,
};
pub struct MediaCache {
+20 -9
View File
@@ -75,9 +75,11 @@ impl Default for MediaCache {
}
}
/// Memory for rendered previews out of the cache share.
fn rendered_budget(share: usize) -> usize {
RENDERED_MEM_BYTES.min(share / 4)
/// Memory for rendered previews out of the cache share: a quarter of it, so a big budget keeps
/// a whole shoot's previews (a 20 GB budget holds about 230 standard previews, or 1 500 loupe
/// renders at 1 200 px), and at least [`RENDERED_MEM_BYTES`] where the share allows.
pub(crate) fn rendered_budget(share: usize) -> usize {
(share / 4).max(RENDERED_MEM_BYTES.min(share / 2))
}
impl MediaCache {
@@ -332,22 +334,27 @@ impl MediaCache {
}
fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc<DcpProfile>)>) -> SourceRef {
let outliers = p.develop.removes_hot_pixels();
// (a source developed with another camera profile, or none, doesn't stand in; a smart preview
// has no camera profile, and decoding it again gives the same picture, so it stands in while the
// original is offline)
if cached
&& let Some(a) = self.get_source(p.id, level)
&& let Some(a) = self.get_source(p.id, level).filter(|a| a.fits_outliers(outliers))
&& (a.camera_profile == wanted.as_ref().map(|(id, _)| id.clone()) || (a.from_proxy && self.original_offline(p)))
{
return SourceRef::Loaded(Box::new(a));
}
// a thumbnail of a photo whose preview is decoded (the one in the loupe) is cut from it; not
// a thumbnail of a photo whose preview or full source is decoded (the one in the loupe) is cut from it; not
// with a denoised picture, which the thumbnail would lose, nor from one decoded with another camera profile
if cached
&& level == SourceLevel::Thumb
&& self.denoise.spec(p.id).is_none()
&& let Some(big) = self.get_source(p.id, SourceLevel::Preview)
&& (big.camera_profile == wanted.as_ref().map(|(tag, _)| tag.clone()) || (big.from_proxy && self.original_offline(p)))
&& let Some(big) = [SourceLevel::Preview, SourceLevel::Full].into_iter().find_map(|level| {
self.get_source(p.id, level).filter(|b| {
b.fits_outliers(outliers)
&& (b.camera_profile.as_deref() == wanted.as_ref().map(|(tag, _)| tag.as_str()) || (b.from_proxy && self.original_offline(p)))
})
})
{
return SourceRef::Fit { from: Box::new(big), max_edge: level.max_edge() };
}
@@ -370,15 +377,17 @@ impl MediaCache {
return SourceRef::Smart { path: sp };
}
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { fallback, camera_profile, .. } = &mut r {
if let SourceRef::File { fallback, camera_profile, outliers: o, .. } = &mut r {
*fallback = Some(sp);
*camera_profile = wanted;
*o = outliers;
}
return r;
}
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { camera_profile, .. } = &mut r {
if let SourceRef::File { camera_profile, outliers: o, .. } = &mut r {
*camera_profile = wanted;
*o = outliers;
}
r
}
@@ -419,6 +428,7 @@ impl MediaCache {
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
},
}
@@ -430,6 +440,7 @@ impl MediaCache {
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
},
}
+37 -6
View File
@@ -25,6 +25,15 @@ pub struct QuickJob {
pub cached: Vec<(Arc<PreviewCache>, Hash128)>,
/// Embedded preview of an unedited raw: (path, loader, max edge).
pub embedded: Option<(String, PreviewLoader, usize)>,
/// Where a decoded [`Self::embedded`] preview is kept in memory, so stepping back to a photo
/// shows its camera JPEG again without reading and decoding it (culling goes back and forth):
/// the cache (memory only, never its disk), the key for this photo and edge, and the cache's
/// generation when the job was made (a Discard Preview Cache since then keeps the picture out).
pub embedded_cache: Option<(Arc<PreviewCache>, Hash128, u64)>,
/// Whether [`Self::embedded_cache`] keeps the decoded preview on disk too: a grid thumbnail,
/// so a folder seen before fills in from small files at once instead of every raw being read
/// and its camera JPEG decoded again (the loupe's large stand-ins stay in memory).
pub embedded_on_disk: bool,
/// Import tiles need this many pixels when a render can provide them. `None` accepts any
/// camera JPEG immediately (ordinary transient stand-ins and preview-only imports).
/// An undersized JPEG remains the fallback if the render fails or is unavailable.
@@ -79,13 +88,30 @@ impl QuickJob {
}
}
let mut embedded_fallback = None;
if let Some((path, loader, edge)) = &self.embedded
&& let Some(image) = loader(path, *edge)
{
if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) {
return done(rendered(image), Some(QuickSource::Embedded));
if let Some((path, loader, edge)) = &self.embedded {
let kept =
self.embedded_cache.as_ref().and_then(|(cache, k, _)| if self.embedded_on_disk { cache.get(*k) } else { cache.get_memory(*k) });
let image = match kept {
Some(img) => Some(Arc::unwrap_or_clone(img)),
None => {
let image = loader(path, *edge);
// written for the generation the job was made in: a cache cleared meanwhile stays clear
if let (Some(image), Some((cache, k, generation))) = (&image, &self.embedded_cache) {
if self.embedded_on_disk {
cache.put_deferred_at(*generation, *k, Arc::new(image.clone()));
} else {
cache.put_memory_at(*generation, *k, Arc::new(image.clone()));
}
}
image
}
};
if let Some(image) = image {
if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) {
return done(rendered(image), Some(QuickSource::Embedded));
}
embedded_fallback = Some(image);
}
embedded_fallback = Some(image);
}
if let Some(job) = self.small {
let r = job.run();
@@ -100,6 +126,11 @@ impl QuickJob {
}
}
/// The thumbnail cache's key for the camera JPEG standing for the thumbnail of cache key `k`.
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
/// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still
+106 -1
View File
@@ -1,5 +1,5 @@
use super::quick::QuickSource;
use super::source::{DecodedSource, SourceLevel, SourceRef};
use super::source::{DecodedSource, SourceLevel, SourceRef, VIEW_REUSE_SLACK};
use super::{
Arc, DevelopSettings, Hash128, Histogram, PhotoId, PreviewCache, Quality, RenderRequest, Rendered, Rgb32f, Rgba8, Source, SourceInfo, StageCache,
};
@@ -241,8 +241,58 @@ impl RenderJob {
r
}
/// The view render kept for this job's photo and settings ([`Self::view_cache`]), fitted to the
/// size asked for, when it is at least that big, or unchanged when it covers the job's display
/// fit (else `None`: render). Only for what the cached
/// view is: a full-quality, 8-bit, whole-frame SDR render (the cache holds sRGB; a display
/// profile is applied to it like to any cached picture, [`crate::display::present`]).
pub fn cached_view(&self) -> Option<Rgba8> {
let (cache, key) = self.view_cache.as_ref()?;
if self.request.quality != Quality::Full
|| self.request.depth != lightcraft_pipeline::OutputDepth::U8
|| self.request.window.is_some()
|| self.settings.hdr.enabled
|| self.slide.is_some()
{
return None;
}
let img = cache.get_at(self.cache_generation, *key)?;
fit_cached(&img, self.request.max_w, self.request.max_h).or_else(|| {
// the loupe at rest asks for at least the preview level and shows the render shrunk to
// the drawn size (the display fit): a cached view that covers the drawn size is enough
let (fw, fh) = self.display_fit?;
let (w, h) = (img.width, img.height);
let s = (fw as f64 / w.max(1) as f64).min(fh as f64 / h.max(1) as f64);
(w > 0 && h > 0 && fw > 0 && fh > 0 && s <= 1.0 + VIEW_REUSE_SLACK).then(|| Arc::unwrap_or_clone(img))
})
}
/// The photo's render (without slide composition).
fn run_photo(self) -> RenderResult {
// the loupe: a cached view render of these settings at least this big is the render (built
// previews and the photos prepared ahead are used, not rendered again; PERF-PREVIEW-REUSE)
if let Some(mut image) = self.cached_view() {
// as for a render: the histogram of the full picture, then the display fit
let histogram = Histogram::of_srgb8(&image);
if let Some((fw, fh)) = self.display_fit
&& (image.width > fw.max(1) || image.height > fh.max(1))
{
image = fit_for_display(&image, fw, fh);
}
return RenderResult {
request_id: self.request_id,
source_key: self.source_key,
photo: self.photo,
level: self.level,
key: self.key,
rendered: Ok(Rendered { image, histogram, deep: None }),
gpu_fallback: None,
loaded: None,
quick: Some(QuickSource::Cached),
display: None,
frame: None,
};
}
if let Some((cache, key)) = &self.cache
&& let Some(img) = cache.get_at(self.cache_generation, *key)
{
@@ -395,6 +445,61 @@ impl RenderJob {
}
}
/// `img` fitted into `max_w × max_h` (its aspect kept), when it is big enough to need no
/// enlarging (within [`VIEW_REUSE_SLACK`]): as it is, or shrunk by averaging.
pub fn fit_cached(img: &Rgba8, max_w: usize, max_h: usize) -> Option<Rgba8> {
let (w, h) = (img.width, img.height);
if w == 0 || h == 0 || max_w == 0 || max_h == 0 {
return None;
}
let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64);
if !s.is_finite() || s > 1.0 + VIEW_REUSE_SLACK {
return None;
}
let (nw, nh) = (((w as f64 * s).round() as usize).clamp(1, w), ((h as f64 * s).round() as usize).clamp(1, h));
if nw == w && nh == h {
return Some(img.clone());
}
Some(shrink_rgba(img, nw, nh))
}
/// `img` shrunk to `nw × nh` (no larger than it), each pixel the average of the ones it covers.
fn shrink_rgba(img: &Rgba8, nw: usize, nh: usize) -> Rgba8 {
let (w, h) = (img.width, img.height);
let (nw, nh) = (nw.clamp(1, w.max(1)), nh.clamp(1, h.max(1)));
// the source columns / rows each output column / row covers: [start, end)
let spans = |n: usize, of: usize| -> Vec<(usize, usize)> {
(0..n)
.map(|i| {
let a = i.saturating_mul(of) / n;
let b = (i.saturating_add(1).saturating_mul(of) / n).max(a.saturating_add(1)).min(of);
(a, b)
})
.collect()
};
let (xs, ys) = (spans(nw, w), spans(nh, h));
let mut data = Vec::with_capacity(nw.saturating_mul(nh));
let mut row = vec![[0u32; 4]; nw];
for &(y0, y1) in &ys {
row.iter_mut().for_each(|r| *r = [0; 4]);
for y in y0..y1 {
let Some(line) = img.data.get(y * w..(y + 1) * w) else { continue };
for (acc, &(x0, x1)) in row.iter_mut().zip(&xs) {
for px in line.get(x0..x1).unwrap_or(&[]) {
for (a, v) in acc.iter_mut().zip(px) {
*a += u32::from(*v);
}
}
}
}
for (acc, &(x0, x1)) in row.iter().zip(&xs) {
let n = (x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0))).max(1) as u32;
data.push(acc.map(|a| ((a + n / 2) / n).min(255) as u8));
}
}
Rgba8 { width: nw, height: nh, data }
}
/// Render `src`: on the GPU when `gpu` is set and a GPU is available (`lightcraft_gpu`), else on
/// the CPU, reusing `stages` either way. Both produce the same image within 1–3 LSB (see
/// `docs/gpu-pipeline.md`); `LIGHTCRAFT_GPU=0` or [`lightcraft_gpu::set_enabled`] forces the CPU.
+76 -12
View File
@@ -1,4 +1,4 @@
use super::quick::{QuickJob, content_key, source_info};
use super::quick::{QuickJob, content_key, embedded_thumb_key, source_info};
use super::render::{RenderJob, RenderResult};
use super::settings_hash::with_process;
use super::source::{PreviewLoader, RENDER_CACHE_VERSION, SourceLevel, SourceRef, THUMB_SIZES, face_edge, source_edge_needed, thumb_bucket};
@@ -58,7 +58,8 @@ impl crate::Session {
let content = Hasher128::new().str(&content_key).finish().0 as u64;
let source_key = super::quick::source_identity(&p);
// Temporary "before" settings must not replace the photo's cached develop hash.
let settings_hash = if before { settings.hash64() } else { self.media.settings_hashes.get(id, &settings) };
let settings_hash =
if before { settings.hash64() ^ crate::files::hot_pixel_key(&settings) } else { self.media.settings_hashes.get(id, &settings) };
let salt = self.media.denoise_salt(id, &settings);
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
let lens = super::quick::lens_key(&p);
@@ -131,6 +132,7 @@ impl crate::Session {
// (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));
job.key = settings.hash64()
^ crate::files::hot_pixel_key(settings)
^ ((max_w as u64) << 40)
^ ((max_h as u64) << 20)
^ (apply_crop as u64)
@@ -144,7 +146,11 @@ impl crate::Session {
/// `profile_salt`: [`MediaCache::camera_profile_salt`] of `settings`' profile.
pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize, profile_salt: u64) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p)).str("variant").u64(settings.hash64()).u64(edge as u64).u64(RENDER_CACHE_VERSION);
k.str(&content_key(p))
.str("variant")
.u64(settings.hash64() ^ crate::files::hot_pixel_key(settings))
.u64(edge as u64)
.u64(RENDER_CACHE_VERSION);
with_process(&mut k, settings).u64(crate::camera_profiles::cache_key());
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
@@ -264,12 +270,23 @@ impl crate::Session {
Some(crate::face_tiles::PreviewCut { path, loader, want, min, rect, aspect, edge })
}
/// Size-independent cache key of a photo's view render (loupe) for its current settings, its lens profile
/// included as in [`Self::variant_key`]. `profile_salt`: [`MediaCache::camera_profile_salt`] of the photo's profile.
pub(crate) fn view_key(p: &Photo, apply_crop: bool, profile_salt: u64) -> Hash128 {
/// Size-independent cache key of a photo's view render (loupe) for its current settings. The
/// denoised picture, camera profile and lens profile in use are part of it (as of the render's own
/// key, [`Self::variant_key`]): a view rendered before the photo's AI Denoise result was there is
/// not shown as the denoised one.
pub(crate) fn view_key(&self, p: &Photo, apply_crop: bool) -> Hash128 {
let salt = self.media.denoise_salt(p.id, &p.develop);
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
let mut k = Hasher128::new();
k.str(&content_key(p)).str("view").u64(p.develop.hash64()).u64(apply_crop as u64).u64(RENDER_CACHE_VERSION);
k.str(&content_key(p))
.str("view")
.u64(p.develop.hash64() ^ crate::files::hot_pixel_key(&p.develop))
.u64(apply_crop as u64)
.u64(RENDER_CACHE_VERSION);
with_process(&mut k, &p.develop).u64(crate::camera_profiles::cache_key());
if salt != 0 {
k.u64(salt);
}
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
@@ -285,8 +302,7 @@ impl crate::Session {
pub fn loupe_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool) -> Option<RenderJob> {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
let p = self.catalog.photo(id)?;
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop, profile_salt)));
job.view_cache = Some((self.media.rendered.clone(), self.view_key(p, apply_crop)));
Some(job)
}
@@ -396,11 +412,55 @@ impl crate::Session {
let small = self.thumb_job(id, THUMB_SIZES[THUMB_SIZES.len() - 1])?;
// (the thumbnail job itself starts with the cached thumbnail, after the sharper embedded preview)
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop, profile_salt))];
let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).u64(profile_salt).finish();
let cached = vec![(self.media.rendered.clone(), self.view_key(&p, apply_crop))];
// (the photo too: a virtual copy shares the file and, unedited, the settings)
let h = Hasher128::new()
.str(&content_key(&p))
.str("quick")
.u64(p.develop.hash64() ^ crate::files::hot_pixel_key(&p.develop))
.u64(apply_crop as u64)
.u64(id.0)
.u64(profile_salt)
.finish();
let key = h.0 as u64;
let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge())));
Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, minimum_embedded_edge: None, small: apply_crop.then(|| Box::new(small)) })
let embedded_cache = embedded.as_ref().map(|(_, _, edge)| {
let cache = self.media.rendered.clone();
let generation = cache.generation();
(cache, Hasher128::new().str(&content_key(&p)).str("embedded").u64(*edge as u64).finish(), generation)
});
Some(QuickJob {
request_id: 0,
photo: id,
key,
cached,
embedded,
embedded_cache,
embedded_on_disk: false,
minimum_embedded_edge: None,
small: apply_crop.then(|| Box::new(small)),
})
}
/// The camera's embedded JPEG of an unedited raw at up to `max_edge` pixels (its full size for
/// a camera that stores one), for the loupe zoomed to 100 % while LightCraft renders the window
/// on screen: a focus check needs the pixels at once, and a 45 MP render of the window takes
/// seconds. Not kept in any cache (a full-size picture is 180 MB). `None` for other photos.
pub fn embedded_full_job(&mut self, id: PhotoId, max_edge: usize) -> Option<QuickJob> {
let p = self.catalog.photo(id)?.clone();
let (path, l) = self.embedded_of(&p)?;
let key = Hasher128::new().str(&content_key(&p)).str("embedded-full").u64(id.0).u64(max_edge as u64).finish().0 as u64;
Some(QuickJob {
request_id: 0,
photo: id,
key,
cached: Vec::new(),
embedded: Some((path, l, max_edge.max(1))),
embedded_cache: None,
embedded_on_disk: false,
minimum_embedded_edge: None,
small: None,
})
}
/// A first grid thumbnail for an unedited raw: the cached render for `job` (the real
@@ -419,6 +479,10 @@ impl crate::Session {
key: job.key,
cached: job.cache.clone().into_iter().collect(),
embedded: Some((path, l, edge)),
// the camera JPEG is this thumbnail (an unedited raw): kept with the rendered ones, under
// a key of its own, so the folder's next visit reads it from the thumbnail cache
embedded_cache: job.cache.as_ref().map(|(c, k)| (c.clone(), embedded_thumb_key(*k), c.generation())),
embedded_on_disk: true,
minimum_embedded_edge: None,
small: Some(Box::new(job.clone())),
})
+1 -1
View File
@@ -17,7 +17,7 @@ impl SettingsHashes {
{
return *hash;
}
let hash = settings.hash64();
let hash = settings.hash64() ^ crate::files::hot_pixel_key(settings);
#[cfg(test)]
{
self.computations += 1;
+54 -16
View File
@@ -1,7 +1,7 @@
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 75;
pub const RENDER_CACHE_VERSION: u64 = 76;
/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];
@@ -24,10 +24,23 @@ pub fn thumb_bucket(long_edge: usize) -> usize {
/// Memory budgets.
pub(super) const THUMB_SOURCE_BYTES: usize = 384 << 20;
/// The least memory kept for rendered previews (when the budget allows it).
pub(super) const RENDERED_MEM_BYTES: usize = 128 << 20;
/// Disk budget for the thumbnail cache.
/// The smallest disk budget for the thumbnail and preview cache.
pub const DISK_CACHE_BYTES: u64 = 2 << 30;
/// What one photo's previews take on disk, about: its standard preview (a 2048 px JPEG, ~1 MB)
/// and its grid thumbnails. The default disk budget grows by this per photo of the library, so
/// built previews of a whole wedding are not pruned while they are being made (PERF-PREVIEW-REUSE).
pub const DISK_CACHE_PER_PHOTO: u64 = 3 << 19;
/// The default disk budget for a library of `photos`: [`DISK_CACHE_BYTES`], or room for every
/// photo's previews ([`DISK_CACHE_PER_PHOTO`]) when that is more.
pub fn default_disk_cache_bytes(photos: usize) -> u64 {
DISK_CACHE_BYTES.max((photos as u64).saturating_mul(DISK_CACHE_PER_PHOTO))
}
/// A cached view render this much smaller than asked for still serves the loupe (rounding: a
/// fit of the same frame into a box one pixel different).
pub(super) const VIEW_REUSE_SLACK: f64 = 0.01;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -74,15 +87,22 @@ pub(super) fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_cr
if needed.is_finite() { needed.min(usize::MAX as f64 / 2.0) as usize } else { out_long }
}
/// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app).
/// The third argument is the photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed
/// with its colour model.
pub type FileLoader = Arc<dyn Fn(&str, usize, Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>;
/// How a raw file is decoded for a photo.
#[derive(Clone, Copy, Default)]
pub struct RawDecode<'a> {
/// The photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed with its colour model.
pub dcp: Option<&'a DcpProfile>,
/// Replace a raw's single outlier photosites first ([`DevelopSettings`] `detail.nr_outliers`).
pub outliers: bool,
}
/// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app), as the third argument says.
pub type FileLoader = Arc<dyn Fn(&str, usize, RawDecode<'_>) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>;
/// [`FileLoader`] for a thumbnail: a raw file that keeps smaller copies of its raw image (Lightroom's merged DNGs)
/// develops the smallest that covers `max_edge` (set by the app); the flag says it did. Never used for an export,
/// which must render the full image.
pub type ReducedLoader = Arc<dyn Fn(&str, usize, Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>;
pub type ReducedLoader = Arc<dyn Fn(&str, usize, RawDecode<'_>) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>;
/// A raw file's embedded (camera-rendered) preview as display sRGB, oriented, no larger than
/// `max_edge` (set by the app). `None`: no usable preview.
@@ -105,8 +125,7 @@ pub struct DenoiseSpec {
/// Decodes a raw file once and develops it twice: as usual, and from the denoised picture in `spec` when that can be
/// read (`None` when it cannot). Both are at most `max_edge` long and the same size.
pub type PairLoader =
Arc<dyn Fn(&str, usize, &DenoiseSpec, Option<&DcpProfile>) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> + Send + Sync>;
pub type PairLoader = Arc<dyn Fn(&str, usize, &DenoiseSpec, RawDecode<'_>) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> + Send + Sync>;
/// A photo's denoised picture next to its plain one, and the last mix of the two that was asked for.
pub struct Twin {
@@ -139,6 +158,8 @@ pub struct DecodedSource {
/// The imported camera profile (`dcp:…` id) the raw file was developed with, if any: a cached source made with
/// another one (or none) doesn't stand in for it.
pub camera_profile: Option<String>,
/// Decoded with a raw's single outlier photosites replaced (`detail.nr_outliers`).
pub outliers: bool,
/// These pixels came from the photo's smart preview (an offline original), not from its file.
/// A refresh must never rebuild a proxy from itself: that would stamp its older look as current.
pub from_proxy: bool,
@@ -149,7 +170,14 @@ pub struct DecodedSource {
impl DecodedSource {
pub fn new(image: Arc<Rgb32f>, info: Option<SourceInfo>) -> Self {
DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, from_proxy: false, reduced: false }
DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, outliers: false, from_proxy: false, reduced: false }
}
/// Whether this source can stand for one decoded with `outliers`: a raw decode must match it; anything without a
/// mosaic (a rendered file, a smart preview, a demo scene) has nothing the flag would change. A smart preview's
/// facts say `raw` for a raw photo, so it is told apart by `from_proxy`.
pub fn fits_outliers(&self, outliers: bool) -> bool {
self.outliers == outliers || self.from_proxy || !self.info.as_ref().is_some_and(|i| i.raw)
}
/// The picture to develop for a Denoise `amount` (0 to 1, see [`DevelopSettings::denoise_amount`]): the plain one,
@@ -243,6 +271,8 @@ pub enum SourceRef {
denoise: Option<(DenoiseSpec, PairLoader)>,
/// The photo's imported camera profile (id and profile): its raw file is developed with it.
camera_profile: Option<(String, Arc<DcpProfile>)>,
/// Replace a raw's single outlier photosites before developing it (`detail.nr_outliers`).
outliers: bool,
/// A thumbnail's loader, used instead of `loader` (see [`ReducedLoader`]); `None` for every other job.
reduced: Option<ReducedLoader>,
},
@@ -270,17 +300,21 @@ impl SourceRef {
return Ok(DecodedSource { image: Arc::new(image), denoised: None, ..(**from).clone() });
}
SourceRef::Demo { scene, max_edge } => crate::demo::scene_pixels(scene, *max_edge)?,
SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile, reduced } => {
let dcp = camera_profile.as_ref().map(|(_, p)| p.as_ref());
SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile, outliers, reduced } => {
let with = RawDecode { dcp: camera_profile.as_ref().map(|(_, p)| p.as_ref()), outliers: *outliers };
let made_with = camera_profile.as_ref().map(|(id, _)| id.clone());
let plain = || match (reduced, loader) {
(Some(l), _) => l(path, *max_edge, dcp).map(|(image, info, reduced)| DecodedSource {
(Some(l), _) => l(path, *max_edge, with).map(|(image, info, reduced)| DecodedSource {
reduced,
camera_profile: made_with.clone(),
outliers: *outliers,
..DecodedSource::new(Arc::new(image), Some(info))
}),
(None, Some(l)) => l(path, *max_edge, with).map(|(image, info)| DecodedSource {
camera_profile: made_with.clone(),
outliers: *outliers,
..DecodedSource::new(Arc::new(image), Some(info))
}),
(None, Some(l)) => l(path, *max_edge, dcp)
.map(|(image, info)| DecodedSource { camera_profile: made_with.clone(), ..DecodedSource::new(Arc::new(image), Some(info)) }),
(None, None) => Err(format!("no decoder available for {path}")),
};
// the denoised picture comes with the plain one from a single decode; when it cannot be read the
@@ -294,7 +328,7 @@ impl SourceRef {
None => true,
};
if made {
pair(path, *max_edge, spec, dcp).and_then(|(image, twin, info)| {
pair(path, *max_edge, spec, with).and_then(|(image, twin, info)| {
if spec.make.is_some() && twin.is_none() {
return Err("the cached AI Denoise picture could not be read; clear the denoise cache and retry".into());
}
@@ -304,6 +338,7 @@ impl SourceRef {
camera_tone: None,
denoised: twin.map(|t| Arc::new(Twin::new(Arc::new(t)))),
camera_profile: made_with.clone(),
outliers: *outliers,
from_proxy: false,
reduced: false,
})
@@ -355,6 +390,9 @@ pub struct ProbeInfo {
pub embedded_lens: Option<lightcraft_develop::EmbeddedLens>,
/// The file's embedded XMP packet (raw/DNG files), for develop settings stored inside the file.
pub xmp: Option<String>,
/// The file's Exif orientation, when it states one: how its stored pixels turn upright (`width` and `height` are
/// the upright size).
pub orientation: Option<lightcraft_geom::Orientation>,
/// A raw variant that can't be decoded yet: why. The file is described (and will be shown and
/// edited) from its embedded preview; see [`lightcraft_catalog::Photo::preview_only`].
pub preview_only: Option<String>,
+18
View File
@@ -91,6 +91,7 @@ fn decoder_info_survives_render_jobs_cache_and_eviction() {
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
job.info = SourceInfo::default(); // Header facts cannot override decoder facts.
@@ -148,6 +149,7 @@ fn old_relative_white_balance_on_a_kelvin_camera_keeps_its_look_and_learns_the_a
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
let undo_before = s.undo.len();
@@ -642,3 +644,19 @@ fn an_export_develops_from_a_source_twice_its_size() {
}
assert_eq!(s.render_job(id, 1600, 1600, false, true).unwrap().level, SourceLevel::Preview, "a view keeps the preview");
}
#[test]
fn a_thumbnail_is_cut_from_the_decoded_full_source() {
let mut s = crate::Session::new();
let p = Photo::new(PhotoId(1), Source::File { path: "/nowhere/a.ARW".into() }, "a.ARW", "ARW", 2400, 1600, "");
s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap();
s.media.insert(p.id, SourceLevel::Full, Arc::new(Rgb32f::from_fn(2400, 1600, |x, _| [x as f32 / 2400.0, 0.5, 0.25])));
let job = s.thumb_job(p.id, 512).unwrap();
assert!(matches!(job.source, SourceRef::Fit { .. }));
let r = job.run();
let thumb = r.rendered.as_ref().unwrap();
assert_eq!((thumb.image.width, thumb.image.height), (512, 341));
s.accept(&r);
let cached = s.media.get(p.id, SourceLevel::Thumb).unwrap();
assert_eq!((cached.width, cached.height), (512, 341), "a thumbnail-sized source is kept, not the full source");
}
+176 -2
View File
@@ -6,6 +6,60 @@ fn session() -> crate::Session {
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
s
}
/// PERF-CULL: an unedited raw's camera JPEG is read once for the loupe and kept in memory for a
/// step back; the full-size one (zoomed in) is made at the size asked for and kept nowhere; an
/// edited raw or another file has none.
#[test]
fn camera_previews_are_kept_for_a_revisit_and_full_size_ones_are_not() {
let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let mut s = crate::Session::new();
let r = reads.clone();
s.media.preview_loader = Some(Arc::new(move |_: &str, edge: usize| {
r.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Some(Rgba8 { width: edge.min(64), height: 2, data: vec![[9, 8, 7, 255]; edge.min(64) * 2] })
}));
let mut raw = Photo::new(PhotoId(1), Source::File { path: "a.cr3".into() }, "a.cr3", "CR3", 6000, 4000, "2026-01-01");
raw.kind = MediaKind::Raw;
raw.develop = Arc::new(raw.camera_defaults());
s.catalog.apply(Op::AddPhoto { photo: Box::new(raw) }).unwrap();
let jpeg = Photo::new(PhotoId(2), Source::File { path: "b.jpg".into() }, "b.jpg", "JPEG", 600, 400, "2026-01-01");
s.catalog.apply(Op::AddPhoto { photo: Box::new(jpeg) }).unwrap();
for _ in 0..3 {
let q = s.quick_view_job(PhotoId(1), 48, true).unwrap();
let r = q.run();
assert_eq!(r.quick, Some(QuickSource::Embedded));
}
assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "read once, then from memory");
let full = s.embedded_full_job(PhotoId(1), 8192).unwrap();
assert!(full.embedded_cache.is_none() && full.cached.is_empty() && full.small.is_none());
assert_eq!(full.embedded.as_ref().map(|e| e.2), Some(8192));
assert_ne!(full.key, s.quick_view_job(PhotoId(1), 48, true).unwrap().key);
assert_eq!(full.run().quick, Some(QuickSource::Embedded));
assert!(s.embedded_full_job(PhotoId(2), 8192).is_none(), "not a raw");
let mut edited = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone();
edited.light.exposure = 1.0;
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edited), label: "edit".into(), edited: None }).unwrap();
assert!(s.embedded_full_job(PhotoId(1), 8192).is_none(), "an edit is shown rendered");
}
/// A virtual copy shares its master's file and, unedited, its settings; its loupe stand-ins
/// are its own all the same (CodeRabbit on #3080).
#[test]
fn a_virtual_copy_has_its_own_stand_in_keys() {
let mut s = crate::Session::new();
s.media.preview_loader = Some(Arc::new(|_: &str, _: usize| None::<Rgba8>));
for id in [1, 2] {
let mut raw = Photo::new(PhotoId(id), Source::File { path: "a.cr3".into() }, "a.cr3", "CR3", 6000, 4000, "2026-01-01");
raw.kind = MediaKind::Raw;
raw.develop = Arc::new(raw.camera_defaults());
s.catalog.apply(Op::AddPhoto { photo: Box::new(raw) }).unwrap();
}
let quick = |s: &mut crate::Session, id: u64| s.quick_view_job(PhotoId(id), 48, true).unwrap().key;
assert_ne!(quick(&mut s, 1), quick(&mut s, 2));
let full = |s: &mut crate::Session, id: u64| s.embedded_full_job(PhotoId(id), 8192).unwrap().key;
assert_ne!(full(&mut s, 1), full(&mut s, 2));
}
/// Settings saved by a newer LightCraft (a process number this build doesn't know) render with
/// this build's latest process, and a build that resolved the number to an older process
/// cached other pixels under the same settings hash: the persistent keys (thumbnails, the
@@ -37,7 +91,7 @@ fn persistent_keys_name_the_process_the_settings_render_with() {
let resolved = u64::from(lightcraft_develop::Process::LATEST.version().0);
let keys = [
(s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1, None, 256),
(crate::Session::view_key(&p, true, 0), Some("view"), 1),
(s.view_key(&p, true), Some("view"), 1),
(crate::Session::variant_key(&p, &newer, 256, 0), Some("variant"), 256),
];
for (key, kind, size) in keys {
@@ -69,7 +123,7 @@ fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() {
};
let keys = [
s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256),
crate::Session::view_key(&p, true, 0) == before_v3(Some("view"), 1),
s.view_key(&p, true) == before_v3(Some("view"), 1),
crate::Session::variant_key(&p, &settings, 256, 0) == before_v3(Some("variant"), 256),
];
let old = process <= Process::V2;
@@ -217,6 +271,8 @@ fn a_render_that_panics_fails_instead_of_never_answering() {
key: 9,
cached: Vec::new(),
embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| -> Option<Rgba8> { panic!("preview reader bug") }), 256)),
embedded_cache: None,
embedded_on_disk: false,
minimum_embedded_edge: None,
small: None,
};
@@ -224,3 +280,121 @@ fn a_render_that_panics_fails_instead_of_never_answering() {
assert_eq!((r.request_id, r.key), (7, 9));
assert_eq!(r.rendered.err().as_deref(), Some("the render failed unexpectedly: preview reader bug"));
}
/// A raw photo's smart preview has no mosaic left: it stands in with the box on or off, so an offline raw keeps
/// reusing the decoded proxy instead of reading the file again for every render.
#[test]
fn a_smart_preview_fits_either_hot_pixel_setting() {
let raw = SourceInfo { raw: true, ..Default::default() };
let decoded = DecodedSource::new(Arc::new(Rgb32f::new(8, 8)), Some(raw));
assert!(decoded.fits_outliers(false) && !decoded.fits_outliers(true), "a raw decode must match the box");
let proxy = DecodedSource { from_proxy: true, ..decoded };
assert!(proxy.fits_outliers(false) && proxy.fits_outliers(true));
}
/// The Remove Hot Pixels box decides how a raw is decoded (#1345): the loader is told, and a source decoded with
/// the other setting is not reused. A rendered file has no mosaic, so its source stays.
#[test]
fn hot_pixel_box_decodes_the_raw_again() {
let mut s = session();
let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
let log = asked.clone();
let raw = Arc::new(std::sync::atomic::AtomicBool::new(true));
let is_raw = raw.clone();
s.media.file_loader = Some(Arc::new(move |_, _, with: crate::media::RawDecode<'_>| {
log.lock().unwrap().push(with.outliers);
Ok((Rgb32f::new(8, 8), SourceInfo { raw: is_raw.load(std::sync::atomic::Ordering::Relaxed), ..Default::default() }))
}));
let set = |s: &mut crate::Session, on: bool| {
let mut d = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone();
d.detail.nr_outliers = on;
// a new edit each time, so a render cached for earlier settings is not simply shown again
d.light.exposure += 0.1;
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(d), label: "box".into(), edited: None }).unwrap();
};
let render = |s: &mut crate::Session| {
let r = s.thumb_job(PhotoId(1), 256).unwrap().run();
s.accept(&r);
};
render(&mut s);
render(&mut s);
assert_eq!(*asked.lock().unwrap(), [false], "decoded once, then cached");
set(&mut s, true);
render(&mut s);
render(&mut s);
assert_eq!(*asked.lock().unwrap(), [false, true], "switched on: decoded again with the filter, then cached");
set(&mut s, false);
render(&mut s);
assert_eq!(*asked.lock().unwrap(), [false, true, false]);
// not a raw: the box changes nothing, the cached source is kept
raw.store(false, std::sync::atomic::Ordering::Relaxed);
s.media.forget(PhotoId(1));
set(&mut s, false);
render(&mut s);
set(&mut s, true);
render(&mut s);
assert_eq!(*asked.lock().unwrap(), [false, true, false, false]);
}
/// With the Detail section's eye off, Remove Hot Pixels contributes nothing either: the raw is decoded without it.
#[test]
fn detail_eye_off_decodes_the_raw_without_hot_pixel_removal() {
let mut s = session();
let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
let log = asked.clone();
s.media.file_loader = Some(Arc::new(move |_, _, with: crate::media::RawDecode<'_>| {
log.lock().unwrap().push(with.outliers);
Ok((Rgb32f::new(8, 8), SourceInfo { raw: true, ..Default::default() }))
}));
for eye in [true, false] {
let mut d = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone();
d.detail.nr_outliers = true;
d.set_section_enabled("detail", eye);
d.light.exposure += 0.1;
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(d), label: "eye".into(), edited: None }).unwrap();
let r = s.thumb_job(PhotoId(1), 256).unwrap().run();
s.accept(&r);
}
assert_eq!(*asked.lock().unwrap(), [true, false]);
}
/// CodeRabbit on #3544: a stand-in job decoding a camera JPEG when Discard Preview Cache clears the
/// cache doesn't put the picture back: it writes for the generation it was made in (memory and
/// disk alike), as render jobs do.
#[test]
fn a_camera_jpeg_decoded_across_a_cache_clear_is_not_kept() {
for on_disk in [false, true] {
let cache = Arc::new(PreviewCache::memory(64 << 20));
let made_in = cache.generation();
let key = Hash128(5);
let quick = QuickJob {
request_id: 1,
photo: PhotoId(1),
key: 2,
cached: Vec::new(),
embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| Some(Rgba8::new(16, 16))), 256)),
embedded_cache: Some((cache.clone(), key, made_in)),
embedded_on_disk: on_disk,
minimum_embedded_edge: None,
small: None,
};
// the user discards the cache while the job is on its way
cache.clear();
assert!(quick.run().rendered.is_ok(), "the stand-in is still shown");
assert!(cache.get_memory(key).is_none(), "on disk {on_disk}: nothing kept in the cleared cache");
// a job made after the clear keeps it as before
let quick = QuickJob {
request_id: 1,
photo: PhotoId(1),
key: 2,
cached: Vec::new(),
embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| Some(Rgba8::new(16, 16))), 256)),
embedded_cache: Some((cache.clone(), key, cache.generation())),
embedded_on_disk: on_disk,
minimum_embedded_edge: None,
small: None,
};
assert!(quick.run().rendered.is_ok());
assert!(cache.get_memory(key).is_some(), "on disk {on_disk}: kept when made after the clear");
}
}
Loaded 100 of 297 files, more files were not shown because too many files have changed in this diff. Show more