mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-28 09:19:25 +01:00
Merge branch 'main' into shared-settings
This commit is contained in:
689 files changed
+66931
-45038
No files matched your search
@@ -0,0 +1,78 @@
|
||||
name: CI (Windows)
|
||||
|
||||
# The Windows leg of the gate: clippy and the tests of the crates with Windows-only code, on pull
|
||||
# requests and pushes to main that touch that code, and on pull requests labelled `full-ci`.
|
||||
# The Linux gate (ci.yml) still runs everything else on every pull request.
|
||||
#
|
||||
# Not the full `cargo xtask ci`: on a cold windows-latest runner that is well over an hour, and
|
||||
# its wasm, layers, assets and parity steps don't differ by platform. What does is the
|
||||
# `cfg(windows)` code (title bar theme, monitor profiles, file handling) and its tests.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
# `labeled`: adding `full-ci` starts it. Other labels skip (see concurrency and the scope job).
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Its own group, so the Windows leg never cancels the Linux gate. A newer push to a PR branch
|
||||
# cancels its older run; a label other than `full-ci` gets a group of its own, so it cancels nothing.
|
||||
concurrency:
|
||||
group: ci-windows-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ github.event.action == 'labeled' && github.event.label.name != 'full-ci' && format('-label-{0}', github.run_id) || '' }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
windows-scope:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
uses: storytold/craft-common-actions/.github/workflows/changed-paths.yml@main
|
||||
with:
|
||||
label: full-ci
|
||||
# The crates and files with `cfg(windows)` code, and what decides how they build: their
|
||||
# manifests and the lockfile (a dependency bump can break only Windows).
|
||||
paths: |
|
||||
.github/workflows/ci-windows.yml
|
||||
apps/lightcraft/*
|
||||
apps/lightcraft-cli/src/bench_cull.rs
|
||||
apps/lightcraft-cli/tests/it/cli.rs
|
||||
apps/lightcraft-cli/Cargo.toml
|
||||
crates/wincolor/*
|
||||
crates/ui-egui/src/theme.rs
|
||||
crates/ui-egui/src/panels/left/local.rs
|
||||
crates/ui-egui/src/menus/files.rs
|
||||
crates/ui-egui/src/dialogs/settings/performance.rs
|
||||
crates/catalog/src/safe_file.rs
|
||||
crates/catalog/Cargo.toml
|
||||
crates/engine/src/originals.rs
|
||||
crates/engine/src/import/scan.rs
|
||||
crates/engine/src/walk.rs
|
||||
crates/engine/src/doc_path.rs
|
||||
crates/engine/src/rename/*
|
||||
crates/engine/src/cmd/geocode.rs
|
||||
crates/engine/src/tests/sync.rs
|
||||
crates/engine/src/tests/import.rs
|
||||
crates/engine/Cargo.toml
|
||||
crates/ui-egui/Cargo.toml
|
||||
Cargo.toml
|
||||
Cargo.lock
|
||||
rust-toolchain.toml
|
||||
.cargo/*
|
||||
|
||||
gate-windows:
|
||||
needs: windows-scope
|
||||
if: needs.windows-scope.outputs.matched == 'true'
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["windows-latest"]'
|
||||
# Same craft-fonts commit as ci.yml and release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
targets: ""
|
||||
tools: ""
|
||||
timeout-minutes: 90
|
||||
windows-command: |
|
||||
pkgs=(-p lightcraft-wincolor -p lightcraft-catalog -p lightcraft-engine -p lightcraft-ui-egui -p lightcraft -p lightcraft-cli)
|
||||
cargo clippy "${pkgs[@]}" --all-targets --keep-going -- -D warnings
|
||||
cargo test "${pkgs[@]}" --lib --bins --tests --no-fail-fast
|
||||
@@ -24,6 +24,9 @@ jobs:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
timeout-minutes: 90
|
||||
# A green run takes about 40 min. A hung test is stopped at 80 min, so the log lists the
|
||||
# processes still running and the leg fails as timed out instead of being cancelled at 90.
|
||||
gate-timeout-minutes: 80
|
||||
# xtask ci runs cargo test: the demo scene cache is per process, so nextest is slower here.
|
||||
tools: ""
|
||||
packages: >-
|
||||
|
||||
@@ -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
|
||||
@@ -19,42 +19,8 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main
|
||||
|
||||
nix:
|
||||
# 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.
|
||||
|
||||
@@ -28,10 +28,16 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# The suite's WiX (5.0.2); the install-folder test needs no extensions.
|
||||
- name: Install WiX
|
||||
shell: pwsh
|
||||
run: dotnet tool install --global wix --version 5.0.2
|
||||
uses: storytold/craft-common-actions/actions/install-wix@main
|
||||
with:
|
||||
install-extensions: "false"
|
||||
- name: Install-folder fallback and precedence (real MSI AppSearch)
|
||||
shell: pwsh
|
||||
run: |
|
||||
@@ -43,6 +49,10 @@ jobs:
|
||||
name: Windows installation policy (no app build)
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
# A nightly dry run on main: every release build except macOS, nothing signed or released
|
||||
# (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
|
||||
schedule:
|
||||
- cron: "4 2 * * *"
|
||||
push:
|
||||
branches: [release]
|
||||
workflow_dispatch:
|
||||
@@ -12,64 +16,37 @@ on:
|
||||
type: string
|
||||
default: ""
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
# Nothing by default; each job names what it needs. Only `release` writes (the draft GitHub Release
|
||||
# and its packages).
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
|
||||
credits:
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
pull-requests: read
|
||||
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
|
||||
|
||||
release:
|
||||
needs: git-sources
|
||||
needs: credits
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: lightcraft
|
||||
app-title: LightCraft
|
||||
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 }}
|
||||
@@ -85,3 +62,4 @@ jobs:
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
@@ -14,3 +14,6 @@ plan/
|
||||
# model weights are never committed (SAM 3: docs/ai-masks.md)
|
||||
*.safetensors
|
||||
*.safetensors.part
|
||||
|
||||
# Python tools import their public operator family.
|
||||
__pycache__/
|
||||
@@ -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 (bump each doc's *Last updated* line and revision history); `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).
|
||||
`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.
|
||||
`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).
|
||||
@@ -38,9 +89,10 @@ of it.
|
||||
"unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]`
|
||||
+ `.expect("why it can't fail")`.
|
||||
- **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed
|
||||
allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new
|
||||
unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe
|
||||
fallback where possible, and a line here naming it.
|
||||
allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile
|
||||
Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every
|
||||
other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper
|
||||
crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it.
|
||||
- **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or
|
||||
arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative
|
||||
casts to `usize`; cap allocations sized by input; slice strings only at char boundaries.
|
||||
@@ -49,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.
|
||||
@@ -81,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.
|
||||
@@ -98,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
|
||||
@@ -107,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`.
|
||||
@@ -120,9 +187,15 @@ 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
|
||||
passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with
|
||||
`#[ignore = "flaky: #<issue>"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its
|
||||
own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that
|
||||
hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under
|
||||
nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do.
|
||||
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
|
||||
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
|
||||
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
|
||||
@@ -154,4 +227,9 @@ evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the work
|
||||
## CI workflows
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- `ci.yml` is the Linux gate, on every pull request. `ci-windows.yml` adds a Windows leg (clippy and tests of the crates with `cfg(windows)` code) when a pull request changes the paths it lists; add the `full-ci` label to run it on any other pull request. When you add `cfg(windows)` code in a new file, add the file to its `paths` in a CI PR.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
|
||||
## Shared libraries
|
||||
|
||||
Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers.
|
||||
@@ -1,156 +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 (bump each doc's *Last updated* line and revision history); `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). Every other production crate root has `#![forbid(unsafe_code)]`. A new
|
||||
unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe
|
||||
fallback where possible, and a line here naming it.
|
||||
- **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/`.
|
||||
- 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.
|
||||
- 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
|
||||
Generated
+570
-118
File diff suppressed because it is too large.
Load diff
+36
-21
@@ -3,31 +3,58 @@ resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.17.0"
|
||||
version = "0.21.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/lightcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms-profile = { package = "craft-cms", git = "https://github.com/storytold/craft-libs", rev = "eeb134def2daa7e03512b4946bd59d6b419b9484" }
|
||||
craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bea6ed1ff031b81df2d64be470485c1ca808847e" }
|
||||
craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "0fd30aeb3e02207d9d4c7c601540d9da45abf8de", default-features = false, features = ["write-raster"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
|
||||
# Canon CRW decoder shared with the other Craft apps
|
||||
craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "2d4b8b8ecd79f87c847961901c40305e7f448d6f" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "7f30d664695cd5ce14fc30659d36c3e32f234247" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", version = "0.1.0" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67", features = ["frames"] }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "478c50560d3c6fad3d613af2a30b35c3bc9f4c0f", default-features = false, features = ["decode", "encode"] }
|
||||
jixel = "=0.3.4"
|
||||
# Photo metadata: EXIF, IPTC-IIM, XMP packets and GPX track logs (craft-libs#949)
|
||||
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "478c50560d3c6fad3d613af2a30b35c3bc9f4c0f" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" }
|
||||
craft-video = { git = "https://github.com/storytold/craft-libs", rev = "5c91598ccc86537a779f438d520fa6406c26efe6", features = ["av1", "av1-large-encode", "threads"] }
|
||||
# Isolate AVIF threading from the existing PNG/TIFF/WebP shared revision.
|
||||
craft-avif-encode = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a", default-features = false, features = ["avif", "threads"] }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2d4b8b8ecd79f87c847961901c40305e7f448d6f" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
|
||||
# HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904).
|
||||
craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" }
|
||||
# PSD/PSB: the header, colour mode data and image resources (craft-libs#885).
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "16d838105b07965832bb43132880176f299634d5" }
|
||||
jpeg-encoder = { version = "0.7", default-features = false, features = ["std"] }
|
||||
# internal
|
||||
lightcraft-denoise-core = { path = "crates/denoise-core" }
|
||||
lightcraft-denoise = { path = "crates/denoise", default-features = false }
|
||||
lightcraft-geom = { path = "crates/geom" }
|
||||
lightcraft-faces = { path = "crates/faces" }
|
||||
lightcraft-sysmem = { path = "crates/sysmem" }
|
||||
lightcraft-wincolor = { path = "crates/wincolor" }
|
||||
lightcraft-color = { path = "crates/color" }
|
||||
lightcraft-raster = { path = "crates/raster" }
|
||||
lightcraft-tiff = { path = "crates/tiff" }
|
||||
# TIFF/IFD: the shared reader and writer (moved from crates/tiff; craft-libs#783).
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" }
|
||||
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" }
|
||||
lightcraft-raw = { path = "crates/raw" }
|
||||
lightcraft-codecs = { path = "crates/codecs" }
|
||||
lightcraft-meta = { path = "crates/meta" }
|
||||
lightcraft-develop = { path = "crates/develop" }
|
||||
lightcraft-film = { path = "crates/film" }
|
||||
lightcraft-lensdb = { path = "crates/lensdb" }
|
||||
lightcraft-inpaint = { path = "crates/inpaint" }
|
||||
lightcraft-scenes = { path = "crates/scenes" }
|
||||
@@ -40,7 +67,8 @@ lightcraft-engine = { path = "crates/engine" }
|
||||
lightcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
lightcraft-mcp = { path = "crates/mcp" }
|
||||
lightcraft-fetch = { path = "crates/fetch" }
|
||||
lightcraft-heif = { path = "crates/heif" }
|
||||
# HEIC/HEIF: the shared decoder (moved from crates/heif; craft-libs#784).
|
||||
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "4ffa307f1a0a6fbd8897318cc719440ab06e9c63", default-features = false }
|
||||
lightcraft-segment = { path = "crates/segment" }
|
||||
lightcraft-geocode = { path = "crates/geocode" }
|
||||
lightcraft-slideshow = { path = "crates/slideshow" }
|
||||
@@ -55,36 +83,23 @@ log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
rayon = "1"
|
||||
# free/total space of a drive (engine's low-disk alert); MIT OR Apache-2.0, pure Rust (rustix / windows-sys)
|
||||
fs4 = { version = "1.1", default-features = false }
|
||||
winapi-util = "0.1" # lightcraft-catalog reads a file's volume serial number and file index with it on Windows
|
||||
proptest = "1"
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
crc32fast = "1"
|
||||
siphasher = "1"
|
||||
libm = "0.2" # pure-Rust maths for lightcraft-film (target-independent results)
|
||||
libc = "0.2" # dev-only: process CPU time in benches
|
||||
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
|
||||
|
||||
# formats
|
||||
quick-xml = "0.41"
|
||||
miniz_oxide = "0.9"
|
||||
|
||||
# codecs
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "webp"] }
|
||||
zune-jpeg = { version = "0.5", default-features = false, features = ["std", "x86", "neon"] }
|
||||
zune-core = { version = "0.5", default-features = false, features = ["std"] }
|
||||
jpeg-decoder = { version = "0.3", default-features = false }
|
||||
jpeg-encoder = { version = "0.7", default-features = false, features = ["std"] }
|
||||
ab_glyph = { version = "0.2", default-features = false, features = ["std"] } # Apache-2.0, pure Rust glyph rasterizer (export watermarks)
|
||||
png = "0.18"
|
||||
tiff = "0.11"
|
||||
image-webp = "0.2"
|
||||
moxcms = { version = "0.9", default-features = false, features = ["lut"] }
|
||||
jxl-oxide = { version = "0.12", default-features = false }
|
||||
jixel = "=0.3.4" # BSD-3-Clause OR Apache-2.0, pure-Rust JPEG XL encoder (export; port of libjxl-tiny)
|
||||
zune-jpegxl = { version = "0.5", default-features = false, features = ["std"] } # MIT/Apache-2.0/Zlib lossless JXL encoder (test fixtures only)
|
||||
ravif = { version = "0.13", default-features = false, features = ["threading"] } # no "asm": it needs nasm (non-Rust)
|
||||
# HDR AVIF (PQ): ravif fixes the sRGB transfer curve, so HDR files drive its rav1e + avif-serialize directly
|
||||
rav1e = { version = "0.8.1", default-features = false, features = ["threading"] }
|
||||
avif-serialize = "0.8.6"
|
||||
|
||||
# gpu (crates/gpu; native backends only, no GL: everything stays pure Rust)
|
||||
# SAM 3 inference (lightcraft-segment). 0.9.2: later releases pull `tokenizers` with the
|
||||
@@ -169,12 +184,12 @@ lightcraft-color = { opt-level = 3 }
|
||||
lightcraft-develop = { opt-level = 3 }
|
||||
lightcraft-geom = { opt-level = 3 }
|
||||
lightcraft-raw = { opt-level = 3 }
|
||||
craft-raw = { opt-level = 3 }
|
||||
lightcraft-codecs = { opt-level = 3 }
|
||||
lightcraft-scenes = { opt-level = 3 }
|
||||
lightcraft-preview = { opt-level = 3 }
|
||||
zune-jpeg = { opt-level = 3 }
|
||||
zune-core = { opt-level = 3 }
|
||||
jpeg-decoder = { opt-level = 3 }
|
||||
jpeg-encoder = { opt-level = 3 }
|
||||
png = { opt-level = 3 }
|
||||
miniz_oxide = { opt-level = 3 }
|
||||
|
||||
@@ -335,3 +335,133 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
JPEG encoding
|
||||
-------------
|
||||
|
||||
The shared JPEG writer includes the following third-party encoder notice. The Apache-2.0
|
||||
alternative referred to below is also included in this distribution as LICENSE-APACHE.
|
||||
|
||||
JPEG encoding dependency: jpeg-encoder 0.6.1
|
||||
|
||||
Source: https://crates.io/crates/jpeg-encoder/0.6.1
|
||||
Declared license: (MIT OR Apache-2.0) AND IJG.
|
||||
This software is based in part on the work of the Independent JPEG Group.
|
||||
|
||||
The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0
|
||||
alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root
|
||||
(https://github.com/storytold/craft-libs/tree/main/licenses/jpeg-encoder-0.6.1).
|
||||
The dependency is used unmodified; no encoder implementation is vendored here.
|
||||
|
||||
LICENSE-MIT
|
||||
|
||||
Copyright (c) 2021 Volker Ströbel <volkerstroebel@mysurdity.de>
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
Original src/fdct.rs opening notice
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg to rust
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1991-1996, Thomas G. Lane.
|
||||
* libjpeg-turbo Modifications:
|
||||
* Copyright (C) 2015, 2020, D. R. Commander.
|
||||
*
|
||||
* Conditions of distribution and use:
|
||||
* In plain English:
|
||||
*
|
||||
* 1. We don't promise that this software works. (But if you find any bugs,
|
||||
* please let us know!)
|
||||
* 2. You can use this software for whatever you want. You don't have to pay us.
|
||||
* 3. You may not pretend that you wrote this software. If you use it in a
|
||||
* program, you must acknowledge somewhere in your documentation that
|
||||
* you've used the IJG code.
|
||||
*
|
||||
* In legalese:
|
||||
*
|
||||
* The authors make NO WARRANTY or representation, either express or implied,
|
||||
* with respect to this software, its quality, accuracy, merchantability, or
|
||||
* fitness for a particular purpose. This software is provided "AS IS", and you,
|
||||
* its user, assume the entire risk as to its quality and accuracy.
|
||||
*
|
||||
* This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
|
||||
* All Rights Reserved except as specified below.
|
||||
*
|
||||
* Permission is hereby granted to use, copy, modify, and distribute this
|
||||
* software (or portions thereof) for any purpose, without fee, subject to these
|
||||
* conditions:
|
||||
* (1) If any part of the source code for this software is distributed, then this
|
||||
* README file must be included, with this copyright and no-warranty notice
|
||||
* unaltered; and any additions, deletions, or changes to the original files
|
||||
* must be clearly indicated in accompanying documentation.
|
||||
* (2) If only executable code is distributed, then the accompanying
|
||||
* documentation must state that "this software is based in part on the work of
|
||||
* the Independent JPEG Group".
|
||||
* (3) Permission for use of this software is granted only if the user accepts
|
||||
* full responsibility for any undesirable consequences; the authors accept
|
||||
* NO LIABILITY for damages of any kind.
|
||||
*
|
||||
* These conditions apply to any software derived from or based on the IJG code,
|
||||
* not just to the unmodified library. If you use our work, you ought to
|
||||
* acknowledge us.
|
||||
*
|
||||
* Permission is NOT granted for the use of any IJG author's name or company name
|
||||
* in advertising or publicity relating to this software or products derived from
|
||||
* it. This software may be referred to only as "the Independent JPEG Group's
|
||||
* software".
|
||||
*
|
||||
* We specifically permit and encourage the use of this software as the basis of
|
||||
* commercial products, provided that all warranty or liability claims are
|
||||
* assumed by the product vendor.
|
||||
*
|
||||
* This file contains a slower but more accurate integer implementation of the
|
||||
* forward DCT (Discrete Cosine Transform).
|
||||
*
|
||||
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
|
||||
* on each column. Direct algorithms are also available, but they are
|
||||
* much more complex and seem not to be any faster when reduced to code.
|
||||
*
|
||||
* This implementation is based on an algorithm described in
|
||||
* C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
|
||||
* Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
|
||||
* Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
|
||||
* The primary algorithm described there uses 11 multiplies and 29 adds.
|
||||
* We use their alternate method with 12 multiplies and 32 adds.
|
||||
* The advantage of this method is that no data path contains more than one
|
||||
* multiplication; this allows a very simple and accurate implementation in
|
||||
* scaled fixed-point arithmetic, with a minimal number of shifts.
|
||||
*/
|
||||
|
||||
Original src/avx2/fdct.rs opening notice
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg / jfdctint-avx2.asm to rust
|
||||
* Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
|
||||
* Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander.
|
||||
*
|
||||
* Based on the x86 SIMD extension for IJG JPEG library
|
||||
* Copyright (C) 1999-2006, MIYASAKA Masaru.
|
||||
*/
|
||||
@@ -349,8 +349,8 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
|
||||
casual use.** It's great for JPEG/DNG and most Sony / Panasonic /
|
||||
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 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix;
|
||||
- **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
|
||||
- **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 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);
|
||||
|
||||
+21
-10
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~14 points and ~340–600 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; the lens profile database priority links its tracking issue #329; Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
|
||||
> **Last reviewed:** 2026-11-15 · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 · **Changes:** [revision history](#revision-history)
|
||||
|
||||
One-page summary of how close LightCraft is to Adobe Lightroom. Agents: read this, then pick work
|
||||
from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are in
|
||||
@@ -14,25 +14,25 @@ from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are
|
||||
|---|---:|---|
|
||||
| **Feature breadth** (checklist) | **81.6%** of 532 rows (P0 98.0%, P1 95.2%, P2 50.0%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount |
|
||||
| **Feature breadth** (weighted by use) | **~77%** | estimated |
|
||||
| **Ready for real work** (full target) | **~61%** (56–66%) | estimated: weighted sum over the dimensions |
|
||||
| **Ready for real work** (full target) | **~62%** (57–67%) | estimated: weighted sum over the dimensions |
|
||||
| **Mainstream practitioner** | **~51%** (46–56%) | estimated |
|
||||
| **Essentials user** | **~65%** (60–70%) | estimated |
|
||||
| Remaining to **beta** | **~340–600 h** (Opus 5.5 agent hours, ~60% parallel) | estimated |
|
||||
| Remaining to **full parity** | **~1,000–1,800 h** (~70% parallel) | estimated |
|
||||
| Remaining to **full parity** | **~980–1,750 h** (~70% parallel) | estimated |
|
||||
|
||||
Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%):
|
||||
|
||||
| Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates |
|
||||
|---|---:|---:|---|
|
||||
| Full target (ready for real work) | **~61%** | **1,000–1,800 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem |
|
||||
| Mainstream practitioner | **~51%** | **450–840 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability |
|
||||
| Full target (ready for real work) | **~62%** | **980–1,750 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem |
|
||||
| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability |
|
||||
| Essentials user | **~65%** | **160–300 h** (~50% parallelizes) | default raw look for popular cameras; launch stability; basic-slider feel; opening CR3 / HEIC files people send |
|
||||
|
||||
The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is
|
||||
estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), compressed ORF and HE NEF
|
||||
open as previews, rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
|
||||
estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens
|
||||
as preview, 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 blocking gaps (compressed ORF and HE NEF open as previews; Canon,
|
||||
the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have gaps (Nikon HE NEF opens as preview; Canon,
|
||||
~30% of raw users, decodes CR3 on 26 verified bodies). It passes the alpha gate: all six core workflows
|
||||
(import, cull, develop, save and reopen, batch looks, export) work end to end on macOS
|
||||
([docs/roadmap.md](docs/roadmap.md#alpha-gate)). The three readiness numbers and their weights and discounts are in
|
||||
@@ -45,7 +45,7 @@ Hours are calibrated on this repo's PR history; see
|
||||
| Dimension | Ready | Breadth | Remaining | Doc |
|
||||
|---|---:|---:|---:|---|
|
||||
| Features | ~61% | ~77% (checklist 81.1%) | 600–1,100 h | [target-app-parity](docs/target-app-parity.md#features) |
|
||||
| ↳ RAW cameras, colour, lens profiles | ~60% | 83% of 1,446 Adobe models decode, 38% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
|
||||
| ↳ RAW cameras, colour, lens profiles | ~60% | 85% of 1,446 Adobe models decode, 39% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
|
||||
| UI/UX fidelity | ~70% | ~85% | 32–54 h | [ui-parity](docs/ui-parity.md) |
|
||||
| File formats (non-raw) | ~70% | ~85% | 30–55 h | [file-format-parity](docs/file-format-parity.md) |
|
||||
| Hardware | ~40% | ~50% | 40–80 h | [hardware-parity](docs/hardware-parity.md) |
|
||||
@@ -107,18 +107,27 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
|
||||
3. Render-fidelity suite against Lightroom, then tuning (30–60 h)
|
||||
4. ~~Full-resolution zoom~~ (done 2026-10-12)
|
||||
5. AI masks: Subject / Sky / People (40–70 h + model decision)
|
||||
6. Compressed ORF and HE NEF (28–55 h)
|
||||
6. Compressed ORF (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-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
|
||||
and `print.set` take their customary names, and names are matched case-, space- and
|
||||
punctuation-insensitively (`L判`, `l`, `L-size` are one paper).
|
||||
- 2026-10-13: Canon CRW (the 2000–2004 CIFF bodies) decodes from sensor data: compression
|
||||
derived clean-room against a black-box reference and frozen (`craft-libs crates/crw/clean-room/02-crw-format.md`);
|
||||
EOS D30/D60/10D/300D and PowerShot G1/G6 verified pixel-exact on 28 of 29 corpus files (18 of
|
||||
them the maintainer's D60 shots); as-shot white balance, black level, rotation and capture time
|
||||
from the CIFF records; the PowerShot G5's anomalous coding stays preview-only. With the
|
||||
camera-coverage sweep and MRW merged, 557 models verified; Canon bucket 95% → 98%.
|
||||
- 2026-10-14: Camera-coverage sweep verifies 30 more models on 40 CC0 files, with file and sensor
|
||||
hashes pinned (`docs/raw/coverage.py`: 515 → 545 verified). Eleven candidates excluded after rechecking
|
||||
identity, provenance and camera-image agreement. Phone and drone DNG tone differences remain tracked in #1277.
|
||||
@@ -190,10 +199,12 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | minor | Lens Blur with AI subject focus and per-mask bokeh; survey tiles fit the photos' shapes and glide to their new places; direct import of Lightroom backup zips (#2592); legacy shutter repair in virtual copies; the opened-library folder-safety fix; v0.21.0 and v0.21.1 released; craft-libs cutover for TIFF/JPEG/JXL/GIF/PSD/HEIF/raw, metadata and gain maps, plus a security-hardening batch; headline numbers not re-measured |
|
||||
| 2026-10-24 | minor | Priority 7 (lens profile database) links its tracking issue #329; headline numbers unchanged |
|
||||
| 2026-10-24 | patch | Alpha rationale: tests run in CI on Linux x64 (#2667) and FreeBSD nightly, not on macOS or Windows; ranked item 8 now reads "Tests in CI on macOS and Windows, and the GPU tests in CI"; percentages and hours unchanged |
|
||||
| 2026-10-22 | minor | Print: Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) in the page setup, Print dialog and PDF output; headline numbers unchanged |
|
||||
| 2026-10-19 | minor | Indonesian interface (`id`): every plain and formats message, plus 69 command labels, locale, menu command and tests; What's New left in English; Localization ~55% → ~64% (mean of the 12 key languages), 8 of 12 present |
|
||||
| 2026-10-13 | minor | Canon CRW decoded (clean-room): 6 bodies verified pixel-exact, G5 preview; 551 models verified after merging the coverage sweep |
|
||||
| 2026-10-12 | minor | Italian interface (`it`, #1192): 2,201 of 2,398 messages, locale, menu command and tests; headline numbers unchanged |
|
||||
| 2026-10-13 | minor | Sony ILCA-99M2 camera colour profile in the log; numbers unchanged |
|
||||
| 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled |
|
||||
|
||||
@@ -37,6 +37,6 @@ rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"]
|
||||
# (open it in DHAT's viewer: allocation sites by bytes at the peak). Slows allocation-heavy work.
|
||||
dhat-heap = ["dep:dhat"]
|
||||
|
||||
# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it (HEVC patents); build with `--features heif` to include it.
|
||||
heif = ["lightcraft-codecs/heif"]
|
||||
@@ -0,0 +1,585 @@
|
||||
//! `lightcraft-cli bench-cull FOLDER`: time what culling a shoot costs, headless, on real files.
|
||||
//!
|
||||
//! What a wedding photographer does most is open a folder of a few thousand raws, look at each
|
||||
//! one, rate it and move on. This times the engine side of each step on the files themselves (the
|
||||
//! desktop app's own frame timings come from `ui.inspect` → `perf.loupeSteps`, see
|
||||
//! `tools/cull-bench.py`):
|
||||
//!
|
||||
//! - browse: reading the folder into the Local view (`library.browse`, the whole folder);
|
||||
//! - grid thumbnails: the camera JPEG at 512 px for the first screen, on as many threads as the
|
||||
//! app renders with;
|
||||
//! - camera preview at loupe sizes (1280, 2560) and at full size (the 100 % view), one at a time;
|
||||
//! - LightCraft's render of the loupe (2560 px) from a cold source;
|
||||
//! - rating: `photo.rate` on many photos in a row, journal included;
|
||||
//! - import: adding N files in place to a fresh library, and copying M of them into it (`--n 0`:
|
||||
//! no import).
|
||||
//!
|
||||
//! `--files K` reads only the first K files (by name) of the folder, as browsing reads them: a
|
||||
//! sample of a folder on a network share, where reading thousands of raws takes hours.
|
||||
//!
|
||||
//! Each number is printed as `name: X ms wall` (median, with p95 and n), the format
|
||||
//! `cargo xtask bench` parses, and the lot as one JSON object with `--json FILE`. Nothing is
|
||||
//! written next to the photos: every library is made in a new folder of the run's own under
|
||||
//! `--work` (default: a folder in the system temp directory; nothing already there is deleted),
|
||||
//! XMP auto-write stays off, and the source folder is only read.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use lightcraft_engine::Session;
|
||||
use lightcraft_engine::catalog::PhotoId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const USAGE: &str = "lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]";
|
||||
|
||||
/// Threads the app renders thumbnails with (`Renderer::default`: cores − 1, at most 6).
|
||||
fn render_threads() -> usize {
|
||||
std::thread::available_parallelism().map(|n| n.get().saturating_sub(1)).unwrap_or(2).clamp(2, 6)
|
||||
}
|
||||
|
||||
/// Median, p95 and count of `ms` (milliseconds).
|
||||
fn stats(ms: &[f64]) -> Value {
|
||||
if ms.is_empty() {
|
||||
return Value::Null;
|
||||
}
|
||||
let mut v = ms.to_vec();
|
||||
v.sort_by(f64::total_cmp);
|
||||
let at = |q: f64| v.get(((v.len() - 1) as f64 * q).round() as usize).copied().unwrap_or(0.0);
|
||||
json!({"p50": round(at(0.5)), "p95": round(at(0.95)), "max": round(at(1.0)), "n": v.len()})
|
||||
}
|
||||
|
||||
fn round(x: f64) -> f64 {
|
||||
(x * 10.0).round() / 10.0
|
||||
}
|
||||
|
||||
fn ms_since(t: Instant) -> f64 {
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// Print one result line the way `xtask bench` parses it (`name: X ms wall`).
|
||||
fn line(name: &str, s: &Value) {
|
||||
if let Some(p50) = s.get("p50").and_then(Value::as_f64) {
|
||||
println!("{name}: {p50:.1} ms wall (p95 {} ms, n {})", s["p95"], s["n"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, empty folder `name` in this run's own folder; never deletes anything already there.
|
||||
fn fresh_dir(root: &Path, name: &str) -> Result<PathBuf, String> {
|
||||
let d = root.join(name);
|
||||
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// A folder of this run's own under `work`, which must not exist yet: a run never deletes or
|
||||
/// reuses what is already under `--work`.
|
||||
fn run_dir(work: &Path) -> Result<PathBuf, String> {
|
||||
std::fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?;
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
|
||||
static RUNS: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = RUNS.fetch_add(1, Ordering::Relaxed);
|
||||
let d = work.join(format!("bench-cull-run-{}-{stamp}-{n}", std::process::id()));
|
||||
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// `take` items of `v` after the first `skip` (photos the stages before have read, so cold in the
|
||||
/// file cache), or, when `v` has no more than `skip`, its first `take`: a small folder is measured
|
||||
/// on photos already read rather than not at all.
|
||||
fn sample_after<T>(v: &[T], skip: usize, take: usize) -> &[T] {
|
||||
let from = if v.len() > skip { skip } else { 0 };
|
||||
let rest = v.get(from..).unwrap_or_default();
|
||||
rest.get(..take.min(rest.len())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether `path` names a file in `folder` (the source folder, which a run only reads), checked
|
||||
/// twice: where its own entry sits (the folder holding it, the final link not followed: writing the
|
||||
/// results replaces that entry, so a link to a file elsewhere that sits in the source folder, maybe
|
||||
/// standing for a photo, would be replaced; CodeRabbit on #3080), and where it resolves to: a file
|
||||
/// that is there by itself (a link to a photo there is the photo), a link that points nowhere yet
|
||||
/// by where writing through it would create the file, and anything else by its nearest folder that
|
||||
/// exists (a `--work` folder may not be there yet).
|
||||
fn inside_source(path: &Path, folder: &Path) -> bool {
|
||||
let Ok(folder) = std::fs::canonicalize(folder) else { return false };
|
||||
entry_inside(path, &folder) || resolves_inside(path, &folder, 0)
|
||||
}
|
||||
|
||||
/// Whether the folder holding `path`'s own entry (its nearest folder that exists, resolved) is in
|
||||
/// `folder` (already resolved). The entry itself is not followed.
|
||||
fn entry_inside(path: &Path, folder: &Path) -> bool {
|
||||
let mut p = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
loop {
|
||||
if let Ok(c) = std::fs::canonicalize(p) {
|
||||
return c.starts_with(folder);
|
||||
}
|
||||
match p.parent() {
|
||||
Some(up) if !up.as_os_str().is_empty() => p = up,
|
||||
Some(_) => p = Path::new("."),
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`inside_source`] for a `folder` already resolved; `hops`: links followed so far (a loop of
|
||||
/// links counts as inside: refused).
|
||||
fn resolves_inside(path: &Path, folder: &Path, hops: u32) -> bool {
|
||||
if let Ok(c) = std::fs::canonicalize(path) {
|
||||
return c.starts_with(folder);
|
||||
}
|
||||
if let Ok(target) = std::fs::read_link(path) {
|
||||
if hops >= 40 {
|
||||
return true;
|
||||
}
|
||||
let target = path.parent().map_or_else(|| target.clone(), |dir| dir.join(&target));
|
||||
return resolves_inside(&target, folder, hops + 1);
|
||||
}
|
||||
entry_inside(path, folder)
|
||||
}
|
||||
|
||||
/// Refuse `--json` or `--work` in the folder being measured: nothing is written next to the photos,
|
||||
/// the results and the run's libraries included. Checked before anything is made.
|
||||
fn check_outputs(folder: &Path, json: Option<&Path>, work: &Path) -> Result<(), String> {
|
||||
// a `..` after a folder not made yet can't be resolved now, and the run makes that folder:
|
||||
// `--json NEW/../FOLDER/r.json` would pass the checks below and land in the source folder
|
||||
// (CodeRabbit on #3544)
|
||||
for (name, p) in [("--json", json), ("--work", Some(work))] {
|
||||
if let Some(p) = p.filter(|p| p.components().any(|c| c == std::path::Component::ParentDir)) {
|
||||
return Err(format!("{}: {name} must not contain \"..\"; give the folder without it", p.display()));
|
||||
}
|
||||
}
|
||||
if let Some(j) = json.filter(|j| inside_source(j, folder)) {
|
||||
return Err(format!("{}: --json must not be in the folder being measured", j.display()));
|
||||
}
|
||||
if inside_source(&work.join("run"), folder) {
|
||||
return Err(format!("{}: --work must not be in the folder being measured", work.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn library(dir: &Path) -> Result<Session, String> {
|
||||
let mut s = Session::new().with_fs().with_system_clock();
|
||||
s.open_library(dir, false).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
// nothing is ever written next to the photos
|
||||
s.execute("library.xmpPreferences", &json!({"autoWrite": false})).map_err(|e| e.to_string())?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
let mut folder = None;
|
||||
let mut n = 2000usize;
|
||||
let mut copy = 200usize;
|
||||
let mut work = None;
|
||||
let mut json_out = None;
|
||||
let mut files = None;
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let value = |i: usize| args.get(i + 1).cloned().ok_or_else(|| format!("{} needs a value\n{USAGE}", args[i]));
|
||||
match args[i].as_str() {
|
||||
"--n" => {
|
||||
n = value(i)?.parse().map_err(|_| "--n needs a number".to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
"--copy" => {
|
||||
copy = value(i)?.parse().map_err(|_| "--copy needs a number".to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
"--files" => {
|
||||
files = Some(value(i)?.parse::<usize>().map_err(|_| "--files needs a number".to_string())?);
|
||||
i += 1;
|
||||
}
|
||||
"--work" => {
|
||||
work = Some(PathBuf::from(value(i)?));
|
||||
i += 1;
|
||||
}
|
||||
"--json" => {
|
||||
json_out = Some(PathBuf::from(value(i)?));
|
||||
i += 1;
|
||||
}
|
||||
"-h" | "--help" => {
|
||||
println!("{USAGE}");
|
||||
return Ok(());
|
||||
}
|
||||
a if a.starts_with("--") => return Err(format!("unknown option {a}\n{USAGE}")),
|
||||
// (a second folder would replace the first and be timed in its place: CodeRabbit on #3583)
|
||||
a if folder.is_some() => return Err(format!("{a}: one FOLDER only\n{USAGE}")),
|
||||
a => folder = Some(PathBuf::from(a)),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let folder = folder.ok_or_else(|| USAGE.to_string())?;
|
||||
if !folder.is_dir() {
|
||||
return Err(format!("{}: not a folder", folder.display()));
|
||||
}
|
||||
let work = work.unwrap_or_else(|| std::env::temp_dir().join(format!("lightcraft-bench-cull-{}", std::process::id())));
|
||||
check_outputs(&folder, json_out.as_deref(), &work)?;
|
||||
let work = run_dir(&work)?;
|
||||
let mut out = json!({"folder": folder.display().to_string(), "threads": render_threads()});
|
||||
|
||||
// --- browse: the whole folder into the Local view -------------------------------------------
|
||||
let mut s = library(&fresh_dir(&work, "lib-browse")?)?;
|
||||
// `--files K`: only the first K files by name, read as browsing reads them (a sample of a slow
|
||||
// network folder)
|
||||
let t = Instant::now();
|
||||
let (photos, ids): (u64, Vec<PhotoId>) = match files {
|
||||
None => {
|
||||
let r = s.execute("library.browse", &json!({"path": folder.display().to_string()})).map_err(|e| e.to_string())?;
|
||||
(r["photos"].as_u64().unwrap_or(0), s.visible_cloned())
|
||||
}
|
||||
Some(k) => {
|
||||
let mut list: Vec<String> = std::fs::read_dir(&folder)
|
||||
.map_err(|e| format!("{}: {e}", folder.display()))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_file() && lightcraft_engine::import::is_supported(p))
|
||||
.map(|p| p.display().to_string())
|
||||
.collect();
|
||||
list.sort();
|
||||
list.truncate(k);
|
||||
let r = s.execute("library.import", &json!({"paths": list, "mode": "add", "local": true})).map_err(|e| e.to_string())?;
|
||||
let ids: Vec<PhotoId> = r["imported"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(PhotoId).collect();
|
||||
(ids.len() as u64, ids)
|
||||
}
|
||||
};
|
||||
let browse_ms = ms_since(t);
|
||||
let what = if files.is_some() { "first files" } else { "whole folder" };
|
||||
println!("browse {photos} photos ({what}): {browse_ms:.1} ms wall");
|
||||
out["browse"] = json!({"ms": round(browse_ms), "photos": photos, "perPhotoMs": round(browse_ms / photos.max(1) as f64)});
|
||||
let paths: Vec<String> = ids
|
||||
.iter()
|
||||
.filter_map(|id| match &s.catalog.photo(*id)?.source {
|
||||
lightcraft_engine::catalog::Source::File { path } => Some(path.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if paths.is_empty() {
|
||||
return Err(format!("{}: no photos", folder.display()));
|
||||
}
|
||||
let loader = s.media.preview_loader.clone().ok_or("no preview loader")?;
|
||||
|
||||
// --- grid thumbnails: the first screen, in parallel ------------------------------------------
|
||||
let screen: Vec<String> = paths.iter().take(48).cloned().collect();
|
||||
let next = Arc::new(AtomicUsize::new(0));
|
||||
let t = Instant::now();
|
||||
let per: Vec<(f64, f64)> = std::thread::scope(|sc| {
|
||||
let workers: Vec<_> = (0..render_threads())
|
||||
.map(|_| {
|
||||
let (next, loader, screen) = (next.clone(), loader.clone(), &screen);
|
||||
sc.spawn(move || {
|
||||
let mut done = Vec::new();
|
||||
while let Some(p) = screen.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
let a = Instant::now();
|
||||
let _ = loader(p, 512);
|
||||
done.push((ms_since(a), ms_since(t)));
|
||||
}
|
||||
done
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect()
|
||||
});
|
||||
let first = per.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
|
||||
let all = per.iter().map(|p| p.1).fold(0.0, f64::max);
|
||||
let each = stats(&per.iter().map(|p| p.0).collect::<Vec<_>>());
|
||||
println!("grid: first thumbnail: {first:.1} ms wall");
|
||||
println!("grid: {} thumbnails: {all:.1} ms wall", per.len());
|
||||
line("grid: one 512 px thumbnail", &each);
|
||||
out["thumbs"] = json!({"firstMs": round(first), "allMs": round(all), "count": per.len(), "each": each});
|
||||
|
||||
// --- camera previews at loupe sizes, one at a time (what a step costs without look-ahead) -----
|
||||
let sample = sample_after(&paths, 48, 20);
|
||||
for edge in [1280usize, 2560, usize::MAX] {
|
||||
let ms: Vec<f64> = sample
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let a = Instant::now();
|
||||
let _ = loader(p, edge);
|
||||
ms_since(a)
|
||||
})
|
||||
.collect();
|
||||
let name = if edge == usize::MAX { "camera preview full size (100 %)".to_string() } else { format!("camera preview {edge} px") };
|
||||
let st = stats(&ms);
|
||||
line(&name, &st);
|
||||
out[if edge == usize::MAX { "cameraFull".to_string() } else { format!("camera{edge}") }] = st;
|
||||
}
|
||||
|
||||
// --- LightCraft's loupe render (2560 px) from a cold source --------------------------------
|
||||
let ms: Vec<f64> = sample_after(&ids, 80, 5)
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let job = s.loupe_job(*id, 2560, 1708, true)?;
|
||||
let a = Instant::now();
|
||||
let r = job.run();
|
||||
let t = ms_since(a);
|
||||
r.rendered.is_ok().then_some(t)
|
||||
})
|
||||
.collect();
|
||||
let st = stats(&ms);
|
||||
line("loupe render 2560 px (cold)", &st);
|
||||
out["loupeRender"] = st;
|
||||
|
||||
// --- rating: a culling pass of keypresses ---------------------------------------------------
|
||||
let ms: Vec<f64> = ids
|
||||
.iter()
|
||||
.take(50)
|
||||
.enumerate()
|
||||
.filter_map(|(k, id)| {
|
||||
// the key acts on the selected photo, as in the loupe
|
||||
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).ok()?;
|
||||
let a = Instant::now();
|
||||
s.execute("photo.rate", &json!({"rating": (k % 5) + 1})).ok()?;
|
||||
Some(ms_since(a))
|
||||
})
|
||||
.collect();
|
||||
let st = stats(&ms);
|
||||
line("rate one photo (journal written)", &st);
|
||||
out["rate"] = st;
|
||||
drop(s);
|
||||
|
||||
// --- import: add in place, then copy ----------------------------------------------------------
|
||||
if n == 0 {
|
||||
return finish(out, json_out);
|
||||
}
|
||||
let add: Vec<String> = paths.iter().take(n).cloned().collect();
|
||||
let mut s = library(&fresh_dir(&work, "lib-add")?)?;
|
||||
let t = Instant::now();
|
||||
let r = s.execute("library.import", &json!({"paths": add, "mode": "add"})).map_err(|e| e.to_string())?;
|
||||
let add_ms = ms_since(t);
|
||||
let added = r["imported"].as_array().map(Vec::len).unwrap_or(0);
|
||||
println!("import {added} photos in place: {add_ms:.1} ms wall");
|
||||
out["importAdd"] = json!({"ms": round(add_ms), "photos": added, "perPhotoMs": round(add_ms / added.max(1) as f64)});
|
||||
drop(s);
|
||||
if copy > 0 {
|
||||
let some: Vec<String> = paths.iter().take(copy).cloned().collect();
|
||||
let lib = fresh_dir(&work, "lib-copy")?;
|
||||
let mut s = library(&lib)?;
|
||||
let t = Instant::now();
|
||||
let r = s
|
||||
.execute("library.import", &json!({"paths": some, "mode": "copy", "destination": lib.join("Originals").display().to_string()}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let copy_ms = ms_since(t);
|
||||
let copied = r["imported"].as_array().map(Vec::len).unwrap_or(0);
|
||||
println!("import {copied} photos by copying: {copy_ms:.1} ms wall");
|
||||
out["importCopy"] = json!({"ms": round(copy_ms), "photos": copied, "perPhotoMs": round(copy_ms / copied.max(1) as f64)});
|
||||
drop(s);
|
||||
let _ = std::fs::remove_dir_all(&lib);
|
||||
}
|
||||
finish(out, json_out)
|
||||
}
|
||||
|
||||
fn finish(out: Value, json_out: Option<PathBuf>) -> Result<(), String> {
|
||||
if let Some(p) = json_out {
|
||||
write_replacing(&p, serde_json::to_string_pretty(&out).unwrap_or_default().as_bytes())?;
|
||||
}
|
||||
println!("{}", serde_json::to_string(&out).unwrap_or_default());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` through a new file next to it, renamed over `path`: an existing `path`
|
||||
/// is replaced as a name, never written into. A hard link there shares its data with another file
|
||||
/// (maybe a photo in the source folder, which [`inside_source`] can't tell), and writing into it
|
||||
/// would overwrite that file too (CodeRabbit on #3077). The temporary file is removed on error.
|
||||
fn write_replacing(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
use std::io::Write;
|
||||
let err = |e: std::io::Error| format!("{}: {e}", path.display());
|
||||
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
let name = path.file_name().ok_or_else(|| format!("{}: not a file name", path.display()))?;
|
||||
static TEMPS: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = TEMPS.fetch_add(1, Ordering::Relaxed);
|
||||
let mut tmp_name = std::ffi::OsString::from(".");
|
||||
tmp_name.push(name);
|
||||
tmp_name.push(format!(".{}-{n}.tmp", std::process::id()));
|
||||
let tmp = dir.join(tmp_name);
|
||||
let written =
|
||||
std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|()| f.sync_all()));
|
||||
if let Err(e) = written.and_then(|()| std::fs::rename(&tmp, path)) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(err(e));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_second_folder_is_an_error() {
|
||||
let e = run(&["a".to_string(), "b".to_string()]).unwrap_err();
|
||||
assert!(e.starts_with("b: one FOLDER only"), "{e}");
|
||||
}
|
||||
|
||||
/// `--work` may hold anything: a run makes a new folder of its own there and never deletes
|
||||
/// what is already in it (it used to remove `lib-browse`, `lib-add` and `lib-copy` there).
|
||||
#[test]
|
||||
fn a_run_never_deletes_what_is_under_work() {
|
||||
// a folder this test owns (made new), so the cleanup below removes nothing else
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let keep = work.join("lib-browse").join("keep.txt");
|
||||
std::fs::create_dir_all(keep.parent().unwrap()).unwrap();
|
||||
std::fs::write(&keep, b"mine").unwrap();
|
||||
let a = run_dir(&work).unwrap();
|
||||
let b = run_dir(&work).unwrap();
|
||||
assert_ne!(a, b);
|
||||
fresh_dir(&a, "lib-browse").unwrap();
|
||||
assert!(fresh_dir(&a, "lib-browse").is_err(), "an existing folder is never reused");
|
||||
assert_eq!(std::fs::read(&keep).unwrap(), b"mine");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// A folder too small for the disjoint samples is measured on the photos it has (CodeRabbit on #3077).
|
||||
#[test]
|
||||
fn a_small_folder_is_sampled_from_its_start() {
|
||||
let v: Vec<u32> = (0..100).collect();
|
||||
assert_eq!(sample_after(&v, 48, 20), &v[48..68]);
|
||||
assert_eq!(sample_after(&v, 90, 20), &v[90..100]);
|
||||
assert_eq!(sample_after(&v[..3], 48, 20), &v[..3]);
|
||||
assert_eq!(sample_after(&v[..48], 48, 5), &v[..5]);
|
||||
assert!(sample_after::<u32>(&[], 48, 20).is_empty());
|
||||
}
|
||||
|
||||
/// A file link at `at` to `target`.
|
||||
#[cfg(unix)]
|
||||
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
|
||||
std::os::unix::fs::symlink(target, at)
|
||||
}
|
||||
|
||||
/// A file link at `at` to `target` (Windows: needs Developer Mode or the right to make links).
|
||||
#[cfg(windows)]
|
||||
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
|
||||
std::os::windows::fs::symlink_file(target, at)
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn link(_: &Path, _: &Path) -> std::io::Result<()> {
|
||||
Err(std::io::Error::other("no file links here"))
|
||||
}
|
||||
|
||||
/// `--json` naming a link (made elsewhere) to a file in the source folder is refused: writing
|
||||
/// the results would follow it and overwrite a photo (CodeRabbit on #3080). So is a link that
|
||||
/// points to a file not made yet in the source folder, and a loop of links.
|
||||
#[test]
|
||||
fn a_json_link_into_the_source_folder_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let photo = src.join("a.jpg");
|
||||
std::fs::write(&photo, b"photo").unwrap();
|
||||
let to_photo = work.join("report.json");
|
||||
if let Err(e) = link(&photo, &to_photo) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
|
||||
return;
|
||||
}
|
||||
assert!(inside_source(&to_photo, &src), "a link to a photo in the source folder");
|
||||
let e = check_outputs(&src, Some(&to_photo), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json"), "{e}");
|
||||
let to_new = work.join("new.json");
|
||||
link(&src.join("not-yet.json"), &to_new).unwrap();
|
||||
assert!(inside_source(&to_new, &src), "a link to a file not made yet in the source folder");
|
||||
let (x, y) = (work.join("x.json"), work.join("y.json"));
|
||||
link(&y, &x).unwrap();
|
||||
link(&x, &y).unwrap();
|
||||
assert!(inside_source(&x, &src), "a loop of links");
|
||||
let to_elsewhere = work.join("fine.json");
|
||||
link(&work.join("out.json"), &to_elsewhere).unwrap();
|
||||
assert!(!inside_source(&to_elsewhere, &src), "a link to a file outside is fine");
|
||||
assert_eq!(std::fs::read(&photo).unwrap(), b"photo");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a link that sits in the source folder and points to a file outside it is
|
||||
/// refused: writing the results would replace the link itself, an entry of the source folder
|
||||
/// (CodeRabbit on #3080). The link stays as it was.
|
||||
#[test]
|
||||
fn a_json_link_in_the_source_folder_to_a_file_outside_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let outside = work.join("out.json");
|
||||
std::fs::write(&outside, b"outside").unwrap();
|
||||
let in_src = src.join("a.jpg");
|
||||
if let Err(e) = link(&outside, &in_src) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
|
||||
return;
|
||||
}
|
||||
assert!(inside_source(&in_src, &src), "a link in the source folder, wherever it points");
|
||||
let e = check_outputs(&src, Some(&in_src), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json"), "{e}");
|
||||
assert!(std::fs::symlink_metadata(&in_src).unwrap().file_type().is_symlink(), "the link stays");
|
||||
assert_eq!(std::fs::read_link(&in_src).unwrap(), outside);
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), b"outside");
|
||||
// a new file in the source folder (nothing there yet) is refused too
|
||||
assert!(check_outputs(&src, Some(&src.join("new.json")), &work.join("elsewhere")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a hard link (made elsewhere) to a photo in the source folder passes
|
||||
/// [`inside_source`] (a hard link has no target to resolve), so the results replace the link
|
||||
/// instead of writing into it: the photo keeps its bytes (CodeRabbit on #3077).
|
||||
#[test]
|
||||
fn a_json_hard_link_to_a_photo_leaves_the_photo_alone() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let photo = src.join("a.jpg");
|
||||
std::fs::write(&photo, b"photo").unwrap();
|
||||
let report = work.join("report.json");
|
||||
if let Err(e) = std::fs::hard_link(&photo, &report) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a hard link here ({e})");
|
||||
return;
|
||||
}
|
||||
finish(json!({"browse": 1}), Some(report.clone())).unwrap();
|
||||
assert_eq!(std::fs::read(&photo).unwrap(), b"photo", "the photo is unchanged");
|
||||
let written: Value = serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap();
|
||||
assert_eq!(written["browse"], 1);
|
||||
let left: Vec<_> = std::fs::read_dir(&work).unwrap().flatten().map(|e| e.file_name()).collect();
|
||||
assert_eq!(left.len(), 2, "no temporary file is left: {left:?}");
|
||||
// a folder that isn't there: an error, nothing panics
|
||||
assert!(write_replacing(&work.join("missing").join("r.json"), b"x").is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a file in the source folder is refused (CodeRabbit on #3077); elsewhere it is fine.
|
||||
#[test]
|
||||
fn the_results_never_go_in_the_source_folder() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let sub = fresh_dir(&src, "sub").unwrap();
|
||||
assert!(inside_source(&src.join("a.png"), &src));
|
||||
assert!(inside_source(&sub.join("x.json"), &src));
|
||||
assert!(inside_source(&src.join("sub").join("..").join("a.png"), &src));
|
||||
assert!(!inside_source(&work.join("out.json"), &src));
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--work` in the source folder is refused before anything is made there, also when it doesn't
|
||||
/// exist yet (CodeRabbit on #3077); elsewhere it is fine.
|
||||
#[test]
|
||||
fn the_work_folder_never_goes_in_the_source_folder() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let inside = src.join("out").join("deeper");
|
||||
let e = check_outputs(&src, None, &inside).unwrap_err();
|
||||
assert!(e.contains("--work"), "{e}");
|
||||
assert!(check_outputs(&src, None, &src).is_err(), "the source folder itself");
|
||||
assert!(!src.join("out").exists(), "nothing was made in the source folder");
|
||||
assert!(check_outputs(&src, None, &work.join("elsewhere")).is_ok());
|
||||
assert!(check_outputs(&src, Some(&src.join("r.json")), &work.join("elsewhere")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// A `..` in `--json` or `--work` is refused: after a folder the run hasn't made yet it can't be
|
||||
/// resolved now, and would lead into the source folder once the run makes it (CodeRabbit on #3544).
|
||||
#[test]
|
||||
fn a_dot_dot_in_the_outputs_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let sneaky = work.join("new").join("..").join("src").join("r.json");
|
||||
let e = check_outputs(&src, Some(&sneaky), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json") && e.contains(".."), "{e}");
|
||||
let e = check_outputs(&src, None, &work.join("new").join("..").join("src")).unwrap_err();
|
||||
assert!(e.contains("--work"), "{e}");
|
||||
assert!(!work.join("new").exists(), "nothing was made");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
}
|
||||
+103
-23
@@ -11,11 +11,13 @@
|
||||
//! lightcraft-cli commands [--json]
|
||||
//! lightcraft-cli controls [--json]
|
||||
//! lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
|
||||
//! lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
|
||||
//! ```
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod alloc_release;
|
||||
mod bench_cull;
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
@@ -106,10 +108,16 @@ USAGE:
|
||||
lightcraft-cli controls [--json] list every develop control id with its range
|
||||
lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
|
||||
Fit a colour profile per camera model from raw files and their embedded camera JPEGs
|
||||
(Sony ARW, Nikon NEF, Fujifilm RAF): up to N files spread over the folders (default 300; 0 = all), pooled per
|
||||
(Sony ARW, Nikon NEF, Fujifilm RAF, Canon CRW): up to N files spread over the folders (default 300; 0 = all), pooled per
|
||||
model, written as <model>.json to DIR (default: the profiles folder LightCraft reads,
|
||||
<config>/camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then
|
||||
take their colour from the profile and only their tone from their own JPEG.
|
||||
lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
|
||||
Time what culling a shoot costs on its own files: reading the folder (browse), the first
|
||||
screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render,
|
||||
rating, and importing N files in place (default 2000) and copying M (default 200). Libraries
|
||||
are made in a new folder under DIR (default: the temp folder); nothing is written next to the
|
||||
photos. --files K reads only the first K files by name (a sample of a slow network folder).
|
||||
lightcraft-cli --version | --help
|
||||
";
|
||||
|
||||
@@ -176,6 +184,7 @@ fn main() -> ExitCode {
|
||||
Some("controls") => controls(&args[1..]),
|
||||
Some("denoise-serve") => denoise_serve(&args[1..]),
|
||||
Some("calibrate") => calibrate(&args[1..]),
|
||||
Some("bench-cull") => bench_cull::run(&args[1..]),
|
||||
Some("--version" | "-V" | "version") => {
|
||||
println!("lightcraft-cli {}", env!("CARGO_PKG_VERSION"));
|
||||
Ok(())
|
||||
@@ -196,26 +205,35 @@ fn main() -> ExitCode {
|
||||
}
|
||||
|
||||
/// Raw files below `path` (or `path` itself), skipping hidden and NAS metadata folders.
|
||||
fn raw_files(path: &Path, out: &mut Vec<std::path::PathBuf>, depth: usize) {
|
||||
let is_raw =
|
||||
|p: &Path| p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["arw", "nef", "nrw", "raf"].iter().any(|x| e.eq_ignore_ascii_case(x)));
|
||||
///
|
||||
/// Folders go through the engine's bounded walk ([`lightcraft_engine::walk::files_in`]): it enters
|
||||
/// a folder reached through a link once at most and stops at a depth and an entry budget. A
|
||||
/// folder of links pointing back at their parents made the old recursive walk re-read the same
|
||||
/// folders exponentially often before its depth limit cut it off (CWE-400).
|
||||
fn raw_files(path: &Path, out: &mut Vec<std::path::PathBuf>) {
|
||||
let is_raw = |p: &Path| {
|
||||
p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["arw", "nef", "nrw", "raf", "crw"].iter().any(|x| e.eq_ignore_ascii_case(x)))
|
||||
};
|
||||
if path.is_file() {
|
||||
if is_raw(path) {
|
||||
out.push(path.to_path_buf());
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(path) else { return };
|
||||
if depth > 32 {
|
||||
return;
|
||||
}
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
if name.to_string_lossy().starts_with(['.', '@']) {
|
||||
continue;
|
||||
}
|
||||
raw_files(&entry.path(), out, depth + 1);
|
||||
// (hidden entries are left out by the walk; `@eaDir` and other NAS metadata folders and files
|
||||
// here, folders before they are listed so their entries do not use up the walk's budget)
|
||||
let nas_metadata = |p: &Path| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('@'));
|
||||
let walked = lightcraft_engine::walk::files_in_entering(
|
||||
path,
|
||||
None,
|
||||
lightcraft_engine::walk::Limits::default(),
|
||||
|p| is_raw(p) && !nas_metadata(p) && p.is_file(),
|
||||
|p| !nas_metadata(p),
|
||||
);
|
||||
if walked.truncated {
|
||||
eprintln!("calibrate: {} has more folders or entries than a walk looks at; the rest is left out", path.display());
|
||||
}
|
||||
out.extend(walked.files);
|
||||
}
|
||||
|
||||
fn calibrate(args: &[String]) -> Result<(), String> {
|
||||
@@ -237,7 +255,7 @@ fn calibrate(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
for input in &inputs {
|
||||
raw_files(Path::new(input), &mut files, 0);
|
||||
raw_files(Path::new(input), &mut files);
|
||||
}
|
||||
files.sort();
|
||||
files.dedup();
|
||||
@@ -425,7 +443,7 @@ fn merge(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
|
||||
let mut s = file_session();
|
||||
let paths = expand_paths(&files);
|
||||
let r = s.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?;
|
||||
let mut ids: Vec<u64> = r["imported"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();
|
||||
@@ -703,6 +721,12 @@ fn read_settings(p: &str) -> Result<SettingsFile, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The session `render` and `merge` develop files in: with the lens database the desktop app downloaded, when it is
|
||||
/// there (never fetched from here: scripts and tests stay offline).
|
||||
fn file_session() -> Session {
|
||||
Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_lens_database()
|
||||
}
|
||||
|
||||
fn render(args: &[String]) -> Result<(), String> {
|
||||
let mut input = None;
|
||||
let mut output = None;
|
||||
@@ -741,7 +765,7 @@ fn render(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
let input = input.ok_or("render: missing input file")?;
|
||||
let output = output.ok_or("render: missing -o OUTPUT")?;
|
||||
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
|
||||
let mut s = file_session();
|
||||
let abs = expand_paths(std::slice::from_ref(&input));
|
||||
let r = s.execute("library.import", &json!({"paths": abs})).map_err(|e| e.to_string())?;
|
||||
let id = r["imported"][0].as_u64().ok_or_else(|| format!("{input}: not a readable photo"))?;
|
||||
@@ -836,15 +860,30 @@ fn snapshot(args: &[String]) -> Result<(), String> {
|
||||
let t0 = Instant::now();
|
||||
let mut session = match &library {
|
||||
Some(dir) => {
|
||||
let mut s =
|
||||
Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates();
|
||||
let mut s = Session::new()
|
||||
.with_fs()
|
||||
.with_default_denoise_models()
|
||||
.with_system_clock()
|
||||
.with_default_face_models()
|
||||
.with_default_lens_database()
|
||||
.with_default_slide_templates();
|
||||
s.open_library(dir, false).map_err(|e| library_error(dir, e))?;
|
||||
s
|
||||
}
|
||||
None if files.is_empty() => {
|
||||
Session::with_demo().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates()
|
||||
}
|
||||
None => Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates(),
|
||||
None if files.is_empty() => Session::with_demo()
|
||||
.with_fs()
|
||||
.with_default_denoise_models()
|
||||
.with_system_clock()
|
||||
.with_default_face_models()
|
||||
.with_default_lens_database()
|
||||
.with_default_slide_templates(),
|
||||
None => Session::new()
|
||||
.with_fs()
|
||||
.with_default_denoise_models()
|
||||
.with_system_clock()
|
||||
.with_default_face_models()
|
||||
.with_default_lens_database()
|
||||
.with_default_slide_templates(),
|
||||
};
|
||||
// Apply compute policy before imports or the first scripted query can discover an adapter.
|
||||
session.execute("app.gpu", &json!({"enabled": false})).map_err(|e| e.to_string())?;
|
||||
@@ -1069,6 +1108,47 @@ fn denoise_serve(_: &[String]) -> Result<(), String> {
|
||||
Err("denoise-serve: this build has no denoise support (build with the `denoise` feature)".into())
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod raw_files_tests {
|
||||
use super::raw_files;
|
||||
|
||||
/// Links back to their own folders are entered once, not once per path that reaches them: a
|
||||
/// handful of such links made the old walk list the same folders exponentially often.
|
||||
#[test]
|
||||
fn folder_links_back_up_are_walked_once() {
|
||||
let dir = std::env::temp_dir().join(format!("lightcraft-cli-raw-files-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let a = dir.join("a");
|
||||
std::fs::create_dir_all(a.join("@eaDir")).unwrap();
|
||||
std::fs::write(a.join("one.NEF"), b"").unwrap();
|
||||
std::fs::write(a.join("@eaDir").join("thumb.nef"), b"").unwrap();
|
||||
std::fs::write(a.join("notes.txt"), b"").unwrap();
|
||||
for i in 0..8 {
|
||||
std::os::unix::fs::symlink(&dir, a.join(format!("up{i}"))).unwrap();
|
||||
}
|
||||
// a named pipe with a raw extension: not a file, so never opened (a read would block)
|
||||
assert!(std::process::Command::new("mkfifo").arg(a.join("pipe.nef")).status().unwrap().success());
|
||||
let started = std::time::Instant::now();
|
||||
let mut files = Vec::new();
|
||||
raw_files(&dir, &mut files);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "walk took {:?}", started.elapsed());
|
||||
assert_eq!(files, vec![a.join("one.NEF")]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// `render` and `merge` read the lens database the desktop app downloaded, as the desktop does (the same raw
|
||||
/// gets the same profile everywhere), but never fetch it.
|
||||
#[test]
|
||||
fn render_reads_the_downloaded_lens_database() {
|
||||
let s = super::file_session();
|
||||
assert_eq!(lightcraft_engine::lens_profiles::host_dir(), lightcraft_engine::lensfun_download::default_dir());
|
||||
assert!(!s.lens_auto_download, "selecting it is not permission to download it");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod import_target_tests {
|
||||
use super::{import_and_select, import_targets, json};
|
||||
|
||||
@@ -101,6 +101,75 @@ fn gradient_png(path: &std::path::Path) {
|
||||
std::fs::write(path, png).unwrap();
|
||||
}
|
||||
|
||||
/// PERF-CULL-5: `bench-cull` times a folder end to end and writes nothing next to the photos.
|
||||
#[test]
|
||||
fn bench_cull_times_a_folder_and_leaves_it_untouched() {
|
||||
let dir = tmp("bench-cull-src");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (seed, name) in ["a.png", "b.png", "c.png"].iter().enumerate() {
|
||||
// three different pictures (the same bytes would import as one photo)
|
||||
let img = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, (seed * 80) as u8, 255]);
|
||||
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
|
||||
std::fs::write(dir.join(name), png).unwrap();
|
||||
}
|
||||
// every file's name and bytes: nothing added, and no photo written into (CodeRabbit on #3577)
|
||||
let listing = |d: &std::path::Path| {
|
||||
let mut v: Vec<(String, Vec<u8>)> = std::fs::read_dir(d)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap())
|
||||
.map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read(e.path()).unwrap()))
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
let before = listing(&dir);
|
||||
let work = tmp("bench-cull-work");
|
||||
let json_out = tmp("bench-cull.json");
|
||||
let r = Command::new(binary())
|
||||
.arg("bench-cull")
|
||||
.arg(&dir)
|
||||
.args(["--n", "3", "--copy", "1", "--work"])
|
||||
.arg(&work)
|
||||
.arg("--json")
|
||||
.arg(&json_out)
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&r.stdout);
|
||||
assert!(r.status.success(), "{stdout}{}", String::from_utf8_lossy(&r.stderr));
|
||||
assert!(stdout.contains("browse 3 photos") && stdout.contains("ms wall"), "{stdout}");
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(&json_out).unwrap()).unwrap();
|
||||
assert_eq!(v["browse"]["photos"], 3);
|
||||
assert_eq!(v["importAdd"]["photos"], 3);
|
||||
assert_eq!(v["importCopy"]["photos"], 1);
|
||||
assert_eq!(v["rate"]["n"], 3);
|
||||
// a folder smaller than the samples is measured on the photos it has, not reported empty
|
||||
for stage in ["camera1280", "camera2560", "cameraFull", "loupeRender"] {
|
||||
assert_eq!(v[stage]["n"], 3, "{stage}: {}", v[stage]);
|
||||
}
|
||||
assert_eq!(listing(&dir), before, "nothing written next to the photos");
|
||||
// results asked for in the source folder: refused, the photo untouched
|
||||
let photo = std::fs::read(dir.join("a.png")).unwrap();
|
||||
let r = Command::new(binary())
|
||||
.arg("bench-cull")
|
||||
.arg(&dir)
|
||||
.args(["--n", "0", "--work"])
|
||||
.arg(&work)
|
||||
.arg("--json")
|
||||
.arg(dir.join("a.png"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("--json"), "{}", String::from_utf8_lossy(&r.stderr));
|
||||
assert_eq!(std::fs::read(dir.join("a.png")).unwrap(), photo);
|
||||
assert_eq!(listing(&dir), before);
|
||||
// a sample of the folder, no import
|
||||
let r = Command::new(binary()).arg("bench-cull").arg(&dir).args(["--files", "2", "--n", "0", "--work"]).arg(&work).output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&r.stdout);
|
||||
assert!(r.status.success() && stdout.contains("browse 2 photos (first files)") && !stdout.contains("import"), "{stdout}");
|
||||
// a bad folder is an error, not a panic
|
||||
let r = Command::new(binary()).args(["bench-cull", "/no/such/folder"]).output().unwrap();
|
||||
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("not a folder"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibrate_reads_raf_inputs_and_reports_bad_files() {
|
||||
let input = tmp("invalid.RAF");
|
||||
|
||||
@@ -32,10 +32,14 @@ js-sys = { workspace = true }
|
||||
web-sys = { workspace = true, features = [
|
||||
"Blob",
|
||||
"BlobPropertyBag",
|
||||
"CustomEvent",
|
||||
"CustomEventInit",
|
||||
"CssStyleDeclaration",
|
||||
"DedicatedWorkerGlobalScope",
|
||||
"Document",
|
||||
"DomStringList",
|
||||
"Element",
|
||||
"Event",
|
||||
"EventTarget",
|
||||
"File",
|
||||
"FileList",
|
||||
@@ -73,10 +77,12 @@ web-sys = { workspace = true, features = [
|
||||
] }
|
||||
|
||||
[features]
|
||||
# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it (HEVC patents); build with `--features heif` to include it. On wasm32 panics abort, so
|
||||
# heic-rs's `catch_unwind` guard does not apply there.
|
||||
heif = ["lightcraft-codecs/heif"]
|
||||
|
||||
[dev-dependencies]
|
||||
egui = { workspace = true }
|
||||
lightcraft-color = { workspace = true }
|
||||
lightcraft-raw = { workspace = true }
|
||||
@@ -233,6 +233,25 @@ pub fn parse_central(cd: &[u8]) -> Result<Vec<ZipEntry>, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What a restore writes, each storage key once, checked against the whole directory before any
|
||||
/// payload is read: a backup names a file once, so a directory naming the same destination again
|
||||
/// is damaged or altered, and its entries' bytes can't add up to more than the file holds (a
|
||||
/// directory can point many entries at one stored range and have each read, checked and written).
|
||||
pub fn restore_plan<'a>(entries: &'a [ZipEntry], dir: &str, file_len: u64) -> Result<Vec<(String, &'a ZipEntry)>, String> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut plan = Vec::new();
|
||||
let mut bytes = 0u64;
|
||||
for e in entries {
|
||||
let Some(key) = restore_key(&e.name, dir) else { continue };
|
||||
if !seen.insert(key.clone()) {
|
||||
return Err(format!("{}: listed twice (damaged or altered backup)", e.name));
|
||||
}
|
||||
bytes = bytes.checked_add(e.size).filter(|&b| b <= file_len).ok_or_else(|| format!("{}: entries larger than the backup itself", e.name))?;
|
||||
plan.push((key, e));
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Offset of an entry's data from its local header's first 30 bytes.
|
||||
pub fn data_offset(entry: &ZipEntry, local: &[u8]) -> Result<u64, String> {
|
||||
if rd32(local, 0) != Some(LOCAL_SIG) {
|
||||
@@ -342,6 +361,23 @@ mod tests {
|
||||
assert!(!valid_library_dir("library-../x") && !valid_library_dir("originals") && !valid_library_dir("library-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_plan_refuses_repeated_and_oversized_entries() {
|
||||
let entry = |name: &str, size: u64| ZipEntry { name: name.into(), crc: 0, size, header: 0, method: 0 };
|
||||
let ok = [entry("README.txt", 10), entry("library/catalog.log", 10), entry("originals/abc123/a.jpg", 100)];
|
||||
let plan = restore_plan(&ok, "d", 200).unwrap();
|
||||
assert_eq!(plan.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(), ["d/catalog.log", "originals/abc123"]);
|
||||
// one stored range named 3 times would be read, checked and written 3 times
|
||||
let twice = [entry("originals/abc123/a.jpg", 100), entry("originals/abc123/b.jpg", 100)];
|
||||
assert!(restore_plan(&twice, "d", 1000).unwrap_err().contains("twice"));
|
||||
let twice = [entry("library/catalog.log", 10), entry("library/catalog.log", 10)];
|
||||
assert!(restore_plan(&twice, "d", 1000).is_err());
|
||||
// entries claiming more bytes than the file has
|
||||
let big = [entry("library/catalog.log", 150), entry("originals/abc123/a.jpg", 100)];
|
||||
assert!(restore_plan(&big, "d", 200).is_err());
|
||||
assert!(restore_plan(&[entry("library/catalog.log", u64::MAX), entry("library/presets.json", 1)], "d", u64::MAX).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_limits_are_errors_not_panics() {
|
||||
let mut w = ZipWriter { offset: MAX_BYTES - 10, ..Default::default() };
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
//! control exactly like a slider drag (begin interaction → N `develop.set` → end) and time each
|
||||
//! step from the command to the moment the new loupe texture is ready. Results go to the log
|
||||
//! (the browser console on the web) as one `lightcraft-bench {…json…}` line.
|
||||
//!
|
||||
//! The web host runs it only on the generated demo photos in an unsaved library (`?bench` implies `?store=memory`): it
|
||||
//! commits edits to the photo it opens, which must never be one in the user's stored library.
|
||||
|
||||
use lightcraft_ui_egui::LightcraftApp;
|
||||
use lightcraft_ui_egui::render::Slot;
|
||||
|
||||
@@ -0,0 +1,632 @@
|
||||
//! The bridge to a host page (issue #2270): a same-origin page embeds LightCraft in an `<iframe>`
|
||||
//! (`?host=parent`) or in its own document (`data-host="page"` on the canvas). The protocol is
|
||||
//! the one PdfCraft, GridCraft and DeckCraft speak, with `lightcraft:` message types:
|
||||
//!
|
||||
//! - `lightcraft:ready` (to the parent): `{ version }`, the app is listening.
|
||||
//! - `lightcraft:failed` (to the parent): `{ error }`, the app couldn't start, or it refused a
|
||||
//! `lightcraft:open` (a file larger than a library backup can hold, [`crate::backup::MAX_BYTES`]).
|
||||
//! - `lightcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
|
||||
//! `Uint8Array`. The photo is added to the library, as one dropped on the window is; `name`
|
||||
//! gives the format (its extension), `photo.jpg` when missing.
|
||||
//! - `lightcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
|
||||
//! file LightCraft would otherwise download: exports and the library backup (the preset, keyword
|
||||
//! and curve file dialogs have no web implementation yet). The parent stores it and reports
|
||||
//! failures itself.
|
||||
//! - `lightcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
|
||||
//! On the web every change is written to browser storage a moment after it is made, so `dirty`
|
||||
//! means "closing the page right now would lose something": a write still queued or running,
|
||||
//! or changes that storage refused (quota).
|
||||
//! - `lightcraft:cmd` (from the parent): `{ id, params }`, params a JSON string (`{}` when
|
||||
//! missing, empty or `null`; anything but a JSON object is refused unrun, see [`crate::automation::params`]).
|
||||
//! Runs the command by id, like `lightcraft.command(..)` from the page itself, and answers with
|
||||
//! `lightcraft:response` `{ ok, value }` (the JSON result, or the error text).
|
||||
//! Responses carry no request id (none of the sibling bridges' do): they come back in the order
|
||||
//! the commands were sent, one per `cmd` that had an id; a `cmd` without one gets no response.
|
||||
//!
|
||||
//! Only the parent window on the page's own origin is heard or answered. A page whose origin is
|
||||
//! opaque (`"null"`: a sandboxed iframe, a `data:` page) gets no bridge at all, since every other
|
||||
//! opaque-origin window would then pass as the parent. A parent on another origin gets no bridge
|
||||
//! either: its `location` cannot be read, and exports keep downloading. There is no `docClosed`: LightCraft has a
|
||||
//! library, not documents that close.
|
||||
//!
|
||||
//! ## `data-host="page"` — the page's own document
|
||||
//!
|
||||
//! A page can also run LightCraft in its own document, no iframe: the canvas opts in with
|
||||
//! `data-host="page"`, and the same messages travel as DOM `CustomEvent`s on the canvas instead
|
||||
//! of `postMessage` — outward with the message's fields as the event's `detail`, inward as
|
||||
//! `lightcraft:open` and `lightcraft:cmd` events the page dispatches on the canvas. Events don't
|
||||
//! bubble, so two editors on one page can't hear each other, and the canvas is the only target
|
||||
//! the bridge listens on.
|
||||
//!
|
||||
//! The message layer (what a message means, what is sent back) is plain Rust, tested natively;
|
||||
//! [`Bridge`] (wasm32 only) moves it over `postMessage`, or over DOM events in page mode.
|
||||
|
||||
/// A message from the parent page, once understood.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Incoming {
|
||||
/// `lightcraft:open`: add this photo to the library.
|
||||
Open { name: String, bytes: Vec<u8> },
|
||||
/// `lightcraft:cmd`: run this command (params as JSON text).
|
||||
Cmd { id: String, params: String },
|
||||
/// `lightcraft:open` with a file too large to keep: tell the parent why (`lightcraft:failed`).
|
||||
Refused(String),
|
||||
}
|
||||
|
||||
/// The fields of a message from the parent, as read off the event (each may be missing).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Raw {
|
||||
pub kind: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub bytes: Option<Vec<u8>>,
|
||||
pub id: Option<String>,
|
||||
pub params: Option<String>,
|
||||
/// The size of `bytes` when it was too large to copy (`bytes` is then `None`).
|
||||
pub oversize: Option<u64>,
|
||||
}
|
||||
|
||||
/// Why a photo of `len` bytes sent with `lightcraft:open` is refused, or `None` when it fits: one
|
||||
/// larger than a library backup can hold ([`crate::backup::MAX_BYTES`]) is never copied in.
|
||||
pub fn open_size_error(len: u64) -> Option<String> {
|
||||
let max = crate::backup::MAX_BYTES;
|
||||
(len > max).then(|| format!("the file is too large to open ({} MB; the limit is {} MB)", len >> 20, max >> 20))
|
||||
}
|
||||
|
||||
/// The name a photo sent without one is stored under (its extension picks the decoder).
|
||||
pub const DEFAULT_OPEN_NAME: &str = "photo.jpg";
|
||||
|
||||
impl Incoming {
|
||||
/// What the parent asked for; `None` for a message type that isn't ours, an `open` without
|
||||
/// bytes or a `cmd` without an id (dropped, the page's other messages are none of our business).
|
||||
pub fn parse(raw: Raw) -> Option<Incoming> {
|
||||
match raw.kind.as_deref() {
|
||||
Some("lightcraft:open") => {
|
||||
if let Some(error) = raw.oversize.and_then(open_size_error) {
|
||||
return Some(Incoming::Refused(error));
|
||||
}
|
||||
let name = raw.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| DEFAULT_OPEN_NAME.to_string());
|
||||
Some(Incoming::Open { name, bytes: raw.bytes? })
|
||||
}
|
||||
Some("lightcraft:cmd") => {
|
||||
let id = raw.id.filter(|i| !i.trim().is_empty())?;
|
||||
Some(Incoming::Cmd { id, params: raw.params.filter(|p| !p.trim().is_empty()).unwrap_or_else(|| "{}".to_string()) })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A field of a message to the parent.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Field {
|
||||
Str(String),
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// A message to the parent, without bytes (`lightcraft:save` carries a transferred buffer and is
|
||||
/// built by the bridge itself).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Outgoing {
|
||||
Ready,
|
||||
Failed(String),
|
||||
Dirty(bool),
|
||||
/// How a `lightcraft:cmd` ended: the JSON result, or the error text.
|
||||
Response {
|
||||
ok: bool,
|
||||
value: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl Outgoing {
|
||||
/// The message's fields, `type` first.
|
||||
pub fn fields(&self) -> Vec<(&'static str, Field)> {
|
||||
match self {
|
||||
Outgoing::Ready => vec![("type", Field::Str("lightcraft:ready".into())), ("version", Field::Str(env!("CARGO_PKG_VERSION").into()))],
|
||||
Outgoing::Failed(error) => vec![("type", Field::Str("lightcraft:failed".into())), ("error", Field::Str(error.clone()))],
|
||||
Outgoing::Dirty(dirty) => vec![("type", Field::Str("lightcraft:dirty".into())), ("dirty", Field::Bool(*dirty))],
|
||||
Outgoing::Response { ok, value } => {
|
||||
vec![("type", Field::Str("lightcraft:response".into())), ("ok", Field::Bool(*ok)), ("value", Field::Str(value.clone()))]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The unsaved-changes state as the parent last heard it: `lightcraft:dirty` goes out only when
|
||||
/// it changes (not every frame), and a message that couldn't be sent is sent again next time.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct DirtyReport {
|
||||
reported: Option<bool>,
|
||||
}
|
||||
|
||||
impl DirtyReport {
|
||||
/// `Some(message)` when `dirty` differs from what the parent knows; call [`DirtyReport::sent`]
|
||||
/// once it went out.
|
||||
pub fn change(&self, dirty: bool) -> Option<Outgoing> {
|
||||
(self.reported != Some(dirty)).then_some(Outgoing::Dirty(dirty))
|
||||
}
|
||||
|
||||
pub fn sent(&mut self, dirty: bool) {
|
||||
self.reported = Some(dirty);
|
||||
}
|
||||
|
||||
/// Record `dirty` before the send. A page host can report another state while the event is
|
||||
/// still dispatching, and that later report wins. Returns the message to send and the state
|
||||
/// to put back if this send fails and nothing else recorded one.
|
||||
pub fn prepare(&mut self, dirty: bool) -> (Option<Outgoing>, Option<bool>) {
|
||||
let previous = self.reported;
|
||||
let message = self.change(dirty);
|
||||
if message.is_some() {
|
||||
self.sent(dirty);
|
||||
}
|
||||
(message, previous)
|
||||
}
|
||||
|
||||
/// Forget a send that failed, unless a nested report already recorded a different state.
|
||||
pub fn restore_if_unchanged(&mut self, dirty: bool, previous: Option<bool>) {
|
||||
if self.reported == Some(dirty) {
|
||||
self.reported = previous;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a page origin can tell the parent apart from any other window: an opaque origin
|
||||
/// (`"null"`, as a sandboxed iframe or a `data:` page has) cannot, so such a page gets no bridge.
|
||||
pub fn origin_is_usable(origin: &str) -> bool {
|
||||
let o = origin.trim();
|
||||
!o.is_empty() && o != "null"
|
||||
}
|
||||
|
||||
/// The name a saved file is handed over under: the file name of the path the export chose.
|
||||
pub fn save_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
|
||||
/// The one `data-host` value that opts a page into page host mode: the exact string `"page"`.
|
||||
pub const PAGE_HOST: &str = "page";
|
||||
|
||||
/// How a host page reaches the app. The modes behave the same; they differ only in how an event
|
||||
/// goes out ([`Bridge::post`] and `save`, wasm32) and how one comes in ([`Bridge::listen`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// `?host=parent`: the page framed LightCraft in an `<iframe>`; `postMessage`.
|
||||
Parent,
|
||||
/// `data-host="page"`: the page runs LightCraft in its own document; DOM `CustomEvent`s.
|
||||
Page,
|
||||
}
|
||||
|
||||
/// The mode the page asked for. `?host=parent` wins when the page asks for both, the same order
|
||||
/// as the other apps. Page mode is the exact `data-host="page"` ([`PAGE_HOST`]). `None` with
|
||||
/// neither, so that URL stays the normal app with downloads.
|
||||
pub fn transport_for(data_host: Option<&str>, query: &str) -> Option<Mode> {
|
||||
if host_parent_requested(query) {
|
||||
Some(Mode::Parent)
|
||||
} else if data_host == Some(PAGE_HOST) {
|
||||
Some(Mode::Page)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The message type. A page-mode `CustomEvent` is named `lightcraft:open` or `lightcraft:cmd`
|
||||
/// and its `detail` is only the fields, so the event name is the type. A parent `postMessage`
|
||||
/// carries `type` in the object and has no event name.
|
||||
pub fn incoming_kind(event_name: Option<&str>, detail_type: Option<String>) -> Option<String> {
|
||||
event_name.map(str::to_string).or(detail_type)
|
||||
}
|
||||
|
||||
/// Does the query ask for the parent bridge? The same reading of `?host=parent` the URL options
|
||||
/// always used: the first `host` parameter whose value is exactly `parent`.
|
||||
pub fn host_parent_requested(query: &str) -> bool {
|
||||
query.trim_start_matches('?').split('&').find_map(|p| {
|
||||
let (k, v) = p.split_once('=').unwrap_or((p, ""));
|
||||
(k == "host").then_some(v == "parent")
|
||||
}) == Some(true)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub use bridge::Bridge;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod bridge {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
|
||||
use super::{DirtyReport, Field, Incoming, Mode, Outgoing, Raw, open_size_error, origin_is_usable, save_name};
|
||||
|
||||
/// How an event goes to the host page, per mode ([`Mode`]).
|
||||
#[derive(Clone)]
|
||||
enum Transport {
|
||||
/// `?host=parent`: `postMessage` between same-origin windows.
|
||||
Parent { parent: web_sys::Window, origin: String },
|
||||
/// `data-host="page"`: DOM `CustomEvent`s on the editor's own canvas.
|
||||
Page { canvas: web_sys::HtmlCanvasElement },
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
/// Hand an event to the host. Parent mode: a `postMessage` whose `type` field is `event`
|
||||
/// (the same message as before, transferring `transfer` when given). Page mode: a
|
||||
/// non-bubbling `CustomEvent` of that name on the canvas, whose `detail` holds the
|
||||
/// fields; nothing is transferred there, the buffer just rides inside `detail`.
|
||||
fn send(&self, event: &str, fields: &[(&str, JsValue)], transfer: Option<&js_sys::ArrayBuffer>) -> Result<(), String> {
|
||||
match self {
|
||||
Transport::Parent { parent, origin } => {
|
||||
let mut all = Vec::with_capacity(fields.len() + 1);
|
||||
all.push(("type", JsValue::from_str(event)));
|
||||
all.extend_from_slice(fields);
|
||||
let message = message(&all).ok_or_else(|| "couldn't build the message".to_string())?;
|
||||
let sent = match transfer {
|
||||
Some(buffer) => parent.post_message_with_transfer(&message, origin, &js_sys::Array::of1(buffer)),
|
||||
None => parent.post_message(&message, origin),
|
||||
};
|
||||
sent.map_err(|e| js_error(&e, "couldn't post the message"))
|
||||
}
|
||||
Transport::Page { canvas } => {
|
||||
let detail = message(fields).ok_or_else(|| "couldn't build the event detail".to_string())?;
|
||||
let init = web_sys::CustomEventInit::new();
|
||||
init.set_bubbles(false);
|
||||
init.set_detail(&detail);
|
||||
let custom =
|
||||
web_sys::CustomEvent::new_with_event_init_dict(event, &init).map_err(|e| js_error(&e, "couldn't create the event"))?;
|
||||
canvas.dispatch_event(&custom).map_err(|e| js_error(&e, "couldn't dispatch the event"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The host page's end of the bridge (cheap to clone; one per page).
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
transport: Transport,
|
||||
/// What the host sent since the last frame, oldest first.
|
||||
incoming: Rc<RefCell<Vec<Incoming>>>,
|
||||
dirty: Rc<RefCell<DirtyReport>>,
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
/// The parent bridge for `?host=parent`. `None` when the page isn't framed, its origin is
|
||||
/// opaque, or the parent is on another origin (exports then keep downloading).
|
||||
pub fn new() -> Option<Self> {
|
||||
let window = web_sys::window()?;
|
||||
let parent = window.parent().ok().flatten()?;
|
||||
if js_sys::Object::is(&parent, &window) {
|
||||
return None;
|
||||
}
|
||||
// the document's own origin (`window.origin`), not the URL's: a sandboxed iframe keeps
|
||||
// its URL but runs with the opaque origin "null"
|
||||
let origin = window.origin();
|
||||
if !origin_is_usable(&origin) {
|
||||
return None;
|
||||
}
|
||||
// Reading another origin's location throws, so this is `None` for a cross-origin parent.
|
||||
if parent.location().origin().ok().as_deref() != Some(origin.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some(Self { transport: Transport::Parent { parent, origin }, incoming: Rc::default(), dirty: Rc::default() })
|
||||
}
|
||||
|
||||
/// The page bridge for `data-host="page"`: the host page runs LightCraft in its own
|
||||
/// document and hears the app's DOM `CustomEvent`s on this canvas.
|
||||
pub fn for_page(canvas: &web_sys::HtmlCanvasElement) -> Self {
|
||||
Self { transport: Transport::Page { canvas: canvas.clone() }, incoming: Rc::default(), dirty: Rc::default() }
|
||||
}
|
||||
|
||||
/// The bridge for the mode the page opted into (`host::transport_for`): page mode needs
|
||||
/// its canvas, and parent mode falls back to `None` as [`Bridge::new`] always did.
|
||||
pub fn for_mode(mode: Mode, canvas: Option<&web_sys::HtmlCanvasElement>) -> Option<Self> {
|
||||
match mode {
|
||||
Mode::Page => canvas.map(Self::for_page),
|
||||
Mode::Parent => Self::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hear the host from now on; a message wakes the app for the next frame.
|
||||
pub fn listen(&self, ctx: egui::Context) {
|
||||
match &self.transport {
|
||||
Transport::Parent { parent, origin } => {
|
||||
let parent = parent.clone();
|
||||
let origin = origin.clone();
|
||||
let incoming = self.incoming.clone();
|
||||
let on_message = Closure::<dyn Fn(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
|
||||
if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) {
|
||||
return;
|
||||
}
|
||||
deliver(&incoming, &ctx, &event.data(), None);
|
||||
});
|
||||
if web_sys::window().is_some_and(|w| w.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok()) {
|
||||
// the listener lives as long as the page
|
||||
on_message.forget();
|
||||
}
|
||||
}
|
||||
Transport::Page { canvas } => {
|
||||
// non-bubbling events: the page dispatches on the canvas, the canvas listens
|
||||
for kind in ["lightcraft:open", "lightcraft:cmd"] {
|
||||
let incoming = self.incoming.clone();
|
||||
let ctx = ctx.clone();
|
||||
let event_type = kind.to_string();
|
||||
// `Fn`, not `FnMut`: a page event is dispatched synchronously, and a host
|
||||
// that answers one event with another would re-enter an `FnMut` listener.
|
||||
let on_custom = Closure::<dyn Fn(web_sys::Event)>::new(move |event: web_sys::Event| {
|
||||
let Some(custom) = event.dyn_ref::<web_sys::CustomEvent>() else { return };
|
||||
deliver(&incoming, &ctx, &custom.detail(), Some(event_type.as_str()));
|
||||
});
|
||||
if canvas.add_event_listener_with_callback(kind, on_custom.as_ref().unchecked_ref()).is_ok() {
|
||||
// the listener lives as long as the page
|
||||
on_custom.forget();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the parent sent since the last frame, oldest first.
|
||||
pub fn take_incoming(&self) -> Vec<Incoming> {
|
||||
std::mem::take(&mut *self.incoming.borrow_mut())
|
||||
}
|
||||
|
||||
/// Post a message; false if it couldn't be sent.
|
||||
pub fn post(&self, m: &Outgoing) -> bool {
|
||||
let fields = m.fields();
|
||||
// every message names its type first (tested natively); the rest go to the transport
|
||||
let Some((_, Field::Str(event))) = fields.first() else { return false };
|
||||
let event = event.clone();
|
||||
let rest: Vec<(&str, JsValue)> = fields.into_iter().skip(1).map(|(k, v)| (k, field(&v))).collect();
|
||||
self.transport.send(&event, &rest, None).is_ok()
|
||||
}
|
||||
|
||||
/// Tell the parent whether closing now would lose something, when that changed.
|
||||
/// The new state is recorded before the send: page mode dispatches synchronously, and a
|
||||
/// host that reports another state from that event wins. A failed send is forgotten
|
||||
/// only when nothing else recorded one, so the next frame retries it.
|
||||
pub fn report_dirty(&self, dirty: bool) {
|
||||
let (message, previous) = self.dirty.borrow_mut().prepare(dirty);
|
||||
if let Some(m) = message
|
||||
&& !self.post(&m)
|
||||
{
|
||||
self.dirty.borrow_mut().restore_if_unchanged(dirty, previous);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand a file to the parent instead of downloading it (`lightcraft:save`).
|
||||
pub fn save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let name = save_name(path);
|
||||
let buffer = js_sys::Uint8Array::from(bytes).buffer();
|
||||
self.transfer(&name, buffer)
|
||||
}
|
||||
|
||||
/// [`Bridge::save`] for a blob built outside the wasm heap (the library backup).
|
||||
pub async fn save_blob(&self, name: String, blob: web_sys::Blob) -> Result<(), String> {
|
||||
let buffer = wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await.map_err(|e| format!("{e:?}"))?;
|
||||
self.transfer(&name, buffer.unchecked_into::<js_sys::ArrayBuffer>())
|
||||
}
|
||||
|
||||
fn transfer(&self, name: &str, buffer: js_sys::ArrayBuffer) -> Result<(), String> {
|
||||
self.transport.send("lightcraft:save", &[("name", name.into()), ("bytes", buffer.clone().into())], Some(&buffer))?;
|
||||
log::info!("handed {name} to the page");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A message from the host (the `data` of a window message, or the `detail` of a page-mode
|
||||
/// `CustomEvent`), read with the same field code both transports share, and pushed for the
|
||||
/// next frame.
|
||||
fn deliver(incoming: &Rc<RefCell<Vec<Incoming>>>, ctx: &egui::Context, data: &JsValue, event_type: Option<&str>) {
|
||||
// moved, not cloned: an accepted photo can be hundreds of MB
|
||||
let (bytes, oversize) = match bytes(data) {
|
||||
Some(Ok(b)) => (Some(b), None),
|
||||
Some(Err(len)) => (None, Some(len)),
|
||||
None => (None, None),
|
||||
};
|
||||
let raw = Raw {
|
||||
kind: super::incoming_kind(event_type, string(data, "type")),
|
||||
name: string(data, "name"),
|
||||
bytes,
|
||||
id: string(data, "id"),
|
||||
params: string(data, "params"),
|
||||
oversize,
|
||||
};
|
||||
if let Some(m) = Incoming::parse(raw) {
|
||||
incoming.borrow_mut().push(m);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
fn field(v: &Field) -> JsValue {
|
||||
match v {
|
||||
Field::Str(s) => s.as_str().into(),
|
||||
Field::Bool(b) => (*b).into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> {
|
||||
let m = js_sys::Object::new();
|
||||
for (key, value) in fields {
|
||||
js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?;
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
fn string(data: &JsValue, key: &str) -> Option<String> {
|
||||
js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string()
|
||||
}
|
||||
|
||||
/// `bytes` as an `ArrayBuffer` or `Uint8Array`.
|
||||
/// `bytes` as an `ArrayBuffer` or `Uint8Array`, copied only when within the size cap
|
||||
/// ([`open_size_error`]); `Err(len)` for an oversize one, never copied into the app's memory.
|
||||
fn bytes(data: &JsValue) -> Option<Result<Vec<u8>, u64>> {
|
||||
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
|
||||
let array = if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
|
||||
array.clone()
|
||||
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
|
||||
js_sys::Uint8Array::new(&bytes)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let len = u64::from(array.byte_length());
|
||||
Some(if open_size_error(len).is_some() { Err(len) } else { Ok(array.to_vec()) })
|
||||
}
|
||||
|
||||
/// A `JsValue` error as a string, after `what` went wrong.
|
||||
fn js_error(e: &JsValue, what: &str) -> String {
|
||||
format!("{what}: {}", e.as_string().unwrap_or_else(|| format!("{e:?}")))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn raw(kind: &str) -> Raw {
|
||||
Raw { kind: Some(kind.into()), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_needs_bytes_and_names_a_nameless_photo() {
|
||||
let mut m = raw("lightcraft:open");
|
||||
assert_eq!(Incoming::parse(m.clone()), None, "no bytes, nothing to add");
|
||||
m.bytes = Some(vec![1, 2, 3]);
|
||||
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Open { name: DEFAULT_OPEN_NAME.into(), bytes: vec![1, 2, 3] }));
|
||||
m.name = Some(" ".into());
|
||||
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Open { name: DEFAULT_OPEN_NAME.into(), bytes: vec![1, 2, 3] }));
|
||||
m.name = Some("IMG_0001.CR2".into());
|
||||
assert_eq!(Incoming::parse(m), Some(Incoming::Open { name: "IMG_0001.CR2".into(), bytes: vec![1, 2, 3] }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_needs_an_id_and_defaults_its_params() {
|
||||
let mut m = raw("lightcraft:cmd");
|
||||
assert_eq!(Incoming::parse(m.clone()), None);
|
||||
m.id = Some("library.info".into());
|
||||
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Cmd { id: "library.info".into(), params: "{}".into() }));
|
||||
m.params = Some(r#"{"rating": 5}"#.into());
|
||||
assert_eq!(Incoming::parse(m), Some(Incoming::Cmd { id: "library.info".into(), params: r#"{"rating": 5}"#.into() }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversize_open_is_refused_not_copied() {
|
||||
let max = crate::backup::MAX_BYTES;
|
||||
assert!(open_size_error(max).is_none());
|
||||
assert!(open_size_error(max + 1).is_some_and(|e| e.contains("too large")));
|
||||
let m = Raw { name: Some("big.tif".into()), oversize: Some(max + 1), ..raw("lightcraft:open") };
|
||||
assert!(matches!(Incoming::parse(m), Some(Incoming::Refused(e)) if e.contains("too large")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_pages_messages_are_not_ours() {
|
||||
for kind in ["deckcraft:open", "lightcraft:save", "lightcraft:ready", ""] {
|
||||
let m = Raw { bytes: Some(vec![1]), id: Some("x".into()), ..raw(kind) };
|
||||
assert_eq!(Incoming::parse(m), None, "{kind:?}");
|
||||
}
|
||||
assert_eq!(Incoming::parse(Raw::default()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_messages_name_their_type_first() {
|
||||
let ready = Outgoing::Ready.fields();
|
||||
assert_eq!(ready[0], ("type", Field::Str("lightcraft:ready".into())));
|
||||
assert_eq!(ready[1].0, "version");
|
||||
assert_eq!(Outgoing::Failed("boom".into()).fields()[1], ("error", Field::Str("boom".into())));
|
||||
assert_eq!(Outgoing::Dirty(true).fields(), vec![("type", Field::Str("lightcraft:dirty".into())), ("dirty", Field::Bool(true))]);
|
||||
let r = Outgoing::Response { ok: false, value: "no such command".into() }.fields();
|
||||
assert_eq!(r[1], ("ok", Field::Bool(false)));
|
||||
assert_eq!(r[2], ("value", Field::Str("no such command".into())));
|
||||
}
|
||||
|
||||
/// The parent hears `dirty` when it changes, not every frame, and again if a send failed.
|
||||
#[test]
|
||||
fn dirty_is_reported_on_change_only() {
|
||||
let mut d = DirtyReport::default();
|
||||
assert_eq!(d.change(false), Some(Outgoing::Dirty(false)), "the first state is news");
|
||||
d.sent(false);
|
||||
assert_eq!(d.change(false), None);
|
||||
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
|
||||
// not marked sent (the post failed): still owed
|
||||
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
|
||||
d.sent(true);
|
||||
assert_eq!(d.change(true), None);
|
||||
assert_eq!(d.change(false), Some(Outgoing::Dirty(false)));
|
||||
}
|
||||
|
||||
/// A failed send is retried. A report that lands during the send (page mode dispatches
|
||||
/// synchronously) is the one that stays.
|
||||
#[test]
|
||||
fn a_failed_dirty_send_is_retried_unless_a_later_report_landed() {
|
||||
let mut d = DirtyReport::default();
|
||||
let (message, previous) = d.prepare(true);
|
||||
assert_eq!(message, Some(Outgoing::Dirty(true)));
|
||||
d.restore_if_unchanged(true, previous);
|
||||
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
|
||||
|
||||
let (message, previous) = d.prepare(true);
|
||||
assert!(message.is_some());
|
||||
let (later, _) = d.prepare(false);
|
||||
assert_eq!(later, Some(Outgoing::Dirty(false)));
|
||||
d.restore_if_unchanged(true, previous);
|
||||
assert_eq!(d.change(false), None);
|
||||
}
|
||||
|
||||
/// A canvas event is named for its type; the detail does not have to repeat it.
|
||||
#[test]
|
||||
fn a_page_event_is_named_for_its_type() {
|
||||
assert_eq!(incoming_kind(Some("lightcraft:open"), None).as_deref(), Some("lightcraft:open"));
|
||||
assert_eq!(incoming_kind(Some("lightcraft:cmd"), Some("lightcraft:open".into())).as_deref(), Some("lightcraft:cmd"));
|
||||
assert_eq!(incoming_kind(None, Some("lightcraft:open".into())).as_deref(), Some("lightcraft:open"));
|
||||
assert_eq!(incoming_kind(None, None), None);
|
||||
}
|
||||
|
||||
/// A sandboxed iframe or a `data:` page has the opaque origin `"null"`, which any other such
|
||||
/// window shares: no bridge there, so the origin check keeps meaning something.
|
||||
#[test]
|
||||
fn an_opaque_origin_gets_no_bridge() {
|
||||
assert!(origin_is_usable("https://photos.example"));
|
||||
assert!(origin_is_usable("http://localhost:8080"));
|
||||
assert!(!origin_is_usable("null"));
|
||||
assert!(!origin_is_usable(" null "));
|
||||
assert!(!origin_is_usable(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_files_are_handed_over_by_file_name() {
|
||||
assert_eq!(save_name("exports/2026/IMG_0001.jpg"), "IMG_0001.jpg");
|
||||
assert_eq!(save_name("IMG_0001.jpg"), "IMG_0001.jpg");
|
||||
assert_eq!(save_name("lightcraft-library-backup-2026-10-19.zip"), "lightcraft-library-backup-2026-10-19.zip");
|
||||
}
|
||||
|
||||
/// Page mode is opt-in by the exact attribute value, parent mode by the query, and parent
|
||||
/// mode wins when a page asks for both.
|
||||
#[test]
|
||||
fn page_mode_is_opt_in_and_parent_mode_wins_when_both_are_set() {
|
||||
assert_eq!(transport_for(Some("page"), ""), Some(Mode::Page));
|
||||
assert_eq!(transport_for(Some("page"), "?host=parent"), Some(Mode::Parent), "parent mode wins");
|
||||
// only the exact value opts in; anything else falls back to the query, or to standalone
|
||||
for not_page in ["Page", " page", "page ", "parent", "host"] {
|
||||
assert_eq!(transport_for(Some(not_page), "?host=parent"), Some(Mode::Parent), "{not_page:?}");
|
||||
assert_eq!(transport_for(Some(not_page), ""), None, "{not_page:?}");
|
||||
}
|
||||
assert_eq!(transport_for(None, ""), None);
|
||||
assert_eq!(transport_for(None, "?store=idb"), None);
|
||||
assert_eq!(transport_for(None, "?host="), None);
|
||||
assert_eq!(transport_for(None, "?host=Parent"), None);
|
||||
assert_eq!(transport_for(None, "?xhost=parent"), None);
|
||||
}
|
||||
|
||||
/// The query is read the way the URL options always read it: the first `host` parameter wins,
|
||||
/// and only a value of exactly `parent` counts.
|
||||
#[test]
|
||||
fn the_query_asks_for_the_parent_bridge() {
|
||||
assert!(host_parent_requested("?host=parent"));
|
||||
assert!(host_parent_requested("host=parent"));
|
||||
assert!(host_parent_requested("?host=parent&store=idb"));
|
||||
assert!(host_parent_requested("?store=idb&host=parent"));
|
||||
assert!(!host_parent_requested(""));
|
||||
assert!(!host_parent_requested("?"));
|
||||
assert!(!host_parent_requested("?host"));
|
||||
assert!(!host_parent_requested("?host="));
|
||||
assert!(host_parent_requested("?host=parent&host=id"), "the first host parameter wins");
|
||||
assert!(!host_parent_requested("?host=id&host=parent"));
|
||||
assert!(!host_parent_requested("?hosts=parent"));
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,13 @@
|
||||
//! - export downloads the file through the browser.
|
||||
//!
|
||||
//! `?bench` in the URL runs a scripted first-paint / slider-latency measurement and logs it to the
|
||||
//! console (see [`bench`]); `?store=idb` forces the IndexedDB backend, `?store=memory` disables
|
||||
//! console (see [`bench`]) on the generated demo photos in an unsaved library (it implies `?store=memory`, so it never edits
|
||||
//! the library in browser storage); `?store=idb` forces the IndexedDB backend, `?store=memory` disables
|
||||
//! persistence and `?workers=0` renders on the main thread.
|
||||
//! `?host=parent` speaks to a same-origin page framing LightCraft (see [`host`]): it hands
|
||||
//! photos in, receives what would be downloaded and hears about unsaved changes. A page can also
|
||||
//! host LightCraft in its own document, no iframe: `data-host="page"` on the canvas opts in, and
|
||||
//! the same messages travel as DOM `CustomEvent`s on the canvas.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -24,6 +29,7 @@ pub mod bench;
|
||||
#[cfg(any(test, target_arch = "wasm32"))]
|
||||
mod drop_gate;
|
||||
pub mod files;
|
||||
pub mod host;
|
||||
pub mod store;
|
||||
pub mod wire;
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::backend::Backend;
|
||||
use crate::backup::{
|
||||
ACTIVE_LIBRARY, README, ZipWriter, data_offset, find_central, original_entry, parse_central, restore_key, restored_dir_name, tail_len,
|
||||
ACTIVE_LIBRARY, README, ZipWriter, data_offset, find_central, original_entry, parse_central, restore_plan, restored_dir_name, tail_len,
|
||||
valid_hash, verify, verify_original,
|
||||
};
|
||||
use crate::files::{Files, LIBRARY_FILES};
|
||||
@@ -149,10 +149,14 @@ pub fn download_blob(name: &str, blob: &web_sys::Blob) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where a finished backup goes: the browser's downloads ([`download_blob`]), or the page framing
|
||||
/// LightCraft (`?host=parent`). Awaited, so the backup counts as done only once it is handed over.
|
||||
pub type Deliver = Box<dyn FnOnce(String, web_sys::Blob) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>>>>>;
|
||||
|
||||
/// File ▸ Back Up Library…: a zip of the library files (as the app has them, saved or not) and
|
||||
/// every original in storage, built entry by entry into the browser's memory (outside the wasm
|
||||
/// heap) and downloaded. `names`: content hash → the photo's file name.
|
||||
pub async fn backup(files: Files, backend: Backend, names: HashMap<String, String>) -> Result<(usize, f64), String> {
|
||||
/// heap) and handed to `deliver`. `names`: content hash → the photo's file name.
|
||||
pub async fn backup(files: Files, backend: Backend, names: HashMap<String, String>, deliver: Deliver) -> Result<(usize, f64), String> {
|
||||
let parts = js_sys::Array::new();
|
||||
let mut zip = ZipWriter::default();
|
||||
let mut bytes = 0f64;
|
||||
@@ -190,7 +194,7 @@ pub async fn backup(files: Files, backend: Backend, names: HashMap<String, Strin
|
||||
opts.set_type("application/zip");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(|e| format!("{e:?}"))?;
|
||||
let day: String = String::from(js_sys::Date::new_0().to_iso_string()).chars().take(10).collect();
|
||||
download_blob(&format!("lightcraft-library-backup-{day}.zip"), &blob)?;
|
||||
deliver(format!("lightcraft-library-backup-{day}.zip"), blob).await?;
|
||||
Ok((originals, bytes + tail.len() as f64))
|
||||
}
|
||||
|
||||
@@ -214,8 +218,7 @@ pub async fn restore(file: web_sys::File, backend: Backend) -> Result<String, St
|
||||
}
|
||||
let dir = restored_dir_name(js_sys::Date::now());
|
||||
let mut written = 0usize;
|
||||
for e in &entries {
|
||||
let Some(key) = restore_key(&e.name, &dir) else { continue };
|
||||
for (key, e) in restore_plan(&entries, &dir, len)? {
|
||||
// originals are named by their content: one already stored is the same file
|
||||
if key.starts_with("originals/") && backend.exists(&key).await? {
|
||||
continue;
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use lightcraft_engine::files::{load_bytes, probe_bytes};
|
||||
use lightcraft_engine::files::{load_bytes_decoded, probe_bytes};
|
||||
use lightcraft_engine::media::{FileLoader, FileProbe};
|
||||
|
||||
/// Prefix of the catalog paths of files kept in browser storage.
|
||||
@@ -144,9 +144,11 @@ impl Originals {
|
||||
/// Engine hooks that decode/probe from memory.
|
||||
pub fn hooks(&self) -> (FileLoader, FileProbe) {
|
||||
let s = self.clone();
|
||||
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| {
|
||||
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
|
||||
// whether it decodes in a worker or inline when workers are unavailable)
|
||||
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, with: lightcraft_engine::media::RawDecode<'_>| {
|
||||
let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?;
|
||||
load_bytes(&bytes, max_edge)
|
||||
load_bytes_decoded(&bytes, max_edge, lightcraft_engine::media::RawDecode { dcp: None, outliers: with.outliers })
|
||||
});
|
||||
let s = self.clone();
|
||||
let probe: FileProbe = Arc::new(move |path: &str| {
|
||||
@@ -237,6 +239,64 @@ mod tests {
|
||||
assert_eq!(out.image.width, 20);
|
||||
}
|
||||
|
||||
/// CodeRabbit on #1063: without web workers a render runs inline and handed the selected camera profile to this
|
||||
/// loader, which applied it, so the picture differed from the worker's (which keeps the raw's own colour, the
|
||||
/// documented web behaviour). The loader now ignores it.
|
||||
#[test]
|
||||
fn the_web_loader_keeps_a_raws_own_colour_with_a_camera_profile() {
|
||||
use lightcraft_raw::*;
|
||||
let (w, h) = (32usize, 24usize);
|
||||
let raw = RawImage {
|
||||
format: RawFormat::Dng,
|
||||
width: w,
|
||||
height: h,
|
||||
cpp: 1,
|
||||
data: RawData::U16((0..w * h).map(|i| 256 + ((i % w) * 300 + (i / w) * 200) as u16).collect()),
|
||||
cfa: Cfa::bayer("RGGB"),
|
||||
bits: 14,
|
||||
black: BlackLevel::uniform(256.0),
|
||||
white: vec![16000.0],
|
||||
active_area: Rect::new(0, 0, w, h),
|
||||
crop: Rect::new(0, 0, w, h),
|
||||
orientation: Orientation::Normal,
|
||||
color: ColorData {
|
||||
illuminant: [21, 0],
|
||||
color_matrix: [Some(lightcraft_color::Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]])), None],
|
||||
as_shot_neutral: Some([0.5, 1.0, 0.7]),
|
||||
..Default::default()
|
||||
},
|
||||
wb_multipliers: None,
|
||||
linearized: false,
|
||||
pixel_aspect: 1.0,
|
||||
opcodes: OpcodeLists::default(),
|
||||
metadata: Default::default(),
|
||||
lens_metadata: Default::default(),
|
||||
};
|
||||
let dng = write_dng(&raw, &DngWriteOptions::default()).unwrap();
|
||||
// our own numbers: a matrix that swaps the camera's red and blue
|
||||
let swap = lightcraft_color::Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]).mul(&lightcraft_color::Mat3([
|
||||
[3.2406, -1.5372, -0.4986],
|
||||
[-0.9689, 1.8758, 0.0415],
|
||||
[0.0557, -0.2040, 1.0570],
|
||||
]));
|
||||
let profile = dcp::DcpProfile {
|
||||
name: "Swap".into(),
|
||||
camera_model: "LightCraft Test Camera".into(),
|
||||
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
|
||||
};
|
||||
assert_ne!(
|
||||
lightcraft_engine::files::load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
|
||||
lightcraft_engine::files::load_bytes_with(&dng, 64, None).unwrap().0.data,
|
||||
"the profile changes a raw's colour where it is applied"
|
||||
);
|
||||
let store = Originals::default();
|
||||
store.insert("h1", Arc::from(dng));
|
||||
let (loader, _) = store.hooks();
|
||||
let with = loader("web/h1/a.dng", 64, lightcraft_engine::media::RawDecode { dcp: Some(&profile), outliers: false }).unwrap();
|
||||
let without = loader("web/h1/a.dng", 64, Default::default()).unwrap();
|
||||
assert_eq!(with.0.data, without.0.data, "the web loader leaves it out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_names() {
|
||||
assert_eq!(download_name("dir/x-lightcraft.png"), "x-lightcraft.png");
|
||||
|
||||
+186
-23
@@ -2,14 +2,14 @@
|
||||
//! `<canvas id="lightcraft_canvas">`, wires the file picker and drag-and-drop, and turns exports
|
||||
//! into downloads.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_engine::Session;
|
||||
use lightcraft_engine::catalog::Source;
|
||||
use lightcraft_engine::library::LibraryStores;
|
||||
use lightcraft_ui_egui::{LightcraftApp, Services, UiState};
|
||||
use lightcraft_ui_egui::{LightcraftApp, Services, UiState, WriteFn};
|
||||
use serde_json::json;
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::prelude::*;
|
||||
@@ -18,6 +18,7 @@ use crate::backend::Backend;
|
||||
use crate::backup::{ACTIVE_LIBRARY, DEFAULT_LIBRARY_DIR, valid_library_dir};
|
||||
use crate::bench::Bench;
|
||||
use crate::files::{Files, FlushOp, LIBRARY_FILES};
|
||||
use crate::host::{Incoming, Outgoing};
|
||||
use crate::safety::{self, notice};
|
||||
use crate::store::{Originals, content_hash, download_name, storage_key};
|
||||
use crate::wire::ThumbIndex;
|
||||
@@ -68,13 +69,15 @@ pub(crate) fn request_repaint() {
|
||||
});
|
||||
}
|
||||
|
||||
/// URL options (`?bench&store=idb&workers=2&reset`).
|
||||
/// URL options (`?bench&store=idb&workers=2&reset&host=parent`).
|
||||
struct Options {
|
||||
bench: bool,
|
||||
/// "opfs" (default: OPFS, falling back to IndexedDB), "idb" or "memory".
|
||||
store: String,
|
||||
workers: Option<usize>,
|
||||
reset: bool,
|
||||
/// The raw query string, for the host mode ([`crate::host::transport_for`]).
|
||||
query: String,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
@@ -90,11 +93,15 @@ impl Options {
|
||||
})
|
||||
.collect();
|
||||
let get = |k: &str| params.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
|
||||
let bench = get("bench").is_some();
|
||||
Options {
|
||||
bench: get("bench").is_some(),
|
||||
store: get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()),
|
||||
workers: get("workers").and_then(|v| v.parse().ok()),
|
||||
bench,
|
||||
// the benchmark edits the first photo it finds: a link with `?bench` must never reach
|
||||
// the library in browser storage, so it always runs on the demo photos in an unsaved library
|
||||
store: if bench { "memory".into() } else { get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()) },
|
||||
workers: get("workers").and_then(|v| v.parse().ok()).map(|n: usize| n.min(crate::workers::MAX_WORKERS)),
|
||||
reset: get("reset").is_some(),
|
||||
query: q,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,12 +175,75 @@ fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keep egui's hidden text field content-box, so host page CSS cannot misplace typed text:
|
||||
/// eframe (0.36 web) types through a hidden `<input type="text">` it inserts as the canvas's
|
||||
/// next sibling, and a host page's global `* { box-sizing: border-box }` reaches it and leaves it
|
||||
/// no content box, so the next key lands before text just committed by an input method or a
|
||||
/// paste-like insert. Inline style beats any host stylesheet rule without `!important`, so the
|
||||
/// property is set on the element itself, in every host mode, and retried on the next animation
|
||||
/// frames while eframe hasn't inserted the field yet.
|
||||
fn fix_text_field_box_sizing() {
|
||||
/// How many animation frames the fix may wait for eframe to insert its hidden text field.
|
||||
const MAX_FRAMES: u32 = 120;
|
||||
|
||||
/// True when the field was found and set: the canvas's next sibling, or an
|
||||
/// `input[type=text]` in the canvas's parent.
|
||||
fn fix_once() -> bool {
|
||||
let Some(doc) = window().and_then(|w| w.document()) else { return false };
|
||||
let Some(canvas) = doc.get_element_by_id("lightcraft_canvas") else { return false };
|
||||
let input = canvas.next_element_sibling().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()).or_else(|| {
|
||||
canvas
|
||||
.parent_element()
|
||||
.and_then(|p| p.query_selector("input[type=text]").ok())
|
||||
.flatten()
|
||||
.and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok())
|
||||
});
|
||||
input.is_some_and(|i| i.style().set_property("box-sizing", "content-box").is_ok())
|
||||
}
|
||||
|
||||
// the closure reschedules itself until the field is fixed or the frames run out; done, it is
|
||||
// left parked in its slot (dropping it from inside itself would free its own state, and the
|
||||
// slot holds the only reference) — a one-off leak, like the forgotten listeners
|
||||
let tries = Rc::new(Cell::new(MAX_FRAMES));
|
||||
let slot: Rc<RefCell<Option<Closure<dyn FnMut()>>>> = Rc::default();
|
||||
let own = Rc::clone(&slot);
|
||||
*slot.borrow_mut() = Some(Closure::new(move || {
|
||||
if fix_once() || tries.get() <= 1 {
|
||||
return; // done: stop rescheduling
|
||||
}
|
||||
tries.set(tries.get() - 1);
|
||||
let again = own.borrow_mut().take();
|
||||
if let Some(again) = again {
|
||||
let _ = window().and_then(|w| w.request_animation_frame(again.as_ref().unchecked_ref()).ok());
|
||||
// put the same closure back, now that the frame it was handed to has its own reference
|
||||
*own.borrow_mut() = Some(again);
|
||||
}
|
||||
}));
|
||||
let first = slot.borrow_mut().take();
|
||||
if let Some(first) = first {
|
||||
let _ = window().and_then(|w| w.request_animation_frame(first.as_ref().unchecked_ref()).ok());
|
||||
*slot.borrow_mut() = Some(first);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the browser host's `Services`: library backup/restore through browser storage and a
|
||||
/// download, asynchronous file picking, downloads for writes, and PNG encoding. Desktop-only
|
||||
/// services (native pickers, reveal, model folders) stay unset.
|
||||
fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen: Rc<Cell<bool>>, ctx: egui::Context) -> Services {
|
||||
let (backup_backend, backup_files) = (backend.clone(), files);
|
||||
fn services(
|
||||
originals: Originals,
|
||||
backend: Option<Backend>,
|
||||
files: Files,
|
||||
frozen: Rc<Cell<bool>>,
|
||||
ctx: egui::Context,
|
||||
bridge: Option<crate::host::Bridge>,
|
||||
) -> Services {
|
||||
let (backup_backend, backup_files, backup_bridge) = (backend.clone(), files, bridge.clone());
|
||||
let restore_backend = backend.clone();
|
||||
// what would be downloaded goes to the page framing LightCraft instead, when there is one
|
||||
let write: WriteFn = match bridge {
|
||||
Some(bridge) => Box::new(move |path: &str, bytes: &[u8]| bridge.save(path, bytes)),
|
||||
None => Box::new(download),
|
||||
};
|
||||
Services {
|
||||
local_places: None,
|
||||
picker: None,
|
||||
@@ -194,9 +264,18 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
|
||||
})
|
||||
.collect();
|
||||
let files = backup_files.clone();
|
||||
notice("Backing up the library… (the download starts when it's ready)");
|
||||
// awaited by `backup`: "backed up" is said only once the page has the file
|
||||
let deliver: safety::Deliver = match backup_bridge.clone() {
|
||||
Some(bridge) => Box::new(move |name: String, blob: web_sys::Blob| Box::pin(async move { bridge.save_blob(name, blob).await })),
|
||||
None => Box::new(|name: String, blob: web_sys::Blob| Box::pin(async move { safety::download_blob(&name, &blob) })),
|
||||
};
|
||||
notice(if backup_bridge.is_some() {
|
||||
"Backing up the library… (handed to the page when it's ready)"
|
||||
} else {
|
||||
"Backing up the library… (the download starts when it's ready)"
|
||||
});
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match safety::backup(files, b, names).await {
|
||||
match safety::backup(files, b, names, deliver).await {
|
||||
Ok((n, bytes)) => notice(format!(
|
||||
"Library backed up: {n} original{} ({:.1} MB). Keep the file somewhere safe.",
|
||||
if n == 1 { "" } else { "s" },
|
||||
@@ -234,7 +313,7 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
|
||||
save_slideshow_template: None,
|
||||
pick_print_templates: None,
|
||||
save_print_template: None,
|
||||
write: Some(Box::new(download)),
|
||||
write: Some(write),
|
||||
// the browser download path has no meaningful create-new file write; the control channel
|
||||
// (and therefore screenshot paths) is not available on the web
|
||||
write_new: None,
|
||||
@@ -286,7 +365,8 @@ async fn flush(files: Files, backend: Backend, dir: String, flushing: Rc<Cell<bo
|
||||
}
|
||||
}
|
||||
flushing.set(false);
|
||||
// the page title drops its unsaved • now, even when nothing else wakes the page
|
||||
// the page title drops its unsaved • now, and the page framing LightCraft hears `dirty: false`,
|
||||
// even when nothing else wakes the page
|
||||
request_repaint();
|
||||
}
|
||||
|
||||
@@ -298,12 +378,14 @@ struct Boot {
|
||||
index: ThumbIndex,
|
||||
/// The library folder in storage (`library`, or a restored backup's).
|
||||
lib_dir: String,
|
||||
/// The page framing LightCraft (`?host=parent`), when there is one.
|
||||
bridge: Option<crate::host::Bridge>,
|
||||
/// Library files that exist but couldn't be read (#1507): the library isn't opened and
|
||||
/// nothing is saved, so the stored copy stays as it was.
|
||||
load_error: Option<String>,
|
||||
}
|
||||
|
||||
async fn boot(opts: Options) -> Boot {
|
||||
async fn boot(opts: Options, bridge: Option<crate::host::Bridge>) -> Boot {
|
||||
let t0 = perf_now();
|
||||
let backend = if opts.store == "memory" {
|
||||
None
|
||||
@@ -400,7 +482,7 @@ async fn boot(opts: Options) -> Boot {
|
||||
index.len(),
|
||||
index.total() as f64 / 1e6
|
||||
);
|
||||
Boot { opts, backend, files, index, lib_dir, load_error }
|
||||
Boot { opts, backend, files, index, lib_dir, bridge, load_error }
|
||||
}
|
||||
|
||||
struct WebApp {
|
||||
@@ -421,6 +503,7 @@ struct WebApp {
|
||||
title: String,
|
||||
last_save: f64,
|
||||
ui_written: Vec<u8>,
|
||||
bridge: Option<crate::host::Bridge>,
|
||||
}
|
||||
|
||||
/// The browser host's drop queues, taken only through the shared gate: a prompt or blocking
|
||||
@@ -455,7 +538,7 @@ impl WebApp {
|
||||
/// browser storage (a read failure starts an empty session and a blocking `LibraryProblem`),
|
||||
/// load the stored UI state, start render workers and the optional benchmark.
|
||||
fn new(cc: &eframe::CreationContext<'_>, boot: Boot, chinese_font: Vec<u8>) -> Self {
|
||||
let Boot { opts, backend, files, index, lib_dir, load_error } = boot;
|
||||
let Boot { opts, backend, files, index, lib_dir, bridge, load_error } = boot;
|
||||
let originals = Originals::default();
|
||||
let t = perf_now();
|
||||
let mut session = Session::new();
|
||||
@@ -496,6 +579,10 @@ impl WebApp {
|
||||
});
|
||||
}
|
||||
}
|
||||
// `?bench` never has storage (see `Options::from_url`): it measures the generated demo photos
|
||||
if opts.bench && backend.is_none() && session.catalog.len() == 0 {
|
||||
lightcraft_engine::demo::load(&mut session);
|
||||
}
|
||||
if backend.is_some() {
|
||||
notice(
|
||||
"LightCraft in the browser is experimental. Your library is kept in this browser's storage: keep your original photos \
|
||||
@@ -506,13 +593,16 @@ impl WebApp {
|
||||
session.media.preview_capacity = 3;
|
||||
// nothing is saved while the stored library couldn't be read
|
||||
let frozen = Rc::new(Cell::new(read_failed));
|
||||
let mut app = LightcraftApp::new(session, services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone()))
|
||||
.with_chinese_font(chinese_font);
|
||||
let services = services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone(), bridge.clone());
|
||||
let mut app = LightcraftApp::new(session, services).with_chinese_font(chinese_font);
|
||||
let ui_written = files.get("ui.json").unwrap_or_default();
|
||||
// an arrangement from an older docking version starts again from the default
|
||||
let mut saved = serde_json::from_slice::<serde_json::Value>(&ui_written).unwrap_or_default();
|
||||
if let Some(fields) = saved.as_object_mut() {
|
||||
lightcraft_ui_egui::docking::drop_outdated(fields);
|
||||
// a stored ui.json means an installation that has been run: due What's New, never
|
||||
// the first-run tour (the same migration the desktop settings loader runs)
|
||||
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
|
||||
}
|
||||
if let Ok(ui) = serde_json::from_value::<UiState>(saved) {
|
||||
app.ui = ui;
|
||||
@@ -540,6 +630,13 @@ impl WebApp {
|
||||
}
|
||||
log::info!("lightcraft: {n} render workers");
|
||||
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
|
||||
if let Some(b) = &bridge {
|
||||
// hear the page from now on, and tell it the app is listening
|
||||
b.listen(cc.egui_ctx.clone());
|
||||
if !b.post(&Outgoing::Ready) {
|
||||
log::warn!("lightcraft: the page framing LightCraft could not be told the app is ready");
|
||||
}
|
||||
}
|
||||
let origin = lightcraft_ui_egui::monotonic_ms();
|
||||
WebApp {
|
||||
app,
|
||||
@@ -556,9 +653,49 @@ impl WebApp {
|
||||
title: String::new(),
|
||||
last_save: 0.0,
|
||||
ui_written,
|
||||
bridge,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the page framing LightCraft sent since the last frame: photos to add (as if dropped
|
||||
/// on the window) and commands to run, each answered with `lightcraft:response`.
|
||||
fn run_host(&mut self, ctx: &egui::Context) {
|
||||
let Some(bridge) = self.bridge.clone() else { return };
|
||||
for m in bridge.take_incoming() {
|
||||
match m {
|
||||
Incoming::Open { name, bytes } => {
|
||||
wasm_bindgen_futures::spawn_local(store_file(self.originals.clone(), self.backend.clone(), name, bytes, ctx.clone()));
|
||||
}
|
||||
Incoming::Refused(error) => {
|
||||
if !bridge.post(&Outgoing::Failed(error)) {
|
||||
log::warn!("lightcraft: a refused open could not be reported to the page");
|
||||
}
|
||||
}
|
||||
Incoming::Cmd { id, params } => {
|
||||
let r = match crate::automation::params(¶ms) {
|
||||
Err(e) => Err(format!("{id}: {e}")),
|
||||
Ok(_) if id == "web.stats" => Ok(self.web_stats()),
|
||||
Ok(params) => self.app.run(&id, params),
|
||||
};
|
||||
let response = match r {
|
||||
Ok(v) => Outgoing::Response { ok: true, value: v.to_string() },
|
||||
Err(e) => Outgoing::Response { ok: false, value: e },
|
||||
};
|
||||
if !bridge.post(&response) {
|
||||
log::warn!("lightcraft: the answer to {id} could not reach the page");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether closing the page now would lose something: a write to browser storage still
|
||||
/// queued or running, or changes storage refused (quota). The page framing LightCraft hears
|
||||
/// when this changes (`lightcraft:dirty`), so it can ask before closing a window with edits.
|
||||
fn dirty_for_host(&self) -> bool {
|
||||
self.files.is_dirty() || self.flushing.get() || self.app.session.unsaved().is_some()
|
||||
}
|
||||
|
||||
/// Consume the drops the raw-input hook queued once (never re-read `raw.dropped_files` in a
|
||||
/// hidden logic tick), and add originals whose bytes have arrived.
|
||||
fn import_dropped(&mut self, ctx: &egui::Context) {
|
||||
@@ -735,6 +872,7 @@ impl eframe::App for WebApp {
|
||||
self.app.ui.toast = Some((text, now + NOTICE_SECS, None));
|
||||
}
|
||||
self.run_inbox();
|
||||
self.run_host(ctx);
|
||||
self.load_originals(ctx);
|
||||
if let Some(w) = &self.workers {
|
||||
// `library.preferences ▸ cacheMb` is read by the session; the worker index prunes on
|
||||
@@ -743,6 +881,9 @@ impl eframe::App for WebApp {
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
self.save();
|
||||
if let Some(b) = &self.bridge {
|
||||
b.report_dirty(self.dirty_for_host());
|
||||
}
|
||||
}
|
||||
|
||||
/// Pass the browser's raw input to the app hook before egui processes it, so prompt barriers
|
||||
@@ -830,6 +971,21 @@ pub fn start(chinese_font: Vec<u8>) {
|
||||
log::warn!("lightcraft: no Simplified Chinese font supplied; Chinese-only glyphs will show as boxes");
|
||||
}
|
||||
let opts = Options::from_url();
|
||||
// `?host=parent`: a same-origin page framing LightCraft hands photos in, stores what would
|
||||
// be downloaded and hears about unsaved changes (see `host`). `data-host="page"` on the
|
||||
// canvas opts a page in instead: it runs LightCraft in its own document and talks over DOM
|
||||
// `CustomEvent`s on the canvas. `?host=parent` wins when a page asks for both.
|
||||
let canvas = window()
|
||||
.and_then(|w| w.document())
|
||||
.and_then(|d| d.get_element_by_id("lightcraft_canvas"))
|
||||
.and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok());
|
||||
let mode = crate::host::transport_for(canvas.as_ref().and_then(|c| c.get_attribute("data-host")).as_deref(), &opts.query);
|
||||
let bridge = mode.and_then(|m| crate::host::Bridge::for_mode(m, canvas.as_ref()));
|
||||
if mode == Some(crate::host::Mode::Parent) && bridge.is_none() {
|
||||
log::warn!(
|
||||
"lightcraft: ?host=parent, but this page is not framed, has an opaque origin, or its parent is on another origin; exports keep downloading"
|
||||
);
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// one tab per library: two would each keep their own copy and overwrite each other's saves
|
||||
if opts.store != "memory" && safety::acquire_tab_lock().await == Some(false) {
|
||||
@@ -837,17 +993,19 @@ pub fn start(chinese_font: Vec<u8>) {
|
||||
"LightCraft is already open in another tab or window of this browser.\n\n\
|
||||
Switch to that tab, or close it and reload this page. (Two tabs would overwrite each other's changes.)",
|
||||
);
|
||||
if let Some(b) = &bridge {
|
||||
b.post(&Outgoing::Failed("LightCraft is already open in another tab or window of this browser".into()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(canvas) = window()
|
||||
.and_then(|w| w.document())
|
||||
.and_then(|d| d.get_element_by_id("lightcraft_canvas"))
|
||||
.and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok())
|
||||
else {
|
||||
let Some(canvas) = canvas else {
|
||||
log::error!("missing <canvas id=\"lightcraft_canvas\">");
|
||||
if let Some(b) = &bridge {
|
||||
b.post(&Outgoing::Failed("the page has no <canvas id=\"lightcraft_canvas\">".into()));
|
||||
}
|
||||
return;
|
||||
};
|
||||
let boot = boot(opts).await;
|
||||
let boot = boot(opts, bridge.clone()).await;
|
||||
let runner = eframe::WebRunner::new();
|
||||
let r = runner.start(canvas, eframe::WebOptions::default(), Box::new(move |cc| Ok(Box::new(WebApp::new(cc, boot, chinese_font))))).await;
|
||||
match r {
|
||||
@@ -855,10 +1013,15 @@ pub fn start(chinese_font: Vec<u8>) {
|
||||
if let Some(el) = window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id("lightcraft_loading")) {
|
||||
el.remove();
|
||||
}
|
||||
// the runner just started: egui's hidden text field exists from now on
|
||||
fix_text_field_box_sizing();
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("LightCraft failed to start: {e:?}");
|
||||
set_status(&format!("LightCraft failed to start: {e:?}"));
|
||||
if let Some(b) = &bridge {
|
||||
b.post(&Outgoing::Failed(format!("{e:?}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct WireJob {
|
||||
pub origin: Source,
|
||||
/// Decode the source at most this long.
|
||||
pub max_edge: usize,
|
||||
/// Resize an already decoded source exactly as the engine's cached-source path does.
|
||||
#[serde(default)]
|
||||
pub fit_edge: Option<usize>,
|
||||
pub raw: bool,
|
||||
#[serde(default)]
|
||||
pub relative_wb: bool,
|
||||
@@ -67,7 +70,8 @@ impl WireJob {
|
||||
/// `view`: the slot name, for jobs that keep a stage cache.
|
||||
pub fn from_job(job: &RenderJob, thumb_cached: bool, view: &str) -> WireJob {
|
||||
let max_edge = match &job.source {
|
||||
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } | SourceRef::Fit { max_edge, .. } => *max_edge,
|
||||
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } => *max_edge,
|
||||
SourceRef::Fit { from, .. } => from.image.width.max(from.image.height),
|
||||
SourceRef::Loaded(img) => img.image.width.max(img.image.height),
|
||||
SourceRef::Smart { .. } => 2560,
|
||||
};
|
||||
@@ -77,6 +81,10 @@ impl WireJob {
|
||||
level: job.level,
|
||||
origin: job.origin.clone(),
|
||||
max_edge,
|
||||
fit_edge: match &job.source {
|
||||
SourceRef::Fit { max_edge, .. } => Some(*max_edge),
|
||||
_ => None,
|
||||
},
|
||||
raw: job.info.raw,
|
||||
relative_wb: job.info.relative_wb,
|
||||
legacy_relative_wb: job.info.legacy_relative_wb,
|
||||
@@ -114,6 +122,7 @@ impl WireJob {
|
||||
RenderRequest {
|
||||
max_w: self.max_w,
|
||||
max_h: self.max_h,
|
||||
exact_size: false,
|
||||
quality: if self.draft { Quality::Draft } else { Quality::Full },
|
||||
apply_crop: self.apply_crop,
|
||||
overlay: lightcraft_engine::pipeline::Overlay::from_parts(self.overlay.0, self.overlay.1),
|
||||
@@ -129,7 +138,9 @@ impl WireJob {
|
||||
/// Identifies the decoded source this job needs.
|
||||
fn source_key(&self) -> String {
|
||||
match &self.origin {
|
||||
Source::File { path } => format!("{}:{:?}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge),
|
||||
Source::File { path } => {
|
||||
format!("{}:{:?}:{}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge, self.settings.removes_hot_pixels())
|
||||
}
|
||||
Source::Demo { scene } => format!("{}:{:?}:{}:demo:{scene}", self.cache_generation, self.source_identity, self.max_edge),
|
||||
}
|
||||
}
|
||||
@@ -181,8 +192,10 @@ impl WorkerCore {
|
||||
None => {
|
||||
let src = match (&job.origin, original) {
|
||||
(Source::File { .. }, Some(bytes)) => {
|
||||
let (image, info) = lightcraft_engine::files::load_bytes(bytes, job.max_edge)?;
|
||||
DecodedSource::new(Arc::new(image), Some(info))
|
||||
let outliers = job.settings.removes_hot_pixels();
|
||||
let with = lightcraft_engine::media::RawDecode { dcp: None, outliers };
|
||||
let (image, info) = lightcraft_engine::files::load_bytes_decoded(bytes, job.max_edge, with)?;
|
||||
DecodedSource { outliers, ..DecodedSource::new(Arc::new(image), Some(info)) }
|
||||
}
|
||||
(Source::File { path }, None) => return Err(format!("{path}: original not found in browser storage")),
|
||||
(origin @ Source::Demo { .. }, _) => self.media.origin_ref(origin, job.max_edge).load_source()?,
|
||||
@@ -192,7 +205,13 @@ impl WorkerCore {
|
||||
src
|
||||
}
|
||||
};
|
||||
let src = match job.fit_edge {
|
||||
Some(max_edge) => SourceRef::Fit { from: Box::new(src), max_edge }.load_source()?,
|
||||
None => src,
|
||||
};
|
||||
let info = src.info_or(job.info());
|
||||
// an over-budget brush mask is an error for the caller, not a preview missing its later strokes
|
||||
lightcraft_engine::pipeline::check_brush_budget(&src.image, &info, &job.settings, &job.request())?;
|
||||
let mut rendered = match &job.stages {
|
||||
Some(view) => {
|
||||
let st = self.stages.entry(view.clone()).or_default().clone();
|
||||
@@ -425,6 +444,21 @@ mod tests {
|
||||
assert!(max.is_some_and(|m| m <= 3), "max channel difference {max:?}");
|
||||
}
|
||||
|
||||
// an over-budget brush mask is an error for the caller, as on native
|
||||
#[test]
|
||||
fn an_over_budget_brush_mask_fails_the_render() {
|
||||
use lightcraft_engine::develop::{BrushStroke, Mask, MaskComponent, MaskShape};
|
||||
let mut s = Session::with_demo();
|
||||
let id = s.visible_cloned()[0];
|
||||
let mut wire = WireJob::from_job(&s.thumb_job(id, 128).unwrap(), false, "Thumb");
|
||||
let points = serde_json::from_value(serde_json::json!([{"x": -4000.0, "y": 0.5}, {"x": 4000.0, "y": 0.5}])).unwrap();
|
||||
let far = BrushStroke { points, size: 0.05, ..Default::default() };
|
||||
let component = MaskComponent { name: None, op: Default::default(), invert: false, shape: MaskShape::Brush { strokes: vec![far; 10] } };
|
||||
Arc::make_mut(&mut wire.settings).masks.push(Mask { visible: true, components: vec![component], ..Default::default() });
|
||||
let err = WorkerCore::default().render(&wire, None).err().unwrap_or_default();
|
||||
assert!(err.contains("dabs"), "{err}");
|
||||
}
|
||||
|
||||
// a job from before windows existed has none
|
||||
#[test]
|
||||
fn a_job_without_a_window_field_has_no_window() {
|
||||
@@ -451,7 +485,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);
|
||||
@@ -468,6 +506,7 @@ mod tests {
|
||||
level: SourceLevel::Thumb,
|
||||
origin,
|
||||
max_edge: 512,
|
||||
fit_edge: None,
|
||||
raw: false,
|
||||
relative_wb: false,
|
||||
legacy_relative_wb: false,
|
||||
|
||||
@@ -207,6 +207,15 @@ impl Inner {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most workers started, whatever `?workers=` asks: more than this brings nothing to a
|
||||
/// render queue and a link can't make the page spawn workers (and their copies of the module)
|
||||
/// without end.
|
||||
pub const MAX_WORKERS: usize = 16;
|
||||
|
||||
/// Worker constructions failing in a row after which the rest are not tried: a browser that
|
||||
/// refused this many refuses the next ones too.
|
||||
const MAX_FAILED_STARTS: usize = 3;
|
||||
|
||||
/// The main thread's handle on the render workers.
|
||||
#[derive(Clone)]
|
||||
pub struct Workers(Rc<RefCell<Inner>>);
|
||||
@@ -244,7 +253,12 @@ impl Workers {
|
||||
return w;
|
||||
}
|
||||
let mut slots = WorkerSlots::default();
|
||||
for attempt in 0..n {
|
||||
let mut failed = 0;
|
||||
for attempt in 0..n.min(MAX_WORKERS) {
|
||||
if failed >= MAX_FAILED_STARTS {
|
||||
log::warn!("render workers: {failed} failed to start in a row; not trying the rest");
|
||||
break;
|
||||
}
|
||||
// The callbacks name their worker by its place in `workers`; a failed attempt takes none.
|
||||
let i = slots.peek();
|
||||
let opts = web_sys::WorkerOptions::new();
|
||||
@@ -254,6 +268,7 @@ impl Workers {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
log::warn!("render worker {attempt}: {e:?}");
|
||||
failed += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -274,10 +289,12 @@ impl Workers {
|
||||
worker.set_onmessage(None);
|
||||
worker.set_onerror(None);
|
||||
worker.terminate();
|
||||
failed += 1;
|
||||
continue;
|
||||
}
|
||||
w.0.borrow_mut().workers.push(W { worker, ready: false, dead: false, busy: None });
|
||||
slots.commit();
|
||||
failed = 0;
|
||||
}
|
||||
w
|
||||
}
|
||||
@@ -301,6 +318,7 @@ impl Workers {
|
||||
loaded: None,
|
||||
quick: None,
|
||||
display: None,
|
||||
frame: None,
|
||||
};
|
||||
g.done.push((b.slot, r, 0.0));
|
||||
}
|
||||
@@ -392,6 +410,7 @@ impl Workers {
|
||||
loaded: None,
|
||||
quick: None,
|
||||
display: None,
|
||||
frame: None,
|
||||
},
|
||||
ms,
|
||||
));
|
||||
@@ -446,6 +465,7 @@ impl RenderOffload for Workers {
|
||||
loaded: None,
|
||||
quick: None,
|
||||
display: None,
|
||||
frame: None,
|
||||
};
|
||||
g.done.push((slot, r, 0.0));
|
||||
return None;
|
||||
|
||||
@@ -13,7 +13,7 @@ workspace = true
|
||||
default = ["denoise"]
|
||||
denoise = ["lightcraft-engine/denoise"]
|
||||
rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"]
|
||||
# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it (HEVC patents); build with `--features heif` to include it.
|
||||
heif = ["lightcraft-codecs/heif"]
|
||||
|
||||
@@ -58,3 +58,6 @@ lightcraft-testkit = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# the colour profile of the monitor showing the window (`win_screen_profile`)
|
||||
lightcraft-wincolor = { workspace = true }
|
||||
raw-window-handle = "0.6"
|
||||
@@ -18,8 +18,6 @@ use std::time::Duration;
|
||||
const POLL: Duration = Duration::from_secs(3);
|
||||
/// A wait before trying again when colord isn't there (not installed, no system bus).
|
||||
const RETRY: Duration = Duration::from_secs(30);
|
||||
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
|
||||
const MAX_PROFILE: u64 = 16 << 20;
|
||||
|
||||
const SERVICE: &str = "org.freedesktop.ColorManager";
|
||||
const DEVICE: &str = "org.freedesktop.ColorManager.Device";
|
||||
@@ -72,7 +70,7 @@ fn read(conn: &zbus::blocking::Connection) -> Option<Vec<u8>> {
|
||||
}
|
||||
}
|
||||
let file = pick(&files)?;
|
||||
load(std::path::Path::new(file))
|
||||
crate::profile_file::load(std::path::Path::new(file))
|
||||
}
|
||||
|
||||
/// The profile to use for these displays' profile files: the one they share, `None` with none or
|
||||
@@ -83,15 +81,6 @@ fn pick(files: &[String]) -> Option<&str> {
|
||||
named.all(|f| f == first).then_some(first)
|
||||
}
|
||||
|
||||
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
|
||||
fn load(path: &std::path::Path) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
|
||||
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -105,21 +94,4 @@ mod tests {
|
||||
assert_eq!(pick(&s(&["/a.icc", "/b.icc"])), None, "which one the window is on isn't known");
|
||||
assert_eq!(pick(&s(&[""])), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_files_are_read_with_a_size_cap() {
|
||||
let dir = std::env::temp_dir().join(format!("colord-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let small = dir.join("small.icc");
|
||||
std::fs::write(&small, b"acsp").unwrap();
|
||||
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
|
||||
let empty = dir.join("empty.icc");
|
||||
std::fs::write(&empty, b"").unwrap();
|
||||
assert_eq!(load(&empty), None);
|
||||
assert_eq!(load(&dir.join("missing.icc")), None);
|
||||
let big = dir.join("big.icc");
|
||||
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
|
||||
assert_eq!(load(&big), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -167,7 +167,19 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
|
||||
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
|
||||
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
|
||||
let message = message.strip_suffix('\n').unwrap_or(message);
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
|
||||
// A message can carry text from files and peers (a file name, a rejected value): it must not be able to start a
|
||||
// record of its own. Later lines of a multi-line message (a panic report) are indented, so none begins like a
|
||||
// record; other control characters (a bare CR, an escape sequence) are shown escaped.
|
||||
let mut safe = String::with_capacity(message.len());
|
||||
for c in message.chars() {
|
||||
match c {
|
||||
'\n' => safe.push_str("\n "),
|
||||
'\t' => safe.push(c),
|
||||
c if c.is_control() => safe.extend(c.escape_default()),
|
||||
c => safe.push(c),
|
||||
}
|
||||
}
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {safe}\n")
|
||||
}
|
||||
|
||||
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
|
||||
|
||||
@@ -167,7 +167,11 @@ fn a_line_carries_time_level_thread_target_and_message() {
|
||||
"2026-10-08T07:59:17.728Z INFO [main] lightcraft: library /photos: 12 photos\n"
|
||||
);
|
||||
// A multi-line message keeps its lines; the record still ends in one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
|
||||
// later lines are indented and control characters escaped, so a message cannot forge a record
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n b\n"));
|
||||
let forged = format_line("t", log::Level::Info, "w", "x", "name\r\n2026-01-01T00:00:00Z ERROR [main] x: fake\u{1b}[2J");
|
||||
assert!(forged.lines().skip(1).all(|l| l.starts_with(' ')), "{forged:?}");
|
||||
assert!(!forged.contains('\r') && !forged.contains('\u{1b}'), "{forged:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -357,7 +361,7 @@ fn a_panic_report_goes_to_the_file_and_never_deadlocks() {
|
||||
logger.record_panic("main", "while the sink is held");
|
||||
}
|
||||
let text = read(&path);
|
||||
assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\nboom\n"), "{text}");
|
||||
assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\n boom\n"), "{text}");
|
||||
assert!(!text.contains("while the sink is held"), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -35,8 +35,12 @@ mod hdr_display;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
mod profile_file;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod screen_profile;
|
||||
#[cfg(windows)]
|
||||
mod win_screen_profile;
|
||||
mod window_gpu;
|
||||
|
||||
use dialog_filter::FileDialogExt as _;
|
||||
@@ -79,7 +83,67 @@ fn app_icon() -> egui::IconData {
|
||||
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
|
||||
}
|
||||
|
||||
struct App(LightcraftApp, PrefsWriter, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
|
||||
struct App(LightcraftApp, PrefsWriter, Option<WindowTextures>, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
|
||||
|
||||
/// Draws renders that stayed on the GPU: registers their textures with the window's egui-wgpu
|
||||
/// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]).
|
||||
struct WindowTextures {
|
||||
device: eframe::wgpu::Device,
|
||||
queue: eframe::wgpu::Queue,
|
||||
renderer: std::sync::Arc<egui::mutex::RwLock<eframe::egui_wgpu::Renderer>>,
|
||||
}
|
||||
|
||||
impl lightcraft_ui_egui::render::ScreenTextures for WindowTextures {
|
||||
fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option<egui::TextureId>) -> Option<egui::TextureId> {
|
||||
let view = frame.texture.create_view(&Default::default());
|
||||
let mut r = self.renderer.write();
|
||||
let filter = eframe::wgpu::FilterMode::Linear;
|
||||
Some(match id {
|
||||
Some(id) => {
|
||||
r.update_egui_texture_from_wgpu_texture(&self.device, &view, filter, id);
|
||||
id
|
||||
}
|
||||
None => r.register_native_texture(&self.device, &view, filter),
|
||||
})
|
||||
}
|
||||
|
||||
fn free(&mut self, id: egui::TextureId) {
|
||||
self.renderer.write().free_texture(&id);
|
||||
}
|
||||
|
||||
fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option<egui::ColorImage> {
|
||||
match lightcraft_engine::gpu::read_texture(&self.device, &self.queue, &frame.texture, frame.width, frame.height) {
|
||||
Ok(img) => Some(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], img.data.as_flattened())),
|
||||
Err(e) => {
|
||||
log::warn!("gpu: a view can't be read back for the screenshot: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render on the window's device (off the UI thread: building the kernels takes a moment), so the
|
||||
/// loupe's drafts are drawn straight from the GPU; the textures they leave are shown through
|
||||
/// [`WindowTextures`] once that worked. Otherwise the GPU renderer makes a device of its own, as
|
||||
/// before, and every render comes back as pixels.
|
||||
fn adopt_window_device(rs: &eframe::egui_wgpu::RenderState, ctx: &egui::Context) -> WindowTextures {
|
||||
let (device, queue, info) = (rs.device.clone(), rs.queue.clone(), rs.adapter.get_info());
|
||||
let ctx = ctx.clone();
|
||||
// before the first frame's GPU warm-up can start a device of its own
|
||||
lightcraft_engine::gpu::set_window_device_pending(true);
|
||||
let spawned = std::thread::Builder::new().name("lc-gpu-window".into()).spawn(move || {
|
||||
match lightcraft_engine::gpu::adopt_window_device(device, queue, info) {
|
||||
Ok(()) => log::info!("gpu: rendering on the window's device"),
|
||||
Err(e) => log::info!("gpu: renders come back as pixels: {e}"),
|
||||
}
|
||||
ctx.request_repaint();
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("gpu: {e}");
|
||||
lightcraft_engine::gpu::set_window_device_pending(false);
|
||||
}
|
||||
WindowTextures { device: rs.device.clone(), queue: rs.queue.clone(), renderer: rs.renderer.clone() }
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
|
||||
@@ -89,7 +153,7 @@ impl eframe::App for App {
|
||||
}
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(m) = self.2.as_mut()
|
||||
if let Some(m) = self.3.as_mut()
|
||||
&& m.update(&mut self.0, ctx)
|
||||
&& lightcraft_ui_egui::panels::notices::may_close(&mut self.0)
|
||||
{
|
||||
@@ -109,6 +173,13 @@ impl eframe::App for App {
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0);
|
||||
// the GPU renderer adopted the window's device: its renders can be drawn as they are
|
||||
if self.2.is_some()
|
||||
&& lightcraft_engine::gpu::on_window_device()
|
||||
&& let Some(t) = self.2.take()
|
||||
{
|
||||
self.0.renderer.set_screen_textures(Box::new(t));
|
||||
}
|
||||
self.0.ui(ui);
|
||||
}
|
||||
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
|
||||
@@ -130,6 +201,10 @@ impl eframe::App for App {
|
||||
// app after this and the session's last writes (face data) still go out under the lock.
|
||||
#[cfg(target_os = "macos")]
|
||||
self.0.session.release_library_lock();
|
||||
// macOS only: the process ends below without dropping the app, so a ready update's helper
|
||||
// starts here. Elsewhere dropping the app starts it.
|
||||
#[cfg(target_os = "macos")]
|
||||
self.0.start_pending_update();
|
||||
// macOS (#1331): end the process here, before eframe tears the window down, as Quit from
|
||||
// the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's
|
||||
// content view and restores its class on teardown; AppKit's Touch Bar support observes
|
||||
@@ -304,6 +379,7 @@ fn main() -> eframe::Result {
|
||||
app.notices.extend(launch_notices);
|
||||
app.notices.extend(window_notice);
|
||||
app.gpu_notice = true;
|
||||
app.disk_space_notice = true;
|
||||
// an empty library opens where Import is offered (a grid, with the sidebar); before
|
||||
// the snapshot below, so this alone isn't written to the settings file
|
||||
if problem.is_none() && files.is_empty() {
|
||||
@@ -358,9 +434,16 @@ fn main() -> eframe::Result {
|
||||
#[cfg(target_os = "macos")]
|
||||
let menu =
|
||||
(std::env::var_os("LIGHTCRAFT_NO_NATIVE_MENU").is_none()).then(|| native_menu::NativeMenu::install(&mut app, &cc.egui_ctx));
|
||||
// the GPU renderer on the window's device, when GPU rendering is on
|
||||
// (LIGHTCRAFT_GPU_WINDOW=0: a device of its own, renders read back - for comparison or a driver
|
||||
// that misbehaves with compute and drawing on one device)
|
||||
let window_device = std::env::var_os("LIGHTCRAFT_GPU_WINDOW").is_none_or(|v| v != "0");
|
||||
let window_textures =
|
||||
cc.wgpu_render_state.as_ref().filter(|_| gpu_on && window_device).map(|rs| adopt_window_device(rs, &cc.egui_ctx));
|
||||
Ok(Box::new(App(
|
||||
app,
|
||||
writer,
|
||||
window_textures,
|
||||
#[cfg(target_os = "macos")]
|
||||
menu,
|
||||
)))
|
||||
|
||||
@@ -67,6 +67,11 @@ fn decode_saved_ui(bytes: &[u8]) -> Result<(UiState, bool), String> {
|
||||
if recovered {
|
||||
fields.remove("docking");
|
||||
}
|
||||
// A settings file from before the startup dialog existed has no `seenVersion` key: the file
|
||||
// is there, so this is an installation that has been run, due What's New — never the
|
||||
// first-run tour. Shared with the browser's loader, which runs the same migration on its
|
||||
// stored `ui.json` (`startup::migrate_legacy_seen_version` carries the full story).
|
||||
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
|
||||
let ui = serde_json::from_value(saved).map_err(|error| error.to_string())?;
|
||||
Ok((ui, recovered))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Reading a display's ICC profile file for the screen-profile services (`colord` on Linux,
|
||||
//! `win_screen_profile` on Windows).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
|
||||
pub const MAX_PROFILE: u64 = 16 << 20;
|
||||
|
||||
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
|
||||
pub fn load(path: &Path) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
|
||||
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
|
||||
}
|
||||
|
||||
/// A profile file read again only when it changes: the services are asked about once a second, and
|
||||
/// calibration software rewrites its profile under the same name.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
#[derive(Default)]
|
||||
pub struct Cached {
|
||||
/// The file last read: its path, length and modification time.
|
||||
stamp: Option<(PathBuf, u64, Option<SystemTime>)>,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
impl Cached {
|
||||
/// The bytes of profile file `path`, read again when it isn't the file read last time or has
|
||||
/// changed since (see [`load`]).
|
||||
pub fn read(&mut self, path: &Path) -> Option<Vec<u8>> {
|
||||
let stamp = std::fs::metadata(path).ok().map(|m| (path.to_path_buf(), m.len(), m.modified().ok()));
|
||||
if stamp.is_none() || stamp != self.stamp {
|
||||
self.bytes = stamp.as_ref().and_then(|_| load(path));
|
||||
self.stamp = stamp;
|
||||
}
|
||||
self.bytes.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn profile_files_are_read_with_a_size_cap() {
|
||||
let dir = std::env::temp_dir().join(format!("profile-file-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let small = dir.join("small.icc");
|
||||
std::fs::write(&small, b"acsp").unwrap();
|
||||
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
|
||||
let empty = dir.join("empty.icc");
|
||||
std::fs::write(&empty, b"").unwrap();
|
||||
assert_eq!(load(&empty), None);
|
||||
assert_eq!(load(&dir.join("missing.icc")), None);
|
||||
let big = dir.join("big.icc");
|
||||
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
|
||||
assert_eq!(load(&big), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cached_profile_is_read_again_when_the_file_changes() {
|
||||
let dir = std::env::temp_dir().join(format!("profile-cache-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (a, b) = (dir.join("a.icc"), dir.join("b.icc"));
|
||||
std::fs::write(&a, b"first").unwrap();
|
||||
std::fs::write(&b, b"other").unwrap();
|
||||
let mut cache = Cached::default();
|
||||
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
|
||||
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
|
||||
// another monitor's profile
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"other"[..]));
|
||||
// rewritten under the same name (a different length, so the change shows whatever the
|
||||
// file system's time resolution)
|
||||
std::fs::write(&b, b"calibrated").unwrap();
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"calibrated"[..]));
|
||||
// gone: nothing, then read again once it is back
|
||||
std::fs::remove_file(&b).unwrap();
|
||||
assert_eq!(cache.read(&b), None);
|
||||
std::fs::write(&b, b"back").unwrap();
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"back"[..]));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
|
||||
pick_lightroom_catalog: Some(Box::new(|| {
|
||||
file_dialog()
|
||||
.set_title(lightcraft_ui_egui::i18n::tr("Import Lightroom Catalog"))
|
||||
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat"])
|
||||
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat", "zip"])
|
||||
.pick_file()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
})),
|
||||
@@ -144,7 +144,11 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
|
||||
// Linux: the profile the desktop assigns in colord, read off the UI thread
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_profile: Some(colord::service()),
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
// Windows: the profile it uses for the window's monitor, unless it colour-manages the
|
||||
// desktop itself (HDR, Auto Color Management)
|
||||
#[cfg(windows)]
|
||||
screen_profile: win_screen_profile::service(cc),
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
|
||||
screen_profile: None,
|
||||
pick_display_profile: Some(Box::new(|| {
|
||||
let mut d = file_dialog()
|
||||
@@ -255,6 +259,10 @@ pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) ->
|
||||
Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_system_clock(), None),
|
||||
Launch::Open { dir, remembered, .. } => open_library_session(in_memory, dir.clone(), *remembered, seed_demo),
|
||||
};
|
||||
// lens profiles from the app's own lensfun copy, offered on the first launch (not for a throwaway session)
|
||||
if !in_memory {
|
||||
s = s.with_default_lens_database().with_lens_auto_download();
|
||||
}
|
||||
s.face_models_dir = lightcraft_engine::config::default_face_models_dir();
|
||||
s.slide_templates_dir = lightcraft_engine::config::config_dir().map(|d| d.join(lightcraft_engine::slide_template::DIR_NAME));
|
||||
// Control requests are answered on the UI thread: Add to Apple Photos must not wait there
|
||||
|
||||
@@ -5,6 +5,7 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() {
|
||||
let mut app = App(
|
||||
LightcraftApp::new(Session::new(), Services::default()),
|
||||
PrefsWriter::default(),
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
);
|
||||
@@ -222,6 +223,42 @@ fn memory_session_leaves_a_damaged_ui_json_alone() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A settings file from before the startup dialog existed (no `seenVersion`) belongs to an
|
||||
/// installation that has been run: its first launch after the update shows What's New, never
|
||||
/// the first-run tour. A file this version saved before the dialog was presented carries an
|
||||
/// explicit `null` and is not migrated; only a missing file stays a first run as well.
|
||||
#[test]
|
||||
fn legacy_ui_json_shows_whats_new_not_the_first_run_tour() {
|
||||
let d = dir("legacy-startup");
|
||||
let path = d.join("ui.json");
|
||||
std::fs::write(&path, br#"{"language":"en","settings":{"startupView":"detail"}}"#).unwrap();
|
||||
let (ui, warning, keep) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none() && !keep);
|
||||
let ui = ui.unwrap();
|
||||
assert_eq!(ui.seen_version.as_deref(), Some(lightcraft_ui_egui::startup::LEGACY_SEEN_VERSION));
|
||||
assert_eq!(
|
||||
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
|
||||
Some(lightcraft_ui_egui::startup::StartupDialog::WhatsNew)
|
||||
);
|
||||
// a file that already records the running version is migrated nowhere
|
||||
std::fs::write(&path, format!(r#"{{"seenVersion":"{}"}}"#, env!("CARGO_PKG_VERSION"))).unwrap();
|
||||
let (ui, warning, _) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none());
|
||||
assert_eq!(ui.unwrap().seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION")));
|
||||
// an explicit `null` is this version's "not presented yet" (the launch chooser saves while
|
||||
// the tour still waits): it stays a first run, not a pre-feature file
|
||||
std::fs::write(&path, br#"{"language":"en","seenVersion":null}"#).unwrap();
|
||||
let (ui, warning, _) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none());
|
||||
let ui = ui.unwrap();
|
||||
assert_eq!(ui.seen_version, None);
|
||||
assert_eq!(
|
||||
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
|
||||
Some(lightcraft_ui_egui::startup::StartupDialog::FirstRun)
|
||||
);
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn docking_survives_native_settings_file_reload() {
|
||||
use lightcraft_ui_egui::docking::Panel;
|
||||
@@ -566,6 +603,7 @@ fn on_exit_ends_the_process_on_macos() {
|
||||
let mut app = App(
|
||||
app,
|
||||
PrefsWriter::default(),
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
);
|
||||
@@ -598,6 +636,7 @@ fn on_exit_removes_the_lock_owner_note() {
|
||||
let mut app = App(
|
||||
LightcraftApp::new(session, Services::default()),
|
||||
PrefsWriter::default(),
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! The ICC profile Windows assigns to the monitor showing LightCraft's window.
|
||||
//!
|
||||
//! On an SDR desktop Windows passes what an app draws to the monitor unchanged, so sRGB previews
|
||||
//! look oversaturated on a wide-gamut monitor and ignore a calibration. While no monitor profile is
|
||||
//! chosen in Settings ▸ Display, previews are shown through the profile Windows uses for the window's
|
||||
//! monitor (`Services::screen_profile`, see `lightcraft_wincolor`), followed when the window moves to
|
||||
//! another monitor or the profile changes in Windows' Color Management. When Windows colour-manages
|
||||
//! the desktop itself (HDR, Auto Color Management) previews stay sRGB, as Windows expects then.
|
||||
|
||||
use lightcraft_wincolor::MonitorColor;
|
||||
|
||||
/// The service the UI polls, for the window `cc` belongs to; `None` when its handle isn't a Win32 one.
|
||||
pub fn service(cc: &eframe::CreationContext<'_>) -> Option<lightcraft_ui_egui::ScreenProfileFn> {
|
||||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
let RawWindowHandle::Win32(handle) = cc.window_handle().ok()?.as_raw() else { return None };
|
||||
let hwnd = handle.hwnd.get();
|
||||
let mut file = crate::profile_file::Cached::default();
|
||||
let mut last: Option<MonitorColor> = None;
|
||||
Some(Box::new(move || {
|
||||
let answer = lightcraft_wincolor::monitor_color(hwnd);
|
||||
if last.as_ref() != Some(&answer) {
|
||||
log::info!("screen profile: {}", describe(&answer));
|
||||
last = Some(answer.clone());
|
||||
}
|
||||
match answer {
|
||||
MonitorColor::Profile(path) => file.read(&path),
|
||||
MonitorColor::ManagedByWindows | MonitorColor::NoProfile | MonitorColor::Unknown => None,
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/// For the log: what the window's monitor answered.
|
||||
fn describe(answer: &MonitorColor) -> String {
|
||||
match answer {
|
||||
MonitorColor::Profile(path) => format!("the monitor's profile, {}", path.display()),
|
||||
MonitorColor::ManagedByWindows => "Windows colour-manages this monitor (HDR or Auto Color Management): previews are sRGB".into(),
|
||||
MonitorColor::NoProfile => "no profile is assigned to the monitor: previews are sRGB".into(),
|
||||
MonitorColor::Unknown => "not known for this monitor: previews are sRGB".into(),
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
@@ -154,16 +159,34 @@ pub fn base_options() -> WgpuConfiguration {
|
||||
n.instance_descriptor.backend_options = backend::backend_options();
|
||||
// no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250)
|
||||
n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags);
|
||||
// the GPU renderer may run on this device (`adopt_window_device`): it needs the adapter's
|
||||
// buffer limits (a 24 MP photo is a 275 MiB buffer), not wgpu's defaults
|
||||
let default = n.device_descriptor.clone();
|
||||
n.device_descriptor = std::sync::Arc::new(move |adapter| {
|
||||
if adapter.get_info().backend == wgpu::Backend::Gl {
|
||||
return default(adapter);
|
||||
}
|
||||
wgpu::DeviceDescriptor { label: Some("lightcraft window"), required_limits: adapter.limits(), ..Default::default() }
|
||||
});
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// 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))),
|
||||
@@ -192,10 +215,12 @@ fn probe(backends: Backends, compose_window: bool) -> Result<WgpuSetupExisting,
|
||||
..Default::default()
|
||||
}))
|
||||
.map_err(|e| format!("no adapter: {e}"))?;
|
||||
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() };
|
||||
// (not GL: the adapter's own limits, which the GPU renderer needs when it adopts this device)
|
||||
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))?;
|
||||
@@ -373,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() {
|
||||
@@ -390,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);
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,13 @@ covers a whole directory), or if a licence file referenced in the Licence column
|
||||
| `assets/camera-profiles/ILCA-99M2.json` | Sony ILCA-99M2 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by @PiMinusMax | original work: fitted by `lightcraft-cli calibrate` to 144 usable ILCA-99M2 ARWs (of 150, seven shooting days, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-11 | none |
|
||||
| `assets/camera-profiles/ILCE-7CR.json` | Sony ILCE-7CR camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by @AlexChambers | original work: fitted by `lightcraft-cli calibrate` to 125 usable ILCE-7CR ARWs (of 131, September 2025 to September 2026, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-09 | none |
|
||||
| `assets/camera-profiles/X-H2S.json`, `assets/camera-profiles/X-T4.json` | Fujifilm camera colour profiles (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by Sebastian Pfluegelmeier | original work: fitted by `lightcraft-cli calibrate` to 201 X-H2S and 545 X-T4 RAFs and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-08 | none |
|
||||
| `assets/camera-profiles/Canon_EOS_D60.json` | Canon EOS D60 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by Robert Woldberg | original work: fitted by `lightcraft-cli calibrate` to 1,424 usable EOS D60 CRWs (of 1,520, 2005 to 2014, Auto white balance) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
|
||||
| `assets/camera-profiles/NIKON_Z_6_2.json` | Nikon Z 6II camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 296 usable Z 6II NEFs of my own (of 299, 2024 to 2026, Standard and Auto picture controls; NIKKOR Z 20mm f/1.8 S, Z 24-70mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
|
||||
| `assets/camera-profiles/NIKON_Z_8.json` | Nikon Z 8 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 261 usable Z 8 NEFs of my own (of 278, 2023 and 2026, nearly all Standard picture control, lossless 14-bit; NIKKOR Z 24-120mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
|
||||
| `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
|
||||
| `assets/camera-profiles/ILCE-7RM5.json` | Sony ILCE-7RM5 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Yule (Brian) Wang (@peaperfish) | original work: fitted by `lightcraft-cli calibrate` to 220 usable ILCE-7RM5 ARWs of my own (of 241, 2025 to 2026, Standard creative style; Sigma 24-70mm F2.8 DG DN II Art and Sony FE 200-600mm F5.6-6.3 G OSS) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-26 | none |
|
||||
| `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix |
|
||||
| `crates/raw/src/chart_table.rs` | Chart-measured camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D50) for the Canon EOS D60 | LightCraft contributors; ColorChecker photographs taken by Robert Woldberg on the maintainer's EOS D60 | original work: fitted to our own CRWs of a ColorChecker Classic (post-November-2014 formulation) under a ~2,900 K tungsten bulb (11 frames) and direct sun (~4,850 K, 20 frames); reference colours: X-Rite's published L*a*b* (D50) for the chart, as packaged by [colour-science](https://github.com/colour-science/colour) (BSD-3-Clause), used for fitting only and not shipped; method in `clean-room/crw/10-chart-calibration.md` | MIT OR Apache-2.0 | 2026-10-25 | kept by hand: a 3×3 matrix per illuminant fitted on chromaticity with neutral held at D50; no Adobe or third-party camera matrix, no number from a GPL raw decoder |
|
||||
| `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none |
|
||||
| `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a |
|
||||
| `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a |
|
||||
@@ -43,6 +45,7 @@ covers a whole directory), or if a licence file referenced in the Licence column
|
||||
| `crates/ui-egui/locales/sv.json`, `crates/ui-egui/locales/sv-formats.json` | Swedish interface catalogs | LightCraft contributors | original work: clean-room Swedish translations of English source phrases | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-15 | none |
|
||||
| `crates/ui-egui/locales/fi.json`, `crates/ui-egui/locales/fi-formats.json` | Finnish interface catalogs | @roopeg with Claude Code (AI-assisted; native-speaker review by @roopeg) | original work: translations of the English source phrases, using common Finnish photo-editing vocabulary; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-17 | count-neutral labels for Finnish partitive agreement, Finnish dates and times (`20.9.2026`, `16:04`), reviewed placeholders |
|
||||
| `crates/ui-egui/locales/vi.json`, `crates/ui-egui/locales/vi-formats.json` | Vietnamese interface catalogs | @duydev (DUY Tran Nhat) with AI assistance (Cursor) | original work: translations of English source phrases; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-13 | plural-neutral counts, Vietnamese dates and weekdays, reviewed placeholders |
|
||||
| `crates/codecs/tests/fixtures/quad-444-gbr-lossless.avif` | AVIF decode test fixture: a 33×17 lossless 8-bit 4:4:4 AV1 still with the identity (GBR) matrix, four flat colour quadrants | craft-libs contributors | [craft-libs 59b4f1e8 `crates/image-codecs/tests/fixtures/avif/quad-444-gbr-lossless.avif`](https://github.com/storytold/craft-libs/blob/59b4f1e8c2909fbcacba491b219958f4a976d5f8/crates/image-codecs/tests/fixtures/avif/quad-444-gbr-lossless.avif) (storytold/craft-libs#1601), encoded with FFmpeg/libaom from a synthetic RGB source as described in `crates/codecs/tests/fixtures/avif-README.md`; no third-party image content | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-11-16 | none: byte-identical copy of the craft-libs fixture; decodes exactly to its four-colour `quad-source.rgb` |
|
||||
|
||||
Notes
|
||||
- egui's default fonts (Hack, Ubuntu Light, Noto Emoji, egui-icons and emoji-icon-font) come from the
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"model":"Canon EOS D60","files":1424,"samples":5140322,"matrix":[[1.13012,-0.360203,0.234919],[-0.0483286,1.21254,-0.166746],[-0.0238897,-0.834382,1.86577]],"hue_sat":{"hue_divisions":72,"sat_divisions":5,"val_divisions":5,"data":[[0.0,1.0,1.0],[8.29241,1.23189,1.0],[6.24278,1.25426,1.0],[5.85238,1.20774,1.0],[3.78008,1.10233,1.0],[0.0,1.0,1.0],[7.49695,1.19919,1.0],[4.58151,1.21364,1.0],[3.60262,1.15474,1.0],[2.74306,1.07068,1.0],[0.0,1.0,1.0],[6.97455,1.16634,1.0],[3.67004,1.18558,1.0],[1.9923,1.12524,1.0],[0.245554,0.982395,1.0],[0.0,1.0,1.0],[6.42589,1.13738,1.0],[2.66266,1.14834,1.0],[0.226251,1.09372,1.0],[-2.23194,0.930707,1.0],[0.0,1.0,1.0],[6.09352,1.1248,1.0],[1.65699,1.12876,1.0],[-1.52059,1.07635,1.0],[-3.87766,0.926268,1.0],[0.0,1.0,1.0],[6.2146,1.10729,1.0],[1.13044,1.11602,1.0],[-2.4179,1.08135,1.0],[-4.69366,0.96409,1.0],[0.0,1.0,1.0],[6.73255,1.09443,1.0],[1.15502,1.09451,1.0],[-2.95449,1.05376,1.0],[-5.86916,0.954201,1.0],[0.0,1.0,1.0],[7.0143,1.0883,1.0],[1.25698,1.07945,1.0],[-3.3853,1.03275,1.0],[-6.46471,0.9465,1.0],[0.0,1.0,1.0],[7.44031,1.08414,1.0],[1.9515,1.06401,1.0],[-3.08108,1.00026,1.0],[-6.03475,0.917114,1.0],[0.0,1.0,1.0],[8.29527,1.07925,1.0],[2.86018,1.03974,1.0],[-2.25228,0.96454,1.0],[-4.98936,0.860481,1.0],[0.0,1.0,1.0],[9.14683,1.08392,1.0],[3.8335,1.01361,1.0],[-1.06889,0.935075,1.0],[-4.04616,0.821455,1.0],[0.0,1.0,1.0],[9.19479,1.10285,1.0],[4.68727,1.00463,1.0],[0.536387,0.911486,1.0],[-2.795,0.795914,1.0],[0.0,1.0,1.0],[8.67599,1.12913,1.0],[5.14131,1.01389,1.0],[1.77075,0.910094,1.0],[-0.965505,0.813756,1.0],[0.0,1.0,1.0],[7.95628,1.12916,1.0],[5.32373,1.0083,1.0],[2.91716,0.905281,1.0],[1.05035,0.834887,1.0],[0.0,1.0,1.0],[6.83544,1.13214,1.0],[4.95639,1.00769,1.0],[3.81032,0.903303,1.0],[2.8937,0.82685,1.0],[0.0,1.0,1.0],[5.89142,1.1369,1.0],[4.55603,1.00893,1.0],[4.04927,0.902735,1.0],[3.59749,0.8313,1.0],[0.0,1.0,1.0],[5.07797,1.14498,1.0],[4.14717,1.01358,1.0],[3.95316,0.909713,1.0],[4.03064,0.834461,1.0],[0.0,1.0,1.0],[3.93584,1.15444,1.0],[3.29081,1.02539,1.0],[3.28057,0.922408,1.0],[3.7798,0.840035,1.0],[0.0,1.0,1.0],[2.45431,1.17195,1.0],[2.1184,1.04565,1.0],[2.31804,0.94015,1.0],[2.84532,0.862496,1.0],[0.0,1.0,1.0],[0.914128,1.1919,1.0],[0.658994,1.06124,1.0],[1.06903,0.95232,1.0],[1.60007,0.890999,1.0],[0.0,1.0,1.0],[-0.709287,1.20875,1.0],[-0.970683,1.0793,1.0],[-0.571268,0.969075,1.0],[-0.0688885,0.893104,1.0],[0.0,1.0,1.0],[-2.56506,1.23369,1.0],[-2.97984,1.10163,1.0],[-2.79742,0.983848,1.0],[-2.01335,0.892256,1.0],[0.0,1.0,1.0],[-4.47609,1.26079,1.0],[-4.91221,1.12068,1.0],[-4.5471,1.00002,1.0],[-2.72325,0.931381,1.0],[0.0,1.0,1.0],[-6.07811,1.27839,1.0],[-6.49836,1.12664,1.0],[-5.47092,0.99826,1.0],[-1.83561,0.972328,1.0],[0.0,1.0,1.0],[-8.37879,1.29932,1.0],[-8.93662,1.13395,1.0],[-7.32093,1.02059,1.0],[-0.98037,0.994534,1.0],[0.0,1.0,1.0],[-10.2729,1.25707,1.0],[-11.0599,1.09129,1.0],[-9.32287,1.00616,1.0],[-1.21689,0.994275,1.0],[0.0,1.0,1.0],[-11.9931,1.22624,1.0],[-12.4979,1.05021,1.0],[-10.2083,0.969313,1.0],[-1.172,0.991243,1.0],[0.0,1.0,1.0],[-13.5442,1.18901,1.0],[-13.5809,1.00396,1.0],[-10.7308,0.93446,1.0],[-1.1717,0.98724,1.0],[0.0,1.0,1.0],[-14.1202,1.16045,1.0],[-14.1451,0.982771,1.0],[-10.5188,0.911345,1.0],[-1.10721,0.983353,1.0],[0.0,1.0,1.0],[-14.5581,1.16209,1.0],[-13.8126,0.986909,1.0],[-8.30721,0.90898,1.0],[-0.995621,0.97911,1.0],[0.0,1.0,1.0],[-14.4013,1.1613,1.0],[-13.2596,0.979666,1.0],[-8.95671,0.890826,1.0],[-2.10024,0.967003,1.0],[0.0,1.0,1.0],[-15.1417,1.16939,1.0],[-13.2246,0.977241,1.0],[-9.7885,0.871629,1.0],[-2.78003,0.957243,1.0],[0.0,1.0,1.0],[-16.0188,1.15745,1.0],[-14.0864,0.974714,1.0],[-10.4183,0.871201,1.0],[-2.37086,0.964302,1.0],[0.0,1.0,1.0],[-16.2546,1.14581,1.0],[-13.912,0.987045,1.0],[-8.19204,0.901434,1.0],[-1.1791,0.982516,1.0],[0.0,1.0,1.0],[-16.3253,1.14274,1.0],[-13.1974,0.996884,1.0],[-7.37707,0.909881,1.0],[-0.796766,0.988333,1.0],[0.0,1.0,1.0],[-17.4833,1.13741,1.0],[-13.1058,0.977386,1.0],[-5.85941,0.919339,1.0],[-0.352557,0.99447,1.0],[0.0,1.0,1.0],[-17.5235,1.10838,1.0],[-13.7099,0.974525,1.0],[-5.10075,0.930882,1.0],[-0.176921,0.995738,1.0],[0.0,1.0,1.0],[-17.5967,1.05115,1.0],[-13.6048,0.938325,1.0],[-5.27843,0.910606,1.0],[-0.167657,0.994507,1.0],[0.0,1.0,1.0],[-17.4696,0.996524,1.0],[-13.115,0.908347,1.0],[-4.95967,0.899867,1.0],[-0.174963,0.992617,1.0],[0.0,1.0,1.0],[-16.5982,0.955417,1.0],[-11.0254,0.879437,1.0],[-3.31212,0.863198,1.0],[-0.175046,0.977174,1.0],[0.0,1.0,1.0],[-15.5952,0.929258,1.0],[-8.31794,0.86823,1.0],[-0.528212,0.846517,1.0],[0.380461,0.923401,1.0],[0.0,1.0,1.0],[-14.4398,0.910204,1.0],[-8.05514,0.876305,1.0],[-0.57323,0.868118,1.0],[0.470409,0.948896,1.0],[0.0,1.0,1.0],[-13.0585,0.905534,1.0],[-7.90773,0.889057,1.0],[-0.976436,0.905932,1.0],[0.542039,0.983099,1.0],[0.0,1.0,1.0],[-11.876,0.908437,1.0],[-7.06937,0.903432,1.0],[-0.539651,0.916127,1.0],[0.779286,0.983595,1.0],[0.0,1.0,1.0],[-10.0702,0.929172,1.0],[-5.39408,0.937425,1.0],[-0.2061,0.920171,1Line truncated
|
||||
@@ -0,0 +1,97 @@
|
||||
# EOS D60 colour matrices from a ColorChecker (2026-10-25)
|
||||
|
||||
The Canon EOS D60 has no published spectral sensitivities, so it is not in `spectral_table.rs`.
|
||||
These are its DNG-style matrices (`ColorMatrix1/2`, `ForwardMatrix1/2`), fitted to our own
|
||||
photographs of a ColorChecker Classic under two lights. They are in
|
||||
`crates/raw/src/chart_table.rs`. Measurements come from the maintainer's own captures (names,
|
||||
sizes and SHA-256 in `logs/chart-captures.tsv`; no image content recorded) and the chart's
|
||||
published reference colours (craft-libs `crates/crw/clean-room/sources.md`). Scripts and measurements are local-only, in
|
||||
`plan/crw/chart/`.
|
||||
|
||||
## Captures
|
||||
|
||||
| Set | Frames used | Light | Notes |
|
||||
|---|---:|---|---|
|
||||
| `SunlightColorCard/` | 20 of 22 | Direct afternoon sun, ISO 100 | Calibrite ColorChecker Classic (50th-anniversary edition, post-2014 formulation) leaning on a wall, filling most of the frame. Auto and Daylight white balance, a shutter bracket. Two frames dropped: a white-patch sample ≥ 3900 (clip ≈ 4000 at ISO 100, craft-libs `crates/crw/clean-room/04-color.md` §2). |
|
||||
| `TungstonColorChart/` 2696–2706 | 11 | One household tungsten bulb, ISO 100 | Chart flat on a wall, a shutter bracket. Brightest white patch 2657 of ~4000. |
|
||||
| `TungstonColorChart/` 2688–2691 | not used | Same bulb, 8 minutes earlier | Steady within the set, but its neutral reads ~3,040 K against ~2,900 K for the later set: the light changed (window light or bulb warm-up). The later, warmer and better-exposed set is used. |
|
||||
|
||||
All 37 frames decode sample-exact against the black-box reference (`craft-crw`'s digest-pinned sample test, formerly `crw_oracle.rs` here).
|
||||
|
||||
An earlier set on a ColorChecker-layout clone (Pixel Perfect "24 Standard Color Calibration
|
||||
Chart", 2026-10-15) was not used. The maker publishes no reference values, and its grey patches
|
||||
are not neutral: against an 18 % grey board they read R/G 0.88–0.94 in shade and B/G up to
|
||||
1.29 under warm LED light, the darker patches drifting most. That is the sign of greys printed
|
||||
from coloured inks.
|
||||
|
||||
## Measurement
|
||||
|
||||
- Patches are located on the embedded JPEG (four corner patch centres, bilinear grid), tracked
|
||||
per frame by phase correlation, and checked visually on drawn boxes. The tungsten-set chart
|
||||
was upside down in the first four frames; patch order is mapped accordingly.
|
||||
- Each patch is measured in a central box of about 40 % of its width in the linear raw (black
|
||||
from the far masked border per CFA site; R, mean of both G, B per 2×2 site). Uniformity
|
||||
across the box (3×3 sub-blocks): ≤ 4 % in sun, ≤ 7 % under the bulb (light falloff across
|
||||
the closer chart).
|
||||
- Frames are normalised by the four middle neutrals (patches 20–23), averaged, and white
|
||||
balanced on those neutrals. White balance (R, B multipliers, G = 1): sun 2.362, 1.298; bulb
|
||||
1.353, 2.213. The neutrals agree on it to ±2 %.
|
||||
|
||||
## Fit
|
||||
|
||||
- The reference is X-Rite's published L\*a\*b\* (D50) for charts made after November 2014.
|
||||
- The model is a 3×3 matrix from white-balanced camera RGB to XYZ (D50), with neutral (1, 1, 1)
|
||||
held exactly at the engine's D50 white (`lightcraft_color::D50`): the third column is D50
|
||||
minus the first two. That is a DNG `ForwardMatrix`.
|
||||
- **Chromaticity only.** Each prediction is scaled to the patch's reference luminance before
|
||||
the CIEDE2000 residual. In the sun the chart warped as it heated: the grey row's brightness
|
||||
slope swung from +4 % to −7 % across the 70 s of shooting, in time order, and the per-patch
|
||||
brightness needed was not smooth across the chart. A fit including lightness would have
|
||||
absorbed that into the matrix. Chromaticity still determines the whole 3×3 up to scale,
|
||||
which the white constraint fixes. The cost is that luminance of saturated blues and purples
|
||||
rests on the model, not the measurement.
|
||||
- `ColorMatrix` per light = diag(1 / multipliers) · ForwardMatrix⁻¹ · Bradford(light → D50),
|
||||
scaled so the light's white maps to camera values with maximum 1. By construction it maps
|
||||
the filed illuminant's white to the measured camera neutral.
|
||||
|
||||
| Light | CIEDE2000 on the 24 patches | Leaving each patch out | Worst |
|
||||
|---|---|---|---|
|
||||
| Sun (filed as D50) | mean 1.70, median 1.46 | mean 1.97 | white 4.5 |
|
||||
| Bulb (filed as A) | mean 2.42, median 1.79 | mean 2.74 | bluish green 6.7 |
|
||||
|
||||
- One matrix does not serve both lights: the sun's matrix on the bulb's chart gives mean 3.6
|
||||
(cyan 9.0), the bulb's on the sun's 3.4 (red 7.7). Hence the dual-illuminant entry.
|
||||
- The neutral row reads a\* within ±0.4 for the middle greys; white and the darkest patches
|
||||
are off by up to 2 (white patch sheen, flare).
|
||||
|
||||
## Which illuminants
|
||||
|
||||
The two lights' colour temperatures come from the camera's own white-balance presets
|
||||
(ColorBalance slots, craft-libs `crates/crw/clean-room/04-color.md` §3) at the temperatures Canon's manuals give them (Daylight
|
||||
5200 K, Tungsten 3200 K, Fluorescent 4000 K), interpolated in mired on ln(R/B): sun ~4,850 K,
|
||||
bulb ~2,900 K. They are filed under the nearest DNG illuminants the engine knows, **D50
|
||||
(5003 K) and Standard Illuminant A (2856 K)**, so `Camera` now carries its own illuminant
|
||||
pair (spectral rows: A and D65).
|
||||
|
||||
## Checks in the app
|
||||
|
||||
- `spectral::tests::the_chart_measured_eos_d60_reads_its_presets_in_kelvin`: the camera's
|
||||
presets, which the fit never saw, read through the matrices as Tungsten 3,264 K, Daylight
|
||||
5,603 K, Cloudy 6,613 K, Flash 7,085 K, near the locus. Canon's nominal values are 3200, 5200,
|
||||
6000 and 6000 K. Order and spacing hold; the daylight presets read 8–15 % high, as Sony's
|
||||
dial does against its spectral matrices (#730).
|
||||
- Real files through the headless app (As Shot): WBModes Fluorescent 4,103 K, tint +26 (green
|
||||
compensation); LED-lit room, Auto 3,761 K; open shade, Auto 6,596 K; sunlit chart, Auto
|
||||
4,762 K.
|
||||
- `files::tests::crw_probes_name_their_camera_from_the_ciff_records`: CRW imports now take make,
|
||||
model and capture time from the decoder's CIFF records (no Exif in a CRW; the catalog had an
|
||||
empty camera, so a D60 stayed on the relative white-balance scale).
|
||||
|
||||
## Limits
|
||||
|
||||
- One body, one bulb, one afternoon. The chart is 24 patches; a 3×3 matrix cannot follow the
|
||||
sensor's departures from the CIE observer (the bulb fit's worst patches are 5–7 ΔE).
|
||||
- The lights are filed under standard illuminants they only approximate (~50 K for the bulb,
|
||||
~150 K for the sun).
|
||||
- The D60's look is still the per-file JPEG fit and the pooled profile; these matrices give the
|
||||
white-balance scale and the fallback colour only.
|
||||
@@ -0,0 +1,18 @@
|
||||
# Canon CRW: where the record is
|
||||
|
||||
The Canon CRW (CIFF) decoder and its clean-room record (the frozen format, the verification
|
||||
summary, the colour, geometry and metadata notes, the private-corpus summary and the source log)
|
||||
live in craft-libs:
|
||||
[`crates/crw/clean-room/`](https://github.com/storytold/craft-libs/tree/main/crates/crw/clean-room).
|
||||
The derivation trail and the frozen table-generation materials stay in LightCraft PR #3021.
|
||||
LightCraft uses the crate `craft-crw` through the adapter `crates/raw/src/vendor/crw.rs`.
|
||||
|
||||
What stays here is LightCraft's own colour work on these cameras:
|
||||
|
||||
- [`10-chart-calibration.md`](10-chart-calibration.md): the EOS D60 colour matrices fitted to
|
||||
ColorChecker captures, implemented in `crates/raw/src/chart_table.rs`.
|
||||
- [`logs/chart-captures.tsv`](logs/chart-captures.tsv): names, sizes and SHA-256 of the chart
|
||||
frames (no image content).
|
||||
|
||||
The capture statistics those documents cite (`04-color.md`, `05-private-corpus.md`, `sources.md`)
|
||||
are in the craft-libs record.
|
||||
@@ -0,0 +1,39 @@
|
||||
# EOS D60 ColorChecker Classic captures (maintainer, local only; never committed). Names, sizes, SHA-256; no image content. Generated 2026-10-25.
|
||||
file bytes sha256
|
||||
SunlightColorCard/CRW_2666.CRW 7791628 371d8e18c12801c72754dd7b277163a866afc422c8edf6ad1ea822009e4170f8
|
||||
SunlightColorCard/CRW_2667.CRW 6638578 188d625c31ab44475a6cf54a5dae00fd861e26aafc90f4b5d18a1905c0a3cef5
|
||||
SunlightColorCard/CRW_2668.CRW 6832770 1189b8dc79642c57a8c9496b5629e36a1741c545d2b0b864d6e6e20d901510c1
|
||||
SunlightColorCard/CRW_2669.CRW 7079102 baf1686b27a9e0a04bf87c0b6cf55168f398d85247f8115a0af69b5e9ea1884c
|
||||
SunlightColorCard/CRW_2670.CRW 7225298 067ba3f4d3026b8009cfe4babb5e4c3b28f988d95c48024a75c6715de32afccf
|
||||
SunlightColorCard/CRW_2671.CRW 7504700 cf81cbb96389624318e890b5506221d49f5fba8e2d45447d87e0f3ff3e9bdc72
|
||||
SunlightColorCard/CRW_2672.CRW 7830852 7a59446bfb1f00d6eabd0115b8e5451c34f5d3d48f483cb27608ce9508e43ee5
|
||||
SunlightColorCard/CRW_2673.CRW 8053180 feeb8f818325d6ddb4e88b5eabe4a74f4cb5e1da9f70135ae3f85938c86695dc
|
||||
SunlightColorCard/CRW_2674.CRW 8312060 45e7402c888582adadb607599eae80644d657d61c9607b426c411ee306e42daf
|
||||
SunlightColorCard/CRW_2675.CRW 8565950 be28d2fa049aa4158ae9e3ec49dd28eb56fcd0ffa7af060235b8bda0d89dfd0a
|
||||
SunlightColorCard/CRW_2676.CRW 7795508 76f7418a82e45e1034b3adacacf4bc756cb65a0d683e5bb3631992784e654f93
|
||||
SunlightColorCard/CRW_2677.CRW 7747450 a5e7bc618e6b80ea70f9bad6a1bf41ee63eadbc51df28b82d0864a73434f7964
|
||||
SunlightColorCard/CRW_2678.CRW 6815054 28824f0f64b087488d8dc5a66a8bdf717e83a4d4e1660676d07991bf32dffb96
|
||||
SunlightColorCard/CRW_2679.CRW 7050606 b5c915fa89542265deb4fa16da3ca7ffda01b1d961903836b0059d024316673a
|
||||
SunlightColorCard/CRW_2680.CRW 7231410 a5780dfe99a2df2a3ed9de1888e91baa614b2e009a2b6e0a84d442b6bf1af9fd
|
||||
SunlightColorCard/CRW_2681.CRW 7438088 eb4475919c2770f816d47787656ab7ecb5396f30d2c03628c3ab167ebbc47c65
|
||||
SunlightColorCard/CRW_2682.CRW 7584262 a6fe417b90ce41b03552963dee6b21e4f02b59a5c51148edc04af7224e8c59e9
|
||||
SunlightColorCard/CRW_2683.CRW 7811474 5402ad40e2689d78ade083d8855ecced5caea9368b9d77ecc4a61a16dc55aa36
|
||||
SunlightColorCard/CRW_2684.CRW 8043372 bbef5da457c0b6d6c45c74a99f3e318e6c80a7d3a0ad5c7cb7e13d24205f64fa
|
||||
SunlightColorCard/CRW_2685.CRW 8242344 8d68d592a5c8933f0f35630114fe7017be808b007867beaf1a8d6d2bd1441f70
|
||||
SunlightColorCard/CRW_2686.CRW 8462380 79f7db32b18a834d5408500185c65d316387d1440aa61e26a11be85883fcc382
|
||||
SunlightColorCard/CRW_2687.CRW 7690732 0333d8d18390e77128f186239e6de71c0432ab6ee9669a71c210255e4d915d19
|
||||
TungstonColorChart/CRW_2688.CRW 6269390 d9c4334edfe3636a8a7e69f29c1d1e89f820b7b704697684d7996faee41f5d43
|
||||
TungstonColorChart/CRW_2689.CRW 6001348 1e8b47645d76a71fd9fb4111c4dce805d6dcd41ac82e6b4ce52debbf71565455
|
||||
TungstonColorChart/CRW_2690.CRW 6114056 f63fe49a9ed13af33ddb8d8ed8d75de4e304a3bc2c1f1d4275ba7edbc4f459f3
|
||||
TungstonColorChart/CRW_2691.CRW 6299730 ad8a2844c00965fb6a12e8fc85a6e8bfbdf1924e6d1a68b55472701cb8ffa115
|
||||
TungstonColorChart/CRW_2696.CRW 6169684 105ee515c94da78dedc1f8d777982c4a1e62781b160428524fbe922f62b3ef5c
|
||||
TungstonColorChart/CRW_2697.CRW 5565982 327eebf702185127feb8a5f4bfac5d7ebad5532f7417b302997b19b97d7ff4a8
|
||||
TungstonColorChart/CRW_2698.CRW 5709092 f0fca20f8dcd51046e53bebf9fb9f624677ee674ad739622cdb2578977669705
|
||||
TungstonColorChart/CRW_2699.CRW 5873492 57724a1ff507cf4e78c80a34cd4e0b77eac397322228d32e5215fc3869853dd1
|
||||
TungstonColorChart/CRW_2700.CRW 5988146 6c97ae2c72114034e2fbe6aed0ef97f475696e43b56ed62273eccbfbba4cbaa0
|
||||
TungstonColorChart/CRW_2701.CRW 6202756 c4032e46b753a718d8748e269a9da5d124891d07912542368ea867529143aa62
|
||||
TungstonColorChart/CRW_2702.CRW 6409582 89b65c1c07e0685841046db85923b0bf80e747fed141ddf0335ba12dc75f3f3c
|
||||
TungstonColorChart/CRW_2703.CRW 6407270 50179d0a330c967a74d76bc8342eea1052689c5c544aa1a913769b241ac6f736
|
||||
TungstonColorChart/CRW_2704.CRW 6483154 6bac4d8229a8d0fff1445d212ca63e53911dc7bda988743215009257b87787fa
|
||||
TungstonColorChart/CRW_2705.CRW 7170488 629f94131e7f598964d2635e3039a20c441563201c4f3cbf177d83ad6b061f78
|
||||
TungstonColorChart/CRW_2706.CRW 6383026 67657e7a21f6fd8580012fccd2210afccf285e747bc4d39b8ea775811528ce83
|
||||
|
@@ -68,6 +68,10 @@ sync_github_name = true
|
||||
[people.ronibalthazar]
|
||||
sync_github_name = true
|
||||
|
||||
[people.esli1283]
|
||||
real_name = "Aaron Lopez"
|
||||
sync_github_name = false
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Fault injection for the catalog log's writer thread (tests only: nothing in the product
|
||||
//! installs a hook, and with none installed a check is one uncontended lock of an empty list).
|
||||
//!
|
||||
//! A test makes the drive under one library directory slow (a hook that sleeps) or failing (a
|
||||
//! hook that returns an error) and proves that a flag never waits for it and that nothing handed
|
||||
//! over is lost: `crates/catalog/src/tests_log_thread.rs`, `crates/engine/src/tests/slow_drive.rs`.
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
/// Where the log thread is about to touch the drive.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Step {
|
||||
/// Writing bytes to the log (or to the file that replaces it).
|
||||
Write,
|
||||
/// Syncing them.
|
||||
Sync,
|
||||
}
|
||||
|
||||
/// Runs before each [`Step`] in the hooked directory: an error fails that step.
|
||||
pub type Hook = Arc<dyn Fn(Step) -> io::Result<()> + Send + Sync>;
|
||||
|
||||
static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Run `hook` before every write and sync of the catalog log in `dir` (replacing an earlier one).
|
||||
#[doc(hidden)]
|
||||
pub fn install(dir: &Path, hook: Hook) {
|
||||
let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
hooks.retain(|(d, _)| d != dir);
|
||||
hooks.push((dir.to_path_buf(), hook));
|
||||
}
|
||||
|
||||
/// Remove the hook of `dir`.
|
||||
#[doc(hidden)]
|
||||
pub fn remove(dir: &Path) {
|
||||
HOOKS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| d != dir);
|
||||
}
|
||||
|
||||
static ON_CALLER: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Write the log in `dir` on the caller's thread, syncing before each append returns, as builds
|
||||
/// before PERF-STEP-STALL did: a test's "before" (stores opened afterwards; the hooks run there too).
|
||||
#[doc(hidden)]
|
||||
pub fn write_on_caller(dir: &Path, on: bool) {
|
||||
let mut dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
dirs.retain(|d| d != dir);
|
||||
if on {
|
||||
dirs.push(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn on_caller(dir: &Path) -> bool {
|
||||
let dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
!dirs.is_empty() && dirs.iter().any(|d| d == dir)
|
||||
}
|
||||
|
||||
pub(crate) fn check(dir: &Path, step: Step) -> io::Result<()> {
|
||||
let hook = {
|
||||
let hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if hooks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
hooks.iter().find(|(d, _)| d == dir).map(|(_, h)| h.clone())
|
||||
};
|
||||
match hook {
|
||||
Some(h) => h(step),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
+167
-30
@@ -6,7 +6,10 @@
|
||||
//! rename).
|
||||
//! - `catalog.log` — JSON lines, one per op applied after the snapshot:
|
||||
//! `{"seq":N,"crc":C,"op":{…}}` where `C` is the CRC-32 of the op's JSON text. Appends are
|
||||
//! fsynced before [`Journal::append`] returns.
|
||||
//! fsynced before [`Journal::append`] returns, except natively: [`crate::FsStore`] hands them to
|
||||
//! a thread of its own that writes and syncs them in order right after (so a flag never waits
|
||||
//! for the drive), holds and retries whatever fails ([`Journal::unwritten`]) and refuses later
|
||||
//! appends meanwhile, so the log never has a gap and nothing handed over is dropped.
|
||||
//!
|
||||
//! Loading = snapshot + replay of the records with `seq > snapshot seq`. Recovery rules:
|
||||
//! - a **torn final record** (crash mid-append: truncated line or bad CRC at the end) is dropped
|
||||
@@ -22,6 +25,12 @@
|
||||
//! - a bad record **followed by good ones** is real damage: replay stops there, the log is kept
|
||||
//! as `catalog.log.damaged-<seq>`, and a fresh snapshot is written so the library stays usable.
|
||||
//!
|
||||
//! Segmentation grids are shared within a snapshot (issue #2154): each distinct grid is written
|
||||
//! once into `Catalog.grids` and the masks of the photo's develop settings, versions, history
|
||||
//! steps and import look refer to it by index, so an unchanged mask no longer repeats with every
|
||||
//! history step. The table lives only in the snapshot file; log records keep the full grids
|
||||
//! inline.
|
||||
//!
|
||||
//! **Background compaction** ([`Journal::snapshot_in_background`], when the store offers a
|
||||
//! [`Store::background_writer`]): a worker thread writes the snapshot of a copy of the catalog at
|
||||
//! op `N` while appends go on (durably, as always) to the same log. Once the snapshot is durable,
|
||||
@@ -52,6 +61,10 @@
|
||||
//! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` |
|
||||
//! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` |
|
||||
//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` |
|
||||
//! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) |
|
||||
//! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` |
|
||||
//! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` |
|
||||
//! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` |
|
||||
//!
|
||||
//! Rules:
|
||||
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
|
||||
@@ -76,7 +89,7 @@ pub const LOG: &str = "catalog.log";
|
||||
const FORMAT: &str = "lightcraft-catalog";
|
||||
/// The catalog format this build writes (and the newest it reads). See the module docs →
|
||||
/// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added.
|
||||
pub const VERSION: u32 = 9;
|
||||
pub const VERSION: u32 = 13;
|
||||
|
||||
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -193,6 +206,10 @@ pub struct Journal {
|
||||
/// A failed append may have left part of its records after `log_bytes`, and cutting them off
|
||||
/// failed too: the next append cuts the log back to `log_bytes` first.
|
||||
tail_dirty: bool,
|
||||
/// An append failed (natively that can be the store's own log thread failing to write records
|
||||
/// handed over before, which it holds and retries): the next chance writes a snapshot, a fresh
|
||||
/// file holding everything, in case only the log's file is broken.
|
||||
snapshot_due: bool,
|
||||
}
|
||||
|
||||
/// A background snapshot in flight.
|
||||
@@ -263,12 +280,18 @@ fn newer(what: String) -> CatalogError {
|
||||
CatalogError::Newer(format!("{what}; this version reads catalog format v{VERSION} and older"))
|
||||
}
|
||||
|
||||
/// The most `resync` spends re-validating the suffixes of one line whose whole bytes are not valid
|
||||
/// UTF-8 (a real fragment ends at any byte): one line of a modest malformed log that holds a start
|
||||
/// of a record in every few bytes used to re-validate the whole remaining suffix at every attempt
|
||||
/// (CWE-407). Past the budget the rest of the line stays a torn tail, which the damaged path keeps
|
||||
/// and reports, same state as before, minus the CPU.
|
||||
const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Start markers that `resync` decoded on this thread (test builds only; see the cost test).
|
||||
pub(crate) static RESYNC_CANDIDATES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Total bytes of candidate suffixes `resync` may decode per damaged line: every attempt reads
|
||||
/// the rest of the line, so trying every candidate of a crafted line would make
|
||||
/// [`Journal::open`] quadratic in the line length (CWE-407). The budget is far above any
|
||||
/// fragment-plus-retry a failed append can leave, but caps the stall; past it the line reads as
|
||||
/// damage, which is handled safely.
|
||||
pub(crate) const MAX_SCAN: usize = 64 << 20;
|
||||
|
||||
/// A line that doesn't decode but ends with a whole record: a fragment of a failed append followed
|
||||
/// by the record that retried it (the retry re-encodes the same ops with the same `seq`s). Returns
|
||||
@@ -276,32 +299,70 @@ const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
|
||||
/// The record's CRC must match, so damage is never mistaken for it.
|
||||
fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> {
|
||||
const START: &[u8] = b"{\"seq\":";
|
||||
// One record per line, so a line of valid UTF-8 holds a valid suffix at every record start and
|
||||
// one validation covers every candidate; only a line that is not wholly valid re-checks, and
|
||||
// then up to the budget rather than the suffix length times the candidate count.
|
||||
let whole = std::str::from_utf8(line).ok();
|
||||
let mut spent = 0usize;
|
||||
(1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| {
|
||||
let text = match &whole {
|
||||
Some(t) => &t[i..],
|
||||
None => {
|
||||
if spent >= RESYNC_BUDGET_BYTES {
|
||||
return None;
|
||||
}
|
||||
spent = spent.saturating_add(line.len() - i);
|
||||
std::str::from_utf8(&line[i..]).ok()?
|
||||
}
|
||||
// The retry record starts with the `{"seq":` marker, but that marker can also occur inside
|
||||
// the op body (a smart-album rule value such as `{"seq":1}`); then the last occurrence is
|
||||
// nested, not the record start, and decoding it rejects a valid retry. Scan every marker
|
||||
// once, left to right, then try them from the end. A candidate must match the record header
|
||||
// shape — `{"seq":<digits>,"crc":<digits>,"op":`, what `encode_record` writes — so a marker
|
||||
// nested inside the op body (followed by `}` or `,`) or plain junk never reaches
|
||||
// `decode_record`; only a real record start does. This imposes no fixed limit on how many
|
||||
// nested markers a valid record may contain. Each attempt then decodes the rest of the line,
|
||||
// so the scan budget bounds the total when a hostile line still holds many header-shaped
|
||||
// markers, keeping the work near-linear instead of quadratic. The fragment that precedes the
|
||||
// record stays to its left (`i > 0`).
|
||||
let digits = |b: &[u8]| b.iter().take_while(|x| x.is_ascii_digit()).count();
|
||||
let mut candidates: Vec<usize> = Vec::new();
|
||||
let mut from = 0;
|
||||
while let Some(i) = line[from..].windows(START.len()).position(|w| w == START) {
|
||||
let pos = from + i;
|
||||
let Some(after) = line.get(pos + START.len()..) else { break };
|
||||
let seq_digits = digits(after);
|
||||
let crc_field = after.get(seq_digits..).and_then(|rest| rest.strip_prefix(b",\"crc\":"));
|
||||
let crc_digits = crc_field.map(digits).unwrap_or(0);
|
||||
let op_field = crc_field.and_then(|rest| rest.get(crc_digits..)).and_then(|rest| rest.strip_prefix(b",\"op\":"));
|
||||
if seq_digits > 0 && crc_digits > 0 && op_field.is_some() {
|
||||
candidates.push(pos);
|
||||
}
|
||||
from = pos + START.len();
|
||||
}
|
||||
let mut scanned = 0usize;
|
||||
for &i in candidates.iter().rev() {
|
||||
if i == 0 {
|
||||
break; // the record must follow a fragment
|
||||
}
|
||||
let Some(suffix) = line.get(i..) else { continue };
|
||||
scanned = match scanned.checked_add(suffix.len()) {
|
||||
Some(total) if total <= MAX_SCAN => total,
|
||||
_ => break, // the budget is spent: stop trying further candidates
|
||||
};
|
||||
let rec = decode_record(text.trim_end_matches('\r'))?;
|
||||
(rec.0 <= last.saturating_add(1)).then_some((i, rec))
|
||||
})
|
||||
let Ok(text) = std::str::from_utf8(suffix) else { continue };
|
||||
#[cfg(test)]
|
||||
RESYNC_CANDIDATES.with(|c| c.set(c.get() + 1));
|
||||
if let Some((seq, op)) = decode_record(text.trim_end_matches('\u{0D}'))
|
||||
&& seq <= last.saturating_add(1)
|
||||
{
|
||||
return Some((i, (seq, op)));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Write `catalog.snap` for the state after op `seq`, streaming the JSON into the store (no
|
||||
/// whole-file string). The bytes are exactly
|
||||
/// `{"format":"lightcraft-catalog","version":1,"seq":N,"catalog":<serde_json of the catalog>}\n`,
|
||||
/// as before streaming. Fills in the serialise / write+sync times and the size.
|
||||
/// as before streaming. Each distinct segmentation grid of the photos' settings holders (see
|
||||
/// `Photo::settings_holders`) is written once (`Catalog.grids`), with the masks referring to it
|
||||
/// by index, so an unchanged mask does not repeat with every history step (issue #2154). Fills
|
||||
/// in the serialise / write+sync times and the size.
|
||||
fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io::Result<SnapshotTiming> {
|
||||
write_snapshot_owned(store, seq, catalog.clone())
|
||||
}
|
||||
|
||||
/// The same write, taking the catalog by value: the background path hands over the copy it
|
||||
/// already made, so a snapshot in flight holds one catalog, not two ([`Catalog::clone`] copies
|
||||
/// the photo pointers and the small tables, and the derived indexes start empty — real work on a
|
||||
/// large library).
|
||||
fn write_snapshot_owned(store: &mut dyn Store, seq: u64, mut snapshot: Catalog) -> std::io::Result<SnapshotTiming> {
|
||||
let t0 = web_time::Instant::now();
|
||||
let mut serialize_ms = 0.0;
|
||||
let bytes = store.write_atomic_with(SNAPSHOT, &mut |w| {
|
||||
@@ -311,7 +372,35 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io
|
||||
// 1 MiB chunks go through the store's `dyn Write`
|
||||
let mut b = std::io::BufWriter::with_capacity(1 << 20, w);
|
||||
write!(b, "{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":{seq},\"catalog\":")?;
|
||||
serde_json::to_writer(&mut b, catalog).map_err(std::io::Error::other)?;
|
||||
// The shared grids, in first-appearance order. The pool is a serialization detail:
|
||||
// `snapshot` itself is never modified (log records, presets and XMP stay inline).
|
||||
let mut pool: Vec<String> = Vec::new();
|
||||
let mut index: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
|
||||
{
|
||||
let mut see = |s: &lightcraft_develop::DevelopSettings| {
|
||||
s.visit_seg_masks(&mut |m| {
|
||||
// borrowed lookup: a grid every history step shares is not cloned just to
|
||||
// find it already indexed (only a new grid is copied, into pool and table)
|
||||
if !m.data.is_empty() && !index.contains_key(m.data.as_str()) {
|
||||
index.insert(m.data.clone(), pool.len() as u32);
|
||||
pool.push(m.data.clone());
|
||||
}
|
||||
});
|
||||
};
|
||||
for p in snapshot.photos.values() {
|
||||
for settings in p.settings_holders() {
|
||||
see(settings);
|
||||
}
|
||||
}
|
||||
}
|
||||
snapshot.grids = pool;
|
||||
match lightcraft_develop::with_grid_interner(index, || serde_json::to_writer(&mut b, &snapshot)) {
|
||||
// no interner can be active here (snapshot writes don't nest), so `None` is a bug:
|
||||
// fail the write rather than store a truncated or reference-less snapshot
|
||||
Some(Ok(())) => {}
|
||||
Some(Err(e)) => return Err(std::io::Error::other(e)),
|
||||
None => return Err(std::io::Error::other("nested grid interner while writing a snapshot")),
|
||||
}
|
||||
b.write_all(b"}\n")?;
|
||||
b.flush()?;
|
||||
serialize_ms = ms_since(t);
|
||||
@@ -381,6 +470,7 @@ impl Journal {
|
||||
pending: None,
|
||||
retry_at_records: 0,
|
||||
tail_dirty: false,
|
||||
snapshot_due: false,
|
||||
};
|
||||
let log = log.unwrap_or_default();
|
||||
|
||||
@@ -514,6 +604,7 @@ impl Journal {
|
||||
self.tail_dirty = false;
|
||||
}
|
||||
if let Err(e) = self.store.append(LOG, buf.as_bytes()) {
|
||||
self.snapshot_due = true;
|
||||
// Part of the batch may be in the file. Cut it back to the last whole record, so the
|
||||
// retry (same seqs) starts on a clean line instead of after a fragment that would
|
||||
// read back as damage.
|
||||
@@ -596,7 +687,7 @@ impl Journal {
|
||||
let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) };
|
||||
let copy = catalog.clone();
|
||||
let seq = self.seq;
|
||||
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot(writer.as_mut(), seq, ©));
|
||||
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot_owned(writer.as_mut(), seq, copy));
|
||||
let worker = match spawned {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
@@ -676,6 +767,7 @@ impl Journal {
|
||||
}
|
||||
|
||||
fn record_snapshot(&mut self, t: SnapshotTiming) {
|
||||
self.snapshot_due = false;
|
||||
self.stats.snapshots += 1;
|
||||
self.stats.last_snapshot = t;
|
||||
self.stats.max_snapshot_ms = self.stats.max_snapshot_ms.max(t.total_ms);
|
||||
@@ -695,6 +787,23 @@ impl Journal {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until every appended record is in the file and synced (natively the store writes the
|
||||
/// log on a thread of its own, [`crate::FsStore`]): before the files are read or copied from
|
||||
/// outside. An error says why some aren't yet: they are held and retried, never dropped.
|
||||
pub fn flush(&mut self) -> Result<()> {
|
||||
self.store.flush().map_err(io)
|
||||
}
|
||||
|
||||
/// Appended records the store holds because writing them failed (retried), and why; `None`
|
||||
/// when nothing is held back. Never waits for the drive.
|
||||
pub fn unwritten(&self) -> Option<(usize, String)> {
|
||||
// a snapshot that holds every op holds whatever the log's thread still holds
|
||||
if self.snapshot_seq >= self.seq && self.pending.is_none() {
|
||||
return None;
|
||||
}
|
||||
self.store.unwritten()
|
||||
}
|
||||
|
||||
/// Where persistence time went so far.
|
||||
pub fn stats(&self) -> PersistStats {
|
||||
PersistStats { snapshot_running: self.pending.is_some(), ..self.stats }
|
||||
@@ -704,7 +813,10 @@ impl Journal {
|
||||
pub fn wants_snapshot(&self) -> bool {
|
||||
self.pending.is_none()
|
||||
&& self.log_records >= self.retry_at_records
|
||||
&& (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_bytes)
|
||||
&& (self.snapshot_due
|
||||
|| self.unwritten().is_some()
|
||||
|| self.log_records >= self.policy.max_records
|
||||
|| self.log_bytes >= self.policy.max_bytes)
|
||||
}
|
||||
|
||||
pub fn seq(&self) -> u64 {
|
||||
@@ -760,4 +872,29 @@ mod tests_resync {
|
||||
// matches, so the double `Some` is only reached with `last >= 4`
|
||||
assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
|
||||
}
|
||||
|
||||
/// A retry record whose op body holds more than eight nested `{"seq":` markers (a
|
||||
/// `SetAlbumRules` with nine rule values of `{"seq":1}`) exhausts `resync`'s fixed
|
||||
/// `MAX_DECODES = 8` decode budget on the nested markers, so the outer record's real
|
||||
/// start is never decoded and the valid operation is truncated as damage.
|
||||
#[test]
|
||||
fn resync_recovers_retry_beyond_eight_nested_markers() {
|
||||
let mut c = Catalog::new();
|
||||
let album_id = c.alloc_album_id();
|
||||
let mut rules = Vec::new();
|
||||
for _ in 0..9 {
|
||||
rules.push(crate::Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) });
|
||||
}
|
||||
let retry_op = Op::SetAlbumRules {
|
||||
id: album_id,
|
||||
rules: Box::new(crate::Filter { rule_set: Some(crate::RuleSet { mode: crate::Match::All, rules }), ..Default::default() }),
|
||||
};
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let record = format!("{{\"seq\":5,\"crc\":{crc},\"op\":{body}}}");
|
||||
let mut line = Vec::from(b"torn fragment" as &[u8]);
|
||||
let fragment = line.len();
|
||||
line.extend_from_slice(record.as_bytes());
|
||||
assert_eq!(resync(&line, 4).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,12 @@ pub fn from_file(flat: &[String], hierarchical: &[String]) -> Vec<String> {
|
||||
/// The deepest a keyword list file may nest keywords: a file is input, so its nesting is bounded.
|
||||
pub const MAX_LEVELS: usize = 64;
|
||||
|
||||
/// The most bytes of full keyword paths a keyword list file may spell out. Every line names its
|
||||
/// keyword by its whole path (`parent|child`), so a file of one long keyword with many short ones
|
||||
/// inside it would otherwise grow into far more memory than its own size (CWE-400). Lightroom
|
||||
/// Classic's own lists of tens of thousands of keywords come to a few MiB.
|
||||
pub const MAX_LIST_PATH_BYTES: usize = 64 << 20; // 64 MiB
|
||||
|
||||
/// A keyword list as written by [`Catalog::keyword_list_text`]: the file's text, the keywords in
|
||||
/// it (paths), and what the format can't hold and so is left out (a keyword, with those inside it,
|
||||
/// as its path; a synonym as `path {synonym}`).
|
||||
@@ -114,6 +120,8 @@ pub fn parse_keyword_list(text: &str) -> Result<Vec<(String, KeywordInfo)>> {
|
||||
let mut synonyms: std::collections::HashMap<usize, std::collections::HashSet<String>> = std::collections::HashMap::new();
|
||||
// the keyword at each level above the line: its path and where it is in `out`
|
||||
let mut above: Vec<(String, usize)> = Vec::new();
|
||||
// bytes of full paths spelled out so far, checked against `MAX_LIST_PATH_BYTES` before each
|
||||
let mut path_bytes = 0usize;
|
||||
for (i, line) in text.split('\n').enumerate() {
|
||||
let n = i + 1;
|
||||
if line.trim().is_empty() {
|
||||
@@ -162,6 +170,11 @@ pub fn parse_keyword_list(text: &str) -> Result<Vec<(String, KeywordInfo)>> {
|
||||
return Err(bad(n, "“|” separates a keyword's levels: a name can't hold one"));
|
||||
}
|
||||
above.truncate(depth);
|
||||
let parent_len = above.last().map_or(0, |(parent, _)| parent.len().saturating_add(1));
|
||||
path_bytes = path_bytes.saturating_add(parent_len.saturating_add(name.len()));
|
||||
if path_bytes > MAX_LIST_PATH_BYTES {
|
||||
return Err(bad(n, &format!("the keywords' full paths come to more than {} MiB", MAX_LIST_PATH_BYTES >> 20)));
|
||||
}
|
||||
let path = match above.last() {
|
||||
Some((parent, _)) => format!("{parent}{SEP}{name}"),
|
||||
None => name.to_string(),
|
||||
@@ -189,6 +202,14 @@ pub fn closest<'a>(k: &str, from: &'a [String]) -> Option<&'a String> {
|
||||
from.iter().filter(|f| is_under(k, f)).max_by_key(|f| f.split(SEP).count())
|
||||
}
|
||||
|
||||
/// Add each of `more` to `synonyms` that isn't there in any case, in order. One lowered set of
|
||||
/// what is there, not a search of the growing list per synonym: an imported list can give a
|
||||
/// keyword many synonyms, and the search was quadratic in them (CWE-407).
|
||||
fn merge_synonyms(synonyms: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
|
||||
let mut seen: std::collections::HashSet<String> = synonyms.iter().map(|s| s.to_lowercase()).collect();
|
||||
synonyms.extend(more.into_iter().filter(|s| seen.insert(s.to_lowercase())));
|
||||
}
|
||||
|
||||
/// Keep the first of case-insensitively equal keywords.
|
||||
fn dedupe(v: &mut Vec<String>) {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
@@ -402,11 +423,7 @@ impl Catalog {
|
||||
Some(there) => {
|
||||
there.info.new_keywords_inside |= l.info.new_keywords_inside;
|
||||
there.info.keyword_shortcut |= l.info.keyword_shortcut;
|
||||
for s in l.info.synonyms {
|
||||
if !there.info.synonyms.iter().any(|x| same(x, &s)) {
|
||||
there.info.synonyms.push(s);
|
||||
}
|
||||
}
|
||||
merge_synonyms(&mut there.info.synonyms, l.info.synonyms);
|
||||
}
|
||||
None => {
|
||||
list.insert(path.to_lowercase(), ListedKeyword { path, info: l.info });
|
||||
@@ -467,8 +484,11 @@ impl Catalog {
|
||||
let defaults = KeywordInfo::default();
|
||||
let info = |path: &str| self.keyword_info(path).unwrap_or(&defaults);
|
||||
let mut out = ExportKeywords::default();
|
||||
let push = |v: &mut Vec<String>, s: &str| {
|
||||
if !s.is_empty() && !v.iter().any(|x| same(x, s)) {
|
||||
// what each list holds, lowered: a search of the list per name was quadratic in a keyword's
|
||||
// synonyms, which an imported list sets (CWE-407)
|
||||
let (mut flat_seen, mut paths_seen) = (std::collections::HashSet::new(), std::collections::HashSet::new());
|
||||
let push = |v: &mut Vec<String>, seen: &mut std::collections::HashSet<String>, s: &str| {
|
||||
if !s.is_empty() && seen.insert(s.to_lowercase()) {
|
||||
v.push(s.to_string());
|
||||
}
|
||||
};
|
||||
@@ -481,11 +501,11 @@ impl Catalog {
|
||||
let levels: Vec<&str> = path.split(SEP).collect();
|
||||
let mut names = |at: usize, i: &KeywordInfo| {
|
||||
if let Some(name) = levels.get(at) {
|
||||
push(&mut out.flat, name);
|
||||
push(&mut out.flat, &mut flat_seen, name);
|
||||
}
|
||||
if i.export_synonyms {
|
||||
for s in &i.synonyms {
|
||||
push(&mut out.flat, s.trim());
|
||||
push(&mut out.flat, &mut flat_seen, s.trim());
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -499,7 +519,7 @@ impl Catalog {
|
||||
}
|
||||
}
|
||||
}
|
||||
push(&mut out.hierarchical, &path);
|
||||
push(&mut out.hierarchical, &mut paths_seen, &path);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -509,6 +529,13 @@ impl Catalog {
|
||||
/// keyword, a keyword left out of export in square brackets; by name. What the format can't hold
|
||||
/// is left out and named, so the file always reads back.
|
||||
pub fn keyword_list_text(&self) -> KeywordListFile {
|
||||
self.keyword_list_text_within(MAX_LIST_PATH_BYTES)
|
||||
}
|
||||
|
||||
/// [`keyword_list_text`](Self::keyword_list_text) with the full paths written held to
|
||||
/// `max_path_bytes` as [`parse_keyword_list`] holds them: a keyword past it is named
|
||||
/// unwritable, with its subtree, so the file reads back.
|
||||
fn keyword_list_text_within(&self, max_path_bytes: usize) -> KeywordListFile {
|
||||
// a name the list would read as something else, or not at all
|
||||
fn unwritable(name: &str) -> bool {
|
||||
name.trim().is_empty()
|
||||
@@ -519,14 +546,27 @@ impl Catalog {
|
||||
|| (name.starts_with('[') && name.ends_with(']'))
|
||||
|| (name.starts_with('{') && name.ends_with('}'))
|
||||
}
|
||||
fn write(c: &Catalog, nodes: &[KeywordNode], depth: usize, file: &mut KeywordListFile) {
|
||||
fn write(
|
||||
c: &Catalog,
|
||||
nodes: &[KeywordNode],
|
||||
depth: usize,
|
||||
file: &mut KeywordListFile,
|
||||
path_bytes: &mut usize,
|
||||
max_path_bytes: usize,
|
||||
parent_len: usize,
|
||||
) {
|
||||
let tabs = "\t".repeat(depth);
|
||||
for n in nodes {
|
||||
// the keywords inside go with it: under its parent they'd be other keywords
|
||||
if depth >= MAX_LEVELS || unwritable(&n.name) {
|
||||
// (a line's full path is what the reader counts against its path budget)
|
||||
// the path the reader rebuilds from the lines written: the parent as emitted, a
|
||||
// separator, the name (a child's `n.path` can spell its parent in another case)
|
||||
let emitted = if depth == 0 { n.name.len() } else { parent_len + SEP.len_utf8() + n.name.len() };
|
||||
if depth >= MAX_LEVELS || unwritable(&n.name) || path_bytes.saturating_add(emitted) > max_path_bytes {
|
||||
file.unwritable.push(n.path.clone());
|
||||
continue;
|
||||
}
|
||||
*path_bytes += emitted;
|
||||
let info = c.keyword_info(&n.path).cloned().unwrap_or_default();
|
||||
if info.include_on_export {
|
||||
file.text.push_str(&format!("{tabs}{}\n", n.name));
|
||||
@@ -536,19 +576,21 @@ impl Catalog {
|
||||
file.written.push(n.path.clone());
|
||||
// the reader trims synonyms and takes one per spelling: an empty one, or another's
|
||||
// in a different case, is no loss; a line break or a “|” is
|
||||
let mut synonyms: Vec<&str> = Vec::new();
|
||||
// (one lowered set, not a search of those written so far per synonym: quadratic
|
||||
// in a keyword's synonyms, which an imported list sets — CWE-407)
|
||||
let mut synonyms: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
for s in info.synonyms.iter().map(|s| s.trim()) {
|
||||
if s.is_empty() || synonyms.iter().any(|x| same(x, s)) {
|
||||
if s.is_empty() || synonyms.contains(&s.to_lowercase()) {
|
||||
continue;
|
||||
}
|
||||
if s.chars().any(char::is_control) || s.contains(SEP) {
|
||||
file.unwritable.push(format!("{} {{{s}}}", n.path));
|
||||
} else {
|
||||
synonyms.push(s);
|
||||
synonyms.insert(s.to_lowercase());
|
||||
file.text.push_str(&format!("{tabs}\t{{{s}}}\n"));
|
||||
}
|
||||
}
|
||||
write(c, &n.children, depth + 1, file);
|
||||
write(c, &n.children, depth + 1, file, path_bytes, max_path_bytes, emitted);
|
||||
}
|
||||
}
|
||||
let mut file = KeywordListFile::default();
|
||||
@@ -568,7 +610,7 @@ impl Catalog {
|
||||
}
|
||||
}
|
||||
}
|
||||
write(self, &self.keyword_tree(), 0, &mut file);
|
||||
write(self, &self.keyword_tree(), 0, &mut file, &mut 0, max_path_bytes, 0);
|
||||
file.unwritable.extend(over_deep);
|
||||
file
|
||||
}
|
||||
@@ -632,11 +674,7 @@ impl Catalog {
|
||||
// one the library has: the list's synonyms join its own (listed only if it gains some)
|
||||
let mut info_now = list.get(&key).map(|l| l.info.clone()).unwrap_or_default();
|
||||
let before = info_now.synonyms.len();
|
||||
for s in &info.synonyms {
|
||||
if !info_now.synonyms.iter().any(|x| same(x, s)) {
|
||||
info_now.synonyms.push(s.clone());
|
||||
}
|
||||
}
|
||||
merge_synonyms(&mut info_now.synonyms, info.synonyms.iter().cloned());
|
||||
if info_now.synonyms.len() > before {
|
||||
let path = list.get(&key).map_or(path, |l| l.path.clone());
|
||||
list.insert(key, ListedKeyword { path, info: info_now });
|
||||
|
||||
@@ -556,6 +556,17 @@ fn the_keyword_list_is_written_as_tab_indented_text() {
|
||||
assert_eq!(c.keyword_list_text().text, "beach\nEvents\n\tWeddings\n[Places]\n\tLisbon\n\t\t{Lisboa}\n");
|
||||
}
|
||||
|
||||
/// The path budget the reader enforces holds for the writer too: a keyword past it, and its
|
||||
/// subtree, is named unwritable instead of making a file `keyword.import` rejects.
|
||||
#[test]
|
||||
fn the_keyword_list_written_stays_within_the_path_budget() {
|
||||
let (c, _) = lib(&[&["Places|Lisbon", "beach"], &["Events|Weddings"]]);
|
||||
let file = c.keyword_list_text_within(17);
|
||||
assert_eq!(file.text, "beach\nEvents\nPlaces\n");
|
||||
assert_eq!(file.unwritable, ["Events|Weddings", "Places|Lisbon"]);
|
||||
assert_eq!(c.keyword_list_text().unwritable, Vec::<String>::new());
|
||||
}
|
||||
|
||||
/// Reading a list gives each keyword's path and attributes: what was written comes back, and a
|
||||
/// file from elsewhere (Windows line ends, a byte-order mark, blank lines) reads too.
|
||||
#[test]
|
||||
@@ -765,3 +776,47 @@ fn keyword_tree_caps_a_keyword_at_the_list_depth() {
|
||||
let deepest = tree_paths(&c.keyword_tree()).iter().map(|(p, _)| p.split(SEP).count()).max().unwrap_or(0);
|
||||
assert_eq!(deepest, MAX_LEVELS);
|
||||
}
|
||||
|
||||
/// A keyword list file spells each keyword's whole path, so one long keyword with many short ones
|
||||
/// inside it expands into far more than its own size: past `MAX_LIST_PATH_BYTES` it is refused
|
||||
/// with the line where that happened, instead of growing without bound (CWE-400).
|
||||
#[test]
|
||||
fn a_list_whose_paths_expand_past_the_budget_is_refused() {
|
||||
let parent = "p".repeat(1 << 20);
|
||||
let children = MAX_LIST_PATH_BYTES / parent.len() + 2;
|
||||
let mut text = format!("{parent}\n");
|
||||
for i in 0..children {
|
||||
text.push_str(&format!("\tc{i}\n"));
|
||||
}
|
||||
let err = parse_keyword_list(&text).unwrap_err().to_string();
|
||||
assert!(err.contains("full paths come to more than"), "{err}");
|
||||
// a list within the budget still reads
|
||||
let ok = parse_keyword_list(&format!("{parent}\n\tchild\n")).unwrap();
|
||||
assert_eq!(ok.len(), 2);
|
||||
assert_eq!(ok[1].0, format!("{parent}|child"));
|
||||
}
|
||||
|
||||
/// Many synonyms joining a keyword the library has, its export and its keyword list file each keep
|
||||
/// every spelling once, in order, without a search of the growing list per synonym (CWE-407).
|
||||
#[test]
|
||||
fn many_synonyms_are_gathered_once_each_in_order() {
|
||||
const N: usize = 40_000;
|
||||
let mut c = Catalog::new();
|
||||
c.apply(Op::SetKeyword { path: "travel".into(), info: Some(with_synonyms(&["Trip"])) }).unwrap();
|
||||
let mut incoming: Vec<String> = (0..N).map(|i| format!("syn{i}")).collect();
|
||||
incoming.push("TRIP".into());
|
||||
incoming.push("SYN7".into());
|
||||
let started = std::time::Instant::now();
|
||||
let (op, added, updated) = c.import_keywords_ops(&[("travel".into(), KeywordInfo { synonyms: incoming, ..KeywordInfo::default() })]);
|
||||
c.apply(op).unwrap();
|
||||
assert_eq!((added, updated), (0, 1));
|
||||
let synonyms = c.keyword_info("travel").unwrap().synonyms.clone();
|
||||
assert_eq!(synonyms.len(), N + 1);
|
||||
assert_eq!(synonyms[0], "Trip");
|
||||
assert_eq!(synonyms[8], "syn7");
|
||||
let exported = c.export_keywords(&["travel".into()]);
|
||||
assert_eq!(exported.flat.len(), N + 2);
|
||||
let file = c.keyword_list_text();
|
||||
assert_eq!(file.text.lines().count(), N + 2);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(20), "took {:?}", started.elapsed());
|
||||
}
|
||||
@@ -14,13 +14,19 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod dates;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[doc(hidden)]
|
||||
pub mod fault;
|
||||
pub mod folders;
|
||||
mod index;
|
||||
pub mod journal;
|
||||
pub mod keywords;
|
||||
pub mod local;
|
||||
pub mod lock;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod log_writer;
|
||||
pub mod model;
|
||||
pub mod opened_folder;
|
||||
pub mod query;
|
||||
pub mod rules;
|
||||
pub mod safe_file;
|
||||
@@ -40,6 +46,7 @@ use lightcraft_develop::DevelopSettings;
|
||||
pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, LocalRecords, folder_of};
|
||||
pub use lock::{LibraryLock, LockError, LockOwner};
|
||||
pub use model::*;
|
||||
pub use opened_folder::OpenedFolder;
|
||||
pub use query::{DateGroup, Filter, Person, RatingOp, Sort, SortKey, mix64};
|
||||
pub use rules::{Match, Rule, RuleSet};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -217,8 +224,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,
|
||||
},
|
||||
@@ -285,6 +292,13 @@ pub struct Catalog {
|
||||
/// What the library keeps about its folders (folder identity → record), see [`folders`].
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
folder_records: BTreeMap<String, FolderRecord>,
|
||||
/// Segmentation grids shared by this snapshot's masks: each distinct grid's data once, in
|
||||
/// first-appearance order, referenced by index from the masks ([`lightcraft_develop::\
|
||||
/// SegMask::grid`] is a position here). A serialization detail of snapshots
|
||||
/// ([`journal`]): never held in the live catalog — [`Catalog::repair`] resolves the
|
||||
/// references and clears the table when a snapshot is read.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
grids: Vec<String>,
|
||||
/// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog
|
||||
/// changed, so what is keyed by the revision is out of date).
|
||||
#[serde(skip)]
|
||||
@@ -363,6 +377,25 @@ impl std::fmt::Debug for PlansMemo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the shared-grid references of one settings holder (see [`Photo::settings_holders`])
|
||||
/// against a snapshot's grid table: each referenced mask takes its
|
||||
/// grid's data and the reference is cleared. A reference past the table (a damaged snapshot)
|
||||
/// leaves the mask empty — it renders nothing, like any other damaged grid. Data present on the
|
||||
/// mask itself wins over a stray reference. Returns the dangling count added to `dangling`.
|
||||
fn resolve_grids(settings: &mut Arc<DevelopSettings>, grids: &[String], dangling: usize) -> usize {
|
||||
let mut dangling = dangling;
|
||||
Arc::make_mut(settings).visit_seg_masks_mut(&mut |m| {
|
||||
if let Some(i) = m.grid.take() {
|
||||
match (m.data.is_empty(), grids.get(i as usize)) {
|
||||
(true, Some(data)) => m.data = data.clone(),
|
||||
(true, None) => dangling += 1,
|
||||
(false, _) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
dangling
|
||||
}
|
||||
|
||||
/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can
|
||||
/// follow a small edit without being worked out again from every photo.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -1193,6 +1226,23 @@ impl Catalog {
|
||||
/// wrote).
|
||||
pub fn repair(&mut self) -> Vec<String> {
|
||||
let mut changed = Vec::new();
|
||||
// Segmentation grids shared by the snapshot this was read from (issue #2154): each
|
||||
// reference takes its grid's data, and the table is not kept — a live catalog always
|
||||
// stores the data inline, so masks render and serialize without the snapshot's table.
|
||||
// Resolving is the normal way a snapshot in this format reads (not reported); a
|
||||
// reference past the table is damage and is reported — that includes a reference into
|
||||
// an empty table, which is always dangling, so the table being empty does not skip it.
|
||||
let grids = std::mem::take(&mut self.grids);
|
||||
let mut dangling = 0usize;
|
||||
for p in self.photos.values_mut() {
|
||||
let photo = Arc::make_mut(p);
|
||||
for settings in photo.settings_holders_mut() {
|
||||
dangling = resolve_grids(settings, &grids, dangling);
|
||||
}
|
||||
}
|
||||
if dangling > 0 {
|
||||
changed.push(format!("{dangling} segmentation grid reference(s) pointed past the shared table: cleared"));
|
||||
}
|
||||
for (id, p) in self.photos.iter_mut() {
|
||||
if p.id != *id {
|
||||
changed.push(format!("photo {} was filed as {}", p.id.0, id.0));
|
||||
@@ -1489,6 +1539,8 @@ mod tests_folders;
|
||||
#[cfg(test)]
|
||||
mod tests_format_version;
|
||||
#[cfg(test)]
|
||||
mod tests_grids;
|
||||
#[cfg(test)]
|
||||
mod tests_index;
|
||||
#[cfg(test)]
|
||||
mod tests_journal;
|
||||
@@ -1496,6 +1548,10 @@ mod tests_journal;
|
||||
mod tests_local;
|
||||
#[cfg(test)]
|
||||
mod tests_lock;
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_log_thread;
|
||||
#[cfg(test)]
|
||||
mod tests_opened_folder;
|
||||
#[cfg(test)]
|
||||
mod tests_repair;
|
||||
#[cfg(test)]
|
||||
|
||||
+87
-19
@@ -18,17 +18,26 @@
|
||||
//! descriptor frees the lock whatever copies a child still holds.
|
||||
//! - Who holds it (process id, computer, program, version) is written to `catalog.lock.owner`, for
|
||||
//! the error message. Only dropping the [`LibraryLock`] removes it, so a program that ends with
|
||||
//! `std::process::exit` releases the lock first (`Session::release_library_lock`). It's a separate
|
||||
//! file because a Windows lock also blocks reading the locked file. It's only a hint: it may be
|
||||
//! missing or left over from a crash.
|
||||
//! `std::process::exit` releases the lock first (`Session::release_library_lock`). Dropping
|
||||
//! removes only the note this lock wrote itself, with the bytes it wrote, and only while the
|
||||
//! path still leads to the folder it locked (a folder that holds exactly that note is it, whatever
|
||||
//! its numbers say: [`OpenedFolder::vouch`]): a note in another folder (a share mounted over the
|
||||
//! library's folder), or one another process wrote over ours, belongs to whoever has that library
|
||||
//! open (issue #3240). It's a separate file because a Windows lock also blocks reading the
|
||||
//! locked file. It's only a hint: it may be missing or left over from a crash. The note holds a
|
||||
//! value no other lock's note has ([`LockOwner::token`]), so no two folders hold the same note.
|
||||
//! - File systems without lock support (some network shares): the library opens unlocked, with a
|
||||
//! warning — refusing it would lock the user out of their own library. Locks over SMB/NFS are
|
||||
//! advisory and depend on the server; the owner file is then the only hint.
|
||||
//! - Browser storage (OPFS) has no file locks: see the web host for its own guard.
|
||||
|
||||
use std::fs::{File, OpenOptions, TryLockError};
|
||||
use std::hash::{BuildHasher, Hasher, RandomState};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::opened_folder::OpenedFolder;
|
||||
|
||||
/// The lock file in the library directory.
|
||||
pub const LOCK: &str = "catalog.lock";
|
||||
@@ -47,6 +56,10 @@ pub struct LockOwner {
|
||||
pub version: String,
|
||||
/// When it opened the library (seconds since 1970).
|
||||
pub since: u64,
|
||||
/// This lock's alone, also among those one process takes in the same second: the note is what
|
||||
/// tells the folder that was locked from every other ([`OpenedFolder::vouch`], issue #3240), so
|
||||
/// no two may be the same. A count of locks mixed with a random key. Not a secret.
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
impl LockOwner {
|
||||
@@ -58,6 +71,7 @@ impl LockOwner {
|
||||
program: program.to_string(),
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
since: web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0),
|
||||
token: lock_token(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +96,14 @@ fn host_name() -> String {
|
||||
env.or_else(|| std::fs::read_to_string("/etc/hostname").ok()).map(|h| h.trim().to_string()).filter(|h| !h.is_empty()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A value no other lock's note has ([`LockOwner::token`]).
|
||||
fn lock_token() -> String {
|
||||
static LOCKS: AtomicU64 = AtomicU64::new(0);
|
||||
let mut h = RandomState::new().build_hasher();
|
||||
h.write_u64(LOCKS.fetch_add(1, Ordering::Relaxed));
|
||||
format!("{:016x}", h.finish())
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LockError {
|
||||
/// Another process has the library open.
|
||||
@@ -97,14 +119,20 @@ pub struct LibraryLock {
|
||||
/// `None` when the file system can't lock (the library is open unlocked).
|
||||
file: Option<File>,
|
||||
held: bool,
|
||||
/// The folder `dir` named when the lock was taken: the lock file and the owner note are in it
|
||||
/// (`None`: it couldn't be looked at).
|
||||
folder: Option<OpenedFolder>,
|
||||
/// The owner note as this lock wrote it (`None`: it wrote none).
|
||||
note: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl LibraryLock {
|
||||
/// Lock `dir` (which must exist) for this process. Fails only when another process holds it.
|
||||
pub fn acquire(dir: &Path, program: &str) -> Result<LibraryLock, LockError> {
|
||||
let folder = OpenedFolder::at(dir).ok();
|
||||
let unlocked = |why: io::Error| {
|
||||
log::warn!("library {}: can't lock {LOCK} ({why}); opening it without protection against a second program", dir.display());
|
||||
LibraryLock { dir: dir.to_path_buf(), file: None, held: false }
|
||||
LibraryLock { dir: dir.to_path_buf(), file: None, held: false, folder: folder.clone(), note: None }
|
||||
};
|
||||
let file = match OpenOptions::new().read(true).write(true).create(true).truncate(false).open(dir.join(LOCK)) {
|
||||
Ok(f) => f,
|
||||
@@ -118,15 +146,20 @@ impl LibraryLock {
|
||||
}
|
||||
Err(TryLockError::Error(e)) => return Ok(unlocked(e)),
|
||||
}
|
||||
// A new file in place of whatever is at the name: a link planted there in a library folder
|
||||
// someone else prepared is removed, never written through (as for the staging files, #1502).
|
||||
let owner = LockOwner::this_process(program);
|
||||
if let Ok(json) = serde_json::to_vec_pretty(&owner)
|
||||
&& let Err(e) = crate::store::create_staging(&dir.join(OWNER)).and_then(|mut f| f.write_all(&json))
|
||||
{
|
||||
log::warn!("library {}: can't write {OWNER}: {e}", dir.display());
|
||||
}
|
||||
Ok(LibraryLock { dir: dir.to_path_buf(), file: Some(file), held: true })
|
||||
let note = serde_json::to_vec_pretty(&LockOwner::this_process(program)).ok().and_then(|json| match write_note(dir, folder.as_ref(), &json) {
|
||||
Ok(()) => {
|
||||
// from now on the folder that holds this note is the locked one, whatever its numbers say
|
||||
if let Some(folder) = &folder {
|
||||
folder.vouch(&json);
|
||||
}
|
||||
Some(json)
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("library {}: can't write {OWNER}: {e}", dir.display());
|
||||
None
|
||||
}
|
||||
});
|
||||
Ok(LibraryLock { dir: dir.to_path_buf(), file: Some(file), held: true, folder, note })
|
||||
}
|
||||
|
||||
/// The OS lock is held (`false`: the file system can't lock; opened unprotected).
|
||||
@@ -138,6 +171,16 @@ impl LibraryLock {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
/// The folder the lock was taken in, as `dir` named it then (`None`: it couldn't be looked at).
|
||||
pub fn folder(&self) -> Option<&OpenedFolder> {
|
||||
self.folder.as_ref()
|
||||
}
|
||||
|
||||
/// The owner note this lock wrote (`None`: it wrote none, so no folder is told by it).
|
||||
pub fn note(&self) -> Option<&[u8]> {
|
||||
self.note.as_deref()
|
||||
}
|
||||
|
||||
/// Another descriptor on the locked file: what a process spawned by another thread holds
|
||||
/// between fork and exec (a `dup` refers to the same open file description). Tests only (the
|
||||
/// test that uses it is Unix-only: `flock` semantics).
|
||||
@@ -145,17 +188,42 @@ impl LibraryLock {
|
||||
pub(crate) fn descriptor_copy(&self) -> Option<File> {
|
||||
self.file.as_ref().and_then(|f| f.try_clone().ok())
|
||||
}
|
||||
|
||||
/// Remove the owner note if it is this lock's: the path still leads to the folder the lock was
|
||||
/// taken in (or to one that holds this very note), and the note has the bytes this lock wrote
|
||||
/// there (issue #3240).
|
||||
fn remove_own_note(&self) {
|
||||
let Some(ours) = &self.note else { return };
|
||||
if self.folder.as_ref().is_some_and(|f| f.check().is_err()) {
|
||||
return;
|
||||
}
|
||||
let path = self.dir.join(OWNER);
|
||||
if crate::opened_folder::holds_exactly(&path, ours) {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the owner note into `dir`: a new file in place of whatever is at the name (a link planted
|
||||
/// there in a library folder someone else prepared is removed, never written through, as for the
|
||||
/// staging files, #1502), and only while `dir` still leads to the folder the lock file was opened in.
|
||||
fn write_note(dir: &Path, folder: Option<&OpenedFolder>, json: &[u8]) -> io::Result<()> {
|
||||
if let Some(folder) = folder {
|
||||
folder.check()?;
|
||||
}
|
||||
crate::store::create_staging(&dir.join(OWNER))?.write_all(json)
|
||||
}
|
||||
|
||||
impl Drop for LibraryLock {
|
||||
/// Remove the owner note while still holding the lock (so it can't delete the next holder's),
|
||||
/// then release the lock explicitly. Closing the handle isn't enough on Unix: `flock` lasts
|
||||
/// while any copy of the descriptor is open, and a process another thread is spawning holds a
|
||||
/// copy of every descriptor until it execs (issue #680). If the unlock fails the handle still
|
||||
/// closes right after, which releases the lock once every copy is gone, as before.
|
||||
/// Remove the owner note, if it is ours, while still holding the lock (so it can't delete the
|
||||
/// next holder's), then release the lock explicitly. Closing the handle isn't enough on Unix:
|
||||
/// `flock` lasts while any copy of the descriptor is open, and a process another thread is
|
||||
/// spawning holds a copy of every descriptor until it execs (issue #680). If the unlock fails
|
||||
/// the handle still closes right after, which releases the lock once every copy is gone, as
|
||||
/// before.
|
||||
fn drop(&mut self) {
|
||||
if self.held {
|
||||
let _ = std::fs::remove_file(self.dir.join(OWNER));
|
||||
self.remove_own_note();
|
||||
if let Some(f) = &self.file
|
||||
&& let Err(e) = f.unlock()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
//! The thread that writes the catalog log for [`crate::FsStore`] (natively).
|
||||
//!
|
||||
//! An append hands its bytes over and returns; the thread writes them in order and makes each batch
|
||||
//! durable (`sync_data`) before the next. The caller (the UI thread, for the app) never waits for
|
||||
//! the drive: on Windows a write to a file waits for a sync of that file in flight, so with the log
|
||||
//! written and synced on the UI thread every flag, rating and step waited for the drive, 30–90 ms
|
||||
//! on a busy disk in a test and over a second on a photographer's machine while previews were
|
||||
//! written.
|
||||
//!
|
||||
//! **Nothing handed over is ever dropped.** The store's log is the file's first `good` bytes (written
|
||||
//! and synced) followed by `held`, the bytes handed over and not yet synced. A write or sync that
|
||||
//! fails keeps `held` and retries it (on every later message, and every [`RETRY`] meanwhile), first
|
||||
//! cutting the file back to `good` so a fragment of the failed write never stays in it. While a
|
||||
//! failure stands, [`LogWriter::append`] refuses new bytes with the failure (the journal keeps those
|
||||
//! records queued, as for any failed append) and [`LogWriter::unwritten`] says how many records are
|
||||
//! held, so the app counts them as not saved and its quit prompt warns before anything could be
|
||||
//! lost. Cutting the log back, replacing it and reading it act on that logical content, after
|
||||
//! everything handed over before; the caller waits for them. Dropping the writer waits for
|
||||
//! everything handed over and tries a last time.
|
||||
//!
|
||||
//! **Every write asks the [`OpenedFolder`] first**, on this thread (a `stat` never makes the caller
|
||||
//! wait for the drive): when the log's path no longer leads to the folder the store opened (a share
|
||||
//! mounted over it, issue #3240) nothing is written. The bytes are held like those of any other
|
||||
//! write that failed, and written once the folder that was opened is back at the path.
|
||||
//!
|
||||
//! **Successful batches reopen the log by path.** A failed batch keeps its descriptor only to
|
||||
//! roll back its own bytes, never to append into a moved-away folder. A copy of the library's folder
|
||||
//! put at the path counts as the opened one (it holds the lock's note) and has a log of its own: a
|
||||
//! file kept open from before would go on writing into the folder that was moved away. A log that
|
||||
//! isn't as long as what this thread wrote (a fragment of its own failed write is cut first) is not
|
||||
//! the one it wrote, and appending to it would leave a gap: what it was handed is held like a failed
|
||||
//! write (reported; later appends are taken meanwhile, since retrying can't heal it), and the
|
||||
//! snapshot the app takes for held records, which holds every change, replaces the log.
|
||||
|
||||
use std::io::{self, Seek, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::opened_folder::OpenedFolder;
|
||||
|
||||
/// How long a caller waits for the thread at most (a cut, a replace, a read, a flush).
|
||||
const WAIT: Duration = Duration::from_secs(60);
|
||||
/// How often held bytes are retried while a failure stands and nothing else arrives.
|
||||
pub(crate) const RETRY: Duration = Duration::from_millis(500);
|
||||
|
||||
enum Msg {
|
||||
Append(Vec<u8>),
|
||||
Truncate(u64, Sender<io::Result<()>>),
|
||||
Replace(Vec<u8>, Sender<io::Result<()>>),
|
||||
Read(Sender<io::Result<Option<Vec<u8>>>>),
|
||||
/// Reply once everything before is written and synced (or why it isn't).
|
||||
Flush(Sender<io::Result<()>>),
|
||||
}
|
||||
|
||||
/// What the caller can see without waiting.
|
||||
#[derive(Default)]
|
||||
struct Shared {
|
||||
/// Why the held bytes couldn't be written (until they are, or the log is cut or replaced).
|
||||
failed: Option<String>,
|
||||
/// Records (lines) handed over and not yet written and synced, while `failed` stands.
|
||||
held_records: usize,
|
||||
/// The file isn't the log the thread wrote: only a replace helps, so appends are taken.
|
||||
foreign: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct LogWriter {
|
||||
pub(crate) name: String,
|
||||
tx: Option<Sender<Msg>>,
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
fn stopped() -> io::Error {
|
||||
io::Error::other("the catalog log writer stopped")
|
||||
}
|
||||
|
||||
fn not_written(why: &str) -> io::Error {
|
||||
io::Error::other(format!("the catalog log could not be written: {why}"))
|
||||
}
|
||||
|
||||
impl LogWriter {
|
||||
/// A writer for `name` in the folder (`None` when no thread can start: the store then writes itself).
|
||||
pub(crate) fn start(folder: OpenedFolder, name: &str, expected: Option<u64>) -> Option<LogWriter> {
|
||||
let (tx, rx) = channel::<Msg>();
|
||||
let shared = Arc::new(Mutex::new(Shared::default()));
|
||||
let sh = shared.clone();
|
||||
let mut w = Writer::new(folder, name);
|
||||
w.good = expected;
|
||||
let thread = std::thread::Builder::new().name("catalog-log".into()).spawn(move || w.run(&rx, &sh)).ok()?;
|
||||
Some(LogWriter { name: name.to_string(), tx: Some(tx), shared, thread: Some(thread) })
|
||||
}
|
||||
|
||||
fn send(&self, m: Msg) -> io::Result<()> {
|
||||
self.tx.as_ref().ok_or_else(stopped)?.send(m).map_err(|_| stopped())
|
||||
}
|
||||
|
||||
fn ask<T>(&self, make: impl FnOnce(Sender<io::Result<T>>) -> Msg) -> io::Result<T> {
|
||||
let (tx, rx) = channel();
|
||||
self.send(make(tx))?;
|
||||
rx.recv_timeout(WAIT).map_err(|e| match e {
|
||||
RecvTimeoutError::Timeout => io::Error::new(io::ErrorKind::TimedOut, "the drive took over a minute to write the catalog log"),
|
||||
RecvTimeoutError::Disconnected => stopped(),
|
||||
})?
|
||||
}
|
||||
|
||||
/// Hand `data` over (never waits for the drive). Refused while bytes handed over before can't
|
||||
/// be written: the caller keeps `data` and appends it again later.
|
||||
pub(crate) fn append(&self, data: &[u8]) -> io::Result<()> {
|
||||
let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(why) = sh.failed.as_deref().filter(|_| !sh.foreign) {
|
||||
return Err(not_written(why));
|
||||
}
|
||||
drop(sh);
|
||||
self.send(Msg::Append(data.to_vec()))
|
||||
}
|
||||
|
||||
/// Cut the log to `len` bytes, after everything handed over; waits for it.
|
||||
pub(crate) fn truncate(&self, len: u64) -> io::Result<()> {
|
||||
self.ask(|r| Msg::Truncate(len, r))
|
||||
}
|
||||
|
||||
/// Replace the log with `data` (atomically, durably), after everything handed over; waits.
|
||||
pub(crate) fn replace(&self, data: &[u8]) -> io::Result<()> {
|
||||
self.ask(|r| Msg::Replace(data.to_vec(), r))
|
||||
}
|
||||
|
||||
/// The log as appended so far (written or still held), after everything handed over.
|
||||
pub(crate) fn read(&self) -> io::Result<Option<Vec<u8>>> {
|
||||
self.ask(Msg::Read)
|
||||
}
|
||||
|
||||
/// Wait until everything handed over is written and synced; an error says why it isn't (the
|
||||
/// bytes are still held and retried).
|
||||
pub(crate) fn flush(&self) -> io::Result<()> {
|
||||
self.ask(Msg::Flush)
|
||||
}
|
||||
|
||||
/// Records handed over that can't be written yet, and why (`None`: nothing is held back by a
|
||||
/// failure). Never waits.
|
||||
pub(crate) fn unwritten(&self) -> Option<(usize, String)> {
|
||||
let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
sh.failed.clone().map(|why| (sh.held_records.max(1), why))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LogWriter {
|
||||
fn drop(&mut self) {
|
||||
drop(self.tx.take());
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread's side: how much of the file is written, and what is held for it.
|
||||
struct Writer {
|
||||
dir: PathBuf,
|
||||
path: PathBuf,
|
||||
tmp: PathBuf,
|
||||
/// The folder the store opened: asked before anything is written.
|
||||
folder: OpenedFolder,
|
||||
/// Bytes read by the journal or written whole and synced (`None` until first observed).
|
||||
good: Option<u64>,
|
||||
/// Handed over, not yet written and synced.
|
||||
held: Vec<u8>,
|
||||
failed: Option<String>,
|
||||
/// The exact file whose append failed; only this descriptor can have its torn bytes removed.
|
||||
torn: Option<std::fs::File>,
|
||||
/// The file isn't the log this thread wrote ([`Writer::open`]).
|
||||
foreign: bool,
|
||||
}
|
||||
|
||||
fn lines(b: &[u8]) -> usize {
|
||||
b.iter().filter(|c| **c == b'\n').count()
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
fn new(folder: OpenedFolder, name: &str) -> Writer {
|
||||
let dir = folder.path().to_path_buf();
|
||||
let path = dir.join(name);
|
||||
let tmp = dir.join(format!("{name}.tmp"));
|
||||
Writer { dir, path, tmp, folder, good: None, held: Vec::new(), failed: None, torn: None, foreign: false }
|
||||
}
|
||||
|
||||
fn hook(&self, step: crate::fault::Step) -> io::Result<()> {
|
||||
crate::fault::check(&self.dir, step)
|
||||
}
|
||||
|
||||
/// Open the file by its path, positioned at `good`, and say where that is. A fragment a failed
|
||||
/// write left past `good` is cut; any other length is not the log this thread wrote (a copy was
|
||||
/// put at the path, or it was changed): refused.
|
||||
fn open(&mut self) -> io::Result<(std::fs::File, u64)> {
|
||||
self.folder.check()?;
|
||||
if let Some(good) = self.good {
|
||||
crate::store::rollback_torn(&mut self.torn, good)?;
|
||||
}
|
||||
// (a link or a device planted at the name meanwhile is refused, as at the first append)
|
||||
crate::store::check_regular_directory_entry(&self.path)?;
|
||||
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(&self.path)?;
|
||||
let len = f.metadata()?.len();
|
||||
let good = match self.good {
|
||||
None => len,
|
||||
Some(g) if len == g => g,
|
||||
Some(g) => {
|
||||
self.foreign = true;
|
||||
return Err(io::Error::other(format!(
|
||||
"{} holds {len} bytes, the log this session wrote has {g}: it is another file, so nothing is appended to it and a snapshot replaces it",
|
||||
self.path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
f.seek(io::SeekFrom::Start(good))?;
|
||||
self.good = Some(good);
|
||||
self.foreign = false;
|
||||
Ok((f, good))
|
||||
}
|
||||
|
||||
/// Write and sync what is held; a failure leaves `good` as it was, and the retry cuts what was left past it.
|
||||
fn write_held(&mut self) -> io::Result<()> {
|
||||
if self.held.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.hook(crate::fault::Step::Write)?;
|
||||
let (mut f, good) = self.open()?;
|
||||
let written = f.write_all(&self.held).and_then(|()| self.hook(crate::fault::Step::Sync)).and_then(|()| f.sync_data());
|
||||
self.torn = written.is_err().then_some(f);
|
||||
written?;
|
||||
self.good = Some(good.saturating_add(self.held.len() as u64));
|
||||
self.held.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cut the logical log (file then held) to `len` bytes.
|
||||
fn truncate(&mut self, len: u64) -> io::Result<()> {
|
||||
let good = match self.good {
|
||||
Some(g) => g,
|
||||
None => match self.open() {
|
||||
Ok((_, g)) => g,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
};
|
||||
// (to exactly `good` with bytes held: the file is cut, since a write that failed may have
|
||||
// left some of them past `good`)
|
||||
if len > good || (len == good && self.held.is_empty()) {
|
||||
// within what is held: nothing on the drive changes (what a failed write left past
|
||||
// `good` is cut before the next write)
|
||||
let keep = usize::try_from(len - good).unwrap_or(usize::MAX).min(self.held.len());
|
||||
self.held.truncate(keep);
|
||||
return Ok(());
|
||||
}
|
||||
self.folder.check()?;
|
||||
crate::store::rollback_torn(&mut self.torn, good)?;
|
||||
crate::store::check_regular_directory_entry(&self.path)?;
|
||||
let f = std::fs::OpenOptions::new().write(true).open(&self.path)?;
|
||||
if f.metadata()?.len() != good {
|
||||
self.foreign = true;
|
||||
return Err(io::Error::other("the log changed before truncate: a snapshot must replace it"));
|
||||
}
|
||||
f.set_len(len)?;
|
||||
f.sync_all()?;
|
||||
self.good = Some(len);
|
||||
self.held.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn replace(&mut self, data: &[u8]) -> io::Result<()> {
|
||||
self.folder.check()?;
|
||||
self.hook(crate::fault::Step::Write)?;
|
||||
let mut file = crate::store::create_staging(&self.tmp)?;
|
||||
let written = (|| {
|
||||
file.write_all(data)?;
|
||||
self.hook(crate::fault::Step::Sync)?;
|
||||
file.sync_all()?;
|
||||
crate::store::check_staging(&self.folder, &self.tmp, &file)?;
|
||||
std::fs::rename(&self.tmp, &self.path)
|
||||
})();
|
||||
match written {
|
||||
Ok(()) => {
|
||||
// what was held is part of what the caller replaced the log with (a snapshot holds
|
||||
// the records before it, `data` the ones after)
|
||||
self.good = Some(data.len() as u64);
|
||||
self.held.clear();
|
||||
self.failed = None;
|
||||
self.torn = None;
|
||||
self.foreign = false;
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if crate::store::check_staging(&self.folder, &self.tmp, &file).is_ok() {
|
||||
let _ = std::fs::remove_file(&self.tmp);
|
||||
}
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read(&mut self) -> io::Result<Option<Vec<u8>>> {
|
||||
let mut bytes = match std::fs::read(&self.path) {
|
||||
Ok(b) => b,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound && self.held.is_empty() => return Ok(None),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if let Some(g) = self.good {
|
||||
bytes.truncate(usize::try_from(g).unwrap_or(usize::MAX));
|
||||
}
|
||||
bytes.extend_from_slice(&self.held);
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
fn publish(&self, shared: &Mutex<Shared>) {
|
||||
let mut sh = shared.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
sh.failed = self.failed.clone().filter(|_| !self.held.is_empty());
|
||||
sh.foreign = self.foreign && sh.failed.is_some();
|
||||
sh.held_records = if sh.failed.is_some() { lines(&self.held) } else { 0 };
|
||||
}
|
||||
|
||||
fn run(&mut self, rx: &Receiver<Msg>, shared: &Mutex<Shared>) {
|
||||
loop {
|
||||
let first = if self.failed.is_some() && !self.held.is_empty() {
|
||||
match rx.recv_timeout(RETRY) {
|
||||
Ok(m) => Some(m),
|
||||
Err(RecvTimeoutError::Timeout) => None,
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
} else {
|
||||
match rx.recv() {
|
||||
Ok(m) => Some(m),
|
||||
Err(_) => break,
|
||||
}
|
||||
};
|
||||
let mut batch: Vec<Msg> = first.into_iter().collect();
|
||||
while let Ok(m) = rx.try_recv() {
|
||||
batch.push(m);
|
||||
}
|
||||
let mut flushes = Vec::new();
|
||||
for m in batch {
|
||||
match m {
|
||||
Msg::Append(data) => self.held.extend_from_slice(&data),
|
||||
// (published before the reply: the caller reads what it left at once)
|
||||
Msg::Truncate(len, reply) => {
|
||||
let r = self.truncate(len);
|
||||
self.publish(shared);
|
||||
let _ = reply.send(r);
|
||||
}
|
||||
Msg::Replace(data, reply) => {
|
||||
let r = self.replace(&data);
|
||||
self.publish(shared);
|
||||
let _ = reply.send(r);
|
||||
}
|
||||
Msg::Read(reply) => {
|
||||
let _ = reply.send(self.read());
|
||||
}
|
||||
Msg::Flush(reply) => flushes.push(reply),
|
||||
}
|
||||
}
|
||||
self.step();
|
||||
self.publish(shared);
|
||||
for r in flushes {
|
||||
let _ = r.send(match &self.failed {
|
||||
Some(why) if !self.held.is_empty() => Err(not_written(why)),
|
||||
_ => Ok(()),
|
||||
});
|
||||
}
|
||||
}
|
||||
// the store is closing: everything handed over gets one more try
|
||||
self.step();
|
||||
self.publish(shared);
|
||||
if !self.held.is_empty() {
|
||||
log::error!("catalog: {} record(s) could not be written to {} (the closing snapshot holds them)", lines(&self.held), self.path.display());
|
||||
}
|
||||
}
|
||||
|
||||
/// Write what is held; a failure is kept (and logged when it is new).
|
||||
fn step(&mut self) {
|
||||
match self.write_held() {
|
||||
Ok(()) => {
|
||||
if self.failed.take().is_some() {
|
||||
log::info!("catalog: {} written again", self.path.display());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let why = e.to_string();
|
||||
if self.failed.as_deref() != Some(why.as_str()) {
|
||||
log::error!("catalog: {}: {why} ({} record(s) held, retried)", self.path.display(), lines(&self.held));
|
||||
}
|
||||
self.failed = Some(why);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+86
-10
@@ -171,11 +171,32 @@ 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>,
|
||||
/// Shutter speed for display, from [`lightcraft_meta::format_exposure_time`] (`1/3`, `0.3571`, `2.5`).
|
||||
pub shutter: String,
|
||||
/// The file's exact exposure time in seconds, kept beside the rounded `shutter` text so export
|
||||
/// writes the original duration; read through [`Meta::shutter_seconds`]. Left out of the catalog
|
||||
/// JSON when unknown, so older catalogs read unchanged.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub exposure_time: Option<f64>,
|
||||
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,
|
||||
@@ -209,6 +230,16 @@ pub struct Meta {
|
||||
pub focus: Option<lightcraft_meta::FocusPoint>,
|
||||
}
|
||||
|
||||
impl Meta {
|
||||
/// Shutter speed in seconds: the exact [`Meta::exposure_time`] while `shutter` still shows it,
|
||||
/// otherwise whatever `shutter` says (set by hand, or a catalog from before the exact time was kept).
|
||||
pub fn shutter_seconds(&self) -> Option<f64> {
|
||||
self.exposure_time
|
||||
.filter(|t| lightcraft_meta::format_exposure_time(*t).is_some_and(|text| text == self.shutter.trim()))
|
||||
.or_else(|| parse_shutter_seconds(&self.shutter))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Version {
|
||||
pub name: String,
|
||||
@@ -304,10 +335,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
|
||||
@@ -335,7 +366,9 @@ pub struct Analysis {
|
||||
/// file's white balance is edited relative to its as-shot look or in Kelvin depends on the camera:
|
||||
/// [`relative_wb_camera`].
|
||||
pub fn relative_wb_format(format: &str) -> bool {
|
||||
["ARW", "NEF", "NRW", "RW2", "RWL", "RAW", "RAF", "CR3", "CR2", "PEF", "SRW", "ORF", "ERF", "MRW"].iter().any(|f| format.eq_ignore_ascii_case(f))
|
||||
["ARW", "NEF", "NRW", "RW2", "RWL", "RAW", "RAF", "CR3", "CR2", "PEF", "SRW", "ORF", "ERF", "MRW", "CRW"]
|
||||
.iter()
|
||||
.any(|f| format.eq_ignore_ascii_case(f))
|
||||
}
|
||||
|
||||
/// Whether a raw of `format` shot on `camera` (Exif make and model, as [`Meta::camera`] keeps them) is developed
|
||||
@@ -415,13 +448,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`]).
|
||||
@@ -440,6 +478,23 @@ impl Photo {
|
||||
pub fn relative_wb(&self) -> bool {
|
||||
self.develops_raw() && relative_wb_camera(&self.format, &self.meta.camera)
|
||||
}
|
||||
/// Every settings holder of this photo that can carry segmentation grids: the develop
|
||||
/// settings, the versions', the history steps' and the import look. A snapshot's shared grid
|
||||
/// table ([`crate::Catalog`]'s `grids`) covers all of them, so a new holder belongs here.
|
||||
pub(crate) fn settings_holders(&self) -> impl Iterator<Item = &Arc<DevelopSettings>> {
|
||||
std::iter::once(&self.develop)
|
||||
.chain(self.versions.iter().map(|v| &v.settings))
|
||||
.chain(self.history.iter().map(|h| &h.settings))
|
||||
.chain(self.import_look.iter())
|
||||
}
|
||||
/// [`Photo::settings_holders`] with mutable access (resolving a snapshot's grid references).
|
||||
pub(crate) fn settings_holders_mut(&mut self) -> impl Iterator<Item = &mut Arc<DevelopSettings>> {
|
||||
let Photo { develop, versions, history, import_look, .. } = self;
|
||||
std::iter::once(develop)
|
||||
.chain(versions.iter_mut().map(|v| &mut v.settings))
|
||||
.chain(history.iter_mut().map(|h| &mut h.settings))
|
||||
.chain(import_look.as_mut())
|
||||
}
|
||||
/// The develop settings import gave this photo: [`Photo::camera_defaults`], or the user's
|
||||
/// default preset applied on top of them ([`Photo::import_look`]). Like the camera defaults,
|
||||
/// in the photo's own rendering process.
|
||||
@@ -725,7 +780,28 @@ mod edited_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod shutter_tests {
|
||||
use super::parse_shutter_seconds;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shutter_seconds_prefers_the_exact_time_while_the_text_still_shows_it() {
|
||||
let mut m = Meta { shutter: "0.3571".into(), exposure_time: Some(1.0 / 2.8), ..Default::default() };
|
||||
assert_eq!(m.shutter_seconds(), Some(1.0 / 2.8));
|
||||
m.shutter = "1/3".into();
|
||||
m.exposure_time = Some(1.0 / 3.0);
|
||||
assert_eq!(m.shutter_seconds(), Some(1.0 / 3.0));
|
||||
// the text no longer matches the stored time (edited elsewhere): the text wins
|
||||
m.shutter = "1/250".into();
|
||||
assert_eq!(m.shutter_seconds(), Some(1.0 / 250.0));
|
||||
// an older catalog without the exact time
|
||||
m.exposure_time = None;
|
||||
m.shutter = "2.5".into();
|
||||
assert_eq!(m.shutter_seconds(), Some(2.5));
|
||||
// the exact time stays out of the JSON when unknown, and round-trips when known
|
||||
assert!(!serde_json::to_string(&m).unwrap().contains("exposure_time"));
|
||||
m.exposure_time = Some(2.5);
|
||||
let back: Meta = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap();
|
||||
assert_eq!(back.exposure_time, Some(2.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fraction_needs_a_positive_numerator_and_denominator() {
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
//! The folder a library was opened from, and whether its path still leads to it (issue #3240).
|
||||
//!
|
||||
//! A library's files are written by path (`<library>/catalog.snap`, …), and a path can come to lead
|
||||
//! somewhere else while the library is open: a share mounted over the folder, or the folder moved
|
||||
//! away and another one put at its path. A session that went on writing then replaced the catalog
|
||||
//! of the library on the share with its own.
|
||||
//!
|
||||
//! [`OpenedFolder`] remembers which folder the path named when the library was opened;
|
||||
//! [`OpenedFolder::check`] asks, with one `stat`, whether it still does. Every write of a library
|
||||
//! file asks first ([`crate::FsStore`], its log thread, [`crate::LibraryLock`]) and is refused,
|
||||
//! writing nothing, when the answer is no. The refusal is an ordinary write error, so the changes
|
||||
//! stay queued and the app says why they aren't saved. The next write asks again: with the folder
|
||||
//! that was opened back at the path, saving goes on.
|
||||
//!
|
||||
//! - **Unix:** a folder is its device and inode number. A volume that is mounted again (a drive
|
||||
//! plugged in again, a share reconnected) gets another device number: its folder counts as the
|
||||
//! same when its inode number and its creation time agree (without one: the note below), so
|
||||
//! saving goes on there as it did before this check. A clone of the volume, with the same inode
|
||||
//! numbers and creation times, counts as that volume mounted again: nothing the check can see
|
||||
//! tells them apart. A folder moved away keeps its own inode number; one deleted and made again
|
||||
//! may be given the same inode number back, so on the same device two creation times that are
|
||||
//! both known must agree too.
|
||||
//! - **The note of the lock:** some file systems number a folder anew each time they are mounted
|
||||
//! (FAT and exFAT on Linux, sshfs, cifs without server inode numbers) and some keep no creation
|
||||
//! time to go by (NFS). A folder that holds exactly the owner note this session's lock wrote
|
||||
//! ([`OpenedFolder::vouch`]) is the opened folder whatever its numbers say: the note holds a
|
||||
//! value found in no other lock's note, so no other library has it. A copy of this library's
|
||||
//! folder made while it was open does, and counts as the library (the log in it is checked when
|
||||
//! it is written to: [`crate::FsStore`]); a share mounted over the folder, with a library of its
|
||||
//! own or none, never does.
|
||||
//! - **Windows:** `std` offers the volume serial number and the file index only on nightly
|
||||
//! (`windows_by_handle`, rust-lang/rust#63010), so there is no identity to compare yet. The check
|
||||
//! only asks that the path is still a folder, and a share mounted over a folder isn't noticed.
|
||||
//! - A check is not a lock: a folder replaced between the `stat` and the write that follows it is
|
||||
//! still written to. Closing that window takes I/O relative to an open directory handle
|
||||
//! (`openat`, `renameat`), which the library doesn't use.
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// Which folder a path named: the device and the inode number the system reports for it, and when
|
||||
/// the folder was made where the file system keeps that.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
struct FolderId {
|
||||
dev: u64,
|
||||
ino: u64,
|
||||
born: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl FolderId {
|
||||
#[cfg(unix)]
|
||||
fn of(folder: &std::fs::Metadata) -> Option<FolderId> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
Some(FolderId { dev: folder.dev(), ino: folder.ino(), born: made_at(folder.created()) })
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn of(_: &std::fs::Metadata) -> Option<FolderId> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `other` is the same folder: the same inode number, and then, where both creation
|
||||
/// times are known, the same creation time, else the same device number. A volume that is mounted
|
||||
/// again gets another device number, and saving went on there before there was a check; two
|
||||
/// creation times that differ are two folders, also on one device (an inode number is given
|
||||
/// again to a folder made later). Without both times another device is another folder: a
|
||||
/// refused save is better than a write into another volume's folder with that inode number.
|
||||
fn is(&self, other: &FolderId) -> bool {
|
||||
self.ino == other.ino
|
||||
&& match (self.born, other.born) {
|
||||
(Some(was), Some(now)) => was == now,
|
||||
_ => self.dev == other.dev,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When a folder was made, where the file system says. macOS reports 0 (the Unix epoch) for a file
|
||||
/// system that keeps no creation time (NFS, macFUSE): the same for every folder there, so no folder
|
||||
/// is told from another by it.
|
||||
#[cfg(unix)]
|
||||
fn made_at(created: io::Result<SystemTime>) -> Option<SystemTime> {
|
||||
created.ok().filter(|t| *t != SystemTime::UNIX_EPOCH)
|
||||
}
|
||||
|
||||
/// The folder a library was opened from (see the module docs). Clones share one record, so the
|
||||
/// stores, the log's thread and the lock of a library all ask about the same folder.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OpenedFolder {
|
||||
inner: Arc<Inner>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
path: PathBuf,
|
||||
/// `None` where the system gives a folder no identity (Windows, for now).
|
||||
id: Option<FolderId>,
|
||||
/// The last check refused: a change is logged when it starts and when it ends, not at every write.
|
||||
refused: AtomicBool,
|
||||
/// The owner note this session's lock wrote into the folder (see [`OpenedFolder::vouch`]); set once.
|
||||
note: OnceLock<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl OpenedFolder {
|
||||
/// The folder `path` names now (a link is followed). Fails when it names no folder.
|
||||
pub fn at(path: &Path) -> io::Result<OpenedFolder> {
|
||||
let folder = std::fs::metadata(path)?;
|
||||
if !folder.is_dir() {
|
||||
return Err(io::Error::other(format!("{} is not a folder", path.display())));
|
||||
}
|
||||
Ok(OpenedFolder::new(path, FolderId::of(&folder)))
|
||||
}
|
||||
|
||||
fn new(path: &Path, id: Option<FolderId>) -> OpenedFolder {
|
||||
OpenedFolder { inner: Arc::new(Inner { path: path.to_path_buf(), id, refused: AtomicBool::new(false), note: OnceLock::new() }) }
|
||||
}
|
||||
|
||||
/// The path the folder was opened by.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.inner.path
|
||||
}
|
||||
|
||||
/// `other` was recorded for the same folder (always, where folders have no identity). A folder
|
||||
/// that holds the note this session's lock wrote is the same whatever its numbers say
|
||||
/// ([`OpenedFolder::vouch`]): the library opened again after a drive was mounted again keeps its lock.
|
||||
pub fn same_folder(&self, other: &OpenedFolder) -> bool {
|
||||
match (self.inner.id, other.inner.id) {
|
||||
(Some(a), Some(b)) => a.is(&b) || self.holds_note(other.path()),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the owner note this session's lock wrote into the folder ([`crate::LibraryLock`]); the
|
||||
/// first one is kept. From then on a folder at the path that holds exactly these bytes is the
|
||||
/// opened folder even when its numbers say otherwise: some file systems number a folder anew at
|
||||
/// every mount (FAT and exFAT on Linux, sshfs), so a drive plugged in again would be refused for
|
||||
/// the rest of the session. The bytes are this lock's alone (the process, the program, the time
|
||||
/// it was taken and a value found in no other note): another library's folder doesn't have them
|
||||
/// (issue #3240), only a copy of this one made while it was open, which counts as it.
|
||||
pub fn vouch(&self, note: &[u8]) {
|
||||
let _ = self.inner.note.set(note.to_vec());
|
||||
}
|
||||
|
||||
/// The note [`OpenedFolder::vouch`] recorded (`None`: none was, the numbers decide alone).
|
||||
pub fn note(&self) -> Option<&[u8]> {
|
||||
self.inner.note.get().map(Vec::as_slice)
|
||||
}
|
||||
|
||||
/// `Ok` while the path leads to the folder that was opened (or to one that holds this session's
|
||||
/// note: [`OpenedFolder::vouch`]); else an error that says what is there now and what to do.
|
||||
pub fn check(&self) -> io::Result<()> {
|
||||
let inner = &*self.inner;
|
||||
let now = match std::fs::metadata(&inner.path) {
|
||||
Ok(now) => now,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(self.refuse("nothing is there now")),
|
||||
// The drive doesn't answer: the write would fail the same way, with less to go on.
|
||||
Err(e) => {
|
||||
let what = format!("can't tell whether {} is still the folder this library was opened from: {e}", inner.path.display());
|
||||
return Err(io::Error::new(e.kind(), what));
|
||||
}
|
||||
};
|
||||
if !now.is_dir() {
|
||||
return Err(self.refuse("it isn't a folder now"));
|
||||
}
|
||||
if let (Some(was), Some(is)) = (inner.id, FolderId::of(&now))
|
||||
&& !was.is(&is)
|
||||
&& !self.holds_note(&inner.path)
|
||||
{
|
||||
// (the same device number is the same volume's: another folder on it was put at the path)
|
||||
return Err(self.refuse(if was.dev == is.dev { "it was moved or replaced" } else { "a different drive or share is there now" }));
|
||||
}
|
||||
if inner.refused.swap(false, Ordering::Relaxed) {
|
||||
log::info!("library folder {}: the folder this library was opened from is back", inner.path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error for a path that doesn't lead to the opened folder, `what` being what is there.
|
||||
fn refuse(&self, what: &str) -> io::Error {
|
||||
let path = self.inner.path.display();
|
||||
let why = format!(
|
||||
"{path} is no longer the folder this library was opened from ({what}), so nothing is written to it: put the original folder back"
|
||||
);
|
||||
if !self.inner.refused.swap(true, Ordering::Relaxed) {
|
||||
log::warn!("library folder {why}");
|
||||
}
|
||||
io::Error::other(why)
|
||||
}
|
||||
|
||||
/// Whether the folder at `dir` holds the note this session's lock wrote ([`OpenedFolder::vouch`]).
|
||||
fn holds_note(&self, dir: &Path) -> bool {
|
||||
self.note().is_some_and(|ours| holds_exactly(&dir.join(crate::lock::OWNER), ours))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is a plain file that holds exactly `bytes`. A link, a folder or a file of another
|
||||
/// size is no match and is not read (a pipe would block, a large file would be read for nothing).
|
||||
pub(crate) fn holds_exactly(path: &Path, bytes: &[u8]) -> bool {
|
||||
let plain = std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file() && m.len() == bytes.len() as u64);
|
||||
plain && std::fs::read(path).is_ok_and(|now| now == bytes)
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
impl OpenedFolder {
|
||||
/// `path` as a volume that numbers its folders anew at every mount would have recorded it: other
|
||||
/// device and inode numbers than the folder has now, and no creation time (a mount can't be
|
||||
/// faked in a test).
|
||||
pub(crate) fn recorded_under_other_numbers(path: &Path) -> OpenedFolder {
|
||||
let now = std::fs::metadata(path).ok().and_then(|m| FolderId::of(&m));
|
||||
OpenedFolder::new(path, now.map(|n| FolderId { dev: n.dev.wrapping_add(1), ino: n.ino.wrapping_add(1), born: None }))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn scratch(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("lc-opened-folder-unit-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn id(dev: u64, ino: u64, born: Option<u64>) -> FolderId {
|
||||
FolderId { dev, ino, born: born.map(|s| SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(s)) }
|
||||
}
|
||||
|
||||
/// A folder is the same one when its inode number agrees and then its device number does or, where
|
||||
/// both creation times are known, its creation time: a volume that is mounted again has another
|
||||
/// device number, and an inode number is given again to a folder made later. Anything less sure
|
||||
/// is another folder.
|
||||
#[test]
|
||||
fn a_folder_on_a_volume_mounted_again_is_the_same_folder_only_when_it_was_made_at_the_same_time() {
|
||||
let was = id(7, 100, Some(1_000));
|
||||
assert!(was.is(&id(7, 100, Some(1_000))), "the same");
|
||||
assert!(!was.is(&id(7, 100, Some(2_000))), "the inode number of a folder that is gone, given to one made later");
|
||||
assert!(was.is(&id(9, 100, Some(1_000))), "mounted again under another device number");
|
||||
assert!(!was.is(&id(9, 100, Some(2_000))), "another volume's folder that has that inode number");
|
||||
assert!(!was.is(&id(9, 100, None)), "no creation time to tell by");
|
||||
assert!(!id(7, 100, None).is(&id(9, 100, None)), "none known at all");
|
||||
assert!(id(7, 100, None).is(&id(7, 100, None)), "the same device, and none to tell by");
|
||||
assert!(id(7, 100, None).is(&id(7, 100, Some(1_000))), "a creation time known for one folder only is no reason to refuse");
|
||||
assert!(!was.is(&id(7, 101, Some(1_000))), "another folder on the volume");
|
||||
assert!(!was.is(&id(9, 101, Some(1_000))), "another folder on another volume");
|
||||
}
|
||||
|
||||
/// The same rule in a check, with the device number recorded at open made different from the
|
||||
/// one reported now (a mount can't be faked in a test).
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_check_accepts_a_remounted_volume_and_refuses_another_volumes_folder() {
|
||||
let dir = scratch("remount");
|
||||
let real = FolderId::of(&std::fs::metadata(&dir).unwrap()).unwrap();
|
||||
let recorded = |id: FolderId| OpenedFolder::new(&dir, Some(id));
|
||||
|
||||
let remounted = recorded(FolderId { dev: real.dev.wrapping_add(1), ..real });
|
||||
match real.born {
|
||||
Some(_) => remounted.check().expect("the same inode number and creation time: the same folder, mounted again"),
|
||||
None => assert!(remounted.check().is_err(), "no creation time to tell by: refused"),
|
||||
}
|
||||
let other = recorded(FolderId { dev: real.dev.wrapping_add(1), ino: real.ino.wrapping_add(1), ..real });
|
||||
let msg = other.check().expect_err("another volume's folder").to_string();
|
||||
assert!(msg.contains("a different drive or share is there now"), "{msg}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The same rule in a check, with the creation time recorded at open made different from the one
|
||||
/// reported now (a folder made again under the inode number of one that was deleted can't be
|
||||
/// arranged in a test): the same device and inode number with another creation time is another
|
||||
/// folder, unless it holds the note this session's lock wrote.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_folder_made_again_under_the_same_inode_number_is_another_folder_unless_it_holds_the_note() {
|
||||
let dir = scratch("made-again");
|
||||
let real = FolderId::of(&std::fs::metadata(&dir).unwrap()).unwrap();
|
||||
let Some(born) = real.born else {
|
||||
OpenedFolder::new(&dir, Some(real)).check().expect("no creation time to tell by: the numbers decide");
|
||||
return;
|
||||
};
|
||||
let earlier = OpenedFolder::new(&dir, Some(FolderId { born: Some(born + std::time::Duration::from_secs(3600)), ..real }));
|
||||
let msg = earlier.check().expect_err("the same numbers, made at another time").to_string();
|
||||
assert!(msg.contains("it was moved or replaced"), "{msg}");
|
||||
assert!(!earlier.same_folder(&OpenedFolder::at(&dir).unwrap()), "not the folder that lock was taken in");
|
||||
|
||||
let note = b"the note of the lock";
|
||||
earlier.vouch(note);
|
||||
std::fs::write(dir.join(crate::lock::OWNER), note).unwrap();
|
||||
earlier.check().expect("this session's note: the folder it locked, whatever its numbers say");
|
||||
assert!(earlier.same_folder(&OpenedFolder::at(&dir).unwrap()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// macOS reports a creation time of 0 for a file system that keeps none (NFS, macFUSE), the same
|
||||
/// for every folder on it: that is no creation time, or any two such folders that have an inode
|
||||
/// number in common would be taken for one folder mounted again.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_creation_time_of_zero_is_no_creation_time() {
|
||||
let made = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
|
||||
assert_eq!(made_at(Ok(made)), Some(made));
|
||||
assert_eq!(made_at(Ok(SystemTime::UNIX_EPOCH)), None);
|
||||
assert_eq!(made_at(Err(io::Error::other("this file system keeps none"))), None);
|
||||
}
|
||||
|
||||
/// A file system that numbers its folders anew at every mount (FAT and exFAT on Linux, sshfs)
|
||||
/// gives a folder that was opened other numbers: it is that folder when it holds the note this
|
||||
/// session's lock wrote, and no other folder is. (A mount can't be faked in a test: the numbers
|
||||
/// recorded at open are made different from the folder's.)
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_folder_with_other_numbers_is_the_opened_one_only_while_it_holds_the_note_the_lock_wrote() {
|
||||
let dir = scratch("note");
|
||||
let note = br#"{"pid":4242,"host":"here","program":"LightCraft","version":"0.2.0","since":1}"#;
|
||||
let renumbered = OpenedFolder::recorded_under_other_numbers(&dir);
|
||||
let msg = renumbered.check().expect_err("other numbers, and no note vouched for").to_string();
|
||||
assert!(msg.contains("a different drive or share is there now"), "{msg}");
|
||||
|
||||
renumbered.vouch(note);
|
||||
assert_eq!(renumbered.note(), Some(note.as_slice()));
|
||||
let path = dir.join(crate::lock::OWNER);
|
||||
assert!(renumbered.check().is_err(), "the note is vouched for, the folder holds none");
|
||||
let longer = [note.as_slice(), b" ".as_slice()].concat();
|
||||
for other in [note.to_ascii_uppercase(), longer, note[1..].to_vec(), Vec::new()] {
|
||||
std::fs::write(&path, &other).unwrap();
|
||||
assert!(renumbered.check().is_err(), "another note: {}", String::from_utf8_lossy(&other));
|
||||
}
|
||||
std::fs::write(&path, note).unwrap();
|
||||
renumbered.check().expect("this session's note: the folder it locked, whatever its numbers say");
|
||||
|
||||
// what is no note: a link to one, a folder
|
||||
let elsewhere = dir.join("elsewhere");
|
||||
std::fs::rename(&path, &elsewhere).unwrap();
|
||||
std::os::unix::fs::symlink(&elsewhere, &path).unwrap();
|
||||
assert!(renumbered.check().is_err(), "a link to the bytes is no note");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
assert!(renumbered.check().is_err(), "a folder is no note");
|
||||
|
||||
// the first note is the one that counts
|
||||
renumbered.vouch(b"another");
|
||||
assert_eq!(renumbered.note(), Some(note.as_slice()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The lock is handed over to a library opened again from the same folder, and a folder that
|
||||
/// holds the note this session's lock wrote is that folder whatever its numbers say (a drive
|
||||
/// that was mounted again): not one with no such note.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_folder_that_holds_the_locks_note_is_the_same_folder_for_the_hand_over() {
|
||||
let dir = scratch("hand-over");
|
||||
let other = scratch("hand-over-other");
|
||||
let note = b"the note of the lock";
|
||||
let at_open = OpenedFolder::recorded_under_other_numbers(&dir);
|
||||
let now = OpenedFolder::at(&dir).unwrap();
|
||||
assert!(!at_open.same_folder(&now), "other numbers, no note");
|
||||
|
||||
at_open.vouch(note);
|
||||
assert!(!at_open.same_folder(&now), "the note is vouched for, the folder holds none");
|
||||
std::fs::write(dir.join(crate::lock::OWNER), note).unwrap();
|
||||
assert!(at_open.same_folder(&now));
|
||||
assert!(!at_open.same_folder(&OpenedFolder::at(&other).unwrap()), "another folder holds no such note");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_dir_all(&other);
|
||||
}
|
||||
}
|
||||
@@ -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"]),
|
||||
@@ -1097,8 +1100,13 @@ impl Rule {
|
||||
"captureDate" => date_op(op, p.captured.as_deref(), value),
|
||||
"importDate" => date_op(op, Some(&p.imported), value),
|
||||
"editDate" => date_op(op, p.edited.as_deref(), value),
|
||||
// (the shown shutter text, not the exact time kept for export: a rule matches the value the
|
||||
// photo shows, `1/3` or `0.3571`, at every op, including `is` and the edges of a range)
|
||||
"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 +1154,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.
|
||||
@@ -774,3 +795,19 @@ fn file_path_contains_finds_every_piece_of_a_long_path() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutter_speed_rules_match_the_shown_value() {
|
||||
let cat = Catalog::new();
|
||||
let mut p = photo(1);
|
||||
let m =
|
||||
|p: &Photo, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": "shutterSpeed", "op": op, "value": value}]})).matches(p, &cat);
|
||||
p.meta.exposure_time = Some(1.0 / 2.8);
|
||||
p.meta.shutter = "0.3571".into();
|
||||
assert!(m(&p, "is", json!("0.3571")) && !m(&p, "isNot", json!("0.3571")), "1/2.8 s is the 0.3571 it shows");
|
||||
assert!(m(&p, "lte", json!("0.3571")) && m(&p, "gte", json!("0.3571")));
|
||||
p.meta.exposure_time = Some(3333.0 / 10000.0);
|
||||
p.meta.shutter = "1/3".into();
|
||||
assert!(m(&p, "is", json!("1/3")) && !m(&p, "isNot", json!("1/3")), "3333/10000 s is the 1/3 it shows");
|
||||
assert!(m(&p, "gte", json!("1/3")) && m(&p, "lte", json!("1/3")) && !m(&p, "lt", json!("1/3")));
|
||||
}
|
||||
@@ -260,7 +260,7 @@ impl Catalog {
|
||||
.filter(|p| !p.deleted && !merged(p))
|
||||
.filter_map(|p| {
|
||||
let t = iso_seconds(p.captured.as_deref()?)?;
|
||||
let s = crate::model::parse_shutter_seconds(&p.meta.shutter)?;
|
||||
let s = p.meta.shutter_seconds()?;
|
||||
let n = p.meta.aperture.filter(|n| n.is_finite() && *n > 0.0).unwrap_or(1.0) as f64;
|
||||
let iso = p.meta.iso.filter(|i| *i > 0).unwrap_or(100) as f64;
|
||||
Some((t, p.file_name.as_str(), p.id, s, (s * iso / (n * n)).log2()))
|
||||
|
||||
+253
-43
@@ -2,13 +2,16 @@
|
||||
//!
|
||||
//! [`FsStore`] is the native implementation (a library directory); [`MemStore`] keeps files in
|
||||
//! memory (tests, ephemeral sessions) and lets tests simulate crashes by editing the bytes. A web
|
||||
//! host can implement [`Store`] over OPFS.
|
||||
//! host can implement [`Store`] over OPFS. [`FsStore`] writes only while its directory still leads
|
||||
//! to the folder it opened ([`crate::OpenedFolder`], issue #3240).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::opened_folder::OpenedFolder;
|
||||
|
||||
/// A flat namespace of named files with the few operations the journal needs.
|
||||
pub trait Store: Send {
|
||||
/// The whole file, or `None` if it doesn't exist.
|
||||
@@ -28,7 +31,9 @@ pub trait Store: Send {
|
||||
self.write_atomic(name, &buf)?;
|
||||
Ok(buf.len() as u64)
|
||||
}
|
||||
/// Append and make durable (fsync) before returning. On an error, part of `data` may have
|
||||
/// Append and make durable (fsync): before returning, or, natively, by the store's own log
|
||||
/// thread right after ([`FsStore`]: a write that fails is returned by a later append, and a
|
||||
/// read through the store sees every byte handed over). On an error, part of `data` may have
|
||||
/// been written (a full disk, a dropped network share): the journal cuts the file back to its
|
||||
/// previous length with [`Store::truncate`] before appending again.
|
||||
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()>;
|
||||
@@ -43,12 +48,23 @@ pub trait Store: Send {
|
||||
fn background_writer(&self) -> Option<Box<dyn Store>> {
|
||||
None
|
||||
}
|
||||
/// Wait until every append handed over is in the file and synced ([`FsStore`] writes them on a
|
||||
/// thread of its own; the default has nothing to wait for). An error says why some aren't: they
|
||||
/// are still held and retried, never dropped.
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
/// Records handed over by [`Store::append`] that can't be written yet (a write or sync on the
|
||||
/// store's own thread failed: they are held and retried), and why. `None`: nothing held back.
|
||||
fn unwritten(&self) -> Option<(usize, String)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends and truncates open the name's own file, so anything else at the name is the library's
|
||||
/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device
|
||||
/// hangs the open. Refused with an error the open can show, before anything is written through.
|
||||
fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
|
||||
pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(md) if md.is_file() => Ok(()),
|
||||
Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))),
|
||||
@@ -57,18 +73,73 @@ fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The synchronous fallback's acknowledged log length. Failed records stay with the caller;
|
||||
/// `Journal::append` requests a snapshot on an error rather than acknowledging a sequence gap.
|
||||
struct SynchronousLog {
|
||||
good: u64,
|
||||
torn: Option<std::fs::File>,
|
||||
}
|
||||
|
||||
fn check_log_len(len: u64, good: u64) -> io::Result<()> {
|
||||
if len == good {
|
||||
return Ok(());
|
||||
}
|
||||
Err(io::Error::other(format!(
|
||||
"catalog log holds {len} bytes, the log this session read or wrote has {good}: it is another file, so a snapshot must replace it"
|
||||
)))
|
||||
}
|
||||
|
||||
/// Roll back only the descriptor whose append failed, never a new file at its old path.
|
||||
pub(crate) fn rollback_torn(file: &mut Option<std::fs::File>, good: u64) -> io::Result<()> {
|
||||
if let Some(f) = file.as_ref() {
|
||||
if f.metadata()?.len() < good {
|
||||
return Err(io::Error::other("the failed log was shortened: a snapshot must replace it"));
|
||||
}
|
||||
f.set_len(good)?;
|
||||
f.sync_data()?;
|
||||
*file = None;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Files in a directory.
|
||||
pub struct FsStore {
|
||||
dir: PathBuf,
|
||||
/// Open append handle (kept between appends; dropped on rewrite/truncate).
|
||||
appender: Option<(String, std::fs::File)>,
|
||||
/// The folder `dir` named when the store was opened. Every write asks it first and is refused
|
||||
/// when `dir` leads somewhere else now (issue #3240); so does the log's thread.
|
||||
folder: OpenedFolder,
|
||||
/// Set only after using the synchronous fallback; do not switch to a fresh thread afterward
|
||||
/// and forget which records that fallback acknowledged.
|
||||
sync_log: Option<SynchronousLog>,
|
||||
/// Length of the log the journal read, retained through the first asynchronous or caller append.
|
||||
known_log_len: Option<u64>,
|
||||
/// The thread that writes the log (natively; started by the first append).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
log: Option<crate::log_writer::LogWriter>,
|
||||
}
|
||||
|
||||
impl FsStore {
|
||||
/// Use `dir` (created if missing).
|
||||
/// Use `dir` (created if missing). The store writes to the folder `dir` names now, and only
|
||||
/// while it still does.
|
||||
pub fn open(dir: impl AsRef<Path>) -> io::Result<FsStore> {
|
||||
std::fs::create_dir_all(dir.as_ref())?;
|
||||
Ok(FsStore { dir: dir.as_ref().to_path_buf(), appender: None })
|
||||
Ok(FsStore::in_folder(OpenedFolder::at(dir.as_ref())?))
|
||||
}
|
||||
/// A store in a folder that was recorded already, so that the stores, the lock and the caches
|
||||
/// of one library ask about the same folder.
|
||||
pub fn in_folder(folder: OpenedFolder) -> FsStore {
|
||||
FsStore {
|
||||
dir: folder.path().to_path_buf(),
|
||||
folder,
|
||||
sync_log: None,
|
||||
known_log_len: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
log: None,
|
||||
}
|
||||
}
|
||||
/// The folder the store opened.
|
||||
pub fn folder(&self) -> &OpenedFolder {
|
||||
&self.folder
|
||||
}
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
@@ -76,6 +147,30 @@ impl FsStore {
|
||||
fn path(&self, name: &str) -> PathBuf {
|
||||
self.dir.join(name)
|
||||
}
|
||||
/// The log thread, when it writes `name`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn log_for(&self, name: &str) -> Option<&crate::log_writer::LogWriter> {
|
||||
self.log.as_ref().filter(|w| w.name == name)
|
||||
}
|
||||
|
||||
/// Wait until the log thread has written and synced everything handed to it.
|
||||
pub fn flush_log(&self) -> io::Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = &self.log {
|
||||
return w.flush();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reset_sync_log(&mut self, name: &str, len: u64) {
|
||||
if name == crate::journal::LOG {
|
||||
self.known_log_len = Some(len);
|
||||
if self.sync_log.is_some() {
|
||||
self.sync_log = Some(SynchronousLog { good: len, torn: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_dir(&self) {
|
||||
// Makes the rename durable on POSIX; opening a directory fails on Windows (where
|
||||
// `rename` is already journaled by NTFS), so errors are ignored.
|
||||
@@ -95,82 +190,179 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result<std::fs::File>
|
||||
std::fs::OpenOptions::new().write(true).create_new(true).open(tmp)
|
||||
}
|
||||
|
||||
/// Recheck after a potentially long fill: neither the folder nor the staging name may now
|
||||
/// belong to another save. Holding `file` also prevents Unix inode reuse while comparing it.
|
||||
pub(crate) fn check_staging(folder: &OpenedFolder, path: &Path, file: &std::fs::File) -> io::Result<()> {
|
||||
folder.check()?;
|
||||
let named = std::fs::symlink_metadata(path)?;
|
||||
if !named.is_file() {
|
||||
return Err(io::Error::other("the snapshot staging file was replaced"));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let held = file.metadata()?;
|
||||
if (held.dev(), held.ino()) != (named.dev(), named.ino()) {
|
||||
return Err(io::Error::other("the snapshot staging file was replaced"));
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = file; // Folder/file identity on Windows remains outside this Unix mitigation.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Store for FsStore {
|
||||
fn read(&mut self, name: &str) -> io::Result<Option<Vec<u8>>> {
|
||||
match std::fs::read(self.path(name)) {
|
||||
Ok(b) => Ok(Some(b)),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = self.log_for(name) {
|
||||
// what was handed over, written or still held
|
||||
return w.read();
|
||||
}
|
||||
let bytes = match std::fs::read(self.path(name)) {
|
||||
Ok(b) => Some(b),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if name == crate::journal::LOG && self.known_log_len.is_none() {
|
||||
self.known_log_len = Some(bytes.as_ref().map_or(0, |b| b.len() as u64));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = self.log_for(name) {
|
||||
// (after the appends handed over before)
|
||||
w.replace(data)?;
|
||||
self.sync_dir();
|
||||
return Ok(());
|
||||
}
|
||||
self.folder.check()?;
|
||||
let tmp = self.path(&format!("{name}.tmp"));
|
||||
{
|
||||
let mut f = create_staging(&tmp)?;
|
||||
f.write_all(data)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
let mut f = create_staging(&tmp)?;
|
||||
f.write_all(data)?;
|
||||
f.sync_all()?;
|
||||
check_staging(&self.folder, &tmp, &f)?;
|
||||
std::fs::rename(&tmp, self.path(name))?;
|
||||
self.sync_dir();
|
||||
self.reset_sync_log(name, data.len() as u64);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result<u64> {
|
||||
use std::io::Write;
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = self.log_for(name) {
|
||||
// (the log is small: buffered, and replaced by its thread after the appends before)
|
||||
let mut buf = Vec::new();
|
||||
fill(&mut buf)?;
|
||||
w.replace(&buf)?;
|
||||
self.sync_dir();
|
||||
return Ok(buf.len() as u64);
|
||||
}
|
||||
self.folder.check()?;
|
||||
let tmp = self.path(&format!("{name}.tmp"));
|
||||
let mut file = create_staging(&tmp)?;
|
||||
let written = (|| {
|
||||
let mut w = Counter { inner: io::BufWriter::with_capacity(1 << 20, create_staging(&tmp)?), n: 0 };
|
||||
let mut w = Counter { inner: io::BufWriter::with_capacity(1 << 20, &mut file), n: 0 };
|
||||
fill(&mut w)?;
|
||||
w.flush()?;
|
||||
let f = w.inner.into_inner().map_err(|e| e.into_error())?;
|
||||
f.sync_all()?;
|
||||
Ok(w.n)
|
||||
let n = w.n;
|
||||
drop(w);
|
||||
file.sync_all()?;
|
||||
Ok(n)
|
||||
})();
|
||||
let n = match written {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
if check_staging(&self.folder, &tmp, &file).is_ok() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
check_staging(&self.folder, &tmp, &file)?;
|
||||
std::fs::rename(&tmp, self.path(name))?;
|
||||
self.sync_dir();
|
||||
self.reset_sync_log(name, n);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
|
||||
check_regular_directory_entry(&self.path(name))?;
|
||||
let existed = self.path(name).exists();
|
||||
let f = std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
|
||||
if !existed {
|
||||
self.sync_dir();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if self.log.is_none() && self.sync_log.is_none() && !crate::fault::on_caller(&self.dir) {
|
||||
self.folder.check()?;
|
||||
check_regular_directory_entry(&self.path(name))?;
|
||||
if !self.path(name).exists() {
|
||||
// created here, so the open's errors are this append's and its entry is durable
|
||||
std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
|
||||
self.sync_dir();
|
||||
}
|
||||
let expected = if name == crate::journal::LOG { self.known_log_len } else { None };
|
||||
self.log = crate::log_writer::LogWriter::start(self.folder.clone(), name, expected);
|
||||
}
|
||||
// (another name than the log's is written here, as without a thread)
|
||||
if let Some(w) = self.log_for(name) {
|
||||
return w.append(data);
|
||||
}
|
||||
self.appender = Some((name.to_string(), f));
|
||||
}
|
||||
let Some((_, f)) = self.appender.as_mut() else { return Err(io::Error::other("appender not open")) };
|
||||
self.folder.check()?;
|
||||
// A note-bearing copy can pass the folder check while an old handle still names the
|
||||
// moved-away folder. As the log thread does, reopen the current path for every batch.
|
||||
check_regular_directory_entry(&self.path(name))?;
|
||||
let existed = self.path(name).exists();
|
||||
// Windows append-only handles cannot truncate their own failed write. For LOG,
|
||||
// match the native writer's writable handle and seek to the checked length.
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.create(true).truncate(false);
|
||||
if name == crate::journal::LOG {
|
||||
options.write(true);
|
||||
} else {
|
||||
options.append(true);
|
||||
}
|
||||
let mut f = options.open(self.path(name))?;
|
||||
if !existed {
|
||||
self.sync_dir();
|
||||
}
|
||||
if name == crate::journal::LOG {
|
||||
let len = f.metadata()?.len();
|
||||
let log = self.sync_log.get_or_insert(SynchronousLog { good: self.known_log_len.unwrap_or(len), torn: None });
|
||||
check_log_len(len, log.good)?;
|
||||
std::io::Seek::seek(&mut f, std::io::SeekFrom::Start(log.good))?;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let written = crate::fault::check(&self.dir, crate::fault::Step::Write)
|
||||
.and_then(|()| f.write_all(data))
|
||||
.and_then(|()| crate::fault::check(&self.dir, crate::fault::Step::Sync))
|
||||
.and_then(|()| f.sync_data());
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let written = f.write_all(data).and_then(|()| f.sync_data());
|
||||
if written.is_err() {
|
||||
// The handle may be dead (a network share that reconnected, a removed volume): the next
|
||||
// attempt reopens the file. Part of `data` may be in the file; the caller cuts it back
|
||||
// ([`Store::truncate`]) before appending again.
|
||||
self.appender = None;
|
||||
if name == crate::journal::LOG
|
||||
&& let Some(log) = self.sync_log.as_mut()
|
||||
{
|
||||
log.torn = written.is_err().then_some(f);
|
||||
if written.is_ok() {
|
||||
log.good = log.good.saturating_add(data.len() as u64);
|
||||
}
|
||||
}
|
||||
// A failed write can leave part of `data`; the caller cuts it back with `truncate`
|
||||
// before retrying. The file is reopened for that retry too.
|
||||
written
|
||||
}
|
||||
|
||||
fn truncate(&mut self, name: &str, len: u64) -> io::Result<()> {
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = self.log_for(name) {
|
||||
return w.truncate(len);
|
||||
}
|
||||
self.folder.check()?;
|
||||
if name == crate::journal::LOG
|
||||
&& let Some(log) = self.sync_log.as_mut()
|
||||
{
|
||||
rollback_torn(&mut log.torn, log.good)?;
|
||||
}
|
||||
check_regular_directory_entry(&self.path(name))?;
|
||||
let f = match std::fs::OpenOptions::new().write(true).open(self.path(name)) {
|
||||
@@ -179,8 +371,17 @@ impl Store for FsStore {
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if name == crate::journal::LOG
|
||||
&& let Some(good) = self.sync_log.as_ref().map(|log| log.good).or(self.known_log_len)
|
||||
{
|
||||
// Also covers initial repair before any append. Our own torn bytes, if any, were
|
||||
// rolled back through their held descriptor, never through this possibly replaced path.
|
||||
check_log_len(f.metadata()?.len(), good)?;
|
||||
}
|
||||
f.set_len(len)?;
|
||||
f.sync_all()
|
||||
f.sync_all()?;
|
||||
self.reset_sync_log(name, len);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
@@ -189,7 +390,16 @@ impl Store for FsStore {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn background_writer(&self) -> Option<Box<dyn Store>> {
|
||||
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None }))
|
||||
Some(Box::new(FsStore { dir: self.dir.clone(), folder: self.folder.clone(), sync_log: None, known_log_len: None, log: None }))
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.flush_log()
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn unwritten(&self) -> Option<(usize, String)> {
|
||||
self.log.as_ref().and_then(|w| w.unwritten())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,13 +466,13 @@ impl Store for MemStore {
|
||||
}
|
||||
}
|
||||
|
||||
// (its one test plants a symlink, so the module is Unix-only: elsewhere `use super::*` would be unused)
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests_staging {
|
||||
use super::*;
|
||||
|
||||
/// A link planted at a staging name (`<name>.tmp`) is removed, never followed: the file it points to keeps its
|
||||
/// bytes and the save still lands (issue #1502).
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_at_the_staging_name_is_never_written_through() {
|
||||
let dir = std::env::temp_dir().join(format!("lc-staging-link-{}", std::process::id()));
|
||||
|
||||
@@ -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();
|
||||
@@ -636,7 +656,8 @@ fn set_embedded_lens_is_undoable_and_journaled() {
|
||||
photo: Box::new(Photo::new(a, Source::File { path: "/x.rw2".into() }, "x.rw2", "RW2", 4000, 3000, "2026-10-06T00:00:00")),
|
||||
})
|
||||
.unwrap();
|
||||
let lens = lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default() };
|
||||
let lens =
|
||||
lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default(), source: Default::default() };
|
||||
let op = Op::SetEmbeddedLens { id: a, lens: Some(Box::new(lens)) };
|
||||
let op: Op = serde_json::from_str(&serde_json::to_string(&op).unwrap()).unwrap();
|
||||
let inv = c.apply(op).unwrap();
|
||||
|
||||
@@ -269,9 +269,10 @@ fn fs_store_background_snapshot() {
|
||||
}
|
||||
// a previous crash mid-snapshot left a partial temp file
|
||||
std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"{\"format\":\"lightcraft-catal").unwrap();
|
||||
// (closed first: its log thread writes what was handed over)
|
||||
drop(j);
|
||||
let (mut j2, c2, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
assert_eq!((c2.to_snapshot(), r.snapshot_seq), (live.to_snapshot(), 0));
|
||||
drop(j);
|
||||
let n = j2.seq();
|
||||
j2.snapshot_in_background(&live).unwrap();
|
||||
for k in 200..260 {
|
||||
|
||||
@@ -238,8 +238,9 @@ fn op_variants_are_versioned() {
|
||||
Op::SetHistoryCursor { .. } => 8,
|
||||
}
|
||||
}
|
||||
/// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`.
|
||||
const NEWEST_FIELDS: u32 = 9;
|
||||
/// v13: Lens Blur in develop settings and mask adjustments (v12: `Catalog.grids` and `SegMask.grid`; v11: `EmbeddedLens.source`;
|
||||
/// v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
|
||||
const NEWEST_FIELDS: u32 = 13;
|
||||
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
|
||||
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Issue #2154: a snapshot keeps each distinct segmentation grid once (`Catalog.grids`) and the
|
||||
//! masks of the develop settings, versions, history steps and import look refer to it by index,
|
||||
//! so an unchanged mask no longer repeats with every history step. In-memory catalogs and log
|
||||
//! records always hold the grids inline; older catalogs (inline everywhere) load and are upgraded.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape, SegMask};
|
||||
|
||||
use crate::journal::{LOG, SNAPSHOT, VERSION};
|
||||
use crate::*;
|
||||
|
||||
fn snapshot_version(m: &MemStore) -> u64 {
|
||||
let v: serde_json::Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap();
|
||||
v["version"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn open(m: &MemStore) -> (Journal, Catalog, LoadReport) {
|
||||
Journal::open(Box::new(m.clone())).unwrap()
|
||||
}
|
||||
|
||||
/// Develop settings with one AI mask over an object segmentation.
|
||||
fn settings_with_seg(seg: SegMask, exposure: f64) -> DevelopSettings {
|
||||
let mut s = DevelopSettings::default();
|
||||
s.light.exposure = exposure;
|
||||
s.masks.push(Mask {
|
||||
id: 1,
|
||||
components: vec![MaskComponent {
|
||||
name: None,
|
||||
op: MaskOp::Add,
|
||||
invert: false,
|
||||
shape: MaskShape::Object {
|
||||
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
|
||||
exclude: vec![],
|
||||
seg: Some(seg),
|
||||
detail: vec![],
|
||||
edge: 0.0,
|
||||
},
|
||||
}],
|
||||
..Default::default()
|
||||
});
|
||||
s
|
||||
}
|
||||
|
||||
/// One mask (`id`) whose only component is an Object segmentation `seg`.
|
||||
fn object_mask(id: u32, seg: SegMask) -> Mask {
|
||||
Mask {
|
||||
id,
|
||||
components: vec![MaskComponent {
|
||||
name: None,
|
||||
op: MaskOp::Add,
|
||||
invert: false,
|
||||
shape: MaskShape::Object {
|
||||
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
|
||||
exclude: vec![],
|
||||
seg: Some(seg),
|
||||
detail: vec![],
|
||||
edge: 0.0,
|
||||
},
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A catalog of one photo whose history is `steps` slider edits over the same mask, plus the
|
||||
/// ops that built it (each step is one `SetDevelop` + one `PushHistory`, as the engine commits
|
||||
/// an edit) and the shared grid's bytes.
|
||||
fn masked_catalog(steps: usize) -> (Catalog, Vec<Op>, PhotoId, String) {
|
||||
let seg = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let blob = seg.data.clone();
|
||||
let mut c = Catalog::new();
|
||||
let id = c.alloc_photo_id();
|
||||
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::File { path: "/p/1.jpg".into() }, "1.jpg", "JPEG", 60, 40, "2026-01-01")) };
|
||||
c.apply(add.clone()).unwrap();
|
||||
let mut ops = vec![add];
|
||||
for i in 1..=steps {
|
||||
let settings = Arc::new(settings_with_seg(seg.clone(), f64::from(i as u32) * 0.1));
|
||||
let op = Op::Batch {
|
||||
ops: vec![
|
||||
Op::SetDevelop { id, settings: settings.clone(), label: "Exposure".into(), edited: Some(format!("t{i}")) },
|
||||
Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings } },
|
||||
],
|
||||
};
|
||||
c.apply(op.clone()).unwrap();
|
||||
ops.push(op);
|
||||
}
|
||||
(c, ops, id, blob)
|
||||
}
|
||||
|
||||
/// N history steps over one mask store the grid exactly once and load back identical.
|
||||
#[test]
|
||||
fn snapshot_deduplicates_shared_grid() {
|
||||
let (live, ops, id, blob) = masked_catalog(20);
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, report) = open(&m);
|
||||
assert!(report.created);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(snapshot_version(&m), u64::from(VERSION));
|
||||
assert_eq!(body.match_indices(&blob).count(), 1, "the grid is stored once for every step that shares it");
|
||||
let v: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 1);
|
||||
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!((report.replayed, report.upgraded_from, report.repaired.len()), (0, None, 0));
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
let p = loaded.photo(id).unwrap();
|
||||
assert_eq!(p.history.len(), 20);
|
||||
for h in &p.history {
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &h.settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), (blob.as_str(), None), "every step's grid is back inline");
|
||||
}
|
||||
}
|
||||
|
||||
/// A catalog written before the shared table (grids inline everywhere, format v9) loads as it
|
||||
/// was and its upgrade rewrite deduplicates.
|
||||
#[test]
|
||||
fn v9_catalog_with_inline_grids_loads_and_is_upgraded() {
|
||||
let (live, _, _, blob) = masked_catalog(3);
|
||||
let body = live.to_snapshot();
|
||||
assert!(body.contains(&blob), "a live catalog stores its grids inline");
|
||||
let m = MemStore::new();
|
||||
m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":2,\"catalog\":{body}}}\n").into_bytes());
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!((report.replayed, report.upgraded_from), (0, Some(9)));
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
// rewritten in this format before anything is appended, with the grid once
|
||||
assert_eq!(snapshot_version(&m), u64::from(VERSION));
|
||||
let rewritten_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let rewritten = std::str::from_utf8(&rewritten_bytes).unwrap();
|
||||
assert_eq!(rewritten.match_indices(&blob).count(), 1);
|
||||
assert!(rewritten.contains("\"grids\":["), "the shared table is in the file");
|
||||
}
|
||||
|
||||
/// The op log is not deduplicated: every record keeps the grids inline (a log never carries the
|
||||
/// shared table), and replaying it rebuilds the same state.
|
||||
#[test]
|
||||
fn log_records_keep_their_grids_inline() {
|
||||
let (live, ops, _, blob) = masked_catalog(2);
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
drop(j); // no snapshot: the log holds the whole state
|
||||
let log_bytes = m.get(LOG).unwrap();
|
||||
let log = std::str::from_utf8(&log_bytes).unwrap();
|
||||
assert_eq!(log.match_indices(&blob).count(), 4, "two edits, SetDevelop + PushHistory each, inline");
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.replayed, 3, "the photo and the two edits");
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A reference that points past the shared table is cleared (the mask renders nothing, like any
|
||||
/// damaged grid); a good reference resolves back to the full grid.
|
||||
#[test]
|
||||
fn shared_grid_references_resolve_or_are_repaired() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: the develop mask refers past the one-entry table
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":7", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"dHdv\"],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared, never a crash");
|
||||
// the history step's inline grid is untouched
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob);
|
||||
|
||||
// a good reference resolves (the normal way a snapshot in this format reads, so it is not
|
||||
// reported as a repair): the mask reads exactly as it was written
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"{blob}\"],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, resolved, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
assert_eq!(resolved.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// The background snapshot path shares the grids too (the interner is per thread).
|
||||
#[test]
|
||||
fn background_snapshot_deduplicates_shared_grid() {
|
||||
let (live, ops, _, blob) = masked_catalog(5);
|
||||
let mut m = MemStore::new();
|
||||
m.background = true;
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot_in_background(&live).unwrap();
|
||||
j.wait().unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&blob).count(), 1);
|
||||
let (_, loaded, _) = open(&m);
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A version (not only history steps) shares the grid: one photo with a snapshot version and a
|
||||
/// history step over the same mask stores the grid once.
|
||||
#[test]
|
||||
fn versions_share_the_grid_too() {
|
||||
let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]);
|
||||
let blob = seg.data.clone();
|
||||
let id = PhotoId(1);
|
||||
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, "d.jpg", "JPEG", 60, 40, "2026-01-01")) };
|
||||
let settings = Arc::new(settings_with_seg(seg, 0.5));
|
||||
let versions =
|
||||
Op::SetVersions { id, versions: vec![Version { name: "v".into(), created: "2026-01-01".into(), settings: settings.clone(), auto: false }] };
|
||||
let history = Op::PushHistory { id, step: HistoryStep { label: "e".into(), settings } };
|
||||
let mut live = Catalog::new();
|
||||
for op in [&add, &versions, &history] {
|
||||
live.apply(op.clone()).unwrap();
|
||||
}
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&[add, versions, history]).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&blob).count(), 1, "the version and the step share the grid");
|
||||
let (_, loaded, _) = open(&m);
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// The import look (`Photo.import_look`, the settings a default preset gave the photo on import)
|
||||
/// can hold AI masks, and their grids can be grids the develop settings or a history step hold.
|
||||
/// Every settings holder shares the snapshot's table, so the look's masks are referenced and
|
||||
/// resolved on load like the others; a grid only the look holds is in the table too.
|
||||
#[test]
|
||||
fn import_look_masks_share_the_table_and_resolve_on_load() {
|
||||
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let look_only = SegMask::from_logits(64, &vec![-0.5f32; 64 * 64]);
|
||||
let mut look = DevelopSettings::default();
|
||||
look.masks.push(object_mask(1, shared.clone()));
|
||||
look.masks.push(object_mask(2, look_only.clone()));
|
||||
let mut edit = DevelopSettings::default();
|
||||
edit.light.exposure = 0.7;
|
||||
edit.masks.push(object_mask(1, shared.clone()));
|
||||
let edit = Arc::new(edit);
|
||||
|
||||
let id = PhotoId(1);
|
||||
let mut photo = Photo::new(id, Source::File { path: "/p/2.jpg".into() }, "2.jpg", "JPEG", 60, 40, "2026-01-01");
|
||||
photo.develop = edit.clone();
|
||||
photo.import_look = Some(Arc::new(look));
|
||||
photo.history.push(HistoryStep { label: "Exposure".into(), settings: edit });
|
||||
let add = Op::AddPhoto { photo: Box::new(photo) };
|
||||
let mut live = Catalog::new();
|
||||
live.apply(add.clone()).unwrap();
|
||||
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&[add]).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&shared.data).count(), 1, "the grid of the look and of the edit is stored once");
|
||||
assert_eq!(body.match_indices(&look_only.data).count(), 1);
|
||||
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
let p = loaded.photo(id).unwrap();
|
||||
let look_masks = &p.import_look.as_ref().unwrap().masks;
|
||||
assert_eq!(look_masks.len(), 2);
|
||||
for (mask, want) in look_masks.iter().zip([&shared, &look_only]) {
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &mask.components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), (want.data.as_str(), None), "the look's grid is back inline");
|
||||
}
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
let v: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 2, "one table entry per distinct grid, the look's included");
|
||||
}
|
||||
|
||||
/// A `grid` that arrives from a document (a command's mask JSON, a preset, a merged partial) is
|
||||
/// not a reference and is never written as one: a snapshot must not resolve it to another mask's
|
||||
/// grid. Here photo two's mask carries `grid: 0` with empty data, while photo one's grid is the
|
||||
/// table's entry 0; before the fix the inline form wrote `"grid":0` and the load filled photo two
|
||||
/// with photo one's grid.
|
||||
#[test]
|
||||
fn stray_grid_from_a_document_is_not_written_as_a_reference() {
|
||||
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let stray: SegMask = serde_json::from_str(r#"{"side":64,"data":"","grid":0}"#).unwrap();
|
||||
assert_eq!(stray.grid, Some(0), "a document can set grid");
|
||||
let mut stray_settings = DevelopSettings::default();
|
||||
stray_settings.masks.push(object_mask(1, stray));
|
||||
|
||||
let (one, two) = (PhotoId(1), PhotoId(2));
|
||||
let photo = |id: PhotoId, name: &str| Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01");
|
||||
let ops = [
|
||||
Op::AddPhoto { photo: Box::new(photo(one, "1.jpg")) },
|
||||
Op::SetDevelop { id: one, settings: Arc::new(settings_with_seg(shared.clone(), 0.2)), label: "Exposure".into(), edited: Some("t1".into()) },
|
||||
Op::AddPhoto { photo: Box::new(photo(two, "2.jpg")) },
|
||||
Op::SetDevelop { id: two, settings: Arc::new(stray_settings), label: "Edit".into(), edited: Some("t2".into()) },
|
||||
];
|
||||
let mut live = Catalog::new();
|
||||
for op in &ops {
|
||||
live.apply(op.clone()).unwrap();
|
||||
}
|
||||
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &loaded.photo(two).unwrap().develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the stray reference is not resolved to photo one's grid");
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A snapshot whose shared grid table is empty (`grids: []`) but whose masks still refer into
|
||||
/// it: the table being empty must not skip the repair. A reference past an empty table is
|
||||
/// dangling, so it is cleared (the mask renders nothing, like any other damaged grid), the
|
||||
/// repair is reported, and a mask that carries its own grid inline is left untouched.
|
||||
#[test]
|
||||
fn empty_shared_grid_table_clears_dangling_references() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: an empty table, but the develop mask still refers to entry 0
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with an empty table");
|
||||
|
||||
// the history step carries its grid inline: nothing there to resolve, left as it was
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
|
||||
}
|
||||
|
||||
/// A snapshot that omits the shared grid table entirely (no `grids` key) but whose masks still
|
||||
/// refer into it: an absent table deserializes to an empty Vec, so a reference past it is
|
||||
/// dangling and is cleared and reported, just like the empty-table case.
|
||||
#[test]
|
||||
fn omitted_shared_grid_table_clears_dangling_references() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: no table at all, but the develop mask still refers to entry 0
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{{} }} }}\n", &body[1..body.len() - 1])
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with no table");
|
||||
|
||||
// the history step carries its grid inline: nothing there to resolve, left as it was
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
|
||||
}
|
||||
@@ -84,6 +84,41 @@ fn a_link_at_the_owner_note_is_never_written_through() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The note is what tells the folder that was locked from every other folder (issue #3240), so no two
|
||||
/// locks write the same one, also when one process takes them in the same second. A note written
|
||||
/// before it had a value of its own is still read.
|
||||
#[test]
|
||||
fn every_lock_writes_a_note_of_its_own() {
|
||||
let notes: std::collections::HashSet<Vec<u8>> =
|
||||
(0..2_000).map(|_| serde_json::to_vec_pretty(&LockOwner::this_process("LightCraft")).unwrap()).collect();
|
||||
assert_eq!(notes.len(), 2_000, "one note for each lock");
|
||||
let old: LockOwner = serde_json::from_slice(br#"{"pid":7,"host":"elsewhere","program":"LightCraft","version":"0.2.0","since":1}"#).unwrap();
|
||||
assert!(old.pid == 7 && old.token.is_empty());
|
||||
}
|
||||
|
||||
/// Two libraries locked by one process in the same second: the folder of the second, put at the
|
||||
/// path of the first, doesn't hold the first lock's note, so it isn't taken for the folder that was
|
||||
/// locked.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_folder_of_another_lock_taken_in_the_same_second_is_not_the_folder_that_was_locked() {
|
||||
let _serial = serial();
|
||||
let (first_dir, second_dir) = (temp_dir("same-second-one"), temp_dir("same-second-two"));
|
||||
let first = LibraryLock::acquire(&first_dir, "LightCraft").unwrap();
|
||||
let second = LibraryLock::acquire(&second_dir, "LightCraft").unwrap();
|
||||
assert_ne!(first.note(), second.note(), "each lock wrote its own note");
|
||||
|
||||
let away = first_dir.with_extension("away");
|
||||
std::fs::rename(&first_dir, &away).unwrap();
|
||||
std::fs::rename(&second_dir, &first_dir).unwrap();
|
||||
let msg = first.folder().unwrap().check().expect_err("another library's folder is at the path now").to_string();
|
||||
assert!(msg.contains("is no longer the folder this library was opened from"), "{msg}");
|
||||
drop(second);
|
||||
drop(first);
|
||||
let _ = std::fs::remove_dir_all(&first_dir);
|
||||
let _ = std::fs::remove_dir_all(&away);
|
||||
}
|
||||
|
||||
/// Another process holds the lock; when it is killed (a crash), the OS releases it.
|
||||
#[test]
|
||||
fn lock_held_by_another_process_is_released_when_it_dies() {
|
||||
@@ -199,3 +234,90 @@ fn dropping_the_lock_frees_the_library_while_another_thread_spawns_processes() {
|
||||
&refused[..refused.len().min(3)]
|
||||
);
|
||||
}
|
||||
|
||||
/// Issue #3240: dropping the lock removes the owner note it wrote, and only that one. Another
|
||||
/// process that has the folder open (the library on a share that the folder was mounted over)
|
||||
/// wrote the note in the folder at the path now; removing it, as dropping the lock did before,
|
||||
/// took away the only hint of who holds that library.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dropping_the_lock_keeps_the_owner_note_of_a_folder_that_replaced_the_locked_one() {
|
||||
let _serial = serial();
|
||||
let base = temp_dir("owner-replaced");
|
||||
let dir = base.join("lib");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
assert!(lock.held());
|
||||
std::fs::rename(&dir, base.join("lib.away")).unwrap();
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let theirs = br#"{"pid":999999,"host":"elsewhere","program":"LightCraft","version":"0.2.0","since":1}"#;
|
||||
std::fs::write(dir.join(OWNER), theirs).unwrap();
|
||||
drop(lock);
|
||||
assert_eq!(std::fs::read(dir.join(OWNER)).ok().as_deref(), Some(&theirs[..]), "the note of the folder at the path now is theirs");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A folder that holds this lock's note, byte for byte, is the locked folder whatever its numbers say
|
||||
/// ([`OpenedFolder::vouch`]): a copy of the library's folder made while it was open, put where the
|
||||
/// locked one was, counts as it. So the note goes from there too, as from the locked folder.
|
||||
/// (A note with other bytes is another's, as the test above has it.)
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dropping_the_lock_removes_a_copy_of_its_note_from_the_folder_that_holds_it() {
|
||||
let _serial = serial();
|
||||
let base = temp_dir("owner-copied");
|
||||
let dir = base.join("lib");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
let note = std::fs::read(dir.join(OWNER)).unwrap();
|
||||
std::fs::rename(&dir, base.join("lib.away")).unwrap();
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
drop(lock);
|
||||
assert!(!dir.join(OWNER).exists(), "the folder at the path holds exactly this lock's note: it is the locked folder");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// The lock vouches for the note it wrote in the record of its folder: that is what recognizes the
|
||||
/// folder when a file system numbers it anew (a drive mounted again), and what the library takes
|
||||
/// over for its stores.
|
||||
#[test]
|
||||
fn the_lock_vouches_for_the_note_it_wrote_in_the_record_of_its_folder() {
|
||||
let _serial = serial();
|
||||
let dir = temp_dir("vouch");
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
let written = std::fs::read(dir.join(OWNER)).unwrap();
|
||||
assert_eq!(lock.note(), Some(written.as_slice()), "the bytes in the folder");
|
||||
assert_eq!(lock.folder().and_then(OpenedFolder::note), Some(written.as_slice()), "are what its folder's record vouches for");
|
||||
drop(lock);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// In the locked folder itself, a note another process wrote over this lock's is theirs too (a
|
||||
/// share that lost this lock's hold and gave it to another computer): it stays when this lock
|
||||
/// is dropped. On every system.
|
||||
#[test]
|
||||
fn dropping_the_lock_keeps_an_owner_note_another_process_wrote() {
|
||||
let _serial = serial();
|
||||
let dir = temp_dir("owner-theirs");
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
assert!(lock.held());
|
||||
let theirs = br#"{"pid":999999,"host":"elsewhere","program":"LightCraft","version":"0.2.0","since":1}"#;
|
||||
std::fs::write(dir.join(OWNER), theirs).unwrap();
|
||||
drop(lock);
|
||||
assert_eq!(std::fs::read(dir.join(OWNER)).ok().as_deref(), Some(&theirs[..]), "a note another process wrote is not ours to remove");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The inverse: the folder is the locked one and the note is as this lock wrote it, so it goes
|
||||
/// (the library can be opened by the next program, with no note left naming this one).
|
||||
#[test]
|
||||
fn dropping_the_lock_removes_its_own_note_from_its_own_folder() {
|
||||
let _serial = serial();
|
||||
let dir = temp_dir("owner-own");
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
assert!(dir.join(OWNER).is_file());
|
||||
drop(lock);
|
||||
assert!(!dir.join(OWNER).exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! PERF-STEP-STALL: the catalog log's own thread ([`crate::log_writer`]). Appends return at once
|
||||
//! however slow the drive is; everything handed over is written in order; a write that fails is
|
||||
//! held, reported and retried, never dropped, and the log never has a gap.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::fault::{self, Step};
|
||||
use crate::store::{FsStore, Store};
|
||||
|
||||
const LOG: &str = "catalog.log";
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("lc-log-thread-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
|
||||
let t = Instant::now();
|
||||
while !done() {
|
||||
assert!(t.elapsed() < Duration::from_secs(20), "{what}");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends are written by the thread in order; a read through the store sees every one; a cut
|
||||
/// and a replace come after the appends before them; dropping the store writes what is left.
|
||||
#[test]
|
||||
fn appends_are_written_in_order_and_cuts_and_replaces_come_after_them() {
|
||||
let dir = temp_dir("order");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
let mut want = Vec::new();
|
||||
for i in 0..200u32 {
|
||||
let line = format!("{i}\n");
|
||||
store.append(LOG, line.as_bytes()).unwrap();
|
||||
want.extend_from_slice(line.as_bytes());
|
||||
if i % 50 == 0 {
|
||||
assert_eq!(store.read(LOG).unwrap().unwrap(), want, "all of it, through the store");
|
||||
}
|
||||
}
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want, "all of it, in the file");
|
||||
store.truncate(LOG, 4).unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
|
||||
// never longer than it is
|
||||
store.truncate(LOG, 400).unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
|
||||
store.append(LOG, b"x\n").unwrap();
|
||||
store.write_atomic(LOG, b"tail\n").unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n");
|
||||
store.append(LOG, b"more\n").unwrap();
|
||||
drop(store);
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\nmore\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// (a) Each sync takes 300 ms: 100 appends still return at once, and a flush then finds all of
|
||||
/// them in the file (before, each append waited for its own sync: 30 s for these).
|
||||
#[test]
|
||||
fn an_append_never_waits_for_a_slow_sync() {
|
||||
let dir = temp_dir("slow");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.append(LOG, b"first\n").unwrap();
|
||||
let syncs = Arc::new(AtomicUsize::new(0));
|
||||
let n = syncs.clone();
|
||||
fault::install(
|
||||
&dir,
|
||||
Arc::new(move |step| {
|
||||
if step == Step::Sync {
|
||||
n.fetch_add(1, Ordering::SeqCst);
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
);
|
||||
let mut want = b"first\n".to_vec();
|
||||
let mut slowest = Duration::ZERO;
|
||||
for i in 0..100u32 {
|
||||
let line = format!("{i}\n");
|
||||
let t = Instant::now();
|
||||
store.append(LOG, line.as_bytes()).unwrap();
|
||||
slowest = slowest.max(t.elapsed());
|
||||
want.extend_from_slice(line.as_bytes());
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
assert!(slowest < Duration::from_millis(50), "an append waited {slowest:?}");
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want);
|
||||
// batched: far fewer syncs than appends
|
||||
assert!(syncs.load(Ordering::SeqCst) < 50, "{} syncs", syncs.load(Ordering::SeqCst));
|
||||
fault::remove(&dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// (c) Writes fail for a while: what was handed over is held (reported, with the reason), later
|
||||
/// appends are refused so the caller keeps them, and once writes work again the held bytes land,
|
||||
/// in order, with no fragment of the failed attempts and no gap.
|
||||
#[test]
|
||||
fn a_failed_write_is_held_reported_and_retried() {
|
||||
let dir = temp_dir("fail");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.append(LOG, b"0\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
let fail = Arc::new(AtomicBool::new(true));
|
||||
let f = fail.clone();
|
||||
let log_path = dir.join(LOG);
|
||||
fault::install(
|
||||
&dir,
|
||||
Arc::new(move |step| {
|
||||
if f.load(Ordering::SeqCst) && step == fault::Step::Sync {
|
||||
// Inject the torn tail before the failed sync returns. Writing it from the test
|
||||
// thread races a successful retry and can append a foreign tail after that retry.
|
||||
use std::io::Write;
|
||||
std::fs::OpenOptions::new().append(true).open(&log_path)?.write_all(b"{\"seq\":")?;
|
||||
Err(std::io::Error::other("disk full (test)"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}),
|
||||
);
|
||||
// (one append: the log thread can fail the first before a second arrives, and then refuses it)
|
||||
store.append(LOG, b"1\n2\n").unwrap();
|
||||
wait_until("the failure is published", || store.unwritten().is_some());
|
||||
let (held, why) = store.unwritten().unwrap();
|
||||
assert!(why.contains("disk full"), "{why}");
|
||||
assert!(held >= 1, "{held}");
|
||||
let refused = store.append(LOG, b"3\n");
|
||||
assert!(refused.is_err(), "refused while held");
|
||||
assert!(store.flush().is_err(), "a flush says it isn't written");
|
||||
// a read through the store still sees what was handed over
|
||||
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
|
||||
// a cut within what is held keeps it (the journal cuts back to its own length on an error)
|
||||
store.truncate(LOG, 6).unwrap();
|
||||
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
|
||||
// The failed sync injected a fragment: the retry must remove it before writing the held bytes.
|
||||
fail.store(false, Ordering::SeqCst);
|
||||
wait_until("retried on its own", || store.unwritten().is_none());
|
||||
store.append(LOG, b"3\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n2\n3\n");
|
||||
fault::remove(&dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A log longer than the thread wrote is cut back only when a write of its own failed (that
|
||||
/// fragment is its own). A failure that never touched the file (here the write step, as a folder
|
||||
/// refused while another is put at the path) leaves the log it finds alone: it may be another
|
||||
/// folder's, and cutting it would corrupt it.
|
||||
#[test]
|
||||
fn a_log_longer_than_the_thread_wrote_is_not_cut_unless_its_own_write_failed() {
|
||||
let dir = temp_dir("not-torn");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.append(LOG, b"0\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
let fail = Arc::new(AtomicBool::new(true));
|
||||
let f = fail.clone();
|
||||
fault::install(
|
||||
&dir,
|
||||
Arc::new(
|
||||
move |step| if f.load(Ordering::SeqCst) && step == fault::Step::Write { Err(std::io::Error::other("refused (test)")) } else { Ok(()) },
|
||||
),
|
||||
);
|
||||
store.append(LOG, b"1\n").unwrap();
|
||||
wait_until("the failure is published", || store.unwritten().is_some());
|
||||
let theirs = b"0\nrecords of another log\n";
|
||||
std::fs::write(dir.join(LOG), theirs).unwrap();
|
||||
fail.store(false, Ordering::SeqCst);
|
||||
wait_until("looked at again", || store.unwritten().is_some_and(|(_, why)| why.contains("another file")));
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), theirs, "left as it was found");
|
||||
fault::remove(&dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a
|
||||
/// journal over a log that failed has no gap (no damage on load).
|
||||
#[test]
|
||||
fn the_journal_reopens_every_op_after_a_slow_then_failing_drive() {
|
||||
use crate::{Catalog, Journal, Op, Photo, PhotoId, Source};
|
||||
let dir = temp_dir("journal");
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
let fail = Arc::new(AtomicBool::new(false));
|
||||
let f = fail.clone();
|
||||
fault::install(
|
||||
&dir,
|
||||
Arc::new(move |step| {
|
||||
if f.load(Ordering::SeqCst) {
|
||||
return Err(std::io::Error::other("network share dropped (test)"));
|
||||
}
|
||||
if step == Step::Sync {
|
||||
std::thread::sleep(Duration::from_millis(40));
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
);
|
||||
let mut queued: Vec<Op> = Vec::new();
|
||||
for id in 1..=60u64 {
|
||||
if id == 20 {
|
||||
fail.store(true, Ordering::SeqCst);
|
||||
}
|
||||
if id == 40 {
|
||||
fail.store(false, Ordering::SeqCst);
|
||||
}
|
||||
let p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 4, 3, "2026-11-02");
|
||||
let op = Op::AddPhoto { photo: Box::new(p) };
|
||||
c.apply(op.clone()).unwrap();
|
||||
queued.push(op);
|
||||
// as the engine does: a failed append keeps its ops queued for the next one
|
||||
if j.append(&queued).is_ok() {
|
||||
queued.clear();
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
wait_until("everything written", || {
|
||||
if !queued.is_empty() && j.append(&queued).is_ok() {
|
||||
queued.clear();
|
||||
}
|
||||
queued.is_empty() && j.unwritten().is_none()
|
||||
});
|
||||
j.flush().unwrap();
|
||||
let expect = c.to_snapshot();
|
||||
drop(j);
|
||||
fault::remove(&dir);
|
||||
let (_, again, report): (_, Catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
assert!(report.damaged.is_none(), "{report:?}");
|
||||
assert_eq!(again.to_snapshot(), expect);
|
||||
assert_eq!(again.len(), 60);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A sync that fails leaves the written bytes past the synced length in the file; a cut to exactly
|
||||
/// that length removes them from the file too, so they never come back on the next open (review
|
||||
/// of #3557).
|
||||
#[test]
|
||||
fn a_cut_to_the_synced_length_removes_bytes_a_failed_sync_left() {
|
||||
let dir = temp_dir("cut-synced");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store
|
||||
.append(
|
||||
LOG, b"0
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
store.flush().unwrap();
|
||||
fault::install(&dir, Arc::new(|step| if step == Step::Sync { Err(std::io::Error::other("sync failed (test)")) } else { Ok(()) }));
|
||||
store
|
||||
.append(
|
||||
LOG, b"1
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
wait_until("the failure is published", || store.unwritten().is_some());
|
||||
assert_eq!(
|
||||
std::fs::read(dir.join(LOG)).unwrap(),
|
||||
b"0
|
||||
1
|
||||
",
|
||||
"written, not synced"
|
||||
);
|
||||
store.truncate(LOG, 2).unwrap();
|
||||
fault::remove(&dir);
|
||||
drop(store);
|
||||
assert_eq!(
|
||||
std::fs::read(dir.join(LOG)).unwrap(),
|
||||
b"0
|
||||
"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
//! Issue #3240: a library's files are written to the folder it was opened from, not to whatever its
|
||||
//! path leads to later (a share mounted over the folder, or the folder moved away and another put
|
||||
//! at its path). A folder's identity is its device and inode number, so the tests that move a
|
||||
//! folder run on Unix; the rest hold everywhere.
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(unix)]
|
||||
use crate::journal::{LOG, SNAPSHOT};
|
||||
#[cfg(unix)]
|
||||
use crate::lock::OWNER;
|
||||
use crate::*;
|
||||
|
||||
/// The start of the sentence a refused write ends with.
|
||||
const REFUSED: &str = "is no longer the folder this library was opened from";
|
||||
|
||||
fn scratch(tag: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("lc-opened-folder-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The files in `dir` with their bytes, by name.
|
||||
#[cfg(unix)]
|
||||
fn files_in(dir: &Path) -> Vec<(String, Vec<u8>)> {
|
||||
let mut files: Vec<_> = std::fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.map(|e| {
|
||||
let e = e.unwrap();
|
||||
(e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Another library's folder where `dir` was, and the folder that was there moved to the path
|
||||
/// returned: what a share mounted over `dir` looks like (the path leads somewhere else, and the
|
||||
/// folder that was opened is out of reach).
|
||||
#[cfg(unix)]
|
||||
fn put_another_folder_at(dir: &Path) -> PathBuf {
|
||||
let away = dir.with_extension("away");
|
||||
std::fs::rename(dir, &away).unwrap();
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
std::fs::write(dir.join(SNAPSHOT), b"their snapshot").unwrap();
|
||||
std::fs::write(dir.join(LOG), b"their log\n").unwrap();
|
||||
std::fs::write(dir.join(OWNER), b"their note").unwrap();
|
||||
away
|
||||
}
|
||||
|
||||
/// Every way a store writes is refused in a folder that replaced the opened one, whether or not
|
||||
/// the log's own thread has started, and nothing is written in either folder.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_store_writes_nothing_into_a_folder_that_replaced_the_one_it_opened() {
|
||||
for log_running in [false, true] {
|
||||
let base = scratch(&format!("store-{log_running}"));
|
||||
let dir = base.join("lib");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.write_atomic(SNAPSHOT, b"ours").unwrap();
|
||||
if log_running {
|
||||
store.append(LOG, b"1\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
}
|
||||
let away = put_another_folder_at(&dir);
|
||||
let (theirs, ours) = (files_in(&dir), files_in(&away));
|
||||
|
||||
let results = [
|
||||
("write_atomic", store.write_atomic(SNAPSHOT, b"x")),
|
||||
("write_atomic_with", store.write_atomic_with(SNAPSHOT, &mut |w| w.write_all(b"x")).map(|_| ())),
|
||||
("write_atomic of the log", store.write_atomic(LOG, b"")),
|
||||
("write_atomic of a settings file", store.write_atomic("prefs.json", b"{}")),
|
||||
("truncate", store.truncate(LOG, 0)),
|
||||
];
|
||||
let appended = store.append(LOG, b"2\n");
|
||||
let flushed = store.flush();
|
||||
|
||||
// what matters most: nothing was written, in either folder
|
||||
assert_eq!(files_in(&dir), theirs, "the folder at the path now is untouched (log thread running: {log_running})");
|
||||
assert_eq!(files_in(&away), ours, "and so is the folder that was opened: saving stops (log thread running: {log_running})");
|
||||
|
||||
// and each write was refused, with the reason
|
||||
for (what, r) in results {
|
||||
let e = r.expect_err(what);
|
||||
assert!(e.to_string().contains(REFUSED), "{what}: {e}");
|
||||
}
|
||||
if log_running {
|
||||
// handed over to the log's thread, which refuses to write it: held, and said so
|
||||
appended.expect("the thread takes it");
|
||||
let e = flushed.expect_err("the thread can't write it");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
let (held, why) = store.unwritten().expect("held, not dropped");
|
||||
assert!(held == 1 && why.contains(REFUSED), "{held}: {why}");
|
||||
} else {
|
||||
let e = appended.expect_err("the first append");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
}
|
||||
|
||||
if log_running {
|
||||
// the folder that was opened is back at the path: what was held is written, into it
|
||||
std::fs::rename(&dir, base.join("lib.theirs")).unwrap();
|
||||
std::fs::rename(&away, &dir).unwrap();
|
||||
store.flush().expect("saving resumes");
|
||||
assert_eq!(store.unwritten(), None);
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"1\n2\n");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
}
|
||||
|
||||
/// A compaction that starts after the folder was replaced writes through a second handle on the
|
||||
/// same files: it is bound to the folder the store opened too.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_snapshot_writer_of_a_store_is_bound_to_the_folder_the_store_opened() {
|
||||
let base = scratch("worker");
|
||||
let dir = base.join("lib");
|
||||
let store = FsStore::open(&dir).unwrap();
|
||||
let _away = put_another_folder_at(&dir);
|
||||
let theirs = files_in(&dir);
|
||||
let mut worker = store.background_writer().expect("a store on disk has one");
|
||||
let e = worker.write_atomic_with(SNAPSHOT, &mut |w| w.write_all(b"ours")).expect_err("refused");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
assert_eq!(files_in(&dir), theirs);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A journal's save (the closing snapshot) in a folder that replaced the opened one fails with the
|
||||
/// reason and writes nothing; with the folder back, the same call saves.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_journal_cannot_snapshot_into_a_folder_that_replaced_the_one_it_opened() {
|
||||
let base = scratch("journal");
|
||||
let dir = base.join("lib");
|
||||
let (mut journal, catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
let away = put_another_folder_at(&dir);
|
||||
let theirs = files_in(&dir);
|
||||
let e = journal.snapshot(&catalog).expect_err("the path leads to another library's folder");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
assert_eq!(files_in(&dir), theirs);
|
||||
|
||||
std::fs::rename(&dir, base.join("lib.theirs")).unwrap();
|
||||
std::fs::rename(&away, &dir).unwrap();
|
||||
journal.snapshot(&catalog).expect("the folder is back");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A file system that numbers its folders anew at every mount (FAT and exFAT on Linux, sshfs) gives
|
||||
/// the folder other numbers: it is the opened folder again while it holds the note this session's
|
||||
/// lock wrote, for every way a store writes, the log's thread included. (A mount can't be faked in
|
||||
/// a test: the numbers the store recorded at open are made different from the folder's.)
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_store_writes_into_a_folder_with_other_numbers_while_the_folder_holds_this_sessions_note() {
|
||||
let dir = scratch("renumbered");
|
||||
let note = b"the note this session's lock wrote";
|
||||
let folder = OpenedFolder::recorded_under_other_numbers(&dir);
|
||||
folder.vouch(note);
|
||||
let mut store = FsStore::in_folder(folder);
|
||||
|
||||
let e = store.write_atomic(SNAPSHOT, b"x").expect_err("other numbers, and no note in the folder");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
assert!(files_in(&dir).is_empty(), "nothing was written");
|
||||
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
store.write_atomic(SNAPSHOT, b"one").expect("the note vouches for the folder");
|
||||
store.write_atomic_with(SNAPSHOT, &mut |w| w.write_all(b"two")).expect("a snapshot written in pieces too");
|
||||
assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), b"two");
|
||||
store.append(LOG, b"1\n").expect("the first append starts the log's thread");
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"1\n");
|
||||
|
||||
// another program's note over this session's: what the thread is handed is held, not written
|
||||
std::fs::write(dir.join(OWNER), b"theirs").unwrap();
|
||||
store.append(LOG, b"2\n").expect("the thread takes it");
|
||||
let e = store.flush().expect_err("the thread can't write it");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"1\n");
|
||||
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
store.flush().expect("this session's note is back: what was held is written");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"1\n2\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A copy of the library's folder (the note in it too) put at the path counts as the opened folder,
|
||||
/// but its log is not the one the log's thread wrote: the thread opens the log by its path for each
|
||||
/// batch and appends only while it is the length the thread left. A log that isn't is refused like a
|
||||
/// failed write (held, reported): not written on through a file kept open in the folder that was
|
||||
/// moved away, where the copy would never get it, and not appended to at its end, where it would
|
||||
/// have a gap. The log reset of a snapshot replaces it and takes what was held.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_log_that_is_not_the_one_the_thread_wrote_is_not_appended_to() {
|
||||
let base = scratch("log-copy");
|
||||
let dir = base.join("lib");
|
||||
let note = b"the note this session's lock wrote";
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.folder().vouch(note);
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
store.append(LOG, b"1\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
|
||||
// a copy made now, which the folder that was opened outgrows, put in its place
|
||||
let copy = base.join("copy");
|
||||
std::fs::create_dir(©).unwrap();
|
||||
for (name, bytes) in files_in(&dir) {
|
||||
std::fs::write(copy.join(name), bytes).unwrap();
|
||||
}
|
||||
store.append(LOG, b"2\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
let away = base.join("away");
|
||||
std::fs::rename(&dir, &away).unwrap();
|
||||
std::fs::rename(©, &dir).unwrap();
|
||||
let (theirs, ours) = (files_in(&dir), files_in(&away));
|
||||
|
||||
store.append(LOG, b"3\n").unwrap();
|
||||
let e = store.flush().expect_err("the log at the path is not the one this session wrote");
|
||||
assert!(e.to_string().contains("holds 2 bytes, the log this session wrote has 4"), "{e}");
|
||||
assert_eq!(files_in(&dir), theirs, "nothing is appended to it");
|
||||
assert_eq!(files_in(&away), ours, "and nothing is written on through a file kept open in the folder that was moved away");
|
||||
assert_eq!(store.unwritten().map(|(n, _)| n), Some(1), "held, not dropped");
|
||||
store.append(LOG, b"4\n").expect("later records are taken: retrying can't heal this, only a replace of the log does");
|
||||
assert_eq!(files_in(&dir), theirs, "and not written either");
|
||||
|
||||
store.write_atomic(LOG, b"tail\n3\n4\n").unwrap();
|
||||
assert_eq!(store.unwritten(), None, "the snapshot's log holds what was held");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n3\n4\n", "the replacement preserves both held records");
|
||||
store.append(LOG, b"5\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n3\n4\n5\n", "and appending goes on");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_is_the_opened_one_while_its_path_leads_to_it() {
|
||||
let dir = scratch("same");
|
||||
let folder = OpenedFolder::at(&dir).unwrap();
|
||||
folder.check().unwrap();
|
||||
std::fs::write(dir.join("catalog.snap"), b"x").unwrap();
|
||||
std::fs::create_dir(dir.join("thumbs")).unwrap();
|
||||
folder.check().expect("what is written in it changes nothing");
|
||||
assert!(folder.same_folder(&folder.clone()));
|
||||
assert_eq!(folder.path(), dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_that_is_not_a_folder_cannot_be_opened() {
|
||||
let dir = scratch("not-a-folder");
|
||||
let file = dir.join("file");
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
assert!(OpenedFolder::at(&file).expect_err("a file").to_string().contains("is not a folder"));
|
||||
assert!(OpenedFolder::at(&dir.join("missing")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A folder that is gone is said to be gone, on every system.
|
||||
#[test]
|
||||
fn a_folder_that_is_gone_is_reported_as_gone() {
|
||||
let base = scratch("gone");
|
||||
let dir = base.join("lib");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let folder = OpenedFolder::at(&dir).unwrap();
|
||||
std::fs::remove_dir(&dir).unwrap();
|
||||
let e = folder.check().expect_err("nothing is there");
|
||||
let msg = e.to_string();
|
||||
assert!(msg.contains(REFUSED) && msg.contains("nothing is there now") && msg.contains(&dir.display().to_string()), "{msg}");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// The reason names the path and what to do; a folder moved and replaced is told from a gone one.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_replaced_folder_is_refused_until_the_opened_one_is_back() {
|
||||
let base = scratch("replaced");
|
||||
let dir = base.join("lib");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let folder = OpenedFolder::at(&dir).unwrap();
|
||||
let away = put_another_folder_at(&dir);
|
||||
let msg = folder.check().expect_err("another folder is at the path").to_string();
|
||||
assert!(msg.contains(REFUSED) && msg.contains("moved or replaced") && msg.contains(&dir.display().to_string()), "{msg}");
|
||||
assert!(msg.contains("put the original folder back"), "{msg}");
|
||||
assert!(!folder.same_folder(&OpenedFolder::at(&dir).unwrap()), "the other folder is another folder");
|
||||
|
||||
std::fs::rename(&dir, base.join("lib.theirs")).unwrap();
|
||||
std::fs::rename(&away, &dir).unwrap();
|
||||
folder.check().expect("the opened folder is back");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A library reached through a link is the folder the link leads to: a link that stays is no
|
||||
/// reason to refuse, and one pointed at another folder is.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_to_the_folder_is_followed() {
|
||||
let base = scratch("link");
|
||||
let (one, two, link) = (base.join("one"), base.join("two"), base.join("link"));
|
||||
std::fs::create_dir(&one).unwrap();
|
||||
std::fs::create_dir(&two).unwrap();
|
||||
std::os::unix::fs::symlink(&one, &link).unwrap();
|
||||
let folder = OpenedFolder::at(&link).unwrap();
|
||||
folder.check().expect("the link still leads to it");
|
||||
std::fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink(&two, &link).unwrap();
|
||||
assert!(folder.check().is_err(), "the link leads to another folder now");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_snapshot_swap_during_fill_cannot_publish_another_librarys_staging_file() {
|
||||
let dir = scratch("stream-swap-publish");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
let mut away = None;
|
||||
let result = store.write_atomic_with(SNAPSHOT, &mut |writer| {
|
||||
writer.write_all(b"our pending snapshot")?;
|
||||
away = Some(put_another_folder_at(&dir));
|
||||
std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"their pending snapshot")?;
|
||||
Ok(())
|
||||
});
|
||||
assert!(result.is_err(), "a folder swapped during a streamed save must be refused");
|
||||
assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), b"their snapshot");
|
||||
assert_eq!(std::fs::read(dir.join(format!("{SNAPSHOT}.tmp"))).unwrap(), b"their pending snapshot");
|
||||
let _ = std::fs::remove_dir_all(away.unwrap());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_snapshot_swap_during_fill_cannot_remove_another_librarys_staging_file() {
|
||||
let dir = scratch("stream-swap-cleanup");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
let mut away = None;
|
||||
let result = store.write_atomic_with(SNAPSHOT, &mut |writer| {
|
||||
writer.write_all(b"our pending snapshot")?;
|
||||
away = Some(put_another_folder_at(&dir));
|
||||
std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"their pending snapshot")?;
|
||||
Err(std::io::Error::other("streaming save failed"))
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), b"their snapshot");
|
||||
assert_eq!(std::fs::read(dir.join(format!("{SNAPSHOT}.tmp"))).unwrap(), b"their pending snapshot");
|
||||
let _ = std::fs::remove_dir_all(away.unwrap());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_caller_append_rolls_back_its_opened_file_not_the_replacement() {
|
||||
let dir = scratch("caller-held-file-rollback");
|
||||
let log = crate::journal::LOG;
|
||||
crate::fault::write_on_caller(&dir, true);
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.append(log, b"first\n").unwrap();
|
||||
crate::fault::install(
|
||||
&dir,
|
||||
std::sync::Arc::new(|step| if step == crate::fault::Step::Sync { Err(std::io::Error::other("injected sync failure")) } else { Ok(()) }),
|
||||
);
|
||||
assert!(store.append(log, b"torn\n").is_err());
|
||||
crate::fault::remove(&dir);
|
||||
let held = dir.join("held.log");
|
||||
std::fs::rename(dir.join(log), &held).unwrap();
|
||||
let replacement = b"other\nextra\n";
|
||||
std::fs::write(dir.join(log), replacement).unwrap();
|
||||
assert!(store.truncate(log, 6).is_err(), "cleanup must refuse the replacement");
|
||||
assert_eq!(std::fs::read(&held).unwrap(), b"first\n", "the retained descriptor must allow rollback on every native platform");
|
||||
assert_eq!(std::fs::read(dir.join(log)).unwrap(), replacement);
|
||||
store.write_atomic(log, b"first\n").unwrap();
|
||||
store.append(log, b"next\n").unwrap();
|
||||
assert_eq!(store.read(log).unwrap().unwrap(), b"first\nnext\n");
|
||||
crate::fault::write_on_caller(&dir, false);
|
||||
drop(store);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_caller_append_reopens_the_file_after_a_note_bearing_copy_replaces_the_folder() {
|
||||
let base = scratch("caller-append-copy");
|
||||
let dir = base.join("lib");
|
||||
let note = b"the note this session's lock wrote";
|
||||
crate::fault::write_on_caller(&dir, true);
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.folder().vouch(note);
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
store.append(LOG, b"1\n").unwrap();
|
||||
let copy = base.join("copy");
|
||||
std::fs::create_dir(©).unwrap();
|
||||
for (name, bytes) in files_in(&dir) {
|
||||
std::fs::write(copy.join(name), bytes).unwrap();
|
||||
}
|
||||
let away = base.join("away");
|
||||
std::fs::rename(&dir, &away).unwrap();
|
||||
std::fs::rename(©, &dir).unwrap();
|
||||
store.append(LOG, b"2\n").unwrap();
|
||||
crate::fault::write_on_caller(&dir, false);
|
||||
assert_eq!(store.read(LOG).unwrap().unwrap(), b"1\n2\n", "the accepted folder must receive the append");
|
||||
assert_eq!(std::fs::read(away.join(LOG)).unwrap(), b"1\n", "the moved-away folder must not receive it");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_caller_append_refuses_a_changed_log_and_a_snapshot_preserves_every_op() {
|
||||
for longer in [false, true] {
|
||||
let base = scratch(&format!("caller-log-length-{longer}"));
|
||||
let dir = base.join("lib");
|
||||
crate::fault::write_on_caller(&dir, true);
|
||||
let store = FsStore::open(&dir).unwrap();
|
||||
let note = b"the note this session's lock wrote";
|
||||
store.folder().vouch(note);
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
let (mut journal, mut catalog, _) = Journal::open(Box::new(store)).unwrap();
|
||||
let add = |n| Op::AddAlbum { album: Album::new(AlbumId(n), format!("album {n}")) };
|
||||
let first = add(1);
|
||||
catalog.apply(first.clone()).unwrap();
|
||||
journal.append(&[first]).unwrap();
|
||||
let copy = base.join("copy");
|
||||
std::fs::create_dir(©).unwrap();
|
||||
for (name, bytes) in files_in(&dir) {
|
||||
std::fs::write(copy.join(name), bytes).unwrap();
|
||||
}
|
||||
let second = add(2);
|
||||
catalog.apply(second.clone()).unwrap();
|
||||
journal.append(&[second]).unwrap();
|
||||
if longer {
|
||||
let mut bytes = std::fs::read(copy.join(LOG)).unwrap();
|
||||
bytes.extend_from_slice(&[b'x'; 4096]);
|
||||
std::fs::write(copy.join(LOG), bytes).unwrap();
|
||||
}
|
||||
let away = base.join("away");
|
||||
std::fs::rename(&dir, &away).unwrap();
|
||||
std::fs::rename(©, &dir).unwrap();
|
||||
let replacement = std::fs::read(dir.join(LOG)).unwrap();
|
||||
let acknowledged = std::fs::read(away.join(LOG)).unwrap();
|
||||
let third = add(3);
|
||||
catalog.apply(third.clone()).unwrap();
|
||||
let result = journal.append(&[third]);
|
||||
crate::fault::write_on_caller(&dir, false);
|
||||
assert!(result.is_err(), "a changed fallback log must not acknowledge a record after a gap");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), replacement, "even the failed-append cleanup must leave the foreign log alone");
|
||||
assert_eq!(std::fs::read(away.join(LOG)).unwrap(), acknowledged);
|
||||
assert!(journal.wants_snapshot(), "the synchronous error requests a snapshot of the live catalog");
|
||||
journal.snapshot_with_unlogged(&catalog, 1).unwrap();
|
||||
let fourth = add(4);
|
||||
catalog.apply(fourth.clone()).unwrap();
|
||||
journal.append(&[fourth]).unwrap();
|
||||
journal.flush().unwrap();
|
||||
drop(journal);
|
||||
let (reopened, loaded, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
assert_eq!(reopened.seq(), 4);
|
||||
for n in 1..=4 {
|
||||
assert_eq!(loaded.album(AlbumId(n)).unwrap().name, format!("album {n}"));
|
||||
}
|
||||
drop(reopened);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_log_open_expectation_survives_a_copy_before_the_first_append() {
|
||||
for caller in [true, false] {
|
||||
let base = scratch(&format!("open-log-copy-{caller}"));
|
||||
let dir = base.join("lib");
|
||||
crate::fault::write_on_caller(&dir, caller);
|
||||
let note = b"the note this session's lock wrote";
|
||||
let open = || {
|
||||
let store = FsStore::open(&dir).unwrap();
|
||||
store.folder().vouch(note);
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
Journal::open(Box::new(store)).unwrap()
|
||||
};
|
||||
let add = |n| Op::AddAlbum { album: Album::new(AlbumId(n), format!("album {n}")) };
|
||||
let (mut seed, mut catalog, _) = open();
|
||||
let first = add(1);
|
||||
catalog.apply(first.clone()).unwrap();
|
||||
seed.append(&[first]).unwrap();
|
||||
seed.flush().unwrap();
|
||||
let copy = base.join("copy");
|
||||
std::fs::create_dir(©).unwrap();
|
||||
for (name, bytes) in files_in(&dir) {
|
||||
std::fs::write(copy.join(name), bytes).unwrap();
|
||||
}
|
||||
let second = add(2);
|
||||
catalog.apply(second.clone()).unwrap();
|
||||
seed.append(&[second]).unwrap();
|
||||
seed.flush().unwrap();
|
||||
drop(seed);
|
||||
let (mut journal, mut catalog, _) = open();
|
||||
std::fs::rename(&dir, base.join("away")).unwrap();
|
||||
std::fs::rename(©, &dir).unwrap();
|
||||
let replacement = std::fs::read(dir.join(LOG)).unwrap();
|
||||
let third = add(3);
|
||||
catalog.apply(third.clone()).unwrap();
|
||||
let result = journal.append(&[third]);
|
||||
let unlogged = u64::from(result.is_err());
|
||||
let refused = result.is_err() || journal.flush().is_err();
|
||||
crate::fault::write_on_caller(&dir, false);
|
||||
assert!(refused, "the first append must use the log length read at open");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), replacement);
|
||||
journal.snapshot_with_unlogged(&catalog, unlogged).unwrap();
|
||||
drop(journal);
|
||||
let (reopened, loaded, _) = open();
|
||||
assert_eq!(reopened.seq(), 3);
|
||||
for n in 1..=3 {
|
||||
assert!(loaded.album(AlbumId(n)).is_some(), "every acknowledged and unlogged op must reload");
|
||||
}
|
||||
drop(reopened);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_log_sync_failure_can_only_roll_back_the_file_that_failed() {
|
||||
for caller in [true, false] {
|
||||
let base = scratch(&format!("failed-log-copy-{caller}"));
|
||||
let dir = base.join("lib");
|
||||
crate::fault::write_on_caller(&dir, caller);
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
let note = b"the note this session's lock wrote";
|
||||
store.folder().vouch(note);
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
store.append(LOG, b"1\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
let copy = base.join("copy");
|
||||
std::fs::create_dir(©).unwrap();
|
||||
let foreign = b"this is a longer log whose records must not be removed\n";
|
||||
std::fs::write(copy.join(LOG), foreign).unwrap();
|
||||
std::fs::write(copy.join(OWNER), note).unwrap();
|
||||
let dir_for_hook = dir.clone();
|
||||
let away = base.join("away");
|
||||
let away_for_hook = away.clone();
|
||||
let swapped = std::sync::atomic::AtomicBool::new(false);
|
||||
crate::fault::install(
|
||||
&dir,
|
||||
std::sync::Arc::new(move |step| {
|
||||
if step == crate::fault::Step::Sync {
|
||||
if !swapped.swap(true, std::sync::atomic::Ordering::SeqCst) {
|
||||
std::fs::rename(&dir_for_hook, &away_for_hook)?;
|
||||
std::fs::rename(©, &dir_for_hook)?;
|
||||
}
|
||||
return Err(std::io::Error::other("injected failed sync"));
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
);
|
||||
let result = store.append(LOG, b"2\n");
|
||||
if caller {
|
||||
assert!(result.is_err());
|
||||
assert!(store.truncate(LOG, 2).is_err(), "cleanup must refuse the replacement log");
|
||||
} else {
|
||||
result.unwrap();
|
||||
assert!(store.flush().is_err());
|
||||
assert!(store.truncate(LOG, 2).is_err(), "cleanup must refuse the replacement log");
|
||||
}
|
||||
crate::fault::remove(&dir);
|
||||
crate::fault::write_on_caller(&dir, false);
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), foreign, "a torn-tail rollback must never touch the replacement");
|
||||
assert_eq!(std::fs::read(away.join(LOG)).unwrap(), b"1\n", "only our own failed append is rolled back");
|
||||
store.write_atomic(LOG, b"tail\n1\n2\n").unwrap();
|
||||
store.append(LOG, b"3\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n1\n2\n3\n");
|
||||
drop(store);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_log_read_for_repair_does_not_permit_truncating_a_shorter_copy() {
|
||||
let base = scratch("read-repair-copy");
|
||||
let dir = base.join("lib");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
let note = b"the note this session's lock wrote";
|
||||
store.folder().vouch(note);
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
std::fs::write(dir.join(LOG), b"good\ntorn").unwrap();
|
||||
assert_eq!(store.read(LOG).unwrap().unwrap(), b"good\ntorn");
|
||||
let copy = base.join("copy");
|
||||
std::fs::create_dir(©).unwrap();
|
||||
std::fs::write(copy.join(OWNER), note).unwrap();
|
||||
std::fs::write(copy.join(LOG), b"x\n").unwrap();
|
||||
let away = base.join("away");
|
||||
std::fs::rename(&dir, &away).unwrap();
|
||||
std::fs::rename(©, &dir).unwrap();
|
||||
assert!(store.truncate(LOG, 5).is_err(), "initial repair must use the length read, not extend a replacement");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"x\n");
|
||||
assert_eq!(std::fs::read(away.join(LOG)).unwrap(), b"good\ntorn");
|
||||
store.write_atomic(LOG, b"whole\n").unwrap();
|
||||
store.append(LOG, b"next\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"whole\nnext\n");
|
||||
drop(store);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_replaced_staging_name_is_neither_published_nor_removed() {
|
||||
for fail_fill in [false, true] {
|
||||
let dir = scratch(&format!("staging-name-{fail_fill}"));
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.write_atomic(SNAPSHOT, b"committed snapshot").unwrap();
|
||||
let tmp = dir.join(format!("{SNAPSHOT}.tmp"));
|
||||
let result = store.write_atomic_with(SNAPSHOT, &mut |writer| {
|
||||
writer.write_all(b"our pending snapshot")?;
|
||||
std::fs::remove_file(&tmp)?;
|
||||
std::fs::write(&tmp, b"another save's staging file")?;
|
||||
if fail_fill { Err(std::io::Error::other("stream failed")) } else { Ok(()) }
|
||||
});
|
||||
assert!(result.is_err(), "a staging name no longer belonging to this save must be refused");
|
||||
assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), b"committed snapshot");
|
||||
assert_eq!(std::fs::read(&tmp).unwrap(), b"another save's staging file");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::journal::LOG;
|
||||
use crate::journal::{LOG, RESYNC_CANDIDATES};
|
||||
use crate::*;
|
||||
|
||||
/// A store whose next append writes only a prefix of its data, then fails.
|
||||
@@ -88,6 +88,9 @@ fn partial_append_then_retry_loads_cleanly() {
|
||||
assert!(j.append(&batch).is_err(), "tear at {tear}");
|
||||
// cut back to the last whole record
|
||||
assert_eq!(t.files.get(LOG).unwrap().len(), good_len, "tear at {tear}");
|
||||
// and a snapshot is due (records handed over before may be missing from a log written
|
||||
// by a thread of its own: note 2 of 2026-10-25)
|
||||
assert!(j.wants_snapshot(), "tear at {tear}");
|
||||
j.append(&batch).unwrap();
|
||||
let more = apply(&mut c, vec![Op::SetLabel { id, label: Some(ColorLabel::ALL[0]) }]);
|
||||
j.append(&more).unwrap();
|
||||
@@ -221,3 +224,208 @@ fn fs_store_truncates_a_missing_file_quietly() {
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Issue #2124: `resync` must be linear in the line length, not quadratic. A line that is nothing
|
||||
/// but the start marker repeated 300k times must open fast, and a valid retry record placed after
|
||||
/// it must still be recovered.
|
||||
#[test]
|
||||
fn resync_is_not_quadratic_in_line_length() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
// Build a valid snapshot + an initial record so `j.seq()` is non-zero and the `seq <= last + 1`
|
||||
// gate in resync can be exercised.
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
let first = apply(&mut c, vec![add]);
|
||||
j.append(&first).unwrap();
|
||||
|
||||
let log = probe.get(LOG).unwrap();
|
||||
let base_len = log.len();
|
||||
|
||||
// A hostile 300k-repetition marker line (about 2.3 MB), then one valid retried record that
|
||||
// continues the log (seq == j.seq() + 1, so resync's gate accepts it).
|
||||
let marker = b"{\"seq\":";
|
||||
let mut hostile = Vec::with_capacity(marker.len() * 300_000 + log.len() + 256);
|
||||
hostile.extend_from_slice(&log[..base_len]);
|
||||
for _ in 0..300_000 {
|
||||
hostile.extend_from_slice(marker);
|
||||
}
|
||||
|
||||
// Encode the retry record the same way the journal writes records, so decode_record accepts it.
|
||||
let next_seq = j.seq() + 1;
|
||||
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
|
||||
hostile.extend_from_slice(retry.as_bytes());
|
||||
|
||||
probe.set(LOG, hostile);
|
||||
|
||||
// Count the start markers resync decodes instead of timing it: a slow worker must not fail this.
|
||||
RESYNC_CANDIDATES.with(|c| c.set(0));
|
||||
let (j2, _c2, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|c| c.get());
|
||||
assert!(candidates <= 1, "resync decoded {candidates} start markers of a hostile 2 MB line; only the last one may be decoded");
|
||||
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
|
||||
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
|
||||
}
|
||||
|
||||
/// A retry record whose op body holds a nested `{"seq":` (a smart-album rule value such as
|
||||
/// `{"seq":1}` on a `title isEmpty` rule) shadows the record's own start marker: `rposition` in
|
||||
/// `resync` picks the nested occurrence, `decode_record` rejects the suffix, and `Journal::open`
|
||||
/// truncates the final line instead of replaying the retry — the valid operation is lost.
|
||||
#[test]
|
||||
fn resync_preserves_retry_record_with_nested_start_marker() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
|
||||
let album_id = c.alloc_album_id();
|
||||
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
|
||||
j.append(&apply(&mut c, vec![add_album])).unwrap();
|
||||
|
||||
let retry_op = Op::SetAlbumRules {
|
||||
id: album_id,
|
||||
rules: Box::new(Filter {
|
||||
rule_set: Some(RuleSet {
|
||||
mode: Match::All,
|
||||
rules: vec![Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }],
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
apply(&mut c, vec![retry_op.clone()]);
|
||||
|
||||
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
|
||||
// resync finds its real start: `seq` continues the log and the CRC matches the body.
|
||||
let next_seq = j.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
|
||||
|
||||
// A torn fragment glued to the retry on the final line. The outer record start sits right
|
||||
// after the fragment, but the last `{"seq":` byte occurrence is the nested rule value.
|
||||
let mut log = probe.get(LOG).unwrap();
|
||||
log.extend_from_slice(b"torn fragment without a newline");
|
||||
log.extend_from_slice(retry.as_bytes());
|
||||
probe.set(LOG, log);
|
||||
|
||||
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
|
||||
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
|
||||
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be truncated as torn");
|
||||
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the recovered smart-album rule should be preserved");
|
||||
}
|
||||
|
||||
/// The maintainer's regression for issue #2124, with the damaged line as the file's LAST one: a
|
||||
/// torn fragment glued to a CRC-valid `SetAlbumRules` retry whose rules hold several nested
|
||||
/// `{"seq":1}` values. Picking the last raw `{"seq":` occurrence as the record start (as the
|
||||
/// original `rposition` scan did) lands in a nested value, rejects the whole record, and cuts the
|
||||
/// final line away — losing the valid operation. `resync` must recover the retry (its real start
|
||||
/// is followed by the `,"crc":` header no nested rule value has) and leave the log file whole.
|
||||
#[test]
|
||||
fn resync_recovers_rules_retry_with_many_nested_values_on_the_final_line() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
|
||||
let album_id = c.alloc_album_id();
|
||||
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
|
||||
j.append(&apply(&mut c, vec![add_album])).unwrap();
|
||||
|
||||
let rules =
|
||||
(0..12).map(|_| Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }).collect::<Vec<_>>();
|
||||
let retry_op =
|
||||
Op::SetAlbumRules { id: album_id, rules: Box::new(Filter { rule_set: Some(RuleSet { mode: Match::All, rules }), ..Default::default() }) };
|
||||
apply(&mut c, vec![retry_op.clone()]);
|
||||
|
||||
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
|
||||
// resync finds its real start: `seq` continues the log and the CRC matches the body.
|
||||
let next_seq = j.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}");
|
||||
|
||||
// The failed append's fragment glued to the retry, and nothing after: the damaged line is the
|
||||
// file's last, without a closing newline.
|
||||
let mut log = probe.get(LOG).unwrap();
|
||||
log.extend_from_slice(b"torn fragment without a newline");
|
||||
log.extend_from_slice(retry.as_bytes());
|
||||
let damaged = log.clone();
|
||||
probe.set(LOG, log);
|
||||
|
||||
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
assert_eq!(report.torn_fragments, 1, "the fragment must be reported and the retry recovered");
|
||||
assert_eq!(report.torn_bytes, 0, "the retry record must not be cut away as a torn tail");
|
||||
assert_eq!(j2.seq(), next_seq, "the retried SetAlbumRules must be recovered");
|
||||
assert_eq!(report.replayed, 3);
|
||||
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the smart-album rules must survive the reload");
|
||||
|
||||
// The log file is preserved: its bytes stay (plus only the newline that closes the final
|
||||
// line), instead of the damaged line being truncated away.
|
||||
let after = probe.get(LOG).unwrap();
|
||||
assert_eq!(after.len(), damaged.len() + 1, "the log must keep the fragment and the recovered record");
|
||||
assert_eq!(&after[..damaged.len()], &damaged[..]);
|
||||
}
|
||||
|
||||
/// A crafted final line of many header-shaped markers (`{"seq":1,"crc":2,"op":`) passes the
|
||||
/// record-header filter, so every marker becomes a resync candidate, and each attempt decodes the
|
||||
/// whole rest of the line: trying all of them is quadratic in the line length, a stall of
|
||||
/// `Journal::open` on a hostile log (CWE-407). The per-line scan budget must bound the candidate
|
||||
/// decodes (counted, not timed) and open must still finish safely. A CRC-valid retry placed after
|
||||
/// the junk must stay recoverable: it is the last candidate, so the scan reaches it first.
|
||||
#[test]
|
||||
fn resync_scan_budget_bounds_a_line_of_header_shaped_markers() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
let good = probe.get(LOG).unwrap();
|
||||
|
||||
const MARKERS: usize = 5_000;
|
||||
let marker: &[u8] = b"{\"seq\":1,\"crc\":2,\"op\":";
|
||||
let mut hostile = good.clone();
|
||||
hostile.extend_from_slice(b"torn fragment"); // so no marker sits at line position 0
|
||||
for _ in 0..MARKERS {
|
||||
hostile.extend_from_slice(marker);
|
||||
}
|
||||
let hostile_len = (hostile.len() - good.len()) as u64;
|
||||
probe.set(LOG, hostile);
|
||||
|
||||
RESYNC_CANDIDATES.with(|count| count.set(0));
|
||||
let (j2, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
|
||||
assert!(
|
||||
candidates < MARKERS,
|
||||
"resync tried all {candidates} candidates of a hostile {hostile_len}-byte line; the scan budget must bound the work"
|
||||
);
|
||||
assert!(report.damaged.is_none(), "{report:?}");
|
||||
assert_eq!(report.torn_fragments, 0);
|
||||
assert_eq!(report.torn_bytes, hostile_len, "the hostile line must be dropped as a torn tail");
|
||||
assert_eq!(j2.seq(), 1, "the records before the hostile line must survive");
|
||||
assert_eq!(probe.get(LOG).unwrap().len(), good.len(), "the log must be cut back to the last good record");
|
||||
|
||||
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
|
||||
let next_seq = j2.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let mut log = good.clone();
|
||||
for _ in 0..MARKERS {
|
||||
log.extend_from_slice(marker);
|
||||
}
|
||||
log.extend_from_slice(format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n").as_bytes());
|
||||
probe.set(LOG, log);
|
||||
|
||||
RESYNC_CANDIDATES.with(|count| count.set(0));
|
||||
let (j3, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
|
||||
assert_eq!(candidates, 1, "the retry is the last candidate and must decode first");
|
||||
assert_eq!(j3.seq(), next_seq, "the retried record after the junk must be recovered");
|
||||
assert_eq!(report.torn_fragments, 1, "the junk before the retry is one skipped fragment");
|
||||
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be cut away");
|
||||
}
|
||||
@@ -55,5 +55,8 @@ fn a_file_path_rule_allocates_nothing_per_photo() {
|
||||
}
|
||||
let blocks = dhat::HeapStats::get().total_blocks - before;
|
||||
assert!(hits > 0, "the rules matched nothing: the test measures nothing");
|
||||
assert_eq!(blocks, 0, "{blocks} heap blocks for {} rule tests", 100 * rules.len() * photos.len());
|
||||
// dhat counts every thread, and the test harness's own thread can allocate a few blocks while this
|
||||
// runs. An allocation per photo would be thousands, two per rule test.
|
||||
let tests = 100 * rules.len() * photos.len();
|
||||
assert!(blocks < 64, "{blocks} heap blocks for {tests} rule tests");
|
||||
}
|
||||
+22
-26
@@ -12,49 +12,45 @@ workspace = true
|
||||
lightcraft-geom = { workspace = true }
|
||||
lightcraft-color = { workspace = true }
|
||||
lightcraft-raster = { workspace = true }
|
||||
lightcraft-heif = { workspace = true, optional = true }
|
||||
craft-gainmap = { workspace = true }
|
||||
craft-cms = { workspace = true }
|
||||
craft-jpeg = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
craft-metadata = { workspace = true }
|
||||
craft-tiff = { workspace = true }
|
||||
craft-gif = { workspace = true }
|
||||
craft-psd = { workspace = true }
|
||||
craft-heif = { workspace = true, optional = true, features = ["decode"] }
|
||||
serde = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
rayon = { workspace = true, optional = true }
|
||||
image = { workspace = true, features = ["gif", "bmp"] }
|
||||
zune-jpeg = { workspace = true }
|
||||
zune-core = { workspace = true }
|
||||
jpeg-decoder = { workspace = true }
|
||||
jpeg-encoder = { workspace = true }
|
||||
png = { workspace = true }
|
||||
tiff = { workspace = true }
|
||||
image-webp = { workspace = true }
|
||||
moxcms = { workspace = true }
|
||||
jxl-oxide = { workspace = true, optional = true }
|
||||
craft-jxl = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
ravif = { workspace = true, optional = true }
|
||||
rav1e = { workspace = true, optional = true }
|
||||
avif-serialize = { workspace = true, optional = true }
|
||||
# spawns threads of its own (std::thread), which wasm32 has not got
|
||||
jixel = { workspace = true, optional = true }
|
||||
craft-video = { workspace = true, optional = true }
|
||||
craft-avif-encode = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
default = ["parallel", "jxl", "avif"]
|
||||
parallel = ["dep:rayon", "lightcraft-raster/parallel", "jpeg-decoder/rayon"]
|
||||
## JPEG XL decode (jxl-oxide) and, on native targets, encode (jixel); both pure Rust.
|
||||
jxl = ["dep:jxl-oxide", "dep:jixel"]
|
||||
# HEIC/HEIF decode via the optional lightcraft-heif crate (heic-rs, pure Rust). Off by default so
|
||||
parallel = ["dep:rayon", "lightcraft-raster/parallel", "craft-jpeg/parallel"]
|
||||
## JPEG XL decoding and encoding via the shared craft-jxl codec.
|
||||
jxl = ["dep:craft-jxl"]
|
||||
# HEIC/HEIF decode via the optional craft-heif crate (heic-rs, pure Rust). Off by default so
|
||||
# distributors choose it at build time (HEVC patents are a distributor's call, same policy as
|
||||
# PhotoCraft); `cargo xtask ci` clippies and tests it (`--features heif`), releases don't ship it yet.
|
||||
heif = ["dep:lightcraft-heif"]
|
||||
## AVIF encoding via ravif/rav1e (pure Rust, BSD). Native targets only; a no-op on wasm32.
|
||||
avif = ["dep:ravif", "dep:rav1e", "dep:avif-serialize"]
|
||||
heif = ["dep:craft-heif"]
|
||||
## AVIF/AV1 encoding via craft-image-codecs / craft-video (pure Rust), plus the shared AVIF decoder. Native targets only; a no-op on wasm32.
|
||||
avif = ["dep:craft-video", "dep:craft-avif-encode", "craft-image-codecs/avif-decode"]
|
||||
|
||||
[dev-dependencies]
|
||||
# tests record why they skip (`cargo xtask ci` lists the skips)
|
||||
lightcraft-testkit = { workspace = true }
|
||||
# JPEG XL tests read encoded samples without our colour conversion
|
||||
jxl-oxide = { workspace = true }
|
||||
# JPEG parity tests and the benchmark use the prior/reference encoder only in development.
|
||||
jpeg-encoder = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# Lossless synthetic HEIC files for the `heif` feature's tests.
|
||||
lightcraft-heif = { workspace = true, features = ["testdata"] }
|
||||
craft-heif = { workspace = true, features = ["testdata"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
dhat = { workspace = true }
|
||||
+10
-9
@@ -46,15 +46,15 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d
|
||||
|
||||
| Format | Decode | Encode | Notes |
|
||||
|---|---|---|---|
|
||||
| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (jpeg-encoder, baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2; only complete, consistently counted, uniquely numbered chunk sequences are assembled; malformed profiles use the existing unsupported-profile fallback), Adobe APP14, MPF previews |
|
||||
| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (shared `craft-jpeg`, optimized baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2; only complete, consistently counted, uniquely numbered chunk sequences are assembled; malformed profiles use the existing unsupported-profile fallback), Adobe APP14, MPF previews |
|
||||
| PNG | yes, 1–16-bit, palette, tRNS, interlaced | 8/16-bit, gray/GA/RGB/RGBA | iCCP, eXIf, iTXt XMP; sRGB/cICP/cHRM/gAMA honoured when no ICC |
|
||||
| TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `lightcraft-tiff`) |
|
||||
| TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `craft-tiff`) |
|
||||
| WebP | lossy + lossless, alpha, first frame of animations | lossless only | ICCP/EXIF/XMP chunks |
|
||||
| GIF / BMP | yes (first GIF frame) | — | via `image` |
|
||||
| PSD / PSB | merged composite: 8/16/32-bit gray, RGB, CMYK, indexed, duotone (as gray); raw/RLE | — | ICC (1039), EXIF (1058), XMP (1060); ZIP-compressed composite, Lab and 1-bit unsupported |
|
||||
| JPEG XL | yes (jxl-oxide, feature `jxl`, default on) | yes (jixel, `encode_jxl`, feature `jxl`, native only): lossy VarDCT / lossless Modular, 8/16-bit, effort (fast / normal), progressive; HDR as 16-bit Rec. 2020 PQ | decode: enum colour → rendered straight to linear Rec.2020 (XYB via linear sRGB primaries); ICC → our ICC path; orientation applied by the decoder (reported as 1). Encode: lossy files declare an enum encoding (sRGB, Display P3, Rec. 2020 BT.709 curve, Rec. 2020 PQ), lossless ones embed the ICC profile; EXIF / XMP in `Exif` / `xml ` boxes |
|
||||
| JPEG XL | yes (`craft-jxl`, feature `jxl`, default on) | yes (`craft-jxl`, `encode_jxl`, feature `jxl`, native only): lossy VarDCT / lossless Modular, 8/16-bit, effort (fast / normal), progressive; HDR as 16-bit Rec. 2020 PQ | decode: enum colour → rendered straight to linear Rec.2020 (XYB via linear sRGB primaries); ICC → our ICC path; orientation applied by the shared decoder (reported as 1). Encode: lossy files declare an enum encoding (sRGB, Display P3, Rec. 2020 BT.709 curve, Rec. 2020 PQ), lossless ones embed the ICC profile; EXIF / XMP in `Exif` / `xml ` boxes |
|
||||
| AVIF | **no** | yes (ravif/rav1e, native only, feature `avif`) | 8/10-bit sRGB, EXIF; no ICC in the muxer. HDR: `encode_avif_hdr` writes 10-bit BT.2020 PQ (SDR white at 203 cd/m², CICP `nclx` + `clli`) or HLG (`hlg_signal`, SDR white at 0.75) |
|
||||
| HEIC/HEIF | yes with feature `heif` (lightcraft-heif: heic-rs + libheif-matching colour; 4:2:0/mono, 8–10-bit, grids, irot/imir/clap, ICC/nclx/VUI, EXIF/XMP, thumbnail item) | — | 4:2:2/4:4:4 (Canon/Sony HIF) unsupported |
|
||||
| HEIC/HEIF | yes with feature `heif` (craft-heif: heic-rs + libheif-matching colour; 4:2:0/mono, 8–10-bit, grids, irot/imir/clap, ICC/nclx/VUI, EXIF/XMP, thumbnail item) | — | 4:2:2/4:4:4 (Canon/Sony HIF) unsupported |
|
||||
| Gain map JPEG (HDR) | gain map found and decoded (`gainmap::read_jpeg`): ISO 21496-1 metadata, else Adobe `hdrgm` XMP | yes (`gainmap::encode_jpeg`) | CIPA DC-007 MPF index (gain map typed `0x050000`), ISO 21496-1 APP2 on both images, `hdrgm` + Container XMP for Android/Chrome, Apple `HDRGainMap`/`HDRToneMap` XMP; gain maps are never used as thumbnails |
|
||||
|
||||
## Colour
|
||||
@@ -85,14 +85,15 @@ All pure Rust, verified with `cargo info` / `cargo tree`:
|
||||
|---|---|---|
|
||||
| zune-jpeg, zune-core | MIT OR Apache-2.0 OR Zlib | JPEG decode |
|
||||
| jpeg-decoder | MIT OR Apache-2.0 | scaled / CMYK JPEG decode |
|
||||
| jpeg-encoder | (MIT OR Apache-2.0) AND IJG | JPEG encode (IJG: permissive, attribution in docs) |
|
||||
| craft-jpeg | MIT OR Apache-2.0 | baseline JPEG encode (shared craft-libs) |
|
||||
| jpeg-encoder | (MIT OR Apache-2.0) AND IJG | 0.6 still ships inside `craft-image-codecs` (IJG: permissive, attribution in docs); 0.7 only in tests and the JPEG benchmark (reference CMYK fixture, prior 4:2:2 output) |
|
||||
| png | MIT OR Apache-2.0 | PNG |
|
||||
| tiff | MIT | TIFF |
|
||||
| image-webp | MIT OR Apache-2.0 | WebP |
|
||||
| image (gif, bmp only) | MIT OR Apache-2.0 | GIF/BMP |
|
||||
| moxcms | BSD-3-Clause OR Apache-2.0 | ICC parse/write, CMS |
|
||||
| jxl-oxide | MIT OR Apache-2.0 | JPEG XL decode |
|
||||
| jixel | BSD-3-Clause OR Apache-2.0 | JPEG XL encode (native only) |
|
||||
| craft-jxl | MIT OR Apache-2.0 | JPEG XL decode/encode (shared craft-libs) |
|
||||
| jxl-oxide | MIT OR Apache-2.0 | JPEG XL test oracle only |
|
||||
| ravif (+ rav1e, avif-serialize) | BSD-3-Clause / BSD-2-Clause | AVIF encode (native only; heavy to compile) |
|
||||
|
||||
Deliberately **not** used: anything AGPL from imazen (heic, zenjpeg, jxl-encoder, rav1d-safe),
|
||||
@@ -113,8 +114,8 @@ Run `cargo test --release -p lightcraft-codecs --test it bench:: -- --ignored --
|
||||
|
||||
## Gaps / limitations
|
||||
|
||||
- **AVIF decode**: no permissively licensed, pure-Rust AV1 decoder exists today (dav1d is C;
|
||||
rav1d-safe is AGPL). Files are sniffed and rejected with `Error::Unsupported`.
|
||||
- **AVIF decode** uses the shared pure-Rust AV1 decoder on native builds with the `avif` feature.
|
||||
Animated AVIF, depth and gain-map auxiliary images, and progressive/layered images are unsupported.
|
||||
- **HEIC** needs the `heif` feature (off by default: HEVC patents are the distributor's call);
|
||||
without it, `Error::Unsupported` says the build has no HEIC support. 4:2:2 and 4:4:4 HEIF
|
||||
(Canon/Sony HIF) is refused: heic-rs 0.1.1 loses sync on those bitstreams.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Compare the parallel JPEG encoder with `jpeg-encoder` (size, time, PSNR):
|
||||
//! Compare the shared JPEG encoder with `jpeg-encoder` (size, time, PSNR):
|
||||
//! `cargo run --release -p lightcraft-codecs --example jpeg_bench [image]` (default: 6000×4000 synthetic).
|
||||
use lightcraft_codecs::ChromaSubsampling;
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
use std::time::Instant;
|
||||
|
||||
fn psnr(a: &[u8], b: &[u8]) -> f64 {
|
||||
@@ -23,8 +23,10 @@ fn best<T>(n: usize, mut f: impl FnMut() -> T) -> (T, f64) {
|
||||
fn main() {
|
||||
let (w, h, rgb) = match std::env::args().nth(1) {
|
||||
Some(p) => {
|
||||
let img = image::open(p).expect("open").to_rgb8();
|
||||
(img.width() as usize, img.height() as usize, img.into_raw())
|
||||
let bytes = std::fs::read(p).expect("read");
|
||||
let img = lightcraft_codecs::decode(&bytes, lightcraft_codecs::DecodeOptions::default()).expect("open").to_srgb8();
|
||||
let rgb = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect();
|
||||
(img.width as usize, img.height as usize, rgb)
|
||||
}
|
||||
None => {
|
||||
let (w, h) = (6000, 4000);
|
||||
@@ -41,7 +43,8 @@ fn main() {
|
||||
for (sub, js) in
|
||||
[(ChromaSubsampling::S444, jpeg_encoder::SamplingFactor::R_4_4_4), (ChromaSubsampling::S420, jpeg_encoder::SamplingFactor::R_4_2_0)]
|
||||
{
|
||||
let (ours, t_ours) = best(5, || lightcraft_codecs::jpeg_par::encode(&rgb, w, h, 3, 90, sub, &[]));
|
||||
let img = EncodeImage::new(w as u32, h as u32, 3, Samples::U8(&rgb));
|
||||
let (ours, t_ours) = best(5, || encode_jpeg(&img, 90, sub, &EncodeMeta::default()).expect("shared JPEG encoder"));
|
||||
let (theirs, t_theirs) = best(3, || {
|
||||
let mut out = Vec::new();
|
||||
let mut e = jpeg_encoder::Encoder::new(&mut out, 90);
|
||||
@@ -49,9 +52,17 @@ fn main() {
|
||||
e.encode(&rgb, w as u16, h as u16, jpeg_encoder::ColorType::Rgb).unwrap();
|
||||
out
|
||||
});
|
||||
let dec = |b: &[u8]| jpeg_decoder::Decoder::new(b).decode().unwrap();
|
||||
let dec = |b: &[u8]| {
|
||||
lightcraft_codecs::decode(b, lightcraft_codecs::DecodeOptions::default())
|
||||
.unwrap()
|
||||
.to_srgb8()
|
||||
.data
|
||||
.into_iter()
|
||||
.flat_map(|p| [p[0], p[1], p[2]])
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
println!(
|
||||
"{w}x{h} {sub:?} q90: parallel {t_ours:.0} ms, {} KB, PSNR {:.2} dB | jpeg-encoder {t_theirs:.0} ms, {} KB, PSNR {:.2} dB",
|
||||
"{w}x{h} {sub:?} q90: craft-jpeg {t_ours:.0} ms, {} KB, PSNR {:.2} dB | jpeg-encoder {t_theirs:.0} ms, {} KB, PSNR {:.2} dB",
|
||||
ours.len() / 1024,
|
||||
psnr(&rgb, &dec(&ours)),
|
||||
theirs.len() / 1024,
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! AVIF container and pixel decoding via shared image codecs.
|
||||
use crate::{DecodeOptions, Decoded, Error, Format, Result};
|
||||
|
||||
const F: Format = Format::Avif;
|
||||
|
||||
#[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))]
|
||||
pub(crate) fn header(_: &[u8]) -> Result<(u32, u32, u16)> {
|
||||
Err(Error::Unsupported(F, "AVIF decoding is not included in this build"))
|
||||
}
|
||||
#[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))]
|
||||
pub(crate) fn decode(_: &[u8], _: &DecodeOptions) -> Result<Decoded> {
|
||||
Err(Error::Unsupported(F, "AVIF decoding is not included in this build"))
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
fn err(e: craft_image_codecs::CodecError) -> Error {
|
||||
match e {
|
||||
craft_image_codecs::CodecError::LimitExceeded(_) => Error::TooLarge(0, 0),
|
||||
craft_image_codecs::CodecError::Unsupported { .. } => Error::Unsupported(F, "unsupported AVIF"),
|
||||
other => Error::Malformed(F, other.to_string()),
|
||||
}
|
||||
}
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> {
|
||||
let (w, h) = craft_image_codecs::probe_size(bytes).map_err(err)?;
|
||||
Ok((w, h, 1))
|
||||
}
|
||||
// Match craft-video's AV1 store: 128-sample superblocks plus 160 samples of edge padding,
|
||||
// three u16 planes, eight references, the current picture, and at most eight workers + two
|
||||
// in-flight pictures. Keep a hard byte ceiling even when the caller permits many pixels.
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
fn picture_store_budget(width: u32, height: u32) -> u64 {
|
||||
let padded = |n: u32| u64::from(n).div_ceil(128) * 128 + 160;
|
||||
padded(width).saturating_mul(padded(height)).saturating_mul(PICTURE_STORE_BYTES_PER_SAMPLE).min(PICTURE_STORE_CAP)
|
||||
}
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
const PICTURE_STORE_BYTES_PER_SAMPLE: u64 = 3 * 2 * (8 + 1 + 8 + 2);
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
const PICTURE_STORE_CAP: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 };
|
||||
|
||||
/// The picture-store budget for any stored AV1 canvas the pixel limit admits. `probe_size` reports
|
||||
/// the size after `clap`, but the decoder builds the stored (pre-crop) canvas, which the shared
|
||||
/// decoder checks against `max_pixels` from its `ispe` before decoding. A canvas of at most
|
||||
/// `max_pixels` samples with AV1's 65,536-sample edge limit has `w + h <= min(max_pixels + 1, 2^17)`,
|
||||
/// and each padded edge is under `edge + 288`, so the padded area is below
|
||||
/// `max_pixels + 288 * (w + h) + 288^2`.
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
fn stored_picture_store_budget(max_pixels: u64) -> u64 {
|
||||
let edge_sum = max_pixels.saturating_add(1).min(2 * 65_536);
|
||||
let area = max_pixels.saturating_add(edge_sum.saturating_mul(288)).saturating_add(288 * 288);
|
||||
area.saturating_mul(PICTURE_STORE_BYTES_PER_SAMPLE).min(PICTURE_STORE_CAP)
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
|
||||
use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
|
||||
use crate::space::SourceSpace;
|
||||
let (w, h, _) = header(bytes)?;
|
||||
check_size(F, w as u64, h as u64, opts)?;
|
||||
let options = craft_image_codecs::DecodeOptions {
|
||||
limits: craft_image_codecs::Limits {
|
||||
max_width: u32::MAX,
|
||||
max_height: u32::MAX,
|
||||
max_pixels: opts.max_pixels,
|
||||
max_alloc: stored_picture_store_budget(opts.max_pixels).max(picture_store_budget(w, h)),
|
||||
},
|
||||
keep_orientation: false,
|
||||
};
|
||||
let (img, bit_depth) = craft_image_codecs::decode_avif_with_depth(bytes, &options).map_err(err)?;
|
||||
let (w, h) = (img.width(), img.height());
|
||||
check_size(F, w as u64, h as u64, opts)?;
|
||||
let buf = match img.sample_type() {
|
||||
craft_image_codecs::SampleType::U8 => Buf::U8(img.as_u8().ok_or_else(|| Error::Malformed(F, "expected 8-bit samples".into()))?.to_vec()),
|
||||
craft_image_codecs::SampleType::U16 => Buf::U16(img.to_u16_samples().ok_or_else(|| Error::Malformed(F, "expected 16-bit samples".into()))?),
|
||||
craft_image_codecs::SampleType::F32 => Buf::F32(img.to_f32_samples().ok_or_else(|| Error::Malformed(F, "expected float samples".into()))?),
|
||||
_ => return Err(Error::Unsupported(F, "unsupported AVIF sample type")),
|
||||
};
|
||||
let hint = img.cicp.and_then(|c| SourceSpace::from_cicp(c.primaries, c.transfer));
|
||||
let raw = Raw { width: w as usize, height: h as usize, model: Model::Rgb, alpha: img.layout().has_alpha(), premultiplied: false, buf, bit_depth };
|
||||
let meta = Meta { icc: img.icc, exif: img.meta.exif, xmp: img.meta.xmp, orientation: Some(1), hint, ..Default::default() };
|
||||
let mut decoded = finish(F, raw, meta, (w, h), opts)?;
|
||||
// AV1 stores integer samples even when HDR transfer decoding produces linear float pixels.
|
||||
decoded.float = false;
|
||||
Ok(decoded)
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "avif", not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/quad-444-gbr-lossless.avif");
|
||||
#[test]
|
||||
fn production_entrypoints_decode_avif_and_enforce_pixel_budget() {
|
||||
assert!(F.can_decode());
|
||||
assert_eq!(crate::sniff(FIXTURE), Some(F));
|
||||
let header = crate::read_header(FIXTURE).unwrap();
|
||||
assert_eq!((header.width, header.height, header.orientation), (33, 17, 1));
|
||||
let decoded = crate::decode(FIXTURE, DecodeOptions::default()).unwrap();
|
||||
assert_eq!((decoded.source_width, decoded.source_height), (33, 17));
|
||||
assert_eq!(decoded.bit_depth, 8);
|
||||
let exact = DecodeOptions { max_pixels: 33 * 17, ..DecodeOptions::default() };
|
||||
let decoded = crate::decode(FIXTURE, exact).unwrap();
|
||||
assert_eq!((decoded.source_width, decoded.source_height), (33, 17));
|
||||
assert!(!decoded.float);
|
||||
let opts = DecodeOptions { max_pixels: 33 * 17 - 1, ..DecodeOptions::default() };
|
||||
assert!(matches!(crate::decode(FIXTURE, opts), Err(Error::TooLarge(..))));
|
||||
}
|
||||
#[test]
|
||||
fn picture_store_budget_accounts_for_padding_and_stays_bounded() {
|
||||
assert_eq!(picture_store_budget(33, 17), 288 * 288 * 6 * 19);
|
||||
let cap = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 };
|
||||
assert_eq!(picture_store_budget(u32::MAX, u32::MAX), cap);
|
||||
assert_eq!(stored_picture_store_budget(u64::MAX), cap);
|
||||
// Every canvas the pixel limit admits fits, whatever its shape.
|
||||
for max_pixels in [1u64, 561, 512 * 512, 1 << 20] {
|
||||
let budget = stored_picture_store_budget(max_pixels);
|
||||
for (w, h) in [(1, max_pixels), (max_pixels, 1), (max_pixels.isqrt(), max_pixels.isqrt())] {
|
||||
let (w, h) = (w.min(65_536) as u32, h.min(65_536) as u32);
|
||||
assert!(picture_store_budget(w, h) <= budget, "{w}x{h} under {max_pixels}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `probe_size` reports the `clap`-cropped size; the decoder still builds the stored canvas.
|
||||
/// A 512×512 picture cropped to 16×16 must decode with the default options and at a pixel
|
||||
/// limit that covers the stored canvas, and fail as too large below it.
|
||||
#[test]
|
||||
fn cropped_avif_decodes_with_a_budget_for_its_stored_canvas() {
|
||||
let pixels = [90u8, 140, 200].repeat(512 * 512);
|
||||
let image = crate::encode::EncodeImage::new(512, 512, 3, crate::encode::Samples::U8(&pixels));
|
||||
let full = crate::encode::encode_avif(&image, 60, 10, &crate::encode::EncodeMeta::default()).unwrap();
|
||||
let cropped = with_clap(&full, 16, 16);
|
||||
assert_eq!(crate::read_header(&cropped).map(|h| (h.width, h.height)).unwrap(), (16, 16));
|
||||
// The old budget, sized from the cropped 16×16, is below what the stored canvas needs.
|
||||
assert!(picture_store_budget(16, 16) < picture_store_budget(512, 512));
|
||||
let decoded = crate::decode(&cropped, DecodeOptions::default()).unwrap();
|
||||
assert_eq!((decoded.source_width, decoded.source_height), (16, 16));
|
||||
let exact = DecodeOptions { max_pixels: 512 * 512, ..DecodeOptions::default() };
|
||||
assert_eq!(crate::decode(&cropped, exact).map(|d| (d.source_width, d.source_height)).unwrap(), (16, 16));
|
||||
let below = DecodeOptions { max_pixels: 512 * 512 - 1, ..DecodeOptions::default() };
|
||||
assert!(crate::decode(&cropped, below).is_err());
|
||||
}
|
||||
|
||||
fn be32(b: &[u8], at: usize) -> usize {
|
||||
u32::from_be_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) as usize
|
||||
}
|
||||
fn put32(b: &mut [u8], at: usize, v: usize) {
|
||||
b[at..at + 4].copy_from_slice(&(v as u32).to_be_bytes());
|
||||
}
|
||||
/// Child boxes of `b[start..end]`: (offset, size, type).
|
||||
fn boxes(b: &[u8], start: usize, end: usize) -> Vec<(usize, usize, [u8; 4])> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = start;
|
||||
while at + 8 <= end {
|
||||
let size = be32(b, at);
|
||||
out.push((at, size, [b[at + 4], b[at + 5], b[at + 6], b[at + 7]]));
|
||||
at += size;
|
||||
}
|
||||
out
|
||||
}
|
||||
fn find(b: &[u8], start: usize, end: usize, kind: &[u8; 4]) -> (usize, usize) {
|
||||
boxes(b, start, end).into_iter().find(|x| &x.2 == kind).map_or((0, 0), |x| (x.0, x.1))
|
||||
}
|
||||
|
||||
/// Adds a centred `clap` of `w × h` to the primary item of a single-item AVIF from the encoder,
|
||||
/// fixing the enclosing box sizes and the `iloc` offsets into `mdat`.
|
||||
fn with_clap(file: &[u8], w: u32, h: u32) -> Vec<u8> {
|
||||
let mut b = file.to_vec();
|
||||
let (meta, meta_size) = find(&b, 0, b.len(), b"meta");
|
||||
let children = meta + 12;
|
||||
let (iprp, _) = find(&b, children, meta + meta_size, b"iprp");
|
||||
let (ipco, ipco_size) = find(&b, iprp + 8, iprp + be32(&b, iprp), b"ipco");
|
||||
let index = boxes(&b, ipco + 8, ipco + ipco_size).len() + 1;
|
||||
let mut clap = Vec::new();
|
||||
for v in [w, 1, h, 1, 0, 1, 0, 1] {
|
||||
clap.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
let clap = [&((8 + clap.len()) as u32).to_be_bytes()[..], b"clap", &clap].concat();
|
||||
// ipma: version/flags, entry count, then item id, association count, associations.
|
||||
let (ipma, ipma_size) = find(&b, iprp + 8, iprp + be32(&b, iprp), b"ipma");
|
||||
let (version, flags) = (b[ipma + 8], b[ipma + 11]);
|
||||
assert_eq!(be32(&b, ipma + 12), 1, "one item");
|
||||
let id_len = if version < 1 { 2 } else { 4 };
|
||||
let count_at = ipma + 16 + id_len;
|
||||
let wide = flags & 1 == 1;
|
||||
let assoc_end = count_at + 1 + b[count_at] as usize * if wide { 2 } else { 1 };
|
||||
assert_eq!(assoc_end, ipma + ipma_size);
|
||||
let assoc: Vec<u8> = if wide { (0x8000u16 | index as u16).to_be_bytes().to_vec() } else { vec![0x80 | index as u8] };
|
||||
let grow = clap.len() + assoc.len();
|
||||
b[count_at] += 1;
|
||||
b.splice(assoc_end..assoc_end, assoc.iter().copied());
|
||||
b.splice(ipco + ipco_size..ipco + ipco_size, clap.iter().copied());
|
||||
// ipco precedes ipma inside iprp, so ipma moved by the clap's length.
|
||||
for (at, by) in [(meta, grow), (iprp, grow), (ipco, clap.len()), (ipma + clap.len(), assoc.len())] {
|
||||
let size = be32(&b, at);
|
||||
put32(&mut b, at, size + by);
|
||||
}
|
||||
// iloc (version 0 or 1): shift every absolute extent offset by the growth of `meta`.
|
||||
let (iloc, _) = find(&b, children, meta + be32(&b, meta), b"iloc");
|
||||
let v = b[iloc + 8];
|
||||
let (offset_size, length_size, base_size) = ((b[iloc + 12] >> 4) as usize, (b[iloc + 12] & 15) as usize, (b[iloc + 13] >> 4) as usize);
|
||||
let index_size = if v >= 1 { (b[iloc + 13] & 15) as usize } else { 0 };
|
||||
let mut at = iloc + 14;
|
||||
let items = if v < 2 {
|
||||
let n = u16::from_be_bytes([b[at], b[at + 1]]) as usize;
|
||||
at += 2;
|
||||
n
|
||||
} else {
|
||||
let n = be32(&b, at);
|
||||
at += 4;
|
||||
n
|
||||
};
|
||||
let read = |b: &[u8], at: usize, n: usize| b[at..at + n].iter().fold(0usize, |acc, &x| acc << 8 | x as usize);
|
||||
let write = |b: &mut [u8], at: usize, n: usize, v: usize| {
|
||||
for i in 0..n {
|
||||
b[at + i] = (v >> (8 * (n - 1 - i))) as u8;
|
||||
}
|
||||
};
|
||||
for _ in 0..items {
|
||||
at += if v < 2 { 2 } else { 4 };
|
||||
if v >= 1 {
|
||||
at += 2;
|
||||
}
|
||||
at += 2;
|
||||
let base = read(&b, at, base_size);
|
||||
if base_size > 0 && base > 0 {
|
||||
write(&mut b, at, base_size, base + grow);
|
||||
}
|
||||
at += base_size;
|
||||
let extents = u16::from_be_bytes([b[at], b[at + 1]]) as usize;
|
||||
at += 2;
|
||||
for _ in 0..extents {
|
||||
at += index_size;
|
||||
let off = read(&b, at, offset_size);
|
||||
if base == 0 && offset_size > 0 {
|
||||
write(&mut b, at, offset_size, off + grow);
|
||||
}
|
||||
at += offset_size + length_size;
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
#[test]
|
||||
fn hdr_avif_round_trips_highlights_through_public_decoder() {
|
||||
let pixels = vec![2.0f32; 16 * 16 * 3];
|
||||
for transfer in [crate::encode::HdrTransfer::Pq, crate::encode::HdrTransfer::Hlg] {
|
||||
let bytes = crate::encode::encode_avif_hdr(16, 16, &pixels, 95, 10, &crate::encode::EncodeMeta::default(), transfer).unwrap();
|
||||
let decoded = crate::decode(&bytes, DecodeOptions::default()).unwrap();
|
||||
assert_eq!(decoded.bit_depth, 10);
|
||||
assert!(!decoded.float, "AV1 source samples are integer for {transfer:?}");
|
||||
assert!(decoded.image.data.iter().any(|pixel| pixel[0] > 1.0), "HDR highlights were lost");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn avif_alpha_survives_public_round_trip() {
|
||||
let pixels = [200u8, 100, 50, 96].repeat(16 * 16);
|
||||
let image = crate::encode::EncodeImage::new(16, 16, 4, crate::encode::Samples::U8(&pixels));
|
||||
let bytes = crate::encode::encode_avif(&image, 95, 10, &crate::encode::EncodeMeta::default()).unwrap();
|
||||
let decoded = crate::decode(&bytes, DecodeOptions::default()).unwrap();
|
||||
let alpha = decoded.alpha.expect("alpha plane");
|
||||
assert!((alpha.data[0] - 96.0 / 255.0).abs() < 0.04);
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,11 @@
|
||||
//!
|
||||
//! All conversions are relative colorimetric: the display's white is the image's white.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::icc;
|
||||
use crate::space::Trc;
|
||||
use craft_cms::{Builtin, ColorSpace, Intent, Pcs, Profile, Transform, TransformOptions};
|
||||
use lightcraft_color::{D50, D65, Mat3, REC2020, bradford};
|
||||
use lightcraft_raster::Rgba8;
|
||||
use moxcms::{ColorProfile, DataColorSpace, Layout, RenderingIntent, Transform8BitExecutor, TransformOptions, Xyzd};
|
||||
|
||||
/// Largest profile file accepted (monitor profiles are a few KB; LUT profiles up to a few MB).
|
||||
pub const MAX_PROFILE_BYTES: usize = 32 << 20;
|
||||
@@ -46,7 +44,7 @@ enum Correction {
|
||||
/// Per-channel tables (matrix/TRC profile: same primaries, other curves).
|
||||
Curves(Box<[[u8; 256]; 3]>),
|
||||
/// A full CMS transform (LUT-based profile).
|
||||
Cms(Arc<Transform8BitExecutor>),
|
||||
Cms(Box<Transform>),
|
||||
}
|
||||
|
||||
/// A parsed display profile with its transforms (built once, applied to every preview).
|
||||
@@ -59,8 +57,8 @@ pub struct DisplayProfile {
|
||||
/// Linear display RGB → linear Rec.2020 (D65; display white → (1, 1, 1)).
|
||||
pub to_rec2020: Mat3,
|
||||
correction: Correction,
|
||||
from_srgb: Arc<Transform8BitExecutor>,
|
||||
to_srgb: Arc<Transform8BitExecutor>,
|
||||
from_srgb: Transform,
|
||||
to_srgb: Transform,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DisplayProfile {
|
||||
@@ -75,11 +73,7 @@ impl std::fmt::Debug for DisplayProfile {
|
||||
}
|
||||
|
||||
fn opts() -> TransformOptions {
|
||||
TransformOptions { rendering_intent: RenderingIntent::RelativeColorimetric, ..TransformOptions::default() }
|
||||
}
|
||||
|
||||
fn xyzd(v: [f64; 3]) -> Xyzd {
|
||||
Xyzd { x: v[0], y: v[1], z: v[2] }
|
||||
TransformOptions { intent: Intent::RelativeColorimetric, bpc: false, precise_float: true }
|
||||
}
|
||||
|
||||
/// Linear Rec.2020 → XYZ relative to D50 (the ICC PCS), Bradford-adapted.
|
||||
@@ -100,11 +94,6 @@ fn hash(bytes: &[u8]) -> u64 {
|
||||
h.finish() | 1
|
||||
}
|
||||
|
||||
/// Runs a moxcms call that may panic on a hostile profile.
|
||||
fn guarded<T>(f: impl FnOnce() -> Option<T>) -> Option<T> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok().flatten()
|
||||
}
|
||||
|
||||
impl DisplayProfile {
|
||||
/// Parse a display profile (an RGB ICC profile, matrix/TRC or LUT-based) and build its
|
||||
/// transforms. Errors say what is wrong with the file; nothing here panics.
|
||||
@@ -112,11 +101,11 @@ impl DisplayProfile {
|
||||
if bytes.len() > MAX_PROFILE_BYTES {
|
||||
return Err(format!("the profile is too large ({} MB)", bytes.len() >> 20));
|
||||
}
|
||||
let p = guarded(|| ColorProfile::new_from_slice(bytes).ok()).ok_or("not a valid ICC profile")?;
|
||||
if p.color_space != DataColorSpace::Rgb {
|
||||
let p = Profile::parse(bytes).map_err(|_| "not a valid ICC profile")?;
|
||||
if p.color_space != ColorSpace::Rgb {
|
||||
return Err("not an RGB profile (a display profile describes an RGB device)".into());
|
||||
}
|
||||
if !matches!(p.pcs, DataColorSpace::Xyz | DataColorSpace::Lab) {
|
||||
if !matches!(p.pcs, Pcs::Xyz | Pcs::Lab) {
|
||||
return Err("unsupported profile connection space".into());
|
||||
}
|
||||
let info = icc::parse(bytes).ok_or("not a valid ICC profile")?;
|
||||
@@ -127,11 +116,8 @@ impl DisplayProfile {
|
||||
.filter(|d| !d.is_empty())
|
||||
.unwrap_or("Display profile")
|
||||
.to_string();
|
||||
let has_lut = p.lut_a_to_b_colorimetric.is_some()
|
||||
|| p.lut_a_to_b_perceptual.is_some()
|
||||
|| p.lut_b_to_a_colorimetric.is_some()
|
||||
|| p.lut_b_to_a_perceptual.is_some();
|
||||
let srgb = ColorProfile::new_srgb();
|
||||
let has_lut = p.a2b[0].is_some() || p.a2b[1].is_some() || p.b2a[0].is_some() || p.b2a[1].is_some();
|
||||
let srgb = Builtin::Srgb.profile().clone();
|
||||
|
||||
// the primaries the pipeline renders into
|
||||
let (kind, to_xyz_d50, curves) = match &info.kind {
|
||||
@@ -147,17 +133,14 @@ impl DisplayProfile {
|
||||
|
||||
// the proxy: the display's primaries (as the pipeline targets them), sRGB curve
|
||||
let proxy_xyz = rec2020_to_xyz_d50().mul(&to_rec2020).0;
|
||||
let mut proxy = ColorProfile::new_srgb();
|
||||
proxy.cicp = None;
|
||||
proxy.red_colorant = xyzd([proxy_xyz[0][0], proxy_xyz[1][0], proxy_xyz[2][0]]);
|
||||
proxy.green_colorant = xyzd([proxy_xyz[0][1], proxy_xyz[1][1], proxy_xyz[2][1]]);
|
||||
proxy.blue_colorant = xyzd([proxy_xyz[0][2], proxy_xyz[1][2], proxy_xyz[2][2]]);
|
||||
let mut proxy = Builtin::Srgb.profile().clone();
|
||||
proxy.matrix = Some(proxy_xyz);
|
||||
|
||||
let transform = |src: &ColorProfile, dst: &ColorProfile| guarded(|| src.create_transform_8bit(Layout::Rgba, dst, Layout::Rgba, opts()).ok());
|
||||
let transform = |src: &Profile, dst: &Profile| Transform::with_options(src, dst, opts()).ok();
|
||||
let correction = match curves {
|
||||
Some(trc) if trc.iter().all(|t| t.approx_eq(&Trc::Srgb, 2e-4)) => Correction::None,
|
||||
Some(trc) => Correction::Curves(Box::new(curve_tables(&trc))),
|
||||
None => Correction::Cms(transform(&proxy, &p).ok_or("the profile's tables can't be applied")?),
|
||||
None => Correction::Cms(Box::new(transform(&proxy, &p).ok_or("the profile's tables can't be applied")?)),
|
||||
};
|
||||
let from_srgb = transform(&srgb, &p).ok_or("can't convert sRGB to this profile")?;
|
||||
let to_srgb = transform(&proxy, &srgb).ok_or("can't convert this profile to sRGB")?;
|
||||
@@ -205,12 +188,12 @@ impl DisplayProfile {
|
||||
|
||||
/// Device RGB → PCS (XYZ D50) of the pure primaries, measured through the profile's tables
|
||||
/// (LUT-only profiles have no colorant tags).
|
||||
fn measured_to_xyz_d50(p: &ColorProfile) -> Result<Mat3, String> {
|
||||
fn measured_to_xyz_d50(p: &Profile) -> Result<Mat3, String> {
|
||||
let lin = icc::linear_rec2020_profile();
|
||||
let x = guarded(|| p.create_transform_f32(Layout::Rgb, &lin, Layout::Rgb, opts()).ok()).ok_or("the profile's tables can't be applied")?;
|
||||
let x = Transform::with_options(p, &lin, opts()).map_err(|_| "the profile's tables can't be applied")?;
|
||||
let src = [1.0f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
|
||||
let mut dst = [0f32; 9];
|
||||
guarded(|| x.transform(&src, &mut dst).ok()).ok_or("the profile's tables can't be applied")?;
|
||||
x.convert_f32(&src, 3, &mut dst, 3, false).map_err(|_| "the profile's tables can't be applied")?;
|
||||
let c = |i: usize| [dst[i] as f64, dst[i + 3] as f64, dst[i + 6] as f64];
|
||||
// columns: each primary in linear Rec.2020
|
||||
let m = Mat3([c(0), c(1), c(2)]);
|
||||
@@ -247,10 +230,10 @@ fn from_linear(t: &Trc, y: f32) -> f32 {
|
||||
0.5 * (lo + hi)
|
||||
}
|
||||
|
||||
fn apply(x: &Arc<Transform8BitExecutor>, img: &mut Rgba8) -> Result<(), String> {
|
||||
fn apply(x: &Transform, img: &mut Rgba8) -> Result<(), String> {
|
||||
const CHUNK: usize = 1 << 14; // pixels
|
||||
let src = img.data.clone();
|
||||
let run = |s: &[[u8; 4]], d: &mut [[u8; 4]]| guarded(|| x.transform(s.as_flattened(), d.as_flattened_mut()).ok()).is_some();
|
||||
let run = |s: &[[u8; 4]], d: &mut [[u8; 4]]| x.convert_u8(s.as_flattened(), 4, d.as_flattened_mut(), 4, true).is_ok();
|
||||
#[cfg(feature = "parallel")]
|
||||
let ok = {
|
||||
use rayon::prelude::*;
|
||||
@@ -340,9 +323,8 @@ mod tests {
|
||||
fn rejects_bad_profiles() {
|
||||
assert!(DisplayProfile::from_icc(&[]).is_err());
|
||||
assert!(DisplayProfile::from_icc(&[0u8; 300]).is_err());
|
||||
let mut gray = ColorProfile::new_gray_with_gamma(2.2);
|
||||
gray.cicp = None;
|
||||
assert!(DisplayProfile::from_icc(&gray.encode().unwrap()).is_err());
|
||||
let gray = Builtin::GrayGamma22.profile().to_bytes();
|
||||
assert!(DisplayProfile::from_icc(&gray).is_err());
|
||||
// truncated / corrupted real profiles never panic
|
||||
let good = icc::write_named(NamedSpace::DisplayP3);
|
||||
for n in [10, 128, 140, 200, good.len() - 1] {
|
||||
@@ -359,55 +341,50 @@ mod tests {
|
||||
/// Display P3 panel with a gamma 2.2 response): the primaries are measured through the tables
|
||||
/// and every preview goes through the CMS.
|
||||
fn lut_only_p3_gamma22() -> Vec<u8> {
|
||||
use moxcms::{LutMultidimensionalType, LutWarehouse, Matrix3d, ProfileClass, ToneReprCurve, Vector3d};
|
||||
use craft_cms::Curve;
|
||||
use craft_cms::pipeline::Stage;
|
||||
use craft_cms::profile::{Lut, LutKind};
|
||||
let m = crate::space::rgb_to_xyz_d50(&DISPLAY_P3).0;
|
||||
let inv = crate::space::rgb_to_xyz_d50(&DISPLAY_P3).inverse().unwrap().0;
|
||||
let curves = |v: Vec<f32>| vec![ToneReprCurve::Parametric(v.clone()), ToneReprCurve::Parametric(v.clone()), ToneReprCurve::Parametric(v)];
|
||||
let ident = || curves(vec![1.0]);
|
||||
// mAB: A → CLUT → M → matrix → B (no CLUT: M curves linearize, the matrix goes to XYZ)
|
||||
let a2b = LutWarehouse::Multidimensional(LutMultidimensionalType {
|
||||
num_input_channels: 3,
|
||||
num_output_channels: 3,
|
||||
grid_points: [0; 16],
|
||||
clut: None,
|
||||
a_curves: vec![],
|
||||
m_curves: curves(vec![2.2]),
|
||||
matrix: Matrix3d { v: m.map(|r| r.map(|v| v * 32768.0 / 65535.0)) },
|
||||
b_curves: ident(),
|
||||
bias: Vector3d::default(),
|
||||
});
|
||||
let b2a = LutWarehouse::Multidimensional(LutMultidimensionalType {
|
||||
num_input_channels: 3,
|
||||
num_output_channels: 3,
|
||||
grid_points: [0; 16],
|
||||
clut: None,
|
||||
a_curves: vec![],
|
||||
m_curves: curves(vec![1.0 / 2.2]),
|
||||
matrix: Matrix3d { v: inv.map(|r| r.map(|v| v * 65535.0 / 32768.0)) },
|
||||
b_curves: ident(),
|
||||
bias: Vector3d::default(),
|
||||
});
|
||||
let mut p = ColorProfile::new_srgb();
|
||||
p.cicp = None;
|
||||
p.profile_class = ProfileClass::DisplayDevice;
|
||||
p.red_colorant = Xyzd::default();
|
||||
p.green_colorant = Xyzd::default();
|
||||
p.blue_colorant = Xyzd::default();
|
||||
p.red_trc = None;
|
||||
p.green_trc = None;
|
||||
p.blue_trc = None;
|
||||
p.lut_a_to_b_colorimetric = Some(a2b.clone());
|
||||
p.lut_a_to_b_perceptual = Some(a2b);
|
||||
p.lut_b_to_a_colorimetric = Some(b2a.clone());
|
||||
p.lut_b_to_a_perceptual = Some(b2a);
|
||||
p.encode().unwrap()
|
||||
let flat = |m: [[f64; 3]; 3], scale: f64| -> Vec<f64> { m.iter().flatten().map(|&v| v * scale).collect() };
|
||||
let curves = |g: f64| vec![Curve::Gamma(g), Curve::Gamma(g), Curve::Gamma(g)];
|
||||
let ident = || vec![Curve::Identity, Curve::Identity, Curve::Identity];
|
||||
let a2b = Lut {
|
||||
kind: LutKind::Ab,
|
||||
inputs: 3,
|
||||
outputs: 3,
|
||||
stages: vec![
|
||||
Stage::Curves(curves(2.2)),
|
||||
Stage::Matrix { rows: 3, cols: 3, m: flat(m, 32768.0 / 65535.0), offset: vec![0.0; 3] },
|
||||
Stage::Curves(ident()),
|
||||
],
|
||||
};
|
||||
let b2a = Lut {
|
||||
kind: LutKind::Ab,
|
||||
inputs: 3,
|
||||
outputs: 3,
|
||||
stages: vec![
|
||||
Stage::Curves(ident()),
|
||||
Stage::Matrix { rows: 3, cols: 3, m: flat(inv, 65535.0 / 32768.0), offset: vec![0.0; 3] },
|
||||
Stage::Curves(curves(1.0 / 2.2)),
|
||||
],
|
||||
};
|
||||
let mut p = Builtin::Srgb.profile().clone();
|
||||
p.class = craft_cms::ProfileClass::Display;
|
||||
p.matrix = None;
|
||||
p.trc = None;
|
||||
p.a2b[0] = Some(a2b.clone());
|
||||
p.a2b[1] = Some(a2b);
|
||||
p.b2a[0] = Some(b2a.clone());
|
||||
p.b2a[1] = Some(b2a);
|
||||
p.with_encoded_bytes().to_bytes().to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lut_profile_goes_through_the_cms() {
|
||||
let bytes = lut_only_p3_gamma22();
|
||||
let parsed = ColorProfile::new_from_slice(&bytes).unwrap();
|
||||
assert!(!parsed.is_matrix_shaper() && parsed.lut_b_to_a_colorimetric.is_some(), "a LUT-only profile");
|
||||
let parsed = Profile::parse(&bytes).unwrap();
|
||||
assert!(!parsed.is_matrix_shaper() && parsed.b2a[1].is_some(), "a LUT-only profile");
|
||||
let d = DisplayProfile::from_icc(&bytes).unwrap();
|
||||
assert_eq!(d.kind, DisplayKind::Lut);
|
||||
assert!(d.needs_correction());
|
||||
|
||||
+170
-390
@@ -1,4 +1,4 @@
|
||||
//! Encoders: JPEG (`jpeg-encoder`), PNG (`png`), TIFF (`tiff`), flat PSD (our own), lossless WebP (`image-webp`) and,
|
||||
//! Encoders: JPEG (`craft-jpeg`), PNG (`png`), TIFF (`tiff`), flat PSD (our own), lossless WebP (`image-webp`) and,
|
||||
//! on native targets with the `avif` feature, AVIF (`ravif`/`rav1e`); JPEG XL is in `jxl_encode`.
|
||||
//! Metadata (ICC/EXIF/XMP) is embedded where the format allows.
|
||||
|
||||
@@ -39,21 +39,21 @@ impl<'a> EncodeImage<'a> {
|
||||
if self.width == 0 || self.height == 0 {
|
||||
return Err(Error::Encode("zero dimension".into()));
|
||||
}
|
||||
let need = self.width as u64 * self.height as u64 * self.channels as u64;
|
||||
// u128: 2^32 x 2^32 x 4 does not fit u64, and every later `width * height * channels` is bounded by this
|
||||
let need = self.width as u128 * self.height as u128 * self.channels as u128;
|
||||
if need > usize::MAX as u128 {
|
||||
return Err(Error::Encode("image too large".into()));
|
||||
}
|
||||
let have = match self.samples {
|
||||
Samples::U8(s) => s.len(),
|
||||
Samples::U16(s) => s.len(),
|
||||
Samples::F32(s) => s.len(),
|
||||
} as u64;
|
||||
} as u128;
|
||||
if have < need {
|
||||
return Err(Error::Encode(format!("sample buffer too short: {have} < {need}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_alpha(&self) -> bool {
|
||||
self.channels == 2 || self.channels == 4
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata to embed.
|
||||
@@ -128,92 +128,75 @@ pub fn encode_jpeg(img: &EncodeImage, quality: u8, subsampling: ChromaSubsamplin
|
||||
if img.width > u16::MAX as u32 || img.height > u16::MAX as u32 {
|
||||
return Err(Error::Encode("JPEG dimensions are limited to 65535".into()));
|
||||
}
|
||||
let n = img.width as usize * img.height as usize;
|
||||
let (data, ct): (std::borrow::Cow<[u8]>, jpeg_encoder::ColorType) = match img.channels {
|
||||
1 => (data[..n].into(), jpeg_encoder::ColorType::Luma),
|
||||
2 => (data.as_chunks::<2>().0.iter().take(n).map(|c| c[0]).collect::<Vec<_>>().into(), jpeg_encoder::ColorType::Luma),
|
||||
3 => (data[..n * 3].into(), jpeg_encoder::ColorType::Rgb),
|
||||
_ => (data[..n * 4].into(), jpeg_encoder::ColorType::Rgba),
|
||||
let pixels = img.width as usize * img.height as usize;
|
||||
let (data, channels): (std::borrow::Cow<'_, [u8]>, usize) = match img.channels {
|
||||
1 => (data[..pixels].into(), 1),
|
||||
2 => (data.as_chunks::<2>().0.iter().take(pixels).map(|c| c[0]).collect::<Vec<_>>().into(), 1),
|
||||
3 => (data[..pixels * 3].into(), 3),
|
||||
_ => (data[..pixels * 4].into(), 4),
|
||||
};
|
||||
if subsampling != ChromaSubsampling::S422 {
|
||||
// Parallel encoder (restart-interval bands on all cores).
|
||||
let segs = jpeg_app_segments(meta)?;
|
||||
let ch = if img.channels == 2 { 1 } else { img.channels as usize };
|
||||
// `data` is already gray for 2-channel input (see above)
|
||||
return Ok(crate::jpeg_par::encode(&data, img.width as usize, img.height as usize, ch, quality, subsampling, &segs));
|
||||
let subsampling = match subsampling {
|
||||
ChromaSubsampling::S444 => craft_jpeg::ChromaSubsampling::S444,
|
||||
ChromaSubsampling::S422 => craft_jpeg::ChromaSubsampling::S422,
|
||||
ChromaSubsampling::S420 => craft_jpeg::ChromaSubsampling::S420,
|
||||
};
|
||||
craft_jpeg::encode_baseline(&data, img.width as usize, img.height as usize, channels, quality, subsampling, &jpeg_app_segments(meta)?)
|
||||
.map_err(|e| Error::Encode(e.to_string()))
|
||||
}
|
||||
|
||||
/// `img` (already validated) as a `craft-image-codecs` image. `refuse_float` is the error for
|
||||
/// 32-bit float samples, for a format that cannot hold them; `None` converts them too.
|
||||
fn shared_image(img: &EncodeImage, refuse_float: Option<&str>) -> Result<craft_image_codecs::Image> {
|
||||
let n = img.width as usize * img.height as usize * img.channels as usize;
|
||||
let layout = match img.channels {
|
||||
1 => craft_image_codecs::ChannelLayout::Gray,
|
||||
2 => craft_image_codecs::ChannelLayout::GrayA,
|
||||
3 => craft_image_codecs::ChannelLayout::Rgb,
|
||||
_ => craft_image_codecs::ChannelLayout::Rgba,
|
||||
};
|
||||
match (img.samples, refuse_float) {
|
||||
(Samples::U8(s), _) => craft_image_codecs::Image::from_u8(img.width, img.height, layout, s[..n].to_vec()),
|
||||
(Samples::U16(s), _) => craft_image_codecs::Image::from_u16(img.width, img.height, layout, &s[..n]),
|
||||
(Samples::F32(_), Some(refusal)) => return Err(Error::Encode(refusal.into())),
|
||||
(Samples::F32(s), None) => craft_image_codecs::Image::from_f32(img.width, img.height, layout, &s[..n]),
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut enc = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100));
|
||||
enc.set_sampling_factor(match subsampling {
|
||||
ChromaSubsampling::S444 => jpeg_encoder::SamplingFactor::R_4_4_4,
|
||||
ChromaSubsampling::S422 => jpeg_encoder::SamplingFactor::R_4_2_2,
|
||||
ChromaSubsampling::S420 => jpeg_encoder::SamplingFactor::R_4_2_0,
|
||||
});
|
||||
// Standard tables: jpeg-encoder's optimized-table mode writes non-interleaved scans, which some
|
||||
// decoders (incl. zune-jpeg 0.5) mishandle. Interleaved baseline is universally supported.
|
||||
let e = |e: jpeg_encoder::EncodingError| Error::Encode(e.to_string());
|
||||
if let Some(ppi) = meta.ppi.filter(|p| *p > 0) {
|
||||
enc.set_density(jpeg_encoder::PixelDensity::dpi(ppi));
|
||||
}
|
||||
if let Some(exif) = meta.exif {
|
||||
if exif.len() > 65_527 {
|
||||
return Err(Error::Encode("EXIF larger than one APP1 segment (64 KiB)".into()));
|
||||
}
|
||||
enc.add_exif_metadata(exif).map_err(e)?;
|
||||
}
|
||||
if let Some(xmp) = meta.xmp {
|
||||
let mut seg = XMP_NS.to_vec();
|
||||
seg.extend_from_slice(xmp.as_bytes());
|
||||
if seg.len() > 65_533 {
|
||||
return Err(Error::Encode("XMP larger than one APP1 segment (extended XMP not supported)".into()));
|
||||
}
|
||||
enc.add_app_segment(1, seg).map_err(e)?;
|
||||
}
|
||||
if let Some(icc) = meta.icc {
|
||||
enc.add_icc_profile(icc).map_err(e)?;
|
||||
}
|
||||
enc.encode(&data, img.width as u16, img.height as u16, ct).map_err(e)?;
|
||||
Ok(out)
|
||||
.map_err(|e| Error::Encode(e.to_string()))
|
||||
}
|
||||
|
||||
/// Encode PNG (8- or 16-bit; float input is rejected — quantize first).
|
||||
pub fn encode_png(img: &EncodeImage, meta: &EncodeMeta) -> Result<Vec<u8>> {
|
||||
img.validate()?;
|
||||
let n = img.width as usize * img.height as usize * img.channels as usize;
|
||||
let (bytes, depth): (Vec<u8>, png::BitDepth) = match img.samples {
|
||||
Samples::U8(s) => (s[..n].to_vec(), png::BitDepth::Eight),
|
||||
Samples::U16(s) => (s[..n].iter().flat_map(|v| v.to_be_bytes()).collect(), png::BitDepth::Sixteen),
|
||||
Samples::F32(_) => return Err(Error::Encode("PNG needs 8- or 16-bit samples".into())),
|
||||
};
|
||||
let mut info = png::Info::with_size(img.width, img.height);
|
||||
info.color_type = match img.channels {
|
||||
1 => png::ColorType::Grayscale,
|
||||
2 => png::ColorType::GrayscaleAlpha,
|
||||
3 => png::ColorType::Rgb,
|
||||
_ => png::ColorType::Rgba,
|
||||
};
|
||||
info.bit_depth = depth;
|
||||
info.icc_profile = meta.icc.map(|b| b.to_vec().into());
|
||||
info.exif_metadata = meta.exif.map(|b| b.to_vec().into());
|
||||
info.pixel_dims = meta.ppi.filter(|p| *p > 0).map(|p| {
|
||||
let ppm = (p as f64 / 0.0254).round() as u32;
|
||||
png::PixelDimensions { xppu: ppm, yppu: ppm, unit: png::Unit::Meter }
|
||||
});
|
||||
let mut out = Vec::new();
|
||||
let e = |e: png::EncodingError| Error::Encode(e.to_string());
|
||||
{
|
||||
let mut enc = png::Encoder::with_info(&mut out, info).map_err(e)?;
|
||||
enc.set_compression(png::Compression::Fast);
|
||||
if let Some(xmp) = meta.xmp {
|
||||
enc.add_itxt_chunk("XML:com.adobe.xmp".into(), xmp.into()).map_err(e)?;
|
||||
}
|
||||
let mut w = enc.write_header().map_err(e)?;
|
||||
w.write_image_data(&bytes).map_err(e)?;
|
||||
w.finish().map_err(e)?;
|
||||
let mut ic_img = shared_image(img, Some("PNG needs 8- or 16-bit samples"))?;
|
||||
ic_img.icc = meta.icc.map(|b| b.to_vec());
|
||||
ic_img.meta.exif = meta.exif.map(|b| b.to_vec());
|
||||
ic_img.meta.xmp = meta.xmp.map(|x| x.to_string());
|
||||
ic_img.meta.dpi = meta.ppi.filter(|p| *p > 0).map(|p| (p as f32, p as f32));
|
||||
let ic_opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
|
||||
let mut out = craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Png, &ic_opts).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
if let Some(exif) = meta.exif {
|
||||
replace_png_exif_chunk(&mut out, exif);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Replace the `eXIf` chunk in an encoded PNG so caller-supplied EXIF (including non-1
|
||||
/// orientation tags) is preserved verbatim.
|
||||
fn replace_png_exif_chunk(png: &mut Vec<u8>, exif: &[u8]) {
|
||||
let mut p = 8usize;
|
||||
while let Some(len_bytes) = png.get(p..p + 4) {
|
||||
let len = u32::from_be_bytes([len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]]) as usize;
|
||||
let end = p.saturating_add(12).saturating_add(len);
|
||||
if end > png.len() {
|
||||
break;
|
||||
}
|
||||
if png.get(p + 4..p + 8) == Some(b"eXIf") {
|
||||
png.splice(p..end, png_chunk(*b"eXIf", exif));
|
||||
return;
|
||||
}
|
||||
p = end;
|
||||
}
|
||||
}
|
||||
|
||||
/// TIFF compression.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum TiffCompression {
|
||||
@@ -225,108 +208,21 @@ pub enum TiffCompression {
|
||||
}
|
||||
|
||||
/// Encode TIFF: 8/16-bit integer or 32-bit float, gray/RGB with optional (unassociated) alpha.
|
||||
/// ICC and XMP are embedded; EXIF is not (write it through the TIFF writer in `lightcraft-tiff`).
|
||||
/// ICC and XMP are embedded; EXIF is not (write it through the TIFF writer in `craft-tiff`).
|
||||
pub fn encode_tiff(img: &EncodeImage, compression: TiffCompression, meta: &EncodeMeta) -> Result<Vec<u8>> {
|
||||
use tiff::encoder::{Compression, DeflateLevel, TiffEncoder};
|
||||
use tiff::tags::Predictor;
|
||||
img.validate()?;
|
||||
let e = |e: tiff::TiffError| Error::Encode(e.to_string());
|
||||
let mut cur = std::io::Cursor::new(Vec::new());
|
||||
let comp = match compression {
|
||||
TiffCompression::None => Compression::Uncompressed,
|
||||
TiffCompression::Lzw => Compression::Lzw,
|
||||
TiffCompression::Deflate => Compression::Deflate(DeflateLevel::Fast),
|
||||
TiffCompression::PackBits => Compression::Packbits,
|
||||
let mut ic_img = shared_image(img, None)?;
|
||||
ic_img.icc = meta.icc.map(|b| b.to_vec());
|
||||
ic_img.meta.xmp = meta.xmp.map(|x| x.to_string());
|
||||
ic_img.meta.dpi = meta.ppi.filter(|p| *p > 0).map(|p| (p as f32, p as f32));
|
||||
let tiff_compression = match compression {
|
||||
TiffCompression::None => craft_image_codecs::TiffCompression::None,
|
||||
TiffCompression::Lzw => craft_image_codecs::TiffCompression::Lzw,
|
||||
TiffCompression::Deflate => craft_image_codecs::TiffCompression::Deflate,
|
||||
TiffCompression::PackBits => craft_image_codecs::TiffCompression::PackBits,
|
||||
};
|
||||
let float = matches!(img.samples, Samples::F32(_));
|
||||
let predictor =
|
||||
if !float && matches!(compression, TiffCompression::Lzw | TiffCompression::Deflate) { Predictor::Horizontal } else { Predictor::None };
|
||||
let mut enc = TiffEncoder::new(&mut cur).map_err(e)?.with_compression(comp).with_predictor(predictor);
|
||||
let (w, h) = (img.width, img.height);
|
||||
let pixels = w as usize * h as usize;
|
||||
match img.samples {
|
||||
Samples::U8(samples) => write_tiff_u8(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
|
||||
Samples::U16(samples) => write_tiff_u16(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
|
||||
Samples::F32(samples) => write_tiff_f32(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
|
||||
}
|
||||
Ok(cur.into_inner())
|
||||
}
|
||||
|
||||
macro_rules! write_tiff_image {
|
||||
($encoder:expr, $image:expr, $meta:expr, $color:ty, $data:expr, $alpha:expr) => {{
|
||||
let mut image = $encoder.new_image::<$color>($image.width, $image.height).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
if let Some(ppi) = $meta.ppi.filter(|ppi| *ppi > 0) {
|
||||
image.resolution(tiff::tags::ResolutionUnit::Inch, tiff::encoder::Rational { n: ppi as u32, d: 1 });
|
||||
}
|
||||
if let Some(icc) = $meta.icc {
|
||||
image.encoder().write_tag(tiff::tags::Tag::IccProfile, icc).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
}
|
||||
if let Some(xmp) = $meta.xmp {
|
||||
image.encoder().write_tag(tiff::tags::Tag::from_u16_exhaustive(700), xmp.as_bytes()).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
}
|
||||
if $alpha {
|
||||
image.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[2u16][..]).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
}
|
||||
image.write_data($data).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
}};
|
||||
}
|
||||
|
||||
fn expanded_gray_alpha<T: Copy>(samples: &[T], pixels: usize) -> Vec<T> {
|
||||
samples.as_chunks::<2>().0.iter().take(pixels).flat_map(|channel| [channel[0], channel[0], channel[0], channel[1]]).collect()
|
||||
}
|
||||
|
||||
fn write_tiff_u8<W: std::io::Write + std::io::Seek>(
|
||||
encoder: &mut tiff::encoder::TiffEncoder<W>,
|
||||
samples: &[u8],
|
||||
pixels: usize,
|
||||
channels: usize,
|
||||
image: &EncodeImage,
|
||||
meta: &EncodeMeta,
|
||||
) -> Result<()> {
|
||||
use tiff::encoder::colortype;
|
||||
match channels {
|
||||
1 => write_tiff_image!(encoder, image, meta, colortype::Gray8, &samples[..pixels], false),
|
||||
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA8, &expanded_gray_alpha(samples, pixels), true),
|
||||
3 => write_tiff_image!(encoder, image, meta, colortype::RGB8, &samples[..pixels * 3], false),
|
||||
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA8, &samples[..pixels * 4], true),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_tiff_u16<W: std::io::Write + std::io::Seek>(
|
||||
encoder: &mut tiff::encoder::TiffEncoder<W>,
|
||||
samples: &[u16],
|
||||
pixels: usize,
|
||||
channels: usize,
|
||||
image: &EncodeImage,
|
||||
meta: &EncodeMeta,
|
||||
) -> Result<()> {
|
||||
use tiff::encoder::colortype;
|
||||
match channels {
|
||||
1 => write_tiff_image!(encoder, image, meta, colortype::Gray16, &samples[..pixels], false),
|
||||
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA16, &expanded_gray_alpha(samples, pixels), true),
|
||||
3 => write_tiff_image!(encoder, image, meta, colortype::RGB16, &samples[..pixels * 3], false),
|
||||
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA16, &samples[..pixels * 4], true),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_tiff_f32<W: std::io::Write + std::io::Seek>(
|
||||
encoder: &mut tiff::encoder::TiffEncoder<W>,
|
||||
samples: &[f32],
|
||||
pixels: usize,
|
||||
channels: usize,
|
||||
image: &EncodeImage,
|
||||
meta: &EncodeMeta,
|
||||
) -> Result<()> {
|
||||
use tiff::encoder::colortype;
|
||||
match channels {
|
||||
1 => write_tiff_image!(encoder, image, meta, colortype::Gray32Float, &samples[..pixels], false),
|
||||
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA32Float, &expanded_gray_alpha(samples, pixels), true),
|
||||
3 => write_tiff_image!(encoder, image, meta, colortype::RGB32Float, &samples[..pixels * 3], false),
|
||||
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA32Float, &samples[..pixels * 4], true),
|
||||
}
|
||||
Ok(())
|
||||
let ic_opts = craft_image_codecs::EncodeOptions { tiff_compression, ..Default::default() };
|
||||
craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Tiff, &ic_opts).map_err(|e| Error::Encode(e.to_string()))
|
||||
}
|
||||
|
||||
/// Encode a flat PSD (8/16-bit gray or RGB, no layers; alpha dropped): the hand-off an image
|
||||
@@ -342,27 +238,49 @@ pub fn encode_webp_lossless(img: &EncodeImage, meta: &EncodeMeta) -> Result<Vec<
|
||||
return Err(Error::Encode("WebP needs 8-bit samples".into()));
|
||||
};
|
||||
let n = img.width as usize * img.height as usize * img.channels as usize;
|
||||
let ct = match img.channels {
|
||||
1 => image_webp::ColorType::L8,
|
||||
2 => image_webp::ColorType::La8,
|
||||
3 => image_webp::ColorType::Rgb8,
|
||||
_ => image_webp::ColorType::Rgba8,
|
||||
let layout = match img.channels {
|
||||
1 => craft_image_codecs::ChannelLayout::Gray,
|
||||
2 => craft_image_codecs::ChannelLayout::GrayA,
|
||||
3 => craft_image_codecs::ChannelLayout::Rgb,
|
||||
_ => craft_image_codecs::ChannelLayout::Rgba,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let mut enc = image_webp::WebPEncoder::new(&mut out);
|
||||
if let Some(icc) = meta.icc {
|
||||
enc.set_icc_profile(icc.to_vec());
|
||||
}
|
||||
let mut ic_img = craft_image_codecs::Image::from_u8(img.width, img.height, layout, s[..n].to_vec()).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
ic_img.icc = meta.icc.map(|b| b.to_vec());
|
||||
ic_img.meta.exif = meta.exif.map(|b| b.to_vec());
|
||||
ic_img.meta.xmp = meta.xmp.map(|x| x.to_string());
|
||||
let ic_opts = craft_image_codecs::EncodeOptions { webp_lossless: true, ..Default::default() };
|
||||
let mut out = craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::WebP, &ic_opts).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
if let Some(exif) = meta.exif {
|
||||
enc.set_exif_metadata(exif.to_vec());
|
||||
replace_webp_exif_chunk(&mut out, exif);
|
||||
}
|
||||
if let Some(xmp) = meta.xmp {
|
||||
enc.set_xmp_metadata(xmp.as_bytes().to_vec());
|
||||
}
|
||||
enc.encode(&s[..n], img.width, img.height, ct).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Replace the `EXIF` RIFF chunk payload in a WebP file so caller-supplied EXIF (including
|
||||
/// non-1 orientation tags) is preserved verbatim.
|
||||
fn replace_webp_exif_chunk(webp: &mut Vec<u8>, exif: &[u8]) {
|
||||
let mut p = 12usize;
|
||||
while let Some(h) = webp.get(p..p.saturating_add(8)) {
|
||||
let size = u32::from_le_bytes([h[4], h[5], h[6], h[7]]) as usize;
|
||||
let end = p.saturating_add(8).saturating_add(size);
|
||||
let padded_end = end.saturating_add(size & 1);
|
||||
if &h[0..4] == b"EXIF" && padded_end <= webp.len() {
|
||||
let mut replacement = Vec::with_capacity(8 + exif.len() + (exif.len() & 1));
|
||||
replacement.extend_from_slice(b"EXIF");
|
||||
replacement.extend_from_slice(&(exif.len() as u32).to_le_bytes());
|
||||
replacement.extend_from_slice(exif);
|
||||
if exif.len() & 1 == 1 {
|
||||
replacement.push(0);
|
||||
}
|
||||
webp.splice(p..padded_end, replacement);
|
||||
let riff_size = (webp.len().saturating_sub(8)) as u32;
|
||||
webp[4..8].copy_from_slice(&riff_size.to_le_bytes());
|
||||
return;
|
||||
}
|
||||
p = padded_end;
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode AVIF (sRGB, 4:4:4, 10-bit AV1) with `ravif` (rav1e). 8-bit samples are widened by the
|
||||
/// encoder; 16-bit samples keep 10 bits of precision (BT.601 full-range YCbCr computed here).
|
||||
/// `quality` 1..=100, `speed` 1 (slow) ..= 10. EXIF is embedded; ICC is not supported by the muxer
|
||||
@@ -372,37 +290,27 @@ pub fn encode_avif(img: &EncodeImage, quality: u8, speed: u8, meta: &EncodeMeta)
|
||||
img.validate()?;
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
{
|
||||
let mut enc = ravif::Encoder::new()
|
||||
.with_quality(quality.clamp(1, 100) as f32)
|
||||
.with_alpha_quality(quality.clamp(1, 100) as f32)
|
||||
.with_speed(speed.clamp(1, 10));
|
||||
if let Some(exif) = meta.exif {
|
||||
enc = enc.with_exif(exif.to_vec());
|
||||
}
|
||||
let s = match img.samples {
|
||||
Samples::U8(s) => s,
|
||||
Samples::U16(s) => return avif_10bit(&enc, img, s),
|
||||
Samples::F32(_) => return Err(Error::Encode("AVIF encoder needs 8- or 16-bit samples".into())),
|
||||
// Keep AVIF on its threading-capable shared revision without changing other codecs.
|
||||
use craft_avif_encode::{ChannelLayout, Image};
|
||||
let n = img.width as usize * img.height as usize * img.channels as usize;
|
||||
let layout = match img.channels {
|
||||
1 => ChannelLayout::Gray,
|
||||
2 => ChannelLayout::GrayA,
|
||||
3 => ChannelLayout::Rgb,
|
||||
_ => ChannelLayout::Rgba,
|
||||
};
|
||||
let n = img.width as usize * img.height as usize;
|
||||
let ch = img.channels as usize;
|
||||
let px: Vec<ravif::RGBA8> = s
|
||||
.chunks_exact(ch)
|
||||
.take(n)
|
||||
.map(|c| match ch {
|
||||
1 => ravif::RGBA8::new(c[0], c[0], c[0], 255),
|
||||
2 => ravif::RGBA8::new(c[0], c[0], c[0], c[1]),
|
||||
3 => ravif::RGBA8::new(c[0], c[1], c[2], 255),
|
||||
_ => ravif::RGBA8::new(c[0], c[1], c[2], c[3]),
|
||||
})
|
||||
.collect();
|
||||
let r = enc.encode_rgba(ravif::Img::new(&px[..], img.width as usize, img.height as usize)).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
let _ = img.has_alpha();
|
||||
Ok(r.avif_file)
|
||||
let mut ic_img = match img.samples {
|
||||
Samples::U8(s) => Image::from_u8(img.width, img.height, layout, s[..n].to_vec()),
|
||||
Samples::U16(s) => Image::from_u16(img.width, img.height, layout, &s[..n]),
|
||||
Samples::F32(_) => return Err(Error::Encode("AVIF encoder needs 8- or 16-bit samples".into())),
|
||||
}
|
||||
.map_err(|e| Error::Encode(e.to_string()))?;
|
||||
ic_img.meta.exif = meta.exif.map(|e| e.to_vec());
|
||||
craft_avif_encode::encode_avif_with_speed(&ic_img, quality, speed).map_err(|e| Error::Encode(e.to_string()))
|
||||
}
|
||||
#[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))]
|
||||
{
|
||||
let _ = (quality, speed, meta, img.has_alpha());
|
||||
let _ = (quality, speed, meta);
|
||||
Err(Error::Encode("AVIF encoding is not available in this build".into()))
|
||||
}
|
||||
}
|
||||
@@ -474,108 +382,12 @@ pub fn encode_avif_hdr(width: u32, height: u32, rgb: &[f32], quality: u8, speed:
|
||||
}
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
{
|
||||
use rav1e::prelude::*;
|
||||
const K: [f32; 3] = [0.2627, 0.6780, 0.0593]; // BT.2020 NCL
|
||||
let mut max_nits = 0f32;
|
||||
let mut sum_nits = 0f64;
|
||||
let planes: Vec<[u16; 3]> = rgb
|
||||
.as_chunks::<3>()
|
||||
.0
|
||||
.iter()
|
||||
.take(n)
|
||||
.map(|c| {
|
||||
let nits = c.map(|v| (if v.is_finite() { v.max(0.0) } else { 0.0 }) * HDR_REFERENCE_WHITE_NITS);
|
||||
let y_nits = K[0] * nits[0] + K[1] * nits[1] + K[2] * nits[2];
|
||||
max_nits = max_nits.max(nits[0].max(nits[1]).max(nits[2]));
|
||||
sum_nits += y_nits as f64;
|
||||
let [r, g, b] = match transfer {
|
||||
HdrTransfer::Pq => nits.map(pq_encode),
|
||||
HdrTransfer::Hlg => hlg_signal([c[0], c[1], c[2]]),
|
||||
};
|
||||
let y = K[0] * r + K[1] * g + K[2] * b;
|
||||
let cb = (b - y) / (2.0 * (1.0 - K[2])) + 0.5;
|
||||
let cr = (r - y) / (2.0 * (1.0 - K[0])) + 0.5;
|
||||
[y, cb, cr].map(|v| (v * 1023.0).round().clamp(0.0, 1023.0) as u16)
|
||||
})
|
||||
.collect();
|
||||
let q = quality.clamp(1, 100) as f32 / 100.0;
|
||||
// ravif's quality → quantizer curve, so qualities match the SDR AVIF path
|
||||
let x = if q >= 0.82 {
|
||||
(1.0 - q) * 2.6
|
||||
} else if q > 0.25 {
|
||||
1.0 - 0.125 - q * 0.5
|
||||
} else {
|
||||
1.0 - q
|
||||
let _ = (w, h, n);
|
||||
let t = match transfer {
|
||||
HdrTransfer::Pq => craft_avif_encode::HdrTransfer::Pq,
|
||||
HdrTransfer::Hlg => craft_avif_encode::HdrTransfer::Hlg,
|
||||
};
|
||||
let quantizer = (x * 255.0).round() as usize;
|
||||
let mut ec = EncoderConfig::with_speed_preset(speed.clamp(1, 10));
|
||||
ec.width = w;
|
||||
ec.height = h;
|
||||
ec.time_base = Rational::new(1, 1);
|
||||
ec.bit_depth = 10;
|
||||
ec.chroma_sampling = ChromaSampling::Cs444;
|
||||
ec.pixel_range = PixelRange::Full;
|
||||
ec.color_description = Some(ColorDescription {
|
||||
color_primaries: ColorPrimaries::BT2020,
|
||||
transfer_characteristics: match transfer {
|
||||
HdrTransfer::Pq => TransferCharacteristics::SMPTE2084,
|
||||
HdrTransfer::Hlg => TransferCharacteristics::HLG,
|
||||
},
|
||||
matrix_coefficients: MatrixCoefficients::BT2020NCL,
|
||||
});
|
||||
let cll = (max_nits.ceil().clamp(1.0, 10_000.0) as u16, ((sum_nits / n as f64).ceil().clamp(1.0, 10_000.0)) as u16);
|
||||
ec.content_light =
|
||||
(transfer == HdrTransfer::Pq).then_some(ContentLight { max_content_light_level: cll.0, max_frame_average_light_level: cll.1 });
|
||||
ec.still_picture = true;
|
||||
ec.quantizer = quantizer;
|
||||
ec.min_quantizer = quantizer.min(255) as u8;
|
||||
ec.speed_settings.multiref = false;
|
||||
ec.speed_settings.rdo_lookahead_frames = 1;
|
||||
ec.speed_settings.scene_detection_mode = SceneDetectionSpeed::None;
|
||||
let e = |e: &dyn std::fmt::Display| Error::Encode(format!("AV1: {e}"));
|
||||
let mut ctx: Context<u16> = Config::new().with_encoder_config(ec).new_context().map_err(|x| e(&x))?;
|
||||
let mut frame = ctx.new_frame();
|
||||
{
|
||||
let mut it = planes.iter();
|
||||
let mut fp = frame.planes.iter_mut();
|
||||
let (Some(py), Some(pu), Some(pv)) = (fp.next(), fp.next(), fp.next()) else {
|
||||
return Err(Error::Encode("AV1: frame has no planes".into()));
|
||||
};
|
||||
let (mut sy, mut su, mut sv) = (py.mut_slice(Default::default()), pu.mut_slice(Default::default()), pv.mut_slice(Default::default()));
|
||||
for ((ry, ru), rv) in sy.rows_iter_mut().zip(su.rows_iter_mut()).zip(sv.rows_iter_mut()).take(h) {
|
||||
for ((y, u), v) in ry.iter_mut().zip(ru.iter_mut()).zip(rv.iter_mut()).take(w) {
|
||||
let Some(p) = it.next() else { break };
|
||||
(*y, *u, *v) = (p[0], p[1], p[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.send_frame(frame).map_err(|x| e(&x))?;
|
||||
ctx.flush();
|
||||
let mut av1 = Vec::new();
|
||||
loop {
|
||||
match ctx.receive_packet() {
|
||||
Ok(mut p) if p.frame_type == FrameType::KEY => av1.append(&mut p.data),
|
||||
Ok(_) => {}
|
||||
Err(EncoderStatus::Encoded | EncoderStatus::LimitReached) => break,
|
||||
Err(x) => return Err(e(&x)),
|
||||
}
|
||||
}
|
||||
use avif_serialize::constants as c;
|
||||
let mut a = avif_serialize::Aviffy::new();
|
||||
a.set_matrix_coefficients(c::MatrixCoefficients::Bt2020Ncl)
|
||||
.set_transfer_characteristics(match transfer {
|
||||
HdrTransfer::Pq => c::TransferCharacteristics::Smpte2084,
|
||||
HdrTransfer::Hlg => c::TransferCharacteristics::Hlg,
|
||||
})
|
||||
.set_color_primaries(c::ColorPrimaries::Bt2020)
|
||||
.set_full_color_range(true);
|
||||
if transfer == HdrTransfer::Pq {
|
||||
a.set_content_light_level(cll.0, cll.1);
|
||||
}
|
||||
if let Some(exif) = meta.exif {
|
||||
a.set_exif(exif.to_vec());
|
||||
}
|
||||
Ok(a.to_vec(&av1, None, width, height, 10))
|
||||
craft_avif_encode::encode_avif_hdr(width, height, rgb, quality, speed, meta.exif, t).map_err(|e| Error::Encode(e.to_string()))
|
||||
}
|
||||
#[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))]
|
||||
{
|
||||
@@ -594,83 +406,51 @@ pub fn encode_avif_hdr(width: u32, height: u32, rgb: &[f32], quality: u8, speed:
|
||||
pub fn encode_png_pq(width: u32, height: u32, rgb: &[f32], meta: &EncodeMeta) -> Result<Vec<u8>> {
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
let n = w.checked_mul(h).ok_or_else(|| Error::Encode("image too large".into()))?;
|
||||
if n == 0 || n.checked_mul(3).is_none_or(|need| rgb.len() < need) {
|
||||
let samples = n.checked_mul(3).ok_or_else(|| Error::Encode("image too large".into()))?;
|
||||
if n == 0 || rgb.len() < samples {
|
||||
return Err(Error::Encode("HDR PNG: sample buffer too short".into()));
|
||||
}
|
||||
const K: [f32; 3] = [0.2627, 0.6780, 0.0593]; // BT.2020 luminance
|
||||
let mut max_nits = 0f32;
|
||||
let mut sum_nits = 0f64;
|
||||
let mut bytes = Vec::with_capacity(n * 6);
|
||||
for c in rgb.as_chunks::<3>().0.iter().take(n) {
|
||||
let nits = c.map(|v| (if v.is_finite() { v.max(0.0) } else { 0.0 }) * HDR_REFERENCE_WHITE_NITS);
|
||||
max_nits = max_nits.max(nits[0].max(nits[1]).max(nits[2]));
|
||||
sum_nits += (K[0] * nits[0] + K[1] * nits[1] + K[2] * nits[2]) as f64;
|
||||
for v in nits {
|
||||
bytes.extend_from_slice(&((pq_encode(v) * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes());
|
||||
}
|
||||
}
|
||||
let cll = (max_nits.ceil().clamp(1.0, 10_000.0) as u32, ((sum_nits / n as f64).ceil().clamp(1.0, 10_000.0)) as u32);
|
||||
let mut info = png::Info::with_size(width, height);
|
||||
info.color_type = png::ColorType::Rgb;
|
||||
info.bit_depth = png::BitDepth::Sixteen;
|
||||
info.exif_metadata = meta.exif.map(|b| b.to_vec().into());
|
||||
info.pixel_dims = meta.ppi.filter(|p| *p > 0).map(|p| {
|
||||
let ppm = (p as f64 / 0.0254).round() as u32;
|
||||
png::PixelDimensions { xppu: ppm, yppu: ppm, unit: png::Unit::Meter }
|
||||
});
|
||||
let mut out = Vec::new();
|
||||
let e = |e: png::EncodingError| Error::Encode(e.to_string());
|
||||
{
|
||||
let mut enc = png::Encoder::with_info(&mut out, info).map_err(e)?;
|
||||
enc.set_compression(png::Compression::Fast);
|
||||
if let Some(xmp) = meta.xmp {
|
||||
enc.add_itxt_chunk("XML:com.adobe.xmp".into(), xmp.into()).map_err(e)?;
|
||||
}
|
||||
let mut wr = enc.write_header().map_err(e)?;
|
||||
// BT.2020 primaries (9), PQ (16), RGB (0), full range (1)
|
||||
wr.write_chunk(png::chunk::ChunkType(*b"cICP"), &[9, 16, 0, 1]).map_err(e)?;
|
||||
// MaxCLL and MaxFALL in units of 0.0001 cd/m²
|
||||
let clli = [(cll.0 * 10_000).to_be_bytes(), (cll.1 * 10_000).to_be_bytes()].concat();
|
||||
wr.write_chunk(png::chunk::ChunkType(*b"cLLI"), &clli).map_err(e)?;
|
||||
wr.write_image_data(&bytes).map_err(e)?;
|
||||
wr.finish().map_err(e)?;
|
||||
}
|
||||
Ok(out)
|
||||
let mut image = craft_image_codecs::Image::from_f32(
|
||||
width,
|
||||
height,
|
||||
craft_image_codecs::ChannelLayout::Rgb,
|
||||
rgb.get(..samples).ok_or_else(|| Error::Encode("HDR PNG: sample buffer too short".into()))?,
|
||||
)
|
||||
.map_err(|e| Error::Encode(e.to_string()))?;
|
||||
image.meta.exif = meta.exif.map(ToOwned::to_owned);
|
||||
image.meta.xmp = meta.xmp.map(ToOwned::to_owned);
|
||||
image.meta.dpi = meta.ppi.filter(|&ppi| ppi > 0).map(|ppi| (f32::from(ppi), f32::from(ppi)));
|
||||
let options = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
|
||||
craft_image_codecs::encode_png_pq(&image, &options).map_err(|e| Error::Encode(e.to_string()))
|
||||
}
|
||||
|
||||
/// 16-bit RGB(A) → 10-bit BT.601 full-range YCbCr planes (the matrix `ravif` uses for 8-bit input).
|
||||
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
|
||||
fn avif_10bit(enc: &ravif::Encoder, img: &EncodeImage, s: &[u16]) -> Result<Vec<u8>> {
|
||||
const K: [f32; 3] = [0.299, 0.587, 0.114];
|
||||
let n = img.width as usize * img.height as usize;
|
||||
let ch = img.channels as usize;
|
||||
let rgb = |c: &[u16]| -> [f32; 3] {
|
||||
let v = |x: u16| x as f32 * (1023.0 / 65535.0);
|
||||
match ch {
|
||||
1 | 2 => [v(c[0]); 3],
|
||||
_ => [v(c[0]), v(c[1]), v(c[2])],
|
||||
fn png_chunk(kind: [u8; 4], data: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(12 + data.len());
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(&kind);
|
||||
out.extend_from_slice(data);
|
||||
let mut crc = 0xFFFF_FFFFu32;
|
||||
for &b in &out[4..] {
|
||||
crc ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
|
||||
}
|
||||
};
|
||||
let planes = s.chunks_exact(ch).take(n).map(|c| {
|
||||
let [r, g, b] = rgb(c);
|
||||
let y = K[0] * r + K[1] * g + K[2] * b;
|
||||
let cb = (b - y) * (0.5 / (1.0 - K[2])) + 512.0;
|
||||
let cr = (r - y) * (0.5 / (1.0 - K[0])) + 512.0;
|
||||
[y, cb, cr].map(|v| v.round().clamp(0.0, 1023.0) as u16)
|
||||
});
|
||||
let alpha_at = |c: &[u16]| if img.has_alpha() { c[ch - 1] } else { u16::MAX };
|
||||
let has_alpha = s.chunks_exact(ch).take(n).any(|c| alpha_at(c) != u16::MAX);
|
||||
let alpha = has_alpha.then(|| s.chunks_exact(ch).take(n).map(move |c| ((alpha_at(c) as u32 * 1023 + 32767) / 65535) as u16));
|
||||
let r = enc
|
||||
.encode_raw_planes_10_bit(img.width as usize, img.height as usize, planes, alpha, ravif::PixelRange::Full, ravif::MatrixCoefficients::BT601)
|
||||
.map_err(|e| Error::Encode(e.to_string()))?;
|
||||
Ok(r.avif_file)
|
||||
}
|
||||
out.extend_from_slice(&(!crc).to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod hlg_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dimensions_whose_sample_count_wraps_are_refused() {
|
||||
// 2^31 x 2^31 x 4 is 2^64 samples: zero when wrapped, which an empty buffer would satisfy
|
||||
let img = EncodeImage::new(1 << 31, 1 << 31, 4, Samples::U8(&[]));
|
||||
assert!(img.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hlg_reference_white_and_peak() {
|
||||
// BT.2408: SDR (HDR reference) white sits at 75 % HLG signal
|
||||
|
||||
@@ -57,6 +57,7 @@ impl<'a> Tiff<'a> {
|
||||
Some((v, next))
|
||||
}
|
||||
/// First value of a SHORT/LONG entry.
|
||||
#[cfg(test)]
|
||||
pub fn uint(&self, e: &Entry) -> Option<u32> {
|
||||
match e.typ {
|
||||
3 => self.u16_at(e.value_pos).map(u32::from),
|
||||
@@ -80,6 +81,10 @@ impl<'a> Tiff<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub use craft_metadata::compat_orientation::minimal_exif;
|
||||
pub(crate) use craft_metadata::compat_orientation::summarize;
|
||||
|
||||
#[cfg(test)]
|
||||
/// What the decoder cares about from an EXIF (TIFF-structured) blob.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct ExifSummary {
|
||||
@@ -90,7 +95,8 @@ pub(crate) struct ExifSummary {
|
||||
pub adobe_rgb_hint: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn summarize(blob: &[u8]) -> ExifSummary {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn legacy_reference(blob: &[u8]) -> ExifSummary {
|
||||
let mut s = ExifSummary::default();
|
||||
let Some(t) = Tiff::new(blob) else { return s };
|
||||
let Some(ifd0) = t.first_ifd() else { return s };
|
||||
@@ -130,23 +136,6 @@ pub(crate) fn summarize(blob: &[u8]) -> ExifSummary {
|
||||
s
|
||||
}
|
||||
|
||||
/// Build a tiny EXIF blob (little-endian TIFF) with just an orientation tag. Used by tests and by
|
||||
/// callers that need to stamp orientation on export when no source EXIF exists.
|
||||
pub fn minimal_exif(orientation: u16) -> Vec<u8> {
|
||||
let mut v = Vec::with_capacity(26);
|
||||
v.extend_from_slice(b"II");
|
||||
v.extend_from_slice(&42u16.to_le_bytes());
|
||||
v.extend_from_slice(&8u32.to_le_bytes());
|
||||
v.extend_from_slice(&1u16.to_le_bytes());
|
||||
v.extend_from_slice(&0x0112u16.to_le_bytes());
|
||||
v.extend_from_slice(&3u16.to_le_bytes());
|
||||
v.extend_from_slice(&1u32.to_le_bytes());
|
||||
v.extend_from_slice(&orientation.to_le_bytes());
|
||||
v.extend_from_slice(&[0, 0]);
|
||||
v.extend_from_slice(&0u32.to_le_bytes());
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -160,7 +149,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn garbage_ok() {
|
||||
assert_eq!(summarize(b"II*\0\xff\xff\xff\xff"), ExifSummary::default());
|
||||
assert_eq!(summarize(&[]), ExifSummary::default());
|
||||
assert_eq!(legacy_reference(b"II*\0\xff\xff\xff\xff"), ExifSummary::default());
|
||||
assert_eq!(legacy_reference(&[]), ExifSummary::default());
|
||||
}
|
||||
}
|
||||
+95
-637
@@ -1,546 +1,20 @@
|
||||
//! Gain map HDR images (ISO 21496-1): an SDR base image plus a gain map that a decoder uses to
|
||||
//! rebuild the HDR rendition, so the file looks right everywhere and lights up on HDR displays.
|
||||
//! Gain map JPEGs (ISO 21496-1): an SDR base image plus a gain map that a decoder uses to rebuild
|
||||
//! the HDR rendition, so the file looks right everywhere and lights up on HDR displays.
|
||||
//!
|
||||
//! The metadata formats and the arithmetic ([`compute`], [`apply`], [`GainMapMeta`]) are
|
||||
//! `craft-gainmap`'s, re-exported here. This module lays the two images out in a JPEG:
|
||||
//!
|
||||
//! - [`compute`] measures a gain map from an SDR and an HDR rendition of the same picture (linear
|
||||
//! light, same primaries). Measure it against the base *as written* (decoded from its 8-bit
|
||||
//! codes), so quantisation in the base is handed back by the gain map.
|
||||
//! - [`apply`] rebuilds the HDR rendition from a base and its gain map.
|
||||
//! - [`encode_jpeg`] writes a gain map JPEG: the base with an MPF index (CIPA DC-007), the ISO
|
||||
//! 21496-1 marker and Adobe/Google container XMP, followed by the gain map JPEG carrying the ISO
|
||||
//! 21496-1 metadata, the Adobe `hdrgm` XMP (Android, Chrome) and Apple's description of the same
|
||||
//! map (what survives an iMessage send).
|
||||
//! - [`read_jpeg`] finds and decodes the gain map of a gain map JPEG (ours, cameras, Lightroom),
|
||||
//! from its ISO 21496-1 metadata or, failing that, its `hdrgm` XMP.
|
||||
//!
|
||||
//! All gains are log2. A decoder recovers `log2(hdr + offset_hdr) − log2(sdr + offset_sdr)` as
|
||||
//! `min + (max − min) · (code / 255)^(1 / gamma)`, scaled by a weight in 0..1 that depends on how
|
||||
//! much headroom the display has between `base_headroom` and `alternate_headroom`.
|
||||
|
||||
pub use craft_gainmap::{GainImage, GainMapMeta, GainMapOptions, ISO_URN, apply, compute};
|
||||
|
||||
use crate::encode::{EncodeImage, EncodeMeta, Samples, jpeg_app_segments, xmp_segment};
|
||||
use crate::{ChromaSubsampling, Error, Format, Result, jpeg, jpeg_par};
|
||||
|
||||
/// The ISO 21496-1 namespace that opens its APP2 payloads (NUL terminated).
|
||||
pub const ISO_URN: &[u8] = b"urn:iso:std:iso:ts:21496:-1\0";
|
||||
|
||||
/// Fixed denominator for the metadata's rationals: one value per setting, byte-identical output.
|
||||
const DENOMINATOR: u32 = 1_000_000;
|
||||
|
||||
/// Gain map parameters (ISO 21496-1 / Adobe `hdrgm`). Per-channel arrays repeat the first value
|
||||
/// when the map is single-channel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct GainMapMeta {
|
||||
/// Three gain channels (R, G, B) instead of one luminance gain.
|
||||
pub multichannel: bool,
|
||||
/// The gain applies in the base image's colour space.
|
||||
pub use_base_colour_space: bool,
|
||||
/// log2 headroom at which the base is shown as is (0: an SDR base).
|
||||
pub base_headroom: f32,
|
||||
/// log2 headroom at which the gain map applies in full.
|
||||
pub alternate_headroom: f32,
|
||||
pub min: [f32; 3],
|
||||
pub max: [f32; 3],
|
||||
pub gamma: [f32; 3],
|
||||
pub base_offset: [f32; 3],
|
||||
pub alternate_offset: [f32; 3],
|
||||
}
|
||||
|
||||
impl Default for GainMapMeta {
|
||||
fn default() -> Self {
|
||||
GainMapMeta {
|
||||
multichannel: false,
|
||||
use_base_colour_space: true,
|
||||
base_headroom: 0.0,
|
||||
alternate_headroom: 1.0,
|
||||
min: [0.0; 3],
|
||||
max: [1.0; 3],
|
||||
gamma: [1.0; 3],
|
||||
base_offset: [1.0 / 64.0; 3],
|
||||
alternate_offset: [1.0 / 64.0; 3],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GainMapMeta {
|
||||
fn channels(&self) -> usize {
|
||||
if self.multichannel { 3 } else { 1 }
|
||||
}
|
||||
|
||||
/// Usable by [`apply`]: finite, positive gammas, max ≥ min, headrooms in order.
|
||||
pub fn is_valid(&self) -> bool {
|
||||
let fin = |a: &[f32; 3]| a.iter().all(|v| v.is_finite());
|
||||
fin(&self.min)
|
||||
&& fin(&self.max)
|
||||
&& fin(&self.gamma)
|
||||
&& fin(&self.base_offset)
|
||||
&& fin(&self.alternate_offset)
|
||||
&& self.gamma.iter().all(|g| *g > 0.0)
|
||||
&& self.min.iter().zip(&self.max).all(|(a, b)| b >= a)
|
||||
&& self.base_headroom.is_finite()
|
||||
&& self.alternate_headroom.is_finite()
|
||||
&& self.alternate_headroom > self.base_headroom
|
||||
}
|
||||
|
||||
/// The ISO 21496-1 APP2 payload of the gain map image, URN included.
|
||||
pub fn to_iso(&self) -> Vec<u8> {
|
||||
let mut p = ISO_URN.to_vec();
|
||||
p.extend_from_slice(&0u16.to_be_bytes()); // minimum_version: readers gate on this
|
||||
p.extend_from_slice(&0u16.to_be_bytes()); // writer_version
|
||||
let mut flags = 0u8;
|
||||
if self.multichannel {
|
||||
flags |= FLAG_MULTICHANNEL;
|
||||
}
|
||||
if self.use_base_colour_space {
|
||||
flags |= FLAG_BASE_COLOUR_SPACE;
|
||||
}
|
||||
p.push(flags);
|
||||
let unsigned = |p: &mut Vec<u8>, v: f32| {
|
||||
let n = (v as f64 * DENOMINATOR as f64).round().clamp(0.0, u32::MAX as f64) as u32;
|
||||
p.extend_from_slice(&n.to_be_bytes());
|
||||
p.extend_from_slice(&DENOMINATOR.to_be_bytes());
|
||||
};
|
||||
let signed = |p: &mut Vec<u8>, v: f32| {
|
||||
let n = (v as f64 * DENOMINATOR as f64).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32;
|
||||
p.extend_from_slice(&n.to_be_bytes());
|
||||
p.extend_from_slice(&DENOMINATOR.to_be_bytes());
|
||||
};
|
||||
unsigned(&mut p, self.base_headroom.max(0.0));
|
||||
unsigned(&mut p, self.alternate_headroom.max(0.0));
|
||||
for c in 0..self.channels() {
|
||||
signed(&mut p, self.min[c]);
|
||||
signed(&mut p, self.max[c]);
|
||||
unsigned(&mut p, self.gamma[c]);
|
||||
signed(&mut p, self.base_offset[c]);
|
||||
signed(&mut p, self.alternate_offset[c]);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Parse an ISO 21496-1 payload (the bytes after [`ISO_URN`]). `None` for the versions-only
|
||||
/// marker a primary image carries, unknown versions, a base that is the HDR rendition, or
|
||||
/// values no decoder could use.
|
||||
pub fn from_iso(p: &[u8]) -> Option<GainMapMeta> {
|
||||
let mut r = Reader { b: p, at: 0 };
|
||||
let min_version = r.u16()?;
|
||||
let _writer_version = r.u16()?;
|
||||
if min_version != 0 {
|
||||
return None;
|
||||
}
|
||||
let flags = r.u8()?;
|
||||
if flags & FLAG_BACKWARD != 0 {
|
||||
return None;
|
||||
}
|
||||
let multichannel = flags & FLAG_MULTICHANNEL != 0;
|
||||
let common = flags & FLAG_COMMON_DENOMINATOR != 0;
|
||||
let common_d = if common { r.u32()? } else { 0 };
|
||||
let unsigned = |r: &mut Reader| -> Option<f32> {
|
||||
let n = r.u32()?;
|
||||
let d = if common { common_d } else { r.u32()? };
|
||||
(d != 0).then(|| (n as f64 / d as f64) as f32)
|
||||
};
|
||||
let signed = |r: &mut Reader| -> Option<f32> {
|
||||
let n = r.u32()? as i32;
|
||||
let d = if common { common_d } else { r.u32()? };
|
||||
(d != 0).then(|| (n as f64 / d as f64) as f32)
|
||||
};
|
||||
let mut m = GainMapMeta {
|
||||
multichannel,
|
||||
use_base_colour_space: flags & FLAG_BASE_COLOUR_SPACE != 0,
|
||||
base_headroom: unsigned(&mut r)?,
|
||||
alternate_headroom: unsigned(&mut r)?,
|
||||
..GainMapMeta::default()
|
||||
};
|
||||
for c in 0..m.channels() {
|
||||
m.min[c] = signed(&mut r)?;
|
||||
m.max[c] = signed(&mut r)?;
|
||||
m.gamma[c] = unsigned(&mut r)?;
|
||||
m.base_offset[c] = signed(&mut r)?;
|
||||
m.alternate_offset[c] = signed(&mut r)?;
|
||||
}
|
||||
if !multichannel {
|
||||
m.fill_from_first();
|
||||
}
|
||||
m.is_valid().then_some(m)
|
||||
}
|
||||
|
||||
fn fill_from_first(&mut self) {
|
||||
for a in [&mut self.min, &mut self.max, &mut self.gamma, &mut self.base_offset, &mut self.alternate_offset] {
|
||||
a[1] = a[0];
|
||||
a[2] = a[0];
|
||||
}
|
||||
}
|
||||
|
||||
/// The gain parameters from Adobe `hdrgm` XMP (the gain map image's packet), for files
|
||||
/// without ISO 21496-1 metadata (the first Ultra HDR files). Attributes or `rdf:Seq` lists.
|
||||
pub fn from_hdrgm_xmp(xmp: &str) -> Option<GainMapMeta> {
|
||||
if !xmp.contains("hdrgm:") {
|
||||
return None;
|
||||
}
|
||||
let base_rendition_hdr = xmp_values(xmp, "BaseRenditionIsHDR").is_some_and(|v| v.first().is_some_and(|s| s.eq_ignore_ascii_case("true")));
|
||||
if base_rendition_hdr {
|
||||
return None;
|
||||
}
|
||||
let get = |name: &str, default: f32| -> Option<([f32; 3], bool)> {
|
||||
let Some(v) = xmp_values(xmp, name) else { return Some(([default; 3], false)) };
|
||||
let f: Vec<f32> = v.iter().map(|s| s.trim().parse::<f32>().ok()).collect::<Option<_>>()?;
|
||||
match f.as_slice() {
|
||||
[a] => Some(([*a; 3], false)),
|
||||
[a, b, c] => Some(([*a, *b, *c], true)),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let (max, m1) = get("GainMapMax", f32::NAN)?;
|
||||
if max.iter().any(|v| v.is_nan()) {
|
||||
return None; // the one required parameter
|
||||
}
|
||||
let (min, m2) = get("GainMapMin", 0.0)?;
|
||||
let (gamma, m3) = get("Gamma", 1.0)?;
|
||||
let (base_offset, m4) = get("OffsetSDR", 1.0 / 64.0)?;
|
||||
let (alternate_offset, m5) = get("OffsetHDR", 1.0 / 64.0)?;
|
||||
let (cap_min, _) = get("HDRCapacityMin", 0.0)?;
|
||||
let max_gain = max.iter().copied().fold(f32::MIN, f32::max);
|
||||
let (cap_max, _) = get("HDRCapacityMax", max_gain)?;
|
||||
let m = GainMapMeta {
|
||||
multichannel: m1 || m2 || m3 || m4 || m5,
|
||||
use_base_colour_space: true,
|
||||
base_headroom: cap_min[0].max(0.0),
|
||||
alternate_headroom: cap_max[0],
|
||||
min,
|
||||
max,
|
||||
gamma,
|
||||
base_offset,
|
||||
alternate_offset,
|
||||
};
|
||||
m.is_valid().then_some(m)
|
||||
}
|
||||
|
||||
/// The gain map image's XMP: the Adobe `hdrgm` parameters (read by Android and Chrome, which
|
||||
/// ignore the ISO payload) and Apple's description of the same map (what iMessage keeps).
|
||||
pub fn to_gain_map_xmp(&self) -> String {
|
||||
let names = ["GainMapMin", "GainMapMax", "Gamma", "OffsetSDR", "OffsetHDR"];
|
||||
let values = [&self.min, &self.max, &self.gamma, &self.base_offset, &self.alternate_offset];
|
||||
let uniform = |v: &[f32; 3]| !self.multichannel || (v[0] == v[1] && v[1] == v[2]);
|
||||
let mut s = String::from(XMP_OPEN);
|
||||
s.push_str(r#"<rdf:Description rdf:about="" xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/" hdrgm:Version="1.0""#);
|
||||
s.push_str(&format!(r#" hdrgm:HDRCapacityMin="{}""#, num(self.base_headroom)));
|
||||
s.push_str(&format!(r#" hdrgm:HDRCapacityMax="{}""#, num(self.alternate_headroom)));
|
||||
s.push_str(r#" hdrgm:BaseRenditionIsHDR="False""#);
|
||||
for (n, v) in names.iter().zip(values) {
|
||||
if uniform(v) {
|
||||
s.push_str(&format!(r#" hdrgm:{n}="{}""#, num(v[0])));
|
||||
}
|
||||
}
|
||||
s.push('>');
|
||||
// per-channel values are an rdf:Seq of three, not a comma list: readers parse each item
|
||||
for (n, v) in names.iter().zip(values) {
|
||||
if !uniform(v) {
|
||||
s.push_str(&format!("<hdrgm:{n}><rdf:Seq>"));
|
||||
for x in v {
|
||||
s.push_str(&format!("<rdf:li>{}</rdf:li>", num(*x)));
|
||||
}
|
||||
s.push_str(&format!("</rdf:Seq></hdrgm:{n}>"));
|
||||
}
|
||||
}
|
||||
s.push_str("</rdf:Description>");
|
||||
s.push_str(&self.apple_description());
|
||||
s.push_str(XMP_CLOSE);
|
||||
s
|
||||
}
|
||||
|
||||
/// Apple's own description of the map (`apdi`, `HDRGainMap`, `HDRToneMap` namespaces).
|
||||
fn apple_description(&self) -> String {
|
||||
// 'L008' (8-bit luminance) or '444f'; the stored map must really have that many channels
|
||||
let format = if self.multichannel { 0x3434_3466u32 } else { 0x4C30_3038 };
|
||||
let mut s = String::from(
|
||||
r#"<rdf:Description rdf:about="" xmlns:apdi="http://ns.apple.com/pixeldatainfo/1.0/" xmlns:HDRGainMap="http://ns.apple.com/HDRGainMap/1.0/" xmlns:HDRToneMap="http://ns.apple.com/HDRToneMap/1.0/">"#,
|
||||
);
|
||||
s.push_str("<apdi:AuxiliaryImageType>urn:com:apple:photo:2020:aux:hdrgainmap</apdi:AuxiliaryImageType>");
|
||||
s.push_str(&format!("<apdi:NativeFormat>{format}</apdi:NativeFormat><apdi:StoredFormat>{format}</apdi:StoredFormat>"));
|
||||
s.push_str("<HDRGainMap:HDRGainMapVersion>131072</HDRGainMap:HDRGainMapVersion>");
|
||||
// linear, not log2: the headroom multiplier itself
|
||||
s.push_str(&format!("<HDRGainMap:HDRGainMapHeadroom>{}</HDRGainMap:HDRGainMapHeadroom>", num(self.alternate_headroom.exp2())));
|
||||
s.push_str(&format!("<HDRToneMap:AlternateHeadroom>{}</HDRToneMap:AlternateHeadroom>", num(self.alternate_headroom)));
|
||||
s.push_str("<HDRToneMap:ChannelMetadata><rdf:Seq>");
|
||||
for c in 0..self.channels() {
|
||||
s.push_str(&format!(
|
||||
r#"<rdf:li rdf:parseType="Resource"><HDRToneMap:GainMapMin>{}</HDRToneMap:GainMapMin><HDRToneMap:GainMapMax>{}</HDRToneMap:GainMapMax><HDRToneMap:Gamma>{}</HDRToneMap:Gamma><HDRToneMap:BaseOffset>{}</HDRToneMap:BaseOffset><HDRToneMap:AlternateOffset>{}</HDRToneMap:AlternateOffset></rdf:li>"#,
|
||||
num(self.min[c]),
|
||||
num(self.max[c]),
|
||||
num(self.gamma[c]),
|
||||
num(self.base_offset[c]),
|
||||
num(self.alternate_offset[c])
|
||||
));
|
||||
}
|
||||
s.push_str("</rdf:Seq></HDRToneMap:ChannelMetadata>");
|
||||
s.push_str(&format!("<HDRToneMap:BaseHeadroom>{}</HDRToneMap:BaseHeadroom>", num(self.base_headroom)));
|
||||
s.push_str("<HDRToneMap:BaseColorIsWorkingColor>True</HDRToneMap:BaseColorIsWorkingColor><HDRToneMap:Version>1</HDRToneMap:Version>");
|
||||
s.push_str("</rdf:Description>");
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
const FLAG_MULTICHANNEL: u8 = 0x80;
|
||||
const FLAG_BASE_COLOUR_SPACE: u8 = 0x40;
|
||||
const FLAG_COMMON_DENOMINATOR: u8 = 0x08;
|
||||
const FLAG_BACKWARD: u8 = 0x04;
|
||||
|
||||
const XMP_OPEN: &str = "<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">";
|
||||
const XMP_CLOSE: &str = "</rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>";
|
||||
|
||||
/// A short decimal (up to 6 significant digits, no exponent for ordinary values).
|
||||
fn num(v: f32) -> String {
|
||||
if !v.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
let s = format!("{:.6}", v);
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" || s.is_empty() { "0".into() } else { s.to_string() }
|
||||
}
|
||||
|
||||
/// The values of `hdrgm:<name>`: an attribute (`name="v"`) or an element holding an `rdf:Seq`.
|
||||
fn xmp_values(xmp: &str, name: &str) -> Option<Vec<String>> {
|
||||
let attr = format!("hdrgm:{name}=");
|
||||
if let Some(i) = xmp.find(&attr) {
|
||||
let rest = xmp.get(i + attr.len()..)?;
|
||||
let q = rest.chars().next()?;
|
||||
if q == '"' || q == '\'' {
|
||||
let body = rest.get(1..)?;
|
||||
let end = body.find(q)?;
|
||||
return Some(vec![body.get(..end)?.to_string()]);
|
||||
}
|
||||
}
|
||||
let open = format!("<hdrgm:{name}>");
|
||||
let close = format!("</hdrgm:{name}>");
|
||||
let i = xmp.find(&open)?;
|
||||
let body = xmp.get(i + open.len()..)?;
|
||||
let body = body.get(..body.find(&close)?)?;
|
||||
let mut out = Vec::new();
|
||||
let mut rest = body;
|
||||
while let Some(a) = rest.find("<rdf:li>") {
|
||||
let after = rest.get(a + 8..)?;
|
||||
let b = after.find("</rdf:li>")?;
|
||||
out.push(after.get(..b)?.to_string());
|
||||
rest = after.get(b..)?;
|
||||
if out.len() > 3 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
// a plain element value
|
||||
out.push(body.trim().to_string());
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
fn take<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
let s = self.b.get(self.at..self.at.checked_add(N)?)?;
|
||||
self.at += N;
|
||||
s.try_into().ok()
|
||||
}
|
||||
fn u8(&mut self) -> Option<u8> {
|
||||
self.take::<1>().map(|a| a[0])
|
||||
}
|
||||
fn u16(&mut self) -> Option<u16> {
|
||||
self.take().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
self.take().map(u32::from_be_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// A gain map image: `channels` (1 or 3) interleaved 8-bit codes.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GainImage {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub channels: usize,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl GainImage {
|
||||
/// Bilinear code of channel `c` at gain map coordinates (`x`, `y`) (pixel centres at +0.5).
|
||||
fn sample(&self, x: f32, y: f32, c: usize) -> f32 {
|
||||
let (w, h) = (self.width, self.height);
|
||||
let fx = (x - 0.5).clamp(0.0, (w - 1) as f32);
|
||||
let fy = (y - 0.5).clamp(0.0, (h - 1) as f32);
|
||||
let (x0, y0) = (fx as usize, fy as usize);
|
||||
let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
|
||||
let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
|
||||
let at = |x: usize, y: usize| self.data.get((y * w + x) * self.channels + c).copied().unwrap_or(0) as f32;
|
||||
let a = at(x0, y0) + (at(x1, y0) - at(x0, y0)) * tx;
|
||||
let b = at(x0, y1) + (at(x1, y1) - at(x0, y1)) * tx;
|
||||
a + (b - a) * ty
|
||||
}
|
||||
}
|
||||
|
||||
/// How [`compute`] builds the map.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct GainMapOptions {
|
||||
/// Downscale factor of the map (1, 2 or 4).
|
||||
pub scale: usize,
|
||||
/// Three gains (R, G, B) instead of one luminance gain. Apple's readers want a single
|
||||
/// channel, so this is off by default.
|
||||
pub multichannel: bool,
|
||||
pub gamma: f32,
|
||||
/// Offsets added to SDR and HDR before the ratio (keep blacks finite and noise quiet).
|
||||
pub offset: f32,
|
||||
}
|
||||
|
||||
impl Default for GainMapOptions {
|
||||
fn default() -> Self {
|
||||
GainMapOptions { scale: 2, multichannel: false, gamma: 1.0, offset: 1.0 / 64.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Measure the gain map that turns `sdr` into `hdr` (both `width × height` linear RGB in the same
|
||||
/// primaries; `luma` = that space's luminance weights).
|
||||
pub fn compute(
|
||||
sdr: &[[f32; 3]],
|
||||
hdr: &[[f32; 3]],
|
||||
width: usize,
|
||||
height: usize,
|
||||
luma: [f32; 3],
|
||||
o: &GainMapOptions,
|
||||
) -> Result<(GainImage, GainMapMeta)> {
|
||||
let n = width.checked_mul(height).ok_or_else(|| Error::Encode("gain map: image too large".into()))?;
|
||||
if n == 0 || sdr.len() < n || hdr.len() < n {
|
||||
return Err(Error::Encode("gain map: SDR and HDR renditions must match the image size".into()));
|
||||
}
|
||||
if !(matches!(o.scale, 1 | 2 | 4) && o.gamma > 0.0 && o.gamma.is_finite() && o.offset > 0.0 && o.offset.is_finite()) {
|
||||
return Err(Error::Encode("gain map: scale must be 1, 2 or 4, gamma and offset positive".into()));
|
||||
}
|
||||
let s = o.scale;
|
||||
let (gw, gh) = (width.div_ceil(s), height.div_ceil(s));
|
||||
let ch = if o.multichannel { 3 } else { 1 };
|
||||
let y = |p: &[f32; 3]| luma[0] * p[0] + luma[1] * p[1] + luma[2] * p[2];
|
||||
let ratio = |a: f32, b: f32| ((b.max(0.0) + o.offset) / (a.max(0.0) + o.offset)).log2();
|
||||
// block means of the log gains
|
||||
let mut gains = vec![0f32; gw * gh * ch];
|
||||
let mut lo = [f32::MAX; 3];
|
||||
let mut hi = [f32::MIN; 3];
|
||||
for gy in 0..gh {
|
||||
for gx in 0..gw {
|
||||
let mut acc = [0f32; 3];
|
||||
let mut count = 0f32;
|
||||
for yy in gy * s..((gy + 1) * s).min(height) {
|
||||
for xx in gx * s..((gx + 1) * s).min(width) {
|
||||
let i = yy * width + xx;
|
||||
let (Some(a), Some(b)) = (sdr.get(i), hdr.get(i)) else { continue };
|
||||
if o.multichannel {
|
||||
for c in 0..3 {
|
||||
acc[c] += ratio(a[c], b[c]);
|
||||
}
|
||||
} else {
|
||||
acc[0] += ratio(y(a), y(b));
|
||||
}
|
||||
count += 1.0;
|
||||
}
|
||||
}
|
||||
for c in 0..ch {
|
||||
let g = if count > 0.0 { acc[c] / count } else { 0.0 };
|
||||
let g = if g.is_finite() { g } else { 0.0 };
|
||||
gains[(gy * gw + gx) * ch + c] = g;
|
||||
lo[c] = lo[c].min(g);
|
||||
hi[c] = hi[c].max(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut m = GainMapMeta {
|
||||
multichannel: o.multichannel,
|
||||
gamma: [o.gamma; 3],
|
||||
base_offset: [o.offset; 3],
|
||||
alternate_offset: [o.offset; 3],
|
||||
..GainMapMeta::default()
|
||||
};
|
||||
for c in 0..ch {
|
||||
// the range always includes 0 (no change) so an SDR-only area encodes exactly
|
||||
m.min[c] = lo[c].min(0.0);
|
||||
m.max[c] = hi[c].max(m.min[c] + 1e-4);
|
||||
}
|
||||
if !o.multichannel {
|
||||
m.fill_from_first();
|
||||
}
|
||||
m.base_headroom = 0.0;
|
||||
m.alternate_headroom = m.max.iter().copied().fold(0.0f32, f32::max).max(1e-3);
|
||||
let data = gains
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, g)| {
|
||||
let c = i % ch;
|
||||
let norm = ((g - m.min[c]) / (m.max[c] - m.min[c])).clamp(0.0, 1.0);
|
||||
(norm.powf(o.gamma) * 255.0).round() as u8
|
||||
})
|
||||
.collect();
|
||||
Ok((GainImage { width: gw, height: gh, channels: ch, data }, m))
|
||||
}
|
||||
|
||||
/// Rebuild the HDR rendition in place: `base` (`width × height` linear RGB) is replaced by the
|
||||
/// rendition at `weight` (0 = the base, 1 = the full alternate rendition; a display with headroom
|
||||
/// `H` uses `(H − base_headroom) / (alternate_headroom − base_headroom)`, clamped).
|
||||
pub fn apply(base: &mut [[f32; 3]], width: usize, height: usize, gain: &GainImage, m: &GainMapMeta, weight: f32) -> Result<()> {
|
||||
let n = width.checked_mul(height).ok_or_else(|| Error::Encode("gain map: image too large".into()))?;
|
||||
if base.len() < n
|
||||
|| gain.width == 0
|
||||
|| gain.height == 0
|
||||
|| !matches!(gain.channels, 1 | 3)
|
||||
|| gain.data.len() < gain.width * gain.height * gain.channels
|
||||
{
|
||||
return Err(Error::Encode("gain map: base and gain map sizes don't match".into()));
|
||||
}
|
||||
if !m.is_valid() {
|
||||
return Err(Error::Encode("gain map: unusable metadata".into()));
|
||||
}
|
||||
let weight = if weight.is_finite() { weight.clamp(0.0, 1.0) } else { 1.0 };
|
||||
let (sx, sy) = (gain.width as f32 / width as f32, gain.height as f32 / height as f32);
|
||||
let inv_gamma = m.gamma.map(|g| 1.0 / g);
|
||||
for (i, p) in base.iter_mut().enumerate().take(n) {
|
||||
let (x, y) = ((i % width) as f32 + 0.5, (i / width) as f32 + 0.5);
|
||||
let (gx, gy) = (x * sx, y * sy);
|
||||
let mut g = [0f32; 3];
|
||||
for (c, gc) in g.iter_mut().enumerate() {
|
||||
let src = if gain.channels == 3 { c } else { 0 };
|
||||
let norm = (gain.sample(gx, gy, src) / 255.0).clamp(0.0, 1.0).powf(inv_gamma[c]);
|
||||
*gc = m.min[c] + (m.max[c] - m.min[c]) * norm;
|
||||
}
|
||||
for c in 0..3 {
|
||||
let v = (p[c] + m.base_offset[c]) * (g[c] * weight).exp2() - m.alternate_offset[c];
|
||||
p[c] = v.max(0.0);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The primary image's container XMP: `hdrgm:Version` (marks the file as a gain map image for
|
||||
/// Adobe/Google readers) and the Container directory naming the gain map and its length.
|
||||
fn primary_description(gain_len: usize) -> String {
|
||||
format!(
|
||||
concat!(
|
||||
r#"<rdf:Description rdf:about="" xmlns:Container="http://ns.google.com/photos/1.0/container/" xmlns:Item="http://ns.google.com/photos/1.0/container/item/" xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/" hdrgm:Version="1.0">"#,
|
||||
r#"<Container:Directory><rdf:Seq>"#,
|
||||
r#"<rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="Primary" Item:Mime="image/jpeg"/></rdf:li>"#,
|
||||
r#"<rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="GainMap" Item:Mime="image/jpeg" Item:Length="{}"/></rdf:li>"#,
|
||||
r#"</rdf:Seq></Container:Directory></rdf:Description>"#
|
||||
),
|
||||
gain_len
|
||||
)
|
||||
}
|
||||
|
||||
/// `xmp` with `description` added as another `rdf:Description` (a fresh packet when there is
|
||||
/// none, or when it has no `rdf:RDF` to add to).
|
||||
fn merge_xmp(xmp: Option<&str>, description: &str) -> String {
|
||||
if let Some(x) = xmp
|
||||
&& let Some(i) = x.rfind("</rdf:RDF>")
|
||||
&& let (Some(a), Some(b)) = (x.get(..i), x.get(i..))
|
||||
{
|
||||
return format!("{a}{description}{b}");
|
||||
}
|
||||
format!("{XMP_OPEN}{description}{XMP_CLOSE}")
|
||||
}
|
||||
use crate::{ChromaSubsampling, Error, Format, Result, jpeg};
|
||||
|
||||
/// Offsets within the MPF payload (from "MPF\0"): the endian field, then the index IFD (3 tags).
|
||||
const MPF_ENTRIES_FROM_ENDIAN: usize = 8 + 2 + 3 * 12 + 4;
|
||||
@@ -576,31 +50,51 @@ pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, qualit
|
||||
return Err(Error::Encode("gain map JPEG needs an 8-bit base image".into()));
|
||||
};
|
||||
let (w, h) = (base.width as usize, base.height as usize);
|
||||
if !matches!(base.channels, 3 | 4) || data.len() < w * h * base.channels as usize {
|
||||
if !matches!(base.channels, 3 | 4) {
|
||||
return Err(Error::Encode("gain map JPEG needs an RGB base image".into()));
|
||||
}
|
||||
let Some(base_bytes) = w.checked_mul(h).and_then(|pixels| pixels.checked_mul(base.channels as usize)) else {
|
||||
return Err(Error::Encode("gain map JPEG needs an RGB base image".into()));
|
||||
};
|
||||
if data.len() < base_bytes {
|
||||
return Err(Error::Encode("gain map JPEG needs an RGB base image".into()));
|
||||
}
|
||||
if w == 0 || h == 0 || w > u16::MAX as usize || h > u16::MAX as usize {
|
||||
return Err(Error::Encode("JPEG dimensions are limited to 65535".into()));
|
||||
}
|
||||
if !matches!(gain.channels, 1 | 3) || gain.width == 0 || gain.height == 0 || gain.data.len() < gain.width * gain.height * gain.channels {
|
||||
if !matches!(gain.channels, 1 | 3) || gain.width == 0 || gain.height == 0 {
|
||||
return Err(Error::Encode("gain map image is malformed".into()));
|
||||
}
|
||||
// Check the JPEG frame-header limit before multiplying dimensions, then validate the source
|
||||
// buffer with checked arithmetic on both 32- and 64-bit targets.
|
||||
if gain.width > u16::MAX as usize || gain.height > u16::MAX as usize {
|
||||
return Err(Error::Encode("JPEG dimensions are limited to 65535".into()));
|
||||
}
|
||||
let Some(gain_bytes) = gain.width.checked_mul(gain.height).and_then(|pixels| pixels.checked_mul(gain.channels)) else {
|
||||
return Err(Error::Encode("gain map image is malformed".into()));
|
||||
};
|
||||
if gain.data.len() < gain_bytes {
|
||||
return Err(Error::Encode("gain map image is malformed".into()));
|
||||
}
|
||||
if !m.is_valid() || m.multichannel != (gain.channels == 3) {
|
||||
return Err(Error::Encode("gain map metadata doesn't match the map".into()));
|
||||
}
|
||||
// jpeg_par writes 4:4:4 or 4:2:0
|
||||
let sub = if sub == ChromaSubsampling::S422 { ChromaSubsampling::S420 } else { sub };
|
||||
|
||||
let gain_segs = vec![(0xE1, xmp_segment(&m.to_gain_map_xmp())?), (0xE2, m.to_iso())];
|
||||
let gain_jpeg = jpeg_par::encode(&gain.data, gain.width, gain.height, gain.channels, quality, ChromaSubsampling::S444, &gain_segs);
|
||||
let gain_jpeg =
|
||||
craft_jpeg::encode_baseline(&gain.data, gain.width, gain.height, gain.channels, quality, craft_jpeg::ChromaSubsampling::S444, &gain_segs)
|
||||
.map_err(|e| Error::Encode(e.to_string()))?;
|
||||
|
||||
let xmp = merge_xmp(meta.xmp, &primary_description(gain_jpeg.len()));
|
||||
let xmp = craft_gainmap::primary_xmp(meta.xmp, gain_jpeg.len());
|
||||
let mut segs = jpeg_app_segments(&EncodeMeta { xmp: Some(&xmp), ..*meta })?;
|
||||
let mut iso_marker = ISO_URN.to_vec();
|
||||
iso_marker.extend_from_slice(&[0, 0, 0, 0]); // versions only: "this image has a gain map"
|
||||
segs.push((0xE2, iso_marker));
|
||||
segs.push((0xE2, craft_gainmap::primary_iso_marker()));
|
||||
segs.push((0xE2, mpf_placeholder()));
|
||||
let mut primary = jpeg_par::encode(data, w, h, base.channels as usize, quality, sub, &segs);
|
||||
let sub = match sub {
|
||||
ChromaSubsampling::S444 => craft_jpeg::ChromaSubsampling::S444,
|
||||
ChromaSubsampling::S422 => craft_jpeg::ChromaSubsampling::S420,
|
||||
ChromaSubsampling::S420 => craft_jpeg::ChromaSubsampling::S420,
|
||||
};
|
||||
let mut primary =
|
||||
craft_jpeg::encode_baseline(data, w, h, base.channels as usize, quality, sub, &segs).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
|
||||
// patch the MPF index: sizes, and the gain map's offset from the MPF endian field
|
||||
let markers = jpeg::parse_markers(&primary).ok_or_else(|| Error::Encode("gain map JPEG: primary image unreadable".into()))?;
|
||||
@@ -668,77 +162,6 @@ pub fn is_gain_map_jpeg(bytes: &[u8]) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn meta3() -> GainMapMeta {
|
||||
GainMapMeta {
|
||||
multichannel: true,
|
||||
use_base_colour_space: true,
|
||||
base_headroom: 0.0,
|
||||
alternate_headroom: 2.5,
|
||||
min: [-0.25, -0.5, 0.0],
|
||||
max: [2.5, 2.25, 2.0],
|
||||
gamma: [1.0, 1.25, 0.75],
|
||||
base_offset: [0.015625; 3],
|
||||
alternate_offset: [0.015625, 0.03125, 0.015625],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_metadata_round_trips() {
|
||||
for m in [GainMapMeta { alternate_headroom: 3.0, max: [3.0; 3], ..GainMapMeta::default() }, meta3()] {
|
||||
let p = m.to_iso();
|
||||
assert!(p.starts_with(ISO_URN));
|
||||
let back = GainMapMeta::from_iso(&p[ISO_URN.len()..]).unwrap();
|
||||
for (a, b) in [(back.min, m.min), (back.max, m.max), (back.gamma, m.gamma), (back.alternate_offset, m.alternate_offset)] {
|
||||
for c in 0..3 {
|
||||
assert!((a[c] - b[c]).abs() < 1e-6, "{a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(back.multichannel, m.multichannel);
|
||||
assert!((back.alternate_headroom - m.alternate_headroom).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_common_denominator_and_rejections() {
|
||||
// common-denominator form, single channel: d = 4, headrooms 0 and 2, min 0, max 2, gamma 1, offsets 0
|
||||
let mut p = vec![0, 0, 0, 0, FLAG_COMMON_DENOMINATOR];
|
||||
for v in [4u32, 0, 8, 0, 8, 4, 0, 0] {
|
||||
p.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
let m = GainMapMeta::from_iso(&p).unwrap();
|
||||
assert_eq!((m.alternate_headroom, m.max[2], m.gamma[1]), (2.0, 2.0, 1.0));
|
||||
// versions only (a primary image's marker), unknown version, truncated, backward
|
||||
assert!(GainMapMeta::from_iso(&[0, 0, 0, 0]).is_none());
|
||||
assert!(GainMapMeta::from_iso(&[0, 1, 0, 0, 0]).is_none());
|
||||
assert!(GainMapMeta::from_iso(&p[..p.len() - 1]).is_none());
|
||||
let mut back = p.clone();
|
||||
back[4] |= FLAG_BACKWARD;
|
||||
assert!(GainMapMeta::from_iso(&back).is_none());
|
||||
// a zero denominator is rejected, not divided by
|
||||
let mut z = p.clone();
|
||||
z[5..9].copy_from_slice(&0u32.to_be_bytes());
|
||||
assert!(GainMapMeta::from_iso(&z).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdrgm_xmp_round_trips_including_per_channel_sequences() {
|
||||
for m in [GainMapMeta { alternate_headroom: 2.0, max: [2.0; 3], ..GainMapMeta::default() }, meta3()] {
|
||||
let x = m.to_gain_map_xmp();
|
||||
assert!(x.contains("apdi:AuxiliaryImageType"));
|
||||
if m.multichannel {
|
||||
assert!(x.contains("<hdrgm:GainMapMax><rdf:Seq><rdf:li>2.5</rdf:li>"), "{x}");
|
||||
}
|
||||
let back = GainMapMeta::from_hdrgm_xmp(&x).unwrap();
|
||||
assert_eq!(back.multichannel, m.multichannel);
|
||||
for c in 0..3 {
|
||||
assert!((back.max[c] - m.max[c]).abs() < 1e-5 && (back.gamma[c] - m.gamma[c]).abs() < 1e-5);
|
||||
}
|
||||
assert!((back.alternate_headroom - m.alternate_headroom).abs() < 1e-5);
|
||||
}
|
||||
assert!(GainMapMeta::from_hdrgm_xmp("<x hdrgm:Version=\"1.0\"/>").is_none(), "no GainMapMax");
|
||||
assert!(GainMapMeta::from_hdrgm_xmp("hdrgm:GainMapMax=\"nope\"").is_none());
|
||||
}
|
||||
|
||||
fn renditions(w: usize, h: usize) -> (Vec<[f32; 3]>, Vec<[f32; 3]>) {
|
||||
// a ramp: SDR rolls off at 1, HDR keeps going to 6
|
||||
let hdr: Vec<[f32; 3]> = (0..w * h)
|
||||
@@ -762,27 +185,62 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_then_apply_recovers_the_hdr_rendition() {
|
||||
let (w, h) = (64, 8);
|
||||
let (sdr, hdr) = renditions(w, h);
|
||||
for multichannel in [false, true] {
|
||||
let o = GainMapOptions { scale: 1, multichannel, ..GainMapOptions::default() };
|
||||
let (g, m) = compute(&sdr, &hdr, w, h, [0.2126, 0.7152, 0.0722], &o).unwrap();
|
||||
assert!(m.is_valid() && m.alternate_headroom > 1.0);
|
||||
let mut out = sdr.clone();
|
||||
apply(&mut out, w, h, &g, &m, 1.0).unwrap();
|
||||
for (a, b) in out.iter().zip(&hdr) {
|
||||
for c in 0..3 {
|
||||
// 8-bit codes over the gain range: within ~2 % in linear light
|
||||
assert!((a[c] - b[c]).abs() <= 0.03 * b[c] + 0.01, "{multichannel}: {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
// weight 0 is the base
|
||||
let mut base = sdr.clone();
|
||||
apply(&mut base, w, h, &g, &m, 0.0).unwrap();
|
||||
for (a, b) in base.iter().zip(&sdr) {
|
||||
assert!((a[0] - b[0]).abs() < 1e-5);
|
||||
}
|
||||
fn a_gain_map_wider_than_a_jpeg_allows_is_refused() {
|
||||
let base = [0u8; 3];
|
||||
let gain = GainImage { width: 65_536, height: 1, channels: 1, data: vec![0; 65_536] };
|
||||
let r = encode_jpeg(
|
||||
&EncodeImage::new(1, 1, 3, Samples::U8(&base)),
|
||||
&gain,
|
||||
&GainMapMeta::default(),
|
||||
90,
|
||||
ChromaSubsampling::S444,
|
||||
&EncodeMeta::default(),
|
||||
);
|
||||
assert!(matches!(r, Err(Error::Encode(m)) if m.contains("65535")));
|
||||
}
|
||||
|
||||
fn encode_fixture(base: &EncodeImage<'_>, gain: &GainImage, meta: &GainMapMeta, sub: ChromaSubsampling) -> Result<Vec<u8>> {
|
||||
encode_jpeg(base, gain, meta, 90, sub, &EncodeMeta::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gain_map_encoder_rejects_malformed_buffers_and_metadata() {
|
||||
let base = [0u8; 3];
|
||||
let rgb = EncodeImage::new(1, 1, 3, Samples::U8(&base));
|
||||
let gain = GainImage { width: 1, height: 1, channels: 1, data: vec![128] };
|
||||
|
||||
let short_base = EncodeImage::new(1, 1, 4, Samples::U8(&base));
|
||||
assert!(
|
||||
matches!(encode_fixture(&short_base, &gain, &GainMapMeta::default(), ChromaSubsampling::S444), Err(Error::Encode(m)) if m.contains("RGB base"))
|
||||
);
|
||||
|
||||
let short_gain = GainImage { data: Vec::new(), ..gain.clone() };
|
||||
assert!(
|
||||
matches!(encode_fixture(&rgb, &short_gain, &GainMapMeta::default(), ChromaSubsampling::S444), Err(Error::Encode(m)) if m.contains("malformed"))
|
||||
);
|
||||
|
||||
let wrong_metadata = GainMapMeta { multichannel: true, ..GainMapMeta::default() };
|
||||
assert!(matches!(encode_fixture(&rgb, &gain, &wrong_metadata, ChromaSubsampling::S444), Err(Error::Encode(m)) if m.contains("metadata")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gain_map_jpeg_writer_preserves_supported_base_layouts_and_subsampling() {
|
||||
let gain = GainImage { width: 1, height: 1, channels: 1, data: vec![128] };
|
||||
let meta = GainMapMeta::default();
|
||||
let rgb = [10u8, 20, 30];
|
||||
let rgba = [10u8, 20, 30, 255];
|
||||
|
||||
for (base, sub) in [
|
||||
(EncodeImage::new(1, 1, 3, Samples::U8(&rgb)), ChromaSubsampling::S444),
|
||||
(EncodeImage::new(1, 1, 3, Samples::U8(&rgb)), ChromaSubsampling::S422),
|
||||
(EncodeImage::new(1, 1, 3, Samples::U8(&rgb)), ChromaSubsampling::S420),
|
||||
(EncodeImage::new(1, 1, 4, Samples::U8(&rgba)), ChromaSubsampling::S420),
|
||||
] {
|
||||
let encoded = encode_fixture(&base, &gain, &meta, sub).unwrap();
|
||||
assert!(is_gain_map_jpeg(&encoded));
|
||||
let decoded = crate::decode(&encoded, crate::DecodeOptions::default()).unwrap();
|
||||
assert_eq!((decoded.width, decoded.height), (1, 1));
|
||||
assert!(read_jpeg(&encoded).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! HEIF / HEIC (the iPhone and Mac photo format), read-only.
|
||||
//!
|
||||
//! Decoding lives in the optional `lightcraft-heif` crate (heic-rs, a pure-Rust HEVC
|
||||
//! Decoding lives in the optional `craft-heif` crate (heic-rs, a pure-Rust HEVC
|
||||
//! still-picture decoder, plus a libheif-matching colour conversion), enabled by this crate's
|
||||
//! `heif` feature — off by default because HEVC is patent-encumbered and whether a build carries
|
||||
//! an HEVC decoder is the distributor's call (the same policy as the sibling PhotoCraft). Without
|
||||
@@ -35,10 +35,10 @@ pub(crate) fn header(_bytes: &[u8]) -> Result<(u32, u32, u16)> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
fn err(e: lightcraft_heif::Error) -> Error {
|
||||
fn err(e: craft_heif::Error) -> Error {
|
||||
match e {
|
||||
lightcraft_heif::Error::Unsupported(why) => Error::Unsupported(F, why),
|
||||
lightcraft_heif::Error::Limit(m) | lightcraft_heif::Error::Malformed(m) => Error::Malformed(F, m),
|
||||
craft_heif::Error::Unsupported(why) => Error::Unsupported(F, why),
|
||||
craft_heif::Error::Limit(m) | craft_heif::Error::Malformed(m) => Error::Malformed(F, m),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,24 +46,24 @@ fn err(e: lightcraft_heif::Error) -> Error {
|
||||
/// alone: no picture is decoded.
|
||||
#[cfg(feature = "heif")]
|
||||
pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> {
|
||||
let info = lightcraft_heif::probe(bytes).map_err(err)?;
|
||||
let info = craft_heif::probe(bytes).map_err(err)?;
|
||||
Ok((info.width, info.height, 1))
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
|
||||
// The container alone: the declared size is checked before any pixel is decoded.
|
||||
let info = lightcraft_heif::probe(bytes).map_err(err)?;
|
||||
let info = craft_heif::probe(bytes).map_err(err)?;
|
||||
if (info.width as u64).saturating_mul(info.height as u64) > opts.max_pixels {
|
||||
return Err(Error::TooLarge(info.width as u64, info.height as u64));
|
||||
}
|
||||
let options = lightcraft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true };
|
||||
let options = craft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true, ..Default::default() };
|
||||
// A small decode (a thumbnail or a cataloguing probe) uses the file's own thumbnail image when
|
||||
// it is at least as large as asked: iPhones store one of 320 × 240, and decoding it is a
|
||||
// hundredth of the work of the 12 MP photo.
|
||||
let thumb = match opts.max_size {
|
||||
Some((mw, mh)) if mw > 0 && mh > 0 && mw.max(mh) < info.width.max(info.height) => {
|
||||
lightcraft_heif::decode_thumbnail(bytes, mw.max(mh), &options).ok().flatten().filter(|t| {
|
||||
craft_heif::decode_thumbnail(bytes, mw.max(mh), &options).ok().flatten().filter(|t| {
|
||||
// Only a thumbnail of the same picture: same orientation and aspect within 1 %.
|
||||
let aspect = |w: u32, h: u32| w as f64 / h.max(1) as f64;
|
||||
(aspect(t.width, t.height) / aspect(info.width, info.height) - 1.0).abs() < 0.01
|
||||
@@ -73,7 +73,7 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
|
||||
};
|
||||
let mut decoded = match thumb {
|
||||
Some(t) => t,
|
||||
None => lightcraft_heif::decode(bytes, &options).map_err(err)?,
|
||||
None => craft_heif::decode(bytes, &options).map_err(err)?,
|
||||
};
|
||||
let raw = Raw {
|
||||
width: decoded.width as usize,
|
||||
|
||||
+85
-155
@@ -1,11 +1,9 @@
|
||||
//! ICC profiles: parsing (via `moxcms`), matrix/TRC extraction, CMS fallback for LUT/CMYK profiles,
|
||||
//! ICC profiles: parsing (via `craft-cms`), matrix/TRC extraction, CMS fallback for LUT/CMYK profiles,
|
||||
//! and writing matrix/TRC profiles for export embedding.
|
||||
|
||||
use crate::space::{NamedSpace, Trc, rgb_to_xyz_d50};
|
||||
use craft_cms::{Builtin, ColorSpace, Curve, Intent, Pcs, Profile, Transform, TransformOptions};
|
||||
use lightcraft_color::{D50, Mat3, RgbSpace, bradford};
|
||||
use moxcms::{
|
||||
ColorProfile, DataColorSpace, Layout, LocalizableString, Matrix3d, ProfileText, RenderingIntent, ToneReprCurve, TransformOptions, Xyzd,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Colour model of the profile's device space.
|
||||
@@ -40,24 +38,24 @@ pub struct IccInfo {
|
||||
|
||||
/// Parse an ICC profile. Returns `None` for malformed or unsupported data (never panics).
|
||||
pub fn parse(bytes: &[u8]) -> Option<IccInfo> {
|
||||
let p = std::panic::catch_unwind(|| ColorProfile::new_from_slice(bytes)).ok()?.ok()?;
|
||||
let p = Profile::parse(bytes).ok()?;
|
||||
Some(info_of(&p))
|
||||
}
|
||||
|
||||
fn info_of(p: &ColorProfile) -> IccInfo {
|
||||
let description = p.description.as_ref().and_then(text_of);
|
||||
fn info_of(p: &Profile) -> IccInfo {
|
||||
let desc = p.description.trim_end_matches('\0').trim().to_string();
|
||||
let description = if desc.is_empty() { None } else { Some(desc) };
|
||||
let model = match p.color_space {
|
||||
DataColorSpace::Rgb => IccColorModel::Rgb,
|
||||
DataColorSpace::Gray => IccColorModel::Gray,
|
||||
DataColorSpace::Cmyk => IccColorModel::Cmyk,
|
||||
ColorSpace::Rgb => IccColorModel::Rgb,
|
||||
ColorSpace::Gray => IccColorModel::Gray,
|
||||
ColorSpace::Cmyk => IccColorModel::Cmyk,
|
||||
_ => IccColorModel::Other,
|
||||
};
|
||||
let has_lut = p.lut_a_to_b_perceptual.is_some() || p.lut_a_to_b_colorimetric.is_some();
|
||||
let kind = if model == IccColorModel::Rgb && p.is_matrix_shaper() && p.pcs == DataColorSpace::Xyz {
|
||||
let c = [p.red_colorant, p.green_colorant, p.blue_colorant];
|
||||
let to_xyz_d50 = Mat3([[c[0].x, c[1].x, c[2].x], [c[0].y, c[1].y, c[2].y], [c[0].z, c[1].z, c[2].z]]);
|
||||
let trcs = [&p.red_trc, &p.green_trc, &p.blue_trc];
|
||||
let trc = trcs.map(|t| t.as_ref().map(trc_from_icc).unwrap_or(Trc::Srgb));
|
||||
let has_lut = p.a2b[0].is_some() || p.a2b[1].is_some();
|
||||
let kind = if model == IccColorModel::Rgb && p.is_matrix_shaper() && p.pcs == Pcs::Xyz {
|
||||
let to_xyz_d50 = Mat3(p.matrix.unwrap_or([[0.0; 3]; 3]));
|
||||
let trc =
|
||||
p.trc.as_ref().map(|ts| [trc_from_icc(&ts[0]), trc_from_icc(&ts[1]), trc_from_icc(&ts[2])]).unwrap_or([Trc::Srgb, Trc::Srgb, Trc::Srgb]);
|
||||
if to_xyz_d50.determinant().abs() > 1e-6 && trc.iter().all(valid_trc) { IccKind::MatrixTrc { to_xyz_d50, trc } } else { IccKind::NeedsCms }
|
||||
} else if model == IccColorModel::Gray && p.gray_trc.is_some() && !has_lut {
|
||||
let trc = p.gray_trc.as_ref().map(trc_from_icc).unwrap_or(Trc::Srgb);
|
||||
@@ -80,124 +78,61 @@ fn valid_trc(t: &Trc) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn text_of(t: &ProfileText) -> Option<String> {
|
||||
let s = match t {
|
||||
ProfileText::PlainString(s) => s.clone(),
|
||||
ProfileText::Localizable(v) => v.first().map(|l| l.value.clone())?,
|
||||
ProfileText::Description(d) => {
|
||||
if d.unicode_string.is_empty() {
|
||||
d.ascii_string.clone()
|
||||
} else {
|
||||
d.unicode_string.clone()
|
||||
fn trc_from_icc(t: &Curve) -> Trc {
|
||||
match t {
|
||||
Curve::Identity => Trc::Linear,
|
||||
Curve::Gamma(g) => Trc::Gamma(*g as f32),
|
||||
Curve::Parametric { kind, p } => Trc::Parametric(p[..Curve::param_count(*kind)].iter().map(|&v| v as f32).collect()),
|
||||
Curve::Table(v) if v.is_empty() => Trc::Linear,
|
||||
Curve::Table(v) if v.len() == 1 => Trc::Gamma(v[0]),
|
||||
Curve::Table(v) => Trc::Table(v.iter().map(|&x| (x.clamp(0.0, 1.0) * 65535.0).round() as u16).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
fn trc_to_icc(t: &Trc) -> Curve {
|
||||
match t {
|
||||
Trc::Linear => Curve::Identity,
|
||||
Trc::Srgb => Curve::Parametric { kind: 3, p: [2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045, 0.0, 0.0] },
|
||||
Trc::Gamma(g) => Curve::Gamma(*g as f64),
|
||||
Trc::Rec709 => Curve::Parametric { kind: 3, p: [1.0 / 0.45, 1.0 / 1.099, 0.099 / 1.099, 1.0 / 4.5, 0.081, 0.0, 0.0] },
|
||||
Trc::Parametric(p) => {
|
||||
let kind = match p.len() {
|
||||
1 => 0,
|
||||
3 => 1,
|
||||
4 => 2,
|
||||
5 => 3,
|
||||
_ => 4,
|
||||
};
|
||||
let mut arr = [0.0f64; 7];
|
||||
for (dst, &src) in arr.iter_mut().zip(p.iter()) {
|
||||
*dst = src as f64;
|
||||
}
|
||||
Curve::Parametric { kind, p: arr }
|
||||
}
|
||||
};
|
||||
let s = s.trim_end_matches('\0').trim().to_string();
|
||||
if s.is_empty() { None } else { Some(s) }
|
||||
}
|
||||
|
||||
fn trc_from_icc(t: &ToneReprCurve) -> Trc {
|
||||
match t {
|
||||
ToneReprCurve::Lut(v) if v.is_empty() => Trc::Linear,
|
||||
ToneReprCurve::Lut(v) if v.len() == 1 => Trc::Gamma(v[0] as f32 / 256.0),
|
||||
ToneReprCurve::Lut(v) => Trc::Table(v.clone()),
|
||||
ToneReprCurve::Parametric(p) => Trc::Parametric(p.clone()),
|
||||
Trc::Table(v) => Curve::Table(v.iter().map(|&x| x as f32 / 65535.0).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
fn trc_to_icc(t: &Trc) -> ToneReprCurve {
|
||||
match t {
|
||||
Trc::Linear => ToneReprCurve::Parametric(vec![1.0]),
|
||||
Trc::Srgb => ToneReprCurve::Parametric(vec![2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045]),
|
||||
Trc::Gamma(g) => ToneReprCurve::Parametric(vec![*g]),
|
||||
Trc::Rec709 => ToneReprCurve::Parametric(vec![1.0 / 0.45, 1.0 / 1.099, 0.099 / 1.099, 1.0 / 4.5, 0.081]),
|
||||
Trc::Parametric(p) => ToneReprCurve::Parametric(p.clone()),
|
||||
Trc::Table(v) => ToneReprCurve::Lut(v.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn xyzd(v: [f64; 3]) -> Xyzd {
|
||||
Xyzd { x: v[0], y: v[1], z: v[2] }
|
||||
}
|
||||
|
||||
/// ICC PCS illuminant (D50) as stored in profiles.
|
||||
const ICC_D50: [f64; 3] = [0.9642, 1.0, 0.8249];
|
||||
|
||||
/// Build an ICC v4 display-class matrix/TRC profile for `space` with the given encoding curve
|
||||
/// (D50 PCS, Bradford `chad`), for embedding in exported files.
|
||||
pub fn write_matrix_trc(space: &RgbSpace, trc: &Trc) -> Vec<u8> {
|
||||
let m = rgb_to_xyz_d50(space).0;
|
||||
let mut p = ColorProfile::new_srgb();
|
||||
p.cicp = None;
|
||||
p.red_colorant = xyzd([m[0][0], m[1][0], m[2][0]]);
|
||||
p.green_colorant = xyzd([m[0][1], m[1][1], m[2][1]]);
|
||||
p.blue_colorant = xyzd([m[0][2], m[1][2], m[2][2]]);
|
||||
let mut p = Builtin::Srgb.profile().clone();
|
||||
p.matrix = Some(rgb_to_xyz_d50(space).0);
|
||||
let curve = trc_to_icc(trc);
|
||||
p.red_trc = Some(curve.clone());
|
||||
p.green_trc = Some(curve.clone());
|
||||
p.blue_trc = Some(curve);
|
||||
p.white_point = xyzd(ICC_D50);
|
||||
p.media_white_point = Some(xyzd(ICC_D50));
|
||||
p.chromatic_adaptation = Some(Matrix3d { v: bradford(space.white, D50).0 });
|
||||
p.rendering_intent = RenderingIntent::Perceptual;
|
||||
let desc = match trc {
|
||||
p.trc = Some([curve.clone(), curve.clone(), curve]);
|
||||
p.white_point = ICC_D50;
|
||||
p.chad = Some(bradford(space.white, D50).0);
|
||||
p.rendering_intent = Intent::Perceptual;
|
||||
p.description = match trc {
|
||||
t if t.is_linear() => format!("{} (linear)", space.name),
|
||||
_ => space.name.to_string(),
|
||||
};
|
||||
p.description = Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), desc)]));
|
||||
p.copyright = Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), "No copyright, use freely".into())]));
|
||||
align_tags(&fixed_date(p.encode().unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Zero the header's creation date/time (ICC.1 §7.2.8, bytes 24..36) so a profile's bytes depend
|
||||
/// only on its colour space and curve. `moxcms` stamps the wall clock there on every `encode`
|
||||
/// (ignoring `ColorProfile::creation_date_time`), which made two exports of one photo differ in
|
||||
/// the embedded profile and nowhere else, so output hashes could not be compared (#180). Readers
|
||||
/// do not interpret the field; all zeros is the conventional "unspecified" value.
|
||||
fn fixed_date(mut b: Vec<u8>) -> Vec<u8> {
|
||||
if let Some(date) = b.get_mut(24..36) {
|
||||
date.fill(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Re-lay a profile's tag data on 4-byte boundaries (ICC.1 §7.3.1). The encoder packs tags back to
|
||||
/// back, so a tag of odd length (e.g. a `mluc` description with an odd number of characters)
|
||||
/// misaligns every following tag — which some readers (macOS ImageIO for PNG `iCCP`) reject.
|
||||
fn align_tags(b: &[u8]) -> Vec<u8> {
|
||||
let be = |i: usize| b.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize);
|
||||
let Some(n) = be(128) else { return b.to_vec() };
|
||||
let table_end = 132 + 12 * n;
|
||||
let tags: Option<Vec<(usize, usize)>> = (0..n).map(|t| Some((be(132 + 12 * t + 4)?, be(132 + 12 * t + 8)?))).collect();
|
||||
let Some(tags) = tags.filter(|t| table_end <= b.len() && t.iter().all(|&(o, l)| o >= table_end && o + l <= b.len())) else {
|
||||
return b.to_vec();
|
||||
};
|
||||
let mut out = b[..table_end].to_vec();
|
||||
let mut placed: Vec<((usize, usize), usize)> = Vec::new();
|
||||
for (t, &(off, len)) in tags.iter().enumerate() {
|
||||
let new_off = match placed.iter().find(|(k, _)| *k == (off, len)) {
|
||||
// tags sharing data keep sharing it
|
||||
Some(&(_, o)) => o,
|
||||
None => {
|
||||
while !out.len().is_multiple_of(4) {
|
||||
out.push(0);
|
||||
}
|
||||
let o = out.len();
|
||||
out.extend_from_slice(&b[off..off + len]);
|
||||
placed.push(((off, len), o));
|
||||
o
|
||||
}
|
||||
};
|
||||
out[132 + 12 * t + 4..132 + 12 * t + 8].copy_from_slice(&(new_off as u32).to_be_bytes());
|
||||
}
|
||||
while !out.len().is_multiple_of(4) {
|
||||
out.push(0);
|
||||
}
|
||||
let size = out.len() as u32;
|
||||
out[0..4].copy_from_slice(&size.to_be_bytes());
|
||||
// the profile ID (MD5) would no longer match: clear it (= "not computed")
|
||||
out[84..100].fill(0);
|
||||
out
|
||||
p.copyright = "No copyright, use freely".to_string();
|
||||
let encoded = p.with_encoded_bytes();
|
||||
craft_cms::normalize_for_embedding(encoded.to_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// A profile for one of the well-known spaces with its standard curve.
|
||||
@@ -205,52 +140,47 @@ pub fn write_named(n: NamedSpace) -> Vec<u8> {
|
||||
write_matrix_trc(&n.rgb_space(), &n.trc())
|
||||
}
|
||||
|
||||
pub(crate) fn linear_rec2020_profile() -> ColorProfile {
|
||||
let mut p = ColorProfile::new_bt2020();
|
||||
p.cicp = None;
|
||||
let lin = ToneReprCurve::Parametric(vec![1.0]);
|
||||
p.red_trc = Some(lin.clone());
|
||||
p.green_trc = Some(lin.clone());
|
||||
p.blue_trc = Some(lin);
|
||||
pub(crate) fn linear_rec2020_profile() -> Profile {
|
||||
let mut p = Builtin::Rec2020.profile().clone();
|
||||
p.trc = Some([Curve::Identity, Curve::Identity, Curve::Identity]);
|
||||
p
|
||||
}
|
||||
|
||||
/// Convert device samples (0..1, interleaved, `channels` = 1, 3 or 4 matching the profile's colour
|
||||
/// model) to linear Rec.2020 through a full CMS transform. `None` if the profile cannot be applied.
|
||||
pub(crate) fn cms_to_linear_rec2020(icc: &[u8], samples: &[f32], channels: usize) -> Option<Vec<[f32; 3]>> {
|
||||
let src = ColorProfile::new_from_slice(icc).ok()?;
|
||||
let layout = match (src.color_space, channels) {
|
||||
(DataColorSpace::Rgb, 3) => Layout::Rgb,
|
||||
(DataColorSpace::Gray, 1) => Layout::Gray,
|
||||
(DataColorSpace::Cmyk, 4) => Layout::Rgba,
|
||||
let src = Profile::parse(icc).ok()?;
|
||||
let expected = match src.color_space {
|
||||
ColorSpace::Rgb => 3,
|
||||
ColorSpace::Gray => 1,
|
||||
ColorSpace::Cmyk => 4,
|
||||
_ => return None,
|
||||
};
|
||||
if channels != expected {
|
||||
return None;
|
||||
}
|
||||
let dst = linear_rec2020_profile();
|
||||
let opts = TransformOptions { rendering_intent: RenderingIntent::RelativeColorimetric, ..TransformOptions::default() };
|
||||
let run = || -> Option<Vec<[f32; 3]>> {
|
||||
let t = src.create_transform_f32(layout, &dst, Layout::Rgb, opts).ok()?;
|
||||
let n = samples.len() / channels;
|
||||
let mut out = vec![0f32; n * 3];
|
||||
// Chunk to bound temporary memory and allow parallelism.
|
||||
const ROWS: usize = 1 << 16;
|
||||
let src_chunks = samples.chunks(ROWS * channels);
|
||||
let dst_chunks = out.chunks_mut(ROWS * 3);
|
||||
#[cfg(feature = "parallel")]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
let pairs: Vec<_> = src_chunks.zip(dst_chunks).collect();
|
||||
let ok = pairs.into_par_iter().all(|(s, d)| t.transform(s, d).is_ok());
|
||||
if !ok {
|
||||
return None;
|
||||
}
|
||||
let opts = TransformOptions { intent: Intent::RelativeColorimetric, bpc: false, precise_float: true };
|
||||
let t = Transform::with_options(&src, &dst, opts).ok()?;
|
||||
let n = samples.len() / channels;
|
||||
let mut out = vec![0f32; n * 3];
|
||||
const ROWS: usize = 1 << 16;
|
||||
let src_chunks = samples.chunks(ROWS * channels);
|
||||
let dst_chunks = out.chunks_mut(ROWS * 3);
|
||||
#[cfg(feature = "parallel")]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
let pairs: Vec<_> = src_chunks.zip(dst_chunks).collect();
|
||||
let ok = pairs.into_par_iter().all(|(s, d)| t.convert_f32(s, channels, d, 3, false).is_ok());
|
||||
if !ok {
|
||||
return None;
|
||||
}
|
||||
#[cfg(not(feature = "parallel"))]
|
||||
for (s, d) in src_chunks.zip(dst_chunks) {
|
||||
t.transform(s, d).ok()?;
|
||||
}
|
||||
Some(out.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect())
|
||||
};
|
||||
std::panic::catch_unwind(run).ok().flatten()
|
||||
}
|
||||
#[cfg(not(feature = "parallel"))]
|
||||
for (s, d) in src_chunks.zip(dst_chunks) {
|
||||
t.convert_f32(s, channels, d, 3, false).ok()?;
|
||||
}
|
||||
Some(out.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+236
-185
@@ -292,17 +292,7 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
|
||||
if m.app1 > MAX_APP1 {
|
||||
return Err(Error::Malformed(F, "too many APP1 markers".into()));
|
||||
}
|
||||
let scale_to = opts.max_size.filter(|&(mw, mh)| mw > 0 && mh > 0 && (m.width >= mw.saturating_mul(2) || m.height >= mh.saturating_mul(2)));
|
||||
// zune-jpeg handles the common cases fastest; jpeg-decoder covers DCT scaling, CMYK/YCCK,
|
||||
// 12-bit, non-interleaved sequential scans (which zune-jpeg 0.5 mis-decodes with subsampling)
|
||||
// and every lossless (SOF3) file, which zune-jpeg refuses outright.
|
||||
let lossless = m.sof == 0xC3;
|
||||
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
|
||||
let raw = if m.components == 4 || scale_to.is_some() || m.precision > 8 || non_interleaved || lossless {
|
||||
decode_jpeg_decoder(bytes, &m, scale_to, opts)?
|
||||
} else {
|
||||
decode_zune(bytes, &m, opts)?
|
||||
};
|
||||
let raw = decode_via_craft_codecs(bytes, opts)?;
|
||||
// A raw container may carry the colour declaration of an otherwise untagged preview.
|
||||
// Apply it before linearization/resizing; existing JPEG metadata always wins.
|
||||
let hint = fallback
|
||||
@@ -312,70 +302,37 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
|
||||
finish(F, raw, meta, (m.width, m.height), opts)
|
||||
}
|
||||
|
||||
fn decode_zune(bytes: &[u8], m: &Markers, budget: &DecodeOptions) -> Result<Raw> {
|
||||
use zune_core::bytestream::ZCursor;
|
||||
use zune_core::colorspace::ColorSpace;
|
||||
use zune_core::options::DecoderOptions;
|
||||
let gray = m.components == 1;
|
||||
let opts = DecoderOptions::default().set_max_width(1 << 16).set_max_height(1 << 16).set_strict_mode(false).jpeg_set_out_colorspace(if gray {
|
||||
ColorSpace::Luma
|
||||
} else {
|
||||
ColorSpace::RGB
|
||||
});
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), opts);
|
||||
// zune's `decode` allocates straight from the frame header it parses, with its own caps
|
||||
// set in us: check that header against the same limits the other decoders honour first.
|
||||
d.decode_headers().map_err(|e| Error::Malformed(F, e.to_string()))?;
|
||||
let (zw, zh) = d.info().map(|i| (i.width as u64, i.height as u64)).ok_or_else(|| Error::Malformed(F, "no info".into()))?;
|
||||
check_size(F, zw, zh, budget)?;
|
||||
let px = d.decode().map_err(|e| Error::Malformed(F, e.to_string()))?;
|
||||
let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?;
|
||||
let (w, h) = (info.width as usize, info.height as usize);
|
||||
let model = if gray { Model::Gray } else { Model::Rgb };
|
||||
if px.len() < w * h * model.channels() {
|
||||
return Err(Error::Malformed(F, "short output".into()));
|
||||
}
|
||||
Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf: Buf::U8(px), bit_depth: 8 })
|
||||
}
|
||||
|
||||
fn decode_jpeg_decoder(bytes: &[u8], m: &Markers, scale_to: Option<(u32, u32)>, budget: &DecodeOptions) -> Result<Raw> {
|
||||
use jpeg_decoder::PixelFormat;
|
||||
let mut d = jpeg_decoder::Decoder::new(bytes);
|
||||
d.read_info().map_err(|e| Error::Malformed(F, e.to_string()))?;
|
||||
// Its frame header is what a decode allocates from (progressive coefficient buffers follow the
|
||||
// unscaled MCU grid): check it against the same limits the other decoders honour, before any
|
||||
// DCT scale is requested.
|
||||
let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?;
|
||||
check_size(F, info.width as u64, info.height as u64, budget)?;
|
||||
// `scale` is the DCT size, not a lossless resample: on a lossless frame it would cut the
|
||||
// output to the top-left of each plane. Those decode at full size; `finish` scales after.
|
||||
if let Some((mw, mh)) = scale_to.filter(|_| m.sof != 0xC3) {
|
||||
// Ask for the smallest DCT scale still covering the target box.
|
||||
let (sw, sh) = scaled_request(m.width, m.height, mw, mh);
|
||||
d.scale(sw, sh).map_err(|e| Error::Malformed(F, e.to_string()))?;
|
||||
}
|
||||
let px = d.decode().map_err(|e| Error::Malformed(F, e.to_string()))?;
|
||||
let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?;
|
||||
let (w, h) = (info.width as usize, info.height as usize);
|
||||
let (model, buf, depth) = match info.pixel_format {
|
||||
PixelFormat::L8 => (Model::Gray, Buf::U8(px), 8),
|
||||
PixelFormat::L16 => (Model::Gray, Buf::U16(lossless_samples(&px, m.precision)), 16),
|
||||
// A lossless frame over 8 bits per sample still reports `RGB24` (or `CMYK32`), but its
|
||||
// buffer holds two native-endian bytes per sample like L16.
|
||||
PixelFormat::RGB24 if m.precision > 8 => (Model::Rgb, Buf::U16(lossless_samples(&px, m.precision)), 16),
|
||||
PixelFormat::RGB24 => (Model::Rgb, Buf::U8(px), 8),
|
||||
PixelFormat::CMYK32 if m.precision > 8 => (Model::Cmyk, Buf::U16(lossless_samples(&px, m.precision)), 16),
|
||||
PixelFormat::CMYK32 => (Model::Cmyk, Buf::U8(px), 8),
|
||||
fn decode_via_craft_codecs(bytes: &[u8], budget: &DecodeOptions) -> Result<Raw> {
|
||||
let ic_opts = craft_image_codecs::DecodeOptions {
|
||||
limits: craft_image_codecs::Limits {
|
||||
max_width: u32::MAX,
|
||||
max_height: u32::MAX,
|
||||
max_pixels: budget.max_pixels,
|
||||
max_alloc: budget.max_pixels.saturating_mul(8),
|
||||
},
|
||||
keep_orientation: true,
|
||||
};
|
||||
Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf, bit_depth: depth })
|
||||
}
|
||||
|
||||
/// jpeg-decoder's lossless samples: one native-endian `u16` per sample holding the raw
|
||||
/// `precision`-bit value. Left-justify it into the 16-bit range the rest of the pipeline reads,
|
||||
/// as every 16-bit decoder feeding [`Buf::U16`] does.
|
||||
fn lossless_samples(px: &[u8], precision: u8) -> Vec<u16> {
|
||||
let shift = 16u8.saturating_sub(precision);
|
||||
px.as_chunks::<2>().0.iter().map(|c| u16::from_ne_bytes([c[0], c[1]]) << shift).collect()
|
||||
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, bytes, &ic_opts).map_err(|e| match e {
|
||||
craft_image_codecs::CodecError::LimitExceeded(_) => Error::TooLarge(0, 0),
|
||||
other => Error::Malformed(F, other.to_string()),
|
||||
})?;
|
||||
if img.warnings.iter().any(|w| matches!(w, craft_image_codecs::DecodeWarning::Truncated { .. })) {
|
||||
return Err(Error::Malformed(F, "truncated: the image data doesn't end with an end-of-image marker".into()));
|
||||
}
|
||||
let (w, h) = (img.width() as usize, img.height() as usize);
|
||||
check_size(F, w as u64, h as u64, budget)?;
|
||||
let model = match img.layout() {
|
||||
craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA => Model::Gray,
|
||||
craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA => Model::Cmyk,
|
||||
_ => Model::Rgb,
|
||||
};
|
||||
let (buf, bit_depth) = match img.sample_type() {
|
||||
craft_image_codecs::SampleType::U16 => {
|
||||
(Buf::U16(img.to_u16_samples().ok_or_else(|| Error::Malformed(F, "expected 16-bit samples".into()))?), 16)
|
||||
}
|
||||
_ => (Buf::U8(img.as_u8().ok_or_else(|| Error::Malformed(F, "expected 8-bit samples".into()))?.to_vec()), 8),
|
||||
};
|
||||
Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf, bit_depth })
|
||||
}
|
||||
|
||||
/// The first `0xFF` byte, eight bytes at a time (scan data has one every few hundred bytes: this
|
||||
@@ -393,15 +350,6 @@ fn find_ff(b: &[u8]) -> Option<usize> {
|
||||
tail.iter().position(|&v| v == 0xFF).map(|j| words.len() * 8 + j)
|
||||
}
|
||||
|
||||
/// The box to request from `jpeg-decoder::scale` so the decoded image still covers `mw × mh` once
|
||||
/// fitted with the source aspect ratio.
|
||||
fn scaled_request(w: u32, h: u32, mw: u32, mh: u32) -> (u16, u16) {
|
||||
let s = (mw as f64 / w as f64).min(mh as f64 / h as f64).min(1.0);
|
||||
let tw = ((w as f64 * s).ceil() as u32).clamp(1, u16::MAX as u32);
|
||||
let th = ((h as f64 * s).ceil() as u32).clamp(1, u16::MAX as u32);
|
||||
(tw as u16, th as u16)
|
||||
}
|
||||
|
||||
/// Fast path: an embedded JPEG preview (EXIF IFD1 thumbnail, or the largest MPF preview) whose long
|
||||
/// edge is ≥ `max_edge`, decoded with DCT scaling and fitted.
|
||||
pub(crate) fn embedded_thumbnail(bytes: &[u8], max_edge: u32, min_edge: u32) -> Option<Thumbnail> {
|
||||
@@ -501,12 +449,7 @@ pub(crate) fn decode_codes8(bytes: &[u8]) -> Result<(usize, usize, usize, Vec<u8
|
||||
if !matches!(m.components, 1 | 3) || m.precision != 8 {
|
||||
return Err(Error::Malformed(F, "expected an 8-bit greyscale or RGB image".into()));
|
||||
}
|
||||
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
|
||||
let raw = if non_interleaved {
|
||||
decode_jpeg_decoder(bytes, &m, None, &DecodeOptions::default())?
|
||||
} else {
|
||||
decode_zune(bytes, &m, &DecodeOptions::default())?
|
||||
};
|
||||
let raw = decode_via_craft_codecs(bytes, &DecodeOptions::default())?;
|
||||
let ch = raw.model.channels();
|
||||
match raw.buf {
|
||||
Buf::U8(v) if v.len() >= raw.width * raw.height * ch => Ok((raw.width, raw.height, ch, v)),
|
||||
@@ -660,12 +603,6 @@ mod tests {
|
||||
assert!(markers.icc_invalid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scaled_request_covers() {
|
||||
assert_eq!(scaled_request(6000, 4000, 256, 256), (256, 171));
|
||||
assert_eq!(scaled_request(100, 100, 256, 256), (100, 100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_ff_matches_a_plain_search() {
|
||||
let mut b: Vec<u8> = (0..300u32).map(|i| (i * 7 % 255) as u8).collect();
|
||||
@@ -699,96 +636,6 @@ mod tests {
|
||||
assert!(m.exif.is_none());
|
||||
}
|
||||
|
||||
// --- lossless (SOF3) synthetic files: one DHT table with a single 1-bit category-0 code, so
|
||||
// every pixel is a zero difference and decodes to the predictor's initial sample. No such
|
||||
// encoder exists here; the bytes are the smallest a decoder accepts.
|
||||
|
||||
fn lossless_header(out: &mut Vec<u8>, components: u8, w: u16, precision: u8) {
|
||||
// DHT: one DC table (id 0) with a single 1-bit code for the category-0 symbol.
|
||||
out.extend_from_slice(&[0xFF, 0xC4]);
|
||||
out.extend_from_slice(&(2u16 + 1 + 16 + 1).to_be_bytes());
|
||||
out.push(0x00);
|
||||
let mut counts = [0u8; 16];
|
||||
counts[0] = 1;
|
||||
out.extend_from_slice(&counts);
|
||||
out.push(0x00);
|
||||
// SOF3
|
||||
out.extend_from_slice(&[0xFF, 0xC3]);
|
||||
out.extend_from_slice(&(8u16 + 3 * components as u16).to_be_bytes());
|
||||
out.push(precision);
|
||||
out.extend_from_slice(&1u16.to_be_bytes());
|
||||
out.extend_from_slice(&w.to_be_bytes());
|
||||
out.push(components);
|
||||
for c in 1..=components {
|
||||
out.extend_from_slice(&[c, 0x11, 0]);
|
||||
}
|
||||
// SOS: predictor Ra, Se = 0, Ah/Al = 0
|
||||
out.extend_from_slice(&[0xFF, 0xDA]);
|
||||
out.extend_from_slice(&(6u16 + 2 * components as u16).to_be_bytes());
|
||||
out.push(components);
|
||||
for c in 1..=components {
|
||||
out.extend_from_slice(&[c, 0]);
|
||||
}
|
||||
out.extend_from_slice(&[1, 0, 0]);
|
||||
}
|
||||
|
||||
/// A minimal lossless JPEG, `w` x 1, `components` samples per pixel, every sample the initial
|
||||
/// prediction `1 << (precision - 1)`.
|
||||
fn lossless_jpeg(components: u8, w: u16, precision: u8) -> Vec<u8> {
|
||||
let mut out = vec![0xFF, 0xD8];
|
||||
lossless_header(&mut out, components, w, precision);
|
||||
// entropy: one zero bit per sample (a category-0 code), padded to whole bytes
|
||||
out.extend_from_slice(&vec![0u8; (components as usize * w as usize).div_ceil(8)]);
|
||||
out.extend_from_slice(&[0xFF, 0xD9]);
|
||||
out
|
||||
}
|
||||
|
||||
/// jpeg-decoder emits lossless samples native-endian (its `to_ne_bytes`) holding the raw
|
||||
/// `precision`-bit value, so the old `from_be_bytes` swapped every sample (2048 -> 8) and the
|
||||
/// raw value was never left-justified into the 16-bit buffer.
|
||||
#[test]
|
||||
fn lossless_grayscale_samples_are_native_endian_and_left_justified() {
|
||||
let bytes = lossless_jpeg(1, 8, 12);
|
||||
let m = parse_markers(&bytes).unwrap();
|
||||
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
|
||||
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
|
||||
assert_eq!(v, &vec![2048u16 << 4; 8], "0x0800 native-endian, left-justified");
|
||||
assert_eq!((raw.model, raw.bit_depth), (Model::Gray, 16));
|
||||
}
|
||||
|
||||
/// A lossless frame over 8 bits per sample reports `RGB24`, but its buffer is two bytes per
|
||||
/// sample: it must become `Buf::U16`, not `Buf::U8` over double-length rows.
|
||||
#[test]
|
||||
fn lossless_high_precision_rgb_is_16_bit() {
|
||||
let bytes = lossless_jpeg(3, 2, 12);
|
||||
let m = parse_markers(&bytes).unwrap();
|
||||
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
|
||||
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
|
||||
assert_eq!(v, &vec![2048u16 << 4; 6]);
|
||||
assert_eq!(raw.model, Model::Rgb);
|
||||
}
|
||||
|
||||
/// The same 16-bit wrapping for four components: `CMYK32` over 8 bits is two bytes a sample.
|
||||
#[test]
|
||||
fn lossless_high_precision_cmyk_is_16_bit() {
|
||||
let bytes = lossless_jpeg(4, 2, 12);
|
||||
let m = parse_markers(&bytes).unwrap();
|
||||
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
|
||||
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
|
||||
assert_eq!(v, &vec![2048u16 << 4; 8]);
|
||||
assert_eq!((raw.model, raw.bit_depth), (Model::Cmyk, 16));
|
||||
}
|
||||
|
||||
/// zune-jpeg refuses SOF3 ("Lossless Huffman"), so an 8-bit lossless file must route to
|
||||
/// jpeg-decoder; `header` accepts it, so `decode` used to fail a file we listed as readable.
|
||||
#[test]
|
||||
fn eight_bit_lossless_jpeg_decodes() {
|
||||
let bytes = lossless_jpeg(1, 8, 8);
|
||||
let d = crate::decode(&bytes, DecodeOptions::default()).unwrap();
|
||||
assert_eq!((d.width, d.height), (8, 1));
|
||||
assert_eq!(d.bit_depth, 8);
|
||||
}
|
||||
|
||||
/// Rewrites an encoded file's frame-header dimensions: same tables and scan, a hostile
|
||||
/// annotated size.
|
||||
fn with_dims(bytes: &[u8], w: u16, h: u16) -> Vec<u8> {
|
||||
@@ -862,3 +709,207 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`crate::decode_jpeg_srgb8_fit`]: a plain 8-bit sRGB JPEG decoded (DCT-scaled when that still
|
||||
/// covers the box) and area-averaged in linear light straight into 8-bit sRGB, without the
|
||||
/// float image the general path builds (for a 45 MP camera preview fitted to 2560 px that float
|
||||
/// image and its conversions were half the time). `Ok(None)` for anything else.
|
||||
pub(crate) fn srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result<Option<(lightcraft_raster::Rgba8, u16)>> {
|
||||
// (a Samsung SEF trailer read as the file it stands for, as the general decode does: CodeRabbit on #3583)
|
||||
let bytes = &*without_sef_trailer(bytes);
|
||||
let Some(m) = parse_markers(bytes) else { return Ok(None) };
|
||||
let plain = matches!(m.components, 1 | 3)
|
||||
&& m.precision == 8
|
||||
&& matches!(m.sof, 0xC0..=0xC2)
|
||||
&& m.icc.is_none()
|
||||
&& !m.icc_invalid
|
||||
&& m.adobe_transform.is_none();
|
||||
let summary = m.exif.as_deref().map(exif::summarize).unwrap_or_default();
|
||||
if !plain || summary.adobe_rgb_hint || max_w == 0 || max_h == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let budget = DecodeOptions::default();
|
||||
check_size(F, m.width as u64, m.height as u64, &budget)?;
|
||||
// as in the general decode: the decoders below walk every APP1 again
|
||||
if m.app1 > MAX_APP1 {
|
||||
return Err(Error::Malformed(F, "too many APP1 markers".into()));
|
||||
}
|
||||
let raw = decode_via_craft_codecs(bytes, &budget)?;
|
||||
let Buf::U8(px) = &raw.buf else { return Ok(None) };
|
||||
let ch = match raw.model {
|
||||
Model::Rgb => 3,
|
||||
Model::Gray => 1,
|
||||
Model::Cmyk => return Ok(None),
|
||||
};
|
||||
let (w, h) = (raw.width, raw.height);
|
||||
if w == 0 || h == 0 || px.len() < w.saturating_mul(h).saturating_mul(ch) {
|
||||
return Err(Error::Malformed(F, "short output".into()));
|
||||
}
|
||||
// the size `lightcraft_raster::resample::fit` gives: within the box, aspect kept, never larger
|
||||
let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0);
|
||||
let tw = ((w as f64 * s).round() as usize).clamp(1, w);
|
||||
let th = ((h as f64 * s).round() as usize).clamp(1, h);
|
||||
let orientation = summary.orientation.filter(|o| (1..=8).contains(o)).unwrap_or(1);
|
||||
Ok(Some((area_average_srgb8(px, w, h, ch, tw, th), orientation)))
|
||||
}
|
||||
|
||||
/// Source pixels and weights each output pixel along one axis covers: a box of the scale's width
|
||||
/// (`n` source pixels onto `out`), partly covered pixels at its ends weighted by their share.
|
||||
fn box_taps(n: usize, out: usize) -> Vec<(usize, Vec<f32>)> {
|
||||
let scale = n as f64 / out as f64;
|
||||
(0..out)
|
||||
.map(|o| {
|
||||
let (a, b) = (o as f64 * scale, ((o + 1) as f64 * scale).min(n as f64));
|
||||
let first = (a.floor() as usize).min(n - 1);
|
||||
let last = ((b.ceil() as usize).max(first + 1)).min(n);
|
||||
let ws: Vec<f32> =
|
||||
(first..last).map(|j| ((b.min(j as f64 + 1.0) - a.max(j as f64)).max(0.0) / (b - a).max(f64::MIN_POSITIVE)) as f32).collect();
|
||||
(first, ws)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `px` (`w × h`, `ch` = 1 or 3 interleaved 8-bit sRGB samples) averaged over boxes in linear
|
||||
/// light into `tw × th` opaque 8-bit sRGB pixels. A copy when the size doesn't change.
|
||||
fn area_average_srgb8(px: &[u8], w: usize, h: usize, ch: usize, tw: usize, th: usize) -> lightcraft_raster::Rgba8 {
|
||||
use lightcraft_color::transfer::{decode_srgb8, encode_srgb8};
|
||||
let mut out = lightcraft_raster::Rgba8::new(tw, th);
|
||||
let sample = |x: usize, y: usize, c: usize| px.get((y * w + x) * ch + if ch == 3 { c } else { 0 }).copied().unwrap_or(0);
|
||||
if (tw, th) == (w, h) {
|
||||
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = [sample(x, y, 0), sample(x, y, 1), sample(x, y, 2), 255];
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
let lut: [f32; 256] = std::array::from_fn(|i| decode_srgb8(i as u8));
|
||||
let xs = box_taps(w, tw);
|
||||
let ys = box_taps(h, th);
|
||||
// one source row filtered across into linear RGB at the output width
|
||||
let across = |sy: usize, buf: &mut Vec<[f32; 3]>| {
|
||||
buf.clear();
|
||||
let Some(src) = px.get(sy * w * ch..(sy + 1) * w * ch) else {
|
||||
buf.resize(tw, [0.0; 3]);
|
||||
return;
|
||||
};
|
||||
for (x0, wx) in &xs {
|
||||
let mut a = [0f32; 3];
|
||||
if let Some(span) = src.get(x0 * ch..(x0 + wx.len()) * ch) {
|
||||
for (p, &k) in span.chunks_exact(ch).zip(wx) {
|
||||
match p {
|
||||
[r, g, b] => {
|
||||
a[0] += lut[*r as usize] * k;
|
||||
a[1] += lut[*g as usize] * k;
|
||||
a[2] += lut[*b as usize] * k;
|
||||
}
|
||||
[v] => {
|
||||
let l = lut[*v as usize] * k;
|
||||
a = [a[0] + l, a[1] + l, a[2] + l];
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
buf.push(a);
|
||||
}
|
||||
};
|
||||
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
|
||||
let Some((y0, wy)) = ys.get(y) else { return };
|
||||
let mut acc = vec![[0f32; 3]; tw];
|
||||
let mut line = Vec::with_capacity(tw);
|
||||
for (dy, &k) in wy.iter().enumerate() {
|
||||
across(y0 + dy, &mut line);
|
||||
for (a, l) in acc.iter_mut().zip(&line) {
|
||||
a[0] += l[0] * k;
|
||||
a[1] += l[1] * k;
|
||||
a[2] += l[2] * k;
|
||||
}
|
||||
}
|
||||
for (o, a) in row.iter_mut().zip(&acc) {
|
||||
*o = [encode_srgb8(a[0]), encode_srgb8(a[1]), encode_srgb8(a[2]), 255];
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod srgb8_fit_tests {
|
||||
use super::*;
|
||||
|
||||
fn jpeg(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
|
||||
let data: Vec<[u8; 4]> = (0..w * h)
|
||||
.map(|i| {
|
||||
let [r, g, b] = f(i % w, i / w);
|
||||
[r, g, b, 255]
|
||||
})
|
||||
.collect();
|
||||
let img = lightcraft_raster::Rgba8 { width: w, height: h, data };
|
||||
crate::encode_jpeg(&crate::EncodeImage::rgba8(&img), 95, crate::ChromaSubsampling::S420, &crate::EncodeMeta::default()).unwrap()
|
||||
}
|
||||
|
||||
/// The fast path shows what the general decode shows for a plain sRGB JPEG, at the same size.
|
||||
#[test]
|
||||
fn matches_the_general_decode_within_a_few_levels() {
|
||||
let b = jpeg(1203, 801, |x, y| [((x * 7) ^ (y * 3)) as u8, (x / 5 + y / 3) as u8, ((x * y) % 251) as u8]);
|
||||
for (mw, mh) in [(300u32, 300u32), (640, 640), (1203, 801), (5000, 5000), (500, 120)] {
|
||||
let (fast, o) = srgb8_fit(&b, mw, mh).unwrap().unwrap();
|
||||
let slow = crate::decode(&b, DecodeOptions::fit(mw, mh)).unwrap().to_srgb8();
|
||||
assert_eq!((fast.width, fast.height), (slow.width, slow.height), "box {mw}×{mh}");
|
||||
assert_eq!(o, 1);
|
||||
let diff: Vec<u32> =
|
||||
fast.data.iter().zip(&slow.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] as i32 - b[c] as i32).unsigned_abs())).collect();
|
||||
let mean = diff.iter().sum::<u32>() as f64 / diff.len() as f64;
|
||||
assert!(mean < 5.0, "box {mw}×{mh}: mean difference {mean}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Anything but plain 8-bit sRGB goes the general way; junk is an error or `None`, never a panic.
|
||||
#[test]
|
||||
fn declines_what_it_does_not_cover_and_never_panics() {
|
||||
let b = jpeg(64, 48, |x, _| [x as u8, 0, 0]);
|
||||
assert!(srgb8_fit(&b, 0, 10).unwrap().is_none());
|
||||
assert!(srgb8_fit(b"not a jpeg", 10, 10).unwrap().is_none());
|
||||
for cut in [0, 2, 20, b.len() / 2, b.len() - 3] {
|
||||
let _ = srgb8_fit(&b[..cut], 32, 32);
|
||||
}
|
||||
// a 1-pixel-wide image into a box much smaller in one axis
|
||||
let thin = jpeg(1, 300, |_, y| [y as u8, y as u8, y as u8]);
|
||||
let (img, _) = srgb8_fit(&thin, 10, 10).unwrap().unwrap();
|
||||
assert_eq!((img.width, img.height), (1, 10));
|
||||
}
|
||||
|
||||
/// An incomplete ICC_PROFILE sequence (chunk 1 of 2) is "has a profile we can't read", not
|
||||
/// "plain sRGB": the general decode handles it, as the doc says (CodeRabbit on #3577).
|
||||
#[test]
|
||||
fn an_incomplete_icc_sequence_goes_the_general_way() {
|
||||
let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]);
|
||||
let mut seg = vec![0xFF, 0xE2, 0, 0];
|
||||
seg.extend_from_slice(b"ICC_PROFILE | ||||