mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge upstream/main into docs/parity-refresh-2
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
commit
c1f2ae16b8
706 files changed
+51258
-151279
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# The craft-i18n pin: CI and the build read it as one SHA, so it stays LF everywhere (readers trim it too).
|
||||
craft-i18n.rev text eol=lf
|
||||
@@ -82,6 +82,10 @@ jobs:
|
||||
windows: ${{ steps.pick.outputs.windows }}
|
||||
web: ${{ steps.pick.outputs.web }}
|
||||
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:
|
||||
fetch-depth: 0
|
||||
@@ -130,13 +134,14 @@ jobs:
|
||||
fi
|
||||
# The browser build (a fat-LTO wasm build) runs only when something it compiles or
|
||||
# packages changed: the web app and its packaging, crate sources and manifests (the web
|
||||
# build compiles nearly every crate), the workspace manifests and this workflow.
|
||||
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/photocraft-web(-boot)?/|packaging/web/|packaging/env\.sh$|crates/[^/]+/(src/|Cargo\.toml$|build\.rs$)|Cargo\.(toml|lock)$|rust-toolchain(\.toml)?$|\.github/workflows/ci\.yml$)'; then
|
||||
# build compiles nearly every crate), the workspace manifests, the craft-i18n pin and this
|
||||
# workflow.
|
||||
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/photocraft-web(-boot)?/|packaging/web/|packaging/env\.sh$|crates/[^/]+/(src/|Cargo\.toml$|build\.rs$)|Cargo\.(toml|lock)$|craft-i18n\.rev$|rust-toolchain(\.toml)?$|\.github/workflows/ci\.yml$)'; then
|
||||
echo "web=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "web=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif|format)/|Cargo\.lock$|(.*/)?build\.rs$|\.github/workflows/ci\.yml$)'; then
|
||||
if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif|format)/|Cargo\.lock$|craft-i18n\.rev$|(.*/)?build\.rs$|\.github/workflows/ci\.yml$)'; then
|
||||
echo "windows=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "windows=false" >> "$GITHUB_OUTPUT"
|
||||
@@ -196,6 +201,10 @@ jobs:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
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
|
||||
@@ -208,6 +217,11 @@ jobs:
|
||||
path: craft-fonts
|
||||
persist-credentials: false
|
||||
|
||||
# The translations at the commit in craft-i18n.rev, as the gate and release.yml embed them
|
||||
# (sets CRAFT_I18N_DIR and CRAFT_I18N_REQUIRED=1).
|
||||
- name: Check out craft-i18n
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
with:
|
||||
components: clippy
|
||||
@@ -247,7 +261,7 @@ jobs:
|
||||
if: matrix.part == 'integration'
|
||||
run: cargo xtask layers
|
||||
|
||||
- uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2.87.29
|
||||
- uses: taiki-e/install-action@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2
|
||||
with:
|
||||
tool: [email protected]
|
||||
|
||||
@@ -284,10 +298,19 @@ jobs:
|
||||
CARGO_INCREMENTAL: 0
|
||||
CARGO_NET_RETRY: 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
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# The translations at the commit in craft-i18n.rev, as the gate and release.yml embed them
|
||||
# (sets CRAFT_I18N_DIR and CRAFT_I18N_REQUIRED=1).
|
||||
- name: Check out craft-i18n
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
|
||||
- name: Install Linux build dependencies
|
||||
uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
@@ -304,12 +327,12 @@ jobs:
|
||||
shared-key: ${{ hashFiles('Cargo.toml') }}-gate
|
||||
save-if: false
|
||||
|
||||
- uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2.87.29
|
||||
- uses: taiki-e/install-action@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2
|
||||
with:
|
||||
tool: [email protected]
|
||||
|
||||
- name: Test without heif
|
||||
run: cargo nextest run -p photocraft-heif -p photocraft-codecs -p photocraft-io --locked --profile ci
|
||||
run: cargo nextest run -p photocraft-codecs -p photocraft-io --locked --profile ci
|
||||
|
||||
corpus:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
@@ -328,6 +351,10 @@ jobs:
|
||||
CARGO_PROFILE_RELEASE_LTO: "false"
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16"
|
||||
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
|
||||
@@ -358,9 +385,19 @@ jobs:
|
||||
# Match release.yml so PR results reflect what would actually ship.
|
||||
TRUNK_VERSION: 0.21.14
|
||||
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
|
||||
|
||||
# The translations at the commit in craft-i18n.rev, as the gate and release.yml embed them
|
||||
# (sets CRAFT_I18N_DIR and CRAFT_I18N_REQUIRED=1).
|
||||
- name: Check out craft-i18n
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
with:
|
||||
targets: wasm32-unknown-unknown
|
||||
@@ -429,6 +466,10 @@ jobs:
|
||||
- { crate: affinity, name: import_preview, args: "--features io" }
|
||||
- { crate: format, name: load }
|
||||
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
|
||||
@@ -457,6 +498,10 @@ jobs:
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
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
|
||||
@@ -487,6 +532,10 @@ jobs:
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
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
|
||||
@@ -522,6 +571,10 @@ jobs:
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 60
|
||||
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
|
||||
@@ -546,6 +599,10 @@ jobs:
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
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
|
||||
@@ -570,6 +627,10 @@ jobs:
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
@@ -616,6 +677,10 @@ jobs:
|
||||
CARGO_PROFILE_RELEASE_LTO: "false"
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16"
|
||||
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:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -31,6 +31,10 @@ jobs:
|
||||
name: mdBook build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7
|
||||
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
- name: Install mdBook
|
||||
|
||||
@@ -5,9 +5,9 @@ name: Packaging lint
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -21,12 +21,18 @@ jobs:
|
||||
lint:
|
||||
# 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/packaging-lint.yml@main
|
||||
with:
|
||||
extra-checks-script: packaging/linux/package-docs-test.sh
|
||||
|
||||
verified-appimage-inputs:
|
||||
timeout-minutes: 10
|
||||
name: Verified AppImage inputs
|
||||
runs-on: ubuntu-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
|
||||
- run: bash packaging/linux/verified-download-test.sh
|
||||
|
||||
@@ -35,6 +41,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
|
||||
|
||||
@@ -43,6 +43,10 @@ jobs:
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -118,7 +118,7 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file,
|
||||
3. **Clean-room.** We studied Photoshop and other proprietary editors for *behaviour and look only*. Never copy their code, shaders, profiles or assets. Implement from public specs (Adobe PSD spec, ICC, ISO 32000 blend modes, papers) and observation. Third-party assets must be permissively licensed, keep their license file next to them, and get a row in `ATTRIBUTION.md` (path, title, author, source, license) in the same change; so do original assets. The ArtCraft logos in `docs/brand/` are not open source (`docs/brand/LICENSE-brand.txt`). **Never commit font files:** fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). PhotoCraft uses it through the optional build input `CRAFT_FONTS_DIR=<craft-fonts checkout>` (read by `crates/text/build.rs`, exposed as `photocraft_text::CRAFT_FONTS`; empty without it, and everything must still work). Build with it: `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo build`; details in `docs/development.md` › Fonts.
|
||||
4. **Tests are the gate.** Every change comes with tests. Format crates use round-trip, synthetic-generator, oracle and fuzz tests. Keep the PSD corpus results and the parity floor (`crates/ui-egui/src/parity.rs`) from regressing.
|
||||
5. **The UI is thin and data-driven.** UI state lives in `ui-egui/src/state.rs` (serde), so the control channel can read and drive it. Colours and radii come from `theme::Tokens`, never hard-coded.
|
||||
6. **Verify UI changes visually.** Render offscreen with `cargo run -p photocraft-ui-egui --example snapshot` (no window, no focus stealing), or launch with `--control` and take `ui.screenshot`. Look at the PNG. Demo images must be public-domain art, never personal photos. When fetching assets, never put a person's name, email or other personal details in requests (User-Agent, headers, URLs); use a generic `Photocraft-dev` User-Agent.
|
||||
6. **Verify UI changes visually.** Render offscreen with `cargo run -p photocraft-ui-egui --example snapshot` (no window, no focus stealing), or launch with `--control` and take `ui.screenshot`. Look at the PNG. **Screenshots that show a PR's change (before/after evidence) go in the PR description, never in the repo:** `docs/images/` holds only images the README or a doc displays (a doc's own before/after comparison included), so a PR adds an image there only together with the doc that shows it. Demo images must be public-domain art, never personal photos. When fetching assets, never put a person's name, email or other personal details in requests (User-Agent, headers, URLs); use a generic `Photocraft-dev` User-Agent.
|
||||
7. **Never break wasm.** L0–L6 must `cargo check --target wasm32-unknown-unknown` (run `cargo xtask wasm`). File-system code is `cfg(not(target_arch = "wasm32"))` or goes through the platform services.
|
||||
8. **Performance is a feature.** Benchmark heavy operations on a 24–36 MP image in release. Work per tile in parallel (rayon), skip empty tiles, never scan a full surface per frame (cache per revision), and record before/after timings in the dev log.
|
||||
|
||||
|
||||
+6
-33
@@ -11,39 +11,13 @@ next to them.
|
||||
| Path | Title | Author | Source | License |
|
||||
|---|---|---|---|---|
|
||||
| `crates/codecs/src/codecs/xpm/x11_colors.rs` | X11 `rgb.txt` color-name lookup table (normalized X.Org RGB values) | X.Org Foundation and X11 contributors | <https://cgit.freedesktop.org/xorg/app/rgb/tree/rgb.txt> | MIT (X.Org app/rgb) |
|
||||
| `crates/ui-egui/src/i18n/el.tsv` | Greek UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/de.tsv` | German UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/es.tsv` | Spanish UI translations | @gorevyoneticisi; AI contributor: OpenAI Codex | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/it.tsv` | Italian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ko.tsv` | Korean UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/nl.tsv` | Dutch UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/pl.tsv` | Polish UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/cs.tsv` | Czech UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/az.tsv` | Azerbaijani (Latin script) UI translations | PhotoCraft contributors; AI contributor: OpenAI Codex | PhotoCraft English labels; Google Translate drafts with edited core terminology, contexts and plurals | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/bs.tsv` | Bosnian (Latin, Ijekavian) UI translations | Nine (@nine-codes) with Claude Code, AI-assisted; not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/sr.tsv` | Serbian (Latin, Ekavian) UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ru.tsv` | Russian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/sv.tsv` | Swedish UI translations | @kler, @davvarn and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish UI translations | @Janiz-zzz, @metuuu and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/da.tsv` | Danish UI translations | @pechnikov2026-star and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål UI translations | @nikolainyegaard, @Bolla76 and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/he.tsv` | Hebrew UI translations | @tronicum with Claude Code, AI-assisted (machine-translated); not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ur.tsv` | Urdu UI translations | @tronicum with Claude Code, AI-assisted (machine-translated); not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ro.tsv` | Romanian UI translations | @tronicum with Claude Code, AI-assisted (machine-translated); not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/th.tsv` | Thai UI translations | @Thanawatttt and PhotoCraft contributors, with opencode (DeepSeek) as an AI contributor | Machine-assisted first draft from PhotoCraft's English labels, reviewed for UI terminology | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ta.tsv` | Tamil UI translations | @newsbaba24x7 and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ka.tsv` | Georgian UI translations | @devius with Claude Code, AI-assisted | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
|
||||
| Embedded at build time from storytold/craft-i18n `locales/<code>/common.tsv` and `locales/<code>/photocraft.tsv` (revision in [`craft-i18n.rev`](craft-i18n.rev)) | UI translations (all languages) | craft-i18n and PhotoCraft contributors; per-language credits and provenance in [craft-i18n's ATTRIBUTION.md](https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md) | <https://github.com/storytold/craft-i18n> | MIT OR Apache-2.0; Copyright (c) 2026 ArtCraft Team and the craft-i18n contributors; notice in [NOTICE](NOTICE) |
|
||||
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/text/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
|
||||
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
|
||||
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
|
||||
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (116 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/*.svg` except `vector-shape.svg`, `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (116 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/vector-shape.svg` | Vector path shape-layer glyph with four anchor points | @superplay2021 | Original work for PhotoCraft | MIT OR Apache-2.0 |
|
||||
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/crop-overlay-*.svg` | Crop overlay glyphs: Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio and Golden Spiral inside the crop-mark frame | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
@@ -107,11 +81,10 @@ The other built-in ICC profiles and the generated LUT looks are produced by code
|
||||
|---|---|---|---|---|
|
||||
| `docs/brand/` (all files) | ArtCraft name, wordmark and mark | ArtCraft Team | getartcraft.com | Not open source; trademarks of the ArtCraft Team, [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt) |
|
||||
| `docs/images/photocraft-*.jpg` | PhotoCraft screenshots | PhotoCraft contributors (UI) | Rendered offscreen with the `snapshot` example | MIT OR Apache-2.0 (UI); the artwork in each is public domain, listed below |
|
||||
| `docs/images/preferences-apply-*.png` | Preferences before and after adding Apply (no artwork) | PhotoCraft contributors | PhotoCraft control-channel capture and offscreen `snapshot` example | MIT OR Apache-2.0 |
|
||||
| `docs/images/guide-position-*-tab.png` | New Guide before and after focusing Position with Tab (no artwork) | PhotoCraft contributors | Offscreen `snapshot` example with `ui.key Tab` | MIT OR Apache-2.0 |
|
||||
| `docs/images/embedded-vector-editor-en.png` | Embedded AI/PDF/EPS conversion warning and editor chooser (no artwork) | Don Omondi | Offscreen `smart_svg_ui::tests::capture_embedded_vector_conversion_prompt` with authored bytes and mock services | MIT OR Apache-2.0 |
|
||||
| `docs/images/embedded-vector-tabs-linux.png` | Shared VectorCraft window after a portal editor save and ordinary document launch | Don Omondi | Local Linux GUI acceptance with authored orange rectangle/blue circle SVGs; no private artwork | MIT OR Apache-2.0 |
|
||||
| `docs/images/gradient-overlay-method-*.png` | Gradient Overlay Method selector, before and after (synthetic gradient) | @oRE-o | Rendered offscreen with the `snapshot` example; no external artwork | MIT OR Apache-2.0 |
|
||||
| `docs/images/preset-invalid-choice-before.png` | Gradient preset import before validation, with the collision dialog closed | @yoriswind | Offscreen PhotoCraft capture with the synthetic `Fire.grd` gradient fixture | MIT OR Apache-2.0 |
|
||||
| `docs/images/preset-invalid-choice-after.png` | Gradient preset import after validation, with the collision dialog still open | @yoriswind | Offscreen PhotoCraft capture with the synthetic `Fire.grd` gradient fixture | MIT OR Apache-2.0 |
|
||||
| `docs/images/cpu-pixel-alignment/*.png` | CPU canvas pixel alignment, before and after #8321 | PhotoCraft contributors | Original synthetic noise rendered with the offscreen `snapshot` example; see the adjacent README | MIT OR Apache-2.0, adjacent `LICENSE-MIT` and `LICENSE-APACHE` |
|
||||
| `docs/images/multi-channel-editing/{curves,curves-choices,levels,drawing,mask-view-before,mask-view-after}.png` | Selected colour channel editing (synthetic gradient) | @hidoba | Original synthetic gradient rendered with the offscreen `snapshot` example; adjacent JSON scripts | MIT OR Apache-2.0, adjacent `LICENSE-MIT` and `LICENSE-APACHE` |
|
||||
| `docs/images/multi-channel-editing/great-wave.jpg`, `rgb.png`, `cmyk.png`, `lab.png`, `gallery-channel-preview-{before,after}.png` | *The Great Wave off Kanagawa*, c. 1830–1832, and PhotoCraft channel-selection captures | Katsushika Hokusai (artwork); PhotoCraft contributors (UI) | [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Tsunami_by_hokusai_19th_century.jpg), Metropolitan Museum reproduction; adjacent JSON capture scripts | Public domain artwork (PD-Art), adjacent `LICENSE-PUBLIC-DOMAIN.txt`; UI/scripts MIT OR Apache-2.0 |
|
||||
|
||||
Generated
+69
-51
@@ -1406,17 +1406,26 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-heif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=081078bb1b44aeedfa5bef3d4f13d978dc77510a#081078bb1b44aeedfa5bef3d4f13d978dc77510a"
|
||||
dependencies = [
|
||||
"heic-rs",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1439,7 +1448,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1457,7 +1466,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hayro",
|
||||
@@ -1469,7 +1478,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"log",
|
||||
@@ -1483,7 +1492,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1504,7 +1513,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1514,6 +1523,7 @@ dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
"plist",
|
||||
"rustix 1.1.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1736,6 +1746,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2964,7 +2975,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hayro-interpret",
|
||||
@@ -2994,7 +3005,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3012,7 +3023,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3036,7 +3047,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f"
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -3076,6 +3087,15 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
@@ -5304,7 +5324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"async-io",
|
||||
@@ -5359,7 +5379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-affinity"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -5369,7 +5389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-algo"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"photocraft-color",
|
||||
@@ -5384,12 +5404,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-automation"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"cap-std",
|
||||
"clap",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"photocraft-codecs",
|
||||
"photocraft-color",
|
||||
"photocraft-compose",
|
||||
@@ -5408,6 +5429,7 @@ dependencies = [
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"wgpu",
|
||||
@@ -5415,7 +5437,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-cli"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
@@ -5441,7 +5463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-cms"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"moxcms",
|
||||
"rayon",
|
||||
@@ -5449,8 +5471,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-codecs"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"craft-heif",
|
||||
"craft-jpeg",
|
||||
"exr",
|
||||
"flate2",
|
||||
@@ -5459,7 +5482,6 @@ dependencies = [
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"jxl-oxide",
|
||||
"photocraft-heif",
|
||||
"png 0.18.1",
|
||||
"proptest",
|
||||
"rayon",
|
||||
@@ -5473,7 +5495,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-color"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-cms",
|
||||
"serde",
|
||||
@@ -5481,7 +5503,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-compose"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"photocraft-cms",
|
||||
@@ -5497,7 +5519,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-doc"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-color",
|
||||
"photocraft-geom",
|
||||
@@ -5508,7 +5530,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-engine"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -5551,7 +5573,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-format"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-pcraft-format",
|
||||
@@ -5575,14 +5597,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-geom"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-gpu"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"half",
|
||||
@@ -5601,16 +5623,9 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-heif"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"heic-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-io"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-docpath",
|
||||
@@ -5650,18 +5665,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-ipp"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-ops"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-doc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-paint"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-cms",
|
||||
"photocraft-color",
|
||||
@@ -5675,7 +5690,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-plugins"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-color",
|
||||
"photocraft-geom",
|
||||
@@ -5691,7 +5706,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-psd"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -5703,7 +5718,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-raster"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"lz4_flex",
|
||||
@@ -5719,7 +5734,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-raw"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -5734,7 +5749,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-tablet"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"log",
|
||||
@@ -5749,7 +5764,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-testkit"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"memory-stats",
|
||||
"serde_json",
|
||||
@@ -5757,7 +5772,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-text"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"parley",
|
||||
@@ -5772,10 +5787,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-ui-egui"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"craft-i18n",
|
||||
"craft-print",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
@@ -5820,7 +5836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-vector"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"photocraft-color",
|
||||
"photocraft-doc",
|
||||
@@ -5831,7 +5847,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-web"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5854,7 +5870,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "photocraft-web-boot"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"js-sys",
|
||||
@@ -9473,7 +9489,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "winprint"
|
||||
version = "0.2.1"
|
||||
source = "git+https://github.com/storytold/winprint.rs?rev=51934db382f225454cf152a8657eb03789be63c4#51934db382f225454cf152a8657eb03789be63c4"
|
||||
source = "git+https://github.com/storytold/winprint.rs?rev=bc06a7c48b768eb27a828c7986f6d2868b245ee0#bc06a7c48b768eb27a828c7986f6d2868b245ee0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"fmt-derive",
|
||||
@@ -9488,6 +9504,7 @@ dependencies = [
|
||||
"windows",
|
||||
"windows-core",
|
||||
"windows-implement",
|
||||
"windows-numerics",
|
||||
"xml",
|
||||
]
|
||||
|
||||
@@ -9739,9 +9756,10 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-i18n",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
|
||||
+18
-12
@@ -4,13 +4,13 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.20.1"
|
||||
version = "0.23.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] }
|
||||
# internal
|
||||
photocraft-geom = { path = "crates/geom" }
|
||||
photocraft-color = { path = "crates/color" }
|
||||
@@ -39,13 +39,19 @@ photocraft-tablet = { path = "crates/tablet" }
|
||||
photocraft-ipp = { path = "crates/ipp" }
|
||||
|
||||
# external
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["raster"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
|
||||
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "081078bb1b44aeedfa5bef3d4f13d978dc77510a" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["raster"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" }
|
||||
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
|
||||
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
|
||||
# the commit in `craft-i18n.rev`). Already in the tree through craft-ui.
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
# 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 = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = "1"
|
||||
@@ -135,7 +141,7 @@ opt-level = "s"
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.photocraft-raw]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.photocraft-heif]
|
||||
[profile.wasm-release.package.craft-heif]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.photocraft-vector]
|
||||
opt-level = "s"
|
||||
@@ -205,7 +211,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README).
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
+11
-2
@@ -33,6 +33,16 @@ RUN set -eu; \
|
||||
trunk --version
|
||||
|
||||
WORKDIR /src
|
||||
# The interface translations at the commit in craft-i18n.rev (crates/ui-egui/build.rs), as CI and
|
||||
# releases embed them; without them the build would be English only.
|
||||
COPY craft-i18n.rev ./
|
||||
RUN set -eu; \
|
||||
rev="$(tr -d '[:space:]' < craft-i18n.rev)"; \
|
||||
mkdir -p /opt/craft-i18n; \
|
||||
curl --proto '=https' -fsSL --retry 3 -A Photocraft-dev "https://codeload.github.com/storytold/craft-i18n/tar.gz/$rev" \
|
||||
| tar -xz --strip-components=1 -C /opt/craft-i18n; \
|
||||
test -d /opt/craft-i18n/locales
|
||||
ENV CRAFT_I18N_DIR=/opt/craft-i18n CRAFT_I18N_REQUIRED=1
|
||||
COPY . .
|
||||
WORKDIR /src/apps/photocraft-web
|
||||
# Docker serving has no static-host per-file size cap. Thin LTO uses less build
|
||||
@@ -57,8 +67,7 @@ FROM nginx:${NGINX_VERSION} AS runtime
|
||||
COPY packaging/web/nginx.conf /etc/nginx/nginx.conf
|
||||
COPY --from=builder /src/dist/web/ /usr/share/nginx/html/
|
||||
COPY LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md /usr/share/nginx/html/
|
||||
COPY assets/fonts/OFL-*.txt assets/icons/LICENSE-*.txt assets/dict/LICENSE-*.txt \
|
||||
crates/ui-egui/src/i18n/LICENSE-translations.txt /usr/share/nginx/html/licenses/
|
||||
COPY assets/fonts/OFL-*.txt assets/icons/LICENSE-*.txt assets/dict/LICENSE-*.txt /usr/share/nginx/html/licenses/
|
||||
# Bypass the stock entrypoint: this configuration needs no runtime rewriting.
|
||||
USER nginx
|
||||
EXPOSE 8080
|
||||
|
||||
@@ -17,17 +17,18 @@ JetBrains Mono font (assets/fonts/JetBrainsMono-Regular.ttf) — SIL Open Font L
|
||||
Lucide icons (assets/icons/*.svg, except slice-knife.svg) — ISC; icons derived from Feather also MIT. See assets/icons/LICENSE-lucide.txt.
|
||||
SCOWL English word list (assets/dict/en_US-scowl-50.txt.gz) — SCOWL license. See assets/dict/LICENSE-SCOWL.txt.
|
||||
libfacedetection face detection weights and network (crates/algo/data/libfacedetection.bin, crates/algo/src/faces/cnn.rs) — BSD-3-Clause, Copyright (c) 2015-2019, Shiqi Yu, all rights reserved. See crates/algo/data/LICENSE-libfacedetection.txt.
|
||||
Interface translations (embedded at build time from storytold/craft-i18n locales/<code>/common.tsv and photocraft.tsv, at the commit in craft-i18n.rev) — MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the craft-i18n contributors; the license texts are the same as LICENSE-MIT and LICENSE-APACHE. Per-language credits and provenance: https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md
|
||||
|
||||
Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) also embed the fonts listed in
|
||||
https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (today BIZ UDPGothic, Shippori Mincho and
|
||||
BIZ UDMincho; not the web build), under the SIL Open Font License 1.1. Their licence texts
|
||||
ship with the package as OFL-<family>.txt.
|
||||
|
||||
Linux Wayland window decorations
|
||||
-------------------------------
|
||||
Linux and FreeBSD Wayland window decorations
|
||||
-------------------------------------------
|
||||
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
|
||||
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
|
||||
for vector window controls. Its title-font features are disabled: no Cantarell
|
||||
and FreeBSD for vector window controls. Its title-font features are disabled: no Cantarell
|
||||
font is embedded by this dependency and no font file is added to this repo.
|
||||
|
||||
sctk-adwaita's MIT licence:
|
||||
|
||||
+2
-1
@@ -86,7 +86,8 @@ Rows and evidence: [target-app-parity › Feature areas](docs/target-app-parity.
|
||||
|
||||
## Languages
|
||||
|
||||
Measured with the `cargo xtask i18n-coverage` key universe (1,608 keys). `partial` everywhere
|
||||
Measured before the craft-i18n cutover with the former `cargo xtask i18n-coverage` key universe
|
||||
(1,608 keys); `cargo xtask i18n-report` now reports coverage. `partial` everywhere
|
||||
because engine messages are still English. Detail: [localization-parity](docs/localization-parity.md).
|
||||
|
||||
| Language | Code | UI strings | Status |
|
||||
|
||||
@@ -8,7 +8,7 @@ build = "build.rs"
|
||||
|
||||
[features]
|
||||
default = ["gpu"]
|
||||
# Open HEIC/HEIF photos (the optional photocraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it; official builds (CI, packaging/, release) build with `--features heif`.
|
||||
heif = ["photocraft-codecs/heif"]
|
||||
# Optional native GPU rendering backend, enabled by default in native CLI builds.
|
||||
|
||||
@@ -7,7 +7,7 @@ license.workspace = true
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
# Open HEIC/HEIF photos (the optional photocraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it; official builds (CI, packaging/, release) build with `--features heif`.
|
||||
heif = ["photocraft-codecs/heif"]
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ description = "PhotoCraft: an open-source, native image editor"
|
||||
build = "build.rs"
|
||||
|
||||
[features]
|
||||
# Open HEIC/HEIF photos (the optional photocraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it; official builds (CI, packaging/, release) build with `--features heif`.
|
||||
heif = ["photocraft-codecs/heif"]
|
||||
|
||||
@@ -102,6 +102,12 @@ async-io = "=2.6.0"
|
||||
# re-export winit's `EventLoopBuilderExtX11`. Already in Cargo.lock (eframe); pinned exactly.
|
||||
winit = { version = "=0.30.13", default-features = false, features = ["wayland-csd-adwaita-notitle", "x11"] }
|
||||
|
||||
# FreeBSD runs the same Wayland and X11 stack, so the System Title Bar preference should get winit's
|
||||
# font-free Adwaita controls there as well: without them winit draws sctk's plain fallback frame on
|
||||
# compositors without server-side decorations (GNOME). Already in Cargo.lock (eframe); pinned exactly.
|
||||
[target.'cfg(target_os = "freebsd")'.dependencies]
|
||||
winit = { version = "=0.30.13", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
|
||||
|
||||
# Safe Win32 wrappers on Windows: the pointer position for file drops (`cursor.rs`,
|
||||
# GetCursorPos) and the window frame for the custom title bar (`window_frame.rs`, window styles),
|
||||
# no dependencies of its own. Pinned exactly: review the diff before bumping.
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use photocraft_automation::budgets::write_reply;
|
||||
use photocraft_automation::security::{
|
||||
AUTH_DEADLINE, AuthDeadlineStream, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream,
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream,
|
||||
read_bounded_line, repeat_auth_reply,
|
||||
};
|
||||
use photocraft_ui_egui::ControlRequest;
|
||||
@@ -66,6 +66,7 @@ fn serve_with_auth_deadline(stream: TcpStream, token: &str, tx: Sender<ControlRe
|
||||
let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
|
||||
let mut out = stream;
|
||||
let mut line = String::new();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut authenticated = false;
|
||||
loop {
|
||||
match read_bounded_line(&mut reader, &mut line) {
|
||||
@@ -84,12 +85,12 @@ fn serve_with_auth_deadline(stream: TcpStream, token: &str, tx: Sender<ControlRe
|
||||
Ok(LineRead::Line) => {}
|
||||
}
|
||||
if !authenticated {
|
||||
let (reply, ok) = authentication_reply(&line, token);
|
||||
authenticated = ok;
|
||||
if ok && reader.get_mut().authenticated().is_err() {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
authenticated = step == AuthStep::Authenticated;
|
||||
if authenticated && reader.get_mut().authenticated().is_err() {
|
||||
break;
|
||||
}
|
||||
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() || !authenticated {
|
||||
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() || step == AuthStep::Rejected {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
@@ -326,4 +327,49 @@ mod tests {
|
||||
handler.join().unwrap();
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
/// NV-6: the desktop server answers challenge authentication, proving it holds the token
|
||||
/// before the client sends its proof, and dispatches only after that proof.
|
||||
#[test]
|
||||
fn challenge_authentication_proves_the_server_then_serves() {
|
||||
use photocraft_automation::security::{CHALLENGE_METHOD, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
serve(stream, TOKEN, tx, egui::Context::default());
|
||||
});
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert_eq!(req.method, "test.after", "only the request after the proof is dispatched");
|
||||
req.reply.send(json!({"ok": true, "result": "served"})).unwrap();
|
||||
});
|
||||
let mut stream = TcpStream::connect(addr).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
let client_nonce = generate_nonce().unwrap();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}})).unwrap();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let challenge: Value = serde_json::from_str(&line).unwrap();
|
||||
assert!(!line.contains(TOKEN), "{line}");
|
||||
let server_nonce = challenge["result"]["serverNonce"].as_str().unwrap().to_owned();
|
||||
let server_proof = challenge["result"]["serverProof"].as_str().unwrap();
|
||||
assert!(proof_matches(TOKEN, ProofRole::Server, &client_nonce, &server_nonce, server_proof), "{line}");
|
||||
let proof = handshake_proof(TOKEN, ProofRole::Client, &client_nonce, &server_nonce).unwrap();
|
||||
writeln!(stream, "{}", json!({"id": 2, "method": "auth", "params": {"proof": proof}})).unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"]["authenticated"], true, "{line}");
|
||||
writeln!(stream, "{}", json!({"id": 3, "method": "test.after"})).unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"], "served");
|
||||
drop(reader);
|
||||
drop(stream);
|
||||
handler.join().unwrap();
|
||||
server.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -45,21 +45,28 @@ pub fn base_dirs(var: &dyn Fn(&str) -> Option<String>) -> Vec<PathBuf> {
|
||||
dirs
|
||||
}
|
||||
|
||||
/// One `[section]` of an `index.theme`, as (key, value) pairs.
|
||||
fn section<'a>(index: &'a str, name: &str) -> Vec<(&'a str, &'a str)> {
|
||||
let mut inside = false;
|
||||
let mut pairs = vec![];
|
||||
/// Every `[section]` of an `index.theme` as (key, value) pairs, in one pass; the first section
|
||||
/// of a name wins. (Looking each directory's section up by rescanning the file multiplied its
|
||||
/// size by the number of directories.)
|
||||
fn sections(index: &str) -> std::collections::HashMap<&str, Vec<(&str, &str)>> {
|
||||
let mut all = std::collections::HashMap::new();
|
||||
let mut current: Option<Vec<(&str, &str)>> = None;
|
||||
let mut name = "";
|
||||
for line in index.lines().map(str::trim) {
|
||||
if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
if inside {
|
||||
break;
|
||||
if let Some(done) = current.take() {
|
||||
all.entry(name).or_insert(done);
|
||||
}
|
||||
inside = s == name;
|
||||
} else if inside && let Some((k, v)) = line.split_once('=') {
|
||||
name = s;
|
||||
current = Some(vec![]);
|
||||
} else if let (Some(pairs), Some((k, v))) = (current.as_mut(), line.split_once('=')) {
|
||||
pairs.push((k.trim(), v.trim()));
|
||||
}
|
||||
}
|
||||
pairs
|
||||
if let Some(done) = current {
|
||||
all.entry(name).or_insert(done);
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn list(value: Option<&str>) -> impl Iterator<Item = &str> {
|
||||
@@ -156,13 +163,14 @@ impl IconTheme {
|
||||
// The first index wins; a theme can still be spread over several base directories.
|
||||
let Some(index) = roots.iter().find_map(|r| read_small(&r.join("index.theme"))) else { continue };
|
||||
let index = String::from_utf8_lossy(&index);
|
||||
let head = section(&index, "Icon Theme");
|
||||
let all = sections(&index);
|
||||
let head = all.get("Icon Theme").map_or(&[][..], Vec::as_slice);
|
||||
let get = |k: &str| head.iter().find(|(key, _)| *key == k).map(|(_, v)| *v);
|
||||
let mut subdirs: Vec<((i64, i64), &str)> = list(get("Directories"))
|
||||
.chain(list(get("ScaledDirectories")))
|
||||
.filter(|d| !d.split('/').any(|part| part == ".." || part.is_empty()))
|
||||
.take(MAX_DIRS)
|
||||
.map(|d| (distance(§ion(&index, d)), d))
|
||||
.map(|d| (distance(all.get(d).map_or(&[][..], Vec::as_slice)), d))
|
||||
.collect();
|
||||
subdirs.sort_by_key(|(key, _)| *key);
|
||||
// Not checked for existence: a theme lists hundreds, and the search stops at a hit.
|
||||
@@ -193,7 +201,8 @@ impl IconTheme {
|
||||
/// unreadable SVG or an absurd size.
|
||||
pub fn rasterize_mask(svg: &[u8], px: u32) -> Option<Vec<u8>> {
|
||||
use resvg::{tiny_skia, usvg};
|
||||
if !(1..=256).contains(&px) {
|
||||
// usvg inflates gzip (`.svgz`) input without a decoded-size limit, and icons are plain `.svg`.
|
||||
if !(1..=256).contains(&px) || svg.starts_with(&[0x1f, 0x8b]) {
|
||||
return None;
|
||||
}
|
||||
// Glyphs are paths: no `<image>` is loaded, so an icon can't make us read another file
|
||||
@@ -287,6 +296,19 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sections_are_read_once_and_the_first_of_a_name_wins() {
|
||||
let all = sections("stray=1\n[A]\nSize=16\n[B]\nSize=22\n[A]\nSize=48\n");
|
||||
assert_eq!(all["A"], vec![("Size", "16")]);
|
||||
assert_eq!(all["B"], vec![("Size", "22")]);
|
||||
assert!(!all.contains_key(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gzip_icon_is_refused() {
|
||||
assert_eq!(rasterize_mask(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0], 16), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distance_follows_the_spec() {
|
||||
assert_eq!(distance(&[("Size", "16"), ("Type", "Fixed")]), (0, 1));
|
||||
|
||||
@@ -153,7 +153,7 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
.with_app_id(APP_ID)
|
||||
.with_title("PhotoCraft")
|
||||
.with_inner_size([1440.0, 900.0])
|
||||
.with_min_inner_size([760.0, 480.0])
|
||||
.with_min_inner_size(photocraft_ui_egui::MIN_WINDOW_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_decorations(!custom_titlebar)
|
||||
.with_fullsize_content_view(true)
|
||||
@@ -682,6 +682,7 @@ fn main() -> eframe::Result {
|
||||
tablet::spawn_x11(&app.stylus.feed, display);
|
||||
app.services.right_button_down = tablet::right_button_service();
|
||||
app.services.pen_end = tablet::pen_end_service();
|
||||
app.services.pen_screen_px = tablet::pen_screen_service();
|
||||
// Paths on the command line (Linux/Windows file associations, `photocraft a.psd`).
|
||||
app.open_paths(&files);
|
||||
if !unreadable_paths.is_empty() {
|
||||
@@ -1066,4 +1067,24 @@ mod tests {
|
||||
let class = entry.lines().find_map(|line| line.strip_prefix("StartupWMClass="));
|
||||
assert_eq!(class, Some(super::APP_ID));
|
||||
}
|
||||
|
||||
/// Both flatpak manifests build with the craft-i18n commit `craft-i18n.rev` pins: CI and
|
||||
/// releases read the file, and the manifests have to name the commit themselves. The pin may
|
||||
/// have a trailing newline or CRLF (a Windows checkout), so it is trimmed, as every reader does.
|
||||
#[test]
|
||||
fn the_flatpak_manifests_pin_the_craft_i18n_rev() {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let rev = std::fs::read_to_string(root.join("craft-i18n.rev")).unwrap();
|
||||
let rev = rev.trim();
|
||||
assert!(rev.len() == 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()), "craft-i18n.rev holds one full SHA: {rev:?}");
|
||||
for manifest in ["ai.storyteller.photocraft.yml", "ai.storyteller.photocraft.bundle.yml"] {
|
||||
let text = std::fs::read_to_string(root.join("packaging/linux/flatpak").join(manifest)).unwrap();
|
||||
let source = text.split("url: https://github.com/storytold/craft-i18n").nth(1).unwrap_or_else(|| panic!("{manifest}: a craft-i18n git source"));
|
||||
let source = source.split("- type:").next().unwrap_or(source);
|
||||
let commit =
|
||||
source.lines().find_map(|l| l.trim().strip_prefix("commit:")).unwrap_or_else(|| panic!("{manifest}: the craft-i18n source pins a commit"));
|
||||
assert_eq!(commit.trim().trim_matches(['\'', '"']), rev, "{manifest}");
|
||||
assert!(text.contains("CRAFT_I18N_DIR: /run/build/photocraft/craft-i18n"), "{manifest}: the build names the catalogs");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,39 +36,40 @@ fn open_filter_extensions(extensions: &[&str]) -> Vec<String> {
|
||||
}
|
||||
|
||||
/// File › Open's file types after All Formats, as Photoshop lists them: one per format, so a folder
|
||||
/// of mixed files can be narrowed to one kind (#6337). Together they cover every extension of
|
||||
/// of mixed files can be narrowed to one kind (#6337). The document formats, the rest by name as in
|
||||
/// [`SAVE_FILTERS`], then the app's own resources. Together they cover every extension of
|
||||
/// [`OPEN_EXTS`]. An explicit SVG filter also keeps vector artwork discoverable when a native
|
||||
/// picker defaults to another filter.
|
||||
const OPEN_FILTERS: &[(&str, &[&str])] = &[
|
||||
("PhotoCraft", &["pcraft"]),
|
||||
("Photoshop", &["psd", "psb", "psdt"]),
|
||||
("PhotoCraft", &["pcraft"]),
|
||||
("Affinity", &["af", "afdesign", "afphoto", "afpub"]),
|
||||
("Krita", &["kra", "krz"]),
|
||||
("Amiga IFF", &["iff", "lbm", "ilbm"]),
|
||||
("BMP", &["bmp", "dib"]),
|
||||
("DDS", &["dds"]),
|
||||
("DICOM", &["dcm", "dicom", "dc3"]),
|
||||
("DPX and Cineon", &["dpx", "cin"]),
|
||||
("FITS", &["fits", "fit", "fts"]),
|
||||
("GIF", &["gif"]),
|
||||
("GIMP", &["xcf", "xcfgz", "gz"]),
|
||||
("HEIF", &["heic", "heif", "hif"]),
|
||||
("ICO", &["ico"]),
|
||||
("JPEG", &["jpg", "jpeg"]),
|
||||
("Krita", &["kra", "krz"]),
|
||||
("OpenEXR", &["exr"]),
|
||||
("OpenRaster", &["ora"]),
|
||||
("Paint.NET", &["pdn"]),
|
||||
("SVG", SVG_EXTS),
|
||||
("PCX", &["pcx"]),
|
||||
("PNG", &["png"]),
|
||||
("JPEG", &["jpg", "jpeg"]),
|
||||
("HEIF", &["heic", "heif", "hif"]),
|
||||
("Portable Bitmap", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]),
|
||||
("QOI", &["qoi"]),
|
||||
("Radiance HDR", &["hdr"]),
|
||||
("RAW images", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
|
||||
("SVG", SVG_EXTS),
|
||||
("Targa", &["tga"]),
|
||||
("TIFF", &["tif", "tiff"]),
|
||||
("WebP", &["webp"]),
|
||||
("GIF", &["gif"]),
|
||||
("BMP", &["bmp", "dib"]),
|
||||
("Targa", &["tga"]),
|
||||
("ICO", &["ico"]),
|
||||
("QOI", &["qoi"]),
|
||||
("PCX", &["pcx"]),
|
||||
("DDS", &["dds"]),
|
||||
("XPM", &["xpm"]),
|
||||
("Portable Bitmap", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]),
|
||||
("OpenEXR", &["exr"]),
|
||||
("Radiance HDR", &["hdr"]),
|
||||
("FITS", &["fits", "fit", "fts"]),
|
||||
("DPX and Cineon", &["dpx", "cin"]),
|
||||
("Amiga IFF", &["iff", "lbm", "ilbm"]),
|
||||
("DICOM", &["dcm", "dicom", "dc3"]),
|
||||
("RAW images", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
|
||||
("Brushes", &["abr"]),
|
||||
("Gradients", &["grd"]),
|
||||
("Styles", &["asl"]),
|
||||
@@ -82,35 +83,40 @@ fn open_filters() -> Vec<(&'static str, Vec<String>)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
|
||||
/// extension comes first, so a .pcraft document saves as .pcraft by default and everything else
|
||||
/// keeps defaulting to PSD.
|
||||
/// File › Save As formats: (filter name, extensions). PSD, PSB and PhotoCraft's own format, which
|
||||
/// keep the most of a document, then the rest by name, so a long list stays easy to search. The
|
||||
/// filter matching the suggested name's extension comes first, so a .pcraft document saves as
|
||||
/// .pcraft by default and everything else keeps defaulting to PSD. The PSD type takes `.psb` too:
|
||||
/// Windows adds the selected type's extension to a name whose extension isn't one of the type's,
|
||||
/// so `art.psb` typed under the PSD type would come back as `art.psb.psd`.
|
||||
const SAVE_FILTERS: &[(&str, &[&str])] = &[
|
||||
("PSD Document", &["psd", "psb"]),
|
||||
("PDF", &["pdf"]),
|
||||
("PSB Large Document", &["psb"]),
|
||||
("PhotoCraft", &["pcraft"]),
|
||||
("OpenRaster", &["ora"]),
|
||||
("PNG", &["png"]),
|
||||
("Amiga IFF", &["iff"]),
|
||||
("BMP", &["bmp", "dib"]),
|
||||
("Cineon", &["cin"]),
|
||||
// Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327).
|
||||
("DDS", &["dds"]),
|
||||
("DPX", &["dpx"]),
|
||||
("FITS", &["fits", "fit"]),
|
||||
("GIF", &["gif"]),
|
||||
// BMP and GIF are also in Photoshop's Save As list; ICO is PhotoCraft's own (#4357): up to
|
||||
// 256×256, with alpha.
|
||||
("ICO", &["ico"]),
|
||||
("JPEG", &["jpg", "jpeg"]),
|
||||
("JPEG XL", &["jxl"]),
|
||||
("WebP", &["webp"]),
|
||||
("TIFF", &["tif", "tiff"]),
|
||||
("Targa", &["tga"]),
|
||||
// Also in Photoshop's Save As list; ICO is PhotoCraft's own (#4357): up to 256×256, with alpha.
|
||||
("BMP", &["bmp", "dib"]),
|
||||
("GIF", &["gif"]),
|
||||
("ICO", &["ico"]),
|
||||
("OpenEXR", &["exr"]),
|
||||
// The encoder picks P5, P6, P7 or PFM from the image, not from the name, so only the neutral
|
||||
// .pnm is offered: a .pbm or .pgm name would hold pixmap data (CodeRabbit on #9775).
|
||||
("Netpbm", &["pnm"]),
|
||||
("OpenEXR", &["exr"]),
|
||||
("OpenRaster", &["ora"]),
|
||||
("PDF", &["pdf"]),
|
||||
("PNG", &["png"]),
|
||||
("Radiance HDR", &["hdr"]),
|
||||
("FITS", &["fits", "fit"]),
|
||||
("DPX", &["dpx"]),
|
||||
// Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327).
|
||||
("DDS", &["dds"]),
|
||||
("Cineon", &["cin"]),
|
||||
("Amiga IFF", &["iff"]),
|
||||
("Targa", &["tga"]),
|
||||
("TIFF", &["tif", "tiff"]),
|
||||
("WebP", &["webp"]),
|
||||
];
|
||||
|
||||
/// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog
|
||||
@@ -136,10 +142,14 @@ fn save_filters(suggested: &str) -> Vec<(String, Vec<String>)> {
|
||||
return vec![(name.to_string(), exts.iter().map(|e| e.to_string()).collect())];
|
||||
}
|
||||
let mut v: Vec<(String, Vec<String>)> = SAVE_FILTERS.iter().map(|(name, exts)| (name.to_string(), exts.iter().map(|e| e.to_string()).collect())).collect();
|
||||
match v.iter().position(|(_, exts)| exts.contains(&ext)) {
|
||||
// The type the extension is first for (`.psb` starts on PSB, not on PSD's second extension),
|
||||
// else any type that lists it.
|
||||
let own = v.iter().position(|(_, exts)| exts.first() == Some(&ext));
|
||||
match own.or_else(|| v.iter().position(|(_, exts)| exts.contains(&ext))) {
|
||||
Some(i) => {
|
||||
let (name, mut exts) = v.remove(i);
|
||||
// Windows adds the first type's first extension to a bare name: `.psb`, not `.psd`.
|
||||
// Windows adds the first type's first extension to a bare name: `cat.jpeg` stays
|
||||
// `.jpeg`, and `sky.fit` stays `.fit`.
|
||||
exts.retain(|e| *e != ext);
|
||||
exts.insert(0, ext);
|
||||
v.insert(0, (name, exts));
|
||||
@@ -156,13 +166,26 @@ fn save_filters(suggested: &str) -> Vec<(String, Vec<String>)> {
|
||||
/// dialog opened with (`opened_with`, `Untitled-1.psd` with PNG picked) or none gets the type's
|
||||
/// extension, as PolyMeilex/rfd#341 does. An extension the user typed that PhotoCraft saves
|
||||
/// (`art.png` with the PSD type untouched, the way to save a PNG before this) is theirs and stays,
|
||||
/// and so does one of the type's own (`.psb` for PSD). One PhotoCraft doesn't save (`scan.2024`)
|
||||
/// is part of the name, and the type's extension is added after it.
|
||||
/// and so does one of the type's own. One PhotoCraft doesn't save (`scan.2024`)
|
||||
/// is part of the name, and the type's extension is added after it. The exception: two of the
|
||||
/// type's own extensions (`art.psb.psd` under the PSD type) lose the last, since KDE's dialog adds
|
||||
/// it after a typed one; the returned name can't tell that from a typed `art.psb.psd`, which is
|
||||
/// rare, so that one is saved as `art.psb` too.
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
pub(crate) fn with_chosen_type(path: &Path, opened_with: Option<&str>, chosen: &[String]) -> PathBuf {
|
||||
let Some(first) = chosen.first() else { return path.to_path_buf() };
|
||||
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
let opened_ext = opened_with.and_then(|n| Path::new(n).extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
// A name that already had one of the type's extensions, with the type's first one added after
|
||||
// it (KDE's dialog does that: `art.psb` typed under the PSD type came back as `art.psb.psd`).
|
||||
let inner = path.file_stem().map(Path::new).and_then(|s| s.extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
if let (Some(ext), Some(inner)) = (&ext, &inner)
|
||||
&& ext != inner
|
||||
&& chosen.contains(ext)
|
||||
&& chosen.contains(inner)
|
||||
{
|
||||
return path.with_extension("");
|
||||
}
|
||||
match ext {
|
||||
Some(ext) if chosen.contains(&ext) => path.to_path_buf(),
|
||||
Some(ext) if opened_ext.as_ref() == Some(&ext) => path.with_extension(first),
|
||||
|
||||
@@ -969,3 +969,40 @@ fn tiff_options_reach_the_written_file() {
|
||||
assert_eq!(info.pages.iter().map(|p| (p.width, p.compression)).collect::<Vec<_>>(), [(200, 5), (100, 5), (50, 5)]);
|
||||
assert!(!photocraft_codecs::decode(&bytes).unwrap().layout().has_alpha());
|
||||
}
|
||||
|
||||
/// PSB is a save type of its own: it shows in the list, and the type gives a typed name its
|
||||
/// extension. As an extension of the PSD type it was hidden, and KDE's dialog, which adds the
|
||||
/// type's first extension, turned `art.psb` into `art.psb.psd`.
|
||||
#[test]
|
||||
fn psb_is_its_own_save_type() {
|
||||
let filters = save_filters("Untitled-1.psd");
|
||||
let (psd, psb) = (&filters[0], &filters[1]);
|
||||
// The PSD type takes a typed .psb too, so Windows doesn't add .psd after it.
|
||||
assert_eq!(psd.1, vec!["psd".to_string(), "psb".to_string()], "{psd:?}");
|
||||
assert_eq!(psb.1, vec!["psb".to_string()], "{psb:?}");
|
||||
let big = save_filters("big.psb");
|
||||
assert_eq!((big[0].0.as_str(), big[0].1.clone()), ("PSB Large Document", vec!["psb".to_string()]), "a .psb starts on its own type");
|
||||
let chosen = |f: &(String, Vec<String>)| with_chosen_type(Path::new("/pics/art"), Some("art.psd"), &f.1);
|
||||
assert_eq!(chosen(psd), PathBuf::from("/pics/art.psd"));
|
||||
assert_eq!(chosen(psb), PathBuf::from("/pics/art.psb"));
|
||||
let opened = Some("Untitled-1");
|
||||
assert_eq!(with_chosen_type(Path::new("/pics/art.psb"), opened, &psd.1), PathBuf::from("/pics/art.psb"), "a typed .psb stays");
|
||||
// KDE adds the type's first extension after a typed one of its own: that one is taken back,
|
||||
// also from an `art.psb.psd` typed in full (the dialog's answer is the same string).
|
||||
assert_eq!(with_chosen_type(Path::new("/pics/art.psb.psd"), opened, &psd.1), PathBuf::from("/pics/art.psb"), "KDE's art.psb.psd");
|
||||
// A dot that's part of the name stays (.jpg isn't one of the PSD type's).
|
||||
assert_eq!(with_chosen_type(Path::new("/pics/scan.jpg.psd"), opened, &psd.1), PathBuf::from("/pics/scan.jpg.psd"));
|
||||
}
|
||||
|
||||
/// The document formats, then the rest by name, so a long list stays easy to search.
|
||||
#[test]
|
||||
fn save_types_list_the_document_formats_then_the_rest_by_name() {
|
||||
let names: Vec<&str> = SAVE_FILTERS.iter().map(|(name, _)| *name).collect();
|
||||
assert_eq!(names[..3], ["PSD Document", "PSB Large Document", "PhotoCraft"]);
|
||||
let key = |name: &&str| name.to_ascii_lowercase();
|
||||
assert!(names[3..].is_sorted_by_key(key), "{:?}", &names[3..]);
|
||||
let names: Vec<&str> = OPEN_FILTERS.iter().map(|(name, _)| *name).collect();
|
||||
assert_eq!(names[..2], ["Photoshop", "PhotoCraft"]);
|
||||
let formats = names.iter().position(|name| *name == "Brushes").expect("the app's own resources");
|
||||
assert!(names[2..formats].is_sorted_by_key(key), "{:?}", &names[2..formats]);
|
||||
}
|
||||
@@ -92,6 +92,17 @@ pub fn right_button_service() -> Option<photocraft_ui_egui::RightButtonDownFn> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Where the pen is on the screen (Windows), for the title bar's pen moves (#7967).
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn pen_screen_service() -> Option<photocraft_ui_egui::PenScreenFn> {
|
||||
Some(Box::new(|| photocraft_tablet::windows::pen_screen_px().map(|(x, y)| [x, y])))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
pub fn pen_screen_service() -> Option<photocraft_ui_egui::PenScreenFn> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Which end of the pen is in use (Windows): flipping the pen to its eraser end selects the
|
||||
/// Eraser (#2285). Elsewhere the end arrives with the samples in the stylus feed.
|
||||
#[cfg(target_os = "windows")]
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
|
||||
<path d="M8 6H16 M18 8V16 M16 18H8 M6 16V8"/>
|
||||
<rect x="4" y="4" width="4" height="4"/>
|
||||
<rect x="16" y="4" width="4" height="4"/>
|
||||
<rect x="4" y="16" width="4" height="4"/>
|
||||
<rect x="16" y="16" width="4" height="4"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 368 B |
@@ -1,6 +1,6 @@
|
||||
# Control protocol
|
||||
|
||||
The desktop control protocol is newline-delimited JSON over a TCP listener bound to `127.0.0.1`. The first frame on every connection must be `auth` with the configured 256-bit bearer token. After authentication, each request carries `id`, `method`, and optional `params`; each reply includes the matching `id` and either a result or error.
|
||||
The desktop control protocol is newline-delimited JSON over a TCP listener bound to `127.0.0.1`. Every connection must first authenticate with the configured 256-bit token: either by challenge (`auth.challenge`, then `auth` with an HMAC proof; the token never crosses the wire and the server proves it holds the token first), or with the original single `auth` frame carrying the token. After authentication, each request carries `id`, `method`, and optional `params`; each reply includes the matching `id` and either a result or error.
|
||||
|
||||
```json
|
||||
{"id":"auth","method":"auth","params":{"token":"<64-hex>"}}
|
||||
|
||||
@@ -11,6 +11,7 @@ Automation requests are untrusted input with potential effects beyond the active
|
||||
| MCP capability scopes | **Partial:** filesystem read/write capabilities only; general tool scopes are absent |
|
||||
| Allowed read/write roots | **Implemented:** separate launch-time roots, with absent authority failing closed |
|
||||
| Symlink-safe capability filesystem | **Implemented:** relative operations use held directory capabilities and reject link escapes |
|
||||
| Windows UNC write roots | **Implemented:** handle-relative deletes; two ambient operations on the canonical root path (`create_dir`, `rename`), each below ancestors pinned by held handles; see below |
|
||||
| Request-byte and JSON-depth limits | **Partial:** 1 MiB request-line limit on TCP and headless JSON-lines stdio (MCP stdio input is not byte-capped); no explicit JSON-depth policy |
|
||||
| Batch-step limit | **Implemented:** 256 steps for headless and MCP batches |
|
||||
| Reply-size limit | **Implemented:** 8 MiB encoded JSON/MCP result; aggregate batch reply budget |
|
||||
@@ -41,3 +42,33 @@ Filesystem handles and a defensive command-path policy are implemented; explicit
|
||||
capabilities, session-memory/command-duration budgets, and audit events remain. Preview and
|
||||
reply ceilings do not bound all document operations or desktop screenshot capture. Private token handling, process
|
||||
isolation, and least-privileged execution are still practical containment measures.
|
||||
|
||||
## Windows UNC write roots
|
||||
|
||||
`cap-std` 4's Windows `rename`, `remove_file` and `create_dir` are not handle-relative: they
|
||||
append the request to the handle's own path, read back without its `\\?\` prefix, which below a
|
||||
UNC root (`\\wsl.localhost\...`, any network share) fails with `ERROR_PATH_NOT_FOUND`
|
||||
(sunfishcode/cap-std#348). Below such a root, judged by the canonical root path's prefix and
|
||||
never by a request, the automation workspace keeps every rule above and completes these steps
|
||||
as follows:
|
||||
|
||||
- **Deletes** (a stranded temporary file, the frames of a cancelled export) open the file
|
||||
relative to the held directory handle with `FILE_FLAG_DELETE_ON_CLOSE` and
|
||||
`FILE_FLAG_OPEN_REPARSE_POINT`, so a link is deleted rather than its target. Nothing is deleted
|
||||
by path.
|
||||
- **Directory creation** and the **rename of a finished temporary file into place** are the only
|
||||
two operations that touch the filesystem by path. Both run on the canonical verbatim root path
|
||||
(trusted launch configuration) only after every directory component on the way has been
|
||||
opened through the handle of its parent, verified a plain directory (not a link, not a file),
|
||||
and kept open. `cap-std` opens directories without `FILE_SHARE_DELETE`. This protects held
|
||||
ancestors from Windows-side rename or deletion only when the provider enforces share modes
|
||||
(`ERROR_SHARING_VIOLATION`). It does not protect against direct Linux-side changes in WSL. The
|
||||
UNC regression test uses an SMB administrative share, not `\\wsl.localhost`.
|
||||
The rename replaces the entry at the target without following it;
|
||||
a directory at the target is refused.
|
||||
|
||||
Saves below a UNC root are therefore as atomic as everywhere else (temporary file, flush,
|
||||
rename). No file contents are written or read through an ambient path; directory creation and
|
||||
rename use ambient paths. Regression tests
|
||||
run against the loopback administrative share of the test drive and are skipped where none is
|
||||
available.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Raster formats
|
||||
|
||||
`photocraft-codecs` provides format detection, capability declarations, decode limits, metadata handling, and encoding for flat images. The default build declares read/write support for PNG, JPEG, TIFF, WebP, GIF, BMP, TGA, ICO, Netpbm/PFM, QOI, OpenEXR, and Radiance HDR. HEIF/HEIC (iPhone and Mac photos) is read-only, decoded in pure Rust by `heic-rs` through the optional `photocraft-heif` crate. It is a build-time choice behind the `heif` cargo feature (`cargo build -p photocraft --features heif`): official builds include it; without it HEIC files are still recognised and opening one reports that HEIC support isn't included in that build. AVIF encoding is optional; AVIF decoding is not implemented in the current crate. Lossless JPEG XL (.jxl) export uses the pure-Rust `zune-jpegxl` encoder for 8/16-bit gray, RGB and RGBA data; gray+alpha is expanded to RGBA at the same bit depth. JPEG XL import is tracked separately in #2868.
|
||||
`photocraft-codecs` provides format detection, capability declarations, decode limits, metadata handling, and encoding for flat images. The default build declares read/write support for PNG, JPEG, TIFF, WebP, GIF, BMP, TGA, ICO, Netpbm/PFM, QOI, OpenEXR, and Radiance HDR. HEIF/HEIC (iPhone and Mac photos) is read-only, decoded in pure Rust by `heic-rs` through the optional `craft-heif` (craft-libs) crate. It is a build-time choice behind the `heif` cargo feature (`cargo build -p photocraft --features heif`): official builds include it; without it HEIC files are still recognised and opening one reports that HEIC support isn't included in that build. AVIF encoding is optional; AVIF decoding is not implemented in the current crate. Lossless JPEG XL (.jxl) export uses the pure-Rust `zune-jpegxl` encoder for 8/16-bit gray, RGB and RGBA data; gray+alpha is expanded to RGBA at the same bit depth. JPEG XL import is tracked separately in #2868.
|
||||
|
||||
## Layered TIFF
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
# To remove your names, delete your entry (or set fields empty) in a PR. The next
|
||||
# contributors.py run, and the next build, drop them.
|
||||
|
||||
[people.chrisringrose]
|
||||
sync_github_name = true
|
||||
|
||||
[people.brianblakely]
|
||||
sync_github_name = true
|
||||
|
||||
@@ -29,6 +32,9 @@ sync_github_name = false
|
||||
display_name = "Skyfuller"
|
||||
sync_github_name = true
|
||||
|
||||
[people.JohnXu28]
|
||||
display_name = "JohnXu"
|
||||
|
||||
[people.AlanRockefeller]
|
||||
sync_github_name = true
|
||||
|
||||
@@ -270,6 +276,10 @@ sync_github_name = false
|
||||
[people.drunkeninja42]
|
||||
real_name = "Kushagra Sharma"
|
||||
|
||||
[people.Terra854]
|
||||
display_name = "Terra854"
|
||||
sync_github_name = true
|
||||
|
||||
[people.hidoba]
|
||||
real_name = "Vlad Grankovsky"
|
||||
display_name = "Vlad Grankovsky"
|
||||
@@ -329,3 +339,7 @@ sync_github_name = false
|
||||
[people.tomgardenart]
|
||||
display_name = "Nostella"
|
||||
sync_github_name = false
|
||||
|
||||
[people.se343r]
|
||||
display_name = "Tsieg"
|
||||
sync_github_name = true
|
||||
@@ -0,0 +1 @@
|
||||
e02939ef009218e81c44e8ec001fbb7603461de4
|
||||
@@ -294,6 +294,9 @@ const MAX_NAME_BYTES: usize = 64 << 20;
|
||||
const MAX_PAGES: usize = 1 << 18;
|
||||
/// Bytes of font names the text runs may retain across the document.
|
||||
const MAX_FONT_NAME_BYTES: usize = 16 << 20;
|
||||
/// Text work units (block and run slots traversed, bytes of story text retained) across all
|
||||
/// text nodes of a document; real documents use a tiny fraction.
|
||||
const MAX_TEXT_WORK: usize = 64 << 20;
|
||||
|
||||
/// Read a document: archive, `doc.dat` and the model.
|
||||
pub fn read(bytes: &[u8], limits: Limits) -> Result<Document, Error> {
|
||||
@@ -316,6 +319,7 @@ pub(crate) struct Reader<'s, 'a, 'b> {
|
||||
name_bytes: usize,
|
||||
pages: usize,
|
||||
font_name_bytes: usize,
|
||||
text_work: usize,
|
||||
active: HashSet<ObjId>,
|
||||
pub(crate) geometry_budget: crate::geometry::Budget,
|
||||
/// Decoded pixels still available ([`Limits::max_pixel_bytes`] less what the layers read so
|
||||
@@ -335,6 +339,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
name_bytes: 0,
|
||||
pages: 0,
|
||||
font_name_bytes: 0,
|
||||
text_work: 0,
|
||||
active: HashSet::new(),
|
||||
geometry_budget: crate::geometry::Budget::default(),
|
||||
pixels_left: limits.max_pixel_bytes,
|
||||
@@ -652,6 +657,12 @@ impl Reader<'_, '_, '_> {
|
||||
self.font_name_bytes <= MAX_FONT_NAME_BYTES
|
||||
}
|
||||
|
||||
/// Counts text traversal work and retained text bytes against [`MAX_TEXT_WORK`]; false once it is spent.
|
||||
pub(crate) fn charge_text(&mut self, n: usize) -> bool {
|
||||
self.text_work = self.text_work.saturating_add(n);
|
||||
self.text_work <= MAX_TEXT_WORK
|
||||
}
|
||||
|
||||
/// Counts retained page rectangles against [`MAX_PAGES`].
|
||||
fn charge_pages(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.pages = self.pages.saturating_add(n);
|
||||
|
||||
@@ -496,6 +496,61 @@ mod shapes {
|
||||
assert!(t.frame.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_story_placed_many_times_is_charged_against_the_text_budget() {
|
||||
// One ~1 MiB story referenced 100 times would retain ~100 MiB of text without a budget.
|
||||
let glyphs = F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("a".repeat((1 << 20) - 1)))]);
|
||||
let run = F::Obj(tag(b"Item"), vec![]);
|
||||
let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(1 << 20)), (tag(b"Item"), run)]]))]);
|
||||
let block = vec![(tag(b"Glyp"), glyphs), (tag(b"GAtt"), attributes)];
|
||||
let text = F::Def(
|
||||
100,
|
||||
vec![tag(b"TxtA")],
|
||||
vec![
|
||||
(tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])),
|
||||
(tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![block]))])),
|
||||
],
|
||||
);
|
||||
let group = F::Def(101, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared((0..100).map(|_| F::Ref(100)).collect()))]);
|
||||
let d = read(vec![text, group], 101);
|
||||
assert!(d.warnings.iter().any(|w| w.contains("document text budget")), "{:?}", d.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_past_the_character_limit_is_not_charged_so_a_later_text_node_survives() {
|
||||
// 64 references to one segment of 1 MiB + 1 characters: only the first is scanned (the
|
||||
// block is cut at the character limit), so only that scan is charged to the text budget.
|
||||
let frame = || (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))]));
|
||||
let segment = F::Def(200, vec![tag(b"Segm")], vec![(tag(b"Utf8"), F::Str("a".repeat((1 << 20) + 1)))]);
|
||||
let mut refs = vec![segment];
|
||||
refs.extend((0..63).map(|_| F::Ref(200)));
|
||||
let big_block = vec![(tag(b"Glyp"), F::Obj(tag(b"Glyp"), vec![(tag(b"Mixd"), F::Shared(refs))]))];
|
||||
let big =
|
||||
F::Def(100, vec![tag(b"TxtA")], vec![frame(), (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![big_block]))]))]);
|
||||
let run = F::Obj(tag(b"Item"), vec![]);
|
||||
let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(2)), (tag(b"Item"), run)]]))]);
|
||||
let small_block = vec![(tag(b"Glyp"), F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("ok".into()))])), (tag(b"GAtt"), attributes)];
|
||||
let small = F::Def(
|
||||
101,
|
||||
vec![tag(b"TxtA")],
|
||||
vec![frame(), (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![small_block]))]))],
|
||||
);
|
||||
let group = F::Def(102, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared(vec![F::Ref(100), F::Ref(101)]))]);
|
||||
let d = read(vec![big, small, group], 102);
|
||||
assert!(!d.warnings.iter().any(|w| w.contains("document text budget")), "{:?}", d.warnings);
|
||||
fn collect(nodes: &[crate::model::Node], out: &mut Vec<String>) {
|
||||
for n in nodes {
|
||||
if let Kind::Text(t) = &n.kind {
|
||||
out.push(t.runs.iter().map(|r| r.text.as_str()).collect());
|
||||
}
|
||||
collect(&n.children, out);
|
||||
}
|
||||
}
|
||||
let mut texts = Vec::new();
|
||||
collect(&d.spreads[0].nodes, &mut texts);
|
||||
assert!(texts.iter().any(|t| t == "ok"), "{texts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pie_angles_with_huge_finite_values_do_not_loop_or_emit_nonfinite_points() {
|
||||
let document = read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(1.0e308)), (tag(b"AngE"), F::F64(-1.0e308))])], 100);
|
||||
|
||||
@@ -19,14 +19,47 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
|
||||
let mut align = None;
|
||||
let mut total = 0usize;
|
||||
let mut placeholders = false;
|
||||
for block in s.objs(story, b"Blok") {
|
||||
// Shared structures are traversed once per occurrence: charge the raw slots (nulls and empty
|
||||
// blocks included) before collecting them, against a document-wide budget.
|
||||
if !r.charge_text(s.array_len(story, b"Blok").unwrap_or(0)) {
|
||||
r.warn("text beyond the document text budget (left out)");
|
||||
return None;
|
||||
}
|
||||
'blocks: for block in s.objs(story, b"Blok") {
|
||||
let glyphs = s.obj(block, b"Glyp")?;
|
||||
let runs_n = s.obj(block, b"GAtt").and_then(|g| s.array_len(g, b"Runs")).unwrap_or(0);
|
||||
if !r.charge_text(1 + runs_n + s.array_len(glyphs, b"Mixd").unwrap_or(0)) {
|
||||
r.warn("text beyond the document text budget (truncated)");
|
||||
break;
|
||||
}
|
||||
// Applied to `align` only once this block passes the character limit below, so a discarded
|
||||
// block does not set the alignment of the text kept from earlier blocks.
|
||||
// Scanning the paragraph runs (null slots included) is charged before it is done.
|
||||
let mut block_align = None;
|
||||
if align.is_none()
|
||||
&& let Some(p) = s.obj(block, b"PAtt")
|
||||
{
|
||||
if r.charge_text(s.array_len(p, b"Runs").unwrap_or(0)) {
|
||||
block_align = s.objs(p, b"Runs").first().copied().and_then(|run| s.obj(run, b"Item")).map(|p| paragraph_align(r, p));
|
||||
} else {
|
||||
r.warn("text beyond the document text budget (paragraph alignment left out)");
|
||||
}
|
||||
}
|
||||
// `block_chars` scans the `Utf8` string, or walks each segment's `Glys` slots (nulls included) and `Utf8` text, and stops at the character limit: charge only that scan, first.
|
||||
let slots = scan_cost(s, glyphs, room(total));
|
||||
if !r.charge_text(slots) {
|
||||
r.warn("text beyond the document text budget (truncated)");
|
||||
break;
|
||||
}
|
||||
let chars = block_chars(s, glyphs, total, &mut placeholders);
|
||||
total = total.checked_add(chars.len())?;
|
||||
if total > MAX_CHARS {
|
||||
r.warn("text longer than a million characters (truncated)");
|
||||
break;
|
||||
}
|
||||
if align.is_none() {
|
||||
align = block_align;
|
||||
}
|
||||
let mut start = 0usize;
|
||||
for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
|
||||
let end = usize::try_from(s.int(run, b"Indx")?).ok()?.min(chars.len());
|
||||
@@ -37,12 +70,13 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
|
||||
start = end;
|
||||
let Some(attrs) = s.obj(run, b"Item") else { continue };
|
||||
if !text.is_empty() {
|
||||
if !r.charge_text(text.len()) {
|
||||
r.warn("text beyond the document text budget (truncated)");
|
||||
break 'blocks;
|
||||
}
|
||||
runs.push(run_attrs(r, attrs, text, world));
|
||||
}
|
||||
}
|
||||
if align.is_none() {
|
||||
align = s.obj(block, b"PAtt").and_then(|p| s.objs(p, b"Runs").first().copied()).and_then(|run| s.obj(run, b"Item")).map(|p| paragraph_align(r, p));
|
||||
}
|
||||
}
|
||||
if placeholders {
|
||||
r.warn("text fields such as page numbers (left out of the text)");
|
||||
@@ -65,12 +99,43 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
|
||||
Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world })
|
||||
}
|
||||
|
||||
/// One past the allowance is enough to trip the check in `read`; `block_chars` stops there.
|
||||
fn room(total: usize) -> usize {
|
||||
MAX_CHARS.saturating_sub(total).saturating_add(1)
|
||||
}
|
||||
|
||||
/// The bytes of `t` that holding `want` characters of it scans, and the characters taken.
|
||||
fn prefix(t: &str, want: usize) -> (usize, usize) {
|
||||
t.char_indices().enumerate().find(|(n, _)| *n == want).map_or((t.len(), t.chars().count()), |(n, (i, _))| (i, n))
|
||||
}
|
||||
|
||||
/// What `block_chars` scans for a block, in the units `charge_text` takes: the `Utf8` bytes it
|
||||
/// reads, or per segment its `Glys` slots (nulls included) and the `Utf8` bytes it reads, up to the
|
||||
/// character allowance `room`; text past it is never scanned, so it is not charged.
|
||||
fn scan_cost(s: &Stream, glyphs: ObjId, room: usize) -> usize {
|
||||
if let Some(t) = s.str(glyphs, b"Utf8") {
|
||||
return prefix(t, room).0;
|
||||
}
|
||||
let (mut len, mut cost) = (0usize, 0usize);
|
||||
for seg in s.objs(glyphs, b"Mixd") {
|
||||
if len >= room {
|
||||
break;
|
||||
}
|
||||
let inline = s.objs(seg, b"Glys").len();
|
||||
len += inline.min(room - len);
|
||||
cost = cost.saturating_add(s.array_len(seg, b"Glys").unwrap_or(0));
|
||||
let (bytes, chars) = prefix(s.str(seg, b"Utf8").unwrap_or_default(), room.saturating_sub(len));
|
||||
len += chars;
|
||||
cost = cost.saturating_add(bytes);
|
||||
}
|
||||
cost
|
||||
}
|
||||
|
||||
/// The characters of one text block. A block without a UTF-8 string is a list of segments: each
|
||||
/// inline object (page number, anchor) takes one `U+FFFC` before its segment's text. Stops once
|
||||
/// `total` plus these characters would pass the cap.
|
||||
fn block_chars(s: &Stream, glyphs: ObjId, total: usize, placeholders: &mut bool) -> Vec<char> {
|
||||
// One past the allowance is enough to trip the check in `read`; both arms stop there.
|
||||
let room = MAX_CHARS.saturating_sub(total).saturating_add(1);
|
||||
let room = room(total);
|
||||
match s.str(glyphs, b"Utf8") {
|
||||
Some(t) => t.chars().take(room).collect(),
|
||||
None => {
|
||||
|
||||
@@ -12,6 +12,10 @@ use photocraft_color::PixelFormat;
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
/// Rows per band when hashing an output region: the hash sequence must match hashing the whole
|
||||
/// region, so bands walk `y` in order, but the buffer stays a few MB instead of the layer's 384 MB.
|
||||
const HASH_BAND_ROWS: usize = 64;
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||
let flag = |k: &str| a.iter().position(|v| v == k);
|
||||
@@ -95,6 +99,21 @@ fn main() {
|
||||
let out = apply(&s, &p, area, r, None);
|
||||
let ms = t.elapsed().as_secs_f64() * 1e3;
|
||||
samples.push(ms);
|
||||
// FNV-1a 64 over the output's raw f32 bytes, in row order: "same pixels" as a
|
||||
// comparison, not a promise. Hashing byte bands of rows keeps the sequence identical
|
||||
// to hashing the whole region while holding a few MB instead of the layer's 384 MB.
|
||||
let mut hash = 0xcbf29ce484222325u64;
|
||||
let mut buf = Vec::new();
|
||||
for y in (r.y0..r.y1).step_by(HASH_BAND_ROWS) {
|
||||
let band = Rect::new(r.x0, y, r.x1, (y + HASH_BAND_ROWS as i32).min(r.y1));
|
||||
out.read_region_into(band, &mut buf);
|
||||
for v in &buf {
|
||||
for byte in v.to_bits().to_le_bytes() {
|
||||
hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("HASH {name} {hash:016x}");
|
||||
drop(out);
|
||||
}
|
||||
let mut sorted = samples.clone();
|
||||
|
||||
@@ -333,10 +333,12 @@ struct SrcView<'a> {
|
||||
h: usize,
|
||||
origin: (i32, i32),
|
||||
ch: usize,
|
||||
alpha: Option<usize>,
|
||||
}
|
||||
|
||||
fn sample_bilinear(src: SrcView<'_>, sx: f32, sy: f32, out: &mut [f32]) -> bool {
|
||||
let ch = src.ch;
|
||||
let alpha = src.alpha.filter(|&a| a < ch);
|
||||
if ch == 0 || out.len() < ch {
|
||||
return false;
|
||||
}
|
||||
@@ -370,12 +372,19 @@ fn sample_bilinear(src: SrcView<'_>, sx: f32, sy: f32, out: &mut [f32]) -> bool
|
||||
let (Ok(ux), Ok(uy)) = (usize::try_from(px), usize::try_from(py)) else { continue };
|
||||
let Some(base) = pixel_index(ux, uy, src.w, src.h, ch) else { continue };
|
||||
let Some(pxs) = src.data.get(base..base.saturating_add(ch)) else { continue };
|
||||
for (d, s) in dst.iter_mut().zip(pxs.iter()) {
|
||||
*d += *s * wt;
|
||||
let coverage = alpha.and_then(|a| pxs.get(a)).copied().unwrap_or(1.0);
|
||||
for (c, (d, s)) in dst.iter_mut().zip(pxs.iter()).enumerate() {
|
||||
*d += *s * wt * if alpha.is_some_and(|a| c < a) { coverage } else { 1.0 };
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
if let Some(a) = alpha {
|
||||
let coverage = dst.get(a).copied().unwrap_or(0.0);
|
||||
for value in dst.iter_mut().take(a) {
|
||||
*value = if coverage > 0.0 { *value / coverage } else { 0.0 };
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
@@ -535,7 +544,11 @@ fn stamp_dab_on_rect(p: &mut StampParams<'_>, dab: &Dab, rect: (i32, i32, i32, i
|
||||
continue;
|
||||
}
|
||||
let (sx, sy) = rotated_source(dab, x, y);
|
||||
if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch }, sx, sy, &mut sampled) {
|
||||
if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch, alpha: p.alpha }, sx, sy, &mut sampled) {
|
||||
continue;
|
||||
}
|
||||
// Stamping a fully transparent sample leaves the pixel as it is.
|
||||
if p.alpha.is_some_and(|a| sampled.get(a).is_some_and(|&v| v == 0.0)) {
|
||||
continue;
|
||||
}
|
||||
let Some(li) = pixel_index(lx, ly, tw, th, p.ch) else { continue };
|
||||
@@ -571,12 +584,14 @@ fn dab_intersects(dab: &Dab, tile: (i32, i32, i32, i32)) -> bool {
|
||||
/// Mean difference between `src` and `dest` over the dab's covered pixels (working-space peak is
|
||||
/// 1, so a tolerance of 50% is `0.5`). Per pixel it is the larger of the mean colour change and the
|
||||
/// alpha change: an opaque pixel's unchanged alpha must not water a colour change down, and the
|
||||
/// Eraser keeps the colour and lowers only the alpha. `None` if nothing is covered.
|
||||
/// Eraser keeps the colour and lowers only the alpha. Fully transparent source samples are left
|
||||
/// out; a dab whose samples are all transparent has a mean of `0.0`. `None` if nothing is covered.
|
||||
fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option<f32> {
|
||||
let (x0, y0, x1, y1) = dab_bounds(dab)?;
|
||||
let mut sampled = vec![0.0f32; p.ch];
|
||||
let mut sum = 0.0f32;
|
||||
let mut count = 0u32;
|
||||
let mut transparent = 0u32;
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
if coverage_at(dab, x, y, p.hardness) <= 0.0 {
|
||||
@@ -585,13 +600,17 @@ fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option<f32> {
|
||||
let Some(di) = origin_index(p.dest_origin, x, y, p.dest_w, p.dest_h, p.ch) else { continue };
|
||||
let Some(dst) = p.dest.get(di..di.saturating_add(p.ch)) else { continue };
|
||||
let (sx, sy) = rotated_source(dab, x, y);
|
||||
if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch }, sx, sy, &mut sampled) {
|
||||
if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch, alpha: p.alpha }, sx, sy, &mut sampled) {
|
||||
continue;
|
||||
}
|
||||
let nch = p.ch.min(dst.len()).min(sampled.len());
|
||||
if nch == 0 {
|
||||
continue;
|
||||
}
|
||||
if p.alpha.is_some_and(|a| sampled.get(a).is_some_and(|&v| v == 0.0)) {
|
||||
transparent = transparent.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
let (mut colour, mut colours, mut alpha) = (0.0f32, 0u32, 0.0f32);
|
||||
for i in 0..nch {
|
||||
let Some((&s, &d)) = sampled.get(i).zip(dst.get(i)) else { continue };
|
||||
@@ -608,7 +627,8 @@ fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option<f32> {
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return None;
|
||||
// Stamping a fully transparent sample leaves the pixel as it is.
|
||||
return (transparent > 0).then_some(0.0);
|
||||
}
|
||||
let mean = sum / count as f32;
|
||||
mean.is_finite().then_some(mean)
|
||||
|
||||
@@ -1,5 +1,148 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tolerance_ignores_fully_transparent_samples() {
|
||||
for ch in [2, 4, 5] {
|
||||
for hidden in [1.0, 0.0] {
|
||||
let src = fill(2, 1, ch, |x, _, c| {
|
||||
if c + 1 == ch {
|
||||
if x == 0 { 1.0 } else { 0.0 }
|
||||
} else if x == 0 {
|
||||
0.4
|
||||
} else {
|
||||
hidden
|
||||
}
|
||||
});
|
||||
let before = fill(2, 1, ch, |x, _, c| {
|
||||
if c + 1 == ch {
|
||||
if x == 0 { 1.0 } else { 0.0 }
|
||||
} else if x == 0 {
|
||||
0.0
|
||||
} else {
|
||||
hidden
|
||||
}
|
||||
});
|
||||
let dab = Dab { x: 1.0, y: 0.5, theta: 0.0, radius: 2.0, pressure: 1.0 };
|
||||
for tolerance in [0.6, 0.3] {
|
||||
let mut dest = before.clone();
|
||||
let written = stamp(&mut StampParams {
|
||||
dest: &mut dest,
|
||||
dest_w: 2,
|
||||
dest_h: 1,
|
||||
dest_origin: (0, 0),
|
||||
src: &src,
|
||||
src_w: 2,
|
||||
src_h: 1,
|
||||
src_origin: (0, 0),
|
||||
ch,
|
||||
dabs: std::slice::from_ref(&dab),
|
||||
hardness: 1.0,
|
||||
opacity: 1.0,
|
||||
flow: 1.0,
|
||||
tolerance,
|
||||
tile: 0,
|
||||
selection: None,
|
||||
lock_transparent: false,
|
||||
alpha: Some(ch - 1),
|
||||
})
|
||||
.unwrap();
|
||||
if tolerance == 0.6 {
|
||||
assert_eq!(written, 0, "channels={ch}, hidden={hidden}");
|
||||
assert_eq!(dest, before);
|
||||
} else {
|
||||
assert!(written > 0, "channels={ch}, hidden={hidden}");
|
||||
assert!((dest[0] - 0.4).abs() < 1e-6);
|
||||
assert_eq!(&dest[ch..], &before[ch..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tolerance_skips_a_dab_whose_source_is_fully_transparent() {
|
||||
for ch in [2, 4, 5] {
|
||||
for opaque in [1.0, 0.0] {
|
||||
let (w, h) = (4, 4);
|
||||
let src = vec![0.0; w * h * ch];
|
||||
let before = fill(w, h, ch, |_, _, c| if c + 1 == ch { opaque } else { 0.5 });
|
||||
let mut dest = before.clone();
|
||||
let dab = Dab { x: 2.0, y: 2.0, theta: 0.0, radius: 2.0, pressure: 1.0 };
|
||||
let written = stamp(&mut StampParams {
|
||||
dest: &mut dest,
|
||||
dest_w: w,
|
||||
dest_h: h,
|
||||
dest_origin: (0, 0),
|
||||
src: &src,
|
||||
src_w: w,
|
||||
src_h: h,
|
||||
src_origin: (0, 0),
|
||||
ch,
|
||||
dabs: std::slice::from_ref(&dab),
|
||||
hardness: 1.0,
|
||||
opacity: 1.0,
|
||||
flow: 1.0,
|
||||
tolerance: 0.1,
|
||||
tile: 0,
|
||||
selection: None,
|
||||
lock_transparent: false,
|
||||
alpha: Some(ch - 1),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(written, 0, "channels={ch}, opaque={opaque}");
|
||||
assert_eq!(dest, before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_tolerance_does_not_write_fully_transparent_samples() {
|
||||
for ch in [2, 4, 5] {
|
||||
for opaque in [1.0, 0.0] {
|
||||
let (w, h) = (4, 4);
|
||||
let src = vec![0.0; w * h * ch];
|
||||
let before = fill(w, h, ch, |_, _, c| if c + 1 == ch { opaque } else { 0.5 });
|
||||
let mut dest = before.clone();
|
||||
let dab = Dab { x: 2.0, y: 2.0, theta: 0.0, radius: 2.0, pressure: 1.0 };
|
||||
let written = stamp_run(w, h, ch, &src, &mut dest, &dab, 0);
|
||||
assert_eq!(written, 0, "channels={ch}, opaque={opaque}");
|
||||
assert_eq!(dest, before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_dabs_preserve_color_at_transparent_edges() {
|
||||
for ch in [2, 4, 5] {
|
||||
for hidden in [0.0, 1.0] {
|
||||
let (w, h) = (4, 4);
|
||||
let src = fill(w, h, ch, |x, _, c| {
|
||||
if c + 1 == ch {
|
||||
if x < 2 { 1.0 } else { 0.0 }
|
||||
} else if x < 2 {
|
||||
if c == 0 { 0.8 } else { 0.25 }
|
||||
} else {
|
||||
hidden
|
||||
}
|
||||
});
|
||||
let mut dest = vec![0.0; w * h * ch];
|
||||
let dab = Dab { x: 2.0, y: 2.0, theta: std::f32::consts::FRAC_PI_4, radius: 4.0, pressure: 1.0 };
|
||||
stamp_run(w, h, ch, &src, &mut dest, &dab, 0);
|
||||
let mut partial = 0;
|
||||
for pixel in dest.chunks_exact(ch) {
|
||||
if pixel[ch - 1] > 0.0 && pixel[ch - 1] < 1.0 {
|
||||
partial += 1;
|
||||
for (c, value) in pixel[..ch - 1].iter().enumerate() {
|
||||
let expected = if c == 0 { 0.8 } else { 0.25 };
|
||||
assert!((value - expected).abs() < 1e-6, "channels={ch}, hidden={hidden}, pixel={pixel:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(partial > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fill(w: usize, h: usize, ch: usize, f: impl Fn(i32, i32, usize) -> f32) -> Vec<f32> {
|
||||
let mut v = vec![0.0; w * h * ch];
|
||||
for y in 0..h {
|
||||
|
||||
+411
-100
@@ -1,135 +1,446 @@
|
||||
//! Average changes colour, never coverage. Keep the existing RGB conversion and selection
|
||||
//! weighting; Photoshop RGB8 observations are documented in docs/average-filter.md.
|
||||
use photocraft_color::{PixelFormat, SampleType};
|
||||
//! Bounded alpha-weighted averaging and Photoshop's coverage-preserving Average.
|
||||
pub use crate::coverage::Error;
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Interrupt, Surface, from_rgba_into, to_rgba};
|
||||
|
||||
use crate::{Ctx, Image};
|
||||
|
||||
/// Accumulation order and F32 products preserve the original Raster Average policy.
|
||||
#[derive(Default)]
|
||||
struct Mean {
|
||||
pub struct Mean {
|
||||
sum: [f64; 3],
|
||||
weight: f64,
|
||||
alpha: f64,
|
||||
count: f64,
|
||||
}
|
||||
|
||||
impl Mean {
|
||||
fn add(&mut self, fmt: &PixelFormat, px: &[f32], coverage: f32) {
|
||||
let rgba = to_rgba(fmt, px);
|
||||
let w = f64::from(coverage);
|
||||
for (sum, value) in self.sum.iter_mut().zip(rgba) {
|
||||
*sum += f64::from(value) * w;
|
||||
/// Accumulate the native selection/alpha-weighted color mean while preserving the established multiplication
|
||||
/// order.
|
||||
pub fn push(&mut self, p: [f32; 4], coverage: f32) {
|
||||
let weight = f64::from(p[3] * coverage);
|
||||
for (sum, value) in self.sum.iter_mut().zip(p) {
|
||||
*sum += f64::from(value) * weight;
|
||||
}
|
||||
self.weight += w;
|
||||
self.weight += weight;
|
||||
self.alpha += f64::from(p[3] * coverage);
|
||||
self.count += f64::from(coverage);
|
||||
}
|
||||
|
||||
fn colour(&self) -> Option<[f32; 3]> {
|
||||
(self.weight > 0.0).then(|| self.sum.map(|s| (s / self.weight) as f32))
|
||||
/// Photoshop Average weights straight colors by selection, including hidden RGB, without changing coverage.
|
||||
fn push_colour(&mut self, p: [f32; 4], coverage: f32) {
|
||||
let weight = f64::from(coverage);
|
||||
for (sum, value) in self.sum.iter_mut().zip(p) {
|
||||
*sum += f64::from(value) * weight;
|
||||
}
|
||||
self.weight += weight;
|
||||
self.count += weight;
|
||||
self.alpha += f64::from(p[3]) * weight;
|
||||
}
|
||||
/// Return the normalized mean only when positive alpha weight exists, keeping the native average-alpha policy.
|
||||
pub fn rgba(&self) -> Option<[f32; 4]> {
|
||||
(self.weight > 0.).then(|| {
|
||||
[
|
||||
(self.sum[0] / self.weight) as f32,
|
||||
(self.sum[1] / self.weight) as f32,
|
||||
(self.sum[2] / self.weight) as f32,
|
||||
(self.alpha / self.count.max(1e-9)) as f32,
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn mix(fmt: &PixelFormat, px: &mut [f32], colour: [f32; 3], coverage: f32) {
|
||||
if coverage <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let mut rgba = to_rgba(fmt, px);
|
||||
for (value, mean) in rgba.iter_mut().zip(colour) {
|
||||
*value += (mean - *value) * coverage;
|
||||
}
|
||||
from_rgba_into(fmt, rgba, px);
|
||||
/// Translate interruption into the shared checked native-filter cancellation error.
|
||||
fn check(ctl: &Interrupt) -> Result<(), Error> {
|
||||
ctl.check().map_err(|_| Error::Cancelled)
|
||||
}
|
||||
|
||||
// Rect's public coordinates can span more than i32::MAX. Reject these before raster helpers
|
||||
// do their signed coordinate arithmetic, and cap a single operation's sample count.
|
||||
fn valid_area(area: Rect, channels: usize) -> bool {
|
||||
area.width() <= i32::MAX as u32
|
||||
&& area.height() <= i32::MAX as u32
|
||||
&& u64::from(area.width()).saturating_mul(u64::from(area.height())).saturating_mul(channels as u64) <= 512 * 1024 * 1024
|
||||
/// Selection coverage saturates like the ordinary filter path; nonfinite masks remain invalid.
|
||||
fn selection_coverage(selection: Option<&Surface>, x: i32, y: i32) -> Result<f32, Error> {
|
||||
let coverage = selection.map_or(1., |surface| surface.sample_channel(x, y, 0));
|
||||
if !coverage.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
Ok(coverage.clamp(0., 1.))
|
||||
}
|
||||
/// Average a bounded native area using fallible row storage and publish only finite, uncancelled selection-mixed
|
||||
/// output.
|
||||
pub fn apply_with(surface: &Surface, area: Rect, bounds: Rect, selection: Option<&Surface>, ctl: &Interrupt) -> Result<Surface, Error> {
|
||||
apply_policy(surface, area, bounds, selection, ctl, false)
|
||||
}
|
||||
|
||||
pub(crate) fn apply(surface: &Surface, area: Rect, selection: Option<&Surface>, ctl: &Interrupt<'_>) -> Option<Surface> {
|
||||
let fmt = surface.format();
|
||||
let n = fmt.channels();
|
||||
if !valid_area(area, n) || ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
/// Photoshop Average edits straight colors with selection weights while preserving every native alpha sample.
|
||||
pub fn apply_preserving_alpha_with(surface: &Surface, area: Rect, bounds: Rect, selection: Option<&Surface>, ctl: &Interrupt) -> Result<Surface, Error> {
|
||||
apply_policy(surface, area, bounds, selection, ctl, true)
|
||||
}
|
||||
|
||||
/// Preserve the upstream optional dispatcher contract while using bounded checked publication.
|
||||
pub(crate) fn apply(surface: &Surface, area: Rect, selection: Option<&Surface>, ctl: &Interrupt) -> Option<Surface> {
|
||||
apply_preserving_alpha_with(surface, area, area, selection, ctl).ok()
|
||||
}
|
||||
|
||||
/// Both averaging policies share finite-sample checks, output admission and cancellable row scratch.
|
||||
fn apply_policy(surface: &Surface, area: Rect, bounds: Rect, selection: Option<&Surface>, ctl: &Interrupt, preserve_alpha: bool) -> Result<Surface, Error> {
|
||||
check(ctl)?;
|
||||
let area = area.intersect(&bounds);
|
||||
if area.is_empty() {
|
||||
return Some(surface.clone());
|
||||
return Ok(surface.clone());
|
||||
}
|
||||
let mut raw = surface.try_read_region(area).ok()?;
|
||||
let width = area.width() as usize;
|
||||
let coverage = |i: usize| selection.map_or(1.0, |s| s.sample_channel(area.x0 + (i % width) as i32, area.y0 + (i / width) as i32, 0));
|
||||
let w = area.width() as usize;
|
||||
let h = area.height() as usize;
|
||||
if w.checked_mul(h).is_none_or(|n| n > crate::coverage::MAX_PIXELS) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let tile = i64::from(photocraft_geom::TILE_SIZE);
|
||||
let axes = |a: i32, b: i32| -> Result<usize, Error> {
|
||||
usize::try_from((i64::from(b) - 1).div_euclid(tile) - i64::from(a).div_euclid(tile) + 1).map_err(|_| Error::WorkspaceLimit)
|
||||
};
|
||||
let bytes = axes(area.x0, area.x1)?
|
||||
.checked_mul(axes(area.y0, area.y1)?)
|
||||
.and_then(|n| n.checked_mul((tile * tile) as usize * surface.format().bytes_per_pixel() + 128))
|
||||
.and_then(|n| n.checked_add(w * (surface.channels() + 4) * 4))
|
||||
.and_then(|n| n.checked_add(surface.tile_count().checked_mul(128)?))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
if bytes > crate::coverage::MAX_WORKSPACE_BYTES {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
let n = surface.channels();
|
||||
if n == 0 || n > 5 {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let mut row = Vec::new();
|
||||
row.try_reserve_exact(w * n).map_err(|_| Error::Allocation)?;
|
||||
let mut mean = Mean::default();
|
||||
for (i, px) in raw.chunks_exact(n).enumerate() {
|
||||
if i % width == 0 && ctl.cancelled() {
|
||||
return None;
|
||||
for y in area.y0..area.y1 {
|
||||
check(ctl)?;
|
||||
surface.read_region_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row);
|
||||
for (x, pixel) in (area.x0..area.x1).zip(row.chunks_exact(n)) {
|
||||
let p = to_rgba(&surface.format(), pixel);
|
||||
let k = selection_coverage(selection, x, y)?;
|
||||
if p.into_iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
if preserve_alpha {
|
||||
mean.push_colour(p, k);
|
||||
} else {
|
||||
mean.push(p, k);
|
||||
}
|
||||
}
|
||||
mean.add(&fmt, px, coverage(i));
|
||||
}
|
||||
let Some(colour) = mean.colour() else { return Some(surface.clone()) };
|
||||
for (i, px) in raw.chunks_exact_mut(n).enumerate() {
|
||||
if i % width == 0 && ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
mix(&fmt, px, colour, coverage(i));
|
||||
let Some(avg) = mean.rgba() else { return Ok(surface.clone()) };
|
||||
if avg.into_iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let mut out = surface.clone();
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
for y in area.y0..area.y1 {
|
||||
check(ctl)?;
|
||||
surface.read_region_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row);
|
||||
for (x, dst) in (area.x0..area.x1).zip(row.chunks_exact_mut(n)) {
|
||||
let k = selection_coverage(selection, x, y)?;
|
||||
if k == 0. {
|
||||
continue;
|
||||
}
|
||||
let original_alpha = dst.last().copied();
|
||||
let p = to_rgba(&surface.format(), dst);
|
||||
let mut target = avg;
|
||||
if preserve_alpha {
|
||||
target[3] = p[3];
|
||||
}
|
||||
let mut mixed = p;
|
||||
if !preserve_alpha && surface.format().alpha && p[3] != avg[3] {
|
||||
let before = f64::from(p[3]) * (1. - f64::from(k));
|
||||
let after = f64::from(avg[3]) * f64::from(k);
|
||||
let alpha = before + after;
|
||||
for c in 0..3 {
|
||||
mixed[c] = if alpha > 0. { ((f64::from(p[c]) * before + f64::from(avg[c]) * after) / alpha) as f32 } else { 0. };
|
||||
}
|
||||
mixed[3] = alpha as f32;
|
||||
if mixed.iter().any(|value| !value.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
from_rgba_into(&surface.format(), mixed, dst);
|
||||
if dst.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for (v, (a, b)) in mixed.iter_mut().zip(p.into_iter().zip(target)) {
|
||||
*v = a + (b - a) * k;
|
||||
if !v.is_finite() {
|
||||
let precise = f64::from(a) + (f64::from(b) - f64::from(a)) * f64::from(k);
|
||||
if !precise.is_finite() || precise.abs() > f64::from(f32::MAX) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
*v = precise as f32;
|
||||
}
|
||||
}
|
||||
from_rgba_into(&surface.format(), mixed, dst);
|
||||
if preserve_alpha
|
||||
&& surface.format().alpha
|
||||
&& let Some(alpha) = dst.last_mut()
|
||||
{
|
||||
*alpha = original_alpha.unwrap_or(p[3]);
|
||||
}
|
||||
if dst.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
}
|
||||
out.try_write_region(Rect::new(area.x0, y, area.x1, y + 1), &row).map_err(|_| Error::Allocation)?;
|
||||
}
|
||||
out.try_write_region(area, &raw).ok()?;
|
||||
check(ctl)?;
|
||||
out.prune();
|
||||
ctl.progress(1.0);
|
||||
Some(out)
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// The direct kernel API has no selection. Its mean is over the reference bounds, even when
|
||||
// the requested output is only a tile; the surface dispatcher above also handles selections.
|
||||
pub(crate) fn kernel(src: &Image, out: Rect, ctx: &Ctx) -> Vec<f32> {
|
||||
let fmt = PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha);
|
||||
let n = fmt.channels();
|
||||
if src.ch != n || !valid_area(src.rect, n) || !valid_area(out, n) {
|
||||
/// Adapt raw native float images to checked Average, preserving bounded identity fallback on rejected work.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn run_image(src: &crate::image::Image, out: Rect, ctx: &crate::Ctx) -> Vec<f32> {
|
||||
run_image_policy(src, out, ctx, false)
|
||||
}
|
||||
|
||||
/// The ordinary command's direct kernel shares the canvas-clipped mean and alpha-preserving policy.
|
||||
pub(crate) fn kernel(src: &crate::image::Image, out: Rect, ctx: &crate::Ctx) -> Vec<f32> {
|
||||
run_image_policy(src, out, ctx, true)
|
||||
}
|
||||
|
||||
/// Raw native images remain bounded and retain identity fallback on rejected work.
|
||||
fn run_image_policy(src: &crate::image::Image, out: Rect, ctx: &crate::Ctx, preserve_alpha: bool) -> Vec<f32> {
|
||||
let format = photocraft_color::PixelFormat::new(ctx.mode, photocraft_color::SampleType::F32, ctx.alpha);
|
||||
let valid = [src.rect, out].into_iter().all(|r| (r.width() as usize).checked_mul(r.height() as usize).is_some_and(|n| n <= crate::coverage::MAX_PIXELS));
|
||||
if !valid
|
||||
|| src.ch != format.channels()
|
||||
|| (src.rect.width() as usize).checked_mul(src.rect.height() as usize).and_then(|n| n.checked_mul(src.ch)) != Some(src.data.len())
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let read = |x: i32, y: i32| -> Option<&[f32]> {
|
||||
if !src.rect.contains(x, y) {
|
||||
return None;
|
||||
let tile = photocraft_geom::TILE_SIZE as u64;
|
||||
let tiles = |r: Rect| (u64::from(r.width()).div_ceil(tile) + 1) * (u64::from(r.height()).div_ceil(tile) + 1);
|
||||
if (tiles(src.rect) + tiles(out)).saturating_mul(tile * tile * format.bytes_per_pixel() as u64) > crate::coverage::MAX_WORKSPACE_BYTES as u64 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut surface = Surface::new(format);
|
||||
let identity = || -> Result<Vec<f32>, Error> {
|
||||
let count = (out.width() as usize).checked_mul(out.height() as usize).and_then(|n| n.checked_mul(src.ch)).ok_or(Error::WorkspaceLimit)?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(count).map_err(|_| Error::Allocation)?;
|
||||
for y in out.y0..out.y1 {
|
||||
for x in out.x0..out.x1 {
|
||||
for c in 0..src.ch {
|
||||
values.push(src.get(x, y, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
let i = (i64::from(y) - i64::from(src.rect.y0)) as usize;
|
||||
let j = (i64::from(x) - i64::from(src.rect.x0)) as usize;
|
||||
let start = i.checked_mul(src.rect.width() as usize)?.checked_add(j)?.checked_mul(n)?;
|
||||
src.data.get(start..start.checked_add(n)?)
|
||||
Ok(values)
|
||||
};
|
||||
let bounds = ctx.bounds.intersect(&src.rect);
|
||||
let mut mean = Mean::default();
|
||||
for y in bounds.y0..bounds.y1 {
|
||||
for x in bounds.x0..bounds.x1 {
|
||||
if let Some(px) = read(x, y) {
|
||||
mean.add(&fmt, px, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let len = (out.width() as usize).checked_mul(out.height() as usize).and_then(|s| s.checked_mul(n));
|
||||
let Some(len) = len else { return Vec::new() };
|
||||
let mut result = Vec::new();
|
||||
if result.try_reserve_exact(len).is_err() {
|
||||
return result;
|
||||
}
|
||||
let colour = mean.colour();
|
||||
for y in out.y0..out.y1 {
|
||||
for x in out.x0..out.x1 {
|
||||
let mut px = [0.0; 5];
|
||||
let Some(pixel) = px.get_mut(..n) else { return Vec::new() };
|
||||
if let Some(source) = read(x, y) {
|
||||
pixel.copy_from_slice(source);
|
||||
}
|
||||
if let Some(colour) = colour {
|
||||
mix(&fmt, pixel, colour, 1.0);
|
||||
}
|
||||
result.extend_from_slice(pixel);
|
||||
}
|
||||
}
|
||||
result
|
||||
let mut run = || -> Result<Vec<f32>, Error> {
|
||||
let domain = src.rect.intersect(&ctx.bounds);
|
||||
surface.try_write_region(src.rect, &src.data).map_err(|_| Error::Allocation)?;
|
||||
// Average the complete supplied image, even when only one output tile is
|
||||
// requested. Unpopulated canvas pixels are not part of this image.
|
||||
apply_policy(&surface, domain, domain, None, &Interrupt::NONE, preserve_alpha)?.try_read_region(out).map_err(|_| Error::Allocation)
|
||||
};
|
||||
run().unwrap_or_else(|_| identity().unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
|
||||
/// Canvas size and output tiling must not dilute a small offset image's color or alpha mean.
|
||||
#[test]
|
||||
fn raw_average_uses_image_domain_and_keeps_global_mean_across_output_tiles() {
|
||||
let rect = Rect::new(12, 15, 14, 16);
|
||||
for alpha in [false, true] {
|
||||
let format = PixelFormat::new(ColorMode::Rgb, SampleType::F32, alpha);
|
||||
let mut data = vec![0.2, 0.4, 0.6];
|
||||
if alpha {
|
||||
data.push(0.5);
|
||||
}
|
||||
data.extend([0.8, 0.6, 0.4]);
|
||||
if alpha {
|
||||
data.push(1.);
|
||||
}
|
||||
let image = crate::Image { rect, ch: format.channels(), data };
|
||||
for bounds in [Rect::new(0, 0, 20, 20), Rect::new(0, 0, 10_000, 10_000)] {
|
||||
let ctx = crate::Ctx { bounds, mode: ColorMode::Rgb, alpha };
|
||||
let expected = if alpha { vec![0.6, 8. / 15., 7. / 15., 0.75] } else { vec![0.5, 0.5, 0.5] };
|
||||
for out in [rect, Rect::new(12, 15, 13, 16), Rect::new(13, 15, 14, 16)] {
|
||||
let result = run_image(&image, out, &ctx);
|
||||
assert_eq!(result.len(), out.size().area() as usize * format.channels());
|
||||
for pixel in result.chunks_exact(format.channels()) {
|
||||
for (value, want) in pixel.iter().zip(&expected) {
|
||||
assert!((value - want).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Keep unselected CMYK separations and out-of-gamut Lab samples unchanged at every native depth.
|
||||
fn zero_coverage_preserves_native_cmyk_and_out_of_gamut_lab_samples() {
|
||||
for mode in [ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in SampleType::ALL {
|
||||
let format = PixelFormat::new(mode, depth, true);
|
||||
let mut source = Surface::new(format);
|
||||
let untouched: &[f32] = if mode == ColorMode::Cmyk { &[0.2, 0.4, 0.6, 0.5, 1.] } else { &[0.5, 1., 1., 1.] };
|
||||
source.write_pixel(1, 0, untouched);
|
||||
source.write_pixel(0, 0, &vec![0.75; format.channels()]);
|
||||
let before = source.pixel(1, 0);
|
||||
let mut mask = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
mask.write_pixel(0, 0, &[1.]);
|
||||
let bounds = Rect::new(0, 0, 2, 1);
|
||||
let output = apply_with(&source, bounds, bounds, Some(&mask), &Interrupt::NONE).unwrap();
|
||||
assert_eq!(output.pixel(1, 0), before, "{mode:?} {depth:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "24MP native Average performance probe"]
|
||||
/// Measure release Average on a full-size original surface with bounded rows rather than a whole-frame sample
|
||||
/// copy.
|
||||
fn average_24mp_bounded_rows_benchmark() {
|
||||
let b = Rect::new(0, 0, 6000, 4000);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
source.fill_rect(Rect::new(0, 0, 3000, 4000), &[1., 0., 0., 0.5]);
|
||||
source.fill_rect(Rect::new(3000, 0, 6000, 4000), &[0., 0., 1., 1.]);
|
||||
let started = std::time::Instant::now();
|
||||
let output = apply_with(&source, b, b, None, &Interrupt::NONE).unwrap();
|
||||
println!("native Average24MP RGBA32F elapsed_ms={}", started.elapsed().as_millis());
|
||||
let p = output.pixel(3000, 2000);
|
||||
assert!((p[0] - 1. / 3.).abs() < 1e-6 && (p[2] - 2. / 3.).abs() < 1e-6 && p[3] == 0.75);
|
||||
}
|
||||
#[test]
|
||||
/// Pin native mean weighting, premultiplied feathering and quantization across color models and depths.
|
||||
fn rgba_weighted_mean_and_premultiplied_selection_at_every_depth() {
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let format = PixelFormat { mode, sample: depth, alpha: true };
|
||||
let mut s = Surface::new(format);
|
||||
let mut p = vec![0.; format.channels()];
|
||||
from_rgba_into(&format, [0.2, 0.4, 0.6, 0.5], &mut p);
|
||||
s.write_pixel(0, 0, &p);
|
||||
from_rgba_into(&format, [0.8, 0.3, 0.1, 1.], &mut p);
|
||||
s.write_pixel(1, 0, &p);
|
||||
let a = to_rgba(&format, &s.pixel(0, 0));
|
||||
let b = to_rgba(&format, &s.pixel(1, 0));
|
||||
let mut mask = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
mask.write_pixel(0, 0, &[1.]);
|
||||
mask.write_pixel(1, 0, &[0.25]);
|
||||
let mut m = Mean::default();
|
||||
m.push(a, 1.);
|
||||
m.push(b, 0.25);
|
||||
let expected = m.rgba().unwrap();
|
||||
let out = apply_with(&s, Rect::new(0, 0, 2, 1), Rect::new(0, 0, 2, 1), Some(&mask), &Interrupt::NONE).unwrap();
|
||||
let mut encoded = Surface::new(format);
|
||||
from_rgba_into(&format, expected, &mut p);
|
||||
encoded.write_pixel(0, 0, &p);
|
||||
assert_eq!(out.pixel(0, 0), encoded.pixel(0, 0));
|
||||
let alpha = f64::from(b[3]) * 0.75 + f64::from(expected[3]) * 0.25;
|
||||
let mixed = std::array::from_fn(|c| {
|
||||
if c == 3 {
|
||||
alpha as f32
|
||||
} else {
|
||||
((f64::from(b[c]) * f64::from(b[3]) * 0.75 + f64::from(expected[c]) * f64::from(expected[3]) * 0.25) / alpha) as f32
|
||||
}
|
||||
});
|
||||
from_rgba_into(&format, mixed, &mut p);
|
||||
encoded.write_pixel(1, 0, &p);
|
||||
assert_eq!(out.pixel(1, 0), encoded.pixel(1, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Compare with an independently calculated weighted mean and require cancellation to preserve source pixels.
|
||||
fn independent_mean_and_cancel_are_atomic() {
|
||||
let mut s = Surface::new(PixelFormat::RGBA32F);
|
||||
s.write_pixel(0, 0, &[1., 0., 0., 0.5]);
|
||||
s.write_pixel(1, 0, &[0., 0., 1., 1.]);
|
||||
let b = Rect::new(0, 0, 2, 1);
|
||||
let out = apply_with(&s, b, b, None, &Interrupt::NONE).unwrap();
|
||||
let p = out.pixel(0, 0);
|
||||
assert!((p[0] - 1. / 3.).abs() < 1e-6);
|
||||
assert!((p[2] - 2. / 3.).abs() < 1e-6);
|
||||
assert_eq!(p[3], 0.75);
|
||||
let cancel = || true;
|
||||
assert_eq!(apply_with(&s, b, b, None, &Interrupt::cancel_only(&cancel)).unwrap_err(), Error::Cancelled);
|
||||
assert_eq!(s.pixel(0, 0), vec![1., 0., 0., 0.5]);
|
||||
assert!(apply_with(&s, Rect::new(0, 0, 100000, 100000), Rect::new(0, 0, 100000, 100000), None, &Interrupt::NONE).is_err());
|
||||
}
|
||||
#[test]
|
||||
/// Cover opaque HDR, empty alpha support and delayed cancellation under the existing native Average policy.
|
||||
fn opaque_hdr_empty_alpha_and_mid_pass_cancel_keep_native_rules() {
|
||||
let b = Rect::new(0, 0, 2, 2);
|
||||
let mut opaque = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, false));
|
||||
opaque.fill_rect(b, &[4., -2., 0.5]);
|
||||
let out = apply_with(&opaque, b, b, None, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(out.read_region(b), opaque.read_region(b));
|
||||
let mut transparent = Surface::new(PixelFormat::RGBA32F);
|
||||
transparent.fill_rect(b, &[1., 0., 0., 0.]);
|
||||
assert_eq!(apply_with(&transparent, b, b, None, &Interrupt::NONE).unwrap().read_region(b), transparent.read_region(b));
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let checks = AtomicUsize::new(0);
|
||||
let cancel = || checks.fetch_add(1, Ordering::Relaxed) >= 3;
|
||||
let before = opaque.clone();
|
||||
assert_eq!(apply_with(&opaque, b, b, None, &Interrupt::cancel_only(&cancel)).unwrap_err(), Error::Cancelled);
|
||||
assert_eq!(opaque, before);
|
||||
opaque.write_pixel(0, 0, &[f32::NAN, 0., 0.]);
|
||||
assert_eq!(apply_with(&opaque, b, b, None, &Interrupt::NONE).unwrap_err(), Error::NonFiniteSample);
|
||||
}
|
||||
#[test]
|
||||
/// Exercise extreme finite HDR selection mixtures so intermediate overflow cannot publish nonfinite pixels.
|
||||
fn finite_hdr_selection_intermediates_never_publish_infinity() {
|
||||
let b = Rect::new(0, 0, 2, 1);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
source.write_pixel(0, 0, &[f32::MAX, 0., 0., 1.]);
|
||||
source.write_pixel(1, 0, &[-f32::MAX, 0., 0., 1.]);
|
||||
let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
selection.write_pixel(0, 0, &[1.]);
|
||||
selection.write_pixel(1, 0, &[0.5]);
|
||||
let before = source.clone();
|
||||
let output = apply_with(&source, b, b, Some(&selection), &Interrupt::NONE).unwrap();
|
||||
assert!(output.read_region(b).iter().all(|v| v.is_finite()));
|
||||
assert!((f64::from(output.pixel(0, 0)[0]) / f64::from(f32::MAX) - 1. / 3.).abs() < 1e-6);
|
||||
assert!((f64::from(output.pixel(1, 0)[0]) / f64::from(f32::MAX) + 1. / 3.).abs() < 1e-6);
|
||||
assert_eq!(source, before);
|
||||
// Hostile finite signed coverage can make the mean itself unrepresentable.
|
||||
source.write_pixel(1, 0, &[-f32::MAX, 0., 0., -0.5]);
|
||||
let before = source.clone();
|
||||
assert_eq!(apply_with(&source, b, b, None, &Interrupt::NONE).unwrap_err(), Error::NonFiniteSample);
|
||||
assert_eq!(source, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Reject selected Average results that overflow native Lab conversion without modifying the input surface.
|
||||
fn alpha_changing_lab_selection_rejects_nonfinite_native_conversion_atomically() {
|
||||
let format = PixelFormat::new(ColorMode::Lab, SampleType::F32, true);
|
||||
let bounds = Rect::new(0, 0, 3, 1);
|
||||
let neutral = 128. / 255.;
|
||||
// Finite signed alpha is hostile but accepted input. Its weights nearly cancel while the
|
||||
// white pixel's color contribution remains, creating finite HDR RGB that overflows Lab.
|
||||
let pixels: [[f32; 4]; 3] = [[1., neutral, neutral, 1.], [0., neutral, neutral, -1.], [0., neutral, neutral, 1e-20]];
|
||||
let mut source = Surface::new(format);
|
||||
let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
let mut mean = Mean::default();
|
||||
for (x, (pixel, coverage)) in pixels.into_iter().zip([1., 1., 0.5]).enumerate() {
|
||||
assert!(pixel.iter().all(|v| v.is_finite()));
|
||||
source.write_pixel(x as i32, 0, &pixel);
|
||||
selection.write_pixel(x as i32, 0, &[coverage]);
|
||||
let rgba = to_rgba(&format, &pixel);
|
||||
assert!(rgba.iter().all(|v| v.is_finite()));
|
||||
mean.push(rgba, coverage);
|
||||
}
|
||||
let avg = mean.rgba().unwrap();
|
||||
assert!(avg.iter().all(|v| v.is_finite()));
|
||||
assert!(avg[0] > 1e19);
|
||||
assert_ne!(avg[3], pixels[0][3]);
|
||||
// Full selection coverage at the first pixel makes its premultiplied mix exactly avg.
|
||||
let mut native = [0.; 4];
|
||||
from_rgba_into(&format, avg, &mut native);
|
||||
assert!(native.iter().any(|v| !v.is_finite()));
|
||||
let before = source.clone();
|
||||
assert_eq!(apply_with(&source, bounds, bounds, Some(&selection), &Interrupt::NONE).unwrap_err(), Error::NonFiniteSample);
|
||||
assert_eq!(source, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "average/tests.rs"]
|
||||
mod upstream_tests;
|
||||
@@ -1,5 +1,66 @@
|
||||
use super::*;
|
||||
use photocraft_color::ColorMode;
|
||||
use crate::{Ctx, Image};
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
|
||||
#[test]
|
||||
/// Long, thin images are admitted by their pixel/workspace budgets rather than an unrelated edge limit.
|
||||
fn average_accepts_a_seventy_thousand_pixel_edge_within_workspace() {
|
||||
let bounds = Rect::new(0, 0, 70_000, 100);
|
||||
let mut source = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false));
|
||||
source.fill_rect(Rect::new(35_000, 0, 70_000, 100), &[1.]);
|
||||
let output = apply_preserving_alpha_with(&source, bounds, bounds, None, &Interrupt::NONE).unwrap();
|
||||
for (x, y) in [(0, 0), (35_000, 50), (69_999, 99)] {
|
||||
assert!((output.pixel(x, y)[0] - 0.5).abs() <= 1. / 255.);
|
||||
}
|
||||
assert_eq!(source.pixel(0, 0), vec![0.]);
|
||||
assert_eq!(source.pixel(69_999, 99), vec![1.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// The raw adapter retains one global mean when a long image produces only a small output tile.
|
||||
fn raw_average_accepts_long_edges_and_keeps_the_global_mean() {
|
||||
for rect in [Rect::new(0, 0, 70_000, 1), Rect::new(0, 0, 1, 70_000)] {
|
||||
let mut data = vec![0.; 70_000];
|
||||
data[35_000..].fill(1.);
|
||||
let source = Image { rect, ch: 1, data };
|
||||
let ctx = Ctx { bounds: rect, mode: ColorMode::Grayscale, alpha: false };
|
||||
assert_eq!(kernel(&source, Rect::new(0, 0, 1, 1), &ctx), vec![0.5]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Finite selection values saturate for both mean weighting and publication under both Average policies.
|
||||
fn finite_selection_coverage_clamps_in_both_average_passes() {
|
||||
let bounds = Rect::new(0, 0, 3, 1);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
source.write_region(bounds, &[1., 0., 0., 0.25, 0., 1., 0., 0.5, 0., 0., 1., 0.75]);
|
||||
let before = source.clone();
|
||||
let format = PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false);
|
||||
let mut unbounded = Surface::new(format);
|
||||
unbounded.write_region(bounds, &[-0.75, 0.25, 2.]);
|
||||
let mut clamped = Surface::new(format);
|
||||
clamped.write_region(bounds, &[0., 0.25, 1.]);
|
||||
for preserve_alpha in [false, true] {
|
||||
let run = |mask: &Surface| {
|
||||
if preserve_alpha {
|
||||
apply_preserving_alpha_with(&source, bounds, bounds, Some(mask), &Interrupt::NONE)
|
||||
} else {
|
||||
apply_with(&source, bounds, bounds, Some(mask), &Interrupt::NONE)
|
||||
}
|
||||
};
|
||||
let expected = run(&clamped).unwrap();
|
||||
let actual = run(&unbounded).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(actual.pixel(0, 0), source.pixel(0, 0), "negative coverage hides the edit");
|
||||
assert_ne!(actual.pixel(2, 0), source.pixel(2, 0), "coverage above one fully applies the mean");
|
||||
for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
unbounded.write_pixel(1, 0, &[value]);
|
||||
assert_eq!(run(&unbounded).unwrap_err(), Error::NonFiniteSample);
|
||||
}
|
||||
unbounded.write_pixel(1, 0, &[0.25]);
|
||||
}
|
||||
assert_eq!(source, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_alpha_and_averages_hidden_rgb_at_each_depth() {
|
||||
|
||||
@@ -55,11 +55,16 @@ pub fn validate_curve(points: &[[f32; 2]]) -> Result<(), String> {
|
||||
|
||||
use crate::photo_util::{hash01, linear_to_srgb, par_rows, srgb_to_linear};
|
||||
|
||||
mod local_tone;
|
||||
pub mod local_tone;
|
||||
mod per_pixel;
|
||||
pub mod spatial;
|
||||
mod whites_blacks;
|
||||
|
||||
pub use per_pixel::{CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, per_pixel, white_black_points};
|
||||
pub use local_tone::{LocalTone, ToneKind, TonePass};
|
||||
pub use per_pixel::{
|
||||
CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, white_black_points, whites_blacks_model,
|
||||
};
|
||||
pub use spatial::{Clarity, Dehaze, Texture};
|
||||
|
||||
/// How the pixels encode light: the sRGB curve (gamma 0) or a pure power law (ProPhoto's 1.8,
|
||||
/// Adobe RGB's 2.2). The tone controls work on light, so the document's own curve decodes it.
|
||||
@@ -388,11 +393,13 @@ fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {
|
||||
|
||||
/// Approximate Gaussian (three box passes).
|
||||
fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {
|
||||
if sigma < 0.3 {
|
||||
return v.to_vec();
|
||||
}
|
||||
box_means(v, w, h, &spatial::gauss_radii(sigma))
|
||||
}
|
||||
|
||||
/// Box means of radii `radii` in turn.
|
||||
fn box_means(v: &[f32], w: usize, h: usize, radii: &[usize]) -> Vec<f32> {
|
||||
let mut out = v.to_vec();
|
||||
for r in crate::fxutil::gauss_box_radii(sigma) {
|
||||
for &r in radii {
|
||||
out = box_mean(&out, w, h, r);
|
||||
}
|
||||
out
|
||||
@@ -402,7 +409,7 @@ fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {
|
||||
/// coefficients are computed on a `s×` subsampled copy and upsampled bilinearly, which is
|
||||
/// visually equivalent for the large radii used by tone controls at a fraction of the cost.
|
||||
fn guided_fast(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec<f32> {
|
||||
let s = (r / 8).clamp(1, 8);
|
||||
let (s, rs) = spatial::fast_guided_steps(r);
|
||||
if s == 1 {
|
||||
return guided(i, p, w, h, r, eps);
|
||||
}
|
||||
@@ -420,7 +427,6 @@ fn guided_fast(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) ->
|
||||
o.iter().zip(&c).map(|(a, b)| a / b.max(1.0)).collect()
|
||||
};
|
||||
let (si, sp) = (down(i), down(p));
|
||||
let rs = (r / s).max(1);
|
||||
let mi = box_mean(&si, sw, sh, rs);
|
||||
let mp = box_mean(&sp, sw, sh, rs);
|
||||
let ip: Vec<f32> = si.iter().zip(&sp).map(|(a, b)| a * b).collect();
|
||||
@@ -680,7 +686,6 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bo
|
||||
return;
|
||||
}
|
||||
let ps = p.pixel_scale.clamp(0.01, 1.0);
|
||||
let long = w.max(h) as f32;
|
||||
// 1. White balance + exposure in linear light.
|
||||
if let Some(g) = per_pixel::gains(p) {
|
||||
par_rows(px, w, 1, |_, row| {
|
||||
@@ -708,8 +713,8 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bo
|
||||
});
|
||||
}
|
||||
// 2. Dehaze.
|
||||
if p.dehaze != 0.0 {
|
||||
dehaze(px, w, h, p.dehaze / 100.0);
|
||||
if let Some(d) = Dehaze::new(p, w, h) {
|
||||
dehaze(px, w, h, &d);
|
||||
}
|
||||
// 3. Tone. Highlights and Shadows: a local Laplacian filter (see `local_tone`).
|
||||
if p.highlights != 0.0 || p.shadows != 0.0 {
|
||||
@@ -718,20 +723,22 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bo
|
||||
if !p.local_tone_neutral() && [p.contrast, p.texture, p.clarity].iter().any(|v| *v != 0.0) {
|
||||
let l: Vec<f32> = px.iter().map(|q| luma([q[0], q[1], q[2]]).max(0.0)).collect();
|
||||
let lc: Vec<f32> = l.iter().map(|v| v.min(1.0)).collect();
|
||||
let clar = (p.clarity != 0.0).then(|| guided_fast(&lc, &lc, w, h, ((long * 0.02) as usize).max(3), 0.005));
|
||||
let tex = (p.texture != 0.0).then(|| gauss(&lc, w, h, (long * 0.002).max(1.5 * ps)));
|
||||
let clarity = Clarity::new(p, w, h);
|
||||
let texture = Texture::new(p, w, h);
|
||||
let clar = clarity.as_ref().map(|c| guided_fast(&lc, &lc, w, h, c.radius, spatial::CLARITY_EPS));
|
||||
let tex = texture.as_ref().map(|t| box_means(&lc, w, h, &t.radii));
|
||||
let k_con = p.contrast / 100.0 * 0.6;
|
||||
par_rows(px, w, 1, |y, row| {
|
||||
for (x, q) in row.iter_mut().enumerate() {
|
||||
let i = y * w + x;
|
||||
let l0 = l[i];
|
||||
let mut lv = lc[i];
|
||||
if let Some(c) = &clar {
|
||||
if let (Some(c), Some(k)) = (&clar, &clarity) {
|
||||
let mw = 1.0 - (2.0 * lv.clamp(0.0, 1.0) - 1.0).powi(2);
|
||||
lv += p.clarity / 100.0 * 0.8 * (lc[i] - c[i]) * mw;
|
||||
lv += k.amount * (lc[i] - c[i]) * mw;
|
||||
}
|
||||
if let Some(t) = &tex {
|
||||
lv += p.texture / 100.0 * 0.9 * (lc[i] - t[i]).clamp(-0.1, 0.1);
|
||||
if let (Some(t), Some(k)) = (&tex, &texture) {
|
||||
lv += k.amount * (lc[i] - t[i]).clamp(-spatial::TEXTURE_LIMIT, spatial::TEXTURE_LIMIT);
|
||||
}
|
||||
*q = tone(*q, l0, lc[i], lv, k_con);
|
||||
}
|
||||
@@ -885,11 +892,17 @@ fn balance(mut q: [f32; 4], g: [f32; 3]) -> [f32; 4] {
|
||||
q
|
||||
}
|
||||
|
||||
/// The index of the `q` quantile (0 … 1) among `len` sorted values, as every percentile in the
|
||||
/// develop picks it.
|
||||
pub fn quantile_rank(len: usize, q: f32) -> usize {
|
||||
(len.saturating_sub(1) as f32 * q).round() as usize
|
||||
}
|
||||
|
||||
/// The image's black and white points as sRGB-encoded grey levels: the 3rd percentile of the
|
||||
/// luminance and the 99.5th of the brightest channel, on a copy at most 256 pixels across (so a
|
||||
/// preview proxy and the full image agree). `map` is applied to each pixel first.
|
||||
fn luminance_points(px: &[[f32; 4]], w: usize, h: usize, enc: Encoding, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> (f32, f32) {
|
||||
let f = w.max(h).div_ceil(256).max(1);
|
||||
let f = w.max(h).div_ceil(whites_blacks::POINTS_SIDE).max(1);
|
||||
let (sw, sh) = (w.div_ceil(f), h.div_ceil(f));
|
||||
// Each band of `f` rows sums into its own row of cells, in the same order as one pass would.
|
||||
let bands = crate::photo_util::par_map(sh, |sy| {
|
||||
@@ -912,10 +925,10 @@ fn luminance_points(px: &[[f32; 4]], w: usize, h: usize, enc: Encoding, map: imp
|
||||
}
|
||||
let pct = |mut v: Vec<f32>, q: f32| {
|
||||
v.sort_by(f32::total_cmp);
|
||||
v[((v.len() - 1) as f32 * q).round() as usize]
|
||||
v[quantile_rank(v.len(), q)]
|
||||
};
|
||||
let bp = pct(cells.iter().map(|c| luma(*c)).collect(), 0.03);
|
||||
let wp = pct(cells.iter().map(|c| c[0].max(c[1]).max(c[2])).collect(), 0.995);
|
||||
let bp = pct(cells.iter().map(|c| luma(*c)).collect(), whites_blacks::POINT_QUANTILES[0]);
|
||||
let wp = pct(cells.iter().map(|c| c[0].max(c[1]).max(c[2])).collect(), whites_blacks::POINT_QUANTILES[1]);
|
||||
(linear_to_srgb(bp), linear_to_srgb(wp))
|
||||
}
|
||||
|
||||
@@ -929,25 +942,32 @@ fn value_noise(x: f32, y: f32, seed: u64) -> f32 {
|
||||
top + (bot - top) * sy
|
||||
}
|
||||
|
||||
fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, amount: f32) {
|
||||
// Transmission on a ≤ 768 px proxy, upsampled.
|
||||
let k = w.max(h).div_ceil(768).max(1);
|
||||
let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
|
||||
let mut small = vec![[0.0f32; 3]; sw * sh];
|
||||
let mut cnt = vec![0f32; sw * sh];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let i = (y / k) * sw + x / k;
|
||||
for c in 0..3 {
|
||||
small[i][c] += px[y * w + x][c].clamp(0.0, 1.0);
|
||||
/// Dehaze's copy of `px` (`w × h`): each pixel mapped by `map`, clipped to 0 … 1 and averaged over
|
||||
/// `d.factor × d.factor` blocks, each block summed in raster order.
|
||||
fn haze_cells(px: &[[f32; 4]], w: usize, h: usize, d: &Dehaze, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Vec<[f32; 3]> {
|
||||
let (k, [sw, sh]) = (d.factor, d.size);
|
||||
let bands = crate::photo_util::par_map(sh, |sy| {
|
||||
let mut small = vec![[0.0f32; 3]; sw];
|
||||
let mut cnt = vec![0f32; sw];
|
||||
for y in sy * k..((sy + 1) * k).min(h) {
|
||||
for x in 0..w {
|
||||
let q = map(px[y * w + x]);
|
||||
let i = x / k;
|
||||
for c in 0..3 {
|
||||
small[i][c] += q[c].clamp(0.0, 1.0);
|
||||
}
|
||||
cnt[i] += 1.0;
|
||||
}
|
||||
cnt[i] += 1.0;
|
||||
}
|
||||
}
|
||||
for (s, c) in small.iter_mut().zip(&cnt) {
|
||||
*s = s.map(|v| v / c.max(1.0));
|
||||
}
|
||||
let r = (sw.max(sh) / 60).max(2);
|
||||
small.iter().zip(&cnt).map(|(s, c)| s.map(|v| v / c.max(1.0))).collect::<Vec<_>>()
|
||||
});
|
||||
bands.into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, d: &Dehaze) {
|
||||
// Transmission on a ≤ DEHAZE_SIDE px proxy, upsampled.
|
||||
let (k, [sw, sh], r, amount) = (d.factor, d.size, d.radius, d.amount);
|
||||
let small = haze_cells(px, w, h, d, |q| q);
|
||||
// The minimum (or, with `f32::max`, maximum) over each (2r + 1)² window.
|
||||
let rank_filter = |v: &[f32], start: f32, pick: fn(f32, f32) -> f32| -> Vec<f32> {
|
||||
let mut a = vec![0.0f32; sw * sh];
|
||||
@@ -968,33 +988,37 @@ fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, amount: f32) {
|
||||
};
|
||||
let min_filter = |v: &[f32]| rank_filter(v, f32::MAX, f32::min);
|
||||
let dark = min_filter(&small.iter().map(|c| c[0].min(c[1]).min(c[2])).collect::<Vec<_>>());
|
||||
// Atmospheric light: mean colour of the brightest 0.1 % of the dark channel.
|
||||
// Atmospheric light: mean colour of the brightest 0.1 % of the dark channel (ties in the
|
||||
// order of the cells).
|
||||
let mut idx: Vec<usize> = (0..sw * sh).collect();
|
||||
idx.sort_by(|&a, &b| dark[b].total_cmp(&dark[a]));
|
||||
let top = (sw * sh / 1000).max(1);
|
||||
let top = d.top;
|
||||
let mut air = [0.0f32; 3];
|
||||
for &i in &idx[..top] {
|
||||
for c in 0..3 {
|
||||
air[c] += small[i][c] / top as f32;
|
||||
}
|
||||
}
|
||||
let air = air.map(|v| v.max(0.2));
|
||||
let air = air.map(|v| v.max(spatial::DEHAZE_AIR_FLOOR));
|
||||
let norm_dark = min_filter(&small.iter().map(|c| (c[0] / air[0]).min(c[1] / air[1]).min(c[2] / air[2])).collect::<Vec<_>>());
|
||||
// Opened (a maximum filter of the same radius after the minimum): the minimum grows every
|
||||
// dark object by `r`, so sky beside a dark building took its dark channel, counted as
|
||||
// haze-free and kept a bright halo (#9273). Opening shrinks dark regions back to their
|
||||
// outline and is still a lower bound of the dark channel over the window. It raises the dark
|
||||
// channel on average, so the 0.95 weight is scaled to keep the slider's overall strength.
|
||||
// channel on average, so the ω weight is scaled to keep the slider's overall strength.
|
||||
let opened = rank_filter(&norm_dark, f32::MIN, f32::max);
|
||||
let mean = |v: &[f32]| v.iter().sum::<f32>() / v.len().max(1) as f32;
|
||||
let weight = 0.95 * mean(&norm_dark) / mean(&opened).max(1e-6);
|
||||
// Summed in f64: an f32 running sum over the copy's few hundred thousand cells drifts by about
|
||||
// 1e-5, which the low transmission beside haze multiplies up to a visible fraction of a level.
|
||||
let mean = |v: &[f32]| (v.iter().map(|x| f64::from(*x)).sum::<f64>() / v.len().max(1) as f64) as f32;
|
||||
let weight = spatial::DEHAZE_OMEGA * mean(&norm_dark) / mean(&opened).max(1e-6);
|
||||
let t_raw: Vec<f32> = opened.iter().map(|d| 1.0 - weight * d).collect();
|
||||
let guide: Vec<f32> = small.iter().map(|c| luma(*c)).collect();
|
||||
let t = guided(&guide, &t_raw, sw, sh, r * 2, 1e-3);
|
||||
let t = guided(&guide, &t_raw, sw, sh, d.guide_radius, spatial::DEHAZE_EPS);
|
||||
let ks = k as f32;
|
||||
par_rows(px, w, 1, |y, row| {
|
||||
for (x, q) in row.iter_mut().enumerate() {
|
||||
let tv = crate::photo_util::bilinear(&t, sw, sh, 1, 0, (x as f32 + 0.5) / ks - 0.5, (y as f32 + 0.5) / ks - 0.5).clamp(0.1, 1.0);
|
||||
let tv =
|
||||
crate::photo_util::bilinear(&t, sw, sh, 1, 0, (x as f32 + 0.5) / ks - 0.5, (y as f32 + 0.5) / ks - 0.5).clamp(spatial::DEHAZE_T_FLOOR, 1.0);
|
||||
for c in 0..3 {
|
||||
let i = q[c];
|
||||
let j = (i - air[c]) / tv + air[c];
|
||||
@@ -1124,7 +1148,8 @@ mod tests {
|
||||
[c[0], c[1], c[2], 1.0]
|
||||
})
|
||||
.collect();
|
||||
dehaze(&mut px, w, h, 1.0);
|
||||
let d = Dehaze::new(&CameraRaw { dehaze: 100.0, ..Default::default() }, w, h).unwrap();
|
||||
dehaze(&mut px, w, h, &d);
|
||||
let sky = |xs: std::ops::Range<usize>| {
|
||||
let v: Vec<f32> =
|
||||
(150..390).flat_map(|y| xs.clone().map(move |x| (x, y))).map(|(x, y)| luma([px[y * w + x][0], px[y * w + x][1], px[y * w + x][2]])).collect();
|
||||
@@ -1403,4 +1428,23 @@ mod tests {
|
||||
develop(&mut a, 4, 4, &CameraRaw { exposure: 0.5, ..Default::default() }, true);
|
||||
assert!(a[0][0] > 2.0);
|
||||
}
|
||||
|
||||
/// A Gaussian narrower than 0.3 px has no box radii, so it returns its input unchanged, and
|
||||
/// Texture on a proxy that small changes nothing.
|
||||
#[test]
|
||||
fn a_gaussian_below_0_3_px_leaves_the_image_alone() {
|
||||
assert!(spatial::gauss_radii(0.29).is_empty());
|
||||
assert!(!spatial::gauss_radii(0.3).is_empty());
|
||||
let (w, h) = (64usize, 48usize);
|
||||
let v: Vec<f32> = (0..w * h).map(|i| ((i * 37) % 101) as f32 / 100.0).collect();
|
||||
assert_eq!(gauss(&v, w, h, 0.29), v);
|
||||
assert_eq!(box_means(&v, w, h, &[]), v);
|
||||
assert_ne!(gauss(&v, w, h, 1.0), v);
|
||||
let src: Vec<[f32; 4]> = v.iter().map(|&x| [x, 1.0 - x, 0.5 * x, 1.0]).collect();
|
||||
let base = CameraRaw { contrast: 10.0, pixel_scale: 0.1, ..Default::default() };
|
||||
let (mut plain, mut textured) = (src.clone(), src);
|
||||
develop(&mut plain, w, h, &base, false);
|
||||
develop(&mut textured, w, h, &CameraRaw { texture: 80.0, ..base }, false);
|
||||
assert_eq!(plain, textured);
|
||||
}
|
||||
}
|
||||
@@ -20,19 +20,31 @@
|
||||
//! mean error against Photoshop is 2.8–9.4 levels (of 255) where the previous heuristic's was
|
||||
//! 3.7–14.3.
|
||||
|
||||
use super::{Encoding, luma};
|
||||
use super::{Encoding, luma, quantile_rank};
|
||||
use crate::photo_util::par_rows;
|
||||
|
||||
/// Spacing of the fast filter's reference values in stops. Its remapping changes within about
|
||||
/// half a stop, and coefficients interpolated across wider gaps show as contour lines on smooth
|
||||
/// gradients (12 references over a whole raw's range left visible steps; at an eighth of a stop a
|
||||
/// ramp's slope varies by under a third, as the remapping itself makes it).
|
||||
const REF_STEP: f32 = 0.125;
|
||||
pub const REF_STEP: f32 = 0.125;
|
||||
/// Most reference values one filter uses.
|
||||
pub const MAX_REFS: usize = 96;
|
||||
/// The lowest reference sits at this quantile of the log luminance: the deepest 0.1 % (noise down
|
||||
/// to the floor) share it instead of stretching the spacing.
|
||||
pub const REF_LOW_QUANTILE: f32 = 0.001;
|
||||
/// The filter works on `log2(luminance + LOG_FLOOR)`.
|
||||
pub const LOG_FLOOR: f32 = 1.0 / 65536.0;
|
||||
/// The filter runs on a copy at most this many pixels across; the change it makes is brought back
|
||||
/// to full size by a guided upsampling, so a preview and the full image agree.
|
||||
const WORK_SIDE: usize = 1600;
|
||||
pub const WORK_SIDE: usize = 1600;
|
||||
/// The image range the strengths are placed in: these quantiles of the log luminance averaged
|
||||
/// over cells of a copy at most [`RANGE_SIDE`] pixels across.
|
||||
pub const RANGE_QUANTILES: [f32; 2] = [0.01, 0.99];
|
||||
/// See [`RANGE_QUANTILES`].
|
||||
pub const RANGE_SIDE: usize = 256;
|
||||
/// Knots of the strength curves over the surroundings' place in the image range (0 … 1).
|
||||
const KNOTS: usize = 5;
|
||||
pub const KNOTS: usize = 5;
|
||||
|
||||
/// Shadows: how far a pixel darker than its surroundings rises, in stops per unit slider, as
|
||||
/// a function of its own place in the image range (`own`) times a factor of its surroundings'
|
||||
@@ -59,6 +71,86 @@ struct Side {
|
||||
sigma: f32,
|
||||
}
|
||||
|
||||
/// Which remapping a [`TonePass`] uses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ToneKind {
|
||||
/// Pixels brighter than their surroundings move toward them (or away, for positive values)
|
||||
/// by the part of the difference past `sigma`.
|
||||
Highlights,
|
||||
/// Pixels darker than their surroundings rise (or sink) by an amount set by their own and
|
||||
/// their surroundings' place in the image range.
|
||||
Shadows,
|
||||
}
|
||||
|
||||
/// One pass of the filter resolved for a slider value: everything its remapping reads.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TonePass {
|
||||
pub kind: ToneKind,
|
||||
/// Highlights: the slider / 100. Shadows: its strength (the slider / 100, times `down` when
|
||||
/// negative).
|
||||
pub amount: f32,
|
||||
/// Highlights: the strengths for the slider's direction, then an unused row. Shadows: the
|
||||
/// curves over the pixel's own (`own`) and its surroundings' (`around`) place.
|
||||
pub knots: [[f32; KNOTS]; 2],
|
||||
/// The detail threshold in stops.
|
||||
pub sigma: f32,
|
||||
/// The quantile of the log luminance the pass puts back where it was.
|
||||
pub keep: f32,
|
||||
}
|
||||
|
||||
/// Shadows and Highlights resolved: Highlights runs first, then Shadows on its result.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LocalTone {
|
||||
pub passes: Vec<TonePass>,
|
||||
}
|
||||
|
||||
impl LocalTone {
|
||||
/// The passes for the sliders (−100 … 100); `None` when both are 0.
|
||||
pub fn new(shadows: f32, highlights: f32) -> Option<Self> {
|
||||
let mut passes = Vec::new();
|
||||
if highlights != 0.0 {
|
||||
let amount = highlights.clamp(-100.0, 100.0) / 100.0;
|
||||
let strengths = if amount < 0.0 { HIGHLIGHTS.pull } else { HIGHLIGHTS.push };
|
||||
// Then the darkest content is put back where it was.
|
||||
passes.push(TonePass { kind: ToneKind::Highlights, amount, knots: [strengths, [0.0; KNOTS]], sigma: HIGHLIGHTS.sigma, keep: 0.01 });
|
||||
}
|
||||
if shadows != 0.0 {
|
||||
let amount = shadows.clamp(-100.0, 100.0) / 100.0;
|
||||
let k = if amount > 0.0 { amount } else { amount * SHADOWS.down };
|
||||
// Keep the brightest content.
|
||||
passes.push(TonePass { kind: ToneKind::Shadows, amount: k, knots: [SHADOWS.own, SHADOWS.around], sigma: SHADOWS.sigma, keep: 0.99 });
|
||||
}
|
||||
(!passes.is_empty()).then_some(LocalTone { passes })
|
||||
}
|
||||
}
|
||||
|
||||
impl TonePass {
|
||||
/// The remapping of log luminance `x` around the reference `g`, in an image range that
|
||||
/// starts at `lo` and is `span` stops wide.
|
||||
pub fn remap(&self, x: f32, g: f32, lo: f32, span: f32) -> f32 {
|
||||
match self.kind {
|
||||
ToneKind::Highlights => x + knot((g - lo) / span, &self.knots[0]) * self.amount * excess((x - g).max(0.0), self.sigma),
|
||||
ToneKind::Shadows => {
|
||||
let below = ((g - x) / self.sigma).clamp(0.0, 1.0);
|
||||
if below == 0.0 {
|
||||
return x;
|
||||
}
|
||||
let w = below * below * (3.0 - 2.0 * below);
|
||||
x + self.amount * knot((x - lo) / span, &self.knots[0]) * knot((g - lo) / span, &self.knots[1]) * w
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pass on the log luminance `u`: the filter, then the kept quantile put back.
|
||||
fn run(&self, u: &Plane) -> Plane {
|
||||
let (lo, hi) = range(u);
|
||||
let span = (hi - lo).max(1.0);
|
||||
let o = llf(u, |x, g| self.remap(x, g, lo, span));
|
||||
let shift = quantile(&u.v, self.keep) - quantile(&o.v, self.keep);
|
||||
Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() }
|
||||
}
|
||||
}
|
||||
|
||||
/// One channel, `w × h`.
|
||||
struct Plane {
|
||||
w: usize,
|
||||
@@ -77,7 +169,8 @@ fn mirror(i: isize, n: usize) -> usize {
|
||||
(if m >= n { p - m } else { m }) as usize
|
||||
}
|
||||
|
||||
const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];
|
||||
/// The pyramid's binomial kernel.
|
||||
pub const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];
|
||||
|
||||
/// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per
|
||||
/// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's
|
||||
@@ -230,14 +323,13 @@ fn gaussian(p: Plane, n: usize) -> Vec<Plane> {
|
||||
fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane {
|
||||
let n = depth(u.w, u.h);
|
||||
let g = gaussian(Plane { w: u.w, h: u.h, v: u.v.clone() }, n);
|
||||
// References span the image's tones; the deepest 0.1 % (noise down to the floor) share the
|
||||
// lowest reference instead of stretching the spacing.
|
||||
// References span the image's tones (see `REF_LOW_QUANTILE`).
|
||||
let hi = u.v.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v));
|
||||
let lo = quantile(&u.v, 0.001).min(hi);
|
||||
let lo = quantile(&u.v, REF_LOW_QUANTILE).min(hi);
|
||||
if hi - lo <= 1e-6 || (hi - lo).is_nan() {
|
||||
return Plane { w: u.w, h: u.h, v: u.v.clone() };
|
||||
}
|
||||
let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, 96);
|
||||
let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, MAX_REFS);
|
||||
let step = (hi - lo) / (refs - 1) as f32;
|
||||
let mut lap: Vec<Vec<f32>> = g[..n - 1].iter().map(|p| vec![0.0; p.v.len()]).collect();
|
||||
for k in 0..refs {
|
||||
@@ -279,13 +371,14 @@ fn quantile(v: &[f32], q: f32) -> f32 {
|
||||
let mut s = v.to_vec();
|
||||
// Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a
|
||||
// fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element.
|
||||
let i = ((s.len() - 1) as f32 * q).round() as usize;
|
||||
let i = quantile_rank(s.len(), q);
|
||||
*s.select_nth_unstable_by(i, f32::total_cmp).1
|
||||
}
|
||||
|
||||
/// 1st and 99th percentiles of the log luminance on a copy at most 256 pixels across.
|
||||
/// The image range: [`RANGE_QUANTILES`] of the log luminance on a copy at most [`RANGE_SIDE`]
|
||||
/// pixels across.
|
||||
fn range(u: &Plane) -> (f32, f32) {
|
||||
let f = u.w.max(u.h).div_ceil(256).max(1);
|
||||
let f = u.w.max(u.h).div_ceil(RANGE_SIDE).max(1);
|
||||
let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f));
|
||||
let mut sum = vec![(0.0f64, 0u32); sw * sh];
|
||||
for y in 0..u.h {
|
||||
@@ -296,7 +389,7 @@ fn range(u: &Plane) -> (f32, f32) {
|
||||
}
|
||||
}
|
||||
let cells: Vec<f32> = sum.iter().filter(|c| c.1 > 0).map(|c| (c.0 / f64::from(c.1)) as f32).collect();
|
||||
(quantile(&cells, 0.01), quantile(&cells, 0.99))
|
||||
(quantile(&cells, RANGE_QUANTILES[0]), quantile(&cells, RANGE_QUANTILES[1]))
|
||||
}
|
||||
|
||||
/// `d` past the detail threshold: about 0 below `sigma`, `d − sigma` well above it.
|
||||
@@ -310,52 +403,19 @@ fn knot(t: f32, k: &[f32; KNOTS]) -> f32 {
|
||||
k[i] + (k[i + 1] - k[i]) * (x - i as f32)
|
||||
}
|
||||
|
||||
/// The Highlights pass on the log luminance `u` (`amount` −1 … 1): pixels brighter than their
|
||||
/// surroundings move toward them (or away, for positive values) by the part of the difference
|
||||
/// past `sigma`, then the darkest content is put back where it was.
|
||||
fn highlights_pass(u: &Plane, amount: f32, side: &Side) -> Plane {
|
||||
let (lo, hi) = range(u);
|
||||
let span = (hi - lo).max(1.0);
|
||||
let strengths = if amount < 0.0 { &side.pull } else { &side.push };
|
||||
let o = llf(u, |x, g| x + knot((g - lo) / span, strengths) * amount * excess((x - g).max(0.0), side.sigma));
|
||||
let shift = quantile(&u.v, 0.01) - quantile(&o.v, 0.01);
|
||||
Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() }
|
||||
}
|
||||
|
||||
/// The Shadows pass on the log luminance `u` (`amount` −1 … 1).
|
||||
fn shadows_pass(u: &Plane, amount: f32) -> Plane {
|
||||
let (lo, hi) = range(u);
|
||||
let span = (hi - lo).max(1.0);
|
||||
let k = if amount > 0.0 { amount } else { amount * SHADOWS.down };
|
||||
let o = llf(u, |x, g| {
|
||||
let below = ((g - x) / SHADOWS.sigma).clamp(0.0, 1.0);
|
||||
if below == 0.0 {
|
||||
return x;
|
||||
}
|
||||
let w = below * below * (3.0 - 2.0 * below);
|
||||
x + k * knot((x - lo) / span, &SHADOWS.own) * knot((g - lo) / span, &SHADOWS.around) * w
|
||||
});
|
||||
// Keep the brightest content.
|
||||
let shift = quantile(&u.v, 0.99) - quantile(&o.v, 0.99);
|
||||
Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() }
|
||||
}
|
||||
|
||||
/// Applies Shadows and Highlights (−100 … 100) to straight RGBA pixels encoded with `enc`.
|
||||
pub(crate) fn apply(px: &mut [[f32; 4]], w: usize, h: usize, shadows: f32, highlights: f32, enc: Encoding) {
|
||||
if (shadows == 0.0 && highlights == 0.0) || w < 2 || h < 2 {
|
||||
let Some(tone) = LocalTone::new(shadows, highlights) else { return };
|
||||
if w < 2 || h < 2 {
|
||||
return;
|
||||
}
|
||||
const FLOOR: f32 = 1.0 / 65536.0;
|
||||
let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + FLOOR).log2()).collect() };
|
||||
let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + LOG_FLOOR).log2()).collect() };
|
||||
// The filter on a copy at most WORK_SIDE across (box-averaged in log).
|
||||
let f = w.max(h).div_ceil(WORK_SIDE).max(1);
|
||||
let small = if f == 1 { Plane { w, h, v: u.v.clone() } } else { shrink(&u, f) };
|
||||
let mut o = Plane { w: small.w, h: small.h, v: small.v.clone() };
|
||||
if highlights != 0.0 {
|
||||
o = highlights_pass(&o, highlights.clamp(-100.0, 100.0) / 100.0, &HIGHLIGHTS);
|
||||
}
|
||||
if shadows != 0.0 {
|
||||
o = shadows_pass(&o, shadows.clamp(-100.0, 100.0) / 100.0);
|
||||
for pass in &tone.passes {
|
||||
o = pass.run(&o);
|
||||
}
|
||||
// The change in log luminance, at full size.
|
||||
let change: Vec<f32> = if f == 1 {
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
//! Develop's per-pixel stages resolved for one image: every constant and table they use, so
|
||||
//! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so
|
||||
//! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the
|
||||
//! same maths. [`develop`](super::develop) builds its own constants with the same functions.
|
||||
//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture
|
||||
//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`].
|
||||
|
||||
use super::local_tone::{LocalTone, WORK_SIDE};
|
||||
use super::spatial::{Clarity, Dehaze, Texture};
|
||||
use super::{CameraRaw, Encoding, Wheel, curve_lut, hsv_to_rgb, is_linear, luma, parametric_lut, white_balance_gains, whites_blacks};
|
||||
|
||||
pub use whites_blacks::Model as WhitesBlacksModel;
|
||||
|
||||
/// Entries of the tone curve tables (parametric and point curves).
|
||||
pub const CURVE_LUT: usize = 1024;
|
||||
/// Samples of a Whites or Blacks curve row: grey levels 0, 1/32, …, 1.
|
||||
@@ -19,11 +25,16 @@ pub(crate) fn gains(p: &CameraRaw) -> Option<[f32; 3]> {
|
||||
Some(g.map(|v| v / norm * 2f32.powf(p.exposure)))
|
||||
}
|
||||
|
||||
/// Contrast's strength, when Contrast is set.
|
||||
/// Contrast's strength, when Contrast is set (with or without Texture and Clarity).
|
||||
fn contrast(p: &CameraRaw) -> Option<f32> {
|
||||
(p.contrast != 0.0).then_some(p.contrast / 100.0 * 0.6)
|
||||
}
|
||||
|
||||
/// Whites and Blacks' tables, for an implementation that measures the image's points itself.
|
||||
pub fn whites_blacks_model() -> WhitesBlacksModel {
|
||||
whites_blacks::model()
|
||||
}
|
||||
|
||||
/// Whites and Blacks as two curve rows for the image's amounts.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WhitesBlacks {
|
||||
@@ -149,10 +160,23 @@ impl Grain {
|
||||
pub struct PerPixel {
|
||||
/// 1. White balance and exposure gains in linear light (sRGB-decoded values).
|
||||
pub gains: Option<[f32; 3]>,
|
||||
/// 3. Contrast's strength (Contrast without Texture or Clarity is per pixel).
|
||||
/// 2. Dehaze.
|
||||
pub dehaze: Option<Dehaze>,
|
||||
/// 3. Shadows and Highlights: a local Laplacian filter of the whole frame, then each pixel's
|
||||
/// light scaled by the change of its log luminance.
|
||||
pub local_tone: Option<LocalTone>,
|
||||
/// 3. Clarity and Texture on the luminance clipped to 1, before Contrast.
|
||||
pub clarity: Option<Clarity>,
|
||||
pub texture: Option<Texture>,
|
||||
/// 3. Contrast's strength.
|
||||
pub contrast: Option<f32>,
|
||||
/// 3b. Whites and Blacks, in the document's encoding.
|
||||
pub whites_blacks: Option<WhitesBlacks>,
|
||||
/// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a
|
||||
/// spatial stage is set: the points then depend on its output, so whatever runs it
|
||||
/// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is
|
||||
/// then `None`.
|
||||
pub measure_whites_blacks: Option<[f32; 2]>,
|
||||
/// The document's transfer curve: 0 for sRGB's, else a power-law gamma.
|
||||
pub encoding: f32,
|
||||
/// 4. Vibrance and Saturation (slider / 100).
|
||||
@@ -183,6 +207,11 @@ impl CameraRaw {
|
||||
|| self.noise_luminance > 0.0
|
||||
|| self.noise_color > 0.0
|
||||
}
|
||||
|
||||
/// Whether developing needs Detail: sharpening or noise reduction.
|
||||
fn detail_on(&self) -> bool {
|
||||
self.sharpen_amount > 0.0 || self.noise_luminance > 0.0 || self.noise_color > 0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`,
|
||||
@@ -201,16 +230,28 @@ pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw) ->
|
||||
}))
|
||||
}
|
||||
|
||||
/// Develop's stages for settings without spatial stages, on a `w × h` image; `points` are the
|
||||
/// image's [`white_black_points`]. `None` when `p` needs a spatial stage or Calibration (these
|
||||
/// stages don't run it), or Whites or Blacks is set without `points`. The points themselves
|
||||
/// leave Calibration out, so a caller may cache them across Calibration changes.
|
||||
/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are
|
||||
/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages
|
||||
/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the
|
||||
/// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks
|
||||
/// without a spatial stage and without `points`. The points themselves leave Calibration out, so a
|
||||
/// caller may cache them across Calibration changes.
|
||||
pub fn per_pixel(p: &CameraRaw, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option<PerPixel> {
|
||||
if p.spatial() || !p.calibration_neutral() {
|
||||
if p.detail_on() || !p.calibration_neutral() {
|
||||
return None;
|
||||
}
|
||||
// The develop leaves frames under 2 pixels on a side alone.
|
||||
let local_tone = if w >= 2 && h >= 2 { LocalTone::new(p.shadows, p.highlights) } else { None };
|
||||
// At 2 pixels on the short side the GPU pass's pyramid has one level, so the CPU develops it.
|
||||
if local_tone.is_some() && (w.max(h) > WORK_SIDE || w.min(h) <= 2) {
|
||||
return None;
|
||||
}
|
||||
let (dehaze, clarity, texture) = (Dehaze::new(p, w, h), Clarity::new(p, w, h), Texture::new(p, w, h));
|
||||
let spatial = local_tone.is_some() || dehaze.is_some() || clarity.is_some() || texture.is_some();
|
||||
let identity = p.is_identity();
|
||||
let whites_blacks = if p.whites != 0.0 || p.blacks != 0.0 {
|
||||
let wb_on = p.whites != 0.0 || p.blacks != 0.0;
|
||||
let measure_whites_blacks = (wb_on && spatial).then(|| [p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0)]);
|
||||
let whites_blacks = if wb_on && measure_whites_blacks.is_none() {
|
||||
let (bp, wp) = points?;
|
||||
let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp);
|
||||
(xw != 0.0 || xb != 0.0).then(|| WhitesBlacks {
|
||||
@@ -225,8 +266,13 @@ pub fn per_pixel(p: &CameraRaw, w: usize, h: usize, float: bool, points: Option<
|
||||
let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, CURVE_LUT));
|
||||
Some(PerPixel {
|
||||
gains: gains(p),
|
||||
dehaze,
|
||||
local_tone,
|
||||
clarity,
|
||||
texture,
|
||||
contrast: contrast(p),
|
||||
whites_blacks,
|
||||
measure_whites_blacks,
|
||||
encoding: Encoding::of(p.encoding_gamma).0,
|
||||
presence: (p.vibrance != 0.0 || p.saturation != 0.0).then_some([p.vibrance / 100.0, p.saturation / 100.0]),
|
||||
parametric: parametric_on.then(|| parametric_lut(p, CURVE_LUT)),
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their
|
||||
//! filters use, so another implementation of them (the GPU preview,
|
||||
//! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds
|
||||
//! its own from the same constructors.
|
||||
//!
|
||||
//! - **Dehaze** follows the dark channel prior (K. He, J. Sun, X. Tang, *Single Image Haze Removal
|
||||
//! Using Dark Channel Prior*, CVPR 2009) on a box-averaged copy at most [`DEHAZE_SIDE`] pixels
|
||||
//! across, with the transmission refined by a guided filter (K. He, J. Sun, X. Tang, *Guided
|
||||
//! Image Filtering*, ECCV 2010) and brought back to full size bilinearly.
|
||||
//! - **Clarity** raises the luminance's difference from a fast guided filter of itself (K. He,
|
||||
//! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones.
|
||||
//! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to
|
||||
//! ±[`TEXTURE_LIMIT`].
|
||||
|
||||
use super::CameraRaw;
|
||||
|
||||
/// Dehaze measures the haze on a copy at most this many pixels across.
|
||||
pub const DEHAZE_SIDE: usize = 768;
|
||||
/// The dark channel's minimum filter has a radius of the copy's long side over this, at least
|
||||
/// [`DEHAZE_MIN_RADIUS`].
|
||||
pub const DEHAZE_RADIUS_DIVISOR: usize = 60;
|
||||
/// See [`DEHAZE_RADIUS_DIVISOR`].
|
||||
pub const DEHAZE_MIN_RADIUS: usize = 2;
|
||||
/// The atmospheric light is the mean colour of the brightest 1 / this of the dark channel (at
|
||||
/// least one cell).
|
||||
pub const DEHAZE_AIR_FRACTION: usize = 1000;
|
||||
/// Each channel of the atmospheric light is at least this.
|
||||
pub const DEHAZE_AIR_FLOOR: f32 = 0.2;
|
||||
/// The share of the haze the raw transmission removes (the paper's ω).
|
||||
pub const DEHAZE_OMEGA: f32 = 0.95;
|
||||
/// The guided filter's regularisation for the transmission.
|
||||
pub const DEHAZE_EPS: f32 = 1e-3;
|
||||
/// The transmission is at least this.
|
||||
pub const DEHAZE_T_FLOOR: f32 = 0.1;
|
||||
/// Clarity's guided filter regularisation.
|
||||
pub const CLARITY_EPS: f32 = 0.005;
|
||||
/// Texture moves the luminance by at most this.
|
||||
pub const TEXTURE_LIMIT: f32 = 0.1;
|
||||
|
||||
/// Dehaze on a `w × h` frame.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Dehaze {
|
||||
/// The slider / 100 (−1 … 1).
|
||||
pub amount: f32,
|
||||
/// The copy averages `factor × factor` blocks.
|
||||
pub factor: usize,
|
||||
/// The copy's size.
|
||||
pub size: [usize; 2],
|
||||
/// The minimum filter's radius.
|
||||
pub radius: usize,
|
||||
/// The guided filter's radius.
|
||||
pub guide_radius: usize,
|
||||
/// How many of the copy's cells the atmospheric light averages.
|
||||
pub top: usize,
|
||||
}
|
||||
|
||||
impl Dehaze {
|
||||
/// Dehaze for `p` on a `w × h` frame; `None` when it is off.
|
||||
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
|
||||
if p.dehaze == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let factor = w.max(h).div_ceil(DEHAZE_SIDE).max(1);
|
||||
let size = [w.div_ceil(factor), h.div_ceil(factor)];
|
||||
let radius = (size[0].max(size[1]) / DEHAZE_RADIUS_DIVISOR).max(DEHAZE_MIN_RADIUS);
|
||||
Some(Dehaze { amount: p.dehaze / 100.0, factor, size, radius, guide_radius: radius * 2, top: (size[0] * size[1] / DEHAZE_AIR_FRACTION).max(1) })
|
||||
}
|
||||
|
||||
/// The copy the haze is measured on, for `px` (`w × h`, display-encoded) before white balance
|
||||
/// and exposure (`gains`, as in [`PerPixel`](super::PerPixel)): `size` cells in rows, each the
|
||||
/// mean light of its block, clipped to 0 … 1. These are exactly the cells
|
||||
/// [`develop`](super::develop) uses: the brightest of them set the atmospheric light, and a
|
||||
/// tie between them decides which, so another implementation that computes stage 1 to a few
|
||||
/// ulps should start from these. Empty when `px` isn't `w × h`.
|
||||
pub fn cells(&self, px: &[[f32; 4]], w: usize, h: usize, gains: Option<[f32; 3]>) -> Vec<[f32; 3]> {
|
||||
if px.len() != w.saturating_mul(h) || w.div_ceil(self.factor) != self.size[0] || h.div_ceil(self.factor) != self.size[1] {
|
||||
return Vec::new();
|
||||
}
|
||||
super::haze_cells(px, w, h, self, |q| gains.map_or(q, |g| super::balance(q, g)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Clarity on a `w × h` frame.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Clarity {
|
||||
/// The strength: the slider / 100 × 0.8.
|
||||
pub amount: f32,
|
||||
/// The guided filter's radius at full size.
|
||||
pub radius: usize,
|
||||
/// The fast guided filter works on `subsample × subsample` block means…
|
||||
pub subsample: usize,
|
||||
/// …with this radius…
|
||||
pub sub_radius: usize,
|
||||
/// …at this size.
|
||||
pub sub_size: [usize; 2],
|
||||
}
|
||||
|
||||
impl Clarity {
|
||||
/// Clarity for `p` on a `w × h` frame; `None` when it is off.
|
||||
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
|
||||
if p.clarity == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let radius = ((w.max(h) as f32 * 0.02) as usize).max(3);
|
||||
let (subsample, sub_radius) = fast_guided_steps(radius);
|
||||
Some(Clarity { amount: p.clarity / 100.0 * 0.8, radius, subsample, sub_radius, sub_size: [w.div_ceil(subsample), h.div_ceil(subsample)] })
|
||||
}
|
||||
}
|
||||
|
||||
/// The fast guided filter's subsampling and its radius there, for radius `r` at full size. A
|
||||
/// subsampling of 1 is the plain guided filter at radius `r`.
|
||||
pub fn fast_guided_steps(r: usize) -> (usize, usize) {
|
||||
let s = (r / 8).clamp(1, 8);
|
||||
(s, if s == 1 { r } else { (r / s).max(1) })
|
||||
}
|
||||
|
||||
/// Texture on a `w × h` frame.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Texture {
|
||||
/// The strength: the slider / 100 × 0.9.
|
||||
pub amount: f32,
|
||||
/// The blur's box radii, in order; empty when the blur is too small to change anything.
|
||||
pub radii: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Texture {
|
||||
/// Texture for `p` on a `w × h` frame; `None` when it is off.
|
||||
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
|
||||
if p.texture == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let ps = p.pixel_scale.clamp(0.01, 1.0);
|
||||
let sigma = (w.max(h) as f32 * 0.002).max(1.5 * ps);
|
||||
Some(Texture { amount: p.texture / 100.0 * 0.9, radii: gauss_radii(sigma) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The box radii of develop's Gaussian of `sigma`: none below 0.3.
|
||||
pub(crate) fn gauss_radii(sigma: f32) -> Vec<usize> {
|
||||
if sigma < 0.3 {
|
||||
return Vec::new();
|
||||
}
|
||||
crate::fxutil::gauss_box_radii(sigma).to_vec()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stages_resolve_for_the_dialogs_proxy_and_are_off_at_zero() {
|
||||
let p = CameraRaw { dehaze: 40.0, clarity: -50.0, texture: 50.0, pixel_scale: 0.143, ..Default::default() };
|
||||
let d = Dehaze::new(&p, 858, 572).unwrap();
|
||||
assert_eq!((d.factor, d.size, d.radius, d.guide_radius, d.top), (2, [429, 286], 7, 14, 122));
|
||||
let c = Clarity::new(&p, 858, 572).unwrap();
|
||||
assert_eq!((c.radius, c.subsample, c.sub_radius, c.sub_size), (17, 2, 8, [429, 286]));
|
||||
assert!((c.amount + 0.4).abs() < 1e-6);
|
||||
assert_eq!(Texture::new(&p, 858, 572).unwrap().radii, [1, 1, 2]);
|
||||
// Small frames: the plain guided filter, a blur too narrow to change anything.
|
||||
assert_eq!(fast_guided_steps(3), (1, 3));
|
||||
assert!(Texture::new(&CameraRaw { texture: 10.0, pixel_scale: 0.1, ..Default::default() }, 64, 48).unwrap().radii.is_empty());
|
||||
let off = CameraRaw::default();
|
||||
assert!(Dehaze::new(&off, 858, 572).is_none() && Clarity::new(&off, 858, 572).is_none() && Texture::new(&off, 858, 572).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() {
|
||||
let d = Dehaze::new(&CameraRaw { dehaze: 10.0, ..Default::default() }, 3, 1).unwrap();
|
||||
let px = [[0.2, 0.4, 1.5, 1.0], [0.4, 0.0, 0.5, 1.0], [0.9, 0.9, 0.9, 1.0]];
|
||||
assert_eq!(d.cells(&px, 3, 1, None), vec![[0.2, 0.4, 1.0], [0.4, 0.0, 0.5], [0.9, 0.9, 0.9]]);
|
||||
let brighter = d.cells(&px, 3, 1, Some([2.0, 2.0, 2.0]));
|
||||
assert!(brighter[0][0] > 0.2 && brighter[2] == [1.0; 3]);
|
||||
assert!(d.cells(&px[..2], 3, 1, None).is_empty());
|
||||
assert!(d.cells(&px, 1, 3, None).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -25,9 +25,66 @@ use crate::photo_util::par_rows;
|
||||
|
||||
/// Grey levels the curves are sampled at: 0, 1/32, …, 1 (sRGB-encoded).
|
||||
pub(crate) const STEPS: usize = 33;
|
||||
/// The first row's internal amount; rows are 10 apart.
|
||||
/// The first row's internal amount; rows are [`ROW_STEP`] apart.
|
||||
const WHITES_FROM: f32 = -100.0;
|
||||
const BLACKS_FROM: f32 = -100.0;
|
||||
const ROW_STEP: f32 = 10.0;
|
||||
/// The image's points are measured on cells of a copy at most this many pixels across.
|
||||
pub(crate) const POINTS_SIDE: usize = 256;
|
||||
/// The black point's quantile of the cells' luminance, the white point's of their brightest
|
||||
/// channel.
|
||||
pub(crate) const POINT_QUANTILES: [f32; 2] = [0.03, 0.995];
|
||||
/// Internal amounts the sliders reach: Whites, then Blacks.
|
||||
const WHITES_RANGE: [f32; 2] = [-100.0, 270.0];
|
||||
const BLACKS_RANGE: [f32; 2] = [-100.0, 100.0];
|
||||
|
||||
/// Whites and Blacks' tables and how an image's points choose from them, for another
|
||||
/// implementation (the GPU preview measures the points after Shadows and Highlights itself).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Model {
|
||||
/// Whites curves over grey levels 0, 1/32, …, 1, at internal amounts `whites_from`,
|
||||
/// `whites_from + row_step`, ….
|
||||
pub whites: &'static [[f32; STEPS]],
|
||||
pub whites_from: f32,
|
||||
/// Blacks curves, likewise.
|
||||
pub blacks: &'static [[f32; STEPS]],
|
||||
pub blacks_from: f32,
|
||||
pub row_step: f32,
|
||||
/// Black points and white points of the adaptation tables' rows and columns.
|
||||
pub black_points: &'static [f32],
|
||||
pub white_points: &'static [f32],
|
||||
/// How much the clipping directions adapt (Whites up, Blacks down), by black and white point.
|
||||
pub whites_adapt: &'static [[f32; 8]; 9],
|
||||
pub blacks_adapt: &'static [[f32; 8]; 9],
|
||||
/// The least Blacks adaptation on photographs.
|
||||
pub photo_blacks: f32,
|
||||
/// Internal amounts the Whites and Blacks sliders reach.
|
||||
pub whites_range: [f32; 2],
|
||||
pub blacks_range: [f32; 2],
|
||||
/// See [`POINTS_SIDE`] and [`POINT_QUANTILES`].
|
||||
pub points_side: usize,
|
||||
pub point_quantiles: [f32; 2],
|
||||
}
|
||||
|
||||
/// The tables [`amounts`], [`whites_row`] and [`blacks_row`] read.
|
||||
pub(crate) fn model() -> Model {
|
||||
Model {
|
||||
whites: &WHITES,
|
||||
whites_from: WHITES_FROM,
|
||||
blacks: &BLACKS,
|
||||
blacks_from: BLACKS_FROM,
|
||||
row_step: ROW_STEP,
|
||||
black_points: &BPS,
|
||||
white_points: &WPS,
|
||||
whites_adapt: &AW,
|
||||
blacks_adapt: &AB,
|
||||
photo_blacks: PHOTO_BLACKS,
|
||||
whites_range: WHITES_RANGE,
|
||||
blacks_range: BLACKS_RANGE,
|
||||
points_side: POINTS_SIDE,
|
||||
point_quantiles: POINT_QUANTILES,
|
||||
}
|
||||
}
|
||||
// Measured levels; some happen to lie near π/8 and π/4.
|
||||
/// Whites curves at internal amounts -100, -90, …, 270 (rows) over grey levels 0, 1/32, …, 1.
|
||||
#[allow(clippy::approx_constant)]
|
||||
@@ -303,7 +360,7 @@ fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 {
|
||||
if v >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let r = ((x - from) / 10.0).clamp(0.0, (rows.len() - 1) as f32);
|
||||
let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32);
|
||||
let i = (r as usize).min(rows.len() - 2);
|
||||
let t = r - i as f32;
|
||||
let at = |row: &[f32; STEPS]| {
|
||||
@@ -318,7 +375,7 @@ fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 {
|
||||
/// The curve at a fractional internal amount `x` as one row: `curve(rows, from, x, v)` is this
|
||||
/// row interpolated at `v`, because both interpolations are linear.
|
||||
fn row_at(rows: &[[f32; STEPS]], from: f32, x: f32) -> [f32; STEPS] {
|
||||
let r = ((x - from) / 10.0).clamp(0.0, (rows.len() - 1) as f32);
|
||||
let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32);
|
||||
let i = (r as usize).min(rows.len() - 2);
|
||||
let t = r - i as f32;
|
||||
std::array::from_fn(|j| rows[i][j] * (1.0 - t) + rows[i + 1][j] * t)
|
||||
@@ -367,7 +424,7 @@ pub(crate) fn amounts(whites: f32, blacks: f32, bp: f32, wp: f32) -> (f32, f32)
|
||||
// On photographs Photoshop's Blacks is about 1.2 times the block images' amount even where
|
||||
// their black point is 0 (ten public-domain photos: 1.08–1.36).
|
||||
let b = if blacks < 0.0 { blacks * adapt(&AB, bp, wp).max(PHOTO_BLACKS) } else { blacks };
|
||||
(w.clamp(-100.0, 270.0), b.clamp(-100.0, 100.0))
|
||||
(w.clamp(WHITES_RANGE[0], WHITES_RANGE[1]), b.clamp(BLACKS_RANGE[0], BLACKS_RANGE[1]))
|
||||
}
|
||||
|
||||
/// Applies Whites and Blacks (internal amounts `w`, `b`) to straight RGBA pixels (`width` per
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
//! Native deterministic channel-wise additive or signal-relative noise.
|
||||
pub use crate::coverage::Error;
|
||||
use crate::{Ctx, Distribution, image::Image};
|
||||
use photocraft_color::{PixelFormat, SampleType};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Params {
|
||||
pub amounts: Vec<f32>,
|
||||
pub distribution: Distribution,
|
||||
pub monochromatic: bool,
|
||||
pub relative: bool,
|
||||
pub seed: u32,
|
||||
}
|
||||
/// Require one finite bounded amplitude per native channel and reject unsupported channel counts.
|
||||
pub fn validate(p: &Params, channels: usize) -> Result<(), Error> {
|
||||
if channels == 0 || channels > 5 || p.amounts.len() != channels || p.amounts.iter().any(|v| !v.is_finite() || !(0.0..=400.).contains(v)) {
|
||||
return Err(Error::InvalidParameter);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Validate positive bounded extents with widened arithmetic before calculating a dense noise region.
|
||||
fn dimensions(r: Rect) -> Result<(usize, usize), Error> {
|
||||
let w = i64::from(r.x1) - i64::from(r.x0);
|
||||
let h = i64::from(r.y1) - i64::from(r.y0);
|
||||
if w <= 0 || h <= 0 || w > 65536 || h > 65536 || w.checked_mul(h).is_none_or(|n| n > 64 * 1024 * 1024) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
Ok((w as usize, h as usize))
|
||||
}
|
||||
/// Admit padded output tiles, cloned sparse headers and selection scratch before noise allocation.
|
||||
fn preflight(s: &Surface, area: Rect, selection: Option<&Surface>) -> Result<(), Error> {
|
||||
dimensions(area)?;
|
||||
let count = |lo: i32, hi: i32| -> Result<usize, Error> {
|
||||
usize::try_from((i64::from(hi) - 1).div_euclid(256) - i64::from(lo).div_euclid(256) + 1).map_err(|_| Error::WorkspaceLimit)
|
||||
};
|
||||
let bytes = count(area.x0, area.x1)?
|
||||
.checked_mul(count(area.y0, area.y1)?)
|
||||
.and_then(|n| n.checked_mul(256 * 256 * s.format().bytes_per_pixel() + 128))
|
||||
.and_then(|n| n.checked_add(s.tile_count().checked_mul(128)?))
|
||||
.and_then(|n| n.checked_add(64 * 64 * 4 * (s.channels() * 3 + selection.map_or(0, Surface::channels))))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
if bytes > crate::coverage::MAX_WORKSPACE_BYTES {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Apply coordinate-seeded native noise per channel, preserving zero-amplitude channels and rejecting nonfinite results
|
||||
/// or cancellation.
|
||||
fn pixels(data: &mut [f32], rect: Rect, channels: usize, alpha: bool, p: &Params, ctl: &Interrupt<'_>) -> Result<(), Error> {
|
||||
let (w, h) = dimensions(rect)?;
|
||||
if data.len() != w * h * channels {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
for (i, pixel) in data.chunks_exact_mut(channels).enumerate() {
|
||||
if i.is_multiple_of(1024) && ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let x = (i64::from(rect.x0) + (i % w) as i64) as i32;
|
||||
let y = (i64::from(rect.y0) + (i / w) as i64) as i32;
|
||||
for (c, value) in pixel.iter_mut().enumerate() {
|
||||
if !value.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let amount = *p.amounts.get(c).ok_or(Error::InvalidParameter)?;
|
||||
if amount == 0. {
|
||||
continue;
|
||||
}
|
||||
let channel = if p.monochromatic { 0 } else { c as u32 };
|
||||
let amplitude = amount / 200.;
|
||||
let noise = match p.distribution {
|
||||
Distribution::Uniform => (crate::noise::hash01(x, y, channel, p.seed) - 0.5) * 2. * amplitude,
|
||||
Distribution::Gaussian => {
|
||||
let u1 = crate::noise::hash01(x, y, channel * 2 + 101, p.seed).max(1e-7);
|
||||
let u2 = crate::noise::hash01(x, y, channel * 2 + 102, p.seed);
|
||||
(-2. * u1.ln()).sqrt() * (std::f32::consts::TAU * u2).cos() * amplitude * 0.5
|
||||
}
|
||||
};
|
||||
let delta = if p.relative { f64::from(*value) * f64::from(noise) } else { f64::from(noise) };
|
||||
let result = f64::from(*value) + delta;
|
||||
if !result.is_finite() || result.abs() > f64::from(f32::MAX) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
*value = if alpha && c + 1 == channels { result.clamp(0., 1.) as f32 } else { result as f32 };
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Publish deterministic noise over the clipped domain with selection mixing, checked workspace and no source mutation
|
||||
/// on failure.
|
||||
pub fn apply_with(s: &Surface, p: &Params, area: Rect, domain: Rect, selection: Option<&Surface>, ctl: &Interrupt<'_>) -> Result<Surface, Error> {
|
||||
validate(p, s.channels())?;
|
||||
// The domain clips work; only the clipped publication area needs dense admission.
|
||||
if domain.is_empty() {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
if area.x1 < area.x0 || area.y1 < area.y0 {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let area = area.intersect(&domain);
|
||||
if area.is_empty() {
|
||||
return Ok(s.clone());
|
||||
}
|
||||
preflight(s, area, selection)?;
|
||||
let mut result = s.clone();
|
||||
let mut y = area.y0;
|
||||
while y < area.y1 {
|
||||
let y1 = (i64::from(y) + 64).min(i64::from(area.y1)) as i32;
|
||||
let mut x = area.x0;
|
||||
while x < area.x1 {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let x1 = (i64::from(x) + 64).min(i64::from(area.x1)) as i32;
|
||||
let tile = Rect::new(x, y, x1, y1);
|
||||
let mut data = s.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
pixels(&mut data, tile, s.channels(), s.format().alpha, p, ctl)?;
|
||||
if let Some(selection) = selection {
|
||||
let mask = selection.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
if mask.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let original = Image { rect: tile, ch: s.channels(), data: s.try_read_region(tile).map_err(|_| Error::Allocation)? };
|
||||
crate::mix_selection(&mut data, tile, selection, &original, s.format().alpha);
|
||||
for (pixel, before) in data.chunks_exact_mut(s.channels()).zip(original.data.chunks_exact(s.channels())) {
|
||||
for ((value, original), amount) in pixel.iter_mut().zip(before).zip(&p.amounts) {
|
||||
if *amount == 0. {
|
||||
*value = *original;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if data.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
result.try_write_region(tile, &data).map_err(|_| Error::Allocation)?;
|
||||
x = x1;
|
||||
}
|
||||
y = y1;
|
||||
ctl.progress((i64::from(y) - i64::from(area.y0)) as f32 / (i64::from(area.y1) - i64::from(area.y0)) as f32);
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
/// Copy a contained, structurally valid raw-image region for the infallible adapter's fallback.
|
||||
fn identity(src: &Image, out: Rect) -> Result<Vec<f32>, Error> {
|
||||
let (w, h) = dimensions(src.rect)?;
|
||||
let (ow, oh) = dimensions(out)?;
|
||||
if src.ch == 0 || src.ch > 5 || out.intersect(&src.rect) != out || w.checked_mul(h).and_then(|n| n.checked_mul(src.ch)) != Some(src.data.len()) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let count = ow
|
||||
.checked_mul(oh)
|
||||
.and_then(|n| n.checked_mul(src.ch))
|
||||
.filter(|n| n.checked_mul(4).is_some_and(|b| b <= crate::coverage::MAX_WORKSPACE_BYTES))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
let mut output = Vec::new();
|
||||
output.try_reserve_exact(count).map_err(|_| Error::Allocation)?;
|
||||
for y in out.y0..out.y1 {
|
||||
let start = ((i64::from(y) - i64::from(src.rect.y0)) as usize * w + (i64::from(out.x0) - i64::from(src.rect.x0)) as usize) * src.ch;
|
||||
output.extend_from_slice(src.data.get(start..start + ow * src.ch).ok_or(Error::InvalidGeometry)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
/// Raw compatibility retains exact-shaped identity on a rejected operation. Checked
|
||||
/// Surface callers propagate the error and never publish an unsuccessful edit.
|
||||
pub(crate) fn run_image(src: &Image, out: Rect, ctx: &Ctx, p: &Params) -> Vec<f32> {
|
||||
let run = || -> Result<Vec<f32>, Error> {
|
||||
validate(p, src.ch)?;
|
||||
if PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha).channels() != src.ch {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let mut output = identity(src, out)?;
|
||||
pixels(&mut output, out, src.ch, ctx.alpha, p, &Interrupt::NONE)?;
|
||||
Ok(output)
|
||||
};
|
||||
run().unwrap_or_else(|_| identity(src, out).unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_color::ColorMode;
|
||||
#[test]
|
||||
/// Admit a small noise edit on a large owner while retaining output-size and invalid-domain checks.
|
||||
fn small_noise_area_in_large_domain_keeps_work_bounds() {
|
||||
let area = Rect::new(11, 13, 13, 15);
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, area);
|
||||
let params = p(vec![40., 80., 0., 0.]);
|
||||
let domain = Rect::new(0, 0, 12_000, 8_000);
|
||||
let got = apply_with(&s, ¶ms, area, domain, None, &Interrupt::NONE).unwrap();
|
||||
let expected = apply_with(&s, ¶ms, area, area, None, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(got, expected);
|
||||
assert_eq!(apply_with(&s, ¶ms, domain, domain, None, &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
assert_eq!(apply_with(&s, ¶ms, area, Rect::new(1, 1, 0, 0), None, &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
}
|
||||
/// Supply a reproducible uniform-noise configuration with independent channels and a fixed seed.
|
||||
fn p(amounts: Vec<f32>) -> Params {
|
||||
Params { amounts, distribution: Distribution::Uniform, monochromatic: false, relative: false, seed: 71 }
|
||||
}
|
||||
/// Build a half-valued native surface so noise amplitudes and unchanged channels have explicit expected baselines.
|
||||
fn surface(mode: ColorMode, depth: SampleType, r: Rect) -> Surface {
|
||||
let fmt = PixelFormat::new(mode, depth, true);
|
||||
let mut s = Surface::new(fmt);
|
||||
s.fill_rect(r, &vec![0.5; fmt.channels()]);
|
||||
s
|
||||
}
|
||||
#[test]
|
||||
/// Compare uniform/Gaussian output to the existing native noise function and separately bound asymmetric channel
|
||||
/// amplitudes.
|
||||
fn native_noise_counterpart_uniform_gaussian_and_independent_channel_amplitudes() {
|
||||
let r = Rect::new(-2, 5, 11, 12);
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, r);
|
||||
let src = Image::read(&s, r);
|
||||
let ctx = Ctx { bounds: r, mode: ColorMode::Rgb, alpha: true };
|
||||
for distribution in [Distribution::Uniform, Distribution::Gaussian] {
|
||||
for mono in [false, true] {
|
||||
let mut p = p(vec![40., 40., 40., 0.]);
|
||||
p.distribution = distribution;
|
||||
p.monochromatic = mono;
|
||||
let native = crate::noise::add(&src, r, &ctx, 40., distribution, mono, 71);
|
||||
let ours = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap().read_region(r);
|
||||
for (a, b) in ours.iter().zip(native) {
|
||||
assert!((a - b).abs() < 1e-7);
|
||||
}
|
||||
}
|
||||
}
|
||||
let p = p(vec![20., 40., 0., 80.]);
|
||||
let got = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap().read_region(r);
|
||||
assert!(
|
||||
got.as_chunks::<4>().0.iter().all(|v| v[2] == 0.5 && (0.4..=0.6).contains(&v[0]) && (0.3..=0.7).contains(&v[1]) && (0.1..=0.9).contains(&v[3]))
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
/// Check alpha-only color preservation across models/depths and signal-relative noise on signed HDR channels.
|
||||
fn all_native_models_depths_alpha_only_and_relative_hdr_are_explicit() {
|
||||
let r = Rect::new(0, 0, 8, 4);
|
||||
for mode in [
|
||||
ColorMode::Bitmap,
|
||||
ColorMode::Grayscale,
|
||||
ColorMode::Indexed,
|
||||
ColorMode::Rgb,
|
||||
ColorMode::Cmyk,
|
||||
ColorMode::Lab,
|
||||
ColorMode::Multichannel,
|
||||
ColorMode::Duotone,
|
||||
] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let s = surface(mode, depth, r);
|
||||
let ch = s.channels();
|
||||
let mut amounts = vec![0.; ch];
|
||||
amounts[ch - 1] = 400.;
|
||||
let got = apply_with(&s, &p(amounts), r, r, None, &Interrupt::NONE).unwrap().read_region(r);
|
||||
let original = s.read_region(r);
|
||||
for (a, b) in got.chunks_exact(ch).zip(original.chunks_exact(ch)) {
|
||||
assert_eq!(&a[..ch - 1], &b[..ch - 1]);
|
||||
assert!((0.0..=1.0).contains(&a[ch - 1]));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut s = surface(ColorMode::Rgb, SampleType::F32, r);
|
||||
s.fill_rect(r, &[-2., 3., 0., 0.5]);
|
||||
let mut p = p(vec![100., 100., 100., 0.]);
|
||||
p.relative = true;
|
||||
let got = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap();
|
||||
for v in got.read_region(r).as_chunks::<4>().0 {
|
||||
assert_eq!(v[2], 0.);
|
||||
assert_eq!(v[3], 0.5);
|
||||
assert!((-3.0..=-1.0).contains(&v[0]));
|
||||
assert!((1.5..=4.5).contains(&v[1]));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Require crop-independent seeded output, zero-selection identity and unchanged sources after cancellation or
|
||||
/// nonfinite overflow.
|
||||
fn coordinates_tiling_selection_cancellation_and_overflow_are_atomic() {
|
||||
let r = Rect::new(-3, 5, 130, 12);
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, r);
|
||||
let before = s.clone();
|
||||
let p = p(vec![40., 80., 10., 20.]);
|
||||
let all = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap();
|
||||
let crop = Rect::new(61, 6, 68, 11);
|
||||
assert_eq!(apply_with(&s, &p, crop, r, None, &Interrupt::NONE).unwrap().read_region(crop), all.read_region(crop));
|
||||
let mask = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
assert_eq!(apply_with(&s, &p, r, r, Some(&mask), &Interrupt::NONE).unwrap(), s);
|
||||
let calls = std::sync::atomic::AtomicUsize::new(0);
|
||||
let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 4;
|
||||
assert_eq!(apply_with(&s, &p, r, r, None, &Interrupt::cancel_only(&cancel)).unwrap_err(), Error::Cancelled);
|
||||
assert_eq!(s, before);
|
||||
let mut huge = s.clone();
|
||||
huge.fill_rect(r, &[f32::MAX, f32::MAX, f32::MAX, 0.5]);
|
||||
let mut p = p.clone();
|
||||
p.relative = true;
|
||||
p.amounts = vec![400.; 4];
|
||||
assert_eq!(apply_with(&huge, &p, r, r, None, &Interrupt::NONE).unwrap_err(), Error::NonFiniteSample);
|
||||
}
|
||||
#[test]
|
||||
/// Reject empty, mismatched, excessive and nonfinite amplitude arrays before native noise processing.
|
||||
fn strict_shape_and_numeric_validation() {
|
||||
for amounts in [vec![], vec![0.; 6], vec![f32::NAN; 4], vec![401.; 4], vec![-1.; 4]] {
|
||||
assert!(validate(&p(amounts), 4).is_err());
|
||||
}
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, Rect::new(0, 0, 1, 1));
|
||||
assert_eq!(apply_with(&s, &p(vec![0.; 3]), Rect::new(0, 0, 1, 1), Rect::new(0, 0, 1, 1), None, &Interrupt::NONE).unwrap_err(), Error::InvalidParameter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
//! Native5×5 channel-selective convolution with explicit edge and alpha support rules.
|
||||
pub use crate::coverage::Error;
|
||||
use crate::{Ctx, image::Image};
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Edge {
|
||||
Transparent,
|
||||
Repeat,
|
||||
Wrap,
|
||||
Black,
|
||||
White,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Params {
|
||||
pub kernel: Vec<f64>,
|
||||
pub scale: f64,
|
||||
pub offset: f64,
|
||||
pub channels: Vec<bool>,
|
||||
pub alpha_weighted: bool,
|
||||
pub edge: Edge,
|
||||
}
|
||||
/// Require a finite 5-by-5 kernel, nonzero divisor and channel mask matching the actual native format.
|
||||
pub fn validate(p: &Params, channels: usize) -> Result<(), Error> {
|
||||
if channels == 0
|
||||
|| channels > 5
|
||||
|| p.channels.len() != channels
|
||||
|| p.kernel.len() != 25
|
||||
|| p.kernel.iter().any(|v| !v.is_finite())
|
||||
|| !p.scale.is_finite()
|
||||
|| p.scale == 0.
|
||||
|| !p.offset.is_finite()
|
||||
|| !p.kernel.iter().map(|v| v.abs()).sum::<f64>().is_finite()
|
||||
{
|
||||
return Err(Error::InvalidParameter);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Bound positive convolution geometry using widened arithmetic before deriving buffer sizes.
|
||||
fn dimensions(r: Rect) -> Result<(usize, usize), Error> {
|
||||
let w = i64::from(r.x1) - i64::from(r.x0);
|
||||
let h = i64::from(r.y1) - i64::from(r.y0);
|
||||
if w <= 0 || h <= 0 || w > 65536 || h > 65536 || w.checked_mul(h).is_none_or(|n| n > 64 * 1024 * 1024) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
Ok((w as usize, h as usize))
|
||||
}
|
||||
/// Admit padded output tiles, map clones and fixed halo scratch under the existing native workspace ceiling.
|
||||
fn preflight(s: &Surface, area: Rect, selection: Option<&Surface>) -> Result<(), Error> {
|
||||
dimensions(area)?;
|
||||
let tiles = |a: i32, b: i32| -> Result<usize, Error> {
|
||||
usize::try_from((i64::from(b) - 1).div_euclid(256) - i64::from(a).div_euclid(256) + 1).map_err(|_| Error::WorkspaceLimit)
|
||||
};
|
||||
let bytes = tiles(area.x0, area.x1)?
|
||||
.checked_mul(tiles(area.y0, area.y1)?)
|
||||
.and_then(|n| n.checked_mul(256 * 256 * s.format().bytes_per_pixel() + 128))
|
||||
.and_then(|n| n.checked_add(s.tile_count().checked_mul(128)?))
|
||||
.and_then(|n| n.checked_add(68 * 68 * s.channels() * 4 + 64 * 64 * (s.channels() * 3 + selection.map_or(0, Surface::channels)) * 4))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
if bytes > crate::coverage::MAX_WORKSPACE_BYTES {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Fill black or white edge samples in the native color model, with opaque alpha when present.
|
||||
fn neutral(mode: ColorMode, white: bool, out: &mut [f32], alpha: bool) {
|
||||
let color_count = out.len().saturating_sub(usize::from(alpha));
|
||||
let value = if white { 1. } else { 0. };
|
||||
for (c, v) in out.iter_mut().take(color_count).enumerate() {
|
||||
*v = match mode {
|
||||
ColorMode::Cmyk => {
|
||||
if c == 3 {
|
||||
1. - value
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
ColorMode::Lab => {
|
||||
if c == 0 {
|
||||
value
|
||||
} else {
|
||||
128. / 255.
|
||||
}
|
||||
}
|
||||
_ => value,
|
||||
};
|
||||
}
|
||||
if alpha && let Some(v) = out.last_mut() {
|
||||
*v = 1.;
|
||||
}
|
||||
}
|
||||
/// Sample the requested native edge policy, distinguishing repeated/wrapped coordinates from transparent or neutral
|
||||
/// borders.
|
||||
fn sample(s: &Surface, x: i64, y: i64, domain: Rect, edge: Edge, out: &mut [f32]) -> Result<(), Error> {
|
||||
let inside = x >= i64::from(domain.x0) && x < i64::from(domain.x1) && y >= i64::from(domain.y0) && y < i64::from(domain.y1);
|
||||
if inside {
|
||||
s.read_pixel(x as i32, y as i32, out);
|
||||
return Ok(());
|
||||
}
|
||||
let axis = |v: i64, lo: i32, hi: i32| match edge {
|
||||
Edge::Repeat => v.clamp(i64::from(lo), i64::from(hi) - 1),
|
||||
Edge::Wrap => i64::from(lo) + (v - i64::from(lo)).rem_euclid(i64::from(hi) - i64::from(lo)),
|
||||
_ => v,
|
||||
};
|
||||
match edge {
|
||||
Edge::Repeat | Edge::Wrap => s.read_pixel(axis(x, domain.x0, domain.x1) as i32, axis(y, domain.y0, domain.y1) as i32, out),
|
||||
Edge::Transparent => out.fill(0.),
|
||||
Edge::Black => neutral(s.format().mode, false, out, s.format().alpha),
|
||||
Edge::White => neutral(s.format().mode, true, out, s.format().alpha),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
/// Apply selected kernel channels with explicit alpha support, finite-value checks and row cancellation.
|
||||
fn convolve(data: &[f32], w: usize, h: usize, format: PixelFormat, p: &Params, ctl: &Interrupt<'_>) -> Result<Vec<f32>, Error> {
|
||||
let ch = format.channels();
|
||||
let stride = (w + 4) * ch;
|
||||
if data.len() != (w + 4) * (h + 4) * ch {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(w * h * ch).map_err(|_| Error::Allocation)?;
|
||||
let weight_sum = p.kernel.iter().map(|v| v.abs()).sum::<f64>();
|
||||
for y in 0..h {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
for x in 0..w {
|
||||
let base = (y + 2) * stride + (x + 2) * ch;
|
||||
let original = data.get(base..base + ch).ok_or(Error::InvalidGeometry)?;
|
||||
for (c, &before) in original.iter().enumerate() {
|
||||
if !before.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
if !p.channels.get(c).copied().ok_or(Error::InvalidParameter)? {
|
||||
out.push(before);
|
||||
continue;
|
||||
}
|
||||
let alpha = format.alpha && c + 1 == ch;
|
||||
let subtractive = format.mode == ColorMode::Cmyk && !alpha;
|
||||
let weighted = p.alpha_weighted && format.alpha && !alpha;
|
||||
let mut sum = 0f64;
|
||||
let mut support = 0f64;
|
||||
for (k, &coefficient) in p.kernel.iter().enumerate() {
|
||||
if coefficient == 0. {
|
||||
continue;
|
||||
}
|
||||
let i = (y + k / 5) * stride + (x + k % 5) * ch;
|
||||
let pixel = data.get(i..i + ch).ok_or(Error::InvalidGeometry)?;
|
||||
let mut value = f64::from(*pixel.get(c).ok_or(Error::InvalidGeometry)?);
|
||||
if !value.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
if subtractive {
|
||||
value = 1. - value;
|
||||
}
|
||||
let a = if weighted {
|
||||
let a = f64::from(*pixel.last().ok_or(Error::InvalidGeometry)?);
|
||||
if !a.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
a.clamp(0., 1.)
|
||||
} else {
|
||||
1.
|
||||
};
|
||||
sum += coefficient * value * a;
|
||||
support += coefficient.abs() * a;
|
||||
}
|
||||
if !sum.is_finite() || !support.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
// Absolute support avoids division by signed/zero convolved alpha. Empty
|
||||
// support retains hidden color; a zero kernel deliberately produces offset.
|
||||
let result = if weighted && weight_sum > 0. && support <= weight_sum * 1e-12 {
|
||||
f64::from(before)
|
||||
} else {
|
||||
if weighted && weight_sum > 0. {
|
||||
sum *= weight_sum / support;
|
||||
}
|
||||
let result = sum / p.scale + p.offset;
|
||||
if subtractive { 1. - result } else { result }
|
||||
};
|
||||
if !result.is_finite() || result.abs() > f64::from(f32::MAX) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
out.push(if alpha { result.clamp(0., 1.) as f32 } else { result as f32 });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// Selection changes publication only; the complete owner supplies the stencil.
|
||||
pub fn apply_with(s: &Surface, p: &Params, area: Rect, domain: Rect, selection: Option<&Surface>, ctl: &Interrupt<'_>) -> Result<Surface, Error> {
|
||||
validate(p, s.channels())?;
|
||||
// Edge sampling does not allocate the domain; preflight bounds the output area.
|
||||
if domain.is_empty() {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
if area.x1 < area.x0 || area.y1 < area.y0 {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let area = area.intersect(&domain);
|
||||
if area.is_empty() {
|
||||
return Ok(s.clone());
|
||||
}
|
||||
preflight(s, area, selection)?;
|
||||
let ch = s.channels();
|
||||
let mut result = s.clone();
|
||||
let mut y = area.y0;
|
||||
while y < area.y1 {
|
||||
let y1 = (i64::from(y) + 64).min(i64::from(area.y1)) as i32;
|
||||
let mut x = area.x0;
|
||||
while x < area.x1 {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let x1 = (i64::from(x) + 64).min(i64::from(area.x1)) as i32;
|
||||
let tile = Rect::new(x, y, x1, y1);
|
||||
let (w, h) = dimensions(tile)?;
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact((w + 4) * (h + 4) * ch).map_err(|_| Error::Allocation)?;
|
||||
for yy in i64::from(y) - 2..i64::from(y1) + 2 {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
for xx in i64::from(x) - 2..i64::from(x1) + 2 {
|
||||
let mut pixel = [0.; 5];
|
||||
let target = pixel.get_mut(..ch).ok_or(Error::InvalidGeometry)?;
|
||||
sample(s, xx, yy, domain, p.edge, target)?;
|
||||
data.extend_from_slice(target);
|
||||
}
|
||||
}
|
||||
let mut filtered = convolve(&data, w, h, s.format(), p, ctl)?;
|
||||
drop(data);
|
||||
if let Some(selection) = selection {
|
||||
let mask = selection.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
if mask.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let original = Image { rect: tile, ch, data: s.try_read_region(tile).map_err(|_| Error::Allocation)? };
|
||||
crate::mix_selection(&mut filtered, tile, selection, &original, s.format().alpha);
|
||||
for (pixel, before) in filtered.chunks_exact_mut(ch).zip(original.data.chunks_exact(ch)) {
|
||||
for ((value, original), selected) in pixel.iter_mut().zip(before).zip(&p.channels) {
|
||||
if !selected {
|
||||
*value = *original;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if filtered.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
result.try_write_region(tile, &filtered).map_err(|_| Error::Allocation)?;
|
||||
x = x1;
|
||||
}
|
||||
y = y1;
|
||||
ctl.progress((i64::from(y) - i64::from(area.y0)) as f32 / (i64::from(area.y1) - i64::from(area.y0)) as f32);
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
/// Bridge raw float images to checked convolution and use bounded identity output when admission fails.
|
||||
pub(crate) fn run_image(src: &Image, out: Rect, ctx: &Ctx, p: &Params) -> Vec<f32> {
|
||||
let identity = || -> Result<Vec<f32>, Error> {
|
||||
let (w, h) = dimensions(src.rect)?;
|
||||
let (ow, oh) = dimensions(out)?;
|
||||
if src.ch == 0 || src.ch > 5 || out.intersect(&src.rect) != out || w.checked_mul(h).and_then(|n| n.checked_mul(src.ch)) != Some(src.data.len()) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let mut result = Vec::new();
|
||||
result.try_reserve_exact(ow * oh * src.ch).map_err(|_| Error::Allocation)?;
|
||||
for y in out.y0..out.y1 {
|
||||
let i = ((i64::from(y) - i64::from(src.rect.y0)) as usize * w + (i64::from(out.x0) - i64::from(src.rect.x0)) as usize) * src.ch;
|
||||
result.extend_from_slice(src.data.get(i..i + ow * src.ch).ok_or(Error::InvalidGeometry)?);
|
||||
}
|
||||
Ok(result)
|
||||
};
|
||||
let run = || -> Result<Vec<f32>, Error> {
|
||||
validate(p, src.ch)?;
|
||||
let (w, h) = dimensions(src.rect)?;
|
||||
dimensions(out)?;
|
||||
if out.intersect(&src.rect) != out {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if src.data.len() > 64 * 1024 * 1024 || w.checked_mul(h).and_then(|n| n.checked_mul(src.ch)) != Some(src.data.len()) {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
let format = PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha);
|
||||
if format.channels() != src.ch {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let mut s = Surface::new(format);
|
||||
s.try_write_region(src.rect, &src.data).map_err(|_| Error::Allocation)?;
|
||||
apply_with(&s, p, out, src.rect, None, &Interrupt::NONE)?.try_read_region(out).map_err(|_| Error::Allocation)
|
||||
};
|
||||
run().unwrap_or_else(|_| identity().unwrap_or_default())
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
/// Retain every convolution edge policy on a large owner without admitting oversized output work.
|
||||
fn small_convolution_area_in_large_domain_keeps_edge_sampling_and_work_bounds() {
|
||||
let area = Rect::new(0, 0, 1, 1);
|
||||
let mut s = Surface::new(PixelFormat::RGBA32F);
|
||||
s.fill_rect(area, &[0.2, 0.4, 0.6, 1.]);
|
||||
let domain = Rect::new(0, 0, 9_000, 9_000);
|
||||
let mut p = params(4);
|
||||
p.kernel[12] = 0.;
|
||||
p.kernel[11] = 1.;
|
||||
for edge in [Edge::Repeat, Edge::Wrap, Edge::Transparent, Edge::Black, Edge::White] {
|
||||
p.edge = edge;
|
||||
let got = apply_with(&s, &p, area, domain, None, &Interrupt::NONE).unwrap();
|
||||
let mut expected = [0.; 4];
|
||||
sample(&s, -1, 0, domain, edge, &mut expected).unwrap();
|
||||
assert_eq!(got.pixel(0, 0), expected, "{edge:?}");
|
||||
}
|
||||
assert_eq!(apply_with(&s, &p, domain, domain, None, &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
assert_eq!(apply_with(&s, &p, area, Rect::new(0, 0, 0, 1), None, &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
}
|
||||
/// Define the native custom-filter fixture kernel independently of imported source configuration.
|
||||
fn params(ch: usize) -> Params {
|
||||
let mut k = vec![0.; 25];
|
||||
k[12] = 1.;
|
||||
Params { kernel: k, scale: 1., offset: 0., channels: vec![true; ch], alpha_weighted: false, edge: Edge::Repeat }
|
||||
}
|
||||
/// Populate a native-format test surface with original samples for cross-depth counterpart comparisons.
|
||||
fn surface(mode: ColorMode, depth: SampleType, r: Rect) -> Surface {
|
||||
let fmt = PixelFormat::new(mode, depth, true);
|
||||
let mut s = Surface::new(fmt);
|
||||
let data: Vec<f32> = (0..r.width() as usize * r.height() as usize * fmt.channels())
|
||||
.map(|i| if depth == SampleType::F32 { (i % 31) as f32 / 9. - 1. } else { (i % 31) as f32 / 30. })
|
||||
.collect();
|
||||
s.try_write_region(r, &data).unwrap();
|
||||
s
|
||||
}
|
||||
#[test]
|
||||
/// Compare the checked kernel with the existing native Custom filter's row-major brightness policy.
|
||||
fn native_custom_counterpart_matches_row_major_brightness_at_every_depth_and_model() {
|
||||
let r = Rect::new(-3, -3, 10, 9);
|
||||
let out = Rect::new(0, 0, 7, 6);
|
||||
for mode in [
|
||||
ColorMode::Bitmap,
|
||||
ColorMode::Grayscale,
|
||||
ColorMode::Indexed,
|
||||
ColorMode::Rgb,
|
||||
ColorMode::Cmyk,
|
||||
ColorMode::Lab,
|
||||
ColorMode::Multichannel,
|
||||
ColorMode::Duotone,
|
||||
] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let s = surface(mode, depth, r);
|
||||
let mut p = params(s.channels());
|
||||
p.kernel[12] = 2.;
|
||||
p.kernel[6] = -0.25;
|
||||
p.kernel[19] = 0.5;
|
||||
p.scale = 2.25;
|
||||
p.offset = 0.125;
|
||||
p.channels[s.channels() - 1] = false;
|
||||
let input = Image::read(&s, r);
|
||||
let kernel: Vec<f32> = p.kernel.iter().map(|v| *v as f32).collect();
|
||||
let expected = crate::other2::custom(&input, out, &Ctx { bounds: r, mode, alpha: true }, &kernel, p.scale as f32, p.offset as f32 * 255.);
|
||||
let mut native = Surface::new(s.format());
|
||||
native.try_write_region(out, &expected).unwrap();
|
||||
let got = apply_with(&s, &p, out, r, None, &Interrupt::NONE).unwrap().read_region(out);
|
||||
for (a, b) in got.iter().zip(native.read_region(out)) {
|
||||
assert!((a - b).abs() < 2. / 65535., "{mode:?} {depth:?} {a}/{b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Exercise signed kernels and missing alpha support without inventing nonfinite hidden HDR samples.
|
||||
fn signed_alpha_weighting_and_empty_support_preserve_finite_hidden_hdr() {
|
||||
let r = Rect::new(0, 0, 3, 1);
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true));
|
||||
s.try_write_region(r, &[1000., -1000., 2., 0., 4., -2., 0.5, 0.5, 8., 3., 0.25, 1.]).unwrap();
|
||||
let mut p = params(4);
|
||||
p.kernel[12] = 2.;
|
||||
p.kernel[11] = -1.;
|
||||
p.alpha_weighted = true;
|
||||
p.channels = vec![true, false, true, true];
|
||||
let got = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(got.pixel(1, 0), vec![12., -2., 1.5, 1.]);
|
||||
s.fill_rect(r, &[-2., 3., 0.4, 0.]);
|
||||
let before = s.clone();
|
||||
let got = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(got.read_region(r), before.read_region(r));
|
||||
p.kernel.fill(0.);
|
||||
p.offset = 0.25;
|
||||
let got = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(got.pixel(1, 0), vec![0.25, 3., 0.25, 0.25]);
|
||||
}
|
||||
#[test]
|
||||
/// Check border policies, native neutral colors and actual scalar/alpha channel selections.
|
||||
fn explicit_edges_neutral_models_and_alpha_scalar_channel_masks() {
|
||||
let r = Rect::new(0, 0, 1, 1);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
let mut s = Surface::new(PixelFormat::new(mode, SampleType::F32, true));
|
||||
s.fill_rect(r, &vec![0.4; s.channels()]);
|
||||
let mut p = params(s.channels());
|
||||
p.kernel.fill(0.);
|
||||
p.kernel[11] = 1.;
|
||||
for edge in [Edge::Repeat, Edge::Wrap, Edge::Transparent, Edge::Black, Edge::White] {
|
||||
p.edge = edge;
|
||||
let got = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap().pixel(0, 0);
|
||||
let mut expected = vec![0.; s.channels()];
|
||||
match edge {
|
||||
Edge::Repeat | Edge::Wrap => expected.fill(0.4),
|
||||
Edge::Transparent => {}
|
||||
Edge::Black => neutral(mode, false, &mut expected, true),
|
||||
Edge::White => neutral(mode, true, &mut expected, true),
|
||||
}
|
||||
assert_eq!(got, expected, "{mode:?} {edge:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Verify tiled selection output while cancellation and numeric failure cannot modify the original input.
|
||||
fn tiling_selection_mid_cancel_and_numeric_failures_are_atomic() {
|
||||
let r = Rect::new(-2, 4, 132, 12);
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, r);
|
||||
let before = s.clone();
|
||||
let mut p = params(4);
|
||||
p.kernel[12] = 0.5;
|
||||
p.kernel[11] = 0.5;
|
||||
p.channels[3] = false;
|
||||
let got = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap();
|
||||
let crop = Rect::new(60, 5, 68, 11);
|
||||
assert_eq!(apply_with(&s, &p, crop, r, None, &Interrupt::NONE).unwrap().read_region(crop), got.read_region(crop));
|
||||
let mask = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
assert_eq!(apply_with(&s, &p, r, r, Some(&mask), &Interrupt::NONE).unwrap(), s);
|
||||
let count = std::sync::atomic::AtomicUsize::new(0);
|
||||
let cancel = || count.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 8;
|
||||
assert_eq!(apply_with(&s, &p, r, r, None, &Interrupt::cancel_only(&cancel)).unwrap_err(), Error::Cancelled);
|
||||
assert_eq!(s, before);
|
||||
p.scale = f64::MIN_POSITIVE;
|
||||
assert_eq!(apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap_err(), Error::NonFiniteSample);
|
||||
}
|
||||
#[test]
|
||||
/// Ensure opaque formats retain their real channel count rather than acquiring an invented alpha plane.
|
||||
fn opaque_native_models_use_actual_channel_counts_without_synthetic_alpha() {
|
||||
let r = Rect::new(0, 0, 3, 2);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let mut s = Surface::new(PixelFormat::new(mode, depth, false));
|
||||
let ch = s.channels();
|
||||
s.fill_rect(r, &vec![0.4; ch]);
|
||||
let mut p = params(ch);
|
||||
p.alpha_weighted = true;
|
||||
assert_eq!(apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap(), s);
|
||||
let rank =
|
||||
crate::rank::Params { radius: 1, color_percentile: 17., alpha_percentile: 83., shape: crate::rank::Neighborhood::Disc, channels: None };
|
||||
assert_eq!(crate::rank::apply_with(&s, &rank, r, r, None, &Interrupt::NONE).unwrap(), s);
|
||||
let noise = crate::channel_noise::Params {
|
||||
amounts: vec![0.; ch],
|
||||
distribution: crate::Distribution::Uniform,
|
||||
monochromatic: false,
|
||||
relative: true,
|
||||
seed: 71,
|
||||
};
|
||||
assert_eq!(crate::channel_noise::apply_with(&s, &noise, r, r, None, &Interrupt::NONE).unwrap(), s);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Reject malformed kernel shapes, masks and geometry before native convolution can allocate or publish work.
|
||||
fn strict_kernel_channel_and_geometry_admission() {
|
||||
let r = Rect::new(0, 0, 2, 2);
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, r);
|
||||
let mut p = params(4);
|
||||
for bad in [0., f64::NAN, f64::INFINITY] {
|
||||
p.scale = bad;
|
||||
assert!(validate(&p, 4).is_err());
|
||||
}
|
||||
p = params(4);
|
||||
p.channels.pop();
|
||||
assert!(validate(&p, 4).is_err());
|
||||
p = params(4);
|
||||
p.kernel[0] = f64::INFINITY;
|
||||
assert!(validate(&p, 4).is_err());
|
||||
p = params(4);
|
||||
p.kernel[0] = f64::MAX;
|
||||
p.kernel[1] = f64::MAX;
|
||||
assert!(validate(&p, 4).is_err());
|
||||
let huge = Rect::new(0, 0, 65536, 65536);
|
||||
assert_eq!(apply_with(&s, ¶ms(4), huge, huge, None, &Interrupt::NONE).unwrap_err(), Error::InvalidGeometry);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,899 @@
|
||||
//! Generic native coverage operations. No file-format identities or external resources.
|
||||
//!
|
||||
//! Hole filling is boundary-connected grayscale reconstruction: each sample is raised to
|
||||
//! min(path to boundary) max(sample along path). This standard minimax definition is also
|
||||
//! described by Barnes/Lehman/Mulla, Computers & Geosciences62 (2014),117–127:
|
||||
//! <https://doi.org/10.1016/j.cageo.2013.04.024>. Independent implementation; no source code copied.
|
||||
use crate::{Ctx, image::Image};
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BinaryHeap;
|
||||
|
||||
pub const MAX_PIXELS: usize = 64 * 1024 * 1024;
|
||||
pub const MAX_WORKSPACE_BYTES: usize = 1_500_000_000;
|
||||
const MAX_EDGE: i64 = 65_536;
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Operation<'a> {
|
||||
SetAlpha(f32),
|
||||
AlphaCurve(&'a [f32]),
|
||||
/// Extract native coverage onto stored neutral axes; opaque output, unchanged model.
|
||||
AlphaToColor,
|
||||
ClampAlpha {
|
||||
low: f32,
|
||||
high: f32,
|
||||
},
|
||||
/// Native rule: alpha strictly greater than value becomes1; equality becomes0.
|
||||
ThresholdAlpha(f32),
|
||||
FillHoles {
|
||||
connectivity: u8,
|
||||
alpha_only: bool,
|
||||
},
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Cancelled,
|
||||
InvalidGeometry,
|
||||
InvalidParameter,
|
||||
AlphaRequired,
|
||||
NonFiniteSample,
|
||||
WorkspaceLimit,
|
||||
Allocation,
|
||||
}
|
||||
impl std::fmt::Display for Error {
|
||||
/// Describe checked coverage failures without exposing implementation-specific error values to callers.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Cancelled => "native coverage operation cancelled",
|
||||
Self::InvalidGeometry => "native coverage bounds are invalid",
|
||||
Self::InvalidParameter => "invalid native coverage parameter",
|
||||
Self::AlphaRequired => "native coverage operation requires an alpha-capable layer",
|
||||
Self::NonFiniteSample => "native coverage operation requires finite samples",
|
||||
Self::WorkspaceLimit => "native coverage operation exceeds its bounded workspace",
|
||||
Self::Allocation => "native coverage workspace could not be allocated",
|
||||
})
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Shape {
|
||||
width: usize,
|
||||
height: usize,
|
||||
pixels: usize,
|
||||
}
|
||||
/// Validate positive native dimensions and channel count, then bound pixel and reconstruction workspace arithmetic.
|
||||
fn shape(rect: Rect, channels: usize, operation: Operation<'_>) -> Result<Shape, Error> {
|
||||
let width = i64::from(rect.x1) - i64::from(rect.x0);
|
||||
let height = i64::from(rect.y1) - i64::from(rect.y0);
|
||||
if width <= 0 || height <= 0 || width > MAX_EDGE || height > MAX_EDGE || channels == 0 || channels > 5 {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let width = usize::try_from(width).map_err(|_| Error::InvalidGeometry)?;
|
||||
let height = usize::try_from(height).map_err(|_| Error::InvalidGeometry)?;
|
||||
let pixels = width.checked_mul(height).ok_or(Error::WorkspaceLimit)?;
|
||||
// Only reconstruction visits/allocates the whole domain. Point operations admit
|
||||
// their clipped output tiles in preflight, even on a larger sparse owner.
|
||||
if matches!(operation, Operation::FillHoles { .. }) && pixels > MAX_PIXELS {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
// Plane/queue workspace is checked separately from padded native output tiles.
|
||||
let per_pixel = if matches!(operation, Operation::FillHoles { .. }) { std::mem::size_of::<Node>() + 5 } else { 0 };
|
||||
if pixels.checked_mul(per_pixel).is_none_or(|bytes| bytes > MAX_WORKSPACE_BYTES) {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
Ok(Shape { width, height, pixels })
|
||||
}
|
||||
/// Admit padded output tiles, cloned sparse headers and selection/topology scratch before allocating any result.
|
||||
fn preflight(surface: &Surface, area: Rect, shape: Shape, operation: Operation<'_>, selection: Option<&Surface>) -> Result<(), Error> {
|
||||
let ts = i64::from(photocraft_geom::TILE_SIZE);
|
||||
let tile_count = |lo: i32, hi: i32| -> Result<usize, Error> {
|
||||
if hi <= lo {
|
||||
return Ok(0);
|
||||
}
|
||||
usize::try_from((i64::from(hi) - 1).div_euclid(ts) - i64::from(lo).div_euclid(ts) + 1).map_err(|_| Error::WorkspaceLimit)
|
||||
};
|
||||
let tile_bytes =
|
||||
usize::try_from(ts).ok().and_then(|n| n.checked_mul(n)).and_then(|n| n.checked_mul(surface.format().bytes_per_pixel())).ok_or(Error::WorkspaceLimit)?;
|
||||
let output = tile_count(area.x0, area.x1)?
|
||||
.checked_mul(tile_count(area.y0, area.y1)?)
|
||||
.and_then(|n| n.checked_mul(tile_bytes.checked_add(128)?))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
// Cloning the sparse Surface also duplicates its map nodes, even outside publication.
|
||||
let cloned_headers = surface.tile_count().checked_mul(128).ok_or(Error::WorkspaceLimit)?;
|
||||
let workspace = if matches!(operation, Operation::FillHoles { .. }) {
|
||||
shape.pixels.checked_mul(std::mem::size_of::<Node>() + 5).ok_or(Error::WorkspaceLimit)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// Up to three interleaved f32 64x64 buffers coexist during selection publication.
|
||||
let scratch_channels =
|
||||
surface.channels().checked_mul(2).and_then(|n| n.checked_add(selection.map_or(0, Surface::channels))).ok_or(Error::WorkspaceLimit)?;
|
||||
let scratch = 64usize.checked_mul(64).and_then(|n| n.checked_mul(scratch_channels)).and_then(|n| n.checked_mul(4)).ok_or(Error::WorkspaceLimit)?;
|
||||
if output.checked_add(cloned_headers).and_then(|n| n.checked_add(workspace)).and_then(|n| n.checked_add(scratch)).is_none_or(|n| n > MAX_WORKSPACE_BYTES) {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Reserve fallibly and initialize bounded chunks, checking cancellation between chunks.
|
||||
fn zeroes<T: Clone>(len: usize, value: T, ctl: &Interrupt<'_>) -> Result<Vec<T>, Error> {
|
||||
let mut result = Vec::new();
|
||||
result.try_reserve_exact(len).map_err(|_| Error::Allocation)?;
|
||||
while result.len() < len {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let end = result.len().saturating_add(2048).min(len);
|
||||
result.resize(end, value.clone());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
/// Enforce finite coverage controls, exact curve shape and the alpha support required by each operation.
|
||||
fn validate(operation: Operation<'_>, alpha: bool) -> Result<(), Error> {
|
||||
match operation {
|
||||
Operation::AlphaCurve(values) if values.len() != 256 || values.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v)) => {
|
||||
Err(Error::InvalidParameter)
|
||||
}
|
||||
Operation::SetAlpha(value) if !value.is_finite() || !(0.0..=1.0).contains(&value) => Err(Error::InvalidParameter),
|
||||
Operation::ClampAlpha { low, high } if !low.is_finite() || !high.is_finite() || !(0.0..=1.0).contains(&low) || !(low..=1.0).contains(&high) => {
|
||||
Err(Error::InvalidParameter)
|
||||
}
|
||||
Operation::ThresholdAlpha(value) if !value.is_finite() || !(0.0..=1.0).contains(&value) => Err(Error::InvalidParameter),
|
||||
Operation::SetAlpha(_) | Operation::AlphaCurve(_) | Operation::AlphaToColor | Operation::ClampAlpha { .. } | Operation::ThresholdAlpha(_) if !alpha => {
|
||||
Err(Error::AlphaRequired)
|
||||
}
|
||||
Operation::FillHoles { connectivity, .. } if connectivity != 4 && connectivity != 8 => Err(Error::InvalidParameter),
|
||||
Operation::FillHoles { alpha_only: true, .. } if !alpha => Err(Error::AlphaRequired),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
/// Evaluate native absolute alpha, strict threshold, clamp or piecewise-linear transfer rules on a finite sample.
|
||||
fn alpha_value(operation: Operation<'_>, current: f32) -> Result<f32, Error> {
|
||||
match operation {
|
||||
Operation::SetAlpha(value) => Ok(value),
|
||||
Operation::AlphaCurve(values) if current.is_finite() => {
|
||||
let pos = current.clamp(0., 1.) * 255.;
|
||||
let index = (pos.floor() as usize).min(255);
|
||||
let t = pos - index as f32;
|
||||
let a = *values.get(index).ok_or(Error::InvalidParameter)?;
|
||||
let b = *values.get(index.saturating_add(1).min(255)).ok_or(Error::InvalidParameter)?;
|
||||
Ok(a + (b - a) * t)
|
||||
}
|
||||
Operation::ClampAlpha { low, high } if current.is_finite() => Ok(current.clamp(low, high)),
|
||||
Operation::ThresholdAlpha(value) if current.is_finite() => Ok(if current > value { 1. } else { 0. }),
|
||||
_ => Err(Error::NonFiniteSample),
|
||||
}
|
||||
}
|
||||
/// Place normalized coverage on the current model's neutral axes and make the pixel opaque, without an RGB conversion.
|
||||
fn alpha_to_color(pixel: &mut [f32], mode: ColorMode) -> Result<(), Error> {
|
||||
let (alpha, color) = pixel.split_last_mut().ok_or(Error::AlphaRequired)?;
|
||||
if !alpha.is_finite() || color.iter().any(|value| !value.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let value = alpha.clamp(0., 1.);
|
||||
color.fill(value);
|
||||
match mode {
|
||||
ColorMode::Cmyk => {
|
||||
color.fill(0.);
|
||||
*color.last_mut().ok_or(Error::InvalidGeometry)? = 1. - value;
|
||||
}
|
||||
ColorMode::Lab => {
|
||||
// Existing native Lab normalization is [L/100,(a+128)/255,(b+128)/255]
|
||||
// (raster::from_rgba_into). This is channel encoding, not an sRGB conversion.
|
||||
for channel in color.iter_mut().skip(1) {
|
||||
*channel = 128. / 255.;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
*alpha = 1.;
|
||||
Ok(())
|
||||
}
|
||||
/// Visit clipped 64-by-64 regions and stop immediately when a region callback fails.
|
||||
fn tiles(rect: Rect, mut action: impl FnMut(Rect) -> Result<(), Error>) -> Result<(), Error> {
|
||||
let mut y = rect.y0;
|
||||
while y < rect.y1 {
|
||||
let y1 = y.saturating_add(64).min(rect.y1);
|
||||
let mut x = rect.x0;
|
||||
while x < rect.x1 {
|
||||
let x1 = x.saturating_add(64).min(rect.x1);
|
||||
action(Rect::new(x, y, x1, y1))?;
|
||||
x = x1;
|
||||
}
|
||||
y = y1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Node {
|
||||
level: f32,
|
||||
index: usize,
|
||||
}
|
||||
impl PartialEq for Node {
|
||||
/// Compare queue nodes by both pixel index and the total ordering of their spill level.
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.index == other.index && self.level.total_cmp(&other.level) == Ordering::Equal
|
||||
}
|
||||
}
|
||||
impl Eq for Node {}
|
||||
impl PartialOrd for Node {
|
||||
/// Delegate to the deterministic total order used by the reconstruction heap.
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
impl Ord for Node {
|
||||
/// Reverse level and index ordering so BinaryHeap removes the lowest deterministic spill candidate first.
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
other.level.total_cmp(&self.level).then_with(|| other.index.cmp(&self.index))
|
||||
}
|
||||
}
|
||||
/// Visit only in-bounds four- or eight-connected neighbors using checked index arithmetic.
|
||||
fn neighbors(index: usize, shape: Shape, connectivity: u8, mut visit: impl FnMut(usize) -> Result<(), Error>) -> Result<(), Error> {
|
||||
let x = index % shape.width;
|
||||
let y = index / shape.width;
|
||||
for dy in -1i64..=1 {
|
||||
for dx in -1i64..=1 {
|
||||
if (dx == 0 && dy == 0) || (connectivity == 4 && dx != 0 && dy != 0) {
|
||||
continue;
|
||||
}
|
||||
let nx = i64::try_from(x).map_err(|_| Error::InvalidGeometry)? + dx;
|
||||
let ny = i64::try_from(y).map_err(|_| Error::InvalidGeometry)? + dy;
|
||||
if nx < 0 || ny < 0 {
|
||||
continue;
|
||||
}
|
||||
let nx = usize::try_from(nx).map_err(|_| Error::InvalidGeometry)?;
|
||||
let ny = usize::try_from(ny).map_err(|_| Error::InvalidGeometry)?;
|
||||
if nx >= shape.width || ny >= shape.height {
|
||||
continue;
|
||||
}
|
||||
let next = ny.checked_mul(shape.width).and_then(|v| v.checked_add(nx)).ok_or(Error::InvalidGeometry)?;
|
||||
visit(next)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Raise enclosed samples by boundary-connected minimax reconstruction with finite-input, allocation and cancellation
|
||||
/// checks.
|
||||
fn fill(plane: &mut [f32], shape: Shape, connectivity: u8, ctl: &Interrupt<'_>) -> Result<(), Error> {
|
||||
if plane.len() != shape.pixels {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
for chunk in plane.chunks(2048) {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
if chunk.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
}
|
||||
let mut visited = zeroes(shape.pixels, false, ctl)?;
|
||||
let mut queue = BinaryHeap::new();
|
||||
queue.try_reserve_exact(shape.pixels).map_err(|_| Error::Allocation)?;
|
||||
for index in 0..shape.pixels {
|
||||
if index.is_multiple_of(2048) && ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let x = index % shape.width;
|
||||
let y = index / shape.width;
|
||||
if x == 0 || y == 0 || x + 1 == shape.width || y + 1 == shape.height {
|
||||
*visited.get_mut(index).ok_or(Error::InvalidGeometry)? = true;
|
||||
queue.push(Node { level: *plane.get(index).ok_or(Error::InvalidGeometry)?, index });
|
||||
}
|
||||
}
|
||||
let mut processed = 0usize;
|
||||
while let Some(node) = queue.pop() {
|
||||
if processed.is_multiple_of(2048) && ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
processed = processed.saturating_add(1);
|
||||
neighbors(node.index, shape, connectivity, |index| {
|
||||
let seen = visited.get_mut(index).ok_or(Error::InvalidGeometry)?;
|
||||
if *seen {
|
||||
return Ok(());
|
||||
}
|
||||
*seen = true;
|
||||
let value = plane.get_mut(index).ok_or(Error::InvalidGeometry)?;
|
||||
*value = value.max(node.level);
|
||||
queue.push(Node { level: *value, index });
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Extract one finite native channel into a checked whole-owner plane using bounded tile reads.
|
||||
fn plane_from(surface: &Surface, domain: Rect, shape: Shape, channel: usize, ctl: &Interrupt<'_>) -> Result<Vec<f32>, Error> {
|
||||
let mut plane = zeroes(shape.pixels, 0.0, ctl)?;
|
||||
let channels = surface.channels();
|
||||
tiles(domain, |tile| {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let data = surface.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
let width = usize::try_from(tile.width()).map_err(|_| Error::InvalidGeometry)?;
|
||||
for (pixel, samples) in data.chunks_exact(channels).enumerate() {
|
||||
let value = *samples.get(channel).ok_or(Error::InvalidGeometry)?;
|
||||
if !value.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let x = usize::try_from(i64::from(tile.x0) - i64::from(domain.x0))
|
||||
.map_err(|_| Error::InvalidGeometry)?
|
||||
.checked_add(pixel % width)
|
||||
.ok_or(Error::InvalidGeometry)?;
|
||||
let y = usize::try_from(i64::from(tile.y0) - i64::from(domain.y0))
|
||||
.map_err(|_| Error::InvalidGeometry)?
|
||||
.checked_add(pixel / width)
|
||||
.ok_or(Error::InvalidGeometry)?;
|
||||
let index = y.checked_mul(shape.width).and_then(|v| v.checked_add(x)).ok_or(Error::InvalidGeometry)?;
|
||||
*plane.get_mut(index).ok_or(Error::InvalidGeometry)? = value;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(plane)
|
||||
}
|
||||
|
||||
/// Whole-owner checked native operation. `domain` defines topology; `area` and `selection`
|
||||
/// limit publication only. Failure/cancellation never changes the source surface.
|
||||
pub fn apply_with(
|
||||
surface: &Surface,
|
||||
operation: Operation<'_>,
|
||||
area: Rect,
|
||||
domain: Rect,
|
||||
selection: Option<&Surface>,
|
||||
ctl: &Interrupt<'_>,
|
||||
) -> Result<Surface, Error> {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
validate(operation, surface.format().alpha)?;
|
||||
if area.x1 < area.x0 || area.y1 < area.y0 {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let shape = shape(domain, surface.channels(), operation)?;
|
||||
let area = area.intersect(&domain);
|
||||
preflight(surface, area, shape, operation, selection)?;
|
||||
let mut output = surface.clone();
|
||||
if area.is_empty() {
|
||||
return Ok(output);
|
||||
}
|
||||
let channels = surface.channels();
|
||||
match operation {
|
||||
Operation::SetAlpha(_) | Operation::AlphaCurve(_) | Operation::ClampAlpha { .. } | Operation::ThresholdAlpha(_) => tiles(area, |tile| {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let mut data = surface.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
for pixel in data.chunks_exact_mut(channels) {
|
||||
if pixel.iter().any(|value| !value.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let alpha = pixel.last_mut().ok_or(Error::AlphaRequired)?;
|
||||
*alpha = alpha_value(operation, *alpha)?;
|
||||
}
|
||||
output.try_write_region(tile, &data).map_err(|_| Error::Allocation)
|
||||
})?,
|
||||
Operation::AlphaToColor => tiles(area, |tile| {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let mut data = surface.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
for pixel in data.chunks_exact_mut(channels) {
|
||||
alpha_to_color(pixel, surface.format().mode)?;
|
||||
}
|
||||
output.try_write_region(tile, &data).map_err(|_| Error::Allocation)
|
||||
})?,
|
||||
Operation::FillHoles { connectivity, alpha_only } => {
|
||||
let first = if alpha_only { channels.checked_sub(1).ok_or(Error::AlphaRequired)? } else { 0 };
|
||||
let count = channels - first;
|
||||
for channel in first..channels {
|
||||
let mut plane = plane_from(surface, domain, shape, channel, ctl)?;
|
||||
fill(&mut plane, shape, connectivity, ctl)?;
|
||||
tiles(area, |tile| {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let mut data = output.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
let width = usize::try_from(tile.width()).map_err(|_| Error::InvalidGeometry)?;
|
||||
for (pixel, samples) in data.chunks_exact_mut(channels).enumerate() {
|
||||
let x = usize::try_from(i64::from(tile.x0) - i64::from(domain.x0))
|
||||
.map_err(|_| Error::InvalidGeometry)?
|
||||
.checked_add(pixel % width)
|
||||
.ok_or(Error::InvalidGeometry)?;
|
||||
let y = usize::try_from(i64::from(tile.y0) - i64::from(domain.y0))
|
||||
.map_err(|_| Error::InvalidGeometry)?
|
||||
.checked_add(pixel / width)
|
||||
.ok_or(Error::InvalidGeometry)?;
|
||||
let index = y.checked_mul(shape.width).and_then(|v| v.checked_add(x)).ok_or(Error::InvalidGeometry)?;
|
||||
*samples.get_mut(channel).ok_or(Error::InvalidGeometry)? = *plane.get(index).ok_or(Error::InvalidGeometry)?;
|
||||
}
|
||||
output.try_write_region(tile, &data).map_err(|_| Error::Allocation)
|
||||
})?;
|
||||
ctl.progress((channel - first + 1) as f32 / count as f32);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(selection) = selection {
|
||||
tiles(area, |tile| {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let selected = selection.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
if selected.chunks_exact(selection.channels()).any(|pixel| pixel.first().is_none_or(|v| !v.is_finite())) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let mut filtered = output.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
let original = Image { rect: tile, ch: channels, data: surface.try_read_region(tile).map_err(|_| Error::Allocation)? };
|
||||
super::mix_selection(&mut filtered, tile, selection, &original, surface.format().alpha);
|
||||
if filtered.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
output.try_write_region(tile, &filtered).map_err(|_| Error::Allocation)
|
||||
})?;
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
ctl.progress(1.0);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Legacy infallible raw-kernel adapter. Valid image regions retain identity on a rejected
|
||||
/// operation rather than returning a short buffer. Production Surface callers use checked
|
||||
/// apply_with directly, so workspace/parameter errors are never reported as successful edits.
|
||||
/// As with other raw kernels, malformed image geometry is outside this low-level contract;
|
||||
/// it yields no samples, never an input-derived unbounded allocation or panic.
|
||||
pub(crate) fn run_image(source: &Image, out: Rect, ctx: &Ctx, operation: Operation<'_>) -> Vec<f32> {
|
||||
let run = || -> Result<Vec<f32>, Error> {
|
||||
if PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha).channels() != source.ch {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
validate(operation, ctx.alpha)?;
|
||||
let geometry = shape(source.rect, source.ch, operation)?;
|
||||
let mut result = identity_region(source, out)?;
|
||||
let workspace = if matches!(operation, Operation::FillHoles { .. }) {
|
||||
geometry.pixels.checked_mul(std::mem::size_of::<Node>() + 5).ok_or(Error::WorkspaceLimit)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if result.len().checked_mul(4).and_then(|n| n.checked_add(workspace)).is_none_or(|n| n > MAX_WORKSPACE_BYTES) {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
match operation {
|
||||
Operation::SetAlpha(_) | Operation::AlphaCurve(_) | Operation::ClampAlpha { .. } | Operation::ThresholdAlpha(_) => {
|
||||
for pixel in result.chunks_exact_mut(source.ch) {
|
||||
let a = pixel.last_mut().ok_or(Error::AlphaRequired)?;
|
||||
*a = alpha_value(operation, *a)?;
|
||||
}
|
||||
}
|
||||
Operation::AlphaToColor => {
|
||||
for pixel in result.chunks_exact_mut(source.ch) {
|
||||
alpha_to_color(pixel, ctx.mode)?;
|
||||
}
|
||||
}
|
||||
Operation::FillHoles { connectivity, alpha_only } => {
|
||||
let first = if alpha_only { source.ch.checked_sub(1).ok_or(Error::AlphaRequired)? } else { 0 };
|
||||
for channel in first..source.ch {
|
||||
let mut plane = zeroes(geometry.pixels, 0., &Interrupt::NONE)?;
|
||||
for (target, pixel) in plane.iter_mut().zip(source.data.chunks_exact(source.ch)) {
|
||||
*target = *pixel.get(channel).ok_or(Error::InvalidGeometry)?;
|
||||
}
|
||||
fill(&mut plane, geometry, connectivity, &Interrupt::NONE)?;
|
||||
let width = usize::try_from(i64::from(out.x1) - i64::from(out.x0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
let x = usize::try_from(i64::from(out.x0) - i64::from(source.rect.x0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
let y = usize::try_from(i64::from(out.y0) - i64::from(source.rect.y0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
for (i, pixel) in result.chunks_exact_mut(source.ch).enumerate() {
|
||||
let index = y
|
||||
.checked_add(i / width)
|
||||
.and_then(|n| n.checked_mul(geometry.width))
|
||||
.and_then(|n| n.checked_add(x))
|
||||
.and_then(|n| n.checked_add(i % width))
|
||||
.ok_or(Error::InvalidGeometry)?;
|
||||
*pixel.get_mut(channel).ok_or(Error::InvalidGeometry)? = *plane.get(index).ok_or(Error::InvalidGeometry)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
};
|
||||
run().unwrap_or_else(|_| identity_region(source, out).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Copy a valid contained raw-image region for the infallible adapter's rejected-operation fallback.
|
||||
fn identity_region(source: &Image, out: Rect) -> Result<Vec<f32>, Error> {
|
||||
let input = shape(source.rect, source.ch, Operation::SetAlpha(1.))?;
|
||||
let output = shape(out, source.ch, Operation::SetAlpha(1.))?;
|
||||
if out.intersect(&source.rect) != out || input.pixels.checked_mul(source.ch) != Some(source.data.len()) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let len = output.pixels.checked_mul(source.ch).filter(|n| n.checked_mul(4).is_some_and(|n| n <= MAX_WORKSPACE_BYTES)).ok_or(Error::WorkspaceLimit)?;
|
||||
let mut result = Vec::new();
|
||||
result.try_reserve_exact(len).map_err(|_| Error::Allocation)?;
|
||||
let row_len = output.width.checked_mul(source.ch).ok_or(Error::InvalidGeometry)?;
|
||||
let x = usize::try_from(i64::from(out.x0) - i64::from(source.rect.x0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
let y = usize::try_from(i64::from(out.y0) - i64::from(source.rect.y0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
for row in 0..output.height {
|
||||
let start = y
|
||||
.checked_add(row)
|
||||
.and_then(|n| n.checked_mul(input.width))
|
||||
.and_then(|n| n.checked_add(x))
|
||||
.and_then(|n| n.checked_mul(source.ch))
|
||||
.ok_or(Error::InvalidGeometry)?;
|
||||
let end = start.checked_add(row_len).ok_or(Error::InvalidGeometry)?;
|
||||
result.extend_from_slice(source.data.get(start..end).ok_or(Error::InvalidGeometry)?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_color::ColorMode;
|
||||
#[test]
|
||||
/// Allow small point edits on large owners while keeping reconstruction, geometry and output workspace limits.
|
||||
fn small_point_operations_in_large_domain_keep_reconstruction_and_output_limits() {
|
||||
let area = Rect::new(11, 13, 12, 14);
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, true, area, &[0.2, 0.4, 0.6, 0.5]);
|
||||
let domain = Rect::new(0, 0, 12_000, 8_000);
|
||||
let curve: Vec<_> = (0..256).map(|i| i as f32 / 255.).collect();
|
||||
for op in [
|
||||
Operation::SetAlpha(0.25),
|
||||
Operation::AlphaCurve(&curve),
|
||||
Operation::AlphaToColor,
|
||||
Operation::ClampAlpha { low: 0., high: 0.3 },
|
||||
Operation::ThresholdAlpha(0.4),
|
||||
] {
|
||||
assert_eq!(apply_with(&s, op, area, domain, None, &Interrupt::NONE).unwrap(), apply(&s, op, area));
|
||||
assert_eq!(apply_with(&s, op, domain, domain, None, &Interrupt::NONE), Err(Error::WorkspaceLimit));
|
||||
}
|
||||
let fill = Operation::FillHoles { connectivity: 4, alpha_only: true };
|
||||
assert_eq!(apply_with(&s, fill, area, domain, None, &Interrupt::NONE), Err(Error::WorkspaceLimit));
|
||||
assert_eq!(apply_with(&s, Operation::SetAlpha(0.5), area, Rect::new(0, 0, 0, 1), None, &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
}
|
||||
/// Encode explicit test samples at the requested native mode, depth and alpha layout.
|
||||
fn surface(mode: ColorMode, depth: SampleType, alpha: bool, rect: Rect, data: &[f32]) -> Surface {
|
||||
let mut s = Surface::new(PixelFormat::new(mode, depth, alpha));
|
||||
s.try_write_region(rect, data).unwrap();
|
||||
s
|
||||
}
|
||||
/// Run a checked operation over the complete fixture domain with no selection or cancellation.
|
||||
fn apply(s: &Surface, op: Operation, r: Rect) -> Surface {
|
||||
apply_with(s, op, r, r, None, &Interrupt::NONE).unwrap()
|
||||
}
|
||||
#[test]
|
||||
/// Compare heap-based reconstruction against a separately iterated grayscale relaxation oracle over varied inputs.
|
||||
fn grayscale_reconstruction_matches_independent_iterative_oracle() {
|
||||
let r = Rect::new(-3, 2, 4, 8);
|
||||
let (w, h) = (7usize, 6usize);
|
||||
for seed in 0..12u32 {
|
||||
let mut state = seed + 1;
|
||||
let input: Vec<f32> = (0..w * h)
|
||||
.map(|_| {
|
||||
state = state.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
(state % 17) as f32 / 16.
|
||||
})
|
||||
.collect();
|
||||
let mut oracle = vec![f32::INFINITY; input.len()];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
if x == 0 || y == 0 || x + 1 == w || y + 1 == h {
|
||||
oracle[y * w + x] = input[y * w + x];
|
||||
}
|
||||
}
|
||||
}
|
||||
loop {
|
||||
let previous = oracle.clone();
|
||||
for y in 1..h - 1 {
|
||||
for x in 1..w - 1 {
|
||||
let i = y * w + x;
|
||||
oracle[i] = input[i].max(previous[i - 1].min(previous[i + 1]).min(previous[i - w]).min(previous[i + w]));
|
||||
}
|
||||
}
|
||||
if oracle == previous {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let s = surface(ColorMode::Grayscale, SampleType::F32, false, r, &input);
|
||||
let got = apply(&s, Operation::FillHoles { connectivity: 4, alpha_only: false }, r);
|
||||
assert_eq!(got.read_region(r), oracle);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Pin the different diagonal escape rules and the exact enclosing spill level with small hand-authored planes.
|
||||
fn connectivity_distinguishes_diagonal_escape_and_preserves_spill_levels() {
|
||||
let r = Rect::new(0, 0, 3, 3);
|
||||
let input = [0., 1., 1., 1., 0.2, 1., 1., 1., 1.];
|
||||
let s = surface(ColorMode::Grayscale, SampleType::F32, false, r, &input);
|
||||
assert_eq!(apply(&s, Operation::FillHoles { connectivity: 4, alpha_only: false }, r).pixel(1, 1), vec![1.]);
|
||||
assert_eq!(apply(&s, Operation::FillHoles { connectivity: 8, alpha_only: false }, r).pixel(1, 1), vec![0.2]);
|
||||
let s = surface(ColorMode::Grayscale, SampleType::F32, false, r, &[0.7, 0.7, 0.7, 0.7, 0.1, 0.7, 0.7, 0.7, 0.7]);
|
||||
assert_eq!(apply(&s, Operation::FillHoles { connectivity: 4, alpha_only: false }, r).pixel(1, 1), vec![0.7]);
|
||||
}
|
||||
#[test]
|
||||
/// Require absolute alpha replacement to leave all stored color channels unchanged across native models and depths.
|
||||
fn every_native_model_depth_keeps_color_when_replacing_absolute_alpha() {
|
||||
let r = Rect::new(0, 0, 2, 1);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let fmt = PixelFormat::new(mode, depth, true);
|
||||
let ch = fmt.channels();
|
||||
let mut data = vec![0.37; ch * 2];
|
||||
data[ch - 1] = 0.;
|
||||
data[ch * 2 - 1] = 1.;
|
||||
if depth == SampleType::F32 {
|
||||
data[0] = -2.;
|
||||
data[ch] = 7.;
|
||||
}
|
||||
let s = surface(mode, depth, true, r, &data);
|
||||
let before = s.read_region(r);
|
||||
let got = apply(&s, Operation::SetAlpha(0.5), r).read_region(r);
|
||||
for i in 0..ch * 2 {
|
||||
if i % ch == ch - 1 {
|
||||
assert!((got[i] - 0.5).abs() < 0.003)
|
||||
} else {
|
||||
assert_eq!(got[i], before[i]);
|
||||
}
|
||||
}
|
||||
let ring = Rect::new(0, 0, 3, 3);
|
||||
let mut values = vec![0.4; ch * 9];
|
||||
for pixel in values.chunks_exact_mut(ch) {
|
||||
pixel[ch - 1] = 1.;
|
||||
if depth == SampleType::F32 {
|
||||
pixel[0] = -2.;
|
||||
}
|
||||
}
|
||||
values[4 * ch + ch - 1] = 0.;
|
||||
let s = surface(mode, depth, true, ring, &values);
|
||||
let before = s.read_region(ring);
|
||||
let filled = apply(&s, Operation::FillHoles { connectivity: 4, alpha_only: true }, ring).read_region(ring);
|
||||
for (old, new) in before.chunks_exact(ch).zip(filled.chunks_exact(ch)) {
|
||||
assert_eq!(&old[..ch - 1], &new[..ch - 1]);
|
||||
assert_eq!(new[ch - 1], 1.);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Check native alpha bounds and strict greater-than thresholding against already quantized source samples.
|
||||
fn clamp_and_strict_threshold_preserve_native_color_and_quantized_boundary_rules() {
|
||||
let r = Rect::new(0, 0, 5, 1);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let channels = PixelFormat::new(mode, depth, true).channels();
|
||||
let data: Vec<f32> = (0..5)
|
||||
.flat_map(|i| {
|
||||
let mut pixel = vec![if depth == SampleType::F32 { -2. } else { 0.3 }; channels];
|
||||
pixel[channels - 1] = i as f32 / 4.;
|
||||
pixel
|
||||
})
|
||||
.collect();
|
||||
let s = surface(mode, depth, true, r, &data);
|
||||
let before = s.read_region(r);
|
||||
for operation in [Operation::ClampAlpha { low: 0.25, high: 0.75 }, Operation::ThresholdAlpha(0.5)] {
|
||||
let got = apply(&s, operation, r).read_region(r);
|
||||
for (original, changed) in before.chunks_exact(channels).zip(got.chunks_exact(channels)) {
|
||||
assert_eq!(&changed[..channels - 1], &original[..channels - 1]);
|
||||
let expected = alpha_value(operation, original[channels - 1]).unwrap();
|
||||
assert!((changed[channels - 1] - expected).abs() < 0.003);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for operation in [Operation::ClampAlpha { low: 0.8, high: 0.2 }, Operation::ClampAlpha { low: f32::NAN, high: 1. }, Operation::ThresholdAlpha(2.)] {
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, true, r, &[0.; 20]);
|
||||
assert!(apply_with(&s, operation, r, r, None, &Interrupt::NONE).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Compare alpha transfer to independently calculated square samples and midpoint interpolation, including invalid
|
||||
/// table rejection.
|
||||
fn native_alpha_transfer_interpolates_preserves_colors_and_respects_depth() {
|
||||
let values: Vec<f32> = (0..256).map(|i| (i as f32 / 255.).powi(2)).collect();
|
||||
let r = Rect::new(0, 0, 5, 1);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let ch = PixelFormat::new(mode, depth, true).channels();
|
||||
let data: Vec<f32> = (0..5)
|
||||
.flat_map(|i| {
|
||||
let mut p = vec![if depth == SampleType::F32 { -3. } else { 0.4 }; ch];
|
||||
p[ch - 1] = i as f32 / 4.;
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
let s = surface(mode, depth, true, r, &data);
|
||||
let original = s.read_region(r);
|
||||
let got = apply(&s, Operation::AlphaCurve(&values), r).read_region(r);
|
||||
for (a, b) in original.chunks_exact(ch).zip(got.chunks_exact(ch)) {
|
||||
assert_eq!(&a[..ch - 1], &b[..ch - 1]);
|
||||
assert!((b[ch - 1] - a[ch - 1].powi(2)).abs() < 0.003);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!((alpha_value(Operation::AlphaCurve(&values), 0.5).unwrap() - (values[127] + values[128]) / 2.).abs() < 1e-7);
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, true, r, &[-3.; 20]);
|
||||
for bad in [&values[..255], &[f32::NAN; 256][..], &[1.1; 256][..]] {
|
||||
assert_eq!(apply_with(&s, Operation::AlphaCurve(bad), r, r, None, &Interrupt::NONE).unwrap_err(), Error::InvalidParameter);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Verify mode-specific neutral encodings and opaque output, including native CMYK and Lab normalization.
|
||||
fn alpha_to_color_is_opaque_native_neutral_data_without_model_conversion() {
|
||||
let r = Rect::new(0, 0, 3, 1);
|
||||
for mode in [
|
||||
ColorMode::Bitmap,
|
||||
ColorMode::Grayscale,
|
||||
ColorMode::Indexed,
|
||||
ColorMode::Rgb,
|
||||
ColorMode::Cmyk,
|
||||
ColorMode::Lab,
|
||||
ColorMode::Multichannel,
|
||||
ColorMode::Duotone,
|
||||
] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let ch = PixelFormat::new(mode, depth, true).channels();
|
||||
let data: Vec<f32> = (0..3)
|
||||
.flat_map(|i| {
|
||||
let mut p = vec![0.7; ch];
|
||||
p[ch - 1] = i as f32 / 2.;
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
let s = surface(mode, depth, true, r, &data);
|
||||
let old = s.read_region(r);
|
||||
let got = apply(&s, Operation::AlphaToColor, r);
|
||||
assert_eq!(got.format(), s.format());
|
||||
for (input, p) in old.chunks_exact(ch).zip(got.read_region(r).chunks_exact(ch)) {
|
||||
let a = input[ch - 1];
|
||||
assert_eq!(p[ch - 1], 1.);
|
||||
for (i, value) in p.iter().take(ch - 1).enumerate() {
|
||||
let expected = match mode {
|
||||
ColorMode::Cmyk => {
|
||||
if i == 3 {
|
||||
1. - a
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
ColorMode::Lab => {
|
||||
if i == 0 {
|
||||
a
|
||||
} else {
|
||||
128. / 255.
|
||||
}
|
||||
}
|
||||
_ => a,
|
||||
};
|
||||
assert!((value - expected).abs() < 0.003);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let normalization = photocraft_raster::from_rgba(&PixelFormat::new(ColorMode::Lab, SampleType::F32, true), [0., 0., 0., 1.]);
|
||||
assert_eq!(&normalization[1..3], &[128. / 255., 128. / 255.]);
|
||||
}
|
||||
#[test]
|
||||
/// Pin selection mixing once and require cancelled alpha transfers to leave their HDR source unchanged.
|
||||
fn alpha_transfer_selection_and_cancellation_are_atomic() {
|
||||
let r = Rect::new(0, 0, 128, 128);
|
||||
let mut s = Surface::new(PixelFormat::RGBA32F);
|
||||
s.fill_rect(r, &[-2., 3., 0.4, 0.25]);
|
||||
let original = s.read_region(r);
|
||||
let values: Vec<f32> = (0..256).map(|i| i as f32 / 255.).collect();
|
||||
let mask = surface(ColorMode::Grayscale, SampleType::F32, false, Rect::new(0, 0, 1, 1), &[0.5]);
|
||||
let got = apply_with(&s, Operation::AlphaToColor, Rect::new(0, 0, 1, 1), r, Some(&mask), &Interrupt::NONE).unwrap();
|
||||
assert_eq!(got.pixel(0, 0)[3], 0.625);
|
||||
assert!((got.pixel(0, 0)[0] + 0.2).abs() < 1e-6);
|
||||
let calls = std::sync::atomic::AtomicUsize::new(0);
|
||||
let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 2;
|
||||
assert_eq!(apply_with(&s, Operation::AlphaCurve(&values), r, r, None, &Interrupt::cancel_only(&cancel)).unwrap_err(), Error::Cancelled);
|
||||
assert_eq!(s.read_region(r), original);
|
||||
}
|
||||
#[test]
|
||||
/// Reject nonfinite color or coverage with and without a selection, including failures after a valid tile.
|
||||
fn alpha_operations_reject_nonfinite_samples_without_changing_source() {
|
||||
let area = Rect::new(0, 0, 65, 1);
|
||||
let curve: Vec<f32> = (0..256).map(|value| value as f32 / 255.).collect();
|
||||
let selection = surface(ColorMode::Grayscale, SampleType::F32, false, area, &[0.5; 65]);
|
||||
for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
let format = PixelFormat::new(mode, SampleType::F32, true);
|
||||
for channel in [0, format.channels() - 1] {
|
||||
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let mut source = Surface::new(format);
|
||||
let mut pixel = vec![0.5; format.channels()];
|
||||
source.fill_rect(area, &pixel);
|
||||
pixel[channel] = invalid;
|
||||
source.write_pixel(64, 0, &pixel);
|
||||
let before: Vec<_> = source.read_region(area).into_iter().map(f32::to_bits).collect();
|
||||
for operation in [
|
||||
Operation::SetAlpha(0.25),
|
||||
Operation::AlphaCurve(&curve),
|
||||
Operation::ClampAlpha { low: 0.1, high: 0.9 },
|
||||
Operation::ThresholdAlpha(0.25),
|
||||
Operation::AlphaToColor,
|
||||
] {
|
||||
for mask in [None, Some(&selection)] {
|
||||
assert_eq!(
|
||||
apply_with(&source, operation, area, area, mask, &Interrupt::NONE).unwrap_err(),
|
||||
Error::NonFiniteSample,
|
||||
"{mode:?}/{operation:?}/channel={channel}/sample={invalid}"
|
||||
);
|
||||
assert_eq!(source.read_region(area).into_iter().map(f32::to_bits).collect::<Vec<_>>(), before);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Fill an alpha hole without changing HDR color, then verify a half selection publishes half coverage only once.
|
||||
fn alpha_topology_preserves_hdr_color_and_selection_publishes_only_once() {
|
||||
let r = Rect::new(0, 0, 3, 3);
|
||||
let data: Vec<f32> = (0..9).flat_map(|i| [-2., 4., 0.3, if i == 4 { 0. } else { 1. }]).collect();
|
||||
let s = surface(ColorMode::Rgb, SampleType::F32, true, r, &data);
|
||||
let got = apply(&s, Operation::FillHoles { connectivity: 4, alpha_only: true }, r);
|
||||
assert_eq!(got.pixel(1, 1), vec![-2., 4., 0.3, 1.]);
|
||||
let mask = surface(ColorMode::Grayscale, SampleType::F32, false, r, &[0.5; 9]);
|
||||
let got = apply_with(&s, Operation::SetAlpha(1.), r, r, Some(&mask), &Interrupt::NONE).unwrap();
|
||||
assert_eq!(got.pixel(1, 1)[3], 0.5);
|
||||
assert_eq!(s.pixel(1, 1)[3], 0.);
|
||||
}
|
||||
#[test]
|
||||
/// Ensure hole connectivity is computed over the full owner even when only a small result area is published.
|
||||
fn topology_uses_whole_owner_even_with_small_publication_and_filter_tiles() {
|
||||
let r = Rect::new(0, 0, 7, 7);
|
||||
let mut data = vec![1.; 49];
|
||||
for y in 1..6 {
|
||||
for x in 1..6 {
|
||||
data[y * 7 + x] = 0.;
|
||||
}
|
||||
}
|
||||
let s = surface(ColorMode::Grayscale, SampleType::F32, false, r, &data);
|
||||
let fp = crate::FilterParams::FillHoles { connectivity: 4, alpha_only: false };
|
||||
for tile in [1, 2, 64] {
|
||||
let out = crate::apply_tiled_with(&s, &fp, Rect::new(3, 3, 4, 4), r, None, tile, Some(r), &Interrupt::NONE).unwrap();
|
||||
assert_eq!(out.pixel(3, 3), vec![1.]);
|
||||
assert_eq!(out.pixel(2, 3), vec![0.]);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Require rejected alpha work on a non-alpha raw image to return the correctly shaped unchanged region.
|
||||
fn infallible_raw_adapter_keeps_valid_identity_shape_when_operation_is_rejected() {
|
||||
let image = Image { rect: Rect::new(0, 0, 3, 2), ch: 1, data: vec![0.3; 6] };
|
||||
let ctx = Ctx { mode: ColorMode::Grayscale, alpha: false, bounds: image.rect };
|
||||
assert_eq!(run_image(&image, Rect::new(1, 0, 3, 2), &ctx, Operation::SetAlpha(0.5)), vec![0.3; 4]);
|
||||
}
|
||||
#[test]
|
||||
/// Reject an offset, thin surface whose padded native tiles exceed the workspace despite its smaller visible area.
|
||||
fn padded_output_tiles_are_charged_before_allocating_thin_or_unaligned_surfaces() {
|
||||
let s = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true));
|
||||
let rect = Rect::new(255, 0, 767, 65_536);
|
||||
let shape = shape(rect, 5, Operation::FillHoles { connectivity: 4, alpha_only: false }).unwrap();
|
||||
assert_eq!(preflight(&s, rect, shape, Operation::FillHoles { connectivity: 4, alpha_only: false }, None), Err(Error::WorkspaceLimit));
|
||||
}
|
||||
#[test]
|
||||
/// Exercise invalid controls, nonfinite samples and mid-work cancellation without mutating the original surface.
|
||||
fn hostile_input_and_midwork_cancellation_are_atomic() {
|
||||
let r = Rect::new(0, 0, 128, 128);
|
||||
let s = surface(ColorMode::Grayscale, SampleType::F32, false, r, &vec![0.2; 128 * 128]);
|
||||
let before = s.read_region(r);
|
||||
let calls = std::sync::atomic::AtomicUsize::new(0);
|
||||
let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 5;
|
||||
assert_eq!(
|
||||
apply_with(&s, Operation::FillHoles { connectivity: 4, alpha_only: false }, r, r, None, &Interrupt::cancel_only(&cancel)).unwrap_err(),
|
||||
Error::Cancelled
|
||||
);
|
||||
assert_eq!(s.read_region(r), before);
|
||||
for op in [Operation::SetAlpha(0.5), Operation::SetAlpha(f32::NAN), Operation::FillHoles { connectivity: 9, alpha_only: false }] {
|
||||
assert!(apply_with(&s, op, r, r, None, &Interrupt::NONE).is_err());
|
||||
}
|
||||
assert!(
|
||||
apply_with(&s, Operation::FillHoles { connectivity: 4, alpha_only: false }, r, Rect::new(i32::MIN, 0, i32::MAX, 2), None, &Interrupt::NONE)
|
||||
.is_err()
|
||||
);
|
||||
let n = surface(ColorMode::Grayscale, SampleType::F32, false, Rect::new(0, 0, 1, 1), &[f32::NAN]);
|
||||
assert_eq!(
|
||||
apply_with(&n, Operation::FillHoles { connectivity: 4, alpha_only: false }, Rect::new(0, 0, 1, 1), Rect::new(0, 0, 1, 1), None, &Interrupt::NONE)
|
||||
.unwrap_err(),
|
||||
Error::NonFiniteSample
|
||||
);
|
||||
}
|
||||
}
|
||||
+243
-26
@@ -11,6 +11,9 @@ use crate::noise::hash01;
|
||||
|
||||
/// Max channels per pixel we keep on the stack (CMYK + alpha + spare).
|
||||
pub(crate) const MAXC: usize = 8;
|
||||
/// Scratch a column gather may hold: L2-resident, so the transposed strip stays hot while it is
|
||||
/// read back. Larger strips evict it and lose the point of gathering.
|
||||
const STRIP_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// The context's model as an `f32` format (for colour conversions).
|
||||
#[inline]
|
||||
@@ -109,39 +112,130 @@ pub(crate) fn unpremul_px(px: &mut [f32], alpha: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// In-place running-sum box blur of every row of a `w × h × n` interleaved
|
||||
/// buffer with radius `r` (edges clamped). `scratch` must hold `w × n`.
|
||||
fn box_rows_n(buf: &mut [f32], w: usize, n: usize, r: usize, scratch: &mut Vec<f32>) {
|
||||
if r == 0 || w == 0 {
|
||||
return;
|
||||
}
|
||||
/// One line of `w` interleaved `n`-channel samples, blurred in place by a running sum (edges
|
||||
/// clamped). `scratch` holds the untouched line so an in-place sweep can still read behind it.
|
||||
fn box_line_n(line: &mut [f32], w: usize, n: usize, r: usize, scratch: &mut Vec<f32>) {
|
||||
debug_assert!(n <= MAXC, "one accumulator per channel");
|
||||
scratch.clear();
|
||||
scratch.extend_from_slice(&line[..w * n]);
|
||||
let src = &scratch[..];
|
||||
let norm = 1.0 / (2 * r + 1) as f64;
|
||||
for row in buf.chunks_exact_mut(w * n) {
|
||||
scratch.clear();
|
||||
scratch.extend_from_slice(row);
|
||||
// f64 sums: rounding must not depend on where a window starts (tile independence).
|
||||
let at = |x: isize, c: usize| scratch[(x.clamp(0, w as isize - 1) as usize) * n + c] as f64;
|
||||
// A tap clamps only within `r` (or `r + 1`) of an end. Between those the index is plain, so
|
||||
// the bulk of the line skips the clamp and the bounds check; the arithmetic is unchanged.
|
||||
// The invariant that makes the plain indices safe: the middle runs while `x >= r` and
|
||||
// `x <= w - r - 2`, where `x - r >= 0` and `x + r + 1 <= w - 1`. `first` is `r` (a line
|
||||
// shorter than the radius has no middle: `first = w`) and `last` is `w - (r + 1)`, never
|
||||
// below `first`; outside that span both taps clamp, which is the same sum, so every index
|
||||
// stays inside the untouched copy `src[..w * n]` for any `w`, `r` and `n <= MAXC`.
|
||||
let first = r.min(w);
|
||||
let last = w.saturating_sub(r + 1).max(first);
|
||||
// f64 sums: rounding must not depend on where a window starts (tile independence).
|
||||
let mut acc = [0.0f64; MAXC];
|
||||
for c in 0..n {
|
||||
let at = |x: isize| src[(x.clamp(0, w as isize - 1) as usize) * n + c] as f64;
|
||||
acc[c] = (-(r as isize)..=r as isize).map(at).sum();
|
||||
}
|
||||
for x in 0..w {
|
||||
for c in 0..n {
|
||||
let mut acc: f64 = (-(r as isize)..=r as isize).map(|x| at(x, c)).sum();
|
||||
for x in 0..w {
|
||||
row[x * n + c] = (acc * norm) as f32;
|
||||
acc += at(x as isize + r as isize + 1, c) - at(x as isize - r as isize, c);
|
||||
line[x * n + c] = (acc[c] * norm) as f32;
|
||||
}
|
||||
if x >= first && x < last {
|
||||
let (out, inp) = ((x + r + 1) * n, (x - r) * n);
|
||||
for c in 0..n {
|
||||
acc[c] += src[out + c] as f64 - src[inp + c] as f64;
|
||||
}
|
||||
} else {
|
||||
for c in 0..n {
|
||||
let at = |i: isize| src[(i.clamp(0, w as isize - 1) as usize) * n + c] as f64;
|
||||
acc[c] += at(x as isize + r as isize + 1) - at(x as isize - r as isize);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Same as [`box_rows_n`] over columns (no transpose; walks with a stride).
|
||||
fn box_cols_n(buf: &mut [f32], w: usize, h: usize, n: usize, r: usize, scratch: &mut Vec<f32>) {
|
||||
if r == 0 || h == 0 {
|
||||
/// In-place box blur of every row of a `w × h × n` interleaved buffer with radius `r` (edges
|
||||
/// clamped).
|
||||
fn box_rows_n(buf: &mut [f32], w: usize, n: usize, r: usize) {
|
||||
let band = w * n;
|
||||
if r == 0 || band == 0 {
|
||||
return;
|
||||
}
|
||||
// Trailing samples that do not fill a row are left alone, as `chunks_exact_mut` did.
|
||||
let full = buf.len() - buf.len() % band;
|
||||
let mut scratch = Vec::with_capacity(band);
|
||||
for row in buf[..full].chunks_exact_mut(band) {
|
||||
box_line_n(row, w, n, r, &mut scratch);
|
||||
}
|
||||
}
|
||||
|
||||
/// Same as [`box_rows_n`] over columns (no transpose of the whole buffer; gathers a strip).
|
||||
///
|
||||
/// A column walk reads one sample per row at a stride of `w * n`, so every sample pulls its own
|
||||
/// cache line and uses `n * 4` of its 64 bytes: on a 1122-wide RGBA buffer that is 8x the
|
||||
/// image's traffic. Gathering `STRIP_BYTES` worth of neighbouring columns into a transposed
|
||||
/// scratch first replaces that with one line read per row, and the running sum then walks
|
||||
/// contiguous runs. `box_line_n`'s rule holds per column too: outside `r` of the ends both taps
|
||||
/// are in range, so only the ends clamp.
|
||||
fn box_cols_n(buf: &mut [f32], w: usize, h: usize, n: usize, r: usize) {
|
||||
if r == 0 || h == 0 || n == 0 || buf.len() < w.saturating_mul(h).saturating_mul(n) {
|
||||
return;
|
||||
}
|
||||
// Columns per gather, from the scratch budget. Below 2 the gather costs more than it saves.
|
||||
let strip = (STRIP_BYTES / (n * h * 4)).clamp(0, w);
|
||||
if strip < 2 {
|
||||
box_cols_strided(buf, w, h, n, r);
|
||||
return;
|
||||
}
|
||||
let norm = 1.0 / (2 * r + 1) as f64;
|
||||
let first = r.min(h);
|
||||
let last = h.saturating_sub(r + 1).max(first);
|
||||
let mut scratch: Vec<f32> = Vec::with_capacity(strip * n * h);
|
||||
let mut x0 = 0;
|
||||
while x0 < w {
|
||||
let sx = strip.min(w - x0);
|
||||
let runs = sx * n;
|
||||
// Transposed gather: run `k` (column `x0 + k / n`, channel `k % n`) is contiguous.
|
||||
scratch.clear();
|
||||
scratch.resize(runs * h, 0.0);
|
||||
for y in 0..h {
|
||||
let base = (y * w + x0) * n;
|
||||
for k in 0..runs {
|
||||
scratch[k * h + y] = buf[base + k];
|
||||
}
|
||||
}
|
||||
for k in 0..runs {
|
||||
let src = &scratch[k * h..][..h];
|
||||
let (col, ch) = (k / n, k % n);
|
||||
// f64 sums, as in `box_line_n`: the result must not depend on the walk's direction.
|
||||
let mut acc: f64 = (-(r as isize)..=r as isize).map(|y| src[y.clamp(0, h as isize - 1) as usize] as f64).sum();
|
||||
for y in 0..h {
|
||||
buf[(y * w + x0 + col) * n + ch] = (acc * norm) as f32;
|
||||
if y >= first && y < last {
|
||||
acc += src[y + r + 1] as f64 - src[y - r] as f64;
|
||||
} else {
|
||||
let hi = (y + r + 1).min(h - 1);
|
||||
let lo = y.saturating_sub(r);
|
||||
acc += src[hi] as f64 - src[lo] as f64;
|
||||
}
|
||||
}
|
||||
}
|
||||
x0 += sx;
|
||||
}
|
||||
}
|
||||
|
||||
/// The column walk one sample at a time, kept for the widths one contiguous gather cannot hold.
|
||||
fn box_cols_strided(buf: &mut [f32], w: usize, h: usize, n: usize, r: usize) {
|
||||
if r == 0 || h == 0 || n == 0 {
|
||||
return;
|
||||
}
|
||||
let norm = 1.0 / (2 * r + 1) as f64;
|
||||
let mut scratch = Vec::with_capacity(h * n);
|
||||
for x in 0..w {
|
||||
scratch.clear();
|
||||
for y in 0..h {
|
||||
scratch.extend_from_slice(&buf[(y * w + x) * n..(y * w + x + 1) * n]);
|
||||
}
|
||||
// f64 sums, as in `box_line_n`: the result must not depend on the walk's direction.
|
||||
let at = |y: isize, c: usize| scratch[(y.clamp(0, h as isize - 1) as usize) * n + c] as f64;
|
||||
for c in 0..n {
|
||||
let mut acc: f64 = (-(r as isize)..=r as isize).map(|y| at(y, c)).sum();
|
||||
@@ -155,9 +249,8 @@ fn box_cols_n(buf: &mut [f32], w: usize, h: usize, n: usize, r: usize, scratch:
|
||||
|
||||
/// Box blur of an interleaved buffer (radius `r` in both directions).
|
||||
pub(crate) fn box_blur_n(buf: &mut [f32], w: usize, h: usize, n: usize, r: usize) {
|
||||
let mut scratch = Vec::with_capacity(w.max(h) * n);
|
||||
box_rows_n(buf, w, n, r, &mut scratch);
|
||||
box_cols_n(buf, w, h, n, r, &mut scratch);
|
||||
box_rows_n(buf, w, n, r);
|
||||
box_cols_n(buf, w, h, n, r);
|
||||
}
|
||||
|
||||
/// Odd box widths whose 3-fold convolution approximates a Gaussian of `sigma`
|
||||
@@ -192,12 +285,12 @@ pub(crate) fn gauss_blur_n(buf: &mut [f32], w: usize, h: usize, n: usize, sigma:
|
||||
if sigma < 0.3 {
|
||||
return;
|
||||
}
|
||||
let mut scratch = Vec::with_capacity(w.max(h) * n);
|
||||
for r in gauss_box_radii(sigma) {
|
||||
box_rows_n(buf, w, n, r, &mut scratch);
|
||||
let radii = gauss_box_radii(sigma);
|
||||
for r in radii {
|
||||
box_rows_n(buf, w, n, r);
|
||||
}
|
||||
for r in gauss_box_radii(sigma) {
|
||||
box_cols_n(buf, w, h, n, r, &mut scratch);
|
||||
for r in radii {
|
||||
box_cols_n(buf, w, h, n, r);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,3 +343,127 @@ pub(crate) fn add_sample_premul(src: &Image, x: f32, y: f32, clip: Rect, alpha:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{box_cols_n, box_cols_strided, box_line_n, box_rows_n};
|
||||
|
||||
/// The pre-split row pass, kept verbatim as the reference: one clamped accumulator per
|
||||
/// channel, stepped with `clamp(x + r + 1) - clamp(x - r)`.
|
||||
fn reference_line(line: &[f32], w: usize, n: usize, r: usize) -> Vec<f32> {
|
||||
let norm = 1.0 / (2 * r + 1) as f64;
|
||||
let at = |x: isize, c: usize| line[(x.clamp(0, w as isize - 1) as usize) * n + c] as f64;
|
||||
let mut out = vec![0.0f32; w * n];
|
||||
for c in 0..n {
|
||||
let mut acc: f64 = (-(r as isize)..=r as isize).map(|x| at(x, c)).sum();
|
||||
for x in 0..w {
|
||||
out[x * n + c] = (acc * norm) as f32;
|
||||
acc += at(x as isize + r as isize + 1, c) - at(x as isize - r as isize, c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The bytes of each sample: `-0.0` and `+0.0` compare equal as `f32`, so the differential
|
||||
/// checks below compare bit patterns rather than values.
|
||||
fn bits(v: &[f32]) -> Vec<u32> {
|
||||
v.iter().map(|x| x.to_bits()).collect()
|
||||
}
|
||||
|
||||
fn line(w: usize, n: usize, seed: u32) -> Vec<f32> {
|
||||
let mut s = seed | 1;
|
||||
(0..w * n)
|
||||
.map(|_| {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
(s >> 8) as f32 / 16_777_216.0
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The split row pass is bit-identical to the clamped one it replaced, including the widths
|
||||
/// (and radii) where the line is shorter than the window and no plain-index middle exists.
|
||||
#[test]
|
||||
fn split_row_pass_matches_the_clamped_reference() {
|
||||
let mut scratch = Vec::new();
|
||||
// `-0.0 == 0.0` as `f32`; comparing bits is what makes the check below fail on a signed-zero
|
||||
// regression, so keep the helper rather than a plain `assert_eq!`.
|
||||
assert_ne!(bits(&[-0.0]), bits(&[0.0]));
|
||||
for r in 1..=50usize {
|
||||
for w in [1usize, 2, 3, 5, 7, 13, 32, 64, r.saturating_sub(1).max(1), r, r + 1, r + 2] {
|
||||
for n in 1..=4usize {
|
||||
let src = line(w, n, (r * 1013 + w * 31 + n) as u32);
|
||||
let mut got = src.clone();
|
||||
box_line_n(&mut got, w, n, r, &mut scratch);
|
||||
assert_eq!(bits(&got), bits(&reference_line(&src, w, n, r)), "w {w} n {n} r {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole buffer, several rows, and a trailing partial row left alone as before.
|
||||
#[test]
|
||||
fn split_row_pass_matches_the_clamped_reference_over_a_buffer() {
|
||||
for (w, h, n, r) in [(9usize, 4usize, 3usize, 2usize), (1, 3, 4, 7), (24, 5, 1, 24), (6, 6, 2, 50)] {
|
||||
let src = line(w * h, n, (w * 7 + h * 13 + r) as u32);
|
||||
let mut got = src.clone();
|
||||
box_rows_n(&mut got, w, n, r);
|
||||
for row in 0..h {
|
||||
let a = &src[row * w * n..(row + 1) * w * n];
|
||||
let b = &got[row * w * n..(row + 1) * w * n];
|
||||
assert_eq!(bits(b), bits(&reference_line(a, w, n, r)), "w {w} h {h} n {n} r {r} row {row}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A buffer with structure, so a wrong tap shows up and not just a flat field.
|
||||
fn ramp(w: usize, h: usize, n: usize) -> Vec<f32> {
|
||||
(0..w * h * n).map(|i| ((i * 37 % 251) as f32) / 251.0).collect()
|
||||
}
|
||||
|
||||
/// The strip gather must produce the strided walk's bytes: same taps, same order.
|
||||
#[test]
|
||||
fn cols_match_the_strided_walk() {
|
||||
for (w, h, n, r) in [(1, 1, 1, 1), (7, 5, 2, 2), (324, 324, 2, 9), (61, 1122, 4, 79), (0, 4, 2, 1), (5, 0, 2, 1), (33, 17, 4, 0), (9, 9, 4, 100)] {
|
||||
let mut a = ramp(w, h, n);
|
||||
let mut b = a.clone();
|
||||
box_cols_n(&mut a, w, h, n, r);
|
||||
box_cols_strided(&mut b, w, h, n, r);
|
||||
let bits = |v: &Vec<f32>| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
|
||||
assert_eq!(bits(&a), bits(&b), "{w}x{h}x{n} r{r} diverged");
|
||||
}
|
||||
// Every radius 1 to 50 at a width the gather spans in several strips (19 columns, runs of
|
||||
// 3), and at a height shorter than the radius: the same bytes as the strided walk.
|
||||
for r in 1..=50usize {
|
||||
for (w, h, n) in [(19usize, 1122usize, 4usize), (13, 3, 1), (7, 1, 2)] {
|
||||
let mut a = ramp(w, h, n);
|
||||
let mut b = a.clone();
|
||||
box_cols_n(&mut a, w, h, n, r);
|
||||
box_cols_strided(&mut b, w, h, n, r);
|
||||
let bits = |v: &Vec<f32>| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
|
||||
assert_eq!(bits(&a), bits(&b), "{w}x{h}x{n} r{r} diverged");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test -p photocraft-algo --release --lib -- --nocapture cols_timing`
|
||||
#[test]
|
||||
fn cols_timing() {
|
||||
for (w, h, n, r) in [(324, 324, 2, 9), (1122, 1122, 2, 79), (1122, 786, 2, 79)] {
|
||||
// Each pass gets its own copy of the same input: a pass run after the other would
|
||||
// otherwise measure a buffer the other one already rewrote.
|
||||
let input = ramp(w, h, n);
|
||||
let mut out = [0.0f64; 2];
|
||||
for (k, f) in [(0usize, box_cols_strided as fn(&mut [f32], usize, usize, usize, usize)), (1, box_cols_n)] {
|
||||
let mut buf = input.clone();
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..5 {
|
||||
f(&mut buf, w, h, n, r);
|
||||
}
|
||||
out[k] = t.elapsed().as_secs_f64() * 200.0;
|
||||
}
|
||||
println!("{w}x{h}x{n} r{r}: strided {:.3} ms, strip {:.3} ms ({:.2}x)", out[0], out[1], out[0] / out[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+294
-9
@@ -21,12 +21,15 @@
|
||||
pub mod art_history;
|
||||
mod artistic;
|
||||
mod artistic_fx;
|
||||
mod average;
|
||||
pub mod average;
|
||||
mod blur;
|
||||
mod blur2;
|
||||
pub mod camera_raw;
|
||||
pub mod channel_noise;
|
||||
pub mod color_to_alpha;
|
||||
pub mod content_aware;
|
||||
pub mod convolution;
|
||||
pub mod coverage;
|
||||
mod cutout;
|
||||
mod denoise;
|
||||
pub mod dff;
|
||||
@@ -64,6 +67,7 @@ pub mod poisson;
|
||||
pub mod puppet;
|
||||
pub mod pyramid;
|
||||
pub mod quantize;
|
||||
pub mod rank;
|
||||
pub mod redeye;
|
||||
mod relight;
|
||||
pub mod remove;
|
||||
@@ -560,6 +564,38 @@ pub enum FilterParams {
|
||||
opacity_threshold: f32,
|
||||
},
|
||||
|
||||
/// Whole-owner native HDR local adaptation; existing document adjustment remains separate.
|
||||
HdrToning(tone::HdrToning),
|
||||
/// Independent native color/coverage order statistics.
|
||||
Percentile(rank::Params),
|
||||
/// Native channel-wise additive or signal-relative deterministic noise.
|
||||
ChannelNoise(channel_noise::Params),
|
||||
Convolution(convolution::Params),
|
||||
/// Coverage onto model-native neutral axes, producing opaque native pixels.
|
||||
AlphaToColor,
|
||||
/// Bounded native256-sample alpha transfer, piecewise-linear between samples.
|
||||
AlphaCurve {
|
||||
values: Vec<f32>,
|
||||
},
|
||||
/// Replace native coverage while preserving every native color channel, including HDR.
|
||||
SetAlpha {
|
||||
value: f32,
|
||||
},
|
||||
/// Clamp existing native alpha; colors remain unchanged.
|
||||
ClampAlpha {
|
||||
low: f32,
|
||||
high: f32,
|
||||
},
|
||||
/// Native strict > threshold on alpha; colors remain unchanged.
|
||||
ThresholdAlpha {
|
||||
value: f32,
|
||||
},
|
||||
/// Boundary-connected grayscale hole filling on each native channel or alpha only.
|
||||
FillHoles {
|
||||
connectivity: u8,
|
||||
alpha_only: bool,
|
||||
},
|
||||
|
||||
// ---- Video ----
|
||||
/// Removes the even (or odd) lines and rebuilds them by interpolation (or duplication).
|
||||
DeInterlace {
|
||||
@@ -603,7 +639,17 @@ impl FilterParams {
|
||||
| FilterParams::Spherize { .. }
|
||||
| FilterParams::Wave { .. }
|
||||
| FilterParams::Ripple { .. }
|
||||
| FilterParams::PolarCoordinates { .. } => Halo::Bounds,
|
||||
| FilterParams::PolarCoordinates { .. }
|
||||
| FilterParams::SetAlpha { .. }
|
||||
| FilterParams::AlphaCurve { .. }
|
||||
| FilterParams::AlphaToColor
|
||||
| FilterParams::ClampAlpha { .. }
|
||||
| FilterParams::ThresholdAlpha { .. }
|
||||
| FilterParams::FillHoles { .. }
|
||||
| FilterParams::HdrToning(_)
|
||||
| FilterParams::Percentile(_) => Halo::Bounds,
|
||||
FilterParams::ChannelNoise(_) => Halo::Bounds,
|
||||
FilterParams::Convolution(_) => Halo::Bounds,
|
||||
other => halo_ext(other),
|
||||
}
|
||||
}
|
||||
@@ -617,11 +663,29 @@ impl FilterParams {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the filter's job is to make pixels transparent (Color to Alpha): it needs a layer
|
||||
/// Whether the filter explicitly changes alpha coverage: it needs a layer
|
||||
/// that can hold transparency, so callers turn the Background into a normal layer first and
|
||||
/// refuse a layer whose transparency is locked instead of putting the old alpha back.
|
||||
pub fn makes_transparency(&self) -> bool {
|
||||
matches!(self, FilterParams::ColorToAlpha { .. })
|
||||
if let Self::ChannelNoise(params) = self {
|
||||
return params.amounts.last().is_some_and(|amount| *amount > 0.);
|
||||
}
|
||||
if let Self::Convolution(params) = self {
|
||||
return params.channels.last().copied().unwrap_or(false);
|
||||
}
|
||||
if let Self::Percentile(params) = self {
|
||||
return params.channels.as_ref().is_none_or(|channels| channels.last().copied().unwrap_or(false));
|
||||
}
|
||||
matches!(
|
||||
self,
|
||||
FilterParams::ColorToAlpha { .. }
|
||||
| FilterParams::SetAlpha { .. }
|
||||
| FilterParams::AlphaCurve { .. }
|
||||
| FilterParams::AlphaToColor
|
||||
| FilterParams::ClampAlpha { .. }
|
||||
| FilterParams::ThresholdAlpha { .. }
|
||||
| FilterParams::FillHoles { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the filter moves pixels around the reference bounds (its
|
||||
@@ -641,7 +705,22 @@ impl FilterParams {
|
||||
/// (Clouds, Fibers), or limits its working area to the canvas (Average). The output
|
||||
/// area is still clipped to the selection; Average also weights its mean by that coverage.
|
||||
pub fn sizes_by_canvas(&self) -> bool {
|
||||
matches!(self, FilterParams::Average | FilterParams::Clouds { .. } | FilterParams::Fibers { .. })
|
||||
matches!(
|
||||
self,
|
||||
FilterParams::Clouds { .. }
|
||||
| FilterParams::Fibers { .. }
|
||||
| FilterParams::SetAlpha { .. }
|
||||
| FilterParams::AlphaCurve { .. }
|
||||
| FilterParams::AlphaToColor
|
||||
| FilterParams::ClampAlpha { .. }
|
||||
| FilterParams::ThresholdAlpha { .. }
|
||||
| FilterParams::FillHoles { .. }
|
||||
| FilterParams::HdrToning(_)
|
||||
| FilterParams::Percentile(_)
|
||||
| FilterParams::ChannelNoise(_)
|
||||
| FilterParams::Convolution(_)
|
||||
| FilterParams::Average
|
||||
)
|
||||
}
|
||||
|
||||
/// Human-readable name.
|
||||
@@ -707,6 +786,16 @@ impl FilterParams {
|
||||
FilterParams::Custom { .. } => "Custom",
|
||||
FilterParams::HsbHsl { .. } => "HSB/HSL",
|
||||
FilterParams::ColorToAlpha { .. } => "Color to Alpha",
|
||||
FilterParams::HdrToning(_) => "HDR Toning",
|
||||
FilterParams::Percentile(_) => "Percentile",
|
||||
FilterParams::ChannelNoise(_) => "Channel Noise",
|
||||
FilterParams::Convolution(_) => "Convolution",
|
||||
FilterParams::AlphaToColor => "Alpha to Color",
|
||||
FilterParams::AlphaCurve { .. } => "Alpha Curve",
|
||||
FilterParams::SetAlpha { .. } => "Set Alpha",
|
||||
FilterParams::ClampAlpha { .. } => "Clamp Alpha",
|
||||
FilterParams::ThresholdAlpha { .. } => "Threshold Alpha",
|
||||
FilterParams::FillHoles { .. } => "Fill Holes",
|
||||
FilterParams::DeInterlace { .. } => "De-Interlace",
|
||||
FilterParams::NtscColors => "NTSC Colors",
|
||||
FilterParams::FilterGallery { effects } => match effects.as_slice() {
|
||||
@@ -756,6 +845,16 @@ fn halo_ext(p: &FilterParams) -> Halo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of workers the current native filter pool can use (one on WebAssembly).
|
||||
/// Callers admitting temporary filter work can bound live tile buffers with the same pool.
|
||||
pub fn filter_worker_count() -> usize {
|
||||
par::threads()
|
||||
}
|
||||
|
||||
/// Target byte allowance for retained native tile results in one filter group.
|
||||
/// A group also holds at least one tile per worker; callers must account for that minimum.
|
||||
pub const FILTER_RESULT_BUDGET: usize = RESULT_BUDGET;
|
||||
|
||||
/// Context a filter runs in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Ctx {
|
||||
@@ -947,6 +1046,18 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f
|
||||
FilterParams::PathBlur { paths } => gallery::path(src, out, ctx, paths),
|
||||
FilterParams::Custom { kernel, scale, offset } => other2::custom(src, out, ctx, kernel, *scale, *offset),
|
||||
FilterParams::HsbHsl { input, output } => other2::hsb_hsl(src, out, ctx, *input, *output),
|
||||
FilterParams::HdrToning(options) => tone::checked_hdr::run_image(src, out, ctx, options),
|
||||
FilterParams::Percentile(options) => rank::run_image(src, out, ctx, options),
|
||||
FilterParams::ChannelNoise(options) => channel_noise::run_image(src, out, ctx, options),
|
||||
FilterParams::Convolution(options) => convolution::run_image(src, out, ctx, options),
|
||||
FilterParams::AlphaToColor => coverage::run_image(src, out, ctx, coverage::Operation::AlphaToColor),
|
||||
FilterParams::AlphaCurve { values } => coverage::run_image(src, out, ctx, coverage::Operation::AlphaCurve(values)),
|
||||
FilterParams::SetAlpha { value } => coverage::run_image(src, out, ctx, coverage::Operation::SetAlpha(*value)),
|
||||
FilterParams::ClampAlpha { low, high } => coverage::run_image(src, out, ctx, coverage::Operation::ClampAlpha { low: *low, high: *high }),
|
||||
FilterParams::ThresholdAlpha { value } => coverage::run_image(src, out, ctx, coverage::Operation::ThresholdAlpha(*value)),
|
||||
FilterParams::FillHoles { connectivity, alpha_only } => {
|
||||
coverage::run_image(src, out, ctx, coverage::Operation::FillHoles { connectivity: *connectivity, alpha_only: *alpha_only })
|
||||
}
|
||||
FilterParams::ColorToAlpha { color, transparency_threshold, opacity_threshold } => {
|
||||
color_to_alpha::color_to_alpha(src, out, ctx, *color, *transparency_threshold, *opacity_threshold)
|
||||
}
|
||||
@@ -1023,7 +1134,81 @@ pub fn apply_in_with(
|
||||
extent: Rect,
|
||||
ctl: &photocraft_raster::Interrupt,
|
||||
) -> Option<Surface> {
|
||||
apply_tiled_with(surface, params, area.intersect(&extent), bounds, selection, auto_tile(params, bounds), Some(extent), ctl)
|
||||
try_apply_in_with(surface, params, area, bounds, selection, extent, ctl).ok()
|
||||
}
|
||||
|
||||
/// A checked native kernel's original failure, or failure of a legacy tiled kernel.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ApplyError {
|
||||
Cancelled,
|
||||
Native(coverage::Error),
|
||||
Hdr(tone::checked_hdr::Error),
|
||||
WorkingData,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ApplyError {
|
||||
/// Preserve the checked kernel's diagnostic instead of guessing why it produced no output.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Cancelled => f.write_str("filter cancelled"),
|
||||
Self::Native(error) => error.fmt(f),
|
||||
Self::Hdr(error) => error.fmt(f),
|
||||
Self::WorkingData => f.write_str("the filter could not prepare its working data (not enough memory, or an unusable kernel)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ApplyError {}
|
||||
|
||||
impl ApplyError {
|
||||
/// Classify cancellation independently of the selected native kernel's error type.
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
matches!(self, Self::Cancelled | Self::Native(coverage::Error::Cancelled) | Self::Hdr(tone::checked_hdr::Error::Cancelled))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`apply_in_with`] with specific checked-kernel diagnostics; compatibility APIs retain their optional result.
|
||||
pub fn try_apply_in_with(
|
||||
surface: &Surface,
|
||||
params: &FilterParams,
|
||||
area: Rect,
|
||||
bounds: Rect,
|
||||
selection: Option<&Surface>,
|
||||
extent: Rect,
|
||||
ctl: &photocraft_raster::Interrupt,
|
||||
) -> Result<Surface, ApplyError> {
|
||||
if ctl.cancelled() {
|
||||
return Err(ApplyError::Cancelled);
|
||||
}
|
||||
let area = area.intersect(&extent);
|
||||
if let Some(result) = checked_native_filter(surface, params, area, bounds, selection, Some(extent), ctl) {
|
||||
return result;
|
||||
}
|
||||
apply_tiled_with(surface, params, area, bounds, selection, auto_tile(params, bounds), Some(extent), ctl)
|
||||
.ok_or_else(|| if ctl.cancelled() { ApplyError::Cancelled } else { ApplyError::WorkingData })
|
||||
}
|
||||
|
||||
/// Keep native error dispatch shared by diagnostic and legacy optional entry points.
|
||||
fn checked_native_filter(
|
||||
surface: &Surface,
|
||||
params: &FilterParams,
|
||||
area: Rect,
|
||||
bounds: Rect,
|
||||
selection: Option<&Surface>,
|
||||
extent: Option<Rect>,
|
||||
ctl: &photocraft_raster::Interrupt,
|
||||
) -> Option<Result<Surface, ApplyError>> {
|
||||
let domain = extent.unwrap_or(bounds);
|
||||
Some(match params {
|
||||
FilterParams::HdrToning(options) => tone::checked_hdr::apply_with(surface, options, area, domain, selection, ctl).map_err(ApplyError::Hdr),
|
||||
FilterParams::Percentile(options) => rank::apply_with(surface, options, area, domain, selection, ctl).map_err(ApplyError::Native),
|
||||
FilterParams::ChannelNoise(options) => channel_noise::apply_with(surface, options, area, domain, selection, ctl).map_err(ApplyError::Native),
|
||||
FilterParams::Convolution(options) => convolution::apply_with(surface, options, area, domain, selection, ctl).map_err(ApplyError::Native),
|
||||
FilterParams::Average => {
|
||||
// Without an owner extent, Average's whole-operation domain is the requested area.
|
||||
average::apply_preserving_alpha_with(surface, area, extent.unwrap_or(area), selection, ctl).map_err(ApplyError::Native)
|
||||
}
|
||||
_ => coverage::apply_with(surface, coverage_operation(params)?, area, domain, selection, ctl).map_err(ApplyError::Native),
|
||||
})
|
||||
}
|
||||
|
||||
/// Results do not depend on the tiling, so wide-halo filters use bigger tiles to keep the
|
||||
@@ -1119,7 +1304,22 @@ pub fn apply_tiled_with(
|
||||
apply_tiled_with_impl(surface, params, area, bounds, selection, tile, extent, ctl, true)
|
||||
}
|
||||
|
||||
/// Map native coverage filters once so the tiled dispatcher only handles their execution.
|
||||
fn coverage_operation(params: &FilterParams) -> Option<coverage::Operation<'_>> {
|
||||
match params {
|
||||
FilterParams::AlphaToColor => Some(coverage::Operation::AlphaToColor),
|
||||
FilterParams::AlphaCurve { values } => Some(coverage::Operation::AlphaCurve(values)),
|
||||
FilterParams::SetAlpha { value } => Some(coverage::Operation::SetAlpha(*value)),
|
||||
FilterParams::ClampAlpha { low, high } => Some(coverage::Operation::ClampAlpha { low: *low, high: *high }),
|
||||
FilterParams::ThresholdAlpha { value } => Some(coverage::Operation::ThresholdAlpha(*value)),
|
||||
FilterParams::FillHoles { connectivity, alpha_only } => Some(coverage::Operation::FillHoles { connectivity: *connectivity, alpha_only: *alpha_only }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// Dispatch checked whole-domain filters or bounded native tiles, publishing a result only after successful processing
|
||||
/// and cancellation checks.
|
||||
fn apply_tiled_with_impl(
|
||||
surface: &Surface,
|
||||
params: &FilterParams,
|
||||
@@ -1144,6 +1344,9 @@ fn apply_tiled_with_impl(
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if let Some(result) = checked_native_filter(surface, params, area, bounds, selection, extent, ctl) {
|
||||
return result.ok();
|
||||
}
|
||||
let mut out = surface.clone();
|
||||
if area.is_empty() {
|
||||
return Some(out);
|
||||
@@ -1450,11 +1653,28 @@ fn mix_selection(data: &mut [f32], t: Rect, sel: &Surface, orig: &Image, alpha:
|
||||
let original_alpha = orig.get(x, y, a);
|
||||
let filtered_alpha = px[a];
|
||||
if original_alpha != filtered_alpha {
|
||||
let mixed_alpha = original_alpha + (filtered_alpha - original_alpha) * k;
|
||||
let mut mixed_alpha = original_alpha + (filtered_alpha - original_alpha) * k;
|
||||
if !mixed_alpha.is_finite() && original_alpha.is_finite() && filtered_alpha.is_finite() && k.is_finite() {
|
||||
let precise = f64::from(original_alpha) + (f64::from(filtered_alpha) - f64::from(original_alpha)) * f64::from(k);
|
||||
if precise.is_finite() && precise.abs() <= f64::from(f32::MAX) {
|
||||
mixed_alpha = precise as f32;
|
||||
}
|
||||
}
|
||||
let original_weight = original_alpha * (1.0 - k);
|
||||
let filtered_weight = filtered_alpha * k;
|
||||
for (c, v) in px[..a].iter_mut().enumerate() {
|
||||
*v = if mixed_alpha > 0.0 { (orig.get(x, y, c) * original_weight + *v * filtered_weight) / mixed_alpha } else { 0.0 };
|
||||
let original = orig.get(x, y, c);
|
||||
let filtered = *v;
|
||||
*v = if mixed_alpha > 0.0 { (original * original_weight + filtered * filtered_weight) / mixed_alpha } else { 0.0 };
|
||||
if !v.is_finite() && [original, filtered, original_alpha, filtered_alpha, k].into_iter().all(f32::is_finite) {
|
||||
let ow = f64::from(original_alpha) * (1. - f64::from(k));
|
||||
let fw = f64::from(filtered_alpha) * f64::from(k);
|
||||
let alpha = ow + fw;
|
||||
let precise = if alpha > 0. { f64::from(original) + (f64::from(filtered) - f64::from(original)) * (fw / alpha) } else { 0. };
|
||||
if precise.is_finite() && precise.abs() <= f64::from(f32::MAX) {
|
||||
*v = precise as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
px[a] = mixed_alpha;
|
||||
continue;
|
||||
@@ -1462,7 +1682,14 @@ fn mix_selection(data: &mut [f32], t: Rect, sel: &Surface, orig: &Image, alpha:
|
||||
}
|
||||
for (c, v) in px.iter_mut().enumerate() {
|
||||
let o = orig.get(x, y, c);
|
||||
*v = o + (*v - o) * k;
|
||||
let filtered = *v;
|
||||
*v = o + (filtered - o) * k;
|
||||
if !v.is_finite() && [o, filtered, k].into_iter().all(f32::is_finite) {
|
||||
let precise = f64::from(o) + (f64::from(filtered) - f64::from(o)) * f64::from(k);
|
||||
if precise.is_finite() && precise.abs() <= f64::from(f32::MAX) {
|
||||
*v = precise as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1486,3 +1713,61 @@ fn apply_radial_reference(
|
||||
) -> Option<Surface> {
|
||||
apply_tiled_with_impl(surface, params, area.intersect(&extent), bounds, selection, auto_tile(params, bounds), Some(extent), ctl, false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod selected_alpha_tests {
|
||||
use super::*;
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
|
||||
#[test]
|
||||
/// Compare declared alpha capability to actual channel-selective noise/convolution pixels across native models and
|
||||
/// depths.
|
||||
fn selective_filters_declare_transparency_only_for_selected_alpha() {
|
||||
let bounds = Rect::new(0, 0, 4, 3);
|
||||
for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk] {
|
||||
for depth in SampleType::ALL {
|
||||
let format = PixelFormat::new(mode, depth, true);
|
||||
let mut source = Surface::new(format);
|
||||
let mut pixel = vec![0.4; format.channels()];
|
||||
*pixel.last_mut().unwrap() = 0.6;
|
||||
source.fill_rect(bounds, &pixel);
|
||||
for alpha in [false, true] {
|
||||
let mut amounts = vec![30.; format.channels()];
|
||||
*amounts.last_mut().unwrap() = if alpha { 100. } else { 0. };
|
||||
let noise = FilterParams::ChannelNoise(channel_noise::Params {
|
||||
amounts,
|
||||
distribution: Distribution::Uniform,
|
||||
monochromatic: false,
|
||||
relative: false,
|
||||
seed: 71,
|
||||
});
|
||||
let mut channels = vec![true; format.channels()];
|
||||
*channels.last_mut().unwrap() = alpha;
|
||||
let mut kernel = vec![0.; 25];
|
||||
kernel[12] = 0.5;
|
||||
let convolution = FilterParams::Convolution(convolution::Params {
|
||||
kernel,
|
||||
scale: 1.,
|
||||
offset: 0.,
|
||||
channels,
|
||||
alpha_weighted: false,
|
||||
edge: convolution::Edge::Repeat,
|
||||
});
|
||||
for filter in [noise, convolution] {
|
||||
assert_eq!(filter.makes_transparency(), alpha, "{mode:?} {depth:?}");
|
||||
let out = apply_in_with(&source, &filter, bounds, bounds, None, bounds, &photocraft_raster::Interrupt::NONE).unwrap();
|
||||
if alpha {
|
||||
assert_ne!(out.pixel(1, 1).last(), source.pixel(1, 1).last());
|
||||
} else {
|
||||
for y in 0..3 {
|
||||
for x in 0..4 {
|
||||
assert_eq!(out.pixel(x, y).last(), source.pixel(x, y).last());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -653,9 +653,9 @@ impl LiquifyField {
|
||||
}
|
||||
let Some((i0, j0, i1, j1)) = self.node_span(c, r) else { return Rect::EMPTY };
|
||||
// Snapshot of the affected nodes plus a margin (sampling reads around them).
|
||||
let m = ((delta[0].abs().max(delta[1].abs()) + r * 0.2) / self.cell).ceil() as usize + 2;
|
||||
let m = (((delta[0].abs().max(delta[1].abs()) + r * 0.2) / self.cell).ceil() as usize).saturating_add(2);
|
||||
let (si0, sj0) = (i0.saturating_sub(m), j0.saturating_sub(m));
|
||||
let (si1, sj1) = ((i1 + m).min(self.w - 1), (j1 + m).min(self.h - 1));
|
||||
let (si1, sj1) = (i1.saturating_add(m).min(self.w - 1), j1.saturating_add(m).min(self.h - 1));
|
||||
let sw = si1 - si0 + 1;
|
||||
let sh = sj1 - sj0 + 1;
|
||||
let mut snap = Vec::with_capacity(sw * sh);
|
||||
@@ -680,7 +680,9 @@ impl LiquifyField {
|
||||
let p = self.node_pos(i, j);
|
||||
let (dx, dy) = (p[0] - c[0], p[1] - c[1]);
|
||||
let t2 = (dx * dx + dy * dy) / (r * r);
|
||||
if t2 >= 1.0 {
|
||||
// NaN is skipped too: it is what a far-off centre with a huge radius gives
|
||||
// (infinity over infinity): a NaN weight would spread NaN displacements.
|
||||
if t2.is_nan() || t2 >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let fall = falloff(t2, density);
|
||||
@@ -749,8 +751,10 @@ impl LiquifyField {
|
||||
self.d[idx] = d;
|
||||
self.freeze[idx] = f;
|
||||
}
|
||||
let pad = r.ceil() as i32 + 2;
|
||||
Rect::new(c[0].floor() as i32 - pad, c[1].floor() as i32 - pad, c[0].ceil() as i32 + pad, c[1].ceil() as i32 + pad).intersect(&self.bounds)
|
||||
// Each edge is worked out in f64 and only then converted (saturating), so a far-off centre
|
||||
// with a huge radius still covers the nodes it changed.
|
||||
let pad = r.ceil() + 2.0;
|
||||
Rect::new((c[0].floor() - pad) as i32, (c[1].floor() - pad) as i32, (c[0].ceil() + pad) as i32, (c[1].ceil() + pad) as i32).intersect(&self.bounds)
|
||||
}
|
||||
|
||||
/// Replays strokes on a fresh field.
|
||||
|
||||
@@ -953,6 +953,120 @@ pub fn masked_copy(src: &Surface, alpha: &Region) -> Surface {
|
||||
out
|
||||
}
|
||||
|
||||
/// Failure of the bounded native Remove Black Matte operation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Cancelled,
|
||||
Allocation,
|
||||
InvalidGeometry,
|
||||
ChannelMismatch,
|
||||
NonFiniteSample,
|
||||
WorkspaceLimit,
|
||||
}
|
||||
impl std::fmt::Display for Error {
|
||||
/// Describe checked native matting failures, including geometry, workspace, allocation and cancellation errors.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Cancelled => "native matting cancelled",
|
||||
Self::Allocation => "native matting allocation unavailable",
|
||||
Self::InvalidGeometry => "native matting geometry is invalid",
|
||||
Self::ChannelMismatch => "native matting color channels do not match",
|
||||
Self::NonFiniteSample => "native matting requires finite samples",
|
||||
Self::WorkspaceLimit => "native matting exceeds its working-byte allowance",
|
||||
})
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// Remove Black/White Matte in floating RGB coordinates without clipping finite HDR values.
|
||||
/// Results outside the representable float range saturate; zero/opaque alpha is unchanged.
|
||||
/// Conversion to/from document channels belongs to the caller's native pixel format.
|
||||
pub fn remove_matte_pixel(q: &mut [f32; 4], white: bool) {
|
||||
if q[3] > 0.0 && q[3] < 1.0 {
|
||||
let a = q[3];
|
||||
for v in &mut q[..3] {
|
||||
let value = if white { (f64::from(*v) - (1.0 - f64::from(a))) / f64::from(a) } else { f64::from(*v) / f64::from(a) };
|
||||
*v = value.clamp(-f64::from(f32::MAX), f64::from(f32::MAX)) as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Existing native Remove Black Matte with fallible COW tiles/rows and cancellation.
|
||||
/// It removes the native black point without a lossy RGB pixel round trip, changes only `bounds`,
|
||||
/// and is identity on a surface without alpha. No partial result is published on error.
|
||||
pub fn remove_black_matte_with(src: &Surface, bounds: Rect, ctl: &photocraft_raster::Interrupt) -> Result<Surface, Error> {
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
let area = src.content_bounds().intersect(&bounds);
|
||||
if !src.format().alpha || area.is_empty() {
|
||||
return Ok(src.clone());
|
||||
}
|
||||
let format = src.format();
|
||||
let channels = format.channels();
|
||||
if channels == 0 || channels > 8 {
|
||||
return Err(Error::ChannelMismatch);
|
||||
}
|
||||
let width = usize::try_from(area.width()).map_err(|_| Error::InvalidGeometry)?;
|
||||
let height = usize::try_from(area.height()).map_err(|_| Error::InvalidGeometry)?;
|
||||
if width.checked_mul(height).is_none_or(|n| n > crate::coverage::MAX_PIXELS) {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
let tile = i64::from(photocraft_geom::TILE_SIZE);
|
||||
let tiles = |a: i32, b: i32| -> Result<usize, Error> {
|
||||
usize::try_from((i64::from(b) - 1).div_euclid(tile) - i64::from(a).div_euclid(tile) + 1).map_err(|_| Error::InvalidGeometry)
|
||||
};
|
||||
let bytes = tiles(area.x0, area.x1)?
|
||||
.checked_mul(tiles(area.y0, area.y1)?)
|
||||
.and_then(|n| n.checked_mul((tile * tile) as usize * format.bytes_per_pixel() + 128))
|
||||
.and_then(|n| n.checked_add(src.tile_count().checked_mul(128)?))
|
||||
.and_then(|n| n.checked_add(width.checked_mul(channels)?.checked_mul(4)?))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
if bytes > crate::coverage::MAX_WORKSPACE_BYTES {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
// Black is not zero in every native encoding. Resolve the working CMYK profile's
|
||||
// black once; Lab stores its neutral chroma at 128/255. Pixel separations stay native.
|
||||
let mut black = [0.; 8];
|
||||
match format.mode {
|
||||
photocraft_color::ColorMode::Cmyk => black[..4].copy_from_slice(&photocraft_color::convert::rgb_to_cmyk([0.; 3])),
|
||||
photocraft_color::ColorMode::Lab => {
|
||||
black[1] = 128. / 255.;
|
||||
black[2] = 128. / 255.;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if black.iter().any(|value| !value.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let mut out = src.clone();
|
||||
for y in area.y0..area.y1 {
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
let row_bounds = Rect::new(area.x0, y, area.x1, y + 1);
|
||||
let mut row = src.try_read_region(row_bounds).map_err(|_| Error::Allocation)?;
|
||||
for (index, samples) in row.chunks_exact_mut(channels).enumerate() {
|
||||
if index.is_multiple_of(1024) {
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
}
|
||||
if samples.iter().any(|value| !value.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let alpha = *samples.last().ok_or(Error::ChannelMismatch)?;
|
||||
if alpha > 0. && alpha < 1. {
|
||||
for (value, matte) in samples.iter_mut().take(channels - 1).zip(black) {
|
||||
let unassociated = (f64::from(*value) - f64::from(matte) * (1. - f64::from(alpha))) / f64::from(alpha);
|
||||
*value = if format.sample == photocraft_color::SampleType::F32 {
|
||||
unassociated.clamp(-f64::from(f32::MAX), f64::from(f32::MAX)) as f32
|
||||
} else {
|
||||
unassociated.clamp(0., 1.) as f32
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
out.try_write_region(row_bounds, &row).map_err(|_| Error::Allocation)?;
|
||||
}
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Copies selected pixels without collecting buffers across the alpha bounds.
|
||||
/// `alpha` is a zero-default GRAY8 surface, as returned by [`refine_surface`].
|
||||
/// Explicit `bounds` preserve source colour under zero alpha inside the finite mask extent.
|
||||
@@ -1318,3 +1432,107 @@ mod tests {
|
||||
assert!((c.pixel(1, 1)[0] - 0.5).abs() < 0.01 && c.pixel(1, 1)[1] == 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod native_matte_tests {
|
||||
use super::*;
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_raster::{Interrupt, from_rgba_into, to_rgba};
|
||||
#[test]
|
||||
/// Compare checked row output to independently evaluated native unpremultiplication across depth/model encodings
|
||||
/// and restricted areas.
|
||||
fn native_black_matte_matches_independent_existing_equation_all_depths_and_models() {
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let format = PixelFormat::new(mode, depth, true);
|
||||
let rect = Rect::new(-2, 3, 2, 4);
|
||||
let mut source = Surface::new(format);
|
||||
let colors = [[0.1, 0.2, 0.3, 0.5], [0.4, 0.2, 0.1, 0.], [0.2, 0.4, 0.6, 1.], [0.9, 0.2, 0.1, 0.25]];
|
||||
for (index, color) in colors.into_iter().enumerate() {
|
||||
let mut values = [0.; 8];
|
||||
let n = from_rgba_into(&format, color, &mut values);
|
||||
let x = rect.x0 + index as i32;
|
||||
source.write_region(Rect::new(x, 3, x + 1, 4), &values[..n]);
|
||||
}
|
||||
let before = source.read_region(rect);
|
||||
let result = remove_black_matte_with(&source, rect, &Interrupt::NONE).unwrap();
|
||||
for x in rect.x0..rect.x1 {
|
||||
let mut expected = to_rgba(&format, &source.pixel(x, 3));
|
||||
if expected[3] > 0. && expected[3] < 1. {
|
||||
let alpha = expected[3];
|
||||
for color in &mut expected[..3] {
|
||||
*color /= alpha;
|
||||
if depth != SampleType::F32 {
|
||||
*color = color.clamp(0., 1.);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut values = [0.; 8];
|
||||
let n = from_rgba_into(&format, expected, &mut values);
|
||||
let actual = result.pixel(x, 3);
|
||||
for (a, b) in actual.iter().zip(&values[..n]) {
|
||||
assert!((a - b).abs() < 0.005, "{mode:?}/{depth:?}/{x}: {actual:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(source.read_region(rect), before);
|
||||
let restricted = remove_black_matte_with(&source, Rect::new(-2, 3, -1, 4), &Interrupt::NONE).unwrap();
|
||||
assert_eq!(restricted.pixel(1, 3), source.pixel(1, 3));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Pin the established matte equations and preserve zero-coverage or hidden HDR data where the native rule leaves
|
||||
/// it unchanged.
|
||||
fn native_black_and_white_pixel_equations_and_hidden_hdr_are_unchanged() {
|
||||
let mut black = [0.1, 0.2, 0.3, 0.5];
|
||||
remove_matte_pixel(&mut black, false);
|
||||
assert_eq!(black, [0.2, 0.4, 0.6, 0.5]);
|
||||
let mut white = [0.6, 0.7, 0.8, 0.5];
|
||||
remove_matte_pixel(&mut white, true);
|
||||
for (a, b) in white.into_iter().zip([0.2, 0.4, 0.6, 0.5]) {
|
||||
assert!((a - b).abs() < 1e-6);
|
||||
}
|
||||
for alpha in [0., 1.] {
|
||||
for white in [false, true] {
|
||||
let mut p = [-2., 3., 0.4, alpha];
|
||||
let before = p;
|
||||
remove_matte_pixel(&mut p, white);
|
||||
assert_eq!(p, before);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Reject a sparsely populated huge extent before dense work, preserving its original tiles and pixels.
|
||||
fn sparse_hostile_geometry_is_rejected_before_dense_row_or_tile_allocation() {
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
source.fill_rect(Rect::new(0, 0, 1, 1), &[0.1, 0.2, 0.3, 0.5]);
|
||||
source.fill_rect(Rect::new(65535, 65535, 65536, 65536), &[0.1, 0.2, 0.3, 0.5]);
|
||||
let count = source.tile_count();
|
||||
assert!(matches!(remove_black_matte_with(&source, Rect::new(0, 0, 65536, 65536), &Interrupt::NONE), Err(Error::WorkspaceLimit)));
|
||||
assert_eq!(source.tile_count(), count);
|
||||
assert_eq!(source.pixel(0, 0), vec![0.1, 0.2, 0.3, 0.5]);
|
||||
}
|
||||
#[test]
|
||||
/// Keep non-alpha and empty-region inputs unchanged and require cancelled matte work to publish nothing.
|
||||
fn no_alpha_empty_bounds_and_cancel_are_atomic() {
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let format = PixelFormat::new(mode, depth, false);
|
||||
let mut source = Surface::new(format);
|
||||
let r = Rect::new(0, 0, 2, 2);
|
||||
source.fill_rect(r, &vec![0.25; format.channels()]);
|
||||
assert_eq!(remove_black_matte_with(&source, r, &Interrupt::NONE).unwrap().read_region(r), source.read_region(r));
|
||||
}
|
||||
}
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
let r = Rect::new(0, 0, 2048, 4);
|
||||
source.fill_rect(r, &[0.1, 0.2, 0.3, 0.5]);
|
||||
assert_eq!(remove_black_matte_with(&source, Rect::EMPTY, &Interrupt::NONE).unwrap().read_region(r), source.read_region(r));
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let checks = AtomicUsize::new(0);
|
||||
let cancel = || checks.fetch_add(1, Ordering::Relaxed) >= 4;
|
||||
let before = source.read_region(r);
|
||||
assert!(matches!(remove_black_matte_with(&source, r, &Interrupt::cancel_only(&cancel)), Err(Error::Cancelled)));
|
||||
assert_eq!(source.read_region(r), before);
|
||||
}
|
||||
}
|
||||
@@ -152,7 +152,8 @@ pub fn paint_gradient(
|
||||
FillMode::Blend(blend_mode),
|
||||
|x, y| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)),
|
||||
|x, y| {
|
||||
let t = tool_gradient_t(shape, from, to, x as f32 + 0.5, y as f32 + 0.5);
|
||||
// Sampled one pixel up and left of the pixel centre, where the reference application samples (#12018).
|
||||
let t = tool_gradient_t(shape, from, to, x as f32 - 0.5, y as f32 - 0.5);
|
||||
let mut c = sample_stops(stops, if reverse { 1.0 - t } else { t });
|
||||
if dither {
|
||||
// One quantisation step of monochromatic noise breaks 8-bit banding without speckle.
|
||||
@@ -262,6 +263,10 @@ pub fn bucket_fill_region_inks(
|
||||
composite_area(s, b, mode, |x, y| region.at(x, y) * opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)), src, lock_transparency, inks);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "paint_gradient_sample_tests.rs"]
|
||||
mod paint_gradient_sample_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -287,8 +292,8 @@ mod tests {
|
||||
paint_gradient(
|
||||
&mut s,
|
||||
a,
|
||||
(0.5, 0.0),
|
||||
(10.5, 0.0),
|
||||
(-0.5, 0.0),
|
||||
(9.5, 0.0),
|
||||
GradientShape::Linear,
|
||||
&[(0.0, [0.0, 0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 1.0, 1.0])],
|
||||
false,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//! #12018: the Gradient tool samples each pixel where the reference application does, so an Angle
|
||||
//! gradient's start row and Radial values match its measurements.
|
||||
//!
|
||||
//! The ramp is the reference application's measured Classic black → white Linear curve (Smooth,
|
||||
//! every tenth of the way), so every shape is checked against the same colour curve.
|
||||
|
||||
use photocraft_color::PixelFormat;
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
use super::{BlendMode, GradientShape, Rect, paint_gradient};
|
||||
|
||||
const LINEAR: [f32; 11] = [0.0, 2.0, 17.0, 42.0, 70.0, 99.0, 129.0, 162.0, 196.0, 228.0, 255.0];
|
||||
|
||||
fn ramp() -> Vec<(f32, [f32; 4])> {
|
||||
LINEAR.iter().enumerate().map(|(i, v)| (i as f32 / 10.0, [v / 255.0, v / 255.0, v / 255.0, 1.0])).collect()
|
||||
}
|
||||
|
||||
/// An 800 × 600 RGB8 gradient from `from` to `to`, dither off.
|
||||
fn painted(shape: GradientShape, from: (f32, f32), to: (f32, f32)) -> Surface {
|
||||
let mut s = Surface::new(PixelFormat::RGBA8);
|
||||
paint_gradient(&mut s, Rect::new(0, 0, 800, 600), from, to, shape, &ramp(), false, 1.0, BlendMode::Normal, false, None, false);
|
||||
s
|
||||
}
|
||||
|
||||
fn check(s: &Surface, shape: GradientShape, expected: &[((i32, i32), f32, f32)]) {
|
||||
for &((x, y), want, within) in expected {
|
||||
let got = s.pixel(x, y)[0] * 255.0;
|
||||
assert!((got - want).abs() <= within, "{shape:?} ({x},{y}): {got} expected {want} ± {within}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_angle_gradient_starts_with_the_end_colour_east_of_the_start() {
|
||||
let s = painted(GradientShape::Angle, (400.0, 300.0), (600.0, 300.0));
|
||||
check(&s, GradientShape::Angle, &[((450, 300), 254.5, 0.5), ((700, 300), 254.5, 0.5), ((500, 400), 4.0, 2.0), ((400, 200), 179.0, 2.0)]);
|
||||
// Further round, clockwise on screen.
|
||||
check(&s, GradientShape::Angle, &[((400, 400), 30.0, 1.0), ((200, 300), 99.5, 1.0), ((500, 200), 220.0, 2.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_values_match_the_reference() {
|
||||
let s = painted(GradientShape::Radial, (400.0, 300.0), (600.0, 300.0));
|
||||
check(&s, GradientShape::Radial, &[((400, 300), 0.0, 1.0), ((450, 300), 28.0, 1.0), ((300, 300), 100.0, 1.0), ((400, 200), 100.0, 1.0)]);
|
||||
check(&s, GradientShape::Radial, &[((500, 300), 98.0, 1.0), ((400, 400), 98.0, 1.0), ((700, 300), 255.0, 0.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_values_stay_within_one_level() {
|
||||
let s = painted(GradientShape::Linear, (100.0, 300.0), (700.0, 300.0));
|
||||
let expected: Vec<_> = LINEAR.iter().enumerate().map(|(i, &v)| ((100 + 60 * i as i32, 300), v, 1.0)).collect();
|
||||
check(&s, GradientShape::Linear, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflected_and_diamond_values_match_the_reference() {
|
||||
let s = painted(GradientShape::Reflected, (400.0, 300.0), (600.0, 300.0));
|
||||
check(&s, GradientShape::Reflected, &[((300, 300), 100.0, 1.0), ((500, 300), 98.0, 1.0), ((400, 100), 0.0, 1.0), ((400, 500), 0.0, 1.0)]);
|
||||
let s = painted(GradientShape::Diamond, (400.0, 300.0), (600.0, 300.0));
|
||||
// The ramp is straight between its tenths, so (300,300) and (400,200) land 1.5 below the
|
||||
// reference's 102, where today's sample point lands 3 below.
|
||||
check(
|
||||
&s,
|
||||
GradientShape::Diamond,
|
||||
&[((300, 300), 102.0, 2.0), ((500, 300), 99.0, 1.0), ((400, 200), 102.0, 2.0), ((450, 250), 99.0, 1.0), ((500, 200), 255.0, 0.0)],
|
||||
);
|
||||
}
|
||||
@@ -805,27 +805,45 @@ fn pass_down(errs: &[f32], below: &mut [f32]) {
|
||||
/// spaced levels `(k + 0.5) / n`, whatever the pattern's own contrast, as Photoshop's does
|
||||
/// (measured: a 2x2 pattern of 32/96/160/224, a 3x1 of 50/128/200 and a 7x1 ramp all give
|
||||
/// exactly those levels).
|
||||
pub fn custom_pattern_thresholds(lightness: &[f32]) -> Vec<f32> {
|
||||
/// Reject oversized workspace or allocation failure rather than aborting the process.
|
||||
pub fn custom_pattern_thresholds(lightness: &[f32]) -> Result<Vec<f32>, photocraft_raster::AllocationError> {
|
||||
let n = lightness.len();
|
||||
let bytes = custom_pattern_working_bytes(n)?;
|
||||
let key = |i: usize| lightness.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let mut order: Vec<usize> = (0..n).collect();
|
||||
order.sort_by(|a, b| key(*a).total_cmp(&key(*b)));
|
||||
let mut out = vec![0.5; n];
|
||||
let allocation = || photocraft_raster::AllocationError::NotEnoughMemory { bytes };
|
||||
let mut order = Vec::new();
|
||||
order.try_reserve_exact(n).map_err(|_| allocation())?;
|
||||
order.extend((0..n).map(|i| i as u32));
|
||||
// Ties receive the same mean rank, so stability is unnecessary. This sort
|
||||
// uses no heap scratch; fixed-width indices also bound web/desktop equally.
|
||||
order.sort_unstable_by(|a, b| key(*a as usize).total_cmp(&key(*b as usize)));
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(n).map_err(|_| allocation())?;
|
||||
out.resize(n, 0.5);
|
||||
let mut start = 0;
|
||||
while start < n {
|
||||
let v = order.get(start).map(|i| key(*i));
|
||||
let end = (start..n).find(|&j| order.get(j).map(|i| key(*i)) != v).unwrap_or(n);
|
||||
let v = order.get(start).map(|i| key(*i as usize));
|
||||
let end = (start..n).find(|&j| order.get(j).map(|i| key(*i as usize)) != v).unwrap_or(n);
|
||||
// Ranks start..end share their mean.
|
||||
let rank = (start + end - 1) as f32 / 2.0;
|
||||
let t = 1.0 - (rank + 0.5) / n as f32;
|
||||
for i in order.get(start..end).unwrap_or_default() {
|
||||
if let Some(o) = out.get_mut(*i) {
|
||||
if let Some(o) = out.get_mut(*i as usize) {
|
||||
*o = t;
|
||||
}
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Admit input lightness, fixed-width order and output thresholds before reading any pattern pixels.
|
||||
pub fn custom_pattern_working_bytes(count: usize) -> Result<usize, photocraft_raster::AllocationError> {
|
||||
let bytes = count.checked_mul(12).ok_or(photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
if bytes > 256 << 20 {
|
||||
return Err(photocraft_raster::AllocationError::SizeOverflow);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Bitmap's Custom Pattern over a whole image (gray 0..=1, row-major `w` wide), see
|
||||
|
||||
@@ -414,15 +414,15 @@ fn custom_pattern_thresholds_match_photoshop() {
|
||||
// Photoshop (Image › Mode › Bitmap, Custom Pattern) on a 0..255 ramp: the first white
|
||||
// level per pattern pixel, measured against defined patterns.
|
||||
let l = |v: &[u8]| v.iter().map(|v| f32::from(*v) / 255.0).collect::<Vec<_>>();
|
||||
let ramp7 = custom_pattern_thresholds(&l(&[0, 40, 80, 120, 160, 200, 240]));
|
||||
let ramp7 = custom_pattern_thresholds(&l(&[0, 40, 80, 120, 160, 200, 240])).unwrap();
|
||||
assert_eq!(ramp7.iter().map(|t| first_white(*t)).collect::<Vec<_>>(), [237, 201, 164, 128, 92, 55, 19]);
|
||||
let five = custom_pattern_thresholds(&l(&[10, 200, 90, 250, 150]));
|
||||
let five = custom_pattern_thresholds(&l(&[10, 200, 90, 250, 150])).unwrap();
|
||||
assert_eq!(five.iter().map(|t| first_white(*t)).collect::<Vec<_>>(), [230, 77, 179, 26, 128]);
|
||||
// Equal pixels share their rank: 100, 100 both sit at 50%.
|
||||
let ties = custom_pattern_thresholds(&l(&[100, 100, 200, 50]));
|
||||
let ties = custom_pattern_thresholds(&l(&[100, 100, 200, 50])).unwrap();
|
||||
assert_eq!(ties.iter().map(|t| first_white(*t)).collect::<Vec<_>>(), [128, 128, 32, 224]);
|
||||
assert!(custom_pattern_thresholds(&[]).is_empty());
|
||||
assert_eq!(custom_pattern_thresholds(&[f32::NAN, 0.3]).len(), 2);
|
||||
assert!(custom_pattern_thresholds(&[]).unwrap().is_empty());
|
||||
assert_eq!(custom_pattern_thresholds(&[f32::NAN, 0.3]).unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -461,7 +461,7 @@ fn bitmap_strips_match_the_whole_image_however_it_is_cut() {
|
||||
// #8477: strip boundaries must preserve diffusion state and keep patterns/screens anchored.
|
||||
let (w, h) = (37, 29);
|
||||
let gray: Vec<f32> = (0..w * h).map(|i| ((i % w) as f32 / w as f32 * 0.7 + (i / w) as f32 / h as f32 * 0.3).fract()).collect();
|
||||
let map = custom_pattern_thresholds(&[0.1, 0.9, 0.4, 0.6, 0.2, 0.8]);
|
||||
let map = custom_pattern_thresholds(&[0.1, 0.9, 0.4, 0.6, 0.2, 0.8]).unwrap();
|
||||
let methods = [
|
||||
BitmapMethod::Threshold,
|
||||
BitmapMethod::Pattern,
|
||||
@@ -547,3 +547,13 @@ fn bitmap_strips_handle_empty_and_ragged_input() {
|
||||
to_bitmap(&mut [], 3, method);
|
||||
}
|
||||
}
|
||||
|
||||
/// Threshold workspace is bounded before allocations, including multiplication overflow.
|
||||
#[test]
|
||||
fn custom_pattern_workspace_is_preflighted() {
|
||||
let limit = (256 << 20) / 12;
|
||||
assert_eq!(custom_pattern_working_bytes(limit).unwrap(), limit * 12);
|
||||
assert!(custom_pattern_working_bytes(limit + 1).is_err());
|
||||
assert!(custom_pattern_working_bytes(usize::MAX).is_err());
|
||||
assert!(custom_pattern_working_bytes(4097 * 4096).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
//! Bounded native order-statistic filtering. Existing Median remains independent.
|
||||
use crate::{Ctx, image::Image};
|
||||
use photocraft_color::{PixelFormat, SampleType};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Neighborhood {
|
||||
Disc,
|
||||
Square,
|
||||
Diamond,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Params {
|
||||
pub radius: u16,
|
||||
pub color_percentile: f32,
|
||||
pub alpha_percentile: f32,
|
||||
pub shape: Neighborhood,
|
||||
/// Absent selects all native channels; empty selects none.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub channels: Option<Vec<bool>>,
|
||||
}
|
||||
pub use crate::coverage::Error;
|
||||
const MAX_WORK: u64 = 128_000_000_000;
|
||||
const TILE: i32 = 256;
|
||||
/// Reject unsupported radius, nonfinite/out-of-range percentile values and oversized channel selections.
|
||||
pub fn validate(p: &Params) -> Result<(), Error> {
|
||||
if p.radius == 0 || p.radius > 500 || [p.color_percentile, p.alpha_percentile].into_iter().any(|v| !v.is_finite() || !(0.0..=100.0).contains(&v)) {
|
||||
return Err(Error::InvalidParameter);
|
||||
}
|
||||
if p.channels.as_ref().is_some_and(|v| v.len() > 5) {
|
||||
return Err(Error::InvalidParameter);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Validate a positive bounded frame using widened arithmetic before sizing percentile workspaces.
|
||||
fn dimensions(r: Rect) -> Result<(usize, usize), Error> {
|
||||
let w = i64::from(r.x1) - i64::from(r.x0);
|
||||
let h = i64::from(r.y1) - i64::from(r.y0);
|
||||
if w <= 0 || h <= 0 || w > 65536 || h > 65536 || w.checked_mul(h).is_none_or(|n| n > 64 * 1024 * 1024) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
Ok((w as usize, h as usize))
|
||||
}
|
||||
/// Allocate initialized scratch fallibly so a failed reservation becomes an allocation error.
|
||||
fn zeroes<T: Clone>(n: usize, v: T) -> Result<Vec<T>, Error> {
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
|
||||
out.resize(n, v);
|
||||
Ok(out)
|
||||
}
|
||||
/// Build each neighborhood row's support for square, diamond or the existing native Median disc footprint.
|
||||
fn rows(p: &Params) -> Result<Vec<usize>, Error> {
|
||||
let r = usize::from(p.radius);
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(2 * r + 1).map_err(|_| Error::Allocation)?;
|
||||
for y in 0..=2 * r {
|
||||
let d = y.abs_diff(r);
|
||||
out.push(match p.shape {
|
||||
Neighborhood::Square => r,
|
||||
Neighborhood::Diamond => r - d,
|
||||
// The existing native Median uses this discrete circular footprint.
|
||||
Neighborhood::Disc => ((r * r + r - d * d) as f64).sqrt().floor() as usize,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// Price padded output tiles, halo scratch and order-statistic work before allocating or publishing output.
|
||||
fn preflight(s: &Surface, p: &Params, area: Rect, selection: Option<&Surface>) -> Result<(), Error> {
|
||||
let (w, h) = dimensions(area)?;
|
||||
let channels = s.channels();
|
||||
if channels == 0 || channels > 5 {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let r = usize::from(p.radius);
|
||||
let hw = w.min(TILE as usize) + 2 * r;
|
||||
let hh = h.min(TILE as usize) + 2 * r;
|
||||
let halo = hw.checked_mul(hh).ok_or(Error::WorkspaceLimit)?;
|
||||
let scratch = halo
|
||||
.checked_mul(channels.checked_add(4).ok_or(Error::WorkspaceLimit)?)
|
||||
.and_then(|n| n.checked_mul(4))
|
||||
.and_then(|n| n.checked_add(65536))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
let tile_axis = |a: i32, b: i32| -> Result<usize, Error> {
|
||||
usize::try_from((i64::from(b) - 1).div_euclid(256) - i64::from(a).div_euclid(256) + 1).map_err(|_| Error::WorkspaceLimit)
|
||||
};
|
||||
let output = tile_axis(area.x0, area.x1)?
|
||||
.checked_mul(tile_axis(area.y0, area.y1)?)
|
||||
.and_then(|n| n.checked_mul(256 * 256 * s.format().bytes_per_pixel() + 128))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
let tile_scratch = 256usize * 256 * (channels * 3 + selection.map_or(0, Surface::channels)) * 4;
|
||||
if output
|
||||
.checked_add(scratch)
|
||||
.and_then(|n| n.checked_add(tile_scratch))
|
||||
.and_then(|n| n.checked_add(s.tile_count().checked_mul(128)?))
|
||||
.is_none_or(|n| n > crate::coverage::MAX_WORKSPACE_BYTES)
|
||||
{
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
let tiles = w.div_ceil(256).checked_mul(h.div_ceil(256)).ok_or(Error::WorkspaceLimit)? as u64;
|
||||
let log = (usize::BITS - halo.leading_zeros()) as u64;
|
||||
// Charge sorting, rank lookup, initial histogram and both Fenwick updates
|
||||
// plus order selection, rather than counting output samples alone.
|
||||
let work = tiles
|
||||
.checked_mul(channels as u64)
|
||||
.and_then(|n| {
|
||||
n.checked_mul((halo as u64).checked_mul(log)?.checked_mul(4)?.checked_add((w.min(256) * h.min(256)) as u64 * (4 * (2 * r + 1) + 2) as u64 * log)?)
|
||||
})
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
if work > MAX_WORK {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
// Fenwick counts permit independent percentile selection without scanning the value domain.
|
||||
/// Update Fenwick counts with checked arithmetic, rejecting invalid support indices or underflow.
|
||||
fn change(tree: &mut [u32], index: usize, add: bool) -> Result<(), Error> {
|
||||
let mut i = index.checked_add(1).ok_or(Error::InvalidGeometry)?;
|
||||
while i < tree.len() {
|
||||
let v = tree.get_mut(i).ok_or(Error::InvalidGeometry)?;
|
||||
*v = if add { v.checked_add(1) } else { v.checked_sub(1) }.ok_or(Error::InvalidGeometry)?;
|
||||
i = i.checked_add(i & i.wrapping_neg()).ok_or(Error::InvalidGeometry)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Locate an order statistic in Fenwick counts without scanning the sample-value domain.
|
||||
fn select(tree: &[u32], rank: u32) -> Result<usize, Error> {
|
||||
let mut index = 0usize;
|
||||
let mut remaining = rank;
|
||||
let mut bit = 1usize;
|
||||
while bit < tree.len() {
|
||||
bit = bit.checked_mul(2).ok_or(Error::InvalidGeometry)?;
|
||||
}
|
||||
while bit > 0 {
|
||||
let next = index.checked_add(bit).ok_or(Error::InvalidGeometry)?;
|
||||
if let Some(&count) = tree.get(next)
|
||||
&& count <= remaining
|
||||
{
|
||||
index = next;
|
||||
remaining -= count;
|
||||
}
|
||||
bit /= 2;
|
||||
}
|
||||
if index + 1 >= tree.len() {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
/// Compute per-channel neighborhood ranks with separate alpha policy and cancellable bounded scratch.
|
||||
fn ranked(data: &[f32], width: usize, height: usize, channels: usize, p: &Params, alpha: bool, ctl: &Interrupt<'_>) -> Result<Vec<f32>, Error> {
|
||||
let r = usize::from(p.radius);
|
||||
let ww = width + 2 * r;
|
||||
let hh = height + 2 * r;
|
||||
let expected = ww.checked_mul(hh).and_then(|n| n.checked_mul(channels)).ok_or(Error::WorkspaceLimit)?;
|
||||
if data.len() != expected {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let row_widths = rows(p)?;
|
||||
let count = row_widths.iter().try_fold(0usize, |n, h| n.checked_add(2 * h + 1)).ok_or(Error::WorkspaceLimit)?;
|
||||
let mut output = zeroes(width * height * channels, 0f32)?;
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let original = (y + r) * ww * channels + (x + r) * channels;
|
||||
let target = (y * width + x) * channels;
|
||||
output
|
||||
.get_mut(target..target + channels)
|
||||
.ok_or(Error::InvalidGeometry)?
|
||||
.copy_from_slice(data.get(original..original + channels).ok_or(Error::InvalidGeometry)?);
|
||||
}
|
||||
}
|
||||
for channel in 0..channels {
|
||||
if p.channels.as_ref().is_some_and(|v| !v.get(channel).copied().unwrap_or(false)) {
|
||||
continue;
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(ww * hh).map_err(|_| Error::Allocation)?;
|
||||
for (i, pixel) in data.chunks_exact(channels).enumerate() {
|
||||
if i.is_multiple_of(2048) && ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let v = *pixel.get(channel).ok_or(Error::InvalidGeometry)?;
|
||||
if !v.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
values.push(v);
|
||||
}
|
||||
let mut sorted = Vec::new();
|
||||
sorted.try_reserve_exact(values.len()).map_err(|_| Error::Allocation)?;
|
||||
sorted.extend_from_slice(&values);
|
||||
sorted.sort_unstable_by(f32::total_cmp);
|
||||
sorted.dedup_by(|a, b| a.to_bits() == b.to_bits());
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let mut ranks = Vec::new();
|
||||
ranks.try_reserve_exact(values.len()).map_err(|_| Error::Allocation)?;
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
if i.is_multiple_of(2048) && ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
ranks.push(sorted.binary_search_by(|a| a.total_cmp(v)).map_err(|_| Error::InvalidGeometry)?);
|
||||
}
|
||||
drop(values);
|
||||
let mut tree = zeroes(sorted.len() + 1, 0u32)?;
|
||||
let rank_at = |x: usize, y: usize| -> Result<usize, Error> {
|
||||
ranks.get(y.checked_mul(ww).and_then(|n| n.checked_add(x)).ok_or(Error::InvalidGeometry)?).copied().ok_or(Error::InvalidGeometry)
|
||||
};
|
||||
for (j, &half) in row_widths.iter().enumerate() {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
for x in r - half..=r + half {
|
||||
change(&mut tree, rank_at(x, j)?, true)?;
|
||||
}
|
||||
}
|
||||
let percentile = if alpha && channel + 1 == channels { p.alpha_percentile } else { p.color_percentile };
|
||||
let target = (((count - 1) as f64 * f64::from(percentile) / 100.).floor() as usize).min(count - 1) as u32;
|
||||
for y in 0..height {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
for step in 0..width {
|
||||
if step.is_multiple_of(8) && ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let x = if y.is_multiple_of(2) { step } else { width - 1 - step };
|
||||
let cx = x + r;
|
||||
let cy = y + r;
|
||||
if y > 0 || step > 0 {
|
||||
for (j, &half) in row_widths.iter().enumerate() {
|
||||
let (gone, new) = if step == 0 {
|
||||
let xx = cx + j - r;
|
||||
((xx, cy - 1 - half), (xx, cy + half))
|
||||
} else if y.is_multiple_of(2) {
|
||||
((cx - 1 - half, cy + j - r), (cx + half, cy + j - r))
|
||||
} else {
|
||||
((cx + 1 + half, cy + j - r), (cx - half, cy + j - r))
|
||||
};
|
||||
change(&mut tree, rank_at(gone.0, gone.1)?, false)?;
|
||||
change(&mut tree, rank_at(new.0, new.1)?, true)?;
|
||||
}
|
||||
}
|
||||
let value = *sorted.get(select(&tree, target)?).ok_or(Error::InvalidGeometry)?;
|
||||
*output.get_mut((y * width + x) * channels + channel).ok_or(Error::InvalidGeometry)? = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
/// Selection limits publication; the complete owner domain supplies repeated edge samples.
|
||||
pub fn apply_with(s: &Surface, p: &Params, area: Rect, domain: Rect, selection: Option<&Surface>, ctl: &Interrupt<'_>) -> Result<Surface, Error> {
|
||||
validate(p)?;
|
||||
if p.channels.as_ref().is_some_and(|v| !v.is_empty() && v.len() != s.channels()) {
|
||||
return Err(Error::InvalidParameter);
|
||||
}
|
||||
// The owner only bounds edge sampling; preflight admits the clipped output and halo.
|
||||
if domain.is_empty() {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
if area.x1 < area.x0 || area.y1 < area.y0 {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let area = area.intersect(&domain);
|
||||
if p.channels.as_ref().is_some_and(|v| v.iter().all(|selected| !*selected)) {
|
||||
if s.tile_count().checked_mul(128).is_none_or(|n| n > crate::coverage::MAX_WORKSPACE_BYTES) {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
return Ok(s.clone());
|
||||
}
|
||||
if area.is_empty() {
|
||||
return Ok(s.clone());
|
||||
}
|
||||
preflight(s, p, area, selection)?;
|
||||
let channels = s.channels();
|
||||
let r = i64::from(p.radius);
|
||||
let mut result = s.clone();
|
||||
let mut y = area.y0;
|
||||
while y < area.y1 {
|
||||
let y1 = (i64::from(y) + i64::from(TILE)).min(i64::from(area.y1)) as i32;
|
||||
let mut x = area.x0;
|
||||
while x < area.x1 {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let x1 = (i64::from(x) + i64::from(TILE)).min(i64::from(area.x1)) as i32;
|
||||
let tile = Rect::new(x, y, x1, y1);
|
||||
let (w, h) = dimensions(tile)?;
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact((w + 2 * r as usize) * (h + 2 * r as usize) * channels).map_err(|_| Error::Allocation)?;
|
||||
for yy in i64::from(y) - r..i64::from(y1) + r {
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
let sy = yy.clamp(i64::from(domain.y0), i64::from(domain.y1) - 1) as i32;
|
||||
for xx in i64::from(x) - r..i64::from(x1) + r {
|
||||
let sx = xx.clamp(i64::from(domain.x0), i64::from(domain.x1) - 1) as i32;
|
||||
let mut pixel = [0.; 5];
|
||||
s.read_pixel(sx, sy, &mut pixel);
|
||||
data.extend_from_slice(pixel.get(..channels).ok_or(Error::InvalidGeometry)?);
|
||||
}
|
||||
}
|
||||
let mut filtered = ranked(&data, w, h, channels, p, s.format().alpha, ctl)?;
|
||||
drop(data);
|
||||
if let Some(selection) = selection {
|
||||
let mask = selection.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
if mask.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let original = Image { rect: tile, ch: channels, data: s.try_read_region(tile).map_err(|_| Error::Allocation)? };
|
||||
crate::mix_selection(&mut filtered, tile, selection, &original, s.format().alpha);
|
||||
if let Some(mask) = &p.channels {
|
||||
for (pixel, before) in filtered.chunks_exact_mut(channels).zip(original.data.chunks_exact(channels)) {
|
||||
for (c, value) in pixel.iter_mut().enumerate() {
|
||||
if !mask.get(c).copied().unwrap_or(false) {
|
||||
*value = *before.get(c).ok_or(Error::InvalidGeometry)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if filtered.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
result.try_write_region(tile, &filtered).map_err(|_| Error::Allocation)?;
|
||||
x = x1;
|
||||
}
|
||||
y = y1;
|
||||
ctl.progress((i64::from(y) - i64::from(area.y0)) as f32 / (i64::from(area.y1) - i64::from(area.y0)) as f32);
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
/// Adapt raw float images to checked native percentile filtering, returning bounded identity data on rejected work.
|
||||
pub(crate) fn run_image(src: &Image, out: Rect, ctx: &Ctx, p: &Params) -> Vec<f32> {
|
||||
let run = || -> Result<Vec<f32>, Error> {
|
||||
validate(p)?;
|
||||
let (w, h) = dimensions(src.rect)?;
|
||||
if src.data.len() > 64 * 1024 * 1024 {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
dimensions(out)?;
|
||||
let fmt = PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha);
|
||||
if src.ch != fmt.channels() || w.checked_mul(h).and_then(|n| n.checked_mul(src.ch)) != Some(src.data.len()) || out.intersect(&src.rect) != out {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let mut s = Surface::new(fmt);
|
||||
preflight(&s, p, src.rect, None)?;
|
||||
s.try_write_region(src.rect, &src.data).map_err(|_| Error::Allocation)?;
|
||||
apply_with(&s, p, out, src.rect, None, &Interrupt::NONE)?.try_read_region(out).map_err(|_| Error::Allocation)
|
||||
};
|
||||
run().unwrap_or_else(|_| {
|
||||
let mut v = Vec::new();
|
||||
if let (Ok((w, h)), Ok((sw, sh))) = (dimensions(out), dimensions(src.rect))
|
||||
&& src.ch > 0
|
||||
&& src.ch <= 5
|
||||
&& sw.checked_mul(sh).and_then(|n| n.checked_mul(src.ch)) == Some(src.data.len())
|
||||
&& out.intersect(&src.rect) == out
|
||||
&& v.try_reserve_exact(w * h * src.ch).is_ok()
|
||||
{
|
||||
for y in out.y0..out.y1 {
|
||||
let start = ((i64::from(y) - i64::from(src.rect.y0)) as usize * sw + (i64::from(out.x0) - i64::from(src.rect.x0)) as usize) * src.ch;
|
||||
if let Some(row) = src.data.get(start..start + w * src.ch) {
|
||||
v.extend_from_slice(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
})
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_color::ColorMode;
|
||||
|
||||
/// Sparse owner size must not change small native edits, repeated-edge samples or selection publication.
|
||||
#[test]
|
||||
fn small_percentile_edits_on_large_owners_match_clamped_oracle() {
|
||||
let interior = Rect::new(11, 13, 13, 15);
|
||||
let large = Rect::new(0, 0, 9000, 9000);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let mut s = source(mode, depth, Rect::new(10, 12, 14, 16));
|
||||
s.fill_rect(Rect::new(0, 0, 3, 3), &vec![0.6; s.channels()]);
|
||||
s.fill_rect(Rect::new(-2, -2, 0, 0), &vec![1.; s.channels()]);
|
||||
let before = s.clone();
|
||||
for shape in [Neighborhood::Disc, Neighborhood::Square, Neighborhood::Diamond] {
|
||||
let p = params(1, shape, 17., 83.);
|
||||
for domain in [Rect::new(0, 0, 100, 100), large, Rect::new(0, 0, 90_000, 9000)] {
|
||||
for area in [interior, Rect::new(-1, -1, 2, 2)] {
|
||||
let clipped = area.intersect(&domain);
|
||||
let mut expected = s.clone();
|
||||
expected.try_write_region(clipped, &oracle(&s, &p, clipped, domain)).unwrap();
|
||||
assert_eq!(apply_with(&s, &p, area, domain, None, &Interrupt::NONE).unwrap(), expected, "{mode:?}/{depth:?}/{shape:?}");
|
||||
}
|
||||
}
|
||||
let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
selection.fill_rect(interior, &[0.37]);
|
||||
let selected = apply_with(&s, &p, interior, large, Some(&selection), &Interrupt::NONE).unwrap();
|
||||
let small = apply_with(&s, &p, interior, Rect::new(0, 0, 100, 100), Some(&selection), &Interrupt::NONE).unwrap();
|
||||
assert_eq!(selected, small);
|
||||
}
|
||||
assert_eq!(s, before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sampling bounds need no dense admission, while clipped output, padded workspace and cancellation retain their limits.
|
||||
#[test]
|
||||
fn large_percentile_owners_keep_geometry_work_and_cancellation_guards() {
|
||||
let s = Surface::with_default(PixelFormat::RGBA32F, &[0.25; 4]);
|
||||
let area = Rect::new(11, 13, 13, 15);
|
||||
let domain = Rect::new(0, 0, 9000, 9000);
|
||||
let p = params(1, Neighborhood::Square, 50., 50.);
|
||||
assert_eq!(s.tile_count(), 0);
|
||||
let shifted = Rect::new(11, 13, 9011, 9013);
|
||||
let out = apply_with(&s, &p, Rect::new(-100_000, -100_000, 13, 15), shifted, None, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(out.read_region(area), vec![0.25; 16]);
|
||||
for invalid in [Rect::new(0, 0, 0, 9000), Rect::new(0, 1, 9000, 1), Rect::new(2, 0, 1, 9000), Rect::new(0, 2, 9000, 1)] {
|
||||
assert_eq!(apply_with(&s, &p, area, invalid, None, &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
}
|
||||
assert_eq!(apply_with(&s, &p, domain, domain, None, &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
let wide = Rect::new(0, 0, 90_000, 9000);
|
||||
assert_eq!(apply_with(&s, &p, Rect::new(0, 0, 65_537, 1), wide, None, &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
let costly = params(500, Neighborhood::Square, 50., 50.);
|
||||
assert_eq!(apply_with(&s, &costly, Rect::new(0, 0, 8192, 8192), domain, None, &Interrupt::NONE), Err(Error::WorkspaceLimit));
|
||||
let cancelled = || true;
|
||||
assert_eq!(apply_with(&s, &p, area, domain, None, &Interrupt::cancel_only(&cancelled)), Err(Error::Cancelled));
|
||||
assert_eq!(apply_with(&s, &p, Rect::new(9001, 9001, 9003, 9003), domain, None, &Interrupt::NONE).unwrap(), s);
|
||||
assert_eq!(s.tile_count(), 0);
|
||||
}
|
||||
/// Build an all-channel percentile request with independently controlled color and alpha ranks.
|
||||
fn params(radius: u16, shape: Neighborhood, q: f32, a: f32) -> Params {
|
||||
Params { radius, shape, color_percentile: q, alpha_percentile: a, channels: None }
|
||||
}
|
||||
/// Create reproducible native-depth samples, including signed HDR values, for order-statistic tests.
|
||||
fn source(mode: ColorMode, depth: SampleType, r: Rect) -> Surface {
|
||||
let fmt = PixelFormat::new(mode, depth, true);
|
||||
let mut s = Surface::new(fmt);
|
||||
let mut state = 19u32;
|
||||
let data: Vec<f32> = (0..r.width() as usize * r.height() as usize * fmt.channels())
|
||||
.map(|_| {
|
||||
state = state.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
if depth == SampleType::F32 { (state % 113) as f32 / 17. - 2. } else { (state % 251) as f32 / 250. }
|
||||
})
|
||||
.collect();
|
||||
s.try_write_region(r, &data).unwrap();
|
||||
s
|
||||
}
|
||||
/// Sort an independently enumerated neighborhood to define expected ranks and clamped edge samples.
|
||||
fn oracle(s: &Surface, p: &Params, area: Rect, domain: Rect) -> Vec<f32> {
|
||||
let r = i32::from(p.radius);
|
||||
let mut out = Vec::new();
|
||||
for y in area.y0..area.y1 {
|
||||
for x in area.x0..area.x1 {
|
||||
for c in 0..s.channels() {
|
||||
let mut v = Vec::new();
|
||||
for dy in -r..=r {
|
||||
for dx in -r..=r {
|
||||
let include = match p.shape {
|
||||
Neighborhood::Square => true,
|
||||
Neighborhood::Diamond => dx.abs() + dy.abs() <= r,
|
||||
Neighborhood::Disc => dx * dx + dy * dy <= r * r + r,
|
||||
};
|
||||
if include {
|
||||
v.push(s.sample_channel((x + dx).clamp(domain.x0, domain.x1 - 1), (y + dy).clamp(domain.y0, domain.y1 - 1), c));
|
||||
}
|
||||
}
|
||||
}
|
||||
v.sort_unstable_by(f32::total_cmp);
|
||||
let q = if c + 1 == s.channels() { p.alpha_percentile } else { p.color_percentile };
|
||||
out.push(v[((v.len() - 1) as f64 * f64::from(q) / 100.).floor() as usize]);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
#[test]
|
||||
/// Compare every neighborhood/rank combination with direct sorting on signed HDR samples and shifted bounds.
|
||||
fn independent_oracle_all_shapes_ranks_edges_and_hdr() {
|
||||
let r = Rect::new(-3, 5, 6, 12);
|
||||
let s = source(ColorMode::Rgb, SampleType::F32, r);
|
||||
for shape in [Neighborhood::Disc, Neighborhood::Square, Neighborhood::Diamond] {
|
||||
for radius in [1, 2, 4] {
|
||||
for q in [0., 17., 50., 83., 100.] {
|
||||
let p = params(radius, shape, q, 100. - q);
|
||||
assert_eq!(apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap().read_region(r), oracle(&s, &p, r, r), "{p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Require the midpoint disc rank to match the established native Median across modes and depths.
|
||||
fn median50_matches_existing_native_median_all_models_depths() {
|
||||
let r = Rect::new(-3, -4, 12, 11);
|
||||
let out = Rect::new(0, 0, 9, 8);
|
||||
for mode in [
|
||||
ColorMode::Bitmap,
|
||||
ColorMode::Grayscale,
|
||||
ColorMode::Indexed,
|
||||
ColorMode::Rgb,
|
||||
ColorMode::Cmyk,
|
||||
ColorMode::Lab,
|
||||
ColorMode::Multichannel,
|
||||
ColorMode::Duotone,
|
||||
] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let s = source(mode, depth, r);
|
||||
let src = Image::read(&s, r);
|
||||
for radius in [1, 2, 3] {
|
||||
let p = params(radius, Neighborhood::Disc, 50., 50.);
|
||||
let expected = crate::noise::median(&src, out, f32::from(radius), None);
|
||||
let got = apply_with(&s, &p, out, r, None, &Interrupt::NONE).unwrap().read_region(out);
|
||||
assert_eq!(got, expected, "{mode:?} {depth:?} radius{radius}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Check endpoint percentiles against existing native extrema for an identical support footprint.
|
||||
fn extrema_match_native_minimum_maximum_same_footprint() {
|
||||
let r = Rect::new(-4, -4, 10, 10);
|
||||
let out = Rect::new(0, 0, 6, 6);
|
||||
let s = source(ColorMode::Rgb, SampleType::F32, r);
|
||||
let src = Image::read(&s, r);
|
||||
for shape in [Neighborhood::Disc, Neighborhood::Square] {
|
||||
for radius in [1u16, 2, 3] {
|
||||
for q in [0., 100.] {
|
||||
let p = params(radius, shape, q, q);
|
||||
let native_radius = if shape == Neighborhood::Disc { (f32::from(radius).powi(2) + f32::from(radius)).sqrt() } else { f32::from(radius) };
|
||||
let preserve = if shape == Neighborhood::Disc { crate::Preserve::Roundness } else { crate::Preserve::Squareness };
|
||||
let native = crate::other::min_max_preserve(&src, out, native_radius, q == 100., preserve);
|
||||
assert_eq!(apply_with(&s, &p, out, r, None, &Interrupt::NONE).unwrap().read_region(out), native);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Verify crop invariance and selection behavior while cancellation leaves the original surface unchanged.
|
||||
fn tiled_crop_invariance_selection_and_cancellation_are_atomic() {
|
||||
let r = Rect::new(-1, 3, 260, 8);
|
||||
let s = source(ColorMode::Rgb, SampleType::F32, r);
|
||||
let before = s.clone();
|
||||
let p = params(2, Neighborhood::Diamond, 29., 78.);
|
||||
let full = apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap();
|
||||
let crop = Rect::new(250, 4, 259, 7);
|
||||
assert_eq!(apply_with(&s, &p, crop, r, None, &Interrupt::NONE).unwrap().read_region(crop), full.read_region(crop));
|
||||
let zero = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
assert_eq!(apply_with(&s, &p, r, r, Some(&zero), &Interrupt::NONE).unwrap(), s);
|
||||
let cancel = || true;
|
||||
let ctl = Interrupt::cancel_only(&cancel);
|
||||
assert_eq!(apply_with(&s, &p, r, r, None, &ctl).unwrap_err(), Error::Cancelled);
|
||||
assert_eq!(s, before);
|
||||
}
|
||||
#[test]
|
||||
/// Ensure fractional coverage cannot modify unselected channels or an explicitly empty channel selection.
|
||||
fn selected_channels_preserve_unselected_bits_through_fractional_selection_and_empty_masks() {
|
||||
let r = Rect::new(-2, 3, 5, 8);
|
||||
let mut s = source(ColorMode::Rgb, SampleType::F32, r);
|
||||
s.write_pixel(0, 5, &[-0., std::f32::consts::PI, -4.125, 0.25]);
|
||||
let original = s.read_region(r);
|
||||
let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
selection.fill_rect(r, &[0.37]);
|
||||
let mut p = params(2, Neighborhood::Square, 100., 100.);
|
||||
p.channels = Some(vec![false, false, false, true]);
|
||||
let got = apply_with(&s, &p, r, r, Some(&selection), &Interrupt::NONE).unwrap().read_region(r);
|
||||
for (a, b) in got.as_chunks::<4>().0.iter().zip(original.as_chunks::<4>().0.iter()) {
|
||||
for c in 0..3 {
|
||||
assert_eq!(a[c].to_bits(), b[c].to_bits());
|
||||
}
|
||||
}
|
||||
assert!(got.as_chunks::<4>().0.iter().zip(original.as_chunks::<4>().0.iter()).any(|(a, b)| a[3] != b[3]));
|
||||
p.channels = Some(vec![true, true, true, false]);
|
||||
let got = apply_with(&s, &p, r, r, Some(&selection), &Interrupt::NONE).unwrap().read_region(r);
|
||||
for (a, b) in got.as_chunks::<4>().0.iter().zip(original.as_chunks::<4>().0.iter()) {
|
||||
assert_eq!(a[3].to_bits(), b[3].to_bits());
|
||||
}
|
||||
for mask in [vec![], vec![false; 4]] {
|
||||
p.channels = Some(mask);
|
||||
assert_eq!(apply_with(&s, &p, r, r, Some(&selection), &Interrupt::NONE).unwrap(), s);
|
||||
}
|
||||
p.channels = Some(vec![true; 3]);
|
||||
assert_eq!(apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap_err(), Error::InvalidParameter);
|
||||
p.channels = None;
|
||||
let json = serde_json::to_value(&p).unwrap();
|
||||
assert!(json.get("channels").is_none());
|
||||
let restored: Params = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(restored, p);
|
||||
}
|
||||
#[test]
|
||||
/// Reject hostile parameters and oversized padded/CPU work before returning a modified surface.
|
||||
fn invalid_inputs_and_padded_tile_or_cpu_budget_fail_before_publication() {
|
||||
let r = Rect::new(0, 0, 2, 2);
|
||||
let s = source(ColorMode::Rgb, SampleType::F32, r);
|
||||
for p in [
|
||||
params(0, Neighborhood::Disc, 50., 50.),
|
||||
params(501, Neighborhood::Disc, 50., 50.),
|
||||
params(1, Neighborhood::Disc, f32::NAN, 50.),
|
||||
params(1, Neighborhood::Disc, 50., 101.),
|
||||
] {
|
||||
assert_eq!(apply_with(&s, &p, r, r, None, &Interrupt::NONE).unwrap_err(), Error::InvalidParameter);
|
||||
}
|
||||
let huge = Rect::new(0, 0, 8192, 8192);
|
||||
assert_eq!(apply_with(&s, ¶ms(500, Neighborhood::Square, 50., 50.), huge, huge, None, &Interrupt::NONE).unwrap_err(), Error::WorkspaceLimit);
|
||||
let thin = Rect::new(0, 0, 1, 65536);
|
||||
// Thin logical geometry still pays for256 full native output tiles. This
|
||||
// bounded case fits; interrupt while gathering its first halo, before publication.
|
||||
let calls = std::sync::atomic::AtomicUsize::new(0);
|
||||
let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 8;
|
||||
assert_eq!(
|
||||
apply_with(&s, ¶ms(400, Neighborhood::Square, 50., 50.), thin, thin, None, &Interrupt::cancel_only(&cancel)).unwrap_err(),
|
||||
Error::Cancelled
|
||||
);
|
||||
let mut bad = s.clone();
|
||||
bad.try_write_region(Rect::new(0, 0, 1, 1), &[f32::NAN, 0., 0., 1.]).unwrap();
|
||||
assert_eq!(apply_with(&bad, ¶ms(1, Neighborhood::Disc, 50., 50.), r, r, None, &Interrupt::NONE).unwrap_err(), Error::NonFiniteSample);
|
||||
}
|
||||
}
|
||||
+108
-2
@@ -42,10 +42,18 @@ fn clouds_value(x: f32, y: f32, base: f32, seed: u32) -> f32 {
|
||||
amp *= 0.5;
|
||||
freq *= 2.0;
|
||||
}
|
||||
// Stretch the bell-shaped sum so the clouds use the full foreground→background range.
|
||||
((sum / norm - 0.5) * 2.2 + 0.5).clamp(0.0, 1.0)
|
||||
// Stretch the bell-shaped sum around mid-grey so the clouds use most of the
|
||||
// foreground→background range. A straight stretch clamped at 0 and 1 flattened its tails
|
||||
// into pure foreground and background (#9959); this S-curve, x/√(1+x²) scaled so it meets
|
||||
// 0 and 1 only where the sum does (at ±h it is ±h/CLOUD_CONTRAST), compresses them instead.
|
||||
let h = (CLOUD_CONTRAST * CLOUD_CONTRAST - 1.0).sqrt();
|
||||
let d = (sum / norm - 0.5) * 2.0 * h;
|
||||
(0.5 + 0.5 * CLOUD_CONTRAST / h * d / (1.0 + d * d).sqrt()).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// The clouds' contrast at mid-grey: the slope of the octave sum's stretch there.
|
||||
const CLOUD_CONTRAST: f32 = 2.2;
|
||||
|
||||
/// Clouds between the foreground and background colours; Difference Clouds subtracts them from
|
||||
/// the pixels (alpha kept). The cloud size is a quarter of the bounds' longer side, and the
|
||||
/// pattern is anchored at the bounds' corner (so it moves with a smart object).
|
||||
@@ -228,3 +236,101 @@ pub(crate) fn lighting(src: &Image, out: Rect, ctx: &Ctx, spec: &LightingSpec) -
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{FilterParams, apply, output_area};
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
|
||||
const WHITE: [f32; 4] = [1.0; 4];
|
||||
|
||||
/// Clouds (or Difference Clouds over `under`) on a `w`×`h` canvas, as the stored pixels.
|
||||
fn render(fmt: PixelFormat, w: i32, h: i32, seed: u32, colours: ([f32; 4], [f32; 4]), under: Option<&[f32]>) -> Vec<f32> {
|
||||
let r = Rect::new(0, 0, w, h);
|
||||
let mut s = Surface::new(fmt);
|
||||
if let Some(px) = under {
|
||||
s.fill_rect(r, px);
|
||||
}
|
||||
let p = FilterParams::Clouds { seed, difference: under.is_some(), foreground: colours.0, background: colours.1 };
|
||||
apply(&s, &p, output_area(&p, s.content_bounds(), r, None), r, None).read_region(r)
|
||||
}
|
||||
|
||||
fn top_level(depth: SampleType) -> f32 {
|
||||
if depth == SampleType::U8 { 255.0 } else { 65535.0 }
|
||||
}
|
||||
|
||||
/// Clouds' histogram is a bell around mid-grey that spans most of the levels without piling
|
||||
/// up at either end: a straight stretch clamped at 0 and 1 put 1–4 % of a 512×512 render on
|
||||
/// each end (#9959).
|
||||
#[test]
|
||||
fn clouds_span_the_levels_without_clipping() {
|
||||
for depth in [SampleType::U8, SampleType::U16] {
|
||||
let top = top_level(depth);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
|
||||
let fmt = PixelFormat::new(mode, depth, true);
|
||||
for (w, h) in [(512, 512), (900, 240), (2400, 1200)] {
|
||||
for seed in [0, 3, 7, 18916] {
|
||||
let px = render(fmt, w, h, seed, (BLACK, WHITE), None);
|
||||
let v: Vec<f32> = px.chunks_exact(fmt.channels()).map(|p| p[0]).collect();
|
||||
let n = v.len() as f32;
|
||||
let at = |level: f32| v.iter().filter(|&&t| (t * top).round() == level).count() as f32 / n;
|
||||
let case = format!("{mode:?} {depth:?} {w}×{h} seed {seed}");
|
||||
assert!(at(0.0) < 1e-4 && at(top) < 1e-4, "{case}: clipped {} black, {} white", at(0.0), at(top));
|
||||
let (lo, hi) = v.iter().fold((1.0f32, 0.0f32), |(a, b), &t| (a.min(t), b.max(t)));
|
||||
assert!(hi - lo > 0.7, "{case}: spans only {lo}..{hi}");
|
||||
// Only a few big cells on a long, thin canvas, so its mean wanders more.
|
||||
let mean = v.iter().sum::<f32>() / n;
|
||||
assert!((0.35..0.65).contains(&mean), "{case}: mean {mean}");
|
||||
// A flat histogram would put a quarter of the pixels in the outer eighths.
|
||||
let outer = v.iter().filter(|t| !(0.125..0.875).contains(*t)).count() as f32 / n;
|
||||
assert!(outer < 0.12, "{case}: {outer} in the outer eighths");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clouds blend between any two colours without reaching either: no channel sits on the
|
||||
/// foreground's or background's level, and every channel stays between them.
|
||||
#[test]
|
||||
fn clouds_stay_strictly_between_any_two_colours() {
|
||||
let (fg, bg) = ([0.85, 0.2, 0.1, 1.0], [0.1, 0.55, 0.9, 1.0]);
|
||||
for depth in [SampleType::U8, SampleType::U16] {
|
||||
let top = top_level(depth);
|
||||
let fmt = PixelFormat::new(ColorMode::Rgb, depth, true);
|
||||
for seed in [3, 18916] {
|
||||
let data = render(fmt, 512, 512, seed, (fg, bg), None);
|
||||
let px = data.as_chunks::<4>().0;
|
||||
let n = px.len() as f32;
|
||||
for k in 0..3 {
|
||||
let ends = [(fg[k] * top).round(), (bg[k] * top).round()];
|
||||
let on_end = px.iter().filter(|p| ends.contains(&(p[k] * top).round())).count() as f32 / n;
|
||||
assert!(on_end < 1e-4, "{depth:?} seed {seed} channel {k}: {on_end} on a colour's level");
|
||||
let (lo, hi) = (fg[k].min(bg[k]) - 0.5 / top, fg[k].max(bg[k]) + 0.5 / top);
|
||||
assert!(px.iter().all(|p| (lo..=hi).contains(&p[k])), "{depth:?} seed {seed} channel {k} left the colours");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Difference Clouds shares the clouds: over white with black and white they are the clouds
|
||||
/// inverted, so they don't clip either.
|
||||
#[test]
|
||||
fn difference_clouds_over_white_are_the_clouds_inverted() {
|
||||
for depth in [SampleType::U8, SampleType::U16] {
|
||||
let top = top_level(depth);
|
||||
let fmt = PixelFormat::new(ColorMode::Rgb, depth, true);
|
||||
let clouds = render(fmt, 300, 200, 5, (BLACK, WHITE), None);
|
||||
let diff = render(fmt, 300, 200, 5, (BLACK, WHITE), Some(&WHITE));
|
||||
let (clouds, diff) = (clouds.as_chunks::<4>().0, diff.as_chunks::<4>().0);
|
||||
for (c, d) in clouds.iter().zip(diff) {
|
||||
assert!((c[0] + d[0] - 1.0).abs() <= 1.0 / top, "{depth:?}: {} + {} ≠ 1", c[0], d[0]);
|
||||
assert_eq!(d[3], 1.0);
|
||||
}
|
||||
assert!(diff.iter().all(|p| (p[0] * top).round() != 0.0 && (p[0] * top).round() != top), "{depth:?}: clipped");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,66 @@ pub trait Sampler: Sync {
|
||||
}
|
||||
RgbImage { w: ow, h: oh, px }
|
||||
}
|
||||
|
||||
/// Straight RGBA (`0..=1`) over `r`, box-downsampled by `step` like [`Self::rgb_scaled`], read
|
||||
/// in the same strips. Unlike [`Self::rgb`], alpha survives, so a transparent working pixel
|
||||
/// stays transparent instead of becoming mid grey: Object Finder needs that to stop at the
|
||||
/// edge of a transparent layer (#12852).
|
||||
fn rgba_scaled(&self, r: Rect, step: usize) -> Vec<[f32; 4]> {
|
||||
if step <= 1 {
|
||||
return self.rgba(r);
|
||||
}
|
||||
let (w, h) = (r.width() as usize, r.height() as usize);
|
||||
let (ow, oh) = (w.div_ceil(step), h.div_ceil(step));
|
||||
let rows_per = (64usize.div_ceil(step)).max(1);
|
||||
let strips: Vec<usize> = (0..oh.div_ceil(rows_per)).collect();
|
||||
let run = |si: &usize| -> Vec<[f32; 4]> {
|
||||
let oy0 = si * rows_per;
|
||||
let oy1 = (oy0 + rows_per).min(oh);
|
||||
let y0 = r.y0 + (oy0 * step) as i32;
|
||||
let y1 = (r.y0 + (oy1 * step) as i32).min(r.y1);
|
||||
let strip = self.rgba(Rect::new(r.x0, y0, r.x1, y1));
|
||||
downsample_rgba(&strip, w, (y1 - y0) as usize, step)
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let parts: Vec<Vec<[f32; 4]>> = {
|
||||
use rayon::prelude::*;
|
||||
strips.par_iter().map(run).collect()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let parts: Vec<Vec<[f32; 4]>> = strips.iter().map(run).collect();
|
||||
let mut px = Vec::with_capacity(ow * oh);
|
||||
for p in parts {
|
||||
px.extend(p);
|
||||
}
|
||||
px
|
||||
}
|
||||
}
|
||||
|
||||
/// Box-average straight RGBA by an integer `step` (`ceil(w/step) × ceil(h/step)`).
|
||||
fn downsample_rgba(px: &[[f32; 4]], w: usize, h: usize, step: usize) -> Vec<[f32; 4]> {
|
||||
let (ow, oh) = (w.div_ceil(step), h.div_ceil(step));
|
||||
let mut out = vec![[0.0f32; 4]; ow * oh];
|
||||
for oy in 0..oh {
|
||||
for ox in 0..ow {
|
||||
let mut acc = [0.0f32; 4];
|
||||
let mut n = 0.0f32;
|
||||
for y in oy * step..((oy + 1) * step).min(h) {
|
||||
for x in ox * step..((ox + 1) * step).min(w) {
|
||||
if let Some(p) = px.get(y * w + x) {
|
||||
for c in 0..4 {
|
||||
acc[c] += p[c];
|
||||
}
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(o) = out.get_mut(oy * ow + ox) {
|
||||
*o = acc.map(|v| v / n.max(1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Samples a raster surface (any format; converted to straight RGBA).
|
||||
|
||||
@@ -182,16 +182,23 @@ pub fn object_at(sampler: &dyn Sampler, canvas: Rect, x: f32, y: f32, work_px: u
|
||||
/// One [`object_at`] pass over `canvas` (the document or a window of it) at working step `step`;
|
||||
/// `(px, py)` lies inside `canvas`.
|
||||
fn object_in(sampler: &dyn Sampler, canvas: Rect, px: i32, py: i32, step: usize) -> Option<Region> {
|
||||
let img = sampler.rgb_scaled(canvas, step);
|
||||
let (w, h) = (img.w, img.h);
|
||||
if w < 2 || h < 2 {
|
||||
// Alpha is kept, so a transparent pixel is a boundary rather than the mid grey `from_rgba`
|
||||
// would composite it to: a mid-grey object on a transparent layer stays an object (#12852).
|
||||
let rgba = sampler.rgba_scaled(canvas, step);
|
||||
let (w, h) = ((canvas.width() as usize).div_ceil(step), (canvas.height() as usize).div_ceil(step));
|
||||
if w < 2 || h < 2 || rgba.len() < w * h {
|
||||
return None;
|
||||
}
|
||||
let opaque: Vec<bool> = rgba.iter().take(w * h).map(|p| p[3] >= 0.5).collect();
|
||||
let img = RgbImage::from_rgba(&rgba, w, h);
|
||||
// Lightly smoothed, so noise and texture don't stop the growth; edges survive.
|
||||
let lab: Vec<[f32; 3]> = box3(&box3(&img.px, w, h), w, h).iter().map(|c| super::slic::rgb_to_lab(*c)).collect();
|
||||
let sx = (((px - canvas.x0) as usize) / step).min(w - 1);
|
||||
let sy = (((py - canvas.y0) as usize) / step).min(h - 1);
|
||||
let grown = grow_similar(&lab, w, h, sx, sy);
|
||||
if !opaque[sy * w + sx] {
|
||||
return None;
|
||||
}
|
||||
let grown = grow_similar(&lab, w, h, sx, sy, &opaque);
|
||||
let count = grown.iter().filter(|g| **g).count();
|
||||
let boundary = grown.iter().enumerate().filter(|(i, on)| **on && (i % w == 0 || i % w + 1 == w || i / w == 0 || i / w + 1 == h)).count();
|
||||
// shortcut: cropped objects covering most of the frame need a semantic segmenter (#2788).
|
||||
@@ -215,6 +222,10 @@ fn object_in(sampler: &dyn Sampler, canvas: Rect, px: i32, py: i32, step: usize)
|
||||
let inside = xx >= bx0 && xx < bx1 && yy >= by0 && yy < by1;
|
||||
trimap[i] = if grown[i] {
|
||||
PR_FG
|
||||
} else if !opaque[i] {
|
||||
// Transparency is background, whatever it was composited to.
|
||||
any_bg = true;
|
||||
BG
|
||||
} else if inside {
|
||||
PR_BG
|
||||
} else {
|
||||
@@ -250,13 +261,17 @@ fn object_in(sampler: &dyn Sampler, canvas: Rect, px: i32, py: i32, step: usize)
|
||||
|
||||
/// Region growing (4-connected) from `(sx, sy)` over pixels whose CIELAB colour is within a
|
||||
/// distance of the seed area's running mean and whose step from the neighbour it was reached
|
||||
/// from is small, so it stops at edges.
|
||||
fn grow_similar(lab: &[[f32; 3]], w: usize, h: usize, sx: usize, sy: usize) -> Vec<bool> {
|
||||
/// from is small, so it stops at edges. A pixel that is not `opaque` is never entered, so
|
||||
/// transparency stops the growth too.
|
||||
fn grow_similar(lab: &[[f32; 3]], w: usize, h: usize, sx: usize, sy: usize, opaque: &[bool]) -> Vec<bool> {
|
||||
const MEAN_DIST: f32 = 32.0;
|
||||
const EDGE_STEP: f32 = 10.0;
|
||||
let d = |a: [f32; 3], b: [f32; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt();
|
||||
let mut out = vec![false; w * h];
|
||||
let Some(&seed) = lab.get(sy * w + sx) else { return out };
|
||||
if !opaque.get(sy * w + sx).copied().unwrap_or(false) {
|
||||
return out;
|
||||
}
|
||||
let (mut sum, mut n) = ([seed[0] as f64, seed[1] as f64, seed[2] as f64], 1.0f64);
|
||||
let mut stack = vec![(sx, sy)];
|
||||
out[sy * w + sx] = true;
|
||||
@@ -269,7 +284,7 @@ fn grow_similar(lab: &[[f32; 3]], w: usize, h: usize, sx: usize, sy: usize) -> V
|
||||
continue;
|
||||
}
|
||||
let i = ny * w + nx;
|
||||
if out[i] {
|
||||
if out[i] || !opaque.get(i).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let q = lab[i];
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::*;
|
||||
use photocraft_color::{PixelFormat, SampleType};
|
||||
mod adversarial_native;
|
||||
mod ext;
|
||||
mod mosaic;
|
||||
mod selection_mix;
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
use super::*;
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
|
||||
#[test]
|
||||
/// Without an owner extent, the requested area supplies Average's domain even beyond reference bounds.
|
||||
fn average_without_extent_uses_requested_area_beyond_reference_bounds() {
|
||||
let bounds = Rect::new(0, 0, 1, 1);
|
||||
let area = Rect::new(-1, 0, 2, 1);
|
||||
for sample in SampleType::ALL {
|
||||
let mut source = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
|
||||
let colors = if sample == SampleType::F32 { [[-2., 0., 4.], [0., 2., 2.], [2., 4., 0.]] } else { [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]] };
|
||||
for (x, (color, alpha)) in (-1..2).zip(colors.into_iter().zip([0., 0.5, 1.])) {
|
||||
source.write_pixel(x, 0, &[color[0], color[1], color[2], alpha]);
|
||||
}
|
||||
source.write_pixel(-2, 0, &[0.25, 0.5, 0.75, 1.]);
|
||||
source.write_pixel(2, 0, &[0.75, 0.5, 0.25, 1.]);
|
||||
let before = source.clone();
|
||||
let params = FilterParams::Average;
|
||||
for output in [
|
||||
apply(&source, ¶ms, area, bounds, None),
|
||||
apply_tiled(&source, ¶ms, area, bounds, None, 1, None),
|
||||
apply_tiled_with(&source, ¶ms, area, bounds, None, 2, None, &Interrupt::NONE).unwrap(),
|
||||
] {
|
||||
let expected = if sample == SampleType::F32 { [0., 2., 2.] } else { [1. / 3.; 3] };
|
||||
for x in -1..2 {
|
||||
let pixel = output.pixel(x, 0);
|
||||
for (value, expected) in pixel.iter().zip(expected) {
|
||||
assert!((value - expected).abs() < 1e-6, "{sample:?}, x={x}: {pixel:?}");
|
||||
}
|
||||
assert_eq!(pixel[3], source.pixel(x, 0)[3], "native alpha is preserved");
|
||||
}
|
||||
for x in [-2, 2] {
|
||||
assert_eq!(output.pixel(x, 0), source.pixel(x, 0), "the requested area still limits publication");
|
||||
}
|
||||
}
|
||||
assert_eq!(source, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Checked and optional Average replay publish the requested owner area beyond the document canvas.
|
||||
fn average_dispatch_uses_owner_extent_for_off_canvas_mean_and_writes() {
|
||||
let canvas = Rect::new(0, 0, 2, 1);
|
||||
let extent = Rect::new(-2, 0, 4, 1);
|
||||
let area = Rect::new(-2, 0, 3, 1);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
for x in -2..4 {
|
||||
source.write_pixel(x, 0, &[(x + 2) as f32, 0.25, 0.5, 0.5]);
|
||||
}
|
||||
let expected = average::apply_preserving_alpha_with(&source, area, extent, None, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(expected.pixel(-2, 0), vec![2., 0.25, 0.5, 0.5]);
|
||||
assert_eq!(expected.pixel(3, 0), source.pixel(3, 0), "outside the requested publication area");
|
||||
let params = FilterParams::Average;
|
||||
let actual = try_apply_in_with(&source, ¶ms, area, canvas, None, extent, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(apply_in_with(&source, ¶ms, area, canvas, None, extent, &Interrupt::NONE).unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// HDR adaptation reads the complete owner while area restricts publication, including off-canvas pixels.
|
||||
fn hdr_dispatch_uses_owner_extent_for_adaptation_and_off_canvas_writes() {
|
||||
let canvas = Rect::new(0, 0, 2, 1);
|
||||
let extent = Rect::new(-2, -1, 4, 2);
|
||||
let area = Rect::new(-1, 0, 3, 1);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
for y in -1..2 {
|
||||
for x in -2..4 {
|
||||
source.write_pixel(x, y, &[if x == -2 { 16. } else { 0.2 + 0.3 * (x + 2) as f32 }, 0.1 + 0.12 * (y + 1) as f32, 0.4, 1.]);
|
||||
}
|
||||
}
|
||||
let options = tone::HdrToning { radius: 1., ..Default::default() };
|
||||
let expected = tone::checked_hdr::apply_with(&source, &options, area, extent, None, &Interrupt::NONE).unwrap();
|
||||
let canvas_only = tone::checked_hdr::apply_with(&source, &options, area, canvas, None, &Interrupt::NONE).unwrap();
|
||||
assert_ne!(expected.pixel(-1, 0), source.pixel(-1, 0), "off-canvas publication must actually change pixels");
|
||||
assert_ne!(expected.pixel(0, 0), canvas_only.pixel(0, 0), "off-canvas owner samples must affect adaptation inside the canvas");
|
||||
assert_eq!(expected.pixel(-2, -1), source.pixel(-2, -1), "area still limits publication");
|
||||
let params = FilterParams::HdrToning(options);
|
||||
let actual = try_apply_in_with(&source, ¶ms, area, canvas, None, extent, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(apply_in_with(&source, ¶ms, area, canvas, None, extent, &Interrupt::NONE).unwrap(), expected);
|
||||
}
|
||||
|
||||
/// The fallible dispatcher retains native failures instead of converting them into missing output.
|
||||
#[test]
|
||||
fn checked_dispatch_preserves_parameters_samples_limits_and_cancellation() {
|
||||
let area = Rect::new(0, 0, 1, 1);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
source.write_pixel(0, 0, &[f32::NAN, 0., 0., 1.]);
|
||||
for params in [FilterParams::Average, FilterParams::SetAlpha { value: 0.5 }] {
|
||||
assert_eq!(try_apply_in_with(&source, ¶ms, area, area, None, area, &Interrupt::NONE), Err(ApplyError::Native(coverage::Error::NonFiniteSample)));
|
||||
}
|
||||
let bad_hdr = FilterParams::HdrToning(tone::HdrToning { radius: f32::NAN, ..Default::default() });
|
||||
assert_eq!(
|
||||
try_apply_in_with(&source, &bad_hdr, area, area, None, area, &Interrupt::NONE),
|
||||
Err(ApplyError::Hdr(tone::checked_hdr::Error::InvalidParameter))
|
||||
);
|
||||
let huge = Rect::new(0, 0, 10_000, 10_000);
|
||||
assert_eq!(
|
||||
try_apply_in_with(&source, &FilterParams::Average, huge, huge, None, huge, &Interrupt::NONE),
|
||||
Err(ApplyError::Native(coverage::Error::InvalidGeometry))
|
||||
);
|
||||
let cancel = || true;
|
||||
assert_eq!(try_apply_in_with(&source, &FilterParams::Average, area, area, None, area, &Interrupt::cancel_only(&cancel)), Err(ApplyError::Cancelled));
|
||||
assert!(apply_in_with(&source, &FilterParams::Average, area, area, None, area, &Interrupt::NONE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Pin CMYK convolution offsets to brightness rather than increasing the stored ink amounts.
|
||||
fn cmyk_convolution_offset_is_a_brightness_offset() {
|
||||
let rect = Rect::new(0, 0, 1, 1);
|
||||
let source = Surface::with_default(PixelFormat::new(ColorMode::Cmyk, SampleType::F32, false), &[0.3; 4]);
|
||||
for (offset, ink) in [(0., 1.), (0.25, 0.75)] {
|
||||
let params =
|
||||
convolution::Params { kernel: vec![0.; 25], scale: 1., offset, channels: vec![true; 4], alpha_weighted: false, edge: convolution::Edge::Repeat };
|
||||
assert_eq!(convolution::apply_with(&source, ¶ms, rect, rect, None, &Interrupt::NONE).unwrap().pixel(0, 0), vec![ink; 4]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Require flat RGB and grayscale histograms to produce identity tone, contrast and color corrections.
|
||||
fn flat_auto_levels_are_identity_at_every_native_depth() {
|
||||
for depth in SampleType::ALL {
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
|
||||
for value in [0., 128. / 255., 1.] {
|
||||
let format = PixelFormat::new(mode, depth, true);
|
||||
let source = Surface::with_default(format, &[vec![value; format.channels() - 1], vec![1.]].concat());
|
||||
for kind in [tone::auto_levels::Kind::Tone, tone::auto_levels::Kind::Contrast, tone::auto_levels::Kind::Color] {
|
||||
assert_eq!(tone::auto_levels::analyze(&source, Rect::new(0, 0, 2, 2), kind, &Interrupt::NONE).unwrap(), [[0., 1., 1.]; 3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Compare matte removal with native-channel unassociation across models, depths and alpha endpoints.
|
||||
fn native_matte_unassociation_keeps_separations_and_hdr() {
|
||||
let rect = Rect::new(0, 0, 1, 1);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Multichannel] {
|
||||
for depth in SampleType::ALL {
|
||||
let format = PixelFormat::new(mode, depth, true);
|
||||
for alpha in [0., 0.5, 1.] {
|
||||
let mut values = (0..format.channels() - 1).map(|c| 0.1 * (c + 1) as f32).collect::<Vec<_>>();
|
||||
if depth == SampleType::F32 {
|
||||
values[0] = -0.75;
|
||||
if values.len() > 1 {
|
||||
values[1] = 2.;
|
||||
}
|
||||
}
|
||||
values.push(alpha);
|
||||
let mut source = Surface::new(format);
|
||||
source.write_pixel(0, 0, &values);
|
||||
let before = source.pixel(0, 0);
|
||||
let mut expected = before.clone();
|
||||
let a = *before.last().unwrap();
|
||||
if a > 0. && a < 1. {
|
||||
let cmyk_black = photocraft_color::convert::rgb_to_cmyk([0.; 3]);
|
||||
for (channel, v) in expected.iter_mut().take(format.channels() - 1).enumerate() {
|
||||
let black: f32 = match (mode, channel) {
|
||||
(ColorMode::Cmyk, c) => cmyk_black[c],
|
||||
(ColorMode::Lab, 1 | 2) => 128. / 255.,
|
||||
_ => 0.,
|
||||
};
|
||||
*v = ((f64::from(*v) - f64::from(black) * (1. - f64::from(a))) / f64::from(a)) as f32;
|
||||
}
|
||||
}
|
||||
let mut oracle = Surface::new(format);
|
||||
oracle.write_pixel(0, 0, &expected);
|
||||
assert_eq!(
|
||||
matting::remove_black_matte_with(&source, rect, &Interrupt::NONE).unwrap().pixel(0, 0),
|
||||
oracle.pixel(0, 0),
|
||||
"{mode:?}/{depth:?}/{alpha}"
|
||||
);
|
||||
assert_eq!(source.pixel(0, 0), before);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Recover CMYK foreground inks and preserve neutral Lab chroma when removing a black matte.
|
||||
fn black_matte_keeps_lab_neutral_and_cmyk_native_separations() {
|
||||
let rect = Rect::new(0, 0, 1, 1);
|
||||
let mut cmyk = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true));
|
||||
let foreground = [0., 0.1, 0.2, 0.3];
|
||||
let matte = photocraft_color::convert::rgb_to_cmyk([0.; 3]);
|
||||
let mut observed: Vec<_> = foreground.into_iter().zip(matte).map(|(f, b)| 0.5 * f + 0.5 * b).collect();
|
||||
observed.push(0.5);
|
||||
cmyk.write_pixel(0, 0, &observed);
|
||||
let unmatte = matting::remove_black_matte_with(&cmyk, rect, &Interrupt::NONE).unwrap();
|
||||
for (got, expected) in unmatte.pixel(0, 0).into_iter().zip(foreground) {
|
||||
assert!((got - expected).abs() < 1e-6);
|
||||
}
|
||||
let mut lab = Surface::new(PixelFormat::new(ColorMode::Lab, SampleType::F32, true));
|
||||
lab.write_pixel(0, 0, &[0.2, 128. / 255., 128. / 255., 0.5]);
|
||||
let unmatte = matting::remove_black_matte_with(&lab, rect, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(unmatte.pixel(0, 0), vec![0.4, 128. / 255., 128. / 255., 0.5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Keep unselected color-channel bits intact when convolution or seeded noise changes selected alpha.
|
||||
fn selected_alpha_filters_preserve_every_unselected_channel_bit() {
|
||||
let rect = Rect::new(0, 0, 1, 1);
|
||||
let mask = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.3]);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
source.write_pixel(0, 0, &[0.3, -0., 1e30, 0.25]);
|
||||
let before = source.pixel(0, 0);
|
||||
let convolution = convolution::Params {
|
||||
kernel: vec![0.; 25],
|
||||
scale: 1.,
|
||||
offset: 0.7,
|
||||
channels: vec![false, false, false, true],
|
||||
alpha_weighted: false,
|
||||
edge: convolution::Edge::Repeat,
|
||||
};
|
||||
let got = convolution::apply_with(&source, &convolution, rect, rect, Some(&mask), &Interrupt::NONE).unwrap();
|
||||
for (v, b) in got.pixel(0, 0).iter().zip(&before).take(3) {
|
||||
assert_eq!(v.to_bits(), b.to_bits());
|
||||
}
|
||||
for seed in 0..32 {
|
||||
let noise = channel_noise::Params { amounts: vec![0., 0., 0., 100.], distribution: Distribution::Uniform, monochromatic: false, relative: false, seed };
|
||||
let got = channel_noise::apply_with(&source, &noise, rect, rect, Some(&mask), &Interrupt::NONE).unwrap();
|
||||
for (v, b) in got.pixel(0, 0).iter().zip(&before).take(3) {
|
||||
assert_eq!(v.to_bits(), b.to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Exclude hidden source colors from the premultiplied Average result when a selection creates coverage.
|
||||
fn average_selection_does_not_mix_hidden_colors_into_new_coverage() {
|
||||
let rect = Rect::new(0, 0, 2, 1);
|
||||
let mask = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.5]);
|
||||
for depth in SampleType::ALL {
|
||||
let mut source = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true));
|
||||
source.write_pixel(0, 0, &[1., 0., 0., 0.]);
|
||||
source.write_pixel(1, 0, &[0., 0., 1., 1.]);
|
||||
let out = average::apply_with(&source, rect, rect, Some(&mask), &Interrupt::NONE).unwrap();
|
||||
for (v, expected) in out.pixel(0, 0).into_iter().zip([0., 0., 1., 0.25]) {
|
||||
assert!((v - expected).abs() < 0.005);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Exercise extreme finite HDR colors and controls without allowing nonfinite or out-of-range tone results.
|
||||
fn checked_hdr_extreme_finite_inputs_and_controls_stay_finite() {
|
||||
for (shadow, highlight) in [(0., 0.), (50., 50.), (50., -50.), (-50., 50.)] {
|
||||
for mut pixels in [
|
||||
[[0.001, 0.001, 0.001, 1.], [1e30, 1e30, 1e30, 1.]],
|
||||
[[1e30, 1e30, 1e30, 1.], [f32::MAX, -f32::MAX, 0., 1.]],
|
||||
[[f32::MAX, f32::MAX, f32::MAX, 1.], [0.001, 0.001, 0.001, 1.]],
|
||||
] {
|
||||
let params = tone::HdrToning { radius: 2., detail: 300., exposure: 5., gamma: 0.1, shadow, highlight, ..Default::default() };
|
||||
tone::checked_hdr::process_with(&mut pixels, 2, 1, ¶ms, &Interrupt::NONE).unwrap();
|
||||
assert!(pixels.iter().flatten().all(|v| v.is_finite() && (0. ..=1.).contains(v)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,3 +96,113 @@ fn selection_mixing_without_alpha_keeps_every_channel_independent() {
|
||||
assert_eq!(data, vec![0.375; ch]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Exercise shared selection mixing with extreme finite HDR through five independently checked native filter entry
|
||||
/// points.
|
||||
fn selected_finite_hdr_is_safe_through_all_five_checked_native_apis() {
|
||||
let ctl = photocraft_raster::Interrupt::NONE;
|
||||
let b = Rect::new(0, 0, 1, 1);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
source.write_pixel(0, 0, &[f32::MAX, 0., 0., 1.]);
|
||||
let mut kernel = vec![0.; 25];
|
||||
kernel[12] = -1.;
|
||||
let p = convolution::Params {
|
||||
kernel,
|
||||
scale: 1.,
|
||||
offset: 0.,
|
||||
channels: vec![true, false, false, false],
|
||||
alpha_weighted: false,
|
||||
edge: convolution::Edge::Repeat,
|
||||
};
|
||||
let output = convolution::apply_with(&source, &p, b, b, Some(&selection(0.5)), &ctl).unwrap();
|
||||
assert_eq!(output.pixel(0, 0), vec![0., 0., 0., 1.]);
|
||||
let p = channel_noise::Params { amounts: vec![400., 0., 0., 0.], distribution: Distribution::Uniform, monochromatic: false, relative: true, seed: 0 };
|
||||
let baseline = channel_noise::apply_with(&source, &p, b, b, None, &ctl).unwrap().pixel(0, 0)[0];
|
||||
assert!(baseline < 0.);
|
||||
let output = channel_noise::apply_with(&source, &p, b, b, Some(&selection(0.5)), &ctl).unwrap();
|
||||
assert_eq!(output.pixel(0, 0)[0], (f64::from(f32::MAX) + (f64::from(baseline) - f64::from(f32::MAX)) * 0.5) as f32);
|
||||
let b = Rect::new(0, 0, 3, 3);
|
||||
source.fill_rect(b, &[-f32::MAX, 0., 0., 1.]);
|
||||
source.write_pixel(1, 1, &[f32::MAX, 0., 0., 1.]);
|
||||
let p = rank::Params { radius: 1, color_percentile: 50., alpha_percentile: 50., shape: rank::Neighborhood::Square, channels: None };
|
||||
let output = rank::apply_with(&source, &p, b, b, Some(&selection(0.5)), &ctl).unwrap();
|
||||
assert_eq!(output.pixel(1, 1), vec![0., 0., 0., 1.]);
|
||||
source.fill_rect(b, &[f32::MAX, 0., 0., 1.]);
|
||||
source.write_pixel(1, 1, &[-f32::MAX, 0., 0., 1.]);
|
||||
let output =
|
||||
coverage::apply_with(&source, coverage::Operation::FillHoles { connectivity: 4, alpha_only: false }, b, b, Some(&selection(0.5)), &ctl).unwrap();
|
||||
assert_eq!(output.pixel(1, 1), vec![0., 0., 0., 1.]);
|
||||
let b = Rect::new(0, 0, 2, 1);
|
||||
source.write_pixel(0, 0, &[f32::MAX, 0., 0., 1.]);
|
||||
source.write_pixel(1, 0, &[-f32::MAX, 0., 0., 1.]);
|
||||
let mut mask = selection(1.);
|
||||
mask.write_pixel(1, 0, &[0.5]);
|
||||
let output = average::apply_with(&source, b, b, Some(&mask), &ctl).unwrap();
|
||||
assert!((f64::from(output.pixel(1, 0)[0]) / f64::from(f32::MAX) + 1. / 3.).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Verify changed-alpha mixing handles finite HDR roundoff and rejects unrepresentable results without source
|
||||
/// mutation.
|
||||
fn changed_alpha_hdr_roundoff_and_unrepresentable_mix_do_not_corrupt_source() {
|
||||
let b = Rect::new(0, 0, 1, 1);
|
||||
let mut source = Surface::new(PixelFormat::RGBA32F);
|
||||
source.write_pixel(0, 0, &[f32::MAX, 0., 0., 0.001]);
|
||||
let original = source.clone();
|
||||
let out = coverage::apply_with(&source, coverage::Operation::SetAlpha(1.), b, b, Some(&selection(0.003)), &photocraft_raster::Interrupt::NONE).unwrap();
|
||||
assert_eq!(out.pixel(0, 0)[0], f32::MAX);
|
||||
assert_eq!(source, original);
|
||||
assert_eq!(out.pixel(0, 0)[3], 0.001 + (1. - 0.001) * 0.003);
|
||||
let b = Rect::new(0, 0, 3, 3);
|
||||
source.fill_rect(b, &[f32::MAX, 0., 0., 1.]);
|
||||
source.write_pixel(1, 1, &[-f32::MAX, 0., 0., -0.5]);
|
||||
let original = source.clone();
|
||||
assert_eq!(
|
||||
coverage::apply_with(
|
||||
&source,
|
||||
coverage::Operation::FillHoles { connectivity: 4, alpha_only: false },
|
||||
b,
|
||||
b,
|
||||
Some(&selection(0.5)),
|
||||
&photocraft_raster::Interrupt::NONE
|
||||
)
|
||||
.unwrap_err(),
|
||||
coverage::Error::NonFiniteSample
|
||||
);
|
||||
assert_eq!(source, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Pin ordinary finite selection arithmetic bit-for-bit so overflow safeguards do not alter established native
|
||||
/// output.
|
||||
fn finite_ordinary_selection_results_keep_legacy_float_bits() {
|
||||
let b = Rect::new(0, 0, 1, 1);
|
||||
for a in [0., 0.25, 0.75, 1.] {
|
||||
for f in [0., 0.25, 0.75, 1.] {
|
||||
for k in [0., 0.1, 0.5, 0.9, 1.] {
|
||||
let before = vec![-2., 0.25, 4., a];
|
||||
let filtered = vec![4., 0.75, -2., f];
|
||||
let mut expected = filtered.clone();
|
||||
if k == 0. {
|
||||
expected = before.clone();
|
||||
} else if k < 1. {
|
||||
if a != f {
|
||||
let ma = a + (f - a) * k;
|
||||
for c in 0..3 {
|
||||
expected[c] = if ma > 0. { (before[c] * (a * (1. - k)) + filtered[c] * (f * k)) / ma } else { 0. };
|
||||
}
|
||||
expected[3] = ma;
|
||||
} else {
|
||||
for c in 0..4 {
|
||||
expected[c] = before[c] + (filtered[c] - before[c]) * k;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut actual = filtered;
|
||||
mix_selection(&mut actual, b, &selection(k), &Image { rect: b, ch: 4, data: before }, true);
|
||||
assert_eq!(actual.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), expected.iter().map(|v| v.to_bits()).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
//! convert any colour model / bit depth to RGBA first (as `Image › Adjustments` does for the
|
||||
//! per-pixel adjustments). Formulas are documented approximations of Photoshop's behaviour,
|
||||
//! derived from its manual and observation, not from its implementation; Shadows/Highlights is
|
||||
//! measured on Photoshop (see [`shadows_highlights`]).
|
||||
//! measured on Photoshop (see [`shadows_highlights()`]).
|
||||
|
||||
use photocraft_color::convert::{lab_to_srgb, srgb_to_lab};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -214,6 +214,9 @@ pub struct HdrToning {
|
||||
pub curve: Vec<(f32, f32)>,
|
||||
}
|
||||
|
||||
pub mod auto_levels;
|
||||
pub mod checked_hdr;
|
||||
|
||||
impl Default for HdrToning {
|
||||
fn default() -> Self {
|
||||
HdrToning {
|
||||
@@ -262,8 +265,9 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) {
|
||||
});
|
||||
let mut base = logl.clone();
|
||||
gauss_blur_n(&mut base, w, h, 1, p.radius.max(1.0) / 2.0);
|
||||
let n = px.iter().filter(|q| q[3] > 0.0).count().max(1) as f32;
|
||||
let mean = base.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).map(|(b, _)| *b).sum::<f32>() / n;
|
||||
let n = px.iter().filter(|q| q[3] > 0.0).count().max(1) as f64;
|
||||
// Match the checked path: narrow sums lose log-luminance samples on large scenes.
|
||||
let mean = (base.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).map(|(b, _)| f64::from(*b)).sum::<f64>() / n) as f32;
|
||||
let compress = 1.0 / (1.0 + p.strength.max(0.0));
|
||||
let detail = 1.0 + p.detail / 100.0;
|
||||
let exposure = 2f32.powf(p.exposure);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
//! Numeric analysis for PhotoCraft's ordinary Auto Tone/Contrast/Color policy.
|
||||
//! Display-bin sampling and clipping are independent of document/layer models.
|
||||
use photocraft_geom::{Rect, TILE_SIZE};
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
|
||||
const MAX_ROW_BYTES: usize = 64 << 20;
|
||||
const MAX_SAMPLES: u64 = 16_000_000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Tone,
|
||||
Contrast,
|
||||
Color,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Cancelled,
|
||||
InvalidGeometry,
|
||||
WorkspaceLimit,
|
||||
Allocation,
|
||||
}
|
||||
impl std::fmt::Display for Error {
|
||||
/// Expose bounded native automatic-analysis errors as actionable messages for calling hosts.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Cancelled => "native automatic tone analysis cancelled",
|
||||
Self::InvalidGeometry => "invalid native automatic tone analysis geometry",
|
||||
Self::WorkspaceLimit => "native automatic tone analysis exceeds bounded workspace",
|
||||
Self::Allocation => "native automatic tone analysis allocation unavailable",
|
||||
})
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// Sample native display bins on a bounded grid, skipping transparent pixels and checking cancellation per
|
||||
/// row/block.
|
||||
fn histograms(surface: &Surface, area: Rect, ctl: &Interrupt<'_>) -> Result<[[u64; 256]; 3], Error> {
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
let width = usize::try_from(i64::from(area.x1) - i64::from(area.x0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
let height = usize::try_from(i64::from(area.y1) - i64::from(area.y0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
if [area.x0, area.y0].iter().any(|n| n.checked_sub(TILE_SIZE).is_none()) || [area.x1, area.y1].iter().any(|n| n.checked_add(TILE_SIZE).is_none()) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let mut histograms = [[0; 256]; 3];
|
||||
if width == 0 || height == 0 {
|
||||
return Ok(histograms);
|
||||
}
|
||||
let pixels = (width as u64).checked_mul(height as u64).ok_or(Error::WorkspaceLimit)?;
|
||||
let step = usize::try_from((pixels / 4_000_000).max(1)).map_err(|_| Error::WorkspaceLimit)?.isqrt().max(1);
|
||||
let samples = (width.div_ceil(step) as u64).checked_mul(height.div_ceil(step) as u64).ok_or(Error::WorkspaceLimit)?;
|
||||
if width.checked_mul(4).is_none_or(|bytes| bytes > MAX_ROW_BYTES) || samples > MAX_SAMPLES {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
let mut row = Vec::new();
|
||||
row.try_reserve_exact(width).map_err(|_| Error::Allocation)?;
|
||||
row.resize(width, [0u8; 4]);
|
||||
for y in (area.y0..area.y1).step_by(step) {
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
surface.read_rgba8_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row);
|
||||
for (index, pixel) in row.iter().step_by(step).enumerate() {
|
||||
if index.is_multiple_of(4096) {
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
}
|
||||
if pixel.get(3) == Some(&0) {
|
||||
continue;
|
||||
}
|
||||
for (channel, &sample) in histograms.iter_mut().zip(pixel) {
|
||||
let count = channel.get_mut(usize::from(sample)).ok_or(Error::InvalidGeometry)?;
|
||||
*count = count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
Ok(histograms)
|
||||
}
|
||||
|
||||
/// Find the native 0.1-percent histogram endpoints; empty or flat ranges use identity.
|
||||
fn clip_points(histogram: &[u64; 256]) -> (f32, f32) {
|
||||
let total: u64 = histogram.iter().sum();
|
||||
if total == 0 {
|
||||
return (0., 1.);
|
||||
}
|
||||
let limit = (total as f64 * 0.001) as u64;
|
||||
let (mut accumulated, mut low) = (0u64, 0usize);
|
||||
while low < 255 && accumulated + histogram.get(low).copied().unwrap_or(0) <= limit {
|
||||
accumulated += histogram.get(low).copied().unwrap_or(0);
|
||||
low += 1;
|
||||
}
|
||||
let (mut accumulated, mut high) = (0u64, 255usize);
|
||||
while high > 0 && accumulated + histogram.get(high).copied().unwrap_or(0) <= limit {
|
||||
accumulated += histogram.get(high).copied().unwrap_or(0);
|
||||
high -= 1;
|
||||
}
|
||||
if low >= high { (0., 1.) } else { (low as f32 / 255., high as f32 / 255.) }
|
||||
}
|
||||
/// Select the central occupied display bin for ordinary native Auto Color neutralization.
|
||||
fn median(histogram: &[u64; 256]) -> f32 {
|
||||
let total: u64 = histogram.iter().sum();
|
||||
let mut accumulated = 0;
|
||||
for (index, value) in histogram.iter().enumerate() {
|
||||
accumulated += value;
|
||||
if accumulated * 2 >= total {
|
||||
return index as f32 / 255.;
|
||||
}
|
||||
}
|
||||
0.5
|
||||
}
|
||||
|
||||
/// Returns three native Levels rows `[in_black, in_white, gamma]` in RGB order.
|
||||
/// Uses the existing 256 display bins, ordinary alpha exclusion, sampled-grid
|
||||
/// policy, 0.1% end clipping, and Auto Color median neutralization unchanged.
|
||||
pub fn analyze(surface: &Surface, area: Rect, kind: Kind, ctl: &Interrupt<'_>) -> Result<[[f32; 3]; 3], Error> {
|
||||
let histogram = histograms(surface, area, ctl)?;
|
||||
let mut rows = [[0., 1., 1.]; 3];
|
||||
if kind == Kind::Contrast {
|
||||
let mut combined = [0u64; 256];
|
||||
for channel in &histogram {
|
||||
for (sum, value) in combined.iter_mut().zip(channel) {
|
||||
*sum += value;
|
||||
}
|
||||
}
|
||||
let (black, white) = clip_points(&combined);
|
||||
rows.fill([black, white, 1.]);
|
||||
} else {
|
||||
for (row, channel) in rows.iter_mut().zip(&histogram) {
|
||||
let (black, white) = clip_points(channel);
|
||||
*row = [black, white, 1.];
|
||||
}
|
||||
if kind == Kind::Color {
|
||||
let medians = histogram.map(|channel| median(&channel));
|
||||
let target = medians.iter().sum::<f32>() / 3.;
|
||||
for (row, median) in rows.iter_mut().zip(medians) {
|
||||
let [black, white, gamma] = row;
|
||||
let t = ((median - *black) / (*white - *black).max(1e-3)).clamp(0.02, 0.98);
|
||||
let want = ((target - *black) / (*white - *black).max(1e-3)).clamp(0.02, 0.98);
|
||||
*gamma = (t.ln() / want.ln()).clamp(0.1, 9.99);
|
||||
}
|
||||
}
|
||||
}
|
||||
ctl.check().map_err(|_| Error::Cancelled)?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
#[test]
|
||||
/// Pin native per-channel, combined-contrast and color-neutralization policies against known histogram samples.
|
||||
fn known_native_bins_keep_tone_contrast_and_color_policy_at_every_depth() {
|
||||
for sample in SampleType::ALL {
|
||||
let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
|
||||
surface.write_region(Rect::new(0, 0, 3, 1), &[0.2, 0.3, 0.4, 1., 0.4, 0.5, 0.6, 1., 0.6, 0.7, 0.8, 1.]);
|
||||
let tone = analyze(&surface, Rect::new(0, 0, 3, 1), Kind::Tone, &Interrupt::NONE).unwrap();
|
||||
let contrast = analyze(&surface, Rect::new(0, 0, 3, 1), Kind::Contrast, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(tone[0], [51. / 255., 153. / 255., 1.]);
|
||||
assert_eq!(contrast, [[51. / 255., 204. / 255., 1.]; 3]);
|
||||
let color = analyze(&surface, Rect::new(0, 0, 3, 1), Kind::Color, &Interrupt::NONE).unwrap();
|
||||
assert!(color[0][2] > 1. && color[2][2] < 1.);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Verify transparent/empty inputs and hostile geometry remain bounded and cancellation returns a controlled
|
||||
/// error.
|
||||
fn transparent_empty_hostile_and_cancelled_analysis_are_bounded() {
|
||||
let surface = Surface::new(PixelFormat::RGBA8);
|
||||
assert_eq!(analyze(&surface, Rect::new(0, 0, 2, 2), Kind::Tone, &Interrupt::NONE).unwrap(), [[0., 1., 1.]; 3]);
|
||||
assert!(matches!(analyze(&surface, Rect::new(2, 0, 1, 1), Kind::Tone, &Interrupt::NONE), Err(Error::InvalidGeometry)));
|
||||
assert!(matches!(analyze(&surface, Rect::new(i32::MIN, 0, i32::MAX, 1), Kind::Tone, &Interrupt::NONE), Err(Error::InvalidGeometry)));
|
||||
// One pixel near the signed-coordinate edge must fail before native
|
||||
// tile bounds can overflow; this does not require a large allocation.
|
||||
assert!(matches!(analyze(&surface, Rect::new(i32::MAX - 1, 0, i32::MAX, 1), Kind::Tone, &Interrupt::NONE), Err(Error::InvalidGeometry)));
|
||||
assert!(matches!(analyze(&surface, Rect::new(0, 0, 20_000_000, 1), Kind::Tone, &Interrupt::NONE), Err(Error::WorkspaceLimit)));
|
||||
assert!(matches!(analyze(&surface, Rect::new(0, 0, 1, 1), Kind::Tone, &Interrupt::cancel_only(&|| true)), Err(Error::Cancelled)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
//! Checked replay of PhotoCraft's native local HDR adaptation. No format-specific controls.
|
||||
use super::{HdrToning, curve_eval, luma};
|
||||
use crate::fxutil::gauss_box_radii;
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Interrupt, Surface, from_rgba_into, to_rgba};
|
||||
|
||||
pub const MAX_PIXELS: usize = 64 * 1024 * 1024;
|
||||
pub const MAX_WORKSPACE_BYTES: usize = 1_500_000_000;
|
||||
const MAX_EDGE: usize = 65_536;
|
||||
const MAX_CURVE: usize = 4096;
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Cancelled,
|
||||
InvalidGeometry,
|
||||
InvalidParameter,
|
||||
NonFiniteSample,
|
||||
WorkspaceLimit,
|
||||
Allocation,
|
||||
}
|
||||
impl std::fmt::Display for Error {
|
||||
/// Render checked HDR geometry, parameter, sample, allocation and cancellation failures as actionable messages.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Cancelled => "native HDR cancelled",
|
||||
Self::InvalidGeometry => "invalid native HDR geometry",
|
||||
Self::InvalidParameter => "invalid native HDR parameter",
|
||||
Self::NonFiniteSample => "native HDR requires finite samples",
|
||||
Self::WorkspaceLimit => "native HDR exceeds bounded workspace",
|
||||
Self::Allocation => "native HDR workspace allocation failed",
|
||||
})
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
/// Convert the shared interrupt check into this operation's explicit cancellation error.
|
||||
fn check(ctl: &Interrupt<'_>) -> Result<(), Error> {
|
||||
ctl.check().map_err(|_| Error::Cancelled)
|
||||
}
|
||||
// Independent pixel phases use PhotoCraft's normal native rayon scheduling. No parallel
|
||||
// reduction: the visibility-weighted mean retains its original deterministic serial order.
|
||||
/// Process disjoint chunks in parallel only on sufficiently large native workloads; preserve chunk offsets and the
|
||||
/// serial wasm path.
|
||||
fn independent_chunks<T: Send>(values: &mut [T], f: impl Fn(usize, &mut [T]) -> Result<(), Error> + Sync + Send) -> Result<(), Error> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if values.len() >= 65_536 {
|
||||
use rayon::prelude::*;
|
||||
return values.par_chunks_mut(2048).enumerate().try_for_each(|(i, q)| f(i * 2048, q));
|
||||
}
|
||||
values.chunks_mut(2048).enumerate().try_for_each(|(i, q)| f(i * 2048, q))
|
||||
}
|
||||
/// Allocate scratch fallibly and initialize it in cancellable bounded chunks.
|
||||
fn zeroes<T: Clone>(count: usize, value: T, ctl: &Interrupt<'_>) -> Result<Vec<T>, Error> {
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(count).map_err(|_| Error::Allocation)?;
|
||||
while out.len() < count {
|
||||
check(ctl)?;
|
||||
out.resize(out.len().saturating_add(2048).min(count), value.clone());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// Refuse nonfinite or out-of-range native HDR controls and invalid bounded tone-curve points before processing.
|
||||
pub fn validate(p: &HdrToning) -> Result<(), Error> {
|
||||
for (v, lo, hi) in [
|
||||
(p.radius, 1., 500.),
|
||||
(p.strength, 0.1, 4.),
|
||||
(p.gamma, 0.1, 2.),
|
||||
(p.exposure, -5., 5.),
|
||||
(p.detail, -100., 300.),
|
||||
(p.shadow, -100., 100.),
|
||||
(p.highlight, -100., 100.),
|
||||
(p.vibrance, -100., 100.),
|
||||
(p.saturation, -100., 100.),
|
||||
] {
|
||||
if !v.is_finite() || v < lo || v > hi {
|
||||
return Err(Error::InvalidParameter);
|
||||
}
|
||||
}
|
||||
if p.curve.len() > MAX_CURVE || p.curve.iter().any(|(x, y)| !x.is_finite() || !y.is_finite() || !(0. ..=1.).contains(x) || !(0. ..=1.).contains(y)) {
|
||||
return Err(Error::InvalidParameter);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Admit only positive bounded edges and a checked pixel count within the native HDR workspace domain.
|
||||
fn geometry(w: usize, h: usize) -> Result<usize, Error> {
|
||||
if w == 0 || h == 0 || w > MAX_EDGE || h > MAX_EDGE {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
w.checked_mul(h).filter(|n| *n <= MAX_PIXELS).ok_or(Error::WorkspaceLimit)
|
||||
}
|
||||
// The same six running-sum box passes as fxutil::gauss_blur_n, with preallocated scratch
|
||||
// and cooperative checks. f64 sums preserve the existing native arithmetic order.
|
||||
/// Apply the existing native box-approximation blur with bounded row/column passes and interrupt checks.
|
||||
fn blur(base: &mut [f32], w: usize, h: usize, scratch: &mut [f32], sigma: f32, ctl: &Interrupt<'_>) -> Result<(), Error> {
|
||||
for radius in gauss_box_radii(sigma) {
|
||||
let r = isize::try_from(radius).map_err(|_| Error::InvalidParameter)?;
|
||||
let norm = 1. / (2 * radius + 1) as f64;
|
||||
for row in base.chunks_exact_mut(w) {
|
||||
check(ctl)?;
|
||||
let tmp = scratch.get_mut(..w).ok_or(Error::InvalidGeometry)?;
|
||||
tmp.copy_from_slice(row);
|
||||
let at = |x: isize| -> f64 { f64::from(tmp.get(x.clamp(0, w as isize - 1) as usize).copied().unwrap_or(0.)) };
|
||||
let mut sum: f64 = (-r..=r).map(at).sum();
|
||||
for (x, v) in row.iter_mut().enumerate() {
|
||||
*v = (sum * norm) as f32;
|
||||
sum += at(x as isize + r + 1) - at(x as isize - r);
|
||||
}
|
||||
}
|
||||
}
|
||||
for radius in gauss_box_radii(sigma) {
|
||||
let r = isize::try_from(radius).map_err(|_| Error::InvalidParameter)?;
|
||||
let norm = 1. / (2 * radius + 1) as f64;
|
||||
for x in 0..w {
|
||||
check(ctl)?;
|
||||
let tmp = scratch.get_mut(..h).ok_or(Error::InvalidGeometry)?;
|
||||
for (y, v) in tmp.iter_mut().enumerate() {
|
||||
*v = *base.get(y * w + x).ok_or(Error::InvalidGeometry)?;
|
||||
}
|
||||
let at = |y: isize| -> f64 { f64::from(tmp.get(y.clamp(0, h as isize - 1) as usize).copied().unwrap_or(0.)) };
|
||||
let mut sum: f64 = (-r..=r).map(at).sum();
|
||||
for y in 0..h {
|
||||
*base.get_mut(y * w + x).ok_or(Error::InvalidGeometry)? = (sum * norm) as f32;
|
||||
sum += at(y as isize + r + 1) - at(y as isize - r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The same native luminance coefficients in a domain that cannot overflow on finite f32 channels.
|
||||
fn wide_luma(c: [f64; 3]) -> f64 {
|
||||
0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
|
||||
}
|
||||
|
||||
/// The caller owns an unpublished work buffer; cancellation may leave that buffer partly processed.
|
||||
pub fn process_with(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, ctl: &Interrupt<'_>) -> Result<(), Error> {
|
||||
check(ctl)?;
|
||||
validate(p)?;
|
||||
let count = geometry(w, h)?;
|
||||
if count != px.len() {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if count.checked_mul(24).and_then(|v| v.checked_add(w.max(h) * 4)).and_then(|v| v.checked_add(p.curve.len() * 8)).is_none_or(|v| v > MAX_WORKSPACE_BYTES) {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
let mut logl = zeroes(count, 0f32, ctl)?;
|
||||
independent_chunks(&mut logl, |start, out| {
|
||||
check(ctl)?;
|
||||
let input = px.get(start..start + out.len()).ok_or(Error::InvalidGeometry)?;
|
||||
for (q, v) in input.iter().zip(out) {
|
||||
if q.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
let luminance = luma([q[0], q[1], q[2]]);
|
||||
*v = if luminance.is_finite() {
|
||||
(luminance.max(0.) + 1e-4).ln()
|
||||
} else {
|
||||
(wide_luma([f64::from(q[0]), f64::from(q[1]), f64::from(q[2])]).max(0.) + 1e-4).ln() as f32
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let mut base = zeroes(count, 0f32, ctl)?;
|
||||
independent_chunks(&mut base, |start, dst| {
|
||||
check(ctl)?;
|
||||
let src = logl.get(start..start + dst.len()).ok_or(Error::InvalidGeometry)?;
|
||||
dst.copy_from_slice(src);
|
||||
Ok(())
|
||||
})?;
|
||||
let mut scratch = zeroes(w.max(h), 0f32, ctl)?;
|
||||
blur(&mut base, w, h, &mut scratch, p.radius / 2., ctl)?;
|
||||
// F32 loses successive log-luminance additions on ordinary megapixel images.
|
||||
let mut total = 0f64;
|
||||
let mut visible = 0usize;
|
||||
for (qs, bs) in px.chunks(2048).zip(base.chunks(2048)) {
|
||||
check(ctl)?;
|
||||
for (q, b) in qs.iter().zip(bs) {
|
||||
if q[3] > 0. {
|
||||
total += f64::from(*b);
|
||||
visible += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mean = (total / visible.max(1) as f64) as f32;
|
||||
let mut curve = zeroes(p.curve.len(), (0f32, 0f32), ctl)?;
|
||||
curve.copy_from_slice(&p.curve);
|
||||
// Stable bounded in-place insertion avoids slice::sort's infallible temporary allocation.
|
||||
for i in 1..curve.len() {
|
||||
check(ctl)?;
|
||||
let mut j = i;
|
||||
while j > 0 && curve.get(j - 1).zip(curve.get(j)).is_some_and(|(a, b)| a.0.total_cmp(&b.0).is_gt()) {
|
||||
curve.swap(j - 1, j);
|
||||
j -= 1;
|
||||
}
|
||||
}
|
||||
let compress = 1. / (1. + p.strength);
|
||||
let detail = 1. + p.detail / 100.;
|
||||
let exposure = 2f32.powf(p.exposure);
|
||||
independent_chunks(px, |start, qs| {
|
||||
check(ctl)?;
|
||||
let bs = base.get(start..start + qs.len()).ok_or(Error::InvalidGeometry)?;
|
||||
let ls = logl.get(start..start + qs.len()).ok_or(Error::InvalidGeometry)?;
|
||||
for ((q, b), l) in qs.iter_mut().zip(bs).zip(ls) {
|
||||
if q[3] <= 0. {
|
||||
continue;
|
||||
}
|
||||
let c = [q[0], q[1], q[2]];
|
||||
let l0 = luma(c).max(0.) + 1e-4;
|
||||
let new_log = mean + (*b - mean) * compress + (*l - *b) * detail;
|
||||
let mut l1 = (new_log.exp() * exposure).max(0.).powf(1. / p.gamma);
|
||||
l1 += p.shadow / 100. * (1. - l1).powi(3) * 0.5 - p.highlight / 100. * l1.powi(3) * 0.5;
|
||||
if !l1.is_finite() {
|
||||
// Preserve ordinary native arithmetic, but evaluate extreme valid HDR in a
|
||||
// wider domain. A cap beyond every f32 control's polynomial crossover keeps
|
||||
// cubing finite; those values already saturate at the final display clamp.
|
||||
let log_value = (f64::from(new_log) + f64::from(p.exposure) * std::f64::consts::LN_2) / f64::from(p.gamma);
|
||||
let value = log_value.exp().min(1e100);
|
||||
let shadow = f64::from(p.shadow) / 200.;
|
||||
let highlight = f64::from(p.highlight) / 200.;
|
||||
let mapped = ((-(shadow + highlight) * value + 3. * shadow) * value + (1. - 3. * shadow)) * value + shadow;
|
||||
l1 = mapped.clamp(0., 1.) as f32;
|
||||
if !l1.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
}
|
||||
l1 = curve_eval(&curve, l1.clamp(0., 1.));
|
||||
let mut out = c.map(|v| v * (l1 / l0));
|
||||
let ll = luma(out);
|
||||
let (mx, mn) = (out[0].max(out[1]).max(out[2]), out[0].min(out[1]).min(out[2]));
|
||||
let sat = if mx > 0. { (mx - mn) / mx } else { 0. };
|
||||
let s = 1. + p.saturation / 100. + p.vibrance / 100. * (1. - sat);
|
||||
out = out.map(|v| (ll + (v - ll) * s.max(0.)).clamp(0., 1.));
|
||||
if out.iter().any(|v| !v.is_finite()) {
|
||||
// Signed wide-gamut values can cancel to black luminance while individual
|
||||
// channels overflow the f32 rescale. Clamp only after the wide color correction.
|
||||
let source = c.map(f64::from);
|
||||
let scale = f64::from(l1) / (wide_luma(source).max(0.) + 1e-4);
|
||||
let wide = source.map(|value| value * scale);
|
||||
let luminance = wide_luma(wide);
|
||||
let (max, min) = (wide[0].max(wide[1]).max(wide[2]), wide[0].min(wide[1]).min(wide[2]));
|
||||
let saturation = if max > 0. { (max - min) / max } else { 0. };
|
||||
let strength = (1. + f64::from(p.saturation) / 100. + f64::from(p.vibrance) / 100. * (1. - saturation)).max(0.);
|
||||
out = wide.map(|value| (luminance + (value - luminance) * strength).clamp(0., 1.) as f32);
|
||||
if out.iter().any(|value| !value.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
}
|
||||
q[..3].copy_from_slice(&out);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
check(ctl)
|
||||
}
|
||||
/// Visit clipped 64-by-64 publication regions and propagate the first callback error.
|
||||
fn tiles(r: Rect, mut f: impl FnMut(Rect) -> Result<(), Error>) -> Result<(), Error> {
|
||||
let mut y = r.y0;
|
||||
while y < r.y1 {
|
||||
let y1 = y.saturating_add(64).min(r.y1);
|
||||
let mut x = r.x0;
|
||||
while x < r.x1 {
|
||||
let x1 = x.saturating_add(64).min(r.x1);
|
||||
f(Rect::new(x, y, x1, y1))?;
|
||||
x = x1;
|
||||
}
|
||||
y = y1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Whole-owner native replay; selection/area restrict publication, not the global adaptation domain.
|
||||
pub fn apply_with(surface: &Surface, p: &HdrToning, area: Rect, domain: Rect, selection: Option<&Surface>, ctl: &Interrupt<'_>) -> Result<Surface, Error> {
|
||||
check(ctl)?;
|
||||
validate(p)?;
|
||||
if area.x1 < area.x0 || area.y1 < area.y0 {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
let w = usize::try_from(i64::from(domain.x1) - i64::from(domain.x0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
let h = usize::try_from(i64::from(domain.y1) - i64::from(domain.y0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
let count = geometry(w, h)?;
|
||||
let area = area.intersect(&domain);
|
||||
let ts = i64::from(photocraft_geom::TILE_SIZE);
|
||||
let tile_count = |lo: i32, hi: i32| -> Option<usize> {
|
||||
if hi <= lo { Some(0) } else { usize::try_from((i64::from(hi) - 1).div_euclid(ts) - i64::from(lo).div_euclid(ts) + 1).ok() }
|
||||
};
|
||||
let output = tile_count(area.x0, area.x1)
|
||||
.and_then(|x| tile_count(area.y0, area.y1).and_then(|y| x.checked_mul(y)))
|
||||
.and_then(|n| n.checked_mul(ts as usize * ts as usize * surface.format().bytes_per_pixel() + 128))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
let bytes = count
|
||||
.checked_mul(24)
|
||||
.and_then(|n| n.checked_add(w.max(h) * 4))
|
||||
.and_then(|n| n.checked_add(output))
|
||||
.and_then(|n| n.checked_add(surface.tile_count().checked_mul(128)?))
|
||||
.and_then(|n| n.checked_add(64 * 64 * 4 * (surface.channels() * 3 + selection.map_or(0, Surface::channels))))
|
||||
.and_then(|n| n.checked_add(MAX_CURVE * 8))
|
||||
.ok_or(Error::WorkspaceLimit)?;
|
||||
if bytes > MAX_WORKSPACE_BYTES {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
let mut px = zeroes(count, [0f32; 4], ctl)?;
|
||||
let fmt = surface.format();
|
||||
let channels = surface.channels();
|
||||
tiles(domain, |tile| {
|
||||
check(ctl)?;
|
||||
let raw = surface.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
let tw = tile.width() as usize;
|
||||
for (i, q) in raw.chunks_exact(channels).enumerate() {
|
||||
let x = (i64::from(tile.x0) - i64::from(domain.x0)) as usize + i % tw;
|
||||
let y = (i64::from(tile.y0) - i64::from(domain.y0)) as usize + i / tw;
|
||||
*px.get_mut(y * w + x).ok_or(Error::InvalidGeometry)? = to_rgba(&fmt, q);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
process_with(&mut px, w, h, p, ctl)?;
|
||||
let mut output = surface.clone();
|
||||
tiles(area, |tile| {
|
||||
check(ctl)?;
|
||||
let original = crate::image::Image { rect: tile, ch: channels, data: surface.try_read_region(tile).map_err(|_| Error::Allocation)? };
|
||||
let mut raw = zeroes(original.data.len(), 0f32, ctl)?;
|
||||
let tw = tile.width() as usize;
|
||||
for (i, q) in raw.chunks_exact_mut(channels).enumerate() {
|
||||
let x = (i64::from(tile.x0) - i64::from(domain.x0)) as usize + i % tw;
|
||||
let y = (i64::from(tile.y0) - i64::from(domain.y0)) as usize + i / tw;
|
||||
from_rgba_into(&fmt, *px.get(y * w + x).ok_or(Error::InvalidGeometry)?, q);
|
||||
}
|
||||
if let Some(mask) = selection {
|
||||
let selected = mask.try_read_region(tile).map_err(|_| Error::Allocation)?;
|
||||
if selected.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
crate::mix_selection(&mut raw, tile, mask, &original, fmt.alpha);
|
||||
}
|
||||
if fmt.alpha {
|
||||
// Toning skips these pixels. RGB conversion must not regenerate their
|
||||
// hidden native separations, including after selection publication.
|
||||
for (q, before) in raw.chunks_exact_mut(channels).zip(original.data.chunks_exact(channels)) {
|
||||
if before.last().is_some_and(|alpha| *alpha <= 0.) {
|
||||
q.copy_from_slice(before);
|
||||
}
|
||||
}
|
||||
}
|
||||
output.try_write_region(tile, &raw).map_err(|_| Error::Allocation)
|
||||
})?;
|
||||
check(ctl)?;
|
||||
ctl.progress(1.);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Compatibility kernel. Checked Surface callers propagate errors instead of using this fallback.
|
||||
pub(crate) fn run_image(src: &crate::Image, out: Rect, ctx: &crate::Ctx, p: &HdrToning) -> Vec<f32> {
|
||||
let run = || -> Result<Vec<f32>, Error> {
|
||||
let w = usize::try_from(i64::from(src.rect.x1) - i64::from(src.rect.x0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
let h = usize::try_from(i64::from(src.rect.y1) - i64::from(src.rect.y0)).map_err(|_| Error::InvalidGeometry)?;
|
||||
let n = geometry(w, h)?;
|
||||
let fmt = photocraft_color::PixelFormat::new(ctx.mode, photocraft_color::SampleType::F32, ctx.alpha);
|
||||
if src.ch != fmt.channels() || n.checked_mul(src.ch) != Some(src.data.len()) || out.intersect(&src.rect) != out {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if n.checked_mul(24 + fmt.bytes_per_pixel() * 2).is_none_or(|v| v > MAX_WORKSPACE_BYTES) {
|
||||
return Err(Error::WorkspaceLimit);
|
||||
}
|
||||
let mut surface = Surface::new(fmt);
|
||||
surface.try_write_region(src.rect, &src.data).map_err(|_| Error::Allocation)?;
|
||||
let result = apply_with(&surface, p, out, src.rect, None, &Interrupt::NONE).unwrap_or(surface);
|
||||
result.try_read_region(out).map_err(|_| Error::Allocation)
|
||||
};
|
||||
run().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Uniform ten-megapixel scenes retain their exposure regardless of the reduction length.
|
||||
#[test]
|
||||
fn megapixel_scene_exposure_matches_single_pixel_reference() {
|
||||
let p = HdrToning { radius: 1., detail: 0., saturation: 0., ..Default::default() };
|
||||
let sample = [0.18, 0.18, 0.18, 1.];
|
||||
let mut reference = [sample];
|
||||
process_with(&mut reference, 1, 1, &p, &Interrupt::NONE).unwrap();
|
||||
let mut pixels = vec![sample; 4000 * 2500];
|
||||
process_with(&mut pixels, 4000, 2500, &p, &Interrupt::NONE).unwrap();
|
||||
for pixel in pixels {
|
||||
for (value, expected) in pixel.into_iter().zip(reference[0]) {
|
||||
assert!((value - expected).abs() < 2e-6, "{value} versus {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Preserve skipped transparent CMYK and Lab samples bit for bit, with and without selection mixing.
|
||||
fn skipped_transparent_native_samples_survive_toning_and_selection_bit_for_bit() {
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
let area = Rect::new(-1, 0, 1, 1);
|
||||
for mode in [ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in SampleType::ALL {
|
||||
let fmt = PixelFormat::new(mode, depth, true);
|
||||
let mut source = Surface::new(fmt);
|
||||
let mut pixel = vec![0.75; fmt.channels()];
|
||||
*pixel.last_mut().unwrap() = 0.;
|
||||
source.write_pixel(-1, 0, &pixel);
|
||||
*pixel.last_mut().unwrap() = if depth == SampleType::F32 { -0.5 } else { 0. };
|
||||
source.write_pixel(0, 0, &pixel);
|
||||
let mut mask = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
mask.fill_rect(area, &[0.5]);
|
||||
for selection in [None, Some(&mask)] {
|
||||
let result = apply_with(&source, &HdrToning::default(), area, area, selection, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(
|
||||
result.read_region(area).iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
|
||||
source.read_region(area).iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
|
||||
"{fmt:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Compare checked HDR output to the existing native tone arithmetic, including unchanged alpha samples.
|
||||
fn matches_existing_native_arithmetic_and_alpha() {
|
||||
let mut input: Vec<_> = (0..72)
|
||||
.map(|i| {
|
||||
let t = i as f32 / 71.;
|
||||
[t * 3. - 0.1, t * 1.4, t * 0.6, if i % 4 == 0 { 0. } else { 0.4 }]
|
||||
})
|
||||
.collect();
|
||||
let mut expected = input.clone();
|
||||
let p = HdrToning { radius: 7., curve: vec![(0., 0.02), (0.6, 0.8), (1., 1.)], ..Default::default() };
|
||||
super::super::hdr_toning(&mut expected, 9, 8, &p);
|
||||
process_with(&mut input, 9, 8, &p, &Interrupt::NONE).unwrap();
|
||||
for (a, b) in input.iter().zip(&expected) {
|
||||
for (x, y) in a.iter().zip(b) {
|
||||
assert!((x - y).abs() < 1e-6, "{a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Pin errors for mismatched geometry, cancellation, nonfinite pixels and controls before accepting native
|
||||
/// processing.
|
||||
fn hostile_and_cancelled_work_is_rejected() {
|
||||
let mut px = vec![[0.5; 4]; 4];
|
||||
assert_eq!(process_with(&mut px, 3, 2, &HdrToning::default(), &Interrupt::NONE), Err(Error::InvalidGeometry));
|
||||
let cancel = || true;
|
||||
assert_eq!(process_with(&mut px, 2, 2, &HdrToning::default(), &Interrupt::cancel_only(&cancel)), Err(Error::Cancelled));
|
||||
px[0][0] = f32::NAN;
|
||||
assert_eq!(process_with(&mut px, 2, 2, &HdrToning::default(), &Interrupt::NONE), Err(Error::NonFiniteSample));
|
||||
assert_eq!(validate(&HdrToning { radius: f32::INFINITY, ..Default::default() }), Err(Error::InvalidParameter));
|
||||
assert!(geometry(65_536, 65_536).is_err());
|
||||
}
|
||||
#[test]
|
||||
/// Compare a parallel-sized workload exactly with the existing native counterpart to guard arithmetic and
|
||||
/// reduction-order drift.
|
||||
fn native_parallel_chunks_keep_exact_counterpart_and_reduction_order() {
|
||||
let mut actual: Vec<_> = (0..256 * 256)
|
||||
.map(|i| {
|
||||
let t = (i % 511) as f32 / 127.;
|
||||
[t, t * 0.6, t * 0.3, if i % 7 == 0 { 0. } else { 0.75 }]
|
||||
})
|
||||
.collect();
|
||||
let mut expected = actual.clone();
|
||||
let params = HdrToning { radius: 11., saturation: -17., exposure: 0.3, ..Default::default() };
|
||||
super::super::hdr_toning(&mut expected, 256, 256, ¶ms);
|
||||
process_with(&mut actual, 256, 256, ¶ms, &Interrupt::NONE).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
#[test]
|
||||
/// Verify offset native surfaces at every supported depth against separately processed pixels, including selection
|
||||
/// publication.
|
||||
fn native_depth_models_offsets_and_selection_match_native_counterpart() {
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
let bounds = Rect::new(-3, 5, 2, 8);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let format = PixelFormat::new(mode, depth, true);
|
||||
let mut source = Surface::new(format);
|
||||
let mut samples = Vec::new();
|
||||
for i in 0..15 {
|
||||
let c = [i as f32 / 9., 0.3, 0.6, if i % 3 == 0 { 0. } else { 0.7 }];
|
||||
samples.extend(photocraft_raster::from_rgba(&format, c));
|
||||
}
|
||||
source.write_region(bounds, &samples);
|
||||
let before = source.read_region(bounds);
|
||||
let mut expected: Vec<_> = before.chunks_exact(format.channels()).map(|q| to_rgba(&format, q)).collect();
|
||||
let p = HdrToning { radius: 3., detail: 12., saturation: 0., ..Default::default() };
|
||||
super::super::hdr_toning(&mut expected, 5, 3, &p);
|
||||
let expected: Vec<_> = expected
|
||||
.iter()
|
||||
.zip(before.chunks_exact(format.channels()))
|
||||
.flat_map(|(q, original)| if q[3] <= 0. { original.to_vec() } else { photocraft_raster::from_rgba(&format, *q) })
|
||||
.collect();
|
||||
let mut oracle = Surface::new(format);
|
||||
oracle.write_region(bounds, &expected);
|
||||
let got = apply_with(&source, &p, bounds, bounds, None, &Interrupt::NONE).unwrap();
|
||||
for (a, b) in got.read_region(bounds).iter().zip(oracle.read_region(bounds)) {
|
||||
assert!((a - b).abs() < 2e-6, "{mode:?} {depth:?}: {a} {b}");
|
||||
}
|
||||
let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
selection.write_region(bounds, &[0.; 15]);
|
||||
let masked = apply_with(&source, &p, bounds, bounds, Some(&selection), &Interrupt::NONE).unwrap();
|
||||
assert_eq!(masked.read_region(bounds), before);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
/// Require cancelled or oversized surface work to preserve the source and the raw adapter's valid identity
|
||||
/// fallback.
|
||||
fn cancelled_surface_never_publishes_and_workspace_is_bounded() {
|
||||
use photocraft_color::{PixelFormat, SampleType};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let bounds = Rect::new(0, 0, 64, 64);
|
||||
let mut source = Surface::new(PixelFormat::new(photocraft_color::ColorMode::Rgb, SampleType::F32, true));
|
||||
source.write_region(bounds, &vec![0.5; 64 * 64 * 4]);
|
||||
let before = source.read_region(bounds);
|
||||
let calls = AtomicUsize::new(0);
|
||||
let cancelled = || calls.fetch_add(1, Ordering::Relaxed) > 80;
|
||||
assert!(matches!(apply_with(&source, &HdrToning::default(), bounds, bounds, None, &Interrupt::cancel_only(&cancelled)), Err(Error::Cancelled)));
|
||||
assert_eq!(source.read_region(bounds), before);
|
||||
assert!(matches!(
|
||||
apply_with(&source, &HdrToning::default(), Rect::new(0, 0, 65_536, 65_536), Rect::new(0, 0, 65_536, 65_536), None, &Interrupt::NONE),
|
||||
Err(Error::WorkspaceLimit)
|
||||
));
|
||||
let ctx = crate::Ctx { bounds, mode: photocraft_color::ColorMode::Rgb, alpha: true };
|
||||
let raw = crate::Image { rect: bounds, ch: 4, data: before.clone() };
|
||||
let p = HdrToning { radius: 0., ..Default::default() };
|
||||
assert_eq!(run_image(&raw, bounds, &ctx, &p), before);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! A project file stores Liquify strokes as plain numbers, so a stroke may name any `f64` for its
|
||||
//! brush size or its points. Replaying one must never overflow, however absurd the values.
|
||||
|
||||
use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, LiquifyTool};
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
const BRUSH_TOOLS: [LiquifyTool; 10] = [
|
||||
LiquifyTool::ForwardWarp,
|
||||
LiquifyTool::Reconstruct,
|
||||
LiquifyTool::Smooth,
|
||||
LiquifyTool::TwirlCw,
|
||||
LiquifyTool::TwirlCcw,
|
||||
LiquifyTool::Pucker,
|
||||
LiquifyTool::Bloat,
|
||||
LiquifyTool::PushLeft,
|
||||
LiquifyTool::Freeze,
|
||||
LiquifyTool::Thaw,
|
||||
];
|
||||
|
||||
const EXTREME: [f64; 9] = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN, 1e300, 3.0e9, -1.0, 0.0];
|
||||
|
||||
/// A stroke of `tool` with brush `size` through `points`, at middling density, pressure and rate.
|
||||
fn stroke(tool: LiquifyTool, size: f64, points: Vec<Vec<f64>>) -> LiquifyStroke {
|
||||
LiquifyStroke { tool, size, density: 50.0, pressure: 50.0, rate: 50.0, points, amount: None }
|
||||
}
|
||||
|
||||
/// Every brush tool, with every absurd size and position, replays without a panic.
|
||||
#[test]
|
||||
fn a_brush_with_an_absurd_size_or_position_replays_without_overflow() {
|
||||
let bounds = Rect::new(0, 0, 64, 64);
|
||||
for tool in BRUSH_TOOLS {
|
||||
for size in EXTREME {
|
||||
for p in [0.0, 1e300, f64::NAN, 3.0e9, -3.0e9] {
|
||||
let points = vec![vec![p, 10.0], vec![20.0, p], vec![p, p, f64::MAX]];
|
||||
let _ = LiquifyField::from_strokes(bounds, 8.0, &[stroke(tool, size, points)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Review on #11013: a dab whose centre and size are both huge gives infinity over infinity for its
|
||||
/// distance; it must not write NaN displacements.
|
||||
#[test]
|
||||
fn a_huge_far_off_dab_leaves_the_field_finite() {
|
||||
let bounds = Rect::new(0, 0, 64, 64);
|
||||
for tool in BRUSH_TOOLS {
|
||||
let f = LiquifyField::from_strokes(bounds, 8.0, &[stroke(tool, 4e200, vec![vec![1e200, 10.0]])]);
|
||||
assert!(f.max_displacement().is_finite(), "{tool:?}");
|
||||
assert!(f.sample(10.0, 10.0).iter().all(|v| v.is_finite()), "{tool:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Review on #11013: a Freeze dab centred far to the left with a radius reaching the image changes
|
||||
/// nodes inside it, so the area it reports must not be empty.
|
||||
#[test]
|
||||
fn a_far_off_dab_that_reaches_the_image_reports_what_it_changed() {
|
||||
let mut f = LiquifyField::new(Rect::new(0, 0, 64, 64), 8.0);
|
||||
let changed = f.stroke_begin(&stroke(LiquifyTool::Freeze, 1.2e10, vec![]), [-3e9, 10.0, 1.0]);
|
||||
assert!(f.freeze_at(10.0, 10.0) > 0.0, "the dab reaches the image, so it freezes nodes there");
|
||||
assert!(!changed.is_empty(), "the freeze changed nodes but reported {changed:?}");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod gallery_reach_extreme;
|
||||
mod liquify_extreme_stroke;
|
||||
mod liquify_freeze_formats;
|
||||
mod liquify_source_footprint;
|
||||
mod retouch_blur_exact;
|
||||
|
||||
@@ -34,6 +34,9 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "syn
|
||||
base64 = "0.23"
|
||||
schemars = "1"
|
||||
getrandom = { workspace = true }
|
||||
# HMAC-SHA256 for the control channel's challenge authentication: the token never crosses the wire (NV-6).
|
||||
hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
cap-std = "4"
|
||||
clap = { workspace = true }
|
||||
|
||||
|
||||
@@ -4,7 +4,13 @@
|
||||
//! dropped before its reply — or before a call, once the connection has been
|
||||
//! idle long enough that the app (which closes idle control connections after
|
||||
//! [`IO_TIMEOUT`](crate::security::IO_TIMEOUT)) may already have closed it.
|
||||
//!
|
||||
//! Each connection authenticates with the challenge handshake (NV-6): the client connects to
|
||||
//! the literal loopback address it was given (never a name lookup that may pick another
|
||||
//! listener) and the server must prove it holds the control token before the client sends its
|
||||
//! own proof. The token itself is never sent, so a process that took the port gets nothing.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -15,7 +21,9 @@ use tokio::sync::Mutex;
|
||||
|
||||
use crate::AutomationError;
|
||||
use crate::budgets::MAX_RESPONSE_BYTES;
|
||||
use crate::security::{AUTH_METHOD, IO_TIMEOUT, MAX_REQUEST_BYTES, validate_token};
|
||||
use crate::security::{
|
||||
AUTH_METHOD, CHALLENGE_METHOD, IO_TIMEOUT, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, is_hex256, proof_matches, validate_token,
|
||||
};
|
||||
|
||||
type Conn = (BufReader<tokio::net::tcp::OwnedReadHalf>, tokio::net::tcp::OwnedWriteHalf);
|
||||
|
||||
@@ -35,6 +43,8 @@ const NO_REPLY_CAUSES: &str =
|
||||
|
||||
pub struct BridgeClient {
|
||||
addr: String,
|
||||
/// Where to connect: `addr` parsed, with `localhost` taken as 127.0.0.1.
|
||||
socket: SocketAddr,
|
||||
token: String,
|
||||
conn: Mutex<Option<(Conn, Instant)>>,
|
||||
next_id: AtomicU64,
|
||||
@@ -48,13 +58,11 @@ impl BridgeClient {
|
||||
pub fn new(addr: impl Into<String>, token: impl Into<String>) -> Result<Self, AutomationError> {
|
||||
let addr = addr.into();
|
||||
let token = token.into();
|
||||
let host = addr.rsplit_once(':').map(|(h, _)| h).unwrap_or(&addr);
|
||||
if !matches!(host, "127.0.0.1" | "localhost" | "[::1]" | "::1") {
|
||||
return Err(AutomationError::BadRequest(format!("bridge address must be loopback, got `{addr}`")));
|
||||
}
|
||||
let socket = loopback_socket(&addr)?;
|
||||
validate_token(&token)?;
|
||||
Ok(BridgeClient {
|
||||
addr,
|
||||
socket,
|
||||
token: token.to_ascii_lowercase(),
|
||||
conn: Mutex::new(None),
|
||||
next_id: AtomicU64::new(1),
|
||||
@@ -126,7 +134,7 @@ impl BridgeClient {
|
||||
*guard = None;
|
||||
}
|
||||
if guard.is_none() {
|
||||
let s = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(&self.addr))
|
||||
let s = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(self.socket))
|
||||
.await
|
||||
.map_err(|_| Failure::NotSent(format!("timed out connecting to {}", self.addr)))?
|
||||
.map_err(|e| {
|
||||
@@ -137,8 +145,7 @@ impl BridgeClient {
|
||||
})?;
|
||||
let (r, w) = s.into_split();
|
||||
let mut conn = (BufReader::new(r), w);
|
||||
let auth_id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||
let auth = tokio::time::timeout(Duration::from_secs(5), exchange(&mut conn, auth_id, AUTH_METHOD, &json!({"token": self.token})))
|
||||
let auth = tokio::time::timeout(Duration::from_secs(5), self.authenticate(&mut conn))
|
||||
.await
|
||||
.map_err(|_| Failure::NotSent("control authentication timed out".into()))?
|
||||
.map_err(|e| Failure::NotSent(e.to_string()))?;
|
||||
@@ -177,6 +184,51 @@ impl BridgeClient {
|
||||
}
|
||||
}
|
||||
|
||||
impl BridgeClient {
|
||||
/// Challenge authentication on a fresh connection. The server must prove it holds the token
|
||||
/// before the client sends its own proof; the token itself is never sent (NV-6).
|
||||
/// Outer `Err` = transport failure; inner = refused.
|
||||
async fn authenticate(&self, conn: &mut Conn) -> Result<Result<(), AutomationError>, AutomationError> {
|
||||
let client_nonce = generate_nonce()?;
|
||||
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||
let challenge = match exchange(conn, id, CHALLENGE_METHOD, &json!({"clientNonce": client_nonce})).await? {
|
||||
Ok(challenge) => challenge,
|
||||
Err(AutomationError::App(e)) => {
|
||||
return Ok(Err(AutomationError::Bridge(format!(
|
||||
"{} refused challenge authentication ({e}): it is not PhotoCraft, or a PhotoCraft too old to support it (update the app); the control token was not sent",
|
||||
self.addr
|
||||
))));
|
||||
}
|
||||
Err(e) => return Ok(Err(e)),
|
||||
};
|
||||
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| is_hex256(v));
|
||||
let server_nonce = match (field("serverNonce"), field("serverProof")) {
|
||||
(Some(nonce), Some(proof)) if proof_matches(&self.token, ProofRole::Server, &client_nonce, nonce, proof) => nonce,
|
||||
_ => {
|
||||
return Ok(Err(AutomationError::Bridge(format!(
|
||||
"{} did not prove it holds this control token: the token does not match the app's, or the listener is not that PhotoCraft app; the control token was not sent",
|
||||
self.addr
|
||||
))));
|
||||
}
|
||||
};
|
||||
let proof = handshake_proof(&self.token, ProofRole::Client, &client_nonce, server_nonce)?;
|
||||
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(exchange(conn, id, AUTH_METHOD, &json!({"proof": proof})).await?.map(|_| ()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The literal loopback socket address for `addr`: `127.0.0.1:<port>` or `[::1]:<port>`, with
|
||||
/// `localhost:<port>` meaning 127.0.0.1, the address the app binds. The name is never looked up,
|
||||
/// since a lookup may return `[::1]` first and reach another process listening there (NV-6).
|
||||
fn loopback_socket(addr: &str) -> Result<SocketAddr, AutomationError> {
|
||||
let refuse = || AutomationError::BadRequest(format!("bridge address must be loopback `127.0.0.1:<port>` or `[::1]:<port>`, got `{addr}`"));
|
||||
let socket = match addr.strip_prefix("localhost:") {
|
||||
Some(port) => SocketAddr::from((Ipv4Addr::LOCALHOST, port.parse::<u16>().map_err(|_| refuse())?)),
|
||||
None => addr.parse::<SocketAddr>().map_err(|_| refuse())?,
|
||||
};
|
||||
if socket.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST) || socket.ip() == IpAddr::V6(Ipv6Addr::LOCALHOST) { Ok(socket) } else { Err(refuse()) }
|
||||
}
|
||||
|
||||
/// How a single attempt failed, deciding the retry and the wording above.
|
||||
enum Failure {
|
||||
/// The connection could not be established or authenticated: nothing was sent.
|
||||
@@ -256,6 +308,17 @@ mod tests {
|
||||
assert!(DEFAULT_CALL_TIMEOUT < Duration::from_secs(60));
|
||||
}
|
||||
|
||||
/// NV-6: `localhost` is the IPv4 loopback the app binds, never a name lookup.
|
||||
#[test]
|
||||
fn bridge_addresses_are_literal_loopback_sockets() {
|
||||
assert_eq!(loopback_socket("localhost:7878").unwrap(), SocketAddr::from((Ipv4Addr::LOCALHOST, 7878)));
|
||||
assert_eq!(loopback_socket("127.0.0.1:7878").unwrap(), SocketAddr::from((Ipv4Addr::LOCALHOST, 7878)));
|
||||
assert_eq!(loopback_socket("[::1]:7878").unwrap(), SocketAddr::from((Ipv6Addr::LOCALHOST, 7878)));
|
||||
for bad in ["10.0.0.5:7878", "127.0.0.2:7878", "localhost", "localhost:", "localhost:99999", "::1:7878", "example.com:7878", "127.0.0.1"] {
|
||||
assert!(loopback_socket(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_reconnect_stays_below_the_app_idle_cutoff() {
|
||||
// Reconnecting later than IO_TIMEOUT would send into a socket the app dropped.
|
||||
|
||||
@@ -33,7 +33,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::budgets::{BatchReplyBudget, write_reply};
|
||||
use crate::security::{
|
||||
AUTH_DEADLINE, AuthDeadlineStream, ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply,
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake,
|
||||
configure_stream, discard_rest_of_line, read_bounded_line, repeat_auth_reply,
|
||||
};
|
||||
use crate::{AutomationError, Headless};
|
||||
@@ -168,9 +168,11 @@ impl Headless {
|
||||
"doc.new" => self.command_run("file.new", p),
|
||||
"doc.save" => {
|
||||
let tga_bits = photocraft_engine::file_cmds::tga_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?;
|
||||
let pdf_spot_plates = photocraft_engine::file_cmds::pdf_spot_plates_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?;
|
||||
let mut opts = photocraft_io::ExportOptions {
|
||||
tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false),
|
||||
tga_bits,
|
||||
pdf_spot_plates,
|
||||
pcraft_full_composite: photocraft_engine::file_cmds::pcraft_full_composite_param(&p, "doc.save")
|
||||
.map_err(|e| bad(e.to_string()))?
|
||||
.unwrap_or(false),
|
||||
@@ -375,6 +377,7 @@ fn serve_tcp_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token:
|
||||
let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
|
||||
let mut out = stream;
|
||||
let mut line = String::new();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut authenticated = false;
|
||||
loop {
|
||||
match read_bounded_line(&mut reader, &mut line)? {
|
||||
@@ -392,19 +395,19 @@ fn serve_tcp_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token:
|
||||
LineRead::Line if line.trim().is_empty() => continue,
|
||||
LineRead::Line => {}
|
||||
}
|
||||
let reply = if authenticated {
|
||||
repeat_auth_reply(&line).unwrap_or_else(|| respond(h, &line))
|
||||
let (reply, step) = if authenticated {
|
||||
(repeat_auth_reply(&line).unwrap_or_else(|| respond(h, &line)), AuthStep::Authenticated)
|
||||
} else {
|
||||
let (reply, ok) = authentication_reply(&line, token);
|
||||
authenticated = ok;
|
||||
if ok {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
if step == AuthStep::Authenticated {
|
||||
authenticated = true;
|
||||
reader.get_mut().authenticated()?;
|
||||
}
|
||||
reply
|
||||
(reply, step)
|
||||
};
|
||||
write_reply(&mut out, &reply)?;
|
||||
out.flush()?;
|
||||
if !authenticated {
|
||||
if step == AuthStep::Rejected {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,17 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use hmac::{Hmac, Mac};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::AutomationError;
|
||||
|
||||
/// The first request on every TCP connection must use this method.
|
||||
/// The request that authenticates a TCP connection: with the token itself (the original form),
|
||||
/// or with the client's proof after [`CHALLENGE_METHOD`].
|
||||
pub const AUTH_METHOD: &str = "auth";
|
||||
/// The first frame of challenge authentication: it carries a client nonce, never the token (NV-6).
|
||||
pub const CHALLENGE_METHOD: &str = "auth.challenge";
|
||||
/// Maximum encoded JSON request line, including its newline.
|
||||
pub const MAX_REQUEST_BYTES: usize = 1 << 20;
|
||||
/// Maximum simultaneously serviced TCP connections per listener.
|
||||
@@ -75,22 +80,42 @@ pub fn discard_rest_of_line(reader: &mut impl BufRead) -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lowercase hexadecimal, two characters per byte.
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for &byte in bytes {
|
||||
out.push(HEX[(byte >> 4) as usize] as char);
|
||||
out.push(HEX[(byte & 0x0f) as usize] as char);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 256 bits from the operating system CSPRNG, as 64 lowercase hexadecimal characters.
|
||||
fn random_hex(what: &str) -> Result<String, AutomationError> {
|
||||
let mut bytes = [0u8; TOKEN_BYTES];
|
||||
getrandom::fill(&mut bytes).map_err(|e| AutomationError::Other(format!("cannot generate {what}: {e}")))?;
|
||||
Ok(hex(&bytes))
|
||||
}
|
||||
|
||||
/// Generate a 256-bit bearer token with the operating system CSPRNG.
|
||||
pub fn generate_token() -> Result<String, AutomationError> {
|
||||
let mut bytes = [0u8; TOKEN_BYTES];
|
||||
getrandom::fill(&mut bytes).map_err(|e| AutomationError::Other(format!("cannot generate control token: {e}")))?;
|
||||
let mut token = String::with_capacity(TOKEN_HEX_LEN);
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
for byte in bytes {
|
||||
token.push(HEX[(byte >> 4) as usize] as char);
|
||||
token.push(HEX[(byte & 0x0f) as usize] as char);
|
||||
}
|
||||
Ok(token)
|
||||
random_hex("control token")
|
||||
}
|
||||
|
||||
/// Generate a fresh 256-bit nonce for challenge authentication ([`CHALLENGE_METHOD`]).
|
||||
pub fn generate_nonce() -> Result<String, AutomationError> {
|
||||
random_hex("authentication nonce")
|
||||
}
|
||||
|
||||
/// Whether `s` has the shape of a token or nonce: exactly 64 hexadecimal characters.
|
||||
pub fn is_hex256(s: &str) -> bool {
|
||||
s.len() == TOKEN_HEX_LEN && s.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// Accept only the fixed-width hexadecimal representation emitted by [`generate_token`].
|
||||
pub fn validate_token(token: &str) -> Result<(), AutomationError> {
|
||||
if token.len() != TOKEN_HEX_LEN || !token.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
if !is_hex256(token) {
|
||||
return Err(AutomationError::BadRequest("control token must contain exactly 64 hexadecimal characters".into()));
|
||||
}
|
||||
Ok(())
|
||||
@@ -108,30 +133,107 @@ pub fn token_matches(expected: &str, supplied: &str) -> bool {
|
||||
expected.bytes().zip(supplied.bytes()).fold(0u8, |different, (a, b)| different | (a.to_ascii_lowercase() ^ b.to_ascii_lowercase())) == 0
|
||||
}
|
||||
|
||||
/// Validate the first TCP frame without exposing any control method before authentication.
|
||||
pub fn authentication_reply(line: &str, expected_token: &str) -> (Value, bool) {
|
||||
let req: Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
return (json!({"id": null, "ok": false, "error": "authentication required"}), false);
|
||||
}
|
||||
/// Which side of the challenge handshake a proof comes from. Each side's proof is keyed by the
|
||||
/// token over both nonces under its own label, so one side's proof never passes for the other's.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProofRole {
|
||||
Server,
|
||||
Client,
|
||||
}
|
||||
|
||||
/// HMAC-SHA256, keyed by the (lowercased) control token, over the role's label and both nonces,
|
||||
/// as 64 lowercase hexadecimal characters. `docs/control-protocol.md` gives the exact message.
|
||||
pub fn handshake_proof(token: &str, role: ProofRole, client_nonce: &str, server_nonce: &str) -> Result<String, AutomationError> {
|
||||
let label: &[u8] = match role {
|
||||
ProofRole::Server => b"photocraft-control-v1 server",
|
||||
ProofRole::Client => b"photocraft-control-v1 client",
|
||||
};
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
let supplied = req.get("params").and_then(|p| p.get("token")).and_then(Value::as_str).unwrap_or("");
|
||||
let ok = req.get("method").and_then(Value::as_str) == Some(AUTH_METHOD) && token_matches(expected_token, supplied);
|
||||
if ok {
|
||||
(json!({"id": id, "ok": true, "result": {"authenticated": true}}), true)
|
||||
} else {
|
||||
(json!({"id": id, "ok": false, "error": "authentication required"}), false)
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(token.to_ascii_lowercase().as_bytes())
|
||||
.map_err(|e| AutomationError::Other(format!("cannot key the authentication proof: {e}")))?;
|
||||
for part in [label, b"\n", client_nonce.to_ascii_lowercase().as_bytes(), b"\n", server_nonce.to_ascii_lowercase().as_bytes()] {
|
||||
mac.update(part);
|
||||
}
|
||||
Ok(hex(&mac.finalize().into_bytes()))
|
||||
}
|
||||
|
||||
/// Whether `supplied` is `role`'s proof for these nonces, compared without an early exit.
|
||||
pub fn proof_matches(token: &str, role: ProofRole, client_nonce: &str, server_nonce: &str, supplied: &str) -> bool {
|
||||
handshake_proof(token, role, client_nonce, server_nonce).is_ok_and(|expected| token_matches(&expected, supplied))
|
||||
}
|
||||
|
||||
/// Where a connection's authentication stands after one frame.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AuthStep {
|
||||
/// Authenticated: dispatch the frames that follow.
|
||||
Authenticated,
|
||||
/// A challenge was answered: the next frame must be `auth` with the client's proof.
|
||||
Challenged,
|
||||
/// Refused: send the reply, then close the connection.
|
||||
Rejected,
|
||||
}
|
||||
|
||||
/// Server side of connection authentication, one per connection. It accepts either
|
||||
///
|
||||
/// - challenge authentication (NV-6): `auth.challenge {clientNonce}` is answered with
|
||||
/// `{serverNonce, serverProof}`, then `auth {proof}` authenticates. The token never crosses the
|
||||
/// wire, and the client learns that the server holds the token before revealing anything
|
||||
/// derived from it; or
|
||||
/// - the original one-frame `auth {token}`, kept so existing clients and scripts keep working.
|
||||
///
|
||||
/// No control method is answered before authentication.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ServerHandshake {
|
||||
/// The client and server nonces of the challenge this connection was given, until its `auth`.
|
||||
challenge: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl ServerHandshake {
|
||||
/// A handshake for a freshly accepted connection: no challenge issued yet.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Answer one frame received before authentication. Never dispatches a control method.
|
||||
pub fn reply(&mut self, line: &str, token: &str) -> (Value, AuthStep) {
|
||||
let refused = |id: Value| (json!({"id": id, "ok": false, "error": "authentication required"}), AuthStep::Rejected);
|
||||
let authenticated = |id: Value| (json!({"id": id, "ok": true, "result": {"authenticated": true}}), AuthStep::Authenticated);
|
||||
let Ok(req) = serde_json::from_str::<Value>(line) else {
|
||||
return refused(Value::Null);
|
||||
};
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
let param = |key: &str| req.get("params").and_then(|p| p.get(key)).and_then(Value::as_str);
|
||||
match (req.get("method").and_then(Value::as_str), self.challenge.take()) {
|
||||
(Some(CHALLENGE_METHOD), None) => {
|
||||
let Some(client_nonce) = param("clientNonce").filter(|n| is_hex256(n)).map(str::to_ascii_lowercase) else {
|
||||
return refused(id);
|
||||
};
|
||||
let Ok(server_nonce) = generate_nonce() else {
|
||||
return (json!({"id": id, "ok": false, "error": "cannot generate an authentication challenge"}), AuthStep::Rejected);
|
||||
};
|
||||
let Ok(server_proof) = handshake_proof(token, ProofRole::Server, &client_nonce, &server_nonce) else {
|
||||
return refused(id);
|
||||
};
|
||||
let reply = json!({"id": id, "ok": true, "result": {"serverNonce": server_nonce, "serverProof": server_proof}});
|
||||
self.challenge = Some((client_nonce, server_nonce));
|
||||
(reply, AuthStep::Challenged)
|
||||
}
|
||||
// After a challenge only the proof authenticates; the token is never needed.
|
||||
(Some(AUTH_METHOD), Some((client_nonce, server_nonce))) => match param("proof") {
|
||||
Some(proof) if proof_matches(token, ProofRole::Client, &client_nonce, &server_nonce, proof) => authenticated(id),
|
||||
_ => refused(id),
|
||||
},
|
||||
(Some(AUTH_METHOD), None) if token_matches(token, param("token").unwrap_or("")) => authenticated(id),
|
||||
_ => refused(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer a repeat `auth` frame on an already authenticated connection. Returns `None` for any
|
||||
/// other frame, which the caller dispatches as usual.
|
||||
/// Answer a repeat `auth` or `auth.challenge` frame on an already authenticated connection.
|
||||
/// Returns `None` for any other frame, which the caller dispatches as usual.
|
||||
/// Without this, a second `auth` fell through to the method dispatcher as an unknown method.
|
||||
pub fn repeat_auth_reply(line: &str) -> Option<Value> {
|
||||
let req: Value = serde_json::from_str(line).ok()?;
|
||||
if req.get("method").and_then(Value::as_str) != Some(AUTH_METHOD) {
|
||||
if !matches!(req.get("method").and_then(Value::as_str), Some(AUTH_METHOD | CHALLENGE_METHOD)) {
|
||||
return None;
|
||||
}
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
@@ -312,6 +414,78 @@ impl Read for AuthDeadlineStream {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// One frame through a fresh handshake: the reply and whether it authenticated.
|
||||
fn authentication_reply(line: &str, token: &str) -> (Value, bool) {
|
||||
let (reply, step) = ServerHandshake::new().reply(line, token);
|
||||
(reply, step == AuthStep::Authenticated)
|
||||
}
|
||||
|
||||
/// An `auth.challenge` frame carrying `client_nonce`.
|
||||
fn challenge_line(client_nonce: &str) -> String {
|
||||
json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}}).to_string()
|
||||
}
|
||||
|
||||
/// An `auth` frame carrying the client's challenge `proof`.
|
||||
fn proof_line(proof: &str) -> String {
|
||||
json!({"id": 2, "method": AUTH_METHOD, "params": {"proof": proof}}).to_string()
|
||||
}
|
||||
|
||||
/// NV-6: a client proves it holds the token, and learns that the server does, without the
|
||||
/// token crossing the wire.
|
||||
#[test]
|
||||
fn challenge_authentication_proves_the_token_both_ways_without_sending_it() {
|
||||
let token = generate_token().unwrap();
|
||||
let client_nonce = generate_nonce().unwrap();
|
||||
let mut server = ServerHandshake::new();
|
||||
let (reply, step) = server.reply(&challenge_line(&client_nonce), &token);
|
||||
assert_eq!(step, AuthStep::Challenged, "{reply}");
|
||||
assert!(!reply.to_string().contains(&token), "the challenge reply must not carry the token");
|
||||
let server_nonce = reply["result"]["serverNonce"].as_str().unwrap();
|
||||
let server_proof = reply["result"]["serverProof"].as_str().unwrap();
|
||||
assert!(is_hex256(server_nonce) && server_nonce != client_nonce);
|
||||
assert!(proof_matches(&token, ProofRole::Server, &client_nonce, server_nonce, server_proof));
|
||||
// A server holding another token cannot produce that proof.
|
||||
let other = generate_token().unwrap();
|
||||
assert!(!proof_matches(&other, ProofRole::Server, &client_nonce, server_nonce, server_proof));
|
||||
// The server's proof is not the client's: replaying it back does not authenticate.
|
||||
assert!(!proof_matches(&token, ProofRole::Client, &client_nonce, server_nonce, server_proof));
|
||||
|
||||
let proof = handshake_proof(&token, ProofRole::Client, &client_nonce, server_nonce).unwrap();
|
||||
assert_ne!(proof, token);
|
||||
let (reply, step) = server.reply(&proof_line(&proof), &token);
|
||||
assert_eq!(step, AuthStep::Authenticated, "{reply}");
|
||||
assert_eq!(reply["result"]["authenticated"], true);
|
||||
}
|
||||
|
||||
/// NV-6: after a challenge, a wrong, missing or token-shaped proof, the token itself, a second
|
||||
/// challenge and a control method are all refused, and a malformed nonce gets no challenge.
|
||||
#[test]
|
||||
fn challenge_authentication_refuses_a_wrong_or_missing_proof() {
|
||||
let token = generate_token().unwrap();
|
||||
let client_nonce = generate_nonce().unwrap();
|
||||
let wrong = handshake_proof(&generate_token().unwrap(), ProofRole::Client, &client_nonce, &client_nonce).unwrap();
|
||||
let bad_proofs = [proof_line(&wrong), proof_line(&token), json!({"id": 2, "method": AUTH_METHOD, "params": {}}).to_string()];
|
||||
for line in bad_proofs {
|
||||
let mut server = ServerHandshake::new();
|
||||
assert_eq!(server.reply(&challenge_line(&client_nonce), &token).1, AuthStep::Challenged);
|
||||
let (reply, step) = server.reply(&line, &token);
|
||||
assert_eq!(step, AuthStep::Rejected, "{line}: {reply}");
|
||||
assert_eq!(reply["error"], "authentication required");
|
||||
}
|
||||
// After a challenge the token itself no longer authenticates, nor does a second challenge.
|
||||
for line in [auth_line(&token), challenge_line(&client_nonce), r#"{"id":3,"method":"methods"}"#.to_owned()] {
|
||||
let mut server = ServerHandshake::new();
|
||||
assert_eq!(server.reply(&challenge_line(&client_nonce), &token).1, AuthStep::Challenged);
|
||||
assert_eq!(server.reply(&line, &token).1, AuthStep::Rejected, "{line}");
|
||||
}
|
||||
// A malformed nonce is refused before any proof is computed.
|
||||
for nonce in ["", "short", &"g".repeat(64), &"a".repeat(65)] {
|
||||
let (reply, step) = ServerHandshake::new().reply(&challenge_line(nonce), &token);
|
||||
assert_eq!(step, AuthStep::Rejected, "{nonce}: {reply}");
|
||||
assert!(reply.get("result").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_tokens_are_valid_and_distinct() {
|
||||
let a = generate_token().unwrap();
|
||||
@@ -404,6 +578,8 @@ mod tests {
|
||||
assert!(authenticated, "{reply}");
|
||||
}
|
||||
|
||||
/// A repeat `auth` or `auth.challenge` on an authenticated connection is answered "already
|
||||
/// authenticated"; any other frame is left to the dispatcher.
|
||||
#[test]
|
||||
fn repeat_auth_on_an_authenticated_connection_says_so() {
|
||||
let line = json!({"id": 3, "method": AUTH_METHOD, "params": {"token": "anything"}}).to_string();
|
||||
@@ -411,6 +587,8 @@ mod tests {
|
||||
assert_eq!(reply["id"], 3);
|
||||
assert_eq!(reply["ok"], false);
|
||||
assert_eq!(reply["error"], "already authenticated");
|
||||
let challenge = json!({"id": 5, "method": CHALLENGE_METHOD, "params": {"clientNonce": "anything"}}).to_string();
|
||||
assert_eq!(repeat_auth_reply(&challenge).unwrap()["error"], "already authenticated");
|
||||
assert!(repeat_auth_reply(r#"{"id":4,"method":"methods"}"#).is_none());
|
||||
assert!(repeat_auth_reply("{not json").is_none());
|
||||
}
|
||||
|
||||
@@ -217,6 +217,10 @@ pub struct SaveParams {
|
||||
/// DDS: also write the full mip chain, each level a box filter of the one above.
|
||||
#[serde(default, rename = "ddsMipmaps")]
|
||||
pub dds_mipmaps: bool,
|
||||
/// PDF: write the spot channels as overprinting Separation plates after the flattened image
|
||||
/// (a Multichannel document as plates alone). On by default; false writes the image only.
|
||||
#[serde(default, rename = "pdfSpotPlates")]
|
||||
pub pdf_spot_plates: Option<bool>,
|
||||
/// .pcraft: request the flattened document at its canvas size as `composite/full.png`.
|
||||
/// The save may omit it; check the manifest's `full_composite` member. Off by default.
|
||||
#[serde(default, rename = "pcraftFullComposite")]
|
||||
@@ -1213,6 +1217,7 @@ impl PhotocraftMcp {
|
||||
p.tiff_layers.then_some("tiffLayers"),
|
||||
p.pcraft_full_composite.is_some().then_some("pcraftFullComposite"),
|
||||
dpx_bits.is_some().then_some("dpxBits"),
|
||||
p.pdf_spot_plates.is_some().then_some("pdfSpotPlates"),
|
||||
p.index.is_some().then_some("index"),
|
||||
]
|
||||
.into_iter()
|
||||
@@ -1255,6 +1260,7 @@ impl PhotocraftMcp {
|
||||
tiff_layers: p.tiff_layers,
|
||||
tiff_transparency: p.tiff_transparency,
|
||||
tga_bits,
|
||||
pdf_spot_plates: p.pdf_spot_plates.unwrap_or(true),
|
||||
pcraft_full_composite: p.pcraft_full_composite.unwrap_or(false),
|
||||
..Default::default()
|
||||
};
|
||||
@@ -1546,6 +1552,25 @@ mod tests {
|
||||
server.await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
/// Answer the bridge's challenge authentication on one fake-app connection, frame by frame,
|
||||
/// as the real control servers do. Returns whether the connection authenticated.
|
||||
async fn fake_app_handshake<R, W>(lines: &mut tokio::io::Lines<R>, write: &mut W, token: &str) -> bool
|
||||
where
|
||||
R: tokio::io::AsyncBufRead + Unpin,
|
||||
W: tokio::io::AsyncWrite + Unpin,
|
||||
{
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let mut handshake = crate::security::ServerHandshake::new();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
if step != crate::security::AuthStep::Challenged {
|
||||
return step == crate::security::AuthStep::Authenticated;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The same over the bridge (#8130): a dropped wait sends `jobs.cancel` for the app's job.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn dropping_a_bridged_wait_cancels_the_apps_job() {
|
||||
@@ -1563,8 +1588,7 @@ mod tests {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let (read, mut write) = socket.into_split();
|
||||
let mut lines = tokio::io::BufReader::new(read).lines();
|
||||
let (auth, _) = crate::security::authentication_reply(&lines.next_line().await.unwrap().unwrap(), TOKEN);
|
||||
write.write_all(format!("{auth}\n").as_bytes()).await.unwrap();
|
||||
fake_app_handshake(&mut lines, &mut write, TOKEN).await;
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
let request: Value = serde_json::from_str(&line).unwrap();
|
||||
let result = match request["method"].as_str().unwrap() {
|
||||
|
||||
@@ -134,10 +134,16 @@ impl AuthorizedWorkspace {
|
||||
///
|
||||
/// Replacing a file carries its extended attributes — macOS Finder tags, Linux `user.*` —
|
||||
/// onto the file that takes its place (#7095), through the two open descriptors rather than
|
||||
/// their paths, so nothing here reaches outside the write root to finish a write. The rest
|
||||
/// of what [`photocraft_format::atomic_write`] preserves does not follow: its permission
|
||||
/// step is tracked in #4963, and the Windows `ReplaceFileW` swap is path-based, which this
|
||||
/// path may not use.
|
||||
/// their paths. The rest of what [`photocraft_format::atomic_write`] preserves does not
|
||||
/// follow: its permission step is tracked in #4963, and the Windows `ReplaceFileW` swap is
|
||||
/// path-based, which this path may not use.
|
||||
///
|
||||
/// Nothing here reaches outside the write root. Below a Windows UNC root
|
||||
/// (`\\wsl.localhost\...`, any network share) the capability's own rename and remove cannot
|
||||
/// reach their target at all (#10317, see [`is_unc_root`]), so there the temporary file is
|
||||
/// renamed into place on the canonical root path while every directory on the way is pinned
|
||||
/// by a handle opened through the root ([`rename_in`]): the same atomic replace, never
|
||||
/// outside the root, and never a stranded temporary file.
|
||||
///
|
||||
/// The parent directory must already exist. `cap-std` performs path
|
||||
/// resolution and file creation relative to the held directory handle, so
|
||||
@@ -195,7 +201,7 @@ impl AuthorizedWorkspace {
|
||||
// Falls back to a plain fsync on shares that refuse a full flush (#1336).
|
||||
photocraft_format::atomic::sync_file(&file)
|
||||
});
|
||||
let renamed = written.and_then(|()| photocraft_format::atomic::retry_rename(RenameRetry::platform(), || root.dir.rename(&tmp, &root.dir, &relative)));
|
||||
let renamed = written.and_then(|()| photocraft_format::atomic::retry_rename(RenameRetry::platform(), || rename_in(root, &tmp, &relative)));
|
||||
if let Err(e) = renamed {
|
||||
return Err(file_error("write", path, e));
|
||||
}
|
||||
@@ -212,7 +218,8 @@ impl AuthorizedWorkspace {
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes a temporary file on drop unless `armed` was cleared after its rename.
|
||||
/// Removes a temporary file on drop unless `armed` was cleared after its rename. The removal
|
||||
/// goes through the held directory handle ([`remove_file_in`]), so it works below every root.
|
||||
struct TempRemoval<'a> {
|
||||
dir: &'a Dir,
|
||||
path: &'a Path,
|
||||
@@ -222,7 +229,7 @@ struct TempRemoval<'a> {
|
||||
impl Drop for TempRemoval<'_> {
|
||||
fn drop(&mut self) {
|
||||
if self.armed {
|
||||
let _ = self.dir.remove_file(self.path);
|
||||
let _ = remove_file_in(self.dir, self.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -297,6 +304,183 @@ fn open_root(path: &Path, authority: &str, opened: &[RootCapability]) -> Result<
|
||||
Ok(RootCapability { dir: Arc::new(dir), path: absolute, configured_path })
|
||||
}
|
||||
|
||||
/// `cap-std`'s Windows `rename`, `remove_file` and `create_dir` do not run relative to the held
|
||||
/// handle: they append the request to the handle's own path and call `std::fs`
|
||||
/// (sunfishcode/cap-std#348), and that path is read back without its `\\?\` prefix. Below a
|
||||
/// drive root the result still resolves; below a UNC root (`\\?\UNC\wsl.localhost\...`, any
|
||||
/// network share) it becomes the relative `UNC\wsl.localhost\...` and each of those steps
|
||||
/// fails with `ERROR_PATH_NOT_FOUND`, so a save left only its temporary file behind (#10317).
|
||||
/// Opening a file or directory and `stat` are handle-relative and work below any root, and
|
||||
/// everything here is built on them: files are removed through handles ([`remove_file_in`]),
|
||||
/// and the two steps that have no handle-relative form, making a directory and renaming the
|
||||
/// finished temporary file into place, run on the canonical root path below directories pinned
|
||||
/// by held handles ([`create_dir_all_unc`], [`rename_unc`]).
|
||||
///
|
||||
/// Whether the root is such a UNC root, judged by the canonical root path's prefix: trusted
|
||||
/// launch configuration, never the request.
|
||||
#[cfg(windows)]
|
||||
fn is_unc_root(root: &RootCapability) -> bool {
|
||||
matches!(root.path.components().next(), Some(Component::Prefix(p)) if matches!(p.kind(), Prefix::VerbatimUNC(..) | Prefix::UNC(..)))
|
||||
}
|
||||
|
||||
/// Rename `from` to `to`, both relative to the write root, replacing whatever file is at `to`.
|
||||
/// Through the capability wherever that works; below a Windows UNC root its `rename` reports
|
||||
/// both names missing (see [`is_unc_root`]), so there the rename is done by [`rename_unc`].
|
||||
fn rename_in(root: &RootCapability, from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
let renamed = root.dir.rename(from, &root.dir, to);
|
||||
#[cfg(windows)]
|
||||
if renamed.as_ref().is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) && is_unc_root(root) {
|
||||
return rename_unc(root, from, to);
|
||||
}
|
||||
renamed
|
||||
}
|
||||
|
||||
/// Rename `from` to `to` below a UNC root with `std::fs::rename` on the canonical root path:
|
||||
/// the second of the two ambient steps, the other being [`create_dir_all_unc`]'s `create_dir`,
|
||||
/// and guarded the same way. The directory of each name is first opened component by component
|
||||
/// through the handle of its parent ([`pinned_directory_chain`]), every component verified a
|
||||
/// plain directory and then held open for the duration, so the path the rename resolves names
|
||||
/// exactly the directories the capability verified: a link anywhere on the way is refused, an
|
||||
/// absent directory is not created, and a held one cannot be renamed away or replaced while the
|
||||
/// rename runs. The rename itself replaces the entry at `to` without following it: a link there
|
||||
/// is replaced, never written through, and a directory there is refused.
|
||||
#[cfg(windows)]
|
||||
fn rename_unc(root: &RootCapability, from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
let parent = |name: &Path| name.parent().map(Path::to_path_buf).unwrap_or_default();
|
||||
let _from_chain = pinned_directory_chain(root, &parent(from))?;
|
||||
let _to_chain = pinned_directory_chain(root, &parent(to))?;
|
||||
std::fs::rename(below_root(root, from), below_root(root, to))
|
||||
}
|
||||
|
||||
/// `relative` below the canonical root path, one component at a time, so the result keeps the
|
||||
/// root's verbatim form (`\\?\UNC\...`): a `/` in a request would not separate there.
|
||||
#[cfg(windows)]
|
||||
fn below_root(root: &RootCapability, relative: &Path) -> PathBuf {
|
||||
let mut path = root.path.clone();
|
||||
path.extend(relative.components());
|
||||
path
|
||||
}
|
||||
|
||||
/// Remove the file `name` relative to `dir`. On Windows the capability's own `remove_file`
|
||||
/// reports every file below a UNC root missing (see [`is_unc_root`]); then the file is deleted
|
||||
/// through a handle opened relative to `dir` instead ([`delete_on_close`]).
|
||||
fn remove_file_in(dir: &Dir, name: &Path) -> std::io::Result<()> {
|
||||
let removed = dir.remove_file(name);
|
||||
#[cfg(windows)]
|
||||
if removed.as_ref().is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) {
|
||||
return delete_on_close(dir, name);
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
/// Delete `name` by opening it relative to `dir` with `FILE_FLAG_DELETE_ON_CLOSE` and dropping
|
||||
/// the handle. The open resolves against the held directory like every other open, so it
|
||||
/// cannot reach outside it. `FILE_FLAG_OPEN_REPARSE_POINT` makes a link at `name` the thing
|
||||
/// deleted rather than its target, as `remove_file` does; a directory is refused and a missing
|
||||
/// name reports `NotFound`, both as `remove_file` would.
|
||||
#[cfg(windows)]
|
||||
fn delete_on_close(dir: &Dir, name: &Path) -> std::io::Result<()> {
|
||||
use cap_std::fs::OpenOptionsExt;
|
||||
const FILE_FLAG_DELETE_ON_CLOSE: u32 = 0x0400_0000;
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
let mut options = OpenOptions::new();
|
||||
options.read(true).custom_flags(FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_OPEN_REPARSE_POINT);
|
||||
dir.open_with(name, &options).map(drop)
|
||||
}
|
||||
|
||||
/// Make `relative` a directory below the write root, with its missing ancestors. Through the
|
||||
/// capability wherever that works; below a Windows UNC root its `create_dir_all` reports
|
||||
/// `NotFound` whether or not the directory exists (see [`is_unc_root`]), so there an existing
|
||||
/// directory is accepted by opening it through the handle and a missing one is made by
|
||||
/// [`create_dir_all_unc`].
|
||||
fn ensure_export_dir(root: &RootCapability, relative: &Path) -> std::io::Result<()> {
|
||||
let created = root.dir.create_dir_all(relative);
|
||||
#[cfg(windows)]
|
||||
if created.as_ref().is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) && is_unc_root(root) {
|
||||
return match root.dir.open_dir(relative) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => create_dir_all_unc(root, relative),
|
||||
};
|
||||
}
|
||||
created
|
||||
}
|
||||
|
||||
/// Directory creation is one of the two steps `cap-std` has no handle-relative form of on
|
||||
/// Windows (it never opens with `FILE_DIRECTORY_FILE`; the other is the rename of
|
||||
/// [`rename_unc`]), so below a UNC root an absent component is made with `std::fs::create_dir`
|
||||
/// on the canonical root path — trusted launch configuration, never the request. The walk
|
||||
/// ([`held_directory_chain`]) descends one component at a time and keeps a handle open on every
|
||||
/// ancestor it has verified through its parent's handle. `cap-std` opens directories without
|
||||
/// `FILE_SHARE_DELETE` precisely so that they cannot be renamed or deleted underneath its
|
||||
/// sandboxed path lookups, and the held chain pins the ancestors here the same way: an ancestor
|
||||
/// cannot be swapped for a link while the walk is below it, so the one ambient `create_dir` can
|
||||
/// only add a new, empty directory inside the directory its held parent handle names. Something
|
||||
/// that appears under the component's name between the check and `create_dir` makes
|
||||
/// `create_dir` fail with `AlreadyExists`, which is reported, never resolved. No file is ever
|
||||
/// written or removed ambiently, and the one ambient rename is guarded by the same held chain.
|
||||
#[cfg(windows)]
|
||||
fn create_dir_all_unc(root: &RootCapability, relative: &Path) -> std::io::Result<()> {
|
||||
held_directory_chain(root, relative).map(drop)
|
||||
}
|
||||
|
||||
/// Open each component of `relative` through the handle of its parent, creating an absent one
|
||||
/// first as described at [`create_dir_all_unc`]. The returned handles, outermost first, keep
|
||||
/// every directory on the way pinned for as long as they are held.
|
||||
#[cfg(windows)]
|
||||
fn held_directory_chain(root: &RootCapability, relative: &Path) -> std::io::Result<Vec<Dir>> {
|
||||
directory_chain(root, relative, open_or_create_plain_dir)
|
||||
}
|
||||
|
||||
/// [`held_directory_chain`] for directories that must already exist: an absent component is
|
||||
/// `NotFound`, and nothing is created. This is what pins the way for [`rename_unc`].
|
||||
#[cfg(windows)]
|
||||
fn pinned_directory_chain(root: &RootCapability, relative: &Path) -> std::io::Result<Vec<Dir>> {
|
||||
directory_chain(root, relative, |parent, name, ancestor, _| open_plain_dir(parent, name, ancestor))
|
||||
}
|
||||
|
||||
/// The walk shared by [`held_directory_chain`] and [`pinned_directory_chain`]: `open` receives
|
||||
/// the parent's handle, the component's name, its path relative to the root and its path below
|
||||
/// the canonical root, in that order.
|
||||
#[cfg(windows)]
|
||||
fn directory_chain(root: &RootCapability, relative: &Path, open: fn(&Dir, &Path, &Path, &Path) -> std::io::Result<Dir>) -> std::io::Result<Vec<Dir>> {
|
||||
let mut chain: Vec<Dir> = Vec::new();
|
||||
let mut ancestor = PathBuf::new();
|
||||
for component in relative.components() {
|
||||
ancestor.push(component);
|
||||
let parent = chain.last().unwrap_or(&root.dir);
|
||||
let dir = open(parent, Path::new(component.as_os_str()), &ancestor, &root.path.join(&ancestor))?;
|
||||
chain.push(dir);
|
||||
}
|
||||
Ok(chain)
|
||||
}
|
||||
|
||||
/// Open `name`, one component of `parent`, when it is a plain directory; when it is absent,
|
||||
/// create it at `ambient` (its path below the canonical root, which `parent` is a handle to)
|
||||
/// and open what is there now. `ancestor` names the component relative to the root in errors.
|
||||
#[cfg(windows)]
|
||||
fn open_or_create_plain_dir(parent: &Dir, name: &Path, ancestor: &Path, ambient: &Path) -> std::io::Result<Dir> {
|
||||
match open_plain_dir(parent, name, ancestor) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
std::fs::create_dir(ambient)?;
|
||||
open_plain_dir(parent, name, ancestor)
|
||||
}
|
||||
opened => opened,
|
||||
}
|
||||
}
|
||||
|
||||
/// Open `name` in `parent` only if it is a plain directory — not a link, which ambient
|
||||
/// resolution would follow out of the root, and not a file.
|
||||
#[cfg(windows)]
|
||||
fn open_plain_dir(parent: &Dir, name: &Path, ancestor: &Path) -> std::io::Result<Dir> {
|
||||
let meta = parent.symlink_metadata(name)?;
|
||||
if meta.is_dir() && !meta.is_symlink() {
|
||||
parent.open_dir(name)
|
||||
} else {
|
||||
let message = format!("`{}` is not a plain directory below the root", ancestor.display());
|
||||
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, message))
|
||||
}
|
||||
}
|
||||
|
||||
/// Both root spellings refer to the capability opened at startup. Do not resolve an untrusted
|
||||
/// absolute request using ambient filesystem access: strip a known root first and let cap-std
|
||||
/// resolve the remaining name. New targets and nested export directories need not exist yet.
|
||||
@@ -603,16 +787,21 @@ pub(crate) struct ExportSequence {
|
||||
}
|
||||
|
||||
impl AuthorizedWorkspace {
|
||||
/// Open the export directory `path` below the write root as its own capability, creating it
|
||||
/// (and missing ancestors) first; see [`ensure_export_dir`]. Every file the sequence then
|
||||
/// writes or removes goes through that held directory handle.
|
||||
pub(crate) fn export_sequence(&self, path: &str) -> Result<ExportSequence, AutomationError> {
|
||||
let relative = request_path(path, self.write.as_ref())?;
|
||||
let root = self.write.as_ref().ok_or_else(|| AutomationError::BadRequest(format!("{DENIED}: write authority is absent")))?;
|
||||
root.dir.create_dir_all(&relative).map_err(|e| file_error("mkdir", path, e))?;
|
||||
ensure_export_dir(root, &relative).map_err(|e| file_error("mkdir", path, e))?;
|
||||
let dir = root.dir.open_dir(&relative).map_err(|e| file_error("open export directory", path, e))?;
|
||||
Ok(ExportSequence { dir, created: Vec::new() })
|
||||
}
|
||||
}
|
||||
|
||||
impl ExportSequence {
|
||||
/// Create `name` (a single path component) in the export directory and write `bytes` to
|
||||
/// it. An existing entry of that name, link or file, is a collision and is refused.
|
||||
pub(crate) fn write(&mut self, name: &str, bytes: &[u8]) -> Result<(), AutomationError> {
|
||||
let relative = relative_path(name)?;
|
||||
if relative.components().count() != 1 {
|
||||
@@ -626,18 +815,26 @@ impl ExportSequence {
|
||||
file.write_all(bytes).and_then(|()| file.sync_all()).map_err(|e| file_error("write export", name, e))
|
||||
}
|
||||
|
||||
/// Keep every file written so far: nothing is removed on cleanup or drop.
|
||||
pub(crate) fn commit(&mut self) {
|
||||
self.created.clear();
|
||||
}
|
||||
|
||||
/// Remove every file written since the last [`commit`](Self::commit), each through the held
|
||||
/// directory handle (see [`remove_file_in`]). A file already gone is fine; any other failure
|
||||
/// is reported, and that name stays listed for a later attempt.
|
||||
pub(crate) fn cleanup(&mut self) -> Result<(), AutomationError> {
|
||||
let mut failed = Vec::new();
|
||||
self.created.retain(|name| match self.dir.remove_file(name) {
|
||||
Ok(()) => false,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
Err(e) => {
|
||||
failed.push(format!("{name}: {e}"));
|
||||
true
|
||||
let (dir, created) = (&self.dir, &mut self.created);
|
||||
created.retain(|name| {
|
||||
let removed = remove_file_in(dir, Path::new(name));
|
||||
match removed {
|
||||
Ok(()) => false,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
Err(e) => {
|
||||
failed.push(format!("{name}: {e}"));
|
||||
true
|
||||
}
|
||||
}
|
||||
});
|
||||
if failed.is_empty() { Ok(()) } else { Err(AutomationError::Io(format!("export cleanup failed: {}", failed.join("; ")))) }
|
||||
@@ -645,6 +842,7 @@ impl ExportSequence {
|
||||
}
|
||||
|
||||
impl Drop for ExportSequence {
|
||||
/// Remove whatever was not committed, best effort.
|
||||
fn drop(&mut self) {
|
||||
// Also cover an escaped rendering panic; normal errors report cleanup failures above.
|
||||
let _ = self.cleanup();
|
||||
|
||||
@@ -371,6 +371,275 @@ fn windows_junction_escape_is_rejected_when_supported() {
|
||||
let _ = std::fs::remove_dir(link);
|
||||
}
|
||||
|
||||
/// #10317: below a UNC root (`\\wsl.localhost\...`, any share) `cap-std`'s Windows rename,
|
||||
/// remove and mkdir fail with `ERROR_PATH_NOT_FOUND`, so a save left only its `.pcsave.tmp`
|
||||
/// behind, an export into a new directory failed, and a cancelled export leaked its frames.
|
||||
/// There a save still goes through its temporary file and is renamed into place on the
|
||||
/// canonical root path below pinned directories, cleanup deletes through handles opened
|
||||
/// relative to the export directory, and directory creation goes through the root path the
|
||||
/// same pinned way. The administrative share of the temp directory's drive stands in for a
|
||||
/// network share; a runner without one has nothing to check here.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_unc_root_writes_and_exports_when_supported() {
|
||||
let (inside, outside, _) = roots("unc-root");
|
||||
let Some(unc) = loopback_unc(&inside) else { return };
|
||||
if std::fs::metadata(&unc).is_err() {
|
||||
return;
|
||||
}
|
||||
let canonical = std::fs::canonicalize(&unc).unwrap();
|
||||
assert!(matches!(canonical.components().next(), Some(Component::Prefix(p)) if matches!(p.kind(), Prefix::VerbatimUNC(..))), "{}", canonical.display());
|
||||
let workspace = AuthorizedWorkspace::new(Some(&unc), Some(&unc)).unwrap();
|
||||
|
||||
workspace.write("out.png", b"first").unwrap();
|
||||
workspace.write("out.png", b"second").unwrap();
|
||||
std::fs::create_dir(inside.join("sub")).unwrap();
|
||||
workspace.write("sub/nested.png", b"nested").unwrap();
|
||||
assert_eq!(std::fs::read(inside.join("out.png")).unwrap(), b"second");
|
||||
assert_eq!(std::fs::read(inside.join("sub/nested.png")).unwrap(), b"nested");
|
||||
assert!(temp_files(&inside).is_empty());
|
||||
assert!(temp_files(&inside.join("sub")).is_empty());
|
||||
// Still atomic: a writer that fails leaves the previous bytes and no temporary file.
|
||||
let failed = workspace.write_stream("out.png", &mut |w| {
|
||||
w.write_all(b"partial")?;
|
||||
Err(std::io::Error::other("encoder gave up"))
|
||||
});
|
||||
assert!(failed.is_err());
|
||||
assert_eq!(std::fs::read(inside.join("out.png")).unwrap(), b"second");
|
||||
assert!(temp_files(&inside).is_empty());
|
||||
// A large streamed save takes the same route as everywhere else.
|
||||
workspace.write_stream("sub/streamed.png", &mut |w| w.write_all(&[7u8; 1 << 20])).unwrap();
|
||||
assert_eq!(std::fs::metadata(inside.join("sub/streamed.png")).unwrap().len(), 1 << 20);
|
||||
assert!(temp_files(&inside.join("sub")).is_empty());
|
||||
// A missing parent is still an error, with nothing left behind, as on every other root.
|
||||
assert!(workspace.write("missing/out.png", b"no parent").is_err());
|
||||
assert!(!inside.join("missing").exists());
|
||||
|
||||
let mut export = workspace.export_sequence("frames/nested").unwrap();
|
||||
export.write("clip_0000.png", b"frame").unwrap();
|
||||
assert_eq!(std::fs::read(inside.join("frames/nested/clip_0000.png")).unwrap(), b"frame");
|
||||
export.cleanup().unwrap();
|
||||
assert!(!inside.join("frames/nested/clip_0000.png").exists());
|
||||
let mut export = workspace.export_sequence("frames/nested").unwrap();
|
||||
export.write("clip_0001.png", b"kept").unwrap();
|
||||
export.commit();
|
||||
drop(export);
|
||||
assert_eq!(std::fs::read(inside.join("frames/nested/clip_0001.png")).unwrap(), b"kept");
|
||||
// The share honours the held ancestors' share mode: no swap while the chain is open.
|
||||
let root = workspace.write.as_ref().unwrap();
|
||||
let chain = held_directory_chain(root, Path::new("frames/nested/deeper")).unwrap();
|
||||
assert!(std::fs::rename(inside.join("frames"), inside.join("frames-moved")).is_err());
|
||||
assert!(inside.join("frames/nested/deeper").is_dir());
|
||||
drop(chain);
|
||||
|
||||
// Neither the rename into place nor directory creation follows a link out of the root.
|
||||
let link = inside.join("junction");
|
||||
if std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).status().is_ok_and(|status| status.success()) {
|
||||
assert!(workspace.write("junction/escape.png", b"blocked").is_err());
|
||||
assert!(workspace.export_sequence("junction/frames").is_err());
|
||||
assert!(!outside.join("escape.png").exists());
|
||||
assert!(!outside.join("frames").exists());
|
||||
assert!(temp_files(&outside).is_empty());
|
||||
let _ = std::fs::remove_dir(link);
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle-relative helpers that stand in for `cap-std`'s path-concatenating Windows
|
||||
/// operations below a UNC root (#10317) behave like the operations they replace, on any root.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_handle_relative_helpers_match_the_capability_operations() {
|
||||
let (inside, _outside, workspace) = roots("unc-helpers");
|
||||
let root = workspace.write.as_ref().unwrap();
|
||||
assert!(!is_unc_root(root));
|
||||
|
||||
std::fs::write(inside.join("gone.png"), b"x").unwrap();
|
||||
delete_on_close(&root.dir, Path::new("gone.png")).unwrap();
|
||||
assert!(!inside.join("gone.png").exists());
|
||||
std::fs::write(inside.join("gone.png"), b"x").unwrap();
|
||||
remove_file_in(&root.dir, Path::new("gone.png")).unwrap();
|
||||
assert!(!inside.join("gone.png").exists());
|
||||
assert_eq!(delete_on_close(&root.dir, Path::new("missing.png")).unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
||||
assert_eq!(remove_file_in(&root.dir, Path::new("missing.png")).unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
||||
std::fs::create_dir(inside.join("dir")).unwrap();
|
||||
assert!(delete_on_close(&root.dir, Path::new("dir")).is_err());
|
||||
assert!(inside.join("dir").is_dir());
|
||||
}
|
||||
|
||||
/// The ambient rename that stands in for the capability's below a UNC root (#10317).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_rename_unc_matches_the_capability_rename() {
|
||||
let (inside, outside, workspace) = roots("unc-rename");
|
||||
let root = workspace.write.as_ref().unwrap();
|
||||
std::fs::create_dir(inside.join("dir")).unwrap();
|
||||
// The ambient rename on the canonical root path behaves like the capability's: it creates,
|
||||
// replaces a file, replaces a link instead of writing through it, and refuses a directory.
|
||||
std::fs::write(inside.join("plain.tmp"), b"the longer first version").unwrap();
|
||||
rename_unc(root, Path::new("plain.tmp"), Path::new("plain.png")).unwrap();
|
||||
std::fs::write(inside.join("plain.tmp"), b"short").unwrap();
|
||||
rename_unc(root, Path::new("plain.tmp"), Path::new("plain.png")).unwrap();
|
||||
rename_in(root, Path::new("plain.png"), Path::new("plain.png")).unwrap();
|
||||
assert_eq!(std::fs::read(inside.join("plain.png")).unwrap(), b"short");
|
||||
assert!(!inside.join("plain.tmp").exists());
|
||||
assert_eq!(rename_unc(root, Path::new("absent.tmp"), Path::new("plain.png")).unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
||||
assert_eq!(rename_unc(root, Path::new("plain.png"), Path::new("missing/plain.png")).unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
||||
assert!(!inside.join("missing").exists());
|
||||
std::fs::write(inside.join("plain.tmp"), b"x").unwrap();
|
||||
assert!(rename_unc(root, Path::new("plain.tmp"), Path::new("dir")).is_err());
|
||||
assert!(inside.join("dir").is_dir());
|
||||
std::fs::write(outside.join("target.png"), b"outside").unwrap();
|
||||
if std::os::windows::fs::symlink_file(outside.join("target.png"), inside.join("linked.png")).is_ok() {
|
||||
rename_unc(root, Path::new("plain.tmp"), Path::new("linked.png")).unwrap();
|
||||
assert_eq!(std::fs::read(inside.join("linked.png")).unwrap(), b"x");
|
||||
assert_eq!(std::fs::read(outside.join("target.png")).unwrap(), b"outside");
|
||||
}
|
||||
let _ = std::fs::remove_file(inside.join("plain.tmp"));
|
||||
}
|
||||
|
||||
/// The directory walk that stands in for the capability's `create_dir_all` below a UNC root
|
||||
/// (#10317) creates, refuses files on the way and never follows a junction outside.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_create_dir_all_unc_matches_the_capability_operation() {
|
||||
let (inside, outside, workspace) = roots("unc-dirs");
|
||||
let root = workspace.write.as_ref().unwrap();
|
||||
create_dir_all_unc(root, Path::new("a/b/c")).unwrap();
|
||||
assert!(inside.join("a/b/c").is_dir());
|
||||
create_dir_all_unc(root, Path::new("a/b/c")).unwrap();
|
||||
assert_eq!(held_directory_chain(root, Path::new("a/b/c")).unwrap().len(), 3);
|
||||
std::fs::write(inside.join("a/file"), b"x").unwrap();
|
||||
assert_eq!(create_dir_all_unc(root, Path::new("a/file")).unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
|
||||
assert!(create_dir_all_unc(root, Path::new("a/file/below")).is_err());
|
||||
assert!(inside.join("a/file").is_file());
|
||||
assert!(ensure_export_dir(root, Path::new("a/b/d")).is_ok());
|
||||
assert!(inside.join("a/b/d").is_dir());
|
||||
|
||||
let link = inside.join("junction");
|
||||
if std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).status().is_ok_and(|status| status.success()) {
|
||||
assert!(create_dir_all_unc(root, Path::new("junction")).is_err());
|
||||
assert!(create_dir_all_unc(root, Path::new("junction/frames")).is_err());
|
||||
assert!(!outside.join("frames").exists());
|
||||
assert_eq!(pinned_directory_chain(root, Path::new("junction")).unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
|
||||
std::fs::write(inside.join("escape.tmp"), b"blocked").unwrap();
|
||||
assert_eq!(rename_unc(root, Path::new("escape.tmp"), Path::new("junction/escape.png")).unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
|
||||
assert!(rename_unc(root, Path::new("junction/source.png"), Path::new("escape.png")).is_err());
|
||||
assert!(!outside.join("escape.png").exists());
|
||||
assert!(inside.join("escape.tmp").is_file());
|
||||
let _ = std::fs::remove_dir(link);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ancestor-swap race against [`create_dir_all_unc`]: between verifying an ancestor and the
|
||||
/// ambient `create_dir`, an attacker renames the ancestor away and puts a junction to the
|
||||
/// outside in its place. The walk holds a handle on every verified ancestor, opened by
|
||||
/// `cap-std` without `FILE_SHARE_DELETE`, so the rename (and a removal) fails with
|
||||
/// `ERROR_SHARING_VIOLATION` for as long as the chain is held, and the directory is created
|
||||
/// inside the root. A junction that is already in place is refused before anything is created.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_held_ancestors_cannot_be_swapped_during_directory_creation() {
|
||||
const ERROR_SHARING_VIOLATION: i32 = 32;
|
||||
let (inside, outside, workspace) = roots("unc-held-chain");
|
||||
let root = workspace.write.as_ref().unwrap();
|
||||
std::fs::create_dir(inside.join("a")).unwrap();
|
||||
|
||||
let chain = held_directory_chain(root, Path::new("a/b")).unwrap();
|
||||
assert_eq!(chain.len(), 2);
|
||||
assert!(inside.join("a/b").is_dir());
|
||||
let swap = std::fs::rename(inside.join("a"), inside.join("a-moved"));
|
||||
assert_eq!(swap.unwrap_err().raw_os_error(), Some(ERROR_SHARING_VIOLATION));
|
||||
assert_eq!(std::fs::remove_dir(inside.join("a/b")).unwrap_err().raw_os_error(), Some(ERROR_SHARING_VIOLATION));
|
||||
// With the ancestors pinned, the one ambient step lands inside the root.
|
||||
let held_parent = &chain[1];
|
||||
open_or_create_plain_dir(held_parent, Path::new("c"), Path::new("a/b/c"), &root.path.join("a/b/c")).unwrap();
|
||||
assert!(inside.join("a/b/c").is_dir());
|
||||
assert!(inside.join("a").is_dir());
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
drop(chain);
|
||||
// The chain that guards the rename pins the same way, and creates nothing.
|
||||
let pinned = pinned_directory_chain(root, Path::new("a/b/c")).unwrap();
|
||||
assert_eq!(pinned.len(), 3);
|
||||
assert_eq!(std::fs::rename(inside.join("a"), inside.join("a-moved")).unwrap_err().raw_os_error(), Some(ERROR_SHARING_VIOLATION));
|
||||
assert_eq!(pinned_directory_chain(root, Path::new("a/b/c/d")).unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
||||
assert!(!inside.join("a/b/c/d").exists());
|
||||
std::fs::write(inside.join("a/b/c/new.tmp"), b"renamed below pinned ancestors").unwrap();
|
||||
rename_unc(root, Path::new("a/b/c/new.tmp"), Path::new("a/b/c/new.png")).unwrap();
|
||||
assert_eq!(std::fs::read(inside.join("a/b/c/new.png")).unwrap(), b"renamed below pinned ancestors");
|
||||
drop(pinned);
|
||||
std::fs::rename(inside.join("a"), inside.join("a-moved")).unwrap();
|
||||
|
||||
// The swap already done: the junction is seen through the parent handle and refused.
|
||||
let link = inside.join("a");
|
||||
if std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).status().is_ok_and(|status| status.success()) {
|
||||
let refused = open_or_create_plain_dir(&root.dir, Path::new("a"), Path::new("a"), &root.path.join("a"));
|
||||
assert_eq!(refused.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
|
||||
assert!(held_directory_chain(root, Path::new("a/b/c")).is_err());
|
||||
assert!(pinned_directory_chain(root, Path::new("a/b/c")).is_err());
|
||||
assert!(ensure_export_dir(root, Path::new("a/b/c")).is_err());
|
||||
assert!(workspace.export_sequence("a/b/c").is_err());
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
let _ = std::fs::remove_dir(link);
|
||||
}
|
||||
}
|
||||
|
||||
/// The rules that do not depend on the root hold below a UNC root too (#10317): `..` is refused
|
||||
/// in a request and climbs no further than the root in the configured spelling, a directory at
|
||||
/// the target is refused before it is opened and survives, and a path past `MAX_PATH` works,
|
||||
/// since the canonical root is verbatim (`\\?\UNC\...`) and every step below it goes through a
|
||||
/// handle or that verbatim root path.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_unc_root_refuses_traversal_and_accepts_long_paths_when_supported() {
|
||||
let (inside, outside, _) = roots("unc-rules");
|
||||
let Some(unc) = loopback_unc(&inside) else { return };
|
||||
if std::fs::metadata(&unc).is_err() {
|
||||
return;
|
||||
}
|
||||
let workspace = AuthorizedWorkspace::new(Some(&unc), Some(&unc)).unwrap();
|
||||
|
||||
for path in ["../escape.png", "sub/../../escape.png", r"sub\..\..\escape.png", r"..\frames"] {
|
||||
assert!(workspace.write(path, b"no").is_err(), "write accepted {path:?}");
|
||||
assert!(workspace.export_sequence(path).is_err(), "export accepted {path:?}");
|
||||
}
|
||||
let spelled = unc.join("..").join("inside");
|
||||
let aliased = AuthorizedWorkspace::new(Some(&spelled), Some(&spelled)).unwrap();
|
||||
aliased.write("spelled.png", b"same grant").unwrap();
|
||||
assert_eq!(std::fs::read(inside.join("spelled.png")).unwrap(), b"same grant");
|
||||
assert!(aliased.write(&spelled.join("..").join("outside").join("climb.png").to_string_lossy(), b"no").is_err());
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
|
||||
std::fs::create_dir(inside.join("adir")).unwrap();
|
||||
assert!(workspace.write("adir", b"x").is_err());
|
||||
assert!(inside.join("adir").is_dir());
|
||||
assert!(temp_files(&inside).is_empty());
|
||||
|
||||
let long = format!("frames/{}/{}", "x".repeat(120), "y".repeat(120));
|
||||
assert!(unc.join(&long).as_os_str().len() > 260);
|
||||
let mut export = workspace.export_sequence(&long).unwrap();
|
||||
export.write("clip_0000.png", b"deep").unwrap();
|
||||
export.commit();
|
||||
drop(export);
|
||||
assert_eq!(std::fs::read(inside.join(&long).join("clip_0000.png")).unwrap(), b"deep");
|
||||
workspace.write(&format!("{long}/saved.png"), b"long save").unwrap();
|
||||
assert_eq!(std::fs::read(inside.join(&long).join("saved.png")).unwrap(), b"long save");
|
||||
assert!(temp_files(&inside.join(&long)).is_empty());
|
||||
}
|
||||
|
||||
/// `\\localhost\C$\...` for a path on drive `C:`; `None` for a path without a drive letter.
|
||||
#[cfg(windows)]
|
||||
fn loopback_unc(path: &Path) -> Option<PathBuf> {
|
||||
let mut components = path.components();
|
||||
let Some(Component::Prefix(prefix)) = components.next() else { return None };
|
||||
let drive = match prefix.kind() {
|
||||
Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => char::from(drive),
|
||||
_ => return None,
|
||||
};
|
||||
let mut unc = PathBuf::from(format!(r"\\localhost\{drive}$"));
|
||||
unc.extend(components.filter(|component| matches!(component, Component::Normal(_))));
|
||||
Some(unc)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filesystem_commands_fail_closed() {
|
||||
for id in [
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use photocraft_automation::security::authentication_reply;
|
||||
use photocraft_automation::security::{AuthStep, ServerHandshake};
|
||||
use photocraft_automation::{AutomationError, BridgeClient};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
const CONTROL_TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
@@ -68,15 +68,28 @@ async fn fake_server(
|
||||
addr
|
||||
}
|
||||
|
||||
/// Authenticate one connection: read the auth line, reply to it.
|
||||
/// Authenticate one connection.
|
||||
async fn authenticate(socket: &mut TcpStream) {
|
||||
let (read, mut write) = socket.split();
|
||||
let mut reader = BufReader::new(read);
|
||||
serve_handshake(&mut BufReader::new(read), &mut write).await;
|
||||
}
|
||||
|
||||
/// The server side of one connection's authentication, as the real control servers run it: the
|
||||
/// bridge's challenge (or a one-frame token), answered frame by frame until it authenticates.
|
||||
pub(crate) async fn serve_handshake(reader: &mut (impl AsyncBufRead + Unpin), writer: &mut (impl AsyncWrite + Unpin)) {
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).await.unwrap();
|
||||
let (auth, ok) = authentication_reply(&line, CONTROL_TOKEN);
|
||||
assert!(ok, "each connection must authenticate");
|
||||
write.write_all(format!("{auth}\n").as_bytes()).await.unwrap();
|
||||
loop {
|
||||
line.clear();
|
||||
reader.read_line(&mut line).await.unwrap();
|
||||
let (reply, step) = handshake.reply(&line, CONTROL_TOKEN);
|
||||
writer.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
match step {
|
||||
AuthStep::Authenticated => return,
|
||||
AuthStep::Challenged => {}
|
||||
AuthStep::Rejected => panic!("each connection must authenticate: {reply}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! NV-6: the bridge never reveals the control token to whatever holds the port. It connects to
|
||||
//! the literal loopback address the app binds (never a `localhost` lookup that may reach a
|
||||
//! `[::1]` listener), and the server must prove it holds the token before the client sends its
|
||||
//! own proof; the token itself never crosses the wire.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use photocraft_automation::{BridgeClient, Headless};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
const CONTROL_TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// How a listener that is not the app answers the frames it receives.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Impostor {
|
||||
/// Accepts and reads, never answers.
|
||||
Silent,
|
||||
/// Refuses every frame, as a server without challenge authentication does.
|
||||
Refuses,
|
||||
/// Answers the challenge with a made-up nonce and proof.
|
||||
FakesTheChallenge,
|
||||
}
|
||||
|
||||
/// Accept one connection on `listener` and return every line it received (until the client
|
||||
/// closes or goes quiet), answering as `kind`.
|
||||
async fn impostor(listener: TcpListener, kind: Impostor) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
let Ok(Ok((socket, _))) = tokio::time::timeout(Duration::from_secs(3), listener.accept()).await else {
|
||||
return lines;
|
||||
};
|
||||
let (read, mut write) = socket.into_split();
|
||||
let mut reader = BufReader::new(read);
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
match tokio::time::timeout(Duration::from_secs(3), reader.read_line(&mut line)).await {
|
||||
Ok(Ok(n)) if n > 0 => {}
|
||||
_ => return lines,
|
||||
}
|
||||
let id = serde_json::from_str::<Value>(&line).map(|v| v["id"].clone()).unwrap_or(Value::Null);
|
||||
lines.push(line);
|
||||
let reply = match kind {
|
||||
Impostor::Silent => continue,
|
||||
Impostor::Refuses => json!({"id": id, "ok": false, "error": "authentication required"}),
|
||||
Impostor::FakesTheChallenge => json!({"id": id, "ok": true, "result": {"serverNonce": "ab".repeat(32), "serverProof": "cd".repeat(32)}}),
|
||||
};
|
||||
if write.write_all(format!("{reply}\n").as_bytes()).await.is_err() {
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Call through a bridge to `addr` while `listener` plays `kind`; the lines it got, and the
|
||||
/// call's error.
|
||||
async fn call_impostor(addr: &str, listener: TcpListener, kind: Impostor) -> (Vec<String>, String) {
|
||||
let bridge = BridgeClient::new(addr, CONTROL_TOKEN).unwrap().with_timeout(Duration::from_secs(2));
|
||||
let call = tokio::spawn(async move { bridge.call("methods", json!({})).await });
|
||||
let lines = impostor(listener, kind).await;
|
||||
let error = match tokio::time::timeout(Duration::from_secs(10), call).await {
|
||||
Ok(Ok(Err(e))) => e.to_string(),
|
||||
other => format!("no error: {other:?}"),
|
||||
};
|
||||
(lines, error)
|
||||
}
|
||||
|
||||
/// Fail if any line a listener received contains the control token.
|
||||
fn assert_token_withheld(lines: &[String]) {
|
||||
for line in lines {
|
||||
assert!(!line.contains(CONTROL_TOKEN), "the control token reached a listener that is not the app: {line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `localhost` is the 127.0.0.1 the app binds: a process listening on `[::1]` at the app's port
|
||||
/// gets no connection, and the app does.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn localhost_reaches_the_ipv4_app_not_an_ipv6_listener() {
|
||||
let app = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
app.set_nonblocking(true).unwrap();
|
||||
let port = app.local_addr().unwrap().port();
|
||||
let Ok(other) = TcpListener::bind(format!("[::1]:{port}")).await else {
|
||||
eprintln!("skipped: IPv6 loopback unavailable");
|
||||
return;
|
||||
};
|
||||
let bridge = BridgeClient::new(format!("localhost:{port}"), CONTROL_TOKEN).unwrap().with_timeout(Duration::from_secs(1));
|
||||
let call = tokio::spawn(async move { bridge.call("methods", json!({})).await });
|
||||
let lines = impostor(other, Impostor::Silent).await;
|
||||
call.abort();
|
||||
assert!(lines.is_empty(), "the [::1] listener was reached: {lines:?}");
|
||||
assert!(app.accept().is_ok(), "the app on 127.0.0.1 got the connection");
|
||||
}
|
||||
|
||||
/// Whoever holds the port, on either loopback, and however it answers, never receives the
|
||||
/// token: the client sends only its challenge and stops when the listener cannot prove it holds
|
||||
/// the token.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_listener_that_is_not_the_app_never_receives_the_token() {
|
||||
for (kind, expected) in [
|
||||
(Impostor::Silent, "the request was not sent"),
|
||||
(Impostor::Refuses, "refused challenge authentication"),
|
||||
(Impostor::FakesTheChallenge, "did not prove it holds this control token"),
|
||||
] {
|
||||
let mut hosts = vec!["127.0.0.1"];
|
||||
if TcpListener::bind("[::1]:0").await.is_ok() {
|
||||
hosts.push("[::1]");
|
||||
}
|
||||
for host in hosts {
|
||||
let listener = TcpListener::bind(format!("{host}:0")).await.unwrap();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
let (lines, error) = call_impostor(&addr, listener, kind).await;
|
||||
assert_token_withheld(&lines);
|
||||
assert_eq!(lines.len(), 1, "{addr}: only the challenge was sent: {lines:?}");
|
||||
assert!(lines[0].contains("auth.challenge"), "{addr}: {lines:?}");
|
||||
assert!(error.contains(expected), "{addr}: {error}");
|
||||
if !matches!(kind, Impostor::Silent) {
|
||||
assert!(error.contains("the control token was not sent"), "{addr}: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bridge authenticates to the headless `photocraft-cli serve` server by challenge.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_authenticates_to_the_headless_server_by_challenge() {
|
||||
let headless = Arc::new(Mutex::new(Headless::new()));
|
||||
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = photocraft_automation::rpc::serve_tcp("127.0.0.1:0", headless, CONTROL_TOKEN.to_owned(), move |addr| {
|
||||
let _ = ready_tx.send(addr);
|
||||
});
|
||||
});
|
||||
let addr = ready_rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
let bridge = BridgeClient::new(addr.to_string(), CONTROL_TOKEN).unwrap().with_timeout(Duration::from_secs(5));
|
||||
let methods = bridge.call("methods", json!({})).await.unwrap();
|
||||
assert!(methods.as_array().unwrap().iter().any(|m| m == "batch"), "{methods}");
|
||||
// A second bridge with another token is refused before anything derived from its token is sent.
|
||||
let other = BridgeClient::new(addr.to_string(), "f".repeat(64)).unwrap().with_timeout(Duration::from_secs(5));
|
||||
let error = other.call("methods", json!({})).await.unwrap_err().to_string();
|
||||
assert!(error.contains("did not prove it holds this control token"), "{error}");
|
||||
}
|
||||
@@ -4,6 +4,7 @@ mod agent_tasks;
|
||||
mod agent_tasks_extended;
|
||||
mod agent_tasks_more;
|
||||
mod bridge;
|
||||
mod bridge_token;
|
||||
mod gpu_backend;
|
||||
mod inactive_save;
|
||||
mod krita;
|
||||
|
||||
@@ -577,6 +577,8 @@ async fn bridge_doc_save_forwards_maximize_compatibility() {
|
||||
app.abort();
|
||||
}
|
||||
|
||||
/// An oversized app reply drops the connection with a budget error and never retries the
|
||||
/// operation on a fresh, authenticated connection.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bridge_response_budget_drops_connection_without_retrying_the_operation() {
|
||||
use photocraft_automation::{BridgeClient, budgets::MAX_RESPONSE_BYTES};
|
||||
@@ -586,13 +588,9 @@ async fn bridge_response_budget_drops_connection_without_retrying_the_operation(
|
||||
let (sock, _) = listener.accept().await.unwrap();
|
||||
let (read, mut write) = sock.into_split();
|
||||
let mut reader = BufReader::new(read);
|
||||
crate::bridge::serve_handshake(&mut reader, &mut write).await;
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).await.unwrap();
|
||||
let auth: Value = serde_json::from_str(&line).unwrap();
|
||||
let reply = json!({"id": auth["id"], "ok": true, "result": {"authenticated": true}});
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).await.unwrap();
|
||||
let request: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(request["method"], "engine.execute");
|
||||
let mut oversized = vec![b'x'; MAX_RESPONSE_BYTES];
|
||||
@@ -1068,11 +1066,16 @@ async fn fake_app() -> (String, tokio::task::JoinHandle<Vec<Value>>) {
|
||||
fake_app_with_screenshot(None).await
|
||||
}
|
||||
|
||||
/// A fake app on one connection: it authenticates with the real [`ServerHandshake`], then
|
||||
/// answers the control methods the bridge tests use, returning the requests it saw.
|
||||
///
|
||||
/// [`ServerHandshake`]: photocraft_automation::security::ServerHandshake
|
||||
async fn fake_app_with_screenshot(screenshot_png: Option<Vec<u8>>) -> (String, tokio::task::JoinHandle<Vec<Value>>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
let h = tokio::spawn(async move {
|
||||
let mut seen = Vec::new();
|
||||
let mut handshake = photocraft_automation::security::ServerHandshake::new();
|
||||
let mut authenticated = false;
|
||||
let (sock, _) = listener.accept().await.unwrap();
|
||||
let (r, mut w) = sock.into_split();
|
||||
@@ -1082,12 +1085,10 @@ async fn fake_app_with_screenshot(screenshot_png: Option<Vec<u8>>) -> (String, t
|
||||
let id = req["id"].clone();
|
||||
let method = req["method"].as_str().unwrap_or("").to_owned();
|
||||
let reply = match method.as_str() {
|
||||
"auth" if req["params"]["token"] == CONTROL_TOKEN => {
|
||||
authenticated = true;
|
||||
json!({"id": id, "ok": true, "result": {"authenticated": true}})
|
||||
}
|
||||
_ if !authenticated => {
|
||||
json!({"id": id, "ok": false, "error": "authentication required"})
|
||||
let (reply, step) = handshake.reply(&line, CONTROL_TOKEN);
|
||||
authenticated = step == photocraft_automation::security::AuthStep::Authenticated;
|
||||
reply
|
||||
}
|
||||
"ui.inspect" => {
|
||||
json!({"id": id, "ok": true, "result": {"tool": "brush", "panels": ["layers"]}})
|
||||
@@ -1148,6 +1149,8 @@ async fn bridge_forwards_to_control_protocol() {
|
||||
app.abort();
|
||||
}
|
||||
|
||||
/// #1007: an edit whose reply is lost is not resent, and the next call reconnects and
|
||||
/// authenticates again.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bridge_lost_reply_does_not_replay_an_edit_and_next_call_reconnects() {
|
||||
use photocraft_automation::{BridgeClient, Headless};
|
||||
@@ -1166,13 +1169,9 @@ async fn bridge_lost_reply_does_not_replay_an_edit_and_next_call_reconnects() {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let (read, mut write) = socket.into_split();
|
||||
let mut reader = BufReader::new(read);
|
||||
crate::bridge::serve_handshake(&mut reader, &mut write).await;
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).await.unwrap();
|
||||
let (auth, authenticated) = photocraft_automation::security::authentication_reply(&line, CONTROL_TOKEN);
|
||||
assert!(authenticated, "each connection must authenticate");
|
||||
write.write_all(format!("{auth}\n").as_bytes()).await.unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).await.unwrap();
|
||||
let request: Value = serde_json::from_str(&line).unwrap();
|
||||
seen.push(request["params"]["command"].as_str().unwrap().to_owned());
|
||||
let result = backend.handle(request["method"].as_str().unwrap(), request["params"].clone()).unwrap();
|
||||
@@ -1321,6 +1320,7 @@ fn bridge_rejects_non_loopback() {
|
||||
assert!(PhotocraftMcp::bridge("localhost:1", "short").is_err());
|
||||
}
|
||||
|
||||
/// A bridge with the wrong token stops at the app's challenge proof, before any control method.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bridge_rejects_wrong_token_before_control_methods() {
|
||||
let (addr, app) = fake_app().await;
|
||||
@@ -1328,7 +1328,8 @@ async fn bridge_rejects_wrong_token_before_control_methods() {
|
||||
let client = connect(PhotocraftMcp::bridge(&addr, wrong).unwrap()).await;
|
||||
let r = call(&client, "ui_inspect", json!({})).await;
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
assert!(text(&r).contains("authentication required"), "{}", text(&r));
|
||||
// The app's challenge proof does not match the client's token, so nothing more is sent.
|
||||
assert!(text(&r).contains("did not prove it holds this control token"), "{}", text(&r));
|
||||
client.cancel().await.unwrap();
|
||||
app.abort();
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use photocraft_automation::security::authentication_reply;
|
||||
use photocraft_automation::security::{AuthStep, ServerHandshake};
|
||||
use photocraft_automation::{Backend, BridgeClient, PhotocraftMcp};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, Lines};
|
||||
@@ -183,7 +183,27 @@ struct FakeApp {
|
||||
log: Vec<Value>,
|
||||
}
|
||||
|
||||
/// Answer the bridge's challenge authentication on one fake-app connection, frame by frame, as
|
||||
/// the real control servers do. Returns whether the connection authenticated.
|
||||
async fn authenticate<R, W>(lines: &mut Lines<R>, write: &mut W) -> bool
|
||||
where
|
||||
R: tokio::io::AsyncBufRead + Unpin,
|
||||
W: tokio::io::AsyncWrite + Unpin,
|
||||
{
|
||||
let mut handshake = ServerHandshake::new();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
let (reply, step) = handshake.reply(&line, TOKEN);
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
if step != AuthStep::Challenged {
|
||||
return step == AuthStep::Authenticated;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
impl FakeApp {
|
||||
/// Listen on a fresh loopback port and serve every connection: authenticate it, then answer
|
||||
/// its requests through [`FakeApp::answer`]. Returns the address and the shared state.
|
||||
async fn serve(runs: Duration, lose_start: bool) -> (String, Arc<Mutex<FakeApp>>) {
|
||||
let app = Arc::new(Mutex::new(FakeApp {
|
||||
runs,
|
||||
@@ -203,9 +223,7 @@ impl FakeApp {
|
||||
tokio::spawn(async move {
|
||||
let (read, mut write) = socket.into_split();
|
||||
let mut lines = BufReader::new(read).lines();
|
||||
let (auth, ok) = authentication_reply(&lines.next_line().await.unwrap().unwrap(), TOKEN);
|
||||
assert!(ok, "each connection must authenticate");
|
||||
write.write_all(format!("{auth}\n").as_bytes()).await.unwrap();
|
||||
assert!(authenticate(&mut lines, &mut write).await, "each connection must authenticate");
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
let request: Value = serde_json::from_str(&line).unwrap();
|
||||
let Some((result, after)) = app.lock().unwrap().answer(&request) else { return };
|
||||
|
||||
@@ -13,10 +13,10 @@ default = []
|
||||
# AVIF *encode* via ravif (pure Rust). Decoding AVIF needs dav1d (C), so AVIF
|
||||
# stays read-unsupported and therefore asymmetric; it is off by default.
|
||||
avif = ["image/avif"]
|
||||
# HEIC/HEIF decode via the optional photocraft-heif crate (heic-rs, pure Rust). Off by default so
|
||||
# HEIC/HEIF decode via the optional craft-heif crate from craft-libs (heic-rs, pure Rust). Off by default so
|
||||
# distributors choose it at build time; official builds and CI enable it (`--features heif` on the
|
||||
# apps). Without it HEIF files are still recognised and opening one is a clear "unsupported" error.
|
||||
heif = ["dep:photocraft-heif"]
|
||||
heif = ["dep:craft-heif"]
|
||||
|
||||
[dependencies]
|
||||
thiserror.workspace = true
|
||||
@@ -35,7 +35,7 @@ jpeg-encoder = "0.6"
|
||||
craft-jpeg.workspace = true
|
||||
# Pure-Rust modular JPEG XL lossless encoder.
|
||||
zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] }
|
||||
photocraft-heif = { path = "../heif", optional = true }
|
||||
craft-heif = { workspace = true, optional = true }
|
||||
|
||||
# Orientation is applied a band of rows per task on native; wasm stays single-threaded.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
@@ -47,6 +47,8 @@ exr = { version = "1.73", default-features = false, features = ["rayon"] }
|
||||
proptest.workspace = true
|
||||
# Oracle decoders for cross-checking in tests only.
|
||||
image = { workspace = true, features = ["png", "jpeg", "tiff"] }
|
||||
# Lossless synthetic HEIC files for the `heif` feature's tests.
|
||||
craft-heif = { workspace = true, features = ["testdata"] }
|
||||
|
||||
# Independent JPEG XL decoder oracle; not linked into the application.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
|
||||
@@ -162,7 +162,7 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them
|
||||
with `CodecError::Unsupported`: they are sensor data, not flat images. `photocraft-raw` decodes
|
||||
and develops them, and `photocraft-io` routes them there.
|
||||
|
||||
* **HEIF/HEIC (read-only, feature `heif`).** Decoding lives in the optional `photocraft-heif` crate
|
||||
* **HEIF/HEIC (read-only, feature `heif`).** Decoding lives in the optional `craft-heif` crate from craft-libs
|
||||
behind the non-default `heif` feature (official PhotoCraft builds enable it; distributors choose).
|
||||
Without it, HEIF is still detected and decoding returns `CodecError::Unsupported` ("HEIC/HEIF
|
||||
support isn't included in this build"). iPhone and Mac photos decode with `heic-rs` (pure Rust, no `unsafe`):
|
||||
|
||||
@@ -219,16 +219,14 @@ fn decompress(compression: Compression, packed: &[u8], expected: usize, what: &s
|
||||
|
||||
// --- the deep chunk stream ---------------------------------------------------------------------
|
||||
|
||||
/// One parsed chunk: where its pixels go and its cumulative sample counts, plus where to
|
||||
/// find the compressed sample data in the second pass.
|
||||
/// One parsed chunk: the block it covers, plus where to find the compressed sample data in
|
||||
/// the second pass. Its pixels' sample counts live in the decode's global index, so a chunk
|
||||
/// holds no per-pixel data.
|
||||
struct DeepChunk {
|
||||
/// Global pixel indices of the block's pixels, in block order (row-major within the block).
|
||||
pixels: Vec<usize>,
|
||||
/// Pixels per row of the block (the data window width for a scan line, the clipped tile
|
||||
/// width for a tile).
|
||||
row_w: usize,
|
||||
/// Cumulative sample count table of the block: `len == pixels.len() + 1`.
|
||||
prefix: Vec<u32>,
|
||||
/// The block's rows within the data window.
|
||||
rows: std::ops::Range<usize>,
|
||||
/// The block's columns within the data window (clipped to it for an edge tile).
|
||||
cols: std::ops::Range<usize>,
|
||||
/// File offset of the chunk start.
|
||||
pos: u64,
|
||||
/// Size of the compressed sample data in the file.
|
||||
@@ -244,6 +242,15 @@ fn sample_bytes(t: ExrSample) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
/// One stored sample as f32. `b` holds [`sample_bytes`] bytes; a short slice reads as zero.
|
||||
fn sample_value(t: ExrSample, b: &[u8]) -> f32 {
|
||||
match t {
|
||||
ExrSample::F16 => b.try_into().map(|a: [u8; 2]| f16::from_le_bytes(a).to_f32()).unwrap_or(0.0),
|
||||
ExrSample::F32 => b.try_into().map(f32::from_le_bytes).unwrap_or(0.0),
|
||||
ExrSample::U32 => b.try_into().map(|a: [u8; 4]| u32::from_le_bytes(a) as f32).unwrap_or(0.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn our_sample_type(t: ExrSample) -> SampleType {
|
||||
match t {
|
||||
ExrSample::F16 => SampleType::F16,
|
||||
@@ -272,6 +279,19 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
let y0 = dw.position.1;
|
||||
let npixels = w.checked_mul(h).ok_or_else(|| err("the data window is too large"))?;
|
||||
limits.check_bytes(w as u32, h as u32, (header.channels.list.len().max(1) as u64) * 4)?;
|
||||
// The per-pixel bookkeeping is the cumulative sample-count index the result returns
|
||||
// (`DeepImage::counts`: one u64 per pixel, plus one), live from the first chunk to the end.
|
||||
// Charge it before anything is allocated; the count tables and the samples are admitted
|
||||
// against what it leaves. The data-window check above budgets only four bytes a pixel.
|
||||
let index_len = npixels.checked_add(1).ok_or_else(|| err("the data window is too large"))?;
|
||||
let index_bytes = (index_len as u64).checked_mul(8).ok_or_else(|| err("the data window is too large"))?;
|
||||
if index_bytes > limits.max_alloc {
|
||||
return Err(CodecError::LimitExceeded(format!(
|
||||
"the sample-count index of {w}x{h} deep pixels needs {index_bytes} bytes, exceeding max_alloc {}",
|
||||
limits.max_alloc
|
||||
)));
|
||||
}
|
||||
let budget = limits.max_alloc - index_bytes;
|
||||
|
||||
// The display window is the full stage the renderer composed onto (a render pass's data
|
||||
// window is often its crop). Open on the stage when it plausibly holds the data region:
|
||||
@@ -326,7 +346,14 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
}
|
||||
};
|
||||
|
||||
let mut counts = vec![0u32; npixels];
|
||||
// Each block has exactly one chunk (a duplicate or a missing one is malformed), so a table
|
||||
// of any other length is refused here, before the per-block bookkeeping is sized by the
|
||||
// header's geometry: `seen` and `chunks` stay proportional to the offset table in the file.
|
||||
if offsets.len() != slots {
|
||||
return Err(err(format!("the offset table lists {} chunks, the data window needs {slots}", offsets.len())));
|
||||
}
|
||||
// Per-pixel sample counts in `counts[p + 1]`, made cumulative after the first pass.
|
||||
let mut counts = alloc_zeroed::<u64>(index_len)?;
|
||||
let mut seen = vec![false; slots];
|
||||
let mut chunks: Vec<DeepChunk> = Vec::with_capacity(offsets.len());
|
||||
|
||||
@@ -341,17 +368,15 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
return Err(err(format!("chunk declares part {part}, expected {header_index}")));
|
||||
}
|
||||
}
|
||||
// Block coordinates → the block's pixel bounds and its slot. The per-pixel index is
|
||||
// built only after the chunk's declared payload sizes are validated below, so a
|
||||
// truncated or lying chunk cannot drive a large index allocation first.
|
||||
let (block_rows, block_cols, slot, row_w, scanline_row): (std::ops::Range<usize>, std::ops::Range<usize>, usize, usize, bool) = match &header.blocks {
|
||||
// Block coordinates → the block's pixel bounds and its slot.
|
||||
let (block_rows, block_cols, slot): (std::ops::Range<usize>, std::ops::Range<usize>, usize) = match &header.blocks {
|
||||
BlockDescription::ScanLines => {
|
||||
let y = i32(&mut cur)?;
|
||||
let row = match y.checked_sub(y0) {
|
||||
Some(d) if d >= 0 && (d as usize) < h => d as usize,
|
||||
_ => return Err(err(format!("scan line block y={y} is outside the data window"))),
|
||||
};
|
||||
(row..row + 1, 0..w, row, w, true)
|
||||
(row..row + 1, 0..w, row)
|
||||
}
|
||||
BlockDescription::Tiles(_) => {
|
||||
let (tx, ty, lx, ly) = (i32(&mut cur)?, i32(&mut cur)?, i32(&mut cur)?, i32(&mut cur)?);
|
||||
@@ -365,7 +390,7 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
let rows = (by + tile_h).min(h);
|
||||
let cols = (bx + tile_w).min(w);
|
||||
let slot = (ty as usize).saturating_mul(tiles_x) + tx as usize;
|
||||
(by..rows, bx..cols, slot, cols - bx, false)
|
||||
(by..rows, bx..cols, slot)
|
||||
}
|
||||
};
|
||||
let block_len = block_rows.len().saturating_mul(block_cols.len());
|
||||
@@ -383,31 +408,18 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
if packed_table > remaining || packed_data > remaining.saturating_sub(packed_table) {
|
||||
return Err(err("deep chunk sizes point past the end of the file"));
|
||||
}
|
||||
// The chunk's payload is present; now materialize the block's global pixel index. For
|
||||
// scan lines this is one row; for tiles the clipped tile rectangle.
|
||||
let block_pixels: Vec<usize> = if scanline_row {
|
||||
let row = block_rows.start;
|
||||
(0..w).map(|x| row * w + x).collect()
|
||||
} else {
|
||||
let mut px = Vec::with_capacity(block_len);
|
||||
for yy in block_rows.clone() {
|
||||
for xx in block_cols.clone() {
|
||||
px.push(yy.saturating_mul(w).saturating_add(xx));
|
||||
}
|
||||
}
|
||||
px
|
||||
};
|
||||
let what = "the sample-count table";
|
||||
let table_bytes = read_exact(&mut cur, packed_table as usize, what)?;
|
||||
let expected_table = block_pixels.len().checked_mul(4).ok_or_else(|| err("count table overflows"))?;
|
||||
let expected_table = block_len.checked_mul(4).ok_or_else(|| err("count table overflows"))?;
|
||||
// A compressed clipped table also needs its scratch copy. The data-window check only
|
||||
// budgets four bytes per channel per pixel, insufficient for a one-channel image.
|
||||
// An equal-sized payload takes decompress's raw path, which allocates no scratch.
|
||||
// Both are admitted against what the sample-count index leaves of `max_alloc`.
|
||||
let buffers = if table_bytes.len() == expected_table { 1 } else { 2 };
|
||||
let clipped_need = (expected_table as u64).saturating_mul(buffers);
|
||||
if clipped_need > limits.max_alloc {
|
||||
if clipped_need > budget {
|
||||
return Err(CodecError::LimitExceeded(format!(
|
||||
"{what} needs {clipped_need} bytes including decompression scratch, exceeding max_alloc {}",
|
||||
"{what} needs {clipped_need} bytes including decompression scratch, on top of the {index_bytes} byte sample-count index, exceeding max_alloc {}",
|
||||
limits.max_alloc
|
||||
)));
|
||||
}
|
||||
@@ -420,75 +432,73 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
let raw = match full_table {
|
||||
// Scan lines and interior tiles: the full size is the clipped size.
|
||||
Some(full) if full <= expected_table => decompress(compression, table_bytes, expected_table, what)?,
|
||||
Some(full) if (full as u64).saturating_mul(2) <= limits.max_alloc => {
|
||||
Some(full) if (full as u64).saturating_mul(2) <= budget => {
|
||||
decompress(compression, table_bytes, full, what).or_else(|_| decompress(compression, table_bytes, expected_table, what))?
|
||||
}
|
||||
_ => decompress(compression, table_bytes, expected_table, what).map_err(|_| {
|
||||
// Four bytes per pixel of the tile, twice: the table and its scratch copy.
|
||||
let need = (tile_w as u64).saturating_mul(tile_h as u64).saturating_mul(8);
|
||||
CodecError::LimitExceeded(format!(
|
||||
"{what} of a {tile_w}x{tile_h} deep tile does not decode at the clipped size, and at the full tile size it needs {need} bytes with its scratch copy, exceeding max_alloc {}",
|
||||
"{what} of a {tile_w}x{tile_h} deep tile does not decode at the clipped size, and at the full tile size it needs {need} bytes with its scratch copy, on top of the {index_bytes} byte sample-count index, exceeding max_alloc {}",
|
||||
limits.max_alloc
|
||||
))
|
||||
})?,
|
||||
};
|
||||
|
||||
// The table is cumulative within each row of the block (a tile restarts at every row);
|
||||
// `prefix` is cumulative over the whole block, and each pixel's own count is the difference.
|
||||
let mut prefix = Vec::with_capacity(block_pixels.len() + 1);
|
||||
prefix.push(0u32);
|
||||
let (mut row_base, mut prev) = (0u32, 0u32);
|
||||
for (i, p) in block_pixels.iter().enumerate() {
|
||||
let b: [u8; 4] = raw.get(i * 4..i * 4 + 4).and_then(|s| s.try_into().ok()).ok_or_else(|| err("the count table is short"))?;
|
||||
let v = u32::from_le_bytes(b);
|
||||
if row_w > 0 && i % row_w == 0 {
|
||||
row_base = row_base.checked_add(prev).ok_or_else(|| err("the block's sample count overflows"))?;
|
||||
prev = 0;
|
||||
// each pixel's own count is the difference to its left neighbour's entry.
|
||||
let mut entries = raw.as_chunks::<4>().0.iter();
|
||||
let mut total = 0u64;
|
||||
for yy in block_rows.clone() {
|
||||
let mut prev = 0u32;
|
||||
for xx in block_cols.clone() {
|
||||
let v = u32::from_le_bytes(*entries.next().ok_or_else(|| err("the count table is short"))?);
|
||||
if v < prev {
|
||||
return Err(err("the sample-count table decreases (malformed cumulative counts)"));
|
||||
}
|
||||
let p = yy.saturating_mul(w).saturating_add(xx).saturating_add(1);
|
||||
if let Some(c) = counts.get_mut(p) {
|
||||
*c = u64::from(v - prev);
|
||||
}
|
||||
prev = v;
|
||||
}
|
||||
if v < prev {
|
||||
return Err(err("the sample-count table decreases (malformed cumulative counts)"));
|
||||
}
|
||||
if let Some(c) = counts.get_mut(*p) {
|
||||
*c = v - prev;
|
||||
}
|
||||
prev = v;
|
||||
prefix.push(row_base.checked_add(v).ok_or_else(|| err("the block's sample count overflows"))?);
|
||||
total = total.checked_add(u64::from(prev)).ok_or_else(|| err("the block's sample count overflows"))?;
|
||||
}
|
||||
let total = prefix.last().copied().unwrap_or(0) as u64;
|
||||
let expected_data = total.checked_mul(bytes_per_sample as u64).ok_or_else(|| err("the sample data size overflows"))?;
|
||||
if expected_data != unpacked_data {
|
||||
return Err(err(format!("the chunk declares {unpacked_data} bytes of sample data, the count table implies {expected_data}")));
|
||||
}
|
||||
chunks.push(DeepChunk { pixels: block_pixels, row_w, prefix, pos: off, packed_data, unpacked_data });
|
||||
chunks.push(DeepChunk { rows: block_rows, cols: block_cols, pos: off, packed_data, unpacked_data });
|
||||
}
|
||||
if seen.iter().any(|s| !s) {
|
||||
let missing = seen.iter().filter(|s| !**s).count();
|
||||
return Err(err(format!("{missing} of {slots} chunks are missing from the offset table")));
|
||||
}
|
||||
|
||||
// Global cumulative counts in raster order.
|
||||
let mut deep_counts = Vec::with_capacity(npixels + 1);
|
||||
deep_counts.push(0u64);
|
||||
// Global cumulative counts in raster order, in place: pixel `p` holds the samples
|
||||
// `counts[p]..counts[p + 1]`.
|
||||
let mut acc = 0u64;
|
||||
for &c in &counts {
|
||||
acc = acc.checked_add(c as u64).ok_or_else(|| err("the total sample count overflows"))?;
|
||||
deep_counts.push(acc);
|
||||
for c in counts.iter_mut() {
|
||||
acc = acc.checked_add(*c).ok_or_else(|| err("the total sample count overflows"))?;
|
||||
*c = acc;
|
||||
}
|
||||
let total_samples = acc;
|
||||
let sample_bytes_total = total_samples.checked_mul(exr_types.len() as u64 * 4).ok_or_else(|| err("the sample buffer size overflows"))?;
|
||||
if sample_bytes_total > limits.max_alloc {
|
||||
return Err(CodecError::LimitExceeded(format!("deep samples need {sample_bytes_total} bytes, exceeding max_alloc {}", limits.max_alloc)));
|
||||
if sample_bytes_total > budget {
|
||||
return Err(CodecError::LimitExceeded(format!(
|
||||
"deep samples need {sample_bytes_total} bytes on top of the {index_bytes} byte sample-count index, exceeding max_alloc {}",
|
||||
limits.max_alloc
|
||||
)));
|
||||
}
|
||||
let total_samples = usize::try_from(total_samples).map_err(|_| CodecError::LimitExceeded(format!("{total_samples} deep samples do not fit in memory")))?;
|
||||
|
||||
let mut channels: Vec<DeepChannel> = Vec::with_capacity(header.channels.list.len());
|
||||
for c in &header.channels.list {
|
||||
channels.push(DeepChannel { name: c.name.to_string(), sample: our_sample_type(c.sample_type), samples: alloc_zeroed::<f32>(total_samples)? });
|
||||
}
|
||||
|
||||
let mut channels: Vec<DeepChannel> = header
|
||||
.channels
|
||||
.list
|
||||
.iter()
|
||||
.map(|c| DeepChannel { name: c.name.to_string(), sample: our_sample_type(c.sample_type), samples: vec![0f32; total_samples as usize] })
|
||||
.collect();
|
||||
|
||||
// Second pass: the compressed sample data, scattered per pixel (a block's channel data
|
||||
// is contiguous in the file but the pixels' samples interleave with other blocks').
|
||||
// Second pass: the compressed sample data, placed row by row (a block's channel data is
|
||||
// contiguous in the file, but a tile's rows interleave with other tiles' in raster order).
|
||||
for chunk in &chunks {
|
||||
seek_to(&mut cur, chunk.pos)?;
|
||||
if multipart {
|
||||
@@ -510,43 +520,32 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
let data_bytes = read_exact(&mut cur, chunk.packed_data as usize, "the deep sample data")?;
|
||||
let raw = decompress(compression, data_bytes, chunk.unpacked_data as usize, "the deep sample data")?;
|
||||
// Row by row (a scan line block is one row), and within a row channel by channel, as
|
||||
// flat tiles are laid out: each pixel's samples are contiguous within its channel.
|
||||
// flat tiles are laid out: each pixel's samples are contiguous within its channel. A
|
||||
// block row is a run of consecutive pixels in raster order, so its samples are the
|
||||
// contiguous range `counts[first]..counts[last + 1]` of every output channel.
|
||||
let mut in_off = 0usize;
|
||||
let row_w = chunk.row_w.max(1);
|
||||
for (r, row) in chunk.pixels.chunks(row_w).enumerate() {
|
||||
let i0 = r * row_w;
|
||||
let row_from = chunk.prefix.get(i0).copied().unwrap_or(0) as usize;
|
||||
let row_to = chunk.prefix.get(i0 + row.len()).copied().unwrap_or(0) as usize;
|
||||
let row_total = row_to.saturating_sub(row_from);
|
||||
for yy in chunk.rows.clone() {
|
||||
let first = yy.saturating_mul(w).saturating_add(chunk.cols.start);
|
||||
let end = yy.saturating_mul(w).saturating_add(chunk.cols.end);
|
||||
let index = |p: usize| counts.get(p).copied().and_then(|c| usize::try_from(c).ok()).ok_or_else(|| err("pixel index out of range"));
|
||||
let (row_from, row_to) = (index(first)?, index(end)?);
|
||||
let row_total = row_to.checked_sub(row_from).ok_or_else(|| err("the sample-count index decreases"))?;
|
||||
for (ci, t) in exr_types.iter().enumerate() {
|
||||
let sb = sample_bytes(*t);
|
||||
let ch_bytes = row_total.checked_mul(sb).ok_or_else(|| err("channel size overflows"))?;
|
||||
let end = in_off.checked_add(ch_bytes).ok_or_else(|| err("channel size overflows"))?;
|
||||
let src = raw.get(in_off..end).ok_or_else(|| err("the sample data is short"))?;
|
||||
in_off = end;
|
||||
let stop = in_off.checked_add(ch_bytes).ok_or_else(|| err("channel size overflows"))?;
|
||||
let src = raw.get(in_off..stop).ok_or_else(|| err("the sample data is short"))?;
|
||||
in_off = stop;
|
||||
let out = channels.get_mut(ci).ok_or_else(|| err("channel index out of range"))?;
|
||||
for (j, p) in row.iter().enumerate() {
|
||||
let from = (chunk.prefix.get(i0 + j).copied().unwrap_or(0) as usize).saturating_sub(row_from);
|
||||
let n = (chunk.prefix.get(i0 + j + 1).copied().unwrap_or(0) as usize).saturating_sub(row_from).saturating_sub(from);
|
||||
let to = deep_counts.get(*p).copied().unwrap_or(0) as usize;
|
||||
for k in 0..n {
|
||||
let base = (from + k) * sb;
|
||||
let v = match t {
|
||||
ExrSample::F16 => src.get(base..base + 2).map(|b| f16::from_le_bytes([b[0], b[1]]).to_f32()),
|
||||
ExrSample::F32 => src.get(base..base + 4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])),
|
||||
ExrSample::U32 => src.get(base..base + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f32),
|
||||
};
|
||||
let (Some(v), Some(slot)) = (v, out.samples.get_mut(to + k)) else {
|
||||
return Err(err("the sample data is short"));
|
||||
};
|
||||
*slot = v;
|
||||
}
|
||||
let dst = out.samples.get_mut(row_from..row_to).ok_or_else(|| err("the sample data is short"))?;
|
||||
for (slot, b) in dst.iter_mut().zip(src.chunks_exact(sb)) {
|
||||
*slot = sample_value(*t, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(DeepImage { width: w as u32, height: h as u32, stage, origin, channels, counts: deep_counts })
|
||||
Ok(DeepImage { width: w as u32, height: h as u32, stage, origin, channels, counts })
|
||||
}
|
||||
|
||||
/// Where the headers end and the offset tables begin. [`MetaData::read_from_buffered`]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! HEIF / HEIC (the iPhone and Mac photo format), read-only: see [`crate::ASYMMETRIC_EXCEPTIONS`].
|
||||
//!
|
||||
//! Decoding lives in the optional `photocraft-heif` crate (heic-rs, a pure-Rust HEVC
|
||||
//! Decoding lives in the optional `craft-heif` crate from craft-libs (heic-rs, a pure-Rust HEVC
|
||||
//! still-picture decoder), enabled by this crate's `heif` feature. Without it, HEIF files are
|
||||
//! still detected and opening one is an [`CodecError::Unsupported`] error, never a panic.
|
||||
//!
|
||||
@@ -26,11 +26,11 @@ pub(crate) fn decode(_bytes: &[u8], _limits: &Limits, _keep_orientation: bool) -
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
fn err(e: photocraft_heif::Error) -> CodecError {
|
||||
fn err(e: craft_heif::Error) -> CodecError {
|
||||
match e {
|
||||
photocraft_heif::Error::Unsupported(what) => CodecError::unsupported(F, what),
|
||||
photocraft_heif::Error::Limit(what) => CodecError::LimitExceeded(what),
|
||||
photocraft_heif::Error::Malformed(what) => CodecError::malformed(F, what),
|
||||
craft_heif::Error::Unsupported(what) => CodecError::unsupported(F, what),
|
||||
craft_heif::Error::Limit(what) => CodecError::LimitExceeded(what),
|
||||
craft_heif::Error::Malformed(what) => CodecError::malformed(F, what),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,26 +40,45 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits, keep_orientation: bool) -> R
|
||||
use crate::image::{ChannelLayout, Metadata, SampleType};
|
||||
|
||||
// The container alone: the declared size is checked before any pixel is decoded.
|
||||
let info = photocraft_heif::probe(bytes).map_err(err)?;
|
||||
let info = craft_heif::probe(bytes).map_err(err)?;
|
||||
let layout = if info.has_alpha { ChannelLayout::Rgba } else { ChannelLayout::Rgb };
|
||||
let sample = if info.sixteen_bit { SampleType::U16 } else { SampleType::U8 };
|
||||
let sample = if info.bit_depth > 8 { SampleType::U16 } else { SampleType::U8 };
|
||||
let (w, h) = if keep_orientation { (info.coded_width, info.coded_height) } else { (info.width, info.height) };
|
||||
limits.check(w, h, layout, sample)?;
|
||||
// craft-heif hands back 16-bit samples at any depth, and that buffer is still live while the
|
||||
// output copy below is built, so the peak is both of them, not the output alone.
|
||||
let peak = (layout.channels() * (2 + sample.bytes())) as u64;
|
||||
limits.check_bytes(w, h, peak)?;
|
||||
// The delegated decoder allocates the full coded image before applying any clean-aperture
|
||||
// crop or orientation transform, so the coded dimensions must pass the limit policy even
|
||||
// when the displayed (transformed) size is small. Checking only the transformed size let a
|
||||
// tiny visible image hide a large coded allocation.
|
||||
if !keep_orientation && (info.coded_width, info.coded_height) != (w, h) {
|
||||
limits.check(info.coded_width, info.coded_height, layout, sample)?;
|
||||
limits.check_bytes(info.coded_width, info.coded_height, peak)?;
|
||||
}
|
||||
let options = photocraft_heif::Options { max_pixels: limits.max_pixels, apply_transforms: !keep_orientation };
|
||||
let decoded = photocraft_heif::decode(bytes, &options).map_err(err)?;
|
||||
// Photoshop on macOS opens HEIC through Apple's decoder, so match its chroma upsampling.
|
||||
// A grid's payload can declare a larger canvas than the `ispe` probed above. craft-heif holds
|
||||
// the canvas it really decodes to `max_pixels`, so `max_alloc` is passed down as pixels too.
|
||||
let max_pixels = limits.max_pixels.min(limits.max_alloc / peak);
|
||||
let options = craft_heif::Options { max_pixels, apply_transforms: !keep_orientation, chroma: craft_heif::Chroma::Apple };
|
||||
let mut decoded = craft_heif::decode(bytes, &options).map_err(err)?;
|
||||
// The decoder re-reads the container; trust its output's shape, not the probe's.
|
||||
let layout = if decoded.has_alpha { ChannelLayout::Rgba } else { ChannelLayout::Rgb };
|
||||
let sample = if decoded.sixteen_bit { SampleType::U16 } else { SampleType::U8 };
|
||||
let mut img = Image::from_raw(decoded.width, decoded.height, layout, sample, decoded.data)?;
|
||||
// The decoder returns full-scale 16-bit samples at any coded depth; an 8-bit file stays 8-bit.
|
||||
// Taken, so the decoder's buffer is freed here and not held through the HDR conversion below.
|
||||
let raw = std::mem::take(&mut decoded.data);
|
||||
let (sample, data) = if decoded.bit_depth > 8 {
|
||||
(SampleType::U16, raw.iter().flat_map(|v| v.to_ne_bytes()).collect())
|
||||
} else {
|
||||
(SampleType::U8, raw.iter().map(|&v| ((u32::from(v) * 255 + 32767) / 65535) as u8).collect())
|
||||
};
|
||||
drop(raw);
|
||||
let mut img = Image::from_raw(decoded.width, decoded.height, layout, sample, data)?;
|
||||
img.icc = decoded.icc;
|
||||
img.cicp = decoded.nclx.map(|n| Cicp { primaries: n.primaries, transfer: n.transfer, matrix: n.matrix, full_range: n.full_range });
|
||||
// `colour` is always filled in (nclx, else the HEVC VUI, else H.273's "unspecified" 2s); only a
|
||||
// specified one tags the image, so a file that says nothing still opens untagged.
|
||||
let c = decoded.colour;
|
||||
img.cicp =
|
||||
(c.primaries != 2 || c.transfer != 2).then_some(Cicp { primaries: c.primaries, transfer: c.transfer, matrix: c.matrix, full_range: c.full_range });
|
||||
img.meta = Metadata {
|
||||
exif: decoded.exif.map(|e| if keep_orientation { e } else { crate::orientation::upright_exif(&e).into_owned() }),
|
||||
xmp: decoded.xmp.map(|x| if keep_orientation { x } else { crate::orientation::upright_xmp(&x).into_owned() }),
|
||||
@@ -69,7 +88,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits, keep_orientation: bool) -> R
|
||||
// ICC curve can describe those transfers, and an 8/16-bit document would clip the highlights.
|
||||
match img.cicp.filter(|c| c.is_hdr()) {
|
||||
Some(c) => {
|
||||
limits.check(decoded.width, decoded.height, layout, SampleType::F32)?;
|
||||
// `linearize` holds the 16-bit image, its float copy and the float output at once.
|
||||
let hdr_peak = (layout.channels() * (SampleType::U16.bytes() + 2 * SampleType::F32.bytes())) as u64;
|
||||
limits.check_bytes(decoded.width, decoded.height, hdr_peak)?;
|
||||
crate::cicp::linearize(img, c)
|
||||
}
|
||||
None => Ok(img),
|
||||
@@ -108,6 +129,44 @@ mod tests {
|
||||
0x00, 0x10, 0x75, 0x75, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x03, 0x08, 0x08, 0x08, 0x00, 0x03, 0x01, 0x03, 0x70, 0x00, 0xa8, 0x00,
|
||||
];
|
||||
|
||||
/// A 10-bit HLG file opens as float: the conversion holds the 16-bit image, its float copy and
|
||||
/// the float output at once, ten bytes a sample.
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn an_hdr_heic_is_checked_against_its_conversion_peak() {
|
||||
use craft_heif::testdata::{Prop, Spec, build};
|
||||
let grey = |_, _| [512u16, 512, 512];
|
||||
let mut spec = Spec::new(32, 32, &grey);
|
||||
spec.bit_depth = 10;
|
||||
spec.props = vec![Prop::Nclx(9, 18, 9, false)];
|
||||
let bytes = build(&spec);
|
||||
let peak = 32 * 32 * 3 * 10;
|
||||
let with = |max_alloc| crate::decode_with(&bytes, &crate::DecodeOptions { limits: Limits { max_alloc, ..Default::default() }, ..Default::default() });
|
||||
assert!(matches!(with(peak - 1), Err(CodecError::LimitExceeded(_))));
|
||||
assert_eq!(with(peak).unwrap().sample_type(), crate::image::SampleType::F32);
|
||||
}
|
||||
|
||||
/// A grid whose payload declares a larger canvas (64 x 64) than its `ispe` (33 x 33): the
|
||||
/// byte budget applies to the canvas that is decoded, not the one the container declares.
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn a_grid_canvas_larger_than_its_declared_size_is_held_to_max_alloc() {
|
||||
use craft_heif::testdata::{Spec, build};
|
||||
let grey = |_, _| [128u16, 128, 128];
|
||||
let mut bytes = build(&Spec::new(33, 33, &grey));
|
||||
// The grid item's payload: version, flags, rows - 1, columns - 1, output width and height.
|
||||
let at = bytes.windows(8).position(|w| w == [0, 0, 1, 1, 0, 33, 0, 33]).unwrap();
|
||||
bytes[at + 5] = 64;
|
||||
bytes[at + 7] = 64;
|
||||
let with = |max_alloc| crate::decode_with(&bytes, &crate::DecodeOptions { limits: Limits { max_alloc, ..Default::default() }, ..Default::default() });
|
||||
// Enough for the declared 33 x 33 (three bytes a sample at the peak), not for 64 x 64.
|
||||
// Refused by the decoder before it allocates the canvas, not by the size check on its output.
|
||||
match with(33 * 33 * 3 * 3) {
|
||||
Err(CodecError::LimitExceeded(m)) => assert!(m.contains("pixel limit"), "{m}"),
|
||||
r => panic!("{:?}", r.map(|i| i.dimensions())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn a_heic_rs_panic_is_a_malformed_file_error() {
|
||||
|
||||
@@ -155,6 +155,9 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
// png's lazy text get_text() inflates without consulting its allocation limit.
|
||||
// Read text separately below, without retaining compressed copies in the decoder.
|
||||
decoder.set_ignore_text_chunk(true);
|
||||
// png inflates iCCP up to the whole allocation limit, so a few kilobytes of zlib could ask
|
||||
// for gigabytes. The profile is read separately, with a cap (`read_iccp`, #8599).
|
||||
decoder.set_ignore_iccp_chunk(true);
|
||||
{
|
||||
let info = decoder.read_header_info().map_err(map_png_err)?;
|
||||
let (w, h) = info.size();
|
||||
@@ -577,6 +580,10 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
/// What the file holds besides its pixels, with what the metadata scan accepted.
|
||||
fn extras(&mut self) -> PngExtras {
|
||||
let info = self.reader.info();
|
||||
// The decoder is told to skip `iCCP` (it inflates the chunk up to the whole allocation
|
||||
// limit), so the profile is read here instead, capped at `max_alloc`: past it the image
|
||||
// opens untagged. `info.icc_profile` is None while that stands; the `or_else` keeps this
|
||||
// correct if the decoder is ever left to read the chunk itself.
|
||||
let icc = info.icc_profile.as_ref().map(|c| c.to_vec());
|
||||
let mut meta = Metadata { exif: info.exif_metadata.as_ref().map(|c| c.to_vec()), ..Default::default() };
|
||||
if let Some(d) = info.pixel_dims
|
||||
@@ -595,6 +602,7 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
warnings.push(DecodeWarning::MoreFrames { total: u32::try_from(self.images).ok() });
|
||||
}
|
||||
let orientation = meta.exif.as_deref().map_or(1, crate::orientation::exif_orientation);
|
||||
let icc = icc.or_else(|| read_iccp(self.bytes.as_ref(), self.limits.max_alloc));
|
||||
PngExtras { icc, meta, warnings, orientation }
|
||||
}
|
||||
|
||||
@@ -633,6 +641,9 @@ pub(crate) fn has_additional_images(bytes: &[u8]) -> Result<bool, CodecError> {
|
||||
let limits = Limits::default();
|
||||
let mut decoder = png::Decoder::new_with_limits(Cursor::new(bytes), png::Limits { bytes: limits.alloc_usize() });
|
||||
decoder.set_ignore_text_chunk(true);
|
||||
// png inflates iCCP up to the whole allocation limit, so a few kilobytes of zlib could ask
|
||||
// for gigabytes. The profile is read separately, with a cap (`read_iccp`, #8599).
|
||||
decoder.set_ignore_iccp_chunk(true);
|
||||
let reader = decoder.read_info().map_err(map_png_err)?;
|
||||
let info = reader.info();
|
||||
Ok(info.animation_control.is_some_and(|a| u64::from(a.num_frames) + u64::from(info.frame_control.is_none()) > 1))
|
||||
@@ -688,6 +699,9 @@ pub struct PngPalette {
|
||||
pub fn palette(bytes: &[u8]) -> Result<Option<PngPalette>, CodecError> {
|
||||
let mut decoder = png::Decoder::new_with_limits(Cursor::new(bytes), png::Limits::default());
|
||||
decoder.set_ignore_text_chunk(true);
|
||||
// png inflates iCCP up to the whole allocation limit, so a few kilobytes of zlib could ask
|
||||
// for gigabytes. The profile is read separately, with a cap (`read_iccp`, #8599).
|
||||
decoder.set_ignore_iccp_chunk(true);
|
||||
let reader = decoder.read_info().map_err(map_png_err)?;
|
||||
let info = reader.info();
|
||||
if info.color_type != png::ColorType::Indexed {
|
||||
@@ -745,6 +759,58 @@ fn map_png_err(e: png::DecodingError) -> CodecError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Largest ICC profile a PNG's `iCCP` may inflate to: what a JPEG can carry at most (255 APP2
|
||||
/// segments of 65 519 bytes), far past any real profile. png itself inflates up to the whole
|
||||
/// allocation limit, so a few kilobytes of zlib could ask for gigabytes (#8599).
|
||||
const MAX_ICC_BYTES: u64 = 255 * 65_519;
|
||||
|
||||
/// The ICC profile of the `iCCP` chunk before the image data, inflated to at most
|
||||
/// [`MAX_ICC_BYTES`] or `max_alloc`, whichever is smaller (png kept profiles within the
|
||||
/// allocation limit too). `None` when there is none, or the first sound one has a bad name or
|
||||
/// zlib stream, or inflates past the cap: the image then opens untagged, as png left a broken
|
||||
/// profile out. A chunk whose CRC does not match is skipped and the walk goes on, because png
|
||||
/// tolerates a CRC failure in an ancillary chunk and still reports a later valid profile — a PNG
|
||||
/// carries at most one `iCCP` (spec 11.3.3.3), so this only decides what happens to a file that
|
||||
/// is already malformed, and there it answers as png does.
|
||||
fn read_iccp(bytes: &[u8], max_alloc: u64) -> Option<Vec<u8>> {
|
||||
let cap = MAX_ICC_BYTES.min(max_alloc);
|
||||
use std::io::Read;
|
||||
let mut rest = bytes.get(8..)?;
|
||||
while let Some((length, tail)) = rest.split_first_chunk::<4>() {
|
||||
let (kind, tail) = tail.split_first_chunk::<4>()?;
|
||||
let length = usize::try_from(u32::from_be_bytes(*length)).ok().filter(|l| *l <= i32::MAX as usize)?;
|
||||
let data = tail.get(..length)?;
|
||||
let (checksum, next) = tail.get(length..).and_then(<[u8]>::split_first_chunk::<4>)?;
|
||||
rest = next;
|
||||
// The profile comes before the image data (PNG spec, 5.6 chunk ordering).
|
||||
if matches!(kind, b"IDAT" | b"IEND") {
|
||||
return None;
|
||||
}
|
||||
if kind != b"iCCP" {
|
||||
continue;
|
||||
}
|
||||
let mut crc = flate2::Crc::new();
|
||||
crc.update(kind);
|
||||
crc.update(data);
|
||||
if crc.sum() != u32::from_be_bytes(*checksum) {
|
||||
// A broken chunk is skipped, not the end of the walk: png tolerates a CRC failure in
|
||||
// an ancillary chunk and still reports a later valid profile, so stopping here would
|
||||
// drop one it would have kept (measured in
|
||||
// `a_broken_iccp_crc_does_not_hide_a_later_valid_profile`, CodeRabbit on #10300).
|
||||
continue;
|
||||
}
|
||||
let (name, value) = split_nul(data)?;
|
||||
let (&0, deflated) = value.split_first()? else { return None };
|
||||
if name.is_empty() || name.len() > 79 {
|
||||
return None;
|
||||
}
|
||||
let mut profile = Vec::new();
|
||||
flate2::read::ZlibDecoder::new(deflated).take(cap.saturating_add(1)).read_to_end(&mut profile).ok()?;
|
||||
return (profile.len() as u64 <= cap).then_some(profile);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn text_limit() -> CodecError {
|
||||
CodecError::LimitExceeded("PNG decoded text metadata exceeds max_alloc".into())
|
||||
}
|
||||
@@ -2024,6 +2090,119 @@ mod streamed_tests {
|
||||
// Two of three rows.
|
||||
assert!(rows.finish().is_err());
|
||||
}
|
||||
/// #8599: an `iCCP` profile is read up to [`MAX_ICC_BYTES`]; one that inflates past it (a
|
||||
/// few kilobytes of zlib) is left out and the image still opens, untagged. A profile at the
|
||||
/// cap still comes through whole.
|
||||
#[test]
|
||||
fn an_iccp_profile_past_the_cap_is_left_out_and_the_image_opens() {
|
||||
let img = |icc: Vec<u8>| Image::from_raw(2, 2, ChannelLayout::Rgb, SampleType::U8, vec![9; 12]).unwrap().with_icc(Some(icc));
|
||||
let cap = usize::try_from(MAX_ICC_BYTES).unwrap();
|
||||
let png = crate::encode(&img(vec![0; cap + 1]), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert!(png.len() < 100_000, "the oversized profile compresses to a small chunk: {}", png.len());
|
||||
let decoded = decode(&png, &Limits::default()).unwrap();
|
||||
assert_eq!((decoded.icc.is_none(), decoded.data()), (true, &[9u8; 12][..]));
|
||||
let png = crate::encode(&img(vec![7; cap]), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(decode(&png, &Limits::default()).unwrap().icc.map(|p| p.len()), Some(cap));
|
||||
// A smaller allocation limit bounds the profile too, as it did inside png.
|
||||
let png = crate::encode(&img(vec![7; 2000]), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(read_iccp(&png, 1999), None);
|
||||
assert_eq!(read_iccp(&png, 2000).map(|p| p.len()), Some(2000));
|
||||
// CodeRabbit on #10300: through `decode`, which passes its own limit on: the profile is
|
||||
// left out and the 12 bytes of pixels still decode.
|
||||
let limits = |max_alloc| Limits { max_alloc, ..Limits::default() };
|
||||
let decoded = decode(&png, &limits(1999)).unwrap();
|
||||
assert_eq!((decoded.icc.as_deref(), decoded.data()), (None, &[9u8; 12][..]));
|
||||
assert_eq!(decode(&png, &limits(2000)).unwrap().icc.map(|p| p.len()), Some(2000));
|
||||
// And one byte under the cap comes through whole.
|
||||
let png = crate::encode(&img(vec![3; cap - 1]), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(decode(&png, &Limits::default()).unwrap().icc.map(|p| p.len()), Some(cap - 1));
|
||||
}
|
||||
|
||||
/// #8599 review: a profile of the size a real one has survives the round trip byte for byte,
|
||||
/// and a file cut off inside its `iCCP` opens untagged instead of reading past the chunk.
|
||||
#[test]
|
||||
fn a_real_sized_profile_round_trips_and_a_truncated_chunk_is_left_out() {
|
||||
// 3 KB of varied bytes, the order of magnitude of an sRGB profile, so it neither
|
||||
// compresses to nothing nor hits any cap.
|
||||
let profile: Vec<u8> = (0..3072u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
|
||||
let img = Image::from_raw(2, 2, ChannelLayout::Rgb, SampleType::U8, vec![9; 12]).unwrap().with_icc(Some(profile.clone()));
|
||||
let png = crate::encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let decoded = decode(&png, &Limits::default()).unwrap();
|
||||
assert_eq!(decoded.icc.as_deref(), Some(&profile[..]), "the profile comes back byte for byte");
|
||||
assert_eq!(decoded.data(), &[9u8; 12][..]);
|
||||
// Cut the file inside the iCCP chunk: the walk runs out of bytes and reads no profile.
|
||||
// (A cut after the chunk still reads it, which is why these all land inside it.)
|
||||
let iccp = png.windows(4).position(|w| w == b"iCCP").expect("the file carries an iCCP chunk");
|
||||
let len = u32::from_be_bytes(png[iccp - 4..iccp].try_into().expect("four length bytes")) as usize;
|
||||
for cut in [iccp + 4, iccp + 20, iccp + 4 + len / 2, iccp + 4 + len - 1] {
|
||||
assert_eq!(read_iccp(&png[..cut], u64::from(u32::MAX)), None, "cut at {cut} of {}", png.len());
|
||||
}
|
||||
// A length field claiming more than the file holds is refused the same way.
|
||||
let mut lying = png.clone();
|
||||
lying[iccp - 4..iccp].copy_from_slice(&u32::to_be_bytes(0x7fff_ffff));
|
||||
assert_eq!(read_iccp(&lying, u64::from(u32::MAX)), None, "a length past the end of the file");
|
||||
}
|
||||
|
||||
/// CodeRabbit on #10300: `read_iccp` promises the first CRC-valid `iCCP` before the image
|
||||
/// data, but returned None as soon as one had a broken CRC. What png itself does with such a
|
||||
/// file decides the right answer, so this test measures that rather than assuming it: the
|
||||
/// chunk is corrupted in place, and png is let read it (no `set_ignore_iccp_chunk`).
|
||||
#[test]
|
||||
fn a_broken_iccp_crc_does_not_hide_a_later_valid_profile() {
|
||||
let profile: Vec<u8> = (0..2048u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 11) as u8).collect();
|
||||
let img = Image::from_raw(2, 2, ChannelLayout::Rgb, SampleType::U8, vec![9; 12]).unwrap().with_icc(Some(profile.clone()));
|
||||
let png = crate::encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let at = png.windows(4).position(|w| w == b"iCCP").expect("the file carries an iCCP chunk");
|
||||
let len = u32::from_be_bytes(png[at - 4..at].try_into().expect("four length bytes")) as usize;
|
||||
// A second iCCP, byte for byte the first, inserted before it with its CRC broken. The
|
||||
// file then holds a broken chunk followed by the valid one.
|
||||
let chunk = png[at - 4..at + 4 + len + 4].to_vec();
|
||||
let mut broken = chunk.clone();
|
||||
let crc_at = chunk.len() - 4;
|
||||
broken[crc_at] ^= 0xff;
|
||||
let mut two = png[..at - 4].to_vec();
|
||||
two.extend_from_slice(&broken);
|
||||
two.extend_from_slice(&png[at - 4..]);
|
||||
|
||||
// What png makes of it, reading the chunk itself: the reference behaviour.
|
||||
let mut decoder = png::Decoder::new_with_limits(Cursor::new(&two[..]), png::Limits { bytes: Limits::default().alloc_usize() });
|
||||
decoder.set_ignore_text_chunk(true);
|
||||
let pngs_own = decoder.read_info().ok().and_then(|r| r.info().icc_profile.as_ref().map(|c| c.len()));
|
||||
|
||||
// And what this file's reader makes of it. The two must agree: a reader that is stricter
|
||||
// than png loses a profile png would have kept, and one that is looser invents one.
|
||||
let ours = read_iccp(&two, u64::from(u32::MAX)).map(|p| p.len());
|
||||
assert_eq!(ours, pngs_own, "read_iccp must answer the broken-then-valid file as png does");
|
||||
// Whichever way that falls, the image itself still opens with its pixels.
|
||||
assert_eq!(decode(&two, &Limits::default()).unwrap().data(), &[9u8; 12][..]);
|
||||
}
|
||||
|
||||
/// CodeRabbit on #10300: every decoder built in this file skips `iCCP`, not just the one
|
||||
/// `decode` uses. `palette` and `has_additional_images` read headers from untrusted bytes
|
||||
/// too, so a profile that inflates to gigabytes must not be unpacked there either — they
|
||||
/// never look at the profile, so skipping it costs them nothing.
|
||||
#[test]
|
||||
fn the_header_only_readers_skip_the_iccp_chunk_as_well() {
|
||||
// An oversized profile, as in the test above: a few kilobytes of zlib, gigabytes inflated.
|
||||
let cap = usize::try_from(MAX_ICC_BYTES).unwrap();
|
||||
let img = Image::from_raw(2, 2, ChannelLayout::Rgb, SampleType::U8, vec![9; 12]).unwrap().with_icc(Some(vec![0; cap + 1]));
|
||||
let png = crate::encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert!(png.windows(4).any(|w| w == b"iCCP"), "the file carries the chunk the readers must skip");
|
||||
// Both read their headers and answer, rather than inflating the profile on the way.
|
||||
assert!(!has_additional_images(&png).unwrap(), "not an animation");
|
||||
assert_eq!(palette(&png).unwrap(), None, "not a palette image");
|
||||
// Every decoder in this file is told to skip it, so none of them can be the one that
|
||||
// inflates it: the count is the guard against a new one being added without the flag.
|
||||
// Counted over the production half only: the tests below build a decoder on purpose
|
||||
// without the flag, to measure what png does with a chunk this one skips.
|
||||
let source = include_str!("png.rs");
|
||||
let production = source.split("#[cfg(test)]").next().unwrap_or(source);
|
||||
assert_eq!(
|
||||
production.matches("png::Decoder::new_with_limits").count(),
|
||||
production.matches("set_ignore_iccp_chunk(true)").count(),
|
||||
"every png::Decoder in this file's production code skips iCCP"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2036,6 +2215,9 @@ mod rows_tests {
|
||||
let mut decoder = png::Decoder::new_with_limits(Cursor::new(bytes), png::Limits { bytes: Limits::default().alloc_usize() });
|
||||
decoder.set_transformations(png::Transformations::EXPAND);
|
||||
decoder.set_ignore_text_chunk(true);
|
||||
// png inflates iCCP up to the whole allocation limit, so a few kilobytes of zlib could ask
|
||||
// for gigabytes. The profile is read separately, with a cap (`read_iccp`, #8599).
|
||||
decoder.set_ignore_iccp_chunk(true);
|
||||
let mut reader = decoder.read_info().map_err(map_png_err)?;
|
||||
let mut buf = vec![0u8; reader.output_buffer_size().ok_or_else(|| err("image too large"))?];
|
||||
let out = reader.next_frame(&mut buf).map_err(map_png_err)?;
|
||||
|
||||
@@ -127,10 +127,45 @@ impl std::ops::Add for Tally {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes an open `tiff` decoder keeps per chunk: its offset and its byte count, as `u64`s.
|
||||
pub(super) const DECODER_BYTES_PER_CHUNK: u64 = 16;
|
||||
|
||||
/// Threads the band decode may run on.
|
||||
pub(super) fn worker_threads() -> usize {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
return rayon::current_num_threads().max(1);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return 1;
|
||||
}
|
||||
|
||||
/// How many band workers, each holding `per_worker` bytes, fit in `max_alloc` beside the `held`
|
||||
/// bytes already allocated (at most `threads`, at least one), or a limit error when none does.
|
||||
pub(super) fn budget_workers(held: u64, per_worker: u64, max_alloc: u64, threads: usize) -> Result<usize, CodecError> {
|
||||
let threads = threads.max(1);
|
||||
let room = max_alloc.saturating_sub(held);
|
||||
let fit = room.checked_div(per_worker).map_or(threads, |n| usize::try_from(n).unwrap_or(usize::MAX));
|
||||
if fit == 0 {
|
||||
return Err(CodecError::LimitExceeded(format!(
|
||||
"decoding needs {per_worker} bytes of strip or tile scratch beside {held} bytes of image, exceeding max_alloc {max_alloc}"
|
||||
)));
|
||||
}
|
||||
Ok(fit.min(threads))
|
||||
}
|
||||
|
||||
/// Bands each parallel task decodes, one after the other: one band per task when every thread
|
||||
/// may hold a worker, else the bands split into `workers` runs so that no more than `workers`
|
||||
/// decoders and scratch buffers are ever alive at once.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
fn bands_per_task(bands: usize, workers: usize, threads: usize) -> usize {
|
||||
if workers >= threads { 1 } else { bands.div_ceil(workers.max(1)).max(1) }
|
||||
}
|
||||
|
||||
/// Decodes the bands from `first` on into `data` (`band_bytes` each), in parallel on native
|
||||
/// targets (one decoder and scratch buffer per worker). `extra` receives samples that are not
|
||||
/// part of the colour image, `extra_band` bytes per band, when it is non-empty.
|
||||
/// targets (one decoder and scratch buffer per worker, at most `workers` of them at once).
|
||||
/// `extra` receives samples that are not part of the colour image, `extra_band` bytes per band,
|
||||
/// when it is non-empty.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn decode_bands(
|
||||
p: &Prepared,
|
||||
b: &[u8],
|
||||
@@ -139,36 +174,37 @@ pub(super) fn decode_bands(
|
||||
first: usize,
|
||||
extra: &mut [u8],
|
||||
extra_band: usize,
|
||||
workers: usize,
|
||||
) -> Result<Tally, CodecError> {
|
||||
use rayon::prelude::*;
|
||||
let band_bytes = band_bytes.max(1);
|
||||
let per_task = bands_per_task(data.len().div_ceil(band_bytes), workers, worker_threads());
|
||||
let task_bytes = band_bytes.saturating_mul(per_task);
|
||||
let init = || p.open(b).map(|d| (d, Vec::new())).map_err(|e| e.to_string());
|
||||
let task_first = |t: usize| first.saturating_add(t.saturating_mul(per_task));
|
||||
if extra.is_empty() {
|
||||
return data
|
||||
.par_chunks_mut(band_bytes.max(1))
|
||||
.par_chunks_mut(task_bytes)
|
||||
.enumerate()
|
||||
.map_init(
|
||||
|| p.open(b).map(|d| (d, Vec::new())).map_err(|e| e.to_string()),
|
||||
|worker, (i, band)| {
|
||||
let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?;
|
||||
decode_band(&p.lay, dec, scratch, first + i, band, None)
|
||||
},
|
||||
)
|
||||
.map_init(init, |worker, (t, task)| {
|
||||
let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?;
|
||||
decode_task(&p.lay, dec, scratch, task_first(t), task, band_bytes, None, extra_band)
|
||||
})
|
||||
.try_reduce(Tally::default, |a, b| Ok(a + b));
|
||||
}
|
||||
data.par_chunks_mut(band_bytes.max(1))
|
||||
.zip(extra.par_chunks_mut(extra_band.max(1)))
|
||||
data.par_chunks_mut(task_bytes)
|
||||
.zip(extra.par_chunks_mut(extra_band.max(1).saturating_mul(per_task)))
|
||||
.enumerate()
|
||||
.map_init(
|
||||
|| p.open(b).map(|d| (d, Vec::new())).map_err(|e| e.to_string()),
|
||||
|worker, (i, (band, extra_band))| {
|
||||
let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?;
|
||||
decode_band(&p.lay, dec, scratch, first + i, band, Some(extra_band))
|
||||
},
|
||||
)
|
||||
.map_init(init, |worker, (t, (task, extra_task))| {
|
||||
let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?;
|
||||
decode_task(&p.lay, dec, scratch, task_first(t), task, band_bytes, Some(extra_task), extra_band)
|
||||
})
|
||||
.try_reduce(Tally::default, |a, b| Ok(a + b))
|
||||
}
|
||||
|
||||
/// Decodes the bands from `first` on into `data` (`band_bytes` each), one after the other.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn decode_bands(
|
||||
p: &Prepared,
|
||||
b: &[u8],
|
||||
@@ -177,18 +213,34 @@ pub(super) fn decode_bands(
|
||||
first: usize,
|
||||
extra: &mut [u8],
|
||||
extra_band: usize,
|
||||
_workers: usize,
|
||||
) -> Result<Tally, CodecError> {
|
||||
let mut dec = p.open(b)?;
|
||||
let mut scratch = Vec::new();
|
||||
let extra = if extra.is_empty() { None } else { Some(extra) };
|
||||
decode_task(&p.lay, &mut dec, &mut scratch, first, data, band_bytes.max(1), extra, extra_band)
|
||||
}
|
||||
|
||||
/// Decodes the consecutive bands in `task` (the first is band `b0`), one after the other.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn decode_task(
|
||||
lay: &Layout,
|
||||
dec: &mut Decoder<Patched<'_>>,
|
||||
scratch: &mut Vec<u8>,
|
||||
b0: usize,
|
||||
task: &mut [u8],
|
||||
band_bytes: usize,
|
||||
extra: Option<&mut [u8]>,
|
||||
extra_band: usize,
|
||||
) -> Result<Tally, CodecError> {
|
||||
let mut tally = Tally::default();
|
||||
if extra.is_empty() {
|
||||
for (i, band) in data.chunks_mut(band_bytes.max(1)).enumerate() {
|
||||
tally = tally + decode_band(&p.lay, &mut dec, &mut scratch, first + i, band, None)?;
|
||||
}
|
||||
return Ok(tally);
|
||||
}
|
||||
for (i, (band, extra_band)) in data.chunks_mut(band_bytes.max(1)).zip(extra.chunks_mut(extra_band.max(1))).enumerate() {
|
||||
tally = tally + decode_band(&p.lay, &mut dec, &mut scratch, first + i, band, Some(extra_band))?;
|
||||
let mut extra = extra.map(|e| e.chunks_mut(extra_band.max(1)));
|
||||
for (i, band) in task.chunks_mut(band_bytes.max(1)).enumerate() {
|
||||
let extra_band = match extra.as_mut() {
|
||||
Some(bands) => Some(bands.next().ok_or_else(|| err("extra-sample band out of range"))?),
|
||||
None => None,
|
||||
};
|
||||
tally = tally + decode_band(lay, dec, scratch, b0.saturating_add(i), band, extra_band)?;
|
||||
}
|
||||
Ok(tally)
|
||||
}
|
||||
@@ -507,3 +559,38 @@ fn finish_band(lay: &Layout, band: &mut [u8]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod scratch_budget {
|
||||
use super::{CodecError, bands_per_task, budget_workers};
|
||||
|
||||
/// Only as many band workers run as fit beside the image, and none fitting is a limit error.
|
||||
#[test]
|
||||
fn workers_are_capped_by_the_room_beside_the_image() {
|
||||
// NV-9: four threads, a 128 MiB strip scratch each, 8 MiB of image, 160 MiB of budget:
|
||||
// one worker fits, not four.
|
||||
let mib = 1u64 << 20;
|
||||
assert_eq!(budget_workers(8 * mib, 128 * mib, 160 * mib, 4).unwrap(), 1);
|
||||
assert_eq!(budget_workers(8 * mib, 32 * mib, 160 * mib, 4).unwrap(), 4);
|
||||
assert_eq!(budget_workers(8 * mib, 32 * mib, 104 * mib, 16).unwrap(), 3);
|
||||
assert!(matches!(budget_workers(8 * mib, 160 * mib, 160 * mib, 4), Err(CodecError::LimitExceeded(_))));
|
||||
assert!(matches!(budget_workers(200 * mib, 1, 160 * mib, 4), Err(CodecError::LimitExceeded(_))));
|
||||
// No scratch: every thread; no threads reported: still one worker.
|
||||
assert_eq!(budget_workers(8 * mib, 0, 160 * mib, 4).unwrap(), 4);
|
||||
assert_eq!(budget_workers(0, 1, u64::MAX, 0).unwrap(), 1);
|
||||
}
|
||||
|
||||
/// Fewer workers than threads split the bands into at most that many consecutive runs.
|
||||
#[test]
|
||||
fn a_short_budget_groups_bands_into_as_many_tasks_as_workers() {
|
||||
assert_eq!(bands_per_task(16, 4, 4), 1);
|
||||
assert_eq!(bands_per_task(16, 8, 4), 1);
|
||||
assert_eq!(bands_per_task(16, 1, 4), 16);
|
||||
assert_eq!(bands_per_task(17, 3, 4), 6);
|
||||
assert_eq!(bands_per_task(0, 0, 4), 1);
|
||||
// Never more tasks than workers.
|
||||
for (bands, workers) in [(1usize, 1usize), (7, 2), (100, 3), (5, 5)] {
|
||||
assert!(bands.div_ceil(bands_per_task(bands, workers, 8)) <= workers);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::bands::{Tally, convert_ab, decode_bands, extra_sample_indices, refill_zeroed, split_extra_samples, zeroed};
|
||||
use super::bands::{
|
||||
DECODER_BYTES_PER_CHUNK, Tally, budget_workers, convert_ab, decode_bands, extra_sample_indices, refill_zeroed, split_extra_samples, worker_threads, zeroed,
|
||||
};
|
||||
use super::tags::{F, TAG_IMAGE_SOURCE_DATA, TAG_PHOTOSHOP, TAG_XMP, TEXT_TAGS, photoshop_tags};
|
||||
use super::ycbcr::YCbCr;
|
||||
use super::{
|
||||
@@ -201,6 +203,9 @@ impl<'a> TiffBands<'a> {
|
||||
pub fn decode<E: From<CodecError>>(&mut self, mut sink: impl FnMut(u32, u32, &Image) -> Result<(), E>) -> Result<(), E> {
|
||||
let per_group = self.bands_per_group()?;
|
||||
let p = &self.p;
|
||||
// The band workers' working memory (scratch buffers, decoder state) fits `max_alloc` as
|
||||
// a group does: no more workers run at once than that allows.
|
||||
let workers = budget_workers(0, p.per_worker, self.cap, worker_threads())?;
|
||||
let band = p.band_bytes()?.max(1);
|
||||
let bands = (p.h as usize).div_ceil(p.band_rows.max(1));
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
@@ -213,7 +218,7 @@ impl<'a> TiffBands<'a> {
|
||||
let len = p.lay.out_row().checked_mul(rows).ok_or_else(|| CodecError::LimitExceeded("band size".into()))?;
|
||||
// Missing chunks leave their rows as they are: they must start empty in every group.
|
||||
buf = refill_zeroed(buf, len)?;
|
||||
tally = tally + decode_bands(p, self.b, &mut buf, band, first, &mut [], 0)?;
|
||||
tally = tally + decode_bands(p, self.b, &mut buf, band, first, &mut [], 0, workers)?;
|
||||
if let Some(c) = p.ycbcr {
|
||||
c.convert(&mut buf, p.lay.out_channels(), p.lay.out);
|
||||
}
|
||||
@@ -496,6 +501,104 @@ fn multiband_layout(photometric: u64, has_alpha: bool, gray_alpha: bool) -> Chan
|
||||
}
|
||||
}
|
||||
|
||||
const TAG_PREDICTOR: u16 = 317;
|
||||
const TAG_JPEG_TABLES: u16 = 347;
|
||||
/// Marker segments looked at before a JPEG chunk's frame header. Real chunks hold a handful
|
||||
/// (SOI, DRI, SOF, DHT, DQT, SOS); the cap keeps chunks that all point at one long run of
|
||||
/// segments from costing chunks x segments.
|
||||
const MAX_JPEG_CHUNK_MARKERS: usize = 256;
|
||||
|
||||
/// Fill bytes (`0xFF` runs before a marker) all JPEG chunks of a TIFF may scan together. Each
|
||||
/// distinct chunk offset rescans its own run, so this bounds the total work.
|
||||
const MAX_JPEG_FILL_BYTES: usize = 1 << 24;
|
||||
|
||||
/// The frame header (width, height, components) of a JPEG stream: `Ok(None)` when it has none
|
||||
/// before its first scan, `Err` when more than [`MAX_JPEG_CHUNK_MARKERS`] segments come first.
|
||||
fn jpeg_frame(b: &[u8], fill: &mut usize) -> Result<Option<(usize, usize, usize)>, CodecError> {
|
||||
if b.get(..2) != Some(&[0xFF, 0xD8][..]) {
|
||||
return Ok(None);
|
||||
}
|
||||
jpeg_frame_from(b, 2, fill)
|
||||
}
|
||||
|
||||
/// [`jpeg_frame`] from byte `start` on, with no SOI check. `fill` counts the fill bytes scanned.
|
||||
fn jpeg_frame_from(b: &[u8], start: usize, fill: &mut usize) -> Result<Option<(usize, usize, usize)>, CodecError> {
|
||||
let be16 = |at: usize| b.get(at..at + 2).and_then(|v| <[u8; 2]>::try_from(v).ok()).map(|v| usize::from(u16::from_be_bytes(v)));
|
||||
let mut i = start;
|
||||
for _ in 0..MAX_JPEG_CHUNK_MARKERS {
|
||||
while b.get(i) == Some(&0xFF) && b.get(i + 1) == Some(&0xFF) {
|
||||
i += 1;
|
||||
*fill += 1;
|
||||
if *fill > MAX_JPEG_FILL_BYTES {
|
||||
return Err(CodecError::LimitExceeded("JPEG strips or tiles scan too many fill bytes".into()));
|
||||
}
|
||||
}
|
||||
if b.get(i) != Some(&0xFF) {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(&code) = b.get(i + 1) else { return Ok(None) };
|
||||
match code {
|
||||
0xC0..=0xCF if !matches!(code, 0xC4 | 0xC8 | 0xCC) => {
|
||||
let frame = be16(i + 5).zip(be16(i + 7)).zip(b.get(i + 9));
|
||||
return Ok(frame.map(|((h, w), &nc)| (w, h, usize::from(nc))));
|
||||
}
|
||||
0xD9 | 0xDA => return Ok(None),
|
||||
0x01 | 0xD0..=0xD8 => i += 2,
|
||||
_ => match be16(i + 2) {
|
||||
Some(len) => i += 2 + len,
|
||||
None => return Ok(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
Err(err("a JPEG strip or tile has too many marker segments before its frame header"))
|
||||
}
|
||||
|
||||
/// Refuses JPEG strips or tiles whose embedded frame is larger than the strip or tile
|
||||
/// (`nominal`, unclipped) or whose decoded frame exceeds `cap` bytes. Chunks sharing an offset
|
||||
/// are checked once.
|
||||
fn check_jpeg_chunks(
|
||||
f: &File<'_>,
|
||||
offsets: &ifd::Entry,
|
||||
sizes: &ifd::Entry,
|
||||
expected: u64,
|
||||
tables: Option<&[u8]>,
|
||||
nominal: (usize, usize),
|
||||
cap: usize,
|
||||
) -> Result<(), CodecError> {
|
||||
// The list below holds 16 bytes per chunk; bound it by the scratch cap, not only by the file size.
|
||||
if expected.saturating_mul(16) > cap as u64 {
|
||||
return Err(CodecError::LimitExceeded(format!("{expected} JPEG strips or tiles")));
|
||||
}
|
||||
// Reserve exactly the budgeted length: collecting from filter_map could over-allocate past `cap`.
|
||||
let mut chunks: Vec<(u64, u64)> = Vec::with_capacity(expected as usize);
|
||||
chunks.extend((0..expected).filter_map(|i| Some((f.uint(offsets, i)?, f.uint(sizes, i)?))));
|
||||
chunks.sort_unstable();
|
||||
// Entries sharing an offset but not a byte count are different chunks: check each one.
|
||||
chunks.dedup();
|
||||
let len = f.b.len() as u64;
|
||||
let mut fill = 0;
|
||||
for (at, n) in chunks {
|
||||
let end = at.saturating_add(n).min(len);
|
||||
let Some(data) = usize::try_from(at).ok().zip(usize::try_from(end).ok()).and_then(|(a, e)| f.b.get(a..e)) else { continue };
|
||||
let mut frame = match jpeg_frame(data, &mut fill)? {
|
||||
Some(frame) => Some(frame),
|
||||
None => tables.map(|t| jpeg_frame(t, &mut fill)).transpose()?.flatten(),
|
||||
};
|
||||
// Without SOI, the tiff crate drops the chunk's first two bytes, so a frame at offset 2 is decoded.
|
||||
if frame.is_none() && data.get(..2) != Some(&[0xFF, 0xD8][..]) {
|
||||
frame = jpeg_frame_from(data, 2, &mut fill)?;
|
||||
}
|
||||
let Some((w, h, nc)) = frame else { continue };
|
||||
if w > nominal.0 || h > nominal.1 {
|
||||
return Err(err(format!("a {w}x{h} JPEG frame in a {}x{} strip or tile", nominal.0, nominal.1)));
|
||||
}
|
||||
if w.checked_mul(h).and_then(|px| px.checked_mul(nc.max(1))).is_none_or(|bytes| bytes > cap) {
|
||||
return Err(CodecError::LimitExceeded(format!("a {w}x{h} JPEG strip or tile")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The chunk tables must match the geometry. Checked in 64 bits, before the `tiff` crate does
|
||||
/// the same arithmetic in narrower types.
|
||||
fn check_chunk_tables(f: &File<'_>, dir: &Ifd, (w, h): (u32, u32), spp: u64, planar: bool, tiled: bool) -> Result<(u64, u64, u64), CodecError> {
|
||||
@@ -600,6 +703,10 @@ pub(super) struct Prepared {
|
||||
/// Bytes one strip or tile decodes to, before clipping to the image: a worker's scratch
|
||||
/// buffer. A strip is the full width; a tile keeps its declared size even at an edge.
|
||||
scratch_bytes: usize,
|
||||
/// Bytes one band worker holds while it decodes: its decoder's chunk tables, its strip or
|
||||
/// tile scratch buffer (none when strips decode in place) and what the `tiff` crate holds
|
||||
/// for one chunk (a JPEG chunk's decoder, a floating-point predictor's row).
|
||||
per_worker: u64,
|
||||
}
|
||||
|
||||
impl Prepared {
|
||||
@@ -617,14 +724,17 @@ impl Prepared {
|
||||
/// Decodes the pixels of one directory.
|
||||
fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecError> {
|
||||
let p = prepare(f, dir, limits, true)?;
|
||||
// The output, allocated once and fallibly.
|
||||
let len = p.lay.out_row().checked_mul(p.h as usize).ok_or_else(|| CodecError::LimitExceeded("image size".into()))?;
|
||||
let mut data = zeroed(len)?;
|
||||
let extra_row = p.lay.extra_row();
|
||||
let extra_len = extra_row.checked_mul(p.h as usize).ok_or_else(|| CodecError::LimitExceeded("extra samples".into()))?;
|
||||
// As many band workers run at once as fit in `max_alloc` beside the output and the extra
|
||||
// samples; when not even one does, the image is refused before anything is allocated.
|
||||
let workers = budget_workers((len as u64).saturating_add(extra_len as u64), p.per_worker, limits.max_alloc, worker_threads())?;
|
||||
// The output, allocated once and fallibly.
|
||||
let mut data = zeroed(len)?;
|
||||
let mut extra_data = if p.lay.extra_at.is_empty() { Vec::new() } else { zeroed(extra_len)? };
|
||||
let extra_band = extra_row.saturating_mul(p.band_rows);
|
||||
let tally = decode_bands(&p, f.b, &mut data, p.band_bytes()?, 0, extra_data.as_mut_slice(), extra_band)?;
|
||||
let tally = decode_bands(&p, f.b, &mut data, p.band_bytes()?, 0, extra_data.as_mut_slice(), extra_band, workers)?;
|
||||
if tally.decoded == 0 && tally.missing > 0 {
|
||||
return Err(err("the image data is missing (cut off or past the end of the file)"));
|
||||
}
|
||||
@@ -665,14 +775,42 @@ fn prepared_warnings(p: &Prepared) -> Vec<DecodeWarning> {
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Checks one directory and lays it out for decoding. `whole`: the image is decoded into one
|
||||
/// buffer, which `limits.max_alloc` bounds; otherwise only its size is checked here.
|
||||
fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prepared, CodecError> {
|
||||
// The values the `tiff` crate reads must exist: a count past the end of the file is
|
||||
// neither allocated nor read.
|
||||
/// The structural tags the `tiff` crate reads must exist (a count past the end of the file is
|
||||
/// neither allocated nor read) and appear once: this parser reads the first entry of a tag and
|
||||
/// the `tiff` crate the last, so a repeated structural tag (a small SamplesPerPixel first, a
|
||||
/// large one last) would be checked here with one value and sized by the crate with another.
|
||||
fn check_structural_tags(f: &File<'_>, dir: &Ifd) -> Result<(), CodecError> {
|
||||
if let Some(e) = dir.entries.iter().find(|e| ifd::STRUCTURAL_TAGS.contains(&e.tag) && f.data(e).is_none()) {
|
||||
return Err(err(format!("tag {} points past the end of the file", e.tag)));
|
||||
}
|
||||
let mut structural: Vec<u16> = dir.entries.iter().map(|e| e.tag).filter(|t| ifd::STRUCTURAL_TAGS.contains(t)).collect();
|
||||
structural.sort_unstable();
|
||||
if let Some(w) = structural.windows(2).find(|w| w[0] == w[1]) {
|
||||
return Err(err(format!("tag {} appears more than once", w[0])));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The bytes the first `expected` strips or tiles hold inside the file, never more than the file.
|
||||
fn held_bytes(f: &File<'_>, (offsets, sizes): (&ifd::Entry, &ifd::Entry), expected: u64) -> u64 {
|
||||
let len = f.b.len() as u64;
|
||||
let mut held = 0u64;
|
||||
for i in 0..expected {
|
||||
if held >= len {
|
||||
break;
|
||||
}
|
||||
if let (Some(at), Some(n)) = (f.uint(offsets, i), f.uint(sizes, i)) {
|
||||
held = held.saturating_add(n.min(len.saturating_sub(at)));
|
||||
}
|
||||
}
|
||||
held.min(len)
|
||||
}
|
||||
|
||||
/// Checks one directory and lays it out for decoding. `whole`: the image is decoded into one
|
||||
/// buffer, which `limits.max_alloc` bounds; otherwise only its size is checked here. Chunk
|
||||
/// tables larger than `limits.max_alloc` are refused before the `tiff` crate reads them.
|
||||
fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prepared, CodecError> {
|
||||
check_structural_tags(f, dir)?;
|
||||
let need = |tag: u16, name: &str| f.tag_uint(dir, tag).ok_or_else(|| err(format!("missing or unreadable {name}")));
|
||||
let w = u32::try_from(need(ifd::TAG_WIDTH, "ImageWidth")?).map_err(|_| err("ImageWidth out of range"))?;
|
||||
let h = u32::try_from(need(ifd::TAG_HEIGHT, "ImageLength")?).map_err(|_| err("ImageLength out of range"))?;
|
||||
@@ -727,6 +865,17 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
let all_samples = palette.is_none() && matches!(photometric, 2 | 5 | 8 | 9) && (alpha_at.is_some_and(|a| a > 0) || (!planar && unused));
|
||||
let patches = header_patches(f, dir, photometric_entry, invert || palette.is_some() || all_samples || lab, lab && !all_samples)?;
|
||||
|
||||
// Opening the directory reads both chunk tables, with the `tiff` crate's default limits
|
||||
// (`with_limits` applies only once it is open), before anything below is charged: tables
|
||||
// that alone are over `max_alloc` (as every band worker holds them, `DECODER_BYTES_PER_CHUNK`
|
||||
// per chunk) are refused before they are read.
|
||||
let table_bytes = expected.saturating_mul(DECODER_BYTES_PER_CHUNK);
|
||||
if table_bytes > limits.max_alloc {
|
||||
return Err(CodecError::LimitExceeded(format!(
|
||||
"the strip or tile tables of a {w}x{h} image ({expected} chunks) need {table_bytes} bytes, exceeding max_alloc {}",
|
||||
limits.max_alloc
|
||||
)));
|
||||
}
|
||||
let tl = {
|
||||
let mut l = tiff::decoder::Limits::default();
|
||||
l.decoding_buffer_size = limits.alloc_usize();
|
||||
@@ -804,21 +953,11 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
4 => cw.clamp(4096, 65_535),
|
||||
_ => 4096,
|
||||
};
|
||||
let len = f.b.len() as u64;
|
||||
let (offsets, sizes) = (
|
||||
dir.get(offsets_tag).ok_or_else(|| err("missing strip or tile offsets"))?,
|
||||
dir.get(counts_tag).ok_or_else(|| err("missing strip or tile byte counts"))?,
|
||||
);
|
||||
let mut held = 0u64;
|
||||
for i in 0..expected {
|
||||
if held >= len {
|
||||
break;
|
||||
}
|
||||
if let (Some(at), Some(n)) = (f.uint(offsets, i), f.uint(sizes, i)) {
|
||||
held = held.saturating_add(n.min(len.saturating_sub(at)));
|
||||
}
|
||||
}
|
||||
let held = held.min(len);
|
||||
let held = held_bytes(f, (offsets, sizes), expected);
|
||||
if stored > held.saturating_mul(ratio).saturating_add(1 << 20) {
|
||||
return Err(err(format!("the strips or tiles in this file hold {held} bytes, too few for a {w}x{h} image")));
|
||||
}
|
||||
@@ -830,10 +969,19 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
let chunks_per_plane = across.checked_mul(down).ok_or_else(|| err("too many tiles"))?;
|
||||
let planes_in_file = if planar { spp as usize } else { 1 };
|
||||
let total = if tiled { dec.tile_count() } else { dec.strip_count() }.map_err(map_err)?;
|
||||
drop(dec);
|
||||
if Some(total as usize) != chunks_per_plane.checked_mul(planes_in_file) {
|
||||
return Err(err("strip or tile count does not match the image size"));
|
||||
}
|
||||
// The first chunk of a plane is the largest in it (the others are the same size or clipped
|
||||
// at the image's edge; the `tiff` crate clips the tiles of later planes only at the right
|
||||
// edge), so no chunk asks for a larger scratch buffer than these two.
|
||||
let first_chunk = dec.image_chunk_buffer_layout(0).map_err(map_err)?;
|
||||
let mut largest = first_chunk.len;
|
||||
if planes_in_file > 1 {
|
||||
let plane1 = u32::try_from(chunks_per_plane).map_err(|_| err("too many tiles"))?;
|
||||
largest = largest.max(dec.image_chunk_buffer_layout(plane1).map_err(map_err)?.len);
|
||||
}
|
||||
drop(dec);
|
||||
// One chunk's decoded bytes, clipped to the image: the scratch buffer may hold a little
|
||||
// more (the `tiff` crate reads whole tiles in some planar cases) but never an amount that
|
||||
// only a hostile tile size could ask for.
|
||||
@@ -844,9 +992,31 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
.and_then(|s| s.checked_mul(src.bytes()))
|
||||
.ok_or_else(|| CodecError::LimitExceeded("tile size".into()))?;
|
||||
let scratch_cap = chunk_bytes.saturating_mul(2).max(64 << 20).min(limits.alloc_usize());
|
||||
// The floating-point predictor makes the `tiff` crate read each row of a tile at its full
|
||||
// stored width (TileWidth, not clipped to the image) into a buffer of its own, outside the
|
||||
// scratch buffer: that row must fit the same cap.
|
||||
if f.tag_uint(dir, TAG_PREDICTOR) == Some(3) {
|
||||
let stored_row = cw.checked_mul(chunk_spp).and_then(|n| n.checked_mul(src.bytes()));
|
||||
if stored_row.is_none_or(|n| n > scratch_cap) {
|
||||
return Err(CodecError::LimitExceeded(format!("a {cw} sample wide predicted tile row")));
|
||||
}
|
||||
}
|
||||
// JPEG-compressed chunks (compression 7) are decoded by the `tiff` crate into a whole JPEG
|
||||
// image sized by the embedded frame header, with no limits, before the chunk's bytes are
|
||||
// taken. The frame must fit the strip or tile it stands for, as libtiff requires, and the
|
||||
// scratch cap.
|
||||
if compression == 7 {
|
||||
let tables = dir.get(TAG_JPEG_TABLES).and_then(|e| f.data(e));
|
||||
let (nominal_w, nominal_h) =
|
||||
(cw, if tiled { ch } else { f.tag_uint(dir, ifd::TAG_ROWS_PER_STRIP).and_then(|r| usize::try_from(r).ok()).unwrap_or(hu) });
|
||||
check_jpeg_chunks(f, offsets, sizes, expected, tables, (nominal_w, nominal_h), scratch_cap)?;
|
||||
}
|
||||
// One chunk as the decoder actually reads it: a tile keeps its declared size at an edge,
|
||||
// which can be more than the clipped image bytes above.
|
||||
let scratch_bytes = cw.saturating_mul(ch).saturating_mul(chunk_spp).saturating_mul(src.bytes());
|
||||
// What the `tiff` crate holds for one chunk beyond its output.
|
||||
let tiff_samples = if planar { 1 } else { spp };
|
||||
let codec_bytes = chunk_codec_bytes(f, dir, (offsets, sizes), expected, (cw as u64, ch as u64), tiff_samples, bits)?;
|
||||
let (extra_at, extras_over_limit) = extra_sample_indices(spp as usize, color, alpha_at, out_layout.has_alpha());
|
||||
let mut lay = Layout {
|
||||
w: wu,
|
||||
@@ -866,13 +1036,31 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
scratch_cap,
|
||||
extra_at,
|
||||
};
|
||||
// The decode's working memory shares `max_alloc` with the output: each band worker holds an
|
||||
// open decoder (its chunk tables), one chunk's scratch buffer unless strips decode in place,
|
||||
// and what the `tiff` crate holds for a chunk. No chunk may ask for more scratch than that.
|
||||
let out_row = lay.out_row();
|
||||
let band_bytes = out_row.checked_mul(ch.min(hu)).ok_or_else(|| CodecError::LimitExceeded("band size".into()))?;
|
||||
let in_place = lay.direct() && first_chunk.len == band_bytes && first_chunk.row_stride.map(|s| s.get()) == Some(out_row);
|
||||
let scratch = if in_place { 0 } else { largest };
|
||||
if scratch > lay.scratch_cap {
|
||||
return Err(CodecError::LimitExceeded(format!("a {scratch} byte strip or tile")));
|
||||
}
|
||||
lay.scratch_cap = scratch;
|
||||
let tables = u64::from(total).saturating_mul(DECODER_BYTES_PER_CHUNK);
|
||||
let per_worker = (scratch as u64).saturating_add(tables).saturating_add(codec_bytes);
|
||||
|
||||
// Extra samples share the allocation budget with the image: their interleaved buffer and the
|
||||
// planes split from it are held next to the image, so both count against `max_alloc`. When
|
||||
// they don't fit, the image still opens (it passed its own check above) without them.
|
||||
// planes split from it are held next to the image, and the interleaved buffer next to the
|
||||
// decode's working memory, so all of it counts against `max_alloc`. When they don't fit, the
|
||||
// image still opens (if it fits on its own) without them.
|
||||
let mut extras_dropped = 0;
|
||||
if whole && !lay.extra_at.is_empty() {
|
||||
let per_pixel = out_layout.channels().saturating_add(lay.extra_at.len().saturating_mul(2)).saturating_mul(out.bytes());
|
||||
if limits.check_bytes(w, h, per_pixel as u64).is_err() {
|
||||
let image = (out_row as u64).saturating_mul(hu as u64);
|
||||
let interleaved = (lay.extra_row() as u64).saturating_mul(hu as u64);
|
||||
let decoding = image.saturating_add(interleaved).saturating_add(per_worker);
|
||||
if limits.check_bytes(w, h, per_pixel as u64).is_err() || decoding > limits.max_alloc {
|
||||
extras_dropped = u32::try_from(lay.extra_at.len()).unwrap_or(u32::MAX);
|
||||
lay.extra_at.clear();
|
||||
}
|
||||
@@ -891,9 +1079,138 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
extras_over_limit,
|
||||
extras_dropped,
|
||||
scratch_bytes,
|
||||
per_worker,
|
||||
})
|
||||
}
|
||||
|
||||
/// Steps [`jpeg_sof`] may take per strip or tile beyond the file's length: room to read again
|
||||
/// the few header segments of strips or tiles that share one stream (a sparse file pointing its
|
||||
/// blank tiles at one tile).
|
||||
const JPEG_HEADER_STEPS_PER_CHUNK: u64 = 64;
|
||||
|
||||
/// What the `tiff` crate holds for one chunk of directory `dir` beyond its output: a JPEG
|
||||
/// chunk's decoder ([`jpeg_working_bytes`]) and a row of the declared strip or tile width for
|
||||
/// the floating-point predictor ([`predictor_row_bytes`]). `offsets` and `sizes` are the chunk
|
||||
/// tables (`count` entries each), `chunk` the strip or tile size and `samples` the samples per
|
||||
/// pixel a chunk holds. The JPEG headers are read within the file's length plus
|
||||
/// [`JPEG_HEADER_STEPS_PER_CHUNK`] steps per chunk, so chunks that overlap cannot make that
|
||||
/// read longer than the file suggests.
|
||||
fn chunk_codec_bytes(
|
||||
f: &File<'_>,
|
||||
dir: &Ifd,
|
||||
(offsets, sizes): (&ifd::Entry, &ifd::Entry),
|
||||
count: u64,
|
||||
chunk: (u64, u64),
|
||||
samples: u64,
|
||||
bits: u64,
|
||||
) -> Result<u64, CodecError> {
|
||||
let jpeg = if f.tag_uint(dir, ifd::TAG_COMPRESSION) == Some(7) {
|
||||
let in_file = |at: u64, n: u64| {
|
||||
let at = usize::try_from(at).ok()?;
|
||||
let end = at.saturating_add(usize::try_from(n).unwrap_or(usize::MAX)).min(f.b.len());
|
||||
f.b.get(at..end)
|
||||
};
|
||||
let chunks = (0..count).map(|i| f.uint(offsets, i).zip(f.uint(sizes, i)).and_then(|(at, n)| in_file(at, n)));
|
||||
let steps = (f.b.len() as u64).saturating_add(count.saturating_mul(JPEG_HEADER_STEPS_PER_CHUNK));
|
||||
jpeg_working_bytes(f.tag_bytes(dir, TAG_JPEG_TABLES), chunks, chunk, steps)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let row = predictor_row_bytes(f.tag_uint(dir, TAG_PREDICTOR).unwrap_or(1), chunk.0, samples, bits);
|
||||
Ok(jpeg.saturating_add(row))
|
||||
}
|
||||
|
||||
/// Bytes the `tiff` crate holds for one row of a strip or tile as the file declares it
|
||||
/// (`chunk_width` pixels of `samples` samples), which the floating-point predictor decodes each
|
||||
/// row into when a chunk row holds more than the row it returns: a tile clipped at the image's
|
||||
/// edge, a hostile TileWidth far wider than the image, or a strip with samples it does not
|
||||
/// return. Charged for every floating-point-predicted chunk, also one that decodes in place
|
||||
/// without that row (one row is a small overcount); zero for other predictors.
|
||||
fn predictor_row_bytes(predictor: u64, chunk_width: u64, samples: u64, bits: u64) -> u64 {
|
||||
if predictor != 3 {
|
||||
return 0;
|
||||
}
|
||||
chunk_width.saturating_mul(samples).saturating_mul(bits).div_ceil(8)
|
||||
}
|
||||
|
||||
/// The most zune-jpeg holds while the `tiff` crate decodes one of `chunks` (each JPEG strip or
|
||||
/// tile in the file, `None` when it is not in the file): the compressed stream with `tables`
|
||||
/// in front, which the `tiff` crate copies whole whether or not it holds a frame, and the
|
||||
/// decoded frame its SOF marker declares with that frame's DCT coefficients (16 bits per
|
||||
/// sample, padded to whole MCUs), which progressive and multi-scan streams hold whole. A frame
|
||||
/// larger than its `chunk` size (width, height) is refused, as libtiff does: the decoder would
|
||||
/// allocate it in full however small the TIFF chunk is. Reading the headers takes at most
|
||||
/// `steps` steps in all ([`jpeg_sof`]), or the image is refused.
|
||||
fn jpeg_working_bytes<'b>(tables: Option<&[u8]>, chunks: impl Iterator<Item = Option<&'b [u8]>>, chunk: (u64, u64), mut steps: u64) -> Result<u64, CodecError> {
|
||||
let table_sof = match tables {
|
||||
Some(t) => jpeg_sof(t, &mut steps)?,
|
||||
None => None,
|
||||
};
|
||||
let table_len = tables.map_or(0, |t| t.len() as u64);
|
||||
let mut most = 0u64;
|
||||
for data in chunks.flatten() {
|
||||
let mut need = (data.len() as u64).saturating_add(table_len);
|
||||
let sof = if table_sof.is_some() { table_sof } else { jpeg_sof(data, &mut steps)? };
|
||||
if let Some((w, h, components)) = sof {
|
||||
if w > chunk.0 || h > chunk.1 {
|
||||
return Err(CodecError::InvalidImage(format!("a {w}x{h} JPEG frame in a {}x{} strip or tile", chunk.0, chunk.1)));
|
||||
}
|
||||
let pad = |v: u64| v.div_ceil(32).saturating_mul(32);
|
||||
let frame = w.saturating_mul(h).saturating_mul(components);
|
||||
let coefficients = pad(w).saturating_mul(pad(h)).saturating_mul(components).saturating_mul(2);
|
||||
need = need.saturating_add(frame).saturating_add(coefficients);
|
||||
}
|
||||
most = most.max(need);
|
||||
}
|
||||
Ok(most)
|
||||
}
|
||||
|
||||
/// The width, height and component count of the first SOF marker in JPEG stream `s`, or `None`
|
||||
/// when the stream reaches its first scan (or its end) without one. Bytes between segments are
|
||||
/// skipped, as zune-jpeg skips them. Each byte stepped over (a stray byte, a fill byte or a
|
||||
/// marker) takes one of `steps` and a segment's body is jumped over, so the walk never takes
|
||||
/// more steps than `s` has bytes. Running out of `steps` is an error, which bounds the walk
|
||||
/// over strips or tiles that overlap.
|
||||
fn jpeg_sof(s: &[u8], steps: &mut u64) -> Result<Option<(u64, u64, u64)>, CodecError> {
|
||||
let mut step = || -> Result<(), CodecError> {
|
||||
*steps = steps
|
||||
.checked_sub(1)
|
||||
.ok_or_else(|| CodecError::InvalidImage("the JPEG headers of the strips or tiles are longer than the file (they overlap)".into()))?;
|
||||
Ok(())
|
||||
};
|
||||
let mut i = if s.starts_with(&[0xFF, 0xD8]) { 2 } else { 0 };
|
||||
loop {
|
||||
while s.get(i).is_some_and(|&b| b != 0xFF) {
|
||||
step()?;
|
||||
i += 1;
|
||||
}
|
||||
while s.get(i) == Some(&0xFF) {
|
||||
step()?;
|
||||
i += 1;
|
||||
}
|
||||
let Some(&marker) = s.get(i) else { return Ok(None) };
|
||||
step()?;
|
||||
i += 1;
|
||||
match marker {
|
||||
// Markers without a length: SOI, TEM and the restart markers.
|
||||
0xD8 | 0x01 | 0xD0..=0xD7 => continue,
|
||||
// End of image, or start of scan: no frame header follows.
|
||||
0xD9 | 0xDA => return Ok(None),
|
||||
_ => {}
|
||||
}
|
||||
let byte = |k: usize| s.get(i.checked_add(k)?).copied().map(u64::from);
|
||||
let pair = |k: usize| Some((byte(k)? << 8) | byte(k.checked_add(1)?)?);
|
||||
// SOF0-SOF15, without DHT (C4), JPG (C8) and DAC (CC).
|
||||
if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
|
||||
return Ok(pair(3).zip(pair(5)).zip(byte(7)).map(|((h, w), components)| (w, h, components)));
|
||||
}
|
||||
let Some(next) = pair(0).filter(|&len| len >= 2).and_then(|len| i.checked_add(usize::try_from(len).ok()?)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
i = next;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -903,14 +1220,15 @@ mod tests {
|
||||
/// so it reports them through the same function as the whole-image decode.
|
||||
#[test]
|
||||
fn extra_samples_over_the_budget_are_reported_by_both_decoders() {
|
||||
// Several strips (about 1 MB each), so one strip of all four samples fits the image's budget.
|
||||
// Several strips (about 1 MB each): the budget holds the image and one strip of all four
|
||||
// samples, the scratch it decodes through, but not the extra sample's planes.
|
||||
let (w, h) = (1024u32, 1024u32);
|
||||
let n = (w * h) as usize;
|
||||
let mut img = Image::from_raw(w, h, ChannelLayout::Rgb, SampleType::U8, vec![90; 3 * n]).unwrap();
|
||||
img.meta.extra_samples = vec![ExtraSample { kind: 0, data: vec![7; n] }];
|
||||
let bytes = crate::encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
|
||||
let (file, dir, _) = open_page(&bytes, None).unwrap();
|
||||
let tight = Limits { max_alloc: 3 * n as u64, ..Limits::default() };
|
||||
let tight = Limits { max_alloc: 3 * n as u64 + (1 << 20), ..Limits::default() };
|
||||
let p = prepare(&file, &dir, &tight, true).unwrap();
|
||||
assert_eq!(prepared_warnings(&p), vec![DecodeWarning::ExtraSamplesDropped { format: F, count: 1 }]);
|
||||
assert!(prepared_warnings(&prepare(&file, &dir, &tight, false).unwrap()).is_empty(), "banded: only the band counts");
|
||||
@@ -929,4 +1247,100 @@ mod tests {
|
||||
assert_eq!(scratch_bound(false, 1 << 20, 0, 2, 8), 2 << 20, "a zero band height counts as one row");
|
||||
assert_eq!(scratch_bound(false, u64::MAX, 1, 1, 8), u64::MAX, "the bound saturates");
|
||||
}
|
||||
|
||||
/// A JPEG stream with SOI, an APP0 segment, stray bytes, a fill run and a baseline SOF of
|
||||
/// `w`x`h` with `components` components, then a scan.
|
||||
fn jpeg_with_sof(w: u16, h: u16, components: u8) -> Vec<u8> {
|
||||
let mut s = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0xAA, 0xBB, 0x00, 0x00, 0xFF, 0xFF, 0xC0, 0x00, 0x0B, 8];
|
||||
s.extend_from_slice(&h.to_be_bytes());
|
||||
s.extend_from_slice(&w.to_be_bytes());
|
||||
s.extend_from_slice(&[components, 1, 0x11, 0, 0xFF, 0xDA, 0x00, 0x02]);
|
||||
s
|
||||
}
|
||||
|
||||
/// [`jpeg_sof`] with no step limit.
|
||||
fn sof(s: &[u8]) -> Option<(u64, u64, u64)> {
|
||||
let mut steps = u64::MAX;
|
||||
jpeg_sof(s, &mut steps).unwrap()
|
||||
}
|
||||
|
||||
/// The SOF walk finds the frame size past other segments and stray bytes, skips DHT, and
|
||||
/// gives up at the scan, at the end or on a malformed length, never reading out of bounds.
|
||||
#[test]
|
||||
fn jpeg_sof_reads_the_frame_header() {
|
||||
assert_eq!(sof(&jpeg_with_sof(640, 480, 3)), Some((640, 480, 3)));
|
||||
// Without SOI (a chunk after JPEGTables) and with a DHT (C4) segment first.
|
||||
let mut s = vec![0xFF, 0xC4, 0x00, 0x03, 0x00];
|
||||
s.extend_from_slice(&jpeg_with_sof(16, 8, 1)[2..]);
|
||||
assert_eq!(sof(&s), Some((16, 8, 1)));
|
||||
assert_eq!(sof(&[0xFF, 0xD8, 0xFF, 0xDA, 0x00, 0x02]), None, "a scan before any frame header");
|
||||
assert_eq!(sof(&[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x01]), None, "a segment length below two");
|
||||
assert_eq!(sof(&[0xFF, 0xD8, 0xFF, 0xC0, 0x00]), None, "a cut-off frame header");
|
||||
assert_eq!(sof(&[]), None);
|
||||
let full = jpeg_with_sof(640, 480, 3);
|
||||
for cut in 0..full.len() {
|
||||
let _ = sof(&full[..cut]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A JPEG chunk is charged its compressed stream (with the shared tables), its decoded
|
||||
/// frame and the frame's coefficients, and a frame larger than its strip or tile is
|
||||
/// refused: zune-jpeg allocates the whole frame its SOF declares.
|
||||
#[test]
|
||||
fn jpeg_chunks_are_charged_their_frame_and_refused_past_their_chunk() {
|
||||
let small = jpeg_with_sof(64, 64, 3);
|
||||
let frame = 64 * 64 * 3;
|
||||
let coefficients = 64 * 64 * 3 * 2;
|
||||
let got = jpeg_working_bytes(None, [Some(small.as_slice()), None].into_iter(), (64, 64), u64::MAX).unwrap();
|
||||
assert_eq!(got, small.len() as u64 + frame + coefficients);
|
||||
let tables = [0xFF, 0xD8, 0xFF, 0xC4, 0x00, 0x03, 0x00, 0xFF, 0xD9];
|
||||
let with_tables = jpeg_working_bytes(Some(&tables), [Some(small.as_slice())].into_iter(), (64, 64), u64::MAX).unwrap();
|
||||
assert_eq!(with_tables, got + tables.len() as u64);
|
||||
// A 16384x16384 frame (zune-jpeg's default cap) in a 64x64 tile.
|
||||
let huge = jpeg_with_sof(16384, 16384, 3);
|
||||
let refused = jpeg_working_bytes(None, [Some(small.as_slice()), Some(huge.as_slice())].into_iter(), (64, 64), u64::MAX);
|
||||
assert!(matches!(refused, Err(CodecError::InvalidImage(_))), "{refused:?}");
|
||||
let no_frame = jpeg_working_bytes(None, [Some(&[0u8, 1, 2][..])].into_iter(), (64, 64), u64::MAX).unwrap();
|
||||
assert_eq!(no_frame, 3, "no frame header: only the copied stream");
|
||||
}
|
||||
|
||||
/// The header walk takes one step per byte it steps over, never more than the stream has,
|
||||
/// and stops with an error when its budget runs out: strips or tiles that overlap (here
|
||||
/// many over one run of zeros) cannot make it read more than the file plus a few steps per
|
||||
/// chunk, while chunks that don't overlap fit in the file's length.
|
||||
#[test]
|
||||
fn jpeg_header_walk_is_bounded_by_its_step_budget() {
|
||||
// SOI is skipped; then a fill byte and APP0, two stray bytes, two fill bytes and SOF0.
|
||||
let s = jpeg_with_sof(640, 480, 3);
|
||||
let mut steps = 7;
|
||||
assert_eq!(jpeg_sof(&s, &mut steps).unwrap(), Some((640, 480, 3)));
|
||||
assert_eq!(steps, 0);
|
||||
let mut too_few = 6;
|
||||
assert!(matches!(jpeg_sof(&s, &mut too_few), Err(CodecError::InvalidImage(_))));
|
||||
let zeros = vec![0u8; 4096];
|
||||
let mut steps = 4096;
|
||||
assert_eq!(jpeg_sof(&zeros, &mut steps).unwrap(), None);
|
||||
assert_eq!(steps, 0, "one step per byte, none past the end");
|
||||
// 1000 chunks over the same 4096 bytes, budgeted as for a 4096-byte file: refused.
|
||||
let budget = 4096 + 1000 * JPEG_HEADER_STEPS_PER_CHUNK;
|
||||
let overlapping = jpeg_working_bytes(None, std::iter::repeat_n(Some(zeros.as_slice()), 1000), (64, 64), budget);
|
||||
assert!(matches!(overlapping, Err(CodecError::InvalidImage(_))), "{overlapping:?}");
|
||||
// 1000 separate chunks fit in the length of the file that holds them.
|
||||
let file_len = 1000 * s.len() as u64;
|
||||
let separate = jpeg_working_bytes(None, std::iter::repeat_n(Some(s.as_slice()), 1000), (640, 480), file_len);
|
||||
assert!(separate.is_ok(), "{separate:?}");
|
||||
}
|
||||
|
||||
/// The floating-point predictor's row is charged at the declared strip or tile width, so a
|
||||
/// hostile TileWidth cannot ask for it unbudgeted, and a strip with samples the `tiff` crate
|
||||
/// does not return is charged its row too; other predictors hold no such row.
|
||||
#[test]
|
||||
fn the_floating_point_predictor_row_is_charged_at_the_declared_tile_width() {
|
||||
assert_eq!(predictor_row_bytes(3, 256, 3, 32), 256 * 3 * 4);
|
||||
assert_eq!(predictor_row_bytes(3, 0xFFFF_FFFF, 3, 64), 0xFFFF_FFFF * 3 * 8, "a 64x64 page with TileWidth 0xFFFFFFFF");
|
||||
assert_eq!(predictor_row_bytes(3, 1024, 4, 32), 1024 * 4 * 4, "a strip row, every sample the file holds");
|
||||
assert_eq!(predictor_row_bytes(2, 0xFFFF_FFFF, 3, 64), 0);
|
||||
assert_eq!(predictor_row_bytes(1, 0xFFFF_FFFF, 3, 64), 0);
|
||||
assert_eq!(predictor_row_bytes(3, u64::MAX, u64::MAX, 64), u64::MAX.div_ceil(8), "saturates");
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[
|
||||
(Format::Jxl, "Lossless JPEG XL export uses the pure-Rust zune-jpegxl encoder; JPEG XL reading is tracked separately and is not yet available."),
|
||||
(
|
||||
Format::Heif,
|
||||
"HEIC decode uses heic-rs (pure Rust, in the optional photocraft-heif crate behind the \
|
||||
"HEIC decode uses heic-rs (pure Rust, in the optional craft-heif crate behind the \
|
||||
non-default `heif` feature, which official builds enable), so iPhone and Mac photos open; \
|
||||
writing needs an HEVC encoder, and the mature ones (x265, libheif) are C, so write stays \
|
||||
unsupported. Without the feature HEIF is detected but neither read nor written.",
|
||||
|
||||
@@ -731,7 +731,7 @@ fn convert_data(data: &[u8], from: ChannelLayout, from_sample: SampleType, layou
|
||||
} else if let Some(fast) = convert_int_direct(data, from, from_sample, layout, sample) {
|
||||
fast
|
||||
} else if layout == from {
|
||||
quantize(&to_normalized(data, from_sample), sample)
|
||||
convert_depth(data, from_sample, sample)
|
||||
} else {
|
||||
let src = to_normalized(data, from_sample);
|
||||
let values = convert_layout(&src, from, layout);
|
||||
@@ -828,11 +828,26 @@ fn clamp01(v: f32) -> f32 {
|
||||
}
|
||||
|
||||
pub(crate) fn quantize(values: &[f32], sample: SampleType) -> Vec<u8> {
|
||||
quantize_samples(values.iter().copied(), sample)
|
||||
}
|
||||
|
||||
/// Quantize normalized samples without an intermediate float buffer.
|
||||
fn quantize_samples(values: impl Iterator<Item = f32>, sample: SampleType) -> Vec<u8> {
|
||||
match sample {
|
||||
SampleType::U8 => values.iter().map(|&v| (clamp01(v) * 255.0).round() as u8).collect(),
|
||||
SampleType::U16 => values.iter().flat_map(|&v| ((clamp01(v) * 65535.0).round() as u16).to_ne_bytes()).collect(),
|
||||
SampleType::F16 => values.iter().flat_map(|&v| f16::from_f32(v).to_bits().to_ne_bytes()).collect(),
|
||||
SampleType::F32 => values.iter().flat_map(|&v| v.to_ne_bytes()).collect(),
|
||||
SampleType::U8 => values.map(|v| (clamp01(v) * 255.0).round() as u8).collect(),
|
||||
SampleType::U16 => values.flat_map(|v| ((clamp01(v) * 65535.0).round() as u16).to_ne_bytes()).collect(),
|
||||
SampleType::F16 => values.flat_map(|v| f16::from_f32(v).to_bits().to_ne_bytes()).collect(),
|
||||
SampleType::F32 => values.flat_map(|v| v.to_ne_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert sample depth with source-type dispatch outside the sample loop.
|
||||
fn convert_depth(data: &[u8], from: SampleType, sample: SampleType) -> Vec<u8> {
|
||||
match from {
|
||||
SampleType::U8 => quantize_samples(data.iter().map(|&v| v as f32 / 255.0), sample),
|
||||
SampleType::U16 => quantize_samples(data.as_chunks::<2>().0.iter().map(|c| u16::from_ne_bytes([c[0], c[1]]) as f32 / 65535.0), sample),
|
||||
SampleType::F16 => quantize_samples(data.as_chunks::<2>().0.iter().map(|c| f16::from_bits(u16::from_ne_bytes([c[0], c[1]])).to_f32()), sample),
|
||||
SampleType::F32 => quantize_samples(data.as_chunks::<4>().0.iter().map(|c| f32::from_ne_bytes([c[0], c[1], c[2], c[3]])), sample),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -928,6 +943,32 @@ mod tests {
|
||||
quantize(&convert_layout(&img.to_normalized(), img.layout, layout), sample)
|
||||
}
|
||||
|
||||
/// Depth changes match eager normalization, including every U16 and F16 bit pattern.
|
||||
#[test]
|
||||
fn depth_conversion_matches_the_normalized_reference() {
|
||||
for from in SampleType::ALL {
|
||||
let data: Vec<u8> = match from {
|
||||
SampleType::U8 => (0..=255).collect(),
|
||||
SampleType::U16 | SampleType::F16 => (0u32..=65535).flat_map(|v| (v as u16).to_ne_bytes()).collect(),
|
||||
SampleType::F32 => [
|
||||
0u32, 0x80000000, 1, 0x007fffff, 0x00800000, 0x3effffff, 0x3f000000, 0x3f000001, 0x3f7fffff, 0x3f800000, 0x3f800001, 0x7f7fffff,
|
||||
0xff7fffff, 0x7f800000, 0xff800000, 0x7fc12345, 0x7f812345,
|
||||
]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_ne_bytes)
|
||||
.collect(),
|
||||
};
|
||||
let img = Image::from_raw((data.len() / from.bytes()) as u32, 1, ChannelLayout::Gray, from, data).unwrap();
|
||||
let normalized = img.to_normalized();
|
||||
for to in SampleType::ALL {
|
||||
if from == to || (!from.is_float() && !to.is_float()) {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(img.convert(ChannelLayout::Gray, to).data(), quantize(&normalized, to), "{from:?} to {to:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn int_fast_path_matches_f32_route_for_every_value() {
|
||||
// Every U8 and every U16 value through every depth pair (alpha goes through the same per-sample conversion; covered by the layout test).
|
||||
|
||||
@@ -16,7 +16,11 @@ pub struct Limits {
|
||||
/// PNG also applies this to the aggregate decoded text/XMP UTF-8 bytes,
|
||||
/// including keywords, separately from pixels. Animated WebP charges
|
||||
/// every retained frame's full pixel copy plus its own copy of the
|
||||
/// file's ICC profile against this budget. This is not a total RSS cap.
|
||||
/// file's ICC profile against this budget. TIFF charges its decode working memory (each
|
||||
/// band worker's strip or tile scratch buffer, decoder state and the frame a JPEG strip or
|
||||
/// tile decodes to) next to the output, runs only as many workers at once as fit, and
|
||||
/// refuses the image when not even one does.
|
||||
/// This is not a total RSS cap.
|
||||
pub max_alloc: u64,
|
||||
}
|
||||
|
||||
|
||||
@@ -349,7 +349,13 @@ fn put_u64(order: Order, v: u64) -> [u8; 8] {
|
||||
}
|
||||
|
||||
/// Removes the IFD0 entries at offsets `removed` (see [`exif_with_resolution`]).
|
||||
fn remove_entries(b: &mut [u8], ifd: &Ifd0, removed: &[usize]) {
|
||||
///
|
||||
/// `removed` is strictly increasing: `Ifd0::parse` visits entries in physical order and the
|
||||
/// caller records each malformed field at most once. Walk those offsets once alongside the
|
||||
/// table, keeping compaction linear even when many duplicate resolution entries are malformed.
|
||||
/// The private offset type lets tests observe real equality checks in this same loop; production
|
||||
/// instantiates it with `usize`, without a counter or a change to the exported codec API.
|
||||
fn remove_entries<Offset: Copy + PartialEq + From<usize>>(b: &mut [u8], ifd: &Ifd0, removed: &[Offset]) {
|
||||
let eb = ifd.entry_bytes;
|
||||
let next_bytes = if ifd.big { 8 } else { 4 };
|
||||
let count_bytes = if ifd.big { 8 } else { 2 };
|
||||
@@ -357,8 +363,11 @@ fn remove_entries(b: &mut [u8], ifd: &Ifd0, removed: &[usize]) {
|
||||
let Some(old) = b.get(ifd.first..table_end.saturating_add(next_bytes)).map(<[u8]>::to_vec) else { return };
|
||||
let mut table = Vec::with_capacity(old.len());
|
||||
let mut kept = 0usize;
|
||||
let mut removed = removed.iter().copied().peekable();
|
||||
for (i, entry) in old.chunks_exact(eb).take(ifd.count).enumerate() {
|
||||
if !removed.contains(&(ifd.first + i * eb)) {
|
||||
if removed.peek() == Some(&Offset::from(ifd.first + i * eb)) {
|
||||
removed.next();
|
||||
} else {
|
||||
table.extend_from_slice(entry);
|
||||
kept += 1;
|
||||
}
|
||||
@@ -573,3 +582,6 @@ pub fn export_xmp(xmp: &str, ppi: Option<(f32, f32)>) -> Cow<'_, str> {
|
||||
pub(crate) fn from_metadata(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)> {
|
||||
xmp.and_then(xmp_resolution).or_else(|| exif.and_then(exif_resolution))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod complexity_tests;
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Count actual offset equality checks, independent of machine speed, while comparing every byte.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use super::{Ifd0, Order, TAG_X_RESOLUTION, TYPE_SHORT, exif_with_resolution, put_u16, put_u32, put_u64, remove_entries};
|
||||
|
||||
std::thread_local! {
|
||||
// Each test thread owns its measurement; other parallel tests cannot change the budget.
|
||||
static COMPARISONS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct CountedOffset(usize);
|
||||
|
||||
impl From<usize> for CountedOffset {
|
||||
/// Wrap a real entry offset without counting construction as search work.
|
||||
fn from(value: usize) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CountedOffset {
|
||||
/// Observe each equality actually requested by compaction, preserving its result.
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
COMPARISONS.with(|count| count.set(count.get() + 1));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum RemovalPattern {
|
||||
None,
|
||||
All,
|
||||
Alternating,
|
||||
Prefix,
|
||||
Suffix,
|
||||
}
|
||||
|
||||
impl RemovalPattern {
|
||||
/// Include exhaustion and long runs before the first removal, not just adjacent matches.
|
||||
fn removes(self, index: usize, count: usize) -> bool {
|
||||
match self {
|
||||
Self::None => false,
|
||||
Self::All => true,
|
||||
Self::Alternating => index.is_multiple_of(2),
|
||||
Self::Prefix => index < count / 2,
|
||||
Self::Suffix => index >= count / 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a parsed EXIF/TIFF block with malformed duplicate XResolution fields. The expected
|
||||
/// block is assembled from retained raw entries, leaving their shared payload, a valid empty
|
||||
/// next IFD and trailing sentinel at the original absolute offsets.
|
||||
fn fixture(order: Order, big: bool, count: usize, pattern: RemovalPattern) -> (Vec<u8>, Vec<u8>, Ifd0, Vec<usize>) {
|
||||
let (header, count_bytes, entry_bytes, next_bytes, alignment) = if big { (16, 8, 20, 8, 8) } else { (8, 2, 12, 4, 2) };
|
||||
let first = header + count_bytes;
|
||||
let payload_at = first + count * entry_bytes + next_bytes;
|
||||
let payload = b"unchanged out-of-line payload\0";
|
||||
let next_at = (payload_at + payload.len()).next_multiple_of(alignment);
|
||||
let mut header_bytes = match order {
|
||||
Order::Little => b"II".to_vec(),
|
||||
Order::Big => b"MM".to_vec(),
|
||||
};
|
||||
header_bytes.extend(put_u16(order, if big { 43 } else { 42 }));
|
||||
if big {
|
||||
header_bytes.extend(put_u16(order, 8));
|
||||
header_bytes.extend(put_u16(order, 0));
|
||||
header_bytes.extend(put_u64(order, header as u64));
|
||||
} else {
|
||||
header_bytes.extend(put_u32(order, header as u32));
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
let mut kept = Vec::new();
|
||||
for index in 0..count {
|
||||
let malformed = pattern.removes(index, count);
|
||||
let tag = if malformed { TAG_X_RESOLUTION } else { 0x8000 + index as u16 };
|
||||
let mut entry = put_u16(order, tag).to_vec();
|
||||
entry.extend(put_u16(order, if malformed { TYPE_SHORT } else { 2 }));
|
||||
let values = if malformed { 1 } else { payload.len() as u64 };
|
||||
if big {
|
||||
entry.extend(put_u64(order, values));
|
||||
} else {
|
||||
entry.extend(put_u32(order, values as u32));
|
||||
}
|
||||
if malformed {
|
||||
entry.extend(put_u16(order, 300));
|
||||
} else if big {
|
||||
entry.extend(put_u64(order, payload_at as u64));
|
||||
} else {
|
||||
entry.extend(put_u32(order, payload_at as u32));
|
||||
}
|
||||
entry.resize(entry_bytes, 0);
|
||||
entries.extend_from_slice(&entry);
|
||||
if !malformed {
|
||||
kept.extend_from_slice(&entry);
|
||||
}
|
||||
}
|
||||
let next = if big { put_u64(order, next_at as u64).to_vec() } else { put_u32(order, next_at as u32).to_vec() };
|
||||
let encoded_count = |value: usize| {
|
||||
if big { put_u64(order, value as u64).to_vec() } else { put_u16(order, value as u16).to_vec() }
|
||||
};
|
||||
let mut source = header_bytes.clone();
|
||||
source.extend(encoded_count(count));
|
||||
source.extend(entries);
|
||||
source.extend_from_slice(&next);
|
||||
source.extend_from_slice(payload);
|
||||
source.resize(next_at, 0);
|
||||
source.extend(vec![0; count_bytes + next_bytes]);
|
||||
source.extend_from_slice(b"trailing sentinel");
|
||||
let mut expected = header_bytes;
|
||||
expected.extend(encoded_count(kept.len() / entry_bytes));
|
||||
expected.extend(kept);
|
||||
expected.extend(next);
|
||||
expected.resize(payload_at, 0);
|
||||
expected.extend_from_slice(&source[payload_at..]);
|
||||
let ifd = Ifd0::parse(&source).expect("bounded synthetic IFD must parse");
|
||||
let removed = ifd.fields.iter().map(|field| field.entry).collect();
|
||||
(source, expected, ifd, removed)
|
||||
}
|
||||
|
||||
/// Thousands of malformed entries must stay within a generous linear comparison budget,
|
||||
/// while retaining exact bytes and agreeing with the public rewrite route. A per-entry
|
||||
/// membership scan exceeds this budget even though its cleaned output is identical.
|
||||
#[test]
|
||||
fn large_cleanup_has_linear_comparison_budget_and_identical_bytes() {
|
||||
for count in [4096, 8192] {
|
||||
for big in [false, true] {
|
||||
for order in [Order::Little, Order::Big] {
|
||||
for pattern in [RemovalPattern::None, RemovalPattern::All, RemovalPattern::Alternating, RemovalPattern::Prefix, RemovalPattern::Suffix] {
|
||||
let (source, expected, ifd, removed) = fixture(order, big, count, pattern);
|
||||
let measured: Vec<CountedOffset> = removed.iter().copied().map(CountedOffset::from).collect();
|
||||
let mut actual = source.clone();
|
||||
COMPARISONS.with(|value| value.set(0));
|
||||
remove_entries(&mut actual, &ifd, &measured);
|
||||
let comparisons = COMPARISONS.with(Cell::get);
|
||||
assert_eq!(actual, expected, "count={count}, big={big}, pattern={pattern:?}");
|
||||
assert_eq!(exif_with_resolution(&source, (240.0, 240.0)).as_ref(), expected);
|
||||
let budget = 4 * (count + removed.len() + 1);
|
||||
assert!(
|
||||
comparisons <= budget,
|
||||
"offset comparison work {comparisons} exceeds linear budget {budget}: entries={count}, removed={}, big={big}, pattern={pattern:?}",
|
||||
removed.len()
|
||||
);
|
||||
assert!(comparisons >= removed.len(), "measurement must observe the comparisons that find removals");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -658,9 +658,11 @@ fn deep_tile_count_table_is_admitted_against_max_alloc() {
|
||||
if compression != 0 {
|
||||
assert!(big.len() < 1 << 20, "compression {compression}: the file is {} bytes", big.len());
|
||||
}
|
||||
// The table and its scratch copy are admitted together: 8 MiB.
|
||||
assert_eq!(decode_deep_exr(&big, &budget(2 * table)).expect("room for the table and its copy"), scan, "compression {compression}");
|
||||
let got = decode_deep_exr(&big, &budget(2 * table - 1));
|
||||
// The table and its scratch copy are admitted together, 8 MiB, on top of the 4x4
|
||||
// image's sample-count index (17 u64).
|
||||
let index = 17 * 8;
|
||||
assert_eq!(decode_deep_exr(&big, &budget(2 * table + index)).expect("room for the table and its copy"), scan, "compression {compression}");
|
||||
let got = decode_deep_exr(&big, &budget(2 * table + index - 1));
|
||||
assert!(matches!(got, Err(CodecError::LimitExceeded(_))), "compression {compression}: one byte short gave {:?}", got.map(|d| d.total_samples()));
|
||||
}
|
||||
// Ordinary tiles: full-size edge tables decode under the small budget, like clipped ones.
|
||||
@@ -726,24 +728,65 @@ fn clipped_count_tables_include_scratch_in_the_budget() {
|
||||
let bytes = gen_deep(64, 1, &channels, compression, tile, &counts, &sample);
|
||||
let what = format!("tile {tile:?}, compression {compression}");
|
||||
let want = decode_deep_exr(&bytes, &Limits::none()).expect("unlimited decode");
|
||||
let required = if compression == 0 { 256 } else { 512 };
|
||||
// The table and any scratch, on top of the sample-count index (65 u64).
|
||||
let index = 65 * 8;
|
||||
let required = index + if compression == 0 { 256 } else { 512 };
|
||||
assert_eq!(decode_deep_exr(&bytes, &budget(required)).expect("table and any scratch fit exactly"), want, "{what}");
|
||||
assert!(matches!(decode_deep_exr(&bytes, &budget(required - 1)), Err(CodecError::LimitExceeded(_))), "{what}");
|
||||
let flat = photocraft_codecs::decode_with(&bytes, &photocraft_codecs::DecodeOptions { limits: budget(required - 1), ..Default::default() });
|
||||
assert!(matches!(flat, Err(CodecError::LimitExceeded(_))), "{what}");
|
||||
if compression == 0 {
|
||||
assert_eq!(decode_deep_exr(&bytes, &budget(511)).expect("raw table needs no scratch"), want, "{what}");
|
||||
assert_eq!(decode_deep_exr(&bytes, &budget(index + 511)).expect("raw table needs no scratch"), want, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-pixel bookkeeping of a deep decode (the cumulative sample-count index that
|
||||
/// [`photocraft_codecs::DeepImage::counts`] returns, eight bytes a pixel plus one entry) is
|
||||
/// charged against `max_alloc`, and the count tables are admitted on top of it. A one-channel
|
||||
/// image without samples passed the data-window check (four bytes a pixel) and decoded while
|
||||
/// holding 24 bytes a pixel of bookkeeping: a 4096x4096 file of 65-300 KB held 384 MiB under a
|
||||
/// 64 or 128 MiB budget. Under that four-byte budget it is now refused; it decodes with room
|
||||
/// for the index plus the largest count table and its scratch copy, and not one byte less.
|
||||
#[test]
|
||||
fn deep_bookkeeping_is_charged_against_max_alloc() {
|
||||
let (w, h) = (256usize, 256usize);
|
||||
let n = w * h;
|
||||
let channels = [Chan { name: "Y", ty: 2 }];
|
||||
let counts = vec![0u32; n];
|
||||
let sample = |_: usize, _: usize| Vec::new();
|
||||
let budget = |max_alloc: u64| Limits { max_alloc, ..Limits::none() };
|
||||
let index = (n as u64 + 1) * 8;
|
||||
for tile in [None, Some((w, h))] {
|
||||
for compression in [0u8, 1, 2] {
|
||||
let bytes = gen_deep(w, h, &channels, compression, tile, &counts, &sample);
|
||||
let what = format!("tile {tile:?}, compression {compression}");
|
||||
let want = decode_deep_exr(&bytes, &Limits::none()).expect("unlimited decode");
|
||||
assert_eq!(want.counts.len(), n + 1, "{what}");
|
||||
let pixel_budget = budget(4 * n as u64);
|
||||
let got = decode_deep_exr(&bytes, &pixel_budget);
|
||||
assert!(matches!(got, Err(CodecError::LimitExceeded(_))), "{what}: a four-byte-a-pixel budget gave {:?}", got.map(|d| d.counts.len()));
|
||||
let flat = photocraft_codecs::decode_with(&bytes, &photocraft_codecs::DecodeOptions { limits: pixel_budget, ..Default::default() });
|
||||
assert!(matches!(flat, Err(CodecError::LimitExceeded(_))), "{what}: the flat decode gave {:?}", flat.map(|i| i.width()));
|
||||
// One block's count table (a scan line, or the single tile), with the scratch copy
|
||||
// that undoes the byte split when it is stored compressed.
|
||||
let table = 4 * if tile.is_some() { n } else { w } as u64;
|
||||
let required = index + table * if compression == 0 { 1 } else { 2 };
|
||||
assert_eq!(decode_deep_exr(&bytes, &budget(required)).expect("index and table fit exactly"), want, "{what}");
|
||||
let got = decode_deep_exr(&bytes, &budget(required - 1));
|
||||
assert!(matches!(got, Err(CodecError::LimitExceeded(_))), "{what}: one byte short gave {:?}", got.map(|d| d.counts.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RLE and ZIPS store incompressible tables raw too. Their actual payload, not the header's
|
||||
/// compression tag, decides whether a scratch buffer is needed.
|
||||
#[test]
|
||||
fn raw_count_tables_need_no_scratch_even_with_compression() {
|
||||
let channels = [Chan { name: "Y", ty: 2 }];
|
||||
let limits = Limits { max_alloc: 4, ..Limits::none() };
|
||||
// The four-byte table on top of the one-pixel sample-count index (two u64).
|
||||
let limits = Limits { max_alloc: 16 + 4, ..Limits::none() };
|
||||
for tile in [None, Some((1, 1)), Some((2, 2))] {
|
||||
for compression in [0u8, 1, 2] {
|
||||
let bytes = gen_deep(1, 1, &channels, compression, tile, &[0], &|_, _| Vec::new());
|
||||
|
||||
@@ -151,6 +151,12 @@ fn limits_are_checked_before_decoding() {
|
||||
assert!(matches!(decode_with(checker_64(), &tight(few)), Err(CodecError::LimitExceeded(_))));
|
||||
let bytes = Limits { max_alloc: 64 * 64 * 3 - 1, ..Default::default() };
|
||||
assert!(matches!(decode_with(checker_64(), &tight(bytes)), Err(CodecError::LimitExceeded(_))));
|
||||
// An 8-bit file peaks at the decoder's 16-bit buffer plus the 8-bit output: 3 bytes a sample.
|
||||
// The budget is held against the picture as coded, which this file pads to 10240 pixels.
|
||||
let peak = 10240 * 3 * 3;
|
||||
let short = Limits { max_alloc: peak - 1, ..Default::default() };
|
||||
assert!(matches!(decode_with(checker_64(), &tight(short)), Err(CodecError::LimitExceeded(_))));
|
||||
decode_with(checker_64(), &tight(Limits { max_alloc: peak, ..Default::default() })).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -22,6 +22,7 @@ mod pcx;
|
||||
mod png_jpeg;
|
||||
mod pnm_headers;
|
||||
mod resolution;
|
||||
mod resolution_cleanup;
|
||||
mod roundtrip;
|
||||
mod source_settings;
|
||||
mod tga;
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Stable IFD0 compaction under repeated malformed resolution tags (#8610).
|
||||
//! Fixtures retain original value offsets and compare the entire metadata block.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use photocraft_codecs::resolution::exif_with_resolution;
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, SampleType, decode, encode};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Layout {
|
||||
big_tiff: bool,
|
||||
big_endian: bool,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// Encode a fixture integer at the selected width and byte order.
|
||||
fn number(self, value: u64, width: usize) -> Vec<u8> {
|
||||
if self.big_endian { value.to_be_bytes()[8 - width..].to_vec() } else { value.to_le_bytes()[..width].to_vec() }
|
||||
}
|
||||
|
||||
/// Build source and expected blocks separately, leaving out-of-line data at its original
|
||||
/// offsets. Cases select unrelated, malformed or rewritable entries in physical order.
|
||||
fn fixture(self, cases: &[u8]) -> (Vec<u8>, Vec<u8>) {
|
||||
let (header, count_bytes, entry_bytes, offset_bytes) = if self.big_tiff { (16, 8, 20, 8) } else { (8, 2, 12, 4) };
|
||||
let first = header + count_bytes;
|
||||
let table_end = first + cases.len() * entry_bytes;
|
||||
let mut data = b"unrelated out-of-line value\0".to_vec();
|
||||
let mut source_table = Vec::new();
|
||||
let mut kept_table = Vec::new();
|
||||
for &case in cases {
|
||||
let rational = |n, d| [self.number(n, 4), self.number(d, 4)].concat();
|
||||
let (tag, ty, count, value, replacement) = match case {
|
||||
0 => (270, 2, data.len() as u64, data.clone(), Some(data.clone())),
|
||||
1 => (282, 3, 1, self.number(300, 2), None), // wrong type
|
||||
2 => (283, 5, 1, rational(300, 0), None), // zero denominator
|
||||
3 => (296, 4, 1, self.number(3, 4), None), // wrong unit type
|
||||
4 => (282, 5, 1, rational(300, 1), Some(rational(240, 1))),
|
||||
5 => (283, 5, 1, rational(300, 1), Some(rational(240, 1))),
|
||||
6 => (296, 3, 1, self.number(3, 2), Some(self.number(2, 2))),
|
||||
7 => (282, 5, 2, [rational(300, 1), rational(300, 1)].concat(), None), // wrong count
|
||||
9 => (282, 5, u64::MAX, vec![0; 16], None), // oversized value span
|
||||
_ => (283, 1, 1, vec![99], None), // unknown value type
|
||||
};
|
||||
let mut entry = [self.number(tag, 2), self.number(ty, 2), self.number(count, offset_bytes)].concat();
|
||||
let mut rewritten = entry.clone();
|
||||
if value.len() > offset_bytes {
|
||||
let at = table_end + offset_bytes + data.len();
|
||||
entry.extend(self.number(at as u64, offset_bytes));
|
||||
rewritten.extend(self.number(at as u64, offset_bytes));
|
||||
// These values occupy their original slots even if their entry is removed.
|
||||
data.extend_from_slice(replacement.as_deref().unwrap_or(&value));
|
||||
} else {
|
||||
let mut inline = value.clone();
|
||||
inline.resize(offset_bytes, 0);
|
||||
entry.extend(inline);
|
||||
let mut inline = replacement.clone().unwrap_or_else(|| value.clone());
|
||||
inline.resize(offset_bytes, 0);
|
||||
rewritten.extend(inline);
|
||||
}
|
||||
source_table.extend_from_slice(&entry);
|
||||
if replacement.is_some() {
|
||||
kept_table.extend_from_slice(&rewritten);
|
||||
}
|
||||
}
|
||||
let mut prefix = if self.big_endian { b"MM".to_vec() } else { b"II".to_vec() };
|
||||
prefix.extend(self.number(if self.big_tiff { 43 } else { 42 }, 2));
|
||||
if self.big_tiff {
|
||||
prefix.extend(self.number(8, 2));
|
||||
prefix.extend(self.number(0, 2));
|
||||
}
|
||||
prefix.extend(self.number(header as u64, offset_bytes));
|
||||
let next = self.number(0x10203040, offset_bytes);
|
||||
let mut source = prefix.clone();
|
||||
source.extend(self.number(cases.len() as u64, count_bytes));
|
||||
source.extend_from_slice(&source_table);
|
||||
source.extend_from_slice(&next);
|
||||
source.extend_from_slice(&data);
|
||||
// Replace the rewritten rational payloads in the source with their original values.
|
||||
// Locate them using source entry offsets, never offsets from the compacted table.
|
||||
for (case, entry) in cases.iter().zip(source_table.chunks_exact(entry_bytes)) {
|
||||
if !self.big_tiff && matches!(case, 4 | 5) {
|
||||
let bytes: [u8; 4] = entry[8..12].try_into().unwrap();
|
||||
let at = if self.big_endian { u32::from_be_bytes(bytes) } else { u32::from_le_bytes(bytes) } as usize;
|
||||
source[at..at + 4].copy_from_slice(&self.number(300, 4));
|
||||
}
|
||||
}
|
||||
let mut expected = prefix;
|
||||
expected.extend(self.number((kept_table.len() / entry_bytes) as u64, count_bytes));
|
||||
expected.extend_from_slice(&kept_table);
|
||||
expected.extend_from_slice(&next);
|
||||
expected.resize(table_end + offset_bytes, 0);
|
||||
expected.extend_from_slice(&data);
|
||||
(source, expected)
|
||||
}
|
||||
}
|
||||
|
||||
/// All layout combinations share the same compaction contract, including JPEG-prefixed EXIF.
|
||||
fn layouts() -> impl Iterator<Item = Layout> {
|
||||
[false, true].into_iter().flat_map(|big_tiff| [false, true].into_iter().map(move |big_endian| Layout { big_tiff, big_endian }))
|
||||
}
|
||||
|
||||
/// Every removal mask exercises first/middle/last entries, adjacent runs, all and none removed.
|
||||
/// Mixed valid duplicates must still be rewritten and unrelated payload offsets must not move.
|
||||
#[test]
|
||||
fn compaction_preserves_complete_blocks_for_removal_patterns() {
|
||||
for layout in layouts() {
|
||||
for mask in 0..256 {
|
||||
let cases: Vec<u8> = (0..8).map(|i| if mask & (1 << i) != 0 { 1 + (i % 3) as u8 } else { [0, 4, 5, 6][i % 4] }).collect();
|
||||
let (source, expected) = layout.fixture(&cases);
|
||||
for prefix in [b"".as_slice(), b"Exif\0\0".as_slice()] {
|
||||
let source = [prefix, &source].concat();
|
||||
let expected = [prefix, &expected].concat();
|
||||
assert_eq!(exif_with_resolution(&source, (240.0, 240.0)).as_ref(), expected, "mask {mask}");
|
||||
}
|
||||
}
|
||||
let (source, expected) = layout.fixture(&[7, 4, 1, 4, 8, 5, 2, 5, 3, 6, 9, 0]);
|
||||
assert_eq!(exif_with_resolution(&source, (240.0, 240.0)).as_ref(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalid output resolution, empty/missing metadata and already-correct first duplicates keep
|
||||
/// the borrowed fast path; truncated or invalid table layouts cannot be partially compacted.
|
||||
#[test]
|
||||
fn cleanup_preserves_noop_and_invalid_layout_behavior() {
|
||||
for layout in layouts() {
|
||||
let (source, _) = layout.fixture(&[1, 4, 2, 5, 3, 6, 0]);
|
||||
for ppi in [(0.0, 240.0), (-1.0, 240.0), (f32::NAN, 240.0), (240.0, f32::INFINITY), (1_000_001.0, 240.0)] {
|
||||
assert!(matches!(exif_with_resolution(&source, ppi), Cow::Borrowed(_)));
|
||||
}
|
||||
let table_end = if layout.big_tiff { 24 + 7 * 20 + 8 } else { 10 + 7 * 12 + 4 };
|
||||
for n in 0..table_end {
|
||||
assert!(matches!(exif_with_resolution(&source[..n], (240.0, 240.0)), Cow::Borrowed(_)), "length {n}");
|
||||
}
|
||||
let mut invalid = source;
|
||||
invalid[0] = 0;
|
||||
assert!(matches!(exif_with_resolution(&invalid, (240.0, 240.0)), Cow::Borrowed(_)));
|
||||
for cases in [&[][..], &[0][..], &[4, 5, 4, 1][..]] {
|
||||
let (source, _) = layout.fixture(cases);
|
||||
assert!(matches!(exif_with_resolution(&source, (300.0, 300.0)), Cow::Borrowed(_)));
|
||||
}
|
||||
}
|
||||
assert!(matches!(exif_with_resolution(&[], (240.0, 240.0)), Cow::Borrowed(_)));
|
||||
}
|
||||
|
||||
/// A small PNG can retain many malformed eXIf entries on decode. Export must clean them while
|
||||
/// preserving pixels at both PNG depths, unrelated metadata, and the metadata-disabled option.
|
||||
#[test]
|
||||
fn png_decode_export_cleans_large_repeated_resolution_metadata() {
|
||||
let layout = Layout { big_tiff: true, big_endian: false };
|
||||
let mut cases = vec![1; 40_000];
|
||||
cases.insert(0, 0);
|
||||
cases.insert(20_000, 0);
|
||||
cases.push(0);
|
||||
let (source, mut expected) = layout.fixture(&cases);
|
||||
// Export intentionally clears the source thumbnail pointer before compaction.
|
||||
expected[24 + 3 * 20..24 + 3 * 20 + 8].fill(0);
|
||||
for depth in [png::BitDepth::Eight, png::BitDepth::Sixteen] {
|
||||
let pixels = match depth {
|
||||
png::BitDepth::Eight => vec![255, 0, 10, 255, 0, 200, 30, 128, 0, 0, 255, 255, 77, 88, 99, 0],
|
||||
_ => (0..16u16).flat_map(|v| (v * 4097).to_be_bytes()).collect(),
|
||||
};
|
||||
let mut info = png::Info::with_size(2, 2);
|
||||
info.color_type = png::ColorType::Rgba;
|
||||
info.bit_depth = depth;
|
||||
info.exif_metadata = Some(source.clone().into());
|
||||
info.uncompressed_latin1_text.push(png::text_metadata::TEXtChunk::new("Comment", "keep this text"));
|
||||
info.utf8_text.push(png::text_metadata::ITXtChunk::new("XML:com.adobe.xmp", "<x:xmpmeta>unrelated</x:xmpmeta>"));
|
||||
let mut input = Vec::new();
|
||||
png::Encoder::with_info(&mut input, info).unwrap().write_header().unwrap().write_image_data(&pixels).unwrap();
|
||||
let mut image = decode(&input).unwrap();
|
||||
assert_eq!(image.dimensions(), (2, 2));
|
||||
assert_eq!(image.layout(), ChannelLayout::Rgba);
|
||||
assert_eq!(image.sample_type(), if depth == png::BitDepth::Eight { SampleType::U8 } else { SampleType::U16 });
|
||||
let native_pixels: Vec<u8> = if depth == png::BitDepth::Eight {
|
||||
pixels.clone()
|
||||
} else {
|
||||
pixels.as_chunks::<2>().0.iter().flat_map(|p| u16::from_be_bytes(*p).to_ne_bytes()).collect()
|
||||
};
|
||||
assert_eq!(image.data(), native_pixels);
|
||||
assert_eq!(image.meta.exif.as_deref(), Some(source.as_slice()));
|
||||
image.meta.dpi = Some((240.0, 240.0));
|
||||
let output = encode(&image, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let restored = decode(&output).unwrap();
|
||||
assert_eq!(restored.data(), image.data());
|
||||
assert_eq!(restored.dimensions(), image.dimensions());
|
||||
assert_eq!(restored.layout(), image.layout());
|
||||
assert_eq!(restored.sample_type(), image.sample_type());
|
||||
assert_eq!(restored.meta.exif.as_deref(), Some(expected.as_slice()));
|
||||
assert_eq!(restored.meta.text, image.meta.text);
|
||||
assert_eq!(restored.meta.xmp, image.meta.xmp);
|
||||
assert_eq!(restored.meta.dpi, Some((240.0, 240.0)));
|
||||
let output = encode(&image, Format::Png, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap();
|
||||
let stripped = decode(&output).unwrap();
|
||||
assert_eq!(stripped.data(), image.data());
|
||||
assert!(stripped.meta.exif.is_none() && stripped.meta.xmp.is_none() && stripped.meta.text.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -839,3 +839,109 @@ fn zoo_long_random_mutations() {
|
||||
poke(&g);
|
||||
}
|
||||
}
|
||||
|
||||
/// A 64-bit gray page whose strips decode through a scratch buffer four times the size of their
|
||||
/// output rows: every sample of row `y` is `y << 48` (it reads back as the 16-bit value `y`).
|
||||
fn wide_gray(w: u32, h: u32, rows: u32) -> Vec<u8> {
|
||||
let px: Vec<u8> = (0..h).flat_map(|y| (0..w).flat_map(move |_| (u64::from(y) << 48).to_le_bytes())).collect();
|
||||
build(true, false, &[strips(w, h, 64, 1, 1, rows, &px)], &[0]).bytes
|
||||
}
|
||||
|
||||
/// Decode options whose only change from the defaults is `max_alloc`.
|
||||
fn with_max_alloc(max_alloc: u64) -> DecodeOptions {
|
||||
DecodeOptions { limits: Limits { max_alloc, ..Limits::default() }, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A strip's scratch buffer is charged against `max_alloc` next to the output it decodes into.
|
||||
#[test]
|
||||
fn strip_scratch_counts_against_max_alloc() {
|
||||
// 64×64: an 8 KiB 16-bit output, but its one strip is 32 KiB of 64-bit samples, decoded
|
||||
// into a scratch buffer held next to the output. The two together are over 36 KiB.
|
||||
let file = wide_gray(64, 64, 64);
|
||||
let r = decode_with(&file, &with_max_alloc(36 << 10));
|
||||
assert!(matches!(r, Err(CodecError::LimitExceeded(_))), "output plus strip scratch over max_alloc: {:?}", r.map(|i| i.data().len()));
|
||||
// With room for both it decodes.
|
||||
let img = decode_with(&file, &with_max_alloc(48 << 10)).unwrap();
|
||||
assert_eq!(img.to_u16_samples().unwrap()[64 * 63], 63);
|
||||
}
|
||||
|
||||
/// A page's strip tables are charged against `max_alloc` before the `tiff` crate reads them:
|
||||
/// it reads both tables in full while it opens the directory, under its own default limits.
|
||||
/// A 1x65536 gray page in one-row strips holds a 64 KiB image but 65536 strips, 1 MiB of
|
||||
/// tables as the decoder keeps them. Under a 512 KiB budget it used to open the decoder (and
|
||||
/// allocate those tables) before the band worker's budget refused it; it is now refused first.
|
||||
#[test]
|
||||
fn strip_tables_are_refused_before_the_decoder_opens() {
|
||||
let h = 65_536u32;
|
||||
let file = build(true, false, &[strips(1, h, 8, 1, 1, 1, &vec![7u8; h as usize])], &[0]).bytes;
|
||||
match decode_with(&file, &with_max_alloc(512 << 10)) {
|
||||
Err(CodecError::LimitExceeded(m)) => assert!(m.contains("tables") && m.contains("65536 chunks"), "{m}"),
|
||||
other => panic!("tables over max_alloc must be refused: {:?}", other.map(|i| i.data().len())),
|
||||
}
|
||||
// With room for the image and one worker's tables it decodes.
|
||||
let img = decode_with(&file, &with_max_alloc(4 << 20)).unwrap();
|
||||
assert_eq!(img.dimensions(), (1, h));
|
||||
assert!(img.data().iter().all(|&v| v == 7));
|
||||
}
|
||||
|
||||
/// Room for one worker's scratch decodes every strip with that one worker, each in its place.
|
||||
#[test]
|
||||
fn a_tight_budget_decodes_its_strips_one_after_another() {
|
||||
// 64×512 in eight 32 KiB strips: a 64 KiB output with room for only one strip's scratch
|
||||
// beside it, so the bands are decoded by one worker, in order, and still land in place.
|
||||
let file = wide_gray(64, 512, 64);
|
||||
let img = decode_with(&file, &with_max_alloc((64 + 40) << 10)).unwrap();
|
||||
let v = img.to_u16_samples().unwrap();
|
||||
for y in 0..512 {
|
||||
assert_eq!(v[y * 64], y as u16, "row {y}");
|
||||
assert_eq!(v[y * 64 + 63], y as u16, "row {y}");
|
||||
}
|
||||
// Unlimited, the same file decodes the same in parallel.
|
||||
assert_eq!(decode(&file).unwrap().to_u16_samples().unwrap(), v);
|
||||
}
|
||||
|
||||
/// The `tiff` crate decodes each row of a floating-point-predicted tile into a buffer of the
|
||||
/// declared tile width. A 64x64 page declaring TileWidth 0xFFFFFFFF asked for about 103 GB
|
||||
/// there, unbudgeted (an allocation failure aborts); it is now refused with a limit error.
|
||||
#[test]
|
||||
fn a_float_predictor_row_of_a_hostile_tile_width_is_refused() {
|
||||
let (w, h) = (64u32, 64u32);
|
||||
let tile = vec![0u8; (w * h * 3 * 8) as usize];
|
||||
let d = Dir { entries: base(w, h, 64, 3, 2), chunks: vec![tile], tiled: true }
|
||||
.tag(322, LONG, &[0xFFFF_FFFF])
|
||||
.tag(323, LONG, &[u64::from(h)])
|
||||
.tag(317, SHORT, &[3])
|
||||
.tag(339, SHORT, &[3]);
|
||||
let file = build(true, false, &[d], &[0]).bytes;
|
||||
let r = decode_with(&file, &with_max_alloc(1 << 30));
|
||||
assert!(matches!(r, Err(CodecError::LimitExceeded(_))), "{:?}", r.map(|i| i.data().len()));
|
||||
}
|
||||
|
||||
/// The JPEG headers of every tile are read before the decode. 65536 JPEG tiles that all span
|
||||
/// the same 512 KiB without a 0xFF (the file's own offset and byte-count tables) made that read
|
||||
/// step through about 34 billion bytes; it is now bounded by the file's length (plus a few steps
|
||||
/// per tile), and the page is refused at once.
|
||||
#[test]
|
||||
fn overlapping_jpeg_tiles_without_markers_are_refused_quickly() {
|
||||
let (w, h, tile) = (4096u32, 4096u32, 16u32);
|
||||
let n = ((w / tile) * (h / tile)) as usize;
|
||||
let mut entries = base(w, h, 8, 1, 1);
|
||||
entries.retain(|e| e.0 != 259);
|
||||
// The tables are the first thing after the header, at 8: every tile spans both of them
|
||||
// (LONG offsets of 8 and counts of 8n, neither holding a 0xFF byte).
|
||||
let offsets = vec![8u64; n];
|
||||
let counts = vec![8 * n as u64; n];
|
||||
let d = Dir { entries, chunks: Vec::new(), tiled: true }
|
||||
.tag(259, SHORT, &[7])
|
||||
.tag(322, LONG, &[u64::from(tile)])
|
||||
.tag(323, LONG, &[u64::from(tile)])
|
||||
.tag(324, LONG, &offsets)
|
||||
.tag(325, LONG, &counts);
|
||||
let file = build(true, false, &[d], &[0]).bytes;
|
||||
assert!(file.len() > 8 + 8 * n, "the tables are in the file");
|
||||
assert!(!file[8..8 + 8 * n].contains(&0xFF), "no marker in the tiles");
|
||||
let started = std::time::Instant::now();
|
||||
let r = decode(&file);
|
||||
assert!(matches!(r, Err(CodecError::InvalidImage(_))), "{:?}", r.map(|i| i.data().len()));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(30), "took {:?}", started.elapsed());
|
||||
}
|
||||
@@ -218,12 +218,13 @@ fn a_wrong_sized_plane_is_refused_before_a_sample_type_conversion() {
|
||||
}
|
||||
|
||||
/// Extra samples count against `max_alloc` with the image (their interleaved buffer and the
|
||||
/// planes split from it): a budget that holds the RGB image but not sixteen extra planes opens
|
||||
/// the image without them, with a warning, instead of allocating past it.
|
||||
/// planes split from it): a budget that holds the RGB image and one strip's decode scratch but not
|
||||
/// sixteen extra planes opens the image without them, with a warning, instead of allocating past
|
||||
/// it.
|
||||
#[test]
|
||||
fn extra_samples_count_against_the_allocation_limit() {
|
||||
// Big enough for several strips (about 1 MB each): one strip of all 19 samples fits the budget
|
||||
// of the image alone, as in real files.
|
||||
// Big enough for several strips (about 1 MB each). Each strip of all 19 samples is decoded
|
||||
// through a scratch buffer that counts against the budget too: 1 MiB more than the image.
|
||||
let (w, h) = (1024u32, 1024u32);
|
||||
let n = (w * h) as usize;
|
||||
let mut img = synth(w, h, ChannelLayout::Rgb, SampleType::U8, 1, 0.0);
|
||||
@@ -232,18 +233,21 @@ fn extra_samples_count_against_the_allocation_limit() {
|
||||
let with = |max_alloc: u64| decode_with(&bytes, &DecodeOptions { limits: Limits { max_alloc, ..Limits::default() }, ..DecodeOptions::default() });
|
||||
// RGB is 3 bytes a pixel; the extra samples add 2 x 16 more.
|
||||
let image_only = 3 * n as u64;
|
||||
let strip_room = 1u64 << 20;
|
||||
let with_extras = (3 + 2 * MAX_EXTRA_SAMPLES as u64) * n as u64;
|
||||
let back = with(with_extras).expect("everything fits");
|
||||
assert_eq!(back.meta.extra_samples.len(), MAX_EXTRA_SAMPLES);
|
||||
assert!(back.warnings.is_empty());
|
||||
// The image fits, its extra samples don't: it opens as before they were read, with a warning.
|
||||
for max_alloc in [image_only, with_extras - 1] {
|
||||
for max_alloc in [image_only + strip_room, with_extras - 1] {
|
||||
let only = with(max_alloc).expect("the image alone fits");
|
||||
assert!(only.meta.extra_samples.is_empty());
|
||||
assert_eq!(only.warnings, vec![DecodeWarning::ExtraSamplesDropped { format: Format::Tiff, count: MAX_EXTRA_SAMPLES as u32 }]);
|
||||
assert_eq!(only.data(), back.data());
|
||||
}
|
||||
assert!(matches!(with(image_only - 1), Err(CodecError::LimitExceeded(_))), "the image itself must still fit");
|
||||
// The image fits but a strip's scratch beside it doesn't: refused, not decoded past the budget.
|
||||
assert!(matches!(with(image_only), Err(CodecError::LimitExceeded(_))), "the strip scratch counts too");
|
||||
}
|
||||
|
||||
/// The value field of a little-endian classic TIFF's ExtraSamples entry (tag 338, SHORT) holding
|
||||
|
||||
@@ -174,3 +174,39 @@ fn default_tiff_is_baseline() {
|
||||
assert_eq!(decode(&bytes).expect("decode").data(), img.data(), "{layout:?}: round trip");
|
||||
}
|
||||
}
|
||||
|
||||
fn refusal(bytes: &[u8]) -> String {
|
||||
match decode(bytes) {
|
||||
Err(e) => e.to_string(),
|
||||
Ok(i) => panic!("decoded a {}x{} image", i.width(), i.height()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_structural_tag_is_refused() {
|
||||
// SamplesPerPixel 1 first (what the directory checks read), 64 last (what the backend reads).
|
||||
let dir = strips(4, 1, 8, 1, 1, 1, &[1, 2, 3, 4]).tag(277, SHORT, &[64]);
|
||||
let bytes = build(true, false, &[dir], &[0]).bytes;
|
||||
let e = refusal(&bytes);
|
||||
assert!(e.contains("277 appears more than once"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_jpeg_strip_larger_than_its_strip_is_refused() {
|
||||
let mut jpeg = Vec::new();
|
||||
jpeg_encoder::Encoder::new(&mut jpeg, 95).encode(&[100u8; 64 * 64], 64, 64, jpeg_encoder::ColorType::Luma).expect("encode the JPEG strip");
|
||||
let mut dir = with_compression(strips(16, 16, 8, 1, 1, 16, &[0; 256]), 7);
|
||||
dir.chunks = vec![jpeg];
|
||||
let e = refusal(&build(true, false, &[dir], &[0]).bytes);
|
||||
assert!(e.contains("64x64 JPEG frame in a 16x16 strip"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_float_predicted_tile_row_wider_than_the_scratch_cap_is_refused() {
|
||||
// A 16x16 32-bit float image in one tile 2^25 samples wide: the floating-point predictor
|
||||
// would make the backend allocate a 128 MiB row for it.
|
||||
let mut dir = Dir { entries: base(16, 16, 32, 1, 1), chunks: vec![vec![0; 64]], tiled: true };
|
||||
dir = with_compression(dir, 8).tag(317, SHORT, &[3]).tag(322, LONG, &[1 << 25]).tag(323, LONG, &[16]).tag(339, SHORT, &[3]);
|
||||
let e = refusal(&build(true, false, &[dir], &[0]).bytes);
|
||||
assert!(e.contains("predicted tile row"), "{e}");
|
||||
}
|
||||
+140
-4
@@ -183,10 +183,81 @@ pub fn blend_channel(mode: BlendMode, cb: f32, cs: f32) -> f32 {
|
||||
|
||||
/// [`blend_channel`] for 32-bit float documents, whose values may exceed 1: Linear Dodge (Add)
|
||||
/// and Divide don't clip at 1 there (Photoshop's 32-bit Add is how light is added in HDR), only
|
||||
/// at `f32::MAX`, so they stay finite. Every other mode is [`blend_channel`].
|
||||
/// at `f32::MAX`, so they stay finite. Nonfinite results from finite inputs are retried in F64
|
||||
/// and saturated to the signed F32 range. Ordinary finite F32 results keep their rounding;
|
||||
/// Multiply also uses signed finite saturation for coverage-compositing callers.
|
||||
#[inline]
|
||||
pub fn blend_channel_hdr(mode: BlendMode, cb: f32, cs: f32) -> f32 {
|
||||
channel(mode, cb, cs, f32::MAX)
|
||||
let out = channel(mode, cb, cs, f32::MAX);
|
||||
if !out.is_finite() && cb.is_finite() && cs.is_finite() {
|
||||
return channel_hdr_wide(mode, cb, cs);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cold]
|
||||
/// Reevaluate an overflowing separable blend in F64 before bounding its signed F32 result.
|
||||
fn channel_hdr_wide(mode: BlendMode, cb: f32, cs: f32) -> f32 {
|
||||
let (b, s) = (f64::from(cb), f64::from(cs));
|
||||
let hard_light = |b: f64, s: f64| {
|
||||
if s <= 0.5 {
|
||||
b * 2.0 * s
|
||||
} else {
|
||||
let s = 2.0 * s - 1.0;
|
||||
b + (1.0 - b) * s
|
||||
}
|
||||
};
|
||||
let out = match mode {
|
||||
BlendMode::Screen => b + s - b * s,
|
||||
BlendMode::LinearBurn => (b + s - 1.0).max(0.0),
|
||||
BlendMode::LinearDodge => b + s,
|
||||
BlendMode::Overlay => hard_light(s, b),
|
||||
BlendMode::HardLight => hard_light(b, s),
|
||||
BlendMode::SoftLight => {
|
||||
if s <= 0.5 {
|
||||
b + (1.0 - 2.0 * s) * (b * b - b)
|
||||
} else {
|
||||
let backdrop = b.max(0.0);
|
||||
let d = if backdrop <= 0.25 { ((16.0 * backdrop - 12.0) * backdrop + 4.0) * backdrop } else { backdrop.sqrt() };
|
||||
if d == b { b } else { 2.0 * b * (1.0 - s) + d * (2.0 * s - 1.0) }
|
||||
}
|
||||
}
|
||||
BlendMode::PinLight => {
|
||||
if s <= 0.5 {
|
||||
b.min(2.0 * s)
|
||||
} else {
|
||||
b.max(2.0 * s - 1.0)
|
||||
}
|
||||
}
|
||||
BlendMode::Difference => (b - s).abs(),
|
||||
BlendMode::Exclusion => b * (1.0 - 2.0 * s) + s,
|
||||
BlendMode::Subtract => (b - s).max(0.0),
|
||||
BlendMode::Divide => {
|
||||
if s <= 0.0 {
|
||||
if b <= 0.0 { 0.0 } else { 1.0 }
|
||||
} else {
|
||||
b / s
|
||||
}
|
||||
}
|
||||
BlendMode::Negation => 1.0 - (1.0 - b - s).abs(),
|
||||
BlendMode::PaintNetColorBurn => {
|
||||
if s <= 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
(1.0 - (1.0 - b) / s).max(0.0)
|
||||
}
|
||||
}
|
||||
BlendMode::PaintNetColorDodge => {
|
||||
if s >= 1.0 {
|
||||
1.0
|
||||
} else {
|
||||
(b / (1.0 - s)).min(1.0)
|
||||
}
|
||||
}
|
||||
// The remaining scalar formulas already produce finite output for finite inputs.
|
||||
_ => f64::from(channel(mode, cb, cs, f32::MAX)),
|
||||
};
|
||||
out.clamp(-f64::from(f32::MAX), f64::from(f32::MAX)) as f32
|
||||
}
|
||||
|
||||
/// `B(cb, cs)` with Linear Dodge and Divide clipped at `hi` (1 at integer depths).
|
||||
@@ -195,7 +266,7 @@ fn channel(mode: BlendMode, cb: f32, cs: f32, hi: f32) -> f32 {
|
||||
match mode {
|
||||
BlendMode::Normal | BlendMode::Dissolve | BlendMode::PassThrough => cs,
|
||||
BlendMode::Darken => cb.min(cs),
|
||||
BlendMode::Multiply => cb * cs,
|
||||
BlendMode::Multiply => (cb * cs).clamp(-f32::MAX, f32::MAX),
|
||||
BlendMode::ColorBurn => color_burn(cb, cs),
|
||||
BlendMode::LinearBurn => (cb + cs - 1.0).max(0.0),
|
||||
BlendMode::Lighten => cb.max(cs),
|
||||
@@ -438,7 +509,72 @@ pub fn blend_rgb_within(mode: BlendMode, cb: [f32; 3], cs: [f32; 3], top: f32) -
|
||||
/// [`blend_rgb`] for 32-bit float documents: separable modes use [`blend_channel_hdr`], and the
|
||||
/// non-separable ones keep values above 1 ([`blend_rgb_within`] at `f32::MAX`).
|
||||
pub fn blend_rgb_hdr(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
|
||||
if mode.is_separable() { std::array::from_fn(|i| blend_channel_hdr(mode, cb[i], cs[i])) } else { blend_rgb_within(mode, cb, cs, f32::MAX) }
|
||||
if mode.is_separable() {
|
||||
return std::array::from_fn(|i| blend_channel_hdr(mode, cb[i], cs[i]));
|
||||
}
|
||||
let out = blend_rgb_within(mode, cb, cs, f32::MAX);
|
||||
if out.iter().all(|v| v.is_finite()) || cb.iter().chain(&cs).any(|v| !v.is_finite()) {
|
||||
return out;
|
||||
}
|
||||
nonseparable_hdr_wide(mode, cb, cs)
|
||||
}
|
||||
|
||||
/// Only replay overflowing finite inputs. A shared F32 normalization can erase a tiny
|
||||
/// source's hue; raw F32 inputs and these helpers' products fit safely in F64.
|
||||
#[cold]
|
||||
fn nonseparable_hdr_wide(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
|
||||
/// Compute the nonseparable blend luminance directly from wide RGB channels.
|
||||
fn lum(c: [f64; 3]) -> f64 {
|
||||
0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
|
||||
}
|
||||
/// Measure wide RGB saturation as the distance between its largest and smallest channels.
|
||||
fn sat(c: [f64; 3]) -> f64 {
|
||||
c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
|
||||
}
|
||||
/// Rescale wide RGB saturation while preserving channel order and placing the minimum channel at zero.
|
||||
fn set_sat(c: [f64; 3], s: f64) -> [f64; 3] {
|
||||
let mut idx = [0usize, 1, 2];
|
||||
idx.sort_by(|&a, &b| c[a].total_cmp(&c[b]));
|
||||
let (imin, imid, imax) = (idx[0], idx[1], idx[2]);
|
||||
let mut out = [0.; 3];
|
||||
if c[imax] > c[imin] {
|
||||
out[imid] = (c[imid] - c[imin]) * s / (c[imax] - c[imin]);
|
||||
out[imax] = s;
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Shift wide RGB to the requested luminance and compress gamut excursions against the F32 white point.
|
||||
fn set_lum(c: [f64; 3], target: f64) -> [f64; 3] {
|
||||
let d = target - lum(c);
|
||||
let c = c.map(|v| v + d);
|
||||
let l = lum(c);
|
||||
let n = c[0].min(c[1]).min(c[2]);
|
||||
let x = c[0].max(c[1]).max(c[2]);
|
||||
let top = f64::from(f32::MAX);
|
||||
let mut out = c;
|
||||
if n < 0. {
|
||||
let d = l - n;
|
||||
for v in &mut out {
|
||||
*v = if l > 0. && d > 0. { l + (*v - l) * l / d } else { l };
|
||||
}
|
||||
}
|
||||
if x > top {
|
||||
let d = x - l;
|
||||
for v in &mut out {
|
||||
*v = if l < top && d > 0. { l + (*v - l) * (top - l) / d } else { l };
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
let (cb, cs) = (cb.map(f64::from), cs.map(f64::from));
|
||||
let out = match mode {
|
||||
BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)),
|
||||
BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)),
|
||||
BlendMode::Color => set_lum(cs, lum(cb)),
|
||||
BlendMode::Luminosity => set_lum(cb, lum(cs)),
|
||||
_ => cs,
|
||||
};
|
||||
out.map(|v| v.clamp(-f64::from(f32::MAX), f64::from(f32::MAX)) as f32)
|
||||
}
|
||||
|
||||
/// Composite a straight-alpha source over a straight-alpha backdrop with blend mode and opacity.
|
||||
|
||||
@@ -2,6 +2,145 @@ use super::*;
|
||||
|
||||
const E: f32 = 1e-5;
|
||||
|
||||
#[test]
|
||||
/// Bound extreme separable HDR blends while preserving ordinary finite F32 bits and integer-depth behavior.
|
||||
fn separable_hdr_extremes_stay_finite_and_keep_ordinary_f32_bits() {
|
||||
let max = f32::MAX;
|
||||
let values = [-max, -max / 2., -2e19, -4., -1., -0., 0., f32::from_bits(1), 1e-20, 0.25, 0.5, 0.75, 1., 4., 2e19, max / 2., max];
|
||||
for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).filter(|m| m.is_separable()) {
|
||||
for cb in values {
|
||||
for cs in values {
|
||||
let ordinary = channel(mode, cb, cs, max);
|
||||
let actual = blend_channel_hdr(mode, cb, cs);
|
||||
assert!(actual.is_finite(), "{mode:?}: {cb}, {cs} -> {actual}");
|
||||
if ordinary.is_finite() {
|
||||
assert_eq!(actual.to_bits(), ordinary.to_bits(), "{mode:?}: ordinary rounding changed for {cb}, {cs}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let rgb = blend_rgb_hdr(mode, [max, -max, 0.5], [-max, max, max]);
|
||||
assert!(rgb.iter().all(|v| v.is_finite()), "{mode:?}: {rgb:?}");
|
||||
// Standard-range calls keep the integer API's results except its intentional Add/Divide cap.
|
||||
for cb in [0., 0.25, 0.5, 0.75, 1.] {
|
||||
for cs in [0., 0.25, 0.5, 0.75, 1.] {
|
||||
if !matches!(mode, BlendMode::LinearDodge | BlendMode::Divide) {
|
||||
assert_eq!(blend_channel_hdr(mode, cb, cs).to_bits(), blend_channel(mode, cb, cs).to_bits(), "{mode:?}: {cb}, {cs}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(blend_channel(BlendMode::LinearDodge, 0.75, 0.75), 1.);
|
||||
assert_eq!(blend_channel_hdr(BlendMode::LinearDodge, 0.75, 0.75), 1.5);
|
||||
assert_eq!(blend_channel(BlendMode::Divide, 0.75, 0.25), 1.);
|
||||
assert_eq!(blend_channel_hdr(BlendMode::Divide, 0.75, 0.25), 3.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Pin signed saturation and blend identities when finite HDR operands require a wide retry.
|
||||
fn overflowing_hdr_retries_keep_signed_results_and_blend_identities() {
|
||||
use BlendMode::*;
|
||||
let max = f32::MAX;
|
||||
for (mode, b, s, expected) in [
|
||||
(Exclusion, max, max, -max),
|
||||
(Exclusion, max, 0.5, 0.5),
|
||||
(Exclusion, -max, 0.5, 0.5),
|
||||
(HardLight, max, 0., 0.),
|
||||
(HardLight, max, 0.5, max),
|
||||
(HardLight, 1., max, 1.),
|
||||
(Overlay, 0., max, 0.),
|
||||
(Overlay, 0.5, max, max),
|
||||
(Overlay, max, 1., 1.),
|
||||
(SoftLight, max, 0.5, max),
|
||||
(SoftLight, max, 1., max.sqrt()),
|
||||
(SoftLight, 1., max, 1.),
|
||||
(Difference, max, -max, max),
|
||||
(Subtract, max, -max, max),
|
||||
(LinearBurn, max, max, max),
|
||||
(LinearBurn, max, -max, 0.),
|
||||
(LinearDodge, -max, -max, -max),
|
||||
(Divide, -max, f32::from_bits(1), -max),
|
||||
(PinLight, 0., -max, -max),
|
||||
(PinLight, 0., max, max),
|
||||
(Negation, max, max, -max),
|
||||
(PaintNetColorBurn, max, f32::from_bits(1), max),
|
||||
(PaintNetColorDodge, -max, 0.5, -max),
|
||||
] {
|
||||
assert_eq!(blend_channel_hdr(mode, b, s), expected, "{mode:?}: {b}, {s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Retain tiny and subnormal source hue ordering when the backdrop approaches the F32 limit.
|
||||
fn overflowing_hdr_hue_keeps_even_subnormal_source_channel_ordering() {
|
||||
let max = f32::MAX;
|
||||
let cb = [max, -max / 2., 0.];
|
||||
// Backdrop luminosity is .005 * MAX. Pure green at that luminosity is
|
||||
// .005/.59 * MAX, irrespective of the positive source's magnitude.
|
||||
for tiny in [1e-20, f32::from_bits(1)] {
|
||||
let out = blend_rgb_hdr(BlendMode::Hue, cb, [0., tiny, 0.]);
|
||||
assert!(out.iter().all(|v| v.is_finite()), "{tiny}: {out:?}");
|
||||
assert!(out[1] > out[0] && out[1] > out[2], "tiny green hue became gray: {out:?}");
|
||||
assert!((out[1] / max - 0.005 / 0.59).abs() < 1e-6, "{out:?}");
|
||||
assert!((out[0] / max).abs() < 1e-6 && (out[2] / max).abs() < 1e-6, "{out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Retry only overflowing HDR Screen results while retaining ordinary F32 and integer-entry arithmetic.
|
||||
fn hdr_screen_replays_only_nonfinite_results_in_wide_arithmetic() {
|
||||
let max = f32::MAX;
|
||||
assert_eq!(blend_channel_hdr(BlendMode::Screen, 2e19, 2e19), -max);
|
||||
assert_eq!(blend_channel_hdr(BlendMode::Screen, max, max), -max);
|
||||
let values = [-max, -2e19, -1., -0., 0., f32::from_bits(1), 0.25, 1., 2e19, max];
|
||||
for cb in values {
|
||||
for cs in values {
|
||||
let ordinary = cb + cs - cb * cs;
|
||||
let actual = blend_channel_hdr(BlendMode::Screen, cb, cs);
|
||||
assert!(actual.is_finite(), "{cb}, {cs}: {actual}");
|
||||
if ordinary.is_finite() {
|
||||
assert_eq!(actual.to_bits(), ordinary.to_bits(), "ordinary F32 rounding changed for {cb}, {cs}");
|
||||
} else {
|
||||
let (b, s) = (f64::from(cb), f64::from(cs));
|
||||
let expected = (b + s - b * s).clamp(-f64::from(max), f64::from(max)) as f32;
|
||||
assert_eq!(actual.to_bits(), expected.to_bits(), "{cb}, {cs}");
|
||||
}
|
||||
// The integer-depth entry point retains its established arithmetic.
|
||||
assert_eq!(blend_channel(BlendMode::Screen, cb, cs).to_bits(), ordinary.to_bits());
|
||||
}
|
||||
}
|
||||
assert_eq!(blend_rgb_hdr(BlendMode::Screen, [max, -max, 2e19], [max, max, 2e19]), [-max, max, -max]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Keep nonseparable blends finite at signed F32 extremes without changing ordinary blend results.
|
||||
fn finite_signed_extreme_nonseparable_hdr_does_not_publish_infinity_or_nan() {
|
||||
let max = f32::MAX;
|
||||
let gray = [max; 3];
|
||||
let signed = [max, -max, 0.];
|
||||
// The original SetLum subtraction overflowed before gamut clipping could produce white.
|
||||
for (mode, cb, cs) in [(BlendMode::Color, gray, signed), (BlendMode::Luminosity, signed, gray)] {
|
||||
let out = blend_rgb_hdr(mode, cb, cs);
|
||||
assert!(out.iter().all(|v| v.is_finite()), "{mode:?}: {out:?}");
|
||||
for value in out {
|
||||
assert!((value / max - 1.).abs() < E, "{mode:?}: {out:?}");
|
||||
}
|
||||
}
|
||||
let values = [-max, 0., max];
|
||||
for mode in [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity] {
|
||||
for b in 0..27 {
|
||||
let cb = [values[b % 3], values[b / 3 % 3], values[b / 9]];
|
||||
for s in 0..27 {
|
||||
let cs = [values[s % 3], values[s / 3 % 3], values[s / 9]];
|
||||
let out = blend_rgb_hdr(mode, cb, cs);
|
||||
assert!(out.iter().all(|v| v.is_finite()), "{mode:?}: {cb:?}, {cs:?} -> {out:?}");
|
||||
}
|
||||
}
|
||||
for (cb, cs) in [([0.2, 0.7, 0.4], [0.8, 0.3, 0.6]), ([-0.5, 2., 4.], [8., 0.25, -1.])] {
|
||||
assert_eq!(blend_rgb_hdr(mode, cb, cs), blend_rgb_within(mode, cb, cs, max));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: f32, b: f32) -> bool {
|
||||
(a - b).abs() < E
|
||||
}
|
||||
@@ -186,6 +325,10 @@ fn add_and_divide_clip_at_integer_depths_but_not_in_float() {
|
||||
assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, -1.0), 1.0);
|
||||
assert_eq!(blend_channel_hdr(BlendMode::Divide, f32::MAX, 1e-30), f32::MAX);
|
||||
assert_eq!(blend_channel_hdr(BlendMode::LinearDodge, f32::MAX, f32::MAX), f32::MAX);
|
||||
assert_eq!(blend_channel_hdr(BlendMode::Multiply, f32::MAX, 2.0), f32::MAX);
|
||||
assert_eq!(blend_channel_hdr(BlendMode::Multiply, f32::MAX, -2.0), -f32::MAX);
|
||||
assert_eq!(blend_channel_hdr(BlendMode::Multiply, -f32::MAX, -2.0), f32::MAX);
|
||||
assert_eq!(blend_channel(BlendMode::Multiply, f32::MAX, 2.0), f32::MAX);
|
||||
assert!(blend_channel_hdr(BlendMode::LinearDodge, f32::INFINITY, 1.0).is_finite());
|
||||
// Every other separable mode is unchanged (the non-separable ones keep values above 1:
|
||||
// blend_rgb_within), and the in-range results agree.
|
||||
|
||||
@@ -246,7 +246,7 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept
|
||||
}
|
||||
})
|
||||
}
|
||||
Adjustment::GradientMap { stops, reverse, dither } => {
|
||||
Adjustment::GradientMap { stops, reverse, dither, .. } => {
|
||||
let (w, x0, y0) = (buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0);
|
||||
for (i, p) in buf.px.iter_mut().enumerate() {
|
||||
if p[3] <= 0.0 {
|
||||
|
||||
@@ -257,7 +257,7 @@ pub(super) fn apply_lab(adj: &Adjustment, buf: &mut Buffer, depth: Option<Sample
|
||||
std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0))
|
||||
})
|
||||
}
|
||||
Adjustment::GradientMap { stops, reverse, dither } => {
|
||||
Adjustment::GradientMap { stops, reverse, dither, .. } => {
|
||||
let (w, x0, y0) = (buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0);
|
||||
for (i, p) in buf.px.iter_mut().enumerate() {
|
||||
if p[3] <= 0.0 {
|
||||
|
||||
@@ -672,7 +672,7 @@ fn gradient_map_follows_the_w3c_luminosity() {
|
||||
let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])];
|
||||
for (c, t) in [([0.0, 1.0, 0.0], 0.59), ([1.0, 0.0, 0.0], 0.3), ([0.0, 0.0, 1.0], 0.11), ([0.2, 0.6, 0.9], 0.513)] {
|
||||
let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]);
|
||||
apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut b);
|
||||
apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false, source: None }, &mut b);
|
||||
assert!((b.px[0][0] - t).abs() < 1e-5, "{c:?}: {}", b.px[0][0]);
|
||||
}
|
||||
}
|
||||
@@ -682,8 +682,8 @@ fn gradient_map_dither_stays_close() {
|
||||
let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])];
|
||||
let mut a = ramp();
|
||||
let mut b = ramp();
|
||||
apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut a);
|
||||
apply(&Adjustment::GradientMap { stops, reverse: false, dither: true }, &mut b);
|
||||
apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false, source: None }, &mut a);
|
||||
apply(&Adjustment::GradientMap { stops, reverse: false, dither: true, source: None }, &mut b);
|
||||
assert!(a.px.iter().zip(&b.px).all(|(x, y)| (x[0] - y[0]).abs() <= 0.5 / 255.0 + 1e-6));
|
||||
assert!(a.px.iter().zip(&b.px).any(|(x, y)| x[0] != y[0]));
|
||||
}
|
||||
@@ -846,7 +846,7 @@ fn lab_brightness_contrast_moves_l_only() {
|
||||
fn lab_gradient_map_follows_l() {
|
||||
let stops = vec![(0.0, [1.0, 0.0, 0.0]), (1.0, [0.0, 0.0, 1.0])];
|
||||
for reverse in [false, true] {
|
||||
let map = Adjustment::GradientMap { stops: stops.clone(), reverse, dither: false };
|
||||
let map = Adjustment::GradientMap { stops: stops.clone(), reverse, dither: false, source: None };
|
||||
// A grey and a saturated colour with the same L map to the same colour.
|
||||
let grey = in_lab(&map, lab(60.0, 0.0, 0.0));
|
||||
let green = in_lab(&map, lab(60.0, -50.0, 40.0));
|
||||
@@ -873,7 +873,7 @@ fn other_modes_and_adjustments_keep_the_screen_colour_path() {
|
||||
}
|
||||
// Transparent pixels are left alone and odd values never panic.
|
||||
let mut t = Buffer::filled(crate::Rect::new(0, 0, 2, 1), [f32::NAN, 2.0, -1.0, 0.0]);
|
||||
for adj in lab_only.iter().chain([&Adjustment::GradientMap { stops: vec![], reverse: true, dither: true }]) {
|
||||
for adj in lab_only.iter().chain([&Adjustment::GradientMap { stops: vec![], reverse: true, dither: true, source: None }]) {
|
||||
for mode in [ColorMode::Lab, ColorMode::Cmyk] {
|
||||
apply_in(adj, &mut t, Transfer::Srgb, None, mode);
|
||||
let mut odd = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [f32::NAN, f32::INFINITY, -3.0, 1.0]);
|
||||
|
||||
@@ -545,7 +545,25 @@ impl<'a> EffectPass<'a> {
|
||||
for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&fields.din) {
|
||||
*mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 };
|
||||
}
|
||||
paint_fx(lay, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, st.common.blend, st.common.opacity, self.patterns);
|
||||
if st.common.blend == BlendMode::Normal {
|
||||
// A Normal stroke replaces the layer under it instead of blending with it
|
||||
// (Photoshop): at 50 % opacity an opaque pixel under the stroke turns into the
|
||||
// stroke colour at 50 % alpha, not a 50/50 mix.
|
||||
let mut stroke_px = Buffer { rect: self.big, px: vec![[0.0; 4]; lay.px.len()] };
|
||||
paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, st.common.opacity, self.patterns);
|
||||
for ((p, s), cov) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) {
|
||||
if s[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let kept = p[3] * (1.0 - cov.clamp(0.0, 1.0));
|
||||
let alpha = kept + s[3];
|
||||
if alpha > 0.0 {
|
||||
*p = [(p[0] * kept + s[0] * s[3]) / alpha, (p[1] * kept + s[1] * s[3]) / alpha, (p[2] * kept + s[2] * s[3]) / alpha, alpha.min(1.0)];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
paint_fx(lay, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, st.common.blend, st.common.opacity, self.patterns);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 706 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user