mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-29 17:56:12 +01:00
Merge remote-tracking branch 'helge/cull-stack-bursts' into cull-group-dnd
# Conflicts: # crates/ui-egui/src/dialogs/confirm.rs
This commit is contained in:
commit
877ddb01f6
128 files changed
+6916
-1192
No files matched your search
@@ -0,0 +1,28 @@
|
||||
name: House rules
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: house-rules-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
house-rules:
|
||||
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
|
||||
with:
|
||||
rust: true
|
||||
@@ -21,6 +21,12 @@ concurrency:
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
|
||||
credits:
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
@@ -61,7 +67,7 @@ jobs:
|
||||
PY
|
||||
|
||||
release:
|
||||
needs: git-sources
|
||||
needs: [git-sources, credits]
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
@@ -70,6 +76,7 @@ jobs:
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
web-craft-fonts: true
|
||||
version: ${{ inputs.version }}
|
||||
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
|
||||
@@ -1,24 +1,75 @@
|
||||
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
|
||||
## House rules
|
||||
|
||||
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
|
||||
|
||||
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
|
||||
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
|
||||
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
|
||||
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
|
||||
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
|
||||
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
|
||||
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
|
||||
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
|
||||
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
|
||||
10. **Keep secrets and personal details out** of the repository, logs and requests.
|
||||
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
|
||||
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
|
||||
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
|
||||
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
|
||||
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
|
||||
<!-- craft-house-rules:end -->
|
||||
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
|
||||
## Rust Craft repositories
|
||||
|
||||
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
|
||||
|
||||
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
|
||||
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
|
||||
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
|
||||
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
|
||||
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
|
||||
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
|
||||
|
||||
## Licence allowlist
|
||||
|
||||
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
|
||||
|
||||
- `ISC`
|
||||
- `MIT`
|
||||
- `BSD-2-Clause`
|
||||
- `BSD-3-Clause`
|
||||
- `Apache-2.0`
|
||||
- `OFL-1.1`
|
||||
- `Ubuntu-font-1.0`
|
||||
- `Bitstream-Vera`
|
||||
- `CC0-1.0`
|
||||
- `CC-BY-4.0`
|
||||
- `CC-BY-SA-4.0`
|
||||
- `LicenseRef-Public-Domain`
|
||||
|
||||
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
|
||||
<!-- craft-house-rules:end -->
|
||||
|
||||
# LightCraft — instructions for agents
|
||||
|
||||
LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructive raw developer targeting Adobe Lightroom parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../pdfcraft` (Acrobat), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator) and `../filmcraft` (Premiere), with the same conventions.
|
||||
|
||||
## Start every session here
|
||||
1. Read `plan/STATUS.md` (current milestone, next unchecked task, blockers).
|
||||
2. Read the task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README/docs of the crate you touch. Behaviour/visual reference: `plan/lightroom/` (incl. `10-observed-ui.md` + screenshots).
|
||||
3. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for
|
||||
`plan/` is an optional gitignored notebook (status, execution notes, `plan/lightroom/`). Do not ask for it and do not stop when it is absent.
|
||||
1. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for
|
||||
method and evidence, [`docs/target-app-parity.md`](docs/target-app-parity.md). The checklist counts features that
|
||||
*exist*; the real gaps are quality and coverage: camera colour calibration, CR3 / compressed raws, per-model
|
||||
verification, render fidelity against Lightroom, AI models, HDR / video / Classic modules (raw detail:
|
||||
[`docs/raw-parity.md`](docs/raw-parity.md)). A ✅ row is not proof of parity — if you find a ✅ feature that is
|
||||
wrong or incomplete, downgrade it to 🟡 with a note.
|
||||
4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row
|
||||
2. **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 (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.
|
||||
|
||||
`plan/` is gitignored (local-only).
|
||||
path the tracker cites still exists and that `docs/gaps.md` lists each gap once, and `cargo xtask parity --write`
|
||||
refreshes its summary.
|
||||
`plan/` stays optional. Do not stop to ask except for the house-rule list.
|
||||
|
||||
**Merging agent branches:** merge one branch, run `cargo xtask ci`, fix, commit — then the next. Two individually green
|
||||
branches can still break each other (e.g. a new struct field vs. a new constructor).
|
||||
@@ -50,20 +101,31 @@ 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
|
||||
`workspace = true` under a `[lints]` table, 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
|
||||
`workspace = true` under a `[lints]` table 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…).
|
||||
- **Pure Rust** in the product. No C/C++ dependencies.
|
||||
- **Layering** (`plan/architecture.md` §3, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd.
|
||||
- **Layering** (enforced by `cargo xtask layers`; `plan/architecture.md` §3 is optional background): nothing below L5 depends on egui/eframe/winit/rfd.
|
||||
- **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.
|
||||
- **Long-running work shows in the activity stack** ([`docs/background-tasks.md`](docs/background-tasks.md)): anything
|
||||
that runs off the UI thread and can take more than a moment holds a `TaskGuard` from `session.activity.start(kind,
|
||||
label, cancel)` for its whole run. It adopts the cancel flag the job already checks (`Cancel::Flag`), or uses
|
||||
`Cancel::No` when the job can't stop. No progress window, panel or progress toast of its own; its tests assert the row.
|
||||
- **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).
|
||||
- **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.
|
||||
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, wasm).
|
||||
For iteration, `cargo xtask ci --quick` runs fmt, clippy, changed packages' tests, layers, assets, roots,
|
||||
and heif / parity / wasm when touched; it does not replace the full gate before merging branches.
|
||||
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.
|
||||
|
||||
## Assets: icons, images, fonts (ABSOLUTE RULE — never violate)
|
||||
- **Never use any iconography, image, artwork, font, sound or other asset from Adobe products** (no Lightroom/Creative Cloud icons, no screenshots, no presets/profiles/LUTs, no UI bitmaps — not even as a temporary placeholder or "reference copy"). Observing Adobe's UI to imitate *layout and behaviour* is allowed; copying or tracing its assets is not.
|
||||
@@ -82,7 +144,7 @@ of it.
|
||||
then `CRAFT_FONTS_DIR=../craft-fonts cargo run -p lightcraft` (or any cargo/xtask command). `crates/engine/build.rs`
|
||||
embeds the manifest's fonts as `lightcraft_engine::CRAFT_FONTS` (wasm32: BIZ UDPGothic Regular only); `cargo xtask web`
|
||||
ships Noto Sans CJK SC Regular as a separate asset loaded by the UI before startup. The UI
|
||||
(`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter. Unset,
|
||||
(`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter; the UI also falls back on the faces of other scripts (Thai, Arabic, …). Unset,
|
||||
`CRAFT_FONTS` is empty: everything builds, tests and runs, but Chinese and Japanese text lack glyphs. Releases always build
|
||||
with it (`release.yml`, `CRAFT_FONTS_REQUIRED=1`) and ship the fonts' OFL licences. Tests that need these fonts skip
|
||||
without it; the FreeBSD CI job runs them with it.
|
||||
@@ -99,7 +161,9 @@ of it.
|
||||
- **Never send OS-level synthetic input** (osascript/System Events keystrokes or clicks, `cliclick`, accessibility
|
||||
automation): it goes to whatever window is frontmost — the user's terminal or other apps. Drive LightCraft only
|
||||
through its control channel (`ui.key`, `ui.pointer`, `ui.clickWidget`, `ui.menu.invoke`) or headless snapshots.
|
||||
- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`, compare with `plan/lightroom/screenshots/`.
|
||||
- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`. Compare with
|
||||
`plan/lightroom/screenshots/` when available. Without that optional notebook, verify the result against the
|
||||
task's requirements, committed documentation and regression tests; do not request the notebook or block work.
|
||||
- **Unattended (display asleep/locked, CI, nightly runs): prefer headless snapshots** — no window needed:
|
||||
`lightcraft-cli snapshot --demo --script tour.jsonl -o out.png --size 1600x1000` (control-protocol requests,
|
||||
one per line; see `docs/control-protocol.md` → Headless rendering). In a running app use
|
||||
@@ -108,7 +172,9 @@ of it.
|
||||
the running app). See `docs/mcp.md`. Quick non-UI checks: `lightcraft-cli render in.jpg -o out.jpg --set light.exposure=1`.
|
||||
- Export goes through `lightcraft_engine::export` (one encoder for app, CLI, MCP and web); UI-only commands live in
|
||||
`crates/ui-egui/src/menus.rs`.
|
||||
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
|
||||
- Text boxes use `crates/ui-egui/src/widgets/text_field.rs` (`TextField`), not `egui::TextEdit`: it gives every field the
|
||||
Cut / Copy / Paste / Select All menu, Esc restoring the text, and reports how an edit ended. Give each a widget id
|
||||
that is unique on screen. Older fields still on `TextEdit` move over as they are touched.
|
||||
- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-<name>`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`<scratch>/<agent-name>/`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone).
|
||||
- Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media.
|
||||
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
|
||||
@@ -121,7 +187,7 @@ of it.
|
||||
- **Benchmarks:** `cargo xtask bench` (24 MP raw from corpus; CPU and GPU columns) appends to `target/bench/history.jsonl`
|
||||
and flags CPU-time regressions > 20 % vs the previous run (`--strict` to fail). Run it before and after perf work.
|
||||
- **Measure, don't guess**: `LIGHTCRAFT_PROFILE=1` prints per-stage pipeline timings to stderr; time CLI renders
|
||||
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
|
||||
with `/usr/bin/time`. Timings may go in the optional `plan/` notebook. 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
|
||||
|
||||
@@ -1,164 +1 @@
|
||||
# LightCraft — instructions for agents
|
||||
|
||||
LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructive raw developer targeting Adobe Lightroom parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../pdfcraft` (Acrobat), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator) and `../filmcraft` (Premiere), with the same conventions.
|
||||
|
||||
## Start every session here
|
||||
1. Read `plan/STATUS.md` (current milestone, next unchecked task, blockers).
|
||||
2. Read the task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README/docs of the crate you touch. Behaviour/visual reference: `plan/lightroom/` (incl. `10-observed-ui.md` + screenshots).
|
||||
3. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for
|
||||
method and evidence, [`docs/target-app-parity.md`](docs/target-app-parity.md). The checklist counts features that
|
||||
*exist*; the real gaps are quality and coverage: camera colour calibration, CR3 / compressed raws, per-model
|
||||
verification, render fidelity against Lightroom, AI models, HDR / video / Classic modules (raw detail:
|
||||
[`docs/raw-parity.md`](docs/raw-parity.md)). A ✅ row is not proof of parity — if you find a ✅ feature that is
|
||||
wrong or incomplete, downgrade it to 🟡 with a note.
|
||||
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 (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.
|
||||
|
||||
`plan/` is gitignored (local-only).
|
||||
|
||||
**Merging agent branches:** merge one branch, run `cargo xtask ci`, fix, commit — then the next. Two individually green
|
||||
branches can still break each other (e.g. a new struct field vs. a new constructor).
|
||||
|
||||
**Resuming after a crash / another session:** check `git status` on main, `git worktree list`, and each worktree's
|
||||
`git log main..HEAD` + `git status` for unmerged commits or uncommitted work before starting anything new. Commit small
|
||||
and often so a crash loses minutes, not hours.
|
||||
|
||||
## Never crash (outranks feature work)
|
||||
People trust LightCraft with their photo libraries and edits; a crash loses their work. A malformed raw/JPEG/XMP, a bad
|
||||
command, control or MCP argument, a corrupt catalog or settings file, or a full disk must produce an error the user (or
|
||||
agent) can act on, never a panic. Don't ship a feature by adding a panic path, and fix a crash before building on top
|
||||
of it.
|
||||
- **Non-test code never panics:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`, and
|
||||
no `unsafe`. Return the crate's error type through `Result` and `?`; use `ok_or(..)?`, `let … else`, `if let`, or a
|
||||
fallback (`unwrap_or…`) only where it can't silently corrupt a document. An unfinished feature returns an
|
||||
"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) **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.
|
||||
- **Bound recursion** (depth limits or seen-sets: IFD chains, nested metadata, collections). **Don't cascade:**
|
||||
`lock().unwrap_or_else(PoisonError::into_inner)` or an error; worker-thread joins are `Result`s.
|
||||
- **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` 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.
|
||||
|
||||
## 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…).
|
||||
- **Pure Rust** in the product. No C/C++ dependencies.
|
||||
- **Layering** (`plan/architecture.md` §3, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd.
|
||||
- **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.
|
||||
- **Long-running work shows in the activity stack** ([`docs/background-tasks.md`](docs/background-tasks.md)): anything
|
||||
that runs off the UI thread and can take more than a moment holds a `TaskGuard` from `session.activity.start(kind,
|
||||
label, cancel)` for its whole run. It adopts the cancel flag the job already checks (`Cancel::Flag`), or uses
|
||||
`Cancel::No` when the job can't stop. No progress window, panel or progress toast of its own; its tests assert the row.
|
||||
- **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
|
||||
(`.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.
|
||||
|
||||
## Assets: icons, images, fonts (ABSOLUTE RULE — never violate)
|
||||
- **Never use any iconography, image, artwork, font, sound or other asset from Adobe products** (no Lightroom/Creative Cloud icons, no screenshots, no presets/profiles/LUTs, no UI bitmaps — not even as a temporary placeholder or "reference copy"). Observing Adobe's UI to imitate *layout and behaviour* is allowed; copying or tracing its assets is not.
|
||||
- **This includes Adobe's open-licensed assets**: no Source Sans/Serif/Code or Source Han fonts, no Adobe Fonts, no
|
||||
Adobe-published icon sets, sample photos, colour profiles or LUTs — even when OFL/MIT. The UI font is Inter (OFL);
|
||||
Japanese and Chinese fonts come from craft-fonts (below). **One exception (maintainer decision, 2026-10-07): Noto
|
||||
Sans/Serif CJK** (Google-branded, OFL, co-developed with Adobe as Source Han) is allowed via craft-fonts for Chinese
|
||||
text, because nearly every OFL Chinese face derives from it. Use it unmodified under its OFL; this does not open the
|
||||
door to Source Han under Adobe's name or to any other Adobe asset.
|
||||
- Every asset in the repository must be one of: **our own original work** (e.g. icons drawn in code as vectors, procedurally generated demo photos), **public domain / CC0**, **Creative Commons** (CC-BY / CC-BY-SA with attribution honoured), **OFL** (fonts), or **permissive open-source** (MIT/Apache-2.0/BSD/ISC) — or contributed by a person who created the asset and licenses it openly.
|
||||
- **Exception: `docs/brand/`.** The ArtCraft name, wordmark and logos there are ArtCraft Team trademarks, not open source and not covered by LightCraft's MIT OR Apache-2.0 licence (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`); their terms are in `docs/brand/LICENSE-brand.txt`. Use them only unmodified and never redraw, recolour or derive from them.
|
||||
- **Every asset must have an entry in `assets/ATTRIBUTION.md`** (path, title, author/creator, source URL or "original work", licence, date added, modifications) and its licence text when required (e.g. `assets/fonts/OFL-*.txt`). Add the entry in the same commit as the asset. Assets without an attribution entry must not be committed.
|
||||
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo.** Don't commit
|
||||
font files here (Inter, already in `assets/fonts/`, is the one exception); add new fonts to craft-fonts. LightCraft
|
||||
uses it as the optional build input `CRAFT_FONTS_DIR`: `git clone https://github.com/storytold/craft-fonts ../craft-fonts`
|
||||
then `CRAFT_FONTS_DIR=../craft-fonts cargo run -p lightcraft` (or any cargo/xtask command). `crates/engine/build.rs`
|
||||
embeds the manifest's fonts as `lightcraft_engine::CRAFT_FONTS` (wasm32: BIZ UDPGothic Regular only); `cargo xtask web`
|
||||
ships Noto Sans CJK SC Regular as a separate asset loaded by the UI before startup. The UI
|
||||
(`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter; the UI also falls back on the faces of other scripts (Thai, Arabic, …). Unset,
|
||||
`CRAFT_FONTS` is empty: everything builds, tests and runs, but Chinese and Japanese text lack glyphs. Releases always build
|
||||
with it (`release.yml`, `CRAFT_FONTS_REQUIRED=1`) and ship the fonts' OFL licences. Tests that need these fonts skip
|
||||
without it; the FreeBSD CI job runs them with it.
|
||||
- Icons drawn in code (e.g. `crates/ui-egui/src/icons.rs`) are original work and are recorded in `assets/ATTRIBUTION.md` as such; do not trace them from Adobe icons.
|
||||
- Demo/test images: generated procedurally by `lightcraft-scenes`, or CC0 downloads kept in the gitignored `corpus/` with their source recorded. Screenshots of Adobe apps live only in the gitignored `plan/` and are never committed or published.
|
||||
- **Enforced:** `cargo xtask assets` (in `ci`) fails when an image/icon/font/sound/video/raw/ICC/XMP file is not matched
|
||||
by a path pattern in the first column of `assets/ATTRIBUTION.md`, when a referenced licence file is missing, when a
|
||||
file name suggests Adobe material, or when an Adobe profile/template format (`.dcp`, `.lcp`, `.lrtemplate`, …) appears.
|
||||
Never weaken this check to make a commit pass — fix the attribution or remove the asset.
|
||||
- When in doubt about an asset's licence: don't use it.
|
||||
|
||||
## Running and looking at the app
|
||||
- `cargo run --release -p lightcraft -- --control 7980` opens the desktop app with the JSON-lines control server (see `docs/control-protocol.md`).
|
||||
- **Never send OS-level synthetic input** (osascript/System Events keystrokes or clicks, `cliclick`, accessibility
|
||||
automation): it goes to whatever window is frontmost — the user's terminal or other apps. Drive LightCraft only
|
||||
through its control channel (`ui.key`, `ui.pointer`, `ui.clickWidget`, `ui.menu.invoke`) or headless snapshots.
|
||||
- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`, compare with `plan/lightroom/screenshots/`.
|
||||
- **Unattended (display asleep/locked, CI, nightly runs): prefer headless snapshots** — no window needed:
|
||||
`lightcraft-cli snapshot --demo --script tour.jsonl -o out.png --size 1600x1000` (control-protocol requests,
|
||||
one per line; see `docs/control-protocol.md` → Headless rendering). In a running app use
|
||||
`ui.screenshot {"path": …, "headless": true}`; windowed screenshots fall back to headless after 2 s.
|
||||
- MCP: `lightcraft-cli mcp` (headless, `--demo` for the procedural library) or `lightcraft-cli mcp --connect` (drives
|
||||
the running app). See `docs/mcp.md`. Quick non-UI checks: `lightcraft-cli render in.jpg -o out.jpg --set light.exposure=1`.
|
||||
- Export goes through `lightcraft_engine::export` (one encoder for app, CLI, MCP and web); UI-only commands live in
|
||||
`crates/ui-egui/src/menus.rs`.
|
||||
- Text boxes use `crates/ui-egui/src/text_field.rs` (`TextField`), not `egui::TextEdit`: it gives every field the
|
||||
Cut / Copy / Paste / Select All menu, Esc restoring the text, and reports how an edit ended. Give each a widget id
|
||||
that is unique on screen. Older fields still on `TextEdit` move over as they are touched.
|
||||
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
|
||||
- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-<name>`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`<scratch>/<agent-name>/`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone).
|
||||
- Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media.
|
||||
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
|
||||
|
||||
## Testing & performance (do this often)
|
||||
- Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`,
|
||||
`apps/lightcraft-cli/tests/`). New features need at least one test that would fail without them.
|
||||
- **Run the app after every user-visible change**: launch with `--control 7980`, drive it with a JSON-lines script
|
||||
(`docs/showcase/run.py file.jsonl`), take `ui.screenshot`, and look at it. Check `ui.inspect` → `perf`.
|
||||
- **Benchmarks:** `cargo xtask bench` (24 MP raw from corpus; CPU and GPU columns) appends to `target/bench/history.jsonl`
|
||||
and flags CPU-time regressions > 20 % vs the previous run (`--strict` to fail). Run it before and after perf work.
|
||||
- **Measure, don't guess**: `LIGHTCRAFT_PROFILE=1` prints per-stage pipeline timings to stderr; time CLI renders
|
||||
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).
|
||||
|
||||
## Map of the code
|
||||
`geom`, `color`, `raster`, `tiff` (L0) → `raw`, `codecs`, `meta`, `develop` (L1) → `pipeline` → `catalog` → `engine`
|
||||
→ `ui-egui`, `mcp` (L5) → apps `lightcraft` (desktop), `lightcraft-cli` (render/commands/MCP). `scenes` generates demo
|
||||
photos. `xtask` = tooling (`ci`, `layers`, `assets`, `parity`, `wasm`, `corpus`, `stats`); `testkit` = test helpers
|
||||
(dev-dependency only). `flake.nix` +
|
||||
`nix/package.nix` = the Nix package (`nix build` builds both binaries with the craft-fonts input, installs the
|
||||
desktop file/icons/AppStream metadata and runs `cargo test --workspace`; `nix develop` = dev shell). Community-maintained; CI only
|
||||
evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the workspace; see README → Quick start.
|
||||
|
||||
## 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.
|
||||
@AGENTS.md
|
||||
@@ -350,7 +350,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
|
||||
Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera.
|
||||
- **The biggest gaps:**
|
||||
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 and CRW raws have guarded estimates from their camera JPEGs, with built-in Canon EOS D60, ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration covers one model so far (chart-measured matrices for the Canon EOS D60), and other raws or rejected fits retain a neutral matrix;
|
||||
- **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF now decodes sensor data on 58 more bodies (2 verified) ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
|
||||
- **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF is unsupported for sensor decoding and uses embedded JPEG previews when available ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
|
||||
- **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an
|
||||
optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and
|
||||
linear-RGB denoise and Super Resolution remain missing; see [AI masks](docs/ai-masks.md) and [AI Denoise](docs/denoise.md);
|
||||
@@ -370,7 +370,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
|
||||
| Profiles (Color, Neutral, Vivid, Landscape, Portrait, Monochrome: our own looks), presets, versions, history, copy/paste/sync settings | ✅ |
|
||||
| Camera colour: DNG matrices, guarded camera-JPEG look fits and built-in profiles for selected cameras | 🚧 measured calibration and per-model coverage remain incomplete ([raw parity](docs/raw-parity.md)) |
|
||||
| Native macOS menu bar (generated from the command registry), control channel + every widget addressable, headless UI snapshots | ✅ |
|
||||
| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp, compressed), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) |
|
||||
| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed ORF / SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) |
|
||||
| Detail: sharpening, luminance + colour noise reduction | ✅ · AI Denoise 🚧 (Bayer, user-installed weights; [setup](docs/denoise.md)), Super Resolution ⬜ |
|
||||
| Remove / Heal / Clone spots (auto source), non-generative Fill, editable spot pins, Visualize Spots, Red Eye and Pet Eye | ✅ · Fill uses PatchMatch; no generative fill |
|
||||
| Export: JPEG / PNG / TIFF / flat PSD / WebP / AVIF / JPEG XL / raw or rendered DNG / original, sizing, file-size limit, output sharpening, naming templates, batch, metadata policy, text or image watermark | ✅ |
|
||||
|
||||
+5
-3
@@ -30,7 +30,7 @@ Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%):
|
||||
|
||||
The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is
|
||||
estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens
|
||||
as preview (compressed ORF now decodes on 58 more bodies (2 verified)), rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
|
||||
as preview, as does compressed ORF when an embedded preview is available; rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
|
||||
tests run in CI on Linux x64 (every pull request and push to `main`) and FreeBSD (nightly), not on macOS or Windows. **Why alpha:** core workflows run end to end, but readiness is below
|
||||
the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have gaps (Nikon HE NEF opens as preview; Canon,
|
||||
~30% of raw users, decodes CR3 on 26 verified bodies). It passes the alpha gate: all six core workflows
|
||||
@@ -107,14 +107,16 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
|
||||
3. Render-fidelity suite against Lightroom, then tuning (30–60 h)
|
||||
4. ~~Full-resolution zoom~~ (done 2026-10-12)
|
||||
5. AI masks: Subject / Sky / People (40–70 h + model decision)
|
||||
6. ~~Compressed ORF~~ (done 2026-11-04) and HE NEF (20–40 h)
|
||||
6. Compressed ORF (support withdrawn; estimate pending provenance review) and HE NEF (20–40 h)
|
||||
7. Lens profile database of our own (40–80 h, #329)
|
||||
8. Tests in CI on macOS and Windows, and the GPU tests in CI (6–12 h)
|
||||
9. Per-model raw verification (20–35 h)
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-04: Olympus / OM System compressed ORF decodes from sensor data: clean-room pure-Rust bitstream decoder (`crates/raw/src/vendor/orfc.rs`) derived strictly from Olympus patents US7333035B2/US7715639B2, maker notes and CC0 samples without third-party decoder code (see `docs/orf-compression.md`), verified on OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) CC0 samples; 58 bodies newly unlocked (78 total across Olympus and OM; OM/Olympus 6% → 81% fully working, overall weighted camera coverage 94% → 97%).
|
||||
- 2026-11-07: Compressed ORF support withdrawn pending provenance review; uncompressed support remains. Regenerated camera coverage: 557 verified, 665 unverified, 187 preview-only and 37 unsupported; 94% use-weighted coverage. See [ORF status](docs/orf-compression.md).
|
||||
|
||||
- 2026-11-04: Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available.
|
||||
- 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判
|
||||
(89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200),
|
||||
六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog
|
||||
|
||||
@@ -468,7 +468,11 @@ mod tests {
|
||||
let mut core = WorkerCore::default();
|
||||
assert_eq!(core.needs_original(&wire), None, "demo scenes are generated");
|
||||
let a = core.render(&wire, None).unwrap();
|
||||
let b = job.run().rendered.unwrap();
|
||||
// The worker uses the CPU. A native thumbnail job may use an already initialized GPU,
|
||||
// so exact serialization parity must use the engine's CPU reference (#3778), regardless
|
||||
// of test order. The window test above separately checks native CPU/GPU equivalence.
|
||||
let source = job.source.load_source().unwrap();
|
||||
let b = lightcraft_engine::pipeline::render(&source.image, &source.info_or(job.info), &job.settings, &job.request);
|
||||
assert_eq!((a.image.width, a.image.height), (b.image.width, b.image.height));
|
||||
assert_eq!(a.image.data, b.image.data);
|
||||
assert_eq!(a.histogram, b.histogram);
|
||||
|
||||
@@ -54,7 +54,12 @@ impl Files {
|
||||
if let Some(d) = p.parent() {
|
||||
let _ = std::fs::create_dir_all(d);
|
||||
}
|
||||
if let Err(e) = std::fs::write(&p, format!("{}\n", r.name())) {
|
||||
// on disk before the driver is touched: a driver fault can take the machine down with it
|
||||
let written = std::fs::File::create(&p).and_then(|mut f| {
|
||||
std::io::Write::write_all(&mut f, format!("{}\n", r.name()).as_bytes())?;
|
||||
f.sync_all()
|
||||
});
|
||||
if let Err(e) = written {
|
||||
log::warn!("window: could not write {}: {e}", p.display());
|
||||
}
|
||||
}
|
||||
@@ -95,7 +100,7 @@ pub fn choose(files: &Files, compose_window: bool) -> Chosen {
|
||||
let order = backend::window_renderer_order(forced, remembered, failed, os, compiled, true);
|
||||
let mut problems = Vec::new();
|
||||
let chosen = if cfg!(windows) {
|
||||
pick_probed(&order, &mut problems, compose_window)
|
||||
pick_probed(files, &order, &mut problems, compose_window)
|
||||
} else if forced == Some(WindowRenderer::Glow) || (forced.is_none() && failed.is_some_and(|f| f != WindowRenderer::Glow)) {
|
||||
// elsewhere eframe's own wgpu set-up stays the default; glow after a failed start
|
||||
Some((WindowRenderer::Glow, None))
|
||||
@@ -168,11 +173,20 @@ pub fn base_options() -> WgpuConfiguration {
|
||||
}
|
||||
|
||||
/// The first renderer of `order` that probes cleanly (glow is taken without a probe).
|
||||
fn pick_probed(order: &[WindowRenderer], problems: &mut Vec<String>, compose_window: bool) -> Option<(WindowRenderer, Option<WgpuSetupExisting>)> {
|
||||
fn pick_probed(
|
||||
files: &Files,
|
||||
order: &[WindowRenderer],
|
||||
problems: &mut Vec<String>,
|
||||
compose_window: bool,
|
||||
) -> Option<(WindowRenderer, Option<WgpuSetupExisting>)> {
|
||||
for &r in order {
|
||||
match r {
|
||||
WindowRenderer::Glow => return Some((r, None)),
|
||||
WindowRenderer::Wgpu(b) => {
|
||||
// name the renderer being probed before the crash-prone device
|
||||
// creation and egui pipeline compile: if the driver kills the
|
||||
// start, the marker survives so the next launch tries it last
|
||||
files.arm(r);
|
||||
let probed = std::panic::catch_unwind(|| probe(b, compose_window)).unwrap_or_else(|_| Err("panicked".into()));
|
||||
match probed {
|
||||
Ok(e) => return Some((r, Some(e))),
|
||||
@@ -205,7 +219,8 @@ fn probe(backends: Backends, compose_window: bool) -> Result<WgpuSetupExisting,
|
||||
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { adapter.limits() };
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("egui wgpu device"),
|
||||
required_limits: wgpu::Limits { max_texture_dimension_2d: 8192, ..base },
|
||||
// (GL takes the conservative defaults for everything else, whose 2048 is too small for a window)
|
||||
required_limits: wgpu::Limits { max_texture_dimension_2d: adapter.limits().max_texture_dimension_2d, ..base },
|
||||
..Default::default()
|
||||
}))
|
||||
.map_err(|e| format!("{}: no device: {e}", adapter.get_info().name))?;
|
||||
@@ -383,6 +398,22 @@ mod tests {
|
||||
let _ = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl("not wgsl".into()) });
|
||||
}
|
||||
|
||||
/// The probed device keeps the adapter's own `max_texture_dimension_2d`, so a window
|
||||
/// ballooned past 8192 px can still configure its surface. Needs an adapter; skipped
|
||||
/// where there is none (CI without a GPU).
|
||||
#[test]
|
||||
fn probed_device_uses_adapter_max_texture_size() {
|
||||
let Ok(setup) = probe(backend::window_backends(), false) else {
|
||||
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
|
||||
return;
|
||||
};
|
||||
assert_eq!(
|
||||
setup.device.limits().max_texture_dimension_2d,
|
||||
setup.adapter.limits().max_texture_dimension_2d,
|
||||
"the probed device must use the adapter's own max_texture_dimension_2d, not a fixed 8192 cap",
|
||||
);
|
||||
}
|
||||
|
||||
/// The workaround is opt-in and changes presentation only for Windows DX12.
|
||||
#[test]
|
||||
fn composition_only_changes_windows_dx12_presentation() {
|
||||
@@ -400,4 +431,22 @@ mod tests {
|
||||
}
|
||||
assert!(!composes_window(true, WindowRenderer::Glow));
|
||||
}
|
||||
|
||||
/// The probe builds egui's pipeline on a live device before the window opens; a driver crash
|
||||
/// there must leave the window-init marker on disk so the next launch tries another renderer.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_window_marker_is_written_while_the_renderer_is_probed() {
|
||||
// glow is taken without a probe, so a forced glow arms nothing here
|
||||
let forced =
|
||||
backend::forced_window_renderer(std::env::var("LIGHTCRAFT_GPU_BACKEND").ok().as_deref(), std::env::var("WGPU_BACKEND").ok().as_deref());
|
||||
if forced == Some(WindowRenderer::Glow) {
|
||||
return;
|
||||
}
|
||||
let d = dir("probe-marker");
|
||||
let f = Files::new(Some(d.clone()));
|
||||
choose(&f, false);
|
||||
assert!(f.armed(), "the window-init marker must be written while the renderer is probed");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -222,8 +222,8 @@ pub enum Op {
|
||||
/// `None` = its raw data decodes (or it isn't a raw).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
preview_only: Option<String>,
|
||||
/// The app version that decided `preview_only` (see [`Photo::preview_checked`]); empty
|
||||
/// when it is `None`.
|
||||
/// The app version that decided `preview_only` (see [`Photo::preview_checked`]); also
|
||||
/// retained for supported ORF files so their withdrawal recheck runs only once.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
preview_checked: String,
|
||||
},
|
||||
|
||||
@@ -171,11 +171,26 @@ pub fn parse_shutter_seconds(s: &str) -> Option<f64> {
|
||||
#[serde(default)]
|
||||
pub struct Meta {
|
||||
pub camera: String,
|
||||
/// The camera's maker, from Exif `Make` (`camera` is maker and model together).
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub make: String,
|
||||
pub lens: String,
|
||||
/// The lens's maker, from Exif `LensMake`.
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub lens_make: String,
|
||||
pub focal_mm: Option<f32>,
|
||||
pub aperture: Option<f32>,
|
||||
pub shutter: String,
|
||||
pub iso: Option<u32>,
|
||||
/// Whether the flash fired, from Exif `Flash`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub flash: Option<bool>,
|
||||
/// Exposure compensation in EV, from Exif `ExposureBiasValue`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub exposure_bias: Option<f32>,
|
||||
/// The camera body's serial number.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub serial_number: String,
|
||||
/// Place (sublocation, e.g. a landmark).
|
||||
pub location: String,
|
||||
pub city: String,
|
||||
@@ -301,10 +316,10 @@ pub struct Photo {
|
||||
/// picture style baked in — so it is treated as a rendered (non-raw) source.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub preview_only: Option<String>,
|
||||
/// The app version (`CARGO_PKG_VERSION`) whose decoder set [`Photo::preview_only`]; empty when
|
||||
/// it isn't set, and in catalogs from before format v9. A preview-only photo whose stamp
|
||||
/// differs from the running version is rechecked when its library opens (issue #662): newer
|
||||
/// builds may decode the file, older ones may decode less.
|
||||
/// The app version (`CARGO_PKG_VERSION`) whose decoder checked [`Photo::preview_only`].
|
||||
/// Also set for supported ORF files: compressed ORF support was withdrawn after #3775, so
|
||||
/// old sensor-decodable records need rechecking too. Empty for other supported formats and
|
||||
/// legacy records. A stale stamp is rechecked when the library opens (issue #662).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub preview_checked: String,
|
||||
/// A Local record: the fingerprint of its state when the browse catalogued it, to tell
|
||||
@@ -428,13 +443,18 @@ impl Photo {
|
||||
}
|
||||
/// Sets [`Photo::preview_only`] as this build decided it, with its stamp.
|
||||
pub fn set_preview_only(&mut self, preview_only: Option<String>) {
|
||||
self.preview_checked = preview_stamp(&preview_only);
|
||||
self.preview_checked = self.preview_stamp(&preview_only);
|
||||
self.preview_only = preview_only;
|
||||
}
|
||||
/// A preview-only photo whose flag was set by another app version (or before stamps existed),
|
||||
/// so this build should probe its file again (issue #662).
|
||||
/// The stamp for a fresh probe. Supported ORFs keep it too, so the support-withdrawal
|
||||
/// recheck runs once, without repeatedly probing uncompressed ORFs on every library open.
|
||||
pub fn preview_stamp(&self, preview_only: &Option<String>) -> String {
|
||||
if self.format.eq_ignore_ascii_case("orf") { APP_VERSION.to_string() } else { preview_stamp(preview_only) }
|
||||
}
|
||||
/// A preview-only photo or ORF whose support was checked by another app version (or before
|
||||
/// stamps existed), so this build should probe its file again (issues #662 and #3775).
|
||||
pub fn preview_only_stale(&self) -> bool {
|
||||
self.preview_only.is_some() && self.preview_checked != APP_VERSION
|
||||
(self.preview_only.is_some() || self.format.eq_ignore_ascii_case("orf")) && self.preview_checked != APP_VERSION
|
||||
}
|
||||
/// A raw file developed from its sensor data: not a rendered image, and not a raw shown from
|
||||
/// its embedded preview ([`Photo::preview_only`]).
|
||||
|
||||
@@ -105,6 +105,9 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[
|
||||
("aperture", "Aperture", Kind::Number),
|
||||
("shutterSpeed", "Shutter Speed", Kind::Number),
|
||||
("iso", "ISO Speed", Kind::Number),
|
||||
("flash", "Flash", Kind::Bool),
|
||||
("exposureBias", "Exposure Bias", Kind::Number),
|
||||
("cameraSerial", "Camera Serial Number", Kind::Text),
|
||||
// Location
|
||||
("location", "Location", Kind::Text),
|
||||
("city", "City", Kind::Text),
|
||||
@@ -136,7 +139,7 @@ pub const FIELD_GROUPS: &[(&str, &[&str])] = &[
|
||||
("Date", &["captureDate", "importDate", "editDate"]),
|
||||
("Keywords & People", &["keywords", "keywordCount", "person", "personCount"]),
|
||||
("Description", &["title", "caption", "altText", "creator", "copyright", "copyrightStatus"]),
|
||||
("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso"]),
|
||||
("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso", "flash", "exposureBias", "cameraSerial"]),
|
||||
("Location", &["location", "city", "state", "country", "hasGps"]),
|
||||
("Size", &["longEdge", "shortEdge", "aspect", "megapixels"]),
|
||||
("Develop", &["edited", "cropped", "treatment"]),
|
||||
@@ -1099,6 +1102,9 @@ impl Rule {
|
||||
"editDate" => date_op(op, p.edited.as_deref(), value),
|
||||
"shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)),
|
||||
"iso" => num_op(op, m.iso.map(|v| v as f64), value),
|
||||
"flash" => yes(m.flash.unwrap_or(false)),
|
||||
"exposureBias" => num_op(op, m.exposure_bias.map(f32_as_decimal), value),
|
||||
"cameraSerial" => text(&m.serial_number),
|
||||
"aperture" => num_op(op, m.aperture.map(f32_as_decimal), value),
|
||||
"focalLength" => num_op(op, m.focal_mm.map(f32_as_decimal), value),
|
||||
"longEdge" | "shortEdge" => {
|
||||
@@ -1146,7 +1152,7 @@ impl Rule {
|
||||
"text" | "filePath" | "location" => COST_TEXT,
|
||||
"keywords" | "person" | "personCount" | "stacked" | "copyName" | "fileName" | "extension" | "format" | "title" | "caption"
|
||||
| "altText" | "city" | "state" | "country" | "camera" | "lens" | "creator" | "copyright" | "captureDate" | "importDate"
|
||||
| "editDate" | "shutterSpeed" | "aspect" => COST_SMALL,
|
||||
| "editDate" | "shutterSpeed" | "aspect" | "flash" | "cameraSerial" | "exposureBias" => COST_SMALL,
|
||||
_ => COST_SCALAR,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -385,6 +385,27 @@ fn in_the_last_survives_hostile_counts() {
|
||||
set_now(None);
|
||||
}
|
||||
|
||||
/// Flash, exposure bias and camera serial number can be tested by a rule, like the other
|
||||
/// camera info; an unrecorded one is empty (or zero bias is no bias).
|
||||
#[test]
|
||||
fn flash_exposure_bias_and_serial_rules() {
|
||||
let cat = Catalog::new();
|
||||
// the values arrive with the photo's metadata, as fields on its meta, as probed from a file
|
||||
let mut v = serde_json::to_value(photo(1)).unwrap();
|
||||
let meta = v.get_mut("meta").unwrap();
|
||||
meta["flash"] = json!(true);
|
||||
meta["exposure_bias"] = json!(-0.67);
|
||||
meta["serial_number"] = json!("SN-X2");
|
||||
let p: Photo = serde_json::from_value(v).unwrap();
|
||||
let m = |field: &str, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(&p, &cat);
|
||||
assert!(m("flash", "is", json!(true)) && !m("flash", "is", json!(false)));
|
||||
assert!(m("exposureBias", "lt", json!(0)) && m("exposureBias", "between", json!([-1.0, -0.3])));
|
||||
assert!(m("cameraSerial", "contains", json!("x2")));
|
||||
assert_eq!(field_group("flash"), Some("Camera Info"));
|
||||
assert_eq!(field_group("exposureBias"), Some("Camera Info"));
|
||||
assert_eq!(field_group("cameraSerial"), Some("Camera Info"));
|
||||
}
|
||||
|
||||
/// Every rule's value is checked against its field, so a rule that can't mean anything is
|
||||
/// reported instead of quietly matching nothing (or everything). Each problem says which rule
|
||||
/// it is about: "rule 2", or "rule 2.1" inside a group.
|
||||
|
||||
@@ -12,6 +12,26 @@ fn photo(c: &mut Catalog, name: &str, date: &str) -> PhotoId {
|
||||
id
|
||||
}
|
||||
|
||||
/// ORF probes record both supported and preview-only outcomes, without changing other formats.
|
||||
#[test]
|
||||
fn orf_support_checks_keep_a_stamp_even_when_sensor_data_decodes() {
|
||||
let mut p = Photo::new(PhotoId(1), Source::File { path: "a.orf".into() }, "a.orf", "ORF", 4, 3, "2026-01-01");
|
||||
p.kind = MediaKind::Raw;
|
||||
assert!(p.preview_only_stale(), "legacy supported ORF needs the withdrawal recheck");
|
||||
p.set_preview_only(None);
|
||||
assert_eq!(p.preview_checked, APP_VERSION);
|
||||
assert!(!p.preview_only_stale());
|
||||
assert!(p.develops_raw(), "supported uncompressed ORF remains sensor-decodable");
|
||||
p.set_preview_only(Some("Olympus compressed ORF".into()));
|
||||
assert_eq!(p.preview_checked, APP_VERSION);
|
||||
assert!(!p.preview_only_stale());
|
||||
assert!(!p.develops_raw());
|
||||
p.format = "DNG".into();
|
||||
p.set_preview_only(None);
|
||||
assert!(p.preview_checked.is_empty(), "other supported formats keep their existing semantics");
|
||||
assert!(!p.preview_only_stale());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_token_matches_time_part_case_insensitively() {
|
||||
let mut c = Catalog::new();
|
||||
|
||||
@@ -93,12 +93,15 @@ pub enum Process {
|
||||
/// 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,
|
||||
/// V5, with colour noise reduction on the linear colour differences R−Y and B−Y, leaving Y alone, with
|
||||
/// edge-aware weights from a denoised guide and a brake for isolated colour specks (issue #815).
|
||||
V6,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
/// Every process, oldest first.
|
||||
pub const ALL: [Process; 5] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5];
|
||||
pub const LATEST: Process = Process::V5;
|
||||
pub const ALL: [Process; 6] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6];
|
||||
pub const LATEST: Process = Process::V6;
|
||||
|
||||
pub const fn version(self) -> ProcessVersion {
|
||||
match self {
|
||||
@@ -107,6 +110,7 @@ impl Process {
|
||||
Process::V3 => ProcessVersion(3),
|
||||
Process::V4 => ProcessVersion(4),
|
||||
Process::V5 => ProcessVersion(5),
|
||||
Process::V6 => ProcessVersion(6),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()?))
|
||||
|
||||
@@ -206,7 +206,7 @@ fn edit_copy(s: &mut Session, p: &Value, id: lightcraft_catalog::PhotoId, opts:
|
||||
/// preview-only photo this version hasn't checked yet: its stamp is refreshed so it isn't probed
|
||||
/// again (see [`lightcraft_catalog::Photo::preview_checked`]).
|
||||
pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: crate::media::ProbeInfo) -> Option<Op> {
|
||||
let preview_checked = lightcraft_catalog::preview_stamp(&info.preview_only);
|
||||
let preview_checked = ph.preview_stamp(&info.preview_only);
|
||||
let same = info.content_hash == ph.content_hash
|
||||
&& info.file_size == ph.file_size
|
||||
&& (info.width, info.height) == (ph.width, ph.height)
|
||||
@@ -233,12 +233,23 @@ fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::P
|
||||
if m.lens.is_empty() {
|
||||
m.lens = src.lens.clone();
|
||||
}
|
||||
if m.make.is_empty() {
|
||||
m.make = src.make.clone();
|
||||
}
|
||||
if m.lens_make.is_empty() {
|
||||
m.lens_make = src.lens_make.clone();
|
||||
}
|
||||
if m.shutter.is_empty() {
|
||||
m.shutter = src.shutter.clone();
|
||||
}
|
||||
m.focal_mm = m.focal_mm.or(src.focal_mm);
|
||||
m.aperture = m.aperture.or(src.aperture);
|
||||
m.iso = m.iso.or(src.iso);
|
||||
m.flash = m.flash.or(src.flash);
|
||||
m.exposure_bias = m.exposure_bias.or(src.exposure_bias);
|
||||
if m.serial_number.is_empty() {
|
||||
m.serial_number = src.serial_number.clone();
|
||||
}
|
||||
m.gps = m.gps.or(src.gps);
|
||||
// the camera's focus point: photos imported before it was read get it here
|
||||
if m.focus.is_none() {
|
||||
|
||||
@@ -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));
|
||||
@@ -1162,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"))?;
|
||||
@@ -1336,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}");
|
||||
}
|
||||
}
|
||||
@@ -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 })
|
||||
|
||||
@@ -1348,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)?;
|
||||
|
||||
@@ -266,7 +266,7 @@ pub fn find_candidates(cat: &Catalog) -> Vec<FindCandidate> {
|
||||
pub enum MatchBy {
|
||||
/// Same name and size (and content, when the library knows its hash).
|
||||
Name,
|
||||
/// Renamed: same size and content hash.
|
||||
/// Renamed: same content hash (and size, when the library knows it).
|
||||
Content,
|
||||
}
|
||||
|
||||
@@ -360,8 +360,8 @@ fn name_key(path: &str) -> String {
|
||||
/// Matching, per photo:
|
||||
/// 1. a file with the same name ([`name_key`]: any letter case), the same size and the same
|
||||
/// content hash;
|
||||
/// 2. renamed: a file of the same size with the same content hash (only same-size files are
|
||||
/// read, so this stays cheap);
|
||||
/// 2. renamed: a file with the same content hash (and the same size, when one is on record; with
|
||||
/// no size on record every file is read, but the hash alone confirms identity);
|
||||
/// 3. without a hash to confirm (or the file was edited in place): the one file with the same
|
||||
/// name and size. Several such files are ambiguous: the photo is skipped and reported in
|
||||
/// `ambiguous`, never guessed (two cameras' `IMG_0001.CR3` of one size are different photos).
|
||||
@@ -406,24 +406,27 @@ pub fn plan_find_missing(candidates: &[FindCandidate], folder: &str) -> std::res
|
||||
// 1. same name and size, confirmed by the content hash
|
||||
let mut hit: Option<(String, MatchBy)> =
|
||||
hash.and_then(|h| named.iter().find(|f| hash_of(f).as_deref() == Some(h))).map(|f| (f.to_string(), MatchBy::Name));
|
||||
// 2. renamed: same size and content
|
||||
// 2. renamed: same content, and same size when one is on record
|
||||
if hit.is_none()
|
||||
&& let Some(h) = hash
|
||||
&& size > 0
|
||||
{
|
||||
let sizes = by_size.get_or_insert_with(|| {
|
||||
let mut m: HashMap<u64, Vec<String>> = HashMap::new();
|
||||
for f in &files {
|
||||
if let Some(n) = size_of(f) {
|
||||
m.entry(n).or_default().push(f.clone());
|
||||
if size > 0 {
|
||||
let sizes = by_size.get_or_insert_with(|| {
|
||||
let mut m: HashMap<u64, Vec<String>> = HashMap::new();
|
||||
for f in &files {
|
||||
if let Some(n) = size_of(f) {
|
||||
m.entry(n).or_default().push(f.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
});
|
||||
hit = sizes
|
||||
.get(&size)
|
||||
.and_then(|v| v.iter().find(|f| !used.contains(*f) && hash_of(f).as_deref() == Some(h)))
|
||||
.map(|f| (f.clone(), MatchBy::Content));
|
||||
m
|
||||
});
|
||||
hit = sizes
|
||||
.get(&size)
|
||||
.and_then(|v| v.iter().find(|f| !used.contains(*f) && hash_of(f).as_deref() == Some(h)))
|
||||
.map(|f| (f.clone(), MatchBy::Content));
|
||||
} else {
|
||||
hit = files.iter().find(|f| !used.contains(*f) && hash_of(f).as_deref() == Some(h)).map(|f| (f.clone(), MatchBy::Content));
|
||||
}
|
||||
}
|
||||
// 3. same name and size only (no hash, or the file was edited in place): one candidate
|
||||
// is taken, several are ambiguous and skipped rather than guessed
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
//! library opens in another version, its stale preview-only photos are probed again and get
|
||||
//! exactly what Reload from Disk would give them: a file that decodes now loses the flag, one that
|
||||
//! still doesn't gets the new reason and a fresh stamp, so it isn't probed again.
|
||||
//! ORF records are rechecked even when previously sensor-decodable: compressed sensor support
|
||||
//! was withdrawn after #3775. Supported uncompressed ORFs also keep a stamp to avoid repeat work.
|
||||
//!
|
||||
//! The work is split so the app can probe on a worker thread: [`stale`] lists what to probe (no
|
||||
//! file-system calls), [`probe`] reads the files without the session, and [`apply`] applies the
|
||||
@@ -17,7 +19,7 @@ use super::{CommandSpec, always, bad, cmd};
|
||||
use crate::media::{FileProbe, ProbeInfo};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// A preview-only photo to probe, and what the library knew about it when it was listed (so a
|
||||
/// A photo to probe, and what the library knew about it when it was listed (so a
|
||||
/// result for a photo that changed meanwhile is dropped).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Stale {
|
||||
@@ -40,12 +42,12 @@ impl Stale {
|
||||
}
|
||||
}
|
||||
|
||||
/// The library's preview-only photos whose flag another app version set (or every preview-only
|
||||
/// photo, with `all`): library photos with a file, not virtual copies (they follow the photo they
|
||||
/// were copied from). No file-system calls.
|
||||
/// The library's preview-only photos and ORFs whose support another app version checked (or
|
||||
/// every such photo, with `all`): library photos with a file, not virtual copies (they follow
|
||||
/// the photo they were copied from). No file-system calls.
|
||||
pub fn stale(cat: &Catalog, all: bool) -> Vec<Stale> {
|
||||
cat.photos()
|
||||
.filter(|p| p.copy_of.is_none() && p.preview_only.is_some() && (all || p.preview_only_stale()))
|
||||
.filter(|p| p.copy_of.is_none() && (p.preview_only_stale() || (all && (p.preview_only.is_some() || p.format.eq_ignore_ascii_case("orf")))))
|
||||
.filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Stale::of(p, path)))
|
||||
.collect()
|
||||
}
|
||||
@@ -92,7 +94,7 @@ pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result<ProbeInfo
|
||||
let first = out.updated.len();
|
||||
crate::cmd::convert::reload_ops(&s.catalog, item.id, &info, &mut ops, &mut out.updated);
|
||||
if info.preview_only.is_none() {
|
||||
out.cleared.extend_from_slice(&out.updated[first..]);
|
||||
out.cleared.extend(out.updated[first..].iter().copied().filter(|id| s.catalog.photo(*id).is_some_and(|p| p.preview_only.is_some())));
|
||||
}
|
||||
}
|
||||
if !ops.is_empty() {
|
||||
@@ -122,7 +124,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recheck Preview-Only Raws",
|
||||
[],
|
||||
None,
|
||||
"{all?: bool} — probe again the raws shown from their embedded preview whose flag another LightCraft version set (the app does this in the background when a library opens; `all` rechecks every preview-only raw, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}",
|
||||
"{all?: bool} — probe again preview-only raws and ORFs whose support another LightCraft version checked (the app does this in the background when a library opens; `all` rechecks every preview-only raw and ORF, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}",
|
||||
always,
|
||||
recheck
|
||||
)]
|
||||
|
||||
@@ -64,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;
|
||||
@@ -2,6 +2,7 @@ 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);
|
||||
|
||||
@@ -334,7 +334,11 @@ pub fn export_metadata(photo: &lightcraft_catalog::Photo, catalog: &lightcraft_c
|
||||
out.gps = m.gps.map(|(latitude, longitude)| Gps { latitude, longitude, altitude: None });
|
||||
}
|
||||
if o.metadata == MetadataPolicy::All {
|
||||
out.model = text(&m.camera);
|
||||
// `camera` is maker and model together: Exif keeps them apart, and a photo from before
|
||||
// the maker was read keeps the whole string as its Model
|
||||
out.make = text(&m.make);
|
||||
out.model = text(m.camera.strip_prefix(m.make.as_str()).and_then(|rest| rest.strip_prefix(' ')).unwrap_or(&m.camera));
|
||||
out.lens_make = text(&m.lens_make);
|
||||
out.lens_model = text(&m.lens);
|
||||
out.focal_length = m.focal_mm.map(f64::from);
|
||||
out.f_number = m.aperture.map(f64::from);
|
||||
|
||||
@@ -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?}");
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -7,12 +7,17 @@ pub(super) fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option<String>) {
|
||||
let camera = [m.make.clone().unwrap_or_default(), m.model.clone().unwrap_or_default()].join(" ").trim().to_string();
|
||||
let meta = Meta {
|
||||
camera,
|
||||
make: m.make.clone().unwrap_or_default(),
|
||||
lens_make: m.lens_make.clone().unwrap_or_default(),
|
||||
// (a camera that writes no lens name, like Nikon's DSLRs, still says what range the lens covers)
|
||||
lens: m.lens_model.clone().or_else(|| m.lens_spec.and_then(lightcraft_meta::lens_spec_name)).unwrap_or_default(),
|
||||
focal_mm: m.focal_length.map(|f| f as f32),
|
||||
aperture: m.f_number.map(|f| f as f32),
|
||||
shutter,
|
||||
iso: m.iso,
|
||||
flash: m.flash.map(|f| f.fired),
|
||||
exposure_bias: m.exposure_bias.map(|v| v as f32),
|
||||
serial_number: m.serial_number.clone().unwrap_or_default(),
|
||||
location: m.sublocation.clone().unwrap_or_default(),
|
||||
city: m.city.clone().unwrap_or_default(),
|
||||
state: m.state.clone().unwrap_or_default(),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -291,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 {
|
||||
|
||||
@@ -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".
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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"))]
|
||||
|
||||
@@ -705,7 +705,12 @@ fn mapped_settings(
|
||||
) -> Result<(Value, Vec<String>), String> {
|
||||
let mut root = crate::preset_import::parse_lua(text)?;
|
||||
let deferred = strip_lua_sentinels(&mut root);
|
||||
let (mut props, values) = crate::preset_import::lua_settings_props(&root)?;
|
||||
let (mut props, mut values) = crate::preset_import::lua_settings_props(&root)?;
|
||||
// Catalog Lua names the component inversion `Inverted` while XMP's is `MaskInverted`;
|
||||
// rename it so an inverted mask keeps its inversion instead of importing as normal.
|
||||
for v in values.values_mut() {
|
||||
alias_catalog_inverted(v);
|
||||
}
|
||||
// A catalog's develop settings carry the crop edges and angle but no `HasCrop` (XMP has it):
|
||||
// any crop field means the photo is cropped.
|
||||
const CROP: [&str; 5] = ["crs:CropLeft", "crs:CropTop", "crs:CropRight", "crs:CropBottom", "crs:CropAngle"];
|
||||
@@ -787,6 +792,24 @@ fn in_photo_frame(catalog: Orientation, user: Orientation) -> Orientation {
|
||||
(0..turns).fold(o, |o, _| o.rotated(true))
|
||||
}
|
||||
|
||||
/// Rename a catalog Lua component's `Inverted` to XMP's `MaskInverted` (see [`mapped_settings`]);
|
||||
/// a `crs:MaskInverted` already present wins, and this does not touch `Flipped`.
|
||||
fn alias_catalog_inverted(v: &mut lightcraft_meta::XmpValue) {
|
||||
use lightcraft_meta::XmpValue;
|
||||
match v {
|
||||
XmpValue::Array(items) => items.iter_mut().for_each(alias_catalog_inverted),
|
||||
XmpValue::Struct(map) => {
|
||||
if let Some(inverted) = map.remove("crs:Inverted")
|
||||
&& !map.contains_key("crs:MaskInverted")
|
||||
{
|
||||
map.insert("crs:MaskInverted".into(), inverted);
|
||||
}
|
||||
map.values_mut().for_each(alias_catalog_inverted);
|
||||
}
|
||||
XmpValue::Text(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lightroom's masks in LightCraft's frame. Like the crop's corners, their positions are on the
|
||||
/// stored image (before orientation), normalized to its size; LightCraft's are on the oriented
|
||||
/// image. So the points go through the orientation, a radial's radii (in long-edge units, from the
|
||||
|
||||
@@ -850,6 +850,22 @@ fn catalog_masks_follow_the_photo_orientation() {
|
||||
assert!(close(&radial["rx"], 0.1) && close(&radial["ry"], 0.1), "{radial}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverted_radial_mask_keeps_its_inversion_on_import() {
|
||||
// #2475: an inverted radial (LocalExposure2012 applies outside the ellipse) keeps its
|
||||
// inversion when the catalog import also turns the mask for the photo's orientation
|
||||
let s = r#"s = { MaskGroupBasedCorrections = { { What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.1, CorrectionMasks = {
|
||||
{ What = "Mask/CircularGradient", Left = 0, Right = 0.2, Top = 0.1, Bottom = 0.3, Angle = 10, Feather = 50, Version = 2, Flipped = true, Inverted = true } } } } }"#;
|
||||
let (partial, _) = mapped_settings(s, crate::crs::Target::RawAbsolute, 1.5, Orientation::Rotate90, 1.5, Orientation::Normal).unwrap();
|
||||
let c = &partial["masks"][0]["components"][0];
|
||||
let close = |v: &Value, want: f64| (v.as_f64().unwrap() - want).abs() < 1e-9;
|
||||
// the orientation is applied: (x, y) → (1 − y, x), a quarter turn clockwise; the radii swap
|
||||
let shape = &c["shape"];
|
||||
assert!(close(&shape["center"]["x"], 0.8) && close(&shape["center"]["y"], 0.1), "{shape}");
|
||||
// but the effect stays outside the ellipse
|
||||
assert!(c["invert"].as_bool().unwrap_or(false) || shape["invert"].as_bool().unwrap_or(false), "{c}");
|
||||
}
|
||||
|
||||
/// The `crs` corners and angle Lightroom would store for LightCraft crop `g` on a stored image
|
||||
/// of aspect `w` (height 1) shown with orientation `o`.
|
||||
fn lightroom_crop(g: CropGeometry, o: Orientation, w: f64) -> String {
|
||||
@@ -1122,7 +1138,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));
|
||||
}
|
||||
|
||||
@@ -131,14 +131,31 @@ pub(super) fn embedded_thumb_key(k: Hash128) -> Hash128 {
|
||||
Hasher128::new().str("embedded-thumb").u64((k.0 >> 64) as u64).u64(k.0 as u64).finish()
|
||||
}
|
||||
|
||||
/// What identifies a photo's pixels for caching: its content hash, else its source.
|
||||
/// Which decode of a photo a loaded source is: its file's content and, when it has one, its database lens profile
|
||||
/// ORF decoding changed when compressed sensor support was withdrawn. Keep its old renders
|
||||
/// out even before catalog rechecking finishes, and distinguish sensor from preview-only
|
||||
/// pixels after Reload. Other formats keep their existing keys. This is deliberately not
|
||||
/// part of `content_key`: smart previews and denoise products identify the original file.
|
||||
pub(super) fn decoder_key(p: &Photo) -> u64 {
|
||||
if !p.format.eq_ignore_ascii_case("ORF") {
|
||||
return 0;
|
||||
}
|
||||
// Spread the status bit: this salt is XORed with frontend dimensions, so adjacent
|
||||
// integers could cancel a small resize occurring at the same time as a recheck.
|
||||
let h = Hasher128::new().str("orf-withdrawal-v1").u64(u64::from(p.preview_only.is_some())).finish();
|
||||
((h.0 as u64) ^ ((h.0 >> 64) as u64)) | 1
|
||||
}
|
||||
|
||||
/// Which decode of a photo a loaded source is: its file's content, decoder identity and database lens profile
|
||||
/// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still
|
||||
/// matches when the job finishes ([`super::Session::accept`]), so a decode started before a profile change never
|
||||
/// returns to the cache after `cmd::lens_refresh` has dropped the photo's sources.
|
||||
pub fn source_identity(p: &Photo) -> Hash128 {
|
||||
let mut k = Hasher128::new();
|
||||
k.str(&content_key(p));
|
||||
let decoder = decoder_key(p);
|
||||
if decoder != 0 {
|
||||
k.str("decoder").u64(decoder);
|
||||
}
|
||||
let lens = lens_key(p);
|
||||
if lens != 0 {
|
||||
k.u64(lens);
|
||||
|
||||
@@ -57,6 +57,7 @@ impl crate::Session {
|
||||
let content_key = content_key(&p);
|
||||
let content = Hasher128::new().str(&content_key).finish().0 as u64;
|
||||
let source_key = super::quick::source_identity(&p);
|
||||
let decoder = super::quick::decoder_key(&p);
|
||||
// Temporary "before" settings must not replace the photo's cached develop hash.
|
||||
let settings_hash =
|
||||
if before { settings.hash64() ^ crate::files::hot_pixel_key(&settings) } else { self.media.settings_hashes.get(id, &settings) };
|
||||
@@ -72,7 +73,8 @@ impl crate::Session {
|
||||
^ content.rotate_left(17)
|
||||
^ salt
|
||||
^ profile_salt.rotate_left(29)
|
||||
^ lens.rotate_left(37);
|
||||
^ lens.rotate_left(37)
|
||||
^ decoder.rotate_left(43);
|
||||
let cache = thumb_bucket.map(|b| {
|
||||
let mut k = Hasher128::new();
|
||||
k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION);
|
||||
@@ -89,6 +91,9 @@ impl crate::Session {
|
||||
if lens != 0 {
|
||||
k.u64(lens);
|
||||
}
|
||||
if decoder != 0 {
|
||||
k.str("decoder").u64(decoder);
|
||||
}
|
||||
(self.media.rendered.clone(), k.finish())
|
||||
});
|
||||
Some(RenderJob {
|
||||
@@ -131,6 +136,7 @@ impl crate::Session {
|
||||
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
|
||||
// (the photo's database lens profile stays part of it: a profile looked up again renders afresh)
|
||||
let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p));
|
||||
let decoder = super::quick::decoder_key(&p);
|
||||
job.key = settings.hash64()
|
||||
^ crate::files::hot_pixel_key(settings)
|
||||
^ ((max_w as u64) << 40)
|
||||
@@ -138,7 +144,8 @@ impl crate::Session {
|
||||
^ (apply_crop as u64)
|
||||
^ (job.level as u64) << 60
|
||||
^ profile_salt.rotate_left(29)
|
||||
^ lens.rotate_left(37);
|
||||
^ lens.rotate_left(37)
|
||||
^ decoder.rotate_left(43);
|
||||
Some(job)
|
||||
}
|
||||
|
||||
@@ -159,6 +166,10 @@ impl crate::Session {
|
||||
if lens != 0 {
|
||||
k.u64(lens);
|
||||
}
|
||||
let decoder = super::quick::decoder_key(p);
|
||||
if decoder != 0 {
|
||||
k.str("decoder").u64(decoder);
|
||||
}
|
||||
k.finish()
|
||||
}
|
||||
|
||||
@@ -294,6 +305,10 @@ impl crate::Session {
|
||||
if lens != 0 {
|
||||
k.u64(lens);
|
||||
}
|
||||
let decoder = super::quick::decoder_key(p);
|
||||
if decoder != 0 {
|
||||
k.str("decoder").u64(decoder);
|
||||
}
|
||||
k.finish()
|
||||
}
|
||||
|
||||
@@ -422,7 +437,7 @@ impl crate::Session {
|
||||
.u64(id.0)
|
||||
.u64(profile_salt)
|
||||
.finish();
|
||||
let key = h.0 as u64;
|
||||
let key = h.0 as u64 ^ super::quick::decoder_key(&p).rotate_left(43);
|
||||
let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge())));
|
||||
let embedded_cache = embedded.as_ref().map(|(_, _, edge)| {
|
||||
let cache = self.media.rendered.clone();
|
||||
|
||||
@@ -226,7 +226,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_denoise::hash::sha256_hex;
|
||||
|
||||
@@ -98,7 +98,7 @@ pub struct PageStyle {
|
||||
pub page_numbers: bool,
|
||||
/// The print settings (sharpening, profile, resolution) at the bottom left of each page.
|
||||
pub page_info: bool,
|
||||
/// Marks at the corners of each photo to cut along.
|
||||
/// Marks at the corners of each photo to cut along (the packages' Cut Guides reuse this).
|
||||
pub crop_marks: bool,
|
||||
}
|
||||
|
||||
@@ -116,7 +116,8 @@ pub fn rec2020_from_srgb8(c: [u8; 3]) -> [u16; 3] {
|
||||
}
|
||||
|
||||
/// Whether a layout style prints the Page Options (page numbers, page info, crop marks):
|
||||
/// Lightroom offers them for Single Image and Contact Sheet; its packages have Cut Guides instead.
|
||||
/// Lightroom offers them for Single Image and Contact Sheet. Its packages have Cut Guides
|
||||
/// instead, which print whatever this says ([`PageStyle::crop_marks`]).
|
||||
pub fn has_page_options(style: Style) -> bool {
|
||||
!style.is_package()
|
||||
}
|
||||
@@ -452,6 +453,8 @@ struct Marks {
|
||||
crop: Option<(usize, usize, usize)>,
|
||||
numbers: bool,
|
||||
info: Option<String>,
|
||||
/// Marks go at each cell's corners (a package's Cut Guides, outside any border), not the photo's.
|
||||
around_cells: bool,
|
||||
ink: [u16; 3],
|
||||
text_px: f32,
|
||||
/// The printable area: the text sits in the margin below it, aligned with its sides.
|
||||
@@ -464,9 +467,10 @@ impl Marks {
|
||||
let page = &settings.page;
|
||||
let px = |inches: f64| (inches * ppi).round() as usize;
|
||||
Marks {
|
||||
crop: (on && page.crop_marks).then(|| (px(CROP_MARK_IN), px(CROP_MARK_GAP_IN), px(CROP_MARK_PT / 72.0).max(1))),
|
||||
crop: page.crop_marks.then(|| (px(CROP_MARK_IN), px(CROP_MARK_GAP_IN), px(CROP_MARK_PT / 72.0).max(1))),
|
||||
numbers: on && page.page_numbers,
|
||||
info: (on && page.page_info).then(|| page_info_text(settings)),
|
||||
around_cells: !on,
|
||||
ink: rec2020_from_srgb8(mark_ink(page.background)),
|
||||
text_px: (PAGE_TEXT_PT / 72.0 * ppi) as f32,
|
||||
area: settings.layout.printable().ok().and_then(|a| px_rect(&a, ppi, pw, ph)),
|
||||
@@ -609,7 +613,9 @@ impl Prepared {
|
||||
}
|
||||
};
|
||||
let photo = &cache.get(at).ok_or("render cache lost an entry")?.1;
|
||||
placed.push(draw_cell(&mut page, photo, item.cell, &self.style).map_err(|e| format!("{}: {e}", item.name))?);
|
||||
let cell = item.cell;
|
||||
let drawn = draw_cell(&mut page, photo, cell, &self.style).map_err(|e| format!("{}: {e}", item.name))?;
|
||||
placed.push(if self.marks.around_cells { cell } else { drawn });
|
||||
}
|
||||
self.marks.draw(&mut page, &placed, index + 1);
|
||||
out.push(PageRaster { width: w as u32, height: h as u32, ppi: self.ppi, rgb: page.rgb });
|
||||
|
||||
@@ -373,13 +373,19 @@ fn page_numbers_and_info_print_in_the_bottom_margin() {
|
||||
for p in &info {
|
||||
assert!(inked(p, left.0, left.1, 550, 600) > 10, "the print settings line");
|
||||
}
|
||||
// the packages have no Page Options in Lightroom: nothing is drawn
|
||||
let all = PageStyle { page_numbers: true, page_info: true, crop_marks: true, ..Default::default() };
|
||||
// the packages have no page numbers or page info in Lightroom: nothing is drawn
|
||||
let all = PageStyle { page_numbers: true, page_info: true, ..Default::default() };
|
||||
let package = page_options_pages(&mut s, Style::PicturePackage, all);
|
||||
assert_eq!(package.len(), 2);
|
||||
for p in &package {
|
||||
assert_eq!(inked(p, 0, 400, 550, 600) + inked(p, 0, 400, 0, 50), 0);
|
||||
}
|
||||
// their Cut Guides are the crop marks, at each photo's corners
|
||||
let guides = page_options_pages(&mut s, Style::PicturePackage, PageStyle { crop_marks: true, ..Default::default() });
|
||||
assert_eq!(guides.len(), 2);
|
||||
for (g, p) in guides.iter().zip(&package) {
|
||||
assert!(inked(g, 0, 400, 0, 600) > inked(p, 0, 400, 0, 600), "the guides add ink");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -945,6 +945,30 @@ fn metadata_none_in_any_case_exports_no_metadata() {
|
||||
assert!(m.gps.is_none() && m.city.is_none(), "{m:?}");
|
||||
}
|
||||
|
||||
/// A raw's Exif Make, Model and LensMake reach an exported JPEG apart, as stitching tools read them.
|
||||
#[test]
|
||||
fn export_writes_camera_make_and_lens_make_to_exif() {
|
||||
let dir = temp_dir("export-raw-exif");
|
||||
let src = dir.join("Canon.dng");
|
||||
let meta = lightcraft_meta::Metadata {
|
||||
make: Some("Canon".into()),
|
||||
model: Some("EOS R5".into()),
|
||||
lens_make: Some("Sigma".into()),
|
||||
lens_model: Some("RF 24-105mm f/4L IS USM".into()),
|
||||
..Default::default()
|
||||
};
|
||||
std::fs::write(&src, synthetic_dng_with(None, meta)).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
let id = s.catalog.photos().next().unwrap().id;
|
||||
let e = export_photo(&mut s, id, &ExportOptions::from_json(&json!({"format": "jpeg", "longEdge": 64, "metadata": "all"})), 1).unwrap();
|
||||
let back = lightcraft_meta::extract(&e.bytes);
|
||||
assert_eq!(back.make.as_deref(), Some("Canon"), "EXIF Make is missing: {back:?}");
|
||||
assert_eq!(back.model.as_deref(), Some("EOS R5"), "EXIF Model holds the model alone: {back:?}");
|
||||
assert_eq!(back.lens_make.as_deref(), Some("Sigma"), "EXIF LensMake is missing: {back:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An original raw whose own metadata holds GPS is refused under "Remove location info".
|
||||
#[test]
|
||||
fn remove_location_refuses_a_raw_that_embeds_gps() {
|
||||
|
||||
@@ -494,6 +494,40 @@ fn find_missing_matches_renamed_files_by_content() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A renamed file whose size is unknown (0) but whose content hash is known is still found by
|
||||
/// content: the hash alone is enough to confirm it is the same photo.
|
||||
#[test]
|
||||
fn find_missing_matches_renamed_file_by_content_without_size() {
|
||||
use lightcraft_catalog::{Op, Photo, Source};
|
||||
let dir = temp_dir("missing-no-size");
|
||||
std::fs::create_dir_all(dir.join("found")).unwrap();
|
||||
let content = b"same pixels as the original";
|
||||
let renamed = dir.join("found").join("Trip-001.png");
|
||||
std::fs::write(&renamed, content).unwrap();
|
||||
let hash = lightcraft_preview::hash_bytes(content).to_string();
|
||||
let mut s = Session::new();
|
||||
let id = s.catalog.alloc_photo_id();
|
||||
let mut p = Photo::new(
|
||||
id,
|
||||
Source::File { path: dir.join("gone").join("orig.png").to_string_lossy().into_owned() },
|
||||
"orig.png",
|
||||
"PNG",
|
||||
48,
|
||||
32,
|
||||
"2026-01-01T10:00:00",
|
||||
);
|
||||
p.file_size = 0;
|
||||
p.content_hash = Some(hash);
|
||||
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
let r = s.execute("library.findMissing", &json!({"folder": dir.join("found").to_string_lossy()})).unwrap();
|
||||
let found = r["found"].as_array().map(Vec::len);
|
||||
assert_eq!(found, Some(1), "renamed file matched by content without a recorded size: {r}");
|
||||
assert_eq!(r["found"][0]["to"], json!(renamed.to_string_lossy().to_string()), "{r}");
|
||||
assert_eq!(r["found"][0]["by"], json!("content"), "{r}");
|
||||
assert_eq!(r["missing"], 0, "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Issue #104: the app plans Find Missing on a worker thread (no session) and relinks the plan
|
||||
/// afterwards; that gives exactly what the synchronous command gives — renamed files by content,
|
||||
/// impostors and look-alikes skipped (`ambiguous`).
|
||||
@@ -853,7 +887,7 @@ fn import_rename_sequence_keeps_flushed_copy_and_move_results() {
|
||||
assert!(paths[3].is_file(), "the failed source remains in place");
|
||||
assert_eq!(r["moved"].as_array().map(Vec::len), Some(3), "{r}");
|
||||
}
|
||||
_ => unreachable!(),
|
||||
other => panic!("no such mode: {other}"),
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -1600,6 +1634,44 @@ fn assisted_culling_burst_limits_are_adjustable() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A box blur of radius `r`: the larger `r`, the lower the focus score.
|
||||
fn soften(img: &lightcraft_raster::Rgb32f, r: usize) -> lightcraft_raster::Rgb32f {
|
||||
let (w, h) = (img.width, img.height);
|
||||
let mut out = img.clone();
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let (mut acc, mut n) = ([0f32; 3], 0.0);
|
||||
for yy in y.saturating_sub(r)..(y + r + 1).min(h) {
|
||||
for xx in x.saturating_sub(r)..(x + r + 1).min(w) {
|
||||
let c = img.data[yy * w + xx];
|
||||
acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]];
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
out.data[y * w + x] = acc.map(|v| v / n);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Write a linear image as an sRGB PNG.
|
||||
fn save_png(img: &lightcraft_raster::Rgb32f, path: &std::path::Path) {
|
||||
let data: Vec<[u8; 4]> = img
|
||||
.data
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8;
|
||||
[e(c[0]), e(c[1]), e(c[2]), 255]
|
||||
})
|
||||
.collect();
|
||||
let png = lightcraft_codecs::encode_png(
|
||||
&lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }),
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(path, png).unwrap();
|
||||
}
|
||||
|
||||
/// Assisted culling with `stackGroups` (#2277): each burst becomes one collapsed stack with its
|
||||
/// sharpest photo on top, an unrelated photo stays loose, analysis and stack are one undo step,
|
||||
/// and a second run neither makes another stack nor splits the existing one.
|
||||
@@ -1607,40 +1679,7 @@ fn assisted_culling_burst_limits_are_adjustable() {
|
||||
fn assisted_culling_stacks_each_burst_best_on_top() {
|
||||
let dir = temp_dir("cull-stack");
|
||||
let scene = lightcraft_scenes::demo_library()[0].render(480, 320);
|
||||
let soften = |img: &lightcraft_raster::Rgb32f, r: usize| {
|
||||
let (w, h) = (img.width, img.height);
|
||||
let mut out = img.clone();
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let (mut acc, mut n) = ([0f32; 3], 0.0);
|
||||
for yy in y.saturating_sub(r)..(y + r + 1).min(h) {
|
||||
for xx in x.saturating_sub(r)..(x + r + 1).min(w) {
|
||||
let c = img.data[yy * w + xx];
|
||||
acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]];
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
out.data[y * w + x] = acc.map(|v| v / n);
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
let save = |img: &lightcraft_raster::Rgb32f, name: &str| {
|
||||
let data: Vec<[u8; 4]> = img
|
||||
.data
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8;
|
||||
[e(c[0]), e(c[1]), e(c[2]), 255]
|
||||
})
|
||||
.collect();
|
||||
let png = lightcraft_codecs::encode_png(
|
||||
&lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }),
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(dir.join(name), png).unwrap();
|
||||
};
|
||||
let save = |img: &lightcraft_raster::Rgb32f, name: &str| save_png(img, &dir.join(name));
|
||||
save(&soften(&scene, 3), "a_soft.png");
|
||||
save(&scene, "b_sharp.png");
|
||||
save(&soften(&scene, 6), "c_softer.png");
|
||||
@@ -1714,6 +1753,49 @@ fn assisted_culling_stacks_each_burst_best_on_top() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Assisted culling with `stackGroups` (#2277): two bursts make two stacks in one undo step, and a
|
||||
/// deleted photo is measured but left out of its burst's stack, even when it is the sharpest.
|
||||
#[test]
|
||||
fn assisted_culling_stacks_two_bursts_and_leaves_deleted_photos_out() {
|
||||
let dir = temp_dir("cull-stack-two");
|
||||
let (one, two) = (lightcraft_scenes::demo_library()[0].render(480, 320), lightcraft_scenes::demo_library()[7].render(480, 320));
|
||||
let files = [
|
||||
("a_soft.png", soften(&one, 3), "10:00:00"),
|
||||
("b_sharp.png", one.clone(), "10:00:01"),
|
||||
("c_softer.png", soften(&one, 6), "10:00:02"),
|
||||
("d_sharp.png", two.clone(), "10:05:00"),
|
||||
("e_soft.png", soften(&two, 4), "10:05:01"),
|
||||
];
|
||||
for (name, img, _) in &files {
|
||||
save_png(img, &dir.join(name));
|
||||
}
|
||||
let mut s = Session::new().with_fs();
|
||||
s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap();
|
||||
let by_name = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id;
|
||||
for (name, _, at) in &files {
|
||||
let id = by_name(&s, name);
|
||||
s.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T{at}")) }).unwrap();
|
||||
}
|
||||
let [soft, sharp, softer, d, e] = files.map(|f| by_name(&s, f.0));
|
||||
let ids: Vec<u64> = [soft, sharp, softer, d, e].iter().map(|p| p.0).collect();
|
||||
s.commit("t", lightcraft_catalog::Op::SetDeleted { id: sharp, deleted: true }).unwrap();
|
||||
let n = s.commits();
|
||||
let r = s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap();
|
||||
assert_eq!((r["groups"].clone(), r["stacks"].clone()), (json!(2), json!(2)), "{r}");
|
||||
assert_eq!(s.commits(), n + 1, "analysis and both stacks are one undo step");
|
||||
// the deleted photo is measured, but its burst is stacked from the other two
|
||||
assert!(s.catalog.photo(sharp).unwrap().analysis.is_some());
|
||||
assert!(s.catalog.stack_of(sharp).is_none(), "a deleted photo is never stacked");
|
||||
let st = s.catalog.stack_of(soft).unwrap();
|
||||
assert!(st.collapsed && st.top() == soft && st.photos.len() == 2 && st.photos.contains(&softer), "{st:?}");
|
||||
let st = s.catalog.stack_of(d).unwrap();
|
||||
assert!(st.collapsed && st.top() == d && st.photos.len() == 2 && st.photos.contains(&e), "{st:?}");
|
||||
// one undo removes both stacks
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.catalog.stacks().next().is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Find Dust Spots: soft dark spots on a smooth sky are found and healed (one undo step).
|
||||
#[test]
|
||||
fn dust_spots_are_found_and_healed() {
|
||||
@@ -3253,6 +3335,319 @@ fn a_file_arriving_beside_its_raws_stem_reads_its_own_sidecar() {
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// A batch-edit recipe changes the imported photos' actual develop settings (not just an option
|
||||
/// label), renders, is one undo step, and can be saved as a preset that stores only what it names.
|
||||
#[test]
|
||||
fn a_batch_edit_recipe_changes_imported_photos() {
|
||||
let src = temp_dir("recipe");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
write_png(&src.join("b.png"), 2);
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s
|
||||
.execute(
|
||||
"library.import",
|
||||
&json!({
|
||||
"paths": [src.to_string_lossy()],
|
||||
"recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}],
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 2, "{r}");
|
||||
for p in s.catalog.photos() {
|
||||
assert_eq!(p.develop.light.exposure, 0.5, "{}", p.file_name);
|
||||
assert_eq!(p.develop.color.vibrance, 20.0, "{}", p.file_name);
|
||||
assert!(p.history.iter().any(|h| h.label == "Import adjustments"), "{}", p.file_name);
|
||||
}
|
||||
// the edit really renders (the recipe is applied to the settings, not only recorded)
|
||||
let id = s.catalog.photos().next().unwrap().id;
|
||||
assert!(s.render_now(id, 32, 32).is_ok());
|
||||
// saving the recipe as a preset keeps only the settings it names
|
||||
let p = s.execute("preset.saveRecipe", &json!({"name": "Warm Trip", "recipe": [{"id": "light.exposure", "value": 0.5}]})).unwrap();
|
||||
let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(0.5)), "{}", saved.settings);
|
||||
assert!(saved.settings.get("color").is_none(), "an unnamed group is not stored: {}", saved.settings);
|
||||
// one undo step for the whole import
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.catalog.len(), 0);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// A malformed recipe, or one naming a control a recipe may not name, is refused before anything
|
||||
/// is imported, and by the command that saves one: unknown ids, controls that belong to one photo,
|
||||
/// geometry and crop controls (the slider refits the crop around them), white balance (a
|
||||
/// temperature means something else on each kind of file), and lists longer than the control list.
|
||||
#[test]
|
||||
fn a_bad_recipe_is_refused() {
|
||||
let mut s = Session::new().with_fs();
|
||||
let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": [{"id": "nope.nope", "value": 1}]})).unwrap_err();
|
||||
assert!(format!("{err}").contains("unknown recipe control"), "{err}");
|
||||
let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": "x"})).unwrap_err();
|
||||
assert!(format!("{err}").contains("recipe"), "{err}");
|
||||
assert_eq!(s.catalog.len(), 0);
|
||||
let too_many: Vec<Value> = (0..lightcraft_develop::controls::CONTROLS.len() + 1).map(|_| json!({"id": "light.exposure", "value": 1})).collect();
|
||||
for (bad, why) in [
|
||||
(json!([{"value": 1}]), "needs an `id`"),
|
||||
(json!([{"id": "light.exposure"}]), "numeric"),
|
||||
(json!([{"id": "light.exposure", "value": "high"}]), "numeric"),
|
||||
(json!([7]), "needs an `id`"),
|
||||
(json!([{"id": "pointColor.0.hueShift", "value": 5}]), "unknown recipe control"),
|
||||
(json!([{"id": "redEye.0.pupilSize", "value": 5}]), "unknown recipe control"),
|
||||
(json!([{"id": "crop.angle", "value": 5}]), "geometry"),
|
||||
(json!([{"id": "geometry.rotate", "value": 5}]), "geometry"),
|
||||
(json!([{"id": "wb.temp", "value": 5200}]), "white balance"),
|
||||
(json!([{"id": "wb.tint", "value": 5}]), "white balance"),
|
||||
(json!([{"id": "light.exposure", "value": 1}, {"id": "crop.angle", "value": 5}]), "geometry"),
|
||||
(json!(too_many), "at most"),
|
||||
] {
|
||||
let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": bad})).unwrap_err().to_string();
|
||||
assert!(err.contains(why), "{why}: {err}");
|
||||
let before = s.presets.len();
|
||||
let err = s.execute("preset.saveRecipe", &json!({"name": "Bad", "recipe": bad})).unwrap_err().to_string();
|
||||
assert!(err.contains(why), "{why}: {err}");
|
||||
assert_eq!(s.presets.len(), before, "nothing saved for {why}");
|
||||
}
|
||||
// the job itself refuses what the command would (a recipe built in code, not from JSON)
|
||||
let opts = crate::import::ImportOptions { recipe: vec![("crop.angle".into(), 5.0)], ..Default::default() };
|
||||
assert!(crate::import::ImportJob::new(&mut s, opts).is_err());
|
||||
// no name, a name that is too long, or nothing in the recipe: no preset
|
||||
let one = json!([{"id": "light.exposure", "value": 1}]);
|
||||
for params in [json!({"recipe": one}), json!({"name": " ", "recipe": one}), json!({"name": "x".repeat(101), "recipe": one})] {
|
||||
assert!(s.execute("preset.saveRecipe", ¶ms).is_err(), "{params}");
|
||||
}
|
||||
assert!(s.execute("preset.saveRecipe", &json!({"name": "x".repeat(100), "recipe": one})).is_ok(), "a name of 100 characters is fine");
|
||||
assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty", "recipe": []})).is_err());
|
||||
assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty"})).is_err());
|
||||
assert!(!s.presets.iter().any(|p| p.name == "Empty"));
|
||||
}
|
||||
|
||||
/// The recipe's values go through the control specs like a slider's: past the range they stop at
|
||||
/// it, for the photo and for the preset. A control named twice counts once, the last value wins.
|
||||
#[test]
|
||||
fn recipe_values_are_clamped_like_a_slider() {
|
||||
let src = temp_dir("recipe-clamp");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
let mut s = Session::new().with_fs();
|
||||
let recipe = json!([{"id": "light.exposure", "value": 1}, {"id": "light.exposure", "value": 99}, {"id": "light.contrast", "value": -1000}]);
|
||||
s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
let p = s.catalog.photos().next().unwrap();
|
||||
assert_eq!((p.develop.light.exposure, p.develop.light.contrast), (5.0, -100.0));
|
||||
let saved = s.execute("preset.saveRecipe", &json!({"name": "Clamped", "recipe": recipe})).unwrap();
|
||||
let saved = s.presets.iter().find(|x| x.id == saved["id"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(5.0)), "{}", saved.settings);
|
||||
assert_eq!(saved.settings.pointer("/light/contrast"), Some(&json!(-100.0)), "{}", saved.settings);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// A session whose files probe as DNG raws shot at 4800 K, tint +12 (the pixels stay the PNG's;
|
||||
/// nothing here renders them), to see what an import does to a raw's as-shot white balance.
|
||||
fn session_with_raw_probe() -> Session {
|
||||
let mut s = Session::new().with_fs();
|
||||
let real = s.media.file_probe.clone().unwrap();
|
||||
s.media.file_probe = Some(std::sync::Arc::new(move |path: &str| {
|
||||
let mut info = real(path)?;
|
||||
info.kind = lightcraft_catalog::MediaKind::Raw;
|
||||
info.format = "DNG".into();
|
||||
info.as_shot_wb = Some((4800.0, 12.0));
|
||||
Ok(info)
|
||||
}));
|
||||
s
|
||||
}
|
||||
|
||||
fn import_one(s: &mut Session, path: &Path, recipe: Value) -> lightcraft_catalog::PhotoId {
|
||||
let r = s.execute("library.import", &json!({"paths": [path.to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
lightcraft_catalog::PhotoId(r["imported"][0].as_u64().unwrap_or_else(|| panic!("{path:?} not imported: {r}")))
|
||||
}
|
||||
|
||||
fn white_balance(s: &Session, id: lightcraft_catalog::PhotoId) -> lightcraft_develop::WhiteBalance {
|
||||
s.catalog.photo(id).unwrap().develop.wb
|
||||
}
|
||||
|
||||
/// A recipe never touches white balance: a raw keeps the as-shot temperature, tint and scale it was
|
||||
/// imported with, whatever else the recipe sets, and a recipe cannot name a temperature or tint.
|
||||
#[test]
|
||||
fn a_recipe_leaves_a_raws_as_shot_white_balance_alone() {
|
||||
use lightcraft_develop::{WbMode, WbScale};
|
||||
let src = temp_dir("recipe-wb");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
write_png(&src.join("b.png"), 2);
|
||||
let mut s = session_with_raw_probe();
|
||||
let plain = import_one(&mut s, &src.join("a.png"), json!([]));
|
||||
let w = white_balance(&s, plain);
|
||||
assert_eq!((w.mode, w.temp, w.tint, w.scale), (WbMode::AsShot, 4800.0, 12.0, WbScale::Kelvin), "{w:?}");
|
||||
let with = import_one(&mut s, &src.join("b.png"), json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 30}]));
|
||||
assert_eq!(white_balance(&s, with), w, "the as-shot white balance is as the import left it");
|
||||
assert_eq!(s.catalog.photo(with).unwrap().develop.light.exposure, 0.5);
|
||||
for id in ["wb.temp", "wb.tint"] {
|
||||
let err = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": [{"id": id, "value": 5200}]})).unwrap_err();
|
||||
assert!(err.to_string().contains("white balance"), "{err}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// Saved as a preset and applied to a photo as it was imported, a recipe gives the settings
|
||||
/// importing with it gives (for a raw too), and the preset holds a control the recipe sets to its
|
||||
/// default: that is a reset, not "nothing named".
|
||||
#[test]
|
||||
fn a_recipe_saved_as_a_preset_gives_what_the_recipe_gives() {
|
||||
let src = temp_dir("recipe-preset");
|
||||
let recipes = [
|
||||
json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]),
|
||||
json!([{"id": "light.exposure", "value": 99}]),
|
||||
json!([{"id": "detail.sharpenAmount", "value": 0}, {"id": "grain.amount", "value": 30}]),
|
||||
json!([{"id": "vignette.amount", "value": -25}, {"id": "effects.clarity", "value": 15}, {"id": "mixer.red.hue", "value": 10}]),
|
||||
];
|
||||
let mut s = session_with_raw_probe();
|
||||
for (i, recipe) in recipes.iter().enumerate() {
|
||||
write_png(&src.join(format!("with{i}.png")), 2 * i as u8);
|
||||
write_png(&src.join(format!("plain{i}.png")), 2 * i as u8 + 1);
|
||||
let with = import_one(&mut s, &src.join(format!("with{i}.png")), recipe.clone());
|
||||
let plain = import_one(&mut s, &src.join(format!("plain{i}.png")), json!([]));
|
||||
let saved = s.execute("preset.saveRecipe", &json!({"name": format!("Recipe {i}"), "recipe": recipe})).unwrap();
|
||||
s.selection = crate::Selection::single(plain);
|
||||
s.execute("preset.apply", &json!({"id": saved["id"], "ids": [plain.0]})).unwrap();
|
||||
let (with, plain) = (s.catalog.photo(with).unwrap(), s.catalog.photo(plain).unwrap());
|
||||
assert_eq!(with.develop, plain.develop, "recipe {recipe}");
|
||||
}
|
||||
// the sharpening reset (a raw's default is 40) is in the preset although 0 is the control's default
|
||||
let reset = s.presets.iter().find(|p| p.name == "Recipe 2").unwrap();
|
||||
assert_eq!(reset.settings.pointer("/detail/sharpen_amount"), Some(&json!(0.0)), "{}", reset.settings);
|
||||
assert_eq!(s.catalog.photos().find(|p| p.file_name == "with2.png").unwrap().develop.detail.sharpen_amount, 0.0);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// The recipe applies to the photos an import adds. A file the library has (by path or by
|
||||
/// content), a trashed one that comes back, and a browsed one that joins keep their own
|
||||
/// settings; a trashed one imported afresh is a new photo and gets the recipe.
|
||||
#[test]
|
||||
fn a_recipe_only_touches_the_photos_an_import_adds() {
|
||||
let src = temp_dir("recipe-skipped");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
write_png(&src.join("b.png"), 2);
|
||||
write_png(&src.join("c.png"), 3);
|
||||
std::fs::copy(src.join("a.png"), src.join("a-copy.png")).unwrap(); // same bytes as a
|
||||
let recipe = json!([{"id": "color.vibrance", "value": 20}]);
|
||||
let adjusted = |s: &Session, name: &str| {
|
||||
let p = s.catalog.photos().find(|p| p.file_name == name && !p.deleted).unwrap_or_else(|| panic!("no {name}"));
|
||||
(p.develop.color.vibrance, p.history.iter().any(|h| h.label == "Import adjustments"))
|
||||
};
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let first = import_one(&mut s, &src.join("a.png"), json!([]));
|
||||
s.selection = crate::Selection::single(first);
|
||||
s.execute("develop.set", &json!({"control": "light.exposure", "value": 1.5})).unwrap();
|
||||
let a_before = s.catalog.photo(first).unwrap().develop.clone();
|
||||
|
||||
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 2, "{r}"); // b and c
|
||||
assert_eq!(ids(&r, "duplicates"), 2, "{r}"); // a (same path) and a-copy (same content)
|
||||
assert_eq!(adjusted(&s, "b.png"), (20.0, true));
|
||||
assert_eq!(adjusted(&s, "c.png"), (20.0, true));
|
||||
assert_eq!(adjusted(&s, "a.png"), (0.0, false), "a duplicate is not edited");
|
||||
assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "nor is the photo it duplicates");
|
||||
assert_eq!(s.catalog.len(), 3);
|
||||
|
||||
// in Recently Deleted: restored with its own settings, no recipe
|
||||
s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
assert_eq!((ids(&r, "imported"), ids(&r, "restored")), (0, 1), "{r}");
|
||||
assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "a restored photo keeps its edits");
|
||||
assert!(!s.catalog.photo(first).unwrap().history.iter().any(|h| h.label == "Import adjustments"));
|
||||
|
||||
// …imported afresh, it is a new photo and gets the recipe
|
||||
s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe, "onDeleted": "fresh"})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1, "{r}");
|
||||
assert_eq!(adjusted(&s, "a.png"), (20.0, true));
|
||||
|
||||
// browsed first (Local), then imported: the record joins the library as it is, as it does for
|
||||
// a preset or keywords
|
||||
let other = temp_dir("recipe-browsed");
|
||||
write_png(&other.join("d.png"), 4);
|
||||
s.execute("library.browse", &json!({"path": other.to_string_lossy()})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [other.join("d.png").to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1, "{r}");
|
||||
assert_eq!(adjusted(&s, "d.png"), (0.0, false), "a browsed photo that joins keeps its own settings");
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
let _ = std::fs::remove_dir_all(&other);
|
||||
}
|
||||
|
||||
/// A saved recipe never takes another preset's id: with presets A and B, A deleted, a recipe saved
|
||||
/// as "B" is its own preset and applying it applies the recipe, not the older B. Saving the same
|
||||
/// recipe under the same name again is that preset, and the presets are in presets.json.
|
||||
#[test]
|
||||
fn saved_recipe_presets_get_distinct_ids_and_survive_reopening() {
|
||||
let lib = temp_dir("recipe-presets-lib");
|
||||
let src = temp_dir("recipe-presets-src");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
let mut s = Session::new().with_fs();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
let photo = import_one(&mut s, &src.join("a.png"), json!([]));
|
||||
s.selection = crate::Selection::single(photo);
|
||||
let create = |s: &mut Session, name: &str| s.execute("preset.create", &json!({"name": name})).unwrap()["id"].as_str().unwrap().to_string();
|
||||
let (a, old_b) = (create(&mut s, "A"), create(&mut s, "B"));
|
||||
s.execute("preset.delete", &json!({"id": a})).unwrap();
|
||||
let recipe = json!([{"id": "light.exposure", "value": 0.7}]);
|
||||
let saved = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap();
|
||||
let new_b = saved["id"].as_str().unwrap().to_string();
|
||||
assert_ne!(new_b, old_b);
|
||||
let mut all: Vec<&str> = s.presets.iter().map(|p| p.id.as_str()).collect();
|
||||
let n = all.len();
|
||||
all.sort();
|
||||
all.dedup();
|
||||
assert_eq!(all.len(), n, "every preset has its own id");
|
||||
s.execute("preset.apply", &json!({"id": new_b})).unwrap();
|
||||
assert_eq!(s.catalog.photo(photo).unwrap().develop.light.exposure, 0.7, "the saved recipe is what gets applied");
|
||||
// the same recipe, name and group: the preset it already is
|
||||
let again = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap();
|
||||
assert_eq!(again["id"], saved["id"]);
|
||||
assert_eq!(s.presets.iter().filter(|p| p.name == "B").count(), 2);
|
||||
drop(s);
|
||||
|
||||
let mut t = Session::new().with_fs();
|
||||
t.open_library(&lib, false).unwrap();
|
||||
let mut bs: Vec<&str> = t.presets.iter().filter(|p| p.name == "B").map(|p| p.id.as_str()).collect();
|
||||
bs.sort();
|
||||
let mut expected = [old_b.as_str(), new_b.as_str()];
|
||||
expected.sort();
|
||||
assert_eq!(bs, expected, "both are still there after reopening");
|
||||
assert!(!t.presets.iter().any(|p| p.name == "A"), "the deleted one stays deleted");
|
||||
drop(t);
|
||||
let _ = std::fs::remove_dir_all(&lib);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// Both commands are in the command list with their parameters documented, which is where the
|
||||
/// control channel, the CLI and MCP's `list_commands` read them.
|
||||
#[test]
|
||||
fn the_recipe_commands_are_listed_with_their_parameters() {
|
||||
let s = Session::new();
|
||||
let commands = s.commands();
|
||||
let import = commands.iter().find(|c| c.id == "library.import").unwrap();
|
||||
assert!(import.params.contains("recipe?: [{id:") && import.params.contains("Import adjustments"), "{}", import.params);
|
||||
assert!(import.params.contains("no white balance, geometry or crop") && import.params.contains("is not changed"), "{}", import.params);
|
||||
let save = commands.iter().find(|c| c.id == "preset.saveRecipe").expect("preset.saveRecipe is a command");
|
||||
assert!(save.enabled && save.params.contains("recipe: [{id:") && save.params.contains("name"), "{}", save.params);
|
||||
}
|
||||
|
||||
/// A saved recipe that resets an HDR control to its default is applied as the recipe would apply it:
|
||||
/// alone, and next to another adjustment, on a photo whose HDR settings are not the default.
|
||||
#[test]
|
||||
fn a_saved_hdr_reset_applies_to_existing_hdr_settings() {
|
||||
let mut s = Session::new();
|
||||
for recipe in [json!([{"id": "hdr.maxEv", "value": 3}]), json!([{"id": "hdr.maxEv", "value": 3}, {"id": "light.exposure", "value": 0.5}])] {
|
||||
let p = s.execute("preset.saveRecipe", &json!({"name": format!("Reset {recipe}"), "recipe": recipe})).unwrap();
|
||||
let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap().settings.clone();
|
||||
let mut base = lightcraft_develop::DevelopSettings::default();
|
||||
base.hdr.enabled = true;
|
||||
base.hdr.max_ev = 1.5;
|
||||
let out = lightcraft_develop::apply_partial(&base, &saved, 1.0);
|
||||
assert_eq!(out.hdr.max_ev, 3.0, "{saved}");
|
||||
assert!(out.hdr.enabled, "the reset leaves the other HDR settings alone: {saved}");
|
||||
let want_exposure = if recipe.as_array().unwrap().len() > 1 { 0.5 } else { base.light.exposure };
|
||||
assert_eq!(out.light.exposure, want_exposure, "{saved}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder's one spelling: `.` is the current folder, `.` and `..` are taken out, never above the
|
||||
/// root (CodeRabbit on #3055 / #3080).
|
||||
#[test]
|
||||
|
||||
@@ -4,4 +4,5 @@
|
||||
mod denoise_cpu;
|
||||
#[cfg(feature = "denoise")]
|
||||
mod denoise_real;
|
||||
mod orf_withdrawal;
|
||||
mod preview_read;
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Compressed ORF withdrawal: public import/recheck and render identities stay consistent.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_catalog::{APP_VERSION, MediaKind, Op, Photo, PhotoId, Source};
|
||||
use lightcraft_engine::{Session, cmd::recheck, media::content_key};
|
||||
use lightcraft_pipeline::SourceInfo;
|
||||
use lightcraft_preview::Hash128;
|
||||
use lightcraft_raster::Rgb32f;
|
||||
use serde_json::json;
|
||||
|
||||
struct OrfLibrary {
|
||||
s: Session,
|
||||
dir: PathBuf,
|
||||
lib: PathBuf,
|
||||
id: PhotoId,
|
||||
}
|
||||
|
||||
impl Drop for OrfLibrary {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixed original and settings isolate decoder status from every other render-key input.
|
||||
fn decoder_session(format: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
let mut p = Photo::new(PhotoId(1), Source::File { path: "same-original.orf".into() }, "same-original.orf", format, 6000, 4000, "2026-01-01");
|
||||
p.kind = MediaKind::Raw;
|
||||
p.content_hash = Some("unchanged-file-bytes".into());
|
||||
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Include the frontend's ordinary, hover and quick-view identities as well as all persistent
|
||||
/// render families. The original-file identity must not change along with any of these.
|
||||
fn decoder_keys(s: &mut Session) -> (Vec<u64>, Vec<Hash128>, String) {
|
||||
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
|
||||
let thumb = s.thumb_job(p.id, 256).unwrap();
|
||||
let render = s.render_job(p.id, 640, 480, false, true).unwrap();
|
||||
let hover = s.preview_job(p.id, 640, 480, true, &p.develop).unwrap();
|
||||
let quick = s.quick_view_job(p.id, 640, true).unwrap();
|
||||
(
|
||||
vec![thumb.key, render.key, hover.key, quick.key],
|
||||
vec![
|
||||
thumb.cache.unwrap().1,
|
||||
s.loupe_job(p.id, 640, 480, true).unwrap().view_cache.unwrap().1,
|
||||
Session::variant_key(&p, &p.develop, 256, 0),
|
||||
render.source_key.unwrap(),
|
||||
],
|
||||
content_key(&p),
|
||||
)
|
||||
}
|
||||
|
||||
/// Old ORF renders cannot stand in after withdrawal; other formats and original-file identities stay stable.
|
||||
#[test]
|
||||
fn withdrawn_orf_decoder_has_distinct_render_keys_without_changing_file_identity() {
|
||||
// Before the withdrawal, format was not part of any of these keys: an otherwise identical
|
||||
// non-ORF photo gives the old keys, preserved for every other camera and ordinary image.
|
||||
let legacy = decoder_keys(&mut decoder_session("DNG"));
|
||||
assert_eq!(legacy, decoder_keys(&mut decoder_session("JPEG")));
|
||||
let orf = decoder_keys(&mut decoder_session("ORF"));
|
||||
for (old, new) in legacy.0.iter().zip(&orf.0) {
|
||||
assert_ne!(old, new, "old ORF frontend render must not be reused");
|
||||
}
|
||||
for (old, new) in legacy.1.iter().zip(&orf.1) {
|
||||
assert_ne!(old, new, "old ORF persistent render or decoded source must not be reused");
|
||||
}
|
||||
assert_eq!(legacy.2, orf.2, "smart previews and denoise products still identify the original file");
|
||||
assert_eq!(orf, decoder_keys(&mut decoder_session("orf")));
|
||||
}
|
||||
|
||||
/// Apply the same-byte capability transition that Reload or the background recheck records.
|
||||
fn mark_orf_preview_only(s: &mut Session) {
|
||||
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
|
||||
s.catalog
|
||||
.apply(Op::SetContent {
|
||||
id: p.id,
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
file_size: p.file_size,
|
||||
content_hash: p.content_hash.clone(),
|
||||
preview_only: Some("Olympus compressed ORF".into()),
|
||||
preview_checked: lightcraft_catalog::APP_VERSION.into(),
|
||||
})
|
||||
.unwrap();
|
||||
s.media.forget(p.id);
|
||||
}
|
||||
|
||||
/// A support-status change invalidates every render family, even when a resize happens at the same time.
|
||||
#[test]
|
||||
fn orf_preview_transition_changes_render_keys_with_identical_bytes_and_settings() {
|
||||
let mut s = decoder_session("ORF");
|
||||
let before = decoder_keys(&mut s);
|
||||
mark_orf_preview_only(&mut s);
|
||||
let after = decoder_keys(&mut s);
|
||||
for (old, new) in before.0.iter().zip(&after.0) {
|
||||
assert_ne!(old, new, "Reload changes frontend render identity");
|
||||
}
|
||||
for (old, new) in before.1.iter().zip(&after.1) {
|
||||
assert_ne!(old, new, "Reload changes persistent render and decoded source identity");
|
||||
}
|
||||
assert_eq!(before.2, after.2, "Reload does not change the original file's identity");
|
||||
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
|
||||
assert_ne!(before.0[1], s.render_job(p.id, 648, 480, false, true).unwrap().key, "a resize must not cancel the status salt");
|
||||
assert_ne!(before.0[2], s.preview_job(p.id, 648, 480, true, &p.develop).unwrap().key, "a hover resize must not cancel the status salt");
|
||||
}
|
||||
|
||||
/// An in-flight sensor decode must not refill a source cache cleared by the preview-only transition.
|
||||
#[test]
|
||||
fn source_from_before_orf_preview_transition_is_not_accepted() {
|
||||
let mut s = decoder_session("ORF");
|
||||
s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
|
||||
let old = s.thumb_job(PhotoId(1), 256).unwrap().run();
|
||||
assert!(old.loaded.is_some());
|
||||
mark_orf_preview_only(&mut s);
|
||||
s.accept(&old);
|
||||
assert_eq!(s.media.source_usage().0, 0, "a sensor decode finishing after Reload cannot repopulate its source cache");
|
||||
}
|
||||
|
||||
/// A legacy ORF record and a controlled probe let the upgrade tests exercise catalog migration
|
||||
/// without downloading camera files. The raw crate separately tests the actual ORF probe.
|
||||
fn legacy_orf(name: &str, preview_only: Option<String>) -> OrfLibrary {
|
||||
let dir = std::env::temp_dir().join(format!("lc-orf-recheck-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let lib = dir.join("lib");
|
||||
let file = dir.join("legacy.orf");
|
||||
let mut s = Session::new();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
let id = s.catalog.alloc_photo_id();
|
||||
let mut p = Photo::new(id, Source::File { path: file.to_string_lossy().into() }, "legacy.orf", "ORF", 96, 64, "2026-01-01");
|
||||
p.kind = MediaKind::Raw;
|
||||
p.file_size = 1024;
|
||||
p.content_hash = Some("same-file".into());
|
||||
let info = lightcraft_engine::media::ProbeInfo {
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
file_size: p.file_size,
|
||||
content_hash: p.content_hash.clone(),
|
||||
format: p.format.clone(),
|
||||
kind: p.kind,
|
||||
preview_only,
|
||||
..Default::default()
|
||||
};
|
||||
s.commit("Legacy ORF", Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
s.selection = lightcraft_engine::Selection::single(id);
|
||||
s.media.file_probe = Some(Arc::new(move |_| Ok(info.clone())));
|
||||
OrfLibrary { s, dir, lib, id }
|
||||
}
|
||||
|
||||
/// Previously supported compressed ORFs and their copies migrate without losing edits, history or persistence.
|
||||
#[test]
|
||||
fn legacy_compressed_orf_and_copies_become_preview_only_without_losing_edits() {
|
||||
let mut x = legacy_orf("compressed", Some("Olympus compressed ORF".into()));
|
||||
x.s.execute("develop.set", &json!({"ids": [x.id.0], "control": "light.exposure", "value": 0.5})).unwrap();
|
||||
let r = x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap();
|
||||
let copy = PhotoId(r["ids"][0].as_u64().unwrap());
|
||||
let before = x.s.catalog.photo(x.id).unwrap().clone();
|
||||
let undo = x.s.undo.len();
|
||||
let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"checked": 1, "updated": [x.id.0, copy.0], "cleared": []}));
|
||||
for id in [x.id, copy] {
|
||||
let p = x.s.catalog.photo(id).unwrap();
|
||||
assert_eq!(p.preview_only.as_deref(), Some("Olympus compressed ORF"));
|
||||
assert_eq!(p.preview_checked, APP_VERSION);
|
||||
assert!(!p.develops_raw());
|
||||
assert_eq!(*p.develop, *before.develop);
|
||||
}
|
||||
assert_eq!(x.s.catalog.photo(x.id).unwrap().history, before.history);
|
||||
assert_eq!(x.s.undo.len(), undo, "bookkeeping is not an undo step");
|
||||
x.s.persist().unwrap();
|
||||
x.s = Session::new();
|
||||
x.s.open_library(&x.lib, false).unwrap();
|
||||
assert!(x.s.catalog.photo(x.id).unwrap().preview_only.is_some());
|
||||
assert!(recheck::stale(&x.s.catalog, false).is_empty());
|
||||
}
|
||||
|
||||
/// Supported uncompressed ORF is checked once and never reported as newly recovered sensor support.
|
||||
#[test]
|
||||
fn legacy_uncompressed_orf_is_stamped_once_without_a_false_recovery_notice() {
|
||||
let mut x = legacy_orf("supported", None);
|
||||
let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"checked": 1, "updated": [x.id.0], "cleared": []}));
|
||||
let p = x.s.catalog.photo(x.id).unwrap();
|
||||
assert!(p.develops_raw());
|
||||
assert_eq!(p.preview_checked, APP_VERSION);
|
||||
assert!(recheck::stale(&x.s.catalog, false).is_empty());
|
||||
assert_eq!(recheck::stale(&x.s.catalog, true).len(), 1);
|
||||
x.s.persist().unwrap();
|
||||
x.s = Session::new();
|
||||
x.s.open_library(&x.lib, false).unwrap();
|
||||
assert!(recheck::stale(&x.s.catalog, false).is_empty());
|
||||
assert!(x.s.catalog.photo(x.id).unwrap().develops_raw());
|
||||
}
|
||||
|
||||
/// An offline original keeps its catalog state and remains eligible for a later recheck.
|
||||
#[test]
|
||||
fn unavailable_legacy_orf_is_unchanged_and_retried() {
|
||||
let mut x = legacy_orf("offline", None);
|
||||
x.s.media.file_probe = Some(std::sync::Arc::new(|_| Err("offline".into())));
|
||||
let before = x.s.catalog.photo(x.id).unwrap().clone();
|
||||
let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"checked": 1, "updated": [], "cleared": []}));
|
||||
assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before);
|
||||
assert_eq!(recheck::stale(&x.s.catalog, false).len(), 1);
|
||||
}
|
||||
+81
-7
@@ -64,6 +64,23 @@ const MODULES: &[Module] = &[
|
||||
"fringe_apply",
|
||||
],
|
||||
},
|
||||
Module {
|
||||
src: include_str!("wgsl/nrcj.wgsl"),
|
||||
bindings: &[("a", false, "f32"), ("b", false, "f32"), ("dst", true, "f32")],
|
||||
entries: &[
|
||||
"nrcj_yuv",
|
||||
"nrcj_uv",
|
||||
"nrcj_samples",
|
||||
"nrcj_speck",
|
||||
"nrcj_pilot",
|
||||
"nrcj_links1",
|
||||
"nrcj_paths",
|
||||
"nrcj_links",
|
||||
"nrcj_dh",
|
||||
"nrcj_dv",
|
||||
"nrcj_recon",
|
||||
],
|
||||
},
|
||||
Module {
|
||||
src: include_str!("wgsl/spot.wgsl"),
|
||||
bindings: &[("img", true, "f32"), ("pts", false, "f32"), ("al", true, "f32"), ("sp", true, "f32"), ("df", true, "f32"), ("wt", true, "f32")],
|
||||
@@ -294,7 +311,8 @@ pub(crate) struct Tracked(wgpu::Buffer);
|
||||
|
||||
impl Tracked {
|
||||
fn new(b: wgpu::Buffer) -> Tracked {
|
||||
ALLOCATED.fetch_add(b.size(), Ordering::Relaxed);
|
||||
let now = ALLOCATED.fetch_add(b.size(), Ordering::Relaxed) + b.size();
|
||||
PEAK.fetch_max(now, Ordering::Relaxed);
|
||||
Tracked(b)
|
||||
}
|
||||
}
|
||||
@@ -317,6 +335,15 @@ thread_local! {
|
||||
|
||||
/// Bytes of device buffers that exist (in use, retired or pooled).
|
||||
static ALLOCATED: AtomicU64 = AtomicU64::new(0);
|
||||
/// Most bytes allocated since [`take_peak`] (profiling).
|
||||
static PEAK: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The most bytes allocated since the last call; starts over from what is allocated now.
|
||||
pub(crate) fn take_peak() -> (u64, u64) {
|
||||
let now = ALLOCATED.load(Ordering::Relaxed);
|
||||
(PEAK.swap(now, Ordering::Relaxed), now)
|
||||
}
|
||||
|
||||
/// Bytes waiting in per-thread retired lists.
|
||||
static RETIRED_BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
/// The render device is lost: wgpu's `poll` panics from then on, so [`Gpu::poll`] stops calling it.
|
||||
@@ -403,6 +430,7 @@ fn constants() -> String {
|
||||
for (i, h) in GRAIN_HASH.iter().enumerate() {
|
||||
s += &format!("const GRAIN_H{i}: u32 = {h}u;\n");
|
||||
}
|
||||
s += &format!("const DEEP_WRITTEN: u32 = {}u;\n", crate::params::DEEP_WRITTEN);
|
||||
for (name, idx) in crate::params::finish_fields() {
|
||||
s += &format!("const F_{name}: u32 = {idx}u;\n");
|
||||
}
|
||||
@@ -556,8 +584,12 @@ impl Gpu {
|
||||
}
|
||||
|
||||
/// Submit command buffers, then make the buffers this thread dropped before reusable.
|
||||
/// Nothing is submitted once this render has failed: the render is discarded and recomputed
|
||||
/// on the CPU, and the failure contract says no further GPU work runs after a fatal failure.
|
||||
pub fn submit(&self, cmds: impl IntoIterator<Item = wgpu::CommandBuffer>) {
|
||||
self.queue.submit(cmds);
|
||||
if !failed() {
|
||||
self.queue.submit(cmds);
|
||||
}
|
||||
let retired = take_retired();
|
||||
self.pool(retired);
|
||||
}
|
||||
@@ -610,6 +642,12 @@ impl Gpu {
|
||||
pub fn upload<T: bytemuck::Pod>(&self, data: &[T]) -> Buf {
|
||||
let bytes: &[u8] = bytemuck::cast_slice(data);
|
||||
let len = bytes.len() / 4;
|
||||
// A failed render runs no further GPU work (`Gpu::submit` skips the submission and the
|
||||
// render is redone on the CPU): staging the bytes would still queue a copy for the next
|
||||
// submission, so the caller gets the placeholder with the requested length instead.
|
||||
if failed() {
|
||||
return Buf { buf: Some(Tracked::new(self.placeholder())), len };
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return self.buffer(1);
|
||||
}
|
||||
@@ -715,7 +753,12 @@ impl Gpu {
|
||||
fail(FailKind::Fatal, format!("unknown kernel {name}"));
|
||||
return;
|
||||
};
|
||||
assert_eq!(bufs.len(), k.nbuf, "{name}: binding count");
|
||||
if bufs.len() != k.nbuf {
|
||||
// a caller/kernel mismatch would bind the wrong buffers: fail this render over to the
|
||||
// CPU instead of crashing
|
||||
fail(FailKind::Fatal, format!("{name}: binding count {} != {}", bufs.len(), k.nbuf));
|
||||
return;
|
||||
}
|
||||
let params = self.init_buffer(bytemuck::cast_slice(if p.is_empty() { &[0u32] } else { p }), wgpu::BufferUsages::STORAGE);
|
||||
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: params.as_entire_binding() }];
|
||||
for (i, b) in bufs.iter().enumerate() {
|
||||
@@ -731,15 +774,27 @@ impl Gpu {
|
||||
|
||||
/// Submit `enc`, then read back the first `len` 32-bit values of `src`.
|
||||
///
|
||||
/// A failed readback (device lost, map error, timeout) fails the render ([`FailKind::Fatal`])
|
||||
/// and returns zeros, which the caller discards; after an earlier failure in the same render
|
||||
/// nothing more is submitted.
|
||||
/// A failed readback (device lost, map error, timeout) or a `len` past the buffer's end fails
|
||||
/// the render ([`FailKind::Fatal`]) and returns zeros, which the caller discards; after an
|
||||
/// earlier failure in the same render nothing more is submitted. `T` is always a 32-bit type
|
||||
/// at the call sites (the copy and the readback tail are defined in 32-bit words).
|
||||
pub fn finish_and_read<T: bytemuck::Pod>(&self, mut enc: wgpu::CommandEncoder, src: &Buf, len: usize) -> Vec<T> {
|
||||
assert!(len <= src.len, "readback of {len} values from a buffer of {}", src.len);
|
||||
let zeros = || vec![<T as bytemuck::Zeroable>::zeroed(); len];
|
||||
if failed() {
|
||||
return zeros();
|
||||
}
|
||||
// a zero-length readback would issue a `copy_buffer_to_buffer` of size 0, which wgpu
|
||||
// rejects as an invalid copy: submit the (possibly staged) work untouched and return
|
||||
// zeros instead
|
||||
if len == 0 {
|
||||
self.submit([enc.finish()]);
|
||||
return zeros();
|
||||
}
|
||||
if len > src.len {
|
||||
// a caller bug would read past the buffer: fail this render over to the CPU
|
||||
fail(FailKind::Fatal, format!("readback of {len} values from a buffer of {}", src.len));
|
||||
return zeros();
|
||||
}
|
||||
let size = (len * 4) as u64;
|
||||
let staging = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("readback"),
|
||||
@@ -1193,6 +1248,25 @@ mod tests {
|
||||
let back: Vec<[u32; 3]> = g.finish_and_read(g.encoder(), &b, data.len());
|
||||
assert!(back.len() == 1 << 20 && back.as_flattened() == data.as_slice());
|
||||
}
|
||||
/// An upload after this render has failed keeps the failure contract (`Gpu::submit` skips the
|
||||
/// submission, so nothing further runs on the GPU): the caller gets the placeholder with the
|
||||
/// requested length instead of a staging buffer holding a copy of the data for a submission
|
||||
/// that will never happen.
|
||||
#[test]
|
||||
fn an_upload_after_a_failure_returns_the_placeholder() {
|
||||
let Some(g) = crate::device() else {
|
||||
lightcraft_testkit::skip!(Gpu, "no GPU device");
|
||||
return;
|
||||
};
|
||||
super::fail(super::FailKind::Fatal, "simulated failure before an upload".into());
|
||||
assert!(super::failed());
|
||||
let b = g.upload(&[7u32; 1024]);
|
||||
assert_eq!(b.buf.as_ref().map(|t| t.0.size()), Some(16), "the placeholder, not a staged 4 KiB buffer");
|
||||
assert_eq!(b.len, 1024, "the requested length is preserved");
|
||||
// leave this thread's failure for nobody: later tests on the thread start unfailed
|
||||
assert_eq!(super::take_failure().map(|f| f.kind), Some(super::FailKind::Fatal));
|
||||
}
|
||||
|
||||
/// Issue #1858: once a Vulkan or DX12 device is lost, wgpu 30 panics in `Device::poll` instead of
|
||||
/// returning an error. A render's readback panicked; while it unwound, a buffer's way back to
|
||||
/// the pool polls again from a destructor, and that second panic aborted the app.
|
||||
|
||||
+13
-5
@@ -45,6 +45,8 @@ pub mod nn;
|
||||
mod params;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod render;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod vram;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use render::{DisplayFrame, GpuStages, Output};
|
||||
@@ -502,12 +504,16 @@ pub fn render(src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &R
|
||||
}
|
||||
|
||||
/// Whether the GPU renders requests of this kind at all (a given render can still fall back to
|
||||
/// the CPU): the kernel writes 8-bit output, so high-bit-depth exports render on the CPU, and so do
|
||||
/// soft proofs against an output-device profile (`device_proof`: its 3D table is CPU-side) and
|
||||
/// Visualize HDR, which needs the float HDR render. [`try_render`] follows it, and the loupe sizes
|
||||
/// its slider-drag drafts by it (issue #330), so the two can't drift apart.
|
||||
/// the CPU): the kernel writes 8-bit output and the float HDR render (`F32Hdr`, in
|
||||
/// [`Rendered::deep`](lightcraft_pipeline::Rendered::deep)); 16-bit and linear float exports render
|
||||
/// on the CPU, and so do soft proofs against an output-device profile (`device_proof`: its 3D table
|
||||
/// is CPU-side) and Visualize HDR, which draws the float render over the 8-bit one. [`try_render`]
|
||||
/// follows it, and the loupe sizes its slider-drag drafts by it (issue #330), so the two can't drift
|
||||
/// apart.
|
||||
pub fn handles(depth: lightcraft_pipeline::OutputDepth, device_proof: bool, overlay: lightcraft_pipeline::Overlay) -> bool {
|
||||
depth == lightcraft_pipeline::OutputDepth::U8 && !device_proof && overlay != lightcraft_pipeline::Overlay::HdrRange
|
||||
matches!(depth, lightcraft_pipeline::OutputDepth::U8 | lightcraft_pipeline::OutputDepth::F32Hdr)
|
||||
&& !device_proof
|
||||
&& overlay != lightcraft_pipeline::Overlay::HdrRange
|
||||
}
|
||||
|
||||
/// [`render`], reporting why this render made no GPU image: [`Fallback::NotTried`] when the GPU
|
||||
@@ -746,7 +752,9 @@ mod tests {
|
||||
fn the_gpu_handles_8_bit_unproofed_renders_without_the_hdr_range() {
|
||||
assert!(super::handles(OutputDepth::U8, false, Overlay::None));
|
||||
assert!(super::handles(OutputDepth::U8, false, Overlay::Spots(50)));
|
||||
assert!(super::handles(OutputDepth::F32Hdr, false, Overlay::None));
|
||||
assert!(!super::handles(OutputDepth::U16, false, Overlay::None));
|
||||
assert!(!super::handles(OutputDepth::F32Linear, false, Overlay::None));
|
||||
assert!(!super::handles(OutputDepth::U8, true, Overlay::None));
|
||||
assert!(!super::handles(OutputDepth::U8, false, Overlay::HdrRange));
|
||||
}
|
||||
|
||||
@@ -5,9 +5,15 @@ use lightcraft_develop::VignetteStyle;
|
||||
use lightcraft_pipeline::colorops::POINT_WORDS;
|
||||
use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut};
|
||||
|
||||
use crate::ctx::{FailKind, fail};
|
||||
|
||||
/// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size).
|
||||
pub const CURVE_N: u32 = 1024;
|
||||
|
||||
/// Set on every word of a float render's output: the values are at least 0, so the sign bit is
|
||||
/// free, and it tells a written 0 from a word the kernel never reached.
|
||||
pub const DEEP_WRITTEN: u32 = 1 << 31;
|
||||
|
||||
/// Field name and number of 32-bit words.
|
||||
const FIELDS: &[(&str, usize)] = &[
|
||||
("W", 1),
|
||||
@@ -101,6 +107,11 @@ const FIELDS: &[(&str, usize)] = &[
|
||||
("LIGHT_MODE", 2),
|
||||
("LIGHT_W", 2),
|
||||
("LIGHT_OFF", 1),
|
||||
// the render's peak over SDR white (`FinishParams::peak`; above 1: an HDR render)
|
||||
("PEAK", 1),
|
||||
// a float render (`finish_deep`): the exact sRGB curve, and three words per pixel in `out`, each
|
||||
// a linear value with `DEEP_WRITTEN` set
|
||||
("DEEP", 1),
|
||||
];
|
||||
|
||||
/// `(name, index)` of every field (for the WGSL constants).
|
||||
@@ -168,7 +179,12 @@ pub struct Present {
|
||||
|
||||
/// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs |
|
||||
/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms).
|
||||
pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec<u32>, Vec<f32>) {
|
||||
///
|
||||
/// `deep`: the kernel writes float samples, as the pipeline's `finish_deep` does.
|
||||
///
|
||||
/// A curve whose length is not [`CURVE_N`] fails the render ([`FailKind::Fatal`]) and returns an
|
||||
/// empty parameter block with a truncated aux table, which the caller discards (CPU fallback).
|
||||
pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present, deep: bool) -> (Vec<u32>, Vec<f32>) {
|
||||
let mut aux: Vec<f32> = fp.tone.lut().to_vec();
|
||||
aux.extend_from_slice(fp.tone.chroma_lut());
|
||||
let srgb_off = aux.len();
|
||||
@@ -176,7 +192,17 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
|
||||
let curve_off = aux.len();
|
||||
if let Some(c) = &fp.curves {
|
||||
for l in c {
|
||||
assert_eq!(l.v.len(), CURVE_N as usize);
|
||||
if l.v.len() != CURVE_N as usize {
|
||||
// a wrong-length curve would shift every later aux offset (CURVE_OFF, MASK_OFF and
|
||||
// the mask terms that follow) and make the kernel read the wrong data. `fail()`
|
||||
// records the failure on this thread so the render falls back to the CPU; the
|
||||
// partial `(p, aux)` returned here is never bound to a pipeline.
|
||||
fail(FailKind::Fatal, format!("curve table has {} entries, expected {}", l.v.len(), CURVE_N));
|
||||
// `p` is only assembled below the curve loop, so an empty block is as good as any:
|
||||
// the caller (render.rs) gates on `failed()` right after this returns and bails to
|
||||
// the CPU fallback before indexing `p` or uploading `aux`.
|
||||
return (Vec::new(), aux);
|
||||
}
|
||||
aux.extend_from_slice(&l.v);
|
||||
}
|
||||
}
|
||||
@@ -206,6 +232,8 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
|
||||
}
|
||||
}
|
||||
p.fs("LIGHT_W", &light.iter().map(|op| op.weight).collect::<Vec<f32>>());
|
||||
p.f("PEAK", fp.peak);
|
||||
p.b("DEEP", deep);
|
||||
p.u("W", fp.w as u32);
|
||||
p.u("H", fp.h as u32);
|
||||
p.u("NMASK", masks.len() as u32);
|
||||
|
||||
+319
-13
@@ -9,12 +9,13 @@ use lightcraft_geom::Orientation;
|
||||
use lightcraft_pipeline::finish::{FinishParams, FinishParamsInput, MASK_TERMS, mask_terms};
|
||||
use lightcraft_pipeline::geometry::SampleMode;
|
||||
use lightcraft_pipeline::local::plane_at;
|
||||
use lightcraft_pipeline::nrc_joint::JointNoise;
|
||||
use lightcraft_pipeline::{Plan, RenderRequest, Rendered, SourceInfo, local};
|
||||
use lightcraft_raster::resample::Filter;
|
||||
use lightcraft_raster::{Histogram, Plane, Rgb32f, Rgba8};
|
||||
|
||||
use crate::ctx::{Buf, FailKind, Gpu, fail, groups1, groups2};
|
||||
use crate::params::{Present, finish_block};
|
||||
use crate::params::{DEEP_WRITTEN, Present, finish_block};
|
||||
|
||||
/// Device-resident stages of one view, kept next to the CPU [`lightcraft_pipeline::StageCache`]
|
||||
/// (as its extension). Holds the last two output sizes, like the CPU cache.
|
||||
@@ -33,6 +34,8 @@ struct Entry {
|
||||
geo: u64,
|
||||
sampled: Arc<Buf>,
|
||||
lin: Option<(u64, Arc<Buf>)>,
|
||||
/// The joint colour NR's noise model of the whole frame, keyed by `Plan::noise_key`.
|
||||
colour_noise: Option<(u64, JointNoise)>,
|
||||
planes: Planes,
|
||||
}
|
||||
|
||||
@@ -645,13 +648,15 @@ pub fn render(
|
||||
fault: Option<crate::Fault>,
|
||||
display: bool,
|
||||
) -> Option<Output> {
|
||||
let _in_flight = InFlight::new();
|
||||
let mut t = profiling().then(std::time::Instant::now);
|
||||
// Each stage is submitted on its own; under `LIGHTCRAFT_PROFILE` also waited for, so the
|
||||
// timings are real.
|
||||
let lap = |what: &str, t: &mut Option<std::time::Instant>, cx: &mut Cx<'_>| match t {
|
||||
Some(t) => {
|
||||
cx.sync();
|
||||
eprintln!(" gpu {what}: {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
|
||||
let (peak, now) = crate::ctx::take_peak();
|
||||
eprintln!(" gpu {what}: {:.1} ms (device buffers: peak {} MB, now {} MB)", t.elapsed().as_secs_f64() * 1e3, peak >> 20, now >> 20);
|
||||
*t = std::time::Instant::now();
|
||||
}
|
||||
None => cx.flush(),
|
||||
@@ -704,9 +709,15 @@ pub fn render(
|
||||
lap("sample", &mut t, &mut cx);
|
||||
|
||||
// 2. white balance, defringe, spots, noise reduction
|
||||
let mut colour_noise = cached.as_ref().and_then(|e| e.colour_noise).filter(|(k, _)| *k == plan.noise_key);
|
||||
let lin = match cached.as_ref().and_then(|e| e.lin.clone()).filter(|(k, _)| *k == plan.lin_key) {
|
||||
Some((_, b)) => b,
|
||||
None => Arc::new(linear(&mut cx, &sampled, info, &plan, &mut host)),
|
||||
None => {
|
||||
if colour_noise.is_none() {
|
||||
colour_noise = lightcraft_pipeline::colour_noise(src, info, &plan).map(|n| (plan.noise_key, n));
|
||||
}
|
||||
Arc::new(linear(&mut cx, &sampled, info, &plan, &mut host, colour_noise.as_ref().map(|c| &c.1)))
|
||||
}
|
||||
};
|
||||
lap("wb/nr", &mut t, &mut cx);
|
||||
|
||||
@@ -722,7 +733,7 @@ pub fn render(
|
||||
}
|
||||
lap("planes", &mut t, &mut cx);
|
||||
if let Some(c) = stages {
|
||||
c.put(Entry { src: src.clone(), geo: plan.geo, sampled, lin: Some((plan.lin_key, lin.clone())), planes });
|
||||
c.put(Entry { src: src.clone(), geo: plan.geo, sampled, lin: Some((plan.lin_key, lin.clone())), colour_noise, planes });
|
||||
}
|
||||
|
||||
// 4. masks
|
||||
@@ -741,7 +752,9 @@ pub fn render(
|
||||
});
|
||||
// soft proofing as the CPU's `finish` sets it up (an output-device table never gets here: see `render`)
|
||||
fp.proof = req.proof.map(|pr| pr.params(req.space));
|
||||
if let Some(d) = &req.display {
|
||||
// a float render is `finish_deep`: its samples are the output space's, whatever the display
|
||||
let deep = req.depth != lightcraft_pipeline::OutputDepth::U8;
|
||||
if let Some(d) = req.display.as_ref().filter(|_| !deep) {
|
||||
fp.for_display(d, req.proof);
|
||||
}
|
||||
let present = Present {
|
||||
@@ -763,10 +776,13 @@ pub fn render(
|
||||
(Some(b), None) | (None, Some(b)) => Some(b.clone()),
|
||||
(None, None) => None,
|
||||
};
|
||||
let (p, aux) = finish_block(&fp, &terms, &present);
|
||||
let (p, aux) = finish_block(&fp, &terms, &present, deep);
|
||||
if crate::ctx::failed() {
|
||||
return None; // a malformed parameter block failed the render: the CPU fallback redoes it
|
||||
}
|
||||
let aux = gpu.upload(&aux);
|
||||
// cleared, so that work which never ran cannot pass for an image (see the check below)
|
||||
let out = cx.zeroed(n);
|
||||
let out = cx.zeroed(if deep { 3 * n } else { n });
|
||||
if fault == Some(crate::Fault::Validation) {
|
||||
// a dispatch the device rejects (too many workgroups)
|
||||
cx.run("box_h", &[0; 5], &[Some(&aux), Some(&out)], [gpu.device.limits().max_compute_workgroups_per_dimension + 1, 1, 1]);
|
||||
@@ -794,6 +810,11 @@ pub fn render(
|
||||
groups2(w, rows.min(h - y0), [16, 16]),
|
||||
);
|
||||
}
|
||||
if deep {
|
||||
let rendered = read_deep(&mut cx, &out, &plan, req);
|
||||
lap("finish + readback (deep)", &mut t, &mut cx);
|
||||
return rendered.map(Output::Image);
|
||||
}
|
||||
if display && can_display(gpu, &plan, req) {
|
||||
return to_texture(&mut cx, &out, w, h).map(|(frame, histogram)| Output::Display { frame, histogram });
|
||||
}
|
||||
@@ -876,6 +897,36 @@ pub fn render(
|
||||
Some(Output::Image(Rendered { image, histogram, deep: None }))
|
||||
}
|
||||
|
||||
/// The finished float output `out` (three words per pixel) read back as the CPU's float render
|
||||
/// returns it, with the same checks as an 8-bit readback: every pixel written, not entirely black.
|
||||
fn read_deep(cx: &mut Cx<'_>, out: &Buf, plan: &Plan<'_>, req: &RenderRequest) -> Option<Rendered> {
|
||||
use lightcraft_pipeline::{DeepImage, DeepSamples};
|
||||
let (w, h) = (plan.w, plan.h);
|
||||
let n = w * h;
|
||||
let words: Vec<u32> = cx.read(out, 3 * n);
|
||||
if crate::ctx::failed() {
|
||||
return None;
|
||||
}
|
||||
let unwritten = words.as_chunks::<3>().0.iter().filter(|p| p.iter().any(|v| v & DEEP_WRITTEN == 0)).count();
|
||||
if unwritten > 0 {
|
||||
fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({unwritten} of {n} pixels unwritten)"));
|
||||
return None;
|
||||
}
|
||||
let samples = words.into_iter().map(|v| f32::from_bits(v & !DEEP_WRITTEN)).collect();
|
||||
let deep = DeepImage { width: w, height: h, space: req.space, samples: DeepSamples::F32(samples) };
|
||||
let deep = match plan.keep {
|
||||
Some(k) => deep.crop(k.x, k.y, k.w, k.h),
|
||||
None => deep,
|
||||
};
|
||||
let image = deep.to_rgba8();
|
||||
let histogram = Histogram::of_srgb8(&image);
|
||||
if n >= 4096 && [&histogram.r, &histogram.g, &histogram.b].iter().all(|c| c.first() == Some(&histogram.total)) {
|
||||
fail(FailKind::Blank, "the GPU result is entirely black; rendering it on the CPU to be sure".into());
|
||||
return None;
|
||||
}
|
||||
Some(Rendered { image, histogram, deep: Some(deep) })
|
||||
}
|
||||
|
||||
/// The finished output `out` (`w × h` packed RGBA8) as a texture on the device, with its
|
||||
/// histogram; the same checks as a readback (every pixel written, not entirely black), done on
|
||||
/// the device: only the histogram and a pixel count come back.
|
||||
@@ -927,8 +978,8 @@ fn unwritten(data: &[[u8; 4]]) -> usize {
|
||||
data.chunks(4096).filter(|c| c.iter().fold(255u8, |a, p| a & p[3]) != 255).map(|c| c.iter().filter(|p| p[3] != 255).count()).sum()
|
||||
}
|
||||
|
||||
/// The white-balanced, retouched, denoised image.
|
||||
fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, host: &mut Host) -> Buf {
|
||||
/// The white-balanced, retouched, denoised image (`colour_noise`: see `denoise`).
|
||||
fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, host: &mut Host, colour_noise: Option<&JointNoise>) -> Buf {
|
||||
let (w, h) = (plan.w, plan.h);
|
||||
let n = w * h;
|
||||
let s = &*plan.settings;
|
||||
@@ -960,7 +1011,7 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho
|
||||
eyed
|
||||
}
|
||||
};
|
||||
denoise(cx, img, plan)
|
||||
denoise(cx, img, plan, colour_noise)
|
||||
}
|
||||
|
||||
/// Defringe (`optics::defringe`) of the white-balanced image.
|
||||
@@ -1053,8 +1104,9 @@ fn histogram(cx: &mut Cx<'_>, out: &Buf, w: usize, region: (usize, usize, usize,
|
||||
Histogram { r: part(0), g: part(1), b: part(2), luma: part(3), total: v.get(4 * Histogram::BINS).copied().unwrap_or(0), hdr: None }
|
||||
}
|
||||
|
||||
/// Noise reduction (`local::denoise`).
|
||||
fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
|
||||
/// Noise reduction (`local::denoise`). `colour_noise`: the whole frame's noise model for the joint colour
|
||||
/// NR (`lightcraft_pipeline::colour_noise`); `None`: measured on `img`.
|
||||
fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>, colour_noise: Option<&JointNoise>) -> Buf {
|
||||
let (w, h) = (plan.w, plan.h);
|
||||
let n = w * h;
|
||||
let (lum, col) = local::nr_params(&plan.settings, plan.detail_scale);
|
||||
@@ -1067,6 +1119,20 @@ fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
|
||||
map(cx, "nr_lum", n, &[nr.k.to_bits()], [Some(&img), Some(&l), Some(&f)], &out);
|
||||
img = out;
|
||||
}
|
||||
if col.is_some() && local::joint_colour_nr(&plan.settings) {
|
||||
let Some(p) = local::nrc_params(&plan.settings, plan.detail_scale) else { return img };
|
||||
let s = &plan.settings.detail;
|
||||
let (detail, amount) = ((s.nr_color_detail / 100.0) as f32, (s.nr_color / 100.0) as f32);
|
||||
if let Some(out) = color_nr_joint(cx, &img, w, h, &p, detail, amount, colour_noise) {
|
||||
return out;
|
||||
}
|
||||
// too small for the noise samples, or not even one band fits the device: this step on the CPU
|
||||
let mut host = cx.read_rgb(&img, w, h);
|
||||
let mut d = (*plan.settings).clone();
|
||||
d.detail.nr_luminance = 0.0;
|
||||
local::denoise(&mut host, &d, plan.detail_scale, colour_noise);
|
||||
return cx.gpu.upload(rgb_words(&host));
|
||||
}
|
||||
if let Some(nr) = col {
|
||||
let chroma = cx.gpu.buffer(n * 3);
|
||||
map(cx, "chroma_k", n, &[], [Some(&img), None, None], &chroma);
|
||||
@@ -1078,6 +1144,226 @@ fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
|
||||
img
|
||||
}
|
||||
|
||||
/// Run a `nrcj.wgsl` kernel on `n` items with inputs `a`, `b` and output `out`.
|
||||
fn nrcj(cx: &mut Cx<'_>, k: &str, n: usize, p: &[u32], a: &Buf, b: Option<&Buf>, out: &Buf) {
|
||||
cx.run(k, p, &[Some(a), b, Some(out)], groups1(n));
|
||||
}
|
||||
|
||||
/// Device memory left aside when the joint NR plans its bands from the free memory (the rest of the
|
||||
/// render, the display, other programs).
|
||||
const VRAM_RESERVE: u64 = 384 << 20;
|
||||
|
||||
/// Renders on the device right now ([`render`]). An export batch renders photos side by side: while one
|
||||
/// plans its noise reduction bands, each of the others may still allocate the buffers of its other stages.
|
||||
static RENDERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
/// Held while a noise reduction plans its bands and runs them: two plans made at once from the same free
|
||||
/// memory would together ask for more than there is.
|
||||
static BANDS: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Counts a render in [`RENDERS`] while it lives.
|
||||
struct InFlight;
|
||||
|
||||
impl InFlight {
|
||||
fn new() -> Self {
|
||||
RENDERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
InFlight
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InFlight {
|
||||
fn drop(&mut self) {
|
||||
RENDERS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// The band budget from the device memory free right now and our own pooled buffers (which we reuse), less
|
||||
/// [`VRAM_RESERVE`] for each render on the device (this one's other stages and every other render's).
|
||||
fn band_budget_from(free: u64, pooled: u64, renders: usize) -> usize {
|
||||
let reserve = VRAM_RESERVE.saturating_mul(renders.max(1) as u64);
|
||||
free.saturating_add(pooled).saturating_sub(reserve) as usize
|
||||
}
|
||||
|
||||
/// The joint colour noise reduction (`lightcraft_pipeline::nrc_joint`) on the GPU, the same steps as the
|
||||
/// CPU: only the noise samples are read back (the noise model is fitted on the CPU, by the same code).
|
||||
/// Large images are filtered in horizontal bands whose halo covers every step's reach, so each kept pixel
|
||||
/// gets the whole-image result; the noise model is the whole image's, or `frame_noise` (the whole frame's,
|
||||
/// for a window). `None` when the image is too small for the noise samples (the caller falls back to the CPU).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn color_nr_joint(
|
||||
cx: &mut Cx<'_>,
|
||||
img: &Buf,
|
||||
w: usize,
|
||||
h: usize,
|
||||
p: &local::NrcParams,
|
||||
detail: f32,
|
||||
amount: f32,
|
||||
frame_noise: Option<&JointNoise>,
|
||||
) -> Option<Buf> {
|
||||
use lightcraft_pipeline::nrc_joint;
|
||||
let strength = nrc_joint::strength(amount);
|
||||
let brake = nrc_joint::speck_brake(amount);
|
||||
if w < 3 || h < 3 {
|
||||
return None;
|
||||
}
|
||||
if strength <= 0.0 {
|
||||
return Some(cx.copy(img));
|
||||
}
|
||||
let n = w * h;
|
||||
let started = profiling().then(std::time::Instant::now);
|
||||
let mut noise = match frame_noise {
|
||||
Some(noise) => *noise,
|
||||
None => {
|
||||
// noise samples of the whole image: same pixels as the CPU, fitted by the same code
|
||||
let stride = nrc_joint::noise_sample_stride(n);
|
||||
let count = n.div_ceil(stride);
|
||||
let smp = cx.gpu.buffer(11 * count);
|
||||
nrcj(cx, "nrcj_samples", count, &[count as u32, w as u32, h as u32, stride as u32], img, None, &smp);
|
||||
let raw: Vec<f32> = cx.read(&smp, 11 * count);
|
||||
drop(smp);
|
||||
if let Some(t) = started {
|
||||
eprintln!(" gpu joint samples + read: {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
let samples: Vec<nrc_joint::NoiseSample> = raw
|
||||
.as_chunks::<11>()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|s| s[0] == 1.0 && s.iter().all(|v| v.is_finite()))
|
||||
.map(|s| (s[1], [[s[2], s[3], s[4]], [s[5], s[6], s[7]], [s[8], s[9], s[10]]]))
|
||||
.collect();
|
||||
nrc_joint::noise_from_samples(samples)
|
||||
}
|
||||
};
|
||||
noise.tolerance = nrc_joint::tolerance(detail);
|
||||
if let Some(t) = started {
|
||||
eprintln!(" gpu joint noise model: {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
let sigma = p.passes.last().map_or(0.0, |q| q.sigma);
|
||||
let plan = nrc_joint::scale_plan(sigma, w, h);
|
||||
// Rows a kept pixel depends on: a wrong value at a band edge (treated as an image border) moves
|
||||
// inwards by delta per vertical sweep, two sweeps per scale; at the farthest row it reaches, a
|
||||
// scale's weight and path still read up to delta rows further (at most the largest delta); the
|
||||
// guide's blur and pilot reach a few rows, the speck brake two more. Hence 2·Σdelta + max delta + 10.
|
||||
let halo = plan.iter().map(|d| 2 * d.0).sum::<usize>() + plan.last().map_or(0, |d| d.0) + 10;
|
||||
// Memory: the whole output (3 values per pixel) is held besides the input; a band then holds about
|
||||
// 12 values per pixel (guide 3, two chroma buffers 2 + 2, paths 2, weights 2; up to 12 while the
|
||||
// speck brake and the guide run). The budget for both together is `band_budget_from` the device memory
|
||||
// free right now (where the driver can be asked, `crate::vram`); else a fixed 2 GB. One band plan at a
|
||||
// time (`BANDS`), held until the bands are done. PROTOTYPE: `NRV2_GPU_BAND_MB` overrides it.
|
||||
// (free memory asked before the lock: the first question for a device waits for the driver)
|
||||
let free = crate::vram::free_bytes(&cx.gpu.info);
|
||||
let _bands = BANDS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let fixed = std::env::var("NRV2_GPU_BAND_MB").ok().and_then(|v| v.parse::<usize>().ok()).map(|mb| mb << 20);
|
||||
let renders = RENDERS.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let measured = free.map(|free| band_budget_from(free, crate::ctx::memory().pooled, renders));
|
||||
let budget = fixed.or(measured).unwrap_or(2048 << 20);
|
||||
if profiling() {
|
||||
eprintln!(
|
||||
" gpu joint budget: {} MB ({}, {renders} render(s) on the device)",
|
||||
budget >> 20,
|
||||
if fixed.is_some() {
|
||||
"NRV2_GPU_BAND_MB"
|
||||
} else if measured.is_some() {
|
||||
"free device memory"
|
||||
} else {
|
||||
"fixed default"
|
||||
}
|
||||
);
|
||||
}
|
||||
let out_bytes = 12 * n;
|
||||
let per_row = 48 * w;
|
||||
// no band may exceed the device's largest buffer either (3 values per pixel are the largest)
|
||||
let limit_rows = (cx.gpu.limit() as usize / (12 * w)).max(1);
|
||||
let rows = (budget.saturating_sub(out_bytes) / per_row).min(limit_rows);
|
||||
let core = if rows >= h {
|
||||
h
|
||||
} else if rows > 2 * halo {
|
||||
rows - 2 * halo
|
||||
} else {
|
||||
// not even one band with its halo fits: this stage runs on the CPU (the rest of the render stays here)
|
||||
return None;
|
||||
};
|
||||
let out = cx.gpu.buffer(3 * n);
|
||||
let mut y0 = 0;
|
||||
while y0 < h {
|
||||
let y1 = (y0 + core).min(h);
|
||||
let (b0, b1) = if core >= h { (0, h) } else { (y0.saturating_sub(halo), (y1 + halo).min(h)) };
|
||||
let filtered = joint_band(cx, img, w, b0, b1 - b0, &noise, brake, &plan);
|
||||
let kept = (y1 - y0) * w;
|
||||
nrcj(cx, "nrcj_recon", kept, &[kept as u32, strength.to_bits(), (y0 * w) as u32, (b0 * w) as u32], img, Some(&filtered), &out);
|
||||
drop(filtered);
|
||||
// wait: the driver frees a dropped buffer only once the GPU is done with it, and a band's
|
||||
// buffers are large (without waiting, freed memory piled up to the whole 4 GB of a Quadro M2200)
|
||||
cx.sync();
|
||||
y0 = y1;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The filtered chroma pairs of rows `b0 .. b0 + bh` of the image, treated as an image of their own.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn joint_band(
|
||||
cx: &mut Cx<'_>,
|
||||
img: &Buf,
|
||||
w: usize,
|
||||
b0: usize,
|
||||
bh: usize,
|
||||
noise: &lightcraft_pipeline::nrc_joint::JointNoise,
|
||||
brake: lightcraft_pipeline::nrc_joint::SpeckBrake,
|
||||
plan: &[(usize, f32)],
|
||||
) -> Buf {
|
||||
let n = w * bh;
|
||||
let mut np = vec![n as u32, w as u32, bh as u32];
|
||||
np.extend(noise.model.alpha.iter().chain(&noise.model.beta).chain(&noise.ymax).map(|v| v.to_bits()));
|
||||
np.push(noise.tolerance.to_bits());
|
||||
let mut yuv = cx.gpu.buffer(3 * n);
|
||||
nrcj(cx, "nrcj_yuv", n, &[n as u32, (b0 * w) as u32], img, None, &yuv);
|
||||
if brake.share > 0.0 {
|
||||
let mut sp = np.clone();
|
||||
sp.extend([brake.threshold.to_bits(), brake.share.to_bits()]);
|
||||
let despecked = cx.gpu.buffer(3 * n);
|
||||
nrcj(cx, "nrcj_speck", n, &sp, &yuv, None, &despecked);
|
||||
yuv = despecked;
|
||||
}
|
||||
let blurred = gaussian(cx, &yuv, w, bh, 3, 0.8);
|
||||
let guide = cx.gpu.buffer(3 * n);
|
||||
nrcj(cx, "nrcj_pilot", n, &np, &yuv, Some(&blurred), &guide);
|
||||
drop(blurred);
|
||||
let mut filtered = cx.gpu.buffer(2 * n);
|
||||
nrcj(cx, "nrcj_uv", n, &[n as u32], &yuv, None, &filtered);
|
||||
drop(yuv);
|
||||
// dropped buffers only become reusable (and their memory free) once the GPU is done with them
|
||||
cx.sync();
|
||||
// paths (exp(−path), as on the CPU) and pair weights; the next scale's paths go to the scratch buffer,
|
||||
// free after the diffusion steps, as on the CPU
|
||||
let mut paths = cx.gpu.buffer(2 * n);
|
||||
nrcj(cx, "nrcj_links1", n, &np, &guide, None, &paths);
|
||||
let links = cx.gpu.buffer(2 * n);
|
||||
let mut lp = np.clone();
|
||||
lp.push(1);
|
||||
nrcj(cx, "nrcj_links", n, &lp, &guide, Some(&paths), &links);
|
||||
let mut scratch = cx.gpu.buffer(2 * n);
|
||||
for (k, &(delta, rate)) in plan.iter().enumerate() {
|
||||
let dp = [n as u32, w as u32, bh as u32, delta as u32, rate.to_bits()];
|
||||
for _ in 0..2 {
|
||||
nrcj(cx, "nrcj_dh", n, &dp, &filtered, Some(&links), &scratch);
|
||||
std::mem::swap(&mut filtered, &mut scratch);
|
||||
nrcj(cx, "nrcj_dv", n, &dp, &filtered, Some(&links), &scratch);
|
||||
std::mem::swap(&mut filtered, &mut scratch);
|
||||
}
|
||||
if let Some(&(next, _)) = plan.get(k + 1) {
|
||||
nrcj(cx, "nrcj_paths", n, &[n as u32, w as u32, bh as u32, delta as u32], &paths, None, &scratch);
|
||||
std::mem::swap(&mut paths, &mut scratch);
|
||||
let mut lp = np.clone();
|
||||
lp.push(next as u32);
|
||||
nrcj(cx, "nrcj_links", n, &lp, &guide, Some(&paths), &links);
|
||||
}
|
||||
}
|
||||
drop((scratch, paths, links, guide));
|
||||
cx.sync();
|
||||
filtered
|
||||
}
|
||||
|
||||
/// The planes the per-pixel stage reads.
|
||||
struct Prep {
|
||||
log_l: Arc<Buf>,
|
||||
@@ -1231,7 +1517,7 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho
|
||||
let mut first = true;
|
||||
for comp in &m.components {
|
||||
let op = match comp.op {
|
||||
_ if first && comp.op != MaskOp::Intersect => 0u32,
|
||||
_ if first => 0u32,
|
||||
MaskOp::Add => 1,
|
||||
MaskOp::Subtract => 2,
|
||||
MaskOp::Intersect => 3,
|
||||
@@ -1371,6 +1657,26 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Two exports side by side: each band plan leaves room for the other render, so the two together
|
||||
/// stay within the free memory they both measured.
|
||||
#[test]
|
||||
fn band_budget_leaves_room_for_every_render_on_the_device() {
|
||||
let (free, pooled) = (3000u64 << 20, 200u64 << 20);
|
||||
let alone = band_budget_from(free, pooled, 1);
|
||||
assert_eq!(alone, (3200usize << 20) - VRAM_RESERVE as usize);
|
||||
assert_eq!(band_budget_from(free, pooled, 0), alone, "the render itself is always counted");
|
||||
let two = band_budget_from(free, pooled, 2);
|
||||
assert_eq!(two, alone - VRAM_RESERVE as usize);
|
||||
assert_eq!(band_budget_from(100 << 20, 0, 3), 0, "nothing left: no band fits, the CPU runs the step");
|
||||
let before = RENDERS.load(std::sync::atomic::Ordering::Relaxed);
|
||||
{
|
||||
let _a = InFlight::new();
|
||||
let _b = InFlight::new();
|
||||
assert!(RENDERS.load(std::sync::atomic::Ordering::Relaxed) >= before + 2);
|
||||
}
|
||||
assert!(RENDERS.load(std::sync::atomic::Ordering::Relaxed) < before + 2, "a finished render no longer counts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_mask_matches_per_pixel_decision() {
|
||||
use lightcraft_develop::{EmbeddedLens, EmbeddedWarp};
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
//! How much device memory is free right now, where that can be asked without `unsafe`: the NVIDIA
|
||||
//! driver's `nvidia-smi` (Linux and Windows) and the amdgpu driver's sysfs counters (Linux). Other
|
||||
//! devices (AMD/Intel on Windows needs DXGI; integrated GPUs share system memory) report `None`, and the
|
||||
//! caller keeps its fixed budget. The answer is cached for a few seconds: renders ask often, and the
|
||||
//! query starts a process on NVIDIA. Only the first question for an adapter waits for the query; later
|
||||
//! ones get the last answer while a background thread asks again, so no render (and no lock it holds)
|
||||
//! waits for `nvidia-smi`. A card is found by its PCI address where the backend reports it, else by its
|
||||
//! device id; when that matches several cards (two of the same model), the answer is `None`.
|
||||
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long an answer is fresh; an older one is still returned while a newer one is asked for.
|
||||
const TTL: Duration = Duration::from_secs(3);
|
||||
/// How long `nvidia-smi` may take before it is given up on.
|
||||
const QUERY_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
const NVIDIA: u32 = 0x10de;
|
||||
const AMD: u32 = 0x1002;
|
||||
|
||||
static CACHE: Cache = Cache::new(TTL);
|
||||
|
||||
/// Free device memory of the adapter `info` describes, in bytes, or `None` when it cannot be asked.
|
||||
pub fn free_bytes(info: &wgpu::AdapterInfo) -> Option<u64> {
|
||||
let adapter = Adapter { vendor: info.vendor, device: info.device, bus: pci_address(&info.device_pci_bus_id) };
|
||||
CACHE.get(&adapter, query)
|
||||
}
|
||||
|
||||
/// Which card: vendor and device id, and the PCI address where the backend reports it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Adapter {
|
||||
vendor: u32,
|
||||
device: u32,
|
||||
bus: Option<Pci>,
|
||||
}
|
||||
|
||||
/// A PCI address: domain, bus, device, function.
|
||||
type Pci = [u32; 4];
|
||||
|
||||
/// `0000:01:00.0` (Vulkan, sysfs) or `00000000:01:00.0` (`nvidia-smi`).
|
||||
fn pci_address(s: &str) -> Option<Pci> {
|
||||
let mut parts = s.trim().split(':');
|
||||
let (domain, bus, rest) = (parts.next()?, parts.next()?, parts.next()?);
|
||||
let (device, function) = rest.split_once('.')?;
|
||||
if parts.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let hex = |x: &str| u32::from_str_radix(x.trim(), 16).ok();
|
||||
Some([hex(domain)?, hex(bus)?, hex(device)?, hex(function)?])
|
||||
}
|
||||
|
||||
/// One card a driver lists, with its free memory in bytes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Card {
|
||||
bus: Option<Pci>,
|
||||
device: u32,
|
||||
free: u64,
|
||||
}
|
||||
|
||||
/// The free memory of `want` among the listed `cards`: the card at its PCI address when both sides
|
||||
/// report one, else the only card with its device id, else the only card listed. `None` when that is
|
||||
/// ambiguous or the address is listed by no card.
|
||||
fn pick(cards: &[Card], want: &Adapter) -> Option<u64> {
|
||||
if let Some(bus) = want.bus
|
||||
&& cards.iter().any(|c| c.bus.is_some())
|
||||
{
|
||||
return cards.iter().find(|c| c.bus == Some(bus)).map(|c| c.free);
|
||||
}
|
||||
let mut same = cards.iter().filter(|c| c.device == want.device);
|
||||
match (same.next(), same.next()) {
|
||||
(Some(c), None) => Some(c.free),
|
||||
(None, _) if cards.len() == 1 => cards.first().map(|c| c.free),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The last answer for one adapter: when it was asked, the answer, and since when a newer one is
|
||||
/// being asked for.
|
||||
struct Answer {
|
||||
adapter: Adapter,
|
||||
at: Instant,
|
||||
free: Option<u64>,
|
||||
asking: Option<Instant>,
|
||||
}
|
||||
|
||||
type Ask = fn(&Adapter) -> Option<u64>;
|
||||
|
||||
/// Adapters remembered (a renderer, a face finder and a model may each use another device).
|
||||
const ADAPTERS: usize = 4;
|
||||
|
||||
/// A background query not done after this is taken as lost, and the next question asks again.
|
||||
const LOST: Duration = Duration::from_secs(10);
|
||||
|
||||
struct Cache {
|
||||
ttl: Duration,
|
||||
answers: Mutex<Vec<Answer>>,
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
const fn new(ttl: Duration) -> Self {
|
||||
Cache { ttl, answers: Mutex::new(Vec::new()) }
|
||||
}
|
||||
|
||||
/// The answer of `ask` for `adapter`: cached, refreshed in the background once it is older than the
|
||||
/// TTL (in the caller where no thread can be started), and asked for directly the first time.
|
||||
fn get(&'static self, adapter: &Adapter, ask: Ask) -> Option<u64> {
|
||||
{
|
||||
let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(a) = answers.iter_mut().find(|a| a.adapter == *adapter) {
|
||||
let busy = a.asking.is_some_and(|t| t.elapsed() < LOST);
|
||||
if a.at.elapsed() >= self.ttl && !busy {
|
||||
let adapter = *adapter;
|
||||
let refresh = std::thread::Builder::new().name("vram-query".into()).spawn(move || self.store(adapter, ask(&adapter)));
|
||||
if refresh.is_err() {
|
||||
drop(answers);
|
||||
return self.ask_now(&adapter, ask);
|
||||
}
|
||||
a.asking = Some(Instant::now());
|
||||
}
|
||||
return a.free;
|
||||
}
|
||||
}
|
||||
self.ask_now(adapter, ask)
|
||||
}
|
||||
|
||||
fn ask_now(&self, adapter: &Adapter, ask: Ask) -> Option<u64> {
|
||||
let free = ask(adapter);
|
||||
self.store(*adapter, free);
|
||||
free
|
||||
}
|
||||
|
||||
/// Keep `adapter`'s answer (each adapter has its own; the oldest one goes when the list is full).
|
||||
fn store(&self, adapter: Adapter, free: Option<u64>) {
|
||||
let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
answers.retain(|a| a.adapter != adapter);
|
||||
if answers.len() >= ADAPTERS {
|
||||
answers.remove(0);
|
||||
}
|
||||
answers.push(Answer { adapter, at: Instant::now(), free, asking: None });
|
||||
}
|
||||
|
||||
/// Make `adapter`'s answer as old as the TTL (tests: no waiting, so no answer goes stale by itself
|
||||
/// on a slow machine). `false` when there is no answer, or the clock does not reach that far back.
|
||||
#[cfg(test)]
|
||||
fn expire(&self, adapter: &Adapter) -> bool {
|
||||
let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let Some(a) = answers.iter_mut().find(|a| a.adapter == *adapter) else { return false };
|
||||
let Some(at) = a.at.checked_sub(self.ttl) else { return false };
|
||||
a.at = at;
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn asking(&self, adapter: &Adapter) -> bool {
|
||||
self.answers.lock().unwrap_or_else(PoisonError::into_inner).iter().any(|a| a.adapter == *adapter && a.asking.is_some())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn query(adapter: &Adapter) -> Option<u64> {
|
||||
match adapter.vendor {
|
||||
NVIDIA => nvidia(adapter),
|
||||
AMD => amdgpu(adapter),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `nvidia-smi --query-gpu=pci.bus_id,pci.device_id,memory.free`: one line per GPU,
|
||||
/// `DDDDDDDD:BB:DD.F, 0xDDDDVVVV, <MiB>`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn nvidia(adapter: &Adapter) -> Option<u64> {
|
||||
let out = run_with_timeout("nvidia-smi", &["--query-gpu=pci.bus_id,pci.device_id,memory.free", "--format=csv,noheader,nounits"])?;
|
||||
pick(&parse_nvidia(&out), adapter)
|
||||
}
|
||||
|
||||
/// The cards `nvidia-smi` lists, free memory in bytes.
|
||||
fn parse_nvidia(out: &str) -> Vec<Card> {
|
||||
out.lines()
|
||||
.filter_map(|l| {
|
||||
let mut f = l.split(',');
|
||||
let (bus, id, free) = (f.next()?, f.next()?, f.next()?);
|
||||
let id = u32::from_str_radix(id.trim().trim_start_matches("0x").trim_start_matches("0X"), 16).ok()?;
|
||||
let free = free.trim().parse::<u64>().ok()?.checked_mul(1 << 20)?;
|
||||
Some(Card { bus: pci_address(bus), device: id >> 16, free })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `mem_info_vram_total - mem_info_vram_used` of the amdgpu card (its sysfs device directory is named
|
||||
/// by its PCI address).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn amdgpu(adapter: &Adapter) -> Option<u64> {
|
||||
let read_hex = |p: &std::path::Path| -> Option<u32> {
|
||||
let s = std::fs::read_to_string(p).ok()?;
|
||||
u32::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok()
|
||||
};
|
||||
let read_u64 = |p: &std::path::Path| -> Option<u64> { std::fs::read_to_string(p).ok()?.trim().parse().ok() };
|
||||
let mut cards: Vec<Card> = Vec::new();
|
||||
let mut seen = Vec::new();
|
||||
for entry in std::fs::read_dir("/sys/class/drm").ok()?.flatten() {
|
||||
// card0 and renderD128 are the same device
|
||||
let Ok(dev) = std::fs::canonicalize(entry.path().join("device")) else { continue };
|
||||
if seen.contains(&dev) || read_hex(&dev.join("vendor")) != Some(adapter.vendor) {
|
||||
continue;
|
||||
}
|
||||
seen.push(dev.clone());
|
||||
let (Some(device), Some(total), Some(used)) =
|
||||
(read_hex(&dev.join("device")), read_u64(&dev.join("mem_info_vram_total")), read_u64(&dev.join("mem_info_vram_used")))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let bus = dev.file_name().and_then(|n| pci_address(&n.to_string_lossy()));
|
||||
cards.push(Card { bus, device, free: total.saturating_sub(used) });
|
||||
}
|
||||
pick(&cards, adapter)
|
||||
}
|
||||
|
||||
/// Run a program and return its standard output, or `None` if it is missing, fails or takes too long.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn run_with_timeout(program: &str, args: &[&str]) -> Option<String> {
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Stdio};
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null());
|
||||
// the release app has no console: without this, Windows opens one for each query
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
let mut child = cmd.spawn().ok()?;
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) if status.success() => break,
|
||||
Ok(Some(_)) | Err(_) => return None,
|
||||
Ok(None) if start.elapsed() > QUERY_TIMEOUT => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(5)),
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
child.stdout.take()?.read_to_string(&mut out).ok()?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const fn adapter(vendor: u32, device: u32) -> Adapter {
|
||||
Adapter { vendor, device, bus: None }
|
||||
}
|
||||
|
||||
/// Wait until `flag` is set (a fake query that answers when the test says so), at most 10 s.
|
||||
fn wait_for(flag: &std::sync::atomic::AtomicBool) {
|
||||
let start = Instant::now();
|
||||
while !flag.load(std::sync::atomic::Ordering::SeqCst) && start.elapsed() < Duration::from_secs(10) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until `cache` has no background query for `a` running, at most 10 s.
|
||||
fn settled(cache: &Cache, a: &Adapter) {
|
||||
let start = Instant::now();
|
||||
while cache.asking(a) && start.elapsed() < Duration::from_secs(10) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
assert!(!cache.asking(a), "the background query finished");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_answer_is_returned_while_a_new_one_is_asked_for() {
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
static CACHE: Cache = Cache::new(Duration::from_secs(30));
|
||||
static ASKED: AtomicU64 = AtomicU64::new(0);
|
||||
static ANSWER: AtomicBool = AtomicBool::new(true);
|
||||
fn blocked(_: &Adapter) -> Option<u64> {
|
||||
wait_for(&ANSWER);
|
||||
Some(ASKED.fetch_add(1, Ordering::SeqCst) + 1)
|
||||
}
|
||||
let a = adapter(NVIDIA, 1);
|
||||
// the first question waits for the answer
|
||||
assert_eq!(CACHE.get(&a, blocked), Some(1));
|
||||
assert!(CACHE.expire(&a));
|
||||
// stale, and the driver does not answer: the old answer at once, a new one in the background
|
||||
ANSWER.store(false, Ordering::SeqCst);
|
||||
let t = Instant::now();
|
||||
assert_eq!(CACHE.get(&a, blocked), Some(1));
|
||||
assert_eq!(CACHE.get(&a, blocked), Some(1));
|
||||
assert!(t.elapsed() < Duration::from_secs(5), "waited {:?} for the query", t.elapsed());
|
||||
assert!(CACHE.asking(&a));
|
||||
ANSWER.store(true, Ordering::SeqCst);
|
||||
settled(&CACHE, &a);
|
||||
assert_eq!(CACHE.get(&a, blocked), Some(2), "the background answer is kept");
|
||||
assert_eq!(ASKED.load(Ordering::SeqCst), 2, "one query in the background, not one per question");
|
||||
// another adapter is asked for directly
|
||||
assert_eq!(CACHE.get(&adapter(AMD, 2), blocked), Some(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_adapter_keeps_its_own_answer() {
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
static CACHE: Cache = Cache::new(Duration::from_secs(30));
|
||||
static ASKED: AtomicU64 = AtomicU64::new(0);
|
||||
static ANSWER: AtomicBool = AtomicBool::new(true);
|
||||
// card 1 answers when the test says so, card 2 at once; 1000s and 2000s
|
||||
fn ask(a: &Adapter) -> Option<u64> {
|
||||
if a.device == 1 {
|
||||
wait_for(&ANSWER);
|
||||
}
|
||||
Some(a.device as u64 * 1000 + ASKED.fetch_add(1, Ordering::SeqCst))
|
||||
}
|
||||
let (one, two) = (adapter(NVIDIA, 1), adapter(NVIDIA, 2));
|
||||
assert_eq!(CACHE.get(&one, ask), Some(1000));
|
||||
assert_eq!(CACHE.get(&two, ask), Some(2001));
|
||||
assert!(CACHE.expire(&one) && CACHE.expire(&two));
|
||||
// card 1 refreshes in the background while card 2 is asked for: neither waits, nor replaces the other
|
||||
ANSWER.store(false, Ordering::SeqCst);
|
||||
assert_eq!(CACHE.get(&one, ask), Some(1000));
|
||||
assert_eq!(CACHE.get(&two, ask), Some(2001));
|
||||
settled(&CACHE, &two);
|
||||
ANSWER.store(true, Ordering::SeqCst);
|
||||
settled(&CACHE, &one);
|
||||
let asked = ASKED.load(Ordering::SeqCst);
|
||||
assert_eq!(asked, 4, "one background query per card");
|
||||
let (a1, a2) = (CACHE.get(&one, ask), CACHE.get(&two, ask));
|
||||
assert!(a1.is_some_and(|v| v / 1000 == 1) && a2.is_some_and(|v| v / 1000 == 2), "{a1:?} {a2:?}");
|
||||
assert_eq!(ASKED.load(Ordering::SeqCst), asked, "fresh answers are not asked for again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pci_addresses_parse_in_both_forms() {
|
||||
assert_eq!(pci_address("0000:01:00.0"), Some([0, 1, 0, 0]));
|
||||
assert_eq!(pci_address("00000000:0A:00.1"), Some([0, 10, 0, 1]));
|
||||
assert_eq!(pci_address(""), None);
|
||||
assert_eq!(pci_address("01:00.0"), None);
|
||||
assert_eq!(pci_address("0000:01:00.0:9"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nvidia_output_is_matched_by_address_then_device_id() {
|
||||
let two = "00000000:01:00.0, 0x179B10DE, 3990\n00000000:02:00.0, 0x1F0810DE, 5120\n";
|
||||
let cards = parse_nvidia(two);
|
||||
assert_eq!(pick(&cards, &adapter(NVIDIA, 0x1f08)), Some(5120 << 20));
|
||||
assert_eq!(pick(&cards, &adapter(NVIDIA, 0x179b)), Some(3990 << 20));
|
||||
// several GPUs and none matches: unknown
|
||||
assert_eq!(pick(&cards, &adapter(NVIDIA, 0x2204)), None);
|
||||
// a single GPU is taken even if its id is reported differently
|
||||
assert_eq!(pick(&parse_nvidia("00000000:01:00.0, 0x179B10DE, 3990\n"), &adapter(NVIDIA, 0x1234)), Some(3990 << 20));
|
||||
// garbage is not a number
|
||||
assert!(parse_nvidia("No devices were found\n").is_empty());
|
||||
assert_eq!(pick(&parse_nvidia(""), &adapter(NVIDIA, 0x179b)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_cards_of_one_model_are_told_apart_by_address_or_not_at_all() {
|
||||
let twins = parse_nvidia("00000000:01:00.0, 0x1F0810DE, 1000\n00000000:02:00.0, 0x1F0810DE, 6000\n");
|
||||
let at = |bus| Adapter { bus: pci_address(bus), ..adapter(NVIDIA, 0x1f08) };
|
||||
assert_eq!(pick(&twins, &at("0000:02:00.0")), Some(6000 << 20));
|
||||
assert_eq!(pick(&twins, &at("0000:01:00.0")), Some(1000 << 20));
|
||||
// without an address the model alone is ambiguous: no answer, the caller keeps its fixed budget
|
||||
assert_eq!(pick(&twins, &adapter(NVIDIA, 0x1f08)), None);
|
||||
assert_eq!(pick(&twins, &at("")), None);
|
||||
// an address no card has is no card: the model is not looked up instead
|
||||
let mixed = parse_nvidia("00000000:01:00.0, 0x1F0810DE, 1000\n00000000:02:00.0, 0x220410DE, 6000\n");
|
||||
assert_eq!(pick(&mixed, &at("0000:03:00.0")), None);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
// The per-pixel stage: a straight port of `lightcraft_pipeline::finish` (keep in step with it).
|
||||
// Bindings: img (rgb, pre-exposure), log_l, base, clar, tex, dark, masks (NMASK planes, then the
|
||||
// blurred chromaticity when HAS_CHROMA), aux
|
||||
// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms | light operator tables), out (packed RGBA8).
|
||||
// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms | light operator tables), out (packed RGBA8; a float render:
|
||||
// three words per pixel, see `F_DEEP`).
|
||||
|
||||
fn tone_apply(y: f32) -> f32 {
|
||||
if (y <= 0.0) {
|
||||
@@ -39,12 +40,33 @@ fn encode_srgb(v: f32) -> f32 {
|
||||
return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t;
|
||||
}
|
||||
|
||||
// `linear_to_srgb`: the exact sRGB curve, unbounded above 1 (a float render encodes with it).
|
||||
fn srgb_exact(v: f32) -> f32 {
|
||||
if (v <= 0.0031308) {
|
||||
return v * 12.92;
|
||||
}
|
||||
return 1.055 * pow(v, 1.0 / 2.4) - 0.055;
|
||||
}
|
||||
|
||||
// `srgb_to_linear`.
|
||||
fn srgb_linear(v: f32) -> f32 {
|
||||
if (v <= 0.04045) {
|
||||
return v / 12.92;
|
||||
}
|
||||
return pow((v + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
// Above SDR white (an HDR render) the curves continue with slope 1 from their end point.
|
||||
fn curve(ch: u32, x: f32) -> f32 {
|
||||
let o = pu(F_CURVE_OFF) + ch * CURVE_N;
|
||||
let f = clamp(x, 0.0, 1.0) * f32(CURVE_N - 1u);
|
||||
let i = min(u32(f), CURVE_N - 2u);
|
||||
let t = f - f32(i);
|
||||
return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t;
|
||||
let v = aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t;
|
||||
if (x > 1.0 && pf(F_PEAK) > 1.0) {
|
||||
return v + (x - 1.0);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// Process V4's calibrated Contrast, Blacks (`lightcraft_pipeline::light_v3`): operator `k`'s
|
||||
@@ -65,6 +87,9 @@ fn light_channel(k: u32, x: f32) -> f32 {
|
||||
if (x < 0.0) {
|
||||
return aux[pu(F_LIGHT_OFF) + k * LIGHT_N] + x;
|
||||
}
|
||||
if (pu(F_DEEP) != 0u) {
|
||||
return light_eval(k, srgb_exact(x));
|
||||
}
|
||||
return light_eval(k, encode_srgb(x));
|
||||
}
|
||||
|
||||
@@ -365,25 +390,25 @@ fn out_encode(v: f32) -> f32 {
|
||||
return 1.099 * pow(l, 0.45) - 0.099;
|
||||
}
|
||||
|
||||
// `finish::gamut_map` (SDR): the chroma scale that brings `r` into 0..1 towards its luminance (1: in gamut) ...
|
||||
fn gamut_scale(r: vec3<f32>, luma: vec3<f32>) -> f32 {
|
||||
let yy = clamp(dot(luma, r), 0.0, 1.0);
|
||||
// `finish::gamut_map_to`: the chroma scale that brings `r` into 0..top towards its luminance (1: in gamut) ...
|
||||
fn gamut_scale(r: vec3<f32>, luma: vec3<f32>, top: f32) -> f32 {
|
||||
let yy = clamp(dot(luma, r), 0.0, top);
|
||||
var tg = 1.0;
|
||||
for (var k = 0u; k < 3u; k++) {
|
||||
let cc = r[k];
|
||||
if (cc < 0.0) {
|
||||
tg = min(tg, yy / max(yy - cc, 1e-9));
|
||||
} else if (cc > 1.0) {
|
||||
tg = min(tg, (1.0 - yy) / max(cc - yy, 1e-9));
|
||||
} else if (cc > top) {
|
||||
tg = min(tg, (top - yy) / max(cc - yy, 1e-9));
|
||||
}
|
||||
}
|
||||
return tg;
|
||||
}
|
||||
|
||||
// ... and `r` scaled by it.
|
||||
fn gamut_apply(r: vec3<f32>, luma: vec3<f32>, tg: f32) -> vec3<f32> {
|
||||
fn gamut_apply(r: vec3<f32>, luma: vec3<f32>, tg: f32, top: f32) -> vec3<f32> {
|
||||
if (tg < 1.0) {
|
||||
let yy = clamp(dot(luma, r), 0.0, 1.0);
|
||||
let yy = clamp(dot(luma, r), 0.0, top);
|
||||
return yy + (r - yy) * tg;
|
||||
}
|
||||
return r;
|
||||
@@ -402,6 +427,9 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let n = w * h;
|
||||
let gain = pf(F_GAIN);
|
||||
let ev = pf(F_EV);
|
||||
let peak = pf(F_PEAK);
|
||||
let hdr = peak > 1.0;
|
||||
let deep = pu(F_DEEP) != 0u;
|
||||
var c = vec3<f32>(img[3u * i], img[3u * i + 1u], img[3u * i + 2u]);
|
||||
if (gain != 1.0) {
|
||||
c = c * gain;
|
||||
@@ -567,8 +595,8 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
d = vec3<f32>(o) + (d - vec3<f32>(o)) * k;
|
||||
}
|
||||
let mx = max(d.x, max(d.y, d.z));
|
||||
if (mx > 1.0) {
|
||||
let t = clamp((mx - 1.0) / max(mx - o, 1e-6), 0.0, 1.0);
|
||||
if (mx > peak) {
|
||||
let t = clamp((mx - peak) / max(mx - o, 1e-6), 0.0, 1.0);
|
||||
d = d + (o - d) * t;
|
||||
}
|
||||
|
||||
@@ -615,6 +643,9 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
} else {
|
||||
d = d * f;
|
||||
}
|
||||
} else if (hdr) {
|
||||
// lighten towards SDR white; never pull HDR highlights down to it
|
||||
d = d + max(1.0 - d, vec3<f32>(0.0)) * amount * t * 0.85;
|
||||
} else {
|
||||
d = d + (1.0 - d) * amount * t * 0.85;
|
||||
}
|
||||
@@ -628,23 +659,28 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
var r: vec3<f32>;
|
||||
if (pu(F_PROOF) != 0u) {
|
||||
let q0 = mul3(mat_at(F_PROOF_M), d);
|
||||
let tq = gamut_scale(q0, vec3<f32>(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u)));
|
||||
let tq = gamut_scale(q0, vec3<f32>(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u)), peak);
|
||||
if (pu(F_PROOF_DEST_WARN) != 0u && out_of_gamut(q0, tq)) {
|
||||
warn = 1u;
|
||||
}
|
||||
r = mul3(mat_at(F_PROOF_OUT), gamut_apply(q0, vec3<f32>(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u)), tq));
|
||||
r = mul3(mat_at(F_PROOF_OUT), gamut_apply(q0, vec3<f32>(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u)), tq, peak));
|
||||
} else {
|
||||
r = mul3(mat_at(F_OUT_M), d);
|
||||
}
|
||||
let oy = vec3<f32>(pf(F_OUT_Y), pf(F_OUT_Y + 1u), pf(F_OUT_Y + 2u));
|
||||
let tg = gamut_scale(r, oy);
|
||||
let tg = gamut_scale(r, oy, peak);
|
||||
if (pu(F_PROOF) != 0u && pu(F_PROOF_DISP_WARN) != 0u && warn == 0u && out_of_gamut(r, tg)) {
|
||||
warn = 2u;
|
||||
}
|
||||
r = gamut_apply(r, oy, tg);
|
||||
r = gamut_apply(r, oy, tg, peak);
|
||||
|
||||
// --- encode, curves, grain
|
||||
var e = vec3<f32>(encode_srgb(r.x), encode_srgb(r.y), encode_srgb(r.z));
|
||||
if (deep) {
|
||||
// the exact curve; an HDR render's values above SDR white encode above 1
|
||||
let q = select(clamp(r, vec3<f32>(0.0), vec3<f32>(1.0)), max(r, vec3<f32>(0.0)), hdr);
|
||||
e = vec3<f32>(srgb_exact(q.x), srgb_exact(q.y), srgb_exact(q.z));
|
||||
}
|
||||
if (pu(F_CURVES) != 0u) {
|
||||
let e0 = e;
|
||||
e = vec3<f32>(curve(0u, e.x), curve(1u, e.y), curve(2u, e.z));
|
||||
@@ -663,19 +699,38 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let seed = pu(F_GRAIN_SEED);
|
||||
var g = grain_noise(gx * sc, gy * sc, seed);
|
||||
g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7;
|
||||
let lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z;
|
||||
var lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z;
|
||||
if (hdr) {
|
||||
lum = clamp(lum, 0.0, 1.0);
|
||||
}
|
||||
let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum));
|
||||
e = e + k;
|
||||
}
|
||||
if (pu(F_LUT) != 0u) {
|
||||
let m = lut_apply(clamp(e, vec3<f32>(0.0), vec3<f32>(1.0)));
|
||||
e = e + (m - e) * pf(F_LUT_AMT);
|
||||
let lc = clamp(e, vec3<f32>(0.0), vec3<f32>(1.0));
|
||||
let m = lut_apply(lc);
|
||||
if (hdr) {
|
||||
// the LUT sees SDR values; the part above SDR white is carried over
|
||||
e = e + (m - lc) * pf(F_LUT_AMT);
|
||||
} else {
|
||||
e = e + (m - e) * pf(F_LUT_AMT);
|
||||
}
|
||||
}
|
||||
if (warn == 1u) {
|
||||
e = vec3<f32>(PROOF_DEST_R, PROOF_DEST_G, PROOF_DEST_B);
|
||||
} else if (warn == 2u) {
|
||||
e = vec3<f32>(PROOF_DISP_R, PROOF_DISP_G, PROOF_DISP_B);
|
||||
}
|
||||
if (deep) {
|
||||
// `finish_deep`: linear, 0..peak. The sign bit a value in that range leaves free says the
|
||||
// word was written (`DEEP_WRITTEN`: `out` starts cleared, and 0 is a valid value).
|
||||
let o3 = 3u * i;
|
||||
for (var k = 0u; k < 3u; k++) {
|
||||
let v = select(0.0, min(srgb_linear(e[k]), peak), e[k] > 0.0);
|
||||
out[o3 + k] = bitcast<u32>(v) | DEEP_WRITTEN;
|
||||
}
|
||||
return;
|
||||
}
|
||||
e = vec3<f32>(out_encode(e.x), out_encode(e.y), out_encode(e.z));
|
||||
let abs_x = u32(pf(F_VIG_VIEW)) + x;
|
||||
let abs_y = u32(pf(F_VIG_VIEW + 1u)) + y;
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
// Joint colour noise reduction (`lightcraft_pipeline::nrc_joint`). Each kernel mirrors its CPU
|
||||
// twin there, in the same order of operations; keep them in step.
|
||||
//
|
||||
// Buffers: `a`, `b` inputs, `dst` output. Images are interleaved: RGB / Y,R−Y,B−Y (3 per pixel),
|
||||
// chroma pairs R−Y,B−Y (2 per pixel), path pairs (h, v; exp(−path), see `nrc_joint`) or weight pairs (h, v).
|
||||
// Kernels with the noise model: P[0] = n, P[1] = w, P[2] = h, P[3..6] = alpha, P[6..9] = beta,
|
||||
// P[9..12] = ymax, P[12] = tolerance.
|
||||
|
||||
fn ja(i: u32) -> vec3<f32> {
|
||||
return vec3<f32>(a[3u * i], a[3u * i + 1u], a[3u * i + 2u]);
|
||||
}
|
||||
|
||||
fn jb3(i: u32) -> vec3<f32> {
|
||||
return vec3<f32>(b[3u * i], b[3u * i + 1u], b[3u * i + 2u]);
|
||||
}
|
||||
|
||||
fn ja2(i: u32) -> vec2<f32> {
|
||||
return vec2<f32>(a[2u * i], a[2u * i + 1u]);
|
||||
}
|
||||
|
||||
fn jvc(v: vec3<f32>, i: u32) -> f32 {
|
||||
return select(select(v.x, v.y, i == 1u), v.z, i == 2u);
|
||||
}
|
||||
|
||||
// `JointNoise::var`.
|
||||
fn nvar(i: u32, y: f32) -> f32 {
|
||||
let yy = min(y, pf(9u + i));
|
||||
return max(pf(3u + i) * max(yy, 0.0) + pf(6u + i), 1e-14);
|
||||
}
|
||||
|
||||
// `nrc_joint::distance`.
|
||||
fn jdist(p: vec3<f32>, q: vec3<f32>) -> f32 {
|
||||
let y = 0.5 * (p.x + q.x);
|
||||
let t = 0.025 * max(y, 0.0);
|
||||
let allowance = t * t;
|
||||
var sum = 0.0;
|
||||
for (var i = 0u; i < 3u; i++) {
|
||||
let v = nvar(i, y);
|
||||
let d = jvc(p, i) - jvc(q, i);
|
||||
let excess = max(d * d - v, 0.0);
|
||||
if (excess != 0.0) {
|
||||
sum += excess / (3.0 * pf(12u) * v + allowance);
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
// `nrc_joint::weight`.
|
||||
fn jweight(d: f32, p: f32) -> f32 {
|
||||
let m = max(d, p);
|
||||
return select(exp(-m), 1.0, m == 0.0);
|
||||
}
|
||||
|
||||
// `nrc_joint::yuv` of pixel `i` of image `a`.
|
||||
fn jyuv(i: u32) -> vec3<f32> {
|
||||
let c = ja(i);
|
||||
let y = lum2020(c);
|
||||
return vec3<f32>(y, c.x - y, c.z - y);
|
||||
}
|
||||
|
||||
// `nrc_joint::yuv` of `n` pixels of image `a` from pixel P[1] on (a band's rows): P[0] = n.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_yuv(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let c = jyuv(pu(1u) + i);
|
||||
dst[3u * i] = c.x;
|
||||
dst[3u * i + 1u] = c.y;
|
||||
dst[3u * i + 2u] = c.z;
|
||||
}
|
||||
|
||||
// The chroma pair (R−Y, B−Y) of the transformed image `a` (P[0] = n).
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_uv(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
dst[2u * i] = a[3u * i + 1u];
|
||||
dst[2u * i + 1u] = a[3u * i + 2u];
|
||||
}
|
||||
|
||||
// Noise samples of image `a`, transformed on the fly (`nrc_joint::noise_model`): P[0] = sample count,
|
||||
// P[1] = w, P[2] = h, P[3] = stride. Per sample 11 values: valid, brightness, 3 × 3 residuals.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_samples(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let k = lin_index(g, nw);
|
||||
if (k >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let w = pu(1u);
|
||||
let h = pu(2u);
|
||||
let index = k * pu(3u);
|
||||
let x = index % w;
|
||||
let y = index / w;
|
||||
let o = 11u * k;
|
||||
if (x == 0u || y == 0u || x + 1u == w || y + 1u == h) {
|
||||
dst[o] = 0.0;
|
||||
return;
|
||||
}
|
||||
let c = jyuv(index);
|
||||
var brightness = 0.0;
|
||||
for (var s = 0u; s < 3u; s++) {
|
||||
let d = min(min(min(min(1u << s, x), y), w - x - 1u), h - y - 1u);
|
||||
var m = vec3<f32>(0.0);
|
||||
m = m + 0.25 * jyuv(index - d);
|
||||
m = m + 0.25 * jyuv(index + d);
|
||||
m = m + 0.25 * jyuv(index - d * w);
|
||||
m = m + 0.25 * jyuv(index + d * w);
|
||||
let r = c - m;
|
||||
dst[o + 2u + 3u * s] = r.x * r.x;
|
||||
dst[o + 3u + 3u * s] = r.y * r.y;
|
||||
dst[o + 4u + 3u * s] = r.z * r.z;
|
||||
brightness += m.x / 3.0;
|
||||
}
|
||||
dst[o] = 1.0;
|
||||
dst[o + 1u] = max(brightness, 0.0);
|
||||
}
|
||||
|
||||
// `nrc_joint::median8`: the same 19-comparator network, on plain variables (a private array indexed in a
|
||||
// loop ends up in slow local memory on some GPUs).
|
||||
fn med8(v0: f32, v1: f32, v2: f32, v3: f32, v4: f32, v5: f32, v6: f32, v7: f32) -> f32 {
|
||||
var a = v0;
|
||||
var b = v1;
|
||||
var c = v2;
|
||||
var d = v3;
|
||||
var e = v4;
|
||||
var f = v5;
|
||||
var g = v6;
|
||||
var h = v7;
|
||||
let t0 = min(a, c);
|
||||
c = max(a, c);
|
||||
a = t0;
|
||||
let t1 = min(b, d);
|
||||
d = max(b, d);
|
||||
b = t1;
|
||||
let t2 = min(e, g);
|
||||
g = max(e, g);
|
||||
e = t2;
|
||||
let t3 = min(f, h);
|
||||
h = max(f, h);
|
||||
f = t3;
|
||||
let t4 = min(a, e);
|
||||
e = max(a, e);
|
||||
a = t4;
|
||||
let t5 = min(b, f);
|
||||
f = max(b, f);
|
||||
b = t5;
|
||||
let t6 = min(c, g);
|
||||
g = max(c, g);
|
||||
c = t6;
|
||||
let t7 = min(d, h);
|
||||
h = max(d, h);
|
||||
d = t7;
|
||||
let t8 = min(a, b);
|
||||
b = max(a, b);
|
||||
a = t8;
|
||||
let t9 = min(c, d);
|
||||
d = max(c, d);
|
||||
c = t9;
|
||||
let t10 = min(e, f);
|
||||
f = max(e, f);
|
||||
e = t10;
|
||||
let t11 = min(g, h);
|
||||
h = max(g, h);
|
||||
g = t11;
|
||||
let t12 = min(c, e);
|
||||
e = max(c, e);
|
||||
c = t12;
|
||||
let t13 = min(d, f);
|
||||
f = max(d, f);
|
||||
d = t13;
|
||||
let t14 = min(b, e);
|
||||
e = max(b, e);
|
||||
b = t14;
|
||||
let t15 = min(d, g);
|
||||
g = max(d, g);
|
||||
d = t15;
|
||||
let t16 = min(b, c);
|
||||
c = max(b, c);
|
||||
b = t16;
|
||||
let t17 = min(d, e);
|
||||
e = max(d, e);
|
||||
d = t17;
|
||||
let t18 = min(f, g);
|
||||
g = max(f, g);
|
||||
f = t18;
|
||||
return 0.5 * (d + e);
|
||||
}
|
||||
|
||||
// The farther of a value's distances to the least and largest of 8 (`speck_share`'s pre-test).
|
||||
fn reach8(p: f32, v0: f32, v1: f32, v2: f32, v3: f32, v4: f32, v5: f32, v6: f32, v7: f32) -> f32 {
|
||||
let lo = min(min(min(v0, v1), min(v2, v3)), min(min(v4, v5), min(v6, v7)));
|
||||
let hi = max(max(max(v0, v1), max(v2, v3)), max(max(v4, v5), max(v6, v7)));
|
||||
return max(abs(p - lo), abs(p - hi));
|
||||
}
|
||||
|
||||
// The two largest values so far (`t.x` ≥ `t.y`) with `s` added, as the CPU's fold.
|
||||
fn top2(t: vec2<f32>, s: f32) -> vec2<f32> {
|
||||
return select(vec2<f32>(t.x, max(t.y, s)), vec2<f32>(s, t.x), s > t.x);
|
||||
}
|
||||
|
||||
// One border pixel's share of the colour shift (`speck_share`).
|
||||
fn sshare(q: vec3<f32>, m: vec3<f32>, du: f32, dv: f32, vu: f32, vv: f32, excess: f32) -> f32 {
|
||||
return ((q.y - m.y) * du / vu + (q.z - m.z) * dv / vv) / excess;
|
||||
}
|
||||
|
||||
// `nrc_joint::despeck` + `speck_share`: `a` = transformed image, writes it with the chroma of compact
|
||||
// colour specks replaced. Noise parameters as `nrcj_pilot`; P[13] = threshold, P[14] = share.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_speck(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let w = pu(1u);
|
||||
let h = pu(2u);
|
||||
let x = i % w;
|
||||
let y = i / w;
|
||||
let p = ja(i);
|
||||
var o = p;
|
||||
if (x >= 2u && y >= 2u && x + 2u < w && y + 2u < h) {
|
||||
let threshold = pf(13u);
|
||||
let share = pf(14u);
|
||||
let up = i - 2u * w;
|
||||
let dn = i + 2u * w;
|
||||
// ring: corners and edge centres of the 5 × 5 square (in the CPU's order)
|
||||
let r0 = ja(up - 2u);
|
||||
let r1 = ja(up);
|
||||
let r2 = ja(up + 2u);
|
||||
let r3 = ja(i - 2u);
|
||||
let r4 = ja(i + 2u);
|
||||
let r5 = ja(dn - 2u);
|
||||
let r6 = ja(dn);
|
||||
let r7 = ja(dn + 2u);
|
||||
let ym = (((((((r0.x + r1.x) + r2.x) + r3.x) + r4.x) + r5.x) + r6.x) + r7.x) / 8.0;
|
||||
let vu = nvar(1u, ym);
|
||||
let vv = nvar(2u, ym);
|
||||
let bu = reach8(p.y, r0.y, r1.y, r2.y, r3.y, r4.y, r5.y, r6.y, r7.y);
|
||||
let bv = reach8(p.z, r0.z, r1.z, r2.z, r3.z, r4.z, r5.z, r6.z, r7.z);
|
||||
if (bu * bu / vu + bv * bv / vv > threshold) {
|
||||
var m = vec3<f32>(0.0, med8(r0.y, r1.y, r2.y, r3.y, r4.y, r5.y, r6.y, r7.y), med8(r0.z, r1.z, r2.z, r3.z, r4.z, r5.z, r6.z, r7.z));
|
||||
let du = p.y - m.y;
|
||||
let dv = p.z - m.z;
|
||||
let excess = du * du / vu + dv * dv / vv;
|
||||
if (excess > threshold) {
|
||||
m.x = med8(r0.x, r1.x, r2.x, r3.x, r4.x, r5.x, r6.x, r7.x);
|
||||
let dy = p.x - m.x;
|
||||
let luminance = dy * dy / nvar(0u, ym);
|
||||
let alone = clamp((1.5 * excess - luminance) / excess, 0.0, 1.0);
|
||||
if (alone > 0.0) {
|
||||
// the two largest border shares (`speck_share`)
|
||||
var top = vec2<f32>(0.0, 0.0);
|
||||
top = top2(top, sshare(r0, m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(r1, m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(r2, m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(r3, m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(r4, m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(r5, m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(r6, m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(r7, m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(ja(up - 1u), m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(ja(up + 1u), m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(ja(i - w - 2u), m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(ja(i - w + 2u), m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(ja(i + w - 2u), m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(ja(i + w + 2u), m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(ja(dn - 1u), m, du, dv, vu, vv, excess));
|
||||
top = top2(top, sshare(ja(dn + 1u), m, du, dv, vu, vv, excess));
|
||||
let compact = clamp((0.8 - top.y) / 0.3, 0.0, 1.0);
|
||||
let t = clamp((excess - threshold) / threshold, 0.0, 1.0);
|
||||
let k = share * t * t * (3.0 - 2.0 * t) * alone * compact;
|
||||
if (k > 0.0) {
|
||||
o.y += k * (m.y - p.y);
|
||||
o.z += k * (m.z - p.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dst[3u * i] = o.x;
|
||||
dst[3u * i + 1u] = o.y;
|
||||
dst[3u * i + 2u] = o.z;
|
||||
}
|
||||
|
||||
// `nrc_joint::pilot`: `a` = transformed image, `b` = its gaussian(0.8); writes the guide.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_pilot(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let w = pu(1u);
|
||||
let h = pu(2u);
|
||||
let x = i % w;
|
||||
let y = i / w;
|
||||
var out = jb3(i);
|
||||
if (!(x == 0u || y == 0u || x + 1u == w || y + 1u == h)) {
|
||||
let p = ja(i);
|
||||
// 9 · noise variance per component, at the pixel's luminance
|
||||
let nv = 9.0 * vec3<f32>(nvar(0u, p.x), nvar(1u, p.x), nvar(2u, p.x));
|
||||
// axis 0 (left/right) and axis 1 (up/down), written out: private arrays indexed in a loop end up in
|
||||
// slow local memory on some GPUs
|
||||
let qa = ja(i - 1u);
|
||||
let qb = ja(i + 1u);
|
||||
let mh = (qa + p + qb) / 3.0;
|
||||
let ha = qa - mh;
|
||||
let hp = p - mh;
|
||||
let hb = qb - mh;
|
||||
let th = (ha * ha + hp * hp + hb * hb) / nv;
|
||||
let vh = th.x + th.y + th.z;
|
||||
let ua = ja(i - w);
|
||||
let ub = ja(i + w);
|
||||
let mv = (ua + p + ub) / 3.0;
|
||||
let va = ua - mv;
|
||||
let vp = p - mv;
|
||||
let vb = ub - mv;
|
||||
let tv = (va * va + vp * vp + vb * vb) / nv;
|
||||
let vvar = tv.x + tv.y + tv.z;
|
||||
// the axis choice fades in between 0.8 and 1.25 times its bound (nrc_joint::pilot_pick)
|
||||
let sv = smoothstep(0.8, 1.25, vh / max(4.0, 4.0 * vvar));
|
||||
let sh = smoothstep(0.8, 1.25, vvar / max(4.0, 4.0 * vh));
|
||||
if (sv >= 1.0) {
|
||||
out = mv;
|
||||
} else if (sh >= 1.0) {
|
||||
out = mh;
|
||||
} else {
|
||||
out = out + (mv - out) * sv + (mh - out) * sh;
|
||||
}
|
||||
}
|
||||
dst[3u * i] = out.x;
|
||||
dst[3u * i + 1u] = out.y;
|
||||
dst[3u * i + 2u] = out.z;
|
||||
}
|
||||
|
||||
// Paths of the direct neighbours, exp(−distance) (1 where there is no pair): `a` = guide; writes path pairs.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_links1(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let w = pu(1u);
|
||||
let h = pu(2u);
|
||||
let x = i % w;
|
||||
let y = i / w;
|
||||
let p = ja(i);
|
||||
var q = vec2<f32>(1.0);
|
||||
if (x + 1u < w) {
|
||||
let d = jdist(p, ja(i + 1u));
|
||||
q.x = jweight(d, d);
|
||||
}
|
||||
if (y + 1u < h) {
|
||||
let d = jdist(p, ja(i + w));
|
||||
q.y = jweight(d, d);
|
||||
}
|
||||
dst[2u * i] = q.x;
|
||||
dst[2u * i + 1u] = q.y;
|
||||
}
|
||||
|
||||
// Paths of length 2·delta from those of length delta (`a`, path pairs): their minimum. P[3] = delta.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_paths(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let w = pu(1u);
|
||||
let h = pu(2u);
|
||||
let delta = pu(3u);
|
||||
let x = i % w;
|
||||
let y = i / w;
|
||||
var ph = a[2u * i];
|
||||
var pv = a[2u * i + 1u];
|
||||
if (x + delta < w) {
|
||||
ph = min(ph, a[2u * (i + delta)]);
|
||||
}
|
||||
if (y + delta < h) {
|
||||
pv = min(pv, a[2u * (i + delta * w) + 1u]);
|
||||
}
|
||||
dst[2u * i] = ph;
|
||||
dst[2u * i + 1u] = pv;
|
||||
}
|
||||
|
||||
// `nrc_joint::path_weight`.
|
||||
fn jpweight(d: f32, path: f32) -> f32 {
|
||||
return select(min(exp(-d), path), path, d == 0.0);
|
||||
}
|
||||
|
||||
// The pair weights at distance `next` from the guide (`a`) and the paths (`b`); writes weight pairs.
|
||||
// Noise parameters as `nrcj_pilot`; P[13] = next.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_links(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let w = pu(1u);
|
||||
let h = pu(2u);
|
||||
let next = pu(13u);
|
||||
let x = i % w;
|
||||
let y = i / w;
|
||||
let p = ja(i);
|
||||
var lh = 0.0;
|
||||
var lv = 0.0;
|
||||
let ph = b[2u * i];
|
||||
let pv = b[2u * i + 1u];
|
||||
if (x + next < w && ph > 0.0) {
|
||||
lh = jpweight(jdist(p, ja(i + next)), ph);
|
||||
}
|
||||
if (y + next < h && pv > 0.0) {
|
||||
lv = jpweight(jdist(p, ja(i + next * w)), pv);
|
||||
}
|
||||
dst[2u * i] = lh;
|
||||
dst[2u * i + 1u] = lv;
|
||||
}
|
||||
|
||||
// One horizontal diffusion step (`nrc_joint::diffuse_h`): `a` = chroma pairs, `b` = weight pairs.
|
||||
// P[0] = n, P[1] = w, P[2] = h, P[3] = delta, P[4] = rate.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_dh(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let w = pu(1u);
|
||||
let delta = pu(3u);
|
||||
let rate = pf(4u);
|
||||
let x = i % w;
|
||||
let p = ja2(i);
|
||||
var o = p;
|
||||
if (x >= delta) {
|
||||
o += rate * b[2u * (i - delta)] * (ja2(i - delta) - p);
|
||||
}
|
||||
if (x + delta < w) {
|
||||
o += rate * b[2u * i] * (ja2(i + delta) - p);
|
||||
}
|
||||
dst[2u * i] = o.x;
|
||||
dst[2u * i + 1u] = o.y;
|
||||
}
|
||||
|
||||
// One vertical diffusion step (`nrc_joint::v_row`), parameters as `nrcj_dh`.
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_dv(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let i = lin_index(g, nw);
|
||||
if (i >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let w = pu(1u);
|
||||
let h = pu(2u);
|
||||
let delta = pu(3u);
|
||||
let rate = pf(4u);
|
||||
let y = i / w;
|
||||
let p = ja2(i);
|
||||
var o = p;
|
||||
if (y >= delta) {
|
||||
o += rate * b[2u * (i - delta * w) + 1u] * (ja2(i - delta * w) - p);
|
||||
}
|
||||
if (y + delta < h) {
|
||||
o += rate * b[2u * i + 1u] * (ja2(i + delta * w) - p);
|
||||
}
|
||||
dst[2u * i] = o.x;
|
||||
dst[2u * i + 1u] = o.y;
|
||||
}
|
||||
|
||||
// Back to RGB with the image's own luminance, blended by the strength: `a` = image, `b` = a band's
|
||||
// filtered chroma pairs, `dst` = the whole output. P[0] = pixels written, P[1] = strength,
|
||||
// P[2] = first pixel written (in the image), P[3] = first pixel of the band (in the image).
|
||||
@compute @workgroup_size(256)
|
||||
fn nrcj_recon(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
|
||||
let k = lin_index(g, nw);
|
||||
if (k >= pu(0u)) {
|
||||
return;
|
||||
}
|
||||
let s = pf(1u);
|
||||
let i = pu(2u) + k;
|
||||
let bi = i - pu(3u);
|
||||
let p = ja(i);
|
||||
let y = lum2020(p);
|
||||
let r = y + b[2u * bi];
|
||||
let bl = y + b[2u * bi + 1u];
|
||||
let res = vec3<f32>(r, (y - 0.2627 * r - 0.0593 * bl) / 0.6780, bl);
|
||||
let o = p + s * (res - p);
|
||||
dst[3u * i] = o.x;
|
||||
dst[3u * i + 1u] = o.y;
|
||||
dst[3u * i + 2u] = o.z;
|
||||
}
|
||||
@@ -16,6 +16,9 @@ use lightcraft_raster::{Rgb32f, Rgba8};
|
||||
|
||||
const MEAN_LSB: f64 = 0.5;
|
||||
const MAX_LSB: u8 = 3;
|
||||
/// Float renders have no dither to allow for: the bounds of [`check_hdr`], in 8-bit steps.
|
||||
const HDR_MEAN_STEPS: f64 = 0.02;
|
||||
const HDR_MAX_STEPS: f64 = 1.0;
|
||||
|
||||
fn gpu() -> bool {
|
||||
let ok = lightcraft_gpu::available();
|
||||
@@ -743,9 +746,9 @@ fn light_v3_operators_match() {
|
||||
s.hdr.enabled = true;
|
||||
s.hdr.max_ev = 2.0;
|
||||
check("V4 HDR preview", &src, &info, &s, &req);
|
||||
// High-bit-depth exports use the CPU; the GPU kernel writes 8-bit previews.
|
||||
let hdr_req = RenderRequest { depth: lightcraft_pipeline::OutputDepth::F32Hdr, ..req };
|
||||
assert_eq!(lightcraft_gpu::try_render(&src, &info, &s, &hdr_req, None).err(), Some(lightcraft_gpu::Fallback::NotTried));
|
||||
// Other high-bit-depth exports use the CPU; the GPU kernel writes 8 bits or the float HDR render.
|
||||
let deep_req = RenderRequest { depth: lightcraft_pipeline::OutputDepth::U16, ..req };
|
||||
assert_eq!(lightcraft_gpu::try_render(&src, &info, &s, &deep_req, None).err(), Some(lightcraft_gpu::Fallback::NotTried));
|
||||
s.hdr.enabled = false;
|
||||
let cache = StageCache::default();
|
||||
for k in 0..3 {
|
||||
@@ -1160,6 +1163,122 @@ fn lut_profiles_match() {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`check`] for the float HDR render, compared on the sRGB curve (unbounded above SDR white) in
|
||||
/// 8-bit steps. `over`: the samples must leave SDR.
|
||||
fn check_hdr(name: &str, src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, over: bool) {
|
||||
use lightcraft_color::transfer::linear_to_srgb;
|
||||
use lightcraft_pipeline::{DeepSamples, OutputDepth};
|
||||
let req = RenderRequest { depth: OutputDepth::F32Hdr, ..*req };
|
||||
let cpu = render(src, info, s, &req);
|
||||
let gpu = lightcraft_gpu::try_render(src, info, s, &req, None).expect("a float render on the GPU, without the CPU fallback");
|
||||
let (cd, gd) = (cpu.deep.expect("CPU float samples"), gpu.deep.expect("GPU float samples"));
|
||||
assert_eq!((cd.width, cd.height, cd.space), (gd.width, gd.height, gd.space), "{name}");
|
||||
let (DeepSamples::F32(c), DeepSamples::F32(g)) = (&cd.samples, &gd.samples) else { panic!("{name}: float samples") };
|
||||
assert_eq!(c.len(), g.len(), "{name}");
|
||||
let peak = s.hdr.peak();
|
||||
assert!(g.iter().all(|v| (0.0..=peak).contains(v)), "{name}: GPU samples outside 0..{peak}");
|
||||
let above = g.iter().filter(|v| **v > 1.0).count() as f64 / g.len() as f64;
|
||||
assert_eq!(above > 0.0, over, "{name}: {:.3}% of the samples above SDR white", above * 100.0);
|
||||
let (mut sum, mut max) = (0f64, 0f64);
|
||||
for (a, b) in c.iter().zip(g) {
|
||||
let d = f64::from((linear_to_srgb(*a) - linear_to_srgb(*b)).abs()) * 255.0;
|
||||
sum += d;
|
||||
max = max.max(d);
|
||||
}
|
||||
let mean = sum / c.len() as f64;
|
||||
eprintln!("{name:<36} {}x{} mean {mean:.4} max {max:.3} above SDR {:.2}%", cd.width, cd.height, above * 100.0);
|
||||
assert!(mean < HDR_MEAN_STEPS && max <= HDR_MAX_STEPS, "{name}: mean {mean:.4}, max {max:.3} steps");
|
||||
let (mean, max, _) = diff(&cpu.image, &gpu.image);
|
||||
assert!(mean < MEAN_LSB && max <= MAX_LSB, "{name}: 8-bit image mean {mean:.4}, max {max}");
|
||||
assert_eq!(cpu.histogram.total, gpu.histogram.total, "{name}");
|
||||
}
|
||||
|
||||
/// The float HDR render matches the CPU's on every process, through every stage with an HDR rule:
|
||||
/// tone map and highlight desaturation to the peak, V4's operators, vignette, gamut map, curves
|
||||
/// above SDR white, grain and LUT profiles.
|
||||
#[test]
|
||||
fn hdr_float_render_matches() {
|
||||
if !gpu() {
|
||||
return;
|
||||
}
|
||||
let src = scene(1, 900, 600);
|
||||
let raw = SourceInfo { raw: true, ..Default::default() };
|
||||
let req = RenderRequest::fit(640, 640);
|
||||
let hdr = |p: Process| {
|
||||
let mut s = DevelopSettings { process: p.version(), ..Default::default() };
|
||||
s.hdr.enabled = true;
|
||||
s.hdr.max_ev = 3.0;
|
||||
s.light.exposure = 1.5;
|
||||
s
|
||||
};
|
||||
for p in Process::ALL {
|
||||
let mut s = hdr(p);
|
||||
check_hdr(&format!("{p:?} HDR"), &src, &raw, &s, &req, true);
|
||||
typical(&mut s);
|
||||
s.light.exposure = 1.5;
|
||||
s.light.contrast = 35.0;
|
||||
s.light.whites = 40.0;
|
||||
s.light.blacks = -30.0;
|
||||
check_hdr(&format!("{p:?} HDR typical"), &src, &raw, &s, &req, true);
|
||||
}
|
||||
lightcraft_pipeline::lut::register("lut:gpu-test-hdr", look_lut(17, 1.0));
|
||||
let cases: [(&str, Edit); 7] = [
|
||||
("HDR vignette out", |s| s.vignette.amount = -40.0),
|
||||
("HDR vignette lighten", |s| s.vignette.amount = 40.0),
|
||||
("HDR saturated", saturated),
|
||||
("HDR curves", |s| {
|
||||
s.curve.master = vec![Point::new(0.0, 0.05), Point::new(0.5, 0.55), Point::new(1.0, 0.95)];
|
||||
s.curve.blue = vec![Point::new(0.0, 0.0), Point::new(0.5, 0.45), Point::new(1.0, 1.0)];
|
||||
s.curve.refine_saturation = 20.0;
|
||||
}),
|
||||
("HDR grain", |s| {
|
||||
s.grain.amount = 50.0;
|
||||
s.grain.size = 40.0;
|
||||
s.grain.roughness = 60.0;
|
||||
}),
|
||||
("HDR LUT", |s| {
|
||||
s.profile.id = "lut:gpu-test-hdr".into();
|
||||
s.profile.amount = 80.0;
|
||||
}),
|
||||
("HDR peak 1 stop", |s| s.hdr.max_ev = 1.0),
|
||||
];
|
||||
for (name, edit) in cases {
|
||||
let mut s = hdr(Process::LATEST);
|
||||
edit(&mut s);
|
||||
check_hdr(name, &src, &raw, &s, &req, true);
|
||||
}
|
||||
let s = hdr(Process::LATEST);
|
||||
for space in lightcraft_pipeline::OutputSpace::ALL {
|
||||
check_hdr(&format!("HDR in {space:?}"), &src, &raw, &s, &RenderRequest { space, ..req }, true);
|
||||
}
|
||||
let win = RenderRequest { window: Some(lightcraft_pipeline::PixelWindow { x: 200, y: 100, w: 320, h: 240 }), ..RenderRequest::fit(900, 600) };
|
||||
check_hdr("HDR window", &src, &raw, &s, &win, true);
|
||||
check_hdr("HDR draft", &src, &raw, &s, &RenderRequest { quality: Quality::Draft, ..req }, true);
|
||||
let proof =
|
||||
Some(lightcraft_pipeline::Proof { space: lightcraft_pipeline::OutputSpace::Srgb, dest_warning: false, display_warning: false, profile: 0 });
|
||||
check_hdr("HDR soft proof", &src, &raw, &s, &RenderRequest { space: lightcraft_pipeline::OutputSpace::Rec2020, proof, ..req }, true);
|
||||
// an edit with HDR off: the same request is the linear float render, 0..1
|
||||
let mut s = DevelopSettings::default();
|
||||
typical(&mut s);
|
||||
check_hdr("HDR off", &src, &raw, &s, &req, false);
|
||||
}
|
||||
|
||||
/// The float output in several bands of rows, with position-dependent grain.
|
||||
#[test]
|
||||
fn hdr_float_render_matches_in_bands() {
|
||||
if !gpu() {
|
||||
return;
|
||||
}
|
||||
let src = scene(3, 3000, 2000);
|
||||
let mut s = DevelopSettings::default();
|
||||
typical(&mut s);
|
||||
s.hdr.enabled = true;
|
||||
s.hdr.max_ev = 2.0;
|
||||
s.light.exposure = 1.5;
|
||||
s.grain.amount = 30.0;
|
||||
check_hdr("HDR banded", &src, &SourceInfo { raw: true, ..Default::default() }, &s, &RenderRequest::fit(3000, 2000), true);
|
||||
}
|
||||
|
||||
/// Refine Edges on a mask is the cross guided filter on the device, blended by √refine.
|
||||
#[test]
|
||||
fn refine_edges_match() {
|
||||
|
||||
@@ -106,6 +106,15 @@ fn failed_gpu_renders_fall_back_with_a_reason() {
|
||||
assert!(!lightcraft_gpu::available());
|
||||
lightcraft_gpu::reset_failures();
|
||||
ok("after dropped work");
|
||||
// ... and the float render, where a cleared word would pass for a valid 0
|
||||
lightcraft_gpu::inject_fault(Fault::DropWork);
|
||||
let hdr = RenderRequest { depth: lightcraft_pipeline::OutputDepth::F32Hdr, ..req };
|
||||
match lightcraft_gpu::try_render(&src, &info, &s, &hdr, None) {
|
||||
Err(Fallback::Failed(why)) => assert!(why.contains("incomplete"), "an unwritten float image must not be returned: {why}"),
|
||||
other => panic!("a float render with dropped work is redone on the CPU: {:?}", other.map(|_| ())),
|
||||
}
|
||||
lightcraft_gpu::reset_failures();
|
||||
ok("after dropped float work");
|
||||
|
||||
// a black photo is still rendered (on the CPU, to be sure)
|
||||
let black = Arc::new(lightcraft_raster::Rgb32f::from_fn(256, 256, |_, _| [0.0; 3]));
|
||||
|
||||
@@ -412,3 +412,48 @@ fn export_without_token_finishes_after_eof() {
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A batch-edit recipe is reachable over MCP without a tool of its own: `run_command` takes
|
||||
/// `library.import` with a `recipe`, the generated `cmd_preset_saveRecipe` tool saves one as a
|
||||
/// preset, `list_commands` documents both, and a recipe naming white balance is a tool error that
|
||||
/// imports nothing.
|
||||
#[test]
|
||||
fn a_batch_edit_recipe_is_reachable_over_mcp() {
|
||||
let dir = std::env::temp_dir().join(format!("lightcraft-mcp-recipe-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let img = lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [(x * 2) as u8, (y * 3) as u8, 128, 255]);
|
||||
lightcraft_mcp::write_image(&dir.join("gradient.png"), &img, 90).unwrap();
|
||||
let paths = json!([dir.to_string_lossy()]);
|
||||
let mut server = Server::new(Box::new(Headless::default()));
|
||||
let replies = session(
|
||||
&mut server,
|
||||
&[
|
||||
call(1, "list_commands", json!({"filter": "recipe"})),
|
||||
call(2, "run_command", json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "wb.temp", "value": 5000}]}})),
|
||||
call(3, "query_photos", json!({"limit": 5})),
|
||||
call(
|
||||
4,
|
||||
"run_command",
|
||||
json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]}}),
|
||||
),
|
||||
call(5, "get_develop", json!({})),
|
||||
call(6, "cmd_preset_saveRecipe", json!({"name": "Warm", "recipe": [{"id": "light.exposure", "value": 0.5}]})),
|
||||
call(7, "list_commands", json!({"filter": "library.import"})),
|
||||
],
|
||||
);
|
||||
let listed = |r: &Value| -> Vec<Value> { serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap() };
|
||||
let save = listed(&replies[0]).into_iter().find(|c| c["id"] == "preset.saveRecipe").expect("preset.saveRecipe is listed");
|
||||
assert!(save["params"].as_str().unwrap().contains("recipe: [{id:"), "{save}");
|
||||
assert_eq!(replies[1]["result"]["isError"], true, "{}", replies[1]);
|
||||
assert!(replies[1]["result"]["content"][0]["text"].as_str().unwrap().contains("white balance"), "{}", replies[1]);
|
||||
assert!(replies[2]["result"]["structuredContent"]["photos"].as_array().unwrap().is_empty(), "the refused import added nothing");
|
||||
assert_eq!(replies[3]["result"]["isError"], false, "{}", replies[3]);
|
||||
assert_eq!(replies[3]["result"]["structuredContent"]["imported"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(replies[4]["result"]["structuredContent"]["light"]["exposure"], 0.5, "{}", replies[4]);
|
||||
assert_eq!(replies[4]["result"]["structuredContent"]["color"]["vibrance"], 20.0, "{}", replies[4]);
|
||||
assert_eq!(replies[5]["result"]["isError"], false, "{}", replies[5]);
|
||||
assert_eq!(replies[5]["result"]["structuredContent"]["name"], "Warm");
|
||||
let import = listed(&replies[6]).into_iter().find(|c| c["id"] == "library.import").expect("library.import is listed");
|
||||
assert!(import["params"].as_str().unwrap().contains("recipe?: [{id:"), "{import}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
//! - [`cr3`] — the Canon CR3 container (metadata blocks, XMP, the JPEG and raw tracks).
|
||||
//! - [`heif`] — the HEIF/HEIC/AVIF container's Exif and XMP items (no HEVC decoder needed).
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod container;
|
||||
pub mod cr3;
|
||||
|
||||
@@ -305,7 +305,7 @@ fn parse_tree(s: &str) -> Result<Node, XmpError> {
|
||||
}
|
||||
}
|
||||
Event::End(_) if stack.len() > 1 => {
|
||||
let n = stack.pop().expect("len > 1");
|
||||
let Some(n) = stack.pop() else { return Err(XmpError::Xml("end tag without an open element".into())) };
|
||||
scopes.pop();
|
||||
if let Some(parent) = stack.last_mut() {
|
||||
parent.children.push(n);
|
||||
@@ -340,10 +340,11 @@ fn parse_tree(s: &str) -> Result<Node, XmpError> {
|
||||
}
|
||||
// close unterminated elements leniently
|
||||
while stack.len() > 1 {
|
||||
let n = stack.pop().expect("len > 1");
|
||||
stack.last_mut().expect("root").children.push(n);
|
||||
let Some(n) = stack.pop() else { return Err(XmpError::Xml("unterminated element without a node".into())) };
|
||||
let Some(parent) = stack.last_mut() else { return Err(XmpError::Xml("unterminated element without a parent".into())) };
|
||||
parent.children.push(n);
|
||||
}
|
||||
Ok(stack.pop().expect("root"))
|
||||
stack.pop().ok_or_else(|| XmpError::Xml("xmp packet without a root element".into()))
|
||||
}
|
||||
|
||||
fn is_rdf_meta_attr(k: &str) -> bool {
|
||||
|
||||
@@ -349,7 +349,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
|
||||
},
|
||||
// V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last
|
||||
// knot, the generic curve from half a stop below its white point instead of clipping (issue #1632)
|
||||
Process::V5 => match info.camera_tone.as_ref().filter(|_| info.raw) {
|
||||
Process::V5 | Process::V6 => match info.camera_tone.as_ref().filter(|_| info.raw) {
|
||||
Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak),
|
||||
None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak),
|
||||
None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak),
|
||||
|
||||
@@ -336,6 +336,43 @@ impl Frame {
|
||||
Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, Filter::Mitchell)),
|
||||
None => std::borrow::Cow::Borrowed(o),
|
||||
};
|
||||
self.sample_base(base, plan, w, h)
|
||||
}
|
||||
|
||||
/// [`Frame::sample`] of each of `windows` of this frame at its `full_w × full_h` output size: the
|
||||
/// same pixels, with the source oriented and prefiltered once for all of them rather than per window.
|
||||
pub fn sample_windows(&self, src: &Rgb32f, full_w: usize, full_h: usize, windows: &[crate::PixelWindow]) -> Vec<Rgb32f> {
|
||||
let oriented = if self.orient == Orientation::Normal { None } else { Some(src.oriented(self.orient)) };
|
||||
let o = oriented.as_ref().unwrap_or(src);
|
||||
let plans: Vec<(Frame, SamplePlan)> = windows
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let frame = if (t.w, t.h) == (full_w, full_h) { self.clone() } else { self.window(full_w, full_h, *t) };
|
||||
let plan = frame.sample_plan(src.width, src.height, t.w, t.h);
|
||||
(frame, plan)
|
||||
})
|
||||
.collect();
|
||||
let mut bases: Vec<((usize, usize), Rgb32f)> = Vec::new();
|
||||
for dims in plans.iter().filter_map(|p| p.1.prefilter) {
|
||||
if !bases.iter().any(|b| b.0 == dims) {
|
||||
bases.push((dims, resize(o, dims.0, dims.1, Filter::Mitchell)));
|
||||
}
|
||||
}
|
||||
plans
|
||||
.into_iter()
|
||||
.zip(windows)
|
||||
.map(|((frame, plan), t)| {
|
||||
let base = match plan.prefilter.and_then(|dims| bases.iter().find(|b| b.0 == dims)) {
|
||||
Some(b) => std::borrow::Cow::Borrowed(&b.1),
|
||||
None => std::borrow::Cow::Borrowed(o),
|
||||
};
|
||||
frame.sample_base(base, plan, t.w, t.h)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The sampling of [`Frame::sample`] from the oriented, prefiltered source `base`.
|
||||
fn sample_base(&self, base: std::borrow::Cow<'_, Rgb32f>, plan: SamplePlan, w: usize, h: usize) -> Rgb32f {
|
||||
let affine = |xf: Affine| {
|
||||
let mut out = Rgb32f::new(w, h);
|
||||
par_rows(&mut out.data, w, |y, row| {
|
||||
|
||||
@@ -40,6 +40,9 @@ pub mod local_tone;
|
||||
pub mod lut;
|
||||
pub mod mask_space;
|
||||
pub mod masks;
|
||||
pub mod nrc_joint;
|
||||
#[cfg(test)]
|
||||
mod nrc_joint_reference;
|
||||
pub mod optics;
|
||||
pub mod output;
|
||||
pub mod profiles;
|
||||
@@ -393,6 +396,8 @@ struct CacheEntry {
|
||||
geo: u64,
|
||||
sampled: Arc<Rgb32f>,
|
||||
lin: Option<(u64, Arc<Rgb32f>)>,
|
||||
/// The joint colour NR's noise model of the whole frame ([`colour_noise`]), keyed by [`Plan::noise_key`].
|
||||
colour_noise: Option<(u64, nrc_joint::JointNoise)>,
|
||||
planes: local::Planes,
|
||||
}
|
||||
|
||||
@@ -425,6 +430,9 @@ pub struct Plan<'a> {
|
||||
/// [`Self::lin_key`] without the noise-reduction settings: draft renders reuse the smooth
|
||||
/// planes of an image that differs from this one only in its noise reduction.
|
||||
pub pre_nr_key: u64,
|
||||
/// Key of the whole frame's noise model for the joint colour NR ([`colour_noise`]): what it is
|
||||
/// measured after (everything before the colour NR), not the colour NR's own settings.
|
||||
pub noise_key: u64,
|
||||
/// Red eye / pet eye corrections with their detected pupils, in output pixels.
|
||||
pub eyes: Vec<redeye::EyeK>,
|
||||
/// The whole frame's dehaze airlight, for a windowed render (which can't see the whole frame).
|
||||
@@ -435,6 +443,8 @@ pub struct Plan<'a> {
|
||||
pub keep: Option<PixelWindow>,
|
||||
/// The source's segmentation mattes ([`SourceInfo::mattes`]).
|
||||
pub mattes: Option<Arc<masks::Mattes>>,
|
||||
/// The whole frame and its output size (a windowed render's [`Self::frame`] is part of it).
|
||||
pub full: (geometry::Frame, usize, usize),
|
||||
}
|
||||
|
||||
/// Long edge of the small render a windowed render estimates the whole frame's airlight from.
|
||||
@@ -461,8 +471,13 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
|
||||
let (full_w, full_h) = req.size(&frame);
|
||||
// sizes and scale are those of the whole output; a window only narrows what is drawn
|
||||
let px_per_long = frame.px_per_long(full_w);
|
||||
let src_long = src.width.max(src.height);
|
||||
// (an original reported smaller than the source is the source)
|
||||
let native_long = info.native_long.unwrap_or(0).max(src_long).max(1);
|
||||
let detail_scale = local::detail_scale(px_per_long, native_long);
|
||||
let mut fixed_air = None;
|
||||
let mut keep = None;
|
||||
let full = (frame.clone(), full_w, full_h);
|
||||
let (frame, w, h) = match req.window {
|
||||
Some(win) => {
|
||||
let win = win.clamped(full_w, full_h);
|
||||
@@ -471,8 +486,20 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
|
||||
let (pw, ph) = (((full_w as f64 * k).round() as usize).max(1), ((full_h as f64 * k).round() as usize).max(1));
|
||||
fixed_air = Some(local::frame_airlight(src, info, s, &frame, pw, ph));
|
||||
}
|
||||
// (spots grow the rendered window; only 8-bit renders are cut back to the request)
|
||||
let work = if req.depth == OutputDepth::U8 { spots::window_for_reads(s, &frame, full_w, full_h, px_per_long, win) } else { win };
|
||||
// (spots grow the rendered window of 8-bit renders; a grown window is cut back to the request)
|
||||
let mut work = if req.depth == OutputDepth::U8 { spots::window_for_reads(s, &frame, full_w, full_h, px_per_long, win) } else { win };
|
||||
if local::joint_colour_nr(s)
|
||||
&& let Some(params) = local::nrc_params(s, detail_scale)
|
||||
{
|
||||
// The joint diffusion reads a chain of neighbours across its scales. Keep
|
||||
// those reads outside the requested zoom window, just as spot reads are, at every depth.
|
||||
let halo = params.passes.last().map_or(0, |p| (6.0 * p.sigma).ceil() as usize).saturating_add(4);
|
||||
let x = work.x.saturating_sub(halo);
|
||||
let y = work.y.saturating_sub(halo);
|
||||
let right = work.x.saturating_add(work.w).saturating_add(halo).min(full_w);
|
||||
let bottom = work.y.saturating_add(work.h).saturating_add(halo).min(full_h);
|
||||
work = PixelWindow { x, y, w: right.saturating_sub(x), h: bottom.saturating_sub(y) }.clamped(full_w, full_h);
|
||||
}
|
||||
if work != win {
|
||||
keep = Some(PixelWindow { x: win.x - work.x, y: win.y - work.y, ..win });
|
||||
}
|
||||
@@ -480,10 +507,6 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
|
||||
}
|
||||
None => (frame, full_w, full_h),
|
||||
};
|
||||
let src_long = src.width.max(src.height);
|
||||
// (an original reported smaller than the source is the source)
|
||||
let native_long = info.native_long.unwrap_or(0).max(src_long).max(1);
|
||||
let detail_scale = local::detail_scale(px_per_long, native_long);
|
||||
let geo = hash_of((format!("{frame:?}"), w, h));
|
||||
let (wb_t, wb_tint) = local::effective_wb(info, s);
|
||||
let eyes = redeye::resolve(src, &s.red_eye, s.orientation, &frame, w, h, px_per_long);
|
||||
@@ -503,7 +526,10 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
|
||||
pre_nr_key,
|
||||
[d.nr_luminance, d.nr_detail, d.nr_color, d.nr_color_detail, d.nr_color_smoothness].map(f64::to_bits),
|
||||
detail_scale.to_bits(),
|
||||
// the process picks the colour filter (Update to Current Process, undo)
|
||||
local::joint_colour_nr(s),
|
||||
));
|
||||
let noise_key = hash_of((pre_nr_key, [d.nr_luminance, d.nr_detail].map(f64::to_bits), detail_scale.to_bits()));
|
||||
Plan {
|
||||
settings,
|
||||
frame,
|
||||
@@ -516,13 +542,64 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
|
||||
geo,
|
||||
lin_key,
|
||||
pre_nr_key,
|
||||
noise_key,
|
||||
eyes,
|
||||
fixed_air,
|
||||
keep,
|
||||
mattes: info.mattes.clone(),
|
||||
full,
|
||||
}
|
||||
}
|
||||
|
||||
/// The joint colour NR's noise model of the whole frame, measured on fixed tiles of it
|
||||
/// ([`nrc_joint::tiles`]) so that every window of it is filtered alike. The tiles are resampled,
|
||||
/// tone-mapped, white-balanced and luminance-denoised like the frame; the retouching and defringing
|
||||
/// are left out. `None` when the joint colour NR is off, or when the render is the whole frame and
|
||||
/// that is a single tile: the noise is then measured on the image itself, as the CPU and the GPU do.
|
||||
pub fn colour_noise(src: &Rgb32f, info: &SourceInfo, p: &Plan<'_>) -> Option<nrc_joint::JointNoise> {
|
||||
let s = &*p.settings;
|
||||
if !local::joint_colour_nr(s) || local::nrc_params(s, p.detail_scale).is_none() {
|
||||
return None;
|
||||
}
|
||||
let (full, fw, fh) = &p.full;
|
||||
let windows = nrc_joint::tiles(*fw, *fh);
|
||||
if (p.w, p.h) == (*fw, *fh) && windows.len() == 1 {
|
||||
return None;
|
||||
}
|
||||
let t = profiling().then(std::time::Instant::now);
|
||||
let (lum, _) = local::nr_params(s, p.detail_scale);
|
||||
// the source oriented and prefiltered once for all tiles
|
||||
let sampled = full.sample_windows(src, *fw, *fh, &windows);
|
||||
let tiles: Vec<Rgb32f> = windows
|
||||
.into_iter()
|
||||
.zip(sampled)
|
||||
.map(|(t, mut img)| {
|
||||
let frame = if (t.w, t.h) == (*fw, *fh) { full.clone() } else { full.window(*fw, *fh, t) };
|
||||
let tile = Plan {
|
||||
settings: Cow::Borrowed(s),
|
||||
frame,
|
||||
w: t.w,
|
||||
h: t.h,
|
||||
eyes: Vec::new(),
|
||||
fixed_air: None,
|
||||
keep: None,
|
||||
mattes: None,
|
||||
full: p.full.clone(),
|
||||
..*p
|
||||
};
|
||||
local_tone::apply(&mut img, info, &tile);
|
||||
local::white_balance(&mut img, info, s);
|
||||
local::apply_nr(&mut img, lum, None);
|
||||
img
|
||||
})
|
||||
.collect();
|
||||
let noise = nrc_joint::noise_of_tiles(&tiles);
|
||||
if let Some(t) = t {
|
||||
eprintln!(" nr colour noise model ({} tiles): {:.0} ms", tiles.len(), t.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
Some(noise)
|
||||
}
|
||||
|
||||
/// Whether the scene-linear stage needs work only the CPU does (defringe, spot removal).
|
||||
pub fn lin_needs_cpu(s: &DevelopSettings, info: &SourceInfo) -> bool {
|
||||
let o = &s.optics;
|
||||
@@ -633,13 +710,17 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
|
||||
};
|
||||
lap("sample", &mut t);
|
||||
|
||||
let mut colour_noise = cached.as_ref().and_then(|e| e.colour_noise).filter(|(k, _)| *k == plan.noise_key);
|
||||
let lin = match cached.as_ref().and_then(|e| e.lin.clone()).filter(|(k, _)| *k == lin_key) {
|
||||
Some((_, img)) => img,
|
||||
None => {
|
||||
// Without a cache the resampled buffer is ours: work on it in place.
|
||||
let mut img = if shared.is_some() { (*sampled).clone() } else { Arc::unwrap_or_clone(sampled.clone()) };
|
||||
lin_cpu(&mut img, info, &plan);
|
||||
local::denoise(&mut img, s, detail_scale);
|
||||
if colour_noise.is_none() {
|
||||
colour_noise = self::colour_noise(src_img, info, &plan).map(|n| (plan.noise_key, n));
|
||||
}
|
||||
local::denoise(&mut img, s, detail_scale, colour_noise.as_ref().map(|c| &c.1));
|
||||
Arc::new(img)
|
||||
}
|
||||
};
|
||||
@@ -659,10 +740,14 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
|
||||
}
|
||||
lap("prepare", &mut t);
|
||||
if let Some((a, c)) = shared {
|
||||
c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), planes });
|
||||
c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), colour_noise, planes });
|
||||
}
|
||||
if req.depth != OutputDepth::U8 {
|
||||
let deep = finish::finish_deep(&prep, s, frame, info, req.space, req.depth, req.proof);
|
||||
let deep = match plan.keep {
|
||||
Some(k) => deep.crop(k.x, k.y, k.w, k.h),
|
||||
None => deep,
|
||||
};
|
||||
let image = deep.to_rgba8();
|
||||
let histogram = Histogram::of_srgb8(&image);
|
||||
lap("finish (deep)", &mut t);
|
||||
|
||||
@@ -284,7 +284,7 @@ pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool {
|
||||
let camera_look = info.raw && info.camera_tone.is_some();
|
||||
match s.process.process() {
|
||||
Process::V1 | Process::V2 | Process::V3 => false,
|
||||
Process::V4 | Process::V5 => camera_look,
|
||||
Process::V4 | Process::V5 | Process::V6 => camera_look,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize {
|
||||
pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize {
|
||||
match s.process.process() {
|
||||
Process::V1 => 0,
|
||||
Process::V2 | Process::V3 | Process::V4 | Process::V5 => base_detail_radius(px_per_long),
|
||||
Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => base_detail_radius(px_per_long),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,9 +458,17 @@ pub fn nr_params(s: &DevelopSettings, scale: f32) -> (Option<NrLum>, Option<NrCo
|
||||
|
||||
/// Noise reduction at output resolution: luminance via an edge-aware self-guided filter on
|
||||
/// log-luminance, colour by blurring chromaticity (rgb / Y) and re-applying the original luminance.
|
||||
/// `scale`: output pixels per pixel of the original ([`nr_params`]).
|
||||
pub fn denoise(img: &mut Rgb32f, s: &DevelopSettings, scale: f32) {
|
||||
/// `scale`: output pixels per pixel of the original ([`nr_params`]). `colour_noise`: the whole
|
||||
/// frame's noise model for the joint colour NR ([`crate::colour_noise`]; `None`: measured on `img`).
|
||||
pub fn denoise(img: &mut Rgb32f, s: &DevelopSettings, scale: f32, colour_noise: Option<&crate::nrc_joint::JointNoise>) {
|
||||
let (lum, col) = nr_params(s, scale);
|
||||
if col.is_some() && joint_colour_nr(s) {
|
||||
apply_nr(img, lum, None);
|
||||
if let Some(p) = nrc_params(s, scale) {
|
||||
crate::nrc_joint::denoise(img, &p, (s.detail.nr_color_detail / 100.0) as f32, (s.detail.nr_color / 100.0) as f32, colour_noise);
|
||||
}
|
||||
return;
|
||||
}
|
||||
apply_nr(img, lum, col);
|
||||
}
|
||||
|
||||
@@ -505,6 +513,87 @@ pub fn apply_nr(img: &mut Rgb32f, lum: Option<NrLum>, col: Option<NrColor>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Most samples the noise level of the new colour noise reduction is measured from. The CPU and
|
||||
/// the GPU sample the same pixels (see `nrc_joint::noise_sample_stride`).
|
||||
pub const NRC_SAMPLES: usize = 131_072;
|
||||
|
||||
/// One self-guided pass of the new colour noise reduction: Gaussian windows of `sigma` px, the
|
||||
/// coefficients computed on a plane subsampled by `step`, `eps = k ×` the `pct`-quantile of the
|
||||
/// local variance.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct NrcPass {
|
||||
pub sigma: f32,
|
||||
pub step: usize,
|
||||
pub k: f32,
|
||||
pub pct: f32,
|
||||
}
|
||||
|
||||
/// Parameters of the new colour noise reduction: the offset of the square roots and the passes
|
||||
/// (fine, then coarse).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NrcParams {
|
||||
pub off: f32,
|
||||
pub passes: Vec<NrcPass>,
|
||||
}
|
||||
|
||||
/// The new colour noise reduction's parameters at `scale` output pixels per pixel of the original
|
||||
/// ([`crate::Plan::detail_scale`]), `None` when Color is 0.
|
||||
pub fn nrc_params(s: &DevelopSettings, scale: f32) -> Option<NrcParams> {
|
||||
let amount = (s.detail.nr_color / 100.0) as f32;
|
||||
if amount <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let detail = (s.detail.nr_color_detail / 100.0) as f32;
|
||||
let smooth = 1.0 + (s.detail.nr_color_smoothness / 100.0) as f32;
|
||||
let scale = if scale.is_finite() { scale.clamp(0.05, 1.0) } else { 1.0 };
|
||||
let sigma = (2.0 + 10.0 * amount) * smooth * scale;
|
||||
let k = 64.0 * amount * (1.5 - detail);
|
||||
// the coefficients vary over about sigma: a grid of sigma / 2 holds them
|
||||
let pass = |sigma: f32| NrcPass { sigma, step: (sigma / 2.0).floor().clamp(1.0, 16.0) as usize, k, pct: 0.2 };
|
||||
// fine, then coarse (three times wider); the joint method takes the coarse one's reach
|
||||
Some(NrcParams { off: 0.003, passes: vec![pass(sigma), pass(sigma * 3.0)] })
|
||||
}
|
||||
|
||||
/// Chroma noise variance per channel as a function of the local luminance: `α · Y + β` (shot plus read noise).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct NrcNoise {
|
||||
pub alpha: [f32; 3],
|
||||
pub beta: [f32; 3],
|
||||
}
|
||||
|
||||
impl NrcNoise {
|
||||
#[inline]
|
||||
pub fn var(&self, i: usize, y: f32) -> f32 {
|
||||
(self.alpha[i] * y.max(0.0) + self.beta[i]).max(1e-14)
|
||||
}
|
||||
}
|
||||
|
||||
/// Weighted least squares `v = a · l + b` over `(l, v, weight)` with `a, b ≥ 0`: the free fit if both come out
|
||||
/// non-negative, else the better of the line through the origin (`b = 0`) and the constant (`a = 0`).
|
||||
pub fn fit_nonneg_line(pts: &[(f64, f64, f64)]) -> (f64, f64) {
|
||||
let sw: f64 = pts.iter().map(|p| p.2).sum::<f64>().max(1e-300);
|
||||
let (ml, mv) = (pts.iter().map(|p| p.2 * p.0).sum::<f64>() / sw, pts.iter().map(|p| p.2 * p.1).sum::<f64>() / sw);
|
||||
let (cov, vl) = pts.iter().fold((0.0, 0.0), |(c, v), p| (c + p.2 * (p.0 - ml) * (p.1 - mv), v + p.2 * (p.0 - ml) * (p.0 - ml)));
|
||||
if vl > 0.0 {
|
||||
let a = cov / vl;
|
||||
let b = mv - a * ml;
|
||||
if a >= 0.0 && b >= 0.0 {
|
||||
return (a, b);
|
||||
}
|
||||
}
|
||||
let sse = |a: f64, b: f64| pts.iter().map(|p| p.2 * (p.1 - a * p.0 - b).powi(2)).sum::<f64>();
|
||||
let ll: f64 = pts.iter().map(|p| p.2 * p.0 * p.0).sum();
|
||||
let origin = if ll > 0.0 { (pts.iter().map(|p| p.2 * p.0 * p.1).sum::<f64>() / ll).max(0.0) } else { 0.0 };
|
||||
let constant = mv.max(0.0);
|
||||
if sse(origin, 0.0) < sse(0.0, constant) { (origin, 0.0) } else { (0.0, constant) }
|
||||
}
|
||||
|
||||
/// Whether `s` gets the joint colour noise reduction (`nrc_joint`, process V6 on), else main's
|
||||
/// blurred chromaticity.
|
||||
pub fn joint_colour_nr(s: &DevelopSettings) -> bool {
|
||||
s.process.process() >= lightcraft_develop::Process::V6
|
||||
}
|
||||
|
||||
pub fn log_lum(c: [f32; 3]) -> f32 {
|
||||
(luminance_2020(c).max(1e-7) / crate::tone::GREY).log2()
|
||||
}
|
||||
@@ -811,6 +900,250 @@ pub fn airlight_of(mut v: Vec<f32>) -> f32 {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// Edits saved under V1 to V5 keep main's colour noise reduction (blurred chromaticity); V6 gets
|
||||
/// the joint method of `nrc_joint`.
|
||||
#[test]
|
||||
fn colour_nr_follows_the_process() {
|
||||
use lightcraft_develop::{DevelopSettings, Process};
|
||||
let (w, h) = (96usize, 64usize);
|
||||
let img = Rgb32f::from_fn(w, h, |x, y| {
|
||||
let n = |c: u32| {
|
||||
let mut v = (x as u32).wrapping_mul(0x9e37_79b9) ^ (y as u32).wrapping_mul(0x85eb_ca6b) ^ c.wrapping_mul(0xc2b2_ae35) | 1;
|
||||
v ^= v << 13;
|
||||
v ^= v >> 17;
|
||||
v ^= v << 5;
|
||||
(v as f32 / u32::MAX as f32 - 0.5) * 0.02
|
||||
};
|
||||
let base = if x < w / 2 { [0.06, 0.03, 0.02] } else { [0.02, 0.04, 0.06] };
|
||||
[base[0] + n(1), base[1] + n(2), base[2] + n(3)]
|
||||
});
|
||||
let run = |p: Process| {
|
||||
let mut s = DevelopSettings { process: p.version(), ..Default::default() };
|
||||
s.detail.nr_color = 50.0;
|
||||
let mut o = img.clone();
|
||||
denoise(&mut o, &s, 1.0, None);
|
||||
o
|
||||
};
|
||||
let (v1, v2, v5, v6) = (run(Process::V1), run(Process::V2), run(Process::V5), run(Process::V6));
|
||||
assert!(v1.data == v2.data && v2.data == v5.data, "V1 to V5 share main's colour NR");
|
||||
// main's colour NR clamps at 0 and keeps each pixel's luminance; the joint method keeps it too
|
||||
assert!(v5.data != v6.data, "V6 takes the joint colour NR");
|
||||
let mut s = DevelopSettings { process: Process::V6.version(), ..Default::default() };
|
||||
s.detail.nr_color = 50.0;
|
||||
let mut joint = img.clone();
|
||||
let p = nrc_params(&s, 1.0).expect("Color 50 has parameters");
|
||||
crate::nrc_joint::denoise(&mut joint, &p, (s.detail.nr_color_detail / 100.0) as f32, 0.5, None);
|
||||
assert!(joint.data == v6.data, "V6 is the joint method");
|
||||
}
|
||||
|
||||
/// Float mean of a flat, noisy dark patch over three noise realisations; linear modes assert drift bounds.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn probe_nrc_mean_drift() {
|
||||
use lightcraft_develop::DevelopSettings;
|
||||
let (w, h) = (768usize, 768usize);
|
||||
let mut worst = 0.0f64;
|
||||
for seed0 in [0x2545_f491_4f6c_dd1du64, 0x9e37_79b9_7f4a_7c15, 0x1234_5678_9abc_def1] {
|
||||
let mut seed = seed0;
|
||||
let mut gauss = || {
|
||||
(0..4)
|
||||
.map(|_| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5
|
||||
})
|
||||
.sum::<f32>()
|
||||
* 1.732
|
||||
};
|
||||
for (name, base, sigma) in [
|
||||
("dark warm, blue near 0", [0.006f32, 0.004, 0.0008], [0.002f32, 0.0015, 0.003]),
|
||||
("cat-like, red near 0", [0.0015, 0.004, 0.009], [0.004, 0.003, 0.005]),
|
||||
] {
|
||||
let mut img = Rgb32f::new(w, h);
|
||||
for p in img.data.iter_mut() {
|
||||
*p = [0, 1, 2].map(|i| base[i] + sigma[i] * gauss());
|
||||
}
|
||||
let mean = |im: &Rgb32f| {
|
||||
let n = im.data.len() as f64;
|
||||
[0, 1, 2].map(|i| im.data.iter().map(|p| p[i] as f64).sum::<f64>() / n)
|
||||
};
|
||||
let m0 = mean(&img);
|
||||
for nr in [25.0, 100.0] {
|
||||
let mut s = DevelopSettings::default();
|
||||
s.detail.nr_color = nr;
|
||||
let mut a = img.clone();
|
||||
denoise(&mut a, &s, 1.0, None);
|
||||
let m = mean(&a);
|
||||
let clipped0 = mean(&img.map(|p| p.map(|v| v.max(0.0))));
|
||||
let sd = |im: &Rgb32f, mm: [f64; 3]| {
|
||||
[0, 1, 2].map(|i| (im.data.iter().map(|p| (p[i] as f64 - mm[i]).powi(2)).sum::<f64>() / im.data.len() as f64).sqrt())
|
||||
};
|
||||
worst = worst.max([0, 1, 2].iter().map(|&i| (m[i] / m0[i] - 1.0).abs()).fold(0.0, f64::max));
|
||||
println!(
|
||||
"{name} NR {nr}: true mean {m0:.5?}, clipped noisy mean {clipped0:.5?}, after v2 {m:.5?} → {:+.3?} % vs true; noise sd {:.5?} → {:.5?}",
|
||||
[0, 1, 2].map(|i| 100.0 * (m[i] / m0[i] - 1.0)),
|
||||
sd(&img, m0),
|
||||
sd(&a, m)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("worst mean deviation {:.4} %", 100.0 * worst);
|
||||
assert!(worst < 0.0005, "the joint colour NR moved a channel's mean by {:.3} %", 100.0 * worst);
|
||||
}
|
||||
|
||||
/// PROBE (prints, never fails): what colour NR v2 keeps of real colour. A clean synthetic scene (an
|
||||
/// equal-luminance red/green edge, a 2 px red line on grey, a saturated blue patch near black, a flat grey
|
||||
/// patch) plus noise; each measure compares the output with the clean scene.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn probe_nrc_real_colour() {
|
||||
use lightcraft_develop::DevelopSettings;
|
||||
let (w, h) = (768usize, 512usize);
|
||||
let y_of = |c: [f32; 3]| luminance_2020(c);
|
||||
// two colours of the same luminance 0.03
|
||||
let red = [0.08f32, 0.0155, 0.02];
|
||||
let green = {
|
||||
let g = [0.012f32, 0.04, 0.015];
|
||||
let k = y_of(red) / y_of(g);
|
||||
g.map(|v| v * k)
|
||||
};
|
||||
let grey = [0.03f32; 3];
|
||||
let blue_dark = [0.001f32, 0.0015, 0.02];
|
||||
// a bright saturated green next to black (a lit leaf against a dark background)
|
||||
let leaf = [0.02f32, 0.12, 0.01];
|
||||
let clean = |x: usize, y: usize| -> [f32; 3] {
|
||||
if y < 256 {
|
||||
if x < 384 { red } else { green }
|
||||
} else if x < 384 {
|
||||
if (190..192).contains(&x) { red } else { grey }
|
||||
} else if x < 576 {
|
||||
blue_dark
|
||||
} else if y < 384 {
|
||||
grey
|
||||
} else if x < 672 {
|
||||
leaf
|
||||
} else {
|
||||
[0.0005f32; 3]
|
||||
}
|
||||
};
|
||||
let mut seed = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut gauss = || {
|
||||
(0..4)
|
||||
.map(|_| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5
|
||||
})
|
||||
.sum::<f32>()
|
||||
* 1.732
|
||||
};
|
||||
let mut img = Rgb32f::new(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let c = clean(x, y);
|
||||
// shot + read noise per channel
|
||||
img.data[y * w + x] = c.map(|v| v + (0.00002 + 0.004 * v.max(0.0)).sqrt() * 0.6 * gauss());
|
||||
}
|
||||
}
|
||||
let chroma = |c: [f32; 3]| {
|
||||
let y = y_of(c);
|
||||
c.map(|v| v - y)
|
||||
};
|
||||
let dist = |a: [f32; 3], b: [f32; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt();
|
||||
for nr in [25.0, 100.0] {
|
||||
let mut s = DevelopSettings::default();
|
||||
s.detail.nr_color = nr;
|
||||
let mut o = img.clone();
|
||||
denoise(&mut o, &s, 1.0, None);
|
||||
let px = |x: usize, y: usize| o.data[y * w + x];
|
||||
// edge: chroma error 1..8 px either side, relative to the step between the two colours
|
||||
let step = dist(chroma(red), chroma(green));
|
||||
let mut e = 0.0;
|
||||
let mut n = 0.0;
|
||||
for y in 40..216 {
|
||||
for d in 1..=8 {
|
||||
for x in [384 - d, 383 + d] {
|
||||
e += dist(chroma(px(x, y)), chroma(clean(x, y)));
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
// line: share of the line's chroma kept (mean over its rows)
|
||||
let (mut kept, mut m) = (0.0, 0.0);
|
||||
for y in 300..480 {
|
||||
for x in 190..192 {
|
||||
let c = chroma(px(x, y));
|
||||
let r = chroma(red);
|
||||
let rg = chroma(grey);
|
||||
let full = [0, 1, 2].map(|i| r[i] - rg[i]);
|
||||
let got = [0, 1, 2].map(|i| c[i] - rg[i]);
|
||||
kept += (got[0] * full[0] + got[1] * full[1] + got[2] * full[2]) / (full[0] * full[0] + full[1] * full[1] + full[2] * full[2]);
|
||||
m += 1.0;
|
||||
}
|
||||
}
|
||||
// saturated blue near black: chroma of the patch's mean kept
|
||||
let mut acc = [0.0f32; 3];
|
||||
let mut cnt = 0.0;
|
||||
for y in 300..480 {
|
||||
for x in 420..540 {
|
||||
acc = [0, 1, 2].map(|i| acc[i] + px(x, y)[i]);
|
||||
cnt += 1.0;
|
||||
}
|
||||
}
|
||||
let mean = acc.map(|v| v / cnt);
|
||||
let sat_kept = dist(chroma(mean), [0.0; 3]) / dist(chroma(blue_dark), [0.0; 3]);
|
||||
// grey: residual chroma noise
|
||||
let mut sd = 0.0;
|
||||
let mut k = 0.0;
|
||||
for y in 270..370 {
|
||||
for x in 600..760 {
|
||||
sd += dist(chroma(px(x, y)), [0.0; 3]).powi(2);
|
||||
k += 1.0;
|
||||
}
|
||||
}
|
||||
let mut sd0 = 0.0;
|
||||
for y in 270..370 {
|
||||
for x in 600..760 {
|
||||
sd0 += dist(chroma(img.data[y * w + x]), [0.0; 3]).powi(2);
|
||||
}
|
||||
}
|
||||
// leaf next to black: chroma kept in the leaf's 12 px next to the black (mean over rows)
|
||||
let (mut lk, mut ln) = (0.0f32, 0.0f32);
|
||||
for y in 400..500 {
|
||||
for x in 660..672 {
|
||||
let c = chroma(px(x, y));
|
||||
let r = chroma(leaf);
|
||||
lk += (c[0] * r[0] + c[1] * r[1] + c[2] * r[2]) / (r[0] * r[0] + r[1] * r[1] + r[2] * r[2]);
|
||||
ln += 1.0;
|
||||
}
|
||||
}
|
||||
println!("NR {nr}: leaf next to black keeps {:.0} % of its chroma (12 px next to the black)", 100.0 * lk / ln);
|
||||
println!(
|
||||
"NR {nr}: edge error {:.1} % of the step | red line kept {:.0} % | dark blue chroma kept {:.0} % | grey chroma noise {:.5} → {:.5}",
|
||||
100.0 * e / n / step,
|
||||
100.0 * kept / m,
|
||||
100.0 * sat_kept,
|
||||
(sd0 / k).sqrt(),
|
||||
(sd / k).sqrt()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nrc_noise_fit_is_non_negative() {
|
||||
// a falling cloud would give a negative slope: the constant fits instead
|
||||
let (a, b) = fit_nonneg_line(&[(0.0, 4.0, 1.0), (1.0, 3.0, 1.0), (2.0, 2.0, 1.0)]);
|
||||
assert!(a == 0.0 && (b - 3.0).abs() < 1e-9);
|
||||
// a line through a negative intercept: refitted through the origin
|
||||
let (a, b) = fit_nonneg_line(&[(1.0, 1.0, 1.0), (2.0, 3.0, 1.0), (3.0, 5.0, 1.0)]);
|
||||
assert!(a > 0.0 && b == 0.0);
|
||||
// an exact shot + read noise line is found as it is
|
||||
let (a, b) = fit_nonneg_line(&[(0.0, 2.0, 1.0), (1.0, 5.0, 1.0), (2.0, 8.0, 1.0)]);
|
||||
assert!((a - 3.0).abs() < 1e-9 && (b - 2.0).abs() < 1e-9);
|
||||
}
|
||||
use super::*;
|
||||
use lightcraft_color::cct::xy_to_uv;
|
||||
|
||||
@@ -1057,7 +1390,7 @@ mod nr_tests {
|
||||
let (v0, m0) = var(&img);
|
||||
let mut s = DevelopSettings::default();
|
||||
s.detail.nr_luminance = 80.0;
|
||||
denoise(&mut img, &s, 1.0);
|
||||
denoise(&mut img, &s, 1.0, None);
|
||||
let (v1, m1) = var(&img);
|
||||
assert!(v1 < v0 * 0.5, "{v0} -> {v1}");
|
||||
assert!((m1 - m0).abs() < 0.01);
|
||||
|
||||
@@ -161,7 +161,7 @@ pub fn evaluate_one(m: &Mask, frame: &Frame, w: usize, h: usize, img: &Rgb32f, l
|
||||
if comp.invert {
|
||||
c.data.iter_mut().for_each(|v| *v = 1.0 - *v);
|
||||
}
|
||||
if first && comp.op != MaskOp::Intersect {
|
||||
if first {
|
||||
alpha = c;
|
||||
first = false;
|
||||
continue;
|
||||
|
||||
@@ -629,3 +629,14 @@ fn people_and_subject_use_person_mattes() {
|
||||
let lips = MaskShape::People { person: 0, parts: vec!["Lips".into()] };
|
||||
assert_eq!(eval(&lips), shape_alpha(&lips, &f, w, h, &img, &l, 0.0, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intersect_first_component_selects_its_shape() {
|
||||
let f = frame(100, 100);
|
||||
let img = Rgb32f::new(100, 100);
|
||||
let l = Plane::new(100, 100);
|
||||
let shape = MaskShape::Radial { center: Point::new(0.5, 0.5), rx: 0.2, ry: 0.2, angle: 0.0, feather: 20.0, invert: false };
|
||||
let m = Mask { components: vec![MaskComponent { name: None, op: MaskOp::Intersect, invert: false, shape }], ..Default::default() };
|
||||
let a = evaluate_one(&m, &f, 100, 100, &img, &l, 0.0, None);
|
||||
assert!(a.get(50, 50) > 0.99 && a.get(5, 5) < 0.01, "intersect first: {} {}", a.get(50, 50), a.get(5, 5));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,352 @@
|
||||
//! TEST ONLY: the joint colour NR as of 8b89526d, kept as the reference the optimised `nrc_joint`
|
||||
//! must reproduce bit for bit. Changed since only where `nrc_joint` changed its result on purpose:
|
||||
//! the noise line's outlier bands fade out (`nrc_joint::robust_line`) and the pilot's axis choice
|
||||
//! fades in (`nrc_joint::pilot_pick`).
|
||||
//!
|
||||
//! Linear colour NR with a fixed, denoised joint guide. Strength controls the spatial scale;
|
||||
//! noise-normalized guide distances control which neighbours can exchange colour. Both chroma
|
||||
//! components use the same weights. Symmetric fluxes preserve the grid's channel sums, including
|
||||
//! at its boundaries; no nonnegative clamp or square-root bias correction is involved.
|
||||
|
||||
use lightcraft_color::luminance_2020;
|
||||
use lightcraft_raster::{Rgb32f, blur::gaussian, resample::Filter};
|
||||
|
||||
use crate::{
|
||||
for_rows,
|
||||
local::{NrcNoise, NrcParams},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct JointNoise {
|
||||
model: NrcNoise,
|
||||
/// Do not extrapolate beyond bands that contain usable noise measurements.
|
||||
ymax: [f32; 3],
|
||||
tolerance: f32,
|
||||
}
|
||||
|
||||
impl JointNoise {
|
||||
fn var(&self, i: usize, y: f32) -> f32 {
|
||||
self.model.var(i, y.min(self.ymax[i]))
|
||||
}
|
||||
}
|
||||
|
||||
fn yuv(c: [f32; 3]) -> [f32; 3] {
|
||||
let y = luminance_2020(c);
|
||||
[y, c[0] - y, c[2] - y]
|
||||
}
|
||||
|
||||
fn rgb(y: f32, uv: [f32; 3]) -> [f32; 3] {
|
||||
let r = y + uv[1];
|
||||
let b = y + uv[2];
|
||||
[r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b]
|
||||
}
|
||||
|
||||
/// Noise of Y, R-Y and B-Y measured from small high-pass residuals, not the colour variance
|
||||
/// of a wide smoothing window. The median-square calibration is for Gaussian residuals.
|
||||
/// Luminance bands with predominantly texture may only lower their weight in the fit: they
|
||||
/// cannot force a shadow scene's extrapolated highlight noise arbitrarily high.
|
||||
fn noise_model(img: &Rgb32f) -> JointNoise {
|
||||
const BANDS: usize = 16;
|
||||
let mut samples = Vec::new();
|
||||
let stride = img.len().div_ceil(crate::local::NRC_SAMPLES).max(1) | 1;
|
||||
if img.width < 3 || img.height < 3 {
|
||||
return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 };
|
||||
}
|
||||
for index in (0..img.len()).step_by(stride) {
|
||||
let (x, y) = (index % img.width, index / img.width);
|
||||
if x == 0 || y == 0 || x + 1 == img.width || y + 1 == img.height {
|
||||
continue;
|
||||
}
|
||||
let Some(c) = img.data.get(index) else { continue };
|
||||
let mut residual = [[0.0f32; 3]; 3];
|
||||
let mut brightness = 0.0;
|
||||
let mut valid = true;
|
||||
for (scale, delta) in [1usize, 2, 4].into_iter().enumerate() {
|
||||
// Tiny images use the nearest supported scale rather than extending an edge
|
||||
// into the noise samples.
|
||||
let delta = delta.min(x).min(y).min(img.width - x - 1).min(img.height - y - 1);
|
||||
let neighbours = [index - delta, index + delta, index - delta * img.width, index + delta * img.width];
|
||||
let mut m = [0.0f32; 3];
|
||||
for n in neighbours {
|
||||
if let Some(p) = img.data.get(n) {
|
||||
m = std::array::from_fn(|i| m[i] + 0.25 * p[i]);
|
||||
}
|
||||
}
|
||||
residual[scale] = std::array::from_fn(|i| (c[i] - m[i]).powi(2));
|
||||
brightness += m[0] / 3.0;
|
||||
valid &= c.iter().chain(m.iter()).all(|v| v.is_finite());
|
||||
}
|
||||
if valid {
|
||||
samples.push((brightness.max(0.0), residual));
|
||||
}
|
||||
}
|
||||
samples.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let per = samples.len().div_ceil(BANDS).max(32);
|
||||
let mut pts: [Vec<(f64, f64, f64)>; 3] = std::array::from_fn(|_| Vec::new());
|
||||
for band in samples.chunks(per).filter(|b| b.len() >= 32) {
|
||||
let y = band.iter().map(|p| p.0 as f64).sum::<f64>() / band.len() as f64;
|
||||
for (i, pts) in pts.iter_mut().enumerate() {
|
||||
let mut variance = 1e-14f64;
|
||||
for scale in 0..3 {
|
||||
let mut r: Vec<f32> = band.iter().map(|p| p.1[scale][i]).collect();
|
||||
let middle = r.len() / 2;
|
||||
let (_, median, _) = r.select_nth_unstable_by(middle, f32::total_cmp);
|
||||
// Each kernel has norm squared 1.25. Larger spacings recover noise
|
||||
// hidden by the positive spatial correlations of demosaiced RGB.
|
||||
variance = variance.max(*median as f64 / (0.454_936_4 * 1.25));
|
||||
}
|
||||
pts.push((y, variance, band.len() as f64));
|
||||
}
|
||||
}
|
||||
let mut model = NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] };
|
||||
let mut ymax = [0.0; 3];
|
||||
for (i, pts) in pts.iter().enumerate() {
|
||||
if pts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Seed from the darker half, then include all bands with a bounded influence for
|
||||
// unexpectedly high residuals (foliage etc.). Refit rather than clamp the intercept.
|
||||
let (a, b, top) = crate::nrc_joint::robust_line(pts);
|
||||
ymax[i] = top;
|
||||
model.alpha[i] = a as f32;
|
||||
model.beta[i] = (b as f32).max(1e-14);
|
||||
}
|
||||
JointNoise { model, ymax, tolerance: 1.0 }
|
||||
}
|
||||
|
||||
/// Squared distance beyond the expected noise in a difference of two guide samples. A small
|
||||
/// relative luminance allowance lets a smooth surface exchange colour without crossing a
|
||||
/// significant luminance or isoluminant colour boundary. The guide is fixed across all scales.
|
||||
fn distance(a: [f32; 3], b: [f32; 3], noise: &JointNoise) -> f32 {
|
||||
let y = 0.5 * (a[0] + b[0]);
|
||||
let allowance = (0.025 * y.max(0.0)).powi(2);
|
||||
(0..3)
|
||||
.map(|i| {
|
||||
let v = noise.var(i, y);
|
||||
// The 3x3 pilot blur reduces uncorrelated noise to 1/9. Keep a conservative
|
||||
// allowance for correlations left by demosaicing and grid resampling.
|
||||
((a[i] - b[i]).powi(2) - v).max(0.0) / (3.0 * noise.tolerance * v + allowance)
|
||||
})
|
||||
.sum::<f32>()
|
||||
}
|
||||
|
||||
/// Denoise the pilot along a clearly smoother axis at strong edges. An isotropic blur
|
||||
/// dilutes a two-pixel isoluminant line before the edge decision even sees it. Weak or
|
||||
/// ambiguous structure uses the isotropic pilot, so noise alone does not protect itself.
|
||||
fn pilot(original: &Rgb32f, noise: &JointNoise) -> Rgb32f {
|
||||
let mut guide = gaussian(original, 0.8);
|
||||
let (w, h) = (original.width, original.height);
|
||||
for_rows(&mut guide.data, w, |y, row| {
|
||||
for (x, out) in row.iter_mut().enumerate() {
|
||||
if x == 0 || y == 0 || x + 1 == w || y + 1 == h {
|
||||
continue;
|
||||
}
|
||||
let index = y * w + x;
|
||||
let Some(&p) = original.data.get(index) else { continue };
|
||||
let mut means = [[0.0f32; 3]; 2];
|
||||
let mut variances = [0.0; 2];
|
||||
for (axis, offset) in [1, w].into_iter().enumerate() {
|
||||
let (Some(&a), Some(&b)) = (original.data.get(index - offset), original.data.get(index + offset)) else { continue };
|
||||
means[axis] = std::array::from_fn(|i| (a[i] + p[i] + b[i]) / 3.0);
|
||||
variances[axis] = (0..3)
|
||||
.map(|i| {
|
||||
let m = means[axis][i];
|
||||
((a[i] - m).powi(2) + (p[i] - m).powi(2) + (b[i] - m).powi(2)) / (9.0 * noise.var(i, p[0]))
|
||||
})
|
||||
.sum::<f32>();
|
||||
}
|
||||
*out = crate::nrc_joint::pilot_pick(*out, means[0], variances[0], means[1], variances[1]);
|
||||
}
|
||||
});
|
||||
guide
|
||||
}
|
||||
|
||||
/// One conservative horizontal/vertical diffusion step. Pair weights are symmetric; the
|
||||
/// guide is never replaced by the filtered result. Long taps also account for the intervening
|
||||
/// guide edges, so a wide pass cannot jump over a thin differently coloured object.
|
||||
fn diffuse(src: &Rgb32f, dst: &mut Rgb32f, links: &Rgb32f, delta: usize, vertical: bool, rate: f32) {
|
||||
let (w, h) = (src.width, src.height);
|
||||
for_rows(&mut dst.data, w, |y, row| {
|
||||
for (x, out) in row.iter_mut().enumerate() {
|
||||
let index = y * w + x;
|
||||
let Some(&p) = src.data.get(index) else { continue };
|
||||
*out = p;
|
||||
let coordinate = if vertical { y } else { x };
|
||||
let length = if vertical { h } else { w };
|
||||
for neighbour in [coordinate.checked_sub(delta), coordinate.checked_add(delta).filter(|&v| v < length)].into_iter().flatten() {
|
||||
let ni = if vertical { neighbour * w + x } else { y * w + neighbour };
|
||||
let start = coordinate.min(neighbour);
|
||||
let pi = if vertical { start * w + x } else { y * w + start };
|
||||
let (Some(&q), Some(link)) = (src.data.get(ni), links.data.get(pi)) else { continue };
|
||||
let weight = rate * link[usize::from(vertical)];
|
||||
for i in 1..3 {
|
||||
out[i] += weight * (q[i] - p[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn denoise_grid(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32) {
|
||||
if img.is_empty() || strength <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let start = crate::profiling().then(std::time::Instant::now);
|
||||
// A maximum 2x grid keeps colour boundaries visible even at high strength. The old grid
|
||||
// grew to 16x with the radius, making the colour loss inseparable from slider strength.
|
||||
let step = if img.width.is_multiple_of(step) && img.height.is_multiple_of(step) { step } else { 1 };
|
||||
let (w, h) = (img.width.div_ceil(step), img.height.div_ceil(step));
|
||||
// Transform before resampling; negative linear differences are valid throughout.
|
||||
let mut original = Rgb32f::new(w, h);
|
||||
for_rows(&mut original.data, w, |y, row| {
|
||||
for (x, p) in row.iter_mut().enumerate() {
|
||||
let mut count = 0.0f32;
|
||||
for sy in y * step..((y + 1) * step).min(img.height) {
|
||||
for sx in x * step..((x + 1) * step).min(img.width) {
|
||||
if let Some(&c) = img.data.get(sy * img.width + sx) {
|
||||
let c = yuv(c);
|
||||
*p = std::array::from_fn(|i| p[i] + c[i]);
|
||||
count += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
*p = p.map(|v| v / count.max(1.0));
|
||||
}
|
||||
});
|
||||
let lap = |what: &str, t: &mut Option<std::time::Instant>| {
|
||||
if let Some(t0) = t {
|
||||
eprintln!(" joint {what}: {:.0} ms", t0.elapsed().as_secs_f64() * 1e3);
|
||||
*t = Some(std::time::Instant::now());
|
||||
}
|
||||
};
|
||||
let mut tt = start;
|
||||
lap("transform", &mut tt);
|
||||
let mut noise = noise_model(&original);
|
||||
lap("noise model", &mut tt);
|
||||
noise.tolerance = (1.5 - detail).clamp(0.5, 1.5);
|
||||
let guide = pilot(&original, &noise);
|
||||
lap("pilot", &mut tt);
|
||||
if std::env::var_os("NRV2_DEBUG").is_some() {
|
||||
eprintln!(" nr joint: {w}x{h}, Y/R-Y/B-Y alpha {:?} beta {:?}, supported Y {:?}", noise.model.alpha, noise.model.beta, noise.ymax);
|
||||
}
|
||||
let mut filtered = original.clone();
|
||||
let mut scratch = Rgb32f::new(w, h);
|
||||
let mut paths = Rgb32f::new(w, h);
|
||||
let mut links = Rgb32f::new(w, h);
|
||||
for_rows(&mut paths.data, w, |y, row| {
|
||||
for (x, out) in row.iter_mut().enumerate() {
|
||||
let index = y * w + x;
|
||||
let Some(&g) = guide.data.get(index) else { continue };
|
||||
if x + 1 < w
|
||||
&& let Some(&b) = guide.data.get(index + 1)
|
||||
{
|
||||
out[0] = distance(g, b, &noise);
|
||||
}
|
||||
if y + 1 < h
|
||||
&& let Some(&b) = guide.data.get(index + w)
|
||||
{
|
||||
out[1] = distance(g, b, &noise);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Scale is independent of the edge decision. K has no role in deciding whether a leaf
|
||||
// is noise. Two dyadic sweeps provide broad smoothing with a fixed number of scales.
|
||||
let sigma = params.passes.last().map_or(0.0, |p| p.sigma / step as f32);
|
||||
let mut remaining = sigma * sigma;
|
||||
let mut delta = 1usize;
|
||||
while remaining > 0.01 && delta <= w.max(h) {
|
||||
let rate = (remaining / (4.0 * (delta as f32).powi(2))).min(0.25);
|
||||
// Each symmetric pair weight is evaluated once per scale and reused by both
|
||||
// diffusion sweeps and both ends of the pair.
|
||||
for_rows(&mut links.data, w, |y, row| {
|
||||
for (x, out) in row.iter_mut().enumerate() {
|
||||
let index = y * w + x;
|
||||
let (Some(&g), Some(path)) = (guide.data.get(index), paths.data.get(index)) else { continue };
|
||||
*out = [0.0; 3];
|
||||
for (axis, offset, valid) in [(0, delta, x + delta < w), (1, delta * w, y + delta < h)] {
|
||||
if valid && let Some(&other) = guide.data.get(index + offset) {
|
||||
out[axis] = (-distance(g, other, &noise).max(path[axis])).exp();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
for _ in 0..2 {
|
||||
diffuse(&filtered, &mut scratch, &links, delta, false, rate);
|
||||
std::mem::swap(&mut filtered, &mut scratch);
|
||||
diffuse(&filtered, &mut scratch, &links, delta, true, rate);
|
||||
std::mem::swap(&mut filtered, &mut scratch);
|
||||
}
|
||||
remaining -= 4.0 * rate * (delta as f32).powi(2);
|
||||
// Maxima over paths of length 2*delta, using the two adjacent delta-length paths.
|
||||
// Reuse the diffusion scratch so a long tap costs O(1), irrespective of radius.
|
||||
for_rows(&mut scratch.data, w, |y, row| {
|
||||
for (x, out) in row.iter_mut().enumerate() {
|
||||
let index = y * w + x;
|
||||
let Some(&p) = paths.data.get(index) else { continue };
|
||||
*out = p;
|
||||
if x + delta < w
|
||||
&& let Some(q) = paths.data.get(index + delta)
|
||||
{
|
||||
out[0] = out[0].max(q[0]);
|
||||
}
|
||||
if y + delta < h
|
||||
&& let Some(q) = paths.data.get(index + delta * w)
|
||||
{
|
||||
out[1] = out[1].max(q[1]);
|
||||
}
|
||||
}
|
||||
});
|
||||
std::mem::swap(&mut paths, &mut scratch);
|
||||
lap(&format!("scale {delta}"), &mut tt);
|
||||
delta = delta.saturating_mul(2);
|
||||
}
|
||||
drop(scratch);
|
||||
drop(paths);
|
||||
drop(links);
|
||||
if step == 1 {
|
||||
for (p, q) in img.data.iter_mut().zip(&filtered.data) {
|
||||
let result = rgb(luminance_2020(*p), *q);
|
||||
*p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i]));
|
||||
}
|
||||
} else {
|
||||
// Reconstruct only rows. Keep the fine residual with a shared, noise-subtracted
|
||||
// Wiener share; a flat noisy patch receives no automatic protection from noisy Y.
|
||||
let mean = gaussian(&original, 1.0);
|
||||
let corr = gaussian(&original.map(|p| p.map(|v| v * v)), 1.0);
|
||||
let share = corr.zip_map(&mean, |c, m| {
|
||||
let snr = (1..3).map(|i| ((c[i] - m[i] * m[i]).max(0.0) / noise.var(i, m[0]) - 1.0).max(0.0)).sum::<f32>() * 0.5;
|
||||
[snr / (snr + 8.0); 3]
|
||||
});
|
||||
let share = gaussian(&share, 0.8);
|
||||
// Resize one output row at a time using the raster resampler's exact pixel centres.
|
||||
use lightcraft_raster::resample::weights;
|
||||
let ux = weights(w, img.width, Filter::Bilinear);
|
||||
let uy = weights(h, img.height, Filter::Bilinear);
|
||||
let ow = img.width;
|
||||
for_rows(&mut img.data, ow, |y, row| {
|
||||
let Some((y0, wy)) = uy.get(y) else { return };
|
||||
for (x, p) in row.iter_mut().enumerate() {
|
||||
let Some((x0, wx)) = ux.get(x) else { continue };
|
||||
let (mut f, mut o, mut a) = ([0.0; 3], [0.0; 3], 0.0);
|
||||
for (j, &dy) in wy.iter().enumerate() {
|
||||
for (i, &dx) in wx.iter().enumerate() {
|
||||
let index = (y0 + j) * w + x0 + i;
|
||||
if let (Some(q), Some(r), Some(s)) = (filtered.data.get(index), original.data.get(index), share.data.get(index)) {
|
||||
let weight = dx * dy;
|
||||
f = std::array::from_fn(|c| f[c] + weight * q[c]);
|
||||
o = std::array::from_fn(|c| o[c] + weight * r[c]);
|
||||
a += weight * s[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = yuv(*p);
|
||||
let q = std::array::from_fn(|i| f[i] + a * (c[i] - o[i]));
|
||||
let result = rgb(c[0], q);
|
||||
*p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i]));
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(start) = start {
|
||||
eprintln!(" nr joint: {:.1} ms", start.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
}
|
||||
@@ -364,6 +364,27 @@ impl DeepImage {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Crop to `[x0, x0+w) × [y0, y0+h)` (clamped to the image).
|
||||
pub fn crop(&self, x0: usize, y0: usize, w: usize, h: usize) -> Self {
|
||||
let x0 = x0.min(self.width);
|
||||
let y0 = y0.min(self.height);
|
||||
let w = w.min(self.width - x0);
|
||||
let h = h.min(self.height - y0);
|
||||
fn rows<T: Copy>(v: &[T], width: usize, x0: usize, y0: usize, w: usize, h: usize) -> Vec<T> {
|
||||
let mut out = Vec::with_capacity(3 * w * h);
|
||||
for y in y0..y0 + h {
|
||||
let at = 3 * (y * width + x0);
|
||||
out.extend_from_slice(v.get(at..at + 3 * w).unwrap_or_default());
|
||||
}
|
||||
out
|
||||
}
|
||||
let samples = match &self.samples {
|
||||
DeepSamples::U16(v) => DeepSamples::U16(rows(v, self.width, x0, y0, w, h)),
|
||||
DeepSamples::F32(v) => DeepSamples::F32(rows(v, self.width, x0, y0, w, h)),
|
||||
};
|
||||
Self { width: w, height: h, space: self.space, samples }
|
||||
}
|
||||
}
|
||||
|
||||
trait IntoRgba {
|
||||
|
||||
@@ -845,6 +845,48 @@ fn sliver_crops_render_quickly_with_wide_stages_on() {
|
||||
}
|
||||
}
|
||||
|
||||
// Given a cached render with one process, a change to a process with another colour filter (Update
|
||||
// to Current Process, undo) renders like a fresh render, not the cached denoised image
|
||||
#[test]
|
||||
fn a_process_change_does_not_reuse_the_other_colour_filter() {
|
||||
use crate::{StageCache, render_cached};
|
||||
use lightcraft_develop::Process;
|
||||
use std::sync::Arc;
|
||||
let src = Arc::new(colour_noise_scene(128, 96, 128));
|
||||
let info = SourceInfo::default();
|
||||
let req = RenderRequest::fit(128, 96);
|
||||
let cache = StageCache::default();
|
||||
let mut old = DevelopSettings::default();
|
||||
old.detail.nr_color = 25.0;
|
||||
old.detail.nr_color_smoothness = 0.0;
|
||||
old.process = Process::V2.version();
|
||||
let current = DevelopSettings { process: Process::LATEST.version(), ..old.clone() };
|
||||
let first = render_cached(&src, &info, &old, &req, &cache).image;
|
||||
let fresh = render(&src, &info, ¤t, &req).image;
|
||||
assert!(max_diff(&first, &fresh) > 0, "the two colour filters differ on this scene");
|
||||
assert_eq!(render_cached(&src, &info, ¤t, &req, &cache).image, fresh, "process update");
|
||||
assert_eq!(render_cached(&src, &info, &old, &req, &cache).image, first, "undo");
|
||||
}
|
||||
|
||||
/// Flat grey with chroma noise: `quiet` columns on the left with little noise, the rest with much.
|
||||
pub(crate) fn colour_noise_scene(w: usize, h: usize, quiet: usize) -> Rgb32f {
|
||||
let mut seed = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let mut noise = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
((seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5) * 2.0
|
||||
};
|
||||
let mut img = Rgb32f::new(w, h);
|
||||
for (i, p) in img.data.iter_mut().enumerate() {
|
||||
let sigma = if i % w < quiet { 0.001 } else { 0.015 };
|
||||
let y = 0.04f32;
|
||||
let (r, b) = (y + noise() * sigma, y + noise() * sigma);
|
||||
*p = [r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b];
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
/// A crop of no width used to give grain NaN coordinates (and NaN pixels); the render stays finite.
|
||||
#[test]
|
||||
fn zero_width_crop_with_grain_renders_finite_pixels() {
|
||||
|
||||
@@ -70,14 +70,14 @@ fn rms_chroma(a: &Rgb32f, b: &Rgb32f) -> f32 {
|
||||
fn preview_error(s: &DevelopSettings, scales: &[f32], metric: fn(&Rgb32f, &Rgb32f) -> f32) -> Vec<(f32, f32, f32)> {
|
||||
let src = noisy_scene(0.15);
|
||||
let mut full = src.clone();
|
||||
denoise(&mut full, s, 1.0);
|
||||
denoise(&mut full, s, 1.0, None);
|
||||
scales
|
||||
.iter()
|
||||
.map(|&k| {
|
||||
let reference = scaled(&full, k);
|
||||
let plain = scaled(&src, k);
|
||||
let mut preview = plain.clone();
|
||||
denoise(&mut preview, s, k);
|
||||
denoise(&mut preview, s, k, None);
|
||||
(k, metric(&preview, &reference), metric(&plain, &reference))
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -422,6 +422,46 @@ fn auto_mask_strokes_match_the_whole_render() {
|
||||
check_noisy("auto mask", &s, PixelWindow { x: 400, y: 300, w: 300, h: 250 }, 2, 0.1);
|
||||
}
|
||||
|
||||
// Given the joint colour NR, a window is filtered with the whole frame's noise model: a quiet part of
|
||||
// the frame does not make a window of its noisy part (or the other way round) smooth differently
|
||||
#[test]
|
||||
fn joint_colour_nr_measures_the_noise_of_the_whole_frame() {
|
||||
let mut s = DevelopSettings::default();
|
||||
s.detail.nr_color = 25.0;
|
||||
s.detail.nr_color_smoothness = 0.0;
|
||||
// a frame that is one noise tile, and one of many tiles (`nrc_joint::tiles`)
|
||||
for (w, h, win) in [(768, 128, PixelWindow { x: 640, y: 32, w: 64, h: 64 }), (1664, 1536, PixelWindow { x: 1400, y: 700, w: 128, h: 128 })] {
|
||||
let src = crate::tests::colour_noise_scene(w, h, w * 2 / 3);
|
||||
let req = RenderRequest::fit(w, h);
|
||||
let f = render(&src, &SourceInfo::default(), &s, &req).image;
|
||||
let part = render(&src, &SourceInfo::default(), &s, &RenderRequest { window: Some(win), ..req }).image;
|
||||
let (max, mean) = compare_inset(&f, &part, win, win.w / 4);
|
||||
assert!(max <= 2 && mean <= 0.1, "{w}×{h}: max {max}, mean {mean:.3}");
|
||||
}
|
||||
}
|
||||
|
||||
// Given a 16-bit or float render of a window with the joint colour NR, then its edges are the whole
|
||||
// render's too: the window is grown by the filter's reach and cut back
|
||||
#[test]
|
||||
fn a_deep_window_with_colour_noise_reduction_matches_the_whole_render() {
|
||||
use crate::OutputDepth;
|
||||
let (w, h, win) = (768, 128, PixelWindow { x: 600, y: 32, w: 96, h: 64 });
|
||||
let src = crate::tests::colour_noise_scene(w, h, w * 2 / 3);
|
||||
let mut s = DevelopSettings::default();
|
||||
s.detail.nr_color = 25.0;
|
||||
s.detail.nr_color_smoothness = 0.0;
|
||||
for depth in [OutputDepth::U16, OutputDepth::F32Linear] {
|
||||
let req = RenderRequest { depth, ..RenderRequest::fit(w, h) };
|
||||
let deep = |req: &RenderRequest| render(&src, &SourceInfo::default(), &s, req).deep.map(|d| d.to_rgba8());
|
||||
let (Some(f), Some(part)) = (deep(&req), deep(&RenderRequest { window: Some(win), ..req })) else {
|
||||
panic!("{depth:?}: no deep image");
|
||||
};
|
||||
assert_eq!((part.width, part.height), (win.w, win.h), "{depth:?}: the window's own size");
|
||||
let (max, mean) = compare_inset(&f, &part, win, 0);
|
||||
assert!(max <= 1 && mean <= 0.01, "{depth:?}: max {max}, mean {mean:.3}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The margin the loupe's windows carry around what they show at this size (`region::margin_for`:
|
||||
/// 4.5 % of the long edge).
|
||||
const OVERLAY_INSET: usize = W * 45 / 1000;
|
||||
|
||||
@@ -57,8 +57,16 @@ pub enum Overlay {
|
||||
SharpenDetail,
|
||||
/// The sharpening mask, white where sharpening applies (Alt-drag on Sharpening Masking).
|
||||
SharpenMask,
|
||||
/// Clipping warnings (J): the photo with every pixel that has a channel at 255 painted
|
||||
/// [`CLIP_HIGH`] and every other pixel with a channel at 0 painted [`CLIP_LOW`].
|
||||
ClipWarnings,
|
||||
}
|
||||
|
||||
/// [`Overlay::ClipWarnings`] colour of clipped highlights.
|
||||
pub const CLIP_HIGH: [u8; 3] = [255, 0, 0];
|
||||
/// [`Overlay::ClipWarnings`] colour of clipped shadows.
|
||||
pub const CLIP_LOW: [u8; 3] = [0, 0, 255];
|
||||
|
||||
/// [`Overlay::HdrRange`] colours (sRGB) for 0–1, 1–2, 2–3 and ≥ 3 stops above SDR white.
|
||||
pub const HDR_BANDS: [[u8; 3]; 4] = [[255, 214, 92], [255, 150, 40], [235, 64, 52], [214, 60, 210]];
|
||||
|
||||
@@ -148,6 +156,7 @@ impl Overlay {
|
||||
Overlay::Grayscale => (8, 0.0),
|
||||
Overlay::SharpenDetail => (9, 0.0),
|
||||
Overlay::SharpenMask => (10, 0.0),
|
||||
Overlay::ClipWarnings => (11, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +180,7 @@ impl Overlay {
|
||||
8 => Overlay::Grayscale,
|
||||
9 => Overlay::SharpenDetail,
|
||||
10 => Overlay::SharpenMask,
|
||||
11 => Overlay::ClipWarnings,
|
||||
_ => Overlay::None,
|
||||
}
|
||||
}
|
||||
@@ -189,6 +199,7 @@ impl Overlay {
|
||||
Overlay::Grayscale => 0x5002,
|
||||
Overlay::SharpenDetail => 0x5003,
|
||||
Overlay::SharpenMask => 0x5004,
|
||||
Overlay::ClipWarnings => 0x5005,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,7 +219,7 @@ impl Overlay {
|
||||
/// The clipping previews, which test the sRGB values the histogram counts (a render for a
|
||||
/// display profile draws them in sRGB, then converts).
|
||||
pub fn is_clipping(self) -> bool {
|
||||
matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights)
|
||||
matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::ClipWarnings)
|
||||
}
|
||||
|
||||
/// Whether the overlay draws from the render's detail planes ([`sharpen_plane`]).
|
||||
@@ -219,7 +230,10 @@ impl Overlay {
|
||||
/// Whether the overlay works pixel by pixel on the finished image, so a window render shows
|
||||
/// the same as the whole frame would.
|
||||
pub fn per_pixel(self) -> bool {
|
||||
matches!(self, Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::Grayscale)
|
||||
matches!(
|
||||
self,
|
||||
Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::ClipWarnings | Overlay::Grayscale
|
||||
)
|
||||
}
|
||||
|
||||
/// The mask an [`Overlay::Mask`] shows (if it exists in `s` and has components).
|
||||
@@ -310,6 +324,7 @@ pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, plane: Option<&Plane>
|
||||
}
|
||||
Overlay::ClipShadows => clipping(img, false),
|
||||
Overlay::ClipHighlights => clipping(img, true),
|
||||
Overlay::ClipWarnings => clip_warnings(img),
|
||||
Overlay::Grayscale => grayscale(img),
|
||||
Overlay::SharpenDetail | Overlay::SharpenMask => {
|
||||
if let Some(p) = plane.filter(|a| (a.width, a.height) == (img.width, img.height)) {
|
||||
@@ -362,6 +377,25 @@ pub fn clipping(img: &mut Rgba8, high: bool) {
|
||||
});
|
||||
}
|
||||
|
||||
/// [`Overlay::ClipWarnings`]: pixels with a channel at 255 in [`CLIP_HIGH`], the rest with a
|
||||
/// channel at 0 in [`CLIP_LOW`], everything else unchanged.
|
||||
pub fn clip_warnings(img: &mut Rgba8) {
|
||||
let w = img.width;
|
||||
for_rows(&mut img.data, w, |_, row| {
|
||||
for px in row.iter_mut() {
|
||||
let c = &px[..3];
|
||||
let paint = if c.contains(&255) {
|
||||
CLIP_HIGH
|
||||
} else if c.contains(&0) {
|
||||
CLIP_LOW
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
*px = [paint[0], paint[1], paint[2], 255];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn grayscale(img: &mut Rgba8) {
|
||||
let w = img.width;
|
||||
for_rows(&mut img.data, w, |_, row| {
|
||||
@@ -713,7 +747,8 @@ mod tests {
|
||||
assert!(Overlay::for_control(c).is_some(), "{c}");
|
||||
}
|
||||
assert!(Overlay::ClipShadows.is_clipping() && Overlay::ClipHighlights.is_clipping() && !Overlay::Grayscale.is_clipping());
|
||||
let all = [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask];
|
||||
let all =
|
||||
[Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask, Overlay::ClipWarnings];
|
||||
for o in all {
|
||||
let (k, v) = o.to_parts();
|
||||
assert_eq!(Overlay::from_parts(k, v), o);
|
||||
@@ -721,6 +756,16 @@ mod tests {
|
||||
assert_ne!(o.key(), Overlay::HdrRange.key());
|
||||
}
|
||||
assert!(Overlay::ClipShadows.per_pixel() && !Overlay::SharpenDetail.per_pixel());
|
||||
assert!(Overlay::ClipWarnings.is_clipping() && Overlay::ClipWarnings.per_pixel());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_warnings_paint_clipped_pixels_only() {
|
||||
let data = vec![[255, 255, 255, 255], [0, 0, 0, 255], [128, 128, 128, 255], [255, 40, 0, 255], [10, 0, 30, 255]];
|
||||
let mut img = Rgba8 { width: 5, height: 1, data };
|
||||
super::clip_warnings(&mut img);
|
||||
let rgb: Vec<[u8; 3]> = img.data.iter().map(|p| [p[0], p[1], p[2]]).collect();
|
||||
assert_eq!(rgb, [super::CLIP_HIGH, super::CLIP_LOW, [128, 128, 128], super::CLIP_HIGH, super::CLIP_LOW]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -82,7 +82,9 @@ pub fn covers(make: Option<&str>, model: &str) -> bool {
|
||||
.map_or(model, |(_, rest)| rest.trim_start())
|
||||
};
|
||||
let listed = MODELS.iter().any(|(b, m)| brand.is_none_or(|x| x.eq_ignore_ascii_case(b)) && bare_of(b).eq_ignore_ascii_case(m));
|
||||
let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM")) && FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m));
|
||||
// A DxO demosaiced DNG keeps the Fujifilm model but carries DxO as its make.
|
||||
let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM") || b.eq_ignore_ascii_case("DxO"))
|
||||
&& FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m));
|
||||
listed || fuji
|
||||
}
|
||||
|
||||
@@ -408,6 +410,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxo_dng_fujifilm_model_is_covered_for_kelvin() {
|
||||
// A DxO demosaiced DNG carries DxO as its make, not FUJIFILM, but it is still a Fujifilm model.
|
||||
assert!(covers(Some("DxO"), "X-T2"));
|
||||
assert!(covers(Some("DxO"), "FUJIFILM X-T2"));
|
||||
assert!(covers_camera("DxO X-T2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn covered_models() {
|
||||
assert!(covers_camera("NIKON CORPORATION NIKON Z5_2") && covers_camera("NIKON Z5_2") && !covers_camera("NIKON CORPORATION NIKON Z6"));
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
//! Canon CR2 / CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW) / CRW (the CIFF bodies of 2000–2004; clean-room-derived
|
||||
//! compression, `vendor::crw`; the PowerShot G5's anomalous coding is refused), Nikon NEF/NRW (uncompressed, Huffman lossless / lossy compressed), Sony ARW (uncompressed, ARW2, lossless), Fujifilm RAF (uncompressed Bayer
|
||||
//! and X-Trans, lossless and lossy compressed), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format: compressed 4 and 6, the prefix-coded strips of 8,
|
||||
//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500; compressed: 12-bit entropy-coded sensor differences across interchangeable-lens and modern compact bodies).
|
||||
//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources
|
||||
//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words,
|
||||
//! two-field 12-bit samples and 12-bit 16-byte blocks of the E-300/E-330/E-500).
|
||||
//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (compressed Olympus ORF, CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources
|
||||
//! (public specifications, tag-name documentation, black-box analysis of CC0 samples) and gaps. Non-DNG files carry no
|
||||
//! colour matrix: [`spectral`] has matrices fitted to measured spectral sensitivities for 52 models, and
|
||||
//! otherwise [`color`] falls back to a documented neutral model. The decoders never panic on malformed input.
|
||||
|
||||
@@ -21,7 +21,6 @@ pub mod nef;
|
||||
mod nef_lens;
|
||||
pub mod nefc;
|
||||
pub mod orf;
|
||||
pub(crate) mod orfc;
|
||||
pub mod pef;
|
||||
pub mod raf;
|
||||
mod raf_lens;
|
||||
|
||||
Vendored
+18
-18
@@ -1,4 +1,4 @@
|
||||
//! Olympus ORF — uncompressed and compressed variants.
|
||||
//! Olympus ORF — uncompressed variants; compressed sensor data is unsupported.
|
||||
//!
|
||||
//! Sources: TIFF 6.0 (the `IIRO`/`MMOR` container is a TIFF with a different magic number), Exif 2.3 (`CFAPattern`,
|
||||
//! tag `0xa302`), the ExifTool Olympus tag-name documentation (maker-note sub-directories `0x2020` CameraSettings —
|
||||
@@ -28,9 +28,8 @@
|
||||
//! (last), the bit order and the pixel order were fixed by measurement on the CC0 files 2878 (E-300), 3540 (E-500)
|
||||
//! and 3624 (E-330), as was the sensor-origin RGGB anchoring (the maker-note crop offsets are odd). The E-M5 Mark II
|
||||
//! and PEN-F files were only checked for smoothness, not for CFA anchoring or black level.
|
||||
//! - Olympus's compressed ORF (interchangeable-lens bodies and compacts using the 12/14-bit entropy coding stream):
|
||||
//! decoded clean-room in `orfc.rs` from Olympus patents US7333035B2 and US7715639B2 (Takashi Ishikawa) and black-box
|
||||
//! CC0 samples (OM-D E-M1, E-M10 Mark III). No GPL/LibRaw code was consulted. See `docs/orf-compression.md`.
|
||||
//! - Compressed ORF sensor data is unsupported. The previous decoder was removed pending provenance
|
||||
//! resolution; embedded previews remain available. See `docs/orf-compression.md`.
|
||||
//! - The colour-filter layout is the file's Exif `CFAPattern`: GRBG on the E-1 and E-400, RGGB on the XZ-2, where
|
||||
//! the colours of the decoded mosaic follow the embedded JPEG best with exactly that layout
|
||||
//! (`corpus_orf_cfa_patterns`). The samples' active areas start at even offsets, so they can't tell whether the
|
||||
@@ -200,7 +199,7 @@ fn field_rows(strips: &[(u64, u64)], w: usize, h: usize, file_len: usize) -> Opt
|
||||
Some(rows)
|
||||
}
|
||||
|
||||
/// Decode an Olympus ORF container into a mosaic raw image, supporting uncompressed 16-bit, packed 12-bit, and compressed formats.
|
||||
/// Decode the supported uncompressed Olympus ORF layouts into a mosaic raw image.
|
||||
pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
let tiff = Tiff::parse(bytes)?;
|
||||
let ifd0 = &tiff.ifds[0];
|
||||
@@ -232,20 +231,10 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
Vec::new()
|
||||
};
|
||||
(RawData::U16(d), 12, false)
|
||||
} else if let Some((params, stream)) = (|| {
|
||||
let params = super::orfc::CompressionParameters::from_ifd(ip.as_ref()?, mn.as_ref())?;
|
||||
let chunk = chunks.first()?;
|
||||
let src = chunk_bytes(bytes, chunk)?;
|
||||
if !super::orfc::validate_stream_header(src, params.header_prefix_len) {
|
||||
return None;
|
||||
}
|
||||
let stream = src.get(params.header_prefix_len.saturating_add(2)..)?;
|
||||
Some((params, stream))
|
||||
})() {
|
||||
let d = if mode == Mode::Full || stated.is_none() { super::orfc::decompress_stream(stream, w, h, ¶ms)? } else { Vec::new() };
|
||||
(RawData::U16(d), params.valid_bits, false)
|
||||
} else if total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 {
|
||||
} else if info.bits() == 12 && total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 {
|
||||
let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?;
|
||||
// Only the declared 12-bit layout is supported here. A compressed stream in a 16-bit
|
||||
// ORF container must not fall through to packed decoding just because its length fits.
|
||||
// the strip as it is in the file (clipped at its end), not as its tag states it: one too short
|
||||
// for the samples is a truncated file, refused before they are allocated
|
||||
if (src.len() as u64).saturating_mul(8) < (n as u64).saturating_mul(12) {
|
||||
@@ -413,6 +402,17 @@ mod tests {
|
||||
b
|
||||
}
|
||||
|
||||
/// A 16-bit container with a short sensor stream is not the supported 12-bit packed layout.
|
||||
/// Both entry points must report unsupported rather than returning fabricated sensor pixels.
|
||||
#[test]
|
||||
fn compressed_sensor_data_is_unsupported_in_probe_and_decode() {
|
||||
for strip_len in [8, 24, 25] {
|
||||
let bytes = orf_with(4, 4, 16, vec![0; strip_len], Some(&[2, 0, 2, 0, 0, 1, 1, 2]));
|
||||
assert!(matches!(crate::decode(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"));
|
||||
assert!(matches!(crate::probe_info(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow.
|
||||
#[test]
|
||||
fn strip_byte_counts_past_u64_max_do_not_overflow() {
|
||||
|
||||
Vendored
-489
@@ -1,489 +0,0 @@
|
||||
//! Olympus compressed ORF entropy and predictive decoding.
|
||||
//!
|
||||
//! Clean-room implementation derived strictly from patent specifications and black-box CC0 samples:
|
||||
//! - Olympus Patent US7333035B2 (Takashi Ishikawa): directional edge-directed prediction across Bayer channels
|
||||
//! and run-length adaptive Golomb-Rice entropy coding with quotient escape codes.
|
||||
//! - Olympus Patent US7715639B2 (Takashi Ishikawa): direct low-order bitfield splitting and residual difference
|
||||
//! correction filters.
|
||||
//! - ImageProcessing maker-note directory (`0x2040`) parameters (`0x0640`–`0x0653`) and valid sensor bit depth (`0x102c`).
|
||||
//! - Verification against CC0 sample files from raw.pixls.us (OM-D E-M1, OM-D E-M10 Mark III).
|
||||
//!
|
||||
//! No LibRaw, dcraw, darktable, RawTherapee, or other GPL/LGPL/AGPL code was consulted or used.
|
||||
//! See `docs/orf-compression.md` for format specification and verification records.
|
||||
|
||||
use crate::{RawError, Result};
|
||||
use lightcraft_tiff::Ifd;
|
||||
use lightcraft_tiff::makernote::MakerNote;
|
||||
|
||||
/// Valid bits tag in Olympus MakerNote.
|
||||
const MN_VALID_BITS: u16 = 0x102c;
|
||||
|
||||
/// Bitstream reader for big-endian, MSB-first compressed ORF bitstreams.
|
||||
struct BitStream<'a> {
|
||||
data: &'a [u8],
|
||||
cursor: usize,
|
||||
buffer: u32,
|
||||
bits_available: u32,
|
||||
bits_loaded: u64,
|
||||
}
|
||||
|
||||
impl<'a> BitStream<'a> {
|
||||
/// Create a new bitstream reader over the supplied byte slice.
|
||||
fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, cursor: 0, buffer: 0, bits_available: 0, bits_loaded: 0 }
|
||||
}
|
||||
|
||||
/// Refill the bit buffer with a 32-bit big-endian word.
|
||||
fn refill_word(&mut self) {
|
||||
self.bits_loaded = self.bits_loaded.saturating_add(32);
|
||||
if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(4)) {
|
||||
self.buffer = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
|
||||
self.cursor = self.cursor.saturating_add(4);
|
||||
self.bits_available = 32;
|
||||
} else {
|
||||
let mut chunk = [0u8; 4];
|
||||
let remaining = self.data.len().saturating_sub(self.cursor);
|
||||
if remaining > 0 {
|
||||
if let Some(src) = self.data.get(self.cursor..self.cursor.saturating_add(remaining)) {
|
||||
chunk[..remaining].copy_from_slice(src);
|
||||
}
|
||||
self.cursor = self.data.len();
|
||||
}
|
||||
self.buffer = u32::from_be_bytes(chunk);
|
||||
self.bits_available = 32;
|
||||
}
|
||||
}
|
||||
|
||||
/// Append up to 16 bits to the lower part of the active bit buffer.
|
||||
fn refill_halfword(&mut self) {
|
||||
self.bits_loaded = self.bits_loaded.saturating_add(16);
|
||||
let next = if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(2)) {
|
||||
self.cursor = self.cursor.saturating_add(2);
|
||||
u16::from_be_bytes([chunk[0], chunk[1]])
|
||||
} else if let Some(&single) = self.data.get(self.cursor) {
|
||||
self.cursor = self.cursor.saturating_add(1);
|
||||
(single as u16) << 8
|
||||
} else {
|
||||
0
|
||||
};
|
||||
self.buffer = (self.buffer << 16) | u32::from(next);
|
||||
self.bits_available = self.bits_available.saturating_add(16);
|
||||
}
|
||||
|
||||
/// Read up to 16 bits from the bitstream.
|
||||
fn read_bits(&mut self, width: u32) -> u32 {
|
||||
if width == 0 {
|
||||
return 0;
|
||||
}
|
||||
while self.bits_available < width {
|
||||
self.refill_halfword();
|
||||
}
|
||||
let shift = self.bits_available & 0x1f;
|
||||
let value = (self.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - width);
|
||||
self.bits_available = self.bits_available.saturating_sub(width);
|
||||
value
|
||||
}
|
||||
|
||||
/// Advance by one bit, refilling the 32-bit buffer if necessary.
|
||||
fn advance_single_bit(&mut self, state: &mut u32) {
|
||||
if *state == 0 {
|
||||
self.refill_word();
|
||||
self.bits_available = self.bits_available.saturating_sub(1);
|
||||
*state = self.bits_available;
|
||||
} else {
|
||||
*state = state.saturating_sub(1);
|
||||
self.bits_available = *state;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters extracted from ImageProcessing SubIFD (`0x2040`) controlling compressed ORF decoding.
|
||||
pub(crate) struct CompressionParameters {
|
||||
/// Low-order direct bits extracted without prediction (tag `0x0640`).
|
||||
pub(crate) direct_bits_low0: u32,
|
||||
/// Gradient difference exponent threshold for edge classification (tag `0x0641`).
|
||||
pub(crate) gradient_thresh_exp_641: u32,
|
||||
/// Default spatial predictor boundary value (tag `0x0642`).
|
||||
pub(crate) boundary_predictor_642: i32,
|
||||
/// Direct residual sub-bits width (tag `0x0643`).
|
||||
pub(crate) direct_bits_sub3: u32,
|
||||
/// Vertical feedback shift exponent (tag `0x0644`).
|
||||
pub(crate) feedback_shift_644: u32,
|
||||
/// Flatness threshold exponent (tag `0x0645`).
|
||||
pub(crate) flatness_thresh_exp_645: u32,
|
||||
/// Flatness run threshold (tag `0x0646`).
|
||||
pub(crate) run_thresh_646: i32,
|
||||
/// Adaptive Rice parameter table offset A (tag `0x0647`).
|
||||
pub(crate) table_647: i32,
|
||||
/// Adaptive Rice parameter table limit A (tag `0x0648`).
|
||||
pub(crate) table_648: i32,
|
||||
/// Adaptive Rice parameter table offset B (tag `0x0649`).
|
||||
pub(crate) table_649: i32,
|
||||
/// Adaptive Rice parameter table limit B (tag `0x0650`).
|
||||
pub(crate) table_650: i32,
|
||||
/// Maximum Rice parameter allowed (tag `0x0651`).
|
||||
pub(crate) max_rice_k: i32,
|
||||
/// Maximum unary quotient run length before escape coding (tag `0x0652`).
|
||||
pub(crate) max_unary_run: u32,
|
||||
/// Prefix length of the compressed stream header in bytes (tag `0x0653`).
|
||||
pub(crate) header_prefix_len: usize,
|
||||
/// Valid sensor bit depth from MakerNote `0x102c`.
|
||||
pub(crate) valid_bits: u32,
|
||||
}
|
||||
|
||||
impl CompressionParameters {
|
||||
/// Parse and validate compression parameters from the ImageProcessing IFD and MakerNote.
|
||||
pub(crate) fn from_ifd(ip: &Ifd, mn: Option<&MakerNote>) -> Option<Self> {
|
||||
let header_prefix_len = usize::try_from(ip.u64(0x0653)?).ok()?;
|
||||
if header_prefix_len == 0 || header_prefix_len > 8 {
|
||||
return None;
|
||||
}
|
||||
if ip.u64(0x0640).is_some_and(|v| v > 16) || ip.u64(0x0643).is_some_and(|v| v > 16) {
|
||||
return None;
|
||||
}
|
||||
if ip.u64(0x0644).is_some_and(|v| v == 0 || v > 15) {
|
||||
return None;
|
||||
}
|
||||
let direct_bits_low0 = ip.u64(0x0640).and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let gradient_thresh_exp_641 = ip.u64(0x0641).and_then(|v| u32::try_from(v).ok()).unwrap_or(5);
|
||||
let boundary_predictor_642 = ip.i64(0x0642).and_then(|v| i32::try_from(v).ok()).filter(|&v| (-65536..=65536).contains(&v)).unwrap_or(0);
|
||||
let direct_bits_sub3 = ip.u64(0x0643).and_then(|v| u32::try_from(v).ok()).unwrap_or(2);
|
||||
let feedback_shift_644 = ip.u64(0x0644).and_then(|v| u32::try_from(v).ok()).unwrap_or(5);
|
||||
let flatness_thresh_exp_645 = ip.u64(0x0645).and_then(|v| u32::try_from(v).ok()).unwrap_or(4);
|
||||
let run_thresh_646 = ip.u64(0x0646).and_then(|v| i32::try_from(v).ok()).unwrap_or(3);
|
||||
let table_647 = ip.u64(0x0647).and_then(|v| i32::try_from(v).ok()).unwrap_or(2);
|
||||
let table_648 = ip.u64(0x0648).and_then(|v| i32::try_from(v).ok()).unwrap_or(3);
|
||||
let table_649 = ip.u64(0x0649).and_then(|v| i32::try_from(v).ok()).unwrap_or(4);
|
||||
let table_650 = ip.u64(0x0650).and_then(|v| i32::try_from(v).ok()).unwrap_or(7);
|
||||
let max_rice_k = ip.u64(0x0651).and_then(|v| i32::try_from(v).ok()).unwrap_or(15);
|
||||
let max_unary_run = ip.u64(0x0652).and_then(|v| u32::try_from(v).ok()).unwrap_or(12).clamp(1, 32);
|
||||
let valid_bits = mn.and_then(|m| m.ifd.u64(MN_VALID_BITS)).and_then(|v| u32::try_from(v).ok()).filter(|b| (8..=16).contains(b)).unwrap_or(12);
|
||||
|
||||
Some(Self {
|
||||
direct_bits_low0,
|
||||
gradient_thresh_exp_641,
|
||||
boundary_predictor_642,
|
||||
direct_bits_sub3,
|
||||
feedback_shift_644,
|
||||
flatness_thresh_exp_645,
|
||||
run_thresh_646,
|
||||
table_647,
|
||||
table_648,
|
||||
table_649,
|
||||
table_650,
|
||||
max_rice_k,
|
||||
max_unary_run,
|
||||
header_prefix_len,
|
||||
valid_bits,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the stream header prefix: $N$ big-endian bytes equal to 1, followed by two zero bytes.
|
||||
pub(crate) fn validate_stream_header(src: &[u8], prefix_bytes: usize) -> bool {
|
||||
if prefix_bytes == 0 || prefix_bytes > 8 || src.len() < prefix_bytes.saturating_add(2) {
|
||||
return false;
|
||||
}
|
||||
let mut prefix_int = 0u64;
|
||||
for &b in src.get(..prefix_bytes).unwrap_or(&[]) {
|
||||
prefix_int = (prefix_int << 8) | u64::from(b);
|
||||
}
|
||||
if prefix_int != 1 {
|
||||
return false;
|
||||
}
|
||||
let Some(delimiter) = src.get(prefix_bytes..prefix_bytes.saturating_add(2)) else {
|
||||
return false;
|
||||
};
|
||||
delimiter == [0x00, 0x00]
|
||||
}
|
||||
|
||||
/// Decoded entropy-coded symbol components for one photosite.
|
||||
struct DecodedSymbol {
|
||||
signed_residual: i32,
|
||||
raw_magnitude: u32,
|
||||
direct_bits_low0: u32,
|
||||
direct_bits_sub3: u32,
|
||||
}
|
||||
|
||||
/// Decode the next Golomb-Rice entropy residual symbol according to the patent specification.
|
||||
fn decode_entropy_symbol(reader: &mut BitStream<'_>, rice_k: u32, params: &CompressionParameters) -> DecodedSymbol {
|
||||
if reader.bits_available == 0 {
|
||||
reader.refill_word();
|
||||
}
|
||||
reader.bits_available = reader.bits_available.saturating_sub(1);
|
||||
let sign_bit = (reader.buffer >> (reader.bits_available & 0x1f)) & 1;
|
||||
|
||||
let direct_bits_sub3 = if params.direct_bits_sub3 > 0 { reader.read_bits(params.direct_bits_sub3) } else { 0 };
|
||||
let direct_bits_low0 = if params.direct_bits_low0 > 0 { reader.read_bits(params.direct_bits_low0) } else { 0 };
|
||||
|
||||
let mut state = reader.bits_available;
|
||||
let mut quotient = 0u32;
|
||||
|
||||
loop {
|
||||
reader.advance_single_bit(&mut state);
|
||||
if ((reader.buffer >> (state & 0x1f)) & 1) != 0 {
|
||||
break;
|
||||
}
|
||||
quotient = quotient.saturating_add(1);
|
||||
if quotient == params.max_unary_run {
|
||||
quotient = 0;
|
||||
if rice_k != 15 {
|
||||
let bits_needed = 15u32.saturating_sub(rice_k);
|
||||
while state < bits_needed {
|
||||
reader.refill_halfword();
|
||||
state = reader.bits_available;
|
||||
}
|
||||
let shift = state & 0x1f;
|
||||
quotient = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (rice_k + 17);
|
||||
state = state.saturating_sub(bits_needed);
|
||||
reader.bits_available = state;
|
||||
}
|
||||
reader.advance_single_bit(&mut state);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let remainder = if rice_k == 0 {
|
||||
0
|
||||
} else {
|
||||
while state < rice_k {
|
||||
reader.refill_halfword();
|
||||
state = reader.bits_available;
|
||||
}
|
||||
let shift = state & 0x1f;
|
||||
let rem = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - (rice_k & 0x1f));
|
||||
reader.bits_available = state.saturating_sub(rice_k);
|
||||
rem
|
||||
};
|
||||
|
||||
let raw_magnitude = remainder | (quotient << rice_k);
|
||||
let sign_mask = if sign_bit != 0 { 0xffff_ffff } else { 0 };
|
||||
let signed_residual = (raw_magnitude ^ sign_mask) as i32;
|
||||
|
||||
DecodedSymbol { signed_residual, raw_magnitude, direct_bits_low0, direct_bits_sub3 }
|
||||
}
|
||||
|
||||
/// Decompress an entire Olympus compressed entropy bitstream into mosaic sensor samples.
|
||||
pub(crate) fn decompress_stream(stream: &[u8], width: usize, height: usize, params: &CompressionParameters) -> Result<Vec<u16>> {
|
||||
let total_pixels = width.checked_mul(height).ok_or(RawError::Limit("ORF image dimensions overflow"))?;
|
||||
if total_pixels > 0 && stream.is_empty() {
|
||||
return Err(RawError::Corrupt("ORF compressed stream is empty".into()));
|
||||
}
|
||||
// Reject streams too short to encode even 1 bit per pixel (prevents large allocation
|
||||
// from a truncated file before we start decoding).
|
||||
if total_pixels > 0 && (stream.len() as u64).saturating_mul(8) < total_pixels as u64 {
|
||||
return Err(RawError::Corrupt("ORF compressed stream too short for frame".into()));
|
||||
}
|
||||
let mut pixels = vec![0u16; total_pixels];
|
||||
let mut reader = BitStream::new(stream);
|
||||
|
||||
let gradient_threshold = 1u32.checked_shl(params.gradient_thresh_exp_641.min(30)).unwrap_or(1 << 5);
|
||||
let flatness_threshold = 1i32.checked_shl(params.flatness_thresh_exp_645.min(30)).unwrap_or(1 << 4);
|
||||
|
||||
let mut context = [0i32; 4];
|
||||
let mut last_predicted_sum = 0i32;
|
||||
let mut pred1 = 0i32;
|
||||
let mut raw_magnitude = 0u32;
|
||||
let mut prev_magnitude_signed = 0i32;
|
||||
|
||||
for row in 0..height {
|
||||
let row_offset = row.checked_mul(width).ok_or(RawError::Limit("ORF row overflow"))?;
|
||||
for col in 0..width {
|
||||
let p = prev_magnitude_signed;
|
||||
prev_magnitude_signed = raw_magnitude as i32;
|
||||
|
||||
let psel = if col > 1 && flatness_threshold >= p { context[3].saturating_add(1) } else { 0 };
|
||||
context[3] = context[2];
|
||||
context[2] = psel;
|
||||
|
||||
let mut rice_k = if col > 1 {
|
||||
let p16 = (p as u32 & 0xffff) as u16;
|
||||
let high_bit_count = if p16 == 0 { 0i32 } else { (16 - p16.leading_zeros()) as i32 };
|
||||
let t1 = if psel >= params.run_thresh_646 { params.table_648 } else { params.table_650 };
|
||||
let t2 = if psel >= params.run_thresh_646 { params.table_647 } else { params.table_649 };
|
||||
let tt = (high_bit_count - t1).max(-1);
|
||||
t2.saturating_add(tt).saturating_add(1)
|
||||
} else {
|
||||
params.table_649
|
||||
};
|
||||
|
||||
if rice_k > params.max_rice_k {
|
||||
rice_k = params.max_rice_k;
|
||||
}
|
||||
if rice_k >= 16 {
|
||||
return Err(RawError::Corrupt("ORF compressed Rice parameter out of range".into()));
|
||||
}
|
||||
|
||||
let symbol = decode_entropy_symbol(&mut reader, rice_k.max(0) as u32, params);
|
||||
let residual = symbol.signed_residual;
|
||||
raw_magnitude = symbol.raw_magnitude;
|
||||
let direct_bits_low0 = symbol.direct_bits_low0;
|
||||
let direct_bits_sub3 = symbol.direct_bits_sub3;
|
||||
|
||||
let (adjusted_residual, feedback_bits) = if params.direct_bits_sub3 > 0 {
|
||||
let v = if col < 2 { 0 } else { pred1 };
|
||||
let v_plus_g = v.checked_add(residual).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
if params.direct_bits_sub3 == 1 {
|
||||
let g_mult = v_plus_g.checked_mul(2).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
let v_res = v.checked_add(g >> 1).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
(g, v_res)
|
||||
} else {
|
||||
let g_mult = v_plus_g.checked_mul(4).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
let half_g = ((g >> 1) as u32 & 0xffff_fffe) as i32;
|
||||
let v_res = half_g
|
||||
.checked_add(v)
|
||||
.and_then(|x| x.checked_add(g >> 2))
|
||||
.ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
(g, v_res)
|
||||
}
|
||||
} else {
|
||||
(residual, 0)
|
||||
};
|
||||
|
||||
pred1 = context[0];
|
||||
context[0] = feedback_bits >> params.feedback_shift_644.min(30);
|
||||
|
||||
let west = if col < 2 { params.boundary_predictor_642 } else { context[1] };
|
||||
let mut north = if row < 2 {
|
||||
params.boundary_predictor_642
|
||||
} else {
|
||||
pixels.get((row - 2) * width + col).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15))
|
||||
};
|
||||
let north_west = if row < 2 || col < 2 {
|
||||
params.boundary_predictor_642
|
||||
} else {
|
||||
pixels.get((row - 2) * width + col - 2).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15))
|
||||
};
|
||||
|
||||
context[1] = last_predicted_sum;
|
||||
|
||||
// Directional edge-directed spatial prediction across Bayer channels (2-step distance)
|
||||
if west < north || north_west < west {
|
||||
if north_west <= north && west >= north {
|
||||
north = west;
|
||||
} else if north_west < north || west >= north {
|
||||
if north_west > west || west >= north {
|
||||
let diff_n_nw = north.abs_diff(north_west);
|
||||
let diff_w_nw = west.abs_diff(north_west);
|
||||
if diff_n_nw > gradient_threshold {
|
||||
north = north.saturating_add(west.saturating_sub(north_west));
|
||||
} else if diff_w_nw <= gradient_threshold {
|
||||
north = (north.saturating_add(west)) >> 1;
|
||||
} else {
|
||||
north = north.saturating_add(west.saturating_sub(north_west));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
north = west;
|
||||
}
|
||||
}
|
||||
|
||||
let sum = adjusted_residual.checked_add(north).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
last_predicted_sum = sum;
|
||||
let final_sample = i64::from(direct_bits_low0).saturating_add(i64::from(sum) << params.direct_bits_low0.min(15));
|
||||
if let Some(px) = pixels.get_mut(row_offset + col) {
|
||||
*px = final_sample.clamp(0, i64::from(u16::MAX)) as u16;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let consumed_bits = reader.bits_loaded.saturating_sub(u64::from(reader.bits_available));
|
||||
if consumed_bits > (stream.len() as u64).saturating_mul(8) {
|
||||
return Err(RawError::Corrupt("ORF compressed bitstream terminates prematurely".into()));
|
||||
}
|
||||
|
||||
Ok(pixels)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stream_header_validation() {
|
||||
assert!(validate_stream_header(&[0, 0, 0, 1, 0, 0], 4));
|
||||
assert!(validate_stream_header(&[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 8));
|
||||
assert!(!validate_stream_header(&[0, 0, 0, 2, 0, 0], 4)); // prefix != 1
|
||||
assert!(!validate_stream_header(&[0, 0, 0, 1, 0, 1], 4)); // trailer != [0, 0]
|
||||
assert!(!validate_stream_header(&[0, 0, 0, 0], 5)); // truncated
|
||||
assert!(!validate_stream_header(&[], 0)); // zero length
|
||||
assert!(!validate_stream_header(&[0; 20], 9)); // > 8 bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitstream_reader_operations() {
|
||||
let data = [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc];
|
||||
let mut stream = BitStream::new(&data);
|
||||
assert_eq!(stream.read_bits(4), 1);
|
||||
assert_eq!(stream.read_bits(4), 2);
|
||||
assert_eq!(stream.read_bits(8), 0x34);
|
||||
assert_eq!(stream.read_bits(16), 0x5678);
|
||||
assert_eq!(stream.read_bits(8), 0x9a);
|
||||
assert_eq!(stream.read_bits(8), 0xbc);
|
||||
// past EOF reads padded zeros without panicking
|
||||
assert_eq!(stream.read_bits(8), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_bounds_and_safety() {
|
||||
let params = CompressionParameters {
|
||||
direct_bits_low0: 0,
|
||||
gradient_thresh_exp_641: 5,
|
||||
boundary_predictor_642: 0,
|
||||
direct_bits_sub3: 2,
|
||||
feedback_shift_644: 5,
|
||||
flatness_thresh_exp_645: 4,
|
||||
run_thresh_646: 3,
|
||||
table_647: 2,
|
||||
table_648: 3,
|
||||
table_649: 4,
|
||||
table_650: 7,
|
||||
max_rice_k: 15,
|
||||
max_unary_run: 12,
|
||||
header_prefix_len: 5,
|
||||
valid_bits: 12,
|
||||
};
|
||||
// empty stream returns error for nonempty image, succeeds for 0x0
|
||||
assert!(decompress_stream(&[], 10, 10, ¶ms).is_err());
|
||||
assert_eq!(decompress_stream(&[], 0, 0, ¶ms).unwrap(), Vec::<u16>::new());
|
||||
// truncated stream (too short for requested dimensions) returns error
|
||||
assert!(decompress_stream(&[0xff; 2], 10, 10, ¶ms).is_err());
|
||||
assert!(decompress_stream(&[0x00; 2], 10, 10, ¶ms).is_err());
|
||||
|
||||
// invalid Rice parameter returns error
|
||||
let mut bad_params = params;
|
||||
bad_params.table_649 = 20;
|
||||
bad_params.max_rice_k = 20;
|
||||
assert!(decompress_stream(&[0xff; 32], 4, 4, &bad_params).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predictor_extreme_difference_never_panics() {
|
||||
assert_eq!(i32::MIN.abs_diff(0), 2_147_483_648u32);
|
||||
assert_eq!(i32::MIN.abs_diff(i32::MAX), 4_294_967_295u32);
|
||||
|
||||
let params = CompressionParameters {
|
||||
direct_bits_low0: 0,
|
||||
gradient_thresh_exp_641: 5,
|
||||
boundary_predictor_642: 0,
|
||||
direct_bits_sub3: 0,
|
||||
feedback_shift_644: 5,
|
||||
flatness_thresh_exp_645: 4,
|
||||
run_thresh_646: 3,
|
||||
table_647: 2,
|
||||
table_648: 3,
|
||||
table_649: 4,
|
||||
table_650: 7,
|
||||
max_rice_k: 15,
|
||||
max_unary_run: 12,
|
||||
header_prefix_len: 5,
|
||||
valid_bits: 12,
|
||||
};
|
||||
for fill in [0x00, 0x55, 0xaa, 0xff] {
|
||||
let stream = vec![fill; 64];
|
||||
let _ = decompress_stream(&stream, 4, 4, ¶ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ fn corpus_root() -> PathBuf {
|
||||
|
||||
/// Variants known not to decode yet (see the crate docs): matched against the lower-case file name.
|
||||
const KNOWN_UNSUPPORTED: &[&str] = &[
|
||||
"orf-olympus-em1.orf", // Compressed Olympus sensor decoding withdrawn pending provenance resolution.
|
||||
"orf-olympus-em10iii.orf",
|
||||
"cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs.
|
||||
"-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193
|
||||
"sraw", // Canon sRAW / mRAW
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! pinned only (its small JPEG gives r 0.59); its render was inspected by eye.
|
||||
//! Missing files are reported as skipped.
|
||||
|
||||
use lightcraft_raw::{RawData, decode, embedded_preview, probe_info};
|
||||
use lightcraft_raw::{RawData, RawError, RawFormat, decode, embedded_preview, probe, probe_info};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn corpus() -> PathBuf {
|
||||
@@ -67,8 +67,6 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() {
|
||||
("orf-olympus-e-330.orf", (3280, 2450), 0xc938_38fa_9822_c81a, true),
|
||||
("orf-olympus-e-500.orf", (3360, 2504), 0x5e22_2ac8_17ed_89d9, true),
|
||||
("orf-olympus-e-m5-mark-ii.orf", (9280, 6932), 0xa222_be38_c767_7782, true),
|
||||
("orf-olympus-em1.orf", (4640, 3472), 0xc61b_0bb3_5170_4735, true),
|
||||
("orf-olympus-em10iii.orf", (4640, 3472), 0xedc1_ec6d_15a8_a303, true),
|
||||
("orf-olympus-pen-f.orf", (10400, 7796), 0x415e_bf27_092e_9897, true),
|
||||
("orf-olympus-sh-2.orf", (4624, 3470), 0xb25b_8d24_4ade_1f3d, true),
|
||||
("orf-olympus-sp510uz.orf", (3088, 2309), 0xa885_b7ca_83ba_02f1, true),
|
||||
@@ -114,3 +112,21 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() {
|
||||
}
|
||||
eprintln!("Olympus / Samsung bodies checked on {seen} files");
|
||||
}
|
||||
|
||||
/// The withdrawn compressed decoder must stay out of both sensor-decode and import-probe paths.
|
||||
/// Camera JPEG extraction is independent of sensor decoding and remains available for preview-only imports.
|
||||
#[test]
|
||||
fn compressed_olympus_bodies_are_unsupported_with_embedded_previews() {
|
||||
for name in ["orf-olympus-em1.orf", "orf-olympus-em10iii.orf"] {
|
||||
let path = corpus().join("raw").join(name);
|
||||
let Ok(bytes) = std::fs::read(&path) else {
|
||||
lightcraft_testkit::skip!(Corpus, "{} absent", path.display());
|
||||
continue;
|
||||
};
|
||||
assert_eq!(probe(&bytes), Some(RawFormat::Orf), "{name}");
|
||||
assert!(matches!(decode(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"), "{name}");
|
||||
assert!(matches!(probe_info(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"), "{name}");
|
||||
let jpeg = embedded_preview(&bytes).unwrap_or_else(|| panic!("{name}: no camera JPEG"));
|
||||
assert!(jpeg.starts_with(&[0xff, 0xd8]) && jpeg.ends_with(&[0xff, 0xd9]), "{name}: invalid camera JPEG");
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
"Added {n} photo{} to My Photos": "{n} Foto{} zu „Meine Fotos“ hinzugefügt",
|
||||
"Added {n} photo{} to “{}”": "{n} Foto{0} zu „{1}“ hinzugefügt",
|
||||
"Added {what} to {name}": "{what} zu {name} hinzugefügt",
|
||||
"Adjustments: {n}": "Anpassungen: {n}",
|
||||
"Adding photos… {} of {}": "Fotos werden hinzugefügt… {} von {}",
|
||||
"All {n} selected photos move by the same amount.": "Alle {n} ausgewählten Fotos werden um denselben Betrag verschoben.",
|
||||
"Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren",
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"Added {n} photo{} to My Photos": "{n} foto{0} añadida{0} a Mis fotos",
|
||||
"Added {n} photo{} to “{}”": "{n} foto{0} añadida{0} a “{1}”",
|
||||
"Added {what} to {name}": "{what} añadido a {name}",
|
||||
"Adjustments: {n}": "Ajustes: {n}",
|
||||
"Adding photos… {} of {}": "Añadiendo fotos… {} de {}",
|
||||
"All {n} selected photos move by the same amount.": "Las {n} fotos seleccionadas se desplazan la misma cantidad.",
|
||||
"Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo",
|
||||
@@ -171,7 +172,7 @@
|
||||
"{n} photo{} now · updates automatically as photos change": "{n} foto{} ahora · se actualiza automáticamente cuando cambian las fotos",
|
||||
"{n} selected photo{} · {pages} page{}": "{n} foto{0} seleccionada{0} · {pages} página{1}",
|
||||
"{pid} (missing)": "{pid} (falta)",
|
||||
"{sel_n} selected · {counted}": "{sel_n} seleccionadas · {counted}",
|
||||
"{sel_n} selected · {counted}": "Seleccionadas: {sel_n} · {counted}",
|
||||
"{stage}… {:.0}%": "{stage}… {:.0}%",
|
||||
"{verb} {n} Photo{}": "{verb} {n} foto{}",
|
||||
"{weekday}, {day}": "{weekday}, {day}",
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"Added {n} photo{} to My Photos": "{n} photo{} ajoutée(s) à Mes photos",
|
||||
"Added {n} photo{} to “{}”": "{n} photo{} ajoutée(s) à « {} »",
|
||||
"Added {what} to {name}": "{what} ajouté à {name}",
|
||||
"Adjustments: {n}": "Réglages : {n}",
|
||||
"Adding photos… {} of {}": "Ajout des photos… {} sur {}",
|
||||
"All {n} selected photos move by the same amount.": "Les {n} photos sélectionnées se déplacent de la même valeur.",
|
||||
"Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau",
|
||||
|
||||
@@ -159,6 +159,7 @@
|
||||
"; {outside} outside its time range": "。{outside}枚は記録時間の範囲外",
|
||||
"@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:PR {}件、コミット {}件、+{} / −{} 行(Δ {})、バイナリアセット +{} / −{}、{} – {}",
|
||||
"Added {what} to {name}": "{what}を{name}に追加しました",
|
||||
"Adjustments: {n}": "調整:{n}",
|
||||
"Auto Import: added {} photo{}": "自動読み込み:{}枚の写真を追加しました{:.0}",
|
||||
"Building previews for {} photos…": "{}枚のプレビューを作成中…",
|
||||
"Couldn't open the editor: {e}": "エディターを開けませんでした:{e}",
|
||||
|
||||
@@ -130,7 +130,7 @@
|
||||
"{n} photo{} match · updates automatically as photos change": "{n} foto{0} correspondente{0} · atualiza automaticamente conforme as fotos mudam",
|
||||
"{n} photo{} now · updates automatically as photos change": "{n} foto{} agora · atualiza automaticamente conforme as fotos mudam",
|
||||
"{n} selected photo{} · {pages} page{}": "{n} foto{0} selecionada{0} · {pages} página{1}",
|
||||
"{sel_n} selected · {counted}": "{sel_n} selecionadas · {counted}",
|
||||
"{sel_n} selected · {counted}": "Selecionadas: {sel_n} · {counted}",
|
||||
"{stage}… {:.0}%": "{stage}… {:.0}%",
|
||||
"{verb} {n} Photo{}": "{verb} {n} foto{}",
|
||||
"{weekday}, {day}": "{weekday}, {day}",
|
||||
@@ -159,6 +159,7 @@
|
||||
"; {outside} outside its time range": "; {outside} fora do intervalo de tempo",
|
||||
"@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}: {} PRs, {} commits, +{} / −{} linhas (Δ {}), +{} / −{} arquivos binários, {} – {}",
|
||||
"Added {what} to {name}": "{what} adicionado a {name}",
|
||||
"Adjustments: {n}": "Ajustes: {n}",
|
||||
"Auto Import: added {} photo{}": "Importação automática: {} foto{1} adicionada{1}",
|
||||
"Building previews for {} photos…": "Gerando prévias de {} fotos…",
|
||||
"Couldn't open the editor: {e}": "Não foi possível abrir o editor: {e}",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"Added {n} photo{} to My Photos": "В «Мои фото» добавлено фото: {n}{:.0}",
|
||||
"Added {n} photo{} to “{}”": "В «{1}» добавлено фото: {n}{0:.0}",
|
||||
"Added {what} to {name}": "{what}: добавлено в {name}",
|
||||
"Adjustments: {n}": "Корректировки: {n}",
|
||||
"Adding photos… {} of {}": "Добавление фото… {} из {}",
|
||||
"All {n} selected photos move by the same amount.": "Все выбранные фото ({n}) сдвигаются на одно и то же значение.",
|
||||
"Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново",
|
||||
|
||||
@@ -253,7 +253,7 @@
|
||||
"{pct} %": "{pct} %",
|
||||
"{photos} catalog records processed; {collections} collections.": "{photos} katalogposter bearbetade; {collections} samlingar.",
|
||||
"{pid} (missing)": "{pid} (saknas)",
|
||||
"{sel_n} selected · {counted}": "{sel_n} markerade · {counted}",
|
||||
"{sel_n} selected · {counted}": "Markerade: {sel_n} · {counted}",
|
||||
"{size} GB": "{size} GB",
|
||||
"{stage}… {:.0}%": "{stage}… {:.0} %",
|
||||
"{s} s of AV1 video": "{s} s AV1-video",
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"Added {n} photo{} to My Photos": "До моїх фото додано: {n}{:.0}",
|
||||
"Added {n} photo{} to “{}”": "До «{1}» додано фото: {n}{0:.0}",
|
||||
"Added {what} to {name}": "{what}: додано до {name}",
|
||||
"Adjustments: {n}": "Коригування: {n}",
|
||||
"Adding photos… {} of {}": "Додавання фото… {} з {}",
|
||||
"All {n} selected photos move by the same amount.": "Усі вибрані фото ({n}) зміщуються на однакове значення.",
|
||||
"Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново",
|
||||
|
||||
@@ -159,6 +159,7 @@
|
||||
"; {outside} outside its time range": ";{outside} 张不在其时间范围内",
|
||||
"@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:{} 个 PR,{} 次提交,+{} / −{} 行(Δ {}),+{} / −{} 个二进制资源,{} – {}",
|
||||
"Added {what} to {name}": "已将{what}添加到 {name}",
|
||||
"Adjustments: {n}": "调整:{n}",
|
||||
"Auto Import: added {} photo{}": "自动导入:已添加 {0} 张照片{1:.0}",
|
||||
"Building previews for {} photos…": "正在为 {0} 张照片生成预览…",
|
||||
"Couldn't open the editor: {e}": "无法打开编辑器:{e}",
|
||||
|
||||
@@ -159,6 +159,7 @@
|
||||
"; {outside} outside its time range": ";{outside} 張不在其時間範圍內",
|
||||
"@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:{} 個 PR,{} 次提交,+{} / −{} 行(Δ {}),+{} / −{} 個二進位資產,{} – {}",
|
||||
"Added {what} to {name}": "已將{what}加入 {name}",
|
||||
"Adjustments: {n}": "調整:{n}",
|
||||
"Auto Import: added {} photo{}": "自動匯入:已新增 {} 張照片{:.0}",
|
||||
"Building previews for {} photos…": "正在為 {} 張照片建立預覽…",
|
||||
"Couldn't open the editor: {e}": "無法開啟編輯器:{e}",
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
//! a grid of thumbnails with checkboxes (duplicates marked and unchecked; Shift-click sets a
|
||||
//! range), the destination (add in place / copy or move into the library's `Originals/` or a
|
||||
//! chosen folder, filed by day, by month, into one folder or by a custom folder template,
|
||||
//! optionally renamed), an album (existing or new), a preset and keywords to apply. When the scan
|
||||
//! optionally renamed), an album (existing or new), a preset, an optional batch-edit recipe
|
||||
//! ("Batch edits": develop controls set on every new photo) and keywords to apply. When the scan
|
||||
//! left something out (a walk cut at its limit, folders it couldn't read, files that are not
|
||||
//! photos) one line under the count says so ([`scan_note`]). Importing runs on a worker thread
|
||||
//! (files are probed, copied or moved there) and its batches join the catalog between frames, with
|
||||
@@ -29,6 +30,7 @@ mod task;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use body::grid_height;
|
||||
use body::recipe_items;
|
||||
pub(crate) use body::scan_note;
|
||||
#[cfg(test)]
|
||||
pub(crate) use body::thumb_edge;
|
||||
@@ -36,6 +38,8 @@ pub(crate) use body::thumb_edge;
|
||||
use body::{DEFAULT_BELOW_GRID, badge_rect, dup_counts};
|
||||
pub use body::{DEFAULT_FOLDER_TEMPLATE, body, example_destination, source_summary};
|
||||
pub(crate) use body::{DIALOG_SIZE, THUMB_SIZE_DEFAULT, note_dialog_bottom, thumb_size};
|
||||
#[cfg(test)]
|
||||
use body::{RECIPE_CONTROLS, note_recipe_value};
|
||||
pub(crate) use scan::StoppingScans;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use scan::cards_seen;
|
||||
@@ -63,6 +67,12 @@ pub struct ImportDialog {
|
||||
pub new_album: String,
|
||||
/// Preset id ("" = none).
|
||||
pub preset: String,
|
||||
/// An optional batch-edit recipe: develop control id → value (only controls moved off their
|
||||
/// default are kept), set on every photo this import adds, on top of its sidecar, camera
|
||||
/// default and preset (the `recipe` param of `library.import`).
|
||||
pub recipe: std::collections::BTreeMap<String, f64>,
|
||||
/// Name typed for "Save as Preset" (the recipe saved for reuse).
|
||||
pub recipe_name: String,
|
||||
/// Comma-separated keywords.
|
||||
pub keywords: String,
|
||||
/// Copy: destination folder ("" = the library's Originals/).
|
||||
@@ -384,4 +394,50 @@ mod tests {
|
||||
d.click(2, true);
|
||||
assert_eq!(d.checked, [true, true, false, false, true, true]);
|
||||
}
|
||||
|
||||
/// The dialog offers only controls a recipe may name: `library.import` refuses the others
|
||||
/// (white balance, geometry and crop, per-photo controls), so one offered here would make every
|
||||
/// import with it fail. Each is moved off its default, as a slider drag does.
|
||||
#[test]
|
||||
fn every_offered_recipe_control_is_accepted_by_the_import() {
|
||||
let session = lightcraft_engine::Session::new();
|
||||
let mut d = dialog();
|
||||
for id in RECIPE_CONTROLS {
|
||||
let spec = lightcraft_develop::controls::find(id).unwrap_or_else(|| panic!("{id} is not a develop control"));
|
||||
let moved = if spec.default < spec.max { spec.max } else { spec.min };
|
||||
note_recipe_value(&mut d.recipe, spec, moved);
|
||||
}
|
||||
assert_eq!(d.recipe.len(), RECIPE_CONTROLS.len(), "all named, none repeated");
|
||||
let params = json!({"paths": ["img0.jpg"], "recipe": recipe_items(&d.recipe)});
|
||||
let request = lightcraft_engine::cmd::library::import_params(&session, ¶ms).unwrap_or_else(|e| panic!("refused: {e}"));
|
||||
assert_eq!(request.opts.recipe.len(), RECIPE_CONTROLS.len());
|
||||
}
|
||||
|
||||
/// A slider moved off its default names its control in the recipe; moved back, it no longer does.
|
||||
#[test]
|
||||
fn a_slider_back_at_its_default_leaves_the_recipe() {
|
||||
let spec = lightcraft_develop::controls::find("light.exposure").unwrap();
|
||||
let mut recipe = std::collections::BTreeMap::new();
|
||||
note_recipe_value(&mut recipe, spec, 0.5);
|
||||
assert_eq!(recipe.get("light.exposure"), Some(&0.5));
|
||||
note_recipe_value(&mut recipe, spec, 1.25);
|
||||
assert_eq!(recipe.get("light.exposure"), Some(&1.25), "a new value replaces the old");
|
||||
note_recipe_value(&mut recipe, spec, spec.default);
|
||||
assert!(recipe.is_empty(), "{recipe:?}");
|
||||
}
|
||||
|
||||
/// `start` hands `library.import` a `recipe` only when the dialog has one.
|
||||
#[test]
|
||||
fn start_passes_the_recipe_only_when_the_dialog_has_one() {
|
||||
let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::new(), crate::Services { png: None, ..Default::default() });
|
||||
let mut d = dialog();
|
||||
start(&mut app, &d).unwrap();
|
||||
let params = app.import.take().map(|t| t.params).unwrap();
|
||||
assert!(params.get("recipe").is_none(), "{params}");
|
||||
d.recipe.insert("light.exposure".into(), 0.5);
|
||||
d.recipe.insert("color.vibrance".into(), -20.0);
|
||||
start(&mut app, &d).unwrap();
|
||||
let params = app.import.take().map(|t| t.params).unwrap();
|
||||
assert_eq!(params["recipe"], json!([{"id": "color.vibrance", "value": -20.0}, {"id": "light.exposure", "value": 0.5}]), "{params}");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use serde_json::json;
|
||||
|
||||
use super::tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning};
|
||||
use super::{Color32, ImportDialog, LightcraftApp, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, Vec2, pos2, register, vec2};
|
||||
use super::{Color32, ImportDialog, LightcraftApp, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, Value, Vec2, pos2, register, vec2};
|
||||
|
||||
/// The review dialog's first size (points). It can be resized; the photo grid takes the height.
|
||||
pub(crate) const DIALOG_SIZE: [f32; 2] = [960.0, 720.0];
|
||||
@@ -447,6 +447,96 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut d.keywords).hint_text(crate::i18n::tr("comma, separated")).desired_width(f32::INFINITY));
|
||||
register(ui, "field:importKeywords", r.rect);
|
||||
});
|
||||
recipe_section(app, ui, d);
|
||||
}
|
||||
|
||||
/// The develop controls offered in the import review's optional batch-edit recipe: the everyday
|
||||
/// adjustments, not a second editor. Each must be one a recipe may name (`library.import` refuses
|
||||
/// the others: no white balance, geometry or crop); a test holds the list to that. Anything else is
|
||||
/// reached by choosing or saving a preset.
|
||||
pub(super) const RECIPE_CONTROLS: &[&str] = &[
|
||||
"light.exposure",
|
||||
"light.contrast",
|
||||
"light.highlights",
|
||||
"light.shadows",
|
||||
"light.whites",
|
||||
"light.blacks",
|
||||
"color.vibrance",
|
||||
"color.saturation",
|
||||
"effects.clarity",
|
||||
"effects.texture",
|
||||
"effects.dehaze",
|
||||
"detail.sharpenAmount",
|
||||
"grain.amount",
|
||||
"vignette.amount",
|
||||
];
|
||||
|
||||
/// A recipe as the `recipe` param of `library.import` and `preset.saveRecipe`.
|
||||
pub(super) fn recipe_items(recipe: &std::collections::BTreeMap<String, f64>) -> Value {
|
||||
Value::Array(recipe.iter().map(|(id, v)| json!({"id": id, "value": v})).collect())
|
||||
}
|
||||
|
||||
/// Record a slider's new value in the recipe: a control back at its default is no longer named.
|
||||
pub(super) fn note_recipe_value(recipe: &mut std::collections::BTreeMap<String, f64>, spec: &lightcraft_develop::controls::ControlSpec, value: f64) {
|
||||
if (value - spec.default).abs() < 1e-9 {
|
||||
recipe.remove(spec.id);
|
||||
} else {
|
||||
recipe.insert(spec.id.to_string(), value);
|
||||
}
|
||||
}
|
||||
|
||||
/// The optional "Batch edits" section of the import review: a small recipe of develop controls set
|
||||
/// on every photo this import adds, on top of its XMP sidecar, camera default and the chosen preset.
|
||||
/// The recipe lives only in the dialog until the import runs, so cancelling changes neither the
|
||||
/// catalog nor the preset collections; "Save as Preset" is the explicit way to keep one for reuse.
|
||||
fn recipe_section(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let open_id = egui::Id::unique("import-recipe-open");
|
||||
let mut open = ui.ctx().data(|m| m.get_temp::<bool>(open_id)).unwrap_or(false);
|
||||
field(ui, "Batch edits", |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
if crate::widgets::text_button(ui, "importRecipeToggle", if open { "Hide adjustments" } else { "Adjust…" }, open).clicked() {
|
||||
open = !open;
|
||||
}
|
||||
let n = d.recipe.len();
|
||||
let summary = if n == 0 { crate::i18n::tr("None").to_string() } else { crate::i18n::tr_format!("Adjustments: {n}", n = n) };
|
||||
ui.label(egui::RichText::new(summary).color(if n == 0 { t.text_dim } else { t.text_label }));
|
||||
});
|
||||
ui.ctx().data_mut(|m| m.insert_temp(open_id, open));
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
ui.label(
|
||||
egui::RichText::new(crate::i18n::tr(
|
||||
"Set on every photo this import adds, after its XMP sidecar and the preset above; photos the library already has are left alone. A slider left at its default changes nothing. Nothing is saved unless you save it as a preset.",
|
||||
))
|
||||
.color(t.text_dim)
|
||||
.small(),
|
||||
);
|
||||
for &id in RECIPE_CONTROLS {
|
||||
let Some(spec) = lightcraft_develop::controls::find(id) else { continue };
|
||||
let v = d.recipe.get(id).copied().unwrap_or(spec.default);
|
||||
if let Some(nv) = crate::widgets::slider(ui, spec, v, true, None).value {
|
||||
note_recipe_value(&mut d.recipe, spec, nv);
|
||||
}
|
||||
}
|
||||
field(ui, "Recipe", |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
crate::text_field::TextField::singleline("field:importRecipeName", &mut d.recipe_name)
|
||||
.hint(crate::i18n::tr("name for a saved preset"))
|
||||
.width(160.0)
|
||||
.show(ui);
|
||||
let can = !d.recipe.is_empty() && !d.recipe_name.trim().is_empty();
|
||||
let b = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Save as Preset")));
|
||||
register(ui, "button:importRecipeSave", b.rect);
|
||||
if b.clicked() {
|
||||
let params = json!({"name": d.recipe_name.trim(), "recipe": recipe_items(&d.recipe)});
|
||||
match app.run("preset.saveRecipe", params) {
|
||||
Ok(_) => app.toast(ui.ctx(), crate::i18n::tr("Saved as a preset")),
|
||||
Err(e) => app.toast_error(ui.ctx(), e),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Draw one import-dialog candidate cell: register `import:{i}`, request the cell's thumbnail,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::scan::{busy_synchronizing, running};
|
||||
use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json};
|
||||
use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json, recipe_items};
|
||||
|
||||
/// Files per batch in the browser build (each batch joins the catalog as it is ready, so the
|
||||
/// progress window updates); the desktop's worker uses [`lightcraft_engine::import::batch_size`].
|
||||
@@ -16,7 +16,7 @@ pub struct ImportTask {
|
||||
queue: Vec<String>,
|
||||
pub total: usize,
|
||||
pub done: usize,
|
||||
params: Value,
|
||||
pub(super) params: Value,
|
||||
pub imported: usize,
|
||||
/// Brought back from Recently Deleted (`onDeleted: restore`).
|
||||
pub restored: usize,
|
||||
@@ -225,6 +225,9 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String>
|
||||
(true, true) => "move",
|
||||
};
|
||||
let mut params = json!({"mode": mode, "keywords": d.keywords()});
|
||||
if !d.recipe.is_empty() {
|
||||
params["recipe"] = recipe_items(&d.recipe);
|
||||
}
|
||||
if !d.on_deleted.is_empty() {
|
||||
params["onDeleted"] = json!(d.on_deleted);
|
||||
}
|
||||
|
||||
@@ -286,6 +286,32 @@ fn image_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, st: &PrintSet
|
||||
});
|
||||
}
|
||||
|
||||
/// The Page panel: the background, and the Page Options or, on a package, Cut Guides.
|
||||
fn page_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, st: &PrintSettings) {
|
||||
let ctx = ui.ctx().clone();
|
||||
heading(ui, t, "Page");
|
||||
row(ui, t, "Background", |ui| {
|
||||
if let Some(c) = colour(ui, "printBackground", st.page.background) {
|
||||
patch(app, &ctx, json!({"page": {"background": c}}));
|
||||
}
|
||||
});
|
||||
if compose::has_page_options(st.layout.style) {
|
||||
ui.label(egui::RichText::new(crate::i18n::tr("Page Options")).color(t.text_label));
|
||||
let p = &st.page;
|
||||
for (id, label, on, key) in [
|
||||
("printPageNumbers", "Page Numbers", p.page_numbers, "pageNumbers"),
|
||||
("printPageInfo", "Page Info", p.page_info, "pageInfo"),
|
||||
("printCropMarks", "Crop Marks", p.crop_marks, "cropMarks"),
|
||||
] {
|
||||
if let Some(v) = check(ui, id, label, on) {
|
||||
patch(app, &ctx, json!({"page": {(key): v}}));
|
||||
}
|
||||
}
|
||||
} else if let Some(v) = check(ui, "printCropMarks", "Cut Guides", st.page.crop_marks) {
|
||||
patch(app, &ctx, json!({"page": {"cropMarks": v}}));
|
||||
}
|
||||
}
|
||||
|
||||
fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, st: &PrintSettings, photos: usize) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let l = &st.layout;
|
||||
@@ -461,25 +487,7 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi,
|
||||
});
|
||||
}
|
||||
|
||||
heading(ui, t, "Page");
|
||||
row(ui, t, "Background", |ui| {
|
||||
if let Some(c) = colour(ui, "printBackground", st.page.background) {
|
||||
patch(app, &ctx, json!({"page": {"background": c}}));
|
||||
}
|
||||
});
|
||||
if compose::has_page_options(l.style) {
|
||||
ui.label(egui::RichText::new(crate::i18n::tr("Page Options")).color(t.text_label));
|
||||
let p = &st.page;
|
||||
for (id, label, on, key) in [
|
||||
("printPageNumbers", "Page Numbers", p.page_numbers, "pageNumbers"),
|
||||
("printPageInfo", "Page Info", p.page_info, "pageInfo"),
|
||||
("printCropMarks", "Crop Marks", p.crop_marks, "cropMarks"),
|
||||
] {
|
||||
if let Some(v) = check(ui, id, label, on) {
|
||||
patch(app, &ctx, json!({"page": {(key): v}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
page_section(app, ui, t, st);
|
||||
|
||||
heading(ui, t, "Print Job");
|
||||
row(ui, t, "Resolution", |ui| {
|
||||
@@ -720,10 +728,12 @@ fn package_cells(
|
||||
let ctx = ui.ctx().clone();
|
||||
let first = ids.first().copied();
|
||||
let cells: Vec<layout::Cell> = st.layout.cells_on_page(pu.page as u32).cloned().collect();
|
||||
let mut shown = Vec::new();
|
||||
for c in &cells {
|
||||
let photo = if st.layout.style == Style::CustomPackage { c.photo.map(PhotoId).or(first) } else { first };
|
||||
let rect = sheet.rect(&c.rect);
|
||||
paint_cell(app, painter, t, st, rect, photo, sheet, &c.rect);
|
||||
shown.push(rect);
|
||||
let resp = ui.interact(rect, egui::Id::unique(("print-cell", c.id)), Sense::click_and_drag());
|
||||
register(ui, format!("print:cell:{}", c.id), rect);
|
||||
if resp.clicked() || resp.drag_started() {
|
||||
@@ -760,6 +770,7 @@ fn package_cells(
|
||||
}
|
||||
});
|
||||
}
|
||||
page_options(painter, st, sheet, &shown, pu.page + 1);
|
||||
// the selected cell's outline and resize handle go over everything
|
||||
let Some(sel) = pu.selected.and_then(|s| cells.iter().find(|c| c.id == s)) else { return };
|
||||
let rect = sheet.rect(&sel.rect);
|
||||
@@ -925,11 +936,9 @@ fn paint_cell(
|
||||
|
||||
/// The Page Options as the print draws them ([`compose`]): crop marks at the corners of each
|
||||
/// photo, the page number at the bottom right and the print settings at the bottom left.
|
||||
/// Packages draw none of them, as the print doesn't ([`compose::has_page_options`]).
|
||||
/// Packages draw only the crop marks, as their Cut Guides at each cell's corners
|
||||
/// ([`compose::has_page_options`]).
|
||||
fn page_options(painter: &egui::Painter, st: &PrintSettings, sheet: &Sheet, photos: &[Rect], number: usize) {
|
||||
if !compose::has_page_options(st.layout.style) {
|
||||
return;
|
||||
}
|
||||
let p = &st.page;
|
||||
let ink = compose::mark_ink(p.background);
|
||||
let ink = Color32::from_rgb(ink[0], ink[1], ink[2]);
|
||||
@@ -946,6 +955,9 @@ fn page_options(painter: &egui::Painter, st: &PrintSettings, sheet: &Sheet, phot
|
||||
}
|
||||
}
|
||||
let Ok(area) = st.layout.printable() else { return };
|
||||
if !compose::has_page_options(st.layout.style) {
|
||||
return;
|
||||
}
|
||||
let area = sheet.rect(&area);
|
||||
let font = egui::FontId::proportional((compose::PAGE_TEXT_PT as f32 / 72.0 * sheet.scale).max(4.0));
|
||||
let y = (area.bottom() + sheet.page.bottom()) / 2.0;
|
||||
|
||||
@@ -80,6 +80,7 @@ fn number_value(ui: &mut egui::Ui, v: &mut Value, field: &str) {
|
||||
"rating" => (0.0, 5.0, 0.05),
|
||||
"iso" => (0.0, 409_600.0, 10.0),
|
||||
"aperture" => (0.0, 64.0, 0.05),
|
||||
"exposureBias" => (-20.0, 20.0, 0.05),
|
||||
"keywordCount" | "personCount" => (0.0, 1000.0, 0.05),
|
||||
"longEdge" | "shortEdge" => (0.0, 100_000.0, 10.0),
|
||||
_ => (0.0, 100_000.0, 0.5),
|
||||
|
||||
@@ -210,12 +210,20 @@ fn request_tile_renders(app: &mut LightcraftApp, id: PhotoId, slot: Slot, want:
|
||||
|
||||
/// Draw one photo fitted into `area` (rendered at its display size into `slot`), with its caption
|
||||
/// strip below. Returns the image rect and the click/drag response.
|
||||
fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slot, area: Rect, label: &str, zoom: Zoom) -> (Rect, egui::Response) {
|
||||
fn photo_tile(
|
||||
app: &mut LightcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
id: PhotoId,
|
||||
slot: Slot,
|
||||
area: Rect,
|
||||
label: &str,
|
||||
zoom: Zoom,
|
||||
) -> (Rect, Rect, egui::Response) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let resp = ui.interact(area, egui::Id::unique(("cull-tile", slot_index(slot), id.0)), Sense::click_and_drag());
|
||||
crate::widgets::announce(&resp, app.session.catalog.photo(id).map(|p| p.file_name.clone()).unwrap_or_default());
|
||||
let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, resp) };
|
||||
let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, area, resp) };
|
||||
let caption_h = 26.0;
|
||||
let img_area = Rect::from_min_max(area.min, pos2(area.right(), area.bottom() - caption_h));
|
||||
let frame = lightcraft_pipeline::geometry::Frame::with_lens(
|
||||
@@ -279,7 +287,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo
|
||||
display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan);
|
||||
p.image(tex.id(), display, uv, Color32::WHITE);
|
||||
if let Some(i) = window {
|
||||
draw_window(&p, app, i, id, photo.develop.hash64(), display);
|
||||
draw_window(&p, app, i, id, photo.develop.hash64(), img);
|
||||
}
|
||||
} else if let Some(tex) = app.renderer.textures.get(&Slot::Thumb(id)) {
|
||||
let texture_aspect = tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32;
|
||||
@@ -369,7 +377,10 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo
|
||||
register(ui, format!("cull:{}:label", id.0), lr);
|
||||
}
|
||||
register(ui, format!("cull:{}", id.0), display);
|
||||
(display, resp)
|
||||
// The frame rect the window was requested in (`img`) and the texture's rect (`display`): they
|
||||
// differ when the texture's aspect differs from the frame's. The first is the window's
|
||||
// reference, the second is the photo as painted.
|
||||
(img, display, resp)
|
||||
}
|
||||
|
||||
/// Panes that get window renders: Compare's Select and Candidate, Reference's two sides.
|
||||
@@ -510,7 +521,7 @@ pub fn show_compare(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
];
|
||||
let zoom = app.ui.zoom;
|
||||
for (id, r, label, i) in panes {
|
||||
let (img, resp) = photo_tile(app, ui, id, Slot::Compare(i), r, label, zoom);
|
||||
let (img, _, resp) = photo_tile(app, ui, id, Slot::Compare(i), r, label, zoom);
|
||||
if i == 1 {
|
||||
app.image_rect = Some(img);
|
||||
}
|
||||
@@ -565,7 +576,8 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
for (i, id) in photos.iter().enumerate() {
|
||||
let (c, r) = (i % cols, i / cols);
|
||||
let cell = Rect::from_min_size(pos2(area.left() + c as f32 * cw, area.top() + r as f32 * ch), vec2(cw, ch)).shrink(6.0);
|
||||
let (img, resp) = photo_tile(app, ui, *id, Slot::Compare(i as u8), cell, "", Zoom::Fit);
|
||||
// (Survey tiles are fit views with no windows: what counts is the photo as painted)
|
||||
let (_, img, resp) = photo_tile(app, ui, *id, Slot::Compare(i as u8), cell, "", Zoom::Fit);
|
||||
if app.session.selection.active == Some(*id) {
|
||||
app.image_rect = Some(img);
|
||||
}
|
||||
@@ -620,8 +632,8 @@ pub fn show_reference(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
let zoom = app.ui.zoom;
|
||||
let left = Rect::from_min_size(area.min, vec2(half, area.height()));
|
||||
let right = Rect::from_min_size(pos2(area.right() - half, area.top()), vec2(half, area.height()));
|
||||
let (_, lresp) = photo_tile(app, ui, r, Slot::Compare(0), left, "Reference", zoom);
|
||||
let (img, _) = photo_tile(app, ui, active, Slot::Compare(1), right, "Active", zoom);
|
||||
let (_, _, lresp) = photo_tile(app, ui, r, Slot::Compare(0), left, "Reference", zoom);
|
||||
let (img, _, _) = photo_tile(app, ui, active, Slot::Compare(1), right, "Active", zoom);
|
||||
app.image_rect = Some(img);
|
||||
crate::widgets::context_menu(&lresp, |ui| {
|
||||
if ui.button(crate::i18n::tr("Clear Reference")).clicked() {
|
||||
|
||||
@@ -344,7 +344,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
// the line of a wipe over both
|
||||
draw_wipe_line(app.ui.before_after, &p, img_rect, line);
|
||||
let map = CanvasMap::new(&frame, img_rect);
|
||||
let over = OverPhoto { photo: &photo, d: &d, map: &map, canvas, img_rect, fullscreen, crop_tool, clipping: !show_before };
|
||||
let over = OverPhoto { photo: &photo, d: &d, map: &map, canvas, img_rect, fullscreen, crop_tool };
|
||||
photo_overlays(app, ui, &p, &over);
|
||||
// Cursor selection must also run on gesture frames, when tool input is suppressed.
|
||||
if !matches!(right, RightPanel::Crop | RightPanel::Masking | RightPanel::Remove | RightPanel::RedEye) {
|
||||
@@ -434,7 +434,8 @@ fn face_boxes(
|
||||
let people = if app.ui.name_edit.is_some() { app.caches.person_names(&app.session.catalog) } else { Default::default() };
|
||||
// while the name box is open and recognition is not set up, the box offers the next step
|
||||
let setup = if app.ui.name_edit.is_some() { super::faces::setup(app, ui.ctx()) } else { super::faces::Setup::Running };
|
||||
let regions = RegionContext { photo, orient: d.orientation, hints: hints.as_deref(), people: &people, setup };
|
||||
let movable = !matches!(app.ui.right, RightPanel::Crop | RightPanel::Masking | RightPanel::Remove | RightPanel::RedEye);
|
||||
let regions = RegionContext { photo, orient: d.orientation, hints: hints.as_deref(), people: &people, setup, movable };
|
||||
match region_overlay(ui, p, map, ®ions, &mut app.ui.name_edit) {
|
||||
Some(RegionEdit::SetUp) => {
|
||||
app.ui.name_edit = None;
|
||||
@@ -1064,17 +1065,12 @@ struct OverPhoto<'a> {
|
||||
img_rect: Rect,
|
||||
fullscreen: bool,
|
||||
crop_tool: bool,
|
||||
/// the clipping overlay may show (not in the Before view)
|
||||
clipping: bool,
|
||||
}
|
||||
|
||||
/// The overlays over the photo: clipping, layout image, info, filter pill, faces, focus point and
|
||||
/// The overlays over the photo: layout image, info, filter pill, faces, focus point and
|
||||
/// the transform grid.
|
||||
fn photo_overlays(app: &mut LightcraftApp, ui: &mut egui::Ui, p: &egui::Painter, o: &OverPhoto) {
|
||||
let (canvas, img_rect) = (o.canvas, o.img_rect);
|
||||
if app.ui.show_clipping && o.clipping && !o.fullscreen {
|
||||
clipping_overlay(app, p, img_rect);
|
||||
}
|
||||
// View ▸ Loupe Overlay ▸ Layout Image, over the photo (the After view in a before/after)
|
||||
super::layout_overlay::draw(app, p, img_rect);
|
||||
register(ui, "canvas:image", img_rect);
|
||||
@@ -1154,7 +1150,7 @@ fn targeted_drag(app: &mut LightcraftApp, resp: &egui::Response, map: &CanvasMap
|
||||
}
|
||||
|
||||
/// The diagnostic overlay the loupe shows (an Alt-drag preview, the selected mask, Point Color's
|
||||
/// visualized range, Visualize Spots).
|
||||
/// visualized range, Visualize Spots, the clipping warnings).
|
||||
pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcraft_pipeline::Overlay {
|
||||
use lightcraft_pipeline::{MaskView, Overlay};
|
||||
if app.ui.fullscreen {
|
||||
@@ -1198,20 +1194,11 @@ pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcra
|
||||
if edit && app.ui.hdr_visualize && d.hdr.enabled {
|
||||
return Overlay::HdrRange;
|
||||
}
|
||||
Overlay::None
|
||||
}
|
||||
|
||||
fn clipping_overlay(app: &LightcraftApp, p: &egui::Painter, r: Rect) {
|
||||
// Highlight clipped regions using the histogram's extremes isn't spatial; show a subtle frame hint.
|
||||
if let Some(h) = app.renderer.textures.get(&Slot::Main).and_then(|t| t.histogram.as_ref()) {
|
||||
let (lo, hi) = h.clipping();
|
||||
if hi > 0.003 {
|
||||
p.rect_stroke(r, 0.0, Stroke::new(2.0, Color32::from_rgb(255, 60, 60)), StrokeKind::Outside);
|
||||
}
|
||||
if lo > 0.003 {
|
||||
p.rect_stroke(r.expand(3.0), 0.0, Stroke::new(2.0, Color32::from_rgb(60, 120, 255)), StrokeKind::Outside);
|
||||
}
|
||||
// Clipping warnings (J): clipped highlights red, clipped shadows blue, on the photo itself
|
||||
if app.ui.show_clipping {
|
||||
return Overlay::ClipWarnings;
|
||||
}
|
||||
Overlay::None
|
||||
}
|
||||
|
||||
fn general_cursor(app: &LightcraftApp, ui: &egui::Ui, resp: &egui::Response, img: Rect, canvas: Rect) {
|
||||
|
||||
@@ -29,7 +29,8 @@ const REGION_HANDLES: [(f32, f32, egui::CursorIcon); 8] = [
|
||||
];
|
||||
|
||||
/// Face/pet/focus regions read from XMP (MWG-RS), drawn as boxes over the photo. Hovering a box shows
|
||||
/// a × in its corner and eight resize handles. A drag previews the new box live and is reported once,
|
||||
/// a × in its corner and eight resize handles, and dragging its body moves it (not under a tool that
|
||||
/// draws on the photo). A drag previews the new box live and is reported once,
|
||||
/// on release (one undo step); the × reports the region to remove. Both are catalog-only edits:
|
||||
/// LightCraft doesn't write regions to XMP. Regions are stored on the upright (EXIF-oriented) photo;
|
||||
/// `orient` is the user's Rotate / Flip on top of it, which the loupe's normalized frame includes.
|
||||
@@ -42,6 +43,52 @@ pub(super) struct RegionContext<'a> {
|
||||
/// the names to offer when a region is named
|
||||
pub people: &'a [String],
|
||||
pub setup: crate::panels::faces::Setup,
|
||||
/// Dragging a box's body moves it: not while a tool that works on the photo owns the drag.
|
||||
pub movable: bool,
|
||||
}
|
||||
|
||||
/// Dragging the body of a box moves it. It is laid out before the handles and the × so they win an
|
||||
/// overlapping press. The press point and the box at press time are remembered, so the box follows the
|
||||
/// pointer from where it was grabbed. The move is reported on release, unless the box ends where it began.
|
||||
fn region_body_drag(
|
||||
ui: &egui::Ui,
|
||||
map: &CanvasMap,
|
||||
rect: Rect,
|
||||
(index, norm): (usize, lightcraft_geom::Rect),
|
||||
orient: lightcraft_geom::Orientation,
|
||||
drag_key: egui::Id,
|
||||
) -> Option<RegionEdit> {
|
||||
let body_key = egui::Id::unique(("region-body", index));
|
||||
let body_resp = ui.interact(rect, body_key, Sense::drag());
|
||||
if body_resp.drag_started() {
|
||||
let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(body_resp.interact_pointer_pos().unwrap_or(rect.center()));
|
||||
let start = map.norm(press);
|
||||
ui.data_mut(|d| d.insert_temp(body_key, (start, norm)));
|
||||
}
|
||||
// (the release frame reports `dragged()` too, so the last position is taken before the stop)
|
||||
if body_resp.dragged() || body_resp.drag_stopped() {
|
||||
let pp = body_resp.interact_pointer_pos();
|
||||
let shown = ui.data(|d| d.get_temp::<(Point, lightcraft_geom::Rect)>(body_key));
|
||||
if let (Some(pp), Some((start, shown))) = (pp, shown) {
|
||||
let now = map.norm(pp);
|
||||
let (w, h) = (shown.x1 - shown.x0, shown.y1 - shown.y0);
|
||||
let (x0, y0) = ((shown.x0 + now.x - start.x).clamp(0.0, (1.0 - w).max(0.0)), (shown.y0 + now.y - start.y).clamp(0.0, (1.0 - h).max(0.0)));
|
||||
let moved = lightcraft_geom::Rect { x0, y0, x1: x0 + w, y1: y0 + h };
|
||||
if moved == shown {
|
||||
ui.data_mut(|d| d.remove_temp::<(usize, lightcraft_geom::Rect)>(drag_key));
|
||||
} else {
|
||||
ui.data_mut(|d| d.insert_temp(drag_key, (index, orient.inverse().map_norm_rect(moved))));
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
if !body_resp.drag_stopped() {
|
||||
return None;
|
||||
}
|
||||
let edit = ui.data(|d| d.get_temp::<(usize, lightcraft_geom::Rect)>(drag_key)).map(|(i, new)| RegionEdit::Resize(i, new));
|
||||
ui.data_mut(|d| d.remove_temp::<(usize, lightcraft_geom::Rect)>(drag_key));
|
||||
ui.data_mut(|d| d.remove_temp::<(Point, lightcraft_geom::Rect)>(body_key));
|
||||
edit
|
||||
}
|
||||
|
||||
pub(super) fn region_overlay(
|
||||
@@ -51,7 +98,7 @@ pub(super) fn region_overlay(
|
||||
regions: &RegionContext,
|
||||
editing: &mut Option<crate::state::NameEdit>,
|
||||
) -> Option<RegionEdit> {
|
||||
let RegionContext { photo, orient, hints, people, setup } = *regions;
|
||||
let RegionContext { photo, orient, hints, people, setup, movable } = *regions;
|
||||
let t = Tokens::get(p.ctx());
|
||||
let clip = p.clip_rect();
|
||||
let pointer = ui.input(|i| i.pointer.hover_pos());
|
||||
@@ -66,6 +113,9 @@ pub(super) fn region_overlay(
|
||||
// white with a black keyline just outside it, so the box shows on any background
|
||||
p.rect_stroke(rect.expand(1.0), 0.0, Stroke::new(1.0, Color32::from_black_alpha(190)), StrokeKind::Outside);
|
||||
p.rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::WHITE), StrokeKind::Outside);
|
||||
if movable && let Some(moved) = region_body_drag(ui, map, rect, (index, norm), orient, drag_key) {
|
||||
edit = Some(moved);
|
||||
}
|
||||
if dragging.is_some() || (live.is_none() && pointer.is_some_and(|h| rect.expand(8.0).contains(h))) {
|
||||
for (h, (fx, fy, cursor)) in REGION_HANDLES.iter().enumerate() {
|
||||
let c = pos2(rect.left() + fx * rect.width(), rect.top() + fy * rect.height());
|
||||
@@ -905,3 +955,70 @@ mod pen_tests {
|
||||
assert_eq!(pen_force(&i), Some(1.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod region_drag_tests {
|
||||
use super::*;
|
||||
|
||||
/// Dragging the body of a face box (not a handle) moves the whole box by the drag, keeps its
|
||||
/// size, and stays inside the photo; the move is reported once, on release.
|
||||
#[test]
|
||||
fn a_moved_face_box_keeps_its_size_and_stays_inside_the_photo() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx);
|
||||
let canvas = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 400.0));
|
||||
let frame = lightcraft_pipeline::geometry::Frame::new(100, 100, &DevelopSettings::default(), true);
|
||||
let map = CanvasMap::new(&frame, canvas);
|
||||
let mut photo = lightcraft_catalog::Photo::new(
|
||||
lightcraft_catalog::PhotoId(1),
|
||||
lightcraft_catalog::Source::Demo { scene: 0 },
|
||||
"a.jpg",
|
||||
"JPEG",
|
||||
100,
|
||||
100,
|
||||
"2026-10-01T00:00:00",
|
||||
);
|
||||
photo.meta.regions = vec![lightcraft_meta::Region {
|
||||
rect: lightcraft_geom::Rect { x0: 0.2, y0: 0.2, x1: 0.4, y1: 0.4 },
|
||||
kind: lightcraft_meta::RegionKind::Face,
|
||||
name: Some("Jane".to_string()),
|
||||
description: None,
|
||||
}];
|
||||
let mut editing = None;
|
||||
let mut run_frame = |events: &[egui::Event]| -> Option<RegionEdit> {
|
||||
let mut edit = None;
|
||||
let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(canvas), events: events.to_vec(), ..Default::default() }, |ui| {
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| {
|
||||
let p = ui.painter_at(canvas);
|
||||
let regions = RegionContext {
|
||||
photo: &photo,
|
||||
orient: lightcraft_geom::Orientation::Normal,
|
||||
hints: None,
|
||||
people: &[],
|
||||
setup: crate::panels::faces::Setup::Running,
|
||||
movable: true,
|
||||
};
|
||||
edit = region_overlay(ui, &p, &map, ®ions, &mut editing);
|
||||
});
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
edit
|
||||
};
|
||||
// the box is at 80..160 px on screen; drag its centre (120, 120) by 40 x 20 px
|
||||
let press =
|
||||
|pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
run_frame(&[egui::Event::PointerMoved(pos2(120.0, 120.0))]);
|
||||
run_frame(&[press(pos2(120.0, 120.0), true)]);
|
||||
run_frame(&[egui::Event::PointerMoved(pos2(140.0, 130.0))]);
|
||||
run_frame(&[egui::Event::PointerMoved(pos2(160.0, 140.0))]);
|
||||
let edit = run_frame(&[press(pos2(160.0, 140.0), false)]);
|
||||
assert!(matches!(edit, Some(RegionEdit::Resize(0, _))), "dragging the face box body reports the moved box");
|
||||
let Some(RegionEdit::Resize(index, moved)) = edit else { return };
|
||||
assert_eq!(index, 0);
|
||||
assert!(((moved.x1 - moved.x0) - 0.2).abs() < 0.02, "width kept: {moved:?}");
|
||||
assert!(((moved.y1 - moved.y0) - 0.2).abs() < 0.02, "height kept: {moved:?}");
|
||||
assert!((moved.x0 - 0.3).abs() < 0.02 && (moved.y0 - 0.25).abs() < 0.02, "moved by the drag: {moved:?}");
|
||||
assert!(moved.x0 >= 0.0 && moved.y0 >= 0.0 && moved.x1 <= 1.0 && moved.y1 <= 1.0, "inside the photo: {moved:?}");
|
||||
}
|
||||
}
|
||||
@@ -291,35 +291,20 @@ pub fn rows_between(rows: &[GridRow], top: f32, bottom: f32) -> &[GridRow] {
|
||||
}
|
||||
|
||||
fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (generation, ids) = app.session.visible_shared();
|
||||
// header: source title + count
|
||||
let sel_n = app.session.selection.ids.len();
|
||||
let chips = lightcraft_engine::filter_chips(&app.session.filter, &app.session.catalog);
|
||||
let total = app.session.source_total();
|
||||
let counted = super::chips::count_text(ids.len(), total, !chips.is_empty());
|
||||
let cnt = if sel_n > 1 { crate::i18n::tr_format!("{sel_n} selected · {counted}", counted = counted, sel_n = sel_n) } else { counted };
|
||||
let cnt = if sel_n > 0 { crate::i18n::tr_format!("{sel_n} selected · {counted}", counted = counted, sel_n = sel_n) } else { counted };
|
||||
match app.session.browse.clone().filter(|_| app.session.source == lightcraft_engine::LibrarySource::Folder) {
|
||||
Some(b) => {
|
||||
let local = app.caches.grid.local(&app.session.catalog, &ids, generation);
|
||||
folder_header(app, ui, &b, &ids, local, &cnt);
|
||||
}
|
||||
None => {
|
||||
let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover());
|
||||
ui.painter().rect_filled(hr, 0.0, t.canvas);
|
||||
let full = crate::i18n::source_title(&app.session);
|
||||
let count_w = ui.painter().layout_no_wrap(cnt.clone(), t.font(12.5), t.text_dim).size().x;
|
||||
// the title gives way to the count: a long album or folder name is trimmed, in full on hover
|
||||
let room = (hr.width() - 20.0 - count_w - 36.0).max(0.0);
|
||||
let font = t.semibold(17.0);
|
||||
let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x);
|
||||
let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text);
|
||||
let count_rect = ui.painter().text(pos2(hr.right() - 20.0, hr.center().y), Align2::RIGHT_CENTER, cnt, t.font(12.5), t.text_dim);
|
||||
crate::widgets::register(ui, "grid:title", title_rect);
|
||||
crate::widgets::register(ui, "grid:count", count_rect);
|
||||
if title != full {
|
||||
ui.interact(title_rect, ui.scope_id().with("grid-title"), Sense::hover()).on_hover_text(full);
|
||||
}
|
||||
library_header(app, ui, &cnt);
|
||||
}
|
||||
}
|
||||
super::chips::show(app, ui, &chips);
|
||||
@@ -1016,6 +1001,35 @@ struct BadgeFlags {
|
||||
hovered: bool,
|
||||
}
|
||||
|
||||
/// The header of a library view (All Photos, an album, a library folder…): the source's title and
|
||||
/// the photo count.
|
||||
fn library_header(app: &LightcraftApp, ui: &mut egui::Ui, cnt: &str) -> Rect {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover());
|
||||
ui.painter().rect_filled(hr, 0.0, t.canvas);
|
||||
let full = crate::i18n::source_title(&app.session);
|
||||
// the title gives way to the count: a long album or folder name is trimmed, in full on hover;
|
||||
// a count wider than all but the title's ellipsis (a narrow centre pane) is cut, as a Local
|
||||
// folder's is, and reads in full on hover
|
||||
let count_w = ui.painter().layout_no_wrap(cnt.to_owned(), t.font(12.5), t.text_dim).size().x.ceil().min((hr.width() - 96.0).max(0.0).floor());
|
||||
let room = (hr.width() - 20.0 - count_w - 36.0).max(0.0);
|
||||
let font = t.semibold(17.0);
|
||||
let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x);
|
||||
let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text);
|
||||
let count_box = Rect::from_min_max(pos2(hr.right() - 20.0 - count_w, hr.top()), pos2(hr.right() - 20.0, hr.bottom()));
|
||||
let label = egui::Label::new(egui::RichText::new(cnt).font(t.font(12.5)).color(t.text_dim)).truncate().show_tooltip_when_elided(false);
|
||||
let count = ui
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(count_box).layout(egui::Layout::right_to_left(egui::Align::Center)), |ui| ui.add(label))
|
||||
.inner;
|
||||
crate::widgets::register(ui, "grid:title", title_rect);
|
||||
crate::widgets::register(ui, "grid:count", count.rect);
|
||||
count.on_hover_text(cnt);
|
||||
if title != full {
|
||||
ui.interact(title_rect, ui.scope_id().with("grid-title"), Sense::hover()).on_hover_text(full);
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
/// The header of a Local folder view: the path as a breadcrumb (each part opens that folder),
|
||||
/// Include subfolders, Add to My Photos.
|
||||
fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engine::Browse, ids: &[PhotoId], local_n: usize, cnt: &str) -> Rect {
|
||||
|
||||
@@ -17,6 +17,122 @@ fn breadcrumbs_open_their_folder_as_spelled() {
|
||||
assert!(to("").is_empty() && to("/").is_empty() && to(r"\\").is_empty());
|
||||
}
|
||||
|
||||
/// Issue #3776: one selected photo is counted in the header as two or more are ("1 selected · 3
|
||||
/// photos"); with nothing selected the header shows the photo count alone.
|
||||
#[test]
|
||||
fn the_header_counts_a_single_selected_photo() {
|
||||
use lightcraft_catalog::{Op, Photo, Source};
|
||||
for (selected, folder) in [(0, false), (1, false), (2, false), (0, true), (1, true)] {
|
||||
let mut session = lightcraft_engine::Session::new();
|
||||
for i in 0..3 {
|
||||
let id = session.catalog.alloc_photo_id();
|
||||
let p = Photo::new(id, Source::File { path: format!("/pics/{i}.jpg") }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00");
|
||||
session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
}
|
||||
session.selection.ids = session.catalog.photos().take(selected).map(|p| p.id).collect();
|
||||
if folder {
|
||||
// a Local folder view: the same count, in the breadcrumb header
|
||||
session.source = lightcraft_engine::LibrarySource::Folder;
|
||||
session.browse = Some(lightcraft_engine::Browse { path: "/pics".into(), subfolders: false });
|
||||
}
|
||||
let mut app = LightcraftApp::new(session, Services { png: None, ..Default::default() });
|
||||
app.ui.view = crate::state::ViewMode::PhotoGrid;
|
||||
let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0);
|
||||
h.step();
|
||||
h.step();
|
||||
assert_eq!(h.app.session.selection.ids.len(), selected, "the selection is kept");
|
||||
let has = |id: &str| h.app.widgets.iter().any(|(w, _)| w == id);
|
||||
assert!(has("grid:count") && has("grid:folderHeader") == folder, "folder {folder}: {:?}", h.app.widgets);
|
||||
let painted = h.painted_text();
|
||||
let photos = crate::panels::chips::count_text(h.app.session.visible_cloned().len(), h.app.session.source_total(), false);
|
||||
assert!(folder || photos == "3 photos", "{photos}");
|
||||
let expected = if selected == 0 { photos } else { format!("{selected} selected · {photos}") };
|
||||
assert!(painted.contains(&expected), "folder {folder}, {selected} selected: the header shows {expected:?}: {painted:?}");
|
||||
if selected == 0 {
|
||||
assert!(!painted.iter().any(|s| s.contains("selected ·")), "nothing selected, no count: {painted:?}");
|
||||
}
|
||||
}
|
||||
// a language whose word for "selected" agrees with the number reads "noun: number", right for one as for many
|
||||
for (locale, expected) in [(Locale::Es, "Seleccionadas: 1 · x"), (Locale::PtBr, "Selecionadas: 1 · x"), (Locale::Sv, "Markerade: 1 · x")] {
|
||||
crate::i18n::set_language(locale);
|
||||
let one = crate::i18n::tr_format!("{sel_n} selected · {counted}", sel_n = 1, counted = "x");
|
||||
crate::i18n::set_language(Locale::En);
|
||||
assert_eq!(one, expected, "{locale:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every text the frame painted as it reads on screen (a cut one with its "…"), with where it was painted.
|
||||
fn texts_painted(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) {
|
||||
match shape {
|
||||
egui::Shape::Text(text) => {
|
||||
let shown = text.galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| g.chr)).collect();
|
||||
out.push((shown, text.visual_bounding_rect()));
|
||||
}
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts_painted(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A library view's count too long for a narrow centre pane (German, at the narrowest the photo
|
||||
/// area gets) is cut to stay inside the header, beside the title, and reads in full on hover.
|
||||
#[test]
|
||||
fn a_long_library_count_stays_inside_a_narrow_header() {
|
||||
for width in [crate::state::MIN_PHOTO_WIDTH, 590.0] {
|
||||
for scale in [1.0, 2.0] {
|
||||
let app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
crate::i18n::set_language(Locale::De);
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx);
|
||||
let counted = crate::i18n::tr_format!("{matching} of {t} photos", matching = 123_456_789, t = 987_654_321);
|
||||
let cnt = crate::i18n::tr_format!("{sel_n} selected · {counted}", sel_n = 123_456_789, counted = counted);
|
||||
let frame = |time: f64, events: Vec<egui::Event>| {
|
||||
let mut header = Rect::NOTHING;
|
||||
let raw = HeadlessView::raw_input(vec2(width, 300.0), scale, time, events);
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| {
|
||||
header = super::library_header(&app, ui, &cnt);
|
||||
});
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let mut texts = Vec::new();
|
||||
for shape in &out.shapes {
|
||||
texts_painted(&shape.shape, &mut texts);
|
||||
}
|
||||
(texts, crate::widgets::take_registry(&ctx), header)
|
||||
};
|
||||
let (mut texts, mut widgets, mut header) = (Vec::new(), Vec::new(), Rect::NOTHING);
|
||||
for f in 0..3 {
|
||||
(texts, widgets, header) = frame(f as f64 / 60.0, vec![]);
|
||||
}
|
||||
let widget = |id: &str| widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r);
|
||||
let (Some(count), Some(title)) = (widget("grid:count"), widget("grid:title")) else { panic!("no count or title: {widgets:?}") };
|
||||
let at = format!("{width} {scale}");
|
||||
assert!(header.left() >= 0.0 && header.right() <= width, "{at}: header must not expand past the centre pane: {header:?}");
|
||||
assert!(header.contains_rect(count), "{at}: the count stays inside the header: {count:?} in {header:?}");
|
||||
assert!(title.right() <= count.left(), "{at}: the title stays left of the count: {title:?} {count:?}");
|
||||
for (i, (text, a)) in texts.iter().enumerate() {
|
||||
assert!(header.expand(1.0).contains_rect(*a), "{at}: {text:?} painted outside the header: {a:?}");
|
||||
for (other, b) in texts.iter().skip(i + 1) {
|
||||
assert!(!a.intersects(*b), "{at}: {text:?} overlaps {other:?}");
|
||||
}
|
||||
}
|
||||
// cut where it doesn't fit, and in full on hover
|
||||
let fits = width > 500.0;
|
||||
assert_eq!(texts.iter().any(|(t, _)| *t == cnt), fits, "{at}: {texts:?}");
|
||||
let cut = cnt.split(" von ").next().unwrap_or_default();
|
||||
assert!(fits || texts.iter().any(|(t, _)| t.ends_with('…') && t.starts_with(cut)), "{at}: the count is cut at its end: {texts:?}");
|
||||
let mut shown = Vec::new();
|
||||
for f in 3..120 {
|
||||
let events = if f == 3 { vec![egui::Event::PointerMoved(count.center())] } else { vec![] };
|
||||
(shown, _, _) = frame(f as f64 / 60.0, events);
|
||||
}
|
||||
assert!(shown.iter().any(|(t, _)| *t == cnt), "{at}: the full count shows on hover: {shown:?}");
|
||||
crate::i18n::set_language(Locale::En);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_bounds(shape: &egui::Shape, out: &mut Vec<Rect>) {
|
||||
match shape {
|
||||
egui::Shape::Text(text) => out.push(text.visual_bounding_rect()),
|
||||
|
||||
@@ -172,9 +172,9 @@ fn filter_button(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rec
|
||||
fn right_icons(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, full: Rect) -> f32 {
|
||||
// right icons
|
||||
let mut x = full.right() - 18.0;
|
||||
// saving is failing: the cloud icon turns into a warning until a save succeeds
|
||||
// saving is failing: a warning shows until a save succeeds (nothing is shown otherwise)
|
||||
let unsaved = app.session.unsaved().map(|(n, e)| unsaved_tip(n, e));
|
||||
let cloud_tip = unsaved.as_deref().unwrap_or("Local library — no cloud account needed");
|
||||
let cloud_tip = unsaved.as_deref().unwrap_or_default();
|
||||
// Import Photos… beside Export, always one click away, with the key it is bound to now
|
||||
let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac;
|
||||
let import_tip = match crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "file.addPhotos") {
|
||||
@@ -189,6 +189,10 @@ fn right_icons(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, full: Rec
|
||||
("import", Icon::Plus, import_tip.as_str(), "file.addPhotos"),
|
||||
("bell", Icon::Bell, "Activity", "panel.activity"),
|
||||
] {
|
||||
let warn = id == "cloud" && unsaved.is_some();
|
||||
if id == "cloud" && !warn {
|
||||
continue;
|
||||
}
|
||||
let r = Rect::from_center_size(pos2(x, full.center().y), vec2(28.0, 28.0));
|
||||
let tip = crate::i18n::tr(tip);
|
||||
let resp = ui.interact(r, egui::Id::unique(("top", id)), Sense::click());
|
||||
@@ -196,7 +200,6 @@ fn right_icons(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, full: Rec
|
||||
let resp = resp.on_hover_text(tip);
|
||||
crate::widgets::announce(&resp, name);
|
||||
register(ui, format!("icon:{id}"), r);
|
||||
let warn = id == "cloud" && unsaved.is_some();
|
||||
let colour = if warn {
|
||||
t.caution
|
||||
} else if resp.hovered() {
|
||||
|
||||
@@ -41,6 +41,7 @@ mod grid;
|
||||
mod grid_drag;
|
||||
mod guided_guides;
|
||||
mod histogram_drag;
|
||||
mod import_recipe;
|
||||
mod import_scan_note;
|
||||
mod import_thumbnails;
|
||||
mod info_dialogs;
|
||||
|
||||
@@ -69,3 +69,38 @@ fn alt_during_a_blacks_drag_shows_shadow_clipping_until_released() {
|
||||
let after = h.app.session.develop_of(h.app.session.active().expect("photo")).expect("develop").light.blacks;
|
||||
assert!(after < before, "the drag itself still moved Blacks: {before} → {after}");
|
||||
}
|
||||
|
||||
/// Share of the loupe render's pixels painted exactly `c`.
|
||||
fn share_of(h: &Headless, c: [u8; 3]) -> f64 {
|
||||
let t = h.app.renderer.textures.get(&crate::render::Slot::Main).expect("loupe render");
|
||||
let px = &t.pixels.as_ref().expect("pixels kept").pixels;
|
||||
let n = px.iter().filter(|p| [p.r(), p.g(), p.b()] == c).count();
|
||||
n as f64 / px.len().max(1) as f64
|
||||
}
|
||||
|
||||
/// Issue #3620: J (clipping warnings) paints the clipped pixels themselves, red where a channel
|
||||
/// is blown to white and blue where one is crushed to black, not just a frame around the photo.
|
||||
#[test]
|
||||
fn j_paints_clipped_highlights_red_and_clipped_shadows_blue() {
|
||||
let mut h = detail();
|
||||
let set = |h: &mut Headless, ev: f64| {
|
||||
let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.exposure", "value": ev}}), T);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
h.settle(SETTLE);
|
||||
};
|
||||
set(&mut h, 5.0);
|
||||
let (red, blue) = ([255, 0, 0], [0, 0, 255]);
|
||||
assert!(share_of(&h, red) < 0.1, "without J the blown photo is not painted red: {}", share_of(&h, red));
|
||||
let r = h.request("ui.key", json!({"key": "J"}), T);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
h.settle(SETTLE);
|
||||
assert!(h.app.ui.show_clipping);
|
||||
assert!(share_of(&h, red) > 0.5, "blown highlights shown in red: {}", share_of(&h, red));
|
||||
set(&mut h, -5.0);
|
||||
// the demo photo's shadows don't reach black on Exposure alone: Blacks crushes them
|
||||
let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.blacks", "value": -100.0}}), T);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
h.settle(SETTLE);
|
||||
assert!(share_of(&h, blue) > 0.01, "crushed shadows shown in blue: {}", share_of(&h, blue));
|
||||
assert!(share_of(&h, red) < 0.01, "nothing blown at -5 EV: {}", share_of(&h, red));
|
||||
}
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user