mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 03:52:45 +01:00
Merge next to pick up the design lint fix
This commit is contained in:
commit
f3c16efa1f
388 files changed
+40162
-1769
No files matched your search
@@ -115,7 +115,10 @@ workflows:
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
'.github/workflows/workspace.yml': []
|
||||
'.github/workflows/workspace.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
- 'storytold/craft-common-actions@d65d611f0ef67eaa94039351be5afce61102dbb0'
|
||||
dependencies:
|
||||
'actions/cache@v6.1.0':
|
||||
ref: 'v6.1.0'
|
||||
@@ -162,8 +165,8 @@ dependencies:
|
||||
commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8'
|
||||
owner_id: 88700172
|
||||
repo_id: 1382753260
|
||||
'swatinem/rust-cache@v2.9.3':
|
||||
ref: 'v2.9.3'
|
||||
commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0'
|
||||
owner_id: 580492
|
||||
repo_id: 298565987
|
||||
'storytold/craft-common-actions@d65d611f0ef67eaa94039351be5afce61102dbb0':
|
||||
ref: 'main'
|
||||
commit: 'sha1-d65d611f0ef67eaa94039351be5afce61102dbb0'
|
||||
owner_id: 76897702
|
||||
repo_id: 1414429108
|
||||
@@ -20,6 +20,9 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
pdf-test-fonts: true
|
||||
# The instrumented build runs without a dependency cache: its 1.2 GB entry does not fit the
|
||||
# repository's 10 GB cache budget beside the Workspace gate's. It runs on main only.
|
||||
build-cache: false
|
||||
# The codec and format code behind features that are off by default. Without these the
|
||||
# coverage build never compiles it, and new code there reads as untested.
|
||||
cargo-features: >-
|
||||
|
||||
+135
-41
@@ -7,9 +7,10 @@ on:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
# A full run on main every 6 hours that is never cancelled, so the caches are saved while pushes
|
||||
# to main cancel each other.
|
||||
# to main cancel each other. The midnight run builds the Linux leg from source (`native`).
|
||||
schedule:
|
||||
- cron: "17 */6 * * *"
|
||||
- cron: "17 0 * * *"
|
||||
- cron: "17 6,12,18 * * *"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -23,49 +24,73 @@ concurrency:
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
# Whether this run needs the macOS and Windows legs. On a pull request they run only when it can
|
||||
# change platform behaviour: a crate with platform cfg code or one that depends on it, the build
|
||||
# setup, or a file outside the crates (craft-common-actions' select-platforms). The full-ci label
|
||||
# runs them anyway from the next push or manual run; every other event runs them.
|
||||
platforms:
|
||||
name: select platforms
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
platform: ${{ steps.select.outputs.platform }}
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
# The merge commit and its first parent.
|
||||
- uses: actions/checkout@v7.0.1
|
||||
if: github.event_name == 'pull_request'
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 2
|
||||
- id: select
|
||||
uses: storytold/craft-common-actions/actions/select-platforms@d65d611f0ef67eaa94039351be5afce61102dbb0
|
||||
with:
|
||||
os: '["ubuntu-latest","windows-latest","macos-latest"]'
|
||||
select-os: '["windows-latest","macos-latest"]'
|
||||
label: full-ci
|
||||
|
||||
# The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each
|
||||
# main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo
|
||||
# rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight
|
||||
# scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and
|
||||
# Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache
|
||||
# budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a
|
||||
# cold lint leg is still shorter than its gate leg.
|
||||
native:
|
||||
name: Workspace
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
# Pushes to next run Linux only.
|
||||
os: ${{ github.ref == 'refs/heads/next' && '["ubuntu-latest"]' || '["ubuntu-latest","windows-latest","macos-latest"]' }}
|
||||
# On a pull request, macOS and Windows run only when it can change platform behaviour: a
|
||||
# crate with platform cfg code or one that depends on it, the build setup, or a file outside
|
||||
# the crates (craft-common-actions' select-platforms). The full-ci label runs them anyway
|
||||
# from the next push or manual run; pushes to main always run every leg. A push to next has
|
||||
# only the Linux leg, so it selects none.
|
||||
select-os: ${{ github.ref == 'refs/heads/next' && '[]' || '["windows-latest","macos-latest"]' }}
|
||||
timeout-minutes: 120
|
||||
os: '["ubuntu-latest"]'
|
||||
cache-workspace-crates: true
|
||||
cold-build: ${{ github.event.schedule == '17 0 * * *' }}
|
||||
lint-cache: false
|
||||
timeout-minutes: &timeout 120
|
||||
# Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml).
|
||||
tools: cargo-nextest@0.9.150
|
||||
tools: &tools cargo-nextest@0.9.150
|
||||
packages: mesa-vulkan-drivers libvulkan1
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
craft-fonts-ref: &craft-fonts b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
linux-env: WGPU_BACKEND=vulkan
|
||||
# No debuginfo on Windows: writing PDBs for every test binary is a large part of its link
|
||||
# time. A panic still names its file and line; only backtrace frames lose theirs, and the
|
||||
# Linux and macOS legs keep line tables.
|
||||
# rust-lld links the test binaries faster than link.exe; /OPT:NOICF skips identical-code
|
||||
# folding and /DEBUG:NONE writes no PDB, both of which only cost link time here.
|
||||
windows-env: |
|
||||
CRAFT_PRINT_REQUIRE_QUEUE=1
|
||||
CARGO_PROFILE_DEV_DEBUG=0
|
||||
CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER=rust-lld
|
||||
CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS=-Clink-arg=/OPT:NOICF -Clink-arg=/DEBUG:NONE
|
||||
# Test binaries without debug info or symbols: about a third of the size, and a panic still
|
||||
# names its file and line.
|
||||
dev-strip: true
|
||||
# The fuzz-style tests run a fraction of their cases here: every hostile-input hammer and
|
||||
# sweep 1/8 (craft-testkit's CRAFT_HOSTILE_DIVISOR), every proptest without its own case
|
||||
# count 64 cases instead of 256. nightly.yml runs them all in full.
|
||||
env: |
|
||||
env: &env |
|
||||
CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
CRAFT_HOSTILE_DIVISOR=8
|
||||
PROPTEST_CASES=64
|
||||
setup-command: bash scripts/ci-test-inputs.sh
|
||||
setup-command: &setup bash scripts/ci-test-inputs.sh
|
||||
# The PhotoCraft corpora, keyed on the script that pins them: a hit skips the PhotoCraft
|
||||
# checkout and its xtask build (1:51 on Windows).
|
||||
cache-paths: .test-inputs/photocraft/corpus
|
||||
cache-key: photocraft-corpus
|
||||
cache-key-files: scripts/ci-test-inputs.sh
|
||||
cache-paths: &cache-paths .test-inputs/photocraft/corpus
|
||||
cache-key: &cache-key photocraft-corpus
|
||||
cache-key-files: &cache-key-files scripts/ci-test-inputs.sh
|
||||
# A `lint (<os>)` leg beside each `gate (<os>)` leg, so clippy is off the tests' critical path.
|
||||
lint-command: |
|
||||
lint-command: &lint |
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
python3 scripts/test-workspace-concurrency.py
|
||||
python3 scripts/test-workspace-tests.py
|
||||
@@ -78,30 +103,98 @@ jobs:
|
||||
fi
|
||||
cargo clippy --workspace --all-targets --locked -- -D warnings
|
||||
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
# A push to main builds the gate's test binaries in their own leg and saves the cache right
|
||||
# after, so a failing test no longer keeps the cache from being saved. The same two builds
|
||||
# the gate's nextest runs do (all features; the two crates with default features).
|
||||
warm-command: |
|
||||
cargo test --workspace --no-run --all-features --locked
|
||||
cargo test -p craft-image-codecs -p craft-text --no-run --locked
|
||||
command: |
|
||||
command: &command |
|
||||
# The tests run once, with every feature, in parallel across test binaries; nextest skips
|
||||
# doctests, so `cargo test --doc` runs them. The default-feature compile is the lint leg's
|
||||
# doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose
|
||||
# tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's
|
||||
# first clippy run; the last command runs the crates whose tests check behaviour with a
|
||||
# feature off, which an all-features build cannot reach.
|
||||
cargo nextest run --workspace --all-features --locked --profile ci
|
||||
cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests
|
||||
cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench
|
||||
cargo test --workspace --doc --all-features --locked
|
||||
cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci
|
||||
cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests
|
||||
|
||||
# The macOS and Windows legs, when `platforms` says this run needs them, with the Linux leg's
|
||||
# inputs.
|
||||
native-platforms:
|
||||
name: Workspace
|
||||
needs: platforms
|
||||
# Pushes to next run Linux only.
|
||||
if: needs.platforms.outputs.platform == 'true' && github.ref != 'refs/heads/next'
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["windows-latest","macos-latest"]'
|
||||
lint-cache: false
|
||||
timeout-minutes: *timeout
|
||||
tools: *tools
|
||||
craft-fonts-ref: *craft-fonts
|
||||
dev-strip: true
|
||||
# No debuginfo on Windows: writing PDBs for every test binary is a large part of its link
|
||||
# time. A panic still names its file and line; only backtrace frames lose theirs, and the
|
||||
# Linux and macOS legs keep line tables.
|
||||
windows-env: |
|
||||
CRAFT_PRINT_REQUIRE_QUEUE=1
|
||||
CARGO_PROFILE_DEV_DEBUG=0
|
||||
env: *env
|
||||
setup-command: *setup
|
||||
cache-paths: *cache-paths
|
||||
cache-key: *cache-key
|
||||
cache-key-files: *cache-key-files
|
||||
lint-command: *lint
|
||||
command: *command
|
||||
windows-command: |
|
||||
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
|
||||
cargo nextest run --workspace --all-features --locked --profile ci
|
||||
cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests
|
||||
cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench
|
||||
cargo test --workspace --doc --all-features --locked
|
||||
cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci
|
||||
cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests
|
||||
|
||||
# Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and
|
||||
# every run restores only the newest. This deletes the older ones as soon as the Linux leg is
|
||||
# done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries
|
||||
# too. The only job with `actions: write`; it checks out and runs nothing from the repository.
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
needs: native
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Delete all but the newest rolling entry of each job and runner
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# `<version>-rust-<profile>-<job>-crates-<os>-<arch>-<run>-<attempt>-...`, newest first.
|
||||
gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \
|
||||
--jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches"
|
||||
declare -A kept
|
||||
while read -r id key; do
|
||||
[[ "$key" =~ ^.+-rust-[0-9a-f]{64}-(.+-crates-[A-Za-z_]+-[a-z0-9]+)-[0-9]+-[0-9]+- ]] || continue
|
||||
entry=${BASH_REMATCH[1]}
|
||||
if [ -n "${kept[$entry]:-}" ]; then
|
||||
echo "delete $key"
|
||||
gh cache delete "$id" --repo "$REPO"
|
||||
else
|
||||
kept[$entry]=1
|
||||
echo "keep $key"
|
||||
fi
|
||||
done < "$RUNNER_TEMP/caches"
|
||||
|
||||
msrv:
|
||||
name: Rust 1.95
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
# Its own dependency-cache entry: the calls in this file share one job id, so without a name
|
||||
# they would write the same key.
|
||||
cache-name: msrv
|
||||
os: '["ubuntu-latest"]'
|
||||
toolchain: 1.95.0
|
||||
targets: ""
|
||||
@@ -116,6 +209,7 @@ jobs:
|
||||
name: UI and settings WASM
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
cache-name: wasm
|
||||
os: '["ubuntu-latest"]'
|
||||
targets: wasm32-unknown-unknown
|
||||
tools: ""
|
||||
|
||||
@@ -11,6 +11,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files |
|
||||
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 |
|
||||
| `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 |
|
||||
| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 |
|
||||
| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
|
||||
Generated
+85
-17
@@ -1809,6 +1809,10 @@ dependencies = [
|
||||
"craft-gcode",
|
||||
"craft-geom",
|
||||
"craft-gif",
|
||||
"craft-gpu",
|
||||
"craft-gpu-null",
|
||||
"craft-gpu-providers",
|
||||
"craft-gpu-wgpu",
|
||||
"craft-gridcraft-format",
|
||||
"craft-gzip",
|
||||
"craft-har",
|
||||
@@ -1824,6 +1828,7 @@ dependencies = [
|
||||
"craft-imaging",
|
||||
"craft-indd",
|
||||
"craft-ipc",
|
||||
"craft-ipp",
|
||||
"craft-java-class",
|
||||
"craft-jmap",
|
||||
"craft-jpeg",
|
||||
@@ -1870,6 +1875,7 @@ dependencies = [
|
||||
"craft-platform",
|
||||
"craft-plist",
|
||||
"craft-plotter",
|
||||
"craft-ppt-binary",
|
||||
"craft-pptx",
|
||||
"craft-prc",
|
||||
"craft-prepress",
|
||||
@@ -1896,6 +1902,7 @@ dependencies = [
|
||||
"craft-smime",
|
||||
"craft-sniff",
|
||||
"craft-sourcemap",
|
||||
"craft-sqlite",
|
||||
"craft-ssip",
|
||||
"craft-stencilcraft-document",
|
||||
"craft-stencilcraft-format",
|
||||
@@ -2047,10 +2054,8 @@ name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-flags",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-keymap",
|
||||
"craft-platform",
|
||||
@@ -2110,6 +2115,7 @@ dependencies = [
|
||||
name = "craft-captions"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-media",
|
||||
"craft-media-testkit",
|
||||
"craft-timeline",
|
||||
"craft-xml",
|
||||
@@ -2314,9 +2320,13 @@ dependencies = [
|
||||
name = "craft-develop"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-color-transform",
|
||||
"craft-develop-model",
|
||||
"craft-render-parity",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2637,6 +2647,7 @@ dependencies = [
|
||||
"craft-dxf",
|
||||
"craft-eps",
|
||||
"craft-file-formats",
|
||||
"craft-image-codecs",
|
||||
"craft-pdf 0.1.0",
|
||||
"craft-raster-codecs",
|
||||
"craft-svg",
|
||||
@@ -2799,6 +2810,40 @@ dependencies = [
|
||||
"image",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-null"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-providers"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"craft-gpu-null",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-wgpu"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"craft-gpu-providers",
|
||||
"pollster 0.4.0",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gridcraft-format"
|
||||
version = "0.1.0"
|
||||
@@ -2989,6 +3034,10 @@ dependencies = [
|
||||
"widestring",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ipp"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-java-class"
|
||||
version = "0.1.0"
|
||||
@@ -3577,10 +3626,24 @@ dependencies = [
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ppt-binary"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-drawingml",
|
||||
"craft-pptx",
|
||||
"image",
|
||||
"log",
|
||||
"miniz_oxide 0.8.9",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pptx"
|
||||
version = "0.1.0"
|
||||
@@ -3895,6 +3958,10 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-sqlite"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ssip"
|
||||
version = "0.1.0"
|
||||
@@ -4398,6 +4465,7 @@ dependencies = [
|
||||
name = "craft-usd"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"half",
|
||||
"lz4_flex",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -5326,7 +5394,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -5382,7 +5450,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5417,7 +5485,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -5436,7 +5504,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5455,7 +5523,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
@@ -5475,7 +5543,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -5488,7 +5556,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5565,7 +5633,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -5638,7 +5706,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5664,7 +5732,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
@@ -14982,19 +15050,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
|
||||
+24
-14
@@ -21,6 +21,7 @@ craft-xfdf = { path = "crates/xfdf" }
|
||||
craft-jsonc = { path = "crates/jsonc" }
|
||||
craft-palette = { path = "crates/palette" }
|
||||
craft-score = { path = "crates/score" }
|
||||
craft-sqlite = { path = "crates/sqlite" }
|
||||
craft-shx = { path = "crates/shx" }
|
||||
craft-http-url = { path = "crates/http-url" }
|
||||
craft-usd = { path = "crates/usd" }
|
||||
@@ -123,6 +124,7 @@ craft-gif = { path = "crates/gif" }
|
||||
craft-hdr = { path = "crates/hdr" }
|
||||
craft-mesh = { path = "crates/mesh" }
|
||||
craft-html = { path = "crates/html" }
|
||||
craft-ipp = { path = "crates/ipp" }
|
||||
craft-heif = { path = "crates/heif" }
|
||||
craft-fig = { path = "crates/fig" }
|
||||
craft-fonts-build = { path = "crates/fonts-build" }
|
||||
@@ -130,6 +132,10 @@ craft-font-subset = { path = "crates/font-subset" }
|
||||
# The HarfBuzz subsetter from storytold's HarfBuzz fork (branch rust-subset-15.0.0: HarfBuzz 15.0.0 plus rust/harfbuzz-subset-sys).
|
||||
harfbuzz-subset-sys = { git = "https://github.com/storytold/harfbuzz.git", rev = "f32ed1e548eaa8852bff47e49a90629a013a2faa" }
|
||||
craft-host = { path = "crates/host" }
|
||||
craft-gpu = { path = "crates/gpu" }
|
||||
craft-gpu-null = { path = "crates/gpu-null" }
|
||||
craft-gpu-providers = { path = "crates/gpu-providers" }
|
||||
craft-gpu-wgpu = { path = "crates/gpu-wgpu" }
|
||||
craft-i18n = { path = "crates/i18n" }
|
||||
craft-ipc = { path = "crates/ipc" }
|
||||
craft-idml = { path = "crates/idml" }
|
||||
@@ -172,6 +178,7 @@ craft-opc = { path = "crates/opc" }
|
||||
craft-openpgp = { path = "crates/openpgp" }
|
||||
craft-ora = { path = "crates/ora" }
|
||||
craft-pptx = { path = "crates/pptx" }
|
||||
craft-ppt-binary = { path = "crates/ppt-binary" }
|
||||
craft-penpot = { path = "crates/penpot" }
|
||||
craft-pcraft-format = { path = "crates/pcraft-format" }
|
||||
craft-pcraft-bundle = { path = "crates/pcraft-bundle" }
|
||||
@@ -269,6 +276,9 @@ proptest = "1"
|
||||
encoding_rs = "0.8"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
# Foundation crates for craft-gpu-wgpu. The versions match the ones the app repos already pin.
|
||||
pollster = "0.4"
|
||||
wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -294,20 +304,20 @@ hayro-jbig2 = { path = "vendor/hayro-jbig2" }
|
||||
hayro-cmap = { path = "vendor/hayro-cmap" }
|
||||
hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
linesweeper = { path = "vendor/linesweeper" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
|
||||
|
||||
@@ -114,6 +114,14 @@ Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. The format imp
|
||||
clean-room work based on their public specifications; dependency licences and X.Org's `rgb.txt`
|
||||
attribution are listed in ATTRIBUTION.md.
|
||||
|
||||
crates/develop (craft-develop) is moved from LightCraft, module by module:
|
||||
- src/inpaint.rs and src/inpaint/ from crates/inpaint (lightcraft-inpaint), with its tests, revision a75497d6.
|
||||
https://github.com/storytold/lightcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the LightCraft contributors.
|
||||
That crate ports the inpainting (PatchMatch completion) and Poisson membrane fill code of PhotoCraft
|
||||
(https://github.com/storytold/photocraft, crates/algo/src/inpaint.rs and poisson.rs), Copyright the PhotoCraft
|
||||
contributors, MIT OR Apache-2.0; the port was modified by the LightCraft contributors (2026).
|
||||
|
||||
crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two other readers:
|
||||
- LightCraft, crates/raw (src/lib.rs, dng.rs, dngwrite.rs, tiffraw.rs, unpack.rs, ljpeg.rs, jxl.rs,
|
||||
opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs,
|
||||
|
||||
@@ -2,6 +2,7 @@ Craft App Libraries
|
||||
===================
|
||||
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_craft-libs"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/craft-libs?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
|
||||
This repo contains libraries used by the various Craft Apps. It's a Rust monorepo workspace, and the libraries can be included by any Craft Apps that need them.
|
||||
|
||||
@@ -341,6 +342,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
- [`craft-plotter`](crates/plotter/README.md): cutter and pen-plotter command languages: HP-GL,
|
||||
DMPL and GP-GL (plain and the Silhouette dialect, three generations, registration marks) from a
|
||||
job in millimetres, plus the Silhouette device queries and reply parsers. No I/O.
|
||||
- [`craft-ppt-binary`](crates/ppt-binary/README.md): the PowerPoint 97-2003 binary format (`.ppt`, `.pot`, `.pps`;
|
||||
[MS-PPT], [MS-ODRAW]) read into `craft-pptx`, on `craft-cfb`. Import only. DeckCraft's reader.
|
||||
- [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation:
|
||||
masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations,
|
||||
comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`.
|
||||
|
||||
@@ -34,7 +34,12 @@ struct EnvelopeOut<'a, P, T> {
|
||||
|
||||
/// Serializes the envelope in its stable wire order and uses AniCraft's compact/pretty threshold.
|
||||
pub fn write<P: Serialize, T: Serialize>(generator: &str, paths: &[P], document: &T) -> Result<String, serde_json::Error> {
|
||||
let envelope = EnvelopeOut { format: FORMAT_NAME, version: FORMAT_VERSION, generator, paths, document };
|
||||
write_version(FORMAT_VERSION, generator, paths, document)
|
||||
}
|
||||
|
||||
/// Serializes the envelope with an explicit format version and AniCraft's compact/pretty threshold.
|
||||
pub fn write_version<P: Serialize, T: Serialize>(version: u32, generator: &str, paths: &[P], document: &T) -> Result<String, serde_json::Error> {
|
||||
let envelope = EnvelopeOut { format: FORMAT_NAME, version, generator, paths, document };
|
||||
let compact = serde_json::to_string(&envelope)?;
|
||||
if compact.len() < PRETTY_LIMIT { serde_json::to_string_pretty(&envelope) } else { Ok(compact) }
|
||||
}
|
||||
|
||||
@@ -71,6 +71,9 @@ ac3-encode = ["craft-media/bitstream"]
|
||||
eac3-encode = ["craft-media/bitstream"]
|
||||
# MPEG-1/2 Layer III (MP3) encoder (`mp3`).
|
||||
mp3-encode = ["craft-media/bitstream"]
|
||||
# Direct Stream Digital (DSD) files: DSF and DSDIFF decoders and DSD-to-PCM decimation.
|
||||
dsd = []
|
||||
|
||||
# MPEG-1/2 Layer II (MP2) encoder (`mpa::encoder`). It shares the polyphase analysis filter of the
|
||||
# MP3 encoder and the tables of the MP1/MP2 decoder.
|
||||
mpa-encode = ["mpa-decode", "mp3-encode"]
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`) parser and writer.
|
||||
//!
|
||||
//! DSDIFF files use an IFF-style big-endian chunk format starting with `FRM8` of type `DSD `:
|
||||
//! - `FRM8` container chunk containing:
|
||||
//! - `FVER`: format version (typically 1.5.0.0).
|
||||
//! - `PROP`: properties chunk with subtype `SND `, containing:
|
||||
//! - `FS `: sampling frequency (e.g. 2,822,400 Hz for DSD64).
|
||||
//! - `CHNL`: channel count and 4-character channel ID codes (`SLFT`, `SRGT`, etc.).
|
||||
//! - `CMPR`: compression type (`DSD ` for uncompressed, `DST ` for compressed).
|
||||
//! - `DSD `: audio data chunk containing channel-interleaved 1-bit samples (MSB-first).
|
||||
//! - Optional `DIIN`: disc and track information (title, artist).
|
||||
|
||||
use super::{BitOrder, Error, Format, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio};
|
||||
|
||||
/// Decodes 4-byte ASCII channel identifiers into human-readable channel names.
|
||||
fn channel_id_to_name(id: &[u8; 4]) -> String {
|
||||
match id {
|
||||
b"SLFT" => "FrontLeft".to_string(),
|
||||
b"SRGT" => "FrontRight".to_string(),
|
||||
b"MLFT" => "Mono/Left".to_string(),
|
||||
b"MRGT" => "Right".to_string(),
|
||||
b"C " => "Center".to_string(),
|
||||
b"LFE " => "LFE".to_string(),
|
||||
b"LS " => "LeftSurround".to_string(),
|
||||
b"RS " => "RightSurround".to_string(),
|
||||
b"CO " => "CenterOverhead".to_string(),
|
||||
b"LH " => "LeftHeight".to_string(),
|
||||
b"RH " => "RightHeight".to_string(),
|
||||
_ => {
|
||||
if let Ok(s) = std::str::from_utf8(id) {
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return trimmed.to_string();
|
||||
}
|
||||
}
|
||||
format!("Channel {:02X}{:02X}{:02X}{:02X}", id[0], id[1], id[2], id[3])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a `DITI` or `DIAR` chunk: a four-byte big-endian character count, then that many
|
||||
/// bytes. `None` when the count is missing or longer than the chunk.
|
||||
fn diin_text(sub_data: &[u8]) -> Option<String> {
|
||||
let count = usize::try_from(u32::from_be_bytes(sub_data.get(..4)?.try_into().ok()?)).ok()?;
|
||||
let text = sub_data.get(4..)?.get(..count)?;
|
||||
Some(String::from_utf8_lossy(text).trim().to_string())
|
||||
}
|
||||
|
||||
/// The channel identifiers DSDIFF 1.5 defines for a channel count (stereo, 5 and 5.1 channels);
|
||||
/// other counts use the generic `C001`, `C002`, ... identifiers.
|
||||
fn channel_ids(num_channels: usize) -> Vec<[u8; 4]> {
|
||||
let named: &[&[u8; 4]] = match num_channels {
|
||||
1 => &[b"SLFT"],
|
||||
2 => &[b"SLFT", b"SRGT"],
|
||||
5 => &[b"MLFT", b"MRGT", b"C ", b"LS ", b"RS "],
|
||||
6 => &[b"MLFT", b"MRGT", b"C ", b"LFE ", b"LS ", b"RS "],
|
||||
_ => &[],
|
||||
};
|
||||
if !named.is_empty() {
|
||||
return named.iter().map(|id| **id).collect();
|
||||
}
|
||||
(1..=num_channels)
|
||||
.map(|n| {
|
||||
let s = format!("C{n:03}");
|
||||
let mut id = [b' '; 4];
|
||||
id.copy_from_slice(&s.as_bytes()[..4]);
|
||||
id
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Parses the metadata from a DSDIFF file.
|
||||
pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Error> {
|
||||
if bytes.len() < 16 {
|
||||
return Err(Error::UnexpectedEof("DSDIFF file is too short"));
|
||||
}
|
||||
|
||||
if &bytes[0..4] != b"FRM8" {
|
||||
return Err(Error::InvalidHeader("missing 'FRM8' magic chunk"));
|
||||
}
|
||||
let form_size = u64::from_be_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("FRM8 size"))?);
|
||||
if &bytes[12..16] != b"DSD " {
|
||||
return Err(Error::InvalidHeader("invalid FRM8 form type (expected 'DSD ')"));
|
||||
}
|
||||
|
||||
let total_file_data = bytes.len().saturating_sub(12);
|
||||
let form_size = usize::try_from(form_size).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
if form_size > total_file_data {
|
||||
return Err(Error::UnexpectedEof("FRM8 chunk extends beyond file size"));
|
||||
}
|
||||
|
||||
let mut pos = 16;
|
||||
let end = 12 + form_size;
|
||||
|
||||
let mut sample_rate = None;
|
||||
let mut channel_names = Vec::new();
|
||||
let mut num_channels = None;
|
||||
let mut is_compressed_dst = false;
|
||||
let mut dsd_data_offset = None;
|
||||
let mut dsd_data_len = None;
|
||||
let mut title = None;
|
||||
let mut artist = None;
|
||||
|
||||
while pos + 12 <= end {
|
||||
let chunk_id: [u8; 4] = bytes[pos..pos + 4].try_into().map_err(|_| Error::UnexpectedEof("chunk ID"))?;
|
||||
let chunk_size = usize::try_from(u64::from_be_bytes(bytes[pos + 4..pos + 12].try_into().map_err(|_| Error::UnexpectedEof("chunk size"))?))
|
||||
.map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
pos += 12;
|
||||
|
||||
if chunk_size > end.saturating_sub(pos) {
|
||||
return Err(Error::UnexpectedEof("subchunk extends beyond container bounds"));
|
||||
}
|
||||
|
||||
let chunk_data = &bytes[pos..pos + chunk_size];
|
||||
let pad = chunk_size & 1;
|
||||
pos = pos.saturating_add(chunk_size).saturating_add(pad);
|
||||
|
||||
match &chunk_id {
|
||||
b"PROP" => {
|
||||
if chunk_data.len() < 4 {
|
||||
continue;
|
||||
}
|
||||
if &chunk_data[0..4] != b"SND " {
|
||||
continue;
|
||||
}
|
||||
let mut prop_pos = 4;
|
||||
while prop_pos + 12 <= chunk_data.len() {
|
||||
let sub_id: [u8; 4] = chunk_data[prop_pos..prop_pos + 4].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk ID"))?;
|
||||
let sub_size = usize::try_from(u64::from_be_bytes(
|
||||
chunk_data[prop_pos + 4..prop_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk size"))?,
|
||||
))
|
||||
.map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
prop_pos += 12;
|
||||
|
||||
if sub_size > chunk_data.len().saturating_sub(prop_pos) {
|
||||
return Err(Error::UnexpectedEof("PROP subchunk extends beyond bounds"));
|
||||
}
|
||||
|
||||
let sub_data = &chunk_data[prop_pos..prop_pos + sub_size];
|
||||
let sub_pad = sub_size & 1;
|
||||
prop_pos = prop_pos.saturating_add(sub_size).saturating_add(sub_pad);
|
||||
|
||||
match &sub_id {
|
||||
b"FS " => {
|
||||
if sub_data.len() < 4 {
|
||||
return Err(Error::UnexpectedEof("truncated FS chunk"));
|
||||
}
|
||||
if sample_rate.is_some() {
|
||||
return Err(Error::InvalidHeader("duplicate FS chunk"));
|
||||
}
|
||||
let sr = u32::from_be_bytes([sub_data[0], sub_data[1], sub_data[2], sub_data[3]]);
|
||||
if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sr) {
|
||||
return Err(Error::InvalidHeader("sampling frequency out of range"));
|
||||
}
|
||||
sample_rate = Some(sr);
|
||||
}
|
||||
b"CHNL" => {
|
||||
if sub_data.len() < 2 {
|
||||
return Err(Error::UnexpectedEof("truncated CHNL chunk"));
|
||||
}
|
||||
if num_channels.is_some() {
|
||||
return Err(Error::InvalidHeader("duplicate CHNL chunk"));
|
||||
}
|
||||
let n = u16::from_be_bytes([sub_data[0], sub_data[1]]);
|
||||
if n == 0 || n > MAX_CHANNELS as u16 {
|
||||
return Err(Error::Unsupported("channel count must be between 1 and 8"));
|
||||
}
|
||||
num_channels = Some(n);
|
||||
channel_names.clear();
|
||||
let mut ch_pos = 2;
|
||||
while ch_pos + 4 <= sub_data.len() && channel_names.len() < n as usize {
|
||||
let id: [u8; 4] = [sub_data[ch_pos], sub_data[ch_pos + 1], sub_data[ch_pos + 2], sub_data[ch_pos + 3]];
|
||||
channel_names.push(channel_id_to_name(&id));
|
||||
ch_pos += 4;
|
||||
}
|
||||
}
|
||||
b"CMPR" if sub_data.len() >= 4 => {
|
||||
if &sub_data[0..4] == b"DST " {
|
||||
is_compressed_dst = true;
|
||||
} else if &sub_data[0..4] != b"DSD " {
|
||||
return Err(Error::Unsupported("unknown DSDIFF compression type"));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
b"DSD " => {
|
||||
dsd_data_offset = Some(pos - chunk_size - pad);
|
||||
dsd_data_len = Some(chunk_size);
|
||||
}
|
||||
b"DST " => {
|
||||
is_compressed_dst = true;
|
||||
}
|
||||
b"DIIN" => {
|
||||
// Parse optional disc info for title and artist.
|
||||
let mut diin_pos = 0;
|
||||
while diin_pos + 12 <= chunk_data.len() {
|
||||
let sub_id = &chunk_data[diin_pos..diin_pos + 4];
|
||||
let sub_size = usize::try_from(u64::from_be_bytes(
|
||||
chunk_data[diin_pos + 4..diin_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("DIIN subchunk size"))?,
|
||||
))
|
||||
.map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
diin_pos += 12;
|
||||
if sub_size > chunk_data.len().saturating_sub(diin_pos) {
|
||||
break;
|
||||
}
|
||||
let sub_data = &chunk_data[diin_pos..diin_pos + sub_size];
|
||||
let sub_pad = sub_size & 1;
|
||||
diin_pos = diin_pos.saturating_add(sub_size).saturating_add(sub_pad);
|
||||
|
||||
if sub_id == b"DITI" && title.is_none() {
|
||||
title = diin_text(sub_data);
|
||||
} else if sub_id == b"DIAR" && artist.is_none() {
|
||||
artist = diin_text(sub_data);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if is_compressed_dst {
|
||||
return Err(Error::Unsupported("DST compression in DSDIFF is not yet supported"));
|
||||
}
|
||||
|
||||
let sample_rate = sample_rate.ok_or(Error::InvalidHeader("missing sample rate ('FS ' chunk)"))?;
|
||||
if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) {
|
||||
return Err(Error::InvalidHeader("sampling frequency out of range"));
|
||||
}
|
||||
|
||||
let channels = num_channels.ok_or(Error::InvalidHeader("missing channel info ('CHNL' chunk)"))?;
|
||||
if channels == 0 || channels > MAX_CHANNELS as u16 {
|
||||
return Err(Error::Unsupported("channel count must be between 1 and 8"));
|
||||
}
|
||||
|
||||
let data_offset = dsd_data_offset.ok_or(Error::InvalidHeader("missing audio data ('DSD ' chunk)"))?;
|
||||
let data_len = dsd_data_len.ok_or(Error::InvalidHeader("missing audio data length"))?;
|
||||
|
||||
let bytes_per_channel = data_len / (channels as usize);
|
||||
let sample_count = (bytes_per_channel as u64).saturating_mul(8);
|
||||
|
||||
if channel_names.len() < channels as usize {
|
||||
for c in channel_names.len()..(channels as usize) {
|
||||
channel_names.push(format!("Channel {}", c + 1));
|
||||
}
|
||||
}
|
||||
|
||||
let metadata = Metadata { format: Format::Dsdiff, sample_rate, channels, sample_count, channel_names, title, artist };
|
||||
|
||||
Ok((metadata, data_offset, data_len))
|
||||
}
|
||||
|
||||
/// Parses a DSDIFF file into raw 1-bit planar channel streams.
|
||||
pub fn parse_dsdiff(bytes: &[u8]) -> Result<RawAudio, Error> {
|
||||
let (metadata, data_offset, data_len) = parse_dsdiff_header(bytes)?;
|
||||
let channels = metadata.channels as usize;
|
||||
let bytes_per_channel = data_len / channels;
|
||||
|
||||
if bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES {
|
||||
return Err(Error::MemoryLimitExceeded);
|
||||
}
|
||||
|
||||
let end_offset = data_offset + data_len;
|
||||
if end_offset > bytes.len() {
|
||||
return Err(Error::UnexpectedEof("DSD sound data extends beyond file bounds"));
|
||||
}
|
||||
let data_slice = &bytes[data_offset..end_offset];
|
||||
|
||||
let mut channel_bytes: Vec<Vec<u8>> = Vec::with_capacity(channels);
|
||||
for _ in 0..channels {
|
||||
let mut ch_vec = Vec::new();
|
||||
ch_vec.try_reserve_exact(bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
channel_bytes.push(ch_vec);
|
||||
}
|
||||
|
||||
// De-interleave byte-by-byte: Ch0, Ch1, ... Ch(N-1), Ch0, Ch1 ...
|
||||
for chunk in data_slice.chunks_exact(channels) {
|
||||
for (c, &byte) in chunk.iter().enumerate() {
|
||||
if let Some(ch_vec) = channel_bytes.get_mut(c) {
|
||||
ch_vec.push(byte);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RawAudio { metadata, bit_order: BitOrder::MsbFirst, channel_bytes })
|
||||
}
|
||||
|
||||
/// Encodes 1-bit planar audio channels into a valid Philips DSDIFF (`.dff`) file.
|
||||
pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result<Vec<u8>, Error> {
|
||||
if channels.is_empty() || channels.len() > MAX_CHANNELS {
|
||||
return Err(Error::Unsupported("channel count must be between 1 and 8"));
|
||||
}
|
||||
if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) {
|
||||
return Err(Error::InvalidData("sample rate out of bounds"));
|
||||
}
|
||||
|
||||
let num_channels = channels.len();
|
||||
let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
let data_size = bytes_per_ch.checked_mul(num_channels).ok_or(Error::MemoryLimitExceeded)?;
|
||||
// Fixed headers plus four bytes for each channel identifier.
|
||||
// An odd-sized chunk payload is followed by a pad byte that its size field does not count.
|
||||
let data_pad = data_size & 1;
|
||||
let padded_size = data_size.checked_add(data_pad).ok_or(Error::MemoryLimitExceeded)?;
|
||||
let file_size = super::encoded_size(padded_size, 110 + 4 * num_channels)?;
|
||||
|
||||
// Build PROP subchunks:
|
||||
// 1. 'FS ' (4 bytes + 12 chunk header)
|
||||
let mut fs_chunk = Vec::with_capacity(16);
|
||||
fs_chunk.extend_from_slice(b"FS ");
|
||||
fs_chunk.extend_from_slice(&4u64.to_be_bytes());
|
||||
fs_chunk.extend_from_slice(&sample_rate.to_be_bytes());
|
||||
|
||||
// 2. 'CHNL' (2 + 4 * num_channels + 12 chunk header)
|
||||
let chnl_data_len = 2 + 4 * num_channels;
|
||||
let mut chnl_chunk = Vec::with_capacity(12 + chnl_data_len + 1);
|
||||
chnl_chunk.extend_from_slice(b"CHNL");
|
||||
chnl_chunk.extend_from_slice(&(chnl_data_len as u64).to_be_bytes());
|
||||
chnl_chunk.extend_from_slice(&(num_channels as u16).to_be_bytes());
|
||||
for id in channel_ids(num_channels) {
|
||||
chnl_chunk.extend_from_slice(&id);
|
||||
}
|
||||
if !chnl_data_len.is_multiple_of(2) {
|
||||
chnl_chunk.push(0);
|
||||
}
|
||||
|
||||
// 3. 'CMPR' (4 + 1 + 3 + pad = 8 bytes + 12 chunk header)
|
||||
let mut cmpr_chunk = Vec::with_capacity(20);
|
||||
cmpr_chunk.extend_from_slice(b"CMPR");
|
||||
cmpr_chunk.extend_from_slice(&8u64.to_be_bytes());
|
||||
cmpr_chunk.extend_from_slice(b"DSD ");
|
||||
cmpr_chunk.push(3); // name len
|
||||
cmpr_chunk.extend_from_slice(b"DSD");
|
||||
|
||||
let prop_payload_len = 4 + fs_chunk.len() + chnl_chunk.len() + cmpr_chunk.len();
|
||||
let mut prop_chunk = Vec::with_capacity(12 + prop_payload_len);
|
||||
prop_chunk.extend_from_slice(b"PROP");
|
||||
prop_chunk.extend_from_slice(&(prop_payload_len as u64).to_be_bytes());
|
||||
prop_chunk.extend_from_slice(b"SND ");
|
||||
prop_chunk.extend_from_slice(&fs_chunk);
|
||||
prop_chunk.extend_from_slice(&chnl_chunk);
|
||||
prop_chunk.extend_from_slice(&cmpr_chunk);
|
||||
|
||||
// FVER chunk (4 bytes payload + 12 chunk header)
|
||||
let mut fver_chunk = Vec::with_capacity(16);
|
||||
fver_chunk.extend_from_slice(b"FVER");
|
||||
fver_chunk.extend_from_slice(&4u64.to_be_bytes());
|
||||
fver_chunk.extend_from_slice(&0x01050000u32.to_be_bytes());
|
||||
|
||||
// DSD chunk (data_size payload + 12 chunk header)
|
||||
let mut dsd_chunk_hdr = Vec::with_capacity(12);
|
||||
dsd_chunk_hdr.extend_from_slice(b"DSD ");
|
||||
dsd_chunk_hdr.extend_from_slice(&(data_size as u64).to_be_bytes());
|
||||
|
||||
let frm8_payload_len = file_size - 12;
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
|
||||
out.extend_from_slice(b"FRM8");
|
||||
out.extend_from_slice(&(frm8_payload_len as u64).to_be_bytes());
|
||||
out.extend_from_slice(b"DSD ");
|
||||
out.extend_from_slice(&fver_chunk);
|
||||
out.extend_from_slice(&prop_chunk);
|
||||
out.extend_from_slice(&dsd_chunk_hdr);
|
||||
|
||||
// Interleave channels byte-by-byte.
|
||||
for i in 0..bytes_per_ch {
|
||||
for ch_data in channels {
|
||||
let byte = ch_data.get(i).copied().unwrap_or(super::filter::SILENCE_MSBF);
|
||||
out.push(byte);
|
||||
}
|
||||
}
|
||||
if data_pad == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
//! Sony DSF (Direct Stream Digital File) parser and writer.
|
||||
//!
|
||||
//! A DSF file consists of three contiguous little-endian chunks:
|
||||
//! - `'DSD '` chunk (28 bytes): file identification, total size, and metadata offset.
|
||||
//! - `'fmt '` chunk (52 bytes): sample rate, channel count, sample count, block size.
|
||||
//! - `'data'` chunk (12 bytes + data): 1-bit audio organized into channel blocks.
|
||||
//! - Optional ID3v2 metadata chunk located at `metadata_offset`.
|
||||
|
||||
use super::{BitOrder, Error, Format, MAX_BLOCK_SIZE, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio};
|
||||
|
||||
/// Channel configuration names for DSF channel types 1..=7.
|
||||
fn dsf_channel_names(channel_type: u32, channel_count: u16) -> Vec<String> {
|
||||
match channel_type {
|
||||
1 => vec!["Mono".to_string()],
|
||||
2 => vec!["Left".to_string(), "Right".to_string()],
|
||||
3 => vec!["Left".to_string(), "Right".to_string(), "Center".to_string()],
|
||||
4 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "BackLeft".to_string(), "BackRight".to_string()],
|
||||
5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "LFE".to_string()],
|
||||
6 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "BackLeft".to_string(), "BackRight".to_string()],
|
||||
7 => vec![
|
||||
"FrontLeft".to_string(),
|
||||
"FrontRight".to_string(),
|
||||
"Center".to_string(),
|
||||
"LFE".to_string(),
|
||||
"BackLeft".to_string(),
|
||||
"BackRight".to_string(),
|
||||
],
|
||||
_ => (0..channel_count).map(|c| format!("Channel {}", c + 1)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to parse basic ID3v2 title and artist tags if present at `offset`.
|
||||
fn parse_id3v2(bytes: &[u8], offset: usize) -> (Option<String>, Option<String>) {
|
||||
let Some(id3) = bytes.get(offset..) else {
|
||||
return (None, None);
|
||||
};
|
||||
if id3.len() < 10 || &id3[..3] != b"ID3" {
|
||||
return (None, None);
|
||||
}
|
||||
|
||||
let mut title = None;
|
||||
let mut artist = None;
|
||||
|
||||
// ID3v2 size is 4 synchsafe bytes at offset 6.
|
||||
let tag_size = ((id3[6] as usize & 0x7F) << 21) | ((id3[7] as usize & 0x7F) << 14) | ((id3[8] as usize & 0x7F) << 7) | (id3[9] as usize & 0x7F);
|
||||
|
||||
let end = (10 + tag_size).min(id3.len());
|
||||
let mut pos = 10;
|
||||
|
||||
// Scan ID3v2.3 / ID3v2.4 frames.
|
||||
while pos + 10 <= end {
|
||||
let frame_id = &id3[pos..pos + 4];
|
||||
if frame_id[0] == 0 {
|
||||
break;
|
||||
}
|
||||
let raw = [id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]];
|
||||
// ID3v2.4 frame sizes are synchsafe; v2.3 ones are plain big-endian.
|
||||
let frame_size = if id3[3] >= 4 {
|
||||
if raw.iter().any(|b| b & 0x80 != 0) {
|
||||
break;
|
||||
}
|
||||
((raw[0] as usize) << 21) | ((raw[1] as usize) << 14) | ((raw[2] as usize) << 7) | raw[3] as usize
|
||||
} else {
|
||||
u32::from_be_bytes(raw) as usize
|
||||
};
|
||||
pos += 10;
|
||||
if frame_size > end.saturating_sub(pos) {
|
||||
break;
|
||||
}
|
||||
|
||||
let frame_data = &id3[pos..pos + frame_size];
|
||||
pos += frame_size;
|
||||
|
||||
if frame_id == b"TIT2" && title.is_none() {
|
||||
title = parse_text_frame(frame_data);
|
||||
} else if frame_id == b"TPE1" && artist.is_none() {
|
||||
artist = parse_text_frame(frame_data);
|
||||
}
|
||||
}
|
||||
|
||||
(title, artist)
|
||||
}
|
||||
|
||||
fn parse_text_frame(data: &[u8]) -> Option<String> {
|
||||
if data.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let encoding = data[0];
|
||||
let content = &data[1..];
|
||||
let text = match encoding {
|
||||
// ISO-8859-1: every byte is the code point of the same value.
|
||||
0 => content.iter().map(|&b| char::from(b)).collect::<String>(),
|
||||
3 => String::from_utf8_lossy(content).into_owned(),
|
||||
// UTF-16 with a byte order mark (which is removed); without one, assume big-endian.
|
||||
1 => {
|
||||
let (big_endian, body) = match content {
|
||||
[0xFE, 0xFF, rest @ ..] => (true, rest),
|
||||
[0xFF, 0xFE, rest @ ..] => (false, rest),
|
||||
_ => (true, content),
|
||||
};
|
||||
utf16(body, big_endian)
|
||||
}
|
||||
// UTF-16BE without a byte order mark.
|
||||
2 => utf16(content, true),
|
||||
_ => return None,
|
||||
};
|
||||
let s = text.trim_end_matches('\0').trim().to_string();
|
||||
if s.is_empty() { None } else { Some(s) }
|
||||
}
|
||||
|
||||
fn utf16(bytes: &[u8], big_endian: bool) -> String {
|
||||
let units: Vec<u16> = bytes
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| if big_endian { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) })
|
||||
.collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
/// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel.
|
||||
pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> {
|
||||
let (metadata, offset, _, block_size) = parse_dsf_header_bounded(bytes)?;
|
||||
Ok((metadata, offset, block_size))
|
||||
}
|
||||
|
||||
fn parse_dsf_header_bounded(bytes: &[u8]) -> Result<(Metadata, usize, usize, u32), Error> {
|
||||
if bytes.len() < 28 + 52 + 12 {
|
||||
return Err(Error::UnexpectedEof("DSF file header is truncated"));
|
||||
}
|
||||
|
||||
// 1. 'DSD ' chunk
|
||||
if &bytes[..4] != b"DSD " {
|
||||
return Err(Error::InvalidHeader("missing 'DSD ' magic header"));
|
||||
}
|
||||
let dsd_chunk_size = u64::from_le_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("DSD chunk size"))?);
|
||||
if dsd_chunk_size != 28 {
|
||||
return Err(Error::InvalidHeader("invalid 'DSD ' chunk size (must be 28)"));
|
||||
}
|
||||
let file_size = u64::from_le_bytes(bytes[12..20].try_into().map_err(|_| Error::UnexpectedEof("file size"))?);
|
||||
let metadata_offset = u64::from_le_bytes(bytes[20..28].try_into().map_err(|_| Error::UnexpectedEof("metadata offset"))?);
|
||||
|
||||
if file_size > bytes.len() as u64 {
|
||||
return Err(Error::UnexpectedEof("declared file size extends beyond buffer"));
|
||||
}
|
||||
let file_len = usize::try_from(file_size).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
if file_len < 28 + 52 + 12 {
|
||||
return Err(Error::InvalidHeader("declared file size is smaller than required headers"));
|
||||
}
|
||||
let file_bytes = &bytes[..file_len];
|
||||
|
||||
// 2. 'fmt ' chunk
|
||||
let fmt_offset = 28;
|
||||
if &file_bytes[fmt_offset..fmt_offset + 4] != b"fmt " {
|
||||
return Err(Error::InvalidHeader("missing 'fmt ' chunk header"));
|
||||
}
|
||||
let fmt_chunk_size =
|
||||
u64::from_le_bytes(file_bytes[fmt_offset + 4..fmt_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("fmt chunk size"))?);
|
||||
if fmt_chunk_size < 52 {
|
||||
return Err(Error::InvalidHeader("invalid 'fmt ' chunk size (must be at least 52)"));
|
||||
}
|
||||
let fmt_size = usize::try_from(fmt_chunk_size).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
if fmt_size > file_bytes.len().saturating_sub(fmt_offset) {
|
||||
return Err(Error::UnexpectedEof("fmt chunk extends beyond file bounds"));
|
||||
}
|
||||
|
||||
let format_version =
|
||||
u32::from_le_bytes(file_bytes[fmt_offset + 12..fmt_offset + 16].try_into().map_err(|_| Error::UnexpectedEof("format version"))?);
|
||||
if format_version != 1 {
|
||||
return Err(Error::Unsupported("unsupported DSF format version (only version 1 is supported)"));
|
||||
}
|
||||
|
||||
let format_id = u32::from_le_bytes(file_bytes[fmt_offset + 16..fmt_offset + 20].try_into().map_err(|_| Error::UnexpectedEof("format id"))?);
|
||||
if format_id != 0 {
|
||||
return Err(Error::Unsupported("unsupported DSF format id (only raw DSD id=0 is supported)"));
|
||||
}
|
||||
|
||||
let channel_type = u32::from_le_bytes(file_bytes[fmt_offset + 20..fmt_offset + 24].try_into().map_err(|_| Error::UnexpectedEof("channel type"))?);
|
||||
let channel_count =
|
||||
u32::from_le_bytes(file_bytes[fmt_offset + 24..fmt_offset + 28].try_into().map_err(|_| Error::UnexpectedEof("channel count"))?);
|
||||
if channel_count == 0 || channel_count > MAX_CHANNELS as u32 {
|
||||
return Err(Error::Unsupported("DSF channel count must be between 1 and 8"));
|
||||
}
|
||||
let channels = channel_count as u16;
|
||||
|
||||
let sample_rate =
|
||||
u32::from_le_bytes(file_bytes[fmt_offset + 28..fmt_offset + 32].try_into().map_err(|_| Error::UnexpectedEof("sampling frequency"))?);
|
||||
if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) {
|
||||
return Err(Error::InvalidHeader("DSF sampling frequency out of valid range"));
|
||||
}
|
||||
|
||||
let bits_per_sample =
|
||||
u32::from_le_bytes(file_bytes[fmt_offset + 32..fmt_offset + 36].try_into().map_err(|_| Error::UnexpectedEof("bits per sample"))?);
|
||||
if bits_per_sample != 1 {
|
||||
return Err(Error::Unsupported("DSF bits per sample must be 1"));
|
||||
}
|
||||
|
||||
let sample_count = u64::from_le_bytes(file_bytes[fmt_offset + 36..fmt_offset + 44].try_into().map_err(|_| Error::UnexpectedEof("sample count"))?);
|
||||
|
||||
let block_size_per_channel =
|
||||
u32::from_le_bytes(file_bytes[fmt_offset + 44..fmt_offset + 48].try_into().map_err(|_| Error::UnexpectedEof("block size per channel"))?);
|
||||
if block_size_per_channel == 0 || block_size_per_channel > MAX_BLOCK_SIZE {
|
||||
return Err(Error::InvalidHeader("DSF block size per channel is invalid or too large"));
|
||||
}
|
||||
|
||||
// 3. 'data' chunk
|
||||
let data_offset = fmt_offset.saturating_add(fmt_size);
|
||||
if data_offset.saturating_add(12) > file_bytes.len() {
|
||||
return Err(Error::UnexpectedEof("missing 'data' chunk header"));
|
||||
}
|
||||
if &file_bytes[data_offset..data_offset + 4] != b"data" {
|
||||
return Err(Error::InvalidHeader("missing 'data' chunk header"));
|
||||
}
|
||||
let data_chunk_size =
|
||||
u64::from_le_bytes(file_bytes[data_offset + 4..data_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("data chunk size"))?);
|
||||
if data_chunk_size < 12 {
|
||||
return Err(Error::InvalidHeader("invalid 'data' chunk size (must be at least 12)"));
|
||||
}
|
||||
|
||||
let payload_offset = data_offset + 12;
|
||||
let payload_size = usize::try_from(data_chunk_size - 12).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
if payload_size > file_bytes.len().saturating_sub(payload_offset) {
|
||||
return Err(Error::UnexpectedEof("data chunk payload extends beyond file bounds"));
|
||||
}
|
||||
let data_end = payload_offset.saturating_add(payload_size);
|
||||
|
||||
// Parse ID3v2 metadata if pointer is valid.
|
||||
let (title, artist) = if metadata_offset == 0 {
|
||||
(None, None)
|
||||
} else {
|
||||
let meta_offset = usize::try_from(metadata_offset).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
if meta_offset < data_end || meta_offset >= file_len {
|
||||
return Err(Error::InvalidHeader("DSF metadata offset outside declared file bounds"));
|
||||
}
|
||||
parse_id3v2(file_bytes, meta_offset)
|
||||
};
|
||||
|
||||
let channel_names = dsf_channel_names(channel_type, channels);
|
||||
|
||||
let metadata = Metadata { format: Format::Dsf, sample_rate, channels, sample_count, channel_names, title, artist };
|
||||
|
||||
Ok((metadata, payload_offset, payload_size, block_size_per_channel))
|
||||
}
|
||||
|
||||
/// Parses a DSF file into raw 1-bit planar channel streams.
|
||||
pub fn parse_dsf(bytes: &[u8]) -> Result<RawAudio, Error> {
|
||||
let (metadata, payload_offset, payload_size, block_size) = parse_dsf_header_bounded(bytes)?;
|
||||
let block_size = block_size as usize;
|
||||
let channels = metadata.channels as usize;
|
||||
|
||||
let target_bytes_per_channel = usize::try_from(metadata.sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
if target_bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES {
|
||||
return Err(Error::MemoryLimitExceeded);
|
||||
}
|
||||
|
||||
let slice_size = channels.saturating_mul(block_size);
|
||||
if slice_size == 0 {
|
||||
return Err(Error::InvalidHeader("zero slice size"));
|
||||
}
|
||||
|
||||
// The header validated this range. Trailing ID3 or other bytes are not audio,
|
||||
// even if sample_count asks for more samples than the data chunk contains.
|
||||
let payload = &bytes[payload_offset..payload_offset + payload_size];
|
||||
let num_slices = payload.len() / slice_size;
|
||||
|
||||
let mut channel_bytes: Vec<Vec<u8>> = Vec::with_capacity(channels);
|
||||
for _ in 0..channels {
|
||||
let mut ch_vec = Vec::new();
|
||||
ch_vec.try_reserve_exact(target_bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
channel_bytes.push(ch_vec);
|
||||
}
|
||||
|
||||
for s in 0..num_slices {
|
||||
let slice_base = s * slice_size;
|
||||
for (c, ch_vec) in channel_bytes.iter_mut().enumerate() {
|
||||
let ch_start = slice_base + c * block_size;
|
||||
let ch_end = ch_start + block_size;
|
||||
if let Some(block) = payload.get(ch_start..ch_end) {
|
||||
let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len());
|
||||
let take = block.len().min(remaining);
|
||||
ch_vec.extend_from_slice(&block[..take]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle any trailing partial slice.
|
||||
let remainder = payload.len() % slice_size;
|
||||
if remainder > 0 {
|
||||
let slice_base = num_slices * slice_size;
|
||||
for (c, ch_vec) in channel_bytes.iter_mut().enumerate() {
|
||||
let ch_start = slice_base + c * block_size;
|
||||
if ch_start < payload.len() {
|
||||
let ch_end = (ch_start + block_size).min(payload.len());
|
||||
let block = &payload[ch_start..ch_end];
|
||||
let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len());
|
||||
let take = block.len().min(remaining);
|
||||
ch_vec.extend_from_slice(&block[..take]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pad with silence (0x69) if the file had fewer bytes than required by sample_count.
|
||||
for ch_vec in &mut channel_bytes {
|
||||
if ch_vec.len() < target_bytes_per_channel {
|
||||
ch_vec.resize(target_bytes_per_channel, super::filter::SILENCE_LSBF);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RawAudio { metadata, bit_order: BitOrder::LsbFirst, channel_bytes })
|
||||
}
|
||||
|
||||
fn unsupported_channel_layout() -> Result<u32, Error> {
|
||||
Err(Error::Unsupported("DSF has no channel type for this channel count (1 to 6 are supported)"))
|
||||
}
|
||||
|
||||
/// Encodes 1-bit planar audio channels into a valid Sony DSF file.
|
||||
pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result<Vec<u8>, Error> {
|
||||
if channels.is_empty() || channels.len() > MAX_CHANNELS {
|
||||
return Err(Error::Unsupported("channel count must be between 1 and 8"));
|
||||
}
|
||||
if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) {
|
||||
return Err(Error::InvalidData("sample rate out of bounds"));
|
||||
}
|
||||
if block_size > MAX_BLOCK_SIZE {
|
||||
return Err(Error::InvalidData("DSF block size exceeds maximum"));
|
||||
}
|
||||
let block_size = if block_size == 0 { 4096 } else { block_size as usize };
|
||||
|
||||
let num_channels = channels.len();
|
||||
let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
let num_blocks = bytes_per_ch.div_ceil(block_size);
|
||||
let payload_size = num_blocks.checked_mul(num_channels).and_then(|n| n.checked_mul(block_size)).ok_or(Error::MemoryLimitExceeded)?;
|
||||
let file_size = super::encoded_size(payload_size, 92)?;
|
||||
|
||||
let data_chunk_size = 12u64 + payload_size as u64;
|
||||
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
|
||||
// 1. 'DSD ' chunk (28 bytes)
|
||||
out.extend_from_slice(b"DSD ");
|
||||
out.extend_from_slice(&28u64.to_le_bytes());
|
||||
out.extend_from_slice(&(file_size as u64).to_le_bytes());
|
||||
out.extend_from_slice(&0u64.to_le_bytes()); // metadata offset = 0
|
||||
|
||||
// 2. 'fmt ' chunk (52 bytes)
|
||||
out.extend_from_slice(b"fmt ");
|
||||
out.extend_from_slice(&52u64.to_le_bytes());
|
||||
out.extend_from_slice(&1u32.to_le_bytes()); // format_version = 1
|
||||
out.extend_from_slice(&0u32.to_le_bytes()); // format_id = 0 (raw DSD)
|
||||
// DSF channel types: 1 mono, 2 stereo, 3 L R C, 4 quad, 6 five channels, 7 5.1.
|
||||
let channel_type = match num_channels {
|
||||
1 => 1u32,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 6,
|
||||
6 => 7,
|
||||
_ => unsupported_channel_layout()?,
|
||||
};
|
||||
out.extend_from_slice(&channel_type.to_le_bytes());
|
||||
out.extend_from_slice(&(num_channels as u32).to_le_bytes());
|
||||
out.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
out.extend_from_slice(&1u32.to_le_bytes()); // bits_per_sample = 1
|
||||
out.extend_from_slice(&sample_count.to_le_bytes());
|
||||
out.extend_from_slice(&(block_size as u32).to_le_bytes());
|
||||
out.extend_from_slice(&0u32.to_le_bytes()); // reserved
|
||||
|
||||
// 3. 'data' chunk
|
||||
out.extend_from_slice(b"data");
|
||||
out.extend_from_slice(&data_chunk_size.to_le_bytes());
|
||||
|
||||
for b in 0..num_blocks {
|
||||
let blk_start = b * block_size;
|
||||
let blk_end = blk_start + block_size;
|
||||
for ch_data in channels {
|
||||
let available = if blk_start < ch_data.len() {
|
||||
let end = blk_end.min(ch_data.len());
|
||||
&ch_data[blk_start..end]
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
out.extend_from_slice(available);
|
||||
if available.len() < block_size {
|
||||
out.resize(out.len() + (block_size - available.len()), super::filter::SILENCE_LSBF);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! DSD-to-PCM decimation filter.
|
||||
//!
|
||||
//! Direct Stream Digital (DSD) uses 1-bit Sigma-Delta modulation sampled at high rates
|
||||
//! (2,822,400 Hz for DSD64, 5,644,800 Hz for DSD128, etc.). Decimation to multi-bit PCM
|
||||
//! involves low-pass filtering to attenuate high-frequency quantization noise followed
|
||||
//! by downsampling.
|
||||
//!
|
||||
//! This module provides a 96-tap symmetric FIR decimation filter that downsamples 1-bit DSD
|
||||
//! to multi-bit PCM at 1/8th of the DSD sampling rate (e.g. 352,800 Hz for DSD64). Further
|
||||
//! integer decimation (to 176.4 kHz, 88.2 kHz, or 44.1 kHz) is supported via subsequent
|
||||
//! downsampling stages.
|
||||
|
||||
use super::{BitOrder, Error, MAX_DECODE_BYTES};
|
||||
|
||||
/// 96-tap symmetric FIR decimation filter coefficients for decimation by 8.
|
||||
///
|
||||
/// Output is normalized so that alternating silence bits (0x69 or 0xAA) decode near 0.0,
|
||||
/// and full-scale runs of 1s or 0s decode near +1.0 and -1.0.
|
||||
#[allow(clippy::excessive_precision)]
|
||||
pub const TAPS_96: [f32; 96] = [
|
||||
2.9802322388e-08_f32,
|
||||
1.1920928955e-07_f32,
|
||||
3.5762786865e-07_f32,
|
||||
7.4505805969e-07_f32,
|
||||
1.3113021851e-06_f32,
|
||||
1.9371509552e-06_f32,
|
||||
2.1755695343e-06_f32,
|
||||
1.2516975403e-06_f32,
|
||||
-1.9967556000e-06_f32,
|
||||
-9.1493129730e-06_f32,
|
||||
-2.1725893021e-05_f32,
|
||||
-4.0739774704e-05_f32,
|
||||
-6.5773725510e-05_f32,
|
||||
-9.3966722488e-05_f32,
|
||||
-1.1900067329e-04_f32,
|
||||
-1.3050436974e-04_f32,
|
||||
-1.1405348778e-04_f32,
|
||||
-5.2779912949e-05_f32,
|
||||
7.0035457611e-05_f32,
|
||||
2.6643276215e-04_f32,
|
||||
5.3817033768e-04_f32,
|
||||
8.7043642998e-04_f32,
|
||||
1.2266933918e-03_f32,
|
||||
1.5456080437e-03_f32,
|
||||
1.7420351505e-03_f32,
|
||||
1.7137229443e-03_f32,
|
||||
1.3538300991e-03_f32,
|
||||
5.7008862495e-04_f32,
|
||||
-6.9221854210e-04_f32,
|
||||
-2.4250447750e-03_f32,
|
||||
-4.5351684093e-03_f32,
|
||||
-6.8288743496e-03_f32,
|
||||
-9.0079009533e-03_f32,
|
||||
-1.0681360960e-02_f32,
|
||||
-1.1394292116e-02_f32,
|
||||
-1.0672420263e-02_f32,
|
||||
-8.0802738667e-03_f32,
|
||||
-3.2847225666e-03_f32,
|
||||
3.8830339909e-03_f32,
|
||||
1.3377487659e-02_f32,
|
||||
2.4909228086e-02_f32,
|
||||
3.7942945957e-02_f32,
|
||||
5.1726281643e-02_f32,
|
||||
6.5348774195e-02_f32,
|
||||
7.7825516462e-02_f32,
|
||||
8.8196486235e-02_f32,
|
||||
9.5628470182e-02_f32,
|
||||
9.9507331848e-02_f32,
|
||||
9.9507331848e-02_f32,
|
||||
9.5628470182e-02_f32,
|
||||
8.8196486235e-02_f32,
|
||||
7.7825516462e-02_f32,
|
||||
6.5348774195e-02_f32,
|
||||
5.1726281643e-02_f32,
|
||||
3.7942945957e-02_f32,
|
||||
2.4909228086e-02_f32,
|
||||
1.3377487659e-02_f32,
|
||||
3.8830339909e-03_f32,
|
||||
-3.2847225666e-03_f32,
|
||||
-8.0802738667e-03_f32,
|
||||
-1.0672420263e-02_f32,
|
||||
-1.1394292116e-02_f32,
|
||||
-1.0681360960e-02_f32,
|
||||
-9.0079009533e-03_f32,
|
||||
-6.8288743496e-03_f32,
|
||||
-4.5351684093e-03_f32,
|
||||
-2.4250447750e-03_f32,
|
||||
-6.9221854210e-04_f32,
|
||||
5.7008862495e-04_f32,
|
||||
1.3538300991e-03_f32,
|
||||
1.7137229443e-03_f32,
|
||||
1.7420351505e-03_f32,
|
||||
1.5456080437e-03_f32,
|
||||
1.2266933918e-03_f32,
|
||||
8.7043642998e-04_f32,
|
||||
5.3817033768e-04_f32,
|
||||
2.6643276215e-04_f32,
|
||||
7.0035457611e-05_f32,
|
||||
-5.2779912949e-05_f32,
|
||||
-1.1405348778e-04_f32,
|
||||
-1.3050436974e-04_f32,
|
||||
-1.1900067329e-04_f32,
|
||||
-9.3966722488e-05_f32,
|
||||
-6.5773725510e-05_f32,
|
||||
-4.0739774704e-05_f32,
|
||||
-2.1725893021e-05_f32,
|
||||
-9.1493129730e-06_f32,
|
||||
-1.9967556000e-06_f32,
|
||||
1.2516975403e-06_f32,
|
||||
2.1755695343e-06_f32,
|
||||
1.9371509552e-06_f32,
|
||||
1.3113021851e-06_f32,
|
||||
7.4505805969e-07_f32,
|
||||
3.5762786865e-07_f32,
|
||||
1.1920928955e-07_f32,
|
||||
2.9802322388e-08_f32,
|
||||
];
|
||||
|
||||
/// The number of filter history bytes (96 taps / 8 bits per byte = 12 bytes).
|
||||
pub const FILTER_BYTES: usize = 12;
|
||||
|
||||
/// Standard DSD silence pattern byte for LSB-first ordering (Sony DSF).
|
||||
pub const SILENCE_LSBF: u8 = 0x69;
|
||||
|
||||
/// Standard DSD silence pattern byte for MSB-first ordering (Philips DSDIFF).
|
||||
pub const SILENCE_MSBF: u8 = 0xAA;
|
||||
|
||||
/// Precomputes lookup table entries for byte position `k` (0..12) and byte value `v` (0..256).
|
||||
///
|
||||
/// In LSB-first order, bit `b` of input byte `k` corresponds to tap `k * 8 + b`.
|
||||
#[inline]
|
||||
fn byte_lut(k: usize, byte_val: u8) -> f32 {
|
||||
let mut sum = 0.0_f32;
|
||||
let base_tap = k * 8;
|
||||
for b in 0..8 {
|
||||
if ((byte_val >> b) & 1) != 0
|
||||
&& let Some(tap) = TAPS_96.get(base_tap + b)
|
||||
{
|
||||
sum += 2.0 * *tap;
|
||||
}
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
// Both the first-stage samples and the secondary output coexist during filtering.
|
||||
pub(super) fn allocation_sizes(len: usize, factor: u32) -> Result<(usize, usize), Error> {
|
||||
if !matches!(factor, 8 | 16 | 32 | 64) {
|
||||
return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64"));
|
||||
}
|
||||
let stage = len.checked_mul(std::mem::size_of::<f32>()).ok_or(Error::MemoryLimitExceeded)?;
|
||||
let output = (len / (factor / 8) as usize).checked_mul(std::mem::size_of::<f32>()).ok_or(Error::MemoryLimitExceeded)?;
|
||||
let working = if factor == 8 { stage } else { stage.checked_add(output).ok_or(Error::MemoryLimitExceeded)? };
|
||||
if working > MAX_DECODE_BYTES {
|
||||
return Err(Error::MemoryLimitExceeded);
|
||||
}
|
||||
Ok((working, output))
|
||||
}
|
||||
|
||||
/// Unity-DC-gain low-pass taps for decimating by `ratio` (cutoff 0.45 / ratio cycles per sample).
|
||||
fn decimation_taps(ratio: usize) -> Vec<f32> {
|
||||
let n = 24 * ratio + 1;
|
||||
let mid = (n / 2) as f64;
|
||||
let fc = 0.45 / ratio as f64;
|
||||
let mut taps: Vec<f64> = (0..n)
|
||||
.map(|k| {
|
||||
let x = k as f64 - mid;
|
||||
let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) };
|
||||
let t = k as f64 / (n - 1) as f64;
|
||||
let window = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * t).cos() + 0.08 * (4.0 * std::f64::consts::PI * t).cos();
|
||||
sinc * window
|
||||
})
|
||||
.collect();
|
||||
let sum: f64 = taps.iter().sum();
|
||||
for t in &mut taps {
|
||||
*t /= sum;
|
||||
}
|
||||
taps.into_iter().map(|t| t as f32).collect()
|
||||
}
|
||||
|
||||
/// Decimates 1-bit DSD audio bytes for a single channel to `f32` PCM.
|
||||
///
|
||||
/// The default decimation factor is 8 (1 output float per input byte).
|
||||
/// When `factor` is 16, 32, or 64, the 1/8 output is further downsampled
|
||||
/// by 2, 4, or 8 respectively.
|
||||
pub fn decimate_channel(channel_bytes: &[u8], bit_order: BitOrder, factor: u32) -> Result<Vec<f32>, Error> {
|
||||
allocation_sizes(channel_bytes.len(), factor)?;
|
||||
let num_bytes = channel_bytes.len();
|
||||
|
||||
// Build the 12 x 256 lookup table for fast convolution.
|
||||
// 12 * 256 * 4 bytes = 12 KB, sits comfortably in L1 cache.
|
||||
let mut lut = [[0.0_f32; 256]; FILTER_BYTES];
|
||||
for (k, lut_k) in lut.iter_mut().enumerate() {
|
||||
for (v, cell) in lut_k.iter_mut().enumerate() {
|
||||
*cell = byte_lut(k, v as u8);
|
||||
}
|
||||
}
|
||||
|
||||
let mut stage1 = Vec::new();
|
||||
stage1.try_reserve_exact(num_bytes).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
|
||||
// History buffer holds the most recent 12 bytes in LSB-first order.
|
||||
// Pre-filled with silence (0x69).
|
||||
let mut history = [SILENCE_LSBF; FILTER_BYTES];
|
||||
|
||||
for &raw_byte in channel_bytes {
|
||||
let byte = match bit_order {
|
||||
BitOrder::LsbFirst => raw_byte,
|
||||
BitOrder::MsbFirst => raw_byte.reverse_bits(),
|
||||
};
|
||||
|
||||
// Shift history left by 1 and push current byte to the end.
|
||||
history.copy_within(1.., 0);
|
||||
if let Some(last) = history.last_mut() {
|
||||
*last = byte;
|
||||
}
|
||||
|
||||
let mut sample = -1.0_f32;
|
||||
for (k, &hist_byte) in history.iter().enumerate() {
|
||||
if let Some(lut_k) = lut.get(k)
|
||||
&& let Some(&contrib) = lut_k.get(hist_byte as usize)
|
||||
{
|
||||
sample += contrib;
|
||||
}
|
||||
}
|
||||
|
||||
stage1.push(sample);
|
||||
}
|
||||
|
||||
if factor == 8 {
|
||||
return Ok(stage1);
|
||||
}
|
||||
|
||||
// Secondary decimation by ratio = factor / 8 (2, 4, or 8). A plain average attenuates the band
|
||||
// between the new Nyquist rate and the stage-1 rate too little (about -7.6 dB at 29.4 kHz for
|
||||
// factor 64), so low-pass first: a Blackman-windowed sinc with its cutoff at 90% of the new
|
||||
// Nyquist frequency, evaluated only at the kept samples.
|
||||
let ratio = (factor / 8) as usize;
|
||||
let out_len = stage1.len() / ratio;
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(out_len).map_err(|_| Error::MemoryLimitExceeded)?;
|
||||
|
||||
let taps = decimation_taps(ratio);
|
||||
let half = (taps.len() / 2) as isize;
|
||||
let last = stage1.len() as isize - 1;
|
||||
for i in 0..out_len {
|
||||
let center = (i * ratio + ratio / 2) as isize;
|
||||
let mut acc = 0.0_f32;
|
||||
for (k, &w) in taps.iter().enumerate() {
|
||||
let idx = (center + k as isize - half).clamp(0, last);
|
||||
if let Some(&x) = stage1.get(idx as usize) {
|
||||
acc += w * x;
|
||||
}
|
||||
}
|
||||
out.push(acc);
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod decimation_tests {
|
||||
use super::*;
|
||||
|
||||
/// A full-scale 29.4 kHz square wave in DSD64 (six bytes of ones, six of zeros) lies between
|
||||
/// the output Nyquist frequency and the sampling rate of a 44.1 kHz result: it must be
|
||||
/// attenuated well, not folded down at 0.42 of its amplitude.
|
||||
#[test]
|
||||
fn factor_64_attenuates_29_4_khz() {
|
||||
let mut bytes = Vec::new();
|
||||
for _ in 0..2000 {
|
||||
bytes.extend_from_slice(&[0xFF; 6]);
|
||||
bytes.extend_from_slice(&[0x00; 6]);
|
||||
}
|
||||
let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap();
|
||||
let mid = &out[out.len() / 4..out.len() * 3 / 4];
|
||||
let peak = mid.iter().fold(0.0_f32, |m, v| m.max(v.abs()));
|
||||
assert!(peak < 0.05, "peak {peak}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimation_keeps_dc_level() {
|
||||
let bytes = vec![0xFF; 4096];
|
||||
let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap();
|
||||
let mid = out[out.len() / 2];
|
||||
assert!((mid - 1.0).abs() < 0.05, "{mid}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! Direct Stream Digital (DSD) audio: Sony DSF and Philips DSDIFF (`.dff`) readers and
|
||||
//! DSD-to-PCM decimation.
|
||||
//!
|
||||
//! DSD stores 1-bit Pulse Density Modulation (PDM) sampled at high rates (e.g. 2,822,400 Hz
|
||||
//! for DSD64, 5,644,800 Hz for DSD128, etc.).
|
||||
//!
|
||||
//! This module provides:
|
||||
//! - File parsers for Sony DSF (`.dsf`) and Philips DSDIFF (`.dff`) containers.
|
||||
//! - Raw 1-bit audio extraction with preservation of native bit ordering (LSB-first for DSF,
|
||||
//! MSB-first for DSDIFF).
|
||||
//! - Clean-room 96-tap symmetric FIR decimation filter converting 1-bit PDM to multi-bit PCM
|
||||
//! (decimation by 8 to 352,800 Hz for DSD64, or downsampled to 176.4, 88.2, or 44.1 kHz).
|
||||
//! - Reference encoders for generating synthetic DSF and DSDIFF files.
|
||||
|
||||
pub mod dsdiff;
|
||||
pub mod dsf;
|
||||
pub mod filter;
|
||||
|
||||
use crate::AudioBuffer;
|
||||
|
||||
/// Maximum number of audio channels supported (1 to 8).
|
||||
pub const MAX_CHANNELS: usize = 8;
|
||||
|
||||
/// Minimum allowable DSD sample rate in Hz.
|
||||
pub const MIN_SAMPLE_RATE: u32 = 44_100;
|
||||
|
||||
/// Maximum allowable DSD sample rate in Hz (e.g. DSD1024 at 45.1584 MHz).
|
||||
pub const MAX_SAMPLE_RATE: u32 = 45_158_400;
|
||||
|
||||
/// Maximum safe block size for DSF channel blocks (16 MiB).
|
||||
pub const MAX_BLOCK_SIZE: u32 = 16 * 1024 * 1024;
|
||||
|
||||
/// Maximum audio-buffer allocation budget (256 MiB).
|
||||
///
|
||||
/// Raw readers limit their channel bytes; PCM conversion separately limits the
|
||||
/// simultaneously live PCM output and scratch buffers. Caller-owned raw input,
|
||||
/// metadata, and the small filter lookup table are not included.
|
||||
pub const MAX_DECODE_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Maximum encoded container size, including headers and block padding (256 MiB).
|
||||
pub const MAX_ENCODE_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
fn encoded_size(payload: usize, header: usize) -> Result<usize, Error> {
|
||||
payload.checked_add(header).filter(|&n| n <= MAX_ENCODE_BYTES).ok_or(Error::MemoryLimitExceeded)
|
||||
}
|
||||
|
||||
// Account for retained channel output plus the current filter's two live buffers.
|
||||
fn pcm_budget(lengths: impl Iterator<Item = usize>, factor: u32) -> Result<(), Error> {
|
||||
let mut retained = 0usize;
|
||||
for len in lengths {
|
||||
let (working, output) = filter::allocation_sizes(len, factor)?;
|
||||
if retained.checked_add(working).is_none_or(|n| n > MAX_DECODE_BYTES) {
|
||||
return Err(Error::MemoryLimitExceeded);
|
||||
}
|
||||
retained = retained.checked_add(output).ok_or(Error::MemoryLimitExceeded)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Supported DSD container formats.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Format {
|
||||
/// Sony DSF (Direct Stream Digital File) format.
|
||||
Dsf,
|
||||
/// Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`).
|
||||
Dsdiff,
|
||||
}
|
||||
|
||||
/// Bit ordering of 1-bit DSD audio samples within bytes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum BitOrder {
|
||||
/// Least-significant bit first (LSB-first, as used in DSF).
|
||||
/// Bit 0 is the earliest temporal sample; bit 7 is the latest.
|
||||
LsbFirst,
|
||||
/// Most-significant bit first (MSB-first, as used in DSDIFF).
|
||||
/// Bit 7 is the earliest temporal sample; bit 0 is the latest.
|
||||
MsbFirst,
|
||||
}
|
||||
|
||||
/// Stream properties and metadata parsed from a DSD container header.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Metadata {
|
||||
/// Container format (DSF or DSDIFF).
|
||||
pub format: Format,
|
||||
/// DSD sampling frequency in Hz (e.g. 2,822,400 for DSD64).
|
||||
pub sample_rate: u32,
|
||||
/// Number of audio channels (1 to 8).
|
||||
pub channels: u16,
|
||||
/// Total number of 1-bit audio samples per channel.
|
||||
pub sample_count: u64,
|
||||
/// Channel identification labels (e.g. "SLFT", "SRGT", "Center").
|
||||
pub channel_names: Vec<String>,
|
||||
/// Optional track title if present in container metadata.
|
||||
pub title: Option<String>,
|
||||
/// Optional artist name if present in container metadata.
|
||||
pub artist: Option<String>,
|
||||
}
|
||||
|
||||
/// Raw 1-bit DSD audio extracted from a file without decimation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RawAudio {
|
||||
/// Stream metadata from the file header.
|
||||
pub metadata: Metadata,
|
||||
/// Bit ordering of the bytes in `channel_bytes`.
|
||||
pub bit_order: BitOrder,
|
||||
/// Planar 1-bit audio bytes per channel.
|
||||
pub channel_bytes: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl RawAudio {
|
||||
/// Converts all channel byte streams to the requested bit ordering in place.
|
||||
pub fn convert_bit_order(&mut self, target: BitOrder) {
|
||||
if self.bit_order == target {
|
||||
return;
|
||||
}
|
||||
for ch in &mut self.channel_bytes {
|
||||
for b in ch.iter_mut() {
|
||||
*b = b.reverse_bits();
|
||||
}
|
||||
}
|
||||
self.bit_order = target;
|
||||
}
|
||||
|
||||
/// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples.
|
||||
///
|
||||
/// The default decimation factor is 8 (e.g. 352,800 Hz for DSD64).
|
||||
pub fn to_pcm(&self) -> Result<DecodedAudio, Error> {
|
||||
self.to_pcm_with_factor(8)
|
||||
}
|
||||
|
||||
/// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples with the given factor (8, 16, 32, or 64).
|
||||
pub fn to_pcm_with_factor(&self, factor: u32) -> Result<DecodedAudio, Error> {
|
||||
// Validate before iterating: public RawAudio may contain no channels.
|
||||
if !matches!(factor, 8 | 16 | 32 | 64) {
|
||||
return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64"));
|
||||
}
|
||||
if self.channel_bytes.len() > MAX_CHANNELS {
|
||||
return Err(Error::Unsupported("channel count must be between 1 and 8"));
|
||||
}
|
||||
pcm_budget(self.channel_bytes.iter().map(Vec::len), factor)?;
|
||||
let mut channels = Vec::with_capacity(self.channel_bytes.len());
|
||||
for ch_bytes in &self.channel_bytes {
|
||||
let pcm = filter::decimate_channel(ch_bytes, self.bit_order, factor)?;
|
||||
channels.push(pcm);
|
||||
}
|
||||
let sample_rate = self.metadata.sample_rate / factor;
|
||||
Ok(DecodedAudio { metadata: self.metadata.clone(), sample_rate, channels })
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoded multi-bit PCM audio produced by DSD-to-PCM decimation.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DecodedAudio {
|
||||
/// Stream metadata from the DSD file header.
|
||||
pub metadata: Metadata,
|
||||
/// PCM sample rate in Hz (e.g. 352,800 Hz for DSD64 decimated by 8).
|
||||
pub sample_rate: u32,
|
||||
/// Planar normalized PCM samples in `[-1.0, 1.0]`, one `Vec<f32>` per channel.
|
||||
pub channels: Vec<Vec<f32>>,
|
||||
}
|
||||
|
||||
impl DecodedAudio {
|
||||
/// Converts the decoded PCM audio into an [`AudioBuffer`].
|
||||
pub fn to_audio_buffer(&self) -> AudioBuffer {
|
||||
AudioBuffer { sample_rate: self.sample_rate, channels: self.channels.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors returned when parsing or decoding DSD audio.
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// Input data ended prematurely while parsing a header or chunk.
|
||||
#[error("unexpected end of file: {0}")]
|
||||
UnexpectedEof(&'static str),
|
||||
/// Invalid magic bytes or malformed chunk header.
|
||||
#[error("invalid DSD header or chunk: {0}")]
|
||||
InvalidHeader(&'static str),
|
||||
/// An unsupported feature, compression, or channel configuration.
|
||||
#[error("unsupported DSD feature: {0}")]
|
||||
Unsupported(&'static str),
|
||||
/// Audio data length or structure does not match the header specification.
|
||||
#[error("invalid audio data: {0}")]
|
||||
InvalidData(&'static str),
|
||||
/// Header or data requested exceeds maximum safe allocation budget.
|
||||
#[error("memory budget exceeded")]
|
||||
MemoryLimitExceeded,
|
||||
}
|
||||
|
||||
/// Inspects the magic bytes of `bytes` and detects whether it is a DSF or DSDIFF file.
|
||||
pub fn probe_format(bytes: &[u8]) -> Result<Format, Error> {
|
||||
if bytes.len() < 4 {
|
||||
return Err(Error::UnexpectedEof("input is too short to determine DSD format"));
|
||||
}
|
||||
if &bytes[0..4] == b"DSD " {
|
||||
Ok(Format::Dsf)
|
||||
} else if bytes.len() >= 16 && &bytes[0..4] == b"FRM8" && &bytes[12..16] == b"DSD " {
|
||||
Ok(Format::Dsdiff)
|
||||
} else {
|
||||
Err(Error::InvalidHeader("unknown or unsupported DSD container format"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the metadata from a DSF or DSDIFF file without decoding audio samples.
|
||||
pub fn read_metadata(bytes: &[u8]) -> Result<Metadata, Error> {
|
||||
match probe_format(bytes)? {
|
||||
Format::Dsf => {
|
||||
let (meta, _, _) = dsf::parse_dsf_header(bytes)?;
|
||||
Ok(meta)
|
||||
}
|
||||
Format::Dsdiff => {
|
||||
let (meta, _, _) = dsdiff::parse_dsdiff_header(bytes)?;
|
||||
Ok(meta)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads raw 1-bit planar audio streams from a DSF or DSDIFF file without decimation.
|
||||
pub fn read_raw(bytes: &[u8]) -> Result<RawAudio, Error> {
|
||||
match probe_format(bytes)? {
|
||||
Format::Dsf => dsf::parse_dsf(bytes),
|
||||
Format::Dsdiff => dsdiff::parse_dsdiff(bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio using decimation by 8.
|
||||
///
|
||||
/// For DSD64 (2,822,400 Hz), the output sample rate is 352,800 Hz.
|
||||
pub fn decode(bytes: &[u8]) -> Result<DecodedAudio, Error> {
|
||||
decode_with_factor(bytes, 8)
|
||||
}
|
||||
|
||||
/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio with the specified decimation factor.
|
||||
///
|
||||
/// Supported decimation factors are:
|
||||
/// - 8: 1/8th of DSD rate (e.g. 352,800 Hz for DSD64).
|
||||
/// - 16: 1/16th of DSD rate (e.g. 176,400 Hz for DSD64).
|
||||
/// - 32: 1/32th of DSD rate (e.g. 88,200 Hz for DSD64).
|
||||
/// - 64: 1/64th of DSD rate (e.g. 44,100 Hz for DSD64).
|
||||
pub fn decode_with_factor(bytes: &[u8], factor: u32) -> Result<DecodedAudio, Error> {
|
||||
let raw = read_raw(bytes)?;
|
||||
raw.to_pcm_with_factor(factor)
|
||||
}
|
||||
|
||||
/// Encodes planar 1-bit audio channels into a Sony DSF file.
|
||||
pub fn encode_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result<Vec<u8>, Error> {
|
||||
dsf::write_dsf(sample_rate, channels, sample_count, block_size)
|
||||
}
|
||||
|
||||
/// Encodes planar 1-bit audio channels into a Philips DSDIFF file.
|
||||
pub fn encode_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result<Vec<u8>, Error> {
|
||||
dsdiff::write_dsdiff(sample_rate, channels, sample_count)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pcm_budget_counts_all_channels_and_live_scratch() {
|
||||
let quarter = MAX_DECODE_BYTES / 4;
|
||||
assert!(pcm_budget([quarter / 2, quarter / 2].into_iter(), 8).is_ok());
|
||||
assert_eq!(pcm_budget([quarter / 2, quarter / 2 + 1].into_iter(), 8), Err(Error::MemoryLimitExceeded));
|
||||
assert!(pcm_budget([quarter / 2].into_iter(), 16).is_ok());
|
||||
assert_eq!(pcm_budget([quarter].into_iter(), 16), Err(Error::MemoryLimitExceeded));
|
||||
assert_eq!(pcm_budget([usize::MAX].into_iter(), 8), Err(Error::MemoryLimitExceeded));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_budget_includes_headers_without_large_allocations() {
|
||||
assert_eq!(encoded_size(MAX_ENCODE_BYTES - 92, 92), Ok(MAX_ENCODE_BYTES));
|
||||
assert_eq!(encoded_size(MAX_ENCODE_BYTES - 91, 92), Err(Error::MemoryLimitExceeded));
|
||||
assert_eq!(encoded_size(usize::MAX, 92), Err(Error::MemoryLimitExceeded));
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
#![warn(missing_docs)]
|
||||
// The docs link items of every feature; built with fewer features, those links have no target.
|
||||
// CI and docs.rs build the docs with all features, where every link must resolve.
|
||||
#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks")), allow(rustdoc::broken_intra_doc_links))]
|
||||
#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks", feature = "dsd")), allow(rustdoc::broken_intra_doc_links))]
|
||||
//! Audio file I/O and codecs for the Craft apps. Input and output are byte slices or a
|
||||
//! [`craft_media::ByteSource`] (no filesystem access of its own); builds for
|
||||
//! `wasm32-unknown-unknown`.
|
||||
@@ -32,7 +32,7 @@
|
||||
//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`]
|
||||
//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder;
|
||||
//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`]
|
||||
//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM),
|
||||
//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM),
|
||||
//! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`:
|
||||
//! Sierra VMD sound).
|
||||
//!
|
||||
@@ -47,6 +47,8 @@ pub mod adpcm;
|
||||
#[cfg(any(feature = "alac-decode", feature = "alac-encode"))]
|
||||
pub mod alac;
|
||||
mod buffer;
|
||||
#[cfg(feature = "dsd")]
|
||||
pub mod dsd;
|
||||
#[cfg(feature = "g722")]
|
||||
pub mod g722;
|
||||
#[cfg(feature = "g726")]
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Hostile container sizes must return errors, never wrap offsets or panic.
|
||||
use craft_audio::dsd::{BitOrder, Error, RawAudio, encode_dsdiff, encode_dsf, read_metadata, read_raw};
|
||||
|
||||
#[test]
|
||||
fn dsf_untrusted_sizes_are_checked() {
|
||||
let original = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap();
|
||||
for offset in [32, 84] {
|
||||
// fmt and data chunk sizes
|
||||
for size in [u64::MAX, u64::MAX - 31, 1 << 32] {
|
||||
let mut bytes = original.clone();
|
||||
bytes[offset..offset + 8].copy_from_slice(&size.to_le_bytes());
|
||||
assert!(read_metadata(&bytes).is_err());
|
||||
assert!(read_raw(&bytes).is_err());
|
||||
}
|
||||
}
|
||||
let mut bytes = original;
|
||||
bytes[64..72].copy_from_slice(&u64::MAX.to_le_bytes());
|
||||
assert_eq!(read_raw(&bytes), Err(Error::MemoryLimitExceeded));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsdiff_untrusted_top_level_and_property_sizes_are_checked() {
|
||||
let original = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap();
|
||||
let prop = original.windows(4).position(|w| w == b"PROP").unwrap();
|
||||
for offset in [4, 20, prop + 20] {
|
||||
// FRM8, FVER, nested FS
|
||||
for size in [u64::MAX, u64::MAX - 31, 1 << 32] {
|
||||
let mut bytes = original.clone();
|
||||
bytes[offset..offset + 8].copy_from_slice(&size.to_be_bytes());
|
||||
assert!(read_metadata(&bytes).is_err());
|
||||
assert!(read_raw(&bytes).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsdiff_invalid_optional_disc_info_is_ignored_without_overflow() {
|
||||
let mut bytes = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap();
|
||||
let expected = read_metadata(&bytes).unwrap();
|
||||
bytes.extend_from_slice(b"DIIN");
|
||||
bytes.extend_from_slice(&12u64.to_be_bytes());
|
||||
bytes.extend_from_slice(b"DITI");
|
||||
bytes.extend_from_slice(&u64::MAX.to_be_bytes());
|
||||
let size = (bytes.len() - 12) as u64;
|
||||
bytes[4..12].copy_from_slice(&size.to_be_bytes());
|
||||
// Optional malformed text is ignored on 64-bit; unrepresentable sizes may
|
||||
// be rejected on narrower targets, but must never wrap or panic.
|
||||
match read_metadata(&bytes) {
|
||||
Ok(actual) => assert_eq!(actual, expected),
|
||||
Err(Error::MemoryLimitExceeded) => {}
|
||||
other => panic!("unexpected result: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_raw_audio_rejects_invalid_decimation_factors() {
|
||||
let bytes = encode_dsf(2_822_400, &[&[]], 0, 8).unwrap();
|
||||
let raw = RawAudio { metadata: read_metadata(&bytes).unwrap(), bit_order: BitOrder::LsbFirst, channel_bytes: Vec::new() };
|
||||
for factor in [0, 1, 7, 9, u32::MAX] {
|
||||
assert!(matches!(raw.to_pcm_with_factor(factor), Err(Error::Unsupported(_))));
|
||||
}
|
||||
for factor in [8, 16, 32, 64] {
|
||||
assert_eq!(raw.to_pcm_with_factor(factor).unwrap().sample_rate, 2_822_400 / factor);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writers_reject_unbounded_output_before_allocating() {
|
||||
let channels: [&[u8]; 8] = [&[]; 8];
|
||||
for count in [u64::MAX, (craft_audio::dsd::MAX_ENCODE_BYTES as u64 + 1) * 8] {
|
||||
assert_eq!(encode_dsf(2_822_400, &channels, count, 8), Err(Error::MemoryLimitExceeded));
|
||||
assert_eq!(encode_dsdiff(2_822_400, &channels, count), Err(Error::MemoryLimitExceeded));
|
||||
}
|
||||
assert!(matches!(encode_dsf(2_822_400, &[&[]], 0, u32::MAX), Err(Error::InvalidData(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() {
|
||||
for channels in 1..=8 {
|
||||
for len in 0..=9 {
|
||||
let data = vec![0x69; len];
|
||||
let planes = vec![data.as_slice(); channels];
|
||||
for block in [0, 1, 3, 8] {
|
||||
// DSF has channel types for 1 to 6 channels only.
|
||||
if channels > 6 {
|
||||
assert!(matches!(encode_dsf(2_822_400, &planes, len as u64 * 8, block), Err(Error::Unsupported(_))));
|
||||
continue;
|
||||
}
|
||||
let dsf = encode_dsf(2_822_400, &planes, len as u64 * 8, block).unwrap();
|
||||
assert_eq!(u64::from_le_bytes(dsf[12..20].try_into().unwrap()), dsf.len() as u64);
|
||||
assert_eq!(read_raw(&dsf).unwrap().channel_bytes, vec![data.clone(); channels]);
|
||||
}
|
||||
let dff = encode_dsdiff(2_822_400, &planes, len as u64 * 8).unwrap();
|
||||
assert_eq!(u64::from_be_bytes(dff[4..12].try_into().unwrap()) + 12, dff.len() as u64);
|
||||
assert_eq!(read_raw(&dff).unwrap().channel_bytes, vec![data; channels]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsf_audio_stops_at_the_declared_data_chunk() {
|
||||
for channels in 1..=2 {
|
||||
let input = vec![&[0x33u8; 8][..]; channels];
|
||||
let mut bytes = encode_dsf(2_822_400, &input, 64, 8).unwrap();
|
||||
// Ask for an additional block without extending the data chunk.
|
||||
bytes[64..72].copy_from_slice(&128u64.to_le_bytes());
|
||||
let expected = read_raw(&bytes).unwrap();
|
||||
for c in &expected.channel_bytes {
|
||||
assert_eq!(&c[..8], &[0x33; 8]);
|
||||
assert_eq!(&c[8..], &[0x69; 8]);
|
||||
}
|
||||
let metadata_offset = bytes.len() as u64;
|
||||
bytes[20..28].copy_from_slice(&metadata_offset.to_le_bytes());
|
||||
bytes.extend_from_slice(b"ID3\x04\x00\x00\x00\x00\x00\x00");
|
||||
bytes.extend_from_slice(&[0xff; 32]);
|
||||
let file_size = bytes.len() as u64;
|
||||
bytes[12..20].copy_from_slice(&file_size.to_le_bytes());
|
||||
assert_eq!(read_raw(&bytes).unwrap().channel_bytes, expected.channel_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsdiff_odd_payload_receives_pad_byte() {
|
||||
let input = [&[0xaau8; 3][..]];
|
||||
let bytes = encode_dsdiff(2_822_400, &input, 24).unwrap();
|
||||
let raw = read_raw(&bytes).unwrap();
|
||||
assert_eq!(raw.channel_bytes[0].len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsf_declared_file_size_and_metadata_pointer_bounds() {
|
||||
let valid = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap();
|
||||
|
||||
// Undersized file size declaration (e.g. 28)
|
||||
let mut undersized = valid.clone();
|
||||
undersized[12..20].copy_from_slice(&28u64.to_le_bytes());
|
||||
assert!(read_metadata(&undersized).is_err());
|
||||
assert!(read_raw(&undersized).is_err());
|
||||
|
||||
// Oversized file size declaration beyond buffer
|
||||
let mut oversized = valid.clone();
|
||||
let big_size = valid.len() as u64 + 100;
|
||||
oversized[12..20].copy_from_slice(&big_size.to_le_bytes());
|
||||
assert!(read_metadata(&oversized).is_err());
|
||||
assert!(read_raw(&oversized).is_err());
|
||||
|
||||
// Metadata pointer outside the declared file bounds
|
||||
let mut outside_meta = valid.clone();
|
||||
let outside_offset = valid.len() as u64 + 10;
|
||||
outside_meta[20..28].copy_from_slice(&outside_offset.to_le_bytes());
|
||||
assert!(read_metadata(&outside_meta).is_err());
|
||||
assert!(read_raw(&outside_meta).is_err());
|
||||
|
||||
// Metadata pointer overlapping data chunk
|
||||
let mut overlap_meta = valid.clone();
|
||||
overlap_meta[20..28].copy_from_slice(&32u64.to_le_bytes());
|
||||
assert!(read_metadata(&overlap_meta).is_err());
|
||||
assert!(read_raw(&overlap_meta).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsdiff_channel_count_and_duplicate_chunks_are_validated() {
|
||||
let base = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap();
|
||||
|
||||
// Locate PROP chunk payload and CHNL subchunk
|
||||
let prop_idx = base.windows(4).position(|w| w == b"PROP").unwrap();
|
||||
let chnl_idx = base.windows(4).position(|w| w == b"CHNL").unwrap();
|
||||
|
||||
// 1. Oversized channel count (e.g. 65535 or 9)
|
||||
let mut bad_count = base.clone();
|
||||
bad_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&65535u16.to_be_bytes());
|
||||
assert!(matches!(read_metadata(&bad_count), Err(Error::Unsupported(_))));
|
||||
assert!(matches!(read_raw(&bad_count), Err(Error::Unsupported(_))));
|
||||
|
||||
let mut zero_count = base.clone();
|
||||
zero_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&0u16.to_be_bytes());
|
||||
assert!(matches!(read_metadata(&zero_count), Err(Error::Unsupported(_))));
|
||||
|
||||
// 2. Conflicting duplicate CHNL chunk in PROP
|
||||
let mut dup_chnl = base.clone();
|
||||
let chnl_chunk = dup_chnl[chnl_idx..chnl_idx + 18].to_vec();
|
||||
dup_chnl.splice(chnl_idx..chnl_idx, chnl_chunk);
|
||||
// Adjust PROP size and FRM8 size
|
||||
let prop_size = u64::from_be_bytes(dup_chnl[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 18;
|
||||
dup_chnl[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes());
|
||||
let frm8_size = (dup_chnl.len() - 12) as u64;
|
||||
dup_chnl[4..12].copy_from_slice(&frm8_size.to_be_bytes());
|
||||
assert_eq!(read_metadata(&dup_chnl), Err(Error::InvalidHeader("duplicate CHNL chunk")));
|
||||
|
||||
// 3. Duplicate FS chunk in PROP
|
||||
let fs_idx = base.windows(4).position(|w| w == b"FS ").unwrap();
|
||||
let mut dup_fs = base.clone();
|
||||
let fs_chunk = dup_fs[fs_idx..fs_idx + 16].to_vec();
|
||||
dup_fs.splice(fs_idx..fs_idx, fs_chunk);
|
||||
let prop_size = u64::from_be_bytes(dup_fs[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 16;
|
||||
dup_fs[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes());
|
||||
let frm8_size = (dup_fs.len() - 12) as u64;
|
||||
dup_fs[4..12].copy_from_slice(&frm8_size.to_be_bytes());
|
||||
assert_eq!(read_metadata(&dup_fs), Err(Error::InvalidHeader("duplicate FS chunk")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
fn dsdiff_32bit_padding_overflow_is_rejected() {
|
||||
let dummy = [&[][..]];
|
||||
let result = encode_dsdiff(2_822_400, &dummy, 34_359_738_360);
|
||||
assert_eq!(result, Err(Error::MemoryLimitExceeded));
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Channel labels, text metadata and padding in the DSF and DSDIFF readers and writers.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use craft_audio::dsd::{encode_dsdiff, encode_dsf, read_metadata, read_raw};
|
||||
|
||||
const RATE: u32 = 2_822_400;
|
||||
|
||||
fn planes(channels: usize, len: usize) -> Vec<Vec<u8>> {
|
||||
vec![vec![0x69; len]; channels]
|
||||
}
|
||||
|
||||
fn refs(p: &[Vec<u8>]) -> Vec<&[u8]> {
|
||||
p.iter().map(Vec::as_slice).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsdiff_names_surround_channels_by_layout() {
|
||||
for (n, names) in [
|
||||
(5, vec!["Mono/Left", "Right", "Center", "LeftSurround", "RightSurround"]),
|
||||
(6, vec!["Mono/Left", "Right", "Center", "LFE", "LeftSurround", "RightSurround"]),
|
||||
] {
|
||||
let p = planes(n, 4);
|
||||
let bytes = encode_dsdiff(RATE, &refs(&p), 32).unwrap();
|
||||
assert_eq!(read_metadata(&bytes).unwrap().channel_names, names, "{n} channels");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsdiff_odd_audio_is_padded_and_counted_in_the_file_size() {
|
||||
let p = planes(1, 1);
|
||||
let bytes = encode_dsdiff(RATE, &refs(&p), 8).unwrap();
|
||||
assert_eq!(bytes.len() % 2, 0);
|
||||
assert_eq!(u64::from_be_bytes(bytes[4..12].try_into().unwrap()) + 12, bytes.len() as u64);
|
||||
assert_eq!(*bytes.last().unwrap(), 0, "pad byte");
|
||||
assert_eq!(read_raw(&bytes).unwrap().channel_bytes, vec![vec![0x69]]);
|
||||
}
|
||||
|
||||
fn with_diin(mut bytes: Vec<u8>, sub: &[u8; 4], payload: &[u8]) -> Vec<u8> {
|
||||
let mut sub_chunk = Vec::new();
|
||||
sub_chunk.extend_from_slice(sub);
|
||||
sub_chunk.extend_from_slice(&(payload.len() as u64).to_be_bytes());
|
||||
sub_chunk.extend_from_slice(payload);
|
||||
if payload.len() % 2 == 1 {
|
||||
sub_chunk.push(0);
|
||||
}
|
||||
bytes.extend_from_slice(b"DIIN");
|
||||
bytes.extend_from_slice(&(sub_chunk.len() as u64).to_be_bytes());
|
||||
bytes.extend_from_slice(&sub_chunk);
|
||||
let size = (bytes.len() - 12) as u64;
|
||||
bytes[4..12].copy_from_slice(&size.to_be_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsdiff_title_and_artist_skip_the_character_count() {
|
||||
let p = planes(2, 4);
|
||||
let base = encode_dsdiff(RATE, &refs(&p), 32).unwrap();
|
||||
let mut payload = 4u32.to_be_bytes().to_vec();
|
||||
payload.extend_from_slice(b"Test");
|
||||
let bytes = with_diin(base.clone(), b"DITI", &payload);
|
||||
assert_eq!(read_metadata(&bytes).unwrap().title.as_deref(), Some("Test"));
|
||||
let bytes = with_diin(base.clone(), b"DIAR", &payload);
|
||||
assert_eq!(read_metadata(&bytes).unwrap().artist.as_deref(), Some("Test"));
|
||||
// A count longer than the chunk is not text.
|
||||
let mut bad = 99u32.to_be_bytes().to_vec();
|
||||
bad.extend_from_slice(b"Test");
|
||||
assert_eq!(read_metadata(&with_diin(base, b"DITI", &bad)).unwrap().title, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsf_channel_types_match_the_channel_count() {
|
||||
for (n, expect) in [(1, 1), (2, 2), (3, 3), (4, 4), (5, 6), (6, 7)] {
|
||||
let p = planes(n, 4);
|
||||
let bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap();
|
||||
assert_eq!(u32::from_le_bytes(bytes[48..52].try_into().unwrap()), expect, "{n} channels");
|
||||
assert_eq!(read_metadata(&bytes).unwrap().channel_names.len(), n);
|
||||
}
|
||||
let p = planes(7, 4);
|
||||
assert!(encode_dsf(RATE, &refs(&p), 32, 4096).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dsf_type_5_names_the_fourth_channel_lfe() {
|
||||
let p = planes(4, 4);
|
||||
let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap();
|
||||
bytes[48..52].copy_from_slice(&5u32.to_le_bytes());
|
||||
assert_eq!(read_metadata(&bytes).unwrap().channel_names, ["FrontLeft", "FrontRight", "Center", "LFE"]);
|
||||
}
|
||||
|
||||
fn id3(version: u8, frames: &[u8]) -> Vec<u8> {
|
||||
let n = frames.len();
|
||||
let mut tag = vec![b'I', b'D', b'3', version, 0, 0];
|
||||
tag.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]);
|
||||
tag.extend_from_slice(frames);
|
||||
tag
|
||||
}
|
||||
|
||||
fn frame(version: u8, id: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
let n = body.len();
|
||||
let mut f = id.to_vec();
|
||||
if version >= 4 {
|
||||
f.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]);
|
||||
} else {
|
||||
f.extend_from_slice(&(n as u32).to_be_bytes());
|
||||
}
|
||||
f.extend_from_slice(&[0, 0]);
|
||||
f.extend_from_slice(body);
|
||||
f
|
||||
}
|
||||
|
||||
fn dsf_with_tag(tag: &[u8]) -> Vec<u8> {
|
||||
let p = planes(2, 4);
|
||||
let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap();
|
||||
let offset = bytes.len() as u64;
|
||||
bytes[20..28].copy_from_slice(&offset.to_le_bytes());
|
||||
bytes.extend_from_slice(tag);
|
||||
let file_size = bytes.len() as u64;
|
||||
bytes[12..20].copy_from_slice(&file_size.to_le_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id3v24_frame_sizes_are_synchsafe() {
|
||||
// A 128-byte frame has the synchsafe size 00 00 01 00; read as plain big-endian it is 256.
|
||||
let mut frames = frame(4, b"APIC", &[0u8; 128]);
|
||||
let mut title = vec![3];
|
||||
title.extend_from_slice(b"After art");
|
||||
frames.extend(frame(4, b"TIT2", &title));
|
||||
let m = read_metadata(&dsf_with_tag(&id3(4, &frames))).unwrap();
|
||||
assert_eq!(m.title.as_deref(), Some("After art"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id3v23_frame_sizes_stay_big_endian() {
|
||||
let mut frames = frame(3, b"APIC", &[0u8; 128]);
|
||||
let mut title = vec![3];
|
||||
title.extend_from_slice(b"Three");
|
||||
frames.extend(frame(3, b"TIT2", &title));
|
||||
let m = read_metadata(&dsf_with_tag(&id3(3, &frames))).unwrap();
|
||||
assert_eq!(m.title.as_deref(), Some("Three"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id3_text_encodings() {
|
||||
let cases: [(&[u8], &str); 5] = [
|
||||
(b"\x00Caf\xe9", "Café"),
|
||||
(b"\x03Caf\xc3\xa9", "Café"),
|
||||
(b"\x02\x00A\x00B", "AB"),
|
||||
(b"\x01\xFF\xFEA\x00B\x00", "AB"),
|
||||
(b"\x01\xFE\xFF\x00A\x00B", "AB"),
|
||||
];
|
||||
for (body, expect) in cases {
|
||||
let m = read_metadata(&dsf_with_tag(&id3(4, &frame(4, b"TIT2", body)))).unwrap();
|
||||
assert_eq!(m.title.as_deref(), Some(expect), "{body:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
//! DSD (DSF and DSDIFF) decoding and decimation tests, including oracle tests against FFmpeg
|
||||
//! (skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`).
|
||||
|
||||
use craft_audio::dsd::{BitOrder, Format, decode, decode_with_factor, encode_dsdiff, encode_dsf, filter::SILENCE_LSBF, read_metadata, read_raw};
|
||||
use std::process::Command;
|
||||
|
||||
/// Generates a test DSD 1-bit stream with various features (silence, alternating tones, noise).
|
||||
fn make_test_stream(num_bytes: usize, seed: u8) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(num_bytes);
|
||||
let mut s = seed as u32;
|
||||
for i in 0..num_bytes {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
let byte = match (i / 128) % 4 {
|
||||
0 => SILENCE_LSBF, // DSD silence
|
||||
1 => 0x55, // Alternate silence pattern
|
||||
2 => (s & 0xFF) as u8,
|
||||
_ => {
|
||||
if (i / 16) % 2 == 0 {
|
||||
0xFF // full positive level
|
||||
} else {
|
||||
0x00 // full negative level
|
||||
}
|
||||
}
|
||||
};
|
||||
out.push(byte);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_dsf() {
|
||||
let sample_rate = 2_822_400;
|
||||
let block_size = 4096;
|
||||
let ch0 = make_test_stream(8192, 42);
|
||||
let ch1 = make_test_stream(8192, 99);
|
||||
let sample_count = 8192 * 8;
|
||||
|
||||
let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf");
|
||||
|
||||
let meta = read_metadata(&dsf_bytes).expect("read_metadata");
|
||||
assert_eq!(meta.format, Format::Dsf);
|
||||
assert_eq!(meta.sample_rate, sample_rate);
|
||||
assert_eq!(meta.channels, 2);
|
||||
assert_eq!(meta.sample_count, sample_count);
|
||||
|
||||
let raw = read_raw(&dsf_bytes).expect("read_raw");
|
||||
assert_eq!(raw.bit_order, BitOrder::LsbFirst);
|
||||
assert_eq!(raw.channel_bytes.len(), 2);
|
||||
assert_eq!(raw.channel_bytes[0], ch0);
|
||||
assert_eq!(raw.channel_bytes[1], ch1);
|
||||
|
||||
let decoded = decode(&dsf_bytes).expect("decode");
|
||||
assert_eq!(decoded.sample_rate, sample_rate / 8);
|
||||
assert_eq!(decoded.channels.len(), 2);
|
||||
assert_eq!(decoded.channels[0].len(), 8192);
|
||||
assert_eq!(decoded.channels[1].len(), 8192);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_dsdiff() {
|
||||
let sample_rate = 2_822_400;
|
||||
let ch0 = make_test_stream(4096, 17);
|
||||
let ch1 = make_test_stream(4096, 73);
|
||||
let sample_count = 4096 * 8;
|
||||
|
||||
let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff");
|
||||
|
||||
let meta = read_metadata(&dff_bytes).expect("read_metadata");
|
||||
assert_eq!(meta.format, Format::Dsdiff);
|
||||
assert_eq!(meta.sample_rate, sample_rate);
|
||||
assert_eq!(meta.channels, 2);
|
||||
assert_eq!(meta.sample_count, sample_count);
|
||||
|
||||
let raw = read_raw(&dff_bytes).expect("read_raw");
|
||||
assert_eq!(raw.bit_order, BitOrder::MsbFirst);
|
||||
assert_eq!(raw.channel_bytes.len(), 2);
|
||||
assert_eq!(raw.channel_bytes[0], ch0);
|
||||
assert_eq!(raw.channel_bytes[1], ch1);
|
||||
|
||||
let decoded = decode(&dff_bytes).expect("decode");
|
||||
assert_eq!(decoded.sample_rate, sample_rate / 8);
|
||||
assert_eq!(decoded.channels.len(), 2);
|
||||
assert_eq!(decoded.channels[0].len(), 4096);
|
||||
assert_eq!(decoded.channels[1].len(), 4096);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimation_factors() {
|
||||
let sample_rate = 2_822_400;
|
||||
let ch0 = make_test_stream(2048, 123);
|
||||
let dsf_bytes = encode_dsf(sample_rate, &[&ch0], 2048 * 8, 4096).expect("encode_dsf");
|
||||
|
||||
// Factor 8 -> 352,800 Hz
|
||||
let dec8 = decode_with_factor(&dsf_bytes, 8).expect("factor 8");
|
||||
assert_eq!(dec8.sample_rate, 352_800);
|
||||
assert_eq!(dec8.channels[0].len(), 2048);
|
||||
|
||||
// Factor 16 -> 176,400 Hz
|
||||
let dec16 = decode_with_factor(&dsf_bytes, 16).expect("factor 16");
|
||||
assert_eq!(dec16.sample_rate, 176_400);
|
||||
assert_eq!(dec16.channels[0].len(), 1024);
|
||||
|
||||
// Factor 32 -> 88,200 Hz
|
||||
let dec32 = decode_with_factor(&dsf_bytes, 32).expect("factor 32");
|
||||
assert_eq!(dec32.sample_rate, 88_200);
|
||||
assert_eq!(dec32.channels[0].len(), 512);
|
||||
|
||||
// Factor 64 -> 44,100 Hz
|
||||
let dec64 = decode_with_factor(&dsf_bytes, 64).expect("factor 64");
|
||||
assert_eq!(dec64.sample_rate, 44_100);
|
||||
assert_eq!(dec64.channels[0].len(), 256);
|
||||
|
||||
// Invalid factor
|
||||
assert!(decode_with_factor(&dsf_bytes, 12).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence_and_dc_levels() {
|
||||
let sample_rate = 2_822_400;
|
||||
// Pure silence
|
||||
let silence = vec![SILENCE_LSBF; 1024];
|
||||
let dsf_bytes = encode_dsf(sample_rate, &[&silence], 1024 * 8, 4096).expect("encode");
|
||||
let dec = decode(&dsf_bytes).expect("decode");
|
||||
for &sample in &dec.channels[0][12..] {
|
||||
assert!(sample.abs() < 1e-4, "silence sample should be ~0.0, got {sample}");
|
||||
}
|
||||
|
||||
// Full positive level
|
||||
let ones = vec![0xFF; 1024];
|
||||
let dsf_ones = encode_dsf(sample_rate, &[&ones], 1024 * 8, 4096).expect("encode");
|
||||
let dec_ones = decode(&dsf_ones).expect("decode");
|
||||
for &sample in &dec_ones.channels[0][12..] {
|
||||
assert!((sample - 1.0).abs() < 1e-4, "ones sample should be ~1.0, got {sample}");
|
||||
}
|
||||
|
||||
// Full negative level
|
||||
let zeros = vec![0x00; 1024];
|
||||
let dsf_zeros = encode_dsf(sample_rate, &[&zeros], 1024 * 8, 4096).expect("encode");
|
||||
let dec_zeros = decode(&dsf_zeros).expect("decode");
|
||||
for &sample in &dec_zeros.channels[0][12..] {
|
||||
assert!((sample - (-1.0)).abs() < 1e-4, "zeros sample should be ~-1.0, got {sample}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multichannel_dsf_and_dsdiff() {
|
||||
let sample_rate = 2_822_400;
|
||||
// Test 6-channel (5.1 surround)
|
||||
let channels: Vec<Vec<u8>> = (0..6).map(|c| make_test_stream(1024, (c * 23 + 5) as u8)).collect();
|
||||
let ch_refs: Vec<&[u8]> = channels.iter().map(Vec::as_slice).collect();
|
||||
|
||||
let dsf = encode_dsf(sample_rate, &ch_refs, 1024 * 8, 512).expect("encode 5.1 dsf");
|
||||
let dsf_meta = read_metadata(&dsf).expect("meta 5.1 dsf");
|
||||
assert_eq!(dsf_meta.channels, 6);
|
||||
let dsf_dec = decode(&dsf).expect("decode 5.1 dsf");
|
||||
assert_eq!(dsf_dec.channels.len(), 6);
|
||||
assert_eq!(dsf_dec.channels[0].len(), 1024);
|
||||
|
||||
let dff = encode_dsdiff(sample_rate, &ch_refs, 1024 * 8).expect("encode 5.1 dsdiff");
|
||||
let dff_meta = read_metadata(&dff).expect("meta 5.1 dsdiff");
|
||||
assert_eq!(dff_meta.channels, 6);
|
||||
let dff_dec = decode(&dff).expect("decode 5.1 dsdiff");
|
||||
assert_eq!(dff_dec.channels.len(), 6);
|
||||
assert_eq!(dff_dec.channels[0].len(), 1024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dst_compression_rejected() {
|
||||
// Construct a minimal DSDIFF with CMPR = 'DST '
|
||||
let mut dff = encode_dsdiff(2_822_400, &[&[0xAA; 64]], 512).expect("encode");
|
||||
// Find 'DSD ' in CMPR chunk and replace with 'DST '
|
||||
let mut replaced = false;
|
||||
for i in 0..dff.len().saturating_sub(8) {
|
||||
if &dff[i..i + 4] == b"CMPR" && &dff[i + 12..i + 16] == b"DSD " {
|
||||
dff[i + 12..i + 16].copy_from_slice(b"DST ");
|
||||
replaced = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(replaced, "should find CMPR DSD chunk");
|
||||
assert!(read_metadata(&dff).is_err(), "DST compression should be rejected as unsupported");
|
||||
assert!(decode(&dff).is_err(), "DST compression should be rejected as unsupported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id3v2_tag_in_dsf() {
|
||||
let sample_rate = 2_822_400;
|
||||
let mut dsf = encode_dsf(sample_rate, &[&[0x69; 128]], 1024, 512).expect("encode");
|
||||
let metadata_offset = dsf.len() as u64;
|
||||
|
||||
// Append simple ID3v2.3 tag with TIT2="Test Title" and TPE1="Test Artist"
|
||||
let mut id3 = Vec::new();
|
||||
id3.extend_from_slice(b"ID3");
|
||||
id3.push(3); // v2.3
|
||||
id3.push(0); // revision
|
||||
id3.push(0); // flags
|
||||
|
||||
let mut frames = Vec::new();
|
||||
// TIT2 frame
|
||||
frames.extend_from_slice(b"TIT2");
|
||||
let title_bytes = b"\x03DSD Master"; // UTF-8
|
||||
frames.extend_from_slice(&(title_bytes.len() as u32).to_be_bytes());
|
||||
frames.extend_from_slice(&[0, 0]); // flags
|
||||
frames.extend_from_slice(title_bytes);
|
||||
|
||||
// TPE1 frame
|
||||
frames.extend_from_slice(b"TPE1");
|
||||
let artist_bytes = b"\x03The Audiophiles";
|
||||
frames.extend_from_slice(&(artist_bytes.len() as u32).to_be_bytes());
|
||||
frames.extend_from_slice(&[0, 0]); // flags
|
||||
frames.extend_from_slice(artist_bytes);
|
||||
|
||||
// synchsafe size
|
||||
let tag_len = frames.len();
|
||||
id3.push(((tag_len >> 21) & 0x7F) as u8);
|
||||
id3.push(((tag_len >> 14) & 0x7F) as u8);
|
||||
id3.push(((tag_len >> 7) & 0x7F) as u8);
|
||||
id3.push((tag_len & 0x7F) as u8);
|
||||
id3.extend_from_slice(&frames);
|
||||
|
||||
dsf.extend_from_slice(&id3);
|
||||
// Update file size and metadata_offset of 'DSD ' chunk
|
||||
let file_size = dsf.len() as u64;
|
||||
dsf[12..20].copy_from_slice(&file_size.to_le_bytes());
|
||||
dsf[20..28].copy_from_slice(&metadata_offset.to_le_bytes());
|
||||
|
||||
let meta = read_metadata(&dsf).expect("read metadata with ID3");
|
||||
assert_eq!(meta.title.as_deref(), Some("DSD Master"));
|
||||
assert_eq!(meta.artist.as_deref(), Some("The Audiophiles"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_audio_bit_order_conversion() {
|
||||
let ch0 = vec![0b00000001, 0b10000000];
|
||||
let dsf = encode_dsf(2_822_400, &[&ch0], 16, 512).expect("encode");
|
||||
let mut raw = read_raw(&dsf).expect("read raw");
|
||||
assert_eq!(raw.bit_order, BitOrder::LsbFirst);
|
||||
assert_eq!(raw.channel_bytes[0], ch0);
|
||||
|
||||
raw.convert_bit_order(BitOrder::MsbFirst);
|
||||
assert_eq!(raw.bit_order, BitOrder::MsbFirst);
|
||||
assert_eq!(raw.channel_bytes[0], vec![0b10000000, 0b00000001]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_inputs() {
|
||||
// Truncated headers
|
||||
assert!(read_metadata(b"").is_err());
|
||||
assert!(read_metadata(b"DSD ").is_err());
|
||||
assert!(read_metadata(b"FRM8").is_err());
|
||||
|
||||
// Bad magic
|
||||
assert!(read_metadata(b"RIFF\x00\x00\x00\x00WAVE").is_err());
|
||||
|
||||
// Truncated DSF chunk
|
||||
let mut bad_dsf = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode");
|
||||
bad_dsf.truncate(50);
|
||||
assert!(decode(&bad_dsf).is_err());
|
||||
|
||||
// Corrupted fmt chunk size
|
||||
let mut bad_fmt = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode");
|
||||
bad_fmt[32] = 0; // bits_per_sample = 0
|
||||
assert!(decode(&bad_fmt).is_err());
|
||||
|
||||
// Absurd channels
|
||||
let mut bad_ch = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode");
|
||||
bad_ch[28 + 24] = 99; // channel_count = 99
|
||||
assert!(decode(&bad_ch).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_dsf_oracle() {
|
||||
let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return };
|
||||
let dir = craft_media_testkit::fixture_subdir("dsd");
|
||||
|
||||
let sample_rate = 2_822_400;
|
||||
let block_size = 4096;
|
||||
let ch0 = make_test_stream(16384, 11);
|
||||
let ch1 = make_test_stream(16384, 88);
|
||||
let sample_count = 16384 * 8;
|
||||
|
||||
let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf");
|
||||
let dsf_path = dir.join("test_oracle.dsf");
|
||||
std::fs::write(&dsf_path, &dsf_bytes).expect("write fixture");
|
||||
|
||||
let raw_out_path = dir.join("ffmpeg_dsf.raw");
|
||||
let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dsf_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg");
|
||||
assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr));
|
||||
|
||||
let raw_bytes = std::fs::read(&raw_out_path).expect("read raw");
|
||||
let ffmpeg_floats: Vec<f32> = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
|
||||
|
||||
let decoded = decode(&dsf_bytes).expect("our decode");
|
||||
assert_eq!(decoded.channels.len(), 2);
|
||||
assert_eq!(decoded.channels[0].len(), 16384);
|
||||
assert_eq!(decoded.channels[1].len(), 16384);
|
||||
|
||||
// FFmpeg interleaves L0, R0, L1, R1...
|
||||
// Compare samples after filter startup (sample 12 onwards).
|
||||
for i in 12..16000 {
|
||||
let ff_l = ffmpeg_floats[i * 2];
|
||||
let ff_r = ffmpeg_floats[i * 2 + 1];
|
||||
let our_l = decoded.channels[0][i];
|
||||
let our_r = decoded.channels[1][i];
|
||||
|
||||
assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}");
|
||||
assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_dsdiff_oracle() {
|
||||
let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return };
|
||||
let dir = craft_media_testkit::fixture_subdir("dsd");
|
||||
|
||||
let sample_rate = 2_822_400;
|
||||
let ch0 = make_test_stream(8192, 33);
|
||||
let ch1 = make_test_stream(8192, 77);
|
||||
let sample_count = 8192 * 8;
|
||||
|
||||
let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff");
|
||||
let dff_path = dir.join("test_oracle.dff");
|
||||
std::fs::write(&dff_path, &dff_bytes).expect("write fixture");
|
||||
|
||||
let raw_out_path = dir.join("ffmpeg_dff.raw");
|
||||
let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dff_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg");
|
||||
assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr));
|
||||
|
||||
let raw_bytes = std::fs::read(&raw_out_path).expect("read raw");
|
||||
let ffmpeg_floats: Vec<f32> = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
|
||||
|
||||
let decoded = decode(&dff_bytes).expect("our decode");
|
||||
assert_eq!(decoded.channels.len(), 2);
|
||||
assert_eq!(decoded.channels[0].len(), 8192);
|
||||
|
||||
for i in 12..8000 {
|
||||
let ff_l = ffmpeg_floats[i * 2];
|
||||
let ff_r = ffmpeg_floats[i * 2 + 1];
|
||||
let our_l = decoded.channels[0][i];
|
||||
let our_r = decoded.channels[1][i];
|
||||
|
||||
assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}");
|
||||
assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,15 @@ mod audio;
|
||||
#[cfg(all(feature = "decode", feature = "encode"))]
|
||||
#[path = "codecs/main.rs"]
|
||||
mod codecs;
|
||||
#[cfg(feature = "dsd")]
|
||||
#[path = "dsd_bounds.rs"]
|
||||
mod dsd_bounds;
|
||||
#[cfg(feature = "dsd")]
|
||||
#[path = "dsd_metadata.rs"]
|
||||
mod dsd_metadata;
|
||||
#[cfg(feature = "dsd")]
|
||||
#[path = "dsd_oracle.rs"]
|
||||
mod dsd_oracle;
|
||||
#[cfg(all(feature = "flac-decode", feature = "flac-encode"))]
|
||||
#[path = "flac_decode.rs"]
|
||||
mod flac_decode;
|
||||
|
||||
@@ -25,12 +25,15 @@ ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"]
|
||||
# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`.
|
||||
screen-testing = ["ui", "agents", "craft-ui/testing"]
|
||||
# Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an
|
||||
# app's `<id>-cli mcp` reads, and with `ui` the link host and the Agents page. The agent settings
|
||||
# build on every target without it.
|
||||
agents = ["dep:craft-ai-agents", "dep:craft-flags", "dep:craft-atomic", "dep:craft-host"]
|
||||
# app's `<id>-cli mcp` reads and that CLI's live client (all `craft-control`'s, re-exported), and
|
||||
# with `ui` the link host and the Agents page. The agent settings build on every target without it.
|
||||
agents = ["craft-control/agents", "dep:craft-host"]
|
||||
|
||||
[dependencies]
|
||||
craft-behavior = { workspace = true, optional = true }
|
||||
# The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the
|
||||
# CLI's live client), re-exported by `agents` so every app shares one copy.
|
||||
craft-control = { workspace = true }
|
||||
craft-keymap = { workspace = true, optional = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-ui = { workspace = true, optional = true }
|
||||
@@ -42,9 +45,6 @@ serde_json = { workspace = true }
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
base64 = "0.22"
|
||||
craft-platform = { workspace = true }
|
||||
craft-ai-agents = { workspace = true, optional = true }
|
||||
craft-atomic = { workspace = true, optional = true }
|
||||
craft-flags = { workspace = true, optional = true }
|
||||
craft-host = { workspace = true, optional = true }
|
||||
getrandom = "0.3"
|
||||
hmac = "0.12"
|
||||
|
||||
@@ -8,7 +8,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch
|
||||
| --- | --- |
|
||||
| `actions` | Recorded actions (every target): `ActionList` of `Action`s and `ActionStep`s, `ActionsFile`, playback with `ActionPlayer` and `ActionRunner` under a `PlaybackBudget`, and `Recording`. The app keeps the command table. |
|
||||
| `ui::actions` | `ActionsPanel` (every target): sets, actions and steps as a tree, include and dialog cells, rename (`start_rename`), drag to move, Button Mode, the footer and the menus (`ActionsPanelCommands`, `ActionsMenuFacts` and `panel_rows`, which leaves out the rows the host has no command for). It runs nothing; it reports `ActionsEvent`s. `ActionsPanelState` holds its view state. `ActionsWords` holds its words. |
|
||||
| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `<id>-cli mcp` finds the open window by. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. |
|
||||
| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `<id>-cli mcp` finds the open window by; the CLI's live client (`Live`, `LiveConfig`, `Route`). All of these are `craft_control::agents`, re-exported, so apps without the shared UI library use the same code. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. |
|
||||
| `ui::agents` | `AgentsPage` (desktop, features `agents` and `ui`): the Agents page of Preferences, a custom page over the agent settings in the Preferences draft, with the link's status; the folder rows are `PathSetting`s. `AgentsWords` holds its words. |
|
||||
| `args` | `ControlOptions`: the `--control <PORT>`, `--control-token`, `--control-token-file` values and their `<APP>_CONTROL_*` environment fallbacks, checked the way the apps' command lines report them (usage errors exit 2). |
|
||||
| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. |
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
//! The connection file: where an app's control server listens for agents.
|
||||
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::AutomationError;
|
||||
|
||||
/// The connection file in the app's settings folder, present while the app accepts agents.
|
||||
pub const CONNECTION_FILE: &str = "agent-connection.json";
|
||||
/// The token file the app keeps in its settings folder for agent connections.
|
||||
pub const TOKEN_FILE: &str = "agent-control.token";
|
||||
/// How long [`probe`] waits for a connection to be accepted.
|
||||
pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
/// The version of the [`Connection`] file format.
|
||||
const CONNECTION_VERSION: u32 = 1;
|
||||
/// The largest connection file read; anything bigger is not one.
|
||||
const MAX_CONNECTION_BYTES: u64 = 1 << 20;
|
||||
|
||||
/// What an app publishes in [`CONNECTION_FILE`]: `{"version", "pid", "port", "tokenFile", "app"}`.
|
||||
/// Holds no secret: the token stays in its own owner-only file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Connection {
|
||||
/// The file format's version (1).
|
||||
pub version: u32,
|
||||
/// The app's process id: only that process removes the file.
|
||||
pub pid: u32,
|
||||
/// The loopback port of the control server.
|
||||
pub port: u16,
|
||||
/// The file holding the token.
|
||||
pub token_file: PathBuf,
|
||||
/// The app's version, for diagnostics.
|
||||
pub app: String,
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// This process's connection on `port`, naming `app` (the app's version string).
|
||||
pub fn new(port: u16, token_file: PathBuf, app: impl Into<String>) -> Self {
|
||||
Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() }
|
||||
}
|
||||
|
||||
/// `127.0.0.1:<port>`.
|
||||
pub fn addr(&self) -> String {
|
||||
format!("127.0.0.1:{}", self.port)
|
||||
}
|
||||
}
|
||||
|
||||
fn io_error(path: &Path, e: impl std::fmt::Display) -> AutomationError {
|
||||
AutomationError::Io(format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Publishes `c` in `dir` (made if missing), written atomically so a reader never sees half a
|
||||
/// file.
|
||||
pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationError> {
|
||||
std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?;
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let text = serde_json::to_string_pretty(c).map_err(|e| io_error(&path, e))?;
|
||||
craft_atomic::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e))
|
||||
}
|
||||
|
||||
/// The connection published in `dir`, if any. A file of another version, with port 0, or one
|
||||
/// that does not parse (invalid UTF-8 included) counts as none: the app rewrites it when it next
|
||||
/// starts listening. Anything but a regular file (a FIFO would block the read) or a file over
|
||||
/// 1 MiB is an error, and left alone.
|
||||
pub fn read_connection(dir: &Path) -> Result<Option<Connection>, AutomationError> {
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let meta = match std::fs::metadata(&path) {
|
||||
Ok(m) => m,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(io_error(&path, e)),
|
||||
};
|
||||
if !meta.is_file() {
|
||||
return Err(io_error(&path, "not a regular file"));
|
||||
}
|
||||
if meta.len() > MAX_CONNECTION_BYTES {
|
||||
return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes")));
|
||||
}
|
||||
let bytes = match std::fs::read(&path) {
|
||||
Ok(b) => b,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(io_error(&path, e)),
|
||||
};
|
||||
Ok(serde_json::from_slice::<Connection>(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0))
|
||||
}
|
||||
|
||||
/// Removes the connection file in `dir` if process `pid` wrote it (another instance may have
|
||||
/// published its own since). Errors are ignored: a stale file only fails [`probe`].
|
||||
pub fn remove_connection(dir: &Path, pid: u32) {
|
||||
if let Ok(Some(c)) = read_connection(dir)
|
||||
&& c.pid == pid
|
||||
{
|
||||
let _ = std::fs::remove_file(dir.join(CONNECTION_FILE));
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the connection file in `dir` when nothing listens on its port any more (an app that
|
||||
/// crashed or quit without removing it), or when it does not read as a connection. A live
|
||||
/// instance's file is kept, and so is anything but a regular file. Errors are ignored.
|
||||
pub fn remove_stale_connection(dir: &Path) {
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let stale = match read_connection(dir) {
|
||||
Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT),
|
||||
Ok(None) => path.is_file(),
|
||||
Err(_) => false,
|
||||
};
|
||||
if stale {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether something accepts connections on loopback `port` within `timeout`; port 0 never does.
|
||||
pub fn probe(port: u16, timeout: Duration) -> bool {
|
||||
port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok()
|
||||
}
|
||||
@@ -9,8 +9,8 @@
|
||||
//! While agents may connect, the app serves its control channel on loopback ([`AgentLink`], over
|
||||
//! [`crate::server`]) and publishes where in its settings folder ([`CONNECTION_FILE`]): the port,
|
||||
//! its process id and the token file ([`TOKEN_FILE`], created `0600` on Unix). The app's
|
||||
//! `<id>-cli mcp` reads that file on every tool call, then the token from the file it names, so an
|
||||
//! MCP client's configuration never holds a port or a token.
|
||||
//! `<id>-cli mcp` reads that file on every tool call ([`Live`]), then the token from the file it
|
||||
//! names, so an MCP client's configuration never holds a port or a token.
|
||||
//!
|
||||
//! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then
|
||||
//! listens on its port ([`probe`]), and the app's next launch removes it
|
||||
@@ -18,29 +18,32 @@
|
||||
//! checks that [`Connection::pid`] is still running before it sends anything derived from the
|
||||
//! token, and authenticates with the challenge handshake ([`crate::security::ServerHandshake`]).
|
||||
//!
|
||||
//! Everything but the link host is `craft_control::agents`, re-exported here: apps that don't use
|
||||
//! the shared UI library use it from there, with the same files and formats.
|
||||
//!
|
||||
//! | Part | Names | Builds |
|
||||
//! |---|---|---|
|
||||
//! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target |
|
||||
//! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` |
|
||||
//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` |
|
||||
//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` |
|
||||
//! | The link host | [`AgentLink`], [`AgentLinkStatus`], [`LinkProblem`], [`LinkUpdate`] | desktop, features `agents` and `ui` |
|
||||
//!
|
||||
//! The Agents page of Preferences is [`crate::ui::agents`].
|
||||
|
||||
mod settings;
|
||||
pub use settings::{AgentSettings, WhenAppClosed, agents_allowed, folder};
|
||||
// The links above name items of the `agents` and `ui` features; without them they have nothing to
|
||||
// point at, and the docs of the settings alone still build.
|
||||
#![cfg_attr(not(all(feature = "agents", feature = "ui", not(target_arch = "wasm32"))), allow(rustdoc::broken_intra_doc_links))]
|
||||
|
||||
pub use craft_control::agents::{AgentSettings, WhenAppClosed, agents_allowed, folder};
|
||||
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
mod connection;
|
||||
#[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))]
|
||||
mod link;
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
mod switch;
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
pub use connection::{
|
||||
CONNECTION_FILE, Connection, PROBE_TIMEOUT, TOKEN_FILE, probe, read_connection, remove_connection, remove_stale_connection, write_connection,
|
||||
pub use craft_control::agents::{
|
||||
AgentSwitch, CONNECTION_FILE, ConnectFn, Connection, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn,
|
||||
Live, LiveConfig, POLL, PROBE_TIMEOUT, Route, TOKEN_FILE, Window, find_window, launcher, launcher_allows, mcp_flag, probe, read_connection,
|
||||
remove_connection, remove_stale_connection, write_connection,
|
||||
};
|
||||
#[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub use link::{AgentLink, AgentLinkStatus, LinkProblem, LinkUpdate, RETRY};
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
pub use switch::{AgentSwitch, POLL, launcher_allows, mcp_flag};
|
||||
@@ -1,124 +0,0 @@
|
||||
//! The agent settings an app saves in its preferences, and who decides that agents may connect.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The agent settings of an app's Preferences (its `integrations` section in PhotoCraft). Saved in
|
||||
/// camelCase: `allowAgentControl`, `controlPort`, `readRoot`, `writeRoot`, `whenAppClosed`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct AgentSettings {
|
||||
/// Off refuses every control server, `--control` included.
|
||||
pub allow_agent_control: bool,
|
||||
/// The loopback port agents connect to; 0 is any free port, published in the connection file.
|
||||
pub control_port: u32,
|
||||
/// The folder agents may open from; empty is none. Applied at once while agents are connected.
|
||||
pub read_root: String,
|
||||
/// The folder agents may save to; empty is none. Applied at once while agents are connected.
|
||||
pub write_root: String,
|
||||
/// What the app's `<id>-cli mcp` does while agents may use the app but it is closed.
|
||||
pub when_app_closed: WhenAppClosed,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
allow_agent_control: true,
|
||||
control_port: 0,
|
||||
read_root: String::new(),
|
||||
write_root: String::new(),
|
||||
when_app_closed: WhenAppClosed::Launch,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentSettings {
|
||||
/// [`Self::read_root`] as a path ([`folder`]).
|
||||
pub fn read_folder(&self) -> Option<PathBuf> {
|
||||
folder(&self.read_root)
|
||||
}
|
||||
|
||||
/// [`Self::write_root`] as a path ([`folder`]).
|
||||
pub fn write_folder(&self) -> Option<PathBuf> {
|
||||
folder(&self.write_root)
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder setting as a path, trimmed; empty or blank is `None`.
|
||||
pub fn folder(pref: &str) -> Option<PathBuf> {
|
||||
let pref = pref.trim();
|
||||
(!pref.is_empty()).then(|| PathBuf::from(pref))
|
||||
}
|
||||
|
||||
/// What an app's `<id>-cli mcp` does when an agent calls a tool while the app is closed.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum WhenAppClosed {
|
||||
/// Open the app and wait for it.
|
||||
#[default]
|
||||
Launch,
|
||||
/// Run the tool without a window.
|
||||
Headless,
|
||||
/// Answer with an error that asks to open the app.
|
||||
Error,
|
||||
}
|
||||
|
||||
impl WhenAppClosed {
|
||||
/// The saved names, in [`Self::ALL`] order.
|
||||
pub const NAMES: &'static [&'static str] = &["launch", "headless", "error"];
|
||||
/// Every choice, in the order a menu lists them.
|
||||
pub const ALL: [Self; 3] = [Self::Launch, Self::Headless, Self::Error];
|
||||
|
||||
/// The saved name.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Launch => "launch",
|
||||
Self::Headless => "headless",
|
||||
Self::Error => "error",
|
||||
}
|
||||
}
|
||||
|
||||
/// The choice a saved name means; `None` for any other text.
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|c| c.name() == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether agents may use the open window. With the suite's `AI-MCP` flag only the launcher's
|
||||
/// switch decides: one switch for every Craft app, none in the app. Without the flag the app's own
|
||||
/// earlier consent decides (`legacy`; PhotoCraft's is a Control Port saved before the switch).
|
||||
/// Allow Agent Control off still refuses agents either way ([`AgentSettings::allow_agent_control`]).
|
||||
pub fn agents_allowed(mcp_flag: bool, launcher: bool, legacy: bool) -> bool {
|
||||
if mcp_flag { launcher } else { legacy }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
// The saved names read back as the same choice, and nothing else reads as one.
|
||||
#[trial]
|
||||
fn when_app_closed_names_round_trip() {
|
||||
for choice in WhenAppClosed::ALL {
|
||||
assert_eq!(WhenAppClosed::parse(choice.name()), Some(choice));
|
||||
assert_eq!(serde_json::to_value(choice).unwrap(), serde_json::json!(choice.name()));
|
||||
}
|
||||
assert_eq!(WhenAppClosed::NAMES, WhenAppClosed::ALL.map(WhenAppClosed::name));
|
||||
assert_eq!(WhenAppClosed::parse("Launch"), None);
|
||||
let settings: AgentSettings = serde_json::from_str(r#"{"whenAppClosed": "headless", "controlPort": 7878}"#).unwrap();
|
||||
assert_eq!((settings.when_app_closed, settings.control_port, settings.allow_agent_control), (WhenAppClosed::Headless, 7878, true));
|
||||
}
|
||||
|
||||
// A folder setting is trimmed; empty or blank means no folder.
|
||||
#[trial]
|
||||
fn folder_preferences_are_trimmed() {
|
||||
assert_eq!(folder(""), None);
|
||||
assert_eq!(folder(" "), None);
|
||||
assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project")));
|
||||
let settings = AgentSettings { read_root: " /in ".into(), ..AgentSettings::default() };
|
||||
assert_eq!((settings.read_folder(), settings.write_folder()), (Some(PathBuf::from("/in")), None));
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
//! The ArtCraft Launcher's switch for one app, behind the suite's `AI-MCP` flag.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_host::Wake;
|
||||
|
||||
use super::agents_allowed;
|
||||
|
||||
/// How often [`AgentSwitch::watch`] reads the launcher's app list.
|
||||
pub const POLL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// The suite's `AI-MCP` flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). Reads the flags file;
|
||||
/// what could not be read is logged.
|
||||
pub fn mcp_flag() -> bool {
|
||||
let flags = craft_flags::load();
|
||||
for problem in &flags.problems {
|
||||
log::warn!("flags: {problem}");
|
||||
}
|
||||
flags.enabled(&craft_flags::AI_MCP)
|
||||
}
|
||||
|
||||
/// The launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets agents use
|
||||
/// the app `app_id`: the `AI-MCP` flag is on and the launcher's app list names the app. Reads two
|
||||
/// small files; ask from a timer or a command, not every frame ([`AgentSwitch`] does that).
|
||||
pub fn launcher_allows(app_id: &str) -> bool {
|
||||
mcp_flag() && craft_ai_agents::allowed(app_id)
|
||||
}
|
||||
|
||||
/// The launcher's switch for one app, watched on a thread so a frame can ask without touching the
|
||||
/// disk. The `AI-MCP` flag is read once, at [`Self::watch`]; the launcher's list every [`POLL`].
|
||||
/// Clones share one watch; the thread ends after the last clone is dropped.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AgentSwitch {
|
||||
mcp_flag: bool,
|
||||
on: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AgentSwitch {
|
||||
/// Watches the launcher's list for `app_id`; a change logs `agents on/off` and calls `wake`.
|
||||
/// Without the `AI-MCP` flag nothing is watched: the launcher's list means nothing then.
|
||||
pub fn watch(app_id: &'static str, wake: Wake) -> Self {
|
||||
let flag = mcp_flag();
|
||||
if !flag {
|
||||
return Self::fixed(false, false);
|
||||
}
|
||||
Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake)
|
||||
}
|
||||
|
||||
/// A switch that never changes: tests, the web, an app without agents.
|
||||
pub fn fixed(mcp_flag: bool, launcher: bool) -> Self {
|
||||
Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) }
|
||||
}
|
||||
|
||||
/// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`.
|
||||
#[doc(hidden)]
|
||||
pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: Wake) -> Self {
|
||||
let on = Arc::new(AtomicBool::new(probe()));
|
||||
let seen: Weak<AtomicBool> = Arc::downgrade(&on);
|
||||
let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(poll);
|
||||
let now = probe();
|
||||
let Some(seen) = seen.upgrade() else { return };
|
||||
if seen.swap(now, Ordering::Relaxed) != now {
|
||||
log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" });
|
||||
wake.wake();
|
||||
}
|
||||
}
|
||||
});
|
||||
// Without a thread the answer stays what it was at launch.
|
||||
if let Err(e) = started {
|
||||
log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}");
|
||||
}
|
||||
Self { mcp_flag, on }
|
||||
}
|
||||
|
||||
/// The `AI-MCP` flag as it was when the watch started.
|
||||
pub fn mcp_flag(&self) -> bool {
|
||||
self.mcp_flag
|
||||
}
|
||||
|
||||
/// Whether the launcher's list named the app at the last poll.
|
||||
pub fn launcher(&self) -> bool {
|
||||
self.on.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether agents may use the open window ([`agents_allowed`]); `legacy` is the app's own
|
||||
/// earlier consent, which counts only without the flag.
|
||||
pub fn allows(&self, legacy: bool) -> bool {
|
||||
agents_allowed(self.mcp_flag, self.launcher(), legacy)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use craft_automation::agents::{
|
||||
};
|
||||
use craft_automation::server;
|
||||
use craft_automation::ui::agents::AgentsPage;
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles, Wake};
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::patterns::preferences::SettingsDraft;
|
||||
use craft_ui::runtime::motion;
|
||||
@@ -68,9 +68,9 @@ fn the_switch_wakes_once_per_change() {
|
||||
};
|
||||
let wake = {
|
||||
let wakes = wakes.clone();
|
||||
Wake::new(move || {
|
||||
move || {
|
||||
wakes.fetch_add(1, Ordering::Relaxed);
|
||||
})
|
||||
}
|
||||
};
|
||||
let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake);
|
||||
let clone = switch.clone();
|
||||
@@ -161,7 +161,9 @@ fn host() -> WindowHost {
|
||||
}
|
||||
|
||||
fn on(port: u32) -> AgentSettings {
|
||||
AgentSettings { control_port: port, ..AgentSettings::default() }
|
||||
let mut s = AgentSettings::default();
|
||||
s.control_port = port;
|
||||
s
|
||||
}
|
||||
|
||||
/// A port nothing listens on: bound, then closed.
|
||||
@@ -188,7 +190,8 @@ fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() {
|
||||
assert!(probe(port, PROBE_TIMEOUT));
|
||||
let token = std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
|
||||
let folders = AgentSettings { read_root: "/in".into(), ..on(0) };
|
||||
let mut folders = on(0);
|
||||
folders.read_root = "/in".into();
|
||||
let kept = link.sync(Some(&folders), &host);
|
||||
assert!(kept.requests.is_none() && !kept.stopped && kept.changed, "a folder change keeps the server");
|
||||
assert_eq!(link.status().port, Some(port));
|
||||
@@ -266,7 +269,9 @@ fn allow_agent_control_off_and_no_settings_folder_keep_agents_out() {
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x");
|
||||
assert!(link.sync(Some(&on(0)), &host).requests.is_some());
|
||||
let port = link.status().port.expect("listening");
|
||||
let refused = link.sync(Some(&AgentSettings { allow_agent_control: false, ..on(0) }), &host);
|
||||
let mut off = on(0);
|
||||
off.allow_agent_control = false;
|
||||
let refused = link.sync(Some(&off), &host);
|
||||
assert!(refused.stopped && refused.requests.is_none());
|
||||
assert_eq!(link.status().problem, Some(LinkProblem::NotAllowed));
|
||||
assert!(!dir.path().join(CONNECTION_FILE).exists());
|
||||
|
||||
@@ -346,5 +346,10 @@ pub enum CursorPriority {
|
||||
|
||||
/// The winning request: the highest priority, the later request on a tie.
|
||||
pub fn pick(requests: &[(Cursor, CursorPriority)]) -> Option<&Cursor> {
|
||||
requests.iter().enumerate().max_by_key(|(order, (_, priority))| (*priority, *order)).map(|(_, (cursor, _))| cursor)
|
||||
pick_index(requests).map(|at| &requests[at].0)
|
||||
}
|
||||
|
||||
/// The index of the winning request ([`pick`]).
|
||||
pub fn pick_index(requests: &[(Cursor, CursorPriority)]) -> Option<usize> {
|
||||
requests.iter().enumerate().max_by_key(|(order, (_, priority))| (*priority, *order)).map(|(at, _)| at)
|
||||
}
|
||||
@@ -30,13 +30,15 @@ pub enum HitShape {
|
||||
/// The other end.
|
||||
b: Pos2,
|
||||
},
|
||||
/// A chain of segments, hit within [`LINE_REACH`].
|
||||
/// A chain of segments, hit within `reach` ([`LINE_REACH`] unless [`HitShape::polyline_within`] says otherwise).
|
||||
#[non_exhaustive]
|
||||
Polyline {
|
||||
/// The corners in order.
|
||||
points: Vec<Pos2>,
|
||||
/// Whether the last corner joins the first.
|
||||
closed: bool,
|
||||
/// How far from the chain a point still hits it, in points.
|
||||
reach: f32,
|
||||
},
|
||||
/// A filled polygon.
|
||||
Polygon(Vec<Pos2>),
|
||||
@@ -62,9 +64,16 @@ impl HitShape {
|
||||
HitShape::Segment { a, b }
|
||||
}
|
||||
|
||||
/// A chain of segments, closed when `closed`.
|
||||
/// A chain of segments, closed when `closed`, hit within [`LINE_REACH`].
|
||||
pub fn polyline(points: Vec<Pos2>, closed: bool) -> Self {
|
||||
HitShape::Polyline { points, closed }
|
||||
HitShape::Polyline { points, closed, reach: LINE_REACH }
|
||||
}
|
||||
|
||||
/// A chain of segments, closed when `closed`, hit within `reach` points: a tool whose measured reach differs from
|
||||
/// a line's. A negative or non-finite `reach` is [`LINE_REACH`].
|
||||
pub fn polyline_within(points: Vec<Pos2>, closed: bool, reach: f32) -> Self {
|
||||
let reach = if reach.is_finite() && reach >= 0.0 { reach } else { LINE_REACH };
|
||||
HitShape::Polyline { points, closed, reach }
|
||||
}
|
||||
|
||||
/// The part of `within` outside `polygon`.
|
||||
@@ -95,7 +104,8 @@ impl HitShape {
|
||||
}
|
||||
HitShape::Circle { center, radius } => center.distance(point) <= radius.max(across / 2.0),
|
||||
HitShape::Segment { a, b } => segment_distance(point, *a, *b) <= reach,
|
||||
HitShape::Polyline { points, closed } => {
|
||||
HitShape::Polyline { points, closed, reach: own } => {
|
||||
let reach = own.max(across / 2.0);
|
||||
let closing = closed.then(|| points.first().zip(points.last())).flatten();
|
||||
points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= reach)
|
||||
|| closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= reach)
|
||||
@@ -116,10 +126,10 @@ impl HitShape {
|
||||
HitShape::Rect(rect) => rect.contains(point),
|
||||
HitShape::Circle { center, radius } => center.distance(point) <= *radius,
|
||||
HitShape::Segment { a, b } => segment_distance(point, *a, *b) <= LINE_REACH,
|
||||
HitShape::Polyline { points, closed } => {
|
||||
HitShape::Polyline { points, closed, reach } => {
|
||||
let closing = closed.then(|| points.first().zip(points.last())).flatten();
|
||||
points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= LINE_REACH)
|
||||
|| closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= LINE_REACH)
|
||||
points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= *reach)
|
||||
|| closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= *reach)
|
||||
}
|
||||
HitShape::Polygon(points) => inside_polygon(point, points),
|
||||
HitShape::OutsidePolygon { within, polygon } => within.contains(point) && !inside_polygon(point, polygon),
|
||||
@@ -330,4 +340,18 @@ mod tests {
|
||||
let tie = [shape(big(), Sense::CLICK, 1, 0, HitLevel::Body, 0), shape(big(), Sense::CLICK, 2, 0, HitLevel::Body, 0)];
|
||||
assert_eq!(owner(&tie), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_hits_within_its_own_reach_and_a_bad_reach_is_a_lines() {
|
||||
let points = vec![pos2(0.0, 0.0), pos2(100.0, 0.0)];
|
||||
let line = HitShape::polyline(points.clone(), false);
|
||||
assert!(line.hit(pos2(50.0, LINE_REACH)) && !line.hit(pos2(50.0, LINE_REACH + 0.5)));
|
||||
let wide = HitShape::polyline_within(points.clone(), false, 5.0);
|
||||
assert!(wide.hit(pos2(50.0, 5.0)) && wide.hit(pos2(50.0, -5.0)) && !wide.hit(pos2(50.0, 5.5)));
|
||||
let hits = |shape: HitShape, y: f32| Shape::new(shape, Sense::CLICK, 0_u8, None, HitPriority::BODY, 0).min_across(8.0).hits(pos2(50.0, y));
|
||||
assert!(hits(wide.clone(), 5.0) && !hits(wide, 5.5), "a target size under twice the reach keeps the reach");
|
||||
for bad in [f32::NAN, f32::INFINITY, -1.0] {
|
||||
assert_eq!(HitShape::polyline_within(points.clone(), false, bad), line);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use craft_host::target::Os;
|
||||
use craft_keymap::{Chord, Key, Mods};
|
||||
|
||||
/// What the focused stop is, as far as the table's rows differ.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct KeyRole {
|
||||
/// A value control with a reset value and no text part: Delete resets it.
|
||||
|
||||
@@ -10,6 +10,11 @@ repository.workspace = true
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# MP4 timed text (3GPP TS 26.245 / mov_text / tx3g) sample codec.
|
||||
mov-text = []
|
||||
|
||||
[dependencies]
|
||||
craft-timeline = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
@@ -21,3 +26,5 @@ proptest = { workspace = true }
|
||||
roxmltree = "0.21"
|
||||
# ffmpeg as the reference for the ASS tests (tests/it/ass.rs).
|
||||
craft-media-testkit = { workspace = true }
|
||||
# craft-media isobmff for mov_text oracle demuxing/muxing tests.
|
||||
craft-media = { workspace = true, features = ["isobmff"] }
|
||||
@@ -27,6 +27,10 @@ assert!(scc.starts_with(b"Scenarist_SCC V1.0"));
|
||||
and the SMPTE ST 334-2 caption distribution packet.
|
||||
- `plain_text` strips inline tags and decodes the common entities, for display or for formats
|
||||
without markup.
|
||||
- Optional feature `mov-text` provides MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245)
|
||||
sample decoding, encoding, modifier box parsing (`styl`, `hlit`, `hclr`, `krok`, `dlay`, `href`,
|
||||
`tbox`, `blnk`, `wrap`), and `Tx3gConfig` sample entry parsing/writing for ISO BMFF (`.mp4`) and
|
||||
QuickTime (`.mov`) subtitle tracks.
|
||||
|
||||
## Time
|
||||
|
||||
|
||||
@@ -36,6 +36,8 @@ pub mod ass;
|
||||
pub mod cea608;
|
||||
pub mod jacosub;
|
||||
pub mod mcc;
|
||||
#[cfg(feature = "mov-text")]
|
||||
pub mod mov_text;
|
||||
pub mod pjs;
|
||||
pub mod realtext;
|
||||
pub mod scc;
|
||||
|
||||
@@ -0,0 +1,871 @@
|
||||
//! MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245).
|
||||
//!
|
||||
//! A clean-room reader and writer for 3GPP Timed Text subtitle samples and sample entry
|
||||
//! configurations (`tx3g`), as carried in ISO BMFF (`.mp4`) and QuickTime (`.mov`) files.
|
||||
//!
|
||||
//! ## Sample Structure
|
||||
//!
|
||||
//! A timed text sample consists of:
|
||||
//! - A 16-bit big-endian text length.
|
||||
//! - The text string bytes (UTF-8, or UTF-16 with BOM).
|
||||
//! - Zero or more modifier boxes:
|
||||
//! - `styl`: Character style runs (bold, italic, underline, font ID, font size, text color).
|
||||
//! - `hlit`: Highlighted character range.
|
||||
//! - `hclr`: Highlight color (RGBA).
|
||||
//! - `krok`: Karaoke highlight timing and character spans.
|
||||
//! - `dlay`: Scroll delay in track-timescale ticks.
|
||||
//! - `href`: Hypertext link URL and alt text.
|
||||
//! - `tbox`: Text box override coordinates (`top, left, bottom, right`).
|
||||
//! - `blnk`: Blinking text character range.
|
||||
//! - `twrp`: Text wrap flag (0 = no wrap, 1 = automatic soft wrap).
|
||||
//!
|
||||
//! ## Style Flags
|
||||
//!
|
||||
//! Style flags in `styl` records:
|
||||
//! - `0x01`: Bold (`<b>...</b>`)
|
||||
//! - `0x02`: Italic (`<i>...</i>`)
|
||||
//! - `0x04`: Underline (`<u>...</u>`)
|
||||
|
||||
use crate::time::Tick;
|
||||
use crate::{Cue, Document, TICKS_PER_SECOND};
|
||||
|
||||
/// What went wrong reading or writing timed text.
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The input slice is shorter than the declared field or box size.
|
||||
#[error("truncated timed text data")]
|
||||
Truncated,
|
||||
/// The text payload is not valid UTF-8 and contains no valid UTF-16 BOM.
|
||||
#[error("invalid text encoding in timed text sample")]
|
||||
InvalidText,
|
||||
/// The text exceeds the 16-bit length prefix (65,535 bytes).
|
||||
#[error("timed text string exceeds 65535 bytes: {0}")]
|
||||
TextTooLong(usize),
|
||||
/// A modifier box header has an invalid size (< 8).
|
||||
#[error("invalid modifier box size: {0}")]
|
||||
InvalidBox(&'static str),
|
||||
}
|
||||
|
||||
/// `Result` alias for timed text operations.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Face style flag: Bold (`0x01`).
|
||||
pub const STYLE_FLAG_BOLD: u8 = 0x01;
|
||||
/// Face style flag: Italic (`0x02`).
|
||||
pub const STYLE_FLAG_ITALIC: u8 = 0x02;
|
||||
/// Face style flag: Underline (`0x04`).
|
||||
pub const STYLE_FLAG_UNDERLINE: u8 = 0x04;
|
||||
|
||||
/// A character styling record within a `styl` box.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct StyleRecord {
|
||||
/// 0-indexed start character index (inclusive, measured in Unicode scalar values).
|
||||
pub start_char: u16,
|
||||
/// 0-indexed end character index (exclusive, measured in Unicode scalar values).
|
||||
pub end_char: u16,
|
||||
/// 16-bit font ID matching an entry in the sample description font table (`ftab`).
|
||||
pub font_id: u16,
|
||||
/// Face style flags: bit 0 = bold, bit 1 = italic, bit 2 = underline.
|
||||
pub face_style_flags: u8,
|
||||
/// Font size in points.
|
||||
pub font_size: u8,
|
||||
/// Text RGBA color (`[r, g, b, a]`).
|
||||
pub text_color_rgba: [u8; 4],
|
||||
}
|
||||
|
||||
impl Default for StyleRecord {
|
||||
fn default() -> Self {
|
||||
Self { start_char: 0, end_char: 0, font_id: 1, face_style_flags: 0, font_size: 16, text_color_rgba: [255, 255, 255, 255] }
|
||||
}
|
||||
}
|
||||
|
||||
impl StyleRecord {
|
||||
/// Returns `true` if bold is set.
|
||||
pub fn is_bold(&self) -> bool {
|
||||
self.face_style_flags & STYLE_FLAG_BOLD != 0
|
||||
}
|
||||
|
||||
/// Returns `true` if italic is set.
|
||||
pub fn is_italic(&self) -> bool {
|
||||
self.face_style_flags & STYLE_FLAG_ITALIC != 0
|
||||
}
|
||||
|
||||
/// Returns `true` if underline is set.
|
||||
pub fn is_underline(&self) -> bool {
|
||||
self.face_style_flags & STYLE_FLAG_UNDERLINE != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Coordinates of a text display box (`tbox`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TextBox {
|
||||
pub top: i16,
|
||||
pub left: i16,
|
||||
pub bottom: i16,
|
||||
pub right: i16,
|
||||
}
|
||||
|
||||
/// An entry in a karaoke box (`krok`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct KaraokeEntry {
|
||||
/// Highlight end time in timescale ticks.
|
||||
pub highlight_end_time: u32,
|
||||
/// Start character index (inclusive).
|
||||
pub start_char: u16,
|
||||
/// End character index (exclusive).
|
||||
pub end_char: u16,
|
||||
}
|
||||
|
||||
/// A hypertext link entry (`href`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HyperText {
|
||||
/// Start character index (inclusive).
|
||||
pub start_char: u16,
|
||||
/// End character index (exclusive).
|
||||
pub end_char: u16,
|
||||
/// Destination URL.
|
||||
pub url: String,
|
||||
/// Accessible alt text string.
|
||||
pub alt_string: String,
|
||||
}
|
||||
|
||||
/// An unpacked 3GPP Timed Text (`tx3g` / `mov_text`) sample.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TextSample {
|
||||
/// Decoded UTF-8 text content.
|
||||
pub text: String,
|
||||
/// Character styling records from the `styl` box.
|
||||
pub styles: Vec<StyleRecord>,
|
||||
/// Highlighted character range `(start_char, end_char)` from `hlit`.
|
||||
pub highlight: Option<(u16, u16)>,
|
||||
/// Highlight color `[r, g, b, a]` from `hclr`.
|
||||
pub highlight_color: Option<[u8; 4]>,
|
||||
/// Karaoke timing and spans `(highlight_start_time, entries)` from `krok`.
|
||||
pub karaoke: Option<(u32, Vec<KaraokeEntry>)>,
|
||||
/// Scroll delay in milliseconds from `dlay`.
|
||||
pub scroll_delay: Option<u32>,
|
||||
/// Hypertext links from `href` boxes.
|
||||
pub hypertext: Vec<HyperText>,
|
||||
/// Text box override from `tbox`.
|
||||
pub text_box: Option<TextBox>,
|
||||
/// Blinking character ranges `(start_char, end_char)` from `blnk` boxes.
|
||||
pub blinking: Vec<(u16, u16)>,
|
||||
/// Wrap flag from `wrap` box: `0` = automatic wrap, `1` = no wrap.
|
||||
pub wrap_flag: Option<u8>,
|
||||
}
|
||||
|
||||
/// Sample description table configuration for a `tx3g` track.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Tx3gConfig {
|
||||
/// 32-bit display flags (e.g. scroll in, scroll out, continuous scroll).
|
||||
pub display_flags: u32,
|
||||
/// Horizontal justification: 0 = left, 1 = center, -1 = right.
|
||||
pub horizontal_justification: i8,
|
||||
/// Vertical justification: 0 = top, 1 = center, -1 = bottom.
|
||||
pub vertical_justification: i8,
|
||||
/// Background RGBA color.
|
||||
pub background_color: [u8; 4],
|
||||
/// Default text box coordinates.
|
||||
pub default_text_box: TextBox,
|
||||
/// Default style record.
|
||||
pub default_style: StyleRecord,
|
||||
/// Font table entries `(font_id, font_name)`.
|
||||
pub fonts: Vec<(u16, String)>,
|
||||
}
|
||||
|
||||
impl Default for Tx3gConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
display_flags: 0,
|
||||
horizontal_justification: 1, // center
|
||||
vertical_justification: -1, // bottom
|
||||
background_color: [0, 0, 0, 255],
|
||||
default_text_box: TextBox::default(),
|
||||
default_style: StyleRecord::default(),
|
||||
fonts: vec![(1, "Arial".to_string())],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Tx3gConfig {
|
||||
/// Parse a `tx3g` sample entry payload (after the standard 8-byte sample entry header).
|
||||
pub fn parse(payload: &[u8]) -> Result<Self> {
|
||||
if payload.len() < 30 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
let display_flags = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
|
||||
let horizontal_justification = payload[4] as i8;
|
||||
let vertical_justification = payload[5] as i8;
|
||||
let background_color = [payload[6], payload[7], payload[8], payload[9]];
|
||||
|
||||
let default_text_box = TextBox {
|
||||
top: i16::from_be_bytes([payload[10], payload[11]]),
|
||||
left: i16::from_be_bytes([payload[12], payload[13]]),
|
||||
bottom: i16::from_be_bytes([payload[14], payload[15]]),
|
||||
right: i16::from_be_bytes([payload[16], payload[17]]),
|
||||
};
|
||||
|
||||
let default_style = StyleRecord {
|
||||
start_char: u16::from_be_bytes([payload[18], payload[19]]),
|
||||
end_char: u16::from_be_bytes([payload[20], payload[21]]),
|
||||
font_id: u16::from_be_bytes([payload[22], payload[23]]),
|
||||
face_style_flags: payload[24],
|
||||
font_size: payload[25],
|
||||
text_color_rgba: [payload[26], payload[27], payload[28], payload[29]],
|
||||
};
|
||||
|
||||
let mut fonts = Vec::new();
|
||||
let mut pos = 30;
|
||||
while pos + 8 <= payload.len() {
|
||||
let box_size = u32::from_be_bytes([payload[pos], payload[pos + 1], payload[pos + 2], payload[pos + 3]]) as usize;
|
||||
if box_size < 8 || pos.checked_add(box_size).is_none_or(|end| end > payload.len()) {
|
||||
break;
|
||||
}
|
||||
let box_type = &payload[pos + 4..pos + 8];
|
||||
if box_type == b"ftab" && box_size >= 10 {
|
||||
let count = u16::from_be_bytes([payload[pos + 8], payload[pos + 9]]) as usize;
|
||||
let mut fpos = pos + 10;
|
||||
for _ in 0..count {
|
||||
if fpos + 3 > pos + box_size {
|
||||
break;
|
||||
}
|
||||
let font_id = u16::from_be_bytes([payload[fpos], payload[fpos + 1]]);
|
||||
let name_len = payload[fpos + 2] as usize;
|
||||
fpos += 3;
|
||||
if fpos + name_len > pos + box_size {
|
||||
break;
|
||||
}
|
||||
if let Ok(name) = std::str::from_utf8(&payload[fpos..fpos + name_len]) {
|
||||
fonts.push((font_id, name.to_string()));
|
||||
}
|
||||
fpos += name_len;
|
||||
}
|
||||
}
|
||||
pos += box_size;
|
||||
}
|
||||
|
||||
Ok(Self { display_flags, horizontal_justification, vertical_justification, background_color, default_text_box, default_style, fonts })
|
||||
}
|
||||
|
||||
/// Write the `tx3g` sample entry payload (after the 8-byte sample entry header).
|
||||
pub fn write(&self) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(30 + 32);
|
||||
out.extend_from_slice(&self.display_flags.to_be_bytes());
|
||||
out.push(self.horizontal_justification as u8);
|
||||
out.push(self.vertical_justification as u8);
|
||||
out.extend_from_slice(&self.background_color);
|
||||
|
||||
out.extend_from_slice(&self.default_text_box.top.to_be_bytes());
|
||||
out.extend_from_slice(&self.default_text_box.left.to_be_bytes());
|
||||
out.extend_from_slice(&self.default_text_box.bottom.to_be_bytes());
|
||||
out.extend_from_slice(&self.default_text_box.right.to_be_bytes());
|
||||
|
||||
out.extend_from_slice(&self.default_style.start_char.to_be_bytes());
|
||||
out.extend_from_slice(&self.default_style.end_char.to_be_bytes());
|
||||
out.extend_from_slice(&self.default_style.font_id.to_be_bytes());
|
||||
out.push(self.default_style.face_style_flags);
|
||||
out.push(self.default_style.font_size);
|
||||
out.extend_from_slice(&self.default_style.text_color_rgba);
|
||||
|
||||
// ftab box
|
||||
let mut ftab_payload = Vec::new();
|
||||
let fonts = &self.fonts[..self.fonts.len().min(u16::MAX as usize)];
|
||||
ftab_payload.extend_from_slice(&(fonts.len() as u16).to_be_bytes());
|
||||
for (id, name) in fonts {
|
||||
ftab_payload.extend_from_slice(&id.to_be_bytes());
|
||||
let name_bytes = name.as_bytes();
|
||||
let limit = name.floor_char_boundary(name_bytes.len().min(255));
|
||||
ftab_payload.push(limit as u8);
|
||||
ftab_payload.extend_from_slice(&name_bytes[..limit]);
|
||||
}
|
||||
let ftab_size = 8u32.saturating_add(ftab_payload.len() as u32);
|
||||
out.extend_from_slice(&ftab_size.to_be_bytes());
|
||||
out.extend_from_slice(b"ftab");
|
||||
out.extend_from_slice(&ftab_payload);
|
||||
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and decode a single 3GPP Timed Text sample (`tx3g` / `mov_text`).
|
||||
pub fn read_sample(data: &[u8]) -> Result<TextSample> {
|
||||
if data.len() < 2 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
|
||||
let text_len = u16::from_be_bytes([data[0], data[1]]) as usize;
|
||||
if data.len() < 2 + text_len {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
|
||||
let text_bytes = &data[2..2 + text_len];
|
||||
let text = decode_text(text_bytes)?;
|
||||
|
||||
let mut sample = TextSample { text, ..Default::default() };
|
||||
|
||||
let mut pos = 2 + text_len;
|
||||
while pos + 8 <= data.len() {
|
||||
let size = u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
|
||||
if size < 8 {
|
||||
return Err(Error::InvalidBox("size smaller than 8"));
|
||||
}
|
||||
let box_end = pos.checked_add(size).ok_or(Error::Truncated)?;
|
||||
if box_end > data.len() {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
|
||||
let box_type = &data[pos + 4..pos + 8];
|
||||
let payload = &data[pos + 8..box_end];
|
||||
|
||||
match box_type {
|
||||
b"styl" => {
|
||||
if payload.len() < 2 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
let count = u16::from_be_bytes([payload[0], payload[1]]) as usize;
|
||||
let mut spos = 2;
|
||||
for _ in 0..count {
|
||||
if spos + 12 > payload.len() {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
sample.styles.push(StyleRecord {
|
||||
start_char: u16::from_be_bytes([payload[spos], payload[spos + 1]]),
|
||||
end_char: u16::from_be_bytes([payload[spos + 2], payload[spos + 3]]),
|
||||
font_id: u16::from_be_bytes([payload[spos + 4], payload[spos + 5]]),
|
||||
face_style_flags: payload[spos + 6],
|
||||
font_size: payload[spos + 7],
|
||||
text_color_rgba: [payload[spos + 8], payload[spos + 9], payload[spos + 10], payload[spos + 11]],
|
||||
});
|
||||
spos += 12;
|
||||
}
|
||||
}
|
||||
b"hlit" => {
|
||||
if payload.len() < 4 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
let start = u16::from_be_bytes([payload[0], payload[1]]);
|
||||
let end = u16::from_be_bytes([payload[2], payload[3]]);
|
||||
sample.highlight = Some((start, end));
|
||||
}
|
||||
b"hclr" => {
|
||||
if payload.len() < 4 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
sample.highlight_color = Some([payload[0], payload[1], payload[2], payload[3]]);
|
||||
}
|
||||
b"krok" => {
|
||||
if payload.len() < 6 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
let start_time = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
|
||||
let count = u16::from_be_bytes([payload[4], payload[5]]) as usize;
|
||||
let mut entries = Vec::new();
|
||||
let mut kpos = 6;
|
||||
for _ in 0..count {
|
||||
if kpos + 8 > payload.len() {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
entries.push(KaraokeEntry {
|
||||
highlight_end_time: u32::from_be_bytes([payload[kpos], payload[kpos + 1], payload[kpos + 2], payload[kpos + 3]]),
|
||||
start_char: u16::from_be_bytes([payload[kpos + 4], payload[kpos + 5]]),
|
||||
end_char: u16::from_be_bytes([payload[kpos + 6], payload[kpos + 7]]),
|
||||
});
|
||||
kpos += 8;
|
||||
}
|
||||
sample.karaoke = Some((start_time, entries));
|
||||
}
|
||||
b"dlay" => {
|
||||
if payload.len() < 4 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
sample.scroll_delay = Some(u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]));
|
||||
}
|
||||
b"href" => {
|
||||
if payload.len() < 6 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
let start = u16::from_be_bytes([payload[0], payload[1]]);
|
||||
let end = u16::from_be_bytes([payload[2], payload[3]]);
|
||||
let url_len = payload[4] as usize;
|
||||
if 5 + url_len > payload.len() {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
let url = std::str::from_utf8(&payload[5..5 + url_len]).map_err(|_| Error::InvalidText)?.to_string();
|
||||
let alt_pos = 5 + url_len;
|
||||
let alt_len = payload.get(alt_pos).copied().unwrap_or(0) as usize;
|
||||
let alt_string = if alt_len > 0 && alt_pos + 1 + alt_len <= payload.len() {
|
||||
std::str::from_utf8(&payload[alt_pos + 1..alt_pos + 1 + alt_len]).map_err(|_| Error::InvalidText)?.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
sample.hypertext.push(HyperText { start_char: start, end_char: end, url, alt_string });
|
||||
}
|
||||
b"tbox" => {
|
||||
if payload.len() < 8 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
sample.text_box = Some(TextBox {
|
||||
top: i16::from_be_bytes([payload[0], payload[1]]),
|
||||
left: i16::from_be_bytes([payload[2], payload[3]]),
|
||||
bottom: i16::from_be_bytes([payload[4], payload[5]]),
|
||||
right: i16::from_be_bytes([payload[6], payload[7]]),
|
||||
});
|
||||
}
|
||||
b"blnk" => {
|
||||
if payload.len() < 4 {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
let start = u16::from_be_bytes([payload[0], payload[1]]);
|
||||
let end = u16::from_be_bytes([payload[2], payload[3]]);
|
||||
sample.blinking.push((start, end));
|
||||
}
|
||||
b"twrp" | b"wrap" => {
|
||||
if payload.is_empty() {
|
||||
return Err(Error::Truncated);
|
||||
}
|
||||
sample.wrap_flag = Some(payload[0]);
|
||||
}
|
||||
_ => {
|
||||
// Unknown modifier box: safely ignored.
|
||||
}
|
||||
}
|
||||
|
||||
pos = box_end;
|
||||
}
|
||||
|
||||
Ok(sample)
|
||||
}
|
||||
|
||||
/// Helper to decode UTF-8 or UTF-16 with BOM.
|
||||
fn decode_text(bytes: &[u8]) -> Result<String> {
|
||||
if bytes.len() >= 2 {
|
||||
if bytes[0] == 0xFE && bytes[1] == 0xFF {
|
||||
// UTF-16 BE
|
||||
let u16s: Vec<u16> = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
|
||||
return String::from_utf16(&u16s).map_err(|_| Error::InvalidText);
|
||||
} else if bytes[0] == 0xFF && bytes[1] == 0xFE {
|
||||
// UTF-16 LE
|
||||
let u16s: Vec<u16> = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
|
||||
return String::from_utf16(&u16s).map_err(|_| Error::InvalidText);
|
||||
}
|
||||
}
|
||||
std::str::from_utf8(bytes).map(ToString::to_string).map_err(|_| Error::InvalidText)
|
||||
}
|
||||
|
||||
/// Pack and encode a timed text sample into bytes.
|
||||
pub fn write_sample(sample: &TextSample) -> Result<Vec<u8>> {
|
||||
let text_bytes = sample.text.as_bytes();
|
||||
if text_bytes.len() > u16::MAX as usize {
|
||||
return Err(Error::TextTooLong(text_bytes.len()));
|
||||
}
|
||||
|
||||
let mut out = Vec::with_capacity(2 + text_bytes.len() + 64);
|
||||
out.extend_from_slice(&(text_bytes.len() as u16).to_be_bytes());
|
||||
out.extend_from_slice(text_bytes);
|
||||
|
||||
// 1. styl box
|
||||
if !sample.styles.is_empty() {
|
||||
if sample.styles.len() > u16::MAX as usize {
|
||||
return Err(Error::InvalidBox("too many styles in sample"));
|
||||
}
|
||||
let size = 8u32.checked_add(2).and_then(|s| s.checked_add(sample.styles.len() as u32 * 12)).ok_or(Error::InvalidBox("styl size overflow"))?;
|
||||
out.extend_from_slice(&size.to_be_bytes());
|
||||
out.extend_from_slice(b"styl");
|
||||
out.extend_from_slice(&(sample.styles.len() as u16).to_be_bytes());
|
||||
for st in &sample.styles {
|
||||
out.extend_from_slice(&st.start_char.to_be_bytes());
|
||||
out.extend_from_slice(&st.end_char.to_be_bytes());
|
||||
out.extend_from_slice(&st.font_id.to_be_bytes());
|
||||
out.push(st.face_style_flags);
|
||||
out.push(st.font_size);
|
||||
out.extend_from_slice(&st.text_color_rgba);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. hlit box
|
||||
if let Some((start, end)) = sample.highlight {
|
||||
out.extend_from_slice(&12u32.to_be_bytes());
|
||||
out.extend_from_slice(b"hlit");
|
||||
out.extend_from_slice(&start.to_be_bytes());
|
||||
out.extend_from_slice(&end.to_be_bytes());
|
||||
}
|
||||
|
||||
// 3. hclr box
|
||||
if let Some(color) = sample.highlight_color {
|
||||
out.extend_from_slice(&12u32.to_be_bytes());
|
||||
out.extend_from_slice(b"hclr");
|
||||
out.extend_from_slice(&color);
|
||||
}
|
||||
|
||||
// 4. krok box
|
||||
if let Some((start_time, ref entries)) = sample.karaoke {
|
||||
if entries.len() > u16::MAX as usize {
|
||||
return Err(Error::InvalidBox("too many karaoke entries"));
|
||||
}
|
||||
let size = 8u32.checked_add(6).and_then(|s| s.checked_add(entries.len() as u32 * 8)).ok_or(Error::InvalidBox("krok size overflow"))?;
|
||||
out.extend_from_slice(&size.to_be_bytes());
|
||||
out.extend_from_slice(b"krok");
|
||||
out.extend_from_slice(&start_time.to_be_bytes());
|
||||
out.extend_from_slice(&(entries.len() as u16).to_be_bytes());
|
||||
for e in entries {
|
||||
out.extend_from_slice(&e.highlight_end_time.to_be_bytes());
|
||||
out.extend_from_slice(&e.start_char.to_be_bytes());
|
||||
out.extend_from_slice(&e.end_char.to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
// 5. dlay box
|
||||
if let Some(delay) = sample.scroll_delay {
|
||||
out.extend_from_slice(&12u32.to_be_bytes());
|
||||
out.extend_from_slice(b"dlay");
|
||||
out.extend_from_slice(&delay.to_be_bytes());
|
||||
}
|
||||
|
||||
// 6. href boxes
|
||||
for link in &sample.hypertext {
|
||||
let url_bytes = link.url.as_bytes();
|
||||
let alt_bytes = link.alt_string.as_bytes();
|
||||
let ulen = url_bytes.len().min(255) as u8;
|
||||
let alen = alt_bytes.len().min(255) as u8;
|
||||
let size = 8u32 + 4 + 1 + ulen as u32 + 1 + alen as u32;
|
||||
out.extend_from_slice(&size.to_be_bytes());
|
||||
out.extend_from_slice(b"href");
|
||||
out.extend_from_slice(&link.start_char.to_be_bytes());
|
||||
out.extend_from_slice(&link.end_char.to_be_bytes());
|
||||
out.push(ulen);
|
||||
out.extend_from_slice(&url_bytes[..ulen as usize]);
|
||||
out.push(alen);
|
||||
out.extend_from_slice(&alt_bytes[..alen as usize]);
|
||||
}
|
||||
|
||||
// 7. tbox box
|
||||
if let Some(tb) = sample.text_box {
|
||||
out.extend_from_slice(&16u32.to_be_bytes());
|
||||
out.extend_from_slice(b"tbox");
|
||||
out.extend_from_slice(&tb.top.to_be_bytes());
|
||||
out.extend_from_slice(&tb.left.to_be_bytes());
|
||||
out.extend_from_slice(&tb.bottom.to_be_bytes());
|
||||
out.extend_from_slice(&tb.right.to_be_bytes());
|
||||
}
|
||||
|
||||
// 8. blnk boxes
|
||||
for &(start, end) in &sample.blinking {
|
||||
out.extend_from_slice(&12u32.to_be_bytes());
|
||||
out.extend_from_slice(b"blnk");
|
||||
out.extend_from_slice(&start.to_be_bytes());
|
||||
out.extend_from_slice(&end.to_be_bytes());
|
||||
}
|
||||
|
||||
// 9. twrp box
|
||||
if let Some(flag) = sample.wrap_flag {
|
||||
out.extend_from_slice(&9u32.to_be_bytes());
|
||||
out.extend_from_slice(b"twrp");
|
||||
out.push(flag);
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn push_escaped_char(out: &mut String, ch: char) {
|
||||
match ch {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
_ => out.push(ch),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a [`TextSample`] into HTML-style formatted markup (`<b>`, `<i>`, `<u>`, `<font color="...">`).
|
||||
pub fn sample_to_markup(sample: &TextSample) -> String {
|
||||
if sample.styles.is_empty() {
|
||||
let mut out = String::with_capacity(sample.text.len());
|
||||
for ch in sample.text.chars() {
|
||||
push_escaped_char(&mut out, ch);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
let chars: Vec<char> = sample.text.chars().collect();
|
||||
let n = chars.len();
|
||||
if n == 0 {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut starts: std::collections::HashMap<u16, Vec<&StyleRecord>> = std::collections::HashMap::new();
|
||||
let mut ends: std::collections::HashMap<u16, Vec<&StyleRecord>> = std::collections::HashMap::new();
|
||||
for st in &sample.styles {
|
||||
if st.end_char > st.start_char {
|
||||
starts.entry(st.start_char).or_default().push(st);
|
||||
ends.entry(st.end_char).or_default().push(st);
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = String::with_capacity(sample.text.len() + sample.styles.len() * 16);
|
||||
|
||||
for (i, &ch) in chars.iter().enumerate() {
|
||||
let char_idx = i as u16;
|
||||
|
||||
// Open tags for any style starting at char_idx
|
||||
if let Some(list) = starts.get(&char_idx) {
|
||||
for st in list {
|
||||
let has_color = st.text_color_rgba != [255, 255, 255, 255];
|
||||
if has_color {
|
||||
out.push_str(&format!(
|
||||
"<font color=\"#{:02x}{:02x}{:02x}\">",
|
||||
st.text_color_rgba[0], st.text_color_rgba[1], st.text_color_rgba[2]
|
||||
));
|
||||
}
|
||||
if st.is_bold() {
|
||||
out.push_str("<b>");
|
||||
}
|
||||
if st.is_italic() {
|
||||
out.push_str("<i>");
|
||||
}
|
||||
if st.is_underline() {
|
||||
out.push_str("<u>");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
push_escaped_char(&mut out, ch);
|
||||
|
||||
// Close tags for any style ending at char_idx + 1
|
||||
if let Some(list) = ends.get(&(char_idx + 1)) {
|
||||
for st in list.iter().rev() {
|
||||
if st.is_underline() {
|
||||
out.push_str("</u>");
|
||||
}
|
||||
if st.is_italic() {
|
||||
out.push_str("</i>");
|
||||
}
|
||||
if st.is_bold() {
|
||||
out.push_str("</b>");
|
||||
}
|
||||
let has_color = st.text_color_rgba != [255, 255, 255, 255];
|
||||
if has_color {
|
||||
out.push_str("</font>");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
struct CharFormatting {
|
||||
flags: u8,
|
||||
color: [u8; 4],
|
||||
}
|
||||
|
||||
impl Default for CharFormatting {
|
||||
fn default() -> Self {
|
||||
Self { flags: 0, color: [255, 255, 255, 255] }
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse HTML-style formatted markup (`<b>`, `<i>`, `<u>`, `<font color="...">`) into a [`TextSample`].
|
||||
pub fn markup_to_sample(markup: &str) -> TextSample {
|
||||
let mut bold_depth = 0usize;
|
||||
let mut italic_depth = 0usize;
|
||||
let mut underline_depth = 0usize;
|
||||
let mut color_stack: Vec<[u8; 4]> = Vec::new();
|
||||
|
||||
let mut decoded_chars: Vec<char> = Vec::with_capacity(markup.len());
|
||||
let mut char_styles: Vec<CharFormatting> = Vec::with_capacity(markup.len());
|
||||
|
||||
let mut chars = markup.chars().peekable();
|
||||
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '<' {
|
||||
let mut tag = String::new();
|
||||
for next in chars.by_ref() {
|
||||
if next == '>' {
|
||||
break;
|
||||
}
|
||||
tag.push(next);
|
||||
}
|
||||
let trimmed = tag.trim().to_ascii_lowercase();
|
||||
if trimmed == "b" {
|
||||
bold_depth += 1;
|
||||
} else if trimmed == "/b" {
|
||||
bold_depth = bold_depth.saturating_sub(1);
|
||||
} else if trimmed == "i" {
|
||||
italic_depth += 1;
|
||||
} else if trimmed == "/i" {
|
||||
italic_depth = italic_depth.saturating_sub(1);
|
||||
} else if trimmed == "u" {
|
||||
underline_depth += 1;
|
||||
} else if trimmed == "/u" {
|
||||
underline_depth = underline_depth.saturating_sub(1);
|
||||
} else if trimmed.starts_with("font") {
|
||||
if let Some(color) = parse_font_color(&tag) {
|
||||
color_stack.push(color);
|
||||
}
|
||||
} else if trimmed == "/font" {
|
||||
color_stack.pop();
|
||||
}
|
||||
} else {
|
||||
let mut text_chunk = String::new();
|
||||
text_chunk.push(ch);
|
||||
while let Some(&next) = chars.peek() {
|
||||
if next == '<' {
|
||||
break;
|
||||
}
|
||||
text_chunk.push(next);
|
||||
chars.next();
|
||||
}
|
||||
|
||||
let decoded = crate::decode_entities(&text_chunk);
|
||||
let mut flags = 0u8;
|
||||
if bold_depth > 0 {
|
||||
flags |= STYLE_FLAG_BOLD;
|
||||
}
|
||||
if italic_depth > 0 {
|
||||
flags |= STYLE_FLAG_ITALIC;
|
||||
}
|
||||
if underline_depth > 0 {
|
||||
flags |= STYLE_FLAG_UNDERLINE;
|
||||
}
|
||||
let color = color_stack.last().copied().unwrap_or([255, 255, 255, 255]);
|
||||
let fmt = CharFormatting { flags, color };
|
||||
|
||||
for c in decoded.chars() {
|
||||
decoded_chars.push(c);
|
||||
char_styles.push(fmt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let text: String = decoded_chars.iter().collect();
|
||||
|
||||
// Group adjacent characters with identical non-default formatting into sorted, non-overlapping style runs.
|
||||
let mut styles = Vec::new();
|
||||
let mut run_start: Option<(usize, CharFormatting)> = None;
|
||||
|
||||
for (idx, &fmt) in char_styles.iter().enumerate() {
|
||||
let is_styled = fmt.flags != 0 || fmt.color != [255, 255, 255, 255];
|
||||
match run_start {
|
||||
Some((start, current_fmt)) => {
|
||||
if fmt != current_fmt {
|
||||
if current_fmt.flags != 0 || current_fmt.color != [255, 255, 255, 255] {
|
||||
styles.push(StyleRecord {
|
||||
start_char: start as u16,
|
||||
end_char: idx as u16,
|
||||
font_id: 1,
|
||||
face_style_flags: current_fmt.flags,
|
||||
font_size: 16,
|
||||
text_color_rgba: current_fmt.color,
|
||||
});
|
||||
}
|
||||
run_start = if is_styled { Some((idx, fmt)) } else { None };
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if is_styled {
|
||||
run_start = Some((idx, fmt));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((start, fmt)) = run_start {
|
||||
styles.push(StyleRecord {
|
||||
start_char: start as u16,
|
||||
end_char: char_styles.len() as u16,
|
||||
font_id: 1,
|
||||
face_style_flags: fmt.flags,
|
||||
font_size: 16,
|
||||
text_color_rgba: fmt.color,
|
||||
});
|
||||
}
|
||||
|
||||
TextSample { text, styles, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Helper to parse color attribute from `<font color="...">` tag.
|
||||
fn parse_font_color(tag: &str) -> Option<[u8; 4]> {
|
||||
let lower = tag.to_ascii_lowercase();
|
||||
let col_idx = lower.find("color=")?;
|
||||
let rest = tag[col_idx + 6..].trim_start();
|
||||
let val = if let Some(stripped) = rest.strip_prefix('"') {
|
||||
let end = stripped.find('"')?;
|
||||
&stripped[..end]
|
||||
} else if let Some(stripped) = rest.strip_prefix('\'') {
|
||||
let end = stripped.find('\'')?;
|
||||
&stripped[..end]
|
||||
} else {
|
||||
let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
|
||||
&rest[..end]
|
||||
};
|
||||
|
||||
let hex = val.strip_prefix('#').unwrap_or(val);
|
||||
if hex.len() == 6 {
|
||||
let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?;
|
||||
let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?;
|
||||
let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?;
|
||||
Some([r, g, b, 255])
|
||||
} else if hex.len() == 8 {
|
||||
let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?;
|
||||
let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?;
|
||||
let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?;
|
||||
let a = u8::from_str_radix(hex.get(6..8)?, 16).ok()?;
|
||||
Some([r, g, b, a])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a caption [`Cue`] into a [`TextSample`].
|
||||
pub fn cue_to_sample(cue: &Cue) -> TextSample {
|
||||
markup_to_sample(&cue.text)
|
||||
}
|
||||
|
||||
/// Convert a [`TextSample`] into a caption [`Cue`] spanning `start` to `end`.
|
||||
pub fn sample_to_cue(sample: &TextSample, start: Tick, end: Tick) -> Cue {
|
||||
Cue { start, end, text: sample_to_markup(sample), speaker: None, id: None, settings: String::new() }
|
||||
}
|
||||
|
||||
/// Decode a stream of timed text samples into a [`Document`].
|
||||
pub fn decode_timed_samples<'a, I>(doc: &mut Document, samples: I, timescale: u32) -> Result<()>
|
||||
where
|
||||
I: IntoIterator<Item = (u64, u32, &'a [u8])>,
|
||||
{
|
||||
decode_timed_samples_with_config(doc, samples, timescale, None)
|
||||
}
|
||||
|
||||
/// Decode a stream of timed text samples into a [`Document`], applying an optional sample description configuration.
|
||||
pub fn decode_timed_samples_with_config<'a, I>(doc: &mut Document, samples: I, timescale: u32, config: Option<&Tx3gConfig>) -> Result<()>
|
||||
where
|
||||
I: IntoIterator<Item = (u64, u32, &'a [u8])>,
|
||||
{
|
||||
if timescale == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let ts = timescale as i128;
|
||||
for (pts, duration, data) in samples {
|
||||
let mut sample = read_sample(data)?;
|
||||
if sample.text.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
if sample.styles.is_empty()
|
||||
&& let Some(cfg) = config
|
||||
&& (cfg.default_style.face_style_flags != 0 || cfg.default_style.text_color_rgba != [255, 255, 255, 255])
|
||||
{
|
||||
sample.styles.push(StyleRecord {
|
||||
start_char: 0,
|
||||
end_char: sample.text.chars().count() as u16,
|
||||
font_id: cfg.default_style.font_id,
|
||||
face_style_flags: cfg.default_style.face_style_flags,
|
||||
font_size: cfg.default_style.font_size,
|
||||
text_color_rgba: cfg.default_style.text_color_rgba,
|
||||
});
|
||||
}
|
||||
let end_pts = pts.checked_add(duration as u64).ok_or(Error::InvalidBox("timestamp interval overflow"))?;
|
||||
let start_ticks = (pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64;
|
||||
let end_ticks = (end_pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64;
|
||||
doc.cues.push(sample_to_cue(&sample, Tick(start_ticks), Tick(end_ticks)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -2,6 +2,8 @@ mod ass;
|
||||
mod limits;
|
||||
mod literal_roundtrips;
|
||||
mod mcc_708_timing;
|
||||
#[cfg(feature = "mov-text")]
|
||||
mod mov_text;
|
||||
mod pjs_realtext_jacosub;
|
||||
mod roundtrip;
|
||||
mod ttml_body_styles;
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
//! Clean-room tests and FFmpeg oracle tests for MP4 Timed Text (`mov_text` / `tx3g`).
|
||||
|
||||
use craft_captions::mov_text::{
|
||||
Error, KaraokeEntry, STYLE_FLAG_BOLD, STYLE_FLAG_ITALIC, STYLE_FLAG_UNDERLINE, StyleRecord, TextBox, TextSample, Tx3gConfig,
|
||||
decode_timed_samples, markup_to_sample, read_sample, sample_to_markup, write_sample,
|
||||
};
|
||||
use craft_captions::time::Tick;
|
||||
use craft_captions::{Document, TICKS_PER_SECOND};
|
||||
|
||||
#[test]
|
||||
fn test_plain_text_roundtrip() {
|
||||
let sample = TextSample { text: "Hello world without styles".to_string(), ..Default::default() };
|
||||
|
||||
let bytes = write_sample(&sample).expect("write sample");
|
||||
assert_eq!(bytes.len(), 2 + sample.text.len());
|
||||
assert_eq!(&bytes[..2], &(sample.text.len() as u16).to_be_bytes());
|
||||
assert_eq!(&bytes[2..], sample.text.as_bytes());
|
||||
|
||||
let decoded = read_sample(&bytes).expect("read sample");
|
||||
assert_eq!(decoded.text, sample.text);
|
||||
assert!(decoded.styles.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_sample_roundtrip() {
|
||||
let sample = TextSample::default();
|
||||
let bytes = write_sample(&sample).expect("write");
|
||||
assert_eq!(bytes, &[0x00, 0x00]);
|
||||
|
||||
let decoded = read_sample(&bytes).expect("read");
|
||||
assert_eq!(decoded.text, "");
|
||||
assert!(decoded.styles.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_styles_roundtrip() {
|
||||
let sample = TextSample {
|
||||
text: "Bold, Italic, Underline, and Colored".to_string(),
|
||||
styles: vec![
|
||||
StyleRecord {
|
||||
start_char: 0,
|
||||
end_char: 4,
|
||||
font_id: 1,
|
||||
face_style_flags: STYLE_FLAG_BOLD,
|
||||
font_size: 16,
|
||||
text_color_rgba: [255, 255, 255, 255],
|
||||
},
|
||||
StyleRecord {
|
||||
start_char: 6,
|
||||
end_char: 12,
|
||||
font_id: 1,
|
||||
face_style_flags: STYLE_FLAG_ITALIC,
|
||||
font_size: 18,
|
||||
text_color_rgba: [255, 255, 255, 255],
|
||||
},
|
||||
StyleRecord {
|
||||
start_char: 14,
|
||||
end_char: 23,
|
||||
font_id: 1,
|
||||
face_style_flags: STYLE_FLAG_UNDERLINE,
|
||||
font_size: 16,
|
||||
text_color_rgba: [255, 255, 255, 255],
|
||||
},
|
||||
StyleRecord { start_char: 29, end_char: 36, font_id: 1, face_style_flags: 0, font_size: 20, text_color_rgba: [255, 0, 0, 255] },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let bytes = write_sample(&sample).expect("write");
|
||||
let decoded = read_sample(&bytes).expect("read");
|
||||
|
||||
assert_eq!(decoded.text, sample.text);
|
||||
assert_eq!(decoded.styles.len(), 4);
|
||||
assert_eq!(decoded.styles, sample.styles);
|
||||
|
||||
assert!(decoded.styles[0].is_bold());
|
||||
assert!(!decoded.styles[0].is_italic());
|
||||
assert!(decoded.styles[1].is_italic());
|
||||
assert!(decoded.styles[2].is_underline());
|
||||
assert_eq!(decoded.styles[3].text_color_rgba, [255, 0, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all_modifier_boxes_roundtrip() {
|
||||
let sample = TextSample {
|
||||
text: "Full modifiers test".to_string(),
|
||||
styles: vec![StyleRecord {
|
||||
start_char: 0,
|
||||
end_char: 4,
|
||||
font_id: 1,
|
||||
face_style_flags: STYLE_FLAG_BOLD,
|
||||
font_size: 16,
|
||||
text_color_rgba: [255, 255, 255, 255],
|
||||
}],
|
||||
highlight: Some((5, 14)),
|
||||
highlight_color: Some([255, 255, 0, 255]),
|
||||
karaoke: Some((
|
||||
100,
|
||||
vec![
|
||||
KaraokeEntry { highlight_end_time: 200, start_char: 0, end_char: 4 },
|
||||
KaraokeEntry { highlight_end_time: 350, start_char: 5, end_char: 14 },
|
||||
],
|
||||
)),
|
||||
scroll_delay: Some(500),
|
||||
hypertext: vec![craft_captions::mov_text::HyperText {
|
||||
start_char: 0,
|
||||
end_char: 19,
|
||||
url: "https://example.com".to_string(),
|
||||
alt_string: "Example".to_string(),
|
||||
}],
|
||||
text_box: Some(TextBox { top: 10, left: 20, bottom: 100, right: 200 }),
|
||||
blinking: vec![(0, 4), (15, 19)],
|
||||
wrap_flag: Some(1),
|
||||
};
|
||||
|
||||
let bytes = write_sample(&sample).expect("write");
|
||||
let decoded = read_sample(&bytes).expect("read");
|
||||
|
||||
assert_eq!(decoded, sample);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_utf16_bom_reading() {
|
||||
// UTF-16 BE with BOM
|
||||
let text = "Hello UTF-16";
|
||||
let mut data_be = Vec::new();
|
||||
let utf16_be_bytes: Vec<u8> = text.encode_utf16().flat_map(|u| u.to_be_bytes()).collect();
|
||||
let total_len = 2 + utf16_be_bytes.len();
|
||||
data_be.extend_from_slice(&(total_len as u16).to_be_bytes());
|
||||
data_be.extend_from_slice(&[0xFE, 0xFF]);
|
||||
data_be.extend_from_slice(&utf16_be_bytes);
|
||||
|
||||
let decoded_be = read_sample(&data_be).expect("read UTF-16 BE");
|
||||
assert_eq!(decoded_be.text, text);
|
||||
|
||||
// UTF-16 LE with BOM
|
||||
let mut data_le = Vec::new();
|
||||
let utf16_le_bytes: Vec<u8> = text.encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
|
||||
data_le.extend_from_slice(&(total_len as u16).to_be_bytes());
|
||||
data_le.extend_from_slice(&[0xFF, 0xFE]);
|
||||
data_le.extend_from_slice(&utf16_le_bytes);
|
||||
|
||||
let decoded_le = read_sample(&data_le).expect("read UTF-16 LE");
|
||||
assert_eq!(decoded_le.text, text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_markup_conversion() {
|
||||
let markup = "Hello <b>Bold</b> and <i>Italic</i> and <u>Underline</u> and <font color=\"#ff0000\">Red</font>";
|
||||
let sample = markup_to_sample(markup);
|
||||
|
||||
assert_eq!(sample.text, "Hello Bold and Italic and Underline and Red");
|
||||
assert_eq!(sample.styles.len(), 4);
|
||||
|
||||
let bold = &sample.styles[0];
|
||||
assert_eq!(&sample.text[bold.start_char as usize..bold.end_char as usize], "Bold");
|
||||
assert!(bold.is_bold());
|
||||
|
||||
let italic = &sample.styles[1];
|
||||
assert_eq!(&sample.text[italic.start_char as usize..italic.end_char as usize], "Italic");
|
||||
assert!(italic.is_italic());
|
||||
|
||||
let underline = &sample.styles[2];
|
||||
assert_eq!(&sample.text[underline.start_char as usize..underline.end_char as usize], "Underline");
|
||||
assert!(underline.is_underline());
|
||||
|
||||
let red = &sample.styles[3];
|
||||
assert_eq!(&sample.text[red.start_char as usize..red.end_char as usize], "Red");
|
||||
assert_eq!(red.text_color_rgba, [255, 0, 0, 255]);
|
||||
|
||||
let regenerated = sample_to_markup(&sample);
|
||||
assert_eq!(regenerated, markup);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_styles_sorted_non_overlapping() {
|
||||
let markup = "<b>A<i>B</i>C</b>";
|
||||
let sample = markup_to_sample(markup);
|
||||
assert_eq!(sample.text, "ABC");
|
||||
assert_eq!(sample.styles.len(), 3);
|
||||
// [0, 1): A is bold
|
||||
assert_eq!(sample.styles[0].start_char, 0);
|
||||
assert_eq!(sample.styles[0].end_char, 1);
|
||||
assert_eq!(sample.styles[0].face_style_flags, STYLE_FLAG_BOLD);
|
||||
// [1, 2): B is bold + italic
|
||||
assert_eq!(sample.styles[1].start_char, 1);
|
||||
assert_eq!(sample.styles[1].end_char, 2);
|
||||
assert_eq!(sample.styles[1].face_style_flags, STYLE_FLAG_BOLD | STYLE_FLAG_ITALIC);
|
||||
// [2, 3): C is bold
|
||||
assert_eq!(sample.styles[2].start_char, 2);
|
||||
assert_eq!(sample.styles[2].end_char, 3);
|
||||
assert_eq!(sample.styles[2].face_style_flags, STYLE_FLAG_BOLD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_entities_and_literal_escaping() {
|
||||
let markup = "A & <b>B < C</b>";
|
||||
let sample = markup_to_sample(markup);
|
||||
assert_eq!(sample.text, "A & B < C");
|
||||
assert_eq!(sample.styles.len(), 1);
|
||||
assert_eq!(sample.styles[0].start_char, 4);
|
||||
assert_eq!(sample.styles[0].end_char, 9);
|
||||
|
||||
let roundtripped = sample_to_markup(&sample);
|
||||
assert_eq!(roundtripped, "A & <b>B < C</b>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_twrp_box() {
|
||||
let sample = TextSample { text: "Wrap me".to_string(), wrap_flag: Some(1), ..Default::default() };
|
||||
let bytes = write_sample(&sample).expect("write sample");
|
||||
// Verify bytes contain twrp box
|
||||
assert!(bytes.windows(4).any(|w| w == b"twrp"));
|
||||
|
||||
let read_back = read_sample(&bytes).expect("read sample");
|
||||
assert_eq!(read_back.wrap_flag, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tx3g_config_roundtrip() {
|
||||
let cfg = Tx3gConfig {
|
||||
display_flags: 0x0000_0001,
|
||||
horizontal_justification: 1,
|
||||
vertical_justification: -1,
|
||||
background_color: [10, 20, 30, 255],
|
||||
default_text_box: TextBox { top: 0, left: 0, bottom: 480, right: 640 },
|
||||
default_style: StyleRecord {
|
||||
start_char: 0,
|
||||
end_char: 0,
|
||||
font_id: 1,
|
||||
face_style_flags: STYLE_FLAG_BOLD,
|
||||
font_size: 24,
|
||||
text_color_rgba: [255, 255, 255, 255],
|
||||
},
|
||||
fonts: vec![(1, "Serif".to_string()), (2, "Sans".to_string())],
|
||||
};
|
||||
|
||||
let bytes = cfg.write();
|
||||
let parsed = Tx3gConfig::parse(&bytes).expect("parse config");
|
||||
assert_eq!(parsed, cfg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_timed_samples_to_document() {
|
||||
let mut doc = Document::default();
|
||||
|
||||
let s1 = write_sample(&markup_to_sample("First <b>cue</b>")).expect("s1");
|
||||
let s2 = write_sample(&markup_to_sample("Second <i>cue</i>")).expect("s2");
|
||||
|
||||
let samples = vec![(0u64, 1000u32, s1.as_slice()), (1000u64, 1500u32, s2.as_slice())];
|
||||
|
||||
decode_timed_samples(&mut doc, samples, 1000).expect("decode samples");
|
||||
|
||||
assert_eq!(doc.cues.len(), 2);
|
||||
assert_eq!(doc.cues[0].start, Tick(0));
|
||||
assert_eq!(doc.cues[0].end, Tick(TICKS_PER_SECOND));
|
||||
assert_eq!(doc.cues[0].text, "First <b>cue</b>");
|
||||
|
||||
assert_eq!(doc.cues[1].start, Tick(TICKS_PER_SECOND));
|
||||
assert_eq!(doc.cues[1].end, Tick((TICKS_PER_SECOND as f64 * 2.5) as i64));
|
||||
assert_eq!(doc.cues[1].text, "Second <i>cue</i>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hostile_inputs_never_panic() {
|
||||
// Empty input
|
||||
assert!(matches!(read_sample(&[]), Err(Error::Truncated)));
|
||||
|
||||
// 1-byte input
|
||||
assert!(matches!(read_sample(&[0x00]), Err(Error::Truncated)));
|
||||
|
||||
// Length says 10 bytes, but slice ends
|
||||
assert!(matches!(read_sample(&[0x00, 0x0A, 0x41]), Err(Error::Truncated)));
|
||||
|
||||
// Invalid UTF-8 without BOM
|
||||
assert!(matches!(read_sample(&[0x00, 0x02, 0xFF, 0xFF]), Err(Error::InvalidText)));
|
||||
|
||||
// Box size < 8
|
||||
let mut bad_box = Vec::new();
|
||||
bad_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']);
|
||||
bad_box.extend_from_slice(&[0x00, 0x00, 0x00, 0x04, b's', b't', b'y', b'l']);
|
||||
assert!(matches!(read_sample(&bad_box), Err(Error::InvalidBox(_))));
|
||||
|
||||
// Box size exceeds remaining slice
|
||||
let mut truncated_box = Vec::new();
|
||||
truncated_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']);
|
||||
truncated_box.extend_from_slice(&[0x00, 0x00, 0x01, 0x00, b's', b't', b'y', b'l']);
|
||||
assert!(matches!(read_sample(&truncated_box), Err(Error::Truncated)));
|
||||
|
||||
// Unknown modifier boxes are safely ignored without error
|
||||
let mut unknown_box = Vec::new();
|
||||
unknown_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']);
|
||||
unknown_box.extend_from_slice(&[0x00, 0x00, 0x00, 0x0C, b'f', b'a', b'k', b'e', 1, 2, 3, 4]);
|
||||
let decoded = read_sample(&unknown_box).expect("unknown box should be skipped");
|
||||
assert_eq!(decoded.text, "Test");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ffmpeg_mov_text_oracle() {
|
||||
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
|
||||
let temp_dir = std::env::temp_dir().join("craft_mov_text_test");
|
||||
let _ = std::fs::create_dir_all(&temp_dir);
|
||||
|
||||
// 1. Create SRT file with formatting: bold, italic, underline
|
||||
let srt_path = temp_dir.join("input.srt");
|
||||
let mp4_path = temp_dir.join("output.mp4");
|
||||
let srt_content = "1\n00:00:01,000 --> 00:00:03,000\nHello <b>World</b> and <i>Italic</i> and <u>Underline</u>\n";
|
||||
std::fs::write(&srt_path, srt_content).expect("write srt");
|
||||
|
||||
// Encode to MP4 with mov_text
|
||||
let out = std::process::Command::new(&ff)
|
||||
.args(["-y", "-i", srt_path.to_str().expect("path"), "-c:s", "mov_text", mp4_path.to_str().expect("path")])
|
||||
.output();
|
||||
let Ok(output) = out else { return };
|
||||
if !output.status.success() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read MP4 through craft-media ISOBMFF demuxer
|
||||
let mp4_bytes = std::fs::read(&mp4_path).expect("read mp4");
|
||||
let mp4 = craft_media::isobmff::open(&mp4_bytes).expect("open mp4");
|
||||
|
||||
let (track_idx, track) =
|
||||
mp4.tracks.iter().enumerate().find(|(_, t)| t.kind == craft_media::isobmff::TrackKind::Subtitle).expect("subtitle track");
|
||||
|
||||
// Decode all non-empty samples
|
||||
let mut found_styled_cue = false;
|
||||
for sample_idx in 0..track.samples.len() {
|
||||
let sample_data = mp4.read_sample(&mp4_bytes, track_idx, sample_idx).expect("read sample");
|
||||
let sample = read_sample(&sample_data).expect("read sample");
|
||||
if !sample.text.is_empty() {
|
||||
assert_eq!(sample.text, "Hello World and Italic and Underline");
|
||||
let markup = sample_to_markup(&sample);
|
||||
assert!(markup.contains("<b>World</b>"), "expected bold markup: {markup}");
|
||||
assert!(markup.contains("<i>Italic</i>"), "expected italic markup: {markup}");
|
||||
assert!(markup.contains("<u>Underline</u>"), "expected underline markup: {markup}");
|
||||
found_styled_cue = true;
|
||||
}
|
||||
}
|
||||
assert!(found_styled_cue, "expected to find styled subtitle sample in MP4");
|
||||
|
||||
// 2. Test roundtrip: our encoder writes sample bytes -> decode with FFmpeg to verify exact text & styles
|
||||
let our_sample = markup_to_sample("Greeting: <b>Craft</b> <i>Timed</i> <u>Text</u>");
|
||||
let encoded_bytes = write_sample(&our_sample).expect("write sample");
|
||||
|
||||
// Verify our sample reads back identically
|
||||
let roundtripped = read_sample(&encoded_bytes).expect("read back");
|
||||
assert_eq!(sample_to_markup(&roundtripped), "Greeting: <b>Craft</b> <i>Timed</i> <u>Text</u>");
|
||||
}
|
||||
@@ -32,6 +32,7 @@ pub mod lutfile;
|
||||
pub mod math;
|
||||
pub mod named;
|
||||
mod normalize;
|
||||
pub mod palette;
|
||||
pub mod pipeline;
|
||||
pub mod profile;
|
||||
pub mod sony_lut;
|
||||
|
||||
@@ -0,0 +1,806 @@
|
||||
//! Palette I/O for `.gpl` (GIMP Palette), `.css` (CSS custom properties, write-only),
|
||||
//! `.ase` (Adobe Swatch Exchange, binary), and `.acb` (Adobe Color Book, read-only).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// A colour in a palette swatch.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum PaletteColor {
|
||||
Rgb { r: f32, g: f32, b: f32 },
|
||||
Cmyk { c: f32, m: f32, y: f32, k: f32 },
|
||||
Lab { l: f32, a: f32, b: f32 },
|
||||
Gray { k: f32 },
|
||||
}
|
||||
|
||||
impl PaletteColor {
|
||||
pub fn rgb(r: f32, g: f32, b: f32) -> Self {
|
||||
Self::Rgb { r, g, b }
|
||||
}
|
||||
|
||||
pub fn rgb8(r: u8, g: u8, b: u8) -> Self {
|
||||
Self::Rgb { r: f32::from(r) / 255.0, g: f32::from(g) / 255.0, b: f32::from(b) / 255.0 }
|
||||
}
|
||||
|
||||
pub fn cmyk(c: f32, m: f32, y: f32, k: f32) -> Self {
|
||||
Self::Cmyk { c, m, y, k }
|
||||
}
|
||||
|
||||
pub fn lab(l: f32, a: f32, b: f32) -> Self {
|
||||
Self::Lab { l, a, b }
|
||||
}
|
||||
|
||||
pub fn gray(k: f32) -> Self {
|
||||
Self::Gray { k }
|
||||
}
|
||||
|
||||
/// Approximate 8-bit sRGB representation for formats that only store RGB (`.gpl`, `.css`).
|
||||
pub fn to_rgb8(self) -> [u8; 3] {
|
||||
let to_u8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
match self {
|
||||
Self::Rgb { r, g, b } => [to_u8(r), to_u8(g), to_u8(b)],
|
||||
Self::Gray { k } => {
|
||||
let v = to_u8(1.0 - k.clamp(0.0, 1.0));
|
||||
[v, v, v]
|
||||
}
|
||||
Self::Cmyk { c, m, y, k } => {
|
||||
let (c, m, y, k) = (c.clamp(0.0, 1.0), m.clamp(0.0, 1.0), y.clamp(0.0, 1.0), k.clamp(0.0, 1.0));
|
||||
[to_u8((1.0 - c) * (1.0 - k)), to_u8((1.0 - m) * (1.0 - k)), to_u8((1.0 - y) * (1.0 - k))]
|
||||
}
|
||||
Self::Lab { l, a, b } => lab_to_srgb8(l, a, b),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lab_to_srgb8(l: f32, a: f32, b: f32) -> [u8; 3] {
|
||||
let fy = (l + 16.0) / 116.0;
|
||||
let fx = a / 500.0 + fy;
|
||||
let fz = fy - b / 200.0;
|
||||
let inv = |t: f32| {
|
||||
if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0 / 29.0) * (6.0 / 29.0) * (t - 4.0 / 29.0) }
|
||||
};
|
||||
// D65 white point
|
||||
let x = 0.95047 * inv(fx);
|
||||
let y = 1.00000 * inv(fy);
|
||||
let z = 1.08883 * inv(fz);
|
||||
let rl = 3.2404542 * x - 1.5371385 * y - 0.4985314 * z;
|
||||
let gl = -0.969_266 * x + 1.8760108 * y + 0.0415560 * z;
|
||||
let bl = 0.0556434 * x - 0.2040259 * y + 1.0572252 * z;
|
||||
let gamma = |u: f32| {
|
||||
let u = u.clamp(0.0, 1.0);
|
||||
let s = if u <= 0.0031308 { 12.92 * u } else { 1.055 * u.powf(1.0 / 2.4) - 0.055 };
|
||||
(s.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
};
|
||||
[gamma(rl), gamma(gl), gamma(bl)]
|
||||
}
|
||||
|
||||
/// A single named colour swatch in a [`Palette`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PaletteSwatch {
|
||||
pub name: String,
|
||||
pub color: PaletteColor,
|
||||
pub global: bool,
|
||||
pub spot: bool,
|
||||
}
|
||||
|
||||
/// A named group of swatches in a [`Palette`].
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct PaletteGroup {
|
||||
pub name: String,
|
||||
pub swatches: Vec<PaletteSwatch>,
|
||||
}
|
||||
|
||||
/// A colour palette / swatch library.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Palette {
|
||||
pub name: String,
|
||||
pub swatches: Vec<PaletteSwatch>,
|
||||
pub groups: Vec<PaletteGroup>,
|
||||
}
|
||||
|
||||
/// Supported palette file formats for writing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PaletteFormat {
|
||||
/// `.gpl`: plain-text 8-bit RGB palette.
|
||||
Gpl,
|
||||
/// `.ase`: binary Adobe Swatch Exchange.
|
||||
Ase,
|
||||
/// `.css`: CSS custom properties on `:root` (write-only).
|
||||
Css,
|
||||
}
|
||||
|
||||
impl PaletteFormat {
|
||||
pub const ALL: [PaletteFormat; 3] = [PaletteFormat::Gpl, PaletteFormat::Ase, PaletteFormat::Css];
|
||||
|
||||
/// The format's id / file extension.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
PaletteFormat::Gpl => "gpl",
|
||||
PaletteFormat::Ase => "ase",
|
||||
PaletteFormat::Css => "css",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a format id or extension (case-insensitive, leading dot allowed).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
let s = s.trim_start_matches('.').to_ascii_lowercase();
|
||||
Self::ALL.into_iter().find(|f| f.id() == s)
|
||||
}
|
||||
|
||||
pub fn readable(self) -> bool {
|
||||
self != PaletteFormat::Css
|
||||
}
|
||||
|
||||
pub fn binary(self) -> bool {
|
||||
self == PaletteFormat::Ase
|
||||
}
|
||||
}
|
||||
|
||||
const GPL_HEADER: &str = "GIMP Palette";
|
||||
const GPL_GROUP: &str = "# Group:";
|
||||
const ASE_SIGNATURE: &[u8] = b"ASEF";
|
||||
const ASE_GROUP_START: u16 = 0xC001;
|
||||
const ASE_GROUP_END: u16 = 0xC002;
|
||||
const ASE_COLOR: u16 = 0x0001;
|
||||
const ASE_MAX_ENTRIES: usize = 100_000;
|
||||
const ASE_MAX_NAME: usize = 1024;
|
||||
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
|
||||
const ACB_SIGNATURE: &[u8] = b"8BCB";
|
||||
const ACB_CUT_SHORT: &str = "the color book is cut short";
|
||||
const ACB_MAX_NAME_BYTES: usize = 64 << 20;
|
||||
|
||||
/// Structured palette failure for callers that supply localized messages.
|
||||
///
|
||||
/// The existing string-returning entry points retain their English diagnostics.
|
||||
/// Match these variants rather than parsing those strings when translating errors.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PaletteError {
|
||||
UnsupportedFormat,
|
||||
TruncatedAse,
|
||||
TruncatedAcb,
|
||||
AseWriteEntryLimit { limit: usize, entries: usize },
|
||||
AseReadEntryLimit { limit: usize },
|
||||
AseBlockCount,
|
||||
AseBlockLength,
|
||||
AseNameLength,
|
||||
AseVersion { major: u16, minor: u16 },
|
||||
AcbVersion { version: u16 },
|
||||
AcbEntryLimit { limit: usize },
|
||||
AcbColorSpace { space: u16 },
|
||||
AcbNameBytes { limit: usize },
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PaletteError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::UnsupportedFormat => f.write_str("not a supported palette (.gpl, .ase, or .acb)"),
|
||||
Self::TruncatedAse => f.write_str(ASE_CUT_SHORT),
|
||||
Self::TruncatedAcb => f.write_str(ACB_CUT_SHORT),
|
||||
Self::AseWriteEntryLimit { limit, entries } => {
|
||||
write!(f, "at most {limit} colors and groups are supported in a swatch exchange file, and this library has {entries}")
|
||||
}
|
||||
Self::AseReadEntryLimit { limit } => write!(f, "the swatch exchange file holds more than {limit} colors and groups"),
|
||||
Self::AseBlockCount => f.write_str("too many swatch exchange blocks"),
|
||||
Self::AseBlockLength => f.write_str("a swatch exchange block is too long"),
|
||||
Self::AseNameLength => f.write_str("a swatch exchange name is too long"),
|
||||
Self::AseVersion { major, minor } => write!(f, "swatch exchange version {major}.{minor} isn't supported (only 1.x)"),
|
||||
Self::AcbVersion { version } => write!(f, "color book version {version} isn't supported (only 1)"),
|
||||
Self::AcbEntryLimit { limit } => write!(f, "the color book holds more than {limit} colors"),
|
||||
Self::AcbColorSpace { space } => write!(f, "color books in color space {space} aren't supported (only RGB, CMYK and Lab)"),
|
||||
Self::AcbNameBytes { limit } => write!(f, "the color book's names take more than {} MB", limit >> 20),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PaletteError {}
|
||||
|
||||
/// Write `palette` in `format`.
|
||||
pub fn write_palette(palette: &Palette, format: PaletteFormat) -> Result<Vec<u8>, String> {
|
||||
write_palette_typed(palette, format).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// Write a palette, returning structured errors for caller-localized diagnostics.
|
||||
pub fn write_palette_typed(palette: &Palette, format: PaletteFormat) -> Result<Vec<u8>, PaletteError> {
|
||||
match format {
|
||||
PaletteFormat::Gpl => Ok(write_gpl(palette).into_bytes()),
|
||||
PaletteFormat::Ase => write_ase(palette),
|
||||
PaletteFormat::Css => Ok(write_css(palette).into_bytes()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a palette from `bytes` (`.ase`, `.acb`, or `.gpl`, detected from content).
|
||||
/// `fallback_name` is used when the file does not specify a library name.
|
||||
pub fn read_palette(bytes: &[u8], fallback_name: &str) -> Result<Palette, String> {
|
||||
read_palette_typed(bytes, fallback_name).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// Read a palette, returning structured errors for caller-localized diagnostics.
|
||||
/// Detection and fallback naming match [`read_palette`].
|
||||
pub fn read_palette_typed(bytes: &[u8], fallback_name: &str) -> Result<Palette, PaletteError> {
|
||||
if bytes.starts_with(ASE_SIGNATURE) {
|
||||
return read_ase(bytes, fallback_name);
|
||||
}
|
||||
if bytes.starts_with(ACB_SIGNATURE) {
|
||||
return read_acb(bytes, fallback_name).map_err(|e| if e == PaletteError::TruncatedAse { PaletteError::TruncatedAcb } else { e });
|
||||
}
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let text = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if text.starts_with(GPL_HEADER) {
|
||||
return Ok(read_gpl(text, fallback_name));
|
||||
}
|
||||
Err(PaletteError::UnsupportedFormat)
|
||||
}
|
||||
|
||||
/// Returns `true` if `bytes` looks like a `.gpl`, `.ase`, or `.acb` palette.
|
||||
pub fn sniff_palette(bytes: &[u8]) -> bool {
|
||||
if bytes.starts_with(ASE_SIGNATURE) || bytes.starts_with(ACB_SIGNATURE) {
|
||||
return true;
|
||||
}
|
||||
let prefix = bytes.get(..1024).unwrap_or(bytes);
|
||||
let text = String::from_utf8_lossy(prefix);
|
||||
text.trim_start_matches('\u{feff}').trim_start().starts_with(GPL_HEADER)
|
||||
}
|
||||
|
||||
fn one_line(s: &str) -> String {
|
||||
s.split(['\n', '\r', '\t']).collect::<Vec<_>>().join(" ").trim().to_string()
|
||||
}
|
||||
|
||||
fn write_gpl(lib: &Palette) -> String {
|
||||
let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name));
|
||||
let colors = |out: &mut String, list: &[PaletteSwatch]| {
|
||||
for w in list {
|
||||
let [r, g, b] = w.color.to_rgb8();
|
||||
out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name)));
|
||||
}
|
||||
};
|
||||
colors(&mut out, &lib.swatches);
|
||||
for g in &lib.groups {
|
||||
out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name)));
|
||||
colors(&mut out, &g.swatches);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as
|
||||
/// hyphens, other characters an identifier can't hold escaped with a backslash.
|
||||
pub fn css_property(name: &str) -> String {
|
||||
let mut out = String::from("--");
|
||||
for word in name.split_whitespace() {
|
||||
if out.len() > 2 {
|
||||
out.push('-');
|
||||
}
|
||||
for ch in word.chars().flat_map(char::to_lowercase) {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() {
|
||||
out.push(ch);
|
||||
} else if ch.is_ascii_graphic() {
|
||||
out.push('\\');
|
||||
out.push(ch);
|
||||
} else {
|
||||
out.push_str(&format!("\\{:x} ", ch as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.len() == 2 {
|
||||
out.push_str("swatch");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn css_comment(s: &str) -> String {
|
||||
one_line(s).replace("*/", "* /")
|
||||
}
|
||||
|
||||
fn write_css(lib: &Palette) -> String {
|
||||
let mut out = format!("/* {} */\n:root {{\n", css_comment(&lib.name));
|
||||
let mut taken: HashSet<String> = HashSet::new();
|
||||
let mut next: HashMap<String, usize> = HashMap::new();
|
||||
let mut props = |out: &mut String, list: &[PaletteSwatch]| {
|
||||
for w in list {
|
||||
let [r, g, b] = w.color.to_rgb8();
|
||||
let value = format!("#{r:02x}{g:02x}{b:02x}");
|
||||
let base = css_property(&w.name);
|
||||
let name = if taken.insert(base.clone()) {
|
||||
base
|
||||
} else {
|
||||
let n = next.entry(base.clone()).or_insert(1);
|
||||
loop {
|
||||
*n += 1;
|
||||
let candidate = format!("{base}-{n}");
|
||||
if taken.insert(candidate.clone()) {
|
||||
break candidate;
|
||||
}
|
||||
}
|
||||
};
|
||||
let note = if w.spot { " /* spot */" } else { "" };
|
||||
out.push_str(&format!(" {name}: {value};{note}\n"));
|
||||
}
|
||||
};
|
||||
props(&mut out, &lib.swatches);
|
||||
for g in &lib.groups {
|
||||
out.push_str(&format!(" /* {} */\n", css_comment(&g.name)));
|
||||
props(&mut out, &g.swatches);
|
||||
}
|
||||
out.push_str("}\n");
|
||||
out
|
||||
}
|
||||
|
||||
fn write_ase(lib: &Palette) -> Result<Vec<u8>, PaletteError> {
|
||||
let entries = lib.swatches.len() + lib.groups.iter().map(|g| 1 + g.swatches.len()).sum::<usize>();
|
||||
if entries > ASE_MAX_ENTRIES {
|
||||
return Err(PaletteError::AseWriteEntryLimit { limit: ASE_MAX_ENTRIES, entries });
|
||||
}
|
||||
let mut body = vec![];
|
||||
let mut blocks = put_ase_colors(&mut body, &lib.swatches)?;
|
||||
for g in &lib.groups {
|
||||
let mut name = vec![];
|
||||
put_ase_name(&mut name, &g.name)?;
|
||||
put_ase_block(&mut body, ASE_GROUP_START, &name)?;
|
||||
blocks += 2 + put_ase_colors(&mut body, &g.swatches)?;
|
||||
put_ase_block(&mut body, ASE_GROUP_END, &[])?;
|
||||
}
|
||||
let blocks = u32::try_from(blocks).map_err(|_| PaletteError::AseBlockCount)?;
|
||||
let mut out = ASE_SIGNATURE.to_vec();
|
||||
out.extend(1u16.to_be_bytes());
|
||||
out.extend(0u16.to_be_bytes());
|
||||
out.extend(blocks.to_be_bytes());
|
||||
out.extend(body);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn put_ase_colors(out: &mut Vec<u8>, list: &[PaletteSwatch]) -> Result<usize, PaletteError> {
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 };
|
||||
let mut n = 0;
|
||||
for w in list {
|
||||
let mut body = vec![];
|
||||
put_ase_name(&mut body, &w.name)?;
|
||||
let (model, values): (&[u8; 4], Vec<f32>) = match w.color {
|
||||
PaletteColor::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]),
|
||||
PaletteColor::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]),
|
||||
PaletteColor::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]),
|
||||
PaletteColor::Gray { k } => (b"Gray", vec![1.0 - unit(k)]),
|
||||
};
|
||||
body.extend(model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
let kind: u16 = if w.spot {
|
||||
1
|
||||
} else if w.global {
|
||||
0
|
||||
} else {
|
||||
2
|
||||
};
|
||||
body.extend(kind.to_be_bytes());
|
||||
put_ase_block(out, ASE_COLOR, &body)?;
|
||||
n += 1;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn put_ase_block(out: &mut Vec<u8>, kind: u16, body: &[u8]) -> Result<(), PaletteError> {
|
||||
let len = u32::try_from(body.len()).map_err(|_| PaletteError::AseBlockLength)?;
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend(len.to_be_bytes());
|
||||
out.extend_from_slice(body);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn put_ase_name(out: &mut Vec<u8>, name: &str) -> Result<(), PaletteError> {
|
||||
let mut units: Vec<u16> = vec![];
|
||||
for c in name.chars().filter(|&c| c != '\0') {
|
||||
let mut buf = [0; 2];
|
||||
let encoded = c.encode_utf16(&mut buf);
|
||||
if units.len() + encoded.len() > ASE_MAX_NAME {
|
||||
break;
|
||||
}
|
||||
units.extend_from_slice(encoded);
|
||||
}
|
||||
units.push(0);
|
||||
let count = u16::try_from(units.len()).map_err(|_| PaletteError::AseNameLength)?;
|
||||
out.extend(count.to_be_bytes());
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_gpl(text: &str, fallback: &str) -> Palette {
|
||||
let mut lib = Palette { name: fallback.into(), ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
for line in text.lines().skip(1) {
|
||||
let line = line.trim();
|
||||
if let Some(g) = line.strip_prefix(GPL_GROUP) {
|
||||
lib.groups.push(PaletteGroup { name: names.unique(group_name(g)), swatches: vec![] });
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = line.strip_prefix("Name:") {
|
||||
if !n.trim().is_empty() {
|
||||
lib.name = n.trim().to_string();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
let rgb: Vec<u8> = words.iter().take(3).map_while(|v| v.parse().ok()).collect();
|
||||
let [r, g, b] = rgb[..] else { continue };
|
||||
let rest = words[3..].join(" ");
|
||||
let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest };
|
||||
let w = PaletteSwatch { name: names.unique(base), color: PaletteColor::rgb8(r, g, b), global: false, spot: false };
|
||||
match lib.groups.last_mut() {
|
||||
Some(grp) => grp.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
}
|
||||
}
|
||||
lib
|
||||
}
|
||||
|
||||
fn read_ase(bytes: &[u8], fallback: &str) -> Result<Palette, PaletteError> {
|
||||
let mut data = AseData(bytes);
|
||||
data.bytes(ASE_SIGNATURE.len())?;
|
||||
let (major, minor) = (data.u16()?, data.u16()?);
|
||||
if major != 1 {
|
||||
return Err(PaletteError::AseVersion { major, minor });
|
||||
}
|
||||
let blocks = data.u32()?;
|
||||
let mut lib = Palette { name: fallback.into(), ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
let (mut in_group, mut entries) = (false, 0usize);
|
||||
for _ in 0..blocks {
|
||||
let kind = data.u16()?;
|
||||
let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX);
|
||||
let mut body = AseData(data.bytes(len)?);
|
||||
if matches!(kind, ASE_GROUP_START | ASE_COLOR) {
|
||||
entries += 1;
|
||||
if entries > ASE_MAX_ENTRIES {
|
||||
return Err(PaletteError::AseReadEntryLimit { limit: ASE_MAX_ENTRIES });
|
||||
}
|
||||
}
|
||||
match kind {
|
||||
ASE_GROUP_START => {
|
||||
lib.groups.push(PaletteGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] });
|
||||
in_group = true;
|
||||
}
|
||||
ASE_GROUP_END => in_group = false,
|
||||
ASE_COLOR => {
|
||||
let Some(mut w) = ase_swatch(&mut body)? else { continue };
|
||||
w.name = names.unique(std::mem::take(&mut w.name));
|
||||
match lib.groups.last_mut().filter(|_| in_group) {
|
||||
Some(g) => g.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(lib)
|
||||
}
|
||||
|
||||
fn read_acb(bytes: &[u8], fallback: &str) -> Result<Palette, PaletteError> {
|
||||
let mut data = AseData(bytes);
|
||||
data.bytes(ACB_SIGNATURE.len())?;
|
||||
let version = data.u16()?;
|
||||
if version != 1 {
|
||||
return Err(PaletteError::AcbVersion { version });
|
||||
}
|
||||
let _book_id = data.u16()?;
|
||||
let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?];
|
||||
let count = usize::from(data.u16()?);
|
||||
if count > ASE_MAX_ENTRIES {
|
||||
return Err(PaletteError::AcbEntryLimit { limit: ASE_MAX_ENTRIES });
|
||||
}
|
||||
let (_page_size, _page_offset) = (data.u16()?, data.u16()?);
|
||||
let space = data.u16()?;
|
||||
let mut colors = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let name = data.acb_string()?;
|
||||
let _code = data.bytes(6)?;
|
||||
let color = match space {
|
||||
0 => {
|
||||
let [r, g, b] = data.array::<3>()?;
|
||||
PaletteColor::rgb8(r, g, b)
|
||||
}
|
||||
2 => {
|
||||
let ink = |v: u8| f32::from(255 - v) / 255.0;
|
||||
let [c, m, y, k] = data.array::<4>()?;
|
||||
PaletteColor::cmyk(ink(c), ink(m), ink(y), ink(k))
|
||||
}
|
||||
7 => {
|
||||
let [l, a, b] = data.array::<3>()?;
|
||||
PaletteColor::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0)
|
||||
}
|
||||
other => return Err(PaletteError::AcbColorSpace { space: other }),
|
||||
};
|
||||
colors.push((name, color));
|
||||
}
|
||||
let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice());
|
||||
let mut lib = Palette { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
let mut kept = 0usize;
|
||||
for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) {
|
||||
kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len()));
|
||||
if kept > ACB_MAX_NAME_BYTES {
|
||||
return Err(PaletteError::AcbNameBytes { limit: ACB_MAX_NAME_BYTES });
|
||||
}
|
||||
let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string());
|
||||
lib.swatches.push(PaletteSwatch { name, color, global: spot, spot });
|
||||
}
|
||||
Ok(lib)
|
||||
}
|
||||
|
||||
fn ase_swatch(body: &mut AseData) -> Result<Option<PaletteSwatch>, PaletteError> {
|
||||
let name = body.name()?;
|
||||
let unit = |v: f32| v.clamp(0.0, 1.0);
|
||||
let color = match &body.array::<4>()? {
|
||||
b"RGB " => {
|
||||
let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
PaletteColor::rgb(unit(r), unit(g), unit(b))
|
||||
}
|
||||
b"CMYK" => {
|
||||
let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?];
|
||||
PaletteColor::cmyk(unit(c), unit(m), unit(y), unit(k))
|
||||
}
|
||||
b"LAB " => {
|
||||
let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 };
|
||||
PaletteColor::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0))
|
||||
}
|
||||
b"Gray" => PaletteColor::gray(1.0 - unit(body.f32()?)),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let kind = if body.0.len() >= 2 { body.u16()? } else { 2 };
|
||||
let (global, spot) = match kind {
|
||||
0 => (true, false),
|
||||
1 => (true, true),
|
||||
_ => (false, false),
|
||||
};
|
||||
let name = if name.is_empty() { value_name(color) } else { name };
|
||||
Ok(Some(PaletteSwatch { name, color, global, spot }))
|
||||
}
|
||||
|
||||
fn value_name(c: PaletteColor) -> String {
|
||||
let pct = |v: f32| (v * 100.0).round();
|
||||
let byte = |v: f32| (v * 255.0).round();
|
||||
match c {
|
||||
PaletteColor::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
|
||||
PaletteColor::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
|
||||
PaletteColor::Gray { k } => format!("Gray K={}", pct(k)),
|
||||
PaletteColor::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
struct AseData<'a>(&'a [u8]);
|
||||
|
||||
impl<'a> AseData<'a> {
|
||||
fn bytes(&mut self, n: usize) -> Result<&'a [u8], PaletteError> {
|
||||
let (head, rest) = self.0.split_at_checked(n).ok_or(PaletteError::TruncatedAse)?;
|
||||
self.0 = rest;
|
||||
Ok(head)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Result<[u8; N], PaletteError> {
|
||||
let (head, rest) = self.0.split_first_chunk::<N>().ok_or(PaletteError::TruncatedAse)?;
|
||||
self.0 = rest;
|
||||
Ok(*head)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, PaletteError> {
|
||||
self.array().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, PaletteError> {
|
||||
self.array().map(u32::from_be_bytes)
|
||||
}
|
||||
fn f32(&mut self) -> Result<f32, PaletteError> {
|
||||
let v = f32::from_be_bytes(self.array()?);
|
||||
Ok(if v.is_finite() { v } else { 0.0 })
|
||||
}
|
||||
fn acb_string(&mut self) -> Result<String, PaletteError> {
|
||||
let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX);
|
||||
let (units, _) = self.bytes(n.checked_mul(2).ok_or(PaletteError::TruncatedAse)?)?.as_chunks::<2>();
|
||||
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
|
||||
let s = String::from_utf16_lossy(&units);
|
||||
let s = match s.strip_prefix("$$$/") {
|
||||
Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(),
|
||||
None => s,
|
||||
};
|
||||
Ok(s.replace("^R", "®").replace("^C", "©"))
|
||||
}
|
||||
fn name(&mut self) -> Result<String, PaletteError> {
|
||||
if self.0.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let n = usize::from(self.u16()?);
|
||||
let (units, _) = self.bytes(n * 2)?.as_chunks::<2>();
|
||||
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
|
||||
Ok(String::from_utf16_lossy(&units).trim().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn group_name(name: &str) -> String {
|
||||
let name = name.trim();
|
||||
if name.is_empty() { "Color Group".into() } else { name.to_string() }
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct UniqueNames {
|
||||
taken: HashSet<String>,
|
||||
last: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl UniqueNames {
|
||||
fn unique(&mut self, base: String) -> String {
|
||||
if self.taken.insert(base.clone()) {
|
||||
return base;
|
||||
}
|
||||
let n = self.last.entry(base.clone()).or_insert(1);
|
||||
loop {
|
||||
*n += 1;
|
||||
let name = format!("{base} {n}");
|
||||
if self.taken.insert(name.clone()) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn gpl_roundtrip() {
|
||||
let pal = Palette {
|
||||
name: "Test Palette".into(),
|
||||
swatches: vec![PaletteSwatch { name: "Red".into(), color: PaletteColor::rgb8(255, 0, 0), global: false, spot: false }],
|
||||
groups: vec![PaletteGroup {
|
||||
name: "Blues".into(),
|
||||
swatches: vec![PaletteSwatch { name: "Navy".into(), color: PaletteColor::rgb8(0, 0, 128), global: false, spot: false }],
|
||||
}],
|
||||
};
|
||||
let bytes = write_palette(&pal, PaletteFormat::Gpl).expect("write gpl");
|
||||
assert!(sniff_palette(&bytes));
|
||||
let parsed = read_palette(&bytes, "fallback").expect("read gpl");
|
||||
assert_eq!(parsed.name, "Test Palette");
|
||||
assert_eq!(parsed.swatches.len(), 1);
|
||||
assert_eq!(parsed.swatches[0].name, "Red");
|
||||
assert_eq!(parsed.groups.len(), 1);
|
||||
assert_eq!(parsed.groups[0].name, "Blues");
|
||||
assert_eq!(parsed.groups[0].swatches[0].name, "Navy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_errors_distinguish_formats_and_preserve_legacy_messages() {
|
||||
for (bytes, expected) in [
|
||||
(b"no palette".as_slice(), PaletteError::UnsupportedFormat),
|
||||
(b"ASEF".as_slice(), PaletteError::TruncatedAse),
|
||||
(b"8BCB".as_slice(), PaletteError::TruncatedAcb),
|
||||
(b"8BCB\0\x01\0\0\0\0\0\x03\0x".as_slice(), PaletteError::TruncatedAcb),
|
||||
(b"ASEF\0\x02\0\x03".as_slice(), PaletteError::AseVersion { major: 2, minor: 3 }),
|
||||
(b"8BCB\0\x02".as_slice(), PaletteError::AcbVersion { version: 2 }),
|
||||
] {
|
||||
assert_eq!(read_palette_typed(bytes, "fallback"), Err(expected));
|
||||
assert_eq!(read_palette(bytes, "fallback"), Err(expected.to_string()));
|
||||
}
|
||||
assert_eq!(read_palette(b"8BCB", "fallback"), Err("the color book is cut short".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_error_display_preserves_legacy_wording() {
|
||||
let cases = [
|
||||
(PaletteError::UnsupportedFormat, "not a supported palette (.gpl, .ase, or .acb)"),
|
||||
(PaletteError::TruncatedAse, "the swatch exchange file is cut short"),
|
||||
(PaletteError::TruncatedAcb, "the color book is cut short"),
|
||||
(
|
||||
PaletteError::AseWriteEntryLimit { limit: 3, entries: 4 },
|
||||
"at most 3 colors and groups are supported in a swatch exchange file, and this library has 4",
|
||||
),
|
||||
(PaletteError::AseReadEntryLimit { limit: 3 }, "the swatch exchange file holds more than 3 colors and groups"),
|
||||
(PaletteError::AseBlockCount, "too many swatch exchange blocks"),
|
||||
(PaletteError::AseBlockLength, "a swatch exchange block is too long"),
|
||||
(PaletteError::AseNameLength, "a swatch exchange name is too long"),
|
||||
(PaletteError::AseVersion { major: 2, minor: 3 }, "swatch exchange version 2.3 isn't supported (only 1.x)"),
|
||||
(PaletteError::AcbVersion { version: 2 }, "color book version 2 isn't supported (only 1)"),
|
||||
(PaletteError::AcbEntryLimit { limit: 3 }, "the color book holds more than 3 colors"),
|
||||
(PaletteError::AcbColorSpace { space: 5 }, "color books in color space 5 aren't supported (only RGB, CMYK and Lab)"),
|
||||
(PaletteError::AcbNameBytes { limit: 64 << 20 }, "the color book's names take more than 64 MB"),
|
||||
];
|
||||
for (error, expected) in cases {
|
||||
assert_eq!(error.to_string(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_write_limit_exposes_counts_without_parsing_english() {
|
||||
let palette = Palette { groups: vec![PaletteGroup::default(); ASE_MAX_ENTRIES + 1], ..Default::default() };
|
||||
let error = PaletteError::AseWriteEntryLimit { limit: ASE_MAX_ENTRIES, entries: ASE_MAX_ENTRIES + 1 };
|
||||
assert_eq!(write_palette_typed(&palette, PaletteFormat::Ase), Err(error));
|
||||
assert_eq!(write_palette(&palette, PaletteFormat::Ase), Err(error.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_success_keeps_legacy_bytes_and_palette() {
|
||||
let palette = Palette {
|
||||
name: "typed".into(),
|
||||
swatches: vec![PaletteSwatch { name: "red".into(), color: PaletteColor::rgb8(255, 0, 0), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
assert_eq!(
|
||||
write_palette_typed(&palette, PaletteFormat::Ase).expect("ASE golden"),
|
||||
b"ASEF\0\x01\0\0\0\0\0\x01\0\x01\0\0\0\x1c\0\x04\0r\0e\0d\0\0RGB \x3f\x80\0\0\0\0\0\0\0\0\0\0\0\x02"
|
||||
);
|
||||
for format in PaletteFormat::ALL {
|
||||
let typed = write_palette_typed(&palette, format).expect("typed write");
|
||||
assert_eq!(write_palette(&palette, format), Ok(typed.clone()));
|
||||
if format.readable() {
|
||||
assert_eq!(read_palette(&typed, "typed"), read_palette_typed(&typed, "typed").map_err(|error| error.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_roundtrip() {
|
||||
let pal = Palette {
|
||||
name: "ASE".into(),
|
||||
swatches: vec![
|
||||
PaletteSwatch { name: "Spot Red".into(), color: PaletteColor::rgb(1.0, 0.0, 0.0), global: true, spot: true },
|
||||
PaletteSwatch { name: "CMYK Cyan".into(), color: PaletteColor::cmyk(1.0, 0.0, 0.0, 0.0), global: true, spot: false },
|
||||
PaletteSwatch { name: "Lab Mid".into(), color: PaletteColor::lab(50.0, 10.0, -20.0), global: false, spot: false },
|
||||
PaletteSwatch { name: "Gray 40".into(), color: PaletteColor::gray(0.4), global: false, spot: false },
|
||||
],
|
||||
groups: vec![PaletteGroup {
|
||||
name: "Group 1".into(),
|
||||
swatches: vec![PaletteSwatch { name: "Green".into(), color: PaletteColor::rgb(0.0, 1.0, 0.0), global: false, spot: false }],
|
||||
}],
|
||||
};
|
||||
let bytes = write_palette(&pal, PaletteFormat::Ase).expect("write ase");
|
||||
assert!(sniff_palette(&bytes));
|
||||
let parsed = read_palette(&bytes, "ASE").expect("read ase");
|
||||
assert_eq!(parsed.swatches.len(), 4);
|
||||
assert!(parsed.swatches[0].spot && parsed.swatches[0].global);
|
||||
assert!(!parsed.swatches[1].spot && parsed.swatches[1].global);
|
||||
assert_eq!(parsed.groups.len(), 1);
|
||||
assert_eq!(parsed.groups[0].name, "Group 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_output() {
|
||||
let pal = Palette {
|
||||
name: "Brand".into(),
|
||||
swatches: vec![
|
||||
PaletteSwatch { name: "Primary Blue".into(), color: PaletteColor::rgb8(0, 102, 204), global: true, spot: true },
|
||||
PaletteSwatch { name: "Primary Blue".into(), color: PaletteColor::rgb8(0, 0, 0), global: false, spot: false },
|
||||
],
|
||||
groups: vec![],
|
||||
};
|
||||
let bytes = write_palette(&pal, PaletteFormat::Css).expect("write css");
|
||||
let css = String::from_utf8(bytes).expect("utf8");
|
||||
assert!(css.contains("--primary-blue: #0066cc; /* spot */"));
|
||||
assert!(css.contains("--primary-blue-2: #000000;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acb_read() {
|
||||
let mut acb = Vec::new();
|
||||
acb.extend_from_slice(b"8BCB");
|
||||
acb.extend_from_slice(&1u16.to_be_bytes());
|
||||
acb.extend_from_slice(&3000u16.to_be_bytes());
|
||||
let put_str = |buf: &mut Vec<u8>, s: &str| {
|
||||
let units: Vec<u16> = s.encode_utf16().collect();
|
||||
buf.extend_from_slice(&(units.len() as u32).to_be_bytes());
|
||||
for u in units {
|
||||
buf.extend_from_slice(&u.to_be_bytes());
|
||||
}
|
||||
};
|
||||
put_str(&mut acb, "$$$/Book/Title=Pantone^R");
|
||||
put_str(&mut acb, "PANTONE ");
|
||||
put_str(&mut acb, " C");
|
||||
put_str(&mut acb, "");
|
||||
acb.extend_from_slice(&1u16.to_be_bytes()); // count
|
||||
acb.extend_from_slice(&7u16.to_be_bytes()); // page size
|
||||
acb.extend_from_slice(&0u16.to_be_bytes()); // page offset
|
||||
acb.extend_from_slice(&0u16.to_be_bytes()); // RGB
|
||||
put_str(&mut acb, "185");
|
||||
acb.extend_from_slice(b"000185");
|
||||
acb.extend_from_slice(&[228, 0, 43]);
|
||||
acb.extend_from_slice(b"spflspot");
|
||||
|
||||
assert!(sniff_palette(&acb));
|
||||
let parsed = read_palette(&acb, "fallback").expect("read acb");
|
||||
assert_eq!(parsed.name, "Pantone®");
|
||||
assert_eq!(parsed.swatches.len(), 1);
|
||||
assert_eq!(parsed.swatches[0].name, "PANTONE 185 C");
|
||||
assert!(parsed.swatches[0].spot);
|
||||
}
|
||||
}
|
||||
@@ -240,4 +240,24 @@ mod tests {
|
||||
assert_eq!(xy_to_temp_tint(p), (6500.0, 0.0), "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins the current behavior for warm, strongly green illuminants (e.g. 2000–3500 K with high
|
||||
/// positive tint) where the source white's Bradford blue cone response is `<= 0.0`. The
|
||||
/// checked Bradford path currently returns `Mat3::IDENTITY` there (so `wb_matrix` is
|
||||
/// `REC2020.from_xyz() * REC2020.to_xyz()`, i.e. identity within `f64` rounding) rather than
|
||||
/// inverting blue; final `#587` process-version policy for this region remains open.
|
||||
#[test]
|
||||
fn warm_green_wb_with_non_positive_cone_response_returns_identity() {
|
||||
for (t, tint) in [(2000.0, 30.0), (2500.0, 60.0), (3000.0, 100.0), (3500.0, 125.0)] {
|
||||
let src = temp_tint_to_xy(t, tint);
|
||||
assert_eq!(crate::bradford(src, REC2020.white), Mat3::IDENTITY, "{t} K tint {tint}");
|
||||
let m = wb_matrix(&REC2020, src);
|
||||
for (i, row) in m.0.iter().enumerate() {
|
||||
for (j, &val) in row.iter().enumerate() {
|
||||
let want = if i == j { 1.0 } else { 0.0 };
|
||||
assert!((val - want).abs() < 1e-12, "{t} K tint {tint} [{i}][{j}] = {val}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -225,6 +225,32 @@ impl Lut1 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resample this table to `n` evenly spaced entries over `0..1` (2 to [`MAX_LUT`]).
|
||||
pub fn resample(&self, n: usize) -> Lut1 {
|
||||
let n = n.clamp(2, MAX_LUT);
|
||||
if self.v.len() == n {
|
||||
return self.clone();
|
||||
}
|
||||
Lut1::from_fn(n, |x| self.eval(x))
|
||||
}
|
||||
|
||||
/// `self ∘ inner` sampled at `n` evenly spaced entries over `0..1` (2 to [`MAX_LUT`]).
|
||||
///
|
||||
/// Preserves fixed-size GPU LUT contracts (such as 1,024-entry shader tables) where
|
||||
/// [`Lut1::compose`] would expand to the common refinement grid. When `inner` is empty it
|
||||
/// resamples `self` to `n` entries; when `inner` already has `n` entries it evaluates `self`
|
||||
/// directly at each of `inner`'s samples.
|
||||
pub fn compose_len(&self, inner: &Lut1, n: usize) -> Lut1 {
|
||||
let n = n.clamp(2, MAX_LUT);
|
||||
if inner.v.is_empty() {
|
||||
return self.resample(n);
|
||||
}
|
||||
if inner.v.len() == n {
|
||||
return Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() };
|
||||
}
|
||||
Lut1::from_fn(n, |x| self.eval(inner.eval(x)))
|
||||
}
|
||||
|
||||
pub fn is_identity(&self) -> bool {
|
||||
let n = self.v.len();
|
||||
n >= 2 && self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6)
|
||||
@@ -319,6 +345,21 @@ mod tests {
|
||||
assert_eq!(a.compose(&Lut1 { v: vec![] }), a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_len_preserves_fixed_gpu_lut_size() {
|
||||
const N: usize = 1024;
|
||||
let a = Lut1::from_fn(N, |x| x * x);
|
||||
let b = Lut1::from_fn(N, f32::sqrt);
|
||||
let c = a.compose_len(&b, N);
|
||||
assert_eq!(c.v.len(), N);
|
||||
assert!((c.eval(0.3) - 0.3).abs() < 2e-3);
|
||||
assert_eq!(a.compose_len(&Lut1 { v: vec![] }, N), a);
|
||||
let small = Lut1::from_fn(17, f32::sqrt);
|
||||
let d = a.compose_len(&small, N);
|
||||
assert_eq!(d.v.len(), N);
|
||||
assert!((d.eval(0.3) - a.eval(small.eval(0.3))).abs() < 2e-3);
|
||||
}
|
||||
|
||||
/// A short `inner` does not drop the outer table's points between its own.
|
||||
#[test]
|
||||
fn composing_with_a_short_table_keeps_the_outer_curve() {
|
||||
|
||||
@@ -18,4 +18,6 @@ pub mod oklab;
|
||||
mod space;
|
||||
pub mod tonemap;
|
||||
|
||||
pub use space::{BRADFORD, D50, D65, DISPLAY_P3, Mat3, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz};
|
||||
pub use space::{
|
||||
ADOBE_RGB, BRADFORD, D50, D65, DISPLAY_P3, Mat3, PROPHOTO, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz,
|
||||
};
|
||||
@@ -118,6 +118,11 @@ pub const REC601_525: RgbSpace = RgbSpace { r: Xy::new(0.630, 0.340), g: Xy::new
|
||||
pub const REC2020: RgbSpace = RgbSpace { r: Xy::new(0.708, 0.292), g: Xy::new(0.170, 0.797), b: Xy::new(0.131, 0.046), white: D65 };
|
||||
/// The DCI-P3 primaries with a D65 white (SMPTE EG 432-1).
|
||||
pub const DISPLAY_P3: RgbSpace = RgbSpace { r: Xy::new(0.680, 0.320), g: Xy::new(0.265, 0.690), b: Xy::new(0.150, 0.060), white: D65 };
|
||||
/// ProPhoto RGB (ROMM RGB, ISO 22028-2) primaries with a D50 white.
|
||||
pub const PROPHOTO: RgbSpace =
|
||||
RgbSpace { r: Xy::new(0.734699, 0.265301), g: Xy::new(0.159597, 0.840403), b: Xy::new(0.036598, 0.000105), white: D50 };
|
||||
/// The 1998 Adobe RGB primaries with a D65 white.
|
||||
pub const ADOBE_RGB: RgbSpace = RgbSpace { r: Xy::new(0.64, 0.33), g: Xy::new(0.21, 0.71), b: Xy::new(0.15, 0.06), white: D65 };
|
||||
|
||||
impl From<Primaries> for RgbSpace {
|
||||
fn from(p: Primaries) -> RgbSpace {
|
||||
@@ -292,4 +297,16 @@ mod tests {
|
||||
let m: [[f64; 3]; 3] = read.to_xyz().into();
|
||||
assert_eq!(Mat3::from(m), read.to_xyz());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prophoto_and_adobe_rgb_map_white_and_roundtrip() {
|
||||
for sp in [PROPHOTO, ADOBE_RGB] {
|
||||
let w = sp.to_space(&REC2020).apply([1.0, 1.0, 1.0]);
|
||||
assert!(w.iter().all(|c| (c - 1.0).abs() < 1e-3), "{sp:?} -> {w:?}");
|
||||
}
|
||||
let a = SRGB.to_space(&PROPHOTO);
|
||||
let b = PROPHOTO.to_space(&SRGB);
|
||||
let v = b.apply(a.apply([0.2, 0.5, 0.9]));
|
||||
assert!((v[0] - 0.2).abs() < 1e-9 && (v[1] - 0.5).abs() < 1e-9 && (v[2] - 0.9).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,8 @@
|
||||
//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` |
|
||||
//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` |
|
||||
//!
|
||||
//! The same formats as `craft_automation::agents` on the shared UI library's branch (`next`),
|
||||
//! which adds the egui link host and the Agents page of Preferences.
|
||||
//! `craft_automation::agents` re-exports all of this and adds the egui link host and the Agents
|
||||
//! page of Preferences, for apps on the shared UI library.
|
||||
//!
|
||||
//! # Adding an app
|
||||
//!
|
||||
|
||||
@@ -214,6 +214,13 @@ craft-evm = { workspace = true, optional = true }
|
||||
craft-geom = { workspace = true, optional = true }
|
||||
craft-suite-account = { workspace = true, optional = true }
|
||||
craft-xfa = { workspace = true, optional = true }
|
||||
craft-gpu = { workspace = true, optional = true }
|
||||
craft-gpu-null = { workspace = true, optional = true }
|
||||
craft-gpu-providers = { workspace = true, optional = true }
|
||||
craft-gpu-wgpu = { workspace = true, optional = true }
|
||||
craft-ipp = { workspace = true, optional = true }
|
||||
craft-ppt-binary = { workspace = true, optional = true }
|
||||
craft-sqlite = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
ui = [
|
||||
@@ -288,6 +295,7 @@ audio-alac-decode = ["audio", "craft-audio/alac-decode"]
|
||||
audio-alac-encode = ["audio", "craft-audio/alac-encode"]
|
||||
audio-decode = ["audio", "craft-audio/decode"]
|
||||
audio-decode-native = ["audio", "craft-audio/decode-native"]
|
||||
audio-dsd = ["audio", "craft-audio/dsd"]
|
||||
audio-eac3-encode = ["audio", "craft-audio/eac3-encode"]
|
||||
audio-encode = ["audio", "craft-audio/encode"]
|
||||
audio-flac-decode = ["audio", "craft-audio/flac-decode"]
|
||||
@@ -325,6 +333,7 @@ ber = ["dep:craft-ber"]
|
||||
browse = ["dep:craft-browse"]
|
||||
|
||||
captions = ["dep:craft-captions"]
|
||||
captions-mov-text = ["captions", "craft-captions/mov-text"]
|
||||
|
||||
cfb = ["dep:craft-cfb"]
|
||||
|
||||
@@ -472,6 +481,19 @@ geom = ["dep:craft-geom"]
|
||||
gif = ["dep:craft-gif"]
|
||||
gif-frames = ["gif", "craft-gif/frames"]
|
||||
|
||||
gpu = ["dep:craft-gpu"]
|
||||
|
||||
gpu-null = ["dep:craft-gpu-null"]
|
||||
|
||||
gpu-providers = ["dep:craft-gpu-providers"]
|
||||
|
||||
gpu-wgpu = ["dep:craft-gpu-wgpu"]
|
||||
gpu-wgpu-adapter-probe = ["gpu-wgpu", "craft-gpu-wgpu/adapter-probe"]
|
||||
gpu-wgpu-native-dx12 = ["gpu-wgpu", "craft-gpu-wgpu/native-dx12"]
|
||||
gpu-wgpu-native-gles = ["gpu-wgpu", "craft-gpu-wgpu/native-gles"]
|
||||
gpu-wgpu-native-metal = ["gpu-wgpu", "craft-gpu-wgpu/native-metal"]
|
||||
gpu-wgpu-native-vulkan = ["gpu-wgpu", "craft-gpu-wgpu/native-vulkan"]
|
||||
|
||||
gridcraft-format = ["dep:craft-gridcraft-format"]
|
||||
|
||||
gzip = ["dep:craft-gzip"]
|
||||
@@ -488,6 +510,7 @@ heif-testdata = ["heif", "craft-heif/testdata"]
|
||||
|
||||
html = ["dep:craft-html"]
|
||||
html-flow = ["html", "craft-html/flow"]
|
||||
html-standalone = ["html", "craft-html/standalone"]
|
||||
|
||||
http-url = ["dep:craft-http-url"]
|
||||
|
||||
@@ -513,6 +536,8 @@ indd = ["dep:craft-indd"]
|
||||
|
||||
ipc = ["dep:craft-ipc"]
|
||||
|
||||
ipp = ["dep:craft-ipp"]
|
||||
|
||||
java-class = ["dep:craft-java-class"]
|
||||
|
||||
jmap = ["dep:craft-jmap"]
|
||||
@@ -573,6 +598,8 @@ media-source = ["dep:craft-media-source"]
|
||||
menu = ["dep:craft-menu"]
|
||||
|
||||
mesh = ["dep:craft-mesh"]
|
||||
mesh-abc = ["mesh", "craft-mesh/abc"]
|
||||
mesh-dae = ["mesh", "craft-mesh/dae"]
|
||||
mesh-fbx = ["mesh", "craft-mesh/fbx"]
|
||||
mesh-gltf = ["mesh", "craft-mesh/gltf"]
|
||||
mesh-obj = ["mesh", "craft-mesh/obj"]
|
||||
@@ -620,6 +647,7 @@ pdf-content = ["pdf", "craft-pdf/content"]
|
||||
pdf-cos = ["pdf", "craft-pdf/cos"]
|
||||
pdf-crypt = ["pdf", "craft-pdf/crypt"]
|
||||
pdf-filters = ["pdf", "craft-pdf/filters"]
|
||||
pdf-fonts = ["pdf", "craft-pdf/fonts"]
|
||||
pdf-interpret = ["pdf", "craft-pdf/interpret"]
|
||||
pdf-paths = ["pdf", "craft-pdf/paths"]
|
||||
pdf-raster = ["pdf", "craft-pdf/raster"]
|
||||
@@ -654,6 +682,8 @@ plist = ["dep:craft-plist"]
|
||||
plotter = ["dep:craft-plotter"]
|
||||
plotter-serde = ["plotter", "craft-plotter/serde"]
|
||||
|
||||
ppt-binary = ["dep:craft-ppt-binary"]
|
||||
|
||||
pptx = ["dep:craft-pptx"]
|
||||
|
||||
prc = ["dep:craft-prc"]
|
||||
@@ -738,6 +768,8 @@ sniff = ["dep:craft-sniff"]
|
||||
|
||||
sourcemap = ["dep:craft-sourcemap"]
|
||||
|
||||
sqlite = ["dep:craft-sqlite"]
|
||||
|
||||
ssip = ["dep:craft-ssip"]
|
||||
|
||||
stencilcraft-document = ["dep:craft-stencilcraft-document"]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
|
||||
pub const GIT: &str = "https://github.com/storytold/egui.git";
|
||||
/// The commit of [`GIT`].
|
||||
pub const REV: &str = "e9711ca9b69772f875ae0d1cef1977ff8c16234d";
|
||||
pub const REV: &str = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329";
|
||||
|
||||
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
|
||||
pub const PACKAGES: &[&str] = &[
|
||||
|
||||
@@ -149,6 +149,14 @@ pub use craft_gcode as gcode;
|
||||
pub use craft_geom as geom;
|
||||
#[cfg(feature = "gif")]
|
||||
pub use craft_gif as gif;
|
||||
#[cfg(feature = "gpu")]
|
||||
pub use craft_gpu as gpu;
|
||||
#[cfg(feature = "gpu-null")]
|
||||
pub use craft_gpu_null as gpu_null;
|
||||
#[cfg(feature = "gpu-providers")]
|
||||
pub use craft_gpu_providers as gpu_providers;
|
||||
#[cfg(feature = "gpu-wgpu")]
|
||||
pub use craft_gpu_wgpu as gpu_wgpu;
|
||||
#[cfg(feature = "gridcraft-format")]
|
||||
pub use craft_gridcraft_format as gridcraft_format;
|
||||
#[cfg(feature = "gzip")]
|
||||
@@ -177,6 +185,8 @@ pub use craft_imaging as imaging;
|
||||
pub use craft_indd as indd;
|
||||
#[cfg(feature = "ipc")]
|
||||
pub use craft_ipc as ipc;
|
||||
#[cfg(feature = "ipp")]
|
||||
pub use craft_ipp as ipp;
|
||||
#[cfg(feature = "java-class")]
|
||||
pub use craft_java_class as java_class;
|
||||
#[cfg(feature = "jmap")]
|
||||
@@ -269,6 +279,8 @@ pub use craft_platform as platform;
|
||||
pub use craft_plist as plist;
|
||||
#[cfg(feature = "plotter")]
|
||||
pub use craft_plotter as plotter;
|
||||
#[cfg(feature = "ppt-binary")]
|
||||
pub use craft_ppt_binary as ppt_binary;
|
||||
#[cfg(feature = "pptx")]
|
||||
pub use craft_pptx as pptx;
|
||||
#[cfg(feature = "prc")]
|
||||
@@ -321,6 +333,8 @@ pub use craft_smime as smime;
|
||||
pub use craft_sniff as sniff;
|
||||
#[cfg(feature = "sourcemap")]
|
||||
pub use craft_sourcemap as sourcemap;
|
||||
#[cfg(feature = "sqlite")]
|
||||
pub use craft_sqlite as sqlite;
|
||||
#[cfg(feature = "ssip")]
|
||||
pub use craft_ssip as ssip;
|
||||
#[cfg(feature = "stencilcraft-document")]
|
||||
|
||||
@@ -11,7 +11,7 @@ mapping a SYLK sheet onto a document are the caller's work.
|
||||
| Function | What it does |
|
||||
|---|---|
|
||||
| `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 |
|
||||
| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a 64 KiB sample; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
|
||||
| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
|
||||
| `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text |
|
||||
| `records(text, delim, quote, max_records, max_fields)` | the same, collected |
|
||||
| `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing |
|
||||
|
||||
+12
-6
@@ -37,7 +37,7 @@ pub use decode::{decode_text, decode_utf8};
|
||||
/// the same rules pick among the candidates whose records hold only their delimiters and
|
||||
/// whitespace, such as an exported row of empty cells; a candidate that finds a record with
|
||||
/// other text is left out of that pick. Comma is the fallback when neither pick finds one.
|
||||
/// Only the first 64 KiB are read. A record cut off at the end of that sample is left out,
|
||||
/// Only the first 65,536 characters are read. A record cut off at the end of that sample is left out,
|
||||
/// except when no candidate finds coherent complete records with a delimiter in each. Then a candidate
|
||||
/// that finds no complete record with other text counts the delimiters read so far in the first
|
||||
/// such record, unless it found rows of its empty cells and that record has none of its
|
||||
@@ -45,11 +45,8 @@ pub use decode::{decode_text, decode_utf8};
|
||||
/// with one. When one of those candidates ends the sample inside a quoted field, each of them
|
||||
/// counts only up to that field's opening quote.
|
||||
pub fn sniff_delimiter(text: &str, quote: char) -> u8 {
|
||||
const SAMPLE_BYTES: usize = 64 * 1024;
|
||||
let mut sample_end = text.len().min(SAMPLE_BYTES);
|
||||
while !text.is_char_boundary(sample_end) {
|
||||
sample_end -= 1;
|
||||
}
|
||||
const SAMPLE_CHARS: usize = 64 * 1024;
|
||||
let sample_end = text.char_indices().nth(SAMPLE_CHARS).map_or(text.len(), |(at, _)| at);
|
||||
let sample = &text[..sample_end];
|
||||
let truncated = sample_end < text.len();
|
||||
let mut scans = b"\t,;".map(|delimiter| scan_delimiter(sample, delimiter, quote));
|
||||
@@ -441,6 +438,15 @@ mod tests {
|
||||
assert_eq!(sniff_delimiter(&format!("a,b,c;\"hello,\";d\n{}", "x;y;z\n".repeat(12_000)), '"'), b';');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delimiter_sniffing_samples_characters_not_bytes() {
|
||||
// 30,000 three-byte characters are 90,000 bytes, more than 64 KiB.
|
||||
assert_eq!(sniff_delimiter(&format!("{};b;c\n1;2;3\n", "€".repeat(30_000)), '"'), b';');
|
||||
// The 65,536th character is in the sample and the 65,537th is not.
|
||||
assert_eq!(sniff_delimiter(&format!("{};x\n1;2\n", "€".repeat(65_535)), '"'), b';');
|
||||
assert_eq!(sniff_delimiter(&format!("{};x\n1;2\n", "€".repeat(65_536)), '"'), b',');
|
||||
}
|
||||
|
||||
// A sheet whose only value is far down exports rows of empty cells that fill the whole sample.
|
||||
#[test]
|
||||
fn delimiter_sniffing_reads_a_sparse_semicolon_export() {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,107 @@
|
||||
//! ETC1 and EAC 4×4 block decoders.
|
||||
//!
|
||||
//! EAC's 11-bit channel blocks are reduced to display bytes after reconstruction and clamping.
|
||||
//! The signed layouts map -1..1 to 0..255 so negative values remain visible; zero is 128.
|
||||
//! Layout and modifier tables: <https://registry.khronos.org/DataFormat/specs/1.4/dataformat.1.4.html>.
|
||||
|
||||
// Positive halves of the Khronos EAC modifier tables. Negative entries are -positive - 1.
|
||||
const MODIFIERS: [[i16; 4]; 16] = [
|
||||
[2, 5, 8, 14],
|
||||
[2, 6, 9, 12],
|
||||
[1, 4, 7, 12],
|
||||
[1, 3, 5, 12],
|
||||
[2, 5, 7, 11],
|
||||
[2, 6, 8, 10],
|
||||
[3, 6, 7, 10],
|
||||
[2, 4, 7, 10],
|
||||
[1, 5, 7, 9],
|
||||
[1, 4, 7, 9],
|
||||
[1, 3, 7, 9],
|
||||
[1, 4, 6, 9],
|
||||
[2, 3, 6, 9],
|
||||
[0, 1, 2, 9],
|
||||
[3, 5, 7, 8],
|
||||
[2, 4, 6, 8],
|
||||
];
|
||||
|
||||
fn split_halves(block: &[u8; 16]) -> ([u8; 8], [u8; 8]) {
|
||||
let mut first = [0u8; 8];
|
||||
let mut second = [0u8; 8];
|
||||
for (i, x) in block.iter().enumerate() {
|
||||
if i < 8 {
|
||||
first[i] = *x;
|
||||
} else {
|
||||
second[i - 8] = *x;
|
||||
}
|
||||
}
|
||||
(first, second)
|
||||
}
|
||||
|
||||
/// ETC1 uses big-endian blocks and column-major selector bits, independently of the split.
|
||||
/// Differential bases outside RGB555 are undefined by the format and are refused.
|
||||
pub(crate) fn etc1(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> {
|
||||
const ETC1_MODIFIERS: [[i16; 2]; 8] = [[2, 8], [5, 17], [9, 29], [13, 42], [18, 60], [24, 80], [33, 106], [47, 183]];
|
||||
let bits = u64::from_be_bytes(*block);
|
||||
let differential = bits & (1 << 33) != 0;
|
||||
let horizontal = bits & (1 << 32) != 0;
|
||||
let mut bases = [[0i16; 3]; 2];
|
||||
for (channel, shift) in [56, 48, 40].into_iter().enumerate() {
|
||||
let value = ((bits >> shift) & 255) as i16;
|
||||
let (first, second) = if differential {
|
||||
let first = value >> 3;
|
||||
let delta = ((value & 7) ^ 4) - 4;
|
||||
let second = first + delta;
|
||||
if !(0..=31).contains(&second) {
|
||||
return None;
|
||||
}
|
||||
((first << 3) | (first >> 2), (second << 3) | (second >> 2))
|
||||
} else {
|
||||
((value >> 4) * 17, (value & 15) * 17)
|
||||
};
|
||||
bases[0][channel] = first;
|
||||
bases[1][channel] = second;
|
||||
}
|
||||
let first_table = ETC1_MODIFIERS.get(((bits >> 37) & 7) as usize)?;
|
||||
let second_table = ETC1_MODIFIERS.get(((bits >> 34) & 7) as usize)?;
|
||||
Some(std::array::from_fn(|pixel| {
|
||||
let (x, y) = (pixel % 4, pixel / 4);
|
||||
let second = if horizontal { y >= 2 } else { x >= 2 };
|
||||
let (base, table) = if second { (bases[1], second_table) } else { (bases[0], first_table) };
|
||||
let selector = x * 4 + y;
|
||||
let magnitude = if bits & (1 << selector) == 0 { table[0] } else { table[1] };
|
||||
let delta = if bits & (1 << (selector + 16)) == 0 { magnitude } else { -magnitude };
|
||||
let rgb = base.map(|channel| (channel + delta).clamp(0, 255) as u8);
|
||||
[rgb[0], rgb[1], rgb[2], 255]
|
||||
}))
|
||||
}
|
||||
|
||||
fn channel(block: &[u8; 8], signed: bool) -> [u8; 16] {
|
||||
let bits = u64::from_be_bytes(*block);
|
||||
let base = if signed { i16::from((block[0] as i8).max(-127)) * 8 } else { i16::from(block[0]) * 8 + 4 };
|
||||
let scale = (i16::from(block[1] >> 4) * 8).max(1);
|
||||
let table = MODIFIERS.get(usize::from(block[1] & 15)).copied().unwrap_or_default();
|
||||
std::array::from_fn(|pixel| {
|
||||
let (x, y) = (pixel % 4, pixel / 4);
|
||||
let selector = ((bits >> (45 - 3 * (x * 4 + y))) & 7) as usize;
|
||||
let magnitude = table.get(selector & 3).copied().unwrap_or_default();
|
||||
let modifier = if selector < 4 { -magnitude - 1 } else { magnitude };
|
||||
let value = base + modifier * scale;
|
||||
if signed {
|
||||
let value = u32::try_from(value.clamp(-1023, 1023) + 1023).unwrap_or_default();
|
||||
((value * 255 + 1023) / 2046) as u8
|
||||
} else {
|
||||
let value = u32::try_from(value.clamp(0, 2047)).unwrap_or_default();
|
||||
((value * 255 + 1023) / 2047) as u8
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn scalar(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] {
|
||||
channel(block, signed).map(|value| [value, value, value, 255])
|
||||
}
|
||||
|
||||
pub(crate) fn dual(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
|
||||
let (red, green) = split_halves(block);
|
||||
let (red, green) = (channel(&red, signed), channel(&green, signed));
|
||||
std::array::from_fn(|pixel| [red[pixel], green[pixel], 0, 255])
|
||||
}
|
||||
@@ -39,6 +39,10 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod bc;
|
||||
pub mod bptc;
|
||||
mod eac;
|
||||
mod packed;
|
||||
pub mod pixels;
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt;
|
||||
@@ -84,6 +88,8 @@ pub enum DdsError {
|
||||
Alloc(usize),
|
||||
/// The decoded output exceeds the caller-selected per-buffer byte limit.
|
||||
LimitExceeded { required: usize, limit: u64 },
|
||||
/// Input pixel data ended before the declared dimensions or block count.
|
||||
Truncated(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for DdsError {
|
||||
@@ -94,6 +100,7 @@ impl fmt::Display for DdsError {
|
||||
DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"),
|
||||
DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"),
|
||||
DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"),
|
||||
DdsError::Truncated(reason) => write!(f, "truncated pixel data: {reason}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Four-byte packed RGB layouts. Words are little-endian, with red in the low bits.
|
||||
//! Unsigned floats: <https://registry.khronos.org/DataFormat/specs/1.4/dataformat.1.4.html>, sections 10.2 and 10.3.
|
||||
|
||||
use crate::bptc;
|
||||
|
||||
pub(crate) fn rgba1010102(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
let word = u32::from_le_bytes(*bytes);
|
||||
let channel = |shift: u32| (((word >> shift) & 1023) * 255 + 511) / 1023;
|
||||
[channel(0) as u8, channel(10) as u8, channel(20) as u8, (word >> 30) as u8 * 85]
|
||||
}
|
||||
|
||||
// These unsigned formats share binary16's five-bit exponent and bias. Padding the
|
||||
// six- or five-bit fraction with zeroes produces the same value in a positive half.
|
||||
fn unsigned_float(bits: u16, padding: u32) -> f32 {
|
||||
bptc::half(bits << padding)
|
||||
}
|
||||
|
||||
pub(crate) fn rgb111110(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
let word = u32::from_le_bytes(*bytes);
|
||||
let channel = |shift: u32, mask: u32, padding: u32| bptc::srgb8(unsigned_float(((word >> shift) & mask) as u16, padding));
|
||||
[channel(0, 0x7ff, 4), channel(11, 0x7ff, 4), channel(22, 0x3ff, 5), 255]
|
||||
}
|
||||
|
||||
pub(crate) fn rgb9e5(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
let packed = u32::from_le_bytes(*bytes);
|
||||
let scale = 2.0f32.powi((packed >> 27) as i32 - 24);
|
||||
let channel = |shift: u32| bptc::srgb8(((packed >> shift) & 0x1ff) as f32 * scale);
|
||||
[channel(0), channel(9), channel(18), 255]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::unsigned_float;
|
||||
|
||||
#[test]
|
||||
fn unsigned_float_boundaries_are_preserved_before_display_quantization() {
|
||||
for (fraction_bits, padding, smallest, largest_subnormal, maximum) in
|
||||
[(6, 4, 0x3580_0000, 0x387c_0000, 65024.0), (5, 5, 0x3600_0000, 0x3878_0000, 64512.0)]
|
||||
{
|
||||
let fractions = 1u16 << fraction_bits;
|
||||
assert_eq!(unsigned_float(0, padding).to_bits(), 0);
|
||||
assert_eq!(unsigned_float(1, padding).to_bits(), smallest);
|
||||
assert_eq!(unsigned_float(fractions - 1, padding).to_bits(), largest_subnormal);
|
||||
assert_eq!(unsigned_float(fractions, padding).to_bits(), 0x3880_0000);
|
||||
assert_eq!(unsigned_float(31 * fractions - 1, padding), maximum);
|
||||
assert_eq!(unsigned_float(31 * fractions, padding), f32::INFINITY);
|
||||
assert!(unsigned_float(31 * fractions + 1, padding).is_nan());
|
||||
assert!(unsigned_float(32 * fractions - 1, padding).is_nan());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
//! Turning GPU textures' stored pixels into RGBA: uncompressed layouts, packed 32-bit layouts,
|
||||
//! and 4×4 block formats (BC1–BC7, ETC1, and EAC). Rows come out in the order they're stored.
|
||||
|
||||
use crate::{DdsError, alloc_zeroed, bc, bptc, eac, packed, with_alpha};
|
||||
|
||||
/// Default RGBA output budget: 256 MiB, matching an 8192×8192 RGBA8 texture.
|
||||
pub const DEFAULT_MAX_RGBA_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// How a texture's pixels are laid out.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PixelLayout {
|
||||
/// Alpha only (shown as white with that alpha).
|
||||
Alpha8,
|
||||
/// One grey channel.
|
||||
R8,
|
||||
/// One unsigned 16-bit channel, shown as grey.
|
||||
R16,
|
||||
/// Two unsigned 8-bit channels; blue is zero and alpha is opaque.
|
||||
Rg8,
|
||||
/// Two unsigned 16-bit channels; blue is zero and alpha is opaque.
|
||||
Rg16,
|
||||
/// Three unsigned 16-bit channels; alpha is opaque.
|
||||
Rgb16,
|
||||
/// Four unsigned 16-bit channels, including alpha.
|
||||
Rgba16,
|
||||
RHalf,
|
||||
RgHalf,
|
||||
RgbaHalf,
|
||||
RFloat,
|
||||
RgFloat,
|
||||
RgbaFloat,
|
||||
/// Nine-bit RGB mantissas with a shared five-bit exponent, displayed as opaque sRGB.
|
||||
Rgb9e5,
|
||||
/// Packed unsigned 10-bit RGB with two-bit alpha, low bits first.
|
||||
Rgba1010102,
|
||||
/// Packed unsigned 11/11/10-bit floating-point RGB, displayed as opaque sRGB.
|
||||
Rgb111110Float,
|
||||
Rgb24,
|
||||
Rgba32,
|
||||
Argb32,
|
||||
Bgra32,
|
||||
Rgb565,
|
||||
Rgba4444,
|
||||
Argb4444,
|
||||
/// BC1 / DXT1.
|
||||
Dxt1,
|
||||
/// BC2 / DXT3: four-colour blocks with one explicit four-bit alpha value per texel.
|
||||
Dxt3,
|
||||
/// BC3 / DXT5.
|
||||
Dxt5,
|
||||
/// One channel in blocks (shown as grey).
|
||||
Bc4,
|
||||
/// Two channels in blocks, usually a normal map (blue is rebuilt from red and green).
|
||||
Bc5,
|
||||
/// High dynamic range RGB in blocks (unsigned half floats), tone-mapped to 8-bit sRGB.
|
||||
Bc6h,
|
||||
/// BC6H with signed half floats.
|
||||
Bc6hSigned,
|
||||
Bc7,
|
||||
/// ETC1 RGB, with individual or differential base colours.
|
||||
Etc1,
|
||||
/// One EAC channel, shown as grey.
|
||||
EacR,
|
||||
/// One signed EAC channel; -1..1 maps to 0..255.
|
||||
EacRSigned,
|
||||
/// Two EAC channels; blue is zero and alpha is opaque.
|
||||
EacRg,
|
||||
/// Two signed EAC channels; -1..1 maps to 0..255.
|
||||
EacRgSigned,
|
||||
}
|
||||
|
||||
/// Bytes of a `width`×`height` picture in `layout`.
|
||||
pub fn size(layout: PixelLayout, width: u32, height: u32) -> Option<usize> {
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
let blocks = w.div_ceil(4).checked_mul(h.div_ceil(4))?;
|
||||
match layout {
|
||||
PixelLayout::Alpha8 | PixelLayout::R8 => w.checked_mul(h),
|
||||
PixelLayout::Rgb565 | PixelLayout::Rgba4444 | PixelLayout::Argb4444 | PixelLayout::RHalf | PixelLayout::R16 | PixelLayout::Rg8 => {
|
||||
w.checked_mul(h)?.checked_mul(2)
|
||||
}
|
||||
PixelLayout::Rgb24 => w.checked_mul(h)?.checked_mul(3),
|
||||
PixelLayout::Rg16 => w.checked_mul(h)?.checked_mul(4),
|
||||
PixelLayout::Rgb16 => w.checked_mul(h)?.checked_mul(6),
|
||||
PixelLayout::Rgba16 => w.checked_mul(h)?.checked_mul(8),
|
||||
PixelLayout::Rgba32
|
||||
| PixelLayout::Argb32
|
||||
| PixelLayout::Bgra32
|
||||
| PixelLayout::RgHalf
|
||||
| PixelLayout::RFloat
|
||||
| PixelLayout::Rgb9e5
|
||||
| PixelLayout::Rgba1010102
|
||||
| PixelLayout::Rgb111110Float => w.checked_mul(h)?.checked_mul(4),
|
||||
PixelLayout::RgbaHalf | PixelLayout::RgFloat => w.checked_mul(h)?.checked_mul(8),
|
||||
PixelLayout::RgbaFloat => w.checked_mul(h)?.checked_mul(16),
|
||||
PixelLayout::Dxt1 | PixelLayout::Bc4 | PixelLayout::Etc1 | PixelLayout::EacR | PixelLayout::EacRSigned => blocks.checked_mul(8),
|
||||
PixelLayout::Dxt3
|
||||
| PixelLayout::Dxt5
|
||||
| PixelLayout::Bc5
|
||||
| PixelLayout::Bc6h
|
||||
| PixelLayout::Bc6hSigned
|
||||
| PixelLayout::Bc7
|
||||
| PixelLayout::EacRg
|
||||
| PixelLayout::EacRgSigned => blocks.checked_mul(16),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert an IEEE 754 binary16 half-float's bits to `f32`.
|
||||
pub fn half_to_f32(h: u16) -> f32 {
|
||||
bptc::half(h)
|
||||
}
|
||||
|
||||
/// Convert a linear-light value to 8-bit sRGB; 0..1 is kept, brighter and negative values clip.
|
||||
pub fn linear_to_srgb8(v: f32) -> u8 {
|
||||
bptc::srgb8(v)
|
||||
}
|
||||
|
||||
/// Decode one BC1 (DXT1) 8-byte block into 16 RGBA8 texels (row by row).
|
||||
pub fn decode_bc1_block(block: &[u8; 8]) -> [[u8; 4]; 16] {
|
||||
bc::decode_colour(block, true)
|
||||
}
|
||||
|
||||
/// Decode one BC2 (DXT3) 16-byte block into 16 RGBA8 texels (row by row).
|
||||
pub fn decode_bc2_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
|
||||
with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_bc2_alpha(block.get(..8).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Decode one BC3 (DXT5) 16-byte block into 16 RGBA8 texels (row by row).
|
||||
pub fn decode_bc3_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
|
||||
with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_values(block.get(..8).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Decode one BC4 8-byte block into 16 greyscale RGBA8 texels (`[r, r, r, 255]`, row by row).
|
||||
pub fn decode_bc4_block(block: &[u8; 8]) -> [[u8; 4]; 16] {
|
||||
bc::decode_values(block).map(|r| [r, r, r, 255])
|
||||
}
|
||||
|
||||
/// Decode one BC5 16-byte normal-map block into 16 RGBA8 texels with reconstructed Z (row by row).
|
||||
pub fn decode_bc5_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
|
||||
let (r, g) = (bc::decode_values(block.get(..8).unwrap_or_default()), bc::decode_values(block.get(8..).unwrap_or_default()));
|
||||
std::array::from_fn(|k| {
|
||||
let (x, y) = (f32::from(r[k]) / 127.5 - 1.0, f32::from(g[k]) / 127.5 - 1.0);
|
||||
let z = (1.0 - x * x - y * y).max(0.0).sqrt();
|
||||
[r[k], g[k], ((z + 1.0) * 127.5) as u8, 255]
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode one BC6H 16-byte block into 16 sRGB8 RGBA texels (opaque).
|
||||
pub fn decode_bc6h_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
|
||||
bptc::bc6h(block, signed)
|
||||
}
|
||||
|
||||
/// Decode one BC7 16-byte block into 16 RGBA8 texels (row by row).
|
||||
pub fn decode_bc7_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
|
||||
bptc::bc7(block)
|
||||
}
|
||||
|
||||
/// Decode one ETC1 8-byte block into 16 RGBA8 texels; returns `None` if differential colours overflow 5 bits.
|
||||
pub fn decode_etc1_block(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> {
|
||||
eac::etc1(block)
|
||||
}
|
||||
|
||||
/// Decode one single-channel EAC 8-byte block into 16 greyscale RGBA8 texels.
|
||||
pub fn decode_eac_r_block(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] {
|
||||
eac::scalar(block, signed)
|
||||
}
|
||||
|
||||
/// Decode one dual-channel EAC 16-byte block into 16 RGBA8 texels (blue 0, alpha 255).
|
||||
pub fn decode_eac_rg_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
|
||||
eac::dual(block, signed)
|
||||
}
|
||||
|
||||
/// Decode one little-endian `RGB9E5` 4-byte pixel into opaque sRGB8 RGBA.
|
||||
pub fn decode_rgb9e5(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
packed::rgb9e5(bytes)
|
||||
}
|
||||
|
||||
/// Decode one little-endian `RGBA1010102` 4-byte pixel into RGBA8.
|
||||
pub fn decode_rgba1010102(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
packed::rgba1010102(bytes)
|
||||
}
|
||||
|
||||
/// Decode one little-endian `R11G11B10_FLOAT` 4-byte pixel into opaque sRGB8 RGBA.
|
||||
pub fn decode_rgb111110_float(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
packed::rgb111110(bytes)
|
||||
}
|
||||
|
||||
fn unorm8(value: u16) -> u8 {
|
||||
((u32::from(value) * 255 + 32767) / 65535) as u8
|
||||
}
|
||||
|
||||
fn unorm16_pixels(samples: impl Iterator<Item = u16>, channels: usize) -> impl Iterator<Item = [u8; 4]> {
|
||||
let mut samples = samples.map(unorm8);
|
||||
std::iter::from_fn(move || {
|
||||
let (r, g) = (samples.next()?, samples.next()?);
|
||||
let b = if channels > 2 { samples.next()? } else { 0 };
|
||||
let a = if channels > 3 { samples.next()? } else { 255 };
|
||||
Some([r, g, b, a])
|
||||
})
|
||||
}
|
||||
|
||||
fn float_pixels(mut samples: impl Iterator<Item = f32>, channels: usize) -> impl Iterator<Item = [u8; 4]> {
|
||||
std::iter::from_fn(move || {
|
||||
let r = bptc::srgb8(samples.next()?);
|
||||
if channels == 1 {
|
||||
return Some([r, r, r, 255]);
|
||||
}
|
||||
let g = bptc::srgb8(samples.next()?);
|
||||
if channels == 2 {
|
||||
return Some([r, g, 0, 255]);
|
||||
}
|
||||
let b = bptc::srgb8(samples.next()?);
|
||||
let a = (samples.next()?.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Some([r, g, b, a])
|
||||
})
|
||||
}
|
||||
|
||||
fn expand5(v: u16) -> u8 {
|
||||
let v = (v & 31) as u8;
|
||||
(v << 3) | (v >> 2)
|
||||
}
|
||||
|
||||
fn expand6(v: u16) -> u8 {
|
||||
let v = (v & 63) as u8;
|
||||
(v << 2) | (v >> 4)
|
||||
}
|
||||
|
||||
fn rgb565(v: u16) -> [u8; 4] {
|
||||
[expand5(v >> 11), expand6(v >> 5), expand5(v), 255]
|
||||
}
|
||||
|
||||
fn nibbles(v: u16, order: [u32; 4]) -> [u8; 4] {
|
||||
order.map(|shift| ((v >> shift) & 15) as u8 * 17)
|
||||
}
|
||||
|
||||
fn place_blocks(out: &mut [u8], w: usize, h: usize, texels: impl Iterator<Item = [[u8; 4]; 16]>) {
|
||||
let across = w.div_ceil(4);
|
||||
for (i, block) in texels.enumerate() {
|
||||
let (bx, by) = (i % across, i / across);
|
||||
for (k, p) in block.iter().enumerate() {
|
||||
let (x, y) = (bx * 4 + k % 4, by * 4 + k / 4);
|
||||
if x < w && y < h {
|
||||
let at = (y * w + x) * 4;
|
||||
if let Some(dst) = out.get_mut(at..at + 4) {
|
||||
dst.copy_from_slice(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a `width`×`height` picture (`data` starts with it) into RGBA8, rows in stored order.
|
||||
///
|
||||
/// Caps the output at [`DEFAULT_MAX_RGBA_BYTES`]; use [`decode_with_limit`] for a different budget.
|
||||
pub fn decode(layout: PixelLayout, width: u32, height: u32, data: &[u8]) -> Result<Vec<u8>, DdsError> {
|
||||
decode_with_limit(layout, width, height, data, DEFAULT_MAX_RGBA_BYTES)
|
||||
}
|
||||
|
||||
/// Decode into RGBA8, allowing at most `max_bytes` of output.
|
||||
///
|
||||
/// The budget applies to RGBA bytes, not the encoded input, and is checked before reading pixels
|
||||
/// or reserving the output.
|
||||
pub fn decode_with_limit(layout: PixelLayout, width: u32, height: u32, data: &[u8], max_bytes: u64) -> Result<Vec<u8>, DdsError> {
|
||||
let need = size(layout, width, height).ok_or(DdsError::Alloc(usize::MAX))?;
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
let out_len =
|
||||
w.checked_mul(h).and_then(|pixels| pixels.checked_mul(4)).filter(|bytes| *bytes <= isize::MAX as usize).ok_or(DdsError::Alloc(usize::MAX))?;
|
||||
if out_len as u64 > max_bytes {
|
||||
return Err(DdsError::LimitExceeded { required: out_len, limit: max_bytes });
|
||||
}
|
||||
let data = data.get(..need).ok_or_else(|| DdsError::Truncated(format!("{} bytes of pixels, {need} needed", data.len())))?;
|
||||
if w == 0 || h == 0 {
|
||||
return Err(DdsError::Malformed("an empty picture".into()));
|
||||
}
|
||||
let mut out: Vec<u8> = alloc_zeroed(out_len)?;
|
||||
let mut put = |px: &mut dyn Iterator<Item = [u8; 4]>| {
|
||||
for (dst, p) in out.as_chunks_mut::<4>().0.iter_mut().zip(px) {
|
||||
*dst = p;
|
||||
}
|
||||
};
|
||||
let u16s = data.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b));
|
||||
let floats = data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b));
|
||||
match layout {
|
||||
PixelLayout::RHalf => put(&mut float_pixels(u16s.map(bptc::half), 1)),
|
||||
PixelLayout::RgHalf => put(&mut float_pixels(u16s.map(bptc::half), 2)),
|
||||
PixelLayout::RgbaHalf => put(&mut float_pixels(u16s.map(bptc::half), 4)),
|
||||
PixelLayout::RFloat => put(&mut float_pixels(floats, 1)),
|
||||
PixelLayout::RgFloat => put(&mut float_pixels(floats, 2)),
|
||||
PixelLayout::RgbaFloat => put(&mut float_pixels(floats, 4)),
|
||||
PixelLayout::Rgba1010102 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgba1010102)),
|
||||
PixelLayout::Rgb111110Float => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb111110)),
|
||||
PixelLayout::Rgb9e5 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb9e5)),
|
||||
PixelLayout::Alpha8 => put(&mut data.iter().map(|a| [255, 255, 255, *a])),
|
||||
PixelLayout::R8 => put(&mut data.iter().map(|r| [*r, *r, *r, 255])),
|
||||
PixelLayout::R16 => put(&mut u16s.map(|value| {
|
||||
let grey = unorm8(value);
|
||||
[grey, grey, grey, 255]
|
||||
})),
|
||||
PixelLayout::Rg8 => put(&mut data.as_chunks::<2>().0.iter().map(|[r, g]| [*r, *g, 0, 255])),
|
||||
PixelLayout::Rg16 => put(&mut unorm16_pixels(u16s, 2)),
|
||||
PixelLayout::Rgb16 => put(&mut unorm16_pixels(u16s, 3)),
|
||||
PixelLayout::Rgba16 => put(&mut unorm16_pixels(u16s, 4)),
|
||||
PixelLayout::Rgb24 => put(&mut data.as_chunks::<3>().0.iter().map(|[r, g, b]| [*r, *g, *b, 255])),
|
||||
PixelLayout::Rgba32 => put(&mut data.as_chunks::<4>().0.iter().copied()),
|
||||
PixelLayout::Argb32 => put(&mut data.as_chunks::<4>().0.iter().map(|[a, r, g, b]| [*r, *g, *b, *a])),
|
||||
PixelLayout::Bgra32 => put(&mut data.as_chunks::<4>().0.iter().map(|[b, g, r, a]| [*r, *g, *b, *a])),
|
||||
PixelLayout::Rgb565 => put(&mut u16s.map(rgb565)),
|
||||
PixelLayout::Rgba4444 => put(&mut u16s.map(|v| nibbles(v, [12, 8, 4, 0]))),
|
||||
PixelLayout::Argb4444 => put(&mut u16s.map(|v| nibbles(v, [8, 4, 0, 12]))),
|
||||
PixelLayout::Dxt1 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc1_block)),
|
||||
PixelLayout::Dxt3 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc2_block)),
|
||||
PixelLayout::Dxt5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc3_block)),
|
||||
PixelLayout::Bc4 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc4_block)),
|
||||
PixelLayout::Bc5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc5_block)),
|
||||
PixelLayout::Bc6h => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, false))),
|
||||
PixelLayout::Bc6hSigned => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, true))),
|
||||
PixelLayout::Bc7 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(bptc::bc7)),
|
||||
PixelLayout::EacR | PixelLayout::EacRSigned => {
|
||||
place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(|block| eac::scalar(block, layout == PixelLayout::EacRSigned)))
|
||||
}
|
||||
PixelLayout::EacRg | PixelLayout::EacRgSigned => {
|
||||
place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|block| eac::dual(block, layout == PixelLayout::EacRgSigned)))
|
||||
}
|
||||
PixelLayout::Etc1 => {
|
||||
let mut valid = true;
|
||||
let texels = data.as_chunks::<8>().0.iter().map_while(|block| {
|
||||
let pixels = eac::etc1(block);
|
||||
valid &= pixels.is_some();
|
||||
pixels
|
||||
});
|
||||
place_blocks(&mut out, w, h, texels);
|
||||
if !valid {
|
||||
return Err(DdsError::Malformed("ETC1 differential colour is outside its five-bit range".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Flip a `width`-wide RGBA8 picture upside down.
|
||||
pub fn flip_rows(rgba: &[u8], width: u32) -> Vec<u8> {
|
||||
let row = (width as usize).saturating_mul(4).max(1);
|
||||
rgba.chunks(row).rev().flatten().copied().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{PixelLayout, decode, decode_with_limit, flip_rows, size};
|
||||
use crate::DdsError;
|
||||
|
||||
#[test]
|
||||
fn uncompressed_and_swizzled_layouts() {
|
||||
assert_eq!(decode(PixelLayout::Rgba32, 1, 2, &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(), [1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
assert_eq!(decode(PixelLayout::Argb32, 1, 1, &[9, 1, 2, 3]).unwrap(), [1, 2, 3, 9]);
|
||||
assert_eq!(decode(PixelLayout::Bgra32, 1, 1, &[3, 2, 1, 9]).unwrap(), [1, 2, 3, 9]);
|
||||
assert_eq!(decode(PixelLayout::Rgb24, 1, 1, &[1, 2, 3]).unwrap(), [1, 2, 3, 255]);
|
||||
assert_eq!(decode(PixelLayout::Alpha8, 1, 1, &[7]).unwrap(), [255, 255, 255, 7]);
|
||||
assert_eq!(decode(PixelLayout::R8, 1, 1, &[7]).unwrap(), [7, 7, 7, 255]);
|
||||
assert_eq!(decode(PixelLayout::Rgb565, 1, 1, &0xf800u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
|
||||
assert_eq!(decode(PixelLayout::Rgba4444, 1, 1, &0xf00fu16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
|
||||
assert_eq!(decode(PixelLayout::Argb4444, 1, 1, &0xff00u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
|
||||
assert_eq!(flip_rows(&[1, 1, 1, 1, 2, 2, 2, 2], 1), [2, 2, 2, 2, 1, 1, 1, 1]);
|
||||
assert!(matches!(decode(PixelLayout::Rgba32, 2, 2, &[0; 15]), Err(DdsError::Truncated(_))));
|
||||
assert!(matches!(decode(PixelLayout::Rgba32, 0, 1, &[]), Err(DdsError::Malformed(_))));
|
||||
assert!(matches!(decode_with_limit(PixelLayout::R8, 2, 2, &[0; 4], 15), Err(DdsError::LimitExceeded { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_and_packed_layouts_crop_partial_blocks() {
|
||||
assert_eq!(size(PixelLayout::Dxt1, 5, 5), Some(32));
|
||||
assert_eq!(decode(PixelLayout::Dxt1, 5, 5, &[0; 32]).unwrap().len(), 100);
|
||||
// DXT1: colour 0 red, colour 1 blue; the first texel uses index 1, the rest index 0.
|
||||
let px = decode(PixelLayout::Dxt1, 4, 4, &[0x00, 0xf8, 0x1f, 0x00, 0b01, 0, 0, 0]).unwrap();
|
||||
assert_eq!((&px[..4], &px[4..8]), (&[0, 0, 255, 255][..], &[255, 0, 0, 255][..]));
|
||||
// DXT5: alpha 255 -> 0; first texel index 1 (0), rest index 0 (255).
|
||||
let mut b = vec![255, 0, 1, 0, 0, 0, 0, 0];
|
||||
b.extend_from_slice(&[0x00, 0xf8, 0x1f, 0x00, 0, 0, 0, 0]);
|
||||
let px = decode(PixelLayout::Dxt5, 4, 4, &b).unwrap();
|
||||
assert_eq!((px[3], px[7]), (0, 255));
|
||||
// BC4 & BC5.
|
||||
assert_eq!(&decode(PixelLayout::Bc4, 4, 4, &[200, 10, 0, 0, 0, 0, 0, 0]).unwrap()[..4], &[200, 200, 200, 255]);
|
||||
let mut n = vec![128, 128, 0, 0, 0, 0, 0, 0];
|
||||
n.extend_from_slice(&[128, 128, 0, 0, 0, 0, 0, 0]);
|
||||
assert_eq!(&decode(PixelLayout::Bc5, 4, 4, &n).unwrap()[..4], &[128, 128, 254, 255]);
|
||||
// Packed RGB9E5 & RGBA1010102.
|
||||
let rgb9e5 = (256u32 | (128 << 9) | (64 << 18) | (15 << 27)).to_le_bytes();
|
||||
assert_eq!(decode(PixelLayout::Rgb9e5, 1, 1, &rgb9e5).unwrap(), [188, 137, 99, 255]);
|
||||
let rgba10 = (1023u32 | (512 << 10) | (2 << 30)).to_le_bytes();
|
||||
assert_eq!(decode(PixelLayout::Rgba1010102, 1, 1, &rgba10).unwrap(), [255, 128, 0, 170]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Independent known-answer test vectors (raw bitstreams and hand-verified spec outputs)
|
||||
//! for BC6H (unsigned/signed), BC7, ETC1, and EAC R/RG (unsigned/signed).
|
||||
|
||||
use craft_dds::DdsError;
|
||||
use craft_dds::pixels::{self, PixelLayout};
|
||||
|
||||
#[test]
|
||||
fn bc7_mode6_known_bitstream() {
|
||||
// Raw 128-bit BC7 Mode 6 block (7-bit RGBA endpoints + per-endpoint P-bits, 4-bit indices):
|
||||
// e0 = (241, 121, 21, 255), e1 = (40, 200, 254, 128); texels 0..3 use indices 0, 15, 8, 4.
|
||||
let block: [u8; 16] = [0x40, 0x3c, 0x85, 0x47, 0x56, 0xfc, 0xff, 0xc0, 0xf0, 0x48, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44];
|
||||
let texels = pixels::decode_bc7_block(&block);
|
||||
assert_eq!(texels[0], [241, 121, 21, 255]);
|
||||
assert_eq!(texels[1], [40, 200, 254, 128]);
|
||||
assert_eq!(texels[2], [134, 163, 145, 188]);
|
||||
assert_eq!(texels[3], [188, 142, 83, 221]);
|
||||
|
||||
// Reserved mode (low byte 0x00) decodes to all zeroes.
|
||||
assert_eq!(pixels::decode_bc7_block(&[0; 16]), [[0, 0, 0, 0]; 16]);
|
||||
|
||||
// Cropped 3x2 image keeps the top-left 3x2 texels in row-major order.
|
||||
let rgba = pixels::decode(PixelLayout::Bc7, 3, 2, &block).unwrap();
|
||||
assert_eq!(rgba.len(), 3 * 2 * 4);
|
||||
assert_eq!(&rgba[..4], &[241, 121, 21, 255]);
|
||||
assert_eq!(&rgba[4..8], &[40, 200, 254, 128]);
|
||||
assert_eq!(&rgba[8..12], &[134, 163, 145, 188]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc6h_unsigned_and_signed_known_bitstreams() {
|
||||
// Mode 11 (untransformed 10-bit endpoints, 1 subset, 4-bit indices):
|
||||
// e0 = (480, 400, 200), e1 = (200, 480, 400); texels 0..2 use indices 0, 15, 8.
|
||||
let block: [u8; 16] = [0x03, 0x3c, 0xc8, 0x90, 0x41, 0x06, 0x3c, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
|
||||
|
||||
let unsigned = pixels::decode_bc6h_block(&block, false);
|
||||
assert_eq!(unsigned[0], [228, 105, 7, 255]);
|
||||
assert_eq!(unsigned[1], [7, 228, 105, 255]);
|
||||
assert_eq!(unsigned[2], [51, 160, 39, 255]);
|
||||
|
||||
let signed_pos = pixels::decode_bc6h_block(&block, true);
|
||||
assert_eq!(signed_pos[0], [255, 255, 105, 255]);
|
||||
assert_eq!(signed_pos[1], [105, 255, 255, 255]);
|
||||
assert_eq!(signed_pos[2], [255, 255, 255, 255]);
|
||||
|
||||
// Signed Mode 11 with negative 10-bit endpoints: R0 = -200 (0x338), G1 = -200 (0x338).
|
||||
// Negative linear values clip to 0 in sRGB8 output.
|
||||
let neg_block: [u8; 16] = [0x03, 0x67, 0x64, 0x20, 0x43, 0x06, 0x67, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
|
||||
let signed_neg = pixels::decode_bc6h_block(&neg_block, true);
|
||||
assert_eq!(signed_neg[0], [0, 105, 255, 255]);
|
||||
assert_eq!(signed_neg[1], [105, 0, 255, 255]);
|
||||
assert_eq!(signed_neg[2], [0, 0, 255, 255]);
|
||||
|
||||
let rgba = pixels::decode(PixelLayout::Bc6h, 2, 1, &block).unwrap();
|
||||
assert_eq!(rgba, [228, 105, 7, 255, 7, 228, 105, 255]);
|
||||
let rgba_signed = pixels::decode(PixelLayout::Bc6hSigned, 2, 1, &neg_block).unwrap();
|
||||
assert_eq!(rgba_signed, [0, 105, 255, 255, 105, 0, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn etc1_known_bitstreams_and_invalid_differential() {
|
||||
// Individual mode (diff=0, flip=0): left half (x<2) RGB4=(15,0,8) + 2, right half (x>=2) RGB4=(0,15,4) + 5.
|
||||
let individual: [u8; 8] = [0xf0, 0x0f, 0x84, 0x04, 0x00, 0x00, 0x00, 0x00];
|
||||
let texels = pixels::decode_etc1_block(&individual).unwrap();
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
let expected = if x < 2 { [255, 2, 138, 255] } else { [5, 255, 73, 255] };
|
||||
assert_eq!(texels[y * 4 + x], expected);
|
||||
}
|
||||
}
|
||||
|
||||
// Differential mode (diff=1, flip=1 horizontal): base0=(20,10,4), delta=(+2,-2,+1), tables=(2,3).
|
||||
let differential: [u8; 8] = [0xa2, 0x56, 0x21, 0x4f, 0x00, 0x00, 0x00, 0x00];
|
||||
let texels = pixels::decode_etc1_block(&differential).unwrap();
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
let expected = if y < 2 { [174, 91, 42, 255] } else { [194, 79, 54, 255] };
|
||||
assert_eq!(texels[y * 4 + x], expected);
|
||||
}
|
||||
}
|
||||
|
||||
// Differential base + delta outside 0..=31 must be rejected.
|
||||
let invalid: [u8; 8] = [0x04, 0x40, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00];
|
||||
assert!(pixels::decode_etc1_block(&invalid).is_none());
|
||||
assert!(matches!(pixels::decode(PixelLayout::Etc1, 4, 4, &invalid), Err(DdsError::Malformed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eac_r_and_rg_unsigned_and_signed_known_bitstreams() {
|
||||
// Unsigned EAC_R: base=100, mult=2, table=0, all selectors=7 (+14) -> 1028/2047 -> 128.
|
||||
let eac_r_u: [u8; 8] = [0x64, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
|
||||
assert_eq!(pixels::decode_eac_r_block(&eac_r_u, false), [[128, 128, 128, 255]; 16]);
|
||||
|
||||
// Signed EAC_R: base=-64 (0xc0), mult=2, table=0, all selectors=0 (-3) -> (-560+1023)/2046 -> 58.
|
||||
let eac_r_s: [u8; 8] = [0xc0, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
|
||||
assert_eq!(pixels::decode_eac_r_block(&eac_r_s, true), [[58, 58, 58, 255]; 16]);
|
||||
|
||||
// Column-major selector order: texel (x=1, y=0) has selector 7 (+14 -> 142), others selector 0 (-3 -> 125).
|
||||
let eac_col: [u8; 8] = [0x80, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00];
|
||||
let col_texels = pixels::decode_eac_r_block(&eac_col, false);
|
||||
assert_eq!(col_texels[1], [142, 142, 142, 255]);
|
||||
assert_eq!(col_texels[0], [125, 125, 125, 255]);
|
||||
assert_eq!(col_texels[4], [125, 125, 125, 255]);
|
||||
|
||||
// Dual-channel EAC_RG (unsigned and signed): R then G.
|
||||
let mut eac_rg_u = [0u8; 16];
|
||||
eac_rg_u[..8].copy_from_slice(&eac_r_u);
|
||||
eac_rg_u[8..].copy_from_slice(&[0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
|
||||
assert_eq!(pixels::decode(PixelLayout::EacRg, 2, 2, &eac_rg_u).unwrap(), [128, 255, 0, 255].repeat(4));
|
||||
|
||||
let mut eac_rg_s = [0u8; 16];
|
||||
eac_rg_s[..8].copy_from_slice(&eac_r_s);
|
||||
eac_rg_s[8..].copy_from_slice(&[0x7f, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
|
||||
assert_eq!(pixels::decode(PixelLayout::EacRgSigned, 2, 2, &eac_rg_s).unwrap(), [58, 255, 0, 255].repeat(4));
|
||||
}
|
||||
@@ -24,8 +24,10 @@ const PATH_FS: [&str; 2] = ["std", "fs"];
|
||||
const PLAIN_DATA: &str = "contract/no-global-state:plain-data";
|
||||
const PROJECTION: &str = "contract/no-global-state:projection";
|
||||
|
||||
/// The hidden `Tracked::__split_for_bind`, called only by `bind_tracked!`; the lint reads source before macro expansion, so every textual hit is a direct call.
|
||||
/// The hidden `Tracked::__split_for_bind`, called only by `bind_tracked!`; the lint reads source before macro expansion, so every textual hit outside its definition is a direct call.
|
||||
const SPLIT_FOR_BIND: &str = "__split_for_bind";
|
||||
/// The macro that calls [`SPLIT_FOR_BIND`]; its definition is not a call site.
|
||||
const BIND_TRACKED: &str = "bind_tracked";
|
||||
|
||||
struct Hits {
|
||||
found: Vec<(proc_macro2::Span, String, String)>,
|
||||
@@ -110,6 +112,10 @@ impl Visit<'_> for Hits {
|
||||
}
|
||||
|
||||
fn visit_item_macro(&mut self, node: &ItemMacro) {
|
||||
// `bind_tracked!`'s own definition is the one place that names the hidden call.
|
||||
if node.mac.path.is_ident("macro_rules") && node.ident.as_ref().is_some_and(|i| i == BIND_TRACKED) {
|
||||
return;
|
||||
}
|
||||
self.macro_path(&node.mac);
|
||||
visit::visit_item_macro(self, node);
|
||||
}
|
||||
|
||||
@@ -137,6 +137,9 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[
|
||||
const NO_GLOBAL_STATE: &[(&str, &str)] = &[
|
||||
// The trait's home crate: it implements `MemoProps` by hand for std and framework value types.
|
||||
("crates/ui-contract/src/contract/memo.rs", "MemoProps"),
|
||||
// Settled fact: `ModalRules` holds a closure the derive cannot take; it keys on its plain fields and the revision
|
||||
// the app moves with every rule change, which stands for the closure.
|
||||
("crates/menu/src/modal.rs", "MemoProps"),
|
||||
// Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init.
|
||||
("crates/ui-contract/src/fonts/defaults.rs", "HACK"),
|
||||
("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"),
|
||||
|
||||
@@ -11,8 +11,14 @@ repository.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-color-transform = { workspace = true }
|
||||
craft-develop-model = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
rayon = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-render-parity = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,45 @@
|
||||
# craft-develop
|
||||
|
||||
The raw develop pipeline, CPU path: the shared pipeline of
|
||||
[#587](https://github.com/storytold/craft-libs/issues/587), moved from LightCraft one module at a time. No `unsafe`,
|
||||
no panics on hostile input, no file I/O, and it builds for `wasm32-unknown-unknown`.
|
||||
|
||||
```toml
|
||||
craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "<commit>" }
|
||||
```
|
||||
|
||||
## What is here
|
||||
|
||||
| Module | From LightCraft (`a75497d6`) | Contents |
|
||||
|---|---|---|
|
||||
| `color::spline` | `crates/color/src/spline.rs` | Re-exports `craft_color_transform::curve` (`MonotoneCurve`, `Lut1`). |
|
||||
| `curve` | `crates/pipeline` | The parametric tone curve and its regions. |
|
||||
| `finish` | `crates/pipeline` | Pure-Rust finishing helpers: sharpening masks/limits, vignette parameters, value grain, gamut mapping, and curve saturation refinement. |
|
||||
| `lut` | `crates/pipeline` | 3D lookup tables and the `.cube` reader. |
|
||||
| `tone` | `crates/pipeline` | Global tone mapping (`ToneMap` and `CameraTone`) from scene luminance to display-linear luminance, SDR and HDR. |
|
||||
| `inpaint` | `crates/inpaint` | Content-aware hole filling for spot removal: `complete` (multi-scale patch completion with PatchMatch) and `membrane_fill` (a smooth harmonic fill, its seed and fallback). Interleaved `f32` buffers of any channel count, a fixed-seed RNG, the same result on any number of threads. |
|
||||
|
||||
## Parity with LightCraft
|
||||
|
||||
Each module comes with a test that its output is LightCraft's at the base commit, compared with
|
||||
[`craft-render-parity`](../render-parity/README.md) at `Tolerance::BASELINE`. The expected pictures in
|
||||
`tests/fixtures/` were written by LightCraft's own crate at that commit, on the scene the test builds.
|
||||
|
||||
Differences from LightCraft (ordinary-range output is covered by the baseline fixtures):
|
||||
|
||||
- `inpaint::complete_with` returns `None` for a patch radius wider than the image before computing with it (LightCraft
|
||||
reaches the same `None`, or overflows on a huge radius), returns an image with no pixels at once, and reports
|
||||
`Cancelled` when any one poll said so, including a poll made on a worker thread.
|
||||
|
||||
- `membrane_fill` scales extreme finite boundaries for the harmonic solve and bounds the result by those
|
||||
boundaries, avoiding overflow in means and neighbour sums. Known pixels remain unchanged; ordinary
|
||||
values take the original arithmetic path. This does not promise arbitrary extreme-value safety for
|
||||
PatchMatch completion, which also computes squared costs and downsamples its input.
|
||||
- Membrane cell indices retain `usize` width. PatchMatch rejects grids whose signed search offsets,
|
||||
summed-area counts or padded table cannot be represented; patch-area arithmetic no longer overflows
|
||||
`i32`. An already-cancelled oversized-patch request returns `Cancelled`, not an unavailable-patch result.
|
||||
|
||||
## Not here yet
|
||||
|
||||
The rest of the pipeline: the rest of colour, raster, the sensor stage, raw loading and the render stages. No app uses this crate
|
||||
yet.
|
||||
@@ -1,3 +1,3 @@
|
||||
//! Colour helpers for the develop pipeline.
|
||||
|
||||
pub mod spline;
|
||||
pub use craft_color_transform::curve as spline;
|
||||
@@ -1,206 +0,0 @@
|
||||
//! Curves for tone mapping: monotone cubic Hermite splines (Fritsch–Carlson) and lookup tables.
|
||||
//!
|
||||
//! Monotone interpolation never overshoots between control points, so a point curve can't invert
|
||||
//! tones by accident (a common complaint with natural cubic splines).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A curve through control points in `0..1 × 0..1` (x strictly increasing after normalization).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MonotoneCurve {
|
||||
xs: Vec<f64>,
|
||||
ys: Vec<f64>,
|
||||
ms: Vec<f64>,
|
||||
}
|
||||
|
||||
impl MonotoneCurve {
|
||||
/// Build from points; sorts by x, merges duplicates. Fewer than two points → identity.
|
||||
pub fn new(points: &[(f64, f64)]) -> MonotoneCurve {
|
||||
let mut p: Vec<(f64, f64)> = points.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect();
|
||||
p.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
p.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9);
|
||||
if p.len() < 2 {
|
||||
p = vec![(0.0, 0.0), (1.0, 1.0)];
|
||||
}
|
||||
let n = p.len();
|
||||
let xs: Vec<f64> = p.iter().map(|q| q.0).collect();
|
||||
let ys: Vec<f64> = p.iter().map(|q| q.1).collect();
|
||||
let d: Vec<f64> = (0..n - 1).map(|i| (ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i])).collect();
|
||||
let mut ms = vec![0.0; n];
|
||||
ms[0] = d[0];
|
||||
ms[n - 1] = d[n - 2];
|
||||
for i in 1..n - 1 {
|
||||
ms[i] = if d[i - 1] * d[i] <= 0.0 { 0.0 } else { (d[i - 1] + d[i]) / 2.0 };
|
||||
}
|
||||
// Fritsch–Carlson limiter where the data is monotone within a segment.
|
||||
for i in 0..n - 1 {
|
||||
if d[i] == 0.0 {
|
||||
ms[i] = 0.0;
|
||||
ms[i + 1] = 0.0;
|
||||
continue;
|
||||
}
|
||||
let a = ms[i] / d[i];
|
||||
let b = ms[i + 1] / d[i];
|
||||
let s = a * a + b * b;
|
||||
if s > 9.0 {
|
||||
let t = 3.0 / s.sqrt();
|
||||
ms[i] = t * a * d[i];
|
||||
ms[i + 1] = t * b * d[i];
|
||||
}
|
||||
}
|
||||
MonotoneCurve { xs, ys, ms }
|
||||
}
|
||||
|
||||
pub fn identity() -> MonotoneCurve {
|
||||
MonotoneCurve::new(&[(0.0, 0.0), (1.0, 1.0)])
|
||||
}
|
||||
|
||||
pub fn eval(&self, x: f64) -> f64 {
|
||||
// NaN passes both bound checks below and would send the search past either end
|
||||
if x.is_nan() {
|
||||
return x;
|
||||
}
|
||||
let n = self.xs.len();
|
||||
if x <= self.xs[0] {
|
||||
return self.ys[0] + self.ms[0] * (x - self.xs[0]).min(0.0) * 0.0;
|
||||
}
|
||||
if x >= self.xs[n - 1] {
|
||||
return self.ys[n - 1];
|
||||
}
|
||||
let i = match self.xs.binary_search_by(|v| v.total_cmp(&x)) {
|
||||
Ok(i) => return self.ys[i],
|
||||
Err(i) => i - 1,
|
||||
};
|
||||
let h = self.xs[i + 1] - self.xs[i];
|
||||
let t = (x - self.xs[i]) / h;
|
||||
let (t2, t3) = (t * t, t * t * t);
|
||||
(2.0 * t3 - 3.0 * t2 + 1.0) * self.ys[i]
|
||||
+ (t3 - 2.0 * t2 + t) * h * self.ms[i]
|
||||
+ (-2.0 * t3 + 3.0 * t2) * self.ys[i + 1]
|
||||
+ (t3 - t2) * h * self.ms[i + 1]
|
||||
}
|
||||
|
||||
/// Sample into a LUT of `n` entries (at least 2) over `0..1`.
|
||||
pub fn to_lut(&self, n: usize) -> Lut1 {
|
||||
let n = n.max(2);
|
||||
Lut1 { v: (0..n).map(|i| self.eval(i as f64 / (n - 1) as f64) as f32).collect() }
|
||||
}
|
||||
|
||||
pub fn points(&self) -> Vec<(f64, f64)> {
|
||||
self.xs.iter().copied().zip(self.ys.iter().copied()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A 1-D lookup table over `0..1` with linear interpolation; inputs outside clamp.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Lut1 {
|
||||
pub v: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Lut1 {
|
||||
/// At least 2 entries, like [`Lut1::from_fn`].
|
||||
pub fn identity(n: usize) -> Lut1 {
|
||||
Lut1::from_fn(n, |x| x)
|
||||
}
|
||||
/// `f` sampled at `n` evenly spaced points over `0..1` (at least 2).
|
||||
pub fn from_fn(n: usize, f: impl Fn(f32) -> f32) -> Lut1 {
|
||||
let n = n.max(2);
|
||||
Lut1 { v: (0..n).map(|i| f(i as f32 / (n - 1) as f32)).collect() }
|
||||
}
|
||||
/// `v` is public, so a table shorter than 2 entries is read as constant (1) or the identity (0).
|
||||
#[inline]
|
||||
pub fn eval(&self, x: f32) -> f32 {
|
||||
let x = x.clamp(0.0, 1.0);
|
||||
let n = self.v.len();
|
||||
if n < 2 {
|
||||
return self.v.first().copied().unwrap_or(x);
|
||||
}
|
||||
let f = x * (n - 1) as f32;
|
||||
let i = (f as usize).min(n - 2);
|
||||
let t = f - i as f32;
|
||||
self.v[i] + (self.v[i + 1] - self.v[i]) * t
|
||||
}
|
||||
/// `self ∘ inner` (apply `inner` first).
|
||||
pub fn compose(&self, inner: &Lut1) -> Lut1 {
|
||||
Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() }
|
||||
}
|
||||
pub fn is_identity(&self) -> bool {
|
||||
let n = self.v.len();
|
||||
self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn identity_curve() {
|
||||
let c = MonotoneCurve::identity();
|
||||
for i in 0..=10 {
|
||||
let x = i as f64 / 10.0;
|
||||
assert!((c.eval(x) - x).abs() < 1e-12);
|
||||
}
|
||||
assert!(c.to_lut(256).is_identity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_through_points_and_is_monotone() {
|
||||
let pts = [(0.0, 0.0), (0.25, 0.15), (0.5, 0.5), (0.75, 0.88), (1.0, 1.0)];
|
||||
let c = MonotoneCurve::new(&pts);
|
||||
for (x, y) in pts {
|
||||
assert!((c.eval(x) - y).abs() < 1e-12);
|
||||
}
|
||||
let mut prev = -1.0;
|
||||
for i in 0..=1000 {
|
||||
let y = c.eval(i as f64 / 1000.0);
|
||||
assert!(y >= prev - 1e-12);
|
||||
prev = y;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_overshoot_on_flat_segment() {
|
||||
let c = MonotoneCurve::new(&[(0.0, 0.0), (0.4, 0.5), (0.6, 0.5), (1.0, 1.0)]);
|
||||
for i in 400..=600 {
|
||||
let y = c.eval(i as f64 / 1000.0);
|
||||
assert!((y - 0.5).abs() < 1e-9, "{y}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lut_compose() {
|
||||
let a = Lut1::from_fn(1024, |x| x * x);
|
||||
let b = Lut1::from_fn(1024, |x| x.sqrt());
|
||||
let c = a.compose(&b);
|
||||
assert!((c.eval(0.3) - 0.3).abs() < 2e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_input_and_short_luts_do_not_panic() {
|
||||
let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]);
|
||||
assert!(c.eval(f64::NAN).is_nan());
|
||||
assert!(c.eval(-f64::NAN).is_nan());
|
||||
for n in [0, 1] {
|
||||
assert_eq!(c.to_lut(n).v.len(), 2, "{n}");
|
||||
assert!(Lut1::identity(n).is_identity(), "{n}");
|
||||
assert_eq!(Lut1::from_fn(n, |x| x).v.len(), 2, "{n}");
|
||||
}
|
||||
assert_eq!(Lut1 { v: vec![] }.eval(0.3), 0.3);
|
||||
assert_eq!(Lut1 { v: vec![] }.eval(-1.0), 0.0, "inputs outside 0..1 clamp, as for any table");
|
||||
assert_eq!(Lut1 { v: vec![] }.eval(2.0), 1.0);
|
||||
assert_eq!(Lut1 { v: vec![0.7] }.eval(0.3), 0.7);
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#[test]
|
||||
fn monotone_for_increasing_data(ys in proptest::collection::vec(0.0f64..1.0, 3..8)) {
|
||||
let mut ys = ys; ys.sort_by(|a, b| a.total_cmp(b));
|
||||
let n = ys.len();
|
||||
let pts: Vec<(f64, f64)> = ys.iter().enumerate().map(|(i, y)| (i as f64 / (n - 1) as f64, *y)).collect();
|
||||
let c = MonotoneCurve::new(&pts);
|
||||
let mut prev = f64::MIN;
|
||||
for i in 0..=200 { let y = c.eval(i as f64 / 200.0); proptest::prop_assert!(y >= prev - 1e-9); prev = y; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Pure-Rust finishing-stage helpers: sharpening masks/limits, vignette parameters, value film
|
||||
//! grain, gamut mapping, and curve saturation refinement.
|
||||
|
||||
use craft_develop_model::{DevelopSettings, VignetteStyle};
|
||||
|
||||
#[inline]
|
||||
fn smooth(e0: f32, e1: f32, x: f32) -> f32 {
|
||||
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// How much of the sharpening a pixel gets (`0..1`) under Masking `masking` (`0..1`), from its
|
||||
/// fine detail `det` (log luminance minus its texture blur): `1` everywhere at `0`, only stronger
|
||||
/// edges as it rises.
|
||||
#[inline]
|
||||
pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 {
|
||||
if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Masking weight for the V3 pixel-scale sharpening band, also used by its Alt-drag preview.
|
||||
#[inline]
|
||||
pub fn pixel_sharpen_mask_weight(masking: f32, det: f32) -> f32 {
|
||||
if masking > 0.0 { smooth(masking * 0.1, masking * 0.1 + 0.06, det.abs()) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Gain of the sharpening detail term (per unit of `Amount / 150`), in stops of luminance per stop of detail.
|
||||
pub const SHARPEN_GAIN: f32 = 7.0;
|
||||
|
||||
/// Soft-clip limit (stops) of the sharpening detail term for Detail `0..=100`: `0.03` stops (large
|
||||
/// edge detail is flattened so halos stay small) up to `1.5` stops (practically linear).
|
||||
pub fn sharpen_limit(detail: f64) -> f32 {
|
||||
let d = (detail / 100.0).clamp(0.0, 1.0) as f32;
|
||||
0.03 * 50f32.powf(d)
|
||||
}
|
||||
|
||||
/// The sharpening boost (stops) for pixel-scale detail `det` (log luminance minus its blur at the
|
||||
/// sharpen radius): linear for small detail, soft-clipped at `limit`, and gated by the Masking edge
|
||||
/// mask (`mask` = Masking / 100) so flat areas and noise can be left alone.
|
||||
#[inline]
|
||||
pub fn sharpen_term(det: f32, limit: f32, mask: f32) -> f32 {
|
||||
let m = pixel_sharpen_mask_weight(mask, det);
|
||||
SHARPEN_GAIN * m * det / (1.0 + det.abs() / limit)
|
||||
}
|
||||
|
||||
/// Vignette (post-crop) parameters.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Vig {
|
||||
pub amount: f32,
|
||||
pub start: f32,
|
||||
pub width: f32,
|
||||
pub aspect_mix: f32,
|
||||
pub power: f32,
|
||||
pub highlights: f32,
|
||||
pub style: VignetteStyle,
|
||||
}
|
||||
|
||||
/// Resolve post-crop vignette parameters from `s`, returning `None` when `s.vignette.amount == 0.0`.
|
||||
pub fn vignette(s: &DevelopSettings) -> Option<Vig> {
|
||||
let v = &s.vignette;
|
||||
(v.amount != 0.0).then(|| {
|
||||
let r = (v.roundness / 100.0) as f32;
|
||||
Vig {
|
||||
amount: (v.amount / 100.0) as f32,
|
||||
start: 0.15 + (v.midpoint / 100.0) as f32 * 0.95,
|
||||
width: 0.05 + (v.feather / 100.0) as f32 * 1.1,
|
||||
aspect_mix: ((r + 1.0) / 2.0).clamp(0.0, 1.0),
|
||||
power: if r >= 0.0 { 2.0 } else { 2.0 + (-r) * 6.0 },
|
||||
highlights: (v.highlights / 100.0) as f32,
|
||||
style: v.style,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Hash constants of [`grain_noise`] (shared with the GPU kernel).
|
||||
pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995];
|
||||
|
||||
/// The grain of processes V1 to V6: two octaves of value noise.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ValueGrain {
|
||||
/// Amplitude (display-encoded).
|
||||
pub amt: f32,
|
||||
/// Noise cell size (output pixels).
|
||||
pub cell: f32,
|
||||
/// Roughness `0..1`: weight of the finer octave.
|
||||
pub rough: f32,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
/// Resolve [`ValueGrain`] parameters from `s` at `px_per_long` output pixels per long edge,
|
||||
/// returning `None` when `s.grain.amount <= 0.0`.
|
||||
pub fn value_grain(s: &DevelopSettings, px_per_long: f64) -> Option<ValueGrain> {
|
||||
let g = &s.grain;
|
||||
(g.amount > 0.0).then(|| {
|
||||
let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32;
|
||||
ValueGrain { amt: (g.amount / 100.0) as f32 * 0.13, cell: cell.max(0.6), rough: (g.roughness / 100.0) as f32, seed: g.seed }
|
||||
})
|
||||
}
|
||||
|
||||
/// Smooth value noise in `-1..1` at `(x, y)` for `seed`. Non-finite coordinates return `0.0`.
|
||||
#[inline]
|
||||
pub fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
let (x0, y0) = (x.floor(), y.floor());
|
||||
let (fx, fy) = (x - x0, y - y0);
|
||||
let h = |i: i32, j: i32| {
|
||||
let mut v = (i as u32).wrapping_mul(GRAIN_HASH[0]) ^ (j as u32).wrapping_mul(GRAIN_HASH[1]) ^ seed.wrapping_mul(GRAIN_HASH[2]);
|
||||
v ^= v >> 13;
|
||||
v = v.wrapping_mul(GRAIN_HASH[3]);
|
||||
v ^= v >> 15;
|
||||
(v & 0xffff) as f32 / 32768.0 - 1.0
|
||||
};
|
||||
let (i, j) = (x0 as i32, y0 as i32);
|
||||
let (u, v) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy));
|
||||
let a = h(i, j) + (h(i + 1, j) - h(i, j)) * u;
|
||||
let b = h(i, j + 1) + (h(i + 1, j + 1) - h(i, j + 1)) * u;
|
||||
a + (b - a) * v
|
||||
}
|
||||
|
||||
/// A colour needing more desaturation than this (scale < `GAMUT_WARN`) to fit is out of gamut for
|
||||
/// the gamut warnings (tolerates rounding at the gamut boundary).
|
||||
pub const GAMUT_WARN: f32 = 0.995;
|
||||
|
||||
/// Desaturate linear `r` towards its luminance (weights `luma`) until every channel is in `0..=1`;
|
||||
/// returns the mapped colour and the chroma scale used (`1.0` = already in gamut).
|
||||
#[inline]
|
||||
pub fn gamut_map(r: [f32; 3], luma: [f32; 3]) -> ([f32; 3], f32) {
|
||||
gamut_map_to(r, luma, 1.0)
|
||||
}
|
||||
|
||||
/// [`gamut_map`] into `0..=peak` (an HDR render's range; `peak = 1.0` is [`gamut_map`]).
|
||||
#[inline]
|
||||
pub fn gamut_map_to(r: [f32; 3], luma: [f32; 3], peak: f32) -> ([f32; 3], f32) {
|
||||
let yy = (luma[0] * r[0] + luma[1] * r[1] + luma[2] * r[2]).clamp(0.0, peak);
|
||||
let mut t = 1.0f32;
|
||||
for c in r {
|
||||
if c < 0.0 {
|
||||
t = t.min(yy / (yy - c).max(1e-9));
|
||||
} else if c > peak {
|
||||
t = t.min((peak - yy) / (c - yy).max(1e-9));
|
||||
}
|
||||
}
|
||||
if t < 1.0 { (r.map(|c| yy + (c - yy) * t), t) } else { (r, 1.0) }
|
||||
}
|
||||
|
||||
/// Refine Saturation: scale the curved colour's chroma (around its luma, encoded values) so its
|
||||
/// saturation (chroma / luma) moves from the curve's towards the pre-curve one: the ratio is
|
||||
/// `(s_curve / s_before)^refine`, so `1` keeps the curve and `0` restores the original saturation.
|
||||
#[inline]
|
||||
pub fn refine_saturation(before: [f32; 3], after: [f32; 3], refine: f32) -> [f32; 3] {
|
||||
let luma = |e: [f32; 3]| 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2];
|
||||
let chroma = |e: [f32; 3]| e[0].max(e[1]).max(e[2]) - e[0].min(e[1]).min(e[2]);
|
||||
let (y0, y1) = (luma(before), luma(after));
|
||||
let s0 = chroma(before) / y0.max(1e-4);
|
||||
let s1 = chroma(after) / y1.max(1e-4);
|
||||
if s1 <= 1e-6 || s0 <= 1e-6 {
|
||||
return after;
|
||||
}
|
||||
let k = (s0 / s1).powf(1.0 - refine).clamp(0.0, 4.0);
|
||||
after.map(|v| y1 + (v - y1) * k)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sharpen_helpers_behave_smoothly_and_bound_detail() {
|
||||
assert_eq!(sharpen_mask_weight(0.0, 0.0), 1.0);
|
||||
assert_eq!(pixel_sharpen_mask_weight(0.0, 0.0), 1.0);
|
||||
assert_eq!(sharpen_mask_weight(0.8, 0.0), 0.0);
|
||||
assert!(sharpen_mask_weight(0.8, 1.0) == 1.0);
|
||||
assert!((sharpen_limit(0.0) - 0.03).abs() < 1e-6);
|
||||
assert!((sharpen_limit(100.0) - 1.5).abs() < 1e-4);
|
||||
let lim = sharpen_limit(50.0);
|
||||
assert!(sharpen_term(0.0, lim, 0.0) == 0.0);
|
||||
assert!(sharpen_term(10.0, lim, 0.0) < SHARPEN_GAIN * lim);
|
||||
assert!(sharpen_term(0.1, lim, 0.0) > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vignette_resolves_only_when_nonzero() {
|
||||
let mut s = DevelopSettings::default();
|
||||
assert!(vignette(&s).is_none());
|
||||
s.vignette.amount = -50.0;
|
||||
s.vignette.roundness = -100.0;
|
||||
let v = vignette(&s).unwrap();
|
||||
assert!((v.amount - -0.5).abs() < 1e-6);
|
||||
assert!((v.power - 8.0).abs() < 1e-6);
|
||||
assert!((v.aspect_mix - 0.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grain_is_bounded_and_handles_non_finite_coords() {
|
||||
let mut s = DevelopSettings::default();
|
||||
assert!(value_grain(&s, 2000.0).is_none());
|
||||
s.grain.amount = 50.0;
|
||||
s.grain.size = 25.0;
|
||||
s.grain.roughness = 50.0;
|
||||
let g = value_grain(&s, 2000.0).unwrap();
|
||||
assert!(g.amt > 0.0 && g.cell >= 0.6);
|
||||
assert_eq!(grain_noise(f32::NAN, 1.0, 7), 0.0);
|
||||
assert_eq!(grain_noise(1.0, f32::INFINITY, 7), 0.0);
|
||||
for i in 0..20 {
|
||||
let n = grain_noise(i as f32 * 0.37, i as f32 * 0.71, g.seed);
|
||||
assert!((-1.0..=1.0).contains(&n), "{n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gamut_map_clamps_out_of_gamut_towards_luma() {
|
||||
let luma = [0.2126, 0.7152, 0.0722];
|
||||
let (in_gamut, t0) = gamut_map([0.2, 0.5, 0.8], luma);
|
||||
assert_eq!(in_gamut, [0.2, 0.5, 0.8]);
|
||||
assert_eq!(t0, 1.0);
|
||||
|
||||
let (mapped, t1) = gamut_map([1.5, -0.2, 0.3], luma);
|
||||
assert!(t1 < GAMUT_WARN);
|
||||
assert!(mapped.iter().all(|&c| (-1e-6..=1.0 + 1e-6).contains(&c)), "{mapped:?}");
|
||||
|
||||
let (hdr, t2) = gamut_map_to([2.5, 0.5, 0.5], luma, 4.0);
|
||||
assert_eq!(hdr, [2.5, 0.5, 0.5]);
|
||||
assert_eq!(t2, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refine_saturation_interpolates_between_original_and_curved() {
|
||||
let before = [0.4, 0.2, 0.1];
|
||||
let after = [0.6, 0.3, 0.15];
|
||||
assert_eq!(refine_saturation(before, after, 1.0), after);
|
||||
let neutral = refine_saturation([0.3, 0.3, 0.3], [0.5, 0.5, 0.5], 0.5);
|
||||
assert_eq!(neutral, [0.5, 0.5, 0.5]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Content-aware hole filling (inpainting) for the Remove tool.
|
||||
//!
|
||||
//! * [`complete`]: multi-scale patch-based completion (Wexler, Shechtman, Irani 2007) with the
|
||||
//! nearest-neighbour field found by PatchMatch (Barnes et al. 2009). See [`patchmatch`].
|
||||
//! * [`membrane_fill`]: smooth harmonic fill, used to seed the coarsest level and as a fallback.
|
||||
//!
|
||||
//! Buffers are interleaved `w × h × ch` floats in any colour model plus a `w × h` hole mask.
|
||||
//! Everything is deterministic (fixed-seed RNG, results independent of the thread count) and never
|
||||
//! panics on mismatched sizes: such calls return `None` or the input unchanged.
|
||||
//!
|
||||
//! Sources: C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman, *PatchMatch: A Randomized
|
||||
//! Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009; Y. Wexler, E. Shechtman,
|
||||
//! M. Irani, *Space-Time Completion of Video*, PAMI 2007.
|
||||
//!
|
||||
//! Ported from PhotoCraft (`crates/algo/src/inpaint.rs`, `poisson.rs`, MIT OR Apache-2.0, same
|
||||
//! organisation; see `NOTICE`).
|
||||
|
||||
pub mod membrane;
|
||||
pub mod patchmatch;
|
||||
|
||||
pub use membrane::membrane_fill;
|
||||
pub use patchmatch::{CompleteParams, complete, complete_with};
|
||||
|
||||
/// A cancelled [`complete_with`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Cancelled;
|
||||
|
||||
impl std::fmt::Display for Cancelled {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Cancelled {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finite_extreme_membrane_boundaries_stay_finite() {
|
||||
let img = [f32::MAX, 0.0, f32::MAX];
|
||||
let out = membrane_fill(3, 1, 1, &img, &[false, true, false]);
|
||||
assert_eq!(out, vec![f32::MAX; 3]);
|
||||
assert_eq!(membrane_fill(3, 1, 1, &[-f32::MAX, 0.0, f32::MAX], &[false, true, false]), vec![-f32::MAX, 0.0, f32::MAX]);
|
||||
// Also exercise the multigrid restriction and prolongation at extreme scale.
|
||||
let hole: Vec<bool> = (0..256).map(|i| i % 16 > 0 && i % 16 < 15 && i / 16 > 0 && i / 16 < 15).collect();
|
||||
assert_eq!(membrane_fill(16, 16, 1, &[f32::MAX; 256], &hole), vec![f32::MAX; 256]);
|
||||
let img: Vec<f32> = (0..256).map(|i| if i % 16 < 8 { -f32::MAX } else { f32::MAX }).collect();
|
||||
let out = membrane_fill(16, 16, 1, &img, &hole);
|
||||
for ((&actual, &original), &unknown) in out.iter().zip(&img).zip(&hole) {
|
||||
assert!(actual.is_finite() && (-f32::MAX..=f32::MAX).contains(&actual));
|
||||
if !unknown {
|
||||
assert_eq!(actual.to_bits(), original.to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_precedes_an_oversized_patch_result() {
|
||||
let mut hole = vec![false; 32 * 32];
|
||||
hole[16 * 32 + 16] = true;
|
||||
let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() };
|
||||
assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_sizes_do_not_panic() {
|
||||
assert_eq!(complete(4, 4, 3, &[0.0; 5], &[true; 16], &CompleteParams::default()), None);
|
||||
assert_eq!(complete(4, 4, 0, &[], &[true; 16], &CompleteParams::default()), None);
|
||||
assert_eq!(complete(usize::MAX, 2, 3, &[0.0; 6], &[true; 2], &CompleteParams::default()), None);
|
||||
assert_eq!(membrane_fill(4, 4, 1, &[0.5; 3], &[true; 16]), vec![0.5; 3]);
|
||||
// A hole covering everything: nothing to copy from.
|
||||
assert_eq!(complete(16, 16, 1, &[0.5; 256], &[true; 256], &CompleteParams::default()), None);
|
||||
// A tiny image smaller than a patch.
|
||||
let _ = complete(2, 2, 1, &[0.5; 4], &[true, false, false, false], &CompleteParams::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_patch_radius_no_image_could_hold_finds_nothing_to_copy() {
|
||||
let mut hole = vec![false; 32 * 32];
|
||||
hole[16 * 32 + 16] = true;
|
||||
for patch_radius in [16, usize::MAX / 2, usize::MAX] {
|
||||
let p = CompleteParams { patch_radius, ..CompleteParams::default() };
|
||||
assert_eq!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p), None, "radius {patch_radius}");
|
||||
}
|
||||
// Cancelled is still cancelled, not "nothing to copy from".
|
||||
let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() };
|
||||
assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled));
|
||||
// A radius the image has room for still fills.
|
||||
let p = CompleteParams { patch_radius: 5, ..CompleteParams::default() };
|
||||
assert!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_with_no_pixels_is_returned_without_walking_its_rows() {
|
||||
let p = CompleteParams::default();
|
||||
assert_eq!(complete_with(0, usize::MAX, 1, &[], &[], &p, &|| false), Ok(Some(Vec::new())));
|
||||
assert_eq!(complete_with(usize::MAX, 0, 3, &[], &[], &p, &|| false), Ok(Some(Vec::new())));
|
||||
}
|
||||
|
||||
/// Whichever poll says "cancelled", and only that one, the call ends in `Err`: also when it was a
|
||||
/// worker's poll, which can stop the worker but not return.
|
||||
#[test]
|
||||
fn one_cancelled_poll_anywhere_cancels_the_call() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let (w, h) = (48usize, 48usize);
|
||||
let img: Vec<f32> = (0..w * h).map(|i| ((i % w) as f32 * 0.37).sin() * 0.5 + 0.5).collect();
|
||||
let hole: Vec<bool> = (0..w * h).map(|i| (i % w).abs_diff(24) < 5 && (i / w).abs_diff(24) < 5).collect();
|
||||
let p = CompleteParams::default();
|
||||
let polls = AtomicUsize::new(0);
|
||||
let count = || {
|
||||
polls.fetch_add(1, Ordering::Relaxed);
|
||||
false
|
||||
};
|
||||
assert!(matches!(complete_with(w, h, 1, &img, &hole, &p, &count), Ok(Some(_))));
|
||||
let total = polls.load(Ordering::Relaxed);
|
||||
assert!(total > 8, "the scene polls in the workers too: {total}");
|
||||
for nth in 0..total {
|
||||
let polls = AtomicUsize::new(0);
|
||||
let once = || polls.fetch_add(1, Ordering::Relaxed) == nth;
|
||||
assert_eq!(complete_with(w, h, 1, &img, &hole, &p, &once), Err(Cancelled), "poll {nth} of {total}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops() {
|
||||
let img = vec![0.5f32; 64 * 64];
|
||||
let hole: Vec<bool> = (0..64 * 64usize).map(|i| (i % 64).abs_diff(32) < 4 && (i / 64).abs_diff(32) < 4).collect();
|
||||
assert_eq!(complete_with(64, 64, 1, &img, &hole, &CompleteParams::default(), &|| true), Err(Cancelled));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Membrane (harmonic) fill: `Δv = 0` inside a hole with the known pixels as Dirichlet boundary.
|
||||
//! Used to initialise the coarsest level of [`crate::inpaint::complete`] and as its fallback.
|
||||
//!
|
||||
//! Sources: the membrane interpolant of P. Pérez, M. Gangnet, A. Blake, *Poisson Image Editing*,
|
||||
//! ACM SIGGRAPH 2003 (§3), solved by successive over-relaxation on the 4-connected grid, accelerated
|
||||
//! cascadically (solve on a half-resolution grid, prolong bilinearly, a few SOR sweeps per level).
|
||||
//! Ported from PhotoCraft's `algo::poisson` (MIT OR Apache-2.0).
|
||||
|
||||
fn allocation_fits<T>(len: usize) -> bool {
|
||||
len.checked_mul(std::mem::size_of::<T>()).is_some_and(|bytes| bytes <= isize::MAX as usize)
|
||||
}
|
||||
|
||||
/// Convergence threshold (max per-sweep update) for the SOR sweeps.
|
||||
const TOL: f32 = 2e-5;
|
||||
/// SOR sweeps (cap) and relaxation factor on every level above the coarsest: tuned so a 96×72 disc
|
||||
/// is within ~1e-3 of a fully converged Gauss–Seidel solve (below one 8-bit step).
|
||||
const FINE_ITERS: usize = 30;
|
||||
const FINE_OMEGA: f32 = 1.7;
|
||||
|
||||
/// Solve `Δv = 0` on `unknown` pixels with Dirichlet values from the known pixels of `v`
|
||||
/// (out-of-grid neighbours are ignored, i.e. a Neumann boundary). `v` holds the known values on
|
||||
/// entry and the solution on exit. Cascadic multigrid + SOR.
|
||||
pub(crate) fn solve_membrane(w: usize, h: usize, unknown: &[bool], v: &mut [f32]) {
|
||||
if Some(unknown.len()) != w.checked_mul(h) || v.len() != unknown.len() {
|
||||
return;
|
||||
}
|
||||
if !allocation_fits::<(usize, u8)>(unknown.iter().filter(|&&hole| hole).count()) {
|
||||
return;
|
||||
}
|
||||
// Keep the ordinary path bit-for-bit unchanged. Extremely large finite boundaries can
|
||||
// overflow even their mean or a four-neighbour sum; harmonic interpolation is linear,
|
||||
// so solve those channels at unit scale instead. The final clamp enforces the harmonic
|
||||
// maximum principle if the finite-iteration relaxation overshoots a boundary extremum.
|
||||
let mut low = f32::INFINITY;
|
||||
let mut high = f32::NEG_INFINITY;
|
||||
for (&value, &hole) in v.iter().zip(unknown) {
|
||||
if !hole {
|
||||
if !value.is_finite() {
|
||||
solve_rec(w, h, unknown, v, 0, &|| false);
|
||||
return;
|
||||
}
|
||||
low = low.min(value);
|
||||
high = high.max(value);
|
||||
}
|
||||
}
|
||||
let scale = low.abs().max(high.abs());
|
||||
let needs_scale = scale.is_finite() && f64::from(scale) > f64::from(f32::MAX) / v.len().max(16) as f64;
|
||||
if needs_scale {
|
||||
let mut normalized: Vec<f32> = v.iter().map(|&value| value / scale).collect();
|
||||
solve_rec(w, h, unknown, &mut normalized, 0, &|| false);
|
||||
for ((value, solved), &hole) in v.iter_mut().zip(normalized).zip(unknown) {
|
||||
if hole {
|
||||
*value = (f64::from(solved) * f64::from(scale)).clamp(f64::from(low), f64::from(high)) as f32;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
solve_rec(w, h, unknown, v, 0, &|| false);
|
||||
}
|
||||
}
|
||||
|
||||
fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, stop: &(dyn Fn() -> bool + Sync)) {
|
||||
if stop() {
|
||||
return;
|
||||
}
|
||||
let n_unknown = unknown.iter().filter(|u| **u).count();
|
||||
if n_unknown == 0 {
|
||||
return;
|
||||
}
|
||||
// Like the cell list below, this filtered collection must not grow geometrically.
|
||||
let mut known = Vec::with_capacity(v.len() - n_unknown);
|
||||
known.extend(v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x));
|
||||
if known.is_empty() {
|
||||
return; // nothing to interpolate from
|
||||
}
|
||||
if w >= 8 && h >= 8 && n_unknown > 64 && depth < 16 {
|
||||
// Restrict: a coarse pixel is known if any of its children is (value = mean of known children).
|
||||
let (cw, chh) = (w.div_ceil(2), h.div_ceil(2));
|
||||
let mut cu = vec![true; cw * chh];
|
||||
let mut cv = vec![0.0f32; cw * chh];
|
||||
for cy in 0..chh {
|
||||
for cx in 0..cw {
|
||||
let (mut s, mut n) = (0.0f32, 0u32);
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let (x, y) = (cx * 2 + dx, cy * 2 + dy);
|
||||
if x < w && y < h && !unknown[y * w + x] {
|
||||
s += v[y * w + x];
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
cu[cy * cw + cx] = false;
|
||||
cv[cy * cw + cx] = s / n as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
solve_rec(cw, chh, &cu, &mut cv, depth + 1, stop);
|
||||
// Prolong: bilinear sample of the coarse solution as the initial guess.
|
||||
for y in 0..h {
|
||||
let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (chh - 1) as f32);
|
||||
let y0 = fy.floor() as usize;
|
||||
let y1 = (y0 + 1).min(chh - 1);
|
||||
let ty = fy - y0 as f32;
|
||||
for x in 0..w {
|
||||
if !unknown[y * w + x] {
|
||||
continue;
|
||||
}
|
||||
let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (cw - 1) as f32);
|
||||
let x0 = fx.floor() as usize;
|
||||
let x1 = (x0 + 1).min(cw - 1);
|
||||
let tx = fx - x0 as f32;
|
||||
let a = cv[y0 * cw + x0] + (cv[y0 * cw + x1] - cv[y0 * cw + x0]) * tx;
|
||||
let b = cv[y1 * cw + x0] + (cv[y1 * cw + x1] - cv[y1 * cw + x0]) * tx;
|
||||
v[y * w + x] = a + (b - a) * ty;
|
||||
}
|
||||
}
|
||||
sor(w, h, unknown, v, FINE_ITERS, FINE_OMEGA, stop);
|
||||
} else {
|
||||
let mean = known.iter().sum::<f32>() / known.len() as f32;
|
||||
for (x, u) in v.iter_mut().zip(unknown) {
|
||||
if *u {
|
||||
*x = mean;
|
||||
}
|
||||
}
|
||||
sor(w, h, unknown, v, 2000, 1.85, stop);
|
||||
}
|
||||
}
|
||||
|
||||
/// SOR sweeps over the unknown pixels until the largest update drops below [`TOL`].
|
||||
fn sor(w: usize, h: usize, unknown: &[bool], v: &mut [f32], max_iter: usize, omega: f32, stop: &(dyn Fn() -> bool + Sync)) {
|
||||
// Precompute the unknown pixels and which neighbours exist.
|
||||
// The caller validated this exact count; reserve it before extend so geometric growth
|
||||
// cannot round the allocation above the target's capacity limit.
|
||||
let mut cells = Vec::with_capacity(unknown.iter().filter(|&&hole| hole).count());
|
||||
cells.extend((0..w * h).filter(|&i| unknown[i]).map(|i| {
|
||||
let (x, y) = (i % w, i / w);
|
||||
let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3);
|
||||
(i, m)
|
||||
}));
|
||||
for _ in 0..max_iter {
|
||||
if stop() {
|
||||
return;
|
||||
}
|
||||
let mut max_d = 0.0f32;
|
||||
for &(i, m) in &cells {
|
||||
let (s, n) = if m == 0b1111 {
|
||||
(v[i - 1] + v[i + 1] + v[i - w] + v[i + w], 4.0)
|
||||
} else {
|
||||
let mut s = 0.0;
|
||||
let mut n = 0.0;
|
||||
if m & 1 != 0 {
|
||||
s += v[i - 1];
|
||||
n += 1.0;
|
||||
}
|
||||
if m & 2 != 0 {
|
||||
s += v[i + 1];
|
||||
n += 1.0;
|
||||
}
|
||||
if m & 4 != 0 {
|
||||
s += v[i - w];
|
||||
n += 1.0;
|
||||
}
|
||||
if m & 8 != 0 {
|
||||
s += v[i + w];
|
||||
n += 1.0;
|
||||
}
|
||||
if n == 0.0 {
|
||||
continue;
|
||||
}
|
||||
(s, n)
|
||||
};
|
||||
let d = omega * (s / n - v[i]);
|
||||
v[i] += d;
|
||||
max_d = max_d.max(d.abs());
|
||||
}
|
||||
if max_d < TOL {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Map `f` over the channels of an interleaved buffer as planar slices (parallel on native).
|
||||
fn per_channel(w: usize, h: usize, ch: usize, f: impl Fn(usize) -> Vec<f32> + Sync + Send) -> Vec<f32> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let planes: Vec<Vec<f32>> = if w * h >= 64 * 64 {
|
||||
use rayon::prelude::*;
|
||||
(0..ch).into_par_iter().map(&f).collect()
|
||||
} else {
|
||||
(0..ch).map(&f).collect()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let planes: Vec<Vec<f32>> = (0..ch).map(&f).collect();
|
||||
let mut out = vec![0.0f32; w * h * ch];
|
||||
for (c, p) in planes.iter().enumerate() {
|
||||
for (i, v) in p.iter().enumerate() {
|
||||
out[i * ch + c] = *v;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Membrane fill (no source texture): harmonic interpolation of the known pixels into `hole`.
|
||||
/// `img` is interleaved `w × h × ch`, `hole` has `w × h` entries; on a size mismatch `img` comes back
|
||||
/// unchanged.
|
||||
pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) -> Vec<f32> {
|
||||
if Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) {
|
||||
return img.to_vec();
|
||||
}
|
||||
// no pixels: nothing to fill (and `ch` would otherwise size one plane per channel, whatever it claims)
|
||||
if hole.is_empty() {
|
||||
return img.to_vec();
|
||||
}
|
||||
// A valid input slice does not prove the wider index/plane vectors fit the target.
|
||||
if !allocation_fits::<Vec<f32>>(ch) || !allocation_fits::<(usize, u8)>(hole.iter().filter(|&&hole| hole).count()) {
|
||||
return img.to_vec();
|
||||
}
|
||||
per_channel(w, h, ch, |c| {
|
||||
let mut v: Vec<f32> = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect();
|
||||
solve_membrane(w, h, hole, &mut v);
|
||||
v
|
||||
})
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec<bool> {
|
||||
(0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auxiliary_vector_limits_are_checked_without_allocating() {
|
||||
let max_cells = isize::MAX as usize / std::mem::size_of::<(usize, u8)>();
|
||||
assert!(allocation_fits::<(usize, u8)>(max_cells));
|
||||
assert!(!allocation_fits::<(usize, u8)>(max_cells + 1));
|
||||
assert!(!allocation_fits::<Vec<f32>>(usize::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() {
|
||||
assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty());
|
||||
assert!(membrane_fill(3, 0, usize::MAX / 2, &[], &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn membrane_reproduces_linear_boundary() {
|
||||
// A linear function is harmonic: the solve must reproduce it exactly inside the hole.
|
||||
let (w, h) = (80, 60);
|
||||
let unknown = disc(w, h, 40.0, 30.0, 20.0);
|
||||
let truth: Vec<f32> = (0..w * h).map(|i| 0.2 + 0.005 * (i % w) as f32 + 0.003 * (i / w) as f32).collect();
|
||||
let mut v: Vec<f32> = truth.iter().zip(&unknown).map(|(t, u)| if *u { 0.0 } else { *t }).collect();
|
||||
solve_membrane(w, h, &unknown, &mut v);
|
||||
let err = v.iter().zip(&truth).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);
|
||||
assert!(err < 2e-3, "{err}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
//! Hole filling for Spot Healing: patch-based completion, proximity match and texture synthesis.
|
||||
//!
|
||||
//! * [`complete`], content-aware fill: the multi-scale "space-time completion" EM scheme of
|
||||
//! Y. Wexler, E. Shechtman, M. Irani, *Space-Time Completion of Video*, IEEE TPAMI 2007, with the
|
||||
//! nearest-neighbour field computed by C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman,
|
||||
//! *PatchMatch: A Randomized Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009
|
||||
//! (random init, propagation, exponentially shrinking random search). Each EM iteration finds, for
|
||||
//! every patch overlapping the hole, its most similar fully-known patch, then re-estimates hole
|
||||
//! pixels by a similarity-weighted vote of the overlapping matches. Coarse-to-fine over an image
|
||||
//! pyramid (the coarsest level is initialised by membrane interpolation), so large holes stay cheap.
|
||||
//! * `best_offset`, proximity match: the single displacement whose surrounding ring best matches the
|
||||
//! ring around the hole (sum of squared differences), i.e. an automatic Healing Brush source.
|
||||
//! * `synthesize`, create texture: patch-based texture synthesis in the style of A. Efros,
|
||||
//! W. Freeman, *Image Quilting for Texture Synthesis and Transfer*, SIGGRAPH 2001 (blocks picked from
|
||||
//! random candidates by overlap error, feathered overlap instead of a min-cut seam).
|
||||
//!
|
||||
//! Ported from PhotoCraft's `algo::inpaint` (MIT OR Apache-2.0); its proximity match and texture
|
||||
//! synthesis are left out.
|
||||
//!
|
||||
//! All functions take interleaved `w × h × ch` normalised floats (any colour model/depth) and a
|
||||
//! `w × h` hole mask, and return a full buffer equal to the input outside the hole. They are
|
||||
//! deterministic (fixed-seed hash RNG, results independent of thread count).
|
||||
|
||||
use crate::inpaint::Cancelled;
|
||||
use crate::inpaint::membrane::membrane_fill;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
/// Below this many grid cells a level runs single-threaded (thread hand-off costs more than it saves).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const PAR_MIN: usize = 128 * 128;
|
||||
|
||||
/// SplitMix64: tiny deterministic RNG.
|
||||
#[derive(Clone)]
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn new(seed: u64) -> Self {
|
||||
Rng(seed ^ 0x9E37_79B9_7F4A_7C15)
|
||||
}
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
/// Uniform integer in `lo..=hi`.
|
||||
fn range(&mut self, lo: i32, hi: i32) -> i32 {
|
||||
if hi <= lo {
|
||||
return lo;
|
||||
}
|
||||
lo + (self.next() % (hi - lo + 1) as u64) as i32
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters for [`complete`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CompleteParams {
|
||||
/// Patch radius (patches are `2r+1` square).
|
||||
pub patch_radius: usize,
|
||||
/// EM iterations at the coarsest level (finer levels use fewer, down to `min_em_iters`).
|
||||
pub em_iters: usize,
|
||||
pub min_em_iters: usize,
|
||||
/// PatchMatch passes per EM iteration.
|
||||
pub pm_iters: usize,
|
||||
/// Levels where the hole is wider than this (in that level's pixels) only *refine* the upsampled
|
||||
/// match field (one local PatchMatch pass and one vote), which keeps big holes tractable: the
|
||||
/// structure is decided at coarse scale, fine levels just add detail.
|
||||
pub refine_extent: usize,
|
||||
pub seed: u64,
|
||||
}
|
||||
|
||||
impl Default for CompleteParams {
|
||||
fn default() -> Self {
|
||||
Self { patch_radius: 3, em_iters: 8, min_em_iters: 2, pm_iters: 2, refine_extent: 96, seed: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
/// One pyramid level.
|
||||
#[derive(Clone)]
|
||||
struct Level {
|
||||
w: usize,
|
||||
h: usize,
|
||||
img: Vec<f32>,
|
||||
hole: Vec<bool>,
|
||||
}
|
||||
|
||||
fn downsample(l: &Level, ch: usize) -> Level {
|
||||
let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2));
|
||||
let mut img = vec![0.0f32; w * h * ch];
|
||||
let mut hole = vec![false; w * h];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut n = 0.0f32;
|
||||
let o = (y * w + x) * ch;
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let (sx, sy) = (x * 2 + dx, y * 2 + dy);
|
||||
if sx >= l.w || sy >= l.h {
|
||||
continue;
|
||||
}
|
||||
let si = sy * l.w + sx;
|
||||
if l.hole[si] {
|
||||
hole[y * w + x] = true;
|
||||
} else {
|
||||
for c in 0..ch {
|
||||
img[o + c] += l.img[si * ch + c];
|
||||
}
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
if n > 0.0 {
|
||||
for c in 0..ch {
|
||||
img[o + c] /= n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Level { w, h, img, hole }
|
||||
}
|
||||
|
||||
// Search offsets add/subtract a full image dimension in i32. Summed-area queries
|
||||
// add two u32 entries before subtracting. Both the padded table and the larger
|
||||
// per-pixel nearest-neighbour/valid-coordinate arrays must fit a Vec.
|
||||
fn supported_grid(w: usize, h: usize) -> bool {
|
||||
let max_dimension = (i32::MAX / 2) as usize;
|
||||
w <= max_dimension
|
||||
&& h <= max_dimension
|
||||
&& w.checked_mul(h).is_some_and(|n| n <= (u32::MAX / 2) as usize)
|
||||
&& w.checked_mul(h).and_then(|n| n.checked_mul(std::mem::size_of::<(i32, i32)>())).is_some_and(|bytes| bytes <= isize::MAX as usize)
|
||||
&& w.checked_add(1)
|
||||
.and_then(|pw| h.checked_add(1).and_then(|ph| pw.checked_mul(ph)))
|
||||
.and_then(|n| n.checked_mul(std::mem::size_of::<u32>()))
|
||||
.is_some_and(|bytes| bytes <= isize::MAX as usize)
|
||||
}
|
||||
|
||||
/// Reserve the already counted source centres exactly, then retain row-major order.
|
||||
fn source_centres(w: usize, valid: &[bool], count: usize, check: &impl Fn() -> Result<(), Cancelled>) -> Result<Vec<(i32, i32)>, Cancelled> {
|
||||
let mut centres = Vec::with_capacity(count);
|
||||
for (i, &is_valid) in valid.iter().enumerate() {
|
||||
if i % (w * 32) == 0 {
|
||||
check()?;
|
||||
}
|
||||
if is_valid {
|
||||
centres.push(((i % w) as i32, (i / w) as i32));
|
||||
}
|
||||
}
|
||||
Ok(centres)
|
||||
}
|
||||
|
||||
/// Summed-area table of a boolean grid (`(w+1) × (h+1)`).
|
||||
fn integral(w: usize, h: usize, m: &[bool]) -> Vec<u32> {
|
||||
let mut s = vec![0u32; (w + 1) * (h + 1)];
|
||||
for y in 0..h {
|
||||
let mut row = 0u32;
|
||||
for x in 0..w {
|
||||
row += u32::from(m[y * w + x]);
|
||||
s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row;
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`.
|
||||
fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 {
|
||||
let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
|
||||
let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh));
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return 0;
|
||||
}
|
||||
let w1 = gw + 1;
|
||||
s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0]
|
||||
}
|
||||
|
||||
fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> {
|
||||
let mut b: Option<(usize, usize, usize, usize)> = None;
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
if hole[y * w + x] {
|
||||
b = Some(match b {
|
||||
None => (x, y, x + 1, y + 1),
|
||||
Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Per-level PatchMatch/EM state.
|
||||
struct Solver<'a> {
|
||||
w: usize,
|
||||
h: usize,
|
||||
ch: usize,
|
||||
r: i32,
|
||||
img: &'a mut Vec<f32>,
|
||||
hole: &'a [bool],
|
||||
/// Valid source centres: the whole patch is inside the grid and contains no hole pixel.
|
||||
valid: Vec<bool>,
|
||||
valid_list: Vec<(i32, i32)>,
|
||||
/// Target centres (patch overlaps the hole), row-major.
|
||||
targets: Vec<bool>,
|
||||
/// Cancellation: checked per row band; a cancelled solve's output is discarded.
|
||||
ctl: &'a (dyn Fn() -> bool + Sync),
|
||||
}
|
||||
|
||||
impl Solver<'_> {
|
||||
#[inline]
|
||||
fn is_valid(&self, x: i32, y: i32) -> bool {
|
||||
x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize]
|
||||
}
|
||||
|
||||
/// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample.
|
||||
fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 {
|
||||
let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r);
|
||||
let diameter = f64::from(2 * r + 1);
|
||||
let full = (diameter * diameter) as f32 * ch as f32;
|
||||
let mut sum = 0.0f32;
|
||||
let mut n = 0usize;
|
||||
for dy in -r..=r {
|
||||
let ty = t.1 + dy;
|
||||
if ty < 0 || ty >= h {
|
||||
continue;
|
||||
}
|
||||
let sy = s.1 + dy;
|
||||
for dx in -r..=r {
|
||||
let tx = t.0 + dx;
|
||||
if tx < 0 || tx >= w {
|
||||
continue;
|
||||
}
|
||||
let ti = (ty as usize * self.w + tx as usize) * ch;
|
||||
let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch;
|
||||
for c in 0..ch {
|
||||
let d = self.img[ti + c] - self.img[si + c];
|
||||
sum += d * d;
|
||||
}
|
||||
n += ch;
|
||||
}
|
||||
// Early out: the mean can only be ≥ sum / (full patch size).
|
||||
if sum > cutoff * full {
|
||||
return f32::INFINITY;
|
||||
}
|
||||
}
|
||||
if n == 0 { f32::INFINITY } else { sum / n as f32 }
|
||||
}
|
||||
|
||||
/// One PatchMatch pass over all target rows, in parallel bands (each band propagates within itself).
|
||||
fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) {
|
||||
const BAND: usize = 16;
|
||||
let w = self.w;
|
||||
let reverse = pass % 2 == 1;
|
||||
let band_fn = |bi: usize, nn: &mut [(i32, i32)], co: &mut [f32]| {
|
||||
if (self.ctl)() {
|
||||
return;
|
||||
}
|
||||
let mut rng = Rng::new(seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40));
|
||||
let y0 = bi * BAND;
|
||||
let rows = nn.len() / w;
|
||||
let step: i32 = if reverse { -1 } else { 1 };
|
||||
for ry in 0..rows {
|
||||
let ly = if reverse { rows - 1 - ry } else { ry };
|
||||
let y = y0 + ly;
|
||||
for rx in 0..w {
|
||||
let x = if reverse { w - 1 - rx } else { rx };
|
||||
let li = ly * w + x;
|
||||
if !self.targets[y * w + x] {
|
||||
continue;
|
||||
}
|
||||
let t = (x as i32, y as i32);
|
||||
let (mut best, mut bc) = (nn[li], co[li]);
|
||||
// Propagation from the already-visited neighbours (within this band).
|
||||
let nx = x as i32 - step;
|
||||
if nx >= 0 && (nx as usize) < w {
|
||||
let c = nn[ly * w + nx as usize];
|
||||
let cand = (c.0 + step, c.1);
|
||||
if self.is_valid(cand.0, cand.1) && cand != best {
|
||||
let d = self.dist(t, cand, bc);
|
||||
if d < bc {
|
||||
(best, bc) = (cand, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
let nly = ly as i32 - step;
|
||||
if nly >= 0 && (nly as usize) < rows {
|
||||
let c = nn[nly as usize * w + x];
|
||||
let cand = (c.0, c.1 + step);
|
||||
if self.is_valid(cand.0, cand.1) && cand != best {
|
||||
let d = self.dist(t, cand, bc);
|
||||
if d < bc {
|
||||
(best, bc) = (cand, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Random search in exponentially shrinking windows.
|
||||
let mut rad = search_radius;
|
||||
while rad >= 1 {
|
||||
let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad));
|
||||
if self.is_valid(cand.0, cand.1) && cand != best {
|
||||
let d = self.dist(t, cand, bc);
|
||||
if d < bc {
|
||||
(best, bc) = (cand, d);
|
||||
}
|
||||
}
|
||||
rad /= 2;
|
||||
}
|
||||
nn[li] = best;
|
||||
co[li] = bc;
|
||||
}
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if w * self.h >= PAR_MIN {
|
||||
use rayon::prelude::*;
|
||||
nnf.par_chunks_mut(BAND * w).zip(cost.par_chunks_mut(BAND * w)).enumerate().for_each(|(bi, (nn, co))| band_fn(bi, nn, co));
|
||||
return;
|
||||
}
|
||||
for (bi, (nn, co)) in nnf.chunks_mut(BAND * w).zip(cost.chunks_mut(BAND * w)).enumerate() {
|
||||
band_fn(bi, nn, co);
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches.
|
||||
fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) {
|
||||
let (w, h, ch, r) = (self.w, self.h, self.ch, self.r);
|
||||
// σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this).
|
||||
let mut cs: Vec<f32> = cost.iter().zip(&self.targets).filter(|(c, t)| **t && c.is_finite()).map(|(c, _)| *c).collect();
|
||||
let sigma2 = if cs.is_empty() {
|
||||
1.0
|
||||
} else {
|
||||
let k = (cs.len() * 3 / 4).min(cs.len() - 1);
|
||||
let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b));
|
||||
v.max(1e-6)
|
||||
};
|
||||
let img = &*self.img;
|
||||
let row = |y: usize| -> Vec<(usize, Vec<f32>)> {
|
||||
let mut out = Vec::new();
|
||||
if (self.ctl)() {
|
||||
return out;
|
||||
}
|
||||
for x in 0..w {
|
||||
if !self.hole[y * w + x] {
|
||||
continue;
|
||||
}
|
||||
let mut acc = vec![0.0f32; ch];
|
||||
let mut wsum = 0.0f32;
|
||||
for dy in -r..=r {
|
||||
let ty = y as i32 + dy;
|
||||
if ty < 0 || ty as usize >= h {
|
||||
continue;
|
||||
}
|
||||
for dx in -r..=r {
|
||||
let tx = x as i32 + dx;
|
||||
if tx < 0 || tx as usize >= w {
|
||||
continue;
|
||||
}
|
||||
let ti = ty as usize * w + tx as usize;
|
||||
if !self.targets[ti] || !cost[ti].is_finite() {
|
||||
continue;
|
||||
}
|
||||
let s = nnf[ti];
|
||||
let (sx, sy) = (s.0 - dx, s.1 - dy);
|
||||
let wt = (-cost[ti] / (2.0 * sigma2)).exp().max(1e-8);
|
||||
let si = (sy as usize * w + sx as usize) * ch;
|
||||
for c in 0..ch {
|
||||
acc[c] += img[si + c] * wt;
|
||||
}
|
||||
wsum += wt;
|
||||
}
|
||||
}
|
||||
if wsum > 0.0 {
|
||||
acc.iter_mut().for_each(|v| *v /= wsum);
|
||||
out.push((x, acc));
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let rows: Vec<Vec<(usize, Vec<f32>)>> = if w * h >= PAR_MIN {
|
||||
use rayon::prelude::*;
|
||||
(0..h).into_par_iter().map(row).collect()
|
||||
} else {
|
||||
(0..h).map(row).collect()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let rows: Vec<Vec<(usize, Vec<f32>)>> = (0..h).map(row).collect();
|
||||
for (y, r) in rows.into_iter().enumerate() {
|
||||
for (x, v) in r {
|
||||
self.img[(y * w + x) * ch..(y * w + x + 1) * ch].copy_from_slice(&v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Content-aware completion of `hole` (see module docs). Returns `None` when there is no fully-known
|
||||
/// patch to copy from (the caller can fall back to [`membrane_fill`]).
|
||||
pub fn complete(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], p: &CompleteParams) -> Option<Vec<f32>> {
|
||||
// Never cancelled, so never `Err`.
|
||||
complete_with(w, h, ch, img, hole, p, &|| false).unwrap_or(None)
|
||||
}
|
||||
|
||||
/// [`complete`] that can be cancelled (checked per EM iteration, PatchMatch pass and row band)
|
||||
/// (`cancelled` is polled per EM iteration, PatchMatch pass and row band): `Err(Cancelled)` once it
|
||||
/// returned `true`. `Ok(None)` also for mismatched buffer sizes or `ch == 0`.
|
||||
pub fn complete_with(
|
||||
w: usize,
|
||||
h: usize,
|
||||
ch: usize,
|
||||
img: &[f32],
|
||||
hole: &[bool],
|
||||
p: &CompleteParams,
|
||||
cancelled: &(dyn Fn() -> bool + Sync),
|
||||
) -> Result<Option<Vec<f32>>, Cancelled> {
|
||||
// The workers poll `cancelled` too and can only stop early, not return an error. One `true` from it,
|
||||
// wherever it was seen, is kept, so the next check out here ends the call and a half-finished pass
|
||||
// is never returned as a result.
|
||||
let seen = AtomicBool::new(false);
|
||||
let cancelled: &(dyn Fn() -> bool + Sync) = &|| {
|
||||
if !seen.load(Ordering::Relaxed) && cancelled() {
|
||||
seen.store(true, Ordering::Relaxed);
|
||||
}
|
||||
seen.load(Ordering::Relaxed)
|
||||
};
|
||||
let check = || if cancelled() { Err(Cancelled) } else { Ok(()) };
|
||||
if ch == 0 || Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) {
|
||||
return Ok(None);
|
||||
}
|
||||
// No pixels (a zero width or height, whatever the other is): nothing to scan and nothing to fill.
|
||||
if hole.is_empty() {
|
||||
return Ok(Some(img.to_vec()));
|
||||
}
|
||||
if !supported_grid(w, h) {
|
||||
check()?;
|
||||
return Ok(None);
|
||||
}
|
||||
let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) };
|
||||
let r = p.patch_radius.max(1);
|
||||
// A patch wider than the image has no place to be copied from, which is the `None` the search below
|
||||
// would reach anyway. Said here, before `2 * r + 1` and `r as i32` can overflow on an absurd radius.
|
||||
if r > (w.min(h) - 1) / 2 {
|
||||
check()?;
|
||||
return Ok(None);
|
||||
}
|
||||
let psz = 2 * r + 1;
|
||||
// Pyramid: shrink until the hole is a few patches across.
|
||||
let mut levels = vec![Level { w, h, img: img.to_vec(), hole: hole.to_vec() }];
|
||||
let mut ext = (bx1 - bx0).max(by1 - by0);
|
||||
let mut exts = vec![ext];
|
||||
while let Some(l) = levels.last() {
|
||||
check()?;
|
||||
if ext <= 2 * psz || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz {
|
||||
break;
|
||||
}
|
||||
let d = downsample(l, ch);
|
||||
levels.push(d);
|
||||
ext = ext.div_ceil(2);
|
||||
exts.push(ext);
|
||||
}
|
||||
let nlev = levels.len();
|
||||
let mut nnf: Vec<(i32, i32)> = Vec::new();
|
||||
let mut prev: Option<(usize, usize, Vec<f32>)> = None;
|
||||
for li in (0..nlev).rev() {
|
||||
check()?;
|
||||
let Level { w: lw, h: lh, img: mut limg, hole: lhole } = levels[li].clone();
|
||||
// Initialise the hole: membrane at the coarsest level, upsampled result elsewhere.
|
||||
match &prev {
|
||||
None => limg = membrane_fill(lw, lh, ch, &limg, &lhole),
|
||||
Some((pw, ph, pimg)) => {
|
||||
for y in 0..lh {
|
||||
for x in 0..lw {
|
||||
if lhole[y * lw + x] {
|
||||
let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1));
|
||||
let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch);
|
||||
limg[d..d + ch].copy_from_slice(&pimg[s..s + ch]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let ri = r as i32;
|
||||
let hs = integral(lw, lh, &lhole);
|
||||
let mut valid = vec![false; lw * lh];
|
||||
let mut valid_count = 0;
|
||||
let mut targets = vec![false; lw * lh];
|
||||
for y in 0..lh as i32 {
|
||||
if y % 32 == 0 {
|
||||
check()?;
|
||||
}
|
||||
for x in 0..lw as i32 {
|
||||
let cnt = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1);
|
||||
let inside = x >= ri && y >= ri && x + ri < lw as i32 && y + ri < lh as i32;
|
||||
let i = y as usize * lw + x as usize;
|
||||
if inside && cnt == 0 {
|
||||
valid[i] = true;
|
||||
valid_count += 1;
|
||||
}
|
||||
targets[i] = cnt > 0;
|
||||
}
|
||||
}
|
||||
if valid_count == 0 {
|
||||
if li == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
prev = Some((lw, lh, limg));
|
||||
nnf.clear();
|
||||
continue;
|
||||
}
|
||||
let valid_list = source_centres(lw, &valid, valid_count, &check)?;
|
||||
let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: cancelled };
|
||||
// NNF init: upsampled from the coarser level where possible, random otherwise.
|
||||
let mut rng = Rng::new(p.seed ^ (li as u64) << 20);
|
||||
let pw_prev = prev.as_ref().map_or(0, |p| p.0);
|
||||
let old = std::mem::take(&mut nnf);
|
||||
let mut new_nnf = vec![(0i32, 0i32); lw * lh];
|
||||
for y in 0..lh {
|
||||
if y % 32 == 0 {
|
||||
check()?;
|
||||
}
|
||||
for x in 0..lw {
|
||||
if !solver.targets[y * lw + x] {
|
||||
continue;
|
||||
}
|
||||
let mut cand = None;
|
||||
if !old.is_empty() && pw_prev > 0 {
|
||||
let pi = (y / 2) * pw_prev + (x / 2);
|
||||
if let Some(&(sx, sy)) = old.get(pi) {
|
||||
let c = (sx * 2 + (x % 2) as i32, sy * 2 + (y % 2) as i32);
|
||||
if solver.is_valid(c.0, c.1) {
|
||||
cand = Some(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
new_nnf[y * lw + x] = cand.unwrap_or_else(|| solver.valid_list[(rng.next() % solver.valid_list.len() as u64) as usize]);
|
||||
}
|
||||
}
|
||||
nnf = new_nnf;
|
||||
let refine_only = li + 1 < nlev && exts[li] > p.refine_extent;
|
||||
let em = if li + 1 == nlev {
|
||||
p.em_iters
|
||||
} else if refine_only {
|
||||
1
|
||||
} else {
|
||||
(p.em_iters >> (nlev - 1 - li)).max(p.min_em_iters)
|
||||
};
|
||||
let pm_iters = if refine_only { 1 } else { p.pm_iters };
|
||||
let full_search = (lw.max(lh)) as i32;
|
||||
let mut cost = vec![f32::INFINITY; lw * lh];
|
||||
for it in 0..em {
|
||||
// Costs change as hole pixels are re-estimated: refresh before each PatchMatch.
|
||||
for (i, c) in cost.iter_mut().enumerate() {
|
||||
if i % (lw * 32).max(1) == 0 {
|
||||
check()?;
|
||||
}
|
||||
if solver.targets[i] {
|
||||
*c = solver.dist(((i % lw) as i32, (i / lw) as i32), nnf[i], f32::INFINITY);
|
||||
}
|
||||
}
|
||||
// Wide random search on coarse levels / first iteration, local refinement afterwards.
|
||||
let radius = if refine_only {
|
||||
2
|
||||
} else if li + 1 == nlev || it == 0 {
|
||||
full_search
|
||||
} else {
|
||||
(4 * psz).min(full_search as usize) as i32
|
||||
};
|
||||
for pass in 0..pm_iters {
|
||||
check()?;
|
||||
solver.patchmatch(&mut nnf, &mut cost, pass + it * pm_iters, p.seed.wrapping_add((li * 1000 + it) as u64), radius);
|
||||
}
|
||||
check()?;
|
||||
solver.vote(&nnf, &cost);
|
||||
check()?;
|
||||
}
|
||||
prev = Some((lw, lh, limg));
|
||||
}
|
||||
Ok(prev.map(|(_, _, img)| img))
|
||||
}
|
||||
|
||||
/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the
|
||||
/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Smooth gradient plus deterministic fine noise.
|
||||
fn texture(w: usize, h: usize) -> Vec<f32> {
|
||||
let mut rng = Rng::new(7);
|
||||
(0..w * h)
|
||||
.flat_map(|i| {
|
||||
let (x, y) = ((i % w) as f32, (i / w) as f32);
|
||||
let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02;
|
||||
[0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec<bool> {
|
||||
(0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect()
|
||||
}
|
||||
|
||||
fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 {
|
||||
let (mut e, mut n) = (0.0f32, 0);
|
||||
for (i, hh) in hole.iter().enumerate() {
|
||||
if *hh {
|
||||
for c in 0..ch {
|
||||
e += (a[i * ch + c] - b[i * ch + c]).powi(2);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
(e / n as f32).sqrt()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_limits_reject_narrowing_and_integral_overflow_without_allocating() {
|
||||
assert!(supported_grid(32, 32));
|
||||
assert!(supported_grid(16_384, 8_192));
|
||||
assert_eq!(supported_grid(20_000, 20_000), usize::BITS > 32);
|
||||
assert!(!supported_grid(i32::MAX as usize, 1));
|
||||
assert!(!supported_grid(65_536, 65_536));
|
||||
assert!(!supported_grid(usize::MAX, usize::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_fills_blemish_from_texture() {
|
||||
let (w, h, ch) = (96, 96, 3);
|
||||
let clean = texture(w, h);
|
||||
let hole = disc(w, h, 48.0, 48.0, 9.0);
|
||||
let mut dirty = clean.clone();
|
||||
for (i, hh) in hole.iter().enumerate() {
|
||||
if *hh {
|
||||
dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]);
|
||||
}
|
||||
}
|
||||
let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap();
|
||||
let before = hole_rmse(&dirty, &clean, &hole, ch);
|
||||
let after = hole_rmse(&out, &clean, &hole, ch);
|
||||
assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}");
|
||||
// Outside the hole untouched.
|
||||
assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b));
|
||||
// Deterministic.
|
||||
assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_continues_structure() {
|
||||
// Vertical stripes: the filled hole should keep the stripes (not a blur).
|
||||
let (w, h, ch) = (80, 80, 1);
|
||||
let clean: Vec<f32> = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect();
|
||||
let hole = disc(w, h, 40.0, 40.0, 7.0);
|
||||
let dirty: Vec<f32> = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect();
|
||||
let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap();
|
||||
let err = hole_rmse(&out, &clean, &hole, ch);
|
||||
assert!(err < 0.15, "{err}");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
//! Raw develop pipeline (CPU path), extracted from LightCraft.
|
||||
//! The raw develop pipeline, CPU path: the shared pipeline of craft-libs#587, moved from LightCraft one module at a
|
||||
//! time. See the README for what is here so far.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod color;
|
||||
pub mod curve;
|
||||
pub mod finish;
|
||||
pub mod inpaint;
|
||||
pub mod lut;
|
||||
pub mod tone;
|
||||
@@ -0,0 +1,696 @@
|
||||
//! The global tone map: scene luminance → display-linear luminance.
|
||||
//!
|
||||
//! Built in the log domain around middle grey (0.18): contrast scales log-exposure about grey,
|
||||
//! whites move the shoulder (white point), blacks move the toe. The shoulder is an extended
|
||||
//! Reinhard curve so highlights roll off smoothly instead of clipping.
|
||||
//!
|
||||
//! Rendered (display-referred) sources such as JPEGs use [`ToneMap::display`] instead: identity at
|
||||
//! neutral settings (an unedited JPEG renders exactly as the file), with contrast/whites/blacks as
|
||||
//! S-curve adjustments in a gamma-2.2 perceptual domain and a short shoulder above 0.95.
|
||||
|
||||
pub const GREY: f32 = 0.18;
|
||||
/// The tone LUT spans `LUT_MIN_EV..LUT_MAX_EV` around grey in `LUT_N` steps.
|
||||
pub const LUT_MIN_EV: f32 = -14.0;
|
||||
pub const LUT_MAX_EV: f32 = 10.0;
|
||||
pub const LUT_N: usize = 4096;
|
||||
/// Nodes of a camera chroma curve, evenly spaced over display luminance 0..=1.
|
||||
pub const CHROMA_N: usize = 8;
|
||||
const NO_CHROMA: [f32; CHROMA_N] = [1.0; CHROMA_N];
|
||||
|
||||
/// A file-local camera look, fitted independently of the scene-linear colour transform.
|
||||
/// Knots are scene/display-linear luminance pairs. Keeping this in the finish stage preserves
|
||||
/// RAW exposure and highlight headroom; it is never baked into the decoded sensor pixels.
|
||||
/// `chroma` scales colourfulness by display luminance after the curve (a camera's per-channel
|
||||
/// curve saturates shadows and bleaches highlights toward white, which a luminance curve can't).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
|
||||
pub struct CameraTone {
|
||||
knots: [[f32; 2]; 32],
|
||||
chroma: [f32; CHROMA_N],
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for CameraTone {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Wire {
|
||||
knots: [[f32; 2]; 32],
|
||||
// absent in smart previews written before the chroma curve existed
|
||||
#[serde(default)]
|
||||
chroma: Option<[f32; CHROMA_N]>,
|
||||
}
|
||||
let w = Wire::deserialize(d)?;
|
||||
let tone = Self::new(w.knots).ok_or_else(|| serde::de::Error::custom("invalid camera tone curve"))?;
|
||||
match w.chroma {
|
||||
Some(c) => tone.with_chroma(c).ok_or_else(|| serde::de::Error::custom("invalid camera chroma curve")),
|
||||
None => Ok(tone),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CameraTone {
|
||||
pub fn new(knots: [[f32; 2]; 32]) -> Option<Self> {
|
||||
let mut previous = [0.0, 0.0];
|
||||
for p in knots {
|
||||
if !p.iter().all(|v| v.is_finite()) || p[0] <= previous[0] || p[1] < previous[1] || p[1] >= 1.0 {
|
||||
return None;
|
||||
}
|
||||
previous = p;
|
||||
}
|
||||
Some(Self { knots, chroma: NO_CHROMA })
|
||||
}
|
||||
|
||||
/// The curve with chroma scales at display luminance 0, 1/7 … 1 (each finite, 0..=4).
|
||||
pub fn with_chroma(self, chroma: [f32; CHROMA_N]) -> Option<Self> {
|
||||
chroma.iter().all(|k| k.is_finite() && (0.0..=4.0).contains(k)).then_some(Self { chroma, ..self })
|
||||
}
|
||||
|
||||
pub fn chroma(&self) -> &[f32; CHROMA_N] {
|
||||
&self.chroma
|
||||
}
|
||||
|
||||
/// The (scene, display) luminance knots, in increasing order.
|
||||
pub fn knots(&self) -> &[[f32; 2]; 32] {
|
||||
&self.knots
|
||||
}
|
||||
|
||||
pub fn apply(&self, y: f32) -> f32 {
|
||||
if !y.is_finite() || y <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let mut previous = [0.0, 0.0];
|
||||
for p in self.knots {
|
||||
if y <= p[0] {
|
||||
let t = (y - previous[0]) / (p[0] - previous[0]);
|
||||
return previous[1] + t * (p[1] - previous[1]);
|
||||
}
|
||||
previous = p;
|
||||
}
|
||||
let a = self.knots[30];
|
||||
let b = self.knots[31];
|
||||
// Extend beyond observed (unclipped) highlights with a continuous, bounded shoulder.
|
||||
let slope = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0);
|
||||
1.0 - (1.0 - b[1]) * (-(y - b[0]) * slope / (1.0 - b[1]).max(0.01)).exp()
|
||||
}
|
||||
|
||||
/// [`CameraTone::apply`] as process V5 extends it past the last knot (issue #1632). The curve is
|
||||
/// fitted only to camera JPEG tones below 0.85, so its last knot lies 1 to 3 stops below the
|
||||
/// sensor's white on most photos and everything above it is extrapolated. [`CameraTone::apply`]
|
||||
/// closes the gap to white exponentially in linear light: it reaches 8-bit 255 within about a
|
||||
/// stop past the sensor's white, and Exposure +1 turns the top stop the sensor recorded white.
|
||||
/// Here the gap shrinks in stops instead, `gap / (1 + c·(2^(k·t) − 1))` at `t` stops past the
|
||||
/// knot, with `c` matching the curve's slope there (so the join is smooth) and the gap halving
|
||||
/// every [`ROLLOFF_STOPS`] stops in the end. Same value as [`CameraTone::apply`] up to the last
|
||||
/// knot, monotone, finite and at most 1. In real numbers it only approaches white; in `f32` the
|
||||
/// gap can round to 0 far up, and within a stop or two for a last knot a few ulps below white.
|
||||
pub fn apply_rolloff(&self, y: f32) -> f32 {
|
||||
let (a, b) = (self.knots[30], self.knots[31]);
|
||||
if !y.is_finite() || y <= b[0] {
|
||||
return self.apply(y);
|
||||
}
|
||||
// the last segment's own slope, so the join is smooth even when it is flat (`new` keeps the
|
||||
// knots non-decreasing, so it is at least 0)
|
||||
let slope = ((b[1] - a[1]) / (b[0] - a[0])).max(0.0);
|
||||
// `CameraTone::new` keeps the last knot below 1, so the gap is positive (no floor: one
|
||||
// would step the curve down past a knot within it of white)
|
||||
rolloff_past(y, b, slope, CAMERA_MIN_SLOPE)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pace [`CameraTone::apply_rolloff`] closes on white at least at, as display per unit of scene
|
||||
/// luminance at the last knot (the floor [`CameraTone::apply`] puts on its slope there). A last
|
||||
/// segment flatter than this still joins with its own slope; [`rolloff_past`] then adds a term that
|
||||
/// has no slope at the knot and reaches this pace further up, so a flat curve does not stay below
|
||||
/// white.
|
||||
const CAMERA_MIN_SLOPE: f32 = 0.1;
|
||||
|
||||
/// Stops in which the gap between a V5 curve and white halves, far past where its shoulder starts
|
||||
/// ([`CameraTone::apply_rolloff`], [`ToneMap::rolloff_hdr`]). With 1, the sensor's white renders at
|
||||
/// 8-bit 239–250 on the CC0 corpus files with a camera curve (Sony, Nikon, Fujifilm) at Exposure 0
|
||||
/// and below 254 up to Exposure +2, where the extension of [`CameraTone::apply`] reaches 254–255 by
|
||||
/// Exposure +1 (issue #1632).
|
||||
pub const ROLLOFF_STOPS: f32 = 1.0;
|
||||
|
||||
/// Process V5's shoulder past a knee at scene luminance `x` and display `o` (below 1), where the
|
||||
/// curve rises at `slope` (display per unit of scene luminance): the gap to white is
|
||||
/// `gap / (1 + c·(2^(k·t) − 1))` at `t = log2(y / x)` stops past the knee, `k = 1 / ROLLOFF_STOPS`,
|
||||
/// so it halves every [`ROLLOFF_STOPS`] stops in the end. `c` gives it the curve's slope at the
|
||||
/// knee: d(display)/d(stop) there is `slope · x · ln 2` on the curve and `gap · c · k · ln 2` on the
|
||||
/// shoulder. When `slope` is below `min_slope`, `d · (u − ln(1 + u))` (with `u = 2^(k·t) − 1`)
|
||||
/// joins the denominator: it adds no slope at the knee, so the join keeps the curve's own slope, and
|
||||
/// far up it grows like `d · u`, so the shoulder closes on white at `min_slope`'s pace (the gap still
|
||||
/// halves every [`ROLLOFF_STOPS`] stops in the end). A term growing faster than `u` would close a
|
||||
/// flat curve on white faster than a steeper one far up, and a darker curve would end up above it.
|
||||
/// Monotone for `y ≥ x`, finite and at most 1; in real numbers it only approaches white, while in
|
||||
/// `f32` the gap rounds to 0 eventually.
|
||||
fn rolloff_past(y: f32, [x, o]: [f32; 2], slope: f32, min_slope: f32) -> f32 {
|
||||
let gap = 1.0 - o;
|
||||
let k = 1.0 / ROLLOFF_STOPS;
|
||||
// bounded, so `c · 0` right past the knee stays 0 for a gap of a few ulps
|
||||
let per = |s: f32| (s * x / (gap * k)).min(1e30);
|
||||
let c = per(slope);
|
||||
let d = (per(min_slope) - c).max(0.0);
|
||||
let u = (k * (y / x).log2()).exp2() - 1.0;
|
||||
// each term only when its coefficient is positive: `0 · ∞` is NaN far up
|
||||
let linear = if c > 0.0 { c * u } else { 0.0 };
|
||||
let floor = if d > 0.0 { d * past_join(u) } else { 0.0 };
|
||||
1.0 - gap / (1.0 + linear + floor)
|
||||
}
|
||||
|
||||
/// `u − ln(1 + u)` for `u ≥ 0`: 0 with no slope at 0, then rising like `u` (infinite for infinite
|
||||
/// `u`). In `f64`, where the difference keeps its digits down to tiny `u`.
|
||||
fn past_join(u: f32) -> f32 {
|
||||
if u.is_infinite() {
|
||||
return u;
|
||||
}
|
||||
let u = f64::from(u);
|
||||
(u - u.ln_1p()).max(0.0) as f32
|
||||
}
|
||||
|
||||
/// Stops below its white point where process V5's generic raw curve ([`ToneMap::rolloff_hdr`])
|
||||
/// leaves the extended Reinhard curve for the [`ROLLOFF_STOPS`] shoulder, instead of clipping at
|
||||
/// the white point. With ½, the sensor's white of a raw without a camera curve (scene 1.0, about
|
||||
/// ¼ stop below that white point at default settings) renders at about 8-bit 235, 248 and 252 at
|
||||
/// Exposure 0, +1 and +2 where V1 to V4 render 239, 255 and 255 (issue #1632).
|
||||
pub const GENERIC_KNEE_STOPS: f32 = 0.5;
|
||||
|
||||
/// Scene EV over grey where [`ToneMap::hdr`] starts lifting highlights above the SDR curve.
|
||||
const HDR_FROM_EV: f32 = 1.5;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ToneMap {
|
||||
lut: Vec<f32>,
|
||||
chroma: [f32; CHROMA_N],
|
||||
}
|
||||
|
||||
impl ToneMap {
|
||||
pub fn camera(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64) -> ToneMap {
|
||||
ToneMap::camera_hdr(curve, contrast, whites, blacks, 1.0)
|
||||
}
|
||||
|
||||
/// [`ToneMap::camera`] for an HDR render reaching `peak` (linear, SDR white = 1; 1 = SDR
|
||||
/// exactly): the camera's look up to 1.5 EV over grey, so midtones match the SDR render (and a
|
||||
/// gain map only lifts highlights), then the highlights gain up to `peak − 1` more as in
|
||||
/// [`ToneMap::hdr`].
|
||||
pub fn camera_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::camera_with(|y| curve.apply(y), curve.chroma, contrast, whites, blacks, peak)
|
||||
}
|
||||
|
||||
/// [`ToneMap::camera_hdr`] of process V5: past its last knot the camera curve rolls off in stops
|
||||
/// ([`CameraTone::apply_rolloff`]) instead of closing on white within a stop of the sensor's.
|
||||
pub fn camera_rolloff_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::camera_with(|y| curve.apply_rolloff(y), curve.chroma, contrast, whites, blacks, peak)
|
||||
}
|
||||
|
||||
fn camera_with(curve: impl Fn(f32) -> f32, chroma: [f32; CHROMA_N], contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 };
|
||||
let adjustment = Self::display(contrast, whites, blacks);
|
||||
let neutral = contrast == 0.0 && whites == 0.0 && blacks == 0.0;
|
||||
let top = (2.9 - 1.6 * (whites as f32 / 100.0) + peak.log2() + 1.0).max(HDR_FROM_EV + 0.5);
|
||||
let lut = (0..LUT_N)
|
||||
.map(|i| {
|
||||
let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32;
|
||||
let y = curve(GREY * 2f32.powf(ev));
|
||||
let o = if neutral { y } else { adjustment.apply(y) };
|
||||
if peak > 1.0 { (o + (peak - 1.0) * smooth(HDR_FROM_EV, top, ev)).clamp(0.0, peak) } else { o }
|
||||
})
|
||||
.collect();
|
||||
ToneMap { lut, chroma }
|
||||
}
|
||||
/// `contrast`, `whites`, `blacks` in −100..100 (Lightroom slider units).
|
||||
pub fn new(contrast: f64, whites: f64, blacks: f64) -> ToneMap {
|
||||
ToneMap::hdr(contrast, whites, blacks, 1.0)
|
||||
}
|
||||
|
||||
/// [`ToneMap::new`] for an HDR render reaching `peak` (linear, SDR white = 1; 1 = SDR exactly).
|
||||
/// Below about half of SDR white the curve is the SDR one; above, the highlights gain up to
|
||||
/// `peak − 1` more along a smoothstep in scene EV, from 1.5 EV over grey to one stop past the
|
||||
/// white point moved up by the headroom, so the result stays monotone, never exceeds `peak`,
|
||||
/// and reaches it there (within the table's range).
|
||||
pub fn hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::generic(contrast, whites, blacks, peak, false)
|
||||
}
|
||||
|
||||
/// [`ToneMap::hdr`] of process V5 (issue #1632): from [`GENERIC_KNEE_STOPS`] below the white
|
||||
/// point the curve rolls off into white in stops, with the same value and slope at the join,
|
||||
/// instead of reaching white about ¼ stop past the sensor's white and clipping there. The SDR
|
||||
/// curve stays below 1 (SDR white) and is the same as [`ToneMap::hdr`]'s below the join; for
|
||||
/// `peak` above 1 the HDR lift then takes highlights up to `peak`, as in [`ToneMap::hdr`].
|
||||
pub fn rolloff_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::generic(contrast, whites, blacks, peak, true)
|
||||
}
|
||||
|
||||
fn generic(contrast: f64, whites: f64, blacks: f64, peak: f32, rolloff: bool) -> ToneMap {
|
||||
let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 };
|
||||
let c = (contrast / 100.0) as f32;
|
||||
let slope = if c >= 0.0 { 1.0 + 0.55 * c } else { 1.0 + 0.4 * c };
|
||||
// White point: scene luminance (after contrast) that maps to display 1.0.
|
||||
let white_ev = 2.9 - 1.6 * (whites as f32 / 100.0);
|
||||
let wl = GREY * 2f32.powf(white_ev);
|
||||
let pre = 1.0 + GREY / wl; // keep grey near grey
|
||||
let b = (blacks / 100.0) as f32;
|
||||
// extended Reinhard with white point wl: y(1 + y/wl²)/(1 + y), reaching 1 at wl
|
||||
let reinhard = |y: f32| y * (1.0 + y / (wl * wl)) / (1.0 + y);
|
||||
// V5's knee, below the white point, and the curve's slope there: (1 + y(2 + y)/wl²)/(1 + y)²
|
||||
let knee = wl * (-GENERIC_KNEE_STOPS).exp2();
|
||||
let knee_slope = (1.0 + knee * (2.0 + knee) / (wl * wl)) / ((1.0 + knee) * (1.0 + knee));
|
||||
let knee = [knee, reinhard(knee)];
|
||||
let lut = (0..LUT_N)
|
||||
.map(|i| {
|
||||
let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32;
|
||||
let y = GREY * 2f32.powf(ev * slope) * pre;
|
||||
let mut o = if rolloff && y > knee[0] && knee[1] < 1.0 { rolloff_past(y, knee, knee_slope, 0.0) } else { reinhard(y) };
|
||||
o = o.min(1.0);
|
||||
// Toe: blacks < 0 crushes, > 0 lifts.
|
||||
if b < 0.0 {
|
||||
// Smooth max(0, o − k) (a soft knee), renormalized so 1 stays 1.
|
||||
let k = -b * 0.035;
|
||||
let e = 0.004;
|
||||
let soft = |v: f32| ((v - k) + ((v - k) * (v - k) + e * e).sqrt()) * 0.5;
|
||||
o = (soft(o) - soft(0.0)) / (soft(1.0) - soft(0.0));
|
||||
} else if b > 0.0 {
|
||||
let k = b * 0.03;
|
||||
o = k + (1.0 - k) * o;
|
||||
}
|
||||
if peak > 1.0 {
|
||||
let top = (white_ev + peak.log2() + 1.0).max(HDR_FROM_EV + 0.5);
|
||||
o += (peak - 1.0) * smooth(HDR_FROM_EV, top, ev * slope);
|
||||
}
|
||||
o.clamp(0.0, peak)
|
||||
})
|
||||
.collect();
|
||||
ToneMap { lut, chroma: NO_CHROMA }
|
||||
}
|
||||
|
||||
/// Tone map for display-referred sources: identity at neutral settings.
|
||||
pub fn display(contrast: f64, whites: f64, blacks: f64) -> ToneMap {
|
||||
ToneMap::display_hdr(contrast, whites, blacks, 1.0)
|
||||
}
|
||||
|
||||
/// [`ToneMap::display`] for an HDR render reaching `peak`: values above SDR white (an HDR
|
||||
/// source, e.g. a decoded gain-map image) pass through and roll off softly towards `peak`
|
||||
/// instead of clipping at 1; SDR sources (≤ 1) render as with [`ToneMap::display`].
|
||||
pub fn display_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 };
|
||||
let c = (contrast / 100.0) as f32;
|
||||
let w = (whites / 100.0) as f32;
|
||||
let b = (blacks / 100.0) as f32;
|
||||
let m = GREY.powf(1.0 / 2.2);
|
||||
// Neutral sliders are the identity up to white (issue #1945): the SDR shoulder below would
|
||||
// pull 1.0 down to 0.9875 (8-bit 255 to 254), so it only shapes an edited curve.
|
||||
let neutral = c == 0.0 && w == 0.0 && b == 0.0;
|
||||
let lut = (0..LUT_N)
|
||||
.map(|i| {
|
||||
let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32;
|
||||
let y = GREY * 2f32.powf(ev);
|
||||
let mut p = y.powf(1.0 / 2.2);
|
||||
if p <= 1.0 {
|
||||
// S-curve anchored at 0, grey and 1
|
||||
p += c * 0.35 * (p - m) * (1.0 - (2.0 * p - 1.0).powi(2));
|
||||
// whites: lift/lower the upper tones; blacks: the lower tones
|
||||
let up = smooth(0.45, 1.0, p);
|
||||
p += w * 0.12 * up * (1.0 - p * 0.5);
|
||||
let lo = 1.0 - smooth(0.0, 0.45, p);
|
||||
p += b * 0.07 * lo * (p * 2.0).min(1.0);
|
||||
} else {
|
||||
p += w * 0.12 * 0.5;
|
||||
}
|
||||
let mut o = p.max(0.0).powf(2.2);
|
||||
// short shoulder (SDR, edited curves): slope 1 at 0.95, reaching 1.0 at 1.05
|
||||
if peak > 1.0 && o > 0.95 {
|
||||
// exponential shoulder: slope 1 at 0.95, asymptote at `peak`
|
||||
let r = peak - 0.95;
|
||||
o = 0.95 + r * (1.0 - (-(o - 0.95) / r).exp());
|
||||
} else if o > 0.95 && !neutral {
|
||||
let d = (o - 0.95).min(0.1);
|
||||
o = 0.95 + d - d * d / 0.2;
|
||||
}
|
||||
o.clamp(0.0, peak)
|
||||
})
|
||||
.collect();
|
||||
ToneMap { lut, chroma: NO_CHROMA }
|
||||
}
|
||||
|
||||
/// The table (`LUT_N` entries, see [`ToneMap::apply`]).
|
||||
pub fn lut(&self) -> &[f32] {
|
||||
&self.lut
|
||||
}
|
||||
|
||||
/// The chroma curve (`CHROMA_N` entries, see [`ToneMap::chroma_scale`]).
|
||||
pub fn chroma_lut(&self) -> &[f32] {
|
||||
&self.chroma
|
||||
}
|
||||
|
||||
/// Chroma scale at display luminance `o` (exactly 1 everywhere unless a camera look sets it).
|
||||
#[inline]
|
||||
pub fn chroma_scale(&self, o: f32) -> f32 {
|
||||
if !o.is_finite() {
|
||||
return 1.0;
|
||||
}
|
||||
let f = o.clamp(0.0, 1.0) * (CHROMA_N - 1) as f32;
|
||||
let i = (f as usize).min(CHROMA_N - 2);
|
||||
let t = f - i as f32;
|
||||
let (a, b) = (self.chroma.get(i).copied().unwrap_or(1.0), self.chroma.get(i + 1).copied().unwrap_or(1.0));
|
||||
if a == b { a } else { a + (b - a) * t }
|
||||
}
|
||||
|
||||
/// Scene luminance → display-linear luminance.
|
||||
#[inline]
|
||||
pub fn apply(&self, y: f32) -> f32 {
|
||||
if y <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let ev = (y / GREY).log2();
|
||||
let f = ((ev - LUT_MIN_EV) / (LUT_MAX_EV - LUT_MIN_EV)).clamp(0.0, 1.0) * (LUT_N - 1) as f32;
|
||||
let i = (f as usize).min(LUT_N - 2);
|
||||
let t = f - i as f32;
|
||||
let v = self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t;
|
||||
if ev < LUT_MIN_EV { v * (y / (GREY * 2f32.powf(LUT_MIN_EV))) } else { v }
|
||||
}
|
||||
}
|
||||
|
||||
fn smooth(e0: f32, e1: f32, x: f32) -> f32 {
|
||||
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn knots() -> [[f32; 2]; 32] {
|
||||
std::array::from_fn(|i| {
|
||||
let x = 0.004 * 1.18f32.powi(i as i32);
|
||||
[x, 1.0 - (-2.0 * x).exp()]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chroma_curve_is_identity_unless_set_and_survives_serde() {
|
||||
let plain = CameraTone::new(knots()).unwrap();
|
||||
let map = ToneMap::camera(&plain, 0.0, 0.0, 0.0);
|
||||
assert!([0.0, 0.3, 0.77, 1.0, 2.0].iter().all(|o| map.chroma_scale(*o) == 1.0));
|
||||
assert!([0.0, 0.5, 1.0].iter().all(|o| ToneMap::new(0.0, 0.0, 0.0).chroma_scale(*o) == 1.0));
|
||||
// smart previews written before the chroma curve existed still load (identity)
|
||||
let old = serde_json::json!({ "knots": knots() });
|
||||
assert_eq!(serde_json::from_value::<CameraTone>(old).unwrap(), plain);
|
||||
let tone = plain.with_chroma([1.4, 1.3, 1.1, 1.0, 0.7, 0.4, 0.25, 0.2]).unwrap();
|
||||
let back: CameraTone = serde_json::from_value(serde_json::to_value(tone).unwrap()).unwrap();
|
||||
assert_eq!(back, tone);
|
||||
let map = ToneMap::camera(&tone, 0.0, 0.0, 0.0);
|
||||
assert!((map.chroma_scale(0.0) - 1.4).abs() < 1e-6 && (map.chroma_scale(1.0) - 0.2).abs() < 1e-6);
|
||||
assert!((map.chroma_scale(0.5 / 7.0) - 1.35).abs() < 1e-5, "interpolates between nodes");
|
||||
assert_eq!(map.chroma_scale(f32::NAN), 1.0);
|
||||
// hostile values are rejected, also when deserialized
|
||||
assert!(plain.with_chroma([f32::NAN; CHROMA_N]).is_none());
|
||||
assert!(plain.with_chroma([-1.0; CHROMA_N]).is_none());
|
||||
let bad = serde_json::json!({ "knots": knots(), "chroma": [9.0, 1, 1, 1, 1, 1, 1, 1] });
|
||||
assert!(serde_json::from_value::<CameraTone>(bad).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_curve_preserves_black_and_extends_headroom() {
|
||||
let knots = std::array::from_fn(|i| {
|
||||
let x = 0.005 * 1.15f32.powi(i as i32);
|
||||
[x, 1.0 - (-3.0 * x).exp()]
|
||||
});
|
||||
let curve = CameraTone::new(knots).unwrap();
|
||||
let base = ToneMap::camera(&curve, 0.0, 0.0, 0.0);
|
||||
assert_eq!(base.apply(0.0), 0.0);
|
||||
assert!(base.apply(0.1) < base.apply(0.2));
|
||||
let mut previous = 0.0;
|
||||
for i in 0..2000 {
|
||||
let y = 1e-6 * 1.01f32.powi(i);
|
||||
let v = base.apply(y);
|
||||
assert!((0.0..=1.0).contains(&v));
|
||||
assert!(v >= previous - 1e-6);
|
||||
previous = v;
|
||||
}
|
||||
assert!((base.apply(0.1) - curve.apply(0.1)).abs() < 0.001);
|
||||
assert!(ToneMap::camera(&curve, 50.0, 0.0, 0.0).apply(0.3) > base.apply(0.3));
|
||||
let mut invalid = knots;
|
||||
invalid[1][0] = invalid[0][0];
|
||||
assert!(CameraTone::new(invalid).is_none());
|
||||
assert!(serde_json::from_value::<CameraTone>(serde_json::json!({"knots": invalid})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolloff_joins_the_curve_smoothly_and_never_reaches_white() {
|
||||
let curve = CameraTone::new(knots()).unwrap();
|
||||
let last = curve.knots()[31];
|
||||
// the camera's curve up to the last knot
|
||||
for i in 0..200 {
|
||||
let y = last[0] * i as f32 / 199.0;
|
||||
assert_eq!(curve.apply_rolloff(y), curve.apply(y), "{y}");
|
||||
}
|
||||
// continuous, with the slope of the last segment, at the knot
|
||||
let a = curve.knots()[30];
|
||||
let slope = (last[1] - a[1]) / (last[0] - a[0]);
|
||||
let h = last[0] * 1e-3;
|
||||
let after = (curve.apply_rolloff(last[0] + h) - curve.apply_rolloff(last[0])) / h;
|
||||
assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}");
|
||||
// monotone, below white, and slower to close on it than the V1/V2 extension
|
||||
let mut previous = last[1];
|
||||
for i in 1..3000 {
|
||||
let y = last[0] * 1.005f32.powi(i);
|
||||
let o = curve.apply_rolloff(y);
|
||||
assert!(o >= previous && o < 1.0, "{y}: {o}");
|
||||
assert!(o <= curve.apply(y) + 1e-6, "{y}");
|
||||
previous = o;
|
||||
}
|
||||
assert!(1.0 - curve.apply_rolloff(last[0] * 8.0) > 4.0 * (1.0 - curve.apply(last[0] * 8.0)));
|
||||
// a steep last segment joins with its own slope, and a last knot next to white without a step
|
||||
for top in [0.9, 0.99995, 1.0 - f32::EPSILON] {
|
||||
let mut k = knots();
|
||||
k[31] = [k[30][0] * 1.01, top];
|
||||
let c = CameraTone::new(k).unwrap();
|
||||
let slope = (k[31][1] - k[30][1]) / (k[31][0] - k[30][0]);
|
||||
assert!(slope > 16.0 || top < 0.99, "{slope}");
|
||||
let mut prev = c.apply_rolloff(k[31][0]);
|
||||
assert_eq!(prev, top);
|
||||
for i in 1..2000 {
|
||||
let o = c.apply_rolloff(k[31][0] * 1.0001f32.powi(i));
|
||||
assert!(o.is_finite() && o >= prev && o <= 1.0, "{top} {i}: {o} < {prev}");
|
||||
prev = o;
|
||||
}
|
||||
if top == 0.9 {
|
||||
let h = k[31][0] * 1e-5;
|
||||
let after = (c.apply_rolloff(k[31][0] + h) - top) / h;
|
||||
assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}");
|
||||
}
|
||||
}
|
||||
// a flat or shallow last segment joins with its own slope (not the 0.1 floor of the V1/V2
|
||||
// extension) and still closes on white further up
|
||||
for s in [0.0f32, 0.05] {
|
||||
let mut k = knots();
|
||||
k[31][1] = k[30][1] + s * (k[31][0] - k[30][0]);
|
||||
let c = CameraTone::new(k).unwrap();
|
||||
let (x, top) = (k[31][0], k[31][1]);
|
||||
let h = x * 1e-4;
|
||||
let after = (c.apply_rolloff(x + h) - top) / h;
|
||||
assert!((after - s).abs() < 0.01, "{s}: right slope {after}");
|
||||
let mut prev = top;
|
||||
for i in 1..3000 {
|
||||
let o = c.apply_rolloff(x * 1.005f32.powi(i));
|
||||
assert!(o.is_finite() && o >= prev && o <= 1.0, "{s} {i}: {o} < {prev}");
|
||||
prev = o;
|
||||
}
|
||||
assert!(1.0 - c.apply_rolloff(x * 64.0) < (1.0 - top) / 4.0, "{s}");
|
||||
for y in [f32::MAX, f32::INFINITY] {
|
||||
assert!((0.0..=1.0).contains(&c.apply_rolloff(y)), "{s} {y}");
|
||||
}
|
||||
}
|
||||
// hostile input
|
||||
for y in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX] {
|
||||
let o = curve.apply_rolloff(y);
|
||||
assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}");
|
||||
}
|
||||
// the tone map built from it is monotone and bounded, SDR and HDR
|
||||
for peak in [1.0f32, 4.0] {
|
||||
let t = ToneMap::camera_rolloff_hdr(&curve, 0.0, 0.0, 0.0, peak);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2400 {
|
||||
let o = t.apply(1e-5 * 1.01f32.powi(i));
|
||||
assert!((0.0..=peak).contains(&o) && o >= prev - 1e-6, "{peak} {i}: {o}");
|
||||
prev = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_rolloff_joins_the_curve_smoothly_and_never_reaches_white() {
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0), (0.0, -100.0, 0.0)] {
|
||||
for peak in [1.0f32, 4.0] {
|
||||
let (clip, roll) = (ToneMap::hdr(c, w, b, peak), ToneMap::rolloff_hdr(c, w, b, peak));
|
||||
let (clip, roll) = (clip.lut(), roll.lut());
|
||||
// the generic curve up to the knee, never brighter past it
|
||||
let join = roll.iter().zip(clip).position(|(r, c)| r != c).expect("the shoulder starts inside the table");
|
||||
assert!(join > 2 && roll[join] < clip[join], "{c} {w} {b} {peak}: {join}");
|
||||
for (i, (r, c)) in roll.iter().zip(clip).enumerate() {
|
||||
assert!(*r <= c + 1e-6, "{c} {w} {b} {peak} {i}: {r} > {c}");
|
||||
}
|
||||
// same value and slope at the join: the step across it is the step before it
|
||||
let (before, across) = (roll[join - 1] - roll[join - 2], roll[join] - roll[join - 1]);
|
||||
assert!((across / before - 1.0).abs() < 0.02, "{c} {w} {b} {peak}: {before} then {across}");
|
||||
// monotone, and below white where the V1/V2 curve clips (SDR) or lifts to `peak` (HDR)
|
||||
assert!(roll.windows(2).all(|p| p[1] >= p[0] - 1e-6), "{c} {w} {b} {peak}");
|
||||
if peak == 1.0 {
|
||||
assert_eq!(clip[LUT_N - 1], 1.0);
|
||||
// close to it at the top of the table at default settings (10 EV over grey);
|
||||
// Whites −100 moves the white point, and so the shoulder, up 1.6 stops
|
||||
let top = roll[LUT_N - 1];
|
||||
assert!(top < 1.0 && (top > 0.999 || w < 0.0), "{c} {w} {b}: {top}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// no kink where V1/V2 clip: there the clipped curve stops rising at once
|
||||
let (clip, roll) = (ToneMap::new(0.0, 0.0, 0.0), ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0));
|
||||
let kink = |lut: &[f32]| lut.windows(3).filter(|p| p[1] - p[0] > 1e-5).map(|p| 1.0 - (p[2] - p[1]) / (p[1] - p[0])).fold(0.0f32, f32::max);
|
||||
assert!(kink(clip.lut()) > 0.9);
|
||||
assert!(kink(roll.lut()) < 0.05, "{}", kink(roll.lut()));
|
||||
// hostile input (NaN passes through `ToneMap::apply` as on every curve)
|
||||
for y in [f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX, f32::MIN_POSITIVE] {
|
||||
let o = roll.apply(y);
|
||||
assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monotone_and_bounded() {
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] {
|
||||
let t = ToneMap::new(c, w, b);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2000 {
|
||||
let y = 1e-5 * 1.012f32.powi(i);
|
||||
let o = t.apply(y);
|
||||
assert!((0.0..=1.0).contains(&o));
|
||||
assert!(o >= prev - 1e-6, "{c} {w} {b} at {y}: {o} < {prev}");
|
||||
prev = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdr_is_sdr_at_peak_one_and_reaches_peak() {
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] {
|
||||
assert_eq!(ToneMap::hdr(c, w, b, 1.0).lut(), ToneMap::new(c, w, b).lut());
|
||||
for peak in [2.0f32, 8.0, 32.0] {
|
||||
let sdr = ToneMap::new(c, w, b);
|
||||
let t = ToneMap::hdr(c, w, b, peak);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2400 {
|
||||
let y = 1e-5 * 1.01f32.powi(i);
|
||||
let o = t.apply(y);
|
||||
assert!((0.0..=peak).contains(&o), "{c} {w} {b} {peak} at {y}: {o}");
|
||||
assert!(o >= prev - 1e-6, "{c} {w} {b} {peak} at {y}: {o} < {prev}");
|
||||
prev = o;
|
||||
if y <= GREY * 2f32.powf(0.9) {
|
||||
assert!((o - sdr.apply(y)).abs() < 1e-6, "midtones differ at {y}");
|
||||
}
|
||||
}
|
||||
assert!(t.apply(4.0) > sdr.apply(4.0));
|
||||
if (c, w, b) == (0.0, 0.0, 0.0) {
|
||||
assert!(t.apply(GREY * 2f32.powf(LUT_MAX_EV)) > peak * 0.99, "{peak}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// a broken peak falls back to SDR
|
||||
assert_eq!(ToneMap::hdr(0.0, 0.0, 0.0, f32::NAN).lut(), ToneMap::new(0.0, 0.0, 0.0).lut());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_hdr_keeps_the_camera_look_and_lifts_highlights() {
|
||||
let curve = CameraTone::new(knots()).unwrap().with_chroma([1.2, 1.1, 1.0, 1.0, 0.9, 0.8, 0.7, 0.6]).unwrap();
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (40.0, -30.0, -20.0)] {
|
||||
let sdr = ToneMap::camera(&curve, c, w, b);
|
||||
assert_eq!(ToneMap::camera_hdr(&curve, c, w, b, 1.0).lut(), sdr.lut());
|
||||
assert_eq!(ToneMap::camera_hdr(&curve, c, w, b, f32::NAN).lut(), sdr.lut());
|
||||
for peak in [2.0f32, 8.0] {
|
||||
let t = ToneMap::camera_hdr(&curve, c, w, b, peak);
|
||||
assert_eq!(t.chroma_lut(), sdr.chroma_lut());
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2400 {
|
||||
let y = 1e-5 * 1.01f32.powi(i);
|
||||
let o = t.apply(y);
|
||||
assert!((0.0..=peak).contains(&o), "{peak} at {y}: {o}");
|
||||
assert!(o >= prev - 1e-6, "{peak} at {y}: {o} < {prev}");
|
||||
prev = o;
|
||||
// the camera's midtones, not the generic HDR curve's (issue: dark HDR exports)
|
||||
if y <= GREY * 2f32.powf(HDR_FROM_EV - 0.01) {
|
||||
assert!((o - sdr.apply(y)).abs() < 1e-6, "midtones differ at {y}: {o} vs {}", sdr.apply(y));
|
||||
}
|
||||
}
|
||||
assert!(t.apply(4.0) > 1.0 && t.apply(4.0) > sdr.apply(4.0) + 0.5, "{peak}: highlights lifted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_hdr_passes_hdr_sources_and_keeps_sdr() {
|
||||
assert_eq!(ToneMap::display_hdr(20.0, 10.0, -5.0, 1.0).lut(), ToneMap::display(20.0, 10.0, -5.0).lut());
|
||||
let t = ToneMap::display_hdr(0.0, 0.0, 0.0, 8.0);
|
||||
for i in 1..=90 {
|
||||
let y = i as f32 / 100.0;
|
||||
assert!((t.apply(y) - y).abs() < 2e-3, "{y} -> {}", t.apply(y));
|
||||
}
|
||||
let mut prev = 0.0;
|
||||
for i in 1..2000 {
|
||||
let o = t.apply(i as f32 / 100.0);
|
||||
assert!(o >= prev - 1e-6 && o <= 8.0);
|
||||
prev = o;
|
||||
}
|
||||
assert!(t.apply(3.0) > 2.0 && t.apply(3.0) < 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_identity_and_monotone() {
|
||||
let t = ToneMap::display(0.0, 0.0, 0.0);
|
||||
// up to and including white (issue #1945: 1.0 came out as 0.9875, 8-bit 255 as 254); the
|
||||
// tolerance is the LUT's interpolation next to the clip at 1.0, far below an 8-bit level
|
||||
for i in 1..=100 {
|
||||
let y = i as f32 / 100.0;
|
||||
assert!((t.apply(y) - y).abs() < 1e-3, "{y} -> {}", t.apply(y));
|
||||
}
|
||||
assert_eq!(t.apply(4.0), 1.0, "neutral values pushed above white clip");
|
||||
for (c, w, b) in [(100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (60.0, -40.0, 30.0)] {
|
||||
let t = ToneMap::display(c, w, b);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..1000 {
|
||||
let o = t.apply(i as f32 / 500.0);
|
||||
assert!(o >= prev - 1e-5, "{c} {w} {b}");
|
||||
prev = o;
|
||||
}
|
||||
}
|
||||
let c = ToneMap::display(60.0, 0.0, 0.0);
|
||||
assert!(c.apply(0.05) < 0.05 && c.apply(0.7) > 0.7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_shoulder_stays_on_edited_curves() {
|
||||
// The short shoulder is part of the V1 look of edited curves (docs/process-versions.md);
|
||||
// only neutral settings are the identity.
|
||||
for (c, w, b) in [(20.0, 0.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, -5.0)] {
|
||||
let t = ToneMap::display(c, w, b);
|
||||
let o = t.apply(1.0);
|
||||
assert!(o < 0.999 && o > 0.95, "{c} {w} {b}: {o}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grey_stays_near_grey_and_highlights_roll_off() {
|
||||
let t = ToneMap::new(0.0, 0.0, 0.0);
|
||||
let g = t.apply(0.18);
|
||||
assert!((0.15..0.24).contains(&g), "{g}");
|
||||
assert!(t.apply(1.0) < 0.95 && t.apply(1.0) > 0.6);
|
||||
assert!(t.apply(8.0) > 0.97);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliders_move_the_right_way() {
|
||||
let base = ToneMap::new(0.0, 0.0, 0.0);
|
||||
let contrast = ToneMap::new(60.0, 0.0, 0.0);
|
||||
assert!(contrast.apply(0.05) < base.apply(0.05));
|
||||
assert!(contrast.apply(0.8) > base.apply(0.8));
|
||||
assert!(ToneMap::new(0.0, 60.0, 0.0).apply(0.8) > base.apply(0.8));
|
||||
assert!(ToneMap::new(0.0, 0.0, -60.0).apply(0.01) < base.apply(0.01));
|
||||
assert!(ToneMap::new(0.0, 0.0, 60.0).apply(0.01) > base.apply(0.01));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,60 @@
|
||||
//! Parity with LightCraft (craft-libs#587): the hole fills of one scene are what `lightcraft-inpaint` at
|
||||
//! `a75497d6` gave for it. The fixtures in `tests/fixtures/` are that crate's `complete` (default parameters) and
|
||||
//! `membrane_fill` on [`scene`], three little-endian `f32` per pixel, row by row.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use craft_develop::inpaint::{CompleteParams, complete, membrane_fill};
|
||||
use craft_render_parity::{Image, Tolerance, compare};
|
||||
|
||||
const W: usize = 96;
|
||||
const H: usize = 72;
|
||||
|
||||
/// A ramp with stripes and a weave, and two holes in it: a rectangle and a disc.
|
||||
fn scene() -> (Vec<f32>, Vec<bool>) {
|
||||
let mut img = Vec::with_capacity(W * H * 3);
|
||||
let mut hole = Vec::with_capacity(W * H);
|
||||
for y in 0..H {
|
||||
for x in 0..W {
|
||||
let (fx, fy) = (x as f32 / W as f32, y as f32 / H as f32);
|
||||
let stripe = if (x / 6 + y / 9) % 2 == 0 { 0.12 } else { 0.0 };
|
||||
let weave = if (x * 3 + y * 5) % 7 < 2 { 0.05 } else { 0.0 };
|
||||
img.extend([0.15 + 0.6 * fx + stripe, 0.2 + 0.5 * fy + weave, 0.7 - 0.4 * fx * fy + stripe * 0.5]);
|
||||
let (dx, dy) = (x as i32 - 60, y as i32 - 44);
|
||||
hole.push((20..38).contains(&x) && (14..30).contains(&y) || dx * dx + dy * dy <= 81);
|
||||
}
|
||||
}
|
||||
(img, hole)
|
||||
}
|
||||
|
||||
fn fixture(bytes: &[u8]) -> Vec<f32> {
|
||||
bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect()
|
||||
}
|
||||
|
||||
fn assert_parity(expected: &[u8], actual: &[f32]) {
|
||||
let expected = fixture(expected);
|
||||
let report = compare(&Image::new(W as u32, H as u32, &expected).unwrap(), &Image::new(W as u32, H as u32, actual).unwrap()).unwrap();
|
||||
assert!(report.within(&Tolerance::BASELINE), "{report}: {:?}", report.exceeded(&Tolerance::BASELINE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_matches_lightcraft() {
|
||||
let (img, hole) = scene();
|
||||
let filled = complete(W, H, 3, &img, &hole, &CompleteParams::default()).expect("a completion");
|
||||
assert_ne!(filled, img, "the holes were filled");
|
||||
assert_parity(include_bytes!("fixtures/inpaint-complete.f32le"), &filled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn membrane_fill_matches_lightcraft() {
|
||||
let (img, hole) = scene();
|
||||
assert_parity(include_bytes!("fixtures/inpaint-membrane.f32le"), &membrane_fill(W, H, 3, &img, &hole));
|
||||
}
|
||||
|
||||
/// The comparison can fail: the unfilled scene is not within tolerance of the filled one.
|
||||
#[test]
|
||||
fn the_unfilled_scene_is_not_at_parity() {
|
||||
let (img, _) = scene();
|
||||
let expected = fixture(include_bytes!("fixtures/inpaint-complete.f32le"));
|
||||
let report = compare(&Image::new(W as u32, H as u32, &expected).unwrap(), &Image::new(W as u32, H as u32, &img).unwrap()).unwrap();
|
||||
assert!(!report.within(&Tolerance::BASELINE));
|
||||
}
|
||||
@@ -11,8 +11,8 @@
|
||||
//! otherwise in the last folder chosen for the same purpose; a Save that names an existing file the
|
||||
//! OS panel did not ask about gets the Replace question (PhotoCraft `file_dialog.rs:193
|
||||
//! replaces_unasked`), a native message box from [`FilePanels::pump`] or, with the `ui` feature, a
|
||||
//! prompt on the app's `DialogHost` from `FilePanels::pump_with`; a typed name without an extension gets the suggested one and an uppercase
|
||||
//! extension is lowercased (`file_dialog.rs:210 lowercased_extension`, `:365 saved_path`); the two
|
||||
//! prompt on the app's `DialogHost` from `FilePanels::pump_with`; a typed name without an extension gets the suggested one and a new file's
|
||||
//! uppercase extension is lowercased, while an existing file keeps its spelling (`file_dialog.rs:210 lowercased_extension`, `:365 saved_path`); the two
|
||||
//! steps are separate settings of the [`ExtensionPolicy`].
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
@@ -114,7 +114,8 @@ fn same_entry(a: &Path, b: &Path) -> bool {
|
||||
/// PhotoCraft with Lowercase Extension off still adds the suggested extension.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ExtensionPolicy {
|
||||
/// Lowercase an extension typed with capitals (`Photo.PNG` becomes `Photo.png`).
|
||||
/// Lowercase an extension typed with capitals (`Photo.PNG` becomes `Photo.png`), unless the
|
||||
/// typed name is a file that already exists.
|
||||
pub lowercase: bool,
|
||||
/// Add the request's suggested extension to a name that has none.
|
||||
pub add_suggested: bool,
|
||||
@@ -425,11 +426,18 @@ impl FilePanels {
|
||||
|
||||
/// The saved path after the extension policy: `"Photo"` becomes `"Photo.png"` with a
|
||||
/// suggested `png` (when `add_suggested`); `"Photo.PNG"` becomes `"Photo.png"` (when
|
||||
/// `lowercase`); a path with another known extension is kept.
|
||||
/// `lowercase`) unless a file named `"Photo.PNG"` already exists; a path with another known
|
||||
/// extension is kept.
|
||||
///
|
||||
/// An existing file keeps the spelling the panel answered: the panel has just asked whether to
|
||||
/// replace that entry, and `"PHOTO.png"` next to `"PHOTO.PNG"` on a file system that tells
|
||||
/// letter case apart is a second file, so the one the user picked would be left unchanged.
|
||||
// pc: crates/ui-egui/src/file_dialog.rs:210 lowercased_extension, :365 saved_path
|
||||
pub fn settled_save_path(policy: ExtensionPolicy, answered: &Path, suggested: Option<&str>) -> PathBuf {
|
||||
match answered.extension().and_then(|e| e.to_str()) {
|
||||
Some(ext) if policy.lowercase && ext.bytes().any(|b| b.is_ascii_uppercase()) => answered.with_extension(ext.to_ascii_lowercase()),
|
||||
Some(ext) if policy.lowercase && ext.bytes().any(|b| b.is_ascii_uppercase()) && !answered.exists() => {
|
||||
answered.with_extension(ext.to_ascii_lowercase())
|
||||
}
|
||||
Some(_) => answered.to_path_buf(),
|
||||
None => match suggested {
|
||||
Some(ext) if policy.add_suggested => answered.with_extension(ext),
|
||||
@@ -691,4 +699,22 @@ mod service_tests {
|
||||
assert_eq!(log.borrow().len(), 3, "no question for a path the panel asked about");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// Saving over an existing `PHOTO.PNG` with Lowercase Extension on writes `PHOTO.PNG`, the
|
||||
// file the panel asked about, not a new `PHOTO.png` beside it (on a file system that tells
|
||||
// letter case apart) or a renamed one (on one that does not). A new name is still lowercased.
|
||||
#[trial]
|
||||
fn an_existing_file_keeps_its_extension_spelling() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-dialogs-existing-case-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
std::fs::write(dir.join("PHOTO.PNG"), b"old").expect("existing file");
|
||||
let typed = |name: &str| Answer::Paths(vec![dir.join(name)]);
|
||||
let (service, mut panels, log) = service_with(vec![typed("PHOTO.PNG"), typed("Other.PNG")]);
|
||||
let lowercase = ExtensionPolicy::default();
|
||||
|
||||
assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("PHOTO.PNG")]), "the existing file is replaced");
|
||||
assert_eq!(log.borrow().len(), 1, "no second question: the panel asked about this file");
|
||||
assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("Other.png")]), "a new file is lowercased");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -114,7 +114,7 @@ impl Blip {
|
||||
/// MS-ODRAW requires MD4 of the uncompressed BLIP payload, not the original import file.
|
||||
/// This legacy-format identifier is not authentication or a security integrity check.
|
||||
fn uid(bytes: &[u8]) -> [u8; 16] {
|
||||
md4::Md4::digest(bytes).into()
|
||||
md4::Md4::digest(bytes).into() // NOSONAR: MS-ODRAW spec-mandated BLIP UID (non-security format identifier)
|
||||
}
|
||||
|
||||
/// An OfficeArt record: header (version, instance, type, length) then the body.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::hash::Hash;
|
||||
|
||||
use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, Value};
|
||||
use craft_behavior::{Codec as _, EditEvent, EditEvents, IconId, Mixed, NumberCodec, Value};
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::contract::{
|
||||
Bind, BodyCx, EditResponse, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _, TooltipSpec, Trigger, clicked,
|
||||
@@ -466,7 +466,8 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
|
||||
};
|
||||
let mut picker = PresetPicker::new(words.picker.clone(), current.reborrowed(), rows, Bind::bound(&mut browser))
|
||||
.field(PickerField::Chip)
|
||||
.caption(env.units().number(values.diameter.round(), 0..=0))
|
||||
.caption(NumberCodec::new(env.units().reader(None), 0).format(&Some(values.diameter.round())))
|
||||
.caption_range((1.0..=max_diameter.round(), 0))
|
||||
.cell_shape(CellShape::Square)
|
||||
.view(if parts.tip_only() { PresetView::Grid } else { PresetView::List })
|
||||
.browser(!compact)
|
||||
|
||||
@@ -47,6 +47,11 @@ use super::{PathOptionsSettings, PathTool};
|
||||
/// Insert on a picked anchor adds one halfway along the segment leaving it.
|
||||
const INSERT: Chord = Chord::plain(Key::Insert);
|
||||
|
||||
/// How far from a segment, in screen points, an Add Anchor press or hover still takes it: the reference application
|
||||
/// adds an anchor 5 px from a segment at 100 % and none at 6 px. The other tools keep a line's reach
|
||||
/// ([`LINE_REACH`](craft_behavior::hit::LINE_REACH)).
|
||||
const ADD_ANCHOR_REACH: f32 = 5.0;
|
||||
|
||||
/// Above this many anchors in the paths shown, the overlay draws outlines only and declares no part (no anchor in
|
||||
/// the AccessKit tree either) (VectorCraft's `OVERLAY_MAX_ANCHORS`).
|
||||
pub const MAX_ANCHORS: usize = 100_000;
|
||||
@@ -66,13 +71,15 @@ pub enum BezierTool {
|
||||
Convert,
|
||||
/// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools).
|
||||
Anchors,
|
||||
/// Add Anchor Point: a press on a segment inserts an anchor at the hit's `t` ([`PathEdit::InsertAnchor`]); a drag
|
||||
/// moves the new anchor, which is selected. A press on an anchor or a shown handle selects and drags it as
|
||||
/// [`BezierTool::Direct`] does (⇧ adds to the selection, ⌥ on a handle moves it alone), and a click on empty canvas
|
||||
/// deselects the anchors and keeps the path. With ⌥ a click on a segment selects its whole subpath and a drag moves a
|
||||
/// copy of it ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on
|
||||
/// an anchor does nothing. Hover: the segment mark with the anchor a click adds ([`HitMark`]) and the pen with "+";
|
||||
/// over an anchor the arrow; with ⌥ no mark and the arrow with "+"; the crosshair under the canvas's precise cursor
|
||||
/// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t`
|
||||
/// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does
|
||||
/// ([`PathEdit::PullAnchor`]: ⇧ turns them to the nearest 45°, ⌥ during the drag breaks the pair); the new anchor is
|
||||
/// selected. A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to
|
||||
/// the selection, ⌥ on a handle moves it alone), and a click on empty canvas deselects the anchors and keeps the
|
||||
/// path. With ⌥ held at the press a click on a segment selects its whole subpath and a drag moves a copy of it
|
||||
/// ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on an anchor does
|
||||
/// nothing. Hover: the segment mark with the anchor a click adds ([`HitMark`]) and the pen with "+"; over an anchor
|
||||
/// the arrow; with ⌥ no mark and the arrow with "+"; the crosshair under the canvas's precise cursor
|
||||
/// ([`CanvasSpace::precise`]).
|
||||
AddAnchor,
|
||||
/// Delete Anchor Point: a click on an anchor reports [`delete`](BezierOutput::delete) of that anchor; ⌥ makes it
|
||||
@@ -236,6 +243,17 @@ enum Target {
|
||||
t: f64,
|
||||
from: Point,
|
||||
},
|
||||
/// Add Anchor's drag from a segment: an insert into `segment` at `t`, whose anchor stays at `from`, the point of
|
||||
/// the curve at `t`, and whose handles follow the pointer. `out` is the out handle of the last pass, and
|
||||
/// `in_ctrl` the in handle ⌥ left once it broke the pair.
|
||||
Pull {
|
||||
path: u64,
|
||||
segment: KnotRef,
|
||||
t: f64,
|
||||
from: Point,
|
||||
out: Point,
|
||||
in_ctrl: Option<Point>,
|
||||
},
|
||||
/// Direct Selection's ⌥ drag on a segment: a copy of `subpath` dragged from `from`, the grabbed point.
|
||||
Duplicate {
|
||||
path: u64,
|
||||
@@ -508,13 +526,18 @@ impl<'a> BezierOverlay<'a> {
|
||||
let start = if ends && i == 0 { reach } else { 0.0 };
|
||||
let end = if ends && i + 1 == sub.segment_count() { reach } else { 0.0 };
|
||||
let Some(points) = trim_polyline(points, start, end) else { continue };
|
||||
let shape = if self.tool == BezierTool::AddAnchor {
|
||||
HitShape::polyline_within(points, false, ADD_ANCHOR_REACH)
|
||||
} else {
|
||||
HitShape::polyline(points, false)
|
||||
};
|
||||
items.push(Item {
|
||||
kind: Kind::Segment,
|
||||
path: at,
|
||||
key: path.key,
|
||||
knot: KnotRef::new(s, i),
|
||||
at: corners[0],
|
||||
shape: HitShape::polyline(points, false),
|
||||
shape,
|
||||
interior: true,
|
||||
straight: sub.is_straight(i),
|
||||
shown: true,
|
||||
@@ -585,6 +608,12 @@ impl<'a> BezierOverlay<'a> {
|
||||
match hit {
|
||||
// Add Anchor with ⌥ takes the whole subpath as Direct's ⌥ does (PhotoCraft #12709).
|
||||
BezierHit::Segment { .. } if self.tool.takes_subpath(mods) => self.target(hit, start, mods, paths),
|
||||
// Add Anchor's drag pulls out the new anchor's handles (PhotoCraft #12707); Auto Add/Delete's, and Delete
|
||||
// Anchor's with ⌥, moves it.
|
||||
BezierHit::Segment { path, segment, t } if self.tool == BezierTool::AddAnchor && self.tool.adds(mods) => {
|
||||
let from = Self::segment_point(paths, path, segment, t);
|
||||
Target::Pull { path, segment, t, from, out: from, in_ctrl: None }
|
||||
}
|
||||
BezierHit::Segment { path, segment, t } if self.tool.adds(mods) => {
|
||||
Target::Insert { path, segment, t, from: Self::segment_point(paths, path, segment, t) }
|
||||
}
|
||||
@@ -709,11 +738,40 @@ impl<'a> BezierOverlay<'a> {
|
||||
PathEdit::InsertCurvature { path, segment, t, by: snapped(from + locked(delta)) - from }
|
||||
}
|
||||
&Target::Insert { path, segment, t, from } => PathEdit::InsertAnchor { path, segment, t, by: snapped(from + locked(delta)) - from },
|
||||
&Target::Pull { path, segment, t, from, in_ctrl, .. } => {
|
||||
let to = from + delta;
|
||||
let out = if mods.shift { handle_45(from, to) } else { snapped(to) };
|
||||
PathEdit::PullAnchor { path, segment, t, out, in_ctrl }
|
||||
}
|
||||
&Target::Duplicate { path, subpath, from } => PathEdit::DuplicateSubpath { path, subpath, by: snapped(from + locked(delta)) - from },
|
||||
Target::Nothing | Target::Toggle { .. } | Target::Pick { .. } | Target::Marquee => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// [`edit`](Self::edit), keeping what a [`Target::Pull`] carries from pass to pass: ⌥ pressed during the drag
|
||||
/// leaves the in handle where the last pass had it, and the out handle is remembered for the next pass.
|
||||
fn edit_pulled(
|
||||
view: &CanvasView,
|
||||
snap: Option<&Snap>,
|
||||
tool: BezierTool,
|
||||
target: &mut Target,
|
||||
origin: Pos2,
|
||||
pointer: Pos2,
|
||||
mods: Mods,
|
||||
) -> Option<PathEdit> {
|
||||
if let Target::Pull { from, out, in_ctrl, .. } = target
|
||||
&& mods.alt
|
||||
&& in_ctrl.is_none()
|
||||
{
|
||||
*in_ctrl = Some(*from - (*out - *from));
|
||||
}
|
||||
let edit = Self::edit(view, snap, tool, target, origin, pointer, mods);
|
||||
if let (Target::Pull { out, .. }, Some(PathEdit::PullAnchor { out: pulled, .. })) = (target, &edit) {
|
||||
*out = *pulled;
|
||||
}
|
||||
edit
|
||||
}
|
||||
|
||||
/// Proposes `paths` with `edit` applied to the paths the press began on.
|
||||
fn propose(&mut self, cx: &mut Cx<'_, Self>, start: &[EditPath], edit: PathEdit) {
|
||||
let mut next = start.to_vec();
|
||||
@@ -886,7 +944,9 @@ impl<'a> BezierOverlay<'a> {
|
||||
let moves = !matches!(held.target, Target::Nothing | Target::Toggle { .. } | Target::Pick { .. });
|
||||
if first && moves {
|
||||
held.began = true;
|
||||
if let Target::CurvatureInsert { path, segment, .. } | Target::Insert { path, segment, .. } = held.target {
|
||||
if let Target::CurvatureInsert { path, segment, .. } | Target::Insert { path, segment, .. } | Target::Pull { path, segment, .. } =
|
||||
held.target
|
||||
{
|
||||
self.report.select = Some(self.inserted(path, segment));
|
||||
}
|
||||
cx.begin();
|
||||
@@ -900,7 +960,7 @@ impl<'a> BezierOverlay<'a> {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some(edit) = Self::edit(view, snap, self.tool, &held.target, start.origin, pos, mods) {
|
||||
if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut held.target, start.origin, pos, mods) {
|
||||
self.propose(cx, &held.start, edit);
|
||||
}
|
||||
}
|
||||
@@ -928,7 +988,8 @@ impl<'a> BezierOverlay<'a> {
|
||||
return;
|
||||
}
|
||||
if held.began {
|
||||
if let Some(edit) = Self::edit(view, snap, self.tool, &held.target, start.origin, pos, mods) {
|
||||
let mut target = held.target.clone();
|
||||
if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut target, start.origin, pos, mods) {
|
||||
self.propose(cx, &held.start, edit);
|
||||
}
|
||||
// The copy is what was dragged: it ends up selected, not the source.
|
||||
@@ -945,7 +1006,7 @@ impl<'a> BezierOverlay<'a> {
|
||||
self.set(cx, &held.start, PathEdit::InsertCurvature { path, segment, t, by: Vec2::ZERO });
|
||||
self.report.select = Some(self.inserted(path, segment));
|
||||
}
|
||||
Target::Insert { path, segment, t, .. } => {
|
||||
Target::Insert { path, segment, t, .. } | Target::Pull { path, segment, t, .. } => {
|
||||
self.set(cx, &held.start, PathEdit::InsertAnchor { path, segment, t, by: Vec2::ZERO });
|
||||
self.report.select = Some(self.inserted(path, segment));
|
||||
}
|
||||
@@ -1117,6 +1178,27 @@ fn nudge_vector(view: &CanvasView, direction: egui::Vec2, distance: f64) -> Vec2
|
||||
if length > 0.0 { doc / length * distance } else { Vec2::ZERO }
|
||||
}
|
||||
|
||||
/// ⇧ on a handle pulled out of the anchor at `anchor` to `to`, as the reference application turns it: the nearest of
|
||||
/// the eight 45° directions, an axis keeping the drag's offset along it and a diagonal the shorter of the two offsets
|
||||
/// on both axes. `to` itself for a zero or non-finite offset.
|
||||
fn handle_45(anchor: Point, to: Point) -> Point {
|
||||
let d = to - anchor;
|
||||
if !d.x.is_finite() || !d.y.is_finite() || d == Vec2::ZERO {
|
||||
return to;
|
||||
}
|
||||
let (ax, ay) = (d.x.abs(), d.y.abs());
|
||||
// tan 22.5°: nearer the axis than the diagonal.
|
||||
let tan = std::f64::consts::FRAC_PI_8.tan();
|
||||
if ay <= ax * tan {
|
||||
Point::new(to.x, anchor.y)
|
||||
} else if ax <= ay * tan {
|
||||
Point::new(anchor.x, to.y)
|
||||
} else {
|
||||
let shorter = ax.min(ay);
|
||||
anchor + Vec2::new(shorter.copysign(d.x), shorter.copysign(d.y))
|
||||
}
|
||||
}
|
||||
|
||||
fn contains(r: DocRect, p: Point) -> bool {
|
||||
(r.x0..=r.x1).contains(&p.x) && (r.y0..=r.y1).contains(&p.y)
|
||||
}
|
||||
@@ -1135,7 +1217,7 @@ pub struct BezierOutput {
|
||||
pub select: Option<PathSelection>,
|
||||
/// Add an anchor to the segment leaving a knot of a path, at `t` (PhotoCraft's Add Anchor Point): Insert on a
|
||||
/// picked anchor (`t` 0.5). A click or drag of an anchor tool on a segment is the [`change`](Self::change)
|
||||
/// [`PathEdit::InsertAnchor`] instead.
|
||||
/// [`PathEdit::InsertAnchor`] instead ([`PathEdit::PullAnchor`] for Add Anchor's drag).
|
||||
pub insert: Option<(u64, KnotRef, f64)>,
|
||||
/// Delete or Backspace with anchors selected under a tool that deletes (Direct, Convert, Curvature, Add Anchor,
|
||||
/// Delete Anchor): remove these anchors of a path (Delete Anchor Point), `segments` true; a Delete Anchor click
|
||||
|
||||
@@ -348,6 +348,22 @@ pub enum PathEdit {
|
||||
/// The move of the new anchor, in document units.
|
||||
by: Vec2,
|
||||
},
|
||||
/// Add Anchor's drag from a segment: add an anchor to the segment leaving `segment` at `t` and pull out its
|
||||
/// handles, as the Pen does: the out handle at `out` and the in handle opposite it through the anchor, a smooth
|
||||
/// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot.
|
||||
#[non_exhaustive]
|
||||
PullAnchor {
|
||||
/// The path's host key.
|
||||
path: u64,
|
||||
/// The anchor the segment leaves.
|
||||
segment: KnotRef,
|
||||
/// Position along the segment, 0..=1.
|
||||
t: f64,
|
||||
/// The new anchor's out handle.
|
||||
out: Point,
|
||||
/// The new anchor's in handle once Alt broke the pair; `None` mirrors `out`.
|
||||
in_ctrl: Option<Point>,
|
||||
},
|
||||
/// The Curvature tool's double-click or Enter on an anchor: a smooth knot becomes a corner
|
||||
/// with retracted handles and a corner becomes smooth, then the subpath reflows.
|
||||
#[non_exhaustive]
|
||||
@@ -425,6 +441,12 @@ impl PathEdit {
|
||||
PathEdit::InsertAnchor { path, segment, t, by }
|
||||
}
|
||||
|
||||
/// Add Anchor's insert into the segment leaving `segment` at `t` with the new anchor's handles pulled out to `out`
|
||||
/// and mirrored, or with the in handle at `in_ctrl`.
|
||||
pub fn pull_anchor(path: u64, segment: KnotRef, t: f64, out: Point, in_ctrl: Option<Point>) -> Self {
|
||||
PathEdit::PullAnchor { path, segment, t, out, in_ctrl }
|
||||
}
|
||||
|
||||
/// The Curvature tool's toggle of `knot` between smooth and corner.
|
||||
pub fn toggle_curvature(path: u64, knot: KnotRef) -> Self {
|
||||
PathEdit::ToggleCurvature { path, knot }
|
||||
@@ -445,6 +467,7 @@ impl PathEdit {
|
||||
| PathEdit::MoveCurvature { path, .. }
|
||||
| PathEdit::InsertCurvature { path, .. }
|
||||
| PathEdit::InsertAnchor { path, .. }
|
||||
| PathEdit::PullAnchor { path, .. }
|
||||
| PathEdit::ToggleCurvature { path, .. }
|
||||
| PathEdit::DuplicateSubpath { path, .. } => path,
|
||||
}
|
||||
|
||||
@@ -137,6 +137,9 @@ impl PathEdit {
|
||||
/// `by`, then the subpath reflowed.
|
||||
/// - `InsertAnchor`: [`EditSubpath::insert_at`], the new knot with its handles moved by `by`; no
|
||||
/// reflow and no smoothing, so a straight segment gets a corner knot.
|
||||
/// - `PullAnchor`: [`EditSubpath::insert_at`], then the new knot's out handle at `out` and its in
|
||||
/// handle at `in_ctrl` (a corner), or mirrored through the anchor (smooth). Nothing changes when
|
||||
/// a handle is not finite.
|
||||
/// - `ToggleCurvature`: a smooth knot becomes a corner with retracted handles, a corner
|
||||
/// becomes smooth, then the subpath reflows.
|
||||
/// - `DuplicateSubpath`: a copy of the subpath goes last and moves, with its handles, by `by`;
|
||||
@@ -203,6 +206,18 @@ impl PathEdit {
|
||||
k.in_ctrl += *by;
|
||||
k.out_ctrl += *by;
|
||||
}
|
||||
PathEdit::PullAnchor { segment, t, out, in_ctrl, .. } => {
|
||||
let finite = |p: &Point| p.x.is_finite() && p.y.is_finite();
|
||||
if !finite(out) || !in_ctrl.as_ref().is_none_or(finite) {
|
||||
return false;
|
||||
}
|
||||
let Some(sp) = path.subpaths.get_mut(segment.subpath) else { return false };
|
||||
let Some(at) = sp.insert_at(segment.knot, *t) else { return false };
|
||||
let k = &mut sp.knots[at];
|
||||
k.out_ctrl = *out;
|
||||
k.in_ctrl = in_ctrl.unwrap_or(k.anchor - (*out - k.anchor));
|
||||
k.smooth = in_ctrl.is_none();
|
||||
}
|
||||
PathEdit::Convert { knot, out, .. } => {
|
||||
if !knot_ok(path, *knot) {
|
||||
return false;
|
||||
|
||||
@@ -73,6 +73,30 @@ fn edit_subpath_insert_at_splits_a_curve_without_changing_it() {
|
||||
|
||||
// MoveAnchors, MoveHandle (smooth and alone), BendSegment (straight and curved), Convert give PhotoCraft's kernel
|
||||
// results; a wrong key or index changes nothing and returns false.
|
||||
#[trial]
|
||||
fn path_edit_pull_anchor_inserts_and_pulls_out_the_handles() {
|
||||
let straight = || ops_path(EditSubpath::new(vec![Knot::corner(p(0.0, 0.0)), Knot::corner(p(100.0, 0.0))], false));
|
||||
let mut path = straight();
|
||||
assert!(PathEdit::pull_anchor(7, kr(0), 0.5, p(50.0, 30.0), None).apply(&mut path));
|
||||
let k = path.subpaths[0].knots[1];
|
||||
assert!(near(k.anchor, p(50.0, 0.0)) && near(k.out_ctrl, p(50.0, 30.0)) && near(k.in_ctrl, p(50.0, -30.0)) && k.smooth, "{k:?}");
|
||||
let mut path = straight();
|
||||
assert!(PathEdit::pull_anchor(7, kr(0), 0.5, p(50.0, 30.0), Some(p(80.0, 0.0))).apply(&mut path));
|
||||
let k = path.subpaths[0].knots[1];
|
||||
assert!(near(k.in_ctrl, p(80.0, 0.0)) && !k.smooth, "{k:?}");
|
||||
for bad in [
|
||||
PathEdit::pull_anchor(7, kr(0), 0.5, p(f64::NAN, 0.0), None),
|
||||
PathEdit::pull_anchor(7, kr(0), 0.5, p(1.0, 1.0), Some(p(0.0, f64::INFINITY))),
|
||||
PathEdit::pull_anchor(7, kr(0), 1.5, p(1.0, 1.0), None),
|
||||
PathEdit::pull_anchor(7, kr(4), 0.5, p(1.0, 1.0), None),
|
||||
PathEdit::pull_anchor(7, KnotRef::new(3, 0), 0.5, p(1.0, 1.0), None),
|
||||
] {
|
||||
let mut path = straight();
|
||||
assert!(!bad.apply(&mut path), "{bad:?}");
|
||||
assert_eq!(path, straight());
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn path_edit_apply_matches_the_kernel_for_every_existing_edit() {
|
||||
let base = || {
|
||||
@@ -417,12 +441,13 @@ fn cmd_or_ctrl_with_page_down_on_a_focused_anchor_scrolls_the_canvas_and_picks_n
|
||||
assert_eq!(h.state.borrow().selection, picked, "the page key picks no part");
|
||||
}
|
||||
|
||||
// Add Anchor on a segment: a press, a drag and a release are one gesture that inserts the anchor and moves it, with the
|
||||
// new anchor selected; a click inserts it where the segment was pressed and moves nothing.
|
||||
// The Pen's Auto Add/Delete on a segment: a press, a drag and a release are one gesture that inserts the anchor and
|
||||
// moves it, with the new anchor selected. Add Anchor's click inserts it where the segment was pressed and moves
|
||||
// nothing (its drag pulls out handles: `an_add_anchor_drag_pulls_out_the_new_anchors_handles`).
|
||||
#[trial]
|
||||
fn an_add_anchor_drag_inserts_and_moves_the_new_anchor_in_one_gesture() {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| st.tool = BezierTool::AddAnchor);
|
||||
h.update(|st| st.tool = BezierTool::AutoAddDelete);
|
||||
let on = h.screen(p(110.0, 60.0));
|
||||
h.drag(on, vec2(0.0, FAR));
|
||||
{
|
||||
@@ -453,6 +478,73 @@ fn an_add_anchor_drag_inserts_and_moves_the_new_anchor_in_one_gesture() {
|
||||
assert_eq!(st.selection, sel(1, &[(0, 1)]));
|
||||
}
|
||||
|
||||
// Add Anchor's drag from a segment inserts the anchor where the segment was pressed and pulls out its handles, as the
|
||||
// reference application does (PhotoCraft #12707): the out handle follows the pointer and the in handle mirrors it, in
|
||||
// one gesture, the new anchor selected and smooth; ⇧ turns the handle to the nearest 45°, an axis keeping the
|
||||
// drag's offset along it and a diagonal the shorter offset; ⌥ pressed during the drag breaks the pair, so only the
|
||||
// out handle follows from then on.
|
||||
#[trial]
|
||||
fn an_add_anchor_drag_pulls_out_the_new_anchors_handles() {
|
||||
let add_anchor = || {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| st.tool = BezierTool::AddAnchor);
|
||||
h
|
||||
};
|
||||
let close = |a: Vec2, b: Vec2| (a - b).hypot() < 1e-6;
|
||||
let on = p(110.0, 60.0);
|
||||
|
||||
let mut h = add_anchor();
|
||||
let at = h.screen(on);
|
||||
h.drag(at, vec2(0.0, 60.0));
|
||||
{
|
||||
let st = h.state.borrow();
|
||||
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1, "{:?}", st.seen);
|
||||
assert_eq!((st.seen.first(), st.seen.last()), (Some(&Seen::Begin), Some(&Seen::Commit)), "{:?}", st.seen);
|
||||
assert!(
|
||||
matches!(st.changes.last(), Some(PathEdit::PullAnchor { path: 1, segment, in_ctrl: None, .. }) if *segment == kr(0)),
|
||||
"{:?}",
|
||||
st.changes
|
||||
);
|
||||
let knots = &st.paths[0].subpaths[0].knots;
|
||||
assert_eq!(knots.len(), 5);
|
||||
let k = knots[1];
|
||||
assert!(k.anchor.distance(on) < 1e-3, "the anchor stays where the segment was pressed: {k:?}");
|
||||
assert!(close(k.out_ctrl - k.anchor, Vec2::new(0.0, 60.0)) && close(k.in_ctrl - k.anchor, Vec2::new(0.0, -60.0)), "{k:?}");
|
||||
assert!(k.smooth);
|
||||
assert_eq!(st.selection, sel(1, &[(0, 1)]));
|
||||
}
|
||||
|
||||
// ⇧: the measured drags.
|
||||
for (by, out) in [((30.0, 80.0), (0.0, 80.0)), ((70.0, 40.0), (40.0, 40.0)), ((-50.0, -60.0), (-50.0, -50.0)), ((60.0, -20.0), (60.0, 0.0))] {
|
||||
let mut h = add_anchor();
|
||||
let at = h.screen(on);
|
||||
h.fixture.hold(egui::Modifiers::SHIFT);
|
||||
h.drag(at, vec2(by.0, by.1));
|
||||
h.fixture.hold(egui::Modifiers::NONE);
|
||||
let st = h.state.borrow();
|
||||
let k = st.paths[0].subpaths[0].knots[1];
|
||||
let out = Vec2::new(out.0, out.1);
|
||||
assert!(close(k.out_ctrl - k.anchor, out) && close(k.in_ctrl - k.anchor, -out), "{by:?}: {k:?}");
|
||||
}
|
||||
|
||||
// ⌥ during the drag: the in handle stays where the pair had it, the out handle follows on.
|
||||
let mut h = add_anchor();
|
||||
let at = h.screen(on);
|
||||
h.press_at(at);
|
||||
h.move_to(at + vec2(-30.0, 0.0));
|
||||
h.move_to(at + vec2(-60.0, 0.0));
|
||||
h.fixture.hold(egui::Modifiers::ALT);
|
||||
h.move_to(at + vec2(-60.0, 20.0));
|
||||
h.move_to(at + vec2(-60.0, 40.0));
|
||||
h.release_at(at + vec2(-60.0, 40.0));
|
||||
h.fixture.hold(egui::Modifiers::NONE);
|
||||
let st = h.state.borrow();
|
||||
let k = st.paths[0].subpaths[0].knots[1];
|
||||
assert!(close(k.out_ctrl - k.anchor, Vec2::new(-60.0, 40.0)) && close(k.in_ctrl - k.anchor, Vec2::new(60.0, 0.0)), "{k:?}");
|
||||
assert!(!k.smooth, "a broken pair is a corner");
|
||||
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1, "{:?}", st.seen);
|
||||
}
|
||||
|
||||
// Convert on a segment: a drag on a straight one bends it when nothing of the path is selected and moves the path when
|
||||
// every anchor is, a partial selection and a curved segment do nothing; handles within the straightness tolerance of
|
||||
// their anchors still make the segment straight.
|
||||
@@ -919,6 +1011,63 @@ fn add_anchor_selects_and_edits_existing_anchors_and_handles() {
|
||||
}
|
||||
}
|
||||
|
||||
// Add Anchor reaches a segment within 5 screen points, as the reference application does (PhotoCraft #12732): a click
|
||||
// 2 to 5 points above or below a straight segment adds an anchor and shows the pen with "+", one 5.5 or 6 points away
|
||||
// adds nothing; Delete Anchor and Direct Selection keep a line's reach.
|
||||
#[trial]
|
||||
fn add_anchor_reaches_a_segment_within_5_points() {
|
||||
use craft_behavior::{Cursor, CursorBadge, PaintedCursor};
|
||||
let segment = p(110.0, 60.0);
|
||||
let at_tool = |tool: BezierTool| {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| st.tool = tool);
|
||||
h
|
||||
};
|
||||
let click = |h: &mut Harness, at: Pos2| {
|
||||
h.press_at(at);
|
||||
h.release_at(at);
|
||||
};
|
||||
let pen_plus = |h: &Harness| {
|
||||
matches!(
|
||||
craft_ui::runtime::cursor::current(h.fixture.ctx()),
|
||||
Some(Cursor::Painted(PaintedCursor::Tool { badge: Some(CursorBadge::Add), .. }))
|
||||
)
|
||||
};
|
||||
for off in [2.0_f32, 3.0, 4.5, 5.0, -2.0, -5.0] {
|
||||
let mut h = at_tool(BezierTool::AddAnchor);
|
||||
let at = h.screen(segment) + vec2(0.0, off);
|
||||
h.move_to(at);
|
||||
h.fixture.frame(Vec::new());
|
||||
assert!(pen_plus(&h), "{off}: the pen with + shows where a click adds");
|
||||
click(&mut h, at);
|
||||
let st = h.state.borrow();
|
||||
assert!(matches!(st.changes.last(), Some(PathEdit::InsertAnchor { path: 1, segment, .. }) if *segment == kr(0)), "{off}: {:?}", st.changes);
|
||||
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5, "{off}");
|
||||
}
|
||||
for off in [5.5_f32, 6.0, -6.0] {
|
||||
let mut h = at_tool(BezierTool::AddAnchor);
|
||||
let at = h.screen(segment) + vec2(0.0, off);
|
||||
h.move_to(at);
|
||||
h.fixture.frame(Vec::new());
|
||||
assert!(!pen_plus(&h), "{off}: no + past the reach");
|
||||
click(&mut h, at);
|
||||
let st = h.state.borrow();
|
||||
assert!(st.changes.is_empty() && st.seen.is_empty(), "{off}: {:?} {:?}", st.changes, st.seen);
|
||||
assert_eq!(st.paths, [path_a(), path_b()], "{off}");
|
||||
}
|
||||
// The other tools keep a line's reach: 4.5 points from the segment misses it, 3 points hits it.
|
||||
for tool in [BezierTool::DeleteAnchor, BezierTool::Direct] {
|
||||
let mut h = at_tool(tool);
|
||||
let near = h.screen(segment) + vec2(0.0, 3.0);
|
||||
h.drag(near, vec2(0.0, FAR));
|
||||
assert!(matches!(h.last_change(), Some(PathEdit::BendSegment { path: 1, .. })), "{tool:?}: {:?}", h.last_change());
|
||||
let mut h = at_tool(tool);
|
||||
let past = h.screen(segment) + vec2(0.0, 4.5);
|
||||
h.drag(past, vec2(0.0, FAR));
|
||||
assert!(!matches!(h.last_change(), Some(PathEdit::BendSegment { .. })), "{tool:?}: {:?}", h.last_change());
|
||||
}
|
||||
}
|
||||
|
||||
// The anchor tools' canvas tool: a press off the paths begins nothing (it never starts a path), and off the paths the
|
||||
// cursor says what a click does: the arrow for Add Anchor (with "+" under ⌥, PhotoCraft #12709), the pen
|
||||
// with "-" for Delete Anchor, the Convert Point icon, the arrow for Direct Selection and under ⌘, the crosshair when
|
||||
|
||||
@@ -160,7 +160,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
|
||||
canvas = canvas.snap(snap);
|
||||
}
|
||||
if let Some(ruler) = config.rulers {
|
||||
canvas = canvas.rulers(ruler, ruler, Point::ZERO);
|
||||
canvas = canvas.rulers(ruler, ruler);
|
||||
}
|
||||
let canvas = canvas.show(ui, |ui, body| {
|
||||
let mut guide_edits = 0;
|
||||
|
||||
@@ -344,6 +344,26 @@ impl ErrorBars {
|
||||
}
|
||||
}
|
||||
|
||||
/// A chart's data table (`c:dTable`), independent of the chart legend.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ChartDataTable {
|
||||
pub show_keys: bool,
|
||||
pub horizontal_border: bool,
|
||||
pub vertical_border: bool,
|
||||
pub outline: bool,
|
||||
}
|
||||
|
||||
impl Default for ChartDataTable {
|
||||
fn default() -> Self {
|
||||
Self { show_keys: true, horizontal_border: true, vertical_border: true, outline: true }
|
||||
}
|
||||
}
|
||||
|
||||
fn is_zero_u16(v: &u16) -> bool {
|
||||
*v == 0
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Chart {
|
||||
@@ -423,6 +443,15 @@ pub struct Chart {
|
||||
/// A histogram's bin width (`cx:binSize`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bin_size: Option<f64>,
|
||||
/// A chart's data table (`c:dTable`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub data_table: Option<ChartDataTable>,
|
||||
/// Pie/doughnut first slice angle in degrees clockwise from 12 o'clock (0–359).
|
||||
#[serde(skip_serializing_if = "is_zero_u16")]
|
||||
pub first_slice_angle: u16,
|
||||
/// A PivotChart's PivotTable reference (`c:pivotSource/c:name`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pivot_source: Option<String>,
|
||||
/// Original chart XML part kept for round-trip of unmodelled options.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub raw: Option<String>,
|
||||
@@ -537,6 +566,9 @@ impl Default for Chart {
|
||||
up_down_bars: false,
|
||||
bin_count: None,
|
||||
bin_size: None,
|
||||
data_table: None,
|
||||
first_slice_angle: 0,
|
||||
pivot_source: None,
|
||||
raw: None,
|
||||
verbatim: false,
|
||||
kept: ChartKept::default(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Chart parts (`c:chartSpace`) → [`Chart`]. The original XML is kept in `Chart.raw`.
|
||||
|
||||
use crate::chart::{Chart, ChartType, ErrorBars, Series, Trendline, TrendlineType};
|
||||
use crate::chart::{Chart, ChartDataTable, ChartType, ErrorBars, Series, Trendline, TrendlineType};
|
||||
use crate::style::Fill;
|
||||
|
||||
use craft_xml::{El, Local, value};
|
||||
@@ -194,6 +194,16 @@ fn chart_within(root: &El, mut budget: usize) -> Option<Chart> {
|
||||
}
|
||||
}
|
||||
c.lang = root.child(Local("lang")).and_then(|c| c.attr_local("val")).map(str::to_string);
|
||||
c.pivot_source = root.path(&[Local("pivotSource"), Local("name")]).map(|n| n.deep_text().trim().to_string()).filter(|n| !n.is_empty());
|
||||
c.data_table = pa.child(Local("dTable")).map(|t| {
|
||||
let flag = |name: &str| t.child(Local(name)).is_some_and(|e| e.attr_local("val").and_then(value::to_bool).unwrap_or(true));
|
||||
ChartDataTable {
|
||||
show_keys: flag("showKeys"),
|
||||
horizontal_border: flag("showHorzBorder"),
|
||||
vertical_border: flag("showVertBorder"),
|
||||
outline: flag("showOutline"),
|
||||
}
|
||||
});
|
||||
let (val_ax, cat_ax) = read_axes(&mut c, pa, &primary_val);
|
||||
read_text_styles(&mut c, root, ch, val_ax, cat_ax);
|
||||
Some(c)
|
||||
@@ -288,6 +298,9 @@ fn read_group_settings(g: &El, c: &mut Chart) -> Option<bool> {
|
||||
if let Some(v) = g.child(Local("holeSize")).and_then(|c| c.attr_local("val")).and_then(|v| v.parse::<f64>().ok()) {
|
||||
c.hole_size = (v / 100.0).clamp(0.0, 0.9);
|
||||
}
|
||||
if let Some(v) = g.child(Local("firstSliceAng")).and_then(|c| c.attr_local("val")).and_then(|v| v.trim().parse::<u16>().ok()) {
|
||||
c.first_slice_angle = v % 360;
|
||||
}
|
||||
// `<c:showVal/>` without a val attribute means true, as in the schema's default.
|
||||
// The setting belongs to this plot group: a group that asks for no labels keeps them
|
||||
// off, even when another group of a combo chart asks for them (#868).
|
||||
@@ -902,4 +915,30 @@ mod tests {
|
||||
assert!(read_chart_xml(vary_xml(r#"<c:varyColors val="0"/>"#).as_bytes()).is_some_and(|c| !c.vary_colors));
|
||||
assert!(read_chart_xml(vary_xml(r#"<c:varyColors val="1"/>"#).as_bytes()).is_some_and(|c| c.vary_colors));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_table_first_slice_angle_and_pivot_source_roundtrip() {
|
||||
let xml = format!(
|
||||
r#"<c:chartSpace xmlns:c="{NS_C}"><c:pivotSource><c:name>[Book.xlsx]Sheet1!PivotTable1</c:name><c:fmtId val="0"/></c:pivotSource><c:chart><c:plotArea><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:val><c:numLit><c:ptCount val="1"/><c:pt idx="0"><c:v>5</c:v></c:pt></c:numLit></c:val></c:ser></c:barChart><c:dTable><c:showHorzBorder/><c:showVertBorder val="0"/><c:showOutline val="1"/><c:showKeys/></c:dTable></c:plotArea></c:chart></c:chartSpace>"#
|
||||
);
|
||||
let c = read_chart_xml(xml.as_bytes()).unwrap();
|
||||
assert_eq!(c.pivot_source.as_deref(), Some("[Book.xlsx]Sheet1!PivotTable1"));
|
||||
assert_eq!(c.data_table, Some(ChartDataTable { show_keys: true, horizontal_border: true, vertical_border: false, outline: true }));
|
||||
let mut edited = c.clone();
|
||||
edited.raw = None;
|
||||
let (written, kept) = crate::chart::write::chart_xml(&edited);
|
||||
assert!(!kept);
|
||||
let back = read_chart_xml(&written).unwrap();
|
||||
assert_eq!(back.pivot_source, c.pivot_source);
|
||||
assert_eq!(back.data_table, c.data_table);
|
||||
|
||||
let pie_xml = format!(
|
||||
r#"<c:chartSpace xmlns:c="{NS_C}"><c:chart><c:plotArea><c:pieChart><c:ser><c:idx val="0"/><c:val><c:numLit><c:ptCount val="1"/><c:pt idx="0"><c:v>5</c:v></c:pt></c:numLit></c:val></c:ser><c:firstSliceAng val="450"/></c:pieChart></c:plotArea></c:chart></c:chartSpace>"#
|
||||
);
|
||||
let mut pie = read_chart_xml(pie_xml.as_bytes()).unwrap();
|
||||
assert_eq!(pie.first_slice_angle, 90);
|
||||
pie.raw = None;
|
||||
let (pie_written, _) = crate::chart::write::chart_xml(&pie);
|
||||
assert_eq!(read_chart_xml(&pie_written).unwrap().first_slice_angle, 90);
|
||||
}
|
||||
}
|
||||
@@ -645,9 +645,9 @@ fn plot_group(w: &mut Writer, c: &Chart, kind: ChartType, list: &[(usize, &Serie
|
||||
w.close();
|
||||
}
|
||||
}
|
||||
Group::Pie => w.tag("c:firstSliceAng").attr("val", 0).empty(),
|
||||
Group::Pie => w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty(),
|
||||
Group::Doughnut => {
|
||||
w.tag("c:firstSliceAng").attr("val", 0).empty();
|
||||
w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty();
|
||||
w.tag("c:holeSize").attr("val", (c.hole_size.clamp(0.1, 0.9) * 100.0).round() as i64).empty();
|
||||
}
|
||||
_ => {}
|
||||
@@ -733,6 +733,12 @@ pub fn chart_xml(c: &Chart) -> (Vec<u8>, bool) {
|
||||
w.tag("c:date1904").attr("val", 0).empty();
|
||||
w.tag("c:roundedCorners").attr("val", 0).empty();
|
||||
w.tag("c:style").attr("val", c.style.clamp(1, 48)).empty();
|
||||
if let Some(pivot) = c.pivot_source.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
w.open("c:pivotSource", &[]);
|
||||
w.tag("c:name").text(pivot);
|
||||
w.tag("c:fmtId").attr("val", 0).empty();
|
||||
w.close();
|
||||
}
|
||||
w.open("c:chart", &[]);
|
||||
match &c.title {
|
||||
Some(t) => {
|
||||
@@ -802,6 +808,22 @@ pub fn chart_xml(c: &Chart) -> (Vec<u8>, bool) {
|
||||
axes(&mut w, c, g);
|
||||
}
|
||||
}
|
||||
if let Some(dt) = &c.data_table {
|
||||
w.open("c:dTable", &[]);
|
||||
if dt.horizontal_border {
|
||||
w.empty("c:showHorzBorder", &[]);
|
||||
}
|
||||
if dt.vertical_border {
|
||||
w.empty("c:showVertBorder", &[]);
|
||||
}
|
||||
if dt.outline {
|
||||
w.empty("c:showOutline", &[]);
|
||||
}
|
||||
if dt.show_keys {
|
||||
w.empty("c:showKeys", &[]);
|
||||
}
|
||||
w.close();
|
||||
}
|
||||
if let Some(f) = &c.plot_fill {
|
||||
sp_pr(&mut w, Some(f), None);
|
||||
}
|
||||
|
||||
+179
-20
@@ -83,6 +83,12 @@ impl Default for Table {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cells a table may hold after [`Table::normalize`] (PowerPoint's own limit is 75 x 75).
|
||||
pub const MAX_CELLS: usize = 100_000;
|
||||
/// Cell visits [`Table::merge`] may spend growing its rectangle over existing merges: a few
|
||||
/// passes over the largest grid, where a real table needs one or two.
|
||||
const MAX_MERGE_WORK: usize = 16 * MAX_CELLS;
|
||||
|
||||
impl Table {
|
||||
pub fn new(rows: usize, cols: usize, width: f64, row_height: f64) -> Self {
|
||||
let rows = rows.clamp(1, 1000);
|
||||
@@ -113,15 +119,26 @@ impl Table {
|
||||
self.rows.iter().map(|r| r.height).sum()
|
||||
}
|
||||
/// Insert an empty row before `at`. A merge the new row falls inside grows to cover it.
|
||||
pub fn insert_row(&mut self, at: usize) {
|
||||
/// Returns false, leaving the table as it was, when the row would take it past [`MAX_CELLS`].
|
||||
#[must_use]
|
||||
pub fn insert_row(&mut self, at: usize) -> bool {
|
||||
if self.cols.len().saturating_mul(self.rows.len().saturating_add(1)) > MAX_CELLS {
|
||||
return false;
|
||||
}
|
||||
let at = at.min(self.rows.len());
|
||||
let merges = self.merges();
|
||||
let h = self.rows.get(at.saturating_sub(1)).map(|r| r.height).unwrap_or(30.0);
|
||||
self.rows.insert(at, Row { height: h, cells: (0..self.cols.len()).map(|_| Cell::new("")).collect() });
|
||||
self.set_merges(merges.into_iter().map(|m| m.insert_row(at)));
|
||||
true
|
||||
}
|
||||
/// Insert an empty column before `at`. A merge the new column falls inside grows to cover it.
|
||||
pub fn insert_col(&mut self, at: usize) {
|
||||
/// Returns false, leaving the table as it was, when the column would take it past [`MAX_CELLS`].
|
||||
#[must_use]
|
||||
pub fn insert_col(&mut self, at: usize) -> bool {
|
||||
if self.cols.len().saturating_add(1).saturating_mul(self.rows.len()) > MAX_CELLS {
|
||||
return false;
|
||||
}
|
||||
let at = at.min(self.cols.len());
|
||||
let merges = self.merges();
|
||||
let w = self.cols.get(at.saturating_sub(1)).copied().unwrap_or(80.0);
|
||||
@@ -131,6 +148,7 @@ impl Table {
|
||||
r.cells.insert(i, Cell::new(""));
|
||||
}
|
||||
self.set_merges(merges.into_iter().map(|m| m.insert_col(at)));
|
||||
true
|
||||
}
|
||||
/// Delete row `at`. Merges through it shrink; a merge anchored on it moves its anchor (and
|
||||
/// text) to the next row it covers.
|
||||
@@ -170,8 +188,12 @@ impl Table {
|
||||
true
|
||||
}
|
||||
/// The merged areas: every uncovered cell spanning more than one cell, clipped to the grid.
|
||||
/// Merges of a well-formed table do not overlap, so together they cover at most the grid; a
|
||||
/// file's overlapping spans past that are dropped, so rebuilding them cannot revisit cells
|
||||
/// without bound.
|
||||
fn merges(&self) -> Vec<Merge> {
|
||||
let (nr, nc) = (self.rows.len(), self.cols.len());
|
||||
let mut area = nr.saturating_mul(nc);
|
||||
let mut out = vec![];
|
||||
for (r, row) in self.rows.iter().enumerate() {
|
||||
for (c, cell) in row.cells.iter().enumerate().take(nc) {
|
||||
@@ -180,7 +202,10 @@ impl Table {
|
||||
}
|
||||
let rs = (cell.row_span.max(1) as usize).min(nr - r);
|
||||
let gs = (cell.grid_span.max(1) as usize).min(nc - c);
|
||||
if rs > 1 || gs > 1 {
|
||||
if (rs > 1 || gs > 1)
|
||||
&& let Some(left) = area.checked_sub(rs.saturating_mul(gs))
|
||||
{
|
||||
area = left;
|
||||
out.push(Merge { r, c, rs, gs });
|
||||
}
|
||||
}
|
||||
@@ -233,9 +258,17 @@ impl Table {
|
||||
if r1 >= self.rows.len() || c1 >= self.cols.len() || (r0 == r1 && c0 == c1) {
|
||||
return false;
|
||||
}
|
||||
// Grow the rectangle until no existing merge sticks out of it.
|
||||
// Grow the rectangle until no existing merge sticks out of it. Each pass reads the whole
|
||||
// grid and may grow it by one row, so the passes are charged against
|
||||
// [`MAX_MERGE_WORK`]: past it the merge is refused, before anything changed.
|
||||
let (mut r0, mut c0, mut r1, mut c1) = (r0, c0, r1, c1);
|
||||
let pass = self.rows.len().saturating_mul(self.cols.len()).max(1);
|
||||
let mut work = 0usize;
|
||||
loop {
|
||||
work = work.saturating_add(pass);
|
||||
if work > MAX_MERGE_WORK {
|
||||
return false;
|
||||
}
|
||||
let before = (r0, c0, r1, c1);
|
||||
for (r, row) in self.rows.iter().enumerate() {
|
||||
for (c, cell) in row.cells.iter().enumerate().take(self.cols.len()) {
|
||||
@@ -289,21 +322,50 @@ impl Table {
|
||||
return false;
|
||||
}
|
||||
// Spans come from the file and may reach past the table; only walk the cells that exist.
|
||||
for rr in r..r.saturating_add(rs).min(self.rows.len()) {
|
||||
for cc in c..c.saturating_add(gs).min(self.cols.len()) {
|
||||
if let Some(x) = self.cell_mut(rr, cc) {
|
||||
x.h_merge = false;
|
||||
x.v_merge = false;
|
||||
x.grid_span = 1;
|
||||
x.row_span = 1;
|
||||
}
|
||||
let end = r.saturating_add(rs).min(self.rows.len());
|
||||
let gs = gs.min(self.cols.len().saturating_sub(c));
|
||||
for row in self.rows.get_mut(r..end).unwrap_or_default() {
|
||||
for x in row.cells.iter_mut().skip(c).take(gs) {
|
||||
x.h_merge = false;
|
||||
x.v_merge = false;
|
||||
x.grid_span = 1;
|
||||
x.row_span = 1;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Make every row have exactly `cols.len()` cells (repair after loading).
|
||||
pub fn normalize(&mut self) {
|
||||
/// Whether the grid is as [`Table::normalize`] leaves it: within [`MAX_CELLS`], every row
|
||||
/// exactly `cols.len()` cells wide.
|
||||
pub fn is_normalized(&self) -> bool {
|
||||
let n = self.cols.len();
|
||||
n <= MAX_CELLS && self.rows.len() <= (MAX_CELLS / n.max(1)).max(1) && self.rows.iter().all(|r| r.cells.len() == n)
|
||||
}
|
||||
/// Whether [`Table::normalize`] would drop rows or columns to fit [`MAX_CELLS`].
|
||||
pub fn over_cap(&self) -> bool {
|
||||
let n = self.cols.len();
|
||||
n > MAX_CELLS || self.rows.len() > (MAX_CELLS / n.max(1)).max(1)
|
||||
}
|
||||
/// What [`Table::normalize`] would leave of this table, cloning only the rows and cells that
|
||||
/// survive (an oversized table is not copied whole first).
|
||||
pub fn normalized(&self) -> Table {
|
||||
let n = self.cols.len().min(MAX_CELLS);
|
||||
let keep = (MAX_CELLS / n.max(1)).max(1);
|
||||
let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect();
|
||||
let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self };
|
||||
t.normalize();
|
||||
if self.over_cap() {
|
||||
t.clip_spans();
|
||||
}
|
||||
t
|
||||
}
|
||||
/// Make every row have exactly `cols.len()` cells (repair after loading). A grid over
|
||||
/// [`MAX_CELLS`] loses its last rows (and columns) first, so a file naming many rows and many
|
||||
/// columns but few cells cannot make this allocate their product.
|
||||
pub fn normalize(&mut self) {
|
||||
let truncated = self.over_cap();
|
||||
self.cols.truncate(MAX_CELLS);
|
||||
let n = self.cols.len();
|
||||
self.rows.truncate((MAX_CELLS / n.max(1)).max(1));
|
||||
for r in &mut self.rows {
|
||||
r.cells.resize_with(n, || Cell::new(""));
|
||||
for c in &mut r.cells {
|
||||
@@ -311,6 +373,20 @@ impl Table {
|
||||
c.row_span = c.row_span.max(1);
|
||||
}
|
||||
}
|
||||
if truncated {
|
||||
self.clip_spans();
|
||||
}
|
||||
}
|
||||
/// Cut every merge span to the rows and columns that remain, so no merge reaches past a
|
||||
/// table that lost rows or columns to the cell cap.
|
||||
fn clip_spans(&mut self) {
|
||||
let (nr, nc) = (self.rows.len(), self.cols.len());
|
||||
for (ri, r) in self.rows.iter_mut().enumerate() {
|
||||
for (ci, c) in r.cells.iter_mut().enumerate() {
|
||||
c.row_span = c.row_span.min((nr - ri) as u32).max(1);
|
||||
c.grid_span = c.grid_span.min((nc - ci) as u32).max(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,10 +630,10 @@ mod tests {
|
||||
fn row_and_column_edits_keep_merges_consistent() {
|
||||
for at in 0..=4 {
|
||||
let mut t = merged();
|
||||
t.insert_row(at);
|
||||
assert!(t.insert_row(at));
|
||||
assert_topology(&t);
|
||||
let mut t = merged();
|
||||
t.insert_col(at);
|
||||
assert!(t.insert_col(at));
|
||||
assert_topology(&t);
|
||||
}
|
||||
for at in 0..4 {
|
||||
@@ -573,11 +649,11 @@ mod tests {
|
||||
#[test]
|
||||
fn inserting_inside_a_merge_grows_it() {
|
||||
let mut t = merged();
|
||||
t.insert_row(2);
|
||||
assert!(t.insert_row(2));
|
||||
let a = t.cell(1, 1).unwrap();
|
||||
assert_eq!((a.row_span, a.grid_span), (3, 2));
|
||||
assert!(t.cell(2, 2).unwrap().h_merge && t.cell(2, 2).unwrap().v_merge);
|
||||
t.insert_col(0);
|
||||
assert!(t.insert_col(0));
|
||||
assert_eq!(t.cell(1, 2).unwrap().grid_span, 2);
|
||||
assert_eq!(anchor_text(&t, 1, 2), "M");
|
||||
assert_topology(&t);
|
||||
@@ -619,8 +695,8 @@ mod tests {
|
||||
fn insert_delete_merge_split() {
|
||||
let mut t = Table::new(3, 3, 300.0, 30.0);
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (3, 3));
|
||||
t.insert_row(1);
|
||||
t.insert_col(3);
|
||||
assert!(t.insert_row(1));
|
||||
assert!(t.insert_col(3));
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (4, 4));
|
||||
assert!(t.delete_row(0) && t.delete_col(0));
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (3, 3));
|
||||
@@ -646,6 +722,89 @@ mod tests {
|
||||
assert!(t.split(0, 0));
|
||||
assert_eq!(t.cell(0, 0).map(|c| (c.grid_span, c.row_span)), Some((1, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_refuses_work_past_cap() {
|
||||
let mut t = Table::new(1000, 10, 100.0, 10.0);
|
||||
for row in &mut t.rows {
|
||||
for c in &mut row.cells {
|
||||
c.row_span = 2;
|
||||
}
|
||||
}
|
||||
let before = t.clone();
|
||||
assert!(!t.merge(998, 0, 999, 9));
|
||||
assert_eq!(t, before);
|
||||
let mut small = Table::new(4, 4, 400.0, 30.0);
|
||||
assert!(small.merge(0, 0, 1, 1));
|
||||
assert!(small.is_normalized() && !Table { cols: vec![1.0; 3], rows: vec![Row::default(); 2], ..Default::default() }.is_normalized());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_caps_a_sparse_grid_at_max_cells() {
|
||||
let mut t = Table { cols: vec![10.0; 1000], rows: vec![Row::default(); 1000], ..Default::default() };
|
||||
t.normalize();
|
||||
assert_eq!(t.cols.len(), 1000);
|
||||
assert_eq!(t.rows.len(), MAX_CELLS / 1000);
|
||||
assert!(t.rows.iter().all(|r| r.cells.len() == 1000));
|
||||
let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() };
|
||||
t.normalize();
|
||||
assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1));
|
||||
let wide = Table { cols: vec![10.0; 1000], rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1500] }; 150], ..Default::default() };
|
||||
let mut n = wide.clone();
|
||||
n.normalize();
|
||||
assert_eq!(wide.normalized(), n);
|
||||
let mut t = Table::new(4, 4, 400.0, 30.0);
|
||||
t.normalize();
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (4, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_file_spans_rebuild_in_bounded_work() {
|
||||
let n = 200;
|
||||
let mut t = Table::new(n, n, 400.0, 30.0);
|
||||
for row in &mut t.rows {
|
||||
for c in &mut row.cells {
|
||||
c.grid_span = u32::MAX;
|
||||
c.row_span = u32::MAX;
|
||||
}
|
||||
}
|
||||
assert_eq!(t.merges().len(), 1, "the first anchor already covers the whole grid");
|
||||
assert!(t.insert_row(n));
|
||||
assert_eq!(t.n_rows(), n + 1);
|
||||
assert!(t.split(0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_past_the_cap_is_refused() {
|
||||
const { assert!(MAX_CELLS >= 75 * 75) };
|
||||
let mut t =
|
||||
Table { cols: vec![1.0; 200], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); 200] }; MAX_CELLS / 200], ..Default::default() };
|
||||
assert!(!t.over_cap());
|
||||
let before = t.clone();
|
||||
assert!(!t.insert_row(0));
|
||||
assert!(!t.insert_col(0));
|
||||
assert_eq!(t, before);
|
||||
assert!(Table::new(75, 75, 100.0, 10.0).insert_row(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merges_are_clipped_when_the_cap_drops_rows() {
|
||||
let cols = 1000;
|
||||
let rows = MAX_CELLS / cols + 1;
|
||||
let mut t = Table { cols: vec![1.0; cols], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); cols] }; rows], ..Default::default() };
|
||||
t.rows[0].cells[0].row_span = rows as u32;
|
||||
t.rows[0].cells[cols - 1].grid_span = 5;
|
||||
let n = t.normalized();
|
||||
assert_eq!(n.rows.len(), rows - 1);
|
||||
assert_eq!(n.rows[0].cells[0].row_span as usize, rows - 1);
|
||||
assert_eq!(n.rows[0].cells[cols - 1].grid_span, 1);
|
||||
t.normalize();
|
||||
assert_eq!(t.rows[0].cells[0].row_span as usize, rows - 1);
|
||||
let mut small = Table::new(3, 3, 30.0, 10.0);
|
||||
small.rows[2].cells[2].grid_span = 4;
|
||||
small.normalize();
|
||||
assert_eq!(small.rows[2].cells[2].grid_span, 4);
|
||||
}
|
||||
}
|
||||
|
||||
pub mod styles;
|
||||
@@ -12,6 +12,7 @@
|
||||
use std::io::Write as _;
|
||||
|
||||
pub mod drawing;
|
||||
pub mod lin_pat;
|
||||
pub mod model;
|
||||
pub mod mtext;
|
||||
pub mod mtext_tokens;
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
//! Readers for AutoCAD-compatible linetype (`.lin`) and hatch pattern (`.pat`) text files.
|
||||
//!
|
||||
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
|
||||
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
|
||||
//! a pattern), with `;` starting a comment. Everything here treats the text as hostile: lines,
|
||||
//! definitions, dashes, families and warnings are capped, numbers must be finite and reasonable,
|
||||
//! and nothing panics. Problems become warnings and the definitions that can be read are kept.
|
||||
|
||||
/// Longest line read; longer lines are skipped with a warning.
|
||||
pub const MAX_LINE_CHARS: usize = 4096;
|
||||
/// Most definitions (linetypes or patterns) read from one file.
|
||||
pub const MAX_DEFINITIONS: usize = 4096;
|
||||
/// Most elements in one linetype.
|
||||
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
|
||||
/// Most line families in one hatch pattern.
|
||||
pub const MAX_PATTERN_FAMILIES: usize = 1024;
|
||||
/// Most dashes in one pattern line family.
|
||||
pub const MAX_PATTERN_DASHES: usize = 256;
|
||||
/// Largest magnitude accepted for a length, offset or scale.
|
||||
pub const MAX_VALUE: f64 = 1.0e6;
|
||||
/// Longest name or description kept.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
/// Most warnings collected; the rest are counted in a last line.
|
||||
const MAX_WARNINGS: usize = 100;
|
||||
|
||||
/// One element of a linetype parsed from a `.lin` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LinDashElement {
|
||||
/// Dash (`> 0`), gap (`< 0`), or dot (`0`) length in drawing units.
|
||||
pub length: f64,
|
||||
/// Embedded text string, if any.
|
||||
pub text: Option<String>,
|
||||
/// Text style name for embedded text, if any.
|
||||
pub style: Option<String>,
|
||||
/// Text scale factor (`S=`, default `1.0`).
|
||||
pub scale: f64,
|
||||
/// Text rotation in radians (`R=`, `A=`, or `U=`, default `0.0`).
|
||||
pub rotation: f64,
|
||||
/// Text X/Y offset (`X=`, `Y=`, default `[0.0, 0.0]`).
|
||||
pub offset: [f64; 2],
|
||||
/// Whether rotation is absolute (`A=`) rather than relative to the line (`R=` or `U=`).
|
||||
pub absolute: bool,
|
||||
}
|
||||
|
||||
impl LinDashElement {
|
||||
/// A simple dash, gap, or dot element with no embedded text.
|
||||
#[must_use]
|
||||
pub fn dash(length: f64) -> Self {
|
||||
Self { length, text: None, style: None, scale: 1.0, rotation: 0.0, offset: [0.0, 0.0], absolute: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// A linetype definition parsed from a `.lin` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LinDefinition {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub pattern: Vec<LinDashElement>,
|
||||
}
|
||||
|
||||
/// One line family of a hatch pattern parsed from a `.pat` file.
|
||||
///
|
||||
/// Values are in pattern-definition coordinates as written: `angle` in degrees, `origin` as
|
||||
/// `[x, y]`, `delta` as `[delta_x, delta_y]` along/perpendicular to the line direction, and
|
||||
/// `dashes` as dash (`> 0`), gap (`< 0`), and dot (`0`) lengths.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PatLineFamily {
|
||||
pub angle: f64,
|
||||
pub origin: [f64; 2],
|
||||
pub delta: [f64; 2],
|
||||
pub dashes: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A hatch pattern definition parsed from a `.pat` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PatDefinition {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub lines: Vec<PatLineFamily>,
|
||||
}
|
||||
|
||||
/// What a file held: the definitions that could be read, and why anything else was skipped.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Parsed<T> {
|
||||
pub items: Vec<T>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T> Default for Parsed<T> {
|
||||
fn default() -> Self {
|
||||
Self { items: Vec::new(), warnings: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Parsed<T> {
|
||||
fn warn(&mut self, line: usize, msg: impl Into<String>) {
|
||||
match self.warnings.len() {
|
||||
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
|
||||
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
|
||||
fn header(rest: &str) -> std::result::Result<(String, String), String> {
|
||||
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("a definition without a name".into());
|
||||
}
|
||||
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
|
||||
return Err("a definition name that is too long or has control characters".into());
|
||||
}
|
||||
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
|
||||
Ok((name.to_string(), desc))
|
||||
}
|
||||
|
||||
/// A finite number within ±[`MAX_VALUE`].
|
||||
fn number(t: &str) -> Option<f64> {
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
|
||||
}
|
||||
|
||||
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
|
||||
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
|
||||
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
|
||||
}
|
||||
|
||||
// ---------- LIN ----------
|
||||
|
||||
/// Read the linetypes of a `.lin` file.
|
||||
///
|
||||
/// Simple linetypes and complex ones with embedded text
|
||||
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
|
||||
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
|
||||
/// Lengths are in drawing units as written: a user's file is never rescaled.
|
||||
#[must_use]
|
||||
pub fn parse_lin(text: &str) -> Parsed<LinDefinition> {
|
||||
let mut out = Parsed::default();
|
||||
// The definition being read: name, description, header line.
|
||||
let mut pending: Option<(String, String, usize)> = None;
|
||||
for (no, line) in lines(text) {
|
||||
if line.is_empty() || line.starts_with(';') {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
if let Some((name, _, at)) = pending.take() {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
match header(rest) {
|
||||
Ok((name, desc)) => pending = Some((name, desc, no)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((name, description, _)) = pending.take() else {
|
||||
out.warn(no, "pattern line without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
|
||||
break;
|
||||
}
|
||||
if out.items.iter().any(|l: &LinDefinition| l.name.eq_ignore_ascii_case(&name)) {
|
||||
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
|
||||
continue;
|
||||
}
|
||||
match lin_pattern(line, no, &name, &mut out) {
|
||||
Ok(pattern) => out.items.push(LinDefinition { name, description, pattern }),
|
||||
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
|
||||
}
|
||||
}
|
||||
if let Some((name, _, at)) = pending {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a pattern line at commas outside `[…]` and `"…"`.
|
||||
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
|
||||
let mut out = Vec::new();
|
||||
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
|
||||
for (i, c) in line.char_indices() {
|
||||
match c {
|
||||
'"' => quoted = !quoted,
|
||||
'[' if !quoted => depth = depth.saturating_add(1),
|
||||
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
|
||||
',' if !quoted && depth == 0 => {
|
||||
out.push(line.get(start..i).unwrap_or("").trim());
|
||||
start = i.saturating_add(1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
}
|
||||
if quoted || depth != 0 {
|
||||
return Err("an unclosed [ or \"".into());
|
||||
}
|
||||
out.push(line.get(start..).unwrap_or("").trim());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The elements of a pattern line `A,dash,gap,[…],…`.
|
||||
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<LinDefinition>) -> std::result::Result<Vec<LinDashElement>, String> {
|
||||
let mut fields = lin_fields(line)?;
|
||||
// The alignment field ("A") comes first; a line of plain numbers is read as well.
|
||||
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
|
||||
fields.remove(0);
|
||||
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
|
||||
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
|
||||
}
|
||||
let mut pattern: Vec<LinDashElement> = Vec::new();
|
||||
for f in fields.into_iter().filter(|f| !f.is_empty()) {
|
||||
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
let Some(inner) = f.strip_prefix('[') else {
|
||||
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
|
||||
pattern.push(LinDashElement::dash(len));
|
||||
continue;
|
||||
};
|
||||
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
|
||||
match lin_text(inner)? {
|
||||
Some(text) => {
|
||||
// The text sits at the end of the element before it (a zero-length one if none).
|
||||
if pattern.last().is_none_or(|e| e.text.is_some()) {
|
||||
pattern.push(LinDashElement::dash(0.0));
|
||||
}
|
||||
if let Some(last) = pattern.last_mut() {
|
||||
*last = LinDashElement { length: last.length, ..text };
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let shape = inner.split(',').next().unwrap_or("").trim();
|
||||
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which is not supported here; left out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if pattern.is_empty() {
|
||||
return Err("no dashes".into());
|
||||
}
|
||||
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
|
||||
return Err("every element has zero length".into());
|
||||
}
|
||||
Ok(pattern)
|
||||
}
|
||||
|
||||
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
|
||||
fn lin_text(inner: &str) -> std::result::Result<Option<LinDashElement>, String> {
|
||||
let inner = inner.trim();
|
||||
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
|
||||
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
|
||||
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
|
||||
return Err("embedded text that is too long or has control characters".into());
|
||||
}
|
||||
let mut parts = rest.split(',').map(str::trim);
|
||||
if !parts.next().unwrap_or("").is_empty() {
|
||||
return Err("text element: expected a comma after the text".into());
|
||||
}
|
||||
let style = parts.next().unwrap_or("").trim();
|
||||
if style.is_empty() || style.contains('=') {
|
||||
return Err("text element: the text style is missing".into());
|
||||
}
|
||||
let mut e = LinDashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..LinDashElement::dash(0.0) };
|
||||
for kv in parts.filter(|p| !p.is_empty()) {
|
||||
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
|
||||
match k.trim().to_ascii_uppercase().as_str() {
|
||||
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
|
||||
"X" => e.offset[0] = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
|
||||
"Y" => e.offset[1] = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
|
||||
// Upright text keeps a rotation relative to the line, like R.
|
||||
k @ ("R" | "A" | "U") => {
|
||||
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
|
||||
e.absolute = k == "A";
|
||||
}
|
||||
other => return Err(format!("text element: unknown option `{other}`")),
|
||||
}
|
||||
}
|
||||
Ok(Some(e))
|
||||
}
|
||||
|
||||
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
|
||||
fn angle(t: &str) -> Option<f64> {
|
||||
let t = t.trim().to_ascii_lowercase();
|
||||
let (num, unit) = match t.char_indices().last() {
|
||||
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
|
||||
_ => (t.as_str(), 'd'),
|
||||
};
|
||||
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
|
||||
Some(match unit {
|
||||
'r' => v,
|
||||
'g' => v * std::f64::consts::PI / 200.0,
|
||||
_ => v.to_radians(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- PAT ----------
|
||||
|
||||
/// Read the hatch patterns of a `.pat` file.
|
||||
///
|
||||
/// Values are used as written (an inch file for inch drawings, a millimetre file for metric ones).
|
||||
#[must_use]
|
||||
pub fn parse_pat(text: &str) -> Parsed<PatDefinition> {
|
||||
let mut out: Parsed<PatDefinition> = Parsed::default();
|
||||
// The pattern being read, its header line, and whether it already failed.
|
||||
let mut cur: Option<(PatDefinition, usize, bool)> = None;
|
||||
for (no, line) in lines(text) {
|
||||
// A comment runs to the end of the line.
|
||||
let line = line.split(';').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
finish_pat(cur.take(), &mut out);
|
||||
match header(rest) {
|
||||
Ok((name, description)) => cur = Some((PatDefinition { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((p, _, failed)) = cur.as_mut() else {
|
||||
out.warn(no, "line family without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if *failed {
|
||||
continue;
|
||||
}
|
||||
if p.lines.len() >= MAX_PATTERN_FAMILIES {
|
||||
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
|
||||
*failed = true;
|
||||
continue;
|
||||
}
|
||||
match pat_family(line) {
|
||||
Ok(l) => p.lines.push(l),
|
||||
Err(e) => {
|
||||
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
|
||||
*failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
finish_pat(cur, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn finish_pat(cur: Option<(PatDefinition, usize, bool)>, out: &mut Parsed<PatDefinition>) {
|
||||
let Some((p, at, failed)) = cur else { return };
|
||||
if failed {
|
||||
return;
|
||||
}
|
||||
if p.lines.is_empty() {
|
||||
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
|
||||
} else if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
|
||||
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
|
||||
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
|
||||
} else {
|
||||
out.items.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
|
||||
fn pat_family(line: &str) -> std::result::Result<PatLineFamily, String> {
|
||||
let mut v = Vec::new();
|
||||
for f in line.split(',') {
|
||||
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
|
||||
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
|
||||
}
|
||||
let f = f.trim();
|
||||
if f.is_empty() && v.len() >= 5 {
|
||||
continue;
|
||||
}
|
||||
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
|
||||
}
|
||||
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
|
||||
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
|
||||
};
|
||||
if dy.abs() < 1e-9 {
|
||||
return Err("a line family with zero spacing (delta-y)".into());
|
||||
}
|
||||
Ok(PatLineFamily { angle, origin: [x, y], delta: [dx, dy], dashes: v.get(5..).unwrap_or(&[]).to_vec() })
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Tests for `.lin` and `.pat` text resource parsing.
|
||||
|
||||
use craft_dxf::lin_pat::{MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, parse_lin, parse_pat};
|
||||
|
||||
const LIN: &str = "\
|
||||
;; my own linetypes
|
||||
*MYDASH,My dash __ __ __
|
||||
A,.5,-.25
|
||||
|
||||
*MYDOTS
|
||||
A,0,-.1,0,-.2
|
||||
*MYTEXT,Text line --MY--MY--
|
||||
A,.5,-.2,[\"MY\",STANDARD,S=.1,R=0.0,X=-0.1,Y=-.05],-.2
|
||||
*MYSHAPE,Shape line
|
||||
A,.25,-.1,[MYBOX,myshapes.shx,S=.1],-.1,1
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn simple_and_text_linetypes_are_read() {
|
||||
let r = parse_lin(LIN);
|
||||
let names: Vec<&str> = r.items.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["MYDASH", "MYDOTS", "MYTEXT", "MYSHAPE"]);
|
||||
let dash = &r.items[0];
|
||||
assert_eq!(dash.description, "My dash __ __ __");
|
||||
assert_eq!(dash.pattern.iter().map(|e| e.length).collect::<Vec<_>>(), [0.5, -0.25]);
|
||||
assert_eq!(r.items[1].description, "");
|
||||
assert_eq!(r.items[1].pattern.len(), 4);
|
||||
|
||||
// The text belongs to the gap before it: drawn at that gap's end.
|
||||
let text = &r.items[2].pattern;
|
||||
assert_eq!(text.len(), 3);
|
||||
assert_eq!(text[1].length, -0.2);
|
||||
assert_eq!(text[1].text.as_deref(), Some("MY"));
|
||||
assert_eq!(text[1].style.as_deref(), Some("STANDARD"));
|
||||
assert!((text[1].scale - 0.1).abs() < 1e-12);
|
||||
assert!((text[1].offset[0] + 0.1).abs() < 1e-12 && (text[1].offset[1] + 0.05).abs() < 1e-12);
|
||||
assert!(!text[1].absolute);
|
||||
assert!(text[2].text.is_none());
|
||||
|
||||
// Shapes need SHX files: left out with a note, the dashes kept.
|
||||
let shape = &r.items[3].pattern;
|
||||
assert_eq!(shape.iter().map(|e| e.length).collect::<Vec<_>>(), [0.25, -0.1, -0.1, 1.0]);
|
||||
assert!(shape.iter().all(|e| e.text.is_none()));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("MYBOX")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_rotation_units_and_absolute_angles() {
|
||||
let r = parse_lin("*R1\nA,1,[\"x\",S1,A=90,S=1],-1\n*R2\nA,1,[\"x\",S1,R=1.5r],-1\n*R3\nA,1,[\"a,b]\",S1,U=100g],-1\n");
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let rot = |i: usize| r.items[i].pattern[0].rotation;
|
||||
assert!((rot(0) - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && r.items[0].pattern[0].absolute);
|
||||
assert!((rot(1) - 1.5).abs() < 1e-12);
|
||||
assert!((rot(2) - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
|
||||
// Commas and brackets inside the quoted text are text.
|
||||
assert_eq!(r.items[2].pattern[0].text.as_deref(), Some("a,b]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_linetypes_are_skipped_with_warnings() {
|
||||
let text = "\
|
||||
*NOPATTERN
|
||||
*BADNUM
|
||||
A,.5,abc
|
||||
*BADALIGN
|
||||
B,.5,-.5
|
||||
*UNCLOSED
|
||||
A,.5,[\"x\",S1
|
||||
*
|
||||
A,1,-1
|
||||
A,1,-1
|
||||
*GOOD
|
||||
A,1,-1
|
||||
*GOOD
|
||||
A,2,-2
|
||||
*ZERO
|
||||
A,0,0
|
||||
*NOSTYLE
|
||||
A,1,[\"x\"],-1
|
||||
";
|
||||
let r = parse_lin(text);
|
||||
assert_eq!(r.items.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["GOOD"]);
|
||||
assert_eq!(r.items[0].pattern[0].length, 1.0, "the first definition is kept");
|
||||
for what in ["NOPATTERN", "BADNUM", "BADALIGN", "UNCLOSED", "without a name", "without a *NAME", "defined twice", "ZERO", "NOSTYLE"] {
|
||||
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_linetype_files_never_panic_and_stay_capped() {
|
||||
let long_line = format!("*LONG\nA,{}", vec!["1"; 5000].join(","));
|
||||
let many = format!("*MANY\nA,{}", vec!["1,-1"; MAX_LINETYPE_ELEMENTS].join(","));
|
||||
let defs: String = (0..5000).map(|i| format!("*L{i}\nA,1,-1\n")).collect();
|
||||
let huge = "*HUGE\nA,1e300,-1\n*NAN\nA,NaN,-1\n*INF\nA,inf,-1\n";
|
||||
for text in [long_line.as_str(), many.as_str(), defs.as_str(), huge, "", "\u{feff}", "]]][[[\"", "*\u{0}\nA,1", "A,1,-1\n*X,", "*X\nA,[[[[\"]]]"]
|
||||
{
|
||||
let r = parse_lin(text);
|
||||
assert!(r.items.len() <= 4096);
|
||||
assert!(r.items.iter().all(|l| l.pattern.len() <= MAX_LINETYPE_ELEMENTS && l.pattern.iter().all(|e| e.length.is_finite())));
|
||||
assert!(r.warnings.len() <= 101);
|
||||
}
|
||||
assert!(parse_lin(huge).items.is_empty());
|
||||
assert_eq!(parse_lin(&defs).items.len(), 4096);
|
||||
}
|
||||
|
||||
const PAT: &str = "\
|
||||
; my own patterns
|
||||
*MYGRID, My grid
|
||||
0, 0,0, 0,.5
|
||||
90, 0,0, 0,.5
|
||||
*MYBRICK,My brick ; trailing comment
|
||||
0, 0,0, 0,.25
|
||||
90, 0,0, .25,.25, .25,-.25
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn hatch_patterns_are_read() {
|
||||
let r = parse_pat(PAT);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(r.items.len(), 2);
|
||||
let grid = &r.items[0];
|
||||
assert_eq!((grid.name.as_str(), grid.description.as_str()), ("MYGRID", "My grid"));
|
||||
assert_eq!(grid.lines.len(), 2);
|
||||
assert_eq!(grid.lines[1].angle, 90.0);
|
||||
assert_eq!(grid.lines[1].delta, [0.0, 0.5]);
|
||||
let brick = &r.items[1];
|
||||
assert_eq!(brick.description, "My brick");
|
||||
assert_eq!(brick.lines[1].origin, [0.0, 0.0]);
|
||||
assert_eq!(brick.lines[1].dashes, [0.25, -0.25]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowercase_pattern_names_are_upper_cased() {
|
||||
let r = parse_pat("*mypat\n45,0,0,0,.125\n");
|
||||
assert_eq!(r.items[0].name, "MYPAT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_patterns_are_skipped_with_warnings() {
|
||||
let text = "\
|
||||
0,0,0,0,1
|
||||
*EMPTY
|
||||
*SHORT
|
||||
0,0,0
|
||||
*ZEROGAP
|
||||
0,0,0,1,0
|
||||
*BADNUM
|
||||
0,0,0,0,x
|
||||
*OK
|
||||
0,0,0,0,1
|
||||
*OK
|
||||
45,0,0,0,1
|
||||
";
|
||||
let r = parse_pat(text);
|
||||
assert_eq!(r.items.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["OK"]);
|
||||
assert_eq!(r.items[0].lines[0].angle, 0.0, "the first definition is kept");
|
||||
for what in ["without a *NAME", "EMPTY", "SHORT", "ZEROGAP", "BADNUM", "defined twice"] {
|
||||
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_pattern_files_never_panic_and_stay_capped() {
|
||||
let families = format!("*FAM\n{}", "0,0,0,0,1\n".repeat(MAX_PATTERN_FAMILIES + 5));
|
||||
let dashes = format!("*DASH\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES + 1].join(","));
|
||||
let ok_dashes = format!("*DASHOK\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES].join(","));
|
||||
let defs: String = (0..5000).map(|i| format!("*P{i}\n0,0,0,0,1\n")).collect();
|
||||
let big = "*BIG\n1e300,0,0,0,1\n*NAN\nNaN,0,0,0,1\n";
|
||||
for text in [families.as_str(), dashes.as_str(), ok_dashes.as_str(), defs.as_str(), big, "", "*", "***\n,,,,,", "*X\n,,,,,,,,,,"] {
|
||||
let r = parse_pat(text);
|
||||
assert!(r.items.len() <= 4096);
|
||||
assert!(r.items.iter().all(|p| p.lines.len() <= MAX_PATTERN_FAMILIES && p.lines.iter().all(|l| l.dashes.len() <= MAX_PATTERN_DASHES)));
|
||||
assert!(r.warnings.len() <= 101);
|
||||
}
|
||||
assert!(parse_pat(&families).items.is_empty());
|
||||
assert!(parse_pat(&dashes).items.is_empty());
|
||||
assert_eq!(parse_pat(&ok_dashes).items.len(), 1);
|
||||
assert!(parse_pat(big).items.is_empty());
|
||||
assert_eq!(parse_pat(&defs).items.len(), 4096);
|
||||
}
|
||||
@@ -39,6 +39,8 @@ pub enum Format {
|
||||
Cineon,
|
||||
Dicom,
|
||||
Iff,
|
||||
/// JPEG-LS (ITU-T T.87). Its files start with the same `FF D8 FF` bytes as JPEG files.
|
||||
JpegLs,
|
||||
Ase,
|
||||
Psd,
|
||||
Affinity,
|
||||
@@ -108,7 +110,7 @@ const fn availability(feature: bool, supported: bool) -> Availability {
|
||||
|
||||
impl Format {
|
||||
/// Every known format, including formats whose reader or writer is not enabled in this build.
|
||||
pub const ALL: [Format; 56] = [
|
||||
pub const ALL: [Format; 57] = [
|
||||
Self::Pdf,
|
||||
Self::Eps,
|
||||
Self::PostScript,
|
||||
@@ -139,6 +141,7 @@ impl Format {
|
||||
Self::Cineon,
|
||||
Self::Dicom,
|
||||
Self::Iff,
|
||||
Self::JpegLs,
|
||||
Self::Ase,
|
||||
Self::Psd,
|
||||
Self::Affinity,
|
||||
@@ -200,6 +203,7 @@ impl Format {
|
||||
Self::Cineon => &["cin"],
|
||||
Self::Dicom => &["dcm", "dicom", "dc3"],
|
||||
Self::Iff => &["iff", "lbm", "ilbm"],
|
||||
Self::JpegLs => &["jls"],
|
||||
Self::Ase => &["ase"],
|
||||
Self::Psd => &["psd", "psb", "psdt"],
|
||||
Self::Affinity => &["afdesign", "afphoto", "afpub", "af"],
|
||||
@@ -270,6 +274,7 @@ impl Format {
|
||||
Self::Cineon => "image/x-cineon",
|
||||
Self::Dicom => "application/dicom",
|
||||
Self::Iff => "image/ilbm",
|
||||
Self::JpegLs => "image/jls",
|
||||
Self::Ase => "application/x-adobe-swatch-exchange",
|
||||
Self::Psd => "image/vnd.adobe.photoshop",
|
||||
Self::Affinity => "application/x-affinity",
|
||||
@@ -327,6 +332,7 @@ impl Format {
|
||||
Self::Cineon => Codec::Cineon,
|
||||
Self::Dicom => Codec::Dicom,
|
||||
Self::Iff => Codec::Iff,
|
||||
Self::JpegLs => Codec::JpegLs,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -381,7 +387,8 @@ impl Format {
|
||||
| Self::Fits
|
||||
| Self::Dpx
|
||||
| Self::Cineon
|
||||
| Self::Iff => capability(raster, true, true, false, false),
|
||||
| Self::Iff
|
||||
| Self::JpegLs => capability(raster, true, true, false, false),
|
||||
Self::Pdf => capability(cfg!(feature = "pdf"), true, true, false, false),
|
||||
Self::Eps | Self::PostScript | Self::Illustrator => capability(cfg!(feature = "pdf"), true, false, false, false),
|
||||
Self::Svg | Self::Svgz => capability(cfg!(feature = "svg"), true, false, false, false),
|
||||
@@ -483,7 +490,7 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<Format> {
|
||||
if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("af")) {
|
||||
return Some(Format::Affinity);
|
||||
}
|
||||
if let Some(raster) = raster_signature(bytes) {
|
||||
if let Some(raster) = raster_signature(name, bytes) {
|
||||
return Some(raster);
|
||||
}
|
||||
if bytes.starts_with(b"silhouette04;") || bytes.starts_with(b"silhouette05;") {
|
||||
@@ -598,13 +605,18 @@ fn dxf_ascii_prefix(bytes: &[u8]) -> bool {
|
||||
matches!((lines.next(), lines.next(), lines.next(), lines.next()), (Some("0"), Some("SECTION"), Some("2"), Some(section)) if matches!(section, "HEADER" | "CLASSES" | "TABLES" | "BLOCKS" | "ENTITIES" | "OBJECTS"))
|
||||
}
|
||||
|
||||
fn raster_signature(bytes: &[u8]) -> Option<Format> {
|
||||
fn raster_signature(name: &str, bytes: &[u8]) -> Option<Format> {
|
||||
let head = bytes.get(..16).unwrap_or(bytes);
|
||||
if head.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
return Some(Format::Png);
|
||||
}
|
||||
if head.starts_with(b"\xff\xd8\xff") {
|
||||
return Some(Format::Jpeg);
|
||||
return Some(match jpeg_frame(bytes) {
|
||||
JpegFrame::Ls => Format::JpegLs,
|
||||
JpegFrame::Other => Format::Jpeg,
|
||||
JpegFrame::Unknown if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("jls")) => Format::JpegLs,
|
||||
JpegFrame::Unknown => Format::Jpeg,
|
||||
});
|
||||
}
|
||||
if head.starts_with(b"BM") {
|
||||
return Some(Format::Bmp);
|
||||
@@ -620,3 +632,50 @@ fn raster_signature(bytes: &[u8]) -> Option<Format> {
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What the marker segments after a JPEG start-of-image marker lead to.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum JpegFrame {
|
||||
/// An SOF55 frame header (`FF F7`, ITU-T T.87): JPEG-LS.
|
||||
Ls,
|
||||
/// Another frame header, a scan header, an end-of-image marker, or a byte that is not a
|
||||
/// marker where one should be.
|
||||
Other,
|
||||
/// The bytes, or the probe's first 1 MiB, end before a frame or scan header.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Walk the marker segments from the start-of-image marker to the first frame or scan header.
|
||||
/// Only the first 1 MiB is read, and each step moves forward at least one byte. The walk follows
|
||||
/// `jpeg_frame_from` in craft-image-codecs, which a build without the `raster-codecs` feature does
|
||||
/// not link.
|
||||
fn jpeg_frame(bytes: &[u8]) -> JpegFrame {
|
||||
const LIMIT: usize = 1 << 20;
|
||||
let bytes = bytes.get(..bytes.len().min(LIMIT)).unwrap_or(bytes);
|
||||
let mut pos = 2;
|
||||
loop {
|
||||
let (Some(&prefix), Some(&marker)) = (bytes.get(pos), bytes.get(pos + 1)) else {
|
||||
return if bytes.get(pos).is_none_or(|&prefix| prefix == 0xFF) { JpegFrame::Unknown } else { JpegFrame::Other };
|
||||
};
|
||||
if prefix != 0xFF {
|
||||
return JpegFrame::Other;
|
||||
}
|
||||
match marker {
|
||||
0xF7 => return JpegFrame::Ls,
|
||||
// `FF 00` is a stuffed zero, not a marker.
|
||||
0x00 | 0xDA | 0xD9 => return JpegFrame::Other,
|
||||
// A DRI segment (`FF DD`) may come before an SOF55 frame header, so it is skipped
|
||||
// by its length below.
|
||||
0xC0..=0xCF | 0xDB | 0xDC | 0xDE | 0xDF => return JpegFrame::Other,
|
||||
// A fill byte, or a marker without a length.
|
||||
0xFF => pos += 1,
|
||||
0x01 | 0xD0..=0xD7 => pos += 2,
|
||||
_ => {
|
||||
let Some(length) = bytes.get(pos + 2..pos + 4).map(|length| usize::from(u16::from_be_bytes([length[0], length[1]]))) else {
|
||||
return JpegFrame::Unknown;
|
||||
};
|
||||
pos += 2 + length;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,17 @@ fn known_formats_separate_build_disabled_and_unsupported_operations() {
|
||||
#[cfg(not(feature = "raster-codecs"))]
|
||||
assert_eq!(jpeg.read, Availability::BuildDisabled);
|
||||
|
||||
// Whether this build reads JPEG XL is craft-image-codecs' `jxl` feature to decide, and this
|
||||
// crate cannot see that through `cfg!`: a workspace build turns it on without this crate
|
||||
// selecting anything, which is how a plain equality here failed every `--all-features` gate.
|
||||
// The codec's own answer is the one to check against, so a wrong read status is still caught.
|
||||
#[cfg(feature = "raster-codecs")]
|
||||
assert!(matches!(Format::Jxl.capabilities().read, Availability::Available | Availability::Unsupported));
|
||||
{
|
||||
let codec = Format::Jxl.raster_codec();
|
||||
assert!(codec.is_some(), "JXL is handled by craft-image-codecs and must map to one of its formats");
|
||||
let expected = if codec.is_some_and(|codec| codec.caps().read) { Availability::Available } else { Availability::Unsupported };
|
||||
assert_eq!(Format::Jxl.capabilities().read, expected);
|
||||
}
|
||||
#[cfg(not(feature = "raster-codecs"))]
|
||||
assert_eq!(Format::Jxl.capabilities().read, Availability::Unsupported);
|
||||
#[cfg(not(feature = "raster-codecs"))]
|
||||
@@ -48,6 +57,72 @@ fn bounded_probes_prefer_signatures_and_resolve_extensions() {
|
||||
assert_eq!(super::detect("unknown", b""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_ls_is_told_from_jpeg_and_resolves_its_extension() {
|
||||
assert_eq!(super::from_extension("JLS"), Some(Format::JpegLs));
|
||||
assert_eq!(Format::JpegLs.mime_type(), Some("image/jls"));
|
||||
assert_eq!(super::detect("scan.jls", b""), Some(Format::JpegLs));
|
||||
// SOI followed by an SOF55 frame header.
|
||||
assert_eq!(super::detect("scan.jpg", b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0"), Some(Format::JpegLs));
|
||||
assert_eq!(super::detect("photo.jls", b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0"), Some(Format::Jpeg));
|
||||
// An APP0 segment, a fill byte and a DRI segment before the SOF55 frame header.
|
||||
let with_segments = b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0";
|
||||
assert_eq!(super::detect("scan.jpg", with_segments), Some(Format::JpegLs));
|
||||
assert_eq!(super::detect("", with_segments), Some(Format::JpegLs));
|
||||
// Bytes that end before any frame header: the name decides.
|
||||
assert_eq!(super::detect("scan.jls", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::JpegLs));
|
||||
assert_eq!(super::detect("photo.jpg", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg));
|
||||
assert_eq!(super::detect("", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_marker_walk_reads_only_the_first_mebibyte() {
|
||||
let mut bytes = vec![0xFF; (1 << 20) + 64];
|
||||
bytes[1] = 0xD8;
|
||||
let len = bytes.len();
|
||||
bytes[len - 2] = 0xF7;
|
||||
assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::Jpeg));
|
||||
assert_eq!(super::detect("scan.jls", &bytes), Some(Format::JpegLs));
|
||||
bytes[1 << 19] = 0xF7;
|
||||
assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::JpegLs));
|
||||
}
|
||||
|
||||
#[cfg(feature = "raster-codecs")]
|
||||
#[test]
|
||||
fn jpeg_marker_walk_matches_the_codec_detection() {
|
||||
let cases: [&[u8]; 6] = [
|
||||
b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0",
|
||||
b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0",
|
||||
b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0",
|
||||
b"\xff\xd8\xff\xd0\xff\x01\xff\xf7\0\x0b",
|
||||
b"\xff\xd8\xff\xe0\0\x04\0\0\x12\x34",
|
||||
b"\xff\xd8\xff\xda\0\x08",
|
||||
];
|
||||
for bytes in cases {
|
||||
let expected = match craft_image_codecs::detect(bytes) {
|
||||
Some(craft_image_codecs::Format::JpegLs) => Format::JpegLs,
|
||||
_ => Format::Jpeg,
|
||||
};
|
||||
assert_eq!(super::detect("", bytes), Some(expected), "{bytes:02x?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_ls_capabilities_follow_the_codec() {
|
||||
#[cfg(feature = "raster-codecs")]
|
||||
{
|
||||
assert_eq!(Format::JpegLs.raster_codec(), Some(craft_image_codecs::Format::JpegLs));
|
||||
assert_eq!(Format::JpegLs.extensions(), craft_image_codecs::Format::JpegLs.extensions());
|
||||
assert_eq!(Format::JpegLs.capabilities().read, Availability::Available);
|
||||
assert_eq!(Format::JpegLs.capabilities().write, Availability::Available);
|
||||
}
|
||||
#[cfg(not(feature = "raster-codecs"))]
|
||||
{
|
||||
assert_eq!(Format::JpegLs.capabilities().read, Availability::BuildDisabled);
|
||||
assert_eq!(Format::JpegLs.capabilities().write, Availability::BuildDisabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_mime_and_preferred_extensions_remain_distinct() {
|
||||
assert_eq!(Format::Svg.mime_type(), Format::Svgz.mime_type());
|
||||
|
||||
@@ -18,5 +18,8 @@ kurbo = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-image-codecs = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -89,14 +89,15 @@ pub const CAPABILITIES: &[Capability] = &[
|
||||
detected_formats: &[
|
||||
craft_file_formats::Format::Png,
|
||||
craft_file_formats::Format::Jpeg,
|
||||
craft_file_formats::Format::JpegLs,
|
||||
craft_file_formats::Format::Bmp,
|
||||
craft_file_formats::Format::Gif,
|
||||
craft_file_formats::Format::Tiff,
|
||||
craft_file_formats::Format::WebP,
|
||||
],
|
||||
extensions: &["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff", "webp"],
|
||||
extensions: &["png", "jpg", "jpeg", "jls", "bmp", "gif", "tif", "tiff", "webp"],
|
||||
write_extensions: &["png", "jpg", "jpeg"],
|
||||
mime_types: &["image/png", "image/jpeg", "image/bmp", "image/gif", "image/tiff", "image/webp"],
|
||||
mime_types: &["image/png", "image/jpeg", "image/jls", "image/bmp", "image/gif", "image/tiff", "image/webp"],
|
||||
raster: true,
|
||||
vector: false,
|
||||
},
|
||||
@@ -197,7 +198,7 @@ pub fn format_for(name: &str, bytes: &[u8]) -> Option<ImportFormat> {
|
||||
F::Pdf => Some(ImportFormat::Pdf),
|
||||
F::Illustrator if bytes.starts_with(b"%PDF-") => Some(ImportFormat::Pdf),
|
||||
F::Eps | F::PostScript | F::Illustrator => Some(ImportFormat::Eps),
|
||||
F::Png | F::Jpeg | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster),
|
||||
F::Png | F::Jpeg | F::JpegLs | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -402,4 +403,27 @@ mod format_tests {
|
||||
let bytes = b"%PDF-1.7\n/AIPrivateData";
|
||||
assert_eq!(format_for("illustration.ai", bytes), Some(ImportFormat::Pdf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_ls_is_routed_to_the_raster_reader() {
|
||||
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, encode};
|
||||
let gray: Vec<u8> = (0..6).map(|value| value * 40).collect();
|
||||
let Ok(image) = Image::from_u8(3, 2, ChannelLayout::Gray, gray.clone()) else {
|
||||
panic!("a 3 by 2 gray image");
|
||||
};
|
||||
let Ok(bytes) = encode(&image, Format::JpegLs, &EncodeOptions::default()) else {
|
||||
panic!("JPEG-LS encodes");
|
||||
};
|
||||
for name in ["scan.jls", "scan.jpg", "scan"] {
|
||||
assert_eq!(format_for(name, &bytes), Some(ImportFormat::Raster), "{name}");
|
||||
let Ok(Imported::Raster(raster)) = import(name, &bytes, Limits::default()) else {
|
||||
panic!("{name} imports as a raster image");
|
||||
};
|
||||
assert_eq!((raster.width, raster.height), (3, 2));
|
||||
let red: Vec<u8> = raster.rgba.as_chunks::<4>().0.iter().map(|pixel| pixel[0]).collect();
|
||||
assert_eq!(red, gray, "{name}");
|
||||
}
|
||||
assert!(supported_formats(ImportFormat::Raster).contains(&craft_file_formats::Format::JpegLs));
|
||||
assert!(supported_extensions().contains(&"jls"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "craft-gpu-null"
|
||||
description = "In-memory GpuContext for CI and headless tests"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-gpu = { workspace = true }
|
||||
@@ -0,0 +1,156 @@
|
||||
//! CPU-only [`GpuContext`] for tests and CI.
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadRequest, WorkerKind};
|
||||
|
||||
/// In-memory buffer store; no GPU hardware required. Reads resolve synchronously (there is
|
||||
/// nothing to wait for), so [`request_read`](GpuContext::request_read) and
|
||||
/// [`poll_reads`](GpuContext::poll_reads) satisfy the trait trivially.
|
||||
/// [`read_buffer`](GpuContext::read_buffer) is overridden to take only its own completion,
|
||||
/// leaving completions for other outstanding requests queued for the next
|
||||
/// [`poll_reads`](GpuContext::poll_reads).
|
||||
pub struct NullContext {
|
||||
caps: DeviceCaps,
|
||||
worker_kind: WorkerKind,
|
||||
/// `None` means freed (or never allocated): handles are stable indices into this Vec, so a
|
||||
/// freed slot cannot simply be removed without shifting every later handle's index.
|
||||
buffers: Vec<Option<Vec<u8>>>,
|
||||
next_request: u64,
|
||||
ready: Vec<ReadOutcome>,
|
||||
}
|
||||
|
||||
impl NullContext {
|
||||
pub fn new(worker_kind: WorkerKind) -> Self {
|
||||
Self {
|
||||
caps: DeviceCaps { backend_name: "null".into(), device_name: "null".into(), ..DeviceCaps::default() },
|
||||
worker_kind,
|
||||
buffers: Vec::new(),
|
||||
next_request: 0,
|
||||
ready: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuContext for NullContext {
|
||||
fn caps(&self) -> DeviceCaps {
|
||||
self.caps.clone()
|
||||
}
|
||||
|
||||
fn worker_kind(&self) -> WorkerKind {
|
||||
self.worker_kind
|
||||
}
|
||||
|
||||
fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result<HandleId, GpuFault> {
|
||||
let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?);
|
||||
self.buffers.push(Some(bytes.to_vec()));
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn buffer_len(&self, handle: HandleId) -> Result<usize, GpuFault> {
|
||||
self.buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))
|
||||
}
|
||||
|
||||
fn request_read(&mut self, handle: HandleId) -> Result<ReadRequest, GpuFault> {
|
||||
let bytes = self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?;
|
||||
let request = ReadRequest(self.next_request);
|
||||
self.next_request = self.next_request.wrapping_add(1);
|
||||
self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) });
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn poll_reads(&mut self) -> Vec<ReadOutcome> {
|
||||
std::mem::take(&mut self.ready)
|
||||
}
|
||||
|
||||
fn read_buffer(&mut self, handle: HandleId) -> Result<Vec<u8>, GpuFault> {
|
||||
let request = self.request_read(handle)?;
|
||||
match self.ready.iter().position(|o| o.request == request) {
|
||||
Some(i) => self.ready.remove(i).result,
|
||||
None => Err(GpuFault::Operation("request_read did not resolve synchronously".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the slot with `None` rather than removing it: handles are stable indices, and
|
||||
/// removing would shift every later handle's index out from under its caller.
|
||||
fn free_buffer(&mut self, handle: HandleId) {
|
||||
if let Some(slot) = self.buffers.get_mut(handle.0 as usize) {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft_gpu::{GpuContext, GpuFault, HandleId, WorkerKind};
|
||||
|
||||
use super::NullContext;
|
||||
|
||||
#[test]
|
||||
fn request_read_then_poll_reads_delivers_the_same_bytes_as_read_buffer() {
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let handle = ctx.upload_buffer("in", b"abc").expect("upload_buffer");
|
||||
let request = ctx.request_read(handle).expect("request_read");
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert_eq!(outcomes[0].handle, handle);
|
||||
assert_eq!(outcomes[0].result.as_deref(), Ok(b"abc".as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_buffer_default_still_works() {
|
||||
let mut ctx = NullContext::new(WorkerKind::SharedWorker);
|
||||
let handle = ctx.upload_buffer("in", b"xyz").expect("upload_buffer");
|
||||
assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"xyz".to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_buffer_keeps_another_outstanding_requests_completion_queued() {
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let a = ctx.upload_buffer("a", b"aa").expect("upload a");
|
||||
let b = ctx.upload_buffer("b", b"bb").expect("upload b");
|
||||
let request_a = ctx.request_read(a).expect("request_read a");
|
||||
assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec());
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1, "a's completion must survive b's read_buffer");
|
||||
assert_eq!(outcomes[0].request, request_a);
|
||||
assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_buffer_uploads_and_reads_back_empty() {
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let handle = ctx.upload_buffer("empty", b"").expect("upload empty");
|
||||
assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0);
|
||||
assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::<u8>::new());
|
||||
}
|
||||
|
||||
/// CodeRabbit finding on gpu-wgpu/src/lib.rs:313: nothing released an uploaded buffer's
|
||||
/// resources, so a backend's buffer table could only ever grow. free_buffer must actually
|
||||
/// reclaim the payload and make the handle behave as invalid afterward, not just forget it
|
||||
/// exists while still holding its bytes.
|
||||
#[test]
|
||||
fn free_buffer_invalidates_the_handle_and_does_not_shift_other_handles() {
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let a = ctx.upload_buffer("a", b"aa").expect("upload a");
|
||||
let b = ctx.upload_buffer("b", b"bb").expect("upload b");
|
||||
|
||||
ctx.free_buffer(a);
|
||||
|
||||
assert!(matches!(ctx.buffer_len(a), Err(GpuFault::InvalidJob(_))), "a freed handle must behave as invalid");
|
||||
assert_eq!(ctx.buffer_len(b).expect("b must be unaffected by freeing a"), 2);
|
||||
assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec(), "b's own index must not have shifted");
|
||||
}
|
||||
|
||||
/// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not
|
||||
/// expected to track whether they already freed one.
|
||||
#[test]
|
||||
fn free_buffer_is_a_harmless_no_op_when_repeated_or_given_an_unknown_handle() {
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let a = ctx.upload_buffer("a", b"aa").expect("upload a");
|
||||
ctx.free_buffer(a);
|
||||
ctx.free_buffer(a); // already freed
|
||||
ctx.free_buffer(HandleId(999)); // never existed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "craft-gpu-providers"
|
||||
description = "Shared GpuProvider implementations (composite, readback, …) — no app deps"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-gpu = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-gpu-null = { workspace = true }
|
||||
@@ -0,0 +1,69 @@
|
||||
use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider};
|
||||
|
||||
use crate::params::parse_u32;
|
||||
|
||||
/// CPU stand-in for FilmCraft `composite.wgsl` Normal/Dissolve premultiplied "over" until WGSL runs on wgpu.
|
||||
pub struct PremulCompositeProvider;
|
||||
|
||||
impl GpuProvider for PremulCompositeProvider {
|
||||
fn id(&self) -> &'static str {
|
||||
"craft.composite.premul"
|
||||
}
|
||||
|
||||
fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result<GpuJobOutcome, GpuFault> {
|
||||
let width = parse_u32(&job.params, b"w:").unwrap_or(1).max(1) as usize;
|
||||
let height = parse_u32(&job.params, b"h:").unwrap_or(1).max(1) as usize;
|
||||
let len = width.saturating_mul(height).saturating_mul(4);
|
||||
let (dst_h, src_h) = match job.inputs.as_slice() {
|
||||
[a, b] => (a, b),
|
||||
[a] => (a, a),
|
||||
_ => {
|
||||
return Err(GpuFault::InvalidJob("craft.composite.premul expects one or two RGBA8 inputs (backdrop, layer)".into()));
|
||||
}
|
||||
};
|
||||
let dst_bytes = ctx.read_buffer(*dst_h)?;
|
||||
let src_bytes = ctx.read_buffer(*src_h)?;
|
||||
if dst_bytes.len() < len || src_bytes.len() < len {
|
||||
return Err(GpuFault::InvalidJob("input buffer shorter than w*h*4".into()));
|
||||
}
|
||||
let mut out = vec![0u8; len];
|
||||
for px in 0..width.saturating_mul(height) {
|
||||
let i = px * 4;
|
||||
let mut dst = straight_to_premul([dst_bytes[i], dst_bytes[i + 1], dst_bytes[i + 2], dst_bytes[i + 3]]);
|
||||
let src = straight_to_premul([src_bytes[i], src_bytes[i + 1], src_bytes[i + 2], src_bytes[i + 3]]);
|
||||
premul_over(&mut dst, src);
|
||||
let straight = premul_to_straight(dst);
|
||||
out[i..i + 4].copy_from_slice(&straight);
|
||||
}
|
||||
let handle = ctx.upload_buffer("craft.composite.premul.out", &out)?;
|
||||
Ok(GpuJobOutcome { outputs: vec![handle], data: None })
|
||||
}
|
||||
}
|
||||
|
||||
/// Premultiplied `src` over premultiplied `dst` (`filmcraft_render` / `composite.wgsl` Normal path).
|
||||
fn premul_over(dst: &mut [f32; 4], src: [f32; 4]) {
|
||||
let k = 1.0 - src[3];
|
||||
for c in 0..4 {
|
||||
dst[c] = src[c] + dst[c] * k;
|
||||
}
|
||||
}
|
||||
|
||||
fn straight_to_premul(p: [u8; 4]) -> [f32; 4] {
|
||||
let a = f32::from(p[3]) / 255.0;
|
||||
let s = a / 255.0;
|
||||
[f32::from(p[0]) * s, f32::from(p[1]) * s, f32::from(p[2]) * s, a]
|
||||
}
|
||||
|
||||
fn premul_to_straight(p: [f32; 4]) -> [u8; 4] {
|
||||
let a = p[3].clamp(0.0, 1.0);
|
||||
if a <= f32::EPSILON {
|
||||
return [0, 0, 0, 0];
|
||||
}
|
||||
let inv = 255.0 / a;
|
||||
[
|
||||
(p[0] * inv).round().clamp(0.0, 255.0) as u8,
|
||||
(p[1] * inv).round().clamp(0.0, 255.0) as u8,
|
||||
(p[2] * inv).round().clamp(0.0, 255.0) as u8,
|
||||
(a * 255.0).round().clamp(0.0, 255.0) as u8,
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider};
|
||||
|
||||
/// Concatenates job params with bytes from the first input handle (shared test / debug provider).
|
||||
pub struct EchoProvider;
|
||||
|
||||
impl GpuProvider for EchoProvider {
|
||||
fn id(&self) -> &'static str {
|
||||
"craft.test.echo"
|
||||
}
|
||||
|
||||
fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result<GpuJobOutcome, GpuFault> {
|
||||
let mut data = job.params.0.clone();
|
||||
if let Some(&h) = job.inputs.first() {
|
||||
data.extend_from_slice(&ctx.read_buffer(h)?);
|
||||
}
|
||||
Ok(GpuJobOutcome { outputs: job.outputs.clone(), data: Some(data) })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Generic GPU providers extracted from app crates over time (craft-libs#7).
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod composite;
|
||||
mod echo;
|
||||
mod mask;
|
||||
mod noop;
|
||||
mod params;
|
||||
mod readback;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use craft_gpu::{GpuProvider, ProviderRegistry};
|
||||
|
||||
pub use composite::PremulCompositeProvider;
|
||||
pub use echo::EchoProvider;
|
||||
pub use mask::MaskProvider;
|
||||
pub use noop::NoopProvider;
|
||||
pub use readback::ReadbackProvider;
|
||||
|
||||
/// Default shared providers for worker/runtime init (`craft.*` ids only).
|
||||
pub fn register_all() -> Vec<Box<dyn GpuProvider>> {
|
||||
vec![Box::new(NoopProvider), Box::new(EchoProvider), Box::new(MaskProvider), Box::new(PremulCompositeProvider), Box::new(ReadbackProvider)]
|
||||
}
|
||||
|
||||
/// Register [`register_all`] providers into an existing registry.
|
||||
pub fn register_all_into(registry: &mut ProviderRegistry) {
|
||||
for provider in register_all() {
|
||||
registry.register(provider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider};
|
||||
|
||||
use crate::params::parse_u32;
|
||||
|
||||
/// CPU stand-in for FilmCraft mask composite until WGSL runs on wgpu.
|
||||
pub struct MaskProvider;
|
||||
|
||||
impl GpuProvider for MaskProvider {
|
||||
fn id(&self) -> &'static str {
|
||||
"craft.mask"
|
||||
}
|
||||
|
||||
fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result<GpuJobOutcome, GpuFault> {
|
||||
let width = parse_u32(&job.params, b"w:").unwrap_or(1).max(1) as usize;
|
||||
let height = parse_u32(&job.params, b"h:").unwrap_or(1).max(1) as usize;
|
||||
let len = width.saturating_mul(height).saturating_mul(4);
|
||||
let (base, mask) = match job.inputs.as_slice() {
|
||||
[a, b] => (a, b),
|
||||
[a] => (a, a),
|
||||
_ => return Err(GpuFault::InvalidJob("craft.mask expects one or two RGBA inputs".into())),
|
||||
};
|
||||
let base_bytes = ctx.read_buffer(*base)?;
|
||||
let mask_bytes = ctx.read_buffer(*mask)?;
|
||||
if base_bytes.len() < len || mask_bytes.len() < len {
|
||||
return Err(GpuFault::InvalidJob("input buffer shorter than w*h*4".into()));
|
||||
}
|
||||
let mut out = vec![0u8; len];
|
||||
for i in 0..len {
|
||||
let m = mask_bytes[i];
|
||||
out[i] = ((u16::from(base_bytes[i]) * u16::from(m)) / 255) as u8;
|
||||
}
|
||||
let handle = ctx.upload_buffer("craft.mask.out", &out)?;
|
||||
Ok(GpuJobOutcome { outputs: vec![handle], data: None })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider};
|
||||
|
||||
/// No-op dispatch for wiring tests; shared readback/composite providers live in sibling modules.
|
||||
pub struct NoopProvider;
|
||||
|
||||
impl GpuProvider for NoopProvider {
|
||||
fn id(&self) -> &'static str {
|
||||
"craft.noop"
|
||||
}
|
||||
|
||||
fn run(&self, _ctx: &mut dyn GpuContext, job: &GpuJob) -> Result<GpuJobOutcome, GpuFault> {
|
||||
Ok(GpuJobOutcome { outputs: job.outputs.clone(), data: None })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use craft_gpu::GpuJobParams;
|
||||
|
||||
pub(crate) fn parse_u32(params: &GpuJobParams, prefix: &[u8]) -> Option<u32> {
|
||||
// `windows(0)` panics; an empty prefix is a caller bug, answered with None, not a crash.
|
||||
if prefix.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let bytes = params.0.as_slice();
|
||||
let start = bytes.windows(prefix.len()).position(|w| w == prefix)? + prefix.len();
|
||||
let rest = &bytes[start..];
|
||||
let end = rest.iter().position(|&b| b == b',' || b == b';').unwrap_or(rest.len());
|
||||
std::str::from_utf8(&rest[..end]).ok()?.parse().ok()
|
||||
}
|
||||
|
||||
pub(crate) fn params_contain(params: &GpuJobParams, needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && params.0.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider, f16_rgba_to_f32_bytes};
|
||||
|
||||
use crate::params::{params_contain, parse_u32};
|
||||
|
||||
/// CPU stand-in for accumulator/output readback (`read_accumulator` / `read_output` in FilmCraft gpu) until wgpu maps buffers.
|
||||
pub struct ReadbackProvider;
|
||||
|
||||
impl GpuProvider for ReadbackProvider {
|
||||
fn id(&self) -> &'static str {
|
||||
"craft.readback"
|
||||
}
|
||||
|
||||
fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result<GpuJobOutcome, GpuFault> {
|
||||
let width = parse_u32(&job.params, b"w:").unwrap_or(0);
|
||||
let height = parse_u32(&job.params, b"h:").unwrap_or(0);
|
||||
let input = job.inputs.first().copied().ok_or_else(|| GpuFault::InvalidJob("craft.readback expects one input buffer".into()))?;
|
||||
let raw = ctx.read_buffer(input)?;
|
||||
// A real GPU provider binds the input as a storage buffer. Refuse a caps report no
|
||||
// device path could satisfy, instead of pretending this stand-in's readback would have
|
||||
// worked there.
|
||||
if ctx.caps().max_storage_buffer_binding_size == 0 {
|
||||
return Err(GpuFault::Operation("max_storage_buffer_binding_size must be non-zero".into()));
|
||||
}
|
||||
|
||||
let out_bytes = if params_contain(&job.params, b"fmt:u8") {
|
||||
let need = usize::try_from(width.saturating_mul(height).saturating_mul(4)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?;
|
||||
if need == 0 || raw.len() < need {
|
||||
return Err(GpuFault::InvalidJob("rgba8 readback shorter than w*h*4".into()));
|
||||
}
|
||||
raw[..need].to_vec()
|
||||
} else {
|
||||
let need = usize::try_from(width.saturating_mul(height).saturating_mul(8)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?;
|
||||
if need == 0 || raw.len() < need {
|
||||
return Err(GpuFault::InvalidJob("f16 rgba readback shorter than w*h*8".into()));
|
||||
}
|
||||
f16_rgba_to_f32_bytes(&raw[..need]).map_err(|len| GpuFault::InvalidJob(format!("f16 rgba length {len} not multiple of 8")))?
|
||||
};
|
||||
|
||||
let handle = ctx.upload_buffer("craft.readback.out", &out_bytes)?;
|
||||
Ok(GpuJobOutcome { outputs: vec![handle], data: None })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
#![allow(clippy::expect_used)]
|
||||
|
||||
use craft_gpu::{GpuContext, GpuJob, GpuJobParams, ProviderRegistry, WorkerKind, f16_to_f32, f16_to_f32_fast};
|
||||
use craft_gpu_null::NullContext;
|
||||
|
||||
use crate::{EchoProvider, MaskProvider, NoopProvider, PremulCompositeProvider, ReadbackProvider, register_all, register_all_into};
|
||||
|
||||
#[test]
|
||||
fn noop_provider_registered_by_id() {
|
||||
let mut registry = ProviderRegistry::new();
|
||||
registry.register(Box::new(NoopProvider));
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let job = GpuJob { provider_id: "craft.noop".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] };
|
||||
let out = registry.dispatch(&mut ctx, &job).expect("noop dispatch");
|
||||
assert!(out.data.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn echo_provider_concatenates_params_and_first_input() {
|
||||
let mut registry = ProviderRegistry::new();
|
||||
registry.register(Box::new(EchoProvider));
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let h = ctx.upload_buffer("in", b"xy").expect("upload_buffer in test");
|
||||
let job = GpuJob { provider_id: "craft.test.echo".into(), params: GpuJobParams(b"a".to_vec()), inputs: vec![h], outputs: vec![] };
|
||||
let out = registry.dispatch(&mut ctx, &job).expect("echo dispatch");
|
||||
assert_eq!(out.data.as_deref(), Some(b"axy".as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn register_all_lists_shared_providers() {
|
||||
let ids: Vec<_> = register_all().iter().map(|p| p.id()).collect();
|
||||
assert_eq!(ids, vec!["craft.noop", "craft.test.echo", "craft.mask", "craft.composite.premul", "craft.readback",]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_providers_cargo_has_no_app_deps() {
|
||||
let manifest = include_str!("../Cargo.toml");
|
||||
for line in manifest.lines() {
|
||||
let t = line.trim();
|
||||
assert!(
|
||||
!(t.starts_with("effectcraft")
|
||||
|| t.starts_with("filmcraft")
|
||||
|| t.contains("effectcraft-")
|
||||
|| t.contains("filmcraft-")
|
||||
|| t.contains("-engine =")
|
||||
|| t.contains("-engine.")
|
||||
|| t.contains("-engine\"")),
|
||||
"forbidden app dependency line: {t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_param_prefix_and_needle_are_refused_not_a_panic() {
|
||||
let params = GpuJobParams(b"w:3,h:2".to_vec());
|
||||
assert_eq!(crate::params::parse_u32(¶ms, b""), None);
|
||||
assert!(!crate::params::params_contain(¶ms, b""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_provider_multiplies_rgba_by_mask_on_cpu() {
|
||||
let mut registry = ProviderRegistry::new();
|
||||
registry.register(Box::new(MaskProvider));
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let base = ctx.upload_buffer("base", &[255u8, 0, 0, 255, 100, 100, 100, 255]).expect("upload base");
|
||||
let mask = ctx.upload_buffer("mask", &[128u8, 255, 255, 255, 0, 255, 255, 255]).expect("upload mask");
|
||||
let job =
|
||||
craft_gpu::GpuJob { provider_id: "craft.mask".into(), params: GpuJobParams(b"w:1,h:2".to_vec()), inputs: vec![base, mask], outputs: vec![] };
|
||||
let out = registry.dispatch(&mut ctx, &job).expect("mask dispatch");
|
||||
let handle = out.outputs[0];
|
||||
let bytes = ctx.read_buffer(handle).expect("read mask out");
|
||||
assert_eq!(bytes[0], 128);
|
||||
assert_eq!(bytes[4], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premul_composite_over_on_cpu() {
|
||||
let mut registry = ProviderRegistry::new();
|
||||
registry.register(Box::new(PremulCompositeProvider));
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
// backdrop: green opaque; layer: half-alpha blue
|
||||
let dst = ctx.upload_buffer("dst", &[0, 255, 0, 255]).expect("upload dst");
|
||||
let src = ctx.upload_buffer("src", &[0, 0, 255, 128]).expect("upload src");
|
||||
let job =
|
||||
GpuJob { provider_id: "craft.composite.premul".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![dst, src], outputs: vec![] };
|
||||
let out = registry.dispatch(&mut ctx, &job).expect("premul composite");
|
||||
let bytes = ctx.read_buffer(out.outputs[0]).expect("read out");
|
||||
assert_eq!(bytes[0], 0);
|
||||
assert_eq!(bytes[1], 127);
|
||||
assert_eq!(bytes[2], 128);
|
||||
assert_eq!(bytes[3], 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readback_decodes_f16_rgba_to_f32() {
|
||||
let mut registry = ProviderRegistry::new();
|
||||
registry.register(Box::new(ReadbackProvider));
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let h = half_float_one();
|
||||
let mut raw = Vec::new();
|
||||
raw.extend_from_slice(&h.to_le_bytes());
|
||||
raw.extend_from_slice(&h.to_le_bytes());
|
||||
raw.extend_from_slice(&h.to_le_bytes());
|
||||
raw.extend_from_slice(&0u16.to_le_bytes());
|
||||
let inp = ctx.upload_buffer("accum", &raw).expect("upload f16");
|
||||
let job = GpuJob { provider_id: "craft.readback".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![inp], outputs: vec![] };
|
||||
let out = registry.dispatch(&mut ctx, &job).expect("readback");
|
||||
let decoded = ctx.read_buffer(out.outputs[0]).expect("read f32 out");
|
||||
assert_eq!(decoded.len(), 16);
|
||||
let r = f32::from_le_bytes(decoded[0..4].try_into().expect("r"));
|
||||
assert!((r - 1.0).abs() < 1e-3);
|
||||
assert_eq!(f16_to_f32(h), f16_to_f32_fast(h));
|
||||
}
|
||||
|
||||
fn half_float_one() -> u16 {
|
||||
f32_to_f16(1.0)
|
||||
}
|
||||
|
||||
fn f32_to_f16(v: f32) -> u16 {
|
||||
let bits = v.to_bits();
|
||||
let sign = ((bits >> 31) & 1) as u16;
|
||||
let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
|
||||
let mant = bits & 0x007f_ffff;
|
||||
if exp <= 0 {
|
||||
return sign << 15;
|
||||
}
|
||||
if exp >= 0x1f {
|
||||
return (sign << 15) | 0x7c00;
|
||||
}
|
||||
(sign << 15) | ((exp as u16) << 10) | ((mant >> 13) as u16)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn register_all_into_populates_registry() {
|
||||
let mut registry = ProviderRegistry::new();
|
||||
register_all_into(&mut registry);
|
||||
let mut ctx = NullContext::new(WorkerKind::SharedWorker);
|
||||
let job = GpuJob { provider_id: "craft.noop".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] };
|
||||
registry.dispatch(&mut ctx, &job).expect("noop via register_all_into");
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "craft-gpu-wgpu"
|
||||
description = "craft-gpu backend using wgpu (WebGPU on wasm32, native APIs on desktop)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-gpu = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wgpu = { workspace = true, features = ["webgpu"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
pollster = { workspace = true, optional = true }
|
||||
wgpu = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
adapter-probe = ["dep:pollster"]
|
||||
native-vulkan = ["wgpu/vulkan"]
|
||||
native-dx12 = ["wgpu/dx12"]
|
||||
native-metal = ["wgpu/metal"]
|
||||
native-gles = ["wgpu/gles"]
|
||||
|
||||
[dev-dependencies]
|
||||
pollster = { workspace = true }
|
||||
# Real-backend test (crates/gpu-wgpu/src/tests.rs): dispatches craft-gpu-providers' CPU-stand-in
|
||||
# providers against a real WgpuContext, not just craft-gpu-null, per RFC-0022 acceptance
|
||||
# requirement 2. Dev-only: no cycle (craft-gpu-providers never depends on craft-gpu-wgpu).
|
||||
craft-gpu-providers = { workspace = true }
|
||||
@@ -0,0 +1,563 @@
|
||||
//! wgpu-backed [`GpuContext`].
|
||||
//!
|
||||
//! WebGPU on `wasm32`; native APIs when backend features are enabled. With the `adapter-probe`
|
||||
//! feature (native only, pollster) and at least one `native-*` backend feature,
|
||||
//! [`WgpuContext::new`] requests a real device and builds [`DeviceCaps`] from what that device
|
||||
//! actually enabled (`Device::limits()` / `Device::features()`), never from the adapter's
|
||||
//! advertised maximum. Without a usable adapter (the features above are off, no GPU is present,
|
||||
//! or on `wasm32` where real device creation needs the async worker-init path noted in
|
||||
//! `docs/gpu-backends.md`), the context degrades to the same in-memory staging behavior as
|
||||
//! `craft_gpu_null::NullContext` (not a dependency of this crate; named here only for context);
|
||||
//! that is RFC-0022's defined no-adapter path, not an error.
|
||||
//!
|
||||
//! Readback is asynchronous end to end (`request_read` + `poll_reads`), because WebGPU can only
|
||||
//! map a buffer that way. Native, with a real device, drives it with `Buffer::map_async` plus
|
||||
//! `Device::poll`. The blocking `read_buffer` convenience (see
|
||||
//! [`GpuContext`]'s trait docs) blocks efficiently on native by polling
|
||||
//! the device while it waits. On `wasm32` the backing is always the in-memory staging store
|
||||
//! today, whose reads complete synchronously, and `read_buffer` serves them; only a read that
|
||||
//! did not complete synchronously returns a fault there, since blocking would freeze the one
|
||||
//! thread a real map's completion callback would need to run on.
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadRequest, WorkerKind};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps {
|
||||
DeviceCaps { backend_name: backend_name.into(), device_name: device_name.into(), ..DeviceCaps::default() }
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
fn probe_caps_native() -> DeviceCaps {
|
||||
let instance = native::instance();
|
||||
let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) {
|
||||
Ok(adapter) => adapter,
|
||||
Err(_) => return probe_fallback("wgpu", "no-adapter"),
|
||||
};
|
||||
let info = adapter.get_info();
|
||||
let limits = adapter.limits();
|
||||
DeviceCaps {
|
||||
backend_name: format!("{:?}", info.backend),
|
||||
device_name: info.name,
|
||||
max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size,
|
||||
max_buffer_size: limits.max_buffer_size,
|
||||
max_texture_dimension_2d: limits.max_texture_dimension_2d,
|
||||
features: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adapter-advertised limits, when an adapter is available; otherwise conservative defaults. This
|
||||
/// is the quick, device-free probe for UI surfaces that want a number before any context exists
|
||||
/// (Settings). It is advisory only: these are the adapter's maximums, not a device's granted
|
||||
/// ones. [`WgpuContext::caps`] is the authoritative, device-truth source once a context exists.
|
||||
pub fn probe_caps() -> DeviceCaps {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
{
|
||||
probe_caps_native()
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), not(feature = "adapter-probe")))]
|
||||
{
|
||||
probe_fallback("wgpu", "probe-not-run")
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
probe_fallback("webgpu", "browser")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
mod native {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use craft_gpu::{DeviceCaps, GpuFault};
|
||||
|
||||
use crate::{Backing, DeviceBacking};
|
||||
|
||||
/// Features this context asks a device for. No provider dispatches a real WGSL job on wgpu
|
||||
/// yet (`craft-gpu-providers` ships CPU stand-ins, by design, until that lands); extend this
|
||||
/// as real compute providers land, and it degrades gracefully regardless: see
|
||||
/// [`create_device`].
|
||||
const DESIRED_FEATURES: wgpu::Features = wgpu::Features::empty();
|
||||
|
||||
/// An instance over whichever native backends were compiled in (`native-vulkan`,
|
||||
/// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the
|
||||
/// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in a local container run or a CI lane.
|
||||
/// `new_without_display_handle` because this context never has a window (no surface is ever
|
||||
/// requested); FilmCraft's own off-screen export device uses the same constructor for the
|
||||
/// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`).
|
||||
pub(crate) fn instance() -> wgpu::Instance {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
if let Some(backends) = wgpu::Backends::from_env() {
|
||||
desc.backends = backends;
|
||||
}
|
||||
wgpu::Instance::new(desc)
|
||||
}
|
||||
|
||||
/// Request a real device. `None` on the defined no-adapter path (no usable adapter): the
|
||||
/// caller degrades to the staging backing, identical in shape to `craft-gpu-null`.
|
||||
///
|
||||
/// Never panics: `required_features` is intersected with what the adapter actually
|
||||
/// advertises, and `required_limits` is set to the adapter's own limits (never more), so
|
||||
/// `request_device`'s documented panics ("features/limits not supported by this adapter")
|
||||
/// cannot trigger here.
|
||||
pub(crate) fn create_device() -> Option<(DeviceCaps, Backing)> {
|
||||
let instance = instance();
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
|
||||
let features = DESIRED_FEATURES & adapter.features();
|
||||
let limits = adapter.limits();
|
||||
let desc =
|
||||
wgpu::DeviceDescriptor { label: Some("craft-gpu-wgpu"), required_features: features, required_limits: limits, ..Default::default() };
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?;
|
||||
|
||||
let lost = Arc::new(Mutex::new(None));
|
||||
{
|
||||
let lost = Arc::clone(&lost);
|
||||
device.set_device_lost_callback(move |reason, message| {
|
||||
if let Ok(mut slot) = lost.lock() {
|
||||
*slot = Some(GpuFault::DeviceLost(format!("{reason:?}: {message}")));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let info = device.adapter_info();
|
||||
let device_limits = device.limits();
|
||||
let caps = DeviceCaps {
|
||||
backend_name: format!("{:?}", info.backend),
|
||||
device_name: info.name,
|
||||
max_storage_buffer_binding_size: device_limits.max_storage_buffer_binding_size,
|
||||
max_buffer_size: device_limits.max_buffer_size,
|
||||
max_texture_dimension_2d: device_limits.max_texture_dimension_2d,
|
||||
features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(),
|
||||
};
|
||||
let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() });
|
||||
Some((caps, backing))
|
||||
}
|
||||
}
|
||||
|
||||
/// No real device: buffers live on the host, exactly like `craft-gpu-null`. RFC-0022's defined
|
||||
/// degrade path for "no adapter" (feature off, no GPU present, or the `wasm32` async-init gap).
|
||||
/// Each slot is `None` once freed (or never allocated): handles are stable indices, so a freed
|
||||
/// slot cannot simply be removed without shifting every later handle's index.
|
||||
#[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))]
|
||||
enum Backing {
|
||||
Staging(Vec<Option<Vec<u8>>>),
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
enum Backing {
|
||||
Staging(Vec<Option<Vec<u8>>>),
|
||||
/// A real device. `DeviceCaps` was built from it, not from the adapter it came from.
|
||||
Device(DeviceBacking),
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
struct DeviceBacking {
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
/// Each buffer paired with its true, caller-given byte length. wgpu requires every buffer
|
||||
/// with copy usage to be sized in multiples of [`COPY_ALIGN`]; the buffer itself is padded to
|
||||
/// that, but callers (`buffer_len`, `request_read`'s returned bytes) see the true length,
|
||||
/// matching the staging path and `craft-gpu-null` exactly, with no padding visible. `None`
|
||||
/// once freed: see the `Backing::Staging` doc for why the slot stays rather than shifting.
|
||||
buffers: Vec<Option<(wgpu::Buffer, u64)>>,
|
||||
/// Set by the device-lost callback registered in [`native::create_device`]; checked before
|
||||
/// every call that would otherwise touch the (now invalid) device.
|
||||
lost: std::sync::Arc<std::sync::Mutex<Option<GpuFault>>>,
|
||||
pending: Vec<PendingRead>,
|
||||
}
|
||||
|
||||
/// wgpu's `COPY_BUFFER_ALIGNMENT`: every buffer with copy usage, and every `write_buffer` /
|
||||
/// `copy_buffer_to_buffer` size, must be a multiple of this (4 bytes). Uploading or reading back
|
||||
/// a buffer length that doesn't land on this boundary (`b"xy"`, two bytes) is a validation error
|
||||
/// on native wgpu, surfaced as a panic from inside `wgpu-core`'s own uncaptured-error path unless
|
||||
/// padded first; `craft-gpu-null`'s plain `Vec<u8>` has no such constraint, so this padding is
|
||||
/// purely an artifact of the real backend, kept invisible to every caller of this crate.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
const COPY_ALIGN: u64 = 4;
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
struct PendingRead {
|
||||
request: ReadRequest,
|
||||
handle: HandleId,
|
||||
staging: wgpu::Buffer,
|
||||
/// True length to truncate the mapped (padded) bytes back down to.
|
||||
true_len: u64,
|
||||
state: std::sync::Arc<std::sync::Mutex<Option<Result<(), String>>>>,
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
fn resolve_pending(pending: PendingRead) -> ReadOutcome {
|
||||
let PendingRead { request, handle, staging, true_len, state } = pending;
|
||||
let result = match state.lock() {
|
||||
Ok(mut guard) => match guard.take() {
|
||||
Some(Ok(())) => match staging.get_mapped_range(0..true_len.next_multiple_of(COPY_ALIGN)) {
|
||||
Ok(view) => {
|
||||
let mut bytes = view.to_vec();
|
||||
drop(view);
|
||||
staging.unmap();
|
||||
bytes.truncate(usize::try_from(true_len).unwrap_or(usize::MAX));
|
||||
Ok(bytes)
|
||||
}
|
||||
Err(err) => Err(GpuFault::Operation(err.to_string())),
|
||||
},
|
||||
Some(Err(message)) => Err(GpuFault::Operation(message)),
|
||||
None => Err(GpuFault::Operation("read_buffer: map_async callback has not run yet".into())),
|
||||
},
|
||||
Err(_) => Err(GpuFault::Operation("read_buffer: map state lock poisoned".into())),
|
||||
};
|
||||
ReadOutcome { request, handle, result }
|
||||
}
|
||||
|
||||
/// wgpu-backed context. See the module docs for the real-device-vs-staging split.
|
||||
pub struct WgpuContext {
|
||||
caps: DeviceCaps,
|
||||
worker_kind: WorkerKind,
|
||||
backing: Backing,
|
||||
next_request: u64,
|
||||
ready: Vec<ReadOutcome>,
|
||||
}
|
||||
|
||||
impl WgpuContext {
|
||||
pub fn new(worker_kind: WorkerKind) -> Self {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
{
|
||||
if let Some((caps, backing)) = native::create_device() {
|
||||
return Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() };
|
||||
}
|
||||
// request_adapter and/or request_device failed: fall back to the conservative
|
||||
// fallback, never probe_caps(). probe_caps() would re-query the adapter here, and a
|
||||
// second, successful adapter query would report the adapter's advertised limits as
|
||||
// if they came from a granted device -- the exact thing probe_caps's own doc comment
|
||||
// says caps() must never do for a context with no device.
|
||||
Self { caps: probe_fallback("wgpu", "no-device"), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
#[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))]
|
||||
Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
|
||||
/// Force the staging (no-device) path with caller-supplied caps. For tests, and for callers
|
||||
/// that intentionally want the portable path (FilmCraft's `?webgl` / `?nogpuworkers`, per
|
||||
/// `docs/pilot-filmcraft.md`) rather than a real device's own caps.
|
||||
pub fn with_caps(worker_kind: WorkerKind, caps: DeviceCaps) -> Self {
|
||||
Self { caps, worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
|
||||
/// True when this context holds a real device (`request_device` succeeded), false on the
|
||||
/// staging/no-adapter path. Settings UI can use this to show "no GPU" honestly instead of
|
||||
/// implying a device that was never created; tests use it to skip rather than fail when the
|
||||
/// host genuinely has no usable adapter (see `crates/gpu-wgpu/src/tests.rs`).
|
||||
pub fn has_device(&self) -> bool {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
{
|
||||
matches!(self.backing, Backing::Device(_))
|
||||
}
|
||||
|
||||
#[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// True once the device has reported loss. Every [`DeviceCaps`] read before this point is
|
||||
/// stale; see [`GpuContext`]'s trait docs for the recovery this context expects.
|
||||
pub fn is_device_lost(&self) -> bool {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
return d.lost.lock().map(|g| g.is_some()).unwrap_or(false);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn take_lost_fault(&self) -> Option<GpuFault> {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
return d.lost.lock().ok().and_then(|g| g.clone());
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuContext for WgpuContext {
|
||||
fn caps(&self) -> DeviceCaps {
|
||||
self.caps.clone()
|
||||
}
|
||||
|
||||
fn worker_kind(&self) -> WorkerKind {
|
||||
self.worker_kind
|
||||
}
|
||||
|
||||
#[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_variables))]
|
||||
fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result<HandleId, GpuFault> {
|
||||
if let Some(fault) = self.take_lost_fault() {
|
||||
return Err(fault);
|
||||
}
|
||||
match &mut self.backing {
|
||||
Backing::Staging(buffers) => {
|
||||
let id = u32::try_from(buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?;
|
||||
buffers.push(Some(bytes.to_vec()));
|
||||
Ok(HandleId(id))
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
Backing::Device(d) => {
|
||||
let true_len = bytes.len() as u64;
|
||||
let padded_len = true_len.next_multiple_of(COPY_ALIGN);
|
||||
if padded_len > self.caps.max_buffer_size {
|
||||
return Err(GpuFault::InvalidJob(format!(
|
||||
"upload_buffer: {true_len} bytes (padded to {padded_len}) exceeds the device's max_buffer_size {}",
|
||||
self.caps.max_buffer_size
|
||||
)));
|
||||
}
|
||||
// The size check above only catches a request past the device's advertised
|
||||
// maximum; it proves nothing about whether the device can actually allocate
|
||||
// padded_len bytes right now (free VRAM varies). wgpu 30.0.1 sends an allocation
|
||||
// failure to the default uncaptured-error handler, which panics, unless a scope
|
||||
// captures it first. Pop this scope immediately, before write_buffer below ever
|
||||
// touches `buffer`: a buffer that failed to create is invalid, and writing to an
|
||||
// invalid buffer raises its own VALIDATION error, a kind this OutOfMemory-only
|
||||
// scope does not catch, so it must reach the default handler and panic regardless
|
||||
// of when this scope is popped. Checking right here is what keeps that from
|
||||
// happening at all.
|
||||
let create_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let buffer = d.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(label),
|
||||
size: padded_len,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
if let Some(err) = pollster::block_on(create_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error creating the buffer: {err}")));
|
||||
}
|
||||
// write_buffer makes its own staging allocation to carry `bytes` to the device, a
|
||||
// second allocation that can also run out of memory; it gets its own scope rather
|
||||
// than reusing the one already closed above.
|
||||
let write_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
if padded_len == true_len {
|
||||
d.queue.write_buffer(&buffer, 0, bytes);
|
||||
} else {
|
||||
let mut padded = bytes.to_vec();
|
||||
padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0);
|
||||
d.queue.write_buffer(&buffer, 0, &padded);
|
||||
}
|
||||
// write_buffer only records the copy into wgpu's PendingWrites; wgpu-core flushes
|
||||
// that queue at the sooner of the caller's next real command-buffer submission or
|
||||
// the next map_async on an affected buffer, and keeps the buffer named by the
|
||||
// write alive internally until then. Without a submission here, a free_buffer
|
||||
// right after this call could never actually release the GPU allocation behind
|
||||
// it, since nothing would ever flush PendingWrites to let it go. An empty submit
|
||||
// is still a submission as far as that flush is concerned, so it is enough.
|
||||
d.queue.submit(std::iter::empty());
|
||||
if let Some(err) = pollster::block_on(write_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error writing the buffer: {err}")));
|
||||
}
|
||||
let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?;
|
||||
d.buffers.push(Some((buffer, true_len)));
|
||||
Ok(HandleId(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_len(&self, handle: HandleId) -> Result<usize, GpuFault> {
|
||||
if let Some(fault) = self.take_lost_fault() {
|
||||
return Err(fault);
|
||||
}
|
||||
match &self.backing {
|
||||
Backing::Staging(buffers) => {
|
||||
buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
Backing::Device(d) => {
|
||||
d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())).and_then(
|
||||
|(_, true_len)| usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request_read(&mut self, handle: HandleId) -> Result<ReadRequest, GpuFault> {
|
||||
if let Some(fault) = self.take_lost_fault() {
|
||||
return Err(fault);
|
||||
}
|
||||
match &mut self.backing {
|
||||
Backing::Staging(buffers) => {
|
||||
let bytes =
|
||||
buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?;
|
||||
let id = self.next_request;
|
||||
self.next_request = self.next_request.wrapping_add(1);
|
||||
let request = ReadRequest(id);
|
||||
self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) });
|
||||
Ok(request)
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
Backing::Device(d) => {
|
||||
let (buffer, true_len) =
|
||||
d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?;
|
||||
let true_len = *true_len;
|
||||
if true_len == 0 {
|
||||
// An empty buffer has nothing to copy or map (wgpu refuses an empty map
|
||||
// range); resolve it immediately, same as the staging path.
|
||||
let id = self.next_request;
|
||||
self.next_request = self.next_request.wrapping_add(1);
|
||||
let request = ReadRequest(id);
|
||||
self.ready.push(ReadOutcome { request, handle, result: Ok(Vec::new()) });
|
||||
return Ok(request);
|
||||
}
|
||||
let copy_len = true_len.next_multiple_of(COPY_ALIGN);
|
||||
if copy_len > self.caps.max_buffer_size {
|
||||
return Err(GpuFault::Operation(format!(
|
||||
"request_read: staging copy of {copy_len} bytes exceeds the device's max_buffer_size {}",
|
||||
self.caps.max_buffer_size
|
||||
)));
|
||||
}
|
||||
// Same reasoning as upload_buffer's error scope: an allocation failure for the
|
||||
// read-staging buffer must become a GpuFault, not reach the default
|
||||
// uncaptured-error handler and panic. Pop immediately, before copy_buffer_to_buffer
|
||||
// below ever names `staging` as a copy destination: a staging buffer that failed
|
||||
// to create is invalid, and copying into an invalid buffer raises its own
|
||||
// VALIDATION error, a kind this OutOfMemory-only scope does not catch, so it must
|
||||
// reach the default handler and panic regardless of when this scope is popped.
|
||||
let create_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let staging = d.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("craft-gpu-wgpu.read-staging"),
|
||||
size: copy_len,
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
if let Some(err) = pollster::block_on(create_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("request_read: device reported an allocation error creating the staging buffer: {err}")));
|
||||
}
|
||||
// The copy and its submission get their own scope rather than reusing the one
|
||||
// already closed above, same split as upload_buffer's create vs. write.
|
||||
let copy_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") });
|
||||
encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len);
|
||||
d.queue.submit(Some(encoder.finish()));
|
||||
if let Some(err) = pollster::block_on(copy_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("request_read: device reported an allocation error copying the buffer: {err}")));
|
||||
}
|
||||
let state = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
{
|
||||
let state = std::sync::Arc::clone(&state);
|
||||
staging.map_async(wgpu::MapMode::Read, 0..copy_len, move |result| {
|
||||
if let Ok(mut slot) = state.lock() {
|
||||
*slot = Some(result.map_err(|e| e.to_string()));
|
||||
}
|
||||
});
|
||||
}
|
||||
let id = self.next_request;
|
||||
self.next_request = self.next_request.wrapping_add(1);
|
||||
let request = ReadRequest(id);
|
||||
d.pending.push(PendingRead { request, handle, staging, true_len, state });
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the slot with `None` rather than removing it: handles are stable indices, and
|
||||
/// removing would shift every later handle's index out from under its caller. Dropping a
|
||||
/// `Some((wgpu::Buffer, _))` here releases that buffer's GPU-side allocation.
|
||||
fn free_buffer(&mut self, handle: HandleId) {
|
||||
match &mut self.backing {
|
||||
Backing::Staging(buffers) => {
|
||||
if let Some(slot) = buffers.get_mut(handle.0 as usize) {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
Backing::Device(d) => {
|
||||
if let Some(slot) = d.buffers.get_mut(handle.0 as usize) {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Covers the gap `poll_reads` has when nothing is pending: that method can only attach a
|
||||
/// device-lost fault to a read it has something to attach it to, so a caller whose event
|
||||
/// loop only polls, with no outstanding read, could never observe loss through it alone.
|
||||
fn device_status(&self) -> Result<(), GpuFault> {
|
||||
if let Some(fault) = self.take_lost_fault() {
|
||||
return Err(fault);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_mut))]
|
||||
fn poll_reads(&mut self) -> Vec<ReadOutcome> {
|
||||
let mut outcomes = std::mem::take(&mut self.ready);
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &mut self.backing {
|
||||
if let Some(fault) = d.lost.lock().ok().and_then(|g| g.clone()) {
|
||||
outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) }));
|
||||
return outcomes;
|
||||
}
|
||||
let _ = d.device.poll(wgpu::PollType::Poll);
|
||||
let mut remaining = Vec::with_capacity(d.pending.len());
|
||||
for pending in d.pending.drain(..) {
|
||||
let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false);
|
||||
if is_ready {
|
||||
outcomes.push(resolve_pending(pending));
|
||||
} else {
|
||||
remaining.push(pending);
|
||||
}
|
||||
}
|
||||
d.pending = remaining;
|
||||
}
|
||||
outcomes
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_buffer(&mut self, handle: HandleId) -> Result<Vec<u8>, GpuFault> {
|
||||
let request = self.request_read(handle)?;
|
||||
loop {
|
||||
let mut matched = None;
|
||||
let mut others = Vec::new();
|
||||
for outcome in self.poll_reads() {
|
||||
if outcome.request == request {
|
||||
matched = Some(outcome.result);
|
||||
} else {
|
||||
others.push(outcome);
|
||||
}
|
||||
}
|
||||
// Completions belonging to other outstanding requests go back on the queue for the
|
||||
// caller's next poll_reads instead of being dropped.
|
||||
self.ready.extend(others);
|
||||
if let Some(result) = matched {
|
||||
return result;
|
||||
}
|
||||
// Block on the GPU between polls instead of busy-spinning the CPU. A no-op when
|
||||
// `backing` is `Staging` (nothing to wait for; the request already resolved above)
|
||||
// or when wgpu is itself WebGPU under the hood, which self-polls.
|
||||
#[cfg(feature = "adapter-probe")]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
let _ = d.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On `wasm32` the backing is always the in-memory staging store today (real device
|
||||
/// creation needs the async worker-init path and does not exist on this target yet), and a
|
||||
/// staging read resolves synchronously, so serving it blocks nothing. The refusal below
|
||||
/// guards the future wasm device backing: WebGPU can only map a buffer asynchronously, and
|
||||
/// `wasm32` is single-threaded, so blocking on a real device would stop the only thread the
|
||||
/// browser needs to run `map_async`'s own completion callback on, hanging the tab. Callers
|
||||
/// on a device backing drive [`request_read`](GpuContext::request_read) and
|
||||
/// [`poll_reads`](GpuContext::poll_reads) from the worker's message loop instead; see
|
||||
/// `docs/gpu-backends.md`.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn read_buffer(&mut self, handle: HandleId) -> Result<Vec<u8>, GpuFault> {
|
||||
let request = self.request_read(handle)?;
|
||||
match self.ready.iter().position(|o| o.request == request) {
|
||||
Some(i) => self.ready.remove(i).result,
|
||||
None => Err(GpuFault::Operation(
|
||||
"read_buffer on wasm32: the read did not resolve synchronously. Use request_read + poll_reads from the worker's message loop \
|
||||
instead."
|
||||
.into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user