diff --git a/.github/workflows/ci-macos.yml b/.github/workflows/ci-macos.yml new file mode 100644 index 000000000..3ef98173a --- /dev/null +++ b/.github/workflows/ci-macos.yml @@ -0,0 +1,28 @@ +name: CI (macOS) + +# The macOS leg of the gate: `cargo xtask ci` on Apple silicon, through the suite's shared gate +# workflow. The Linux gate (ci.yml) has no real GPU and runs on x86, so GPU tests on Metal and +# results that depend on the platform's math library first ran on a contributor's Mac. +# +# On pushes to main, not on every pull request: macOS runners are scarce. A newer push cancels the +# older run, so main is checked at its latest commit. Pull requests that change this file run it. +on: + push: + branches: [main] + pull_request: + paths: [.github/workflows/ci-macos.yml] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-macos-${{ github.ref }} + cancel-in-progress: true + +jobs: + gate: + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["macos-15"]' + timeout-minutes: 120 diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 000000000..de64ad3ee --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index b903f82ea..ccf74f43a 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -28,6 +28,10 @@ jobs: name: Windows installation policy (no app build) runs-on: windows-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 603b21c18..354fbd268 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,14 @@ concurrency: cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main release: + needs: credits permissions: contents: write packages: write @@ -25,6 +32,7 @@ jobs: app-name: effectcraft app-title: EffectCraft version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} @@ -40,3 +48,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} diff --git a/.gitignore b/.gitignore index 4a79323c8..ff6ad2397 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,7 @@ target/ /log .DS_Store .claude/worktrees/ +__pycache__/ + +# After Effects test corpus fetched by `cargo xtask aep-corpus` +/corpus/ diff --git a/AGENTS.md b/AGENTS.md index 97c35c2b9..ba48c1a97 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # EffectCraft — rules for agents and contributors These rules apply to every human and AI contributor. `CLAUDE.md` holds the working instructions; this @@ -102,10 +155,20 @@ reproduce an image (for example, point lists traced from someone else's icon). ## 3. Engineering rules -See `CLAUDE.md`: pure Rust, dependency layering (`cargo xtask layers`), exact `Tick` time, everything is -a command, everything is agent-drivable, and the quality gates (`cargo xtask ci`) before every commit. +- **Layering** (`cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd/cpal; L0–L4 build for wasm32. +- **Exact time:** `effectcraft_time::Tick` (254 016 000 000/s). Keyframe times are layer time. +- **Property tree:** everything animatable is a `Property` in the layer's `PropGroup` tree, addressed by paths (`transform/position`, `effects/#1/blurriness`, `@uid`). +- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP dispatch by id. +- **Everything is agent-drivable:** every interactive widget registers an automation id; UI state is serde. +- **Community links** (Help menu, About, header Discord button): https://discord.gg/artcraft, https://getartcraft.com, https://getartcraft.com/apps/effectcraft, https://github.com/storytold/effectcraft. +- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm). +- New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. +- **Commits:** one task id per commit (`M6.3: trim paths`). Only green states. +- `cargo run -p effectcraft -- --control 9877` opens the desktop app with the JSON-lines control server (`docs/control-protocol.md`). For UI work, look at the result, including the headless `snapshot` example. +- `plan/` is an optional gitignored notebook (`plan/aftereffects/` may hold reference notes and captures). Do not ask for it, do not stop when it is absent, and never commit those captures. +- Read [`docs/gaps.md`](docs/gaps.md) and [`docs/target-app-parity.md`](docs/target-app-parity.md) before choosing work. Fidelity, reliability and stability (G1–G3) come before new features. +- Some workflow files still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c97d32ed9..b463e79ea 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -64,6 +64,8 @@ and licence texts are in [`NOTICE`](NOTICE). | `crates/model/tests/fixtures/cube.obj` | EffectCraft contributors | Original work: Wavefront OBJ test fixture (unit cube, two materials) | MIT OR Apache-2.0 | | `crates/model/tests/fixtures/cube.mtl` | EffectCraft contributors | Original work: MTL test fixture (materials of cube.obj) | MIT OR Apache-2.0 | +Two small After Effects test projects of `crates/aep` are in this repository: `crates/aep/tests/fixtures/synthetic.aep` (original work, made with After Effects 2026 from own data, working space None, the embedded colour profile removed; MIT OR Apache-2.0, with its `.attribution` sidecar) and `crates/aep/tests/fixtures/ai-mask-3099.aep` (original work, made with After Effects 2026 from four hand-written one-page PDFs named `.ai`, footage paths and host name neutralised, the embedded colour profiles replaced by stubs made with `crates/aep/examples/stubicc.rs`; MIT OR Apache-2.0, with its `.attribution` sidecar). The other After Effects test projects of `crates/aep` are not in this repository. They are original work of an EffectCraft contributor, generated with After Effects 2026 as own test data (MIT OR Apache-2.0, each file with its `.attribution` sidecar); they are in [storytold/effectcraft-corpus](https://github.com/storytold/effectcraft-corpus) with their sidecars, fetched by `cargo xtask aep-corpus` (commit-pinned, SHA-256-verified), and the tests read them only from the folder named by `EFFECTCRAFT_AEP_FIXTURES` (opt-in). Their embedded colour profiles are replaced by stubs made with `crates/aep/examples/stubicc.rs` (a header and a description, no colour data), so no vendor profile data is in them. + ## Screenshots Screenshots of EffectCraft itself, rendered headlessly, showing only procedurally generated demo content. @@ -97,7 +99,7 @@ Screenshots of EffectCraft itself, rendered headlessly, showing only procedurall (sidecars `.attribution`). - Bundled extension (ScriptUI panel) with its twelve built-in ease presets: `extensions/scriptui-panels/Ease Presets.jsx` (sidecar `.attribution`). -- Example effect plug-in: `examples/plugins/posterize-bands` (plug-in API v1, WebAssembly). +- Example effect plug-in: `examples/plugins/posterize-bands` (WebAssembly ABI 1). ## Trained models (optional downloads, not bundled) @@ -127,6 +129,12 @@ configuration from these Apache-2.0 projects: - `crates/segment/src/mobilesam.rs` follows the MobileSAM, TinyViT and Segment Anything architectures and their Apache-2.0 reference code. +## Frozen matte regression fixture + +| Asset | Author | Source | Licence | +|---|---|---|---| +| `crates/engine/src/tests/fixtures/object-matte-0.22.ecproj` | lisn0 | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | + ## First-party brand marks The ArtCraft name, wordmark and logos are trademarks of the ArtCraft Team. They are not open source and are not diff --git a/CLAUDE.md b/CLAUDE.md index 640b9800e..43c994c2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,37 +1 @@ -# EffectCraft — instructions for agents - -EffectCraft is a clean-room, open-source, pure-Rust motion graphics and visual effects compositor targeting Adobe After Effects parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom) and `../designcraft` (InDesign), with the same conventions. - -## Start every session here -`plan/` is maintainer-local (gitignored). Public equivalents: [`ROADMAP.md`](ROADMAP.md), [`docs/`](docs/). -1. Read `plan/STATUS.md` (current milestone, next task, running agents, blockers). -2. Read the task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the crate README/docs you touch. Feature ids: `plan/aftereffects/feature-catalog.md`; effects: `plan/aftereffects/effects-list.md`; UI reference: `plan/aftereffects/README.md`. -3. Read [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked, and the prioritised workstreams; the numbers are in [`docs/target-app-parity.md`](docs/target-app-parity.md). Fidelity, reliability and stability (G1–G3) come before new features. -4. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask. - -## Non-negotiables -**Read [`AGENTS.md`](AGENTS.md) first; its rules override everything here.** No Adobe assets, every asset licensed + attributed (`cargo xtask assets`). -- **Never crash** (AGENTS.md "Never crash"; outranks feature work: a crash loses people's work). Non-test code has no `unwrap()`/`expect()`/`panic!`/`unreachable!`/`todo!`/`unimplemented!` and no `unsafe`: return `Result` and use `?`, `ok_or`, `let … else`. Input-derived indices, slices and arithmetic use `get()` and checked/saturating math; recursion is depth-limited; locks handle poisoning. The app's last-resort guard turns an escaped panic into an error and keeps the document. Every crash fix gets a regression test. -- **Clean-room.** Behaviour and public docs only. No GPL/LGPL/AGPL code. ffmpeg only as an external test oracle. -- **Pure Rust.** Media codecs come from FilmCraft crates (git deps behind `crates/media`, see `plan/adr/0001`). -- **Layering** (`cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd/cpal; L0–L4 build for wasm32. -- **Exact time:** `effectcraft_time::Tick` (254 016 000 000/s). Keyframe times are **layer time**. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). -- **Property tree:** everything animatable is a `Property` in the layer's `PropGroup` tree, addressed by paths (`transform/position`, `effects/#1/blurriness`, `@uid`). -- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP dispatch by id. -- **Everything is agent-drivable:** every interactive widget registers an automation id; UI state is serde. -- **Community links** (Help menu, About, header Discord button): https://discord.gg/artcraft, https://getartcraft.com, https://getartcraft.com/apps/effectcraft, https://github.com/storytold/effectcraft. -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm). -- **New workspace crates** must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare the required crate-level lint attributes before modules or other crate items; crate-level `//!` documentation may precede them. -- **Commits:** one task id per commit (`M6.3: trim paths`). Only green states. - -## Running and looking at the app -- `cargo run -p effectcraft -- --control 9877` opens the desktop app with the JSON-lines control server (`docs/control-protocol.md`). -- For UI work, **look at the result**. Headless (no window, works while the user is busy on the machine): `cargo run -p effectcraft-ui-egui --example snapshot -- --out ui.png --step '{"method":"engine.execute","params":{"command":"layer.select","params":{"layers":["#2"]}}}'` (steps are control-channel requests; `--script steps.jsonl`; `{"method":"snap","params":{"path":…}}` for intermediate shots). Or drive the live app via the control channel and take `ui.screenshot` (needs the window visible on screen). -- After Effects reference: drive AE via ExtendScript (`osascript -e 'tell application "Adobe After Effects 2026" to DoScriptFile "x.jsx"'`) and capture only AE's window (`screencapture -l `); keep captures in `plan/aftereffects/ref/` (gitignored), never commit them, never capture the Home screen. -- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-`; keep every `Cargo.toml` valid (the `crates/*` glob). - -## CI workflows -- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. -- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. -- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 29521ad73..8ce4b85aa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,7 +26,7 @@ that variable set. ```sh cargo run -p effectcraft -- --demo # the desktop app, with the demo project cargo test --workspace -cargo xtask ci # what every commit must pass +cargo xtask ci # what every commit must pass (dev-profile checks and tests) ``` The default `dev` profile keeps debug info to line tables: builds are fast and panics/backtraces diff --git a/Cargo.lock b/Cargo.lock index c43ba9d9c..fb12590be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1092,7 +1092,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" [[package]] name = "craft-ecproj-format" @@ -1107,12 +1107,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1132,10 +1132,18 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4#f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" dependencies = [ "hayro-syntax", "thiserror 2.0.21", @@ -1144,7 +1152,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" dependencies = [ "dispatch2", "egui", @@ -1155,7 +1163,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1176,7 +1184,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "chrono", "dunce", @@ -1186,6 +1194,7 @@ dependencies = [ "image", "log", "plist", + "rustix 1.1.5", "semver", "serde", "serde_json", @@ -1412,8 +1421,9 @@ dependencies = [ [[package]] name = "effectcraft" -version = "0.21.0" +version = "0.24.1" dependencies = [ + "chrono", "cpal", "craft-update", "effectcraft-engine", @@ -1431,14 +1441,29 @@ dependencies = [ "rfd", "serde", "serde_json", + "sysinfo", "winit", "winresource", "zbus", ] +[[package]] +name = "effectcraft-aep" +version = "0.24.1" +dependencies = [ + "effectcraft-color", + "effectcraft-effects", + "effectcraft-keyframe", + "effectcraft-project", + "effectcraft-time", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "effectcraft-automation" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-engine", "effectcraft-host", @@ -1446,19 +1471,21 @@ dependencies = [ "effectcraft-script", "image", "serde_json", + "tempfile", "thiserror 2.0.21", ] [[package]] name = "effectcraft-av1enc" -version = "0.21.0" +version = "0.24.1" dependencies = [ "filmcraft-av1", + "tempfile", ] [[package]] name = "effectcraft-cli" -version = "0.21.0" +version = "0.24.1" dependencies = [ "cpu-time", "effectcraft-automation", @@ -1477,7 +1504,7 @@ dependencies = [ [[package]] name = "effectcraft-color" -version = "0.21.0" +version = "0.24.1" dependencies = [ "proptest", "serde", @@ -1485,7 +1512,7 @@ dependencies = [ [[package]] name = "effectcraft-effects" -version = "0.21.0" +version = "0.24.1" dependencies = [ "chrono", "effectcraft-color", @@ -1503,10 +1530,11 @@ dependencies = [ [[package]] name = "effectcraft-engine" -version = "0.21.0" +version = "0.24.1" dependencies = [ "chrono", "craft-docpath", + "effectcraft-aep", "effectcraft-color", "effectcraft-effects", "effectcraft-geom", @@ -1541,7 +1569,7 @@ dependencies = [ [[package]] name = "effectcraft-export" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-av1enc", "effectcraft-color", @@ -1555,6 +1583,7 @@ dependencies = [ "effectcraft-render", "effectcraft-time", "effectcraft-vp9enc", + "exr", "filmcraft-aac", "filmcraft-h264enc", "filmcraft-isobmff", @@ -1565,13 +1594,14 @@ dependencies = [ "image", "log", "rayon", + "tempfile", "thiserror 2.0.21", "web-time", ] [[package]] name = "effectcraft-expr" -version = "0.21.0" +version = "0.24.1" dependencies = [ "boa_engine", "effectcraft-color", @@ -1588,7 +1618,7 @@ dependencies = [ [[package]] name = "effectcraft-geom" -version = "0.21.0" +version = "0.24.1" dependencies = [ "proptest", "serde", @@ -1596,7 +1626,7 @@ dependencies = [ [[package]] name = "effectcraft-gpu" -version = "0.21.0" +version = "0.24.1" dependencies = [ "bytemuck", "effectcraft-color", @@ -1611,25 +1641,38 @@ dependencies = [ "js-sys", "log", "pollster 1.0.1", + "rayon", "wasm-bindgen", "web-time", "wgpu", ] +[[package]] +name = "effectcraft-helper-host" +version = "0.24.1" +dependencies = [ + "bytemuck", + "effectcraft-effects", + "log", + "serde", + "serde_json", +] + [[package]] name = "effectcraft-hevcenc" -version = "0.21.0" +version = "0.24.1" dependencies = [ "filmcraft-hevc", ] [[package]] name = "effectcraft-host" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-engine", "effectcraft-export", "effectcraft-expr", + "effectcraft-helper-host", "effectcraft-interchange", "effectcraft-media", "effectcraft-pdf", @@ -1646,11 +1689,12 @@ dependencies = [ "log", "rayon", "serde_json", + "tempfile", ] [[package]] name = "effectcraft-interchange" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-color", "effectcraft-keyframe", @@ -1669,7 +1713,7 @@ dependencies = [ [[package]] name = "effectcraft-keyframe" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-color", "effectcraft-geom", @@ -1681,7 +1725,7 @@ dependencies = [ [[package]] name = "effectcraft-lottie" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-docpath", "effectcraft-color", @@ -1699,10 +1743,11 @@ dependencies = [ [[package]] name = "effectcraft-media" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-docpath", "effectcraft-color", + "effectcraft-effects", "effectcraft-model", "effectcraft-pdf", "effectcraft-project", @@ -1726,12 +1771,13 @@ dependencies = [ "log", "rayon", "serde_json", + "tempfile", "thiserror 2.0.21", ] [[package]] name = "effectcraft-model" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-geom", "image", @@ -1744,14 +1790,14 @@ dependencies = [ [[package]] name = "effectcraft-opusenc" -version = "0.21.0" +version = "0.24.1" dependencies = [ "filmcraft-opus", ] [[package]] name = "effectcraft-path" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-geom", "effectcraft-keyframe", @@ -1763,7 +1809,7 @@ dependencies = [ [[package]] name = "effectcraft-pdf" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-pdf", "effectcraft-raster", @@ -1779,7 +1825,7 @@ dependencies = [ [[package]] name = "effectcraft-plugin" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-effects", "effectcraft-keyframe", @@ -1791,7 +1837,7 @@ dependencies = [ [[package]] name = "effectcraft-project" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-ecproj-format", "effectcraft-color", @@ -1805,23 +1851,24 @@ dependencies = [ [[package]] name = "effectcraft-psd" -version = "0.21.0" +version = "0.24.1" dependencies = [ "miniz_oxide 0.9.1", ] [[package]] name = "effectcraft-raster" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-color", "effectcraft-geom", "rayon", + "tempfile", ] [[package]] name = "effectcraft-render" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-color", "effectcraft-effects", @@ -1838,12 +1885,13 @@ dependencies = [ "lz4_flex", "rayon", "serde", + "tempfile", "web-time", ] [[package]] name = "effectcraft-sam2" -version = "0.21.0" +version = "0.24.1" dependencies = [ "bytemuck", "candle-core", @@ -1858,7 +1906,7 @@ dependencies = [ [[package]] name = "effectcraft-script" -version = "0.21.0" +version = "0.24.1" dependencies = [ "boa_engine", "effectcraft-engine", @@ -1876,7 +1924,7 @@ dependencies = [ [[package]] name = "effectcraft-segment" -version = "0.21.0" +version = "0.24.1" dependencies = [ "miniz_oxide 0.9.1", "ndarray", @@ -1885,19 +1933,20 @@ dependencies = [ [[package]] name = "effectcraft-svg" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-geom", "effectcraft-path", "effectcraft-raster", "kurbo", + "log", "rayon", "roxmltree", ] [[package]] name = "effectcraft-text" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-keyframe", "harfrust", @@ -1909,7 +1958,7 @@ dependencies = [ [[package]] name = "effectcraft-time" -version = "0.21.0" +version = "0.24.1" dependencies = [ "proptest", "serde", @@ -1917,7 +1966,7 @@ dependencies = [ [[package]] name = "effectcraft-track" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-raster", "effectcraft-segment", @@ -1929,8 +1978,9 @@ dependencies = [ [[package]] name = "effectcraft-ui-egui" -version = "0.21.0" +version = "0.24.1" dependencies = [ + "bytemuck", "chrono", "craft-quit", "craft-ui", @@ -1941,6 +1991,7 @@ dependencies = [ "effectcraft-gpu", "effectcraft-host", "effectcraft-keyframe", + "effectcraft-media", "effectcraft-path", "effectcraft-project", "effectcraft-render", @@ -1949,8 +2000,10 @@ dependencies = [ "effectcraft-time", "eframe", "egui", + "egui_extras", "egui_kittest", "exr", + "half", "image", "kurbo", "log", @@ -1959,17 +2012,18 @@ dependencies = [ "serde", "serde_json", "sys-locale", + "tempfile", "toml", "web-time", ] [[package]] name = "effectcraft-vp9enc" -version = "0.21.0" +version = "0.24.1" [[package]] name = "effectcraft-web" -version = "0.21.0" +version = "0.24.1" dependencies = [ "effectcraft-engine", "effectcraft-export", @@ -2089,6 +2143,19 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools", + "log", + "profiling", +] + [[package]] name = "egui_glow" version = "0.37.0" @@ -2165,6 +2232,26 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -2356,8 +2443,8 @@ dependencies = [ [[package]] name = "filmcraft-aac" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "thiserror 2.0.21", @@ -2365,16 +2452,16 @@ dependencies = [ [[package]] name = "filmcraft-ac3" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "thiserror 2.0.21", ] [[package]] name = "filmcraft-apv" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2383,8 +2470,8 @@ dependencies = [ [[package]] name = "filmcraft-av1" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2393,23 +2480,26 @@ dependencies = [ [[package]] name = "filmcraft-avi" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" [[package]] name = "filmcraft-bitstream" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +dependencies = [ + "craft-media", +] [[package]] name = "filmcraft-cfb" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" [[package]] name = "filmcraft-codecs" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-aac", "filmcraft-ac3", @@ -2445,16 +2535,16 @@ dependencies = [ [[package]] name = "filmcraft-color" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "serde", ] [[package]] name = "filmcraft-dng" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2462,8 +2552,8 @@ dependencies = [ [[package]] name = "filmcraft-dnx" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2472,8 +2562,8 @@ dependencies = [ [[package]] name = "filmcraft-frame" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-color", "filmcraft-time", @@ -2483,16 +2573,16 @@ dependencies = [ [[package]] name = "filmcraft-geom" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "serde", ] [[package]] name = "filmcraft-h264" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2501,8 +2591,8 @@ dependencies = [ [[package]] name = "filmcraft-h264enc" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2511,8 +2601,8 @@ dependencies = [ [[package]] name = "filmcraft-hevc" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2521,8 +2611,8 @@ dependencies = [ [[package]] name = "filmcraft-interchange" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-cfb", "filmcraft-color", @@ -2538,22 +2628,24 @@ dependencies = [ [[package]] name = "filmcraft-isobmff" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ - "filmcraft-bitstream", - "thiserror 2.0.21", + "craft-media", ] [[package]] name = "filmcraft-matroska" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +dependencies = [ + "craft-media", +] [[package]] name = "filmcraft-media" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-color", "filmcraft-dng", @@ -2567,8 +2659,8 @@ dependencies = [ [[package]] name = "filmcraft-mpa" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "thiserror 2.0.21", @@ -2576,8 +2668,8 @@ dependencies = [ [[package]] name = "filmcraft-mpeg2v" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2585,31 +2677,34 @@ dependencies = [ [[package]] name = "filmcraft-mpegts" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "thiserror 2.0.21", ] [[package]] name = "filmcraft-mxf" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +dependencies = [ + "chrono", +] [[package]] name = "filmcraft-ogg" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" [[package]] name = "filmcraft-opus" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" [[package]] name = "filmcraft-project" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-color", "filmcraft-geom", @@ -2622,8 +2717,8 @@ dependencies = [ [[package]] name = "filmcraft-prores" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2632,24 +2727,24 @@ dependencies = [ [[package]] name = "filmcraft-time" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "serde", ] [[package]] name = "filmcraft-vp8" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "thiserror 2.0.21", ] [[package]] name = "filmcraft-vp9" -version = "0.8.0" -source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" +version = "0.12.0" +source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2980,7 +3075,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ "rustix 1.1.5", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3233,7 +3328,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" dependencies = [ "hayro-ccitt", ] @@ -3247,7 +3342,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" dependencies = [ "hayro-jbig2", "hayro-jpeg2000", @@ -3580,7 +3675,7 @@ dependencies = [ "simd_cesu8", "thiserror 2.0.21", "walkdir", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3726,7 +3821,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4032,6 +4127,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -4346,6 +4450,16 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -4547,7 +4661,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.45.0", + "windows-sys 0.61.2", ] [[package]] @@ -4576,7 +4690,7 @@ dependencies = [ "libc", "redox_syscall 0.5.18", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -5983,6 +6097,20 @@ dependencies = [ "walkdir", ] +[[package]] +name = "sysinfo" +version = "0.37.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16607d5caffd1c07ce073528f9ed972d88db15dd44023fa57142963be3feb11f" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows 0.61.3", +] + [[package]] name = "tag_ptr" version = "0.1.0" @@ -7136,16 +7264,38 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections 0.2.0", + "windows-core 0.61.2", + "windows-future 0.2.1", + "windows-link 0.1.3", + "windows-numerics 0.2.0", +] + [[package]] name = "windows" version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ - "windows-collections", + "windows-collections 0.3.2", "windows-core 0.62.2", - "windows-future", - "windows-numerics", + "windows-future 0.3.2", + "windows-numerics 0.3.1", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", ] [[package]] @@ -7167,6 +7317,19 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -7175,9 +7338,20 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", - "windows-link", + "windows-link 0.2.1", "windows-result 0.4.1", - "windows-strings", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading 0.1.0", ] [[package]] @@ -7187,8 +7361,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ "windows-core 0.62.2", - "windows-link", - "windows-threading", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -7213,12 +7387,28 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + [[package]] name = "windows-numerics" version = "0.3.1" @@ -7226,7 +7416,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ "windows-core 0.62.2", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7235,9 +7425,9 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ - "windows-link", + "windows-link 0.2.1", "windows-result 0.4.1", - "windows-strings", + "windows-strings 0.5.1", ] [[package]] @@ -7249,13 +7439,31 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-result" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -7264,7 +7472,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7300,7 +7508,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7334,13 +7542,22 @@ dependencies = [ "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-threading" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7623,11 +7840,12 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.21.0" +version = "0.24.1" dependencies = [ "chrono", "pkg-config", "serde_json", + "sha2", "tempfile", ] @@ -7870,7 +8088,6 @@ dependencies = [ "nix", "typed-path 0.13.0", "windows-sys 0.61.2", - "zopfli", ] [[package]] @@ -7885,18 +8102,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zune-core" version = "0.5.3" @@ -7961,23 +8166,3 @@ dependencies = [ "syn 3.0.6", "winnow", ] - -[[patch.unused]] -name = "egui_demo_lib" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - -[[patch.unused]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - -[[patch.unused]] -name = "egui_inspection" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - -[[patch.unused]] -name = "egui_system_font_provider" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" diff --git a/Cargo.toml b/Cargo.toml index f5f84775f..6cb650067 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,19 +4,19 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/*"] [workspace.package] -version = "0.21.0" +version = "0.24.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", default-features = false, features = ["read"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", version = "=0.1.0", default-features = false, features = ["read"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } +craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ca1b5e2edb8568335c6c14f390307bd5beae8238" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } # internal effectcraft-time = { path = "crates/time" } effectcraft-geom = { path = "crates/geom" } @@ -40,6 +40,7 @@ effectcraft-lottie = { path = "crates/lottie" } effectcraft-interchange = { path = "crates/interchange" } effectcraft-pdf = { path = "crates/pdf" } effectcraft-psd = { path = "crates/psd" } +effectcraft-aep = { path = "crates/aep" } effectcraft-vp9enc = { path = "crates/vp9enc" } effectcraft-svg = { path = "crates/svg" } effectcraft-engine = { path = "crates/engine" } @@ -51,6 +52,7 @@ effectcraft-script = { path = "crates/script" } effectcraft-hevcenc = { path = "crates/hevcenc" } effectcraft-av1enc = { path = "crates/av1enc" } effectcraft-plugin = { path = "crates/plugin" } +effectcraft-helper-host = { path = "crates/helper-host" } # foundation thiserror = "2" @@ -82,43 +84,46 @@ tempfile = "3.27" # media codecs + containers: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001). # Only `crates/media`, `crates/export` and `crates/interchange` may depend on these. -filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } +filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } # encoders + muxer (crates/export) -filmcraft-h264enc = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-prores = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-aac = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-isobmff = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } +filmcraft-h264enc = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-prores = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-aac = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-isobmff = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } # container headers read for AAC channel layouts (crates/media) -filmcraft-matroska = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-mpegts = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } +filmcraft-matroska = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-mpegts = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } # decoder used as the round-trip oracle of effectcraft-opusenc (crates/export dev-dependency) -filmcraft-opus = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-vp9 = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } +filmcraft-opus = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-vp9 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } # decoders used as the round-trip oracles of effectcraft-hevcenc / effectcraft-av1enc (dev-dependencies only) -filmcraft-hevc = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-av1 = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } +filmcraft-hevc = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-av1 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } # timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only) -filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } -filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5" } +filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } # gpu (the same wgpu eframe / egui-wgpu use) wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] } bytemuck = "1" pollster = "1" +half = "2.7" # ui # Shared frontend components; keep this dependency above the engine boundary. # Shared UI and the complete egui family select reviewed immutable commits below. -craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] } +craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", features = ["serde"] } # `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()` # and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate. egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] } eframe = { version = "0.37", default-features = false } +# Resizable table columns (About ▸ Contributors / Models); no image loaders. +egui_extras = { version = "0.37", default-features = false } egui_kittest = "0.37" rfd = "0.17" cpal = "0.16" @@ -237,8 +242,8 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.3.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", version = "=0.3.0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } @@ -249,8 +254,7 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968 egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +# Patch a crate only together with the dependency that needs it: an unused patch makes the Nix +# build, which uses vendored sources, fail (`cargo xtask lock-patches`). winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/README.md b/README.md index 81b5a0ba5..913f8aa06 100644 --- a/README.md +++ b/README.md @@ -129,18 +129,14 @@ or into the Timeline, between layers and at the time you point to. 308 built-in effects across its categories, each with its parameter names, order and defaults: blur and sharpen, channel, color correction (Curves, Levels, Hue/Saturation, a full -color-grading panel…), distort (Warp, Bulge, Turbulent Displace, CC Power Pin…), generate (Fractal Noise, +color-grading panel…), distort (Warp, Bulge, Turbulent Displace, Perspective Pin…), generate (Fractal Noise, Gradient Ramp, Stroke, Write-on, Audio Spectrum…), keying, matte, noise and grain, perspective, -**simulation** (CC Particle World, CC Rainfall, Shatter, Card Dance, Caustics, Wave World…), -stylize (Glow, CC Glass…), **time** (Echo, Posterize Time, Timewarp, Time Displacement…), +**simulation** (Particle Emitter 3D, Rainfall, Shatter, Card Dance, Caustics, Wave World…), +stylize (Glow, Glass Relief…), **time** (Echo, Posterize Time, Timewarp, Time Displacement…), **audio** (Reverb, Parametric EQ, Delay, Stereo Mixer…), text, transitions, utility and expression controls. All nine **Layer Styles** (Drop Shadow, Inner/Outer Glow, Bevel and Emboss, Satin, overlays, Stroke) with Global Light. Preview plays audio in sync, with meters and waveforms. -

- A CC Particle World burst with Glow, and the Effect Controls panel listing the particle system's parameters -

- ## 3D Classic 3D compositing: 3D layers with orientation and material options, diff --git a/ROADMAP.md b/ROADMAP.md index dff795d85..e41cbe2f1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~30 points of "ready for real work" and ~350–620 h away -> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-10-30 · **Change:** minor (features of 30 October in the progress log: text Line Join, Timeline drag-reorder and multi-select of effects, viewer edge pan, ScriptUI drag capture and dock size; previously: localization recount after #1774) · **Target:** Adobe After Effects 2026 (26.5.0.89) +> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-11-05 · **Change:** minor (ProRes alpha final-run conformance; previously: features of 30 October in the progress log: text Line Join, Timeline drag-reorder and multi-select of effects, viewer edge pan, ScriptUI drag capture and dock size; previously: localization recount after #1774) · **Target:** Adobe After Effects 2026 (26.5.0.89) EffectCraft aims to do what After Effects does, with the same panels, menus and behaviour, written from scratch in Rust. This page is the one-page summary; the evidence is in @@ -117,6 +117,10 @@ Come tell us what matters most to you on [Discord](https://discord.gg/artcraft). ## Progress log +- 2026-11-05: ProRes 4444 and XQ exports write the required run after the final alpha + difference. The FilmCraft encoder pin fixes alpha movies rejected by native macOS + decoding; an export regression checks the stored bytes for both profiles, alpha modes, + and motion-blur settings (#293). Resolve itself still needs confirmation. - 2026-10-30: Text strokes take a Line Join (Miter, Round or Bevel) in the Character panel, Miter for new text as in After Effects (#2077). In the Timeline, effects, masks and shape items drag to a new place in their stack (#2210) and Shift-click adds them to the selection, so one diff --git a/apps/effectcraft-cli/src/main.rs b/apps/effectcraft-cli/src/main.rs index 6ba352247..f52401a00 100644 --- a/apps/effectcraft-cli/src/main.rs +++ b/apps/effectcraft-cli/src/main.rs @@ -17,6 +17,7 @@ //! [--jpeg-quality N] [--bitrate KBPS] [--prores proxy|lt|standard|hq|4444|4444xq] [--audio auto|on|off] //! [--profile main|main10] [--level auto|4.1] [--rate-control bitrate|quality] [--video-quality 1-100] //! [--keyint FRAMES] [--webm-codec vp9|av1] [--audio-bitrate KBPS] [--opus-app audio|voice] +//! [--exr-compression none|rle|zips|zip|piz|pxr24|b44|b44a|dwaa|dwab] [--exr-depth half|float] //! (a relative --out is relative to the working directory; --queue outputs follow the project's own settings) //! [--progress] report progress on stderr when it is not a terminal, up to four lines a second: //! `progress ` @@ -30,12 +31,13 @@ //! effectcraft-cli bench --roto [--frames N] [--sam2 model.safetensors] [--mobilesam mobile_sam.pt] [--fixes] [--clip FRAMES --truth MASKS] [--json] Roto Brush trackers on synthetic clips with known mattes //! (classical engine, MobileSAM and SAM 2.1 (any installed size) when installed; IoU, flicker, re-appearance, seconds per frame) //! effectcraft-cli script FILE.jsx [F.ecproj] | --eval CODE run an After Effects-style script +//! effectcraft-cli replay SCRIPT.jsonl [--keep-going] replay a repro script (docs/agents.md) //! effectcraft-cli mcp [--autosave | --bridge PORT] MCP server on stdio //! //! Project: --project F.ecproj (or a positional *.ecproj) | --demo | --empty (default: demo; mcp: empty) //! Saving: --save (back to --project) | --save-as F.ecproj -//! GPU: --gpu renders on the GPU compositor (Mercury GPU Acceleration) when an adapter exists; -//! the default is the CPU (Mercury Software Only) +//! GPU: --gpu renders on the GPU compositor (GPU Acceleration) when an adapter exists; +//! the default is the CPU (Software Rendering) //! Bridge: --bridge PORT drives a running `effectcraft --control PORT` instead of a headless session //! Output: --json for one compact JSON document on stdout (errors: {"error": …}, exit 1) //! ``` @@ -47,6 +49,7 @@ use std::io::Write; +mod project_lock; mod template; use effectcraft_automation::tools::{self, Reply}; @@ -95,7 +98,7 @@ fn stdout_broken() -> bool { STDOUT_FAILED.get().is_some_and(|k| *k != std::io::ErrorKind::BrokenPipe) } -const USAGE: &str = "usage: effectcraft-cli [args] [--json] +const USAGE: &str = "usage: effectcraft-cli [args] [--json] info project + engine summary commands [--filter TEXT] [--enabled] list engine commands exec [--params JSON] run one engine command (exec --list: list them, as `commands`) @@ -113,9 +116,13 @@ const USAGE: &str = "usage: effectcraft-cli ) @@ -132,6 +139,9 @@ const USAGE: &str = "usage: effectcraft-cli Result { } /// A wired session; `--gpu` attaches the GPU compositor (renders then follow the project's -/// renderer setting, Mercury GPU Acceleration by default). +/// renderer setting, GPU Acceleration by default). fn session(args: &Args) -> Result { let mut s = effectcraft_host::session(); if args.flag("--autosave") { @@ -508,6 +521,7 @@ fn script_cmd(args: &Args, json_out: bool) -> Result<(), Failure> { (None, Some(f)) => (std::fs::read_to_string(f).map_err(|e| Failure::Error(format!("cannot read {f}: {e}")))?, f.clone()), (None, None) => return usage_err("script needs a .jsx/.js file or --eval CODE"), }; + let _lock = project_lock::for_save(args)?; let mut b = backend(args, false)?; let r = b.exec("script.run", json!({"code": code, "name": name}))?; let saved = maybe_save(&mut b, args)?; @@ -543,6 +557,59 @@ fn script_cmd(args: &Args, json_out: bool) -> Result<(), Failure> { Ok(()) } +/// `replay SCRIPT.jsonl`: run a repro script against a headless session (its start line picks +/// the project) and report every step. Exits 1 when the replay fails. +fn replay_cmd(args: &Args, json_out: bool) -> Result<(), Failure> { + use effectcraft_engine::replay; + let Some(file) = args.pos.first() else { return usage_err("replay needs a .jsonl script") }; + if args.opt("--bridge").is_some() || args.project.is_some() || args.flag("--demo") || args.flag("--empty") { + return usage_err("replay runs headless from the script's start line ({\"start\": \"new\" | \"demo\" | {\"project\": path}})"); + } + use std::io::Read; + let path = std::path::Path::new(file); + let input = std::fs::File::open(path).map_err(|e| Failure::Error(format!("cannot read {file}: {e}")))?; + // Bound the read itself: metadata can be stale or describe a pipe rather than its contents. + let mut script = String::new(); + input.take(replay::MAX_SCRIPT_BYTES as u64 + 1).read_to_string(&mut script).map_err(|e| Failure::Error(format!("cannot read {file}: {e}")))?; + if script.len() > replay::MAX_SCRIPT_BYTES { + return Err(Failure::Error(format!("{file} is larger than {} MB", replay::MAX_SCRIPT_BYTES >> 20))); + } + let mut s = session(args)?; + let opts = replay::Options { keep_going: args.flag("--keep-going"), base_dir: path.parent().map(std::path::Path::to_path_buf) }; + let report = replay::run(&mut s, &script, &opts); + if json_out { + emit(&serde_json::to_value(&report).unwrap_or_else(|e| json!({"error": e.to_string()})), true); + } else { + for st in &report.steps { + let what = st.command.as_deref().unwrap_or(st.kind); + match (&st.error, st.ok) { + (None, _) => say!("line {:>4} ok {what}", st.line), + (Some(e), true) => say!("line {:>4} ok {what} (tolerated error: {e})", st.line), + (Some(e), false) => say!("line {:>4} FAIL {what}: {e}", st.line), + } + } + } + let Some(first) = &report.first_failure else { + if !json_out { + say!("replay ok: {} steps", report.steps.len()); + } + return Ok(()); + }; + let msg = format!( + "failed at line {} ({}){}: {}{}", + first.line, + first.command.as_deref().unwrap_or(first.kind), + if report.panicked { ", a command panicked" } else { "" }, + first.error.as_deref().unwrap_or(""), + if report.skipped > 0 { format!(" ({} later steps not run)", report.skipped) } else { String::new() } + ); + if json_out { + note!("effectcraft-cli replay: {msg}"); + std::process::exit(1); + } + Err(Failure::Error(msg)) +} + /// Print a result: compact JSON with `--json`, else pretty JSON. fn emit(v: &Value, json_out: bool) { if json_out { @@ -605,12 +672,14 @@ fn run(cmd: &str, args: &Args, json_out: bool) -> Result<(), Failure> { "commands" => list_commands_cmd(args, json_out)?, "exec" if args.flag("--list") => list_commands_cmd(args, json_out)?, "script" => script_cmd(args, json_out)?, + "replay" => replay_cmd(args, json_out)?, "exec" => { let Some(id) = args.pos.first().cloned() else { return usage_err("exec needs a command id") }; let params = match (args.opt("--params"), args.pos.get(1).map(String::as_str)) { (Some(p), _) | (None, Some(p)) => serde_json::from_str(p).map_err(|e| Failure::Usage(format!("params are not valid JSON: {e}")))?, (None, None) => json!({}), }; + let _lock = project_lock::for_save(args)?; let mut b = backend(args, true)?; let r = b.exec(&id, params)?; if let Some(e) = failed_render(&id, &r) { @@ -654,6 +723,7 @@ fn run(cmd: &str, args: &Args, json_out: bool) -> Result<(), Failure> { if steps.is_empty() { return Err(Failure::Usage(format!("--commands {}: no commands", sources.join(", ")))); } + let _lock = project_lock::for_save(args)?; let mut b = backend(args, true)?; let mut results = vec![]; // The step's index closes the message: a generated list repeats ids, and callers match @@ -690,7 +760,7 @@ fn run(cmd: &str, args: &Args, json_out: bool) -> Result<(), Failure> { if let Some(e) = p.get("expression").and_then(Value::as_str) { extra += &format!(" expr: {e}"); } - say!(" {:<44} {:<8} {}{extra}", p["path"].as_str().unwrap_or(""), p["type"].as_str().unwrap_or(""), p["value"]); + say!(" {:<44} {:<8} {}{extra}", p["path"].as_str().unwrap_or(""), p["type"].as_str().unwrap_or(""), value_text(p)); } } } @@ -708,6 +778,7 @@ fn run(cmd: &str, args: &Args, json_out: bool) -> Result<(), Failure> { } let (comp, layer, path) = (args.pos[0].clone(), args.pos[1].clone(), args.pos[2].clone()); let value = args.pos.get(3).map(|v| value_arg(v)); + let _lock = project_lock::for_save(args)?; let mut b = backend(args, true)?; let a = json!({"comp": reference(&comp), "layer": reference(&layer), "path": path, "value": value, "time": args.num("--time")?, "expression": expr}); @@ -876,6 +947,8 @@ fn render(args: &Args, json_out: bool) -> Result<(), Failure> { ("--rate-control", "rateControl"), ("--webm-codec", "webmCodec"), ("--opus-app", "opusApplication"), + ("--exr-compression", "exrCompression"), + ("--exr-depth", "exrBitDepth"), ] { if let Some(v) = args.opt(flag) { p[key] = json!(v); @@ -1429,7 +1502,7 @@ fn adv3d_bench_comp(p: &mut effectcraft_engine::project::Project) -> Option Result<(), Failure> { use effectcraft_render::Backend; @@ -1539,6 +1612,16 @@ fn bench_gpu(s: &Session, args: &Args) -> Result<(), Failure> { Ok(()) } +/// A flat property's value for the text listing: an enum's number with the label `options` gives it +/// (#2928), since the numbers are 0-based where After Effects scripting counts from 1. +fn value_text(p: &Value) -> String { + let label = p["options"].as_array().and_then(|o| o.iter().find(|o| o["value"] == p["value"])).and_then(|o| o["label"].as_str()); + match label { + Some(l) => format!("{} ({l})", p["value"]), + None => p["value"].to_string(), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/apps/effectcraft-cli/src/project_lock.rs b/apps/effectcraft-cli/src/project_lock.rs new file mode 100644 index 000000000..234bbfd33 --- /dev/null +++ b/apps/effectcraft-cli/src/project_lock.rs @@ -0,0 +1,150 @@ +//! One saving run at a time per project file. +//! +//! A `--save` run reads the project, edits it and writes the whole file back, so two at once would +//! silently drop the edits of whichever saved first (#2851). Each run holds an OS lock from before +//! its read until it exits; the next one waits, then reads what the first one saved. This is how +//! filmcraft-cli does it (storytold/filmcraft#3926). +//! +//! The lock is on a file next to the project, not on the project: a save replaces the project's +//! inode, and on Windows a locked file can't be read by other processes. The OS drops the lock when +//! the process ends, however it ends, so a crash leaves nothing stale. The file itself stays, since +//! removing it would let one run wait on the old file while another locks a new one. + +use crate::{Args, Failure}; +use std::fs::{File, TryLockError}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// Most bytes of the project's file name kept in the lock's name; the rest of the 255-byte limit +/// is left for the leading dot and `.lock`. +const MAX_NAME_BYTES: usize = 200; + +fn lock_path(project: &Path) -> PathBuf { + let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + project.with_file_name(format!(".{}.lock", &name[..name.floor_char_boundary(MAX_NAME_BYTES)])) +} + +/// Do two paths name one existing file? +fn same_file(a: &str, b: &str) -> bool { + a == b || matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b) +} + +/// The path this run saves over, when that is the file it opens. `--save-as` somewhere else replaces +/// that file whatever it held, so there is no edit of its to lose. +/// +/// The lock goes by this path as written, not by where a symlink points: runs that name the +/// project the same way share one lock. +/// +/// A missing project is an error here, before anything else, the same one opening it would give. +/// If the run went on, another one could create the project before it is read, and this run would +/// edit and save it with no lock. Checking first also means the paths compared below exist, so +/// `canonicalize` tells exactly whether they are one file, however they are spelt. A project that +/// exists but isn't a file gets no lock file beside it, and opening it reports why. +fn saved_in_place(a: &Args) -> Result, String> { + // `--bridge` with a project is a usage error, which `backend` reports + let Some(project) = a.project.as_deref().filter(|_| a.opt("--bridge").is_none()) else { return Ok(None) }; + match Path::new(project).metadata() { + Ok(meta) if meta.is_file() => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(format!("cannot read {project}: {e}")), + _ => return Ok(None), + } + match a.opt("--save-as") { + Some(target) if same_file(target, project) => Ok(Some(Path::new(target))), + None if a.flag("--save") => Ok(Some(Path::new(project))), + _ => Ok(None), + } +} + +/// Lock `project`, calling `waiting` first if another run holds the lock. +fn lock(project: &Path, waiting: impl FnOnce()) -> std::io::Result { + let file = File::options().create(true).truncate(false).read(true).write(true).open(lock_path(project))?; + match file.try_lock() { + Ok(()) => {} + Err(TryLockError::WouldBlock) => { + waiting(); + file.lock()?; + } + Err(TryLockError::Error(e)) => return Err(e), + } + Ok(file) +} + +/// Take the project's lock if this run saves over the file it opens, or fail if the project is +/// missing. Call it before opening the project and keep the result until the save is done. Blocks +/// while another run holds the lock, which is fine here: nothing else is running yet. A lock that +/// can't be had (a read-only folder, a file system without locks) is a warning and not an error, so +/// that saving works where it did. +pub(crate) fn for_save(a: &Args) -> Result, Failure> { + let Some(project) = saved_in_place(a).map_err(Failure::Error)? else { return Ok(None) }; + let shown = project.display(); + let waiting = || { + let _ = writeln!(std::io::stderr(), "effectcraft-cli: waiting for another run saving {shown}"); + }; + match lock(project, waiting) { + Ok(file) => Ok(Some(file)), + Err(e) => { + let _ = writeln!(std::io::stderr(), "effectcraft-cli: warning: can't lock {shown} ({e}); another run saving it now could overwrite these edits"); + Ok(None) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(list: &[&str]) -> Args { + Args::parse(list.iter().map(|s| s.to_string()).collect()).unwrap() + } + + #[test] + fn the_lock_sits_next_to_the_project() { + assert_eq!(lock_path(Path::new("/a/b/p.ecproj")), Path::new("/a/b/.p.ecproj.lock")); + assert_eq!(lock_path(Path::new("p.ecproj")), Path::new(".p.ecproj.lock")); + } + + #[test] + fn a_long_project_name_still_gets_a_lock_name_the_file_system_takes() { + for name in ["a".repeat(255), "é".repeat(127)] { + let lock = lock_path(Path::new(&name)); + let lock = lock.to_str().unwrap(); + assert!(lock.len() <= 255, "{} bytes", lock.len()); + assert!(lock.ends_with(".lock")); + } + } + + /// The moment between this check and opening the project can't be hit on demand, so this pins + /// the decision that closes it: a run never goes on to open a project that wasn't there, however + /// its paths are spelt and whatever it saves. + #[test] + fn a_missing_project_stops_the_run_before_anything_opens_it() { + let name = format!("ec-cli-gone-{}.ecproj", std::process::id()); + let gone = std::env::temp_dir().join(&name); + let gone = gone.to_str().unwrap(); + let alias = std::env::temp_dir().join(".").join(&name); + let alias = alias.to_str().unwrap(); + let dotted = format!("./{name}"); + // in a folder that doesn't exist either, so no part of either spelling can be resolved + let new_dir = std::env::temp_dir().join(format!("ec-cli-new-dir-{}", std::process::id())); + let in_new_dir = new_dir.join("p.ecproj"); + let in_new_dir = in_new_dir.to_str().unwrap(); + let in_new_dir_alias = new_dir.join(".").join("p.ecproj"); + let in_new_dir_alias = in_new_dir_alias.to_str().unwrap(); + for (project, list) in [ + (gone, &["exec", "--project", gone, "--save"][..]), + (gone, &["exec", gone, "--save"]), + (gone, &["exec", "--project", gone, "--save-as", gone]), + (gone, &["exec", "--project", gone, "--save-as", alias]), + (name.as_str(), &["exec", "--project", &name, "--save-as", &dotted]), + (in_new_dir, &["exec", "--project", in_new_dir, "--save-as", in_new_dir_alias]), + (gone, &["exec", "--project", gone, "--save-as", "other.ecproj"]), + (gone, &["exec", "--project", gone]), + ] { + let error = saved_in_place(&args(list)).unwrap_err(); + assert_eq!(error.split_once(": ").map(|(head, _)| head), Some(format!("cannot read {project}").as_str()), "{list:?}: {error}"); + } + // a project with --bridge is a usage error, which `backend` reports; no project, no lock + assert_eq!(saved_in_place(&args(&["exec", "--bridge", "9877", "--project", gone, "--save"])), Ok(None)); + assert_eq!(saved_in_place(&args(&["exec", "--demo", "--save-as", gone])), Ok(None)); + } +} diff --git a/apps/effectcraft-cli/tests/it/cli.rs b/apps/effectcraft-cli/tests/it/cli.rs index e9a96dd7e..4510f16c9 100644 --- a/apps/effectcraft-cli/tests/it/cli.rs +++ b/apps/effectcraft-cli/tests/it/cli.rs @@ -110,6 +110,197 @@ fn exec_set_get_with_saved_project() { assert_eq!(v[1]["result"]["time"], v[0]["result"]["time"], "{v}"); } +/// #2928: the text listing gives an enum's label next to its number (0-based, unlike After +/// Effects scripting), the way `props --json` lists its `options`. +#[test] +fn props_lists_enum_labels() { + let proj = tmp("enum-labels.ecproj"); + let p = proj.to_str().unwrap(); + let anim = r#"{"layer":"t","properties":["opacity"]}"#; + ok_json(&[ + "run", + "comp.new", + r#"{"name":"T","width":64,"height":36}"#, + "layer.newText", + r#"{"text":"AB","name":"t"}"#, + "layer.addTextAnimator", + anim, + "--empty", + "--save-as", + p, + ]); + ok_json(&["set", "T", "t", "text/animators/animator/selectors/rangeSelector/advanced/shape", "1", p, "--save"]); + let out = bin().args(["props", "T", "t", p]).output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + let shape = text.lines().find(|l| l.contains("advanced/shape")).unwrap_or_else(|| panic!("no shape line in:\n{text}")); + assert!(shape.trim_end().ends_with("enum 1 (Ramp Up)"), "{shape}"); + let units = text.lines().find(|l| l.contains("advanced/units")).unwrap_or_default(); + assert!(units.trim_end().ends_with("0 (Percentage)"), "{units}"); + let size = text.lines().find(|l| l.contains("transform/opacity")).unwrap_or_default(); + assert!(size.trim_end().ends_with("100.0"), "a number without options stays bare: {size}"); +} + +/// A project in a new folder of its own, for the save lock tests (#2851). +fn lock_test_project(tag: &str) -> (PathBuf, String) { + let dir = tmp(&format!("lock-{tag}")); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let proj = dir.join("p.ecproj").to_str().unwrap().to_string(); + ok_json(&["exec", "project.newFolder", r#"{"name":"start"}"#, "--empty", "--save-as", &proj]); + (dir, proj) +} + +/// The lock of the project file `name`, held by this process. +fn hold_lock(dir: &std::path::Path, name: &str) -> std::fs::File { + let lock = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(format!(".{name}.lock"))).unwrap(); + lock.lock().unwrap(); + lock +} + +/// Start a run that has to wait for a lock this process holds; returns once it says it is waiting. +fn start_waiting_run(args: &[&str]) -> std::process::Child { + let mut child = bin().args(args).stdout(Stdio::null()).stderr(Stdio::piped()).spawn().unwrap(); + let mut stderr = BufReader::new(child.stderr.take().unwrap()); + let mut line = String::new(); + while !line.contains("waiting for another run saving") { + line.clear(); + assert_ne!(stderr.read_line(&mut line).unwrap(), 0, "{args:?} ended without waiting"); + } + assert!(child.try_wait().unwrap().is_none(), "{args:?} did not wait"); + child +} + +/// Folder names in a saved project. +fn has_folder(proj: &str, name: &str) -> bool { + std::fs::read_to_string(proj).unwrap().contains(&format!("\"{name}\"")) +} + +#[test] +fn parallel_saves_keep_every_edit() { + let (dir, proj) = lock_test_project("parallel"); + let names = |writer: usize| (0..300).map(move |i| format!("edit-{writer}-{i}")); + let mut writers: Vec<_> = (0..4) + .map(|_| { + bin() + .args(["run", "--project", &proj, "--commands", "-", "--save"]) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap() + }) + .collect(); + // Each writer reads its whole script before it opens the project, so closing the stdins together + // starts all the edits at once, and long scripts keep each read-to-save span over the others. + for (n, writer) in writers.iter_mut().enumerate() { + let script: String = names(n).map(|name| format!("{}\n", json!({"command": "project.newFolder", "params": {"name": name}}))).collect(); + writer.stdin.take().unwrap().write_all(script.as_bytes()).unwrap(); + } + for mut writer in writers { + assert!(writer.wait().unwrap().success()); + } + let lost: Vec = (0..4).flat_map(names).filter(|name| !has_folder(&proj, name)).collect(); + assert!(lost.is_empty(), "lost {} edits: {lost:?}", lost.len()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_save_in_place_waits_for_the_lock_then_edits_the_latest_project() { + let (dir, proj) = lock_test_project("wait"); + for save in [&["--save"][..], &["--save-as", proj.as_str()]] { + let held = hold_lock(&dir, "p.ecproj"); + let before = std::fs::read(&proj).unwrap(); + let params = json!({"name": format!("waited-{}", save.len())}).to_string(); + let args = [&["exec", "project.newFolder", ¶ms, "--project", &proj][..], save].concat(); + let mut child = start_waiting_run(&args); + assert_eq!(std::fs::read(&proj).unwrap(), before, "{save:?} wrote while another run held the lock"); + // an edit made meanwhile by the holder must survive: the waiter reads only after the lock is free + let held_params = json!({"name": format!("held-{}", save.len())}).to_string(); + ok_json(&["exec", "project.newFolder", &held_params, "--project", &proj, "--save-as", &format!("{proj}.tmp")]); + std::fs::rename(format!("{proj}.tmp"), &proj).unwrap(); + drop(held); + assert!(child.wait().unwrap().success(), "{save:?}"); + for want in [format!("waited-{}", save.len()), format!("held-{}", save.len())] { + assert!(has_folder(&proj, &want), "{save:?} lost {want}"); + } + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Runs through a symlink take the same lock before and after a save, or a run still waiting on +/// the old one could overwrite a later run's save. +#[cfg(unix)] +#[test] +fn a_symlinked_project_keeps_its_lock_after_a_save() { + let (dir, proj) = lock_test_project("symlink"); + let link = dir.join("link.ecproj"); + std::os::unix::fs::symlink(&proj, &link).unwrap(); + for name in [r#"{"name":"first"}"#, r#"{"name":"second"}"#] { + let held = hold_lock(&dir, "link.ecproj"); + let mut child = start_waiting_run(&["exec", "project.newFolder", name, "--project", link.to_str().unwrap(), "--save"]); + drop(held); + assert!(child.wait().unwrap().success(), "{name}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn runs_that_do_not_save_in_place_ignore_the_lock() { + let (dir, proj) = lock_test_project("ignore"); + let other = dir.join("other.ecproj").to_str().unwrap().to_string(); + let _held = hold_lock(&dir, "p.ecproj"); + let params = r#"{"name":"copy-only"}"#; + let cases: [&[&str]; 3] = [ + &["info", "--project", &proj], + &["exec", "project.newFolder", params, "--project", &proj], + &["exec", "project.newFolder", params, "--project", &proj, "--save-as", &other], + ]; + for args in cases { + let mut child = bin().args(args).stdout(Stdio::null()).stderr(Stdio::null()).spawn().unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break status; + } + if std::time::Instant::now() > deadline { + let _ = child.kill(); + panic!("{args:?} is waiting for a lock it doesn't need"); + } + std::thread::sleep(std::time::Duration::from_millis(10)); + }; + assert!(status.success(), "{args:?}"); + } + assert!(!has_folder(&proj, "copy-only")); + assert!(has_folder(&other, "copy-only")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_missing_project_gets_no_lock_file_and_keeps_its_error() { + let (dir, _) = lock_test_project("missing"); + let gone = dir.join("gone.ecproj").to_str().unwrap().to_string(); + let other = dir.join("other.ecproj").to_str().unwrap().to_string(); + // what opening it says, after the `effectcraft-cli : ` prefix + let error = |args: &[&str]| { + let out = bin().args(args).output().unwrap(); + assert_eq!(out.status.code(), Some(1), "{args:?}"); + let stderr = String::from_utf8_lossy(&out.stderr).into_owned(); + stderr.split_once(": ").map(|(_, e)| e.to_string()).unwrap_or(stderr) + }; + let plain = error(&["info", "--project", &gone]); + assert!(plain.contains("gone.ecproj"), "{plain}"); + // saving in place, saving elsewhere, or not saving: the error is the one opening gives + for save in [&["--save"][..], &["--save-as", gone.as_str()], &["--save-as", other.as_str()], &[]] { + let args = [&["exec", "project.newFolder", r#"{"name":"copy-only"}"#, "--project", &gone][..], save].concat(); + assert_eq!(error(&args), plain, "{save:?}"); + } + assert!(!dir.join(".gone.ecproj.lock").exists()); + assert!(!dir.join("other.ecproj").exists()); + // a project with --bridge stays a usage error + assert_eq!(bin().args(["exec", "project.newFolder", "--bridge", "9877", "--project", &gone, "--save"]).output().unwrap().status.code(), Some(2)); + let _ = std::fs::remove_dir_all(&dir); +} + /// `run --args-file` reads its command / params pairs from a file, one per line: a batch longer /// than a Windows command line (32 767 characters, os error 206) still runs. #[test] @@ -136,7 +327,14 @@ fn run_reads_arguments_from_a_file() { /// Run with `stdin` piped in; returns (exit code, stdout, stderr). fn run_with_stdin(args: &[&str], stdin: &str) -> (i32, String, String) { let mut child = bin().args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); - child.stdin.take().unwrap().write_all(stdin.as_bytes()).unwrap(); + // The child may exit before it has read all of standard input (the usage-error cases below + // exit with code 2 without draining stdin), so a broken pipe while writing is that early + // exit, not a failure of this helper; the assertions on the returned output still hold. + let mut stdin_pipe = child.stdin.take().unwrap(); + if let Err(err) = stdin_pipe.write_all(stdin.as_bytes()) { + assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe, "writing the child's standard input: {err}"); + } + drop(stdin_pipe); let out = child.wait_with_output().unwrap(); (out.status.code().unwrap_or(-1), String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned()) } @@ -973,3 +1171,91 @@ fn render_without_progress_writes_no_progress_lines() { let stderr = render_demo_stderr("no-progress.gif", &[]); assert!(!stderr.lines().any(|l| l.starts_with("progress")), "{stderr}"); } + +/// `render --exr-compression C --exr-depth half` writes OpenEXR frames with that compression and +/// half-float channels (#2911); an unknown value is an error naming the parameter. +#[test] +fn render_exr_compression_and_depth() { + let root = tmp("render-exr-options"); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let project = root.join("x.ecproj"); + let p = project.to_str().unwrap(); + ok_json(&[ + "run", + "comp.new", + r#"{"name":"T","width":64,"height":36,"duration":1}"#, + "layer.newSolid", + r#"{"width":64,"height":36}"#, + "--empty", + "--save-as", + p, + ]); + let out = root.join("f_[#####].exr"); + let reply = ok_json(&[ + "render", + "--project", + p, + "--start", + "0", + "--end", + "0.01", + "--exr-compression", + "piz", + "--exr-depth", + "half", + "--out", + out.to_str().unwrap(), + ]); + assert_eq!(reply["rendered"].as_array().unwrap().len(), 1, "{reply}"); + let bytes = std::fs::read(root.join("f_00000.exr")).unwrap(); + // The `compression` attribute: name, type name, a 1-byte size, then PIZ (4). + let attr = b"compression\0compression\0\x01\0\0\0"; + let at = bytes.windows(attr.len()).position(|w| w == attr).expect("compression attribute"); + assert_eq!(bytes[at + attr.len()], 4, "PIZ"); + // Each channel in `chlist`: its name, then the pixel type (1 = half). + for name in [&b"R\0"[..], b"G\0", b"B\0", b"A\0"] { + let half = [name, &[1, 0, 0, 0]].concat(); + assert!(bytes.windows(half.len()).any(|w| w == half.as_slice()), "{:?} is half float", std::str::from_utf8(name)); + } + let (code, reply) = run_json(&["render", "--project", p, "--exr-depth", "8", "--out", out.to_str().unwrap()]); + assert_eq!(code, 1, "{reply}"); + assert!(reply["error"].as_str().unwrap().contains("exrBitDepth: half|float"), "{reply}"); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn replay_reports_steps_and_the_first_failure() { + let repro = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/repros/comp-zero-frame-rate.jsonl"); + let v = ok_json(&["replay", repro.to_str().unwrap()]); + assert_eq!(v["ok"], true, "{v}"); + assert!(v["steps"].as_array().unwrap().len() > 5); + let bad = tmp("bad-repro.jsonl"); + std::fs::write( + &bad, + "{\"start\": \"new\"}\n{\"command\": \"comp.new\"}\n{\"expect\": {\"query\": \"comp.info\", \"pointer\": \"/width\", \"equals\": 1}}\nnot json\n", + ) + .unwrap(); + let (code, v) = run_json(&["replay", bad.to_str().unwrap()]); + assert_eq!(code, 1); + assert_eq!(v["ok"], false); + assert_eq!(v["first_failure"]["line"], 3, "{v}"); + assert_eq!(v["skipped"], 1); + let out = bin().args(["replay", bad.to_str().unwrap(), "--keep-going"]).output().unwrap(); + assert_eq!(out.status.code(), Some(1)); + let text = String::from_utf8_lossy(&out.stdout); + assert!(text.contains("line 2 ok comp.new") && text.contains("line 4 FAIL invalid: not JSON"), "{text}"); + assert!(String::from_utf8_lossy(&out.stderr).contains("failed at line 3 (comp.info)")); + // The start line picks the project. + assert_eq!(bin().args(["replay", bad.to_str().unwrap(), "--demo"]).output().unwrap().status.code(), Some(2)); +} + +/// Text editors can prefix an exported JSON-lines repro with a UTF-8 BOM. +#[test] +fn replay_accepts_a_utf8_bom() { + let path = tmp("bom-repro.jsonl"); + std::fs::write(&path, "\u{feff}{\"command\":\"comp.new\"}\n").unwrap(); + let (code, report) = run_json(&["replay", path.to_str().unwrap()]); + assert_eq!(code, 0, "{report}"); + assert_eq!(report["ok"], true); +} diff --git a/apps/effectcraft-web/src/app.rs b/apps/effectcraft-web/src/app.rs index 2882b16cf..99e71117f 100644 --- a/apps/effectcraft-web/src/app.rs +++ b/apps/effectcraft-web/src/app.rs @@ -329,7 +329,7 @@ pub async fn start(canvas_id: String) -> Result<(), JsValue> { if n > 0 { app.frames.set_remote(Some(Arc::new(frames::WebFrames::start(n, !query_flag("nogpuworkers"))))); } - app.frames.set_virtual_media(files::STORE.media_epoch(), Arc::new(|path| files::STORE.file_identity(path))); + app.frames.set_virtual_id(Arc::new(|path| files::STORE.file_identity(path))); let (tx, rx) = std::sync::mpsc::channel(); api::set_sender(tx); app = app.with_control(rx); diff --git a/apps/effectcraft-web/src/diskcache.rs b/apps/effectcraft-web/src/diskcache.rs index ef9d46f8c..72e9a9e11 100644 --- a/apps/effectcraft-web/src/diskcache.rs +++ b/apps/effectcraft-web/src/diskcache.rs @@ -4,23 +4,28 @@ //! //! - **Writes** happen in the frame workers: a render request carries the frame's disk-cache key //! (`effectcraft_engine::remote::FrameMsg::Render`), the worker posts the frame, then writes -//! the sealed entry (`disk_cache::frame_entry`: LZ4, checksum) with a synchronous access -//! handle into a temporary file moved into place (`js/host.js` `cacheWrite`), and reports -//! `FrameReply::Stored`. +//! the sealed entry (`disk_cache::frame_entry`: the source files the frame read, LZ4, +//! checksum) with a synchronous access handle into a temporary file moved into place +//! (`js/host.js` `cacheWrite`), and reports `FrameReply::Stored`. A frame whose files can't +//! all be named is not stored. //! - **The index** lives here, on the page ([`DiskIndex`], shared with the desktop's cache): //! rebuilt at startup from the folder listing (oldest files first), updated by the workers' //! `Stored` replies and by reads; eviction deletes the least recently used files. //! - **Reads** are asynchronous: a frame whose key is indexed is read and decoded here instead -//! of rendering it (`crate::frames`); a damaged or missing file is a miss and is forgotten. +//! of rendering it (`crate::frames`), if the files its entry lists still have the size and +//! content hash it was made of (the file table's identities); a damaged or missing entry, or +//! one whose files changed, is a miss and is deleted. //! //! - **Layer buffers** too (`layers/<32 hex>.ecc`): a layer lookup happens in the middle of a //! synchronous render, where the browser's file system can't be read, so the frame workers //! back their layer caches with a `PrefetchStore`. They report each frame's layer-cache //! misses; before the next request the page names the recent misses that are on disk //! ([`layer_prefetch`], `disk_cache::LayerPrefetch`), and the worker reads those entries -//! into memory before rendering, so the lookups find them. Slow buffers are written by the -//! worker after its frame and indexed here like frames (one least-recently-used order for -//! both kinds). +//! into memory before rendering, so the lookups find them; an entry is used only while the +//! files it lists (the file table's size and content hash) are unchanged, and a buffer whose +//! files can't all be named is not written (#3184). Slow buffers are written by the worker +//! after its frame and indexed here like frames (one least-recently-used order for both +//! kinds). use std::cell::RefCell; @@ -187,11 +192,12 @@ pub fn note_miss() { } /// Read and decode a cached frame; `None` (forgotten and deleted) when the file is missing or -/// damaged. +/// damaged, or the source files it was made of changed since. pub async fn read(key: u128) -> Option { let name = disk_cache::entry_name(key); let bytes = JsFuture::from(cache_read(&name)).await.ok().and_then(|b| b.dyn_into::().ok()).map(|b| b.to_vec()); - let frame = bytes.as_deref().and_then(disk_cache::read_frame_entry); + let identity = |path: &str| crate::files::STORE.file_identity(path); + let frame = bytes.as_deref().and_then(|b| disk_cache::read_frame_entry(b, Some(&identity))); ST.with(|s| { let mut s = s.borrow_mut(); if frame.is_some() { diff --git a/apps/effectcraft-web/src/frames.rs b/apps/effectcraft-web/src/frames.rs index 69089e308..0159fe23b 100644 --- a/apps/effectcraft-web/src/frames.rs +++ b/apps/effectcraft-web/src/frames.rs @@ -473,10 +473,13 @@ pub async fn worker_frame(json: String) { g.settled().await; replies = SERVER.with(|c| c.borrow_mut().as_mut().map(|s| s.resume()).unwrap_or_default()); } + // The source files the frame read, kept with its entry (checked by the page before use); a + // frame whose files can't all be named is not stored (#3184). + let (files, virtual_id) = SERVER.with(|c| c.borrow_mut().as_mut().map(|s| (s.take_files(), s.virtual_id().cloned())).unwrap_or_default()); for (r, px) in replies { post_reply(&r, px.as_deref()); - if let (FrameReply::Frame { width, height, .. }, Some(px), Some(key)) = (&r, &px, &disk) { - let entry = effectcraft_engine::render::disk_cache::frame_entry(*width, *height, px); + if let (FrameReply::Frame { width, height, .. }, Some(px), Some(key), Some(files)) = (&r, &px, &disk, &files) { + let Some(entry) = effectcraft_engine::render::disk_cache::frame_entry(*width, *height, px, files, virtual_id.as_deref()) else { continue }; let name = format!("{key}.ecc"); match JsFuture::from(crate::diskcache::cache_write(&name, js_sys::Uint8Array::from(&entry[..]))).await { Ok(n) => post_reply(&FrameReply::Stored { key: key.clone(), bytes: n.as_f64().unwrap_or(entry.len() as f64) as u64, layer: false }, None), diff --git a/apps/effectcraft-web/src/store.rs b/apps/effectcraft-web/src/store.rs index 0cc877948..a4947600b 100644 --- a/apps/effectcraft-web/src/store.rs +++ b/apps/effectcraft-web/src/store.rs @@ -20,7 +20,6 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use effectcraft_engine::config::{ConfigStore, FileOps}; @@ -187,13 +186,12 @@ pub struct Store { pub on_change: OnceLock, /// Clock in milliseconds since the Unix epoch (tests pin it). pub clock: OnceLock f64>, - /// Bumped when a virtual file is written. Preview cache lookups key on it; they do not hash. - media_epoch: Arc, } impl Default for Store { + /// An empty store with no mirror contents, change callback or clock. fn default() -> Self { - Self { mirror: Mutex::default(), on_change: OnceLock::new(), clock: OnceLock::new(), media_epoch: Arc::new(AtomicU64::new(0)) } + Self { mirror: Mutex::default(), on_change: OnceLock::new(), clock: OnceLock::new() } } } @@ -218,22 +216,12 @@ impl Store { pub fn put_file(&self, path: &str, data: Arc<[u8]>, persist: bool) { let now = self.now(); let key = file_key(path); - let replaced = self.lock().get(&key).is_none_or(|e| !Arc::ptr_eq(&e.data, &data)); self.lock().put(&key, data, now, persist); - if replaced { - self.media_epoch.fetch_add(1, Ordering::Relaxed); - } if persist { self.changed(); } } - /// The generation preview cache lookups key on. It changes when [`Self::put_file`] writes - /// a different blob, and it is not a content hash. - pub fn media_epoch(&self) -> Arc { - self.media_epoch.clone() - } - /// Size and content hash of the file under `path`. The hash is stored on the entry so a /// later key does not walk the bytes again. pub fn file_identity(&self, path: &str) -> Option<(u64, u64)> { @@ -541,11 +529,9 @@ mod tests { assert_ne!(a, b); assert_eq!(&data[..], b"blue"); assert_eq!(s.file_versioned("/collision.png").map(|f| f.1), Some(b), "reading doesn't change it"); - let epoch = s.media_epoch().load(Ordering::Relaxed); let id = s.file_identity("/collision.png").expect("identity"); assert_eq!(id, (4, content_hash(b"blue"))); assert_eq!(s.file_identity("/collision.png"), Some(id), "the hash is kept on the entry"); - assert!(epoch >= 2, "each new blob bumps the generation the preview keys on"); } /// A write that failed is flushed again with the key's latest state (#215). diff --git a/apps/effectcraft/Cargo.toml b/apps/effectcraft/Cargo.toml index 3030ee96d..21bd46755 100644 --- a/apps/effectcraft/Cargo.toml +++ b/apps/effectcraft/Cargo.toml @@ -25,6 +25,9 @@ rfd = { workspace = true } pollster = { workspace = true } cpal = { workspace = true } log = { workspace = true } +chrono = { workspace = true } +# MIT; safe process handles and target-only memory observation for the crash helper. +sysinfo = { version = "=0.37.2", default-features = false, features = ["system"] } [target.'cfg(target_os = "linux")'.dependencies] # Native GNOME/Wayland controls without a bundled title font. diff --git a/apps/effectcraft/src/crash_observation.rs b/apps/effectcraft/src/crash_observation.rs new file mode 100644 index 000000000..b67dc07fe --- /dev/null +++ b/apps/effectcraft/src/crash_observation.rs @@ -0,0 +1,264 @@ +//! Bounded observations made outside the failed GUI. Measurements are evidence, not a cause. +use std::io::{self, Write}; +use std::sync::mpsc::{self, Receiver}; +use std::time::{Duration, Instant, SystemTime}; + +use sysinfo::{MemoryRefreshKind, Pid, ProcessRefreshKind, ProcessesToUpdate, System}; + +pub fn utc() -> String { + chrono::DateTime::::from(SystemTime::now()).to_rfc3339_opts(chrono::SecondsFormat::Millis, true) +} + +#[derive(Default)] +struct Memory { + samples: u64, + resident_peak: u64, + virtual_peak: u64, + available_min: Option, + total: u64, + last_at: Option, + last_uptime_secs: Option, +} + +impl Memory { + fn sample(&mut self, resident: u64, virtual_bytes: u64, available: u64, total: u64) { + self.samples = self.samples.saturating_add(1); + self.resident_peak = self.resident_peak.max(resident); + self.virtual_peak = self.virtual_peak.max(virtual_bytes); + // Zero total means the platform could not supply physical-memory information. + if total != 0 { + self.available_min = Some(self.available_min.map_or(available, |old| old.min(available))); + self.total = total; + } + self.last_at = Some(utc()); + } +} + +pub struct Observation { + pid: Pid, + system: System, + birth: Option, + started: Instant, + started_at: String, + detected_at: Option, + last_sample: Instant, + memory: Memory, + // Only Windows can retrieve an unrelated process's ExitStatus through a retained handle. + exit: Receiver>, + status: Option, + alive: Option, +} + +fn target_system(pid: Pid) -> System { + let mut system = System::new(); + system.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), false, ProcessRefreshKind::nothing().with_memory()); + system +} + +impl Observation { + /// Acquire the Windows handle before acknowledging reporter readiness, so even an immediate + /// GUI abort leaves an observable process object. Never enumerate commands or environments. + pub fn start(pid: u32) -> Self { + let pid = Pid::from_u32(pid); + let system = target_system(pid); + let birth = system.process(pid).map(|p| p.start_time()); + let (send, exit) = mpsc::sync_channel(1); + #[cfg(windows)] + { + let waiting = target_system(pid); + let _ = std::thread::Builder::new().name("ec-exit-status".into()).spawn(move || { + let status = waiting.process(pid).and_then(|p| p.wait()); + let _ = send.send(status); + }); + } + #[cfg(not(windows))] + drop(send); + let now = Instant::now(); + let mut result = Self { + pid, + system, + birth, + started: now, + started_at: utc(), + detected_at: None, + last_sample: now, + memory: Memory::default(), + exit, + status: None, + alive: None, + }; + result.sample(); + result + } + + fn sample(&mut self) { + self.system.refresh_processes_specifics(ProcessesToUpdate::Some(&[self.pid]), false, ProcessRefreshKind::nothing().with_memory()); + self.system.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram()); + let process = self.system.process(self.pid).filter(|p| Some(p.start_time()) == self.birth && p.exists()); + self.alive = self.birth.map(|_| process.is_some()); + if let Some(process) = process { + self.memory.last_uptime_secs = Some(process.run_time()); + self.memory.sample(process.memory(), process.virtual_memory(), self.system.available_memory(), self.system.total_memory()); + } + if let Ok(status) = self.exit.try_recv() { + self.status = status; + } + self.last_sample = Instant::now(); + } + + pub fn tick(&mut self) { + if self.last_sample.elapsed() >= Duration::from_secs(1) { + self.sample(); + } + } + + /// Pipe closure can precede the OS signalling process termination. Bound that grace period; + /// a broken pipe or early reporter drop must never be called a confirmed process exit. + pub fn finish(&mut self) { + self.detected_at = Some(utc()); + if self.status.is_none() + && let Ok(status) = self.exit.recv_timeout(Duration::from_millis(750)) + { + self.status = status; + } + self.sample(); + } + + pub fn confirmed_exit(&self) -> bool { + self.status.is_some() + } + + pub fn write(&self, report: &mut impl Write) -> io::Result<()> { + writeln!( + report, + "Detection UTC: {}\nObserver started UTC: {}\nObserved duration: {} ms", + self.detected_at.as_deref().unwrap_or("not captured"), + self.started_at, + self.started.elapsed().as_millis() + )?; + writeln!( + report, + "Process observation: {}", + if self.confirmed_exit() { + "process termination observed" + } else if self.alive == Some(true) { + "GUI still present when the control channel ended" + } else { + "target absent from refresh or process identity/status unavailable (not proof of termination)" + } + )?; + match &self.status { + Some(status) => { + writeln!(report, "OS exit status: {status}")?; + #[cfg(windows)] + if let Some(code) = status.code() { + write_windows_status(report, code as u32)?; + } + } + None => writeln!(report, "OS exit status: unavailable (not inferred from the control pipe)")?, + } + let memory = &self.memory; + writeln!(report, "\nMemory evidence (1 s sampling; sampled maxima, not OS peaks):\nTarget-present sampling attempts: {}", memory.samples)?; + if let Some(uptime) = memory.last_uptime_secs { + writeln!(report, "GUI uptime at last target-present observation: {uptime} s")?; + } + #[cfg(windows)] + let virtual_label = "Peak sampled private committed bytes"; + #[cfg(not(windows))] + let virtual_label = "Peak sampled virtual bytes"; + if memory.samples != 0 { + writeln!( + report, + "Last target sampling attempt UTC: {}\nPeak sampled resident bytes: {}\n{virtual_label}: {}", + memory.last_at.as_deref().unwrap_or("unavailable"), + memory.resident_peak, + memory.virtual_peak + )?; + } + if let Some(available) = memory.available_min { + writeln!(report, "Minimum sampled system available RAM bytes: {available}\nSystem total RAM bytes at last sample: {}", memory.total)?; + } + writeln!( + report, + "Samples can miss short spikes or retain stale/zero readings when an OS query fails; per-field success is not exposed by sysinfo. Windows private commit is not GPU VRAM; on other platforms virtual memory is not physical RAM. System commit limit/usage and GPU memory budgets were not collected. No memory-pressure threshold establishes the cause of this incident.\nThe memory observer does not collect process command lines, environments, documents, native dumps or system event logs. The existing session-log tail below may contain paths or other logged details; review it before sharing." + ) + } +} + +#[cfg(any(windows, test))] +fn write_windows_status(report: &mut impl Write, code: u32) -> io::Result<()> { + let meaning = match code { + 0xc0000005 => "STATUS_ACCESS_VIOLATION", + 0xc0000017 => "STATUS_NO_MEMORY", + 0xc000012d => "STATUS_COMMITMENT_LIMIT", + 0xc0000374 => "STATUS_HEAP_CORRUPTION", + 0xc0000409 => "STATUS_STACK_BUFFER_OVERRUN / fast fail", + 0x40000015 => "STATUS_FATAL_APP_EXIT", + _ => "unclassified", + }; + writeln!( + report, + "Windows status bits: 0x{code:08X} ({meaning})\nThese are process exit bits, not a verified exception record. Software can set an exit code explicitly; an access violation does not identify the faulting module or prove a driver crash." + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn missing_target_without_exit_status_does_not_confirm_termination() { + let (send, exit) = mpsc::sync_channel(1); + drop(send); + let now = Instant::now(); + let observation = Observation { + pid: Pid::from_u32(1), + system: System::new(), + birth: Some(1), + started: now, + started_at: utc(), + detected_at: Some(utc()), + last_sample: now, + memory: Memory::default(), + exit, + status: None, + alive: Some(false), + }; + assert!(!observation.confirmed_exit()); + let mut report = Vec::new(); + observation.write(&mut report).unwrap(); + let report = String::from_utf8(report).unwrap(); + assert!(report.contains("not proof of termination")); + assert!(!report.contains("process termination observed")); + } + + #[test] + fn memory_high_water_marks_are_bounded_and_not_a_causal_diagnosis() { + let mut memory = Memory::default(); + memory.sample(40, 80, 30, 100); + memory.sample(20, 90, 50, 100); + assert_eq!((memory.samples, memory.resident_peak, memory.virtual_peak, memory.available_min), (2, 40, 90, Some(30))); + memory.sample(0, 0, 0, 0); + assert_eq!(memory.available_min, Some(30)); + } + + #[test] + fn windows_status_bits_preserve_unsigned_codes_without_claiming_a_driver_crash() { + for (code, name) in + [(0xc0000005, "STATUS_ACCESS_VIOLATION"), (0xc0000017, "STATUS_NO_MEMORY"), (0xc000012d, "STATUS_COMMITMENT_LIMIT"), (42, "unclassified")] + { + let mut text = Vec::new(); + write_windows_status(&mut text, code).unwrap(); + let text = String::from_utf8(text).unwrap(); + assert!(text.contains(name)); + assert!(text.contains(&format!("0x{code:08X}"))); + assert!(text.contains("not a verified exception record")); + } + } + + #[test] + fn utc_timestamps_are_parseable_and_zero_offset() { + let time = chrono::DateTime::parse_from_rfc3339(&utc()).unwrap(); + assert_eq!(time.offset().local_minus_utc(), 0); + } +} diff --git a/apps/effectcraft/src/crash_report.rs b/apps/effectcraft/src/crash_report.rs new file mode 100644 index 000000000..6ca42aab7 --- /dev/null +++ b/apps/effectcraft/src/crash_report.rs @@ -0,0 +1,797 @@ +//! A small, separate process reports an unexpected desktop exit (#3357). +//! +//! Allocation failure can abort without a panic hook. The GUI therefore owns a pipe to a +//! helper which never loads a project, font database or GPU. Only an explicit marker after +//! normal teardown suppresses the report. EOF alone identifies a lost control channel, not +//! a process exit or its cause. System-wide exhaustion can still prevent the helper or its native dialog working. + +use std::collections::VecDeque; +use std::ffi::{OsStr, OsString}; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{self, RecvTimeoutError}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +#[path = "crash_observation.rs"] +mod observation; + +const FLAG: &str = "--internal-crash-reporter"; +const CLEAN: &[u8] = b"EFFECTCRAFT_CLEAN_EXIT_V1\n"; +const LOG_BYTES: usize = 64 * 1024; +const HEADER_BYTES: usize = 128; +const READY: &[u8] = b"READY\n"; +const EVENT_BYTES: usize = 128; +const EVENT_COUNT: usize = 32; + +/// Owned only by the GUI, never handed to another child. Dropping it without `finish` closes +/// the pipe and reports the incident; there is intentionally no clean-exit Drop hook. +pub struct Reporter { + pipe: ChildStdin, + child: Child, +} + +impl Reporter { + /// Call only after application teardown, including handled startup/device-loss errors. + pub fn finish(mut self) -> io::Result<()> { + let sent = self.pipe.write_all(CLEAN).and_then(|()| self.pipe.flush()); + drop(self.pipe); + // Do not let a suspended/broken helper hang shutdown. Reap it before the GUI + // exits where possible, so Windows updates do not race an old executable. + let cleanup = finish_child(&mut self.child, Duration::from_secs(2)); + match (sent, cleanup) { + (Err(sent), Err(cleanup)) => Err(io::Error::other(format!("clean marker failed: {sent}; cleanup failed: {cleanup}"))), + (Err(error), _) | (_, Err(error)) => Err(error), + (Ok(()), Ok(())) => Ok(()), + } + } +} + +fn finish_child(child: &mut Child, grace: Duration) -> io::Result<()> { + let start = Instant::now(); + while start.elapsed() < grace { + if let Some(status) = child.try_wait()? { + return if status.success() { Ok(()) } else { Err(io::Error::other(format!("crash reporter exited with {status}"))) }; + } + std::thread::sleep(Duration::from_millis(20)); + } + child.kill()?; + // Even after termination, do not introduce an unbounded wait on a stuck OS process. + let start = Instant::now(); + while start.elapsed() < Duration::from_secs(1) { + if child.try_wait()?.is_some() { + return Err(io::Error::other("crash reporter did not finish promptly and was terminated")); + } + std::thread::sleep(Duration::from_millis(20)); + } + Err(io::Error::other("crash reporter termination could not be confirmed")) +} + +/// Shared ownership lets macOS finish in on_exit, while main retains the startup-error path. +#[derive(Clone, Default)] +pub struct Shutdown(std::sync::Arc>>); + +impl Shutdown { + /// Install the one reporter created for this desktop launch. + pub fn install(&self, reporter: Reporter) -> io::Result<()> { + let mut slot = self.0.lock().map_err(|_| io::Error::other("crash reporter ownership was poisoned"))?; + *slot = Some(reporter); + Ok(()) + } + + /// Keep only fixed-vocabulary, bounded lifecycle facts outside the GUI. Callers emit each + /// category once; their combined payload fits well below the smallest OS pipe buffer. + pub fn record(&self, event: &'static str) -> io::Result<()> { + if event.len() > 100 || event.contains(['\n', '\r']) { + return Err(io::Error::other("invalid diagnostic observation")); + } + let mut slot = self.0.lock().map_err(|_| io::Error::other("crash reporter ownership was poisoned"))?; + if let Some(reporter) = slot.as_mut() { + writeln!(reporter.pipe, "EVENT {event}")?; + reporter.pipe.flush()?; + } + Ok(()) + } + + /// Consume the reporter exactly once, after the applicable platform teardown boundary. + pub fn finish(&self) -> io::Result<()> { + let reporter = self.0.lock().map_err(|_| io::Error::other("crash reporter ownership was poisoned"))?.take(); + reporter.map_or(Ok(()), Reporter::finish) + } +} + +/// A panic during teardown must leave the reporter armed. macOS terminates after this hook +/// without returning to main; other platforms pass None and finish after run_native returns. +pub fn after_teardown(reporter: Option<&Shutdown>, teardown: impl FnOnce()) -> io::Result<()> { + teardown(); + reporter.map_or(Ok(()), Shutdown::finish) +} + +/// Each process/run has its own report, including simultaneous launches. +pub fn run_id() -> String { + let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos(); + format!("{}-{nanos}", std::process::id()) +} + +pub fn session_marker(id: &str) -> String { + format!("crash-report session {id}") +} + +/// Start before heavy work. A missing helper is a warning, never a reason to refuse the app. +pub fn start(id: &str, log: Option<&Path>, reports: &Path, interactive: bool) -> io::Result { + let exe = std::env::current_exe()?; + let args = [ + OsString::from(FLAG), + OsString::from(id), + log.map_or_else(OsString::new, |p| p.as_os_str().to_owned()), + reports.as_os_str().to_owned(), + OsString::from(if interactive { "1" } else { "0" }), + OsString::from(std::process::id().to_string()), + ]; + spawn(&exe, &args) +} + +fn spawn(exe: &Path, args: &[OsString]) -> io::Result { + let mut child = Command::new(exe).args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?; + if let Err(error) = ready(&mut child) { + let _ = child.kill(); + let _ = finish_child(&mut child, Duration::from_millis(100)); + return Err(error); + } + match child.stdin.take() { + Some(pipe) => Ok(Reporter { pipe, child }), + None => { + let _ = child.kill(); + let _ = child.wait(); + Err(io::Error::other("crash reporter has no control pipe")) + } + } +} + +/// A fixed acknowledgement means the helper holds the process observation before heavy GUI +/// work begins. A suspended helper cannot hold startup indefinitely. +fn ready(child: &mut Child) -> io::Result<()> { + let mut output = child.stdout.take().ok_or_else(|| io::Error::other("crash reporter has no readiness pipe"))?; + let (send, receive) = mpsc::sync_channel(1); + std::thread::Builder::new().name("ec-reporter-ready".into()).spawn(move || { + let mut bytes = [0; READY.len()]; + #[cfg(not(test))] + let result = + output.read_exact(&mut bytes).and_then(|()| if bytes == READY { Ok(()) } else { Err(io::Error::other("invalid reporter acknowledgement")) }); + // libtest prints its bounded banner before invoking the helper role. + #[cfg(test)] + let result = (|| { + for _ in 0..1024 { + bytes.rotate_left(1); + output.read_exact(&mut bytes[READY.len() - 1..])?; + if bytes == READY { + return Ok(()); + } + } + Err(io::Error::other("reporter acknowledgement missing")) + })(); + let _ = send.send(result); + // Keep the pipe open for libtest's trailing result (and future helper output), without + // storing it. Dropping it at READY would turn a clean helper exit into BrokenPipe. + let _ = io::copy(&mut output, &mut io::sink()); + })?; + receive.recv_timeout(Duration::from_secs(3)).map_err(|_| io::Error::other("crash reporter readiness timed out"))? +} + +/// Handle the internal mode before logging, argument parsing, updates or GUI initialization. +/// The callback is a native dialog on this helper's main thread, not on the failed GUI's. +pub fn maybe_run(args: &[OsString], show: impl FnOnce(&str)) -> bool { + if args.first().map(OsString::as_os_str) != Some(OsStr::new(FLAG)) { + return false; + } + let parsed = match args { + [_, id, log, reports, interactive, pid] => id + .to_str() + .filter(|id| valid_id(id)) + .zip(match interactive.to_str() { + Some("0") => Some(false), + Some("1") => Some(true), + _ => None, + }) + .zip(pid.to_str().and_then(|p| p.parse::().ok()).filter(|pid| *pid != 0)) + .map(|((id, interactive), pid)| (id, (!log.is_empty()).then(|| Path::new(log)), Path::new(reports), interactive, pid)), + _ => None, + }; + let Some((id, log, reports, interactive, pid)) = parsed else { + eprintln!("EffectCraft crash reporter: invalid internal arguments"); + return true; + }; + // Keep the exact file open while the GUI is alive: a later rotation must not substitute + // another instance's log. If rotation won the startup race, the session marker rejects it. + let mut log = SessionLog::open(log, id); + let mut observation = observation::Observation::start(pid); + // A GUI that dies during helper startup can already have closed this read end. Keep + // watching its control pipe and save the report rather than losing that early failure. + let _ = io::stdout().write_all(READY).and_then(|()| io::stdout().flush()); + // The reader has one bounded queue; the monitor never waits on a live pipe, so it can + // sample the target even when no log or lifecycle message is emitted. + let (send, receive) = mpsc::sync_channel(1); + let reader = std::thread::Builder::new().name("ec-reporter-pipe".into()).spawn(move || { + let mut input = io::stdin().lock(); + loop { + let message = read_message(&mut input); + let terminal = !matches!(message, Ok(Message::Event(_))); + if send.send(message).is_err() || terminal { + break; + } + } + }); + let mut events = VecDeque::with_capacity(EVENT_COUNT); + let failure = if reader.is_err() { + Some("control reader could not start".to_owned()) + } else { + loop { + observation.tick(); + match receive.recv_timeout(Duration::from_millis(250)) { + Ok(Ok(Message::Clean)) => return true, + Ok(Ok(Message::Event(event))) => { + if events.len() == EVENT_COUNT { + events.pop_front(); + } + events.push_back(format!("{} {event}", observation::utc())); + } + Ok(Ok(Message::Ended)) => break None, + Ok(Err(error)) => break Some(error.to_string()), + Err(RecvTimeoutError::Timeout) => continue, + Err(RecvTimeoutError::Disconnected) => break Some("control reader disconnected".to_owned()), + } + } + }; + observation.finish(); + let saved = write_report(reports, id, &mut log, failure.as_deref(), &observation, &events); + let description = description(&saved, observation.confirmed_exit()); + eprintln!("{description}"); + if interactive { + show(&description); + } + true +} + +fn valid_id(id: &str) -> bool { + !id.is_empty() && id.len() <= 80 && id.bytes().all(|c| c.is_ascii_digit() || c == b'-') +} + +enum Message { + Clean, + Event(String), + Ended, +} + +/// Every line and the retained event ring are bounded, including malformed control input. +fn read_message(input: &mut impl Read) -> io::Result { + let mut line = [0u8; EVENT_BYTES]; + for i in 0..line.len() { + let byte = line.get_mut(i).ok_or_else(|| io::Error::other("invalid control offset"))?; + loop { + match input.read(std::slice::from_mut(byte)) { + Ok(0) => return Ok(Message::Ended), + Ok(_) => break, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + } + } + if *byte == b'\n' { + let text = line.get(..=i).ok_or_else(|| io::Error::other("invalid control line"))?; + if text == CLEAN { + return Ok(Message::Clean); + } + if let Some(event) = text.strip_prefix(b"EVENT ") { + let event = std::str::from_utf8(event).map_err(|_| io::Error::other("non-UTF8 diagnostic observation"))?; + return Ok(Message::Event(event.trim_end().to_owned())); + } + return Ok(Message::Ended); + } + } + Err(io::Error::other("control line exceeded its fixed limit")) +} + +#[cfg(test)] +fn clean_exit(input: &mut impl Read) -> io::Result { + Ok(matches!(read_message(input)?, Message::Clean)) +} + +enum SessionLog { + Captured { file: File, marker: String }, + Unavailable(String), +} + +impl SessionLog { + fn open(path: Option<&Path>, id: &str) -> Self { + let opened = (|| { + let path = path.ok_or_else(|| io::Error::other("no session log was opened"))?; + let mut file = File::open(path)?; + let mut header = [0u8; HEADER_BYTES]; + let marker = format!("{}\n", session_marker(id)); + let prefix = header.get_mut(..marker.len()).ok_or_else(|| io::Error::other("session marker too long"))?; + file.read_exact(prefix)?; + if prefix != marker.as_bytes() { + return Err(io::Error::other("matching session marker unavailable; the log may have rotated")); + } + Ok(file) + })(); + match opened { + Ok(file) => Self::Captured { file, marker: format!("{}\n", session_marker(id)) }, + Err(e) => Self::Unavailable(e.to_string()), + } + } + + fn write_tail(&mut self, report: &mut File) -> io::Result<()> { + match self { + Self::Unavailable(reason) => writeln!(report, "Recent log unavailable: {reason}"), + Self::Captured { file, marker } => { + // An older concurrent launcher may have truncated the captured file. + // Recheck its identity before copying any content into this report. + file.seek(SeekFrom::Start(0))?; + let mut header = [0u8; HEADER_BYTES]; + let prefix = header.get_mut(..marker.len()).ok_or_else(|| io::Error::other("session marker too long"))?; + if file.read_exact(prefix).is_err() || prefix != marker.as_bytes() { + return writeln!(report, "Recent log unavailable: session identity changed"); + } + let size = file.metadata()?.len(); + file.seek(SeekFrom::Start(size.saturating_sub(LOG_BYTES as u64)))?; + writeln!(report, "\nRecorded session log tail (last {LOG_BYTES} bytes at most; logging filters/size caps may omit later events):")?; + io::copy(&mut file.take(LOG_BYTES as u64), report)?; + Ok(()) + } + } + } +} + +fn write_report( + reports: &Path, + id: &str, + log: &mut SessionLog, + pipe_error: Option<&str>, + observation: &observation::Observation, + events: &VecDeque, +) -> io::Result { + if !valid_id(id) { + return Err(io::Error::other("invalid report identity")); + } + std::fs::create_dir_all(reports)?; + let path = reports.join(format!("crash-{id}.txt")); + let mut report = OpenOptions::new().write(true).create_new(true).open(&path)?; + writeln!( + report, + "EffectCraft unexpected-exit diagnostic\nVersion: {}\nPlatform: {} / {}\nSession: {id}", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS, + std::env::consts::ARCH + )?; + writeln!( + report, + "The GUI control channel ended without its clean-exit marker.\nThe exact cause is not established. GPU fallback, memory pressure and process exit are separate observations, not a proven causal chain.\nThis report was saved locally; it was not sent anywhere." + )?; + observation.write(&mut report)?; + writeln!(report, "\nRetained lifecycle observations (last {EVENT_COUNT}; UTC is helper receipt time):")?; + for event in events { + writeln!(report, "{event}")?; + } + if let Some(error) = pipe_error { + writeln!(report, "Control pipe error: {error}")?; + } + if let Err(error) = log.write_tail(&mut report) { + writeln!(report, "\nCould not read the recent session log: {error}")?; + } + report.flush()?; + Ok(path) +} + +fn description(saved: &io::Result, confirmed_exit: bool) -> String { + let diagnostic = match saved { + Ok(path) => format!("A diagnostic report was saved to:\n{}", path.display()), + Err(error) => format!("A diagnostic report could not be saved: {error}"), + }; + let incident = + if confirmed_exit { "EffectCraft stopped unexpectedly." } else { "EffectCraft lost its diagnostic control channel; process exit is not confirmed." }; + format!( + "{incident}\n\n{diagnostic}\n\nThe exact cause is unknown. If EffectCraft has closed, reopen it to check for an existing auto-save. Changes since the last auto-save may be lost.\n\nNo report has been sent anywhere." + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::thread; + use std::time::{Duration, Instant}; + + static NEXT: AtomicUsize = AtomicUsize::new(0); + const ROLE: &str = "EFFECTCRAFT_CRASH_REPORT_TEST_ROLE"; + + fn test_report(dir: &Path, id: &str, log: &mut SessionLog) -> io::Result { + write_report(dir, id, log, None, &observation::Observation::start(std::process::id()), &VecDeque::new()) + } + + fn folder() -> PathBuf { + let p = std::env::temp_dir().join(format!("ec-crash-report-{}-{}", run_id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir_all(&p).unwrap(); + p + } + + fn test_name(name: &str) -> String { + // Also usable from an isolated harness with the reporter dependencies. + let prefix = module_path!().split_once("::").map_or("", |(_, rest)| rest); + format!("{prefix}::{name}") + } + + fn helper(dir: &Path, id: &str) -> Reporter { + helper_mode(dir, id, false) + } + + fn helper_mode(dir: &Path, id: &str, interactive: bool) -> Reporter { + let mut child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &test_name("reporter_process"), "--ignored", "--nocapture"]) + .env(ROLE, "reporter") + .env("EC_REPORT_DIR", dir) + .env("EC_REPORT_ID", id) + .env("EC_REPORT_INTERACTIVE", if interactive { "1" } else { "0" }) + .env("EC_REPORT_PID", std::process::id().to_string()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + ready(&mut child).unwrap(); + Reporter { pipe: child.stdin.take().unwrap(), child } + } + + fn wait_file(path: &Path) { + let until = Instant::now() + Duration::from_secs(10); + while !path.is_file() && Instant::now() < until { + thread::sleep(Duration::from_millis(20)); + } + assert!(path.is_file(), "report did not arrive: {}", path.display()); + } + + #[test] + fn bounded_protocol_rejects_eof_and_partial_or_wrong_markers() { + let mut clean = CLEAN; + assert!(clean_exit(&mut clean).unwrap()); + for mut input in [b"".as_slice(), &CLEAN[..CLEAN.len() - 1], b"clean", b"EFFECTCRAFT_CLEAN_EXIT_V0\n"] { + assert!(!clean_exit(&mut input).unwrap()); + } + assert!(clean_exit(&mut &vec![b'x'; 100_000][..]).is_err()); + } + + #[test] + fn report_is_bounded_and_keeps_its_session_after_log_rotation() { + let dir = folder(); + let original = dir.join("effectcraft.log"); + let id = "123-456"; + std::fs::write(&original, format!("{}\n", session_marker(id))).unwrap(); + let mut log = SessionLog::open(Some(&original), id); + std::fs::rename(&original, dir.join("effectcraft.1.log")).unwrap(); + std::fs::write(&original, "OTHER SESSION MUST NOT APPEAR").unwrap(); + let mut old = OpenOptions::new().append(true).open(dir.join("effectcraft.1.log")).unwrap(); + old.write_all(&vec![b'a'; LOG_BYTES * 2]).unwrap(); + old.write_all(b"\nGPU context retired\n").unwrap(); + let report = test_report(&dir, id, &mut log).unwrap(); + let text = std::fs::read_to_string(report).unwrap(); + assert!(text.len() < LOG_BYTES + 4096); + assert!(text.contains("GPU context retired")); + assert!(!text.contains("OTHER SESSION")); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn wrong_session_and_missing_logs_are_reported_without_reading_other_content() { + let dir = folder(); + let path = dir.join("log"); + std::fs::write(&path, "private other session").unwrap(); + for (id, source) in [("1-1", Some(path.as_path())), ("1-2", None)] { + let report = test_report(&dir, id, &mut SessionLog::open(source, id)).unwrap(); + let text = std::fs::read_to_string(report).unwrap(); + assert!(text.contains("Recent log unavailable")); + assert!(!text.contains("private other session")); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn captured_log_rejects_a_session_overwritten_after_open() { + let dir = folder(); + let path = dir.join("log"); + std::fs::write(&path, "crash-report session 1-2\noriginal session\n").unwrap(); + let mut log = SessionLog::open(Some(&path), "1-2"); + std::fs::write(&path, "crash-report session 3-4\nprivate other session\n").unwrap(); + let report = test_report(&dir, "1-2", &mut log).unwrap(); + let text = std::fs::read_to_string(report).unwrap(); + assert!(text.contains("Recent log unavailable")); + assert!(!text.contains("private other session")); + assert!(!text.contains("session 3-4")); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn session_identity_requires_the_exact_first_line() { + let dir = folder(); + let path = dir.join("log"); + for header in ["crash-report session 1-20\n", "unrelated\ncrash-report session 1-2\n"] { + std::fs::write(&path, header).unwrap(); + assert!(matches!(SessionLog::open(Some(&path), "1-2"), SessionLog::Unavailable(_))); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn report_write_failure_is_described_and_existing_report_is_not_overwritten() { + let dir = folder(); + let mut log = SessionLog::Unavailable("no log".into()); + let first = test_report(&dir, "2-1", &mut log).unwrap(); + let before = std::fs::read(&first).unwrap(); + let result = test_report(&dir, "2-1", &mut log); + assert!(result.is_err()); + assert!(description(&result, false).contains("could not be saved")); + assert_eq!(std::fs::read(first).unwrap(), before); + assert!(test_report(&dir, "../escape", &mut log).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn normal_and_handled_shutdown_send_clean_marker_without_a_report() { + for id in ["3-1", "3-2"] { + let dir = folder(); + let r = helper(&dir, id); + r.finish().unwrap(); + // A completion file proves the helper consumed the marker, not merely that it + // hadn't yet produced a report. + wait_file(&dir.join(format!("ready-{id}"))); + assert!(!dir.join(format!("crash-{id}.txt")).exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + } + + #[test] + fn accepted_native_close_finishes_before_process_termination() { + let dir = folder(); + let status = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) + .env(ROLE, "native-close") + .env("EC_REPORT_DIR", &dir) + .stdout(Stdio::null()) + .status() + .unwrap(); + assert!(status.success()); + wait_file(&dir.join("ready-8-1")); + assert!(!dir.join("crash-8-1.txt").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_teardown_panic_does_not_mark_the_reporter_clean() { + let dir = folder(); + let reporter = Shutdown::default(); + reporter.install(helper(&dir, "8-2")).unwrap(); + let result = std::panic::catch_unwind(|| { + let _ = after_teardown(Some(&reporter), || panic!("simulated teardown failure")); + }); + assert!(result.is_err()); + drop(reporter); + wait_file(&dir.join("ready-8-2")); + assert!(dir.join("crash-8-2.txt").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn platforms_returning_to_main_keep_the_reporter_armed_until_then() { + let dir = folder(); + let reporter = Shutdown::default(); + reporter.install(helper(&dir, "8-3")).unwrap(); + after_teardown(None, || {}).unwrap(); + assert!(reporter.0.lock().unwrap().is_some()); + reporter.clone().finish().unwrap(); + reporter.finish().unwrap(); + wait_file(&dir.join("ready-8-3")); + assert!(!dir.join("crash-8-3.txt").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_aborting_parent_leaves_one_diagnostic_report() { + let dir = folder(); + let status = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) + .env(ROLE, "abort") + .env("EC_REPORT_DIR", &dir) + .stdout(Stdio::null()) + .status() + .unwrap(); + assert!(!status.success()); + wait_file(&dir.join("ready-4-1")); + let text = std::fs::read_to_string(dir.join("crash-4-1.txt")).unwrap(); + assert!(text.contains("exact cause is not established")); + assert!(text.contains("Detection UTC:")); + #[cfg(windows)] + assert!(text.contains("Windows status bits:")); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_unrelated_child_does_not_keep_the_control_pipe_open() { + let dir = folder(); + let r = helper(&dir, "5-1"); + let mut unrelated = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &test_name("lingering_child"), "--ignored", "--nocapture"]) + .env(ROLE, "linger") + .stdout(Stdio::null()) + .spawn() + .unwrap(); + drop(r); + wait_file(&dir.join("ready-5-1")); + assert!(unrelated.try_wait().unwrap().is_none()); + unrelated.kill().unwrap(); + unrelated.wait().unwrap(); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_unresponsive_helper_cannot_hang_clean_shutdown() { + let mut child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &test_name("lingering_child"), "--ignored", "--nocapture"]) + .env(ROLE, "linger") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .spawn() + .unwrap(); + let pipe = child.stdin.take().unwrap(); + let started = Instant::now(); + let result = Reporter { pipe, child }.finish(); + assert!(result.unwrap_err().to_string().contains("was terminated")); + assert!(started.elapsed() < Duration::from_secs(5)); + } + + #[test] + fn simultaneous_sessions_write_separate_reports() { + let dir = folder(); + let a = helper(&dir, "6-1"); + let b = helper(&dir, "6-2"); + drop(a); + drop(b); + wait_file(&dir.join("ready-6-1")); + wait_file(&dir.join("ready-6-2")); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn interactive_failure_calls_dialog_once_after_saving_the_report() { + let dir = folder(); + drop(helper_mode(&dir, "7-1", true)); + wait_file(&dir.join("ready-7-1")); + let text = std::fs::read_to_string(dir.join("dialog-7-1")).unwrap(); + assert!(text.contains("crash-7-1.txt")); + assert!(text.contains("No report has been sent")); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn lost_pipe_keeps_bounded_lifecycle_evidence_without_claiming_process_exit() { + let dir = folder(); + let reporter = Shutdown::default(); + reporter.install(helper(&dir, "9-1")).unwrap(); + for _ in 0..40 { + reporter.record("GPU observation: wgpu validation error").unwrap(); + } + drop(reporter); + wait_file(&dir.join("ready-9-1")); + let text = std::fs::read_to_string(dir.join("crash-9-1.txt")).unwrap(); + assert!(text.contains("GUI still present")); + assert!(!text.contains("process termination observed")); + assert_eq!(text.matches("GPU observation: wgpu validation error").count(), EVENT_COUNT); + assert!(text.contains("Target-present sampling attempts:")); + assert!(text.len() < 8192); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn clean_exit_after_lifecycle_events_does_not_write_a_report() { + let dir = folder(); + let reporter = Shutdown::default(); + reporter.install(helper(&dir, "9-2")).unwrap(); + reporter.record("Backend selection source: default").unwrap(); + reporter.finish().unwrap(); + wait_file(&dir.join("ready-9-2")); + assert!(!dir.join("crash-9-2.txt").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + #[cfg(windows)] + fn windows_report_preserves_real_unsigned_exit_bits() { + let dir = folder(); + let status = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) + .env(ROLE, "windows-status") + .env("EC_REPORT_DIR", &dir) + .stdout(Stdio::null()) + .status() + .unwrap(); + assert_eq!(status.code().map(|code| code as u32), Some(0xc0000017)); + wait_file(&dir.join("ready-9-3")); + let text = std::fs::read_to_string(dir.join("crash-9-3.txt")).unwrap(); + assert!(text.contains("Windows status bits: 0xC0000017 (STATUS_NO_MEMORY)")); + assert!(text.contains("not a verified exception record")); + assert!(text.contains("process termination observed")); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn internal_mode_rejects_invalid_arguments_without_launching_the_app() { + assert!(!maybe_run(&[], |_| panic!("no dialog"))); + assert!(!maybe_run(&[OsString::from("--version")], |_| panic!("no dialog"))); + assert!(maybe_run(&[OsString::from(FLAG)], |_| panic!("no dialog"))); + let args = [FLAG, "../escape", "", "", "1", "1"].map(OsString::from); + assert!(maybe_run(&args, |_| panic!("no dialog"))); + let args = [FLAG, "1-1", "", "", "invalid", "1"].map(OsString::from); + assert!(maybe_run(&args, |_| panic!("no dialog"))); + for pid in ["0", "not-a-pid", "4294967296"] { + let args = [FLAG, "1-1", "", "", "0", pid].map(OsString::from); + assert!(maybe_run(&args, |_| panic!("no dialog"))); + } + } + + #[test] + fn missing_helper_is_an_error_not_a_panic() { + assert!(spawn(Path::new("/nonexistent-effectcraft-crash-helper"), &[]).is_err()); + } + + // Roles are ignored by ordinary test runs. Explicit subprocess invocations exercise + // real EOF/abort behavior without allocating a huge image or killing the test runner. + #[test] + #[ignore] + fn reporter_process() { + assert_eq!(std::env::var(ROLE).unwrap(), "reporter"); + let dir = PathBuf::from(std::env::var_os("EC_REPORT_DIR").unwrap()); + let id = std::env::var("EC_REPORT_ID").unwrap(); + let interactive = std::env::var("EC_REPORT_INTERACTIVE").unwrap(); + let args = [ + OsString::from(FLAG), + OsString::from(&id), + OsString::new(), + dir.as_os_str().to_owned(), + OsString::from(&interactive), + std::env::var_os("EC_REPORT_PID").unwrap(), + ]; + assert!(maybe_run(&args, |description| { + assert_eq!(interactive, "1", "non-interactive reporter must not show a dialog"); + assert!(dir.join(format!("crash-{id}.txt")).exists()); + let mut shown = OpenOptions::new().write(true).create_new(true).open(dir.join(format!("dialog-{id}"))).unwrap(); + shown.write_all(description.as_bytes()).unwrap(); + })); + std::fs::write(dir.join(format!("ready-{id}")), b"done").unwrap(); + } + + #[test] + #[ignore] + fn aborting_parent() { + let role = std::env::var(ROLE).unwrap(); + let dir = PathBuf::from(std::env::var_os("EC_REPORT_DIR").unwrap()); + if role == "native-close" { + let reporter = Shutdown::default(); + reporter.install(helper(&dir, "8-1")).unwrap(); + after_teardown(Some(&reporter.clone()), || {}).unwrap(); + std::process::exit(0); // Models macOS not returning from its native event loop. + } + if role == "windows-status" { + let _reporter = helper(&dir, "9-3"); + // The real OS status is intentionally set, not actual memory exhaustion. The + // report must preserve this distinction rather than claiming a verified exception. + std::process::exit(0xc0000017u32 as i32); + } + assert_eq!(role, "abort"); + let _reporter = helper(&dir, "4-1"); + std::process::abort(); + } + + #[test] + #[ignore] + fn lingering_child() { + assert_eq!(std::env::var(ROLE).unwrap(), "linger"); + thread::sleep(Duration::from_secs(30)); + } +} diff --git a/apps/effectcraft/src/diagnostic_state.rs b/apps/effectcraft/src/diagnostic_state.rs new file mode 100644 index 000000000..042e6e88c --- /dev/null +++ b/apps/effectcraft/src/diagnostic_state.rs @@ -0,0 +1,147 @@ +//! Fixed-vocabulary observations retained by the crash helper independently of the log tail. +//! Driver messages and environment text can contain private data; never forward either here. + +use std::ffi::OsStr; +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; + +use crate::crash_report::Shutdown; + +pub fn record(reporter: &Shutdown, event: &'static str) { + log::info!("diagnostic observation: {event}"); + if let Err(error) = reporter.record(event) { + log::warn!("could not retain diagnostic observation: {error}"); + } +} + +/// Mirror only wgpu's documented names/aliases, without calling its parser: that parser +/// logs unknown tokens verbatim. Unknown, non-Unicode and oversized values remain private. +pub fn backend_override_events(value: &OsStr) -> Vec<&'static str> { + let Some(value) = value.to_str().filter(|value| value.len() <= 4096) else { + return vec!["WGPU_BACKEND: non-Unicode or oversized value omitted"]; + }; + let mut selected = [false; 6]; + let mut unknown = false; + for token in value.split(',').map(str::trim) { + let aliases: &[&[&str]] = &[&["vulkan", "vk"], &["dx12", "d3d12"], &["metal", "mtl"], &["opengl", "gles", "gl"], &["webgpu"], &["noop"]]; + if let Some(index) = aliases.iter().position(|names| names.iter().any(|name| token.eq_ignore_ascii_case(name))) { + if let Some(flag) = selected.get_mut(index) { + *flag = true; + } + } else { + unknown = true; + } + } + let events = [ + "WGPU_BACKEND requests: vulkan", + "WGPU_BACKEND requests: dx12", + "WGPU_BACKEND requests: metal", + "WGPU_BACKEND requests: gl", + "WGPU_BACKEND requests: webgpu", + "WGPU_BACKEND requests: noop", + ]; + let mut result: Vec<_> = selected.into_iter().zip(events).filter_map(|(present, event)| present.then_some(event)).collect(); + if unknown { + result.push("WGPU_BACKEND: unrecognized or empty tokens omitted"); + } + result +} + +/// At most eight events per device, even when a driver floods its callbacks. A wgpu OOM +/// observation is not proof of system RAM exhaustion; device loss is not a driver-crash verdict. +#[derive(Clone)] +pub struct GpuObservations { + seen: Arc, + reporter: Shutdown, +} + +impl GpuObservations { + pub fn new(reporter: &Shutdown) -> Self { + Self { seen: Arc::new(AtomicU8::new(0)), reporter: reporter.clone() } + } + + pub fn uncaptured(&self, error: &eframe::wgpu::Error) { + let (bit, event) = match error { + eframe::wgpu::Error::OutOfMemory { .. } => (1, "GPU observation: wgpu out-of-memory error (not proof of system RAM exhaustion)"), + eframe::wgpu::Error::Validation { .. } => (2, "GPU observation: wgpu validation error"), + eframe::wgpu::Error::Internal { .. } => (4, "GPU observation: wgpu internal error"), + }; + self.once(bit, event); + } + + pub fn scoped(&self, error: effectcraft_ui_egui::gpu_failure::ScopedError) { + use effectcraft_ui_egui::gpu_failure::ScopedError; + let (bit, event) = match error { + ScopedError::OutOfMemory => (32, "GPU scoped observation: out-of-memory (not proof of system RAM exhaustion)"), + ScopedError::Internal => (64, "GPU scoped observation: internal error (not confirmed out-of-memory)"), + ScopedError::Validation => (128, "GPU scoped observation: validation error"), + }; + self.once(bit, event); + } + + pub fn device_lost(&self, reason: eframe::wgpu::DeviceLostReason) { + match reason { + eframe::wgpu::DeviceLostReason::Unknown => self.once(8, "GPU observation: device lost, reason unknown (not proof of a driver crash)"), + eframe::wgpu::DeviceLostReason::Destroyed => self.once(16, "GPU observation: device-lost callback, explicit device destruction"), + }; + } + + fn once(&self, bit: u8, event: &'static str) -> bool { + if self.seen.fetch_or(bit, Ordering::Relaxed) & bit != 0 { + return false; + } + record(&self.reporter, event); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn override_names_are_normalized_deduplicated_and_private() { + let events = backend_override_events(OsStr::new(" Vk, VULKAN, d3d12, MTL, gles, webgpu, noop, private-token")); + assert_eq!(events.len(), 7); + assert_eq!(events.first(), Some(&"WGPU_BACKEND requests: vulkan")); + assert!(!events.join(" ").contains("private-token")); + assert!(events.iter().all(|event| event.len() <= 100)); + assert_eq!(backend_override_events(OsStr::new("")).len(), 1); + assert_eq!(backend_override_events(OsStr::new(&"x".repeat(4097))), ["WGPU_BACKEND: non-Unicode or oversized value omitted"]); + } + + #[test] + fn gpu_categories_are_latched_independently() { + let observations = GpuObservations::new(&Shutdown::default()); + observations.uncaptured(&eframe::wgpu::Error::OutOfMemory { source: Box::new(std::io::Error::other("private driver detail")) }); + observations.device_lost(eframe::wgpu::DeviceLostReason::Unknown); + observations.device_lost(eframe::wgpu::DeviceLostReason::Unknown); + assert_eq!(observations.seen.load(Ordering::Relaxed), 9); + observations.device_lost(eframe::wgpu::DeviceLostReason::Destroyed); + observations.uncaptured(&eframe::wgpu::Error::Validation { + source: Box::new(std::io::Error::other("private driver detail")), + description: "private validation detail".into(), + }); + observations.uncaptured(&eframe::wgpu::Error::Internal { + source: Box::new(std::io::Error::other("private driver detail")), + description: "private internal detail".into(), + }); + assert_eq!(observations.seen.load(Ordering::Relaxed), 31); + use effectcraft_ui_egui::gpu_failure::ScopedError; + observations.scoped(ScopedError::Internal); + assert_eq!(observations.seen.load(Ordering::Relaxed), 95, "internal scope must not set scoped OOM bit"); + observations.scoped(ScopedError::OutOfMemory); + observations.scoped(ScopedError::Validation); + observations.scoped(ScopedError::OutOfMemory); + assert_eq!(observations.seen.load(Ordering::Relaxed), 255); + assert!(!observations.once(1, "GPU observation: duplicate")); + assert!(!observations.once(8, "GPU observation: duplicate")); + } + + #[test] + #[cfg(unix)] + fn non_unicode_override_is_not_copied() { + use std::os::unix::ffi::OsStrExt; + assert_eq!(backend_override_events(OsStr::from_bytes(b"private\xff")), ["WGPU_BACKEND: non-Unicode or oversized value omitted"]); + } +} diff --git a/apps/effectcraft/src/launch_guard.rs b/apps/effectcraft/src/launch_guard.rs index fac91c05b..2656179ac 100644 --- a/apps/effectcraft/src/launch_guard.rs +++ b/apps/effectcraft/src/launch_guard.rs @@ -8,9 +8,9 @@ //! until its window has kept drawing for [`SETTLE`] (or the app quits normally before then). A //! launch that finds the previous one's marker switches Window Graphics to OpenGL, which those //! drivers run, and says so once the window is up. `WGPU_BACKEND` (wgpu's own override) still -//! wins over both. The marker is locked while its launch runs, so a second copy opened meanwhile -//! isn't taken for a crash; and a window OpenGL can't open either puts Window Graphics back to -//! Automatic ([`opengl_failed`]) rather than failing every launch. +//! wins over both. A separate guard file is locked while its launch runs, so a second copy opened +//! meanwhile isn't taken for a crash; and a window OpenGL can't open either puts Window Graphics +//! back to Automatic ([`opengl_failed`]) rather than failing every launch. use std::fs::File; use std::path::{Path, PathBuf}; @@ -21,6 +21,46 @@ use eframe::wgpu::Backends; /// Left in the settings folder from a launch until its window has settled. const MARKER: &str = "launch-pending"; +const LOCK: &str = "launch.lock"; + +/// Keep this file in place: unlinking a locked file lets a second inode acquire a new lock. +fn acquire_guard(dir: &Path) -> Option { + let file = match std::fs::create_dir_all(dir) + .and_then(|()| std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(dir.join(LOCK))) + { + Ok(file) => file, + Err(e) => { + log::warn!("launch guard unavailable: {e}"); + return None; + } + }; + match file.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return None, + Err(e) => { + log::warn!("launch guard lock unavailable: {e}"); + return None; + } + } + // Older versions lock the marker itself. Probe only the lock: Windows also prevents + // reads through another handle while it is held. An unreadable marker is not a stale one. + match File::open(dir.join(MARKER)) { + Ok(marker) => match marker.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return None, + Err(e) => { + log::warn!("launch marker lock unavailable: {e}"); + return None; + } + }, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => { + log::warn!("launch marker unavailable: {e}"); + return None; + } + } + Some(file) +} /// How long the window keeps drawing after its first frame before the launch counts as made. /// A driver that fails as the window is shown and its surface re-created does so within the @@ -28,16 +68,39 @@ const MARKER: &str = "launch-pending"; /// switch back in Settings. pub const SETTLE: Duration = Duration::from_secs(3); +/// Why this launch requested its window graphics APIs. An interrupted startup is an +/// observation, not proof that a driver caused the previous exit. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum BackendSource { + #[default] + Default, + SavedPreference, + InterruptedStartup, + EnvironmentOverride, +} + +impl BackendSource { + pub fn event(self) -> &'static str { + match self { + Self::Default => "backend source: default", + Self::SavedPreference => "backend source: saved OpenGL preference", + Self::InterruptedStartup => "backend source: previous interrupted startup; OpenGL fallback", + Self::EnvironmentOverride => "backend source: WGPU_BACKEND present", + } + } +} + /// This launch's window graphics. #[derive(Debug, Default)] pub struct Launch { /// The graphics APIs the window may use (`None`: eframe's default). pub backends: Option, + pub source: BackendSource, /// Switched to OpenGL because the previous launch stopped as its window opened: the message /// to show. pub notice: Option, marker: Option, - /// Holds the marker's lock until the launch settles (or the process ends). + /// Holds the separate guard file's lock until the launch settles (or the process ends). lock: Option, /// When the window drew its first frame, until the launch settles. first_frame: Option, @@ -48,14 +111,22 @@ impl Launch { /// launch stopped as its window opened (where OpenGL exists: not macOS), and leave this /// launch's marker. `env_override`: `WGPU_BACKEND` is set. pub fn begin(dir: Option<&Path>, env_override: bool) -> Launch { - let Some(dir) = dir.filter(|_| !env_override) else { return Launch::default() }; + if env_override { + return Launch { source: BackendSource::EnvironmentOverride, ..Launch::default() }; + } + let Some(dir) = dir else { return Launch::default() }; let prefs_path = dir.join(PREFS_FILE); let mut prefs = std::fs::read_to_string(&prefs_path).map(|t| Prefs::from_json(&t)).unwrap_or_default(); let marker = dir.join(MARKER); - // Locked by another launch that is still opening its window: not a crash. - let held = File::open(&marker).is_ok_and(|f| matches!(f.try_lock(), Err(std::fs::TryLockError::WouldBlock))); + let Some(lock) = acquire_guard(dir) else { + let backends = (prefs.startup.window_graphics == "gl").then_some(Backends::GL); + let source = if backends.is_some() { BackendSource::SavedPreference } else { BackendSource::Default }; + return Launch { backends, source, ..Launch::default() }; + }; + // Read again while owning the guard: another launch may have just changed preferences. + prefs = std::fs::read_to_string(&prefs_path).map(|t| Prefs::from_json(&t)).unwrap_or_default(); let mut notice = None; - if marker.exists() && !held && prefs.startup.window_graphics == "auto" && cfg!(not(target_os = "macos")) { + if marker.exists() && prefs.startup.window_graphics == "auto" && cfg!(not(target_os = "macos")) { prefs.startup.window_graphics = "gl".into(); match std::fs::create_dir_all(dir).and_then(|()| std::fs::write(&prefs_path, prefs.to_json())) { Ok(()) => log::warn!("the last launch stopped as its window opened: switching Window Graphics to OpenGL"), @@ -69,15 +140,21 @@ impl Launch { ); } let backends = (prefs.startup.window_graphics == "gl").then_some(Backends::GL); - let (marker, lock) = match std::fs::create_dir_all(dir).and_then(|()| File::create(&marker)) { - // Where locks aren't available the guard works as before. - Ok(f) => (Some(marker), f.try_lock().is_ok().then_some(f)), + let source = if notice.is_some() { + BackendSource::InterruptedStartup + } else if backends.is_some() { + BackendSource::SavedPreference + } else { + BackendSource::Default + }; + let marker = match File::create(&marker) { + Ok(_) => Some(marker), Err(e) => { log::warn!("launch marker: {e}"); - (None, None) + None } }; - Launch { backends, notice, marker, lock, first_frame: None } + Launch { backends, source, notice, marker, lock: Some(lock), first_frame: None } } /// The window drew a frame. Until the launch has settled, returns how long that still takes @@ -104,18 +181,19 @@ impl Launch { /// The launch made it: release and remove its marker. fn settled(&mut self) { - self.lock = None; if let Some(m) = self.marker.take() && let Err(e) = std::fs::remove_file(&m) { log::warn!("launch marker: {e}"); } + self.lock = None; } } /// The window couldn't open with OpenGL (an error, not a crash): back to Automatic, and no marker. pub fn opengl_failed(dir: Option<&Path>) { let Some(dir) = dir else { return }; + let Some(_lock) = acquire_guard(dir) else { return }; let prefs_path = dir.join(PREFS_FILE); let mut prefs = std::fs::read_to_string(&prefs_path).map(|t| Prefs::from_json(&t)).unwrap_or_default(); prefs.startup.window_graphics = "auto".into(); @@ -142,6 +220,7 @@ mod tests { // may still crash as the window is shown); frames for `SETTLE` do. let mut l = Launch::begin(Some(&dir), false); assert_eq!((l.backends, l.notice.is_some()), (None, false)); + assert_eq!(l.source, BackendSource::Default); assert!(dir.join(MARKER).exists()); let t0 = Instant::now(); assert_eq!(l.frame_drawn_at(t0), Some(SETTLE)); @@ -159,14 +238,18 @@ mod tests { } else { assert_eq!(l.backends, Some(Backends::GL)); assert!(l.notice.is_some()); + assert_eq!(l.source, BackendSource::InterruptedStartup); assert_eq!(window_graphics(&dir), "gl", "saved in Settings"); l.exited(); let l = Launch::begin(Some(&dir), false); assert_eq!((l.backends, l.notice.is_some()), (Some(Backends::GL), false), "it stays, without the notice"); + assert_eq!(l.source, BackendSource::SavedPreference); } // `WGPU_BACKEND` wins, and leaves no marker. let _ = std::fs::remove_file(dir.join(MARKER)); - assert_eq!(Launch::begin(Some(&dir), true).backends, None); + let overridden = Launch::begin(Some(&dir), true); + assert_eq!(overridden.backends, None); + assert_eq!(overridden.source, BackendSource::EnvironmentOverride); assert!(!dir.join(MARKER).exists()); let _ = std::fs::remove_dir_all(&dir); } @@ -217,4 +300,232 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + /// A fresh settings folder for one test. + fn fresh_dir(case: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ec-launch-guard-{case}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// Window Graphics saved as OpenGL. + fn save_opengl(dir: &Path) { + let mut prefs = Prefs::default(); + prefs.startup.window_graphics = "gl".into(); + std::fs::write(dir.join(PREFS_FILE), prefs.to_json()).unwrap(); + } + + #[test] + fn a_second_copy_reports_the_saved_backend_without_owning_the_guard() { + let dir = fresh_dir("second-source"); + save_opengl(&dir); + let mut first = Launch::begin(Some(&dir), false); + let mut second = Launch::begin(Some(&dir), false); + assert!(second.lock.is_none()); + assert_eq!((second.backends, second.source), (Some(Backends::GL), BackendSource::SavedPreference)); + second.exited(); + first.exited(); + let _ = std::fs::remove_dir_all(dir); + } + + /// A second copy that quits normally while the first is still opening doesn't remove the first + /// one's marker (#477). + #[test] + fn a_second_copy_quitting_leaves_the_running_launchs_marker() { + let dir = fresh_dir("second-quits"); + let mut first = Launch::begin(Some(&dir), false); + let mut second = Launch::begin(Some(&dir), false); + second.exited(); + let kept = dir.join(MARKER).exists(); + first.exited(); + let _ = std::fs::remove_dir_all(&dir); + assert!(kept, "the second copy removed the running launch's marker"); + } + + /// A second copy whose OpenGL window fails doesn't remove a running launch's marker. + #[test] + fn failed_opengl_in_a_second_copy_leaves_the_running_launchs_marker() { + let dir = fresh_dir("second-gl-fails"); + let mut first = Launch::begin(Some(&dir), false); + let second = Launch::begin(Some(&dir), false); + opengl_failed(Some(&dir)); + let kept = dir.join(MARKER).exists(); + drop(second); + first.exited(); + let _ = std::fs::remove_dir_all(&dir); + assert!(kept, "OpenGL cleanup removed another running launch's marker"); + } + + /// With `WGPU_BACKEND` set, a stale marker and a saved OpenGL choice are left as they are. + #[test] + fn wgpu_backend_leaves_a_stale_marker_and_saved_opengl_alone() { + let dir = fresh_dir("env-override"); + save_opengl(&dir); + std::fs::write(dir.join(MARKER), b"stale-marker").unwrap(); + let before = std::fs::read(dir.join(PREFS_FILE)).unwrap(); + let mut l = Launch::begin(Some(&dir), true); + assert_eq!(l.backends, None); + assert!(l.notice.is_none()); + l.exited(); + assert!(dir.join(MARKER).exists()); + assert_eq!(std::fs::read(dir.join(PREFS_FILE)).unwrap(), before); + let _ = std::fs::remove_dir_all(&dir); + } + + /// After OpenGL fails to open a window, the next launch is back on Automatic, without a notice. + #[test] + fn failed_opengl_puts_the_next_launch_back_on_automatic() { + let dir = fresh_dir("gl-recovers"); + save_opengl(&dir); + let l = Launch::begin(Some(&dir), false); + assert_eq!(l.backends, Some(Backends::GL)); + drop(l); + opengl_failed(Some(&dir)); + assert!(!dir.join(MARKER).exists()); + assert_eq!(Prefs::from_json(&std::fs::read_to_string(dir.join(PREFS_FILE)).unwrap()).startup.window_graphics, "auto"); + let mut l = Launch::begin(Some(&dir), false); + assert_eq!(l.backends, None); + assert!(l.notice.is_none()); + l.exited(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The guard file is never removed or replaced: unlinking a locked file would let the next + /// launch lock a new one while the old lock is still held. + #[cfg(unix)] + #[test] + fn the_guard_file_stays_the_same_file_across_launches() { + use std::os::unix::fs::MetadataExt; + let dir = fresh_dir("guard-identity"); + let mut a = Launch::begin(Some(&dir), false); + let before = std::fs::metadata(dir.join(LOCK)).unwrap(); + let t0 = Instant::now(); + assert_eq!(a.frame_drawn_at(t0), Some(SETTLE)); + assert_eq!(a.frame_drawn_at(t0 + SETTLE), None); + assert!(!dir.join(MARKER).exists()); + let after = std::fs::metadata(dir.join(LOCK)).unwrap(); + assert_eq!((before.dev(), before.ino()), (after.dev(), after.ino())); + let mut b = Launch::begin(Some(&dir), false); + assert!(b.lock.is_some()); + let reused = std::fs::metadata(dir.join(LOCK)).unwrap(); + assert_eq!((before.dev(), before.ino()), (reused.dev(), reused.ino())); + b.exited(); + let _ = std::fs::remove_dir_all(dir); + } + + /// A second copy's frames and quit neither settle nor unlock the running launch. + #[test] + fn a_second_copys_frames_dont_settle_the_running_launch() { + let dir = fresh_dir("second-frames"); + let mut a = Launch::begin(Some(&dir), false); + std::fs::write(dir.join(MARKER), b"owner-marker").unwrap(); + let mut b = Launch::begin(Some(&dir), false); + assert!(b.lock.is_none()); + assert!(b.marker.is_none()); + let t0 = Instant::now(); + assert_eq!(b.frame_drawn_at(t0), None); + assert_eq!(b.frame_drawn_at(t0 + SETTLE), None); + b.exited(); + assert_eq!(std::fs::read(dir.join(MARKER)).unwrap(), b"owner-marker"); + let probe = File::open(dir.join(LOCK)).unwrap(); + assert!(matches!(probe.try_lock(), Err(std::fs::TryLockError::WouldBlock))); + a.exited(); + let _ = std::fs::remove_dir_all(dir); + } + + /// Older versions lock the marker itself: while one runs, a new launch changes nothing, and + /// once it has stopped without settling the next launch still switches to OpenGL. + #[test] + fn a_running_older_version_holding_the_marker_is_left_alone() { + let dir = fresh_dir("older-version"); + std::fs::write(dir.join(MARKER), b"old-owner").unwrap(); + std::fs::write(dir.join(PREFS_FILE), Prefs::default().to_json()).unwrap(); + let old = File::open(dir.join(MARKER)).unwrap(); + old.try_lock().unwrap(); + let before = std::fs::read(dir.join(PREFS_FILE)).unwrap(); + let mut b = Launch::begin(Some(&dir), false); + assert!(b.lock.is_none()); + assert!(b.marker.is_none()); + assert!(b.backends.is_none()); + assert!(b.notice.is_none()); + b.exited(); + opengl_failed(Some(&dir)); + assert_eq!(std::fs::read(dir.join(PREFS_FILE)).unwrap(), before); + // Windows locks forbid reading through another handle. Inspect the contents only after + // releasing the old owner's lock, but before recovery can truncate the marker. + drop(old); + assert_eq!(std::fs::read(dir.join(MARKER)).unwrap(), b"old-owner"); + let mut recovered = Launch::begin(Some(&dir), false); + if cfg!(not(target_os = "macos")) { + assert_eq!(recovered.backends, Some(Backends::GL)); + } + recovered.exited(); + let _ = std::fs::remove_dir_all(dir); + } + + /// A Windows sharing violation is not evidence that a marker is stale or absent. + #[cfg(windows)] + #[test] + fn an_unopenable_marker_leaves_settings_and_marker_alone() { + use std::os::windows::fs::OpenOptionsExt; + + let dir = fresh_dir("marker-unopenable"); + std::fs::write(dir.join(MARKER), b"old-owner").unwrap(); + std::fs::write(dir.join(PREFS_FILE), Prefs::default().to_json()).unwrap(); + let old = std::fs::OpenOptions::new().read(true).write(true).share_mode(0).open(dir.join(MARKER)).unwrap(); + let before = std::fs::read(dir.join(PREFS_FILE)).unwrap(); + let mut launch = Launch::begin(Some(&dir), false); + assert!(launch.lock.is_none()); + assert!(launch.marker.is_none()); + assert!(launch.backends.is_none()); + assert!(launch.notice.is_none()); + launch.exited(); + opengl_failed(Some(&dir)); + assert_eq!(std::fs::read(dir.join(PREFS_FILE)).unwrap(), before); + drop(old); + assert_eq!(std::fs::read(dir.join(MARKER)).unwrap(), b"old-owner"); + let _ = std::fs::remove_dir_all(dir); + } + + /// A guard file that can't be opened leaves Window Graphics and the marker as they are. + #[test] + fn an_unusable_guard_file_leaves_settings_and_marker_alone() { + let dir = fresh_dir("guard-unusable"); + std::fs::create_dir(dir.join(LOCK)).unwrap(); + std::fs::write(dir.join(MARKER), b"stale-marker").unwrap(); + std::fs::write(dir.join(PREFS_FILE), Prefs::default().to_json()).unwrap(); + let before = std::fs::read(dir.join(PREFS_FILE)).unwrap(); + let mut l = Launch::begin(Some(&dir), false); + assert!(l.backends.is_none()); + assert!(l.notice.is_none()); + assert!(l.lock.is_none()); + assert!(l.marker.is_none()); + l.exited(); + opengl_failed(Some(&dir)); + assert_eq!(std::fs::read(dir.join(PREFS_FILE)).unwrap(), before); + assert_eq!(std::fs::read(dir.join(MARKER)).unwrap(), b"stale-marker"); + let _ = std::fs::remove_dir_all(dir); + } + + /// OpenGL cleanup from elsewhere waits until the running launch has let go; then it resets + /// Window Graphics to Automatic and removes the marker. + #[test] + fn failed_opengl_cleanup_waits_for_the_running_launch() { + let dir = fresh_dir("gl-cleanup-waits"); + save_opengl(&dir); + let launch = Launch::begin(Some(&dir), false); + assert_eq!(launch.backends, Some(Backends::GL)); + assert!(launch.lock.is_some()); + let before = std::fs::read(dir.join(PREFS_FILE)).unwrap(); + opengl_failed(Some(&dir)); + assert_eq!(std::fs::read(dir.join(PREFS_FILE)).unwrap(), before); + assert!(dir.join(MARKER).exists(), "cleanup elsewhere can't remove a running launch's marker"); + drop(launch); + opengl_failed(Some(&dir)); + let after = Prefs::from_json(&std::fs::read_to_string(dir.join(PREFS_FILE)).unwrap()).startup.window_graphics; + assert_eq!(after, "auto", "once the launch has let go, failed OpenGL resets Window Graphics"); + assert!(!dir.join(MARKER).exists()); + let _ = std::fs::remove_dir_all(dir); + } } diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs index a560b00e3..5a602adcb 100644 --- a/apps/effectcraft/src/main.rs +++ b/apps/effectcraft/src/main.rs @@ -8,7 +8,9 @@ //! `--demo` opens the demo project instead (also Help ▸ Open Demo Project). //! //! `--control ` (or `EFFECTCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server; -//! see `effectcraft_ui_egui::control` for the methods. +//! see `effectcraft_ui_egui::control` for the methods. An app started for an agent opens without +//! taking keyboard focus and skips crash recovery, the Home screen (unless `--home`) and the +//! startup update check. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] @@ -20,6 +22,8 @@ mod appimage; mod apple_events; mod audio_out; mod control_server; +mod crash_report; +mod diagnostic_state; mod launch_guard; #[cfg(target_os = "macos")] mod native_menu; @@ -112,6 +116,13 @@ fn parse_args(args: impl IntoIterator, env_port: Result) -> bool { + control_port.is_none() +} + /// A control-channel port from 1 to 65535 (0 would listen on a port nobody is told); `name` is /// the flag or variable it came from. fn control_port(name: &str, value: Option<&str>) -> Result { @@ -148,11 +159,46 @@ fn install_file_dialogs(app: &mut EffectcraftApp) -> Option { + for e in r["errors"].as_array().into_iter().flatten() { + log::warn!("effect helpers: {}", e.as_str().unwrap_or("error")); + } + } + Err(e) => log::warn!("effect helpers: {e}"), + } +} + /// Run a normal desktop launch: install logging and the panic hook, parse arguments (`--version` exits before the /// session log is attached), scan fonts, honor the launch guard's backend choice and open the eframe window. /// Builds the session, loads settings, plugins, the requested project/media and the optional control server, then /// reports startup failure through `startup_failed`. Returns the event loop's result. fn main() -> eframe::Result { + let args: Vec<_> = std::env::args_os().skip(1).collect(); + if crash_report::maybe_run(&args, |description| { + rfd::MessageDialog::new().set_level(rfd::MessageLevel::Error).set_title("EffectCraft diagnostic report").set_description(description).show(); + }) { + return Ok(()); + } + let reporter = crash_report::Shutdown::default(); + let result = run_desktop(&reporter); + // run_desktop has dropped the app and handled any startup error with its existing dialog. + // An unwinding panic or abort never reaches this marker. + if let Err(error) = reporter.finish() { + log::warn!("could not mark crash reporter clean: {error}"); + } + result +} + +fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result { // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] if let Some(result) = craft_update::self_update::finish(&effectcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { @@ -178,20 +224,38 @@ fn main() -> eframe::Result { // The session log lives in the settings folder (`Logs/effectcraft.log`, the previous two runs // kept): a launch from the Dock or a menu has no terminal. Opened after the arguments, so // `--version` leaves no file behind; records logged until now are written to it first. + let run_id = crash_report::run_id(); if let Some(dir) = effectcraft_host::config_dir() { - match effectcraft_engine::logging::attach_session_log(&effectcraft_engine::logging::log_dir(Some(&dir))) { + let header = format!("{}\n", crash_report::session_marker(&run_id)); + match effectcraft_engine::logging::attach_session_log_with_header(&effectcraft_engine::logging::log_dir(Some(&dir)), &header) { Ok(path) => log::info!("effectcraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()), Err(e) => log::warn!("no log file: {e}"), } } + let logs = effectcraft_engine::logging::log_dir(effectcraft_host::config_dir().as_deref()); + match crash_report::start(&run_id, effectcraft_engine::logging::session_file().as_deref(), &logs.join("Crash Reports"), control_port.is_none()) { + Ok(started) => { + if let Err(error) = reporter.install(started) { + log::warn!("crash reporter could not be retained: {error}"); + } + } + Err(error) => log::warn!("crash reporter could not start: {error}"), + } // The font menus list the installed fonts: read their names while the window opens. effectcraft_engine::text::fonts::scan_system_in_background(); // Wayland shows the window's icon from its desktop entry: an AppImage brings its own. #[cfg(target_os = "linux")] appimage::integrate_from_env(ICON_PNG); // Settings ▸ Startup & Repair ▸ Window Graphics, switched to OpenGL when the last launch - // stopped as its window opened (a crashing graphics driver, #243). - let mut launch = launch_guard::Launch::begin(effectcraft_host::config_dir().as_deref(), std::env::var_os("WGPU_BACKEND").is_some()); + // stopped as its window opened (the marker alone does not establish a cause). + let backend_override = std::env::var_os("WGPU_BACKEND"); + let mut launch = launch_guard::Launch::begin(effectcraft_host::config_dir().as_deref(), backend_override.is_some()); + diagnostic_state::record(reporter, launch.source.event()); + if let Some(value) = backend_override { + for event in diagnostic_state::backend_override_events(&value) { + diagnostic_state::record(reporter, event); + } + } let on_gl = launch.backends == Some(eframe::wgpu::Backends::GL); let notice = launch.notice.take(); let options = eframe::NativeOptions { @@ -218,22 +282,40 @@ fn main() -> eframe::Result { let apple_events = apple_events::AppleEvents::install(); #[cfg(target_os = "macos")] let apple_events = &apple_events; + let desktop_reporter = reporter.clone(); let result = eframe::run_native( "EffectCraft", options, Box::new(move |cc| { EffectcraftApp::install_ime_reset_hooks(&cc.egui_ctx); match &cc.wgpu_render_state { - Some(rs) => log::info!("graphics: {:?}", rs.adapter.get_info()), - None => log::info!("graphics: no wgpu device"), + Some(rs) => { + let info = rs.adapter.get_info(); + log::info!("graphics: {info:?}"); + let event = match info.backend { + eframe::wgpu::Backend::Noop => "actual GPU backend: noop", + eframe::wgpu::Backend::Vulkan => "actual GPU backend: vulkan", + eframe::wgpu::Backend::Metal => "actual GPU backend: metal", + eframe::wgpu::Backend::Dx12 => "actual GPU backend: dx12", + eframe::wgpu::Backend::Gl => "actual GPU backend: gl", + eframe::wgpu::Backend::BrowserWebGpu => "actual GPU backend: webgpu", + }; + diagnostic_state::record(&desktop_reporter, event); + } + None => diagnostic_state::record(&desktop_reporter, "actual GPU backend: no wgpu device"), } // This executable owns the shared device's handlers. Install them before // EffectCraft's compositor pipelines are built, without changing handlers from // inside Gpu::new. eframe has already constructed its presentation renderer here. let gpu_failures = effectcraft_ui_egui::gpu_failure::GpuFailureBridge::new(&cc.egui_ctx); + let observations = diagnostic_state::GpuObservations::new(&desktop_reporter); + let scoped_observed = observations.clone(); + gpu_failures.set_scoped_error_observer(move |error| scoped_observed.scoped(error)); if let Some(rs) = &cc.wgpu_render_state { + let errors_observed = observations.clone(); let errors = gpu_failures.clone(); rs.device.on_uncaptured_error(std::sync::Arc::new(move |error| { + errors_observed.uncaptured(&error); let message = format!("uncaptured GPU error: {error}"); if errors.report(&message, false) { log::error!("{message}"); @@ -241,6 +323,7 @@ fn main() -> eframe::Result { })); let lost = gpu_failures.clone(); rs.device.set_device_lost_callback(move |reason, message| { + observations.device_lost(reason); lost.report(&format!("GPU device lost ({reason:?}): {message}"), true); }); } @@ -253,10 +336,16 @@ fn main() -> eframe::Result { // config directory. Agent-driven runs (`--control`) skip crash recovery. if let Some(dir) = effectcraft_host::config_dir() { // WebAssembly effect plug-ins in /Plug-ins load before the menus are built. - let plugins = dir.join("Plug-ins"); + let plugins = dir.join(effectcraft_engine::commands::PLUGINS_DIR); if plugins.is_dir() { let _ = session.execute("effect.plugins.load", json!({"folder": plugins.to_string_lossy()})); + // Packages installed from the Plug-in Library (/Plug-ins/Library). + // Each package that fails to load is logged by the library itself. + if let Err(e) = session.execute("library.loadInstalled", json!({})) { + log::warn!("plug-in library: {e}"); + } } + start_helpers_if_opted_in(&mut session); session.config = Some(std::sync::Arc::new(effectcraft_engine::config::DirConfig::new(dir))); } session.load_settings(); @@ -286,7 +375,7 @@ fn main() -> eframe::Result { // reported in a toast and forgotten). let _ = session.execute("window.restoreScriptPanels", json!({})); let mut app = EffectcraftApp::new(session); - app.set_startup_update_check(true); + app.set_startup_update_check(startup_update_check(control_port)); app.set_gpu_failure_bridge(gpu_failures); app.ui.start_screen = show_home; if let Some(n) = notice { @@ -365,6 +454,7 @@ fn main() -> eframe::Result { window: window::Tracker::new(opened, saved_window, control_port.is_none()), launch, drawn: false, + reporter: desktop_reporter, })) }), ); @@ -458,6 +548,7 @@ struct Desktop { launch: launch_guard::Launch, /// The first frame was drawn (logged once). drawn: bool, + reporter: crash_report::Shutdown, } impl eframe::App for Desktop { @@ -492,14 +583,20 @@ impl eframe::App for Desktop { } fn on_exit(&mut self) { - // On macOS the app quits through `-[NSApplication terminate:]`, and the process ends - // before `eframe::run_native` returns (#341). - log::info!("the window is closing"); - self.launch.exited(); - self.window.save(self.app.session.config.as_deref()); - self.app.on_exit(); - // Scripts in Scripts/Shutdown run with the project closed. - let _ = self.app.session.execute("file.runShutdownScripts", json!({})); + // macOS terminates after this hook without returning from run_native (#341). + // Other platforms keep the reporter armed until main sees complete event-loop teardown. + let reporter = cfg!(target_os = "macos").then(|| self.reporter.clone()); + if let Err(error) = crash_report::after_teardown(reporter.as_ref(), || { + log::info!("the window is closing"); + self.launch.exited(); + self.window.save(self.app.session.config.as_deref()); + self.app.on_exit(); + effectcraft_host::stop_helpers(); + // Scripts in Scripts/Shutdown run with the project closed. + let _ = self.app.session.execute("file.runShutdownScripts", json!({})); + }) { + log::warn!("could not mark crash reporter clean after teardown: {error}"); + } } fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { @@ -641,6 +738,18 @@ mod tests { assert_eq!(parse_env(&[], Ok("9000".into())).unwrap().map(|a| a.control_port), Some(Some(9000))); } + /// An app started for an agent (`--control` or `EFFECTCRAFT_CONTROL_PORT`) doesn't check for + /// updates at start, so no modal update prompt blocks the run; a normal launch still does. + #[test] + fn agent_runs_skip_the_startup_update_check() { + let port = |args: &[&str], env| parse_env(args, env).unwrap().unwrap_or_default().control_port; + assert!(super::startup_update_check(port(&[], Err(VarError::NotPresent)))); + assert!(super::startup_update_check(port(&[], Ok(String::new())))); + assert!(!super::startup_update_check(port(&["--control", "9877"], Err(VarError::NotPresent)))); + assert!(!super::startup_update_check(port(&["--control=9877"], Err(VarError::NotPresent)))); + assert!(!super::startup_update_check(port(&[], Ok("9877".into())))); + } + /// A missing, non-numeric or zero `--control` value stops the launch instead of starting /// without a control server, and the argument after `--control` isn't reinterpreted (#997). #[test] diff --git a/contributors/people.toml b/contributors/people.toml index 95e7e2e93..e9144f9ea 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -62,7 +62,8 @@ sync_github_name = false [people.vangel76] real_name = "Valentin Klein" -display_name = "Valentin Klein" +display_name = "vangel76" +sync_github_name = false [people.Losminek] sync_github_name = true @@ -104,6 +105,10 @@ sync_github_name = false [people.ki2pixel] display_name = "ki2pixel" +[people.iseemhlyfta] +display_name = "iseemhlyfta" +sync_github_name = false + [people.becauseno7] real_name = "Shuvra Basak" display_name = "Shuvra Basak" @@ -127,3 +132,6 @@ sync_github_name = false [people.JonRC] real_name = "Jonathan Cardoso" display_name = "Jonathan Cardoso" + +[people.nazar-gavrylyk] +sync_github_name = true diff --git a/crates/aep/Cargo.toml b/crates/aep/Cargo.toml new file mode 100644 index 000000000..b1bf3f9fe --- /dev/null +++ b/crates/aep/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "effectcraft-aep" +description = "After Effects projects: the .aep (RIFX 'Egg!') / .aepx container as a lossless chunk tree with a typed view, import into an EffectCraft project and export back to .aep with every chunk built in code; each reports everything it does not carry over" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +effectcraft-time = { workspace = true } +effectcraft-color = { workspace = true } +effectcraft-keyframe = { workspace = true } +effectcraft-project = { workspace = true } +effectcraft-effects = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } + +# The tool's own tests run with the crate's (examples are only built by default). +[[example]] +name = "stubicc" +test = true diff --git a/crates/aep/README.md b/crates/aep/README.md new file mode 100644 index 000000000..5e8035d8f --- /dev/null +++ b/crates/aep/README.md @@ -0,0 +1,99 @@ +# effectcraft-aep + +After Effects projects (`.aep`, `.aepx`) in one crate, the way `effectcraft-lottie` handles Lottie: + +- `container`: reads and writes the container as a lossless chunk tree, with a typed, read-only + view (below; its API is re-exported at the crate root); +- `import`: maps the typed view into an EffectCraft project and reports everything it does not + import ([`docs/aep-import.md`](../../docs/aep-import.md)); +- `export`: writes an EffectCraft project as an `.aep` with every chunk built in code, and reports everything it does not export + ([`docs/aep-export.md`](../../docs/aep-export.md)). + +No file access: callers pass bytes, so the crate builds for wasm32. + +## Container + +An `.aep` is a `RIFX` container (big-endian RIFF) with form type `Egg!`: chunks of a 4-byte id, a +big-endian `u32` size and a body padded to an even length; `LIST` chunks start with a 4-byte list +type followed by chunks. `parse` builds the tree, `write` serialises it, and for every input that +parses, `write(parse(x)) == x` byte for byte (container and chunk sizes are recomputed from the +tree; pad bytes, odd bodies and the bytes after the container, an XMP packet, are kept). + +The XML form of a project (`.aepx`) is read into the same tree by `read_aepx` (a small bounded +XML tokenizer, no dependency); `parse_any` picks the reader by content, so the typed view and the +importer take either form. The mapping is in `docs/aep-format.md`, section 1. + +Bodies that look like lists but are not chunk sequences (for example `LIST btdk`, raw text) stay +opaque rather than failing the parse. Input is untrusted: sizes are checked against the remaining +input, nesting and chunk count are bounded (`Limits`), nothing is allocated from a declared size, +and truncated or damaged files return `Err` (or, inside the container, an opaque body). + +The container layer decodes no chunk body. On top of it, a typed view (`Project`, `Item`, `Comp`, `Layer`, +`Property`, ...) reads the fields whose layout was verified against the values the test files were made +with: layer and composition headers (switches, exact times and time stretch, size, frame rate, work area, shutter phase, display start, renderer), +static transform values in After Effects' units with the "absent = default" rule, keyframe records +(interpolation sides, ease per component, plain and spatial templates), Time Remapping, expressions with their enable switch, effect +instances and parameter values, masks and bezier paths with tangents, shape layer groups, text documents +(paragraph and style runs, box, justification, tracking, faux styles, caps, leading), markers with +duration, strings and cue data, cameras and lights with their options, footage (stills, audio, image +sequences), solids and precomp links. Every accessor returns `Option`/an empty list on damaged data and never +panics. Which fields are verified, which are not decoded, and how it was found is in +[`docs/aep-format.md`](../../docs/aep-format.md). + +## Specifications + +Public specifications used for parts the format embeds: + +- ICC.1:2010: the profile description of a working-space profile (a v2 `desc` or a v4 `mluc` + tag), from which the working space's name is read (`container/settings.rs`). +- RFC 4648 (base64): the profile data in the project's colour settings JSON (read, and written + by the exporter). +- The exporter's own colour profiles (`export/icc.rs`): ICC.1:2010 version 4.3 display profiles + with ITU-R BT.709 primaries, D65 white, a D50 PCS and a Bradford adaptation, the IEC 61966-2-1 + sRGB curve or a 2.4 power curve; the profile ID is the MD5 of RFC 1321. + +## Clean room + +Everything here comes from our own observations: project files that we generated ourselves with +After Effects, one change per file, compared byte by byte. No source code or format +documentation of another `.aep` reader or writer was used, and no Adobe asset is used. The test fixtures are such generated files +(own test data): a few combined projects, one composition per case (`tests/fixtures/CASES.md`; +the generator is in `tests/fixtures/tools/`). They are not in this repository but in +[storytold/effectcraft-corpus](https://github.com/storytold/effectcraft-corpus), with their +attribution, the generation notes and the inspection of their embedded content. +`cargo xtask aep-corpus` fetches them at the commit pinned in `tests/fixtures/corpus.lock`, checks +every file against the SHA-256 listed there and only then installs them in `corpus/aep` (ignored by +git). The tests read them from the folder named by the `EFFECTCRAFT_AEP_FIXTURES` environment +variable (opt-in; set `EFFECTCRAFT_AEP_FIXTURES_REQUIRED=1` too, so that a missing project fails). The +tests reach them only through `tests/it/common/mod.rs`, which hands a test its case as a project +of its own cut from the combined file; a test whose fixture is missing (or with the variable not +set) prints `SKIPPED: fixture missing` and passes. + +`tests/fixtures/synthetic.aep` (115 KB) is one of the two projects in the repository: made in After Effects 2026 +with the working space set to None (one composition, an image sequence of three 8x8 PNGs, a +solid, a folder, a Levels and a Glow effect with expressions). Every After Effects project embeds +the working space's ICC profile (HP sRGB IEC61966-2.1 for the default) in a JSON settings chunk; +the one `Utf8` chunk of this file that held a profile was replaced by `{}`, and nothing else was +changed. The tests in `tests/it/import/synthetic.rs` damage copies of it and need no other file. + +`tests/fixtures/ai-mask-3099.aep` (131 KB, #3099) is the second: four hand-written one-page PDFs +named `.ai` with distinct page boxes, placed in a composition, one of them with two masks under a +Null parented to a Null (generated by `tests/fixtures/tools/ai-mask-3099.py` and +`ai-mask-3099.jsx`, scrubbed with `scrub.py` and `stubicc`). `tests/it/import/ai_mask.rs` checks +the import against After Effects' read-back, and the host's `vector_import` tests render it. + +## Tools + +- `tests/fixtures/tools/`: the generator of the test projects (regenerates the corpus with After + Effects; its README says how). +- `examples/aepdump.rs`: prints the chunk tree of a file (ids, sizes, short data, match names): + `cargo run -p effectcraft-aep --example aepdump -- file.aep`. +- `examples/stubicc.rs`: replaces every embedded ICC profile of a saved project by a stub that keeps + only the profile's description: the JSON `colorProfileData` of the working space (any white space + around the colon, `\/` escapes, quotes as `"`) in an `.aep` chunk or the `.aepx` text, and a raw + profile of an imported image (an `.aep` chunk, or the `bdata` hex of an `.aepx`): + `cargo run -p effectcraft-aep --example stubicc -- in.aep out.aep`. A profile it cannot replace + stops it before anything is written. The importer reads the working space's name from the + description only, so the project imports the same; no vendor colour data stays in the test + project. Check the result independently, not by the tool's count (the corpus repository has + `tools/aep/inspect-embedded.py`, which scans the raw bytes, base64 and hex). diff --git a/crates/aep/examples/aepdump.rs b/crates/aep/examples/aepdump.rs new file mode 100644 index 000000000..2fe492696 --- /dev/null +++ b/crates/aep/examples/aepdump.rs @@ -0,0 +1,75 @@ +//! Developer tool: prints the chunk tree of an .aep (ids, sizes, short data), match names inline. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +use effectcraft_aep::{Body, Chunk}; + +/// Ends this developer tool with a message instead of a panic. +trait OrExit { + fn or_exit(self, what: &str) -> T; +} + +impl OrExit for Option { + fn or_exit(self, what: &str) -> T { + match self { + Some(v) => v, + None => exit(what), + } + } +} + +impl OrExit for Result { + fn or_exit(self, what: &str) -> T { + match self { + Ok(v) => v, + Err(e) => exit(&format!("{what}: {e:?}")), + } + } +} + +fn exit(msg: &str) -> ! { + eprintln!("{msg}"); + std::process::exit(1) +} + +fn show(c: &Chunk<'_>, depth: usize, max: usize, hex: usize) { + let ind = " ".repeat(depth); + let id = String::from_utf8_lossy(&c.id).to_string(); + match &c.body { + Body::Data(d) if &c.id == b"tdmn" => { + let n: String = d.iter().take_while(|b| **b != 0).map(|b| *b as char).collect(); + println!("{ind}tdmn {n}"); + } + Body::Data(d) => { + let h: String = d.iter().take(hex).map(|b| format!("{b:02x}")).collect(); + let a: String = d.iter().take(hex).map(|b| if (32..127).contains(b) { *b as char } else { '.' }).collect(); + println!("{ind}{id} [{}] {h} |{a}|", d.len()); + } + Body::Chunks(k) => { + println!("{ind}{id} (nested)"); + if depth < max { + for x in k { + show(x, depth + 1, max, hex); + } + } + } + Body::List { list_type, children } => { + println!("{ind}LIST {} ({} children)", String::from_utf8_lossy(list_type), children.len()); + if depth < max { + for x in children { + show(x, depth + 1, max, hex); + } + } + } + Body::OpaqueList { list_type, data } => println!("{ind}LIST {} opaque [{}]", String::from_utf8_lossy(list_type), data.len()), + } +} +fn main() { + let a: Vec = std::env::args().collect(); + let bytes = std::fs::read(a.get(1).or_exit("usage: see the comment at the top of this file")).or_exit("read"); + let max: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(4); + let hex: usize = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(32); + let f = effectcraft_aep::parse(&bytes).or_exit("parse"); + for c in &f.chunks { + show(c, 0, max, hex); + } + println!("trailer {} bytes", f.trailer.len()); +} diff --git a/crates/aep/examples/stubicc.rs b/crates/aep/examples/stubicc.rs new file mode 100644 index 000000000..9438da06d --- /dev/null +++ b/crates/aep/examples/stubicc.rs @@ -0,0 +1,359 @@ +//! Developer tool: replaces every embedded ICC profile of an .aep / .aepx by a stub that keeps only the +//! profile's description. Fixture hygiene: a saved project carries the vendor's working-space profile +//! (a few KB of colour data); the importer reads only the profile's name, the `desc` tag, so the stub +//! (a 128-byte header, one `desc` tag, no colour data, made here) imports identically. +//! +//! `cargo run -p effectcraft-aep --example stubicc -- in.aep out.aep` +//! +//! It handles: +//! - the JSON value `"colorProfileData": ""` in any chunk of an .aep and anywhere in the text +//! of an .aepx (white space around the colon, `\/` escapes and quotes written as `"` allowed); +//! - a raw ICC profile stored as a chunk of its own (the profile of an imported image), in an .aep +//! as the chunk's bytes and in an .aepx as its `bdata=""` attribute. +//! +//! A profile it cannot replace (no readable description, data that does not decode) stops the tool +//! before anything is written. Check the result independently (the corpus has +//! `tools/aep/inspect-embedded.py`), not by this tool's own count. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +use effectcraft_aep::{Body, Chunk}; + +const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/// Ends this developer tool with a message instead of a panic. +trait OrExit { + fn or_exit(self, what: &str) -> T; +} + +impl OrExit for Option { + fn or_exit(self, what: &str) -> T { + match self { + Some(v) => v, + None => exit(what), + } + } +} + +impl OrExit for Result { + fn or_exit(self, what: &str) -> T { + match self { + Ok(v) => v, + Err(e) => exit(&format!("{what}: {e:?}")), + } + } +} + +fn exit(msg: &str) -> ! { + eprintln!("{msg}"); + std::process::exit(1) +} + +fn b64_decode(text: &[u8]) -> Option> { + let (mut out, mut acc, mut bits) = (Vec::new(), 0u32, 0u32); + for &c in text.iter().filter(|c| **c != b'=') { + let v = u32::try_from(B64.iter().position(|b| *b == c)?).ok()?; + acc = (acc << 6 | v) & 0x00ff_ffff; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push(((acc >> bits) & 0xff) as u8); + } + } + Some(out) +} + +fn b64_encode(data: &[u8]) -> Vec { + let mut out = Vec::new(); + for ch in data.chunks(3) { + let at = |i: usize| u32::from(ch.get(i).copied().unwrap_or(0)); + let n = (at(0) << 16) | (at(1) << 8) | at(2); + for i in 0..4usize { + if i <= ch.len() { + out.push(B64.get(((n >> (18 - 6 * i)) & 63) as usize).copied().unwrap_or(b'A')); + } else { + out.push(b'='); + } + } + } + out +} + +fn be32(d: &[u8], at: usize) -> Option { + let b: [u8; 4] = d.get(at..at.checked_add(4)?)?.try_into().ok()?; + usize::try_from(u32::from_be_bytes(b)).ok() +} + +/// The profile description (ICC.1 `desc`: v2 ASCII or v4 `mluc`, first record). +fn description(icc: &[u8]) -> Option { + let count = be32(icc, 128)?; + let tag = (0..count.min(1024)).find_map(|i| { + let at = 132usize.checked_add(i.checked_mul(12)?)?; + (icc.get(at..at.checked_add(4)?)? == b"desc").then_some(at) + })?; + let off = be32(icc, tag.checked_add(4)?)?; + let body = icc.get(off..off.checked_add(be32(icc, tag.checked_add(8)?)?)?)?; + let text = match body.get(..4)? { + b"desc" => { + let n = be32(body, 8)?; + String::from_utf8_lossy(body.get(12..12usize.checked_add(n)?)?.split(|b| *b == 0).next()?).into_owned() + } + b"mluc" => { + let (n, at) = (be32(body, 20)?, be32(body, 24)?); + let units: Vec = body.get(at..at.checked_add(n)?)?.chunks(2).filter_map(|p| Some(u16::from_be_bytes([*p.first()?, *p.get(1)?]))).collect(); + String::from_utf16_lossy(&units) + } + _ => return None, + }; + Some(text.trim_end_matches('\0').trim().to_owned()) +} + +/// A profile with a header, one `desc` tag and no colour data. +fn stub(desc: &str) -> Option> { + let mut body = b"desc\0\0\0\0".to_vec(); + body.extend_from_slice(&u32::try_from(desc.len().checked_add(1)?).ok()?.to_be_bytes()); + body.extend_from_slice(desc.as_bytes()); + body.push(0); + body.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); + let mut p = vec![0u8; 128]; + for (at, v) in [(8, &0x0240_0000u32.to_be_bytes()[..]), (12, b"mntr"), (16, b"RGB "), (20, b"XYZ "), (36, b"acsp")] { + p.get_mut(at..at + v.len())?.copy_from_slice(v); + } + p.extend_from_slice(&1u32.to_be_bytes()); + p.extend_from_slice(b"desc"); + p.extend_from_slice(&144u32.to_be_bytes()); + p.extend_from_slice(&u32::try_from(body.len()).ok()?.to_be_bytes()); + p.extend_from_slice(&body); + let size = u32::try_from(p.len()).ok()?.to_be_bytes(); + p.get_mut(..4)?.copy_from_slice(&size); + Some(p) +} + +/// The JSON key, without its quotes. +const KEY: &[u8] = b"colorProfileData"; +/// How a JSON quote is written: as is (a `Utf8` chunk, the `` text of an .aepx) and as an +/// XML entity (JSON inside an attribute of an .aepx). +const QUOTES: [&[u8]; 2] = [b"\"", b"""]; + +/// What the tool did, counted. +#[derive(Default)] +struct Tally { + stubbed: usize, + /// Values too short to be a profile (no ICC header), kept as they are. + kept_short: usize, + /// Profiles that could not be replaced (no readable description, undecodable data): the tool + /// fails, so no profile is ever left behind silently. + failed: Vec, +} + +fn is_profile(d: &[u8]) -> bool { + d.len() > 132 && d.get(36..40) == Some(b"acsp") +} + +/// The stub for the bytes `d` of a value, or `None` (counted) when it holds no profile or the +/// profile has no readable description. +fn stub_of(d: &[u8], at: usize, tally: &mut Tally) -> Option> { + if !is_profile(d) { + tally.kept_short += 1; + return None; + } + let s = description(d).and_then(|t| stub(&t)); + if s.is_none() { + tally.failed.push(format!("profile at byte {at}: no readable description")); + } + s +} + +/// At the start of `t`: the key in quotes, optional white space, a colon, optional white space and +/// the opening quote of the value. Returns the length up to and including that quote, and the quote. +fn value_start(t: &[u8]) -> Option<(usize, &'static [u8])> { + let ws = |mut i: usize| { + while t.get(i).is_some_and(u8::is_ascii_whitespace) { + i += 1; + } + i + }; + QUOTES.into_iter().find_map(|q| { + let key_end = q.len().checked_mul(2)?.checked_add(KEY.len())?; + let quoted = t.get(..key_end)?; + if !(quoted.starts_with(q) && quoted.get(q.len()..q.len() + KEY.len())? == KEY && quoted.ends_with(q)) { + return None; + } + let colon = ws(key_end); + if t.get(colon) != Some(&b':') { + return None; + } + let open = ws(colon + 1); + t.get(open..)?.starts_with(q).then_some((open + q.len(), q)) + }) +} + +fn hex_decode(h: &[u8]) -> Option> { + if !h.len().is_multiple_of(2) { + return None; + } + h.chunks(2).map(|p| u8::from_str_radix(std::str::from_utf8(p).ok()?, 16).ok()).collect() +} + +fn hex_encode(d: &[u8], upper: bool) -> Vec { + d.iter().flat_map(|b| if upper { format!("{b:02X}") } else { format!("{b:02x}") }.into_bytes()).collect() +} + +/// Replaces, in `text`, every `colorProfileData` JSON value (base64; `\/` escapes, white space +/// around the colon and quotes written as `"` allowed) and every .aepx `bdata=""` +/// attribute that holds a raw profile. +fn stub_text(text: &[u8], tally: &mut Tally) -> Vec { + const BDATA: &[u8] = b"bdata=\""; + let (mut out, mut i) = (Vec::with_capacity(text.len()), 0); + while let Some(&b) = text.get(i) { + let rest = text.get(i..).unwrap_or_default(); + if let Some((open, q)) = value_start(rest) + && let Some(len) = rest.get(open..).and_then(|v| v.windows(q.len()).position(|w| w == q)) + { + let raw = rest.get(open..open + len).unwrap_or_default(); + let unescaped: Vec = raw.iter().copied().filter(|c| *c != b'\\').collect(); + let replaced = match b64_decode(&unescaped) { + Some(d) => stub_of(&d, i, tally).map(|s| b64_encode(&s)), + None => { + tally.failed.push(format!("colorProfileData at byte {i}: not base64")); + None + } + }; + out.extend_from_slice(rest.get(..open).unwrap_or_default()); + match replaced { + Some(enc) => { + out.extend_from_slice(&enc); + tally.stubbed += 1; + } + None => out.extend_from_slice(raw), + } + i += open + len; + continue; + } + if rest.starts_with(BDATA) + && let Some(len) = rest.get(BDATA.len()..).and_then(|v| v.iter().position(|c| *c == b'"')) + { + let hex = rest.get(BDATA.len()..BDATA.len() + len).unwrap_or_default(); + let replaced = hex_decode(hex).filter(|d| is_profile(d)).and_then(|d| stub_of(&d, i, tally)); + out.extend_from_slice(BDATA); + match replaced { + Some(s) => { + out.extend_from_slice(&hex_encode(&s, hex.iter().any(u8::is_ascii_uppercase))); + tally.stubbed += 1; + } + None => out.extend_from_slice(hex), + } + i += BDATA.len() + len; + continue; + } + out.push(b); + i += 1; + } + out +} + +fn walk(chunks: &mut [Chunk<'_>], tally: &mut Tally) { + for c in chunks.iter_mut() { + // Only a data chunk is rewritten as one: an opaque `LIST` also has bytes, but replacing it by + // a data chunk would drop its list type. + let data = if let Body::Data(d) = &c.body { Some(d.to_vec()) } else { None }; + match data { + Some(d) if d.windows(KEY.len()).any(|w| w == KEY) => { + let new = stub_text(&d, tally); + *c = Chunk::data(c.id, new); + } + Some(d) if is_profile(&d) => { + if let Some(s) = stub_of(&d, 0, tally) { + *c = Chunk::data(c.id, s); + tally.stubbed += 1; + } + } + _ => { + if let Body::List { children, .. } | Body::Chunks(children) = &mut c.body { + walk(children, tally); + } + } + } + } +} + +fn main() { + let args: Vec = std::env::args().collect(); + let (Some(input), Some(output)) = (args.get(1), args.get(2)) else { exit("usage: stubicc ") }; + let bytes = std::fs::read(input).or_exit("read the input"); + let mut tally = Tally::default(); + let out = if input.ends_with(".aepx") { + stub_text(&bytes, &mut tally) + } else { + let mut file = effectcraft_aep::parse(&bytes).or_exit("parse the input"); + walk(&mut file.chunks, &mut tally); + effectcraft_aep::write(&file).or_exit("write the output") + }; + if !tally.failed.is_empty() { + exit(&format!("nothing written: {} profile(s) could not be replaced:\n{}", tally.failed.len(), tally.failed.join("\n"))); + } + std::fs::write(output, out).or_exit("write the output"); + println!("stubbed {} profile(s); kept {} short value(s) that hold no profile", tally.stubbed, tally.kept_short); +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn profile(desc: &str) -> Vec { + // A profile with colour data after the description (like a real one): the stub of `desc` + // plus 3000 bytes, its size field updated. + let mut p = stub(desc).unwrap(); + p.extend(std::iter::repeat_n(0x5a, 3000)); + let size = u32::try_from(p.len()).unwrap().to_be_bytes(); + p[..4].copy_from_slice(&size); + p + } + + fn stubbed(text: &[u8]) -> (Vec, Tally) { + let mut tally = Tally::default(); + (stub_text(text, &mut tally), tally) + } + + #[test] + fn json_values_in_every_spelling_are_replaced() { + let b64 = String::from_utf8(b64_encode(&profile("sRGB IEC61966-2.1"))).unwrap(); + let want = String::from_utf8(b64_encode(&stub("sRGB IEC61966-2.1").unwrap())).unwrap(); + for (before, after) in [ + (format!("{{\"colorProfileData\":\"{b64}\"}}"), format!("{{\"colorProfileData\":\"{want}\"}}")), + (format!("{{\"colorProfileData\" : \n\t\"{b64}\"}}"), format!("{{\"colorProfileData\" : \n\t\"{want}\"}}")), + (format!("{{\"colorProfileData\":\"{}\"}}", b64.replace('/', "\\/")), format!("{{\"colorProfileData\":\"{want}\"}}")), + (format!("{{"colorProfileData": "{b64}"}}"), format!("{{"colorProfileData": "{want}"}}")), + ] { + let (out, tally) = stubbed(before.as_bytes()); + assert_eq!(String::from_utf8(out).unwrap(), after); + assert_eq!((tally.stubbed, tally.failed.len()), (1, 0)); + } + } + + #[test] + fn a_raw_profile_in_aepx_hex_is_replaced_and_other_hex_kept() { + let hex = String::from_utf8(hex_encode(&profile("Rec.709 Gamma 2.4"), false)).unwrap(); + let want = String::from_utf8(hex_encode(&stub("Rec.709 Gamma 2.4").unwrap(), false)).unwrap(); + let text = format!("", "ab".repeat(200)); + let (out, tally) = stubbed(text.as_bytes()); + assert_eq!(String::from_utf8(out).unwrap(), format!("", "ab".repeat(200))); + assert_eq!((tally.stubbed, tally.failed.len()), (1, 0)); + // Upper-case hex stays upper case. + let (out, _) = stubbed(format!("bdata=\"{}\"", hex.to_uppercase()).as_bytes()); + assert_eq!(String::from_utf8(out).unwrap(), format!("bdata=\"{}\"", want.to_uppercase())); + } + + #[test] + fn a_profile_that_cannot_be_replaced_is_a_failure_not_a_silent_copy() { + // An ICC header whose tag table has no `desc`. + let mut p = profile("x"); + p[132..136].copy_from_slice(b"wtpt"); + let (_, tally) = stubbed(format!("\"colorProfileData\":\"{}\"", String::from_utf8(b64_encode(&p)).unwrap()).as_bytes()); + assert_eq!((tally.stubbed, tally.failed.len()), (0, 1)); + let (_, tally) = stubbed(b"\"colorProfileData\":\"not*base64\""); + assert_eq!(tally.failed.len(), 1); + // A short value holds no profile: kept and counted, not a failure. + let (out, tally) = stubbed(b"\"colorProfileData\":\"AAAA\""); + assert_eq!((out.as_slice(), tally.kept_short, tally.failed.len()), (&b"\"colorProfileData\":\"AAAA\""[..], 1, 0)); + } +} diff --git a/crates/aep/src/container.rs b/crates/aep/src/container.rs new file mode 100644 index 000000000..531d74843 --- /dev/null +++ b/crates/aep/src/container.rs @@ -0,0 +1,61 @@ +//! After Effects project (`.aep`) container reader and writer. +//! +//! An `.aep` is a `RIFX` container (big-endian RIFF) with form type `Egg!`. This crate reads it +//! into a lossless chunk tree ([`AepFile`]) and writes it back byte for byte. The XML form of a +//! project (`.aepx`) is read into the same tree by [`read_aepx`]; [`parse_any`] picks the reader +//! by content. See +//! `docs/aep-format.md` for the observed format and how it was established (clean room: only +//! files we generated ourselves, one change per file). +//! +//! [`Project::new`] opens a typed, read-only view over the tree: items, compositions +//! ([`CompHeader`]), layers ([`LayerHeader`], [`Transform`], effects, masks, text documents, +//! markers), properties, keyframes and footage. Only fields whose layout was verified against the +//! values the test files were made with are decoded; every accessor returns `None` (or an empty +//! list) on damaged data instead of failing. + +mod aepx; +mod arbitrary; +mod bytes; +mod camera; +mod chunk; +pub mod effect_map; +mod effects; +mod error; +mod footage; +mod header; +mod keys; +mod masks; +mod matte; +mod read; +mod settings; +mod shapes; +pub mod style_map; +mod textdoc; +mod typed; +mod values; +mod version; +mod write; + +pub use aepx::{is_aepx, parse_any, read_aepx, read_aepx_with_limits}; +pub use arbitrary::{ + CURVE_IDENTITY, CryptomatteData, CurvesData, ExtractorChannels, HueSaturationData, LevelsData, MeshData, curve_lut, identifier_channel_type, +}; +pub use camera::{CameraPosition, DEFAULT_CAMERA_ZOOM}; +pub use chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; +pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue}; +pub use error::AepError; +pub use footage::{Footage, SequenceInfo}; +pub use header::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Quality, Rational, Renderer}; +pub use keys::{ExpressionFlags, Interpolation, KeyEase, KeyframeKind, SpatialKey}; +pub use masks::{Mask, MaskAtom, MaskMode, PathVertex, ShapePath}; +pub use matte::{MatteMode, TrackMatte}; +pub use read::{Limits, parse, parse_with_limits}; +pub use settings::{ProjectSettings, TimeDisplay, WorkingSpace}; +pub use shapes::{GradientType, PolystarType, ShapeDetail, ShapeGroup, ShapeItem, Stroke, StrokeCap, StrokeJoin}; +pub use textdoc::{ + AutoKern, Caps, CueType, FontBaseline, Justification, KernRun, Marker, ParagraphRun, StyleRun, TextBox, TextDocument, TextValue, parse_text_dict, +}; +pub use typed::{Comp, Item, ItemKind, KeyLayout, KeyList, Keyframe, Layer, ListHeader, Project, PropEntry, PropGroup, PropNode, Property, TimeBase}; +pub use values::{Orientation, OrientationKey, TimeRemap, TimeRemapKey, Tracked, Transform, ValueSource}; +pub use version::AeVersion; +pub use write::{write, write_to}; diff --git a/crates/aep/src/container/aepx.rs b/crates/aep/src/container/aepx.rs new file mode 100644 index 000000000..a45cbae1d --- /dev/null +++ b/crates/aep/src/container/aepx.rs @@ -0,0 +1,640 @@ +//! Reading the XML form of a project (`.aepx`) into the same chunk tree as an `.aep`. +//! +//! An `.aepx` is the `RIFX` chunk tree written as XML: one element per chunk, named by the chunk +//! id (or the list type of a `LIST`), with the body as hex in a `bdata` attribute. A few chunks +//! are written as text instead (`Utf8` as ``, the numbers `numS` and `ppSn`, the footage +//! alias `alas` as ``), and the XMP packet that follows the container of an `.aep` +//! is the element ``. The mapping, with the cases it was found on, is in +//! `docs/aep-format.md` (section 1.1). +//! +//! The reader is a small XML tokenizer for exactly that subset: elements, attributes, text, the +//! five predefined entities and character references, CDATA, comments and processing +//! instructions. A document type declaration is refused (no entity expansion). It runs without +//! recursion; the nesting depth and the element count are bounded by [`Limits`], and everything +//! it allocates is bounded by the size of the input. + +use std::borrow::Cow; + +use crate::container::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; +use crate::container::error::AepError; +use crate::container::read::{Limits, parse}; + +/// The root element of an `.aepx`. +const ROOT: &[u8] = b"AfterEffectsProject"; +/// The element that holds the XMP packet (the trailer of an `.aep`). +const XMP: &[u8] = b"ProjectXMPMetadata"; +/// The element of a `Utf8` chunk. +const STRING: &[u8] = b"string"; +/// The element of an `alas` chunk (footage alias), written as attributes instead of JSON. +const FILE_REFERENCE: &[u8] = b"fileReference"; + +/// List types whose body is not a chunk sequence: the `.aepx` writes them like data chunks (with +/// `bdata`), the `.aep` as an opaque `LIST`. +const OPAQUE_LIST_TYPES: [[u8; 4]; 1] = [*b"btdk"]; + +/// True when `data` looks like an `.aepx`: optional UTF-8 byte order mark and white space, then +/// an XML declaration or the `AfterEffectsProject` root element. +pub fn is_aepx(data: &[u8]) -> bool { + let rest = data.strip_prefix(&[0xef, 0xbb, 0xbf][..]).unwrap_or(data); + let start = rest.iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(rest.len()); + let rest = rest.get(start..).unwrap_or(&[]); + rest.starts_with(b" Result, AepError> { + if is_aepx(data) { read_aepx(data) } else { parse(data) } +} + +/// Reads an `.aepx` with the default [`Limits`] into the chunk tree an `.aep` of the same project +/// gives. +/// +/// # Errors +/// [`AepError::Xml`] for input that is not well-formed XML of the `.aepx` subset (bad UTF-8, an +/// unknown entity, an unclosed or mismatched tag, invalid or odd-length hex, a number that does +/// not parse, a document type declaration, a root element other than `AfterEffectsProject`); +/// [`AepError::TooDeep`] / [`AepError::TooManyChunks`] beyond the limits. +pub fn read_aepx(data: &[u8]) -> Result, AepError> { + read_aepx_with_limits(data, Limits::default()) +} + +/// Like [`read_aepx`] with explicit [`Limits`]: `max_depth` bounds the element nesting (the root +/// element's children are depth 1), `max_chunks` the number of elements. +/// +/// # Errors +/// See [`read_aepx`]. +pub fn read_aepx_with_limits(data: &[u8], limits: Limits) -> Result, AepError> { + let text = match std::str::from_utf8(data) { + Ok(t) => t.as_bytes(), + Err(e) => return Err(xml(e.valid_up_to(), "the file is not valid UTF-8")), + }; + Reader { data: text, pos: 0, limits, count: 0, stack: Vec::new(), top: None, trailer: None }.run() +} + +fn xml(offset: usize, what: &'static str) -> AepError { + AepError::Xml { offset, what } +} + +/// What an open element becomes when it closes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + /// The root element: its children are the top-level chunks. + Root, + /// A chunk with this id (or a `LIST` with this list type). + Chunk([u8; 4]), + /// A `Utf8` chunk. + Utf8, + /// An `alas` chunk built from the attributes. + Alias, + /// The XMP packet (only directly below the root). + Xmp, + /// An element without a chunk counterpart (a name that is no chunk id); skipped with its content. + Skip, +} + +struct Frame { + kind: Kind, + /// Offset of the start tag (for errors). + at: usize, + /// The name as written, to match the end tag. + name: (usize, usize), + /// The decoded `bdata` attribute. + bdata: Option>, + /// The attributes of a `fileReference`, in document order. + attrs: Vec<(String, String)>, + /// Collected text (only for `string` and the XMP packet). + text: Vec, + children: Vec>, +} + +struct Reader<'d> { + data: &'d [u8], + pos: usize, + limits: Limits, + count: usize, + stack: Vec, + /// The top-level chunks once the root element has closed. + top: Option>>, + trailer: Option>, +} + +impl Reader<'_> { + fn run(mut self) -> Result, AepError> { + if self.data.starts_with(&[0xef, 0xbb, 0xbf]) { + self.pos = 3; + } + while self.pos < self.data.len() { + if self.rest().starts_with(b"<") { + self.markup()?; + } else { + self.text()?; + } + } + if let Some(open) = self.stack.last() { + return Err(xml(open.at, "an element is not closed before the end of the file")); + } + let chunks = self.top.ok_or_else(|| xml(self.data.len(), "no AfterEffectsProject root element"))?; + Ok(AepFile { chunks, trailer: Cow::Owned(self.trailer.unwrap_or_default()) }) + } + + fn rest(&self) -> &[u8] { + self.data.get(self.pos..).unwrap_or(&[]) + } + + /// The offset of `needle` at or after `from`. + fn find(&self, from: usize, needle: &[u8]) -> Option { + let hay = self.data.get(from..)?; + if needle.is_empty() || hay.len() < needle.len() { + return None; + } + let first = *needle.first()?; + let mut i = 0; + while let Some(p) = hay.get(i..)?.iter().position(|b| *b == first) { + let at = i.checked_add(p)?; + if hay.get(at..)?.starts_with(needle) { + return from.checked_add(at); + } + i = at.checked_add(1)?; + } + None + } + + /// Skips to just after `close`, which must follow. + fn skip_past(&mut self, close: &[u8], what: &'static str) -> Result { + let at = self.find(self.pos, close).ok_or(xml(self.pos, what))?; + self.pos = at.saturating_add(close.len()); + Ok(at) + } + + fn markup(&mut self) -> Result<(), AepError> { + let rest = self.rest(); + if rest.starts_with(b"", "a processing instruction is not closed")?; + } else if rest.starts_with(b"", "a comment is not closed")?; + } else if rest.starts_with(b"", "a CDATA section is not closed")?; + let content = self.data.get(start..end).unwrap_or(&[]); + let at = start; + match self.stack.last_mut() { + Some(frame) => { + if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) { + frame.text.extend_from_slice(content); + } + } + None => return Err(xml(at, "CDATA outside the root element")), + } + } else if rest.starts_with(b" bool { + !(b.is_ascii_whitespace() || matches!(b, b'<' | b'>' | b'/' | b'=' | b'"' | b'\'' | b'&')) + } + + fn name(&mut self) -> Result<(usize, usize), AepError> { + let start = self.pos; + let len = self.rest().iter().position(|b| !Self::is_name_byte(*b)).unwrap_or(self.rest().len()); + if len == 0 { + return Err(xml(start, "a tag or attribute has no name")); + } + self.pos = start.saturating_add(len); + Ok((start, self.pos)) + } + + fn skip_ws(&mut self) { + let n = self.rest().iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(self.rest().len()); + self.pos = self.pos.saturating_add(n); + } + + fn slice(&self, (a, b): (usize, usize)) -> &[u8] { + self.data.get(a..b).unwrap_or(&[]) + } + + fn start_tag(&mut self) -> Result<(), AepError> { + let at = self.pos; + self.pos = self.pos.saturating_add(1); + let name = self.name()?; + let mut attrs: Vec<((usize, usize), Vec)> = Vec::new(); + let self_closing = loop { + self.skip_ws(); + let rest = self.rest(); + if rest.starts_with(b"/>") { + self.pos = self.pos.saturating_add(2); + break true; + } + if rest.starts_with(b">") { + self.pos = self.pos.saturating_add(1); + break false; + } + if rest.is_empty() { + return Err(xml(at, "a start tag is not closed")); + } + let key = self.name()?; + self.skip_ws(); + if !self.rest().starts_with(b"=") { + return Err(xml(self.pos, "an attribute has no value")); + } + self.pos = self.pos.saturating_add(1); + self.skip_ws(); + let quote = *self.rest().first().ok_or(xml(self.pos, "a start tag is not closed"))?; + if quote != b'"' && quote != b'\'' { + return Err(xml(self.pos, "an attribute value is not quoted")); + } + let vstart = self.pos.saturating_add(1); + let vend = self.find(vstart, &[quote]).ok_or(xml(vstart, "an attribute value is not closed"))?; + let raw = self.data.get(vstart..vend).unwrap_or(&[]); + if raw.contains(&b'<') { + return Err(xml(vstart, "`<` inside an attribute value")); + } + let mut value = Vec::new(); + decode_entities(raw, vstart, &mut value)?; + self.pos = vend.saturating_add(1); + attrs.push((key, value)); + }; + let kind = self.kind_of(name, at)?; + if kind != Kind::Root { + self.count = self.count.saturating_add(1); + if self.count > self.limits.max_chunks { + return Err(AepError::TooManyChunks); + } + // The root's children are depth 1, like the top-level chunks of an `.aep`. + if self.stack.len() > self.limits.max_depth { + return Err(AepError::TooDeep); + } + } + let mut frame = Frame { kind, at, name, bdata: None, attrs: Vec::new(), text: Vec::new(), children: Vec::new() }; + if matches!(kind, Kind::Chunk(_)) { + if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { + frame.bdata = Some(decode_hex(value, key.1)?); + } + } else if kind == Kind::Alias { + frame.attrs = attrs.iter().map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())).collect(); + } + self.stack.push(frame); + if self_closing { + self.close()?; + } + Ok(()) + } + + /// Classifies an element by its name and where it is. + fn kind_of(&self, name: (usize, usize), at: usize) -> Result { + let n = self.slice(name); + let parent = match self.stack.last() { + None => { + if self.top.is_some() { + return Err(xml(at, "a second root element")); + } + if n != ROOT { + return Err(xml(at, "the root element is not AfterEffectsProject")); + } + return Ok(Kind::Root); + } + Some(p) => p.kind, + }; + Ok(match parent { + Kind::Skip | Kind::Utf8 | Kind::Xmp | Kind::Alias => Kind::Skip, + Kind::Root | Kind::Chunk(_) => { + if n == STRING { + Kind::Utf8 + } else if n == FILE_REFERENCE { + Kind::Alias + } else if n == XMP && parent == Kind::Root { + Kind::Xmp + } else if let Some(id) = chunk_id(n) { + Kind::Chunk(id) + } else { + Kind::Skip + } + } + }) + } + + fn end_tag(&mut self) -> Result<(), AepError> { + let at = self.pos; + self.pos = self.pos.saturating_add(2); + let name = self.name()?; + self.skip_ws(); + if !self.rest().starts_with(b">") { + return Err(xml(at, "an end tag is not closed")); + } + self.pos = self.pos.saturating_add(1); + let open = self.stack.last().ok_or(xml(at, "an end tag without a start tag"))?; + if self.slice(open.name) != self.slice(name) { + return Err(xml(at, "an end tag does not match its start tag")); + } + self.close() + } + + /// Closes the innermost element and hands its chunk to the parent. + fn close(&mut self) -> Result<(), AepError> { + let frame = self.stack.pop().ok_or(xml(self.pos, "an end tag without a start tag"))?; + let chunk = match frame.kind { + Kind::Root => { + self.top = Some(frame.children); + return Ok(()); + } + Kind::Skip => return Ok(()), + Kind::Xmp => { + if self.trailer.is_none() { + self.trailer = Some(frame.text); + } + return Ok(()); + } + Kind::Utf8 => Chunk::data(*b"Utf8", frame.text), + Kind::Alias => Chunk::data(*b"alas", alias_json(&frame.attrs).into_bytes()), + Kind::Chunk(id) => chunk_of(id, frame)?, + }; + if let Some(parent) = self.stack.last_mut() { + parent.children.push(chunk); + } + Ok(()) + } + + fn text(&mut self) -> Result<(), AepError> { + let start = self.pos; + let len = self.rest().iter().position(|b| *b == b'<').unwrap_or(self.rest().len()); + let end = start.saturating_add(len); + self.pos = end; + let raw = self.data.get(start..end).unwrap_or(&[]); + match self.stack.last_mut() { + Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut frame.text), + Some(_) => Ok(()), + None if raw.iter().all(u8::is_ascii_whitespace) => Ok(()), + None => Err(xml(start, "text outside the root element")), + } + } +} + +/// The chunk id of an element name: 1 to 4 printable ASCII bytes, padded with spaces (`Pin` is +/// the list type `Pin `). +fn chunk_id(name: &[u8]) -> Option<[u8; 4]> { + if name.is_empty() || name.len() > 4 || !name.iter().all(|b| b.is_ascii_graphic()) { + return None; + } + let mut id = [b' '; 4]; + for (d, s) in id.iter_mut().zip(name) { + *d = *s; + } + Some(id) +} + +/// The chunk of a closed element named by a chunk id. +fn chunk_of(id: [u8; 4], frame: Frame) -> Result, AepError> { + if let Some(bytes) = frame.bdata { + if OPAQUE_LIST_TYPES.contains(&id) { + let pad = if bytes.len() % 2 == 1 { Some(0) } else { None }; + return Ok(Chunk { id: LIST, body: Body::OpaqueList { list_type: id, data: Cow::Owned(bytes) }, pad }); + } + return Ok(Chunk::data(id, bytes)); + } + // Numbers written as text: `0` and `150.000000000`. + if &id == b"numS" || &id == b"ppSn" { + let text = match frame.children.as_slice() { + [only] if only.is(b"Utf8") => only.bytes().unwrap_or(&[]), + _ => return Err(xml(frame.at, "a numS or ppSn element without its number")), + }; + let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); + let body = if &id == b"numS" { + // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. + let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); + let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; + (n as u32).to_be_bytes().to_vec() + } else { + text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes().to_vec() + }; + return Ok(Chunk::data(id, body)); + } + if NESTED_IDS.contains(&id) { + if frame.children.is_empty() { + return Ok(Chunk::data(id, Vec::new())); + } + return Ok(Chunk { id, body: Body::Chunks(frame.children), pad: None }); + } + Ok(Chunk::list(id, frame.children)) +} + +/// Appends `raw` with the predefined entities and character references decoded. +fn decode_entities(raw: &[u8], offset: usize, out: &mut Vec) -> Result<(), AepError> { + let mut i = 0; + while let Some(rest) = raw.get(i..) { + let Some(amp) = rest.iter().position(|b| *b == b'&') else { + out.extend_from_slice(rest); + break; + }; + out.extend_from_slice(rest.get(..amp).unwrap_or(&[])); + let at = offset.saturating_add(i).saturating_add(amp); + let after = rest.get(amp.saturating_add(1)..).unwrap_or(&[]); + let semi = after.iter().take(12).position(|b| *b == b';').ok_or(xml(at, "an entity is not terminated"))?; + let name = after.get(..semi).unwrap_or(&[]); + let ch = match name { + b"amp" => '&', + b"lt" => '<', + b"gt" => '>', + b"quot" => '"', + b"apos" => '\'', + _ => { + let code = if let Some(hex) = name.strip_prefix(b"#x").or_else(|| name.strip_prefix(b"#X")) { + std::str::from_utf8(hex).ok().and_then(|h| u32::from_str_radix(h, 16).ok()) + } else if let Some(dec) = name.strip_prefix(b"#") { + std::str::from_utf8(dec).ok().and_then(|d| d.parse::().ok()) + } else { + return Err(xml(at, "an unknown entity")); + }; + code.filter(|c| *c != 0).and_then(char::from_u32).ok_or(xml(at, "an invalid character reference"))? + } + }; + let mut buf = [0u8; 4]; + out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); + i = i.saturating_add(amp).saturating_add(semi).saturating_add(2); + } + Ok(()) +} + +/// Decodes a `bdata` value (hex digits, two per byte). +fn decode_hex(text: &[u8], offset: usize) -> Result, AepError> { + if text.len() % 2 == 1 { + return Err(xml(offset, "bdata has an odd number of hex digits")); + } + let digit = |b: u8| match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + }; + let (pairs, _) = text.as_chunks::<2>(); + pairs + .iter() + .map(|[hi, lo]| digit(*hi).zip(digit(*lo)).map(|(h, l)| (h << 4) | l)) + .collect::>>() + .ok_or(xml(offset, "bdata holds a character that is not a hex digit")) +} + +/// The JSON body of an `alas` chunk from the attributes of a `fileReference`, keys in document +/// order (alphabetical in every sample, as in the `.aep`): the two `ascendcount_*` values as +/// numbers, `platform` `Win` as `1`, `target_is_folder` `0` / `1` as `false` / `true`, everything +/// else as a string. +fn alias_json(attrs: &[(String, String)]) -> String { + let mut out = String::from("{"); + for (i, (key, value)) in attrs.iter().enumerate() { + if i > 0 { + out.push(','); + } + json_str(&mut out, key); + out.push(':'); + let number = value.parse::().ok(); + match (key.as_str(), value.as_str()) { + ("ascendcount_base" | "ascendcount_target", _) if number.is_some() => out.push_str(value), + ("platform", "Win") => out.push('1'), + ("platform", _) if number.is_some() => out.push_str(value), + ("target_is_folder", "0" | "false") => out.push_str("false"), + ("target_is_folder", "1" | "true") => out.push_str("true"), + _ => json_str(&mut out, value), + } + } + out.push('}'); + out +} + +fn json_str(out: &mut String, s: &str) { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if u32::from(c) < 0x20 => out.push_str(&format!("\\u{:04x}", u32::from(c))), + c => out.push(c), + } + } + out.push('"'); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn doc(body: &str) -> String { + format!("\n{body}\n") + } + + #[test] + fn maps_elements_to_chunks() { + let x = doc(concat!( + "\n", + "A & BA-3", + "150.000000000x", + "]]>" + )); + let f = read_aepx(x.as_bytes()).unwrap(); + assert_eq!(f.trailer.as_ref(), b""); + let ids: Vec<_> = f.chunks.iter().map(|c| (c.id, c.list_type())).collect(); + assert_eq!( + ids, + vec![ + (*b"head", None), + (LIST, Some(*b"Pin ")), + (LIST, Some(*b"Pefl")), + (*b"tdsn", None), + (*b"numS", None), + (*b"ppSn", None), + (LIST, Some(*b"btdk")) + ] + ); + assert_eq!(f.chunks[1].children()[0].bytes(), Some(&[1u8][..])); + assert_eq!(f.chunks[1].children()[0].pad, Some(0)); + assert_eq!(f.chunks[3].children()[0].bytes(), Some(&b"A & BA"[..])); + assert_eq!(f.chunks[4].bytes(), Some(&(-3i32).to_be_bytes()[..])); + assert_eq!(f.chunks[5].bytes(), Some(&150f64.to_be_bytes()[..])); + assert_eq!(f.chunks[6].bytes(), Some(&b"ABC"[..])); + // The tree writes as a valid `.aep` that parses back to itself. + let bin = crate::container::write(&f).unwrap(); + assert_eq!(parse(&bin).unwrap(), f); + } + + #[test] + fn file_reference_becomes_alias_json() { + let x = doc(concat!( + "" + )); + let f = read_aepx(x.as_bytes()).unwrap(); + let alas = f.chunks[0].children()[0].bytes().unwrap(); + assert_eq!( + std::str::from_utf8(alas).unwrap(), + r#"{"ascendcount_base":1,"ascendcount_target":1,"fullpath":"C:\\a\\\"b.png","platform":1,"server_name":"N","server_volume_name":"V","target_is_folder":false}"# + ); + } + + #[test] + fn nums_takes_signed_and_unsigned_32_bit_values() { + for (text, bytes) in [("-2147483648", [0x80, 0, 0, 0]), ("4294967295", [0xff; 4]), (" 7 ", [0, 0, 0, 7])] { + let f = read_aepx(doc(&format!("{text}")).as_bytes()).unwrap(); + assert_eq!(f.chunks[0].bytes(), Some(&bytes[..]), "{text}"); + } + for text in ["-2147483649", "4294967296", "1.5"] { + assert!(read_aepx(doc(&format!("{text}")).as_bytes()).is_err(), "{text}"); + } + } + + #[test] + fn detection() { + assert!(is_aepx(b"\xef\xbb\xbf ")); + assert!(is_aepx(b"")); + assert!(!is_aepx(b"RIFX\0\0\0\x04Egg!")); + assert!(parse_any(b"RIFX\0\0\0\x04Egg!").is_ok()); + assert!(parse_any(doc("").as_bytes()).is_ok()); + } + + #[test] + fn bad_input_is_an_error() { + let bad = [ + doc(""), + doc(""), + doc(" "), + doc("�"), + doc("&"), + doc(""), + doc(""), + doc("x"), + doc(""), + doc(""), + doc(""), + "]>".into(), + "".into(), + "".into(), + "".into(), + "junk".into(), + "]]>"), 2); assert_eq!(super::import::json_depth(br#"{"a": "[[[{{", "b": [[1], {"c": "\\\"["}]}"#), 3); } + +/// A hostile project: footage in a folder whose parents loop back to it. Export walked the +/// folder's parents recursively and never reached the cache insert, so the stack ran out. +#[test] +fn export_survives_a_folder_parent_cycle() { + let (mut p, cid) = ae_project(); + let a = p.add_item("A", effectcraft_color::Label::None, None, ItemKind::Folder); + let b = p.add_item("B", effectcraft_color::Label::None, Some(a), ItemKind::Folder); + p.items.get_mut(&a).unwrap().parent = Some(b); + let footage: Vec = p.items.values().filter(|i| matches!(i.kind, ItemKind::Footage(_))).map(|i| i.id).collect(); + for f in footage { + p.items.get_mut(&f).unwrap().parent = Some(a); + } + let out = export(&p, cid, &ExportOptions::default(), &HashMap::new()).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("contains itself")), "{:?}", out.warnings); +} + +/// Precomps that use each other, and a chain of comps that each use the next one twice: the +/// audio check recursed forever on the first and 2^depth times on the second. +#[test] +fn export_audio_check_ends_on_precomp_cycles_and_shared_chains() { + let mut p = Project::default(); + let a = footage_item(&mut p, "/media/a.mov"); + let comp = || Comp::new(W, H, FrameRate::new(25, 1), t(2.0)); + // A chain of 60 comps, each using the next twice; the last one is silent footage. + let mut next = { + let mut c = comp(); + let l = effectcraft_project::build::layer(&mut p, &c, "a", LayerSource::Footage { item: a }, (W, H), None); + c.layers.push(l); + comp_item(&mut p, "Leaf", c) + }; + for i in 0..60 { + let mut c = comp(); + for n in 0..2 { + let l = effectcraft_project::build::layer(&mut p, &c, &format!("use {n}"), LayerSource::Comp { item: next }, (W, H), None); + c.layers.push(l); + } + next = comp_item(&mut p, &format!("Chain {i}"), c); + } + let started = std::time::Instant::now(); + export(&p, next, &ExportOptions::default(), &HashMap::new()).unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(30), "{:?}", started.elapsed()); + // Two comps nesting each other. + let x = comp_item(&mut p, "X", comp()); + let mut y = comp(); + let l = effectcraft_project::build::layer(&mut p, &y, "x", LayerSource::Comp { item: x }, (W, H), None); + y.layers.push(l); + let y = comp_item(&mut p, "Y", y); + let mut xc = comp(); + let l = effectcraft_project::build::layer(&mut p, &xc, "y", LayerSource::Comp { item: y }, (W, H), None); + xc.layers.push(l); + if let Some(ItemKind::Comp(c)) = p.items.get_mut(&x).map(|i| &mut i.kind) { + *c = Arc::new(xc); + } + export(&p, x, &ExportOptions::default(), &HashMap::new()).unwrap(); +} + +/// A flat edit with many clips and many transitions: each clip finds its own transitions (it +/// scanned every transition of the track per clip), and they still extend and fade it. +#[test] +fn import_finds_each_clips_transitions_without_scanning_the_track() { + let mut p = fp::Project::new("Flat"); + let a = media(&mut p, "a.png", "/media/a.mov", filmcraft_media::MediaKind::Movie, true, false, None); + let settings = fp::SequenceSettings { width: W, height: H, frame_rate: rate(), ..Default::default() }; + let main = p.new_sequence("Main", settings, 1, 0, None); + const N: usize = 500; + let mut items = Vec::with_capacity(N); + let mut transitions = Vec::with_capacity(N); + for i in 0..N { + let ti = item(&mut p, a, fp::TrackKind::Video, i as f64 * 0.4, 0.0, 0.4); + if let Some(prev) = items.last().map(|x: &fp::TrackItem| x.id) { + transitions.push(fp::Transition { + id: fp::TransitionId(p.alloc_id()), + effect: fp::find_effect("cross_dissolve").unwrap().instance(), + start: secs(i as f64 * 0.4 - 0.08), + duration: secs(0.16), + from: Some(prev), + to: Some(ti.id), + align: fp::TransitionAlign::CenterAtCut, + reverse: false, + }); + } + items.push(ti); + } + let seq = p.sequence_mut(main).unwrap(); + seq.video_tracks[0].items = items; + seq.video_tracks[0].transitions = transitions; + let (bytes, _) = fc::export(&p, main, fc::Format::Otio, &Default::default()).unwrap(); + let (q, r) = import_doc(&bytes, "Flat.otio", &mut probe); + let m = q.comp(r.comps[0]).unwrap(); + assert_eq!(m.layers.len(), N); + // A middle clip reaches over both of its transitions' handles. + let mid = m.layers.iter().find(|l| near(l.in_point, t(100.0 - 0.08))).expect("clip 250 extended into its incoming transition"); + assert!(near(mid.out_point, t(100.4 + 0.08)), "{}", mid.out_point.seconds()); +} diff --git a/crates/keyframe/src/lib.rs b/crates/keyframe/src/lib.rs index abf929fe9..0998790a1 100644 --- a/crates/keyframe/src/lib.rs +++ b/crates/keyframe/src/lib.rs @@ -57,6 +57,12 @@ impl Ease { pub const EASY: Ease = Ease { speed: 0.0, influence: 1.0 / 3.0 }; } +/// Influence of a linear key side in a segment whose other side is eased: the side keeps the +/// segment's average speed with a 16.67 % influence, as After Effects shows it in the Keyframe +/// Velocity dialog and evaluates it (time-remap read-backs: a bezier-out (speed 0, 50 %) into a +/// linear-in from 3.5 to 0.5 over 2 s gives 3.290 at a quarter and 2.657 at half of the segment). +pub const LINEAR_SIDE_INFLUENCE: f64 = 1.0 / 6.0; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Keyframe { pub time: Tick, @@ -408,7 +414,7 @@ fn effective_ease>(keys: &[K], i: usize, d: usize, spatial: /// The ease a key side presents in the Graph Editor and the Keyframe Velocity dialog: stored /// Bezier eases, auto-Bezier slopes, or the equivalent of a linear side (speed of the straight -/// segment, 33.3 % influence). `None` for hold sides and sides without a neighbour. +/// segment, [`LINEAR_SIDE_INFLUENCE`]). `None` for hold sides and sides without a neighbour. pub fn side_ease(keys: &[Keyframe], i: usize, d: usize, spatial: bool, out: bool) -> Option { let k = keys.get(i)?; let j = if out { i + 1 } else { i.checked_sub(1)? }; @@ -429,7 +435,7 @@ pub fn side_ease(keys: &[Keyframe], i: usize, d: usize, spatial: bool, out: bool let dv = b.get(d).unwrap_or(&0.0) - a.get(d).unwrap_or(&0.0); if out { dv } else { -dv } }; - return Some(Ease { speed: dv / dur, influence: 1.0 / 3.0 }); + return Some(Ease { speed: dv / dur, influence: LINEAR_SIDE_INFLUENCE }); } Some(effective_ease(keys, i, if is_spatial { 0 } else { d }, is_spatial, out)) } @@ -546,6 +552,63 @@ fn evaluate_active>(keys: &[K], t: Tick, spatial: bool) -> O Some(segment_value_of(keys, i, t, spatial)) } +/// Evaluate keyed 3D Orientation at `t` as After Effects does: the temporal ease gives the +/// progress through each segment, and the rotation moves along the shortest arc between the two +/// keys ([`effectcraft_geom::orientation_slerp`]) instead of blending each angle. Speeds are +/// degrees per second along that arc. Values other than 3D vectors evaluate as [`evaluate`]. +pub fn evaluate_orientation(keys: &[Keyframe], t: Tick) -> Option { + let first = keys.first()?; + if keys.len() == 1 || t <= first.time { + return Some(first.value.clone()); + } + let last = keys.last()?; + if t >= last.time { + return Some(last.value.clone()); + } + let i = keys.partition_point(|k| k.time <= t).checked_sub(1)?; + let (a, b) = (keys.get(i)?, keys.get(i + 1)?); + let (Value::Vec3(va), Value::Vec3(vb)) = (&a.value, &b.value) else { return Some(segment_value(keys, i, t, false)) }; + if a.out_interp == Interp::Hold { + return Some(a.value.clone()); + } + let (t0, t1) = (secs(a.time), secs(b.time)); + let dur = (t1 - t0).max(1e-12); + let x = ((secs(t) - t0) / dur).clamp(0.0, 1.0); + // On a key: its own value, as stored. + if x <= 0.0 { + return Some(a.value.clone()); + } + let arc = effectcraft_geom::orientation_arc_deg((*va).into(), (*vb).into()); + let lin_out = a.out_interp == Interp::Linear; + let lin_in = b.in_interp != Interp::Bezier; + let f = if lin_out && lin_in || arc <= 1e-9 { + x + } else { + // Auto-Bezier keys take the arc speed between their neighbours. + let side = |j: usize, out: bool| -> Ease { + // A linear side keeps the segment's average speed at the same influence as in + // `segment_value` (and a missing key, unreachable here, is treated as one). + let Some(k) = keys.get(j) else { return Ease { speed: arc / dur, influence: LINEAR_SIDE_INFLUENCE } }; + let linear = if out { lin_out } else { lin_in }; + if linear { + return Ease { speed: arc / dur, influence: LINEAR_SIDE_INFLUENCE }; + } + if k.auto_bezier && j > 0 && j + 1 < keys.len() { + let span = (secs(keys[j + 1].time) - secs(keys[j - 1].time)).max(1e-12); + let (Value::Vec3(p), Value::Vec3(n)) = (&keys[j - 1].value, &keys[j + 1].value) else { return Ease { speed: arc / dur, influence: 1.0 / 6.0 } }; + return Ease { speed: effectcraft_geom::orientation_arc_deg((*p).into(), (*n).into()) / span, influence: 1.0 / 6.0 }; + } + let list = if out { &k.out_ease } else { &k.in_ease }; + list.first().copied().unwrap_or_default() + }; + let (eo, ei) = (side(i, true), side(i + 1, false)); + ease_progress(eo.speed * dur / arc, eo.influence, ei.speed * dur / arc, ei.influence, x) + }; + let f = if f.is_finite() { f } else { x }; + let o = effectcraft_geom::orientation_slerp((*va).into(), (*vb).into(), f); + Some(Value::Vec3([o.x, o.y, o.z])) +} + /// Value inside segment `i` → `i+1` at time `t`. pub fn segment_value(keys: &[Keyframe], i: usize, t: Tick, spatial: bool) -> Value { segment_value_of(keys, i, t, spatial) @@ -576,8 +639,8 @@ fn segment_value_of>(keys: &[K], i: usize, t: Tick, spatial: let f = if lin_out && lin_in || len <= 1e-12 { x } else { - let eo = if lin_out { Ease { speed: len / dur, influence: 1.0 / 3.0 } } else { effective_ease(keys, i, 0, true, true) }; - let ei = if lin_in { Ease { speed: len / dur, influence: 1.0 / 3.0 } } else { effective_ease(keys, i + 1, 0, true, false) }; + let eo = if lin_out { Ease { speed: len / dur, influence: LINEAR_SIDE_INFLUENCE } } else { effective_ease(keys, i, 0, true, true) }; + let ei = if lin_in { Ease { speed: len / dur, influence: LINEAR_SIDE_INFLUENCE } } else { effective_ease(keys, i + 1, 0, true, false) }; ease_progress(eo.speed * dur / len, eo.influence, ei.speed * dur / len, ei.influence, x) }; // A straight path (both handles on the chord, as auto-Bezier keys on a line have) is the @@ -596,16 +659,16 @@ fn segment_value_of>(keys: &[K], i: usize, t: Tick, spatial: let cb = b.value.components(); if ca.is_empty() || ca.len() != cb.len() { // Paths, gradients: ease on dimension 0 as overall progress. - let eo = if lin_out { Ease { speed: 1.0 / dur, influence: 1.0 / 3.0 } } else { effective_ease(keys, i, 0, false, true) }; - let ei = if lin_in { Ease { speed: 1.0 / dur, influence: 1.0 / 3.0 } } else { effective_ease(keys, i + 1, 0, false, false) }; + let eo = if lin_out { Ease { speed: 1.0 / dur, influence: LINEAR_SIDE_INFLUENCE } } else { effective_ease(keys, i, 0, false, true) }; + let ei = if lin_in { Ease { speed: 1.0 / dur, influence: LINEAR_SIDE_INFLUENCE } } else { effective_ease(keys, i + 1, 0, false, false) }; let f = ease_progress(eo.speed * dur, eo.influence, ei.speed * dur, ei.influence, x); return a.value.lerp(&b.value, f); } let mut out = Vec::with_capacity(ca.len()); for d in 0..ca.len() { let dv = cb[d] - ca[d]; - let eo = if lin_out { Ease { speed: dv / dur, influence: 1.0 / 3.0 } } else { effective_ease(keys, i, d, false, true) }; - let ei = if lin_in { Ease { speed: dv / dur, influence: 1.0 / 3.0 } } else { effective_ease(keys, i + 1, d, false, false) }; + let eo = if lin_out { Ease { speed: dv / dur, influence: LINEAR_SIDE_INFLUENCE } } else { effective_ease(keys, i, d, false, true) }; + let ei = if lin_in { Ease { speed: dv / dur, influence: LINEAR_SIDE_INFLUENCE } } else { effective_ease(keys, i + 1, d, false, false) }; // Bezier in (time, value) space directly: P1 = (i0, v0 + s0*i0*dur), P2 = (1-i1, v1 - s1*i1*dur). let (i0, i1) = (eo.influence.clamp(0.0, 1.0), ei.influence.clamp(0.0, 1.0)); let u = solve_u(0.0, i0, 1.0 - i1, 1.0, x); diff --git a/crates/keyframe/src/tests.rs b/crates/keyframe/src/tests.rs index 312703239..68823b76b 100644 --- a/crates/keyframe/src/tests.rs +++ b/crates/keyframe/src/tests.rs @@ -92,6 +92,41 @@ fn maximum_influence_resolves_flat_midpoint_time_curve() { } } +/// Keyed Orientation moves along the shortest arc, eased in time, as After Effects 2026 reads +/// it back (cases 802 and 803: keys [0,0,0] at 0 s and [60,80,40] at 2 s). +#[test] +fn keyed_orientation_matches_after_effects() { + let close = |v: Value, e: [f64; 3]| { + let v = v.as_vec3(); + assert!((0..3).all(|i| (v[i] - e[i]).abs() < 2e-3), "{v:?} vs {e:?}"); + }; + let lin = vec![Keyframe::new(s(0.0), Value::Vec3([0.0; 3])), Keyframe::new(s(2.0), Value::Vec3([60.0, 80.0, 40.0]))]; + close(evaluate_orientation(&lin, s(0.5)).unwrap(), [16.9201, 16.0688, 16.0629]); + close(evaluate_orientation(&lin, s(1.0)).unwrap(), [30.6186, 35.7617, 28.4317]); + close(evaluate_orientation(&lin, s(2.0)).unwrap(), [60.0, 80.0, 40.0]); + // A middle key reads back as stored (not as another angle triple of the same rotation). + let three = + vec![Keyframe::new(s(0.0), Value::Vec3([0.0; 3])), Keyframe::new(s(1.0), Value::Vec3([0.0, 120.0, 0.0])), Keyframe::new(s(2.0), Value::Vec3([0.0; 3]))]; + assert_eq!(evaluate_orientation(&three, s(1.0)), Some(Value::Vec3([0.0, 120.0, 0.0]))); + // Easy ease (AE's preset: speed 0, influence 33 %) on both keys. + let ease = |k: Keyframe| { + let mut k = k.eased(); + k.in_ease = vec![Ease { speed: 0.0, influence: 0.33 }]; + k.out_ease = vec![Ease { speed: 0.0, influence: 0.33 }]; + k + }; + let eased: Vec = lin.into_iter().map(ease).collect(); + close(evaluate_orientation(&eased, s(0.5)).unwrap(), [11.0974, 9.5750, 10.5916]); + close(evaluate_orientation(&eased, s(1.0)).unwrap(), [30.6186, 35.7617, 28.4317]); + close(evaluate_orientation(&eased, s(1.5)).unwrap(), [47.6915, 65.7590, 40.3338]); + // Hold keys and other value types. + let held = vec![Keyframe::new(s(0.0), Value::Vec3([1.0, 2.0, 3.0])).hold(), Keyframe::new(s(1.0), Value::Vec3([0.0; 3]))]; + close(evaluate_orientation(&held, s(0.5)).unwrap(), [1.0, 2.0, 3.0]); + let scalar = vec![Keyframe::new(s(0.0), Value::Scalar(0.0)), Keyframe::new(s(1.0), Value::Scalar(10.0))]; + assert_eq!(evaluate_orientation(&scalar, s(0.5)), Some(Value::Scalar(5.0))); + assert_eq!(evaluate_orientation(&[], s(0.5)), None); +} + /// M13.15: agents set gradients as plain JSON, not only the tagged form `get` returns. #[test] fn gradients_coerce_from_plain_json() { @@ -130,6 +165,27 @@ fn gradient_tracks_sample_separately() { assert_eq!((empty.color_at(0.3), empty.opacity_at(0.3)), ([1.0; 4], 1.0)); } +/// A gradient's stop count multiplies every painted pixel's sampling: plain JSON with more than +/// `MAX_GRADIENT_STOPS` is refused, and a longer stored list is sampled through its first ones. +#[test] +fn gradient_stop_count_is_bounded() { + use crate::value::MAX_GRADIENT_STOPS; + let g = Value::Gradient(Gradient::default()); + let many: Vec = (0..=MAX_GRADIENT_STOPS).map(|_| serde_json::json!("#ff0000")).collect(); + assert_eq!(g.coerce_json(&serde_json::Value::Array(many.clone())), None); + assert!(g.coerce_json(&serde_json::Value::Array(many[..MAX_GRADIENT_STOPS].to_vec())).is_some()); + let ops: Vec = (0..=MAX_GRADIENT_STOPS).map(|i| serde_json::json!([i as f64 / MAX_GRADIENT_STOPS as f64, 1.0])).collect(); + assert_eq!(g.coerce_json(&serde_json::json!({"colors": ["#000000", "#ffffff"], "opacities": ops})), None); + // The tagged (typed) form is bounded the same way. + let tagged = Value::Gradient(Gradient { colors: (0..=MAX_GRADIENT_STOPS).map(|i| (i as f64, [0.0; 4])).collect(), opacities: vec![(0.0, 1.0)] }); + assert_eq!(g.coerce_json(&tagged.to_json()), None); + // A stored gradient with a huge tail: stops past the limit don't take part in sampling. + let mut colors: Vec<(f64, [f32; 4])> = (0..MAX_GRADIENT_STOPS).map(|i| (i as f64 / MAX_GRADIENT_STOPS as f64 * 0.5, [0.0, 0.0, 0.0, 1.0])).collect(); + colors.extend((0..100_000).map(|_| (1.0, [1.0, 1.0, 1.0, 1.0]))); + let big = Gradient { colors, opacities: vec![(0.0, 1.0)] }; + assert_eq!(big.sample(1.0), [0.0, 0.0, 0.0, 1.0]); +} + /// #612: the editor saves the typed form, so one colour stop (which the plain JSON parser /// rejects) and each stop's RGBA come back exactly. #[test] @@ -189,6 +245,61 @@ fn bezier_with_linear_speed_matches_linear() { } } +/// A linear side next to an eased one keeps the segment's average speed at 16.67 % +/// influence. After Effects time-remap read-backs (a square at x = 50 + 455 * remap): out of +/// a key at 2 s (3.5, speed 0, influence 50 %) into a linear key at 4 s (0.5) the remap is +/// 3.290 at 2.5 s and 2.657 at 3 s (33.3 % gave 3.308 and 2.629). +#[test] +fn a_linear_side_next_to_an_eased_side_matches_after_effects() { + let mut a = Keyframe::new(s(2.0), Value::Scalar(3.5)); + a.out_interp = Interp::Bezier; + a.out_ease = vec![Ease { speed: 0.0, influence: 0.5 }]; + let keys = vec![a, Keyframe::new(s(4.0), Value::Scalar(0.5))]; + for (t, ae) in [(2.5, 3.290), (3.0, 2.657)] { + let v = evaluate(&keys, s(t), false).unwrap().as_f64(); + // AE's square edge is read to the pixel: 1 px = 1 / 455 of remap. + assert!((v - ae).abs() < 2.0 / 455.0, "{t}: {v} vs {ae}"); + } + // The mirror case: a linear out into an eased in. + let mut b = Keyframe::new(s(4.0), Value::Scalar(0.5)); + b.in_interp = Interp::Bezier; + b.in_ease = vec![Ease { speed: 0.0, influence: 0.5 }]; + let mirror = vec![Keyframe::new(s(2.0), Value::Scalar(3.5)), b]; + let v = evaluate(&mirror, s(3.5), false).unwrap().as_f64(); + assert!((v - (4.0 - 3.290)).abs() < 2.0 / 455.0, "{v}"); + assert_eq!(side_ease(&keys, 1, 0, false, false).map(|e| e.influence), Some(LINEAR_SIDE_INFLUENCE)); +} + +/// Keyed Orientation shapes a linear side next to an eased one as a scalar property does +/// (`LINEAR_SIDE_INFLUENCE`): about one axis the shortest arc is the angle itself, so the +/// orientation follows the same curve as a scalar with the same keys (CodeRabbit on #1876). +#[test] +fn orientation_linear_side_next_to_an_eased_side_matches_a_scalar() { + let ease = vec![Ease { speed: 0.0, influence: 0.5 }]; + let (mut a, mut sa) = (Keyframe::new(s(2.0), Value::Vec3([0.0, 0.0, 0.0])), Keyframe::new(s(2.0), Value::Scalar(0.0))); + for k in [&mut a, &mut sa] { + k.out_interp = Interp::Bezier; + k.out_ease = ease.clone(); + } + let orient = vec![a, Keyframe::new(s(4.0), Value::Vec3([0.0, 0.0, 90.0]))]; + let scalar = vec![sa, Keyframe::new(s(4.0), Value::Scalar(90.0))]; + // The mirror: a linear out into an eased in. + let (mut b, mut sb) = (Keyframe::new(s(4.0), Value::Vec3([0.0, 0.0, 90.0])), Keyframe::new(s(4.0), Value::Scalar(90.0))); + for k in [&mut b, &mut sb] { + k.in_interp = Interp::Bezier; + k.in_ease = ease.clone(); + } + let orient_m = vec![Keyframe::new(s(2.0), Value::Vec3([0.0, 0.0, 0.0])), b]; + let scalar_m = vec![Keyframe::new(s(2.0), Value::Scalar(0.0)), sb]; + for (o, sc) in [(&orient, &scalar), (&orient_m, &scalar_m)] { + for t in [2.25, 2.5, 3.0, 3.5, 3.75] { + let Some(Value::Vec3(v)) = evaluate_orientation(o, s(t)) else { panic!("orientation at {t}") }; + let want = evaluate(sc, s(t), false).unwrap().as_f64(); + assert!((v[2] - want).abs() < 1e-6 && v[0].abs() < 1e-9 && v[1].abs() < 1e-9, "{t}: {v:?} vs {want}"); + } + } +} + #[test] fn spatial_linear_constant_speed() { let keys = vec![Keyframe::new(s(0.0), Value::Vec2([0.0, 0.0])), Keyframe::new(s(1.0), Value::Vec2([300.0, 400.0]))]; diff --git a/crates/keyframe/src/text_doc.rs b/crates/keyframe/src/text_doc.rs index 96a8b6be3..f91d8be4d 100644 --- a/crates/keyframe/src/text_doc.rs +++ b/crates/keyframe/src/text_doc.rs @@ -977,7 +977,19 @@ impl TextDoc { if r.start >= r.end && n > 0 { return Ok(true); } - self.apply_style(r.start..r.end.max(r.start + usize::from(n == 0)), |s| { + // Empty text: apply_style ignores the bounds, so a fixed range avoids `start + 1` overflow. + let range = if n == 0 { 0..1 } else { r.start..r.end }; + // Check every affected run first, so a value one run refuses changes none of them. + let mut err = None; + self.apply_style(range.clone(), |s| { + if let Err(e) = apply_char_attr(&mut s.clone(), key, v) { + err.get_or_insert(e); + } + }); + if let Some(e) = err { + return Err(e); + } + self.apply_style(range, |s| { let _ = apply_char_attr(s, key, v); }); return Ok(true); @@ -1057,6 +1069,11 @@ pub const CHAR_ATTRS: &[&str] = &[ pub const PARA_ATTRS: &[&str] = &["justify", "indentLeft", "indentRight", "indentFirst", "spaceBefore", "spaceAfter", "direction", "composer", "hangingPunctuation"]; +/// Most variable font axes one style can set. Real fonts have a handful (OpenType registers +/// five; custom axes rarely bring the total past twenty); a `variations` object with more is +/// rejected before any of it is applied. +pub const MAX_VARIATION_AXES: usize = 64; + /// Set one character attribute; Ok(false) for keys that aren't character attributes. pub fn apply_char_attr(s: &mut CharStyle, key: &str, v: &J) -> Result { match key { @@ -1173,20 +1190,28 @@ pub fn apply_char_attr(s: &mut CharStyle, key: &str, v: &J) -> Result match v { J::Null => s.variations.clear(), J::Object(m) => { - if m.is_empty() { - s.variations.clear(); + if m.len() > MAX_VARIATION_AXES { + return Err(format!("variations: at most {MAX_VARIATION_AXES} axes")); } + // One keyed merge (the result sorted by tag), applied only when every entry is valid. + let mut axes: std::collections::BTreeMap = if m.is_empty() { Default::default() } else { s.variations.iter().cloned().collect() }; for (tag, val) in m { if tag.is_empty() || tag.len() > 4 { return Err(format!("variations: `{tag}` is not an axis tag")); } - s.variations.retain(|(t, _)| t != tag); match val { - J::Null => {} - _ => s.variations.push((tag.clone(), val.as_f64().ok_or("variations: expected {tag: number}")? as f32)), + J::Null => { + axes.remove(tag); + } + _ => { + axes.insert(tag.clone(), val.as_f64().ok_or("variations: expected {tag: number}")? as f32); + } } } - s.variations.sort_by(|a, b| a.0.cmp(&b.0)); + if axes.len() > MAX_VARIATION_AXES { + return Err(format!("variations: at most {MAX_VARIATION_AXES} axes")); + } + s.variations = axes.into_iter().collect(); } _ => return Err("variations: expected {tag: number, …}".into()), }, @@ -1321,6 +1346,44 @@ pub fn word_at(text: &str, ci: usize) -> Range { mod tests { use super::*; + #[test] + fn variations_merge_by_tag_and_reject_too_many_axes() { + let mut doc = TextDoc::plain("ab"); + assert!(doc.set_attr("variations", &serde_json::json!({"wght": 650, "wdth": 90}), None).unwrap()); + assert!(doc.set_attr("variations", &serde_json::json!({"wght": 700, "wdth": null, "opsz": 12}), None).unwrap()); + assert_eq!(doc.style_at(0).variations, vec![("opsz".to_string(), 12.0), ("wght".to_string(), 700.0)]); + // More axes than any font has: refused up front, the style untouched. + let many: serde_json::Map = (0..MAX_VARIATION_AXES + 1).map(|i| (format!("a{i:03}"), J::from(1.0))).collect(); + assert!(doc.set_attr("variations", &J::Object(many), None).is_err()); + assert_eq!(doc.style_at(0).variations.len(), 2); + // A merge that would grow past the limit is refused too. + let fill: serde_json::Map = (0..MAX_VARIATION_AXES - 2).map(|i| (format!("b{i:03}"), J::from(1.0))).collect(); + assert!(doc.set_attr("variations", &J::Object(fill), None).unwrap()); + assert_eq!(doc.style_at(0).variations.len(), MAX_VARIATION_AXES); + // (The probe on an empty style passes; the styles already at the limit keep their axes.) + let _ = doc.set_attr("variations", &serde_json::json!({"zzzz": 1}), None); + assert_eq!(doc.style_at(0).variations.len(), MAX_VARIATION_AXES); + assert!(!doc.style_at(0).variations.iter().any(|(t, _)| t == "zzzz")); + } + + #[test] + fn refused_variation_leaves_every_run_unchanged() { + // "ab" is at the axis limit; "cd" has none. Three new axes over both runs must be refused + // for both, not applied to "cd" only. + let mut doc = TextDoc::plain("abcd"); + let fill: serde_json::Map = (0..MAX_VARIATION_AXES).map(|i| (format!("b{i:03}"), J::from(1.0))).collect(); + assert!(doc.set_attr("variations", &J::Object(fill), Some(0..2)).unwrap()); + assert!(doc.set_attr("variations", &serde_json::json!({"x1": 1, "x2": 1, "x3": 1}), None).is_err()); + assert_eq!(doc.style_at(3).variations.len(), 0); + assert_eq!(doc.style_at(0).variations.len(), MAX_VARIATION_AXES); + } + + #[test] + fn empty_document_accepts_an_extreme_range_without_overflow() { + let mut doc = TextDoc::plain(""); + assert!(doc.set_attr("size", &J::from(20), Some(usize::MAX..usize::MAX)).unwrap()); + } + #[test] fn mixed_line_breaks_keep_original_byte_and_character_ranges() { let text = "é\r\nβ\rx\n\n"; diff --git a/crates/keyframe/src/value.rs b/crates/keyframe/src/value.rs index 6609aed68..6e87f8933 100644 --- a/crates/keyframe/src/value.rs +++ b/crates/keyframe/src/value.rs @@ -210,7 +210,13 @@ impl Gradient { } } +/// Most stops (colour or opacity) a gradient is sampled through. Gradients are sampled per +/// pixel, so the stop count multiplies every painted pixel's work: stops past this are ignored +/// when sampling, and a gradient written as JSON with more is refused. +pub const MAX_GRADIENT_STOPS: usize = 256; + fn sample_stops(stops: &[(f64, T)], t: f64, lerp: impl Fn(T, T, f64) -> T) -> Option { + let stops = &stops[..stops.len().min(MAX_GRADIENT_STOPS)]; let first = stops.first()?; if t <= first.0 { return Some(first.1); @@ -243,7 +249,7 @@ fn gradient_json(j: &serde_json::Value) -> Option { } fn stops(a: &[J]) -> Option> { let n = a.len(); - if n < 2 { + if !(2..=MAX_GRADIENT_STOPS).contains(&n) { return None; } a.iter() @@ -259,6 +265,7 @@ fn gradient_json(j: &serde_json::Value) -> Option { J::Object(o) => { let colors = stops(o.get("colors")?.as_array()?)?; let op = match o.get("opacities") { + Some(J::Array(a)) if a.len() > MAX_GRADIENT_STOPS => return None, Some(J::Array(a)) => Some( a.iter() .map(|s| { @@ -469,9 +476,10 @@ impl Value { } Value::Layer(_) => Some(Value::Layer(j.as_u64())), Value::Path(_) => serde_json::from_value::(j.clone()).ok().map(Value::Path).or_else(|| serde_json::from_value::(j.clone()).ok()), - Value::Gradient(_) => { - serde_json::from_value::(j.clone()).ok().filter(|v| matches!(v, Value::Gradient(_))).or_else(|| gradient_json(j).map(Value::Gradient)) - } + Value::Gradient(_) => serde_json::from_value::(j.clone()) + .ok() + .filter(|v| matches!(v, Value::Gradient(g) if g.colors.len() <= MAX_GRADIENT_STOPS && g.opacities.len() <= MAX_GRADIENT_STOPS)) + .or_else(|| gradient_json(j).map(Value::Gradient)), } } /// JSON for display/automation (numbers/arrays for numeric kinds). diff --git a/crates/lottie/src/anim.rs b/crates/lottie/src/anim.rs index 4925460a9..40a56a7eb 100644 --- a/crates/lottie/src/anim.rs +++ b/crates/lottie/src/anim.rs @@ -21,6 +21,9 @@ use serde_json::{Value as Json, json}; use crate::Timebase; +/// Most distinct warnings an import or export reports. +const MAX_WARNINGS: usize = 200; + /// Export state shared by the whole document. pub(crate) struct Ex { pub tb: Timebase, @@ -31,7 +34,8 @@ pub(crate) struct Ex { impl Ex { pub fn warn(&mut self, w: impl Into) { let w = w.into(); - if !self.warnings.contains(&w) { + // Each warning is looked for among the earlier ones: past a screenful, more add nothing. + if self.warnings.len() < MAX_WARNINGS && !self.warnings.contains(&w) { self.warnings.push(w); } } @@ -46,7 +50,8 @@ pub(crate) struct Im { impl Im { pub fn warn(&mut self, w: impl Into) { let w = w.into(); - if !self.warnings.contains(&w) { + // Each warning is looked for among the earlier ones: past a screenful, more add nothing. + if self.warnings.len() < MAX_WARNINGS && !self.warnings.contains(&w) { self.warnings.push(w); } } @@ -150,11 +155,15 @@ fn segment_ease(keys: &[Keyframe], i: usize, spatial: bool) -> (Vec, Vec String { format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2])) } -fn mime_of(path: &str) -> &'static str { - let lower = path.to_ascii_lowercase(); - if lower.ends_with(".jpg") || lower.ends_with(".jpeg") { - "image/jpeg" - } else if lower.ends_with(".webp") { - "image/webp" - } else if lower.ends_with(".gif") { - "image/gif" +/// The image type `bytes` hold, by their signature; `None` for anything else. +pub(crate) fn image_mime(bytes: &[u8]) -> Option<&'static str> { + if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + Some("image/png") + } else if bytes.starts_with(&[0xff, 0xd8, 0xff]) { + Some("image/jpeg") + } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { + Some("image/gif") + } else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") { + Some("image/webp") } else { - "image/png" + None } } @@ -286,7 +288,13 @@ impl Doc<'_> { self.ex.warn(format!("{}: cannot read image `{}` (layer exported as a null)", l.name, f.path)); return None; }; - let uri = format!("data:{};base64,{}", mime_of(&f.path), crate::base64::encode(&bytes)); + // What a project calls a still is embedded only when it is one: the path can name any + // file (an imported animation's asset), and the export would carry its bytes verbatim. + let Some(mime) = image_mime(&bytes) else { + self.ex.warn(format!("{}: `{}` is not a PNG, JPEG, GIF or WebP image (layer exported as a null)", l.name, f.path)); + return None; + }; + let uri = format!("data:{mime};base64,{}", crate::base64::encode(&bytes)); self.assets.push(json!({"id": id, "nm": it.name, "w": f.width, "h": f.height, "u": "", "p": uri, "e": 1})); self.done.insert(id.clone()); Some(id) diff --git a/crates/lottie/src/import.rs b/crates/lottie/src/import.rs index 6d7cc1f5a..1e1430e12 100644 --- a/crates/lottie/src/import.rs +++ b/crates/lottie/src/import.rs @@ -1,6 +1,6 @@ //! Lottie document → EffectCraft compositions (the inverse of [`crate::export`]). -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; use effectcraft_color::Label; @@ -17,6 +17,9 @@ use crate::anim::{self, Im, import_prop}; use crate::export::{fx_by_id, fx_by_type, fx_params, mask_mode_from}; use crate::{LottieError, Timebase, shapes, text}; +/// Longest font family or style name kept (each text key using the font holds a copy). +const MAX_FONT_NAME_CHARS: usize = 256; + /// An embedded image asset handed to the caller to store (the returned path becomes the /// footage item's file). #[derive(Clone, Debug)] @@ -129,21 +132,36 @@ pub fn import( Ctx { im: Im { tb, warnings: vec![] }, assets: BTreeMap::new(), fonts: vec![], store, base_dir, items: vec![], folder: None, name: name.clone() }; if let Some(list) = doc.get("fonts").and_then(|f| f.get("list")).and_then(Json::as_array) { for fo in list { + // Every text key referring to the font copies its family and style: keep them to + // a font name's length. + let short = |v: &str| v.chars().take(MAX_FONT_NAME_CHARS).collect::(); let n = s(fo, "fName").unwrap_or("").to_string(); - let fam = s(fo, "fFamily").unwrap_or(&n).to_string(); - let st = s(fo, "fStyle").unwrap_or("Regular").to_string(); + let fam = short(s(fo, "fFamily").unwrap_or(&n)); + let st = short(s(fo, "fStyle").unwrap_or("Regular")); cx.fonts.push((n, fam, st)); } } + // Glyph outlines embedded for players without the fonts. Text is set in installed fonts. + if let Some(chars) = doc.get("chars").and_then(Json::as_array).filter(|c| !c.is_empty()) { + let mut fams: Vec<&str> = vec![]; + for fam in chars.iter().filter_map(|c| s(c, "fFamily")).filter(|f| !f.trim().is_empty()) { + if !fams.contains(&fam) { + fams.push(fam); + } + } + let of = if fams.is_empty() { String::new() } else { format!(" of {}", fams.join(", ")) }; + cx.im.warn(format!("embedded glyphs (`chars`){of} are not imported; text uses the installed fonts")); + } let (w, h) = (w.round().max(1.0) as u32, h.round().max(1.0) as u32); let duration = tb.tick(op); // Pass 1: asset items (precomps empty for now, images stored). let assets = doc.get("assets").and_then(Json::as_array).cloned().unwrap_or_default(); + let layer_sizes = precomp_layer_sizes(&doc, &assets); for a in &assets { let Some(id) = s(a, "id") else { continue }; if a.get("layers").is_some() { let folder = cx.folder(project); - let layer = precomp_layer_size(&doc, &assets, id); + let layer = layer_sizes.get(id).copied(); let aw = f(a, "w").map(|v| v as u32).or(layer.map(|l| l.0)).unwrap_or(w); let ah = f(a, "h").map(|v| v as u32).or(layer.map(|l| l.1)).unwrap_or(h); let arate = f(a, "fr").map(FrameRate::from_f64).unwrap_or(rate); @@ -244,17 +262,20 @@ pub fn import( Ok(ImportResult { comp: id, items: cx.items, warnings: cx.im.warnings }) } -/// The `w`/`h` of the first precomp layer, in the main comp or in any asset, that shows asset `id`. -/// lottie-spec gives a precomposition asset no size: the layer's `w`/`h` are its clipping rect. -fn precomp_layer_size(doc: &Json, assets: &[Json], id: &str) -> Option<(u32, u32)> { +/// By asset id, the `w`/`h` of the first precomp layer, in the main comp or in any asset, that +/// shows it. lottie-spec gives a precomposition asset no size: the layer's `w`/`h` are its +/// clipping rect. One pass over all layers, not one per asset. +fn precomp_layer_sizes<'a>(doc: &'a Json, assets: &'a [Json]) -> HashMap<&'a str, (u32, u32)> { + let mut out = HashMap::new(); let lists = doc.get("layers").into_iter().chain(assets.iter().filter_map(|a| a.get("layers"))); - lists.filter_map(Json::as_array).flatten().find_map(|l| { - if l.get("ty").and_then(Json::as_u64) != Some(0) || s(l, "refId") != Some(id) { - return None; + for l in lists.filter_map(Json::as_array).flatten() { + if l.get("ty").and_then(Json::as_u64) != Some(0) { + continue; } - let (lw, lh) = f(l, "w").zip(f(l, "h"))?; - Some((lw.round().max(1.0) as u32, lh.round().max(1.0) as u32)) - }) + let (Some(id), Some((lw, lh))) = (s(l, "refId"), f(l, "w").zip(f(l, "h"))) else { continue }; + out.entry(id).or_insert((lw.round().max(1.0) as u32, lh.round().max(1.0) as u32)); + } + out } fn transform(im: &Im, ks: &Json, tr: &mut PropGroup, next: &mut u64) { @@ -305,7 +326,8 @@ fn masks(im: &Im, ids: &mut Ids, list: &[Json], g: &mut PropGroup) { import_prop(im, j, p, conv); } }; - set("pt", "path", &shapes::to_path); + let closed = m.get("cl").and_then(Json::as_bool).unwrap_or(false); + set("pt", "path", &|v| shapes::to_path(v, closed)); set("o", "opacity", &anim::to_scalar); set("x", "expansion", &anim::to_scalar); set("f", "feather", &anim::to_vec2); @@ -399,8 +421,8 @@ fn layer_source(cx: &mut Ctx, project: &mut Project, comp: &Comp, j: &Json) -> O fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[Json]) { let tb = cx.im.tb; let mut by_ind: BTreeMap = BTreeMap::new(); - // (layer id, parent ind, matte: (kind, explicit tp ind), json position) - let mut pending: Vec<(LayerId, Option, Option<(MatteKind, Option)>, usize)> = vec![]; + // (layer id, its index in `comp.layers`, parent ind, matte: (kind, explicit tp ind), json position) + let mut pending: Vec<(LayerId, usize, Option, Option<(MatteKind, Option)>, usize)> = vec![]; let mut pos_ind: Vec> = vec![]; for (ji, j) in layers.iter().enumerate() { let ind = j.get("ind").and_then(Json::as_i64); @@ -419,7 +441,12 @@ fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[ // Below 1 % (or 0) the layer time divides by ~0, and layer.timeStretch refuses it too. let sr = f(j, "sr").unwrap_or(1.0); l.stretch = if sr.is_finite() && sr.abs() >= 0.01 { - sr * 100.0 + // Past ±9900 % too (#3247): the largest stretch a layer supports, sign kept. + let pct = effectcraft_project::limits::stretch(sr * 100.0); + if pct.to_bits() != (sr * 100.0).to_bits() { + cx.im.warn(format!("{name}: a time stretch of {} % is not supported ({pct} % used)", sr * 100.0)); + } + pct } else { cx.im.warn(format!("{name}: a time stretch of {} % is not supported (100 % used)", sr * 100.0)); 100.0 @@ -446,8 +473,8 @@ fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[ let mut ids = Ids(&mut next); match &source { LayerSource::Shape => { - let items = j.get("shapes").and_then(Json::as_array).cloned().unwrap_or_default(); - let groups = shapes::import_items(&mut cx.im, &mut ids, &items); + let mut items = j.get("shapes").and_then(Json::as_array).into_iter().flatten(); + let groups = shapes::import_items(&mut cx.im, &mut ids, &mut items); if let Some(c) = l.props.sub_mut("contents") { c.children.extend(groups.into_iter().map(Node::Group)); } @@ -490,10 +517,10 @@ fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[ _ => None, } .map(|k| (k, j.get("tp").and_then(Json::as_i64))); - pending.push((l.id, parent, matte, ji)); + pending.push((l.id, comp.layers.len(), parent, matte, ji)); comp.layers.push(l); } - for (id, parent, matte, ji) in pending { + for (id, at, parent, matte, ji) in pending { let parent_id = parent.and_then(|p| by_ind.get(&p).copied()).filter(|p| *p != id); let matte_id = matte.and_then(|(k, tp)| { let target = match tp { @@ -503,7 +530,7 @@ fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[ }; target.filter(|t| *t != id).map(|t| TrackMatte { layer: t, kind: k }) }); - if let Some(l) = comp.layer_mut(id) { + if let Some(l) = comp.layers.get_mut(at) { l.parent = parent_id; l.track_matte = matte_id; } diff --git a/crates/lottie/src/shapes.rs b/crates/lottie/src/shapes.rs index 5b9d29970..6cd1f09cc 100644 --- a/crates/lottie/src/shapes.rs +++ b/crates/lottie/src/shapes.rs @@ -27,7 +27,9 @@ pub(crate) fn path_value(v: &Value) -> Json { } } -pub(crate) fn to_path(j: &Json) -> Option { +/// A Lottie path. `closed` is used when the path has no `c`: Bodymovin 3.x and early 4.x keep the +/// flag outside the path, as `cl` on a mask and `closed` on an `sh` item. +pub(crate) fn to_path(j: &Json, closed: bool) -> Option { let o = match j { Json::Array(a) => a.first()?, o => o, @@ -48,7 +50,7 @@ pub(crate) fn to_path(j: &Json) -> Option { in_tangents: fit(pts("i")), out_tangents: fit(pts("o")), vertices, - closed: o.get("c").and_then(Json::as_bool).unwrap_or(false), + closed: o.get("c").and_then(Json::as_bool).unwrap_or(closed), feather: Vec::new(), })) } @@ -434,7 +436,7 @@ fn import_shape_transform(im: &Im, j: &Json, tr: &mut PropGroup) { } /// Import Lottie shape items into shape contents groups. -pub(crate) fn import_items(im: &mut Im, ids: &mut Ids, items: &[Json]) -> Vec { +pub(crate) fn import_items(im: &mut Im, ids: &mut Ids, items: &mut dyn Iterator) -> Vec { let mut out = vec![]; for j in items { let ty = j.get("ty").and_then(Json::as_str).unwrap_or(""); @@ -445,9 +447,10 @@ pub(crate) fn import_items(im: &mut Im, ids: &mut Ids, items: &[Json]) -> Vec { - let list = j.get("it").and_then(Json::as_array).cloned().unwrap_or_default(); - let inner: Vec = list.iter().filter(|i| i.get("ty").and_then(Json::as_str) != Some("tr")).cloned().collect(); - let children = import_items(im, ids, &inner); + // Borrowed, not cloned: each nesting level copying its subtree costs memory + // quadratic in the depth. + let list = j.get("it").and_then(Json::as_array).map(Vec::as_slice).unwrap_or_default(); + let children = import_items(im, ids, &mut list.iter().filter(|i| i.get("ty").and_then(Json::as_str) != Some("tr"))); let mut g = build::shape_group(ids, "Group 1", children); if let Some(tr) = list.iter().find(|i| i.get("ty").and_then(Json::as_str) == Some("tr")) && let Some(t) = g.sub_mut("transform") @@ -493,7 +496,8 @@ pub(crate) fn import_items(im: &mut Im, ids: &mut Ids, items: &[Json]) -> Vec { let mut g = build::shape_path(ids, ShapePath::default()); dir(&mut g); - set(im, &mut g, "path", j.get("ks"), &to_path); + let closed = j.get("closed").and_then(Json::as_bool).unwrap_or(false); + set(im, &mut g, "path", j.get("ks"), &|v| to_path(v, closed)); g } "fl" => { diff --git a/crates/lottie/src/tests.rs b/crates/lottie/src/tests.rs index 83c81e242..8656852de 100644 --- a/crates/lottie/src/tests.rs +++ b/crates/lottie/src/tests.rs @@ -520,6 +520,59 @@ fn zero_time_stretch_is_not_imported() { assert!(imp.warnings.iter().any(|w| w.contains("time stretch")), "{:?}", imp.warnings); } +#[test] +fn a_time_stretch_past_9900_percent_is_held_to_it() { + // `sr` 1e300 was imported as 1e302 % (#3247); the sign of a reversed layer is kept. + for (sr, want) in [(1e300, 9900.0), (-1e300, -9900.0), (99.0, 9900.0)] { + let doc = json!({"w": 20, "h": 20, "fr": 30, "ip": 0, "op": 30, "assets": [], + "layers": [{"ty": 1, "ind": 1, "sc": "#ff0000", "sw": 20, "sh": 20, "sr": sr, "ip": 0, "op": 30, "st": 0, "ks": {}}]}); + let mut q = Project::default(); + let imp = import(&mut q, doc.to_string().as_bytes(), "Imported", "", &mut |_| None).unwrap(); + let l = &q.comp(imp.comp).unwrap().layers[0]; + assert_eq!(l.stretch, want, "sr {sr}"); + let warned = imp.warnings.iter().any(|w| w.contains("time stretch")); + assert_eq!(warned, sr != 99.0, "sr {sr}: {:?}", imp.warnings); + } +} + +#[test] +fn embedded_glyphs_are_reported_when_dropped() { + let glyph = |ch: &str, fam: &str| json!({"ch": ch, "size": 100, "style": "Regular", "w": 60, "fFamily": fam, "data": {"shapes": []}}); + let doc = json!({"w": 20, "h": 20, "fr": 30, "ip": 0, "op": 30, "assets": [], "layers": [], + "fonts": {"list": [{"fName": "Sans-Regular", "fFamily": "Sans", "fStyle": "Regular"}]}, + "chars": [glyph("A", "Sans"), glyph("B", ""), glyph("C", "Serif")]}); + let warnings = |doc: &Json| import(&mut Project::default(), doc.to_string().as_bytes(), "Imported", "", &mut |_| None).unwrap().warnings; + // A blank family name is left out, not listed as "of , …". + assert_eq!(warnings(&doc), ["embedded glyphs (`chars`) of Sans, Serif are not imported; text uses the installed fonts"]); + let blank = json!({"w": 20, "h": 20, "fr": 30, "layers": [], "chars": [glyph("A", " ")]}); + assert_eq!(warnings(&blank), ["embedded glyphs (`chars`) are not imported; text uses the installed fonts"]); +} + +#[test] +fn legacy_closed_flags_close_masks_and_paths() { + // Bodymovin 3.x and early 4.x put the closed flag on the mask (`cl`) and on the `sh` item + // (`closed`), with no `c` in the path. An open mask would leave the solid whole. + let square = json!({"i": [[0, 0], [0, 0], [0, 0], [0, 0]], "o": [[0, 0], [0, 0], [0, 0], [0, 0]], "v": [[5, 5], [15, 5], [15, 15], [5, 15]]}); + let doc = json!({"w": 20, "h": 20, "fr": 30, "ip": 0, "op": 30, "assets": [], "layers": [ + {"ty": 4, "ind": 1, "ip": 0, "op": 30, "st": 0, "ks": {}, + "shapes": [{"ty": "sh", "closed": true, "ks": {"k": [{"t": 0, "s": [square], "e": [square]}, {"t": 10}]}}]}, + {"ty": 1, "ind": 2, "sc": "#ff0000", "sw": 20, "sh": 20, "ip": 0, "op": 30, "st": 0, "ks": {}, + "masksProperties": [{"mode": "a", "cl": true, "pt": {"k": square}}]}]}); + let mut q = Project::default(); + let nc = import(&mut q, doc.to_string().as_bytes(), "Imported", "", &mut |_| None).unwrap().comp; + let comp = q.comp(nc).unwrap(); + let closed = |v: &Value| matches!(v, Value::Path(sp) if sp.closed); + let shape = comp.layers[0].props.sub("contents").unwrap().groups().next().unwrap(); + let keys = &shape.get("path").unwrap().keys; + assert_eq!(keys.len(), 2); + assert!(keys.iter().all(|k| closed(&k.value))); + let mask = comp.layers[1].masks().unwrap().groups().next().unwrap(); + assert!(closed(&mask.get("path").unwrap().value)); + let img = render_frame(&q, nc, s(0.0), 1.0); + assert_eq!(img.data[0][3], 0.0, "the mask cuts the corner away"); + assert!(img.data[10 * 20 + 10][3] > 0.99); +} + #[test] fn precomp_with_time_remap() { let (mut p, cid) = setup(); @@ -672,7 +725,7 @@ fn effects_expressions_and_warnings() { #[test] fn images_embed_as_base64_and_come_back() { let (mut p, cid) = setup(); - let png: Vec = vec![0x89, b'P', b'N', b'G', 1, 2, 3, 4, 5]; + let png: Vec = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4, 5]; let fid = p.add_item( "pic.png", Label::Lavender, @@ -722,6 +775,17 @@ fn images_embed_as_base64_and_come_back() { assert!(f.path.starts_with("/tmp/image_") && f.path.ends_with(".png"), "{}", f.path); } +#[test] +fn image_signatures_are_matched_in_full() { + use crate::export::image_mime; + assert_eq!(image_mime(b"\x89PNG\r\n\x1a\n\0"), Some("image/png")); + assert_eq!(image_mime(b"GIF89a\0"), Some("image/gif")); + assert_eq!(image_mime(b"GIF87a\0"), Some("image/gif")); + // Near matches (a prefix of the signature, or text that starts with it) are not images. + assert_eq!(image_mime(b"\x89PNG\x01\x02\x03\x04"), None); + assert_eq!(image_mime(b"GIF8 is a text file"), None); +} + #[test] fn dotlottie_archive_roundtrip() { let (mut p, cid) = setup(); @@ -932,3 +996,69 @@ fn per_corner_roundness_exports_equal_radii_and_warns_when_mixed() { assert_eq!(rc(&json)["r"]["k"], json!(5.0)); assert!(!warnings.iter().any(|w| w.contains("per-corner")), "{warnings:?}"); } + +#[test] +fn many_layers_and_precomps_import_with_their_parents_and_sizes() { + // 5 000 null layers each parented to the previous, and 2 000 empty precomp assets: the + // relationship and size passes index the layers instead of searching them per layer. (Each + // has its own name: `Comp::unique_layer_name` numbering one repeated name is a separate cost.) + let n = 5_000; + let layers: Vec = (1..=n).map(|i| json!({"ty": 3, "nm": format!("N{i}"), "ind": i, "parent": i - 1, "ip": 0, "op": 30, "st": 0, "ks": {}})).collect(); + let mut assets: Vec = (0..2_000).map(|i| json!({"id": format!("c{i}"), "layers": []})).collect(); + assets.push(json!({"id": "last", "layers": []})); + let mut layers = layers; + layers.push(json!({"ty": 0, "ind": n + 1, "refId": "last", "w": 50, "h": 40, "ip": 0, "op": 30, "st": 0, "ks": {}})); + let doc = json!({"w": 200, "h": 120, "fr": 30, "ip": 0, "op": 30, "assets": assets, "layers": layers}); + let mut q = Project::default(); + let nc = import(&mut q, doc.to_string().as_bytes(), "Imported", "", &mut |_| None).unwrap().comp; + let c = q.comp(nc).unwrap(); + assert_eq!(c.layers.len(), n as usize + 1); + assert_eq!(c.layers.get(0).unwrap().parent, None); + assert_eq!(c.layers.get(1).unwrap().parent, Some(c.layers.get(0).unwrap().id)); + let LayerSource::Comp { item } = c.layers.get(n as usize).unwrap().source else { panic!("not a precomp") }; + let pc = q.comp(item).unwrap(); + assert_eq!((pc.width, pc.height), (50, 40)); +} + +#[test] +fn deeply_nested_shape_groups_and_long_font_names_import() { + let mut g = json!({"ty": "rc", "s": {"a": 0, "k": [10, 10]}, "p": {"a": 0, "k": [0, 0]}, "r": {"a": 0, "k": 0}}); + // 50 levels: each is two levels of JSON, within serde_json's recursion limit of 128. + for _ in 0..50 { + g = json!({"ty": "gr", "it": [g, {"ty": "tr", "o": {"a": 0, "k": 100}}]}); + } + let family = "F".repeat(100_000); + let keys: Vec = (0..50).map(|i| json!({"t": i, "s": {"t": "x", "f": "A", "s": 10}})).collect(); + let doc = json!({"w": 200, "h": 120, "fr": 30, "ip": 0, "op": 60, + "fonts": {"list": [{"fName": "A", "fFamily": family, "fStyle": "Regular"}]}, + "layers": [ + {"ty": 4, "ind": 1, "ip": 0, "op": 60, "st": 0, "ks": {}, "shapes": [g]}, + {"ty": 5, "ind": 2, "ip": 0, "op": 60, "st": 0, "ks": {}, "t": {"d": {"k": keys}}} + ]}); + let mut q = Project::default(); + let nc = import(&mut q, doc.to_string().as_bytes(), "Imported", "", &mut |_| None).unwrap().comp; + let c = q.comp(nc).unwrap(); + let st = c.layers.get(1).unwrap().props.prop("text/sourceText").unwrap(); + assert_eq!(st.keys.len(), 50); + let Value::Text(d) = &st.keys[0].value else { panic!("not text") }; + assert_eq!(d.font.len(), 256); +} + +/// A footage item called a still whose file is not an image is not embedded. +#[test] +fn only_image_bytes_are_embedded() { + let (mut p, cid) = setup(); + let fid = p.add_item( + "secret.png", + Label::Lavender, + None, + ItemKind::Footage(Footage { path: "/virtual/secret.png".into(), kind: FootageKind::Still, width: 8, height: 8, has_video: true, ..Default::default() }), + ); + let c = comp(&p, cid); + let l = build::layer(&mut p, &c, "secret.png", LayerSource::Footage { item: fid }, (8, 8), None); + push(&mut p, cid, l); + let read = |path: &str| (path == "/virtual/secret.png").then(|| b"root:x:0:0:root:/root:/bin/sh\n".to_vec()); + let res = export_comp(&p, cid, &ExportOptions::default(), &read).unwrap(); + assert!(res.json["assets"].as_array().is_none_or(|a| a.is_empty()), "{}", res.json["assets"]); + assert!(res.warnings.iter().any(|w| w.contains("not a PNG")), "{:?}", res.warnings); +} diff --git a/crates/lottie/src/text.rs b/crates/lottie/src/text.rs index 125835c2b..4e50b461d 100644 --- a/crates/lottie/src/text.rs +++ b/crates/lottie/src/text.rs @@ -310,7 +310,8 @@ pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGro st.value = Value::Text(Box::new(first.clone())); } if docs.len() > 1 { - st.keys = docs.iter().map(|(f, d)| effectcraft_keyframe::Keyframe::new(im.tb.tick(*f), Value::Text(Box::new(d.clone()))).hold()).collect(); + // Moved into the keys, not cloned: the documents are not kept twice. + st.keys = docs.into_iter().map(|(f, d)| effectcraft_keyframe::Keyframe::new(im.tb.tick(f), Value::Text(Box::new(d))).hold()).collect(); } } if let Some(m) = t.get("m") diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index a4070297b..2fa54e0eb 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -36,3 +36,8 @@ rayon = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } +# (tests render comps that read layers through effects; already a dependency of effectcraft-render) +effectcraft-effects = { workspace = true } diff --git a/crates/media/src/convert.rs b/crates/media/src/convert.rs index 9e88ab4dd..86fb088f9 100644 --- a/crates/media/src/convert.rs +++ b/crates/media/src/convert.rs @@ -7,8 +7,9 @@ //! are encoded in the file. Alpha follows the footage's [`AlphaMode`] interpretation. use effectcraft_project::{AlphaMode, Footage}; -use effectcraft_raster::{Image, Px}; +use effectcraft_raster::{Image, Px, quantize_px_u8}; use effectcraft_render::FloatCurve; +use effectcraft_render::disk_cache::Frame8; use filmcraft_color::{Matrix, Range}; use filmcraft_frame::{Chroma, PixelData, VideoFrame}; use rayon::prelude::*; @@ -80,14 +81,7 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec) - return img; } match &f.data { - PixelData::Rgba8(d) => { - img.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { - let src = &d[y * w * 4..(y + 1) * w * 4]; - for (o, s) in row.iter_mut().zip(src.as_chunks::<4>().0.iter()) { - *o = op.apply([U8[s[0] as usize], U8[s[1] as usize], U8[s[2] as usize]], U8[s[3] as usize]); - } - }); - } + PixelData::Rgba8(d) => convert_rgba8(&mut img.data, d, w, op, |p| p), PixelData::RgbaF32(d) => { // linear premultiplied → encoded premultiplied img.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { @@ -104,7 +98,7 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec) - let yuv = Yuv::new(f.color.matrix, f.color.range, 8); let amax = 255.0; convert_yuv( - &mut img, + &mut img.data, YuvSource { size: (w, h), chroma: *chroma, @@ -114,13 +108,14 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec) - }, &yuv, op, + |p| p, ); } PixelData::Yuv16 { planes, chroma, bits, alpha } => { let yuv = Yuv::new(f.color.matrix, f.color.range, *bits); let amax = ((1u32 << *bits) - 1) as f32; convert_yuv( - &mut img, + &mut img.data, YuvSource { size: (w, h), chroma: *chroma, @@ -130,12 +125,52 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec) - }, &yuv, op, + |p| p, ); } } img } +/// An 8-bit frame as [`frame_to_image_in`] converts it and an 8 bpc render then quantises it +/// ([`effectcraft_raster::quantize_px`]), kept as the 8-bit levels: expanded with +/// [`effectcraft_raster::expand_u8`] it is that quantised image to the bit, in a quarter of +/// the memory. `None` for frames with more than 8 bits (10/12-bit Y'CbCr, float). +pub(crate) fn frame_to_rgba8(f: &VideoFrame, op: AlphaOp) -> Option { + let (w, h) = (f.width as usize, f.height as usize); + let mut px = vec![[0u8; 4]; w * h]; + if w > 0 && h > 0 { + match &f.data { + PixelData::Rgba8(d) => convert_rgba8(&mut px, d, w, op, quantize_px_u8), + PixelData::Yuv8 { planes, chroma, alpha } => convert_yuv( + &mut px, + YuvSource { + size: (w, h), + chroma: *chroma, + planes: [&planes[0][..], &planes[1][..], &planes[2][..]], + alpha: alpha.as_deref().map(|a| &a[..]), + amax: 255.0, + }, + &Yuv::new(f.color.matrix, f.color.range, 8), + op, + quantize_px_u8, + ), + PixelData::RgbaF32(_) | PixelData::Yuv16 { .. } => return None, + } + } + Some(Frame8 { width: f.width, height: f.height, rgba: px.into_flattened() }) +} + +/// Straight or premultiplied 8-bit RGBA into `out` (one `O` per pixel, made by `store`). +fn convert_rgba8(out: &mut [O], d: &[u8], w: usize, op: AlphaOp, store: impl Fn(Px) -> O + Sync) { + out.par_chunks_mut(w).enumerate().for_each(|(y, row)| { + let Some(src) = d.get(y * w * 4..(y + 1) * w * 4) else { return }; + for (o, s) in row.iter_mut().zip(src.as_chunks::<4>().0.iter()) { + *o = store(op.apply([U8[s[0] as usize], U8[s[1] as usize], U8[s[2] as usize]], U8[s[3] as usize])); + } + }); +} + /// A movie frame turned the way its file says it is shown ([`crate::probe::video_turn`]: /// clockwise quarter turns; anything else leaves it as decoded). pub(crate) fn turned(img: Image, turn: image::metadata::Orientation) -> Image { @@ -311,13 +346,14 @@ struct YuvSource<'a, T> { amax: f32, } -fn convert_yuv(img: &mut Image, source: YuvSource<'_, T>, k: &Yuv, op: AlphaOp) { +/// Y'CbCr into `out` (one `O` per pixel, made by `store` from the converted pixel). +fn convert_yuv(out: &mut [O], source: YuvSource<'_, T>, k: &Yuv, op: AlphaOp, store: impl Fn(Px) -> O + Sync) { let YuvSource { size: (w, h), chroma, planes, alpha, amax } = source; let (sx, sy) = chroma.shifts(); let cw = w.div_ceil(1 << sx); let ch = h.div_ceil(1 << sy); let inv_amax = 1.0 / amax; - img.data.par_chunks_mut(w).enumerate().for_each_init( + out.par_chunks_mut(w).enumerate().for_each_init( || (vec![0f32; cw], vec![0f32; cw], vec![0f32; w], vec![0f32; w]), |(uc, vc, uf, vf), (y, row)| { // vertical chroma interpolation into normalised rows (Cb, Cr in −0.5..0.5) @@ -357,13 +393,13 @@ fn convert_yuv(img: &mut Image, source: YuvSource<'_, T>, k: &Yuv, op None => { for (x, o) in row.iter_mut().enumerate() { let c = rgb(x); - *o = [c[0], c[1], c[2], 1.0]; + *o = store([c[0], c[1], c[2], 1.0]); } } Some(al) => { let arow = &al[y * w..y * w + w]; for (x, o) in row.iter_mut().enumerate() { - *o = op.apply(rgb(x), (arow[x].f() * inv_amax).clamp(0.0, 1.0)); + *o = store(op.apply(rgb(x), (arow[x].f() * inv_amax).clamp(0.0, 1.0))); } } } @@ -376,30 +412,20 @@ fn convert_yuv(img: &mut Image, source: YuvSource<'_, T>, k: &Yuv, op pub(crate) fn dynamic_to_image(img: &image::DynamicImage, op: AlphaOp) -> Image { use image::DynamicImage as D; let (w, h) = (img.width(), img.height()); + if let D::ImageRgb32F(_) | D::ImageRgba32F(_) = img { + let px = img.to_rgba32f(); + let raw = px.as_raw(); + return float_to_image(w, h, op, |i| { + let s = &raw[i * 4..i * 4 + 4]; + [s[0], s[1], s[2], s[3]] + }); + } let mut out = Image::new(w, h); let wu = w as usize; if wu == 0 || h == 0 { return out; } match img { - D::ImageRgb32F(_) | D::ImageRgba32F(_) => { - let px = img.to_rgba32f(); - let raw = px.as_raw(); - let premul = op.mode == AlphaMode::Premultiplied; - out.data.par_chunks_mut(wu).enumerate().for_each(|(y, row)| { - for (x, o) in row.iter_mut().enumerate() { - let s = &raw[(y * wu + x) * 4..(y * wu + x) * 4 + 4]; - let a = s[3]; - let c = if premul { - let inv = if a > 0.0 { 1.0 / a } else { 0.0 }; - [op.float(s[0] * inv) * a, op.float(s[1] * inv) * a, op.float(s[2] * inv) * a] - } else { - [op.float(s[0]), op.float(s[1]), op.float(s[2])] - }; - *o = op.apply(c, a.clamp(0.0, 1.0)); - } - }); - } D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => { let px = img.to_rgba16(); let raw = px.as_raw(); @@ -425,6 +451,32 @@ pub(crate) fn dynamic_to_image(img: &image::DynamicImage, op: AlphaOp) -> Image out } +/// Float RGBA (linear light, alpha straight or premultiplied as the footage says), `px(i)` for +/// pixel `i` in rows, to an [`Image`]: how [`dynamic_to_image`] converts float stills, also used +/// for OpenEXR pictures made from decoded channel planes without an interleaved copy (#474). +pub(crate) fn float_to_image(w: u32, h: u32, op: AlphaOp, px: impl Fn(usize) -> [f32; 4] + Sync) -> Image { + let mut out = Image::new(w, h); + let wu = w as usize; + if wu == 0 || h == 0 { + return out; + } + let premul = op.mode == AlphaMode::Premultiplied; + out.data.par_chunks_mut(wu).enumerate().for_each(|(y, row)| { + for (x, o) in row.iter_mut().enumerate() { + let s = px(y * wu + x); + let a = s[3]; + let c = if premul { + let inv = if a > 0.0 { 1.0 / a } else { 0.0 }; + [op.float(s[0] * inv) * a, op.float(s[1] * inv) * a, op.float(s[2] * inv) * a] + } else { + [op.float(s[0]), op.float(s[1]), op.float(s[2])] + }; + *o = op.apply(c, a.clamp(0.0, 1.0)); + } + }); + out +} + /// Straight RGBA `f32` pixels (layered stills: Photoshop, SVG) to an [`Image`]. pub(crate) fn straight_to_image(w: u32, h: u32, px: &[[f32; 4]], op: AlphaOp) -> Image { let mut out = Image::new(w, h); @@ -536,6 +588,43 @@ mod tests { assert!((p[0] - 0.5).abs() < 1e-3 && (p[1] - 1.0).abs() < 1e-5 && p[2] > 1.5, "{p:?}"); } + /// The 8-bit levels of a frame expand to the float frame quantised to 8 bpc, bit for bit: + /// 4:2:0 and 4:4:4 Y'CbCr with and without alpha, and RGBA, under every alpha interpretation. + #[test] + fn rgba8_levels_are_the_quantised_float_frame() { + let (w, h) = (37usize, 18usize); + let noise = |n: usize, seed: usize| Arc::new((0..n).map(|i| ((i * 7919 + seed * 104_729) % 256) as u8).collect::>()); + let frame = |data| VideoFrame { + width: w as u32, + height: h as u32, + data, + color: filmcraft_color::ColorInfo::REC709, + par: (1, 1), + pts: filmcraft_time::Tick::ZERO, + }; + let yuv = |chroma: Chroma, alpha: bool| { + let n = w.div_ceil(1 << chroma.shifts().0) * h.div_ceil(1 << chroma.shifts().1); + frame(PixelData::Yuv8 { planes: [noise(w * h, 1), noise(n, 2), noise(n, 3)], chroma, alpha: alpha.then(|| noise(w * h, 4)) }) + }; + let frames = [yuv(Chroma::C420, false), yuv(Chroma::C420, true), yuv(Chroma::C444, true), frame(PixelData::Rgba8(noise(w * h * 4, 5)))]; + for f in &frames { + for mode in [AlphaMode::Straight, AlphaMode::Premultiplied, AlphaMode::Ignore] { + let op = AlphaOp::new(mode, [0.2, 0.5, 0.9]); + let q8 = frame_to_rgba8(f, op).expect("8-bit"); + let mut want = frame_to_image(f, op); + for p in &mut want.data { + effectcraft_raster::quantize_px(p, 255.0, 1.0 / 255.0); + } + assert_eq!((q8.width, q8.height), (want.width, want.height)); + for (got, want) in q8.rgba.as_chunks::<4>().0.iter().zip(&want.data) { + assert_eq!(effectcraft_raster::expand_u8(*got).map(f32::to_bits), want.map(f32::to_bits)); + } + } + } + let wide = frame(PixelData::RgbaF32(Arc::new(vec![0.5; w * h * 4]))); + assert!(frame_to_rgba8(&wide, AlphaOp::new(AlphaMode::Straight, [0.0; 3])).is_none()); + } + /// `cargo test -p effectcraft-media --lib bench -- --ignored --nocapture` #[test] #[ignore] diff --git a/crates/media/src/exr_channels.rs b/crates/media/src/exr_channels.rs index d372ec849..d0acf590f 100644 --- a/crates/media/src/exr_channels.rs +++ b/crates/media/src/exr_channels.rs @@ -6,12 +6,26 @@ //! 0, or the background depth for depth channels). Cryptomatte manifests come from the //! `cryptomatte//name` and `cryptomatte//manifest` header attributes (the published //! Cryptomatte metadata convention: the manifest is a JSON object of name → hex hash). +//! +//! Decoded files are kept in a small cache ([`CACHE_BUDGET`]) that the picture of an EXR +//! footage item shares with EXtractoR / Cryptomatte once an effect has read its channels +//! (#474); a file is decoded once however many callers ask for it at the same time. use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; -use effectcraft_raster::AuxChannels; use effectcraft_raster::channels3d::{BACKGROUND_DEPTH, split_channel}; +use effectcraft_raster::{AuxChannels, Image}; +use effectcraft_render::reads::{ReadFile, ReadFiles}; +use exr::block::UncompressedBlock; +use exr::block::chunk::TileCoordinates; +use exr::image::read::image::ReadImage; +use exr::image::read::layers::{ChannelsReader, ReadAllLayers, ReadChannels}; +use exr::meta::attribute::SampleType; +use exr::meta::header::Header; + +use crate::convert::{AlphaOp, float_to_image}; /// The largest display window decoded (16384²; vector footage and Continuously Rasterize /// stop at the same size). @@ -33,6 +47,11 @@ fn channel_name(part: Option<&str>, channel: &str) -> String { } } +/// The part name channels are prefixed with (`None`: unnamed). +fn part_name(header: &Header) -> Option { + header.own_attributes.layer_name.as_ref().map(|t| t.to_string()).filter(|s| !s.is_empty()) +} + /// Parse a Cryptomatte manifest (`{"name": "hexhash", …}`). pub fn parse_manifest(json: &str) -> Vec<(String, u32)> { let Ok(serde_json::Value::Object(m)) = serde_json::from_str::(json) else { return vec![] }; @@ -53,23 +72,245 @@ pub fn unsupported_compression(bytes: &[u8]) -> Option<&'static str> { .then_some("OpenEXR HTJ2K compression isn't supported yet: re-save the file with ZIP, PIZ or DWAA compression") } -/// Read all channels of an EXR file's bytes. `None` when it is not a readable EXR. -pub fn read_exr_channels(bytes: &[u8]) -> Option { - use exr::prelude::*; - let img = read().no_deep_data().largest_resolution_level().all_channels().all_layers().all_attributes().from_buffered(std::io::Cursor::new(bytes)).ok()?; - let dw = img.attributes.display_window; - let (w, h) = (dw.size.0, dw.size.1); - if w == 0 || h == 0 { - return None; +/// Which channels a decode keeps, by plane name, and the display window they are placed in +/// (the first part's, as the `exr` crate reports the image's). +struct Planes<'k> { + keep: &'k dyn Fn(&str) -> bool, + display: exr::meta::attribute::IntegerBounds, +} + +/// One part's kept channels while it is decoded: each line of samples goes straight into its +/// channel's display-window plane (no copy of the part's samples in their own type first). +struct PlanesReader { + /// Per channel of the part: its plane name, sample type and plane (`None`: not kept). + planes: Vec)>>, + /// The data window's position in the display window, and the data window's and display + /// window's sizes. + offset: (i64, i64), + layer: (usize, usize), + display: (usize, usize), + f16s: Vec, + u32s: Vec, + f32s: Vec, + /// The part's channel indices of exact `R`, `G`, `B` and `A`, when it has R, G and B. + rgb: Option<([usize; 3], Option)>, + /// The part's display window differs from the first part's. + own_display: bool, +} + +/// A decoded part: its kept planes (in channel order) and what [`PlanesReader`] found. +struct PartPlanes { + planes: Vec<(String, Vec)>, + /// Positions in `planes` of the part's R, G, B (and A) channels, when it has them and keeps + /// them all. + rgb: Option<([usize; 3], Option)>, + has_rgb: bool, + exact: bool, +} + +impl<'s> ReadChannels<'s> for Planes<'_> { + type Reader = PlanesReader; + + fn create_channels_reader(&'s self, header: &Header) -> exr::error::Result { + if header.deep { + return Err(exr::error::Error::NotSupported("deep data".into())); + } + let dw = self.display; + let display = (dw.size.0, dw.size.1); + // Each channel is a display-window plane: a 60000² window over a 1×1 data window was a + // multi-gigabyte allocation per channel (#2141). + let n = display.0.checked_mul(display.1).filter(|n| *n > 0 && *n <= MAX_DISPLAY_PIXELS).ok_or(exr::error::Error::Invalid("display window".into()))?; + let prefix = part_name(header); + let pos = header.own_attributes.layer_position; + let offset = (i64::from(pos.0) - i64::from(dw.position.0), i64::from(pos.1) - i64::from(dw.position.1)); + let planes = header + .channels + .list + .iter() + .map(|ch| { + let name = channel_name(prefix.as_deref(), &ch.name.to_string()); + let fill = if is_depth(&name) { BACKGROUND_DEPTH } else { 0.0 }; + (self.keep)(&name).then(|| (name, ch.sample_type, vec![fill; n])) + }) + .collect(); + let find = |c: &str| header.channels.find_index_of_channel(&exr::meta::attribute::Text::from(c)); + let rgb = match (find("R"), find("G"), find("B")) { + (Some(r), Some(g), Some(b)) => Some(([r, g, b], find("A"))), + _ => None, + }; + Ok(PlanesReader { + planes, + offset, + layer: (header.layer_size.0, header.layer_size.1), + display, + f16s: vec![], + u32s: vec![], + f32s: vec![], + rgb, + own_display: header.shared_attributes.display_window != dw, + }) } - let mut aux = AuxChannels::new(w as u32, h as u32, 1.0); +} + +impl ChannelsReader for PlanesReader { + type Channels = PartPlanes; + + fn filter_block(&self, tile: TileCoordinates) -> bool { + tile.is_largest_resolution_level() && self.planes.iter().any(Option::is_some) + } + + fn read_block(&mut self, header: &Header, block: UncompressedBlock) -> exr::error::UnitResult { + let ((lw, lh), (w, h)) = (self.layer, self.display); + for line in block.lines(&header.channels) { + let Some(Some((_, kind, plane))) = self.planes.get_mut(line.location.channel) else { continue }; + let (x0, y, count) = (line.location.position.0, line.location.position.1, line.location.sample_count); + // The samples of data-window row `y`, columns `x0..x0 + count`, at display row `ty` + // from display column `tx0`; clipped to the display window. + if y >= lh || x0.checked_add(count).is_none_or(|end| end > lw) { + continue; + } + let Some(ty) = usize::try_from(y as i64 + self.offset.1).ok().filter(|ty| *ty < h) else { continue }; + let tx0 = x0 as i64 + self.offset.0; + let skip = usize::try_from(-tx0).unwrap_or(0).min(count); + let tx = usize::try_from(tx0.max(0)).unwrap_or(usize::MAX); + let take = (count - skip).min(w.saturating_sub(tx)); + let start = ty.checked_mul(w).and_then(|row| row.checked_add(tx)); + let Some(dst) = start.filter(|_| take > 0).and_then(|s| plane.get_mut(s..s.checked_add(take)?)) else { continue }; + match kind { + SampleType::F16 => { + self.f16s.resize(count, exr::prelude::f16::ZERO); + line.read_samples_into_slice(&mut self.f16s)?; + for (d, s) in dst.iter_mut().zip(self.f16s.iter().skip(skip)) { + *d = s.to_f32(); + } + } + SampleType::F32 => { + self.f32s.resize(count, 0.0); + line.read_samples_into_slice(&mut self.f32s)?; + for (d, s) in dst.iter_mut().zip(self.f32s.iter().skip(skip)) { + *d = *s; + } + } + SampleType::U32 => { + self.u32s.resize(count, 0); + line.read_samples_into_slice(&mut self.u32s)?; + for (d, s) in dst.iter_mut().zip(self.u32s.iter().skip(skip)) { + *d = *s as f32; + } + } + } + } + Ok(()) + } + + fn into_channels(self) -> PartPlanes { + // Positions of the kept channels among the kept planes. + let mut at = vec![None; self.planes.len()]; + let mut planes = Vec::with_capacity(self.planes.len()); + for (i, p) in self.planes.into_iter().enumerate() { + if let Some((name, _, data)) = p { + if let Some(slot) = at.get_mut(i) { + *slot = Some(planes.len()); + } + planes.push((name, data)); + } + } + let kept = |i: usize| at.get(i).copied().flatten(); + let has_rgb = self.rgb.is_some(); + let rgb = self.rgb.and_then(|([r, g, b], a)| { + let a = match a { + Some(a) => Some(kept(a)?), + None => None, + }; + Some(([kept(r)?, kept(g)?, kept(b)?], a)) + }); + PartPlanes { planes, rgb, has_rgb, exact: !self.own_display } + } +} + +/// How the `image` crate's OpenEXR decoder would show a file: the first part with exact `R`, `G` +/// and `B` channels (alpha `A` when it has one, else opaque), placed in the display window with +/// 0 outside the data window. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Rgb { + /// No part has R, G and B: the decoder refuses the file (a multi-layer file, shown with + /// [`layered_image`]'s rule). + None, + /// The channels (indices in [`AuxChannels::channels`]) hold exactly what it would show. + Planes([usize; 3], Option), + /// The planes can't stand in for it (a depth-named channel, whose plane is filled with the + /// background depth, or another display window): decode with the `image` crate. + Unsupported, +} + +/// A decoded file: its channels and how its picture is made of them. +pub(crate) struct Decoded { + pub(crate) aux: Arc, + rgb: Rgb, +} + +impl Decoded { + /// Bytes held (the planes; names and manifests are small). + fn bytes(&self) -> usize { + self.aux.channels.iter().map(|(n, p)| n.len() + std::mem::size_of_val(p.as_slice())).sum() + } +} + +/// The most bytes of planes one decode allocates (every kept channel is a display-window plane +/// of f32, allocated before any pixels are read): a header can ask for far more than the file +/// holds. +#[cfg(target_pointer_width = "64")] +const MAX_DECODE_BYTES: usize = 8 << 30; +#[cfg(not(target_pointer_width = "64"))] +const MAX_DECODE_BYTES: usize = 512 << 20; + +/// Why a file's channels weren't decoded. +#[derive(Debug, PartialEq)] +enum Refused { + /// Not a readable OpenEXR file. + Unreadable, + /// Its kept channels need more memory than [`MAX_DECODE_BYTES`] (the reason, to show). + TooLarge(String), +} + +/// Bytes the planes of the channels `keep` names would take (`None`: not a readable header). +fn planes_bytes(meta: &exr::meta::MetaData, keep: &dyn Fn(&str) -> bool) -> Option { + let dw = meta.headers.first()?.shared_attributes.display_window; + let n = dw.size.0.checked_mul(dw.size.1)?; + let mut kept = 0usize; + for header in meta.headers.iter() { + let prefix = part_name(header); + kept = kept.saturating_add(header.channels.list.iter().filter(|ch| keep(&channel_name(prefix.as_deref(), &ch.name.to_string()))).count()); + } + Some(n.saturating_mul(kept).saturating_mul(std::mem::size_of::())) +} + +/// Decode the channels of an EXR file's bytes that `keep` names (by plane name). +fn decode(bytes: &[u8], keep: &dyn Fn(&str) -> bool) -> Result { + let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).map_err(|_| Refused::Unreadable)?; + let display = meta.headers.first().ok_or(Refused::Unreadable)?.shared_attributes.display_window; + let need = planes_bytes(&meta, keep).ok_or(Refused::Unreadable)?; + if need > MAX_DECODE_BYTES { + let gb = |b: usize| b as f64 / f64::from(1u32 << 30); + return Err(Refused::TooLarge(format!( + "its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", + display.size.0, + display.size.1, + gb(need), + gb(MAX_DECODE_BYTES) + ))); + } + let read = ReadImage::new(ReadAllLayers { read_channels: Planes { keep, display } }, |_| {}); + let img = read.from_buffered(std::io::Cursor::new(bytes)).map_err(|_| Refused::Unreadable)?; + let dw = img.attributes.display_window; + let mut aux = AuxChannels::new(dw.size.0 as u32, dw.size.1 as u32, 1.0); let mut crypto: HashMap, Option)> = HashMap::new(); - let mut collect_meta = |other: &HashMap| { + let mut collect_meta = |other: &HashMap| { for (k, v) in other { let key = k.to_string(); let Some(rest) = key.strip_prefix("cryptomatte/") else { continue }; let Some((id, field)) = rest.split_once('/') else { continue }; - let AttributeValue::Text(t) = v else { continue }; + let exr::meta::attribute::AttributeValue::Text(t) = v else { continue }; let e = crypto.entry(id.to_string()).or_default(); match field { "name" => e.0 = Some(t.to_string()), @@ -79,24 +320,22 @@ pub fn read_exr_channels(bytes: &[u8]) -> Option { } }; collect_meta(&img.attributes.other); - // Each channel is a display-window plane: a 60000² window over a 1×1 data window was a - // multi-gigabyte allocation per channel (#2141). - let n = w.checked_mul(h).filter(|n| *n <= MAX_DISPLAY_PIXELS)?; - // The decoded image is consumed channel by channel, so each channel's samples are freed (or - // moved) as its plane is made instead of the whole file being held twice (#474). + let mut rgb = Rgb::None; for layer in img.layer_data { collect_meta(&layer.attributes.other); - let prefix = layer.attributes.layer_name.as_ref().map(|t| t.to_string()).filter(|s| !s.is_empty()); - let size = (layer.size.0, layer.size.1); - let pos = layer.attributes.layer_position; - let offset = (i64::from(pos.0) - i64::from(dw.position.0), i64::from(pos.1) - i64::from(dw.position.1)); - for ch in layer.channel_data.list { - let name = channel_name(prefix.as_deref(), &ch.name.to_string()); - let fill = if is_depth(&name) { BACKGROUND_DEPTH } else { 0.0 }; - if let Some(plane) = place(ch.sample_data, size, offset, (w, h), n, fill) { - aux.channels.push((name, plane)); - } + let part = layer.channel_data; + if rgb == Rgb::None && part.has_rgb { + let base = aux.channels.len(); + rgb = match part.rgb { + Some(([r, g, b], a)) if part.exact => { + let picked = [Some(r), Some(g), Some(b), a]; + let depth = picked.iter().flatten().any(|i| part.planes.get(*i).is_some_and(|(n, _)| is_depth(n))); + if depth { Rgb::Unsupported } else { Rgb::Planes([base + r, base + g, base + b], a.map(|a| base + a)) } + } + _ => Rgb::Unsupported, + }; } + aux.channels.extend(part.planes); } for (_, (name, manifest)) in crypto { if let (Some(n), Some(m)) = (name, manifest) { @@ -104,46 +343,13 @@ pub fn read_exr_channels(bytes: &[u8]) -> Option { } } aux.manifests.sort(); - Some(aux) + Ok(Decoded { aux: Arc::new(aux), rgb }) } -/// One channel's samples (`size`, at `offset` in the `display` window of `n` pixels) as a -/// display-window plane, `fill` outside its data window. A channel covering exactly the display -/// window is converted in one pass, and an f32 one is moved without a copy. `None` when the -/// channel has fewer samples than its size. -fn place(samples: exr::image::FlatSamples, size: (usize, usize), offset: (i64, i64), display: (usize, usize), n: usize, fill: f32) -> Option> { - use exr::image::FlatSamples; - let (lw, lh) = size; - if samples.len() < lw.checked_mul(lh)? { - return None; - } - if size == display && offset == (0, 0) { - return Some(match samples { - FlatSamples::F32(mut v) => { - v.truncate(n); - v - } - FlatSamples::F16(v) => v.iter().take(n).map(|s| s.to_f32()).collect(), - FlatSamples::U32(v) => v.iter().take(n).map(|s| *s as f32).collect(), - }); - } - let value = |i: usize| match &samples { - FlatSamples::F32(v) => v.get(i).copied(), - FlatSamples::F16(v) => v.get(i).map(|s| s.to_f32()), - FlatSamples::U32(v) => v.get(i).map(|s| *s as f32), - }; - let (w, h) = display; - let mut plane = vec![fill; n]; - for y in 0..lh { - let Some(ty) = usize::try_from(y as i64 + offset.1).ok().filter(|ty| *ty < h) else { continue }; - for x in 0..lw { - let Some(tx) = usize::try_from(x as i64 + offset.0).ok().filter(|tx| *tx < w) else { continue }; - if let (Some(v), Some(p)) = (value(y * lw + x), plane.get_mut(ty * w + tx)) { - *p = v; - } - } - } - Some(plane) +/// Read all channels of an EXR file's bytes. `None` when it is not a readable EXR. +pub fn read_exr_channels(bytes: &[u8]) -> Option { + let aux = decode(bytes, &|_| true).ok()?.aux; + Some(Arc::try_unwrap(aux).unwrap_or_else(|a| (*a).clone())) } /// Names of the beauty pass, most preferred first, matched against the last part of a layer's @@ -186,6 +392,36 @@ fn picture_layer<'a>(aux: &AuxChannels, layers: &[&'a str]) -> Option<&'a str> { .copied() } +/// The planes a multi-layer file's picture is made of (see [`layered_image`]): red, green, blue +/// (one channel thrice for grey) and alpha, by name. Only the names of `aux` are read. +fn picture_names(aux: &AuxChannels) -> Option<([String; 3], Option)> { + let layers = aux.layers(); + let colour = picture_layer(aux, &layers)?; + let names = aux.layer_rgba(colour); + // A layer without R, G and B channels shows its first channel as grey. + let first = aux.names().into_iter().find(|n| split_channel(n).0 == colour).unwrap_or_default(); + let pick = |k: usize| names.get(k).map(String::as_str).filter(|n| !n.is_empty()).unwrap_or(first).to_string(); + let a = names.get(3).filter(|n| !n.is_empty() && aux.get(n).is_some()).cloned(); + Some(([pick(0), pick(1), pick(2)], a)) +} + +/// The channels of the picture of a multi-layer file and nothing else (names first from the +/// headers, then only those channels decoded; in a multi-part file the other parts' pixels are +/// not even decompressed), with the names of its planes. +fn picture_only(bytes: &[u8]) -> Result<(Decoded, [String; 3], Option), Refused> { + let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).map_err(|_| Refused::Unreadable)?; + let mut names = AuxChannels::new(0, 0, 1.0); + for header in meta.headers.iter() { + let prefix = part_name(header); + names.channels.extend(header.channels.list.iter().map(|ch| (channel_name(prefix.as_deref(), &ch.name.to_string()), vec![]))); + } + let (rgb, a) = picture_names(&names).ok_or(Refused::Unreadable)?; + // Planes are looked up by name ignoring case, so every channel that could answer is kept. + let keep = |n: &str| rgb.iter().chain(&a).any(|k| k.eq_ignore_ascii_case(n)); + let decoded = decode(bytes, &keep)?; + Ok((decoded, rgb, a)) +} + /// The picture of a multi-layer OpenEXR file without an unnamed RGB layer (Blender's /// `ViewLayer.Combined.R`, the compositor's `Image.R`, Nuke's `beauty.R`, …), which the image /// decoder rejects. After Effects shows a file's main RGBA channels and leaves the other layers @@ -193,26 +429,13 @@ fn picture_layer<'a>(aux: &AuxChannels, layers: &[&'a str]) -> Option<&'a str> { /// that is not a data pass (never Cryptomatte, depth or normals, #412), else the first channel /// as grey. Linear, straight RGBA as the file stores it. `None` when it is not a readable EXR. pub fn layered_image(bytes: &[u8]) -> Option { - picture_of(&read_exr_channels(bytes)?) -} - -/// [`layered_image`] of the EXR at `path` from the channel cache, so the picture and EXtractoR / -/// Cryptomatte share one decode of the file (#474). -pub(crate) fn cached_layered_image(path: &str, bytes: Arc<[u8]>) -> Option { - let aux = cached(path, || Some(bytes))?; - picture_of(&aux) -} - -/// The picture of decoded channels (see [`layered_image`]). -fn picture_of(aux: &AuxChannels) -> Option { - let layers = aux.layers(); - let colour = picture_layer(aux, &layers)?; - let names = aux.layer_rgba(colour); - // A layer without R, G and B channels shows its first channel as grey. - let first = aux.names().into_iter().find(|n| split_channel(n).0 == colour).unwrap_or_default(); - let plane = |k: usize| -> Option<&[f32]> { aux.get(names.get(k).map(String::as_str).filter(|n| !n.is_empty()).unwrap_or(first)) }; - let (r, g, b) = (plane(0)?, plane(1)?, plane(2)?); - let a = names.get(3).filter(|n| !n.is_empty()).and_then(|n| aux.get(n)); + let (d, rgb, a) = picture_only(bytes).ok()?; + let aux = &d.aux; + let [r, g, b] = [aux.get(&rgb[0])?, aux.get(&rgb[1])?, aux.get(&rgb[2])?]; + let a = match &a { + Some(n) => Some(aux.get(n)?), + None => None, + }; let n = (aux.width as usize).checked_mul(aux.height as usize)?; let mut data = Vec::with_capacity(n.checked_mul(4)?); for i in 0..n { @@ -227,40 +450,357 @@ fn picture_of(aux: &AuxChannels) -> Option { } } -type Cache = Mutex>)>>; +/// The picture made of planes `rgb` and `a` (opaque without one) of `aux`, as +/// [`crate::convert::dynamic_to_image`] makes it of the same values. `None` when a plane is +/// missing or short. +fn planes_picture(aux: &AuxChannels, rgb: [&[f32]; 3], a: Option<&[f32]>, op: AlphaOp) -> Option { + let n = (aux.width as usize).checked_mul(aux.height as usize)?; + if rgb.iter().chain(&a).any(|p| p.len() < n) { + return None; + } + let [r, g, b] = rgb; + let at = |p: &[f32], i: usize| p.get(i).copied().unwrap_or(0.0); + Some(float_to_image(aux.width, aux.height, op, |i| [at(r, i), at(g, i), at(b, i), a.map_or(1.0, |a| at(a, i))])) +} -fn cache() -> &'static Cache { - static CACHE: OnceLock = OnceLock::new(); - CACHE.get_or_init(|| Mutex::new(Vec::new())) +/// The picture of a decoded file by [`layered_image`]'s rule. +fn layered_picture_of(aux: &AuxChannels, op: AlphaOp) -> Option { + let (rgb, a) = picture_names(aux)?; + let a = match &a { + Some(n) => Some(aux.get(n)?), + None => None, + }; + planes_picture(aux, [aux.get(&rgb[0])?, aux.get(&rgb[1])?, aux.get(&rgb[2])?], a, op) +} + +/// The picture of the multi-layer EXR at `path` ([`layered_image`]'s rule) as an [`Image`]: +/// from the channel cache when `shared` (an effect reads the footage's channels, so they are +/// decoded anyway), else of the picture's channels alone (also when the cache has no channels +/// for the file: a read that failed, or a broken part the picture doesn't use). `Err(Some(why))` +/// when the file is too large to decode, `Err(None)` when it isn't a readable multi-layer EXR. +pub(crate) fn layered_picture(path: &str, bytes: Arc<[u8]>, file: &ReadFile, op: AlphaOp, shared: bool) -> Result> { + if shared && let Some(d) = cache().get(path, Use::Picture, || read_as(file, bytes.clone())) { + return layered_picture_of(&d.aux, op).ok_or(None); + } + let (d, rgb, a) = picture_only(&bytes).map_err(|r| match r { + Refused::TooLarge(why) => Some(why), + Refused::Unreadable => None, + })?; + let aux = &d.aux; + let plane = |n: &str| aux.get(n).ok_or(None); + let a = match &a { + Some(n) => Some(plane(n)?), + None => None, + }; + planes_picture(aux, [plane(&rgb[0])?, plane(&rgb[1])?, plane(&rgb[2])?], a, op).ok_or(None) +} + +/// The picture of the EXR at `path` from the channel cache (#474: EXtractoR / Cryptomatte read +/// this footage's channels, so the picture shares their decode): what the `image` crate's +/// decoder shows for a file it reads, [`layered_image`]'s rule for one it refuses. `None` when +/// the planes can't stand in for the `image` crate's picture (decode with it), or the file is +/// not a readable EXR. +pub(crate) fn cached_picture(path: &str, bytes: Arc<[u8]>, file: &ReadFile, op: AlphaOp) -> Option { + let d = cache().get(path, Use::Picture, || read_as(file, bytes))?; + let aux = &d.aux; + match d.rgb { + Rgb::None => layered_picture_of(aux, op), + Rgb::Planes([r, g, b], a) => { + let plane = |i: usize| aux.channels.get(i).map(|(_, p)| p.as_slice()); + let a = match a { + Some(a) => Some(plane(a)?), + None => None, + }; + planes_picture(aux, [plane(r)?, plane(g)?, plane(b)?], a, op) + } + Rgb::Unsupported => None, + } +} + +/// How many bytes of decoded channels the cache keeps, like the frame cache's default +/// ([`crate::DEFAULT_BUDGET`]): two 2560×1440 files of 32 channels (470 MB each, as every plane +/// is f32). A soft bound: the newest file is kept whatever its size (so a frame's picture and its +/// effects share its decode), and files still in use are never dropped (planes an effect holds, +/// [`HELD_FILES`] pictures waiting for their effects, decodes in progress), so memory can go +/// above it while they are. (Measured on such a sequence decoded one frame at a time: 1 GiB held +/// peak memory about 1 GB lower than 2 GiB, at the same speed.) +#[cfg(not(target_arch = "wasm32"))] +pub const CACHE_BUDGET: usize = 1 << 30; +#[cfg(target_arch = "wasm32")] +pub const CACHE_BUDGET: usize = 512 << 20; + +/// At most this many files are cached (unreadable ones hold no bytes). +const CACHE_FILES: usize = 64; + +/// At most this many files whose picture was made of their planes are kept for their effects +/// (the renderer asks for a frame's picture, then its channels): about as many frames as are +/// rendered at once. The oldest stops being kept when another comes. +const HELD_FILES: usize = 4; + +/// A file's decode: done once, by the first caller; the others wait for it. With the files read +/// for it (see [`crate::reads`]), noted again on every hit. +type Slot = Arc>, ReadFiles)>>; + +/// Bytes the caller already read from `file`, given to the cache as read from it (so the entry +/// keeps the file's identity). +fn read_as(file: &ReadFile, bytes: Arc<[u8]>) -> Option> { + crate::reads::note(file.clone()); + Some(bytes) +} + +struct Entry { + path: String, + slot: Slot, + /// Bytes of the finished decode, or the planes it will allocate while it decodes. + bytes: usize, + /// When it was last asked for or finished decoding (a counter). + used: u64, +} + +impl Entry { + /// Dropping it would free nothing or lose a decode in progress: an effect (or a picture + /// waiting for its effects) still holds its planes, or it is decoding. + fn in_use(&self) -> bool { + match self.slot.get() { + None => true, + Some((None, _)) => false, + Some((Some(d), _)) => Arc::strong_count(d) > 1 || Arc::strong_count(&d.aux) > 1, + } + } +} + +struct State { + entries: Vec, + clock: u64, + /// Files whose picture was made of their planes and whose channels haven't been asked for + /// since, oldest first (at most [`HELD_FILES`]). + held: std::collections::VecDeque<(String, Arc)>, +} + +/// Who asks for a file's channels. +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum Use { + /// The picture of a footage item whose effects read its channels next: kept for them. + Picture, + /// The channels themselves (EXtractoR, Cryptomatte, the 3D Channel effects). + Channels, +} + +/// Decoded EXR files by path, bounded by bytes, least recently used out first. +pub(crate) struct ChannelCache { + state: Mutex, + budget: usize, + /// Files decoded (for tests). + decodes: AtomicU64, +} + +/// Removes a decode's entry if the decode panics, so the file doesn't stay "decoding" (never +/// dropped, its estimated bytes counted) until someone asks for it again. +struct Abandon<'a> { + cache: &'a ChannelCache, + slot: &'a Slot, +} + +impl Drop for Abandon<'_> { + fn drop(&mut self) { + if std::thread::panicking() { + self.cache.lock().entries.retain(|e| !Arc::ptr_eq(&e.slot, self.slot)); + } + } +} + +impl ChannelCache { + pub(crate) const fn new(budget: usize) -> Self { + Self { state: Mutex::new(State { entries: Vec::new(), clock: 0, held: std::collections::VecDeque::new() }), budget, decodes: AtomicU64::new(0) } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Set the bytes of the entry of `slot` (if it's still cached), mark it used now and drop + /// least recently used files until the rest fit the budget. + fn account(&self, slot: &Slot, bytes: usize) { + let mut state = self.lock(); + state.clock += 1; + let clock = state.clock; + // (gone when the file was forgotten meanwhile) Used as of now: a file asked for before + // another but decoded after it is not the older one. + if let Some(e) = state.entries.iter_mut().find(|e| Arc::ptr_eq(&e.slot, slot)) { + e.bytes = bytes; + e.used = clock; + } + Self::evict(&mut state.entries, self.budget, slot); + } + + /// The decoded file at `path`, read with `read` by the first caller; callers asking for the + /// same file meanwhile wait for that decode instead of decoding it again. + pub(crate) fn get(&self, path: &str, by: Use, read: impl FnOnce() -> Option>) -> Option> { + let slot = { + let mut state = self.lock(); + state.clock += 1; + let clock = state.clock; + match state.entries.iter_mut().find(|e| e.path == path) { + Some(e) => { + e.used = clock; + e.slot.clone() + } + None => { + let slot = Slot::default(); + state.entries.push(Entry { path: path.to_string(), slot: slot.clone(), bytes: 0, used: clock }); + slot + } + } + }; + let mut decoded_here = false; + // Waiting here can block a rayon worker (which `Inner::frame_at` avoids for frames): that + // is safe because the decode never waits on rayon's global pool (the exr crate + // decompresses on a pool of its own and this thread only receives the blocks), so the + // decoding thread can't be waiting for this one. + let (v, files) = slot.get_or_init(|| { + decoded_here = true; + self.decodes.fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + count_decode(true); + let _abandon = Abandon { cache: self, slot: &slot }; + let (bytes, files) = crate::reads::captured(read); + (bytes.and_then(|bytes| self.decode_file(path, &slot, &bytes)), files) + }); + // The file(s) the decode was made of, read now or for an earlier caller. + crate::reads::note_all(files); + let v = v.clone(); + if decoded_here { + self.account(&slot, v.as_ref().map_or(0, |d| d.bytes())); + } + let mut state = self.lock(); + match (by, &v) { + (Use::Picture, Some(d)) => { + if !state.held.iter().any(|(p, _)| p == path) { + state.held.push_back((path.to_string(), d.clone())); + if state.held.len() > HELD_FILES { + state.held.pop_front(); + } + } + } + (Use::Channels, _) => state.held.retain(|(p, _)| p != path), + (Use::Picture, None) => {} + } + drop(state); + v + } + + /// Decode the file at `path` whose bytes are `bytes` for `slot` (see [`ChannelCache::get`]). + fn decode_file(&self, path: &str, slot: &Slot, bytes: &[u8]) -> Option> { + // The planes it will allocate count against the budget while it decodes. + if let Ok(meta) = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false) + && let Some(need) = planes_bytes(&meta, &|_| true) + { + self.account(slot, need.min(MAX_DECODE_BYTES)); + } + match decode(bytes, &|_| true) { + Ok(d) => Some(Arc::new(d)), + Err(Refused::TooLarge(why)) => { + log::warn!("media: {path}: {why}"); + None + } + Err(Refused::Unreadable) => None, + } + } + + /// Drop least recently used files not in use until the rest fit the budget, keeping `newest`. + fn evict(entries: &mut Vec, budget: usize, newest: &Slot) { + while entries.iter().map(|e| e.bytes).sum::() > budget || entries.len() > CACHE_FILES { + let oldest = entries.iter().enumerate().filter(|(_, e)| !Arc::ptr_eq(&e.slot, newest) && !e.in_use()).min_by_key(|(_, e)| e.used).map(|(i, _)| i); + let Some(i) = oldest else { break }; + entries.remove(i); + } + } + + pub(crate) fn forget(&self, path: &str) { + let mut state = self.lock(); + state.entries.retain(|e| e.path != path); + state.held.retain(|(p, _)| p != path); + } + + #[cfg(test)] + fn decodes(&self) -> u64 { + self.decodes.load(Ordering::Relaxed) + } + + #[cfg(test)] + fn cached(&self) -> Vec { + self.lock().entries.iter().map(|e| e.path.clone()).collect() + } +} + +fn cache() -> &'static ChannelCache { + static CACHE: ChannelCache = ChannelCache::new(CACHE_BUDGET); + &CACHE } /// Drop the cached channels of `path` (the file changed on disk). pub(crate) fn forget(path: &str) { - if let Ok(mut c) = cache().lock() { - c.retain(|(p, _)| p != path); - } + cache().forget(path); } -/// Read (and cache, a few files) the channels of the EXR at `path` via `read`. +/// Stop keeping the decodes of the last pictures for their effects ([`HELD_FILES`]): which +/// footage effects read changed, so they may wait for effects that are gone. Their entries stay +/// cached as any other, least recently used out first. +pub(crate) fn release_held() { + cache().lock().held.clear(); +} + +/// Read (and cache, see [`CACHE_BUDGET`]) the channels of the EXR at `path` via `read`. pub(crate) fn cached(path: &str, read: impl FnOnce() -> Option>) -> Option> { - let cache = cache(); - if let Some(v) = cache.lock().ok().and_then(|c| c.iter().find(|(p, _)| p == path).map(|(_, v)| v.clone())) { - return v; - } - let v = read().and_then(|b| read_exr_channels(&b)).map(Arc::new); - if let Ok(mut c) = cache.lock() { - if c.len() >= 4 { - c.remove(0); - } - c.push((path.to_string(), v.clone())); - } - v + cache().get(path, Use::Channels, read).map(|d| d.aux.clone()) +} + +#[cfg(test)] +thread_local! { + /// Decodes of a still's pixels on this thread ([`count_decode`]): the `image` crate's, then + /// the channel cache's. + static DECODES: std::cell::Cell<[u64; 2]> = const { std::cell::Cell::new([0; 2]) }; +} + +/// Count a decode of a file's pixels on this thread (tests): by the channel cache (`channels`) +/// or by the `image` crate. +#[cfg(test)] +pub(crate) fn count_decode(channels: bool) { + DECODES.with(|d| { + let mut n = d.get(); + n[usize::from(channels)] += 1; + d.set(n); + }); +} + +/// The decodes [`count_decode`] counted on this thread since the last call: by the `image` crate +/// and by the channel cache. +#[cfg(test)] +pub(crate) fn take_decodes() -> [u64; 2] { + DECODES.with(|d| d.replace([0; 2])) } #[cfg(test)] mod tests { use super::*; + /// An EXR file of `layers` (with their display window `display`). + fn file(layers: Vec>>, display: exr::prelude::IntegerBounds) -> Vec { + use exr::prelude::*; + let image = Image::from_layers(ImageAttributes::new(display), layers); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut bytes).unwrap(); + bytes.into_inner() + } + + /// A single-part file of float channels named `names`, `w`×`h`, every sample `v`. + fn flat(names: &[&str], (w, h): (usize, usize), v: f32) -> Vec { + use exr::prelude::*; + let list: Vec> = names.iter().map(|n| AnyChannel::new(*n, FlatSamples::F32(vec![v; w * h]))).collect(); + let layer = Layer::new((w, h), LayerAttributes::default(), Encoding::FAST_LOSSLESS, AnyChannels::sort(list.into())); + file(vec![layer], IntegerBounds::from_dimensions((w, h))) + } + #[test] fn reads_layered_channels_and_cryptomatte_metadata() { use exr::prelude::*; @@ -294,53 +834,368 @@ mod tests { assert!(read_exr_channels(b"not an exr").is_none()); } - /// #474: a full-window f32 channel (Cryptomatte ranks, …) becomes its plane without a copy, - /// so a decode no longer holds the file's samples twice; other channels are placed in the - /// display window as before. + /// #474: each line of samples goes straight into its display-window plane: a data window + /// inside the display window is placed with the fill around it (the background depth for + /// depth), one partly outside is clipped, never out of bounds; half and uint samples are + /// converted as the file stores them. #[test] - fn channels_become_planes_without_an_extra_copy() { - use exr::image::FlatSamples; - let v = vec![0.25f32; 6]; - let ptr = v.as_ptr(); - let plane = place(FlatSamples::F32(v), (3, 2), (0, 0), (3, 2), 6, 0.0).unwrap(); - assert_eq!(plane.as_ptr(), ptr, "moved, not copied"); - assert_eq!(plane, [0.25; 6]); - let half = |x: f32| exr::prelude::f16::from_f32(x); - let full = place(FlatSamples::F16(vec![half(0.5); 6]), (3, 2), (0, 0), (3, 2), 6, 0.0).unwrap(); - assert_eq!(full, [0.5; 6]); - // A 2×1 data window at (1, 1) of a 3×2 display window; the rest is the fill. - let part = place(FlatSamples::F16(vec![half(1.0), half(2.0)]), (2, 1), (1, 1), (3, 2), 6, 9.0).unwrap(); - assert_eq!(part, [9.0, 9.0, 9.0, 9.0, 1.0, 2.0]); - // Partly outside the display window: clipped, never out of bounds. - let off = place(FlatSamples::U32(vec![7, 8]), (2, 1), (2, -1), (3, 2), 6, 0.0).unwrap(); - assert_eq!(off, [0.0; 6]); - let edge = place(FlatSamples::U32(vec![7, 8]), (2, 1), (2, 0), (3, 2), 6, 0.0).unwrap(); - assert_eq!(edge, [0.0, 0.0, 7.0, 0.0, 0.0, 0.0]); - assert!(place(FlatSamples::F32(vec![1.0; 5]), (3, 2), (0, 0), (3, 2), 6, 0.0).is_none(), "too few samples"); + fn channels_are_placed_in_the_display_window() { + use exr::prelude::*; + let half = |x: f32| f16::from_f32(x); + let part = |pos: (i32, i32), size: (usize, usize), list: Vec>| { + let attrs = LayerAttributes { layer_position: Vec2(pos.0, pos.1), ..Default::default() }; + Layer::new(size, attrs, Encoding::FAST_LOSSLESS, AnyChannels::sort(list.into())) + }; + let display = IntegerBounds::from_dimensions((3, 2)); + // A 2×1 data window at (1, 1). + let inside = file( + vec![part( + (1, 1), + (2, 1), + vec![AnyChannel::new("G", FlatSamples::F16(vec![half(1.0), half(2.0)])), AnyChannel::new("Z", FlatSamples::U32(vec![7, 8]))], + )], + display, + ); + let aux = read_exr_channels(&inside).unwrap(); + assert_eq!(aux.get("G").unwrap(), [0.0, 0.0, 0.0, 0.0, 1.0, 2.0]); + let bg = BACKGROUND_DEPTH; + assert_eq!(aux.get("Z").unwrap(), [bg, bg, bg, bg, 7.0, 8.0]); + // A 2×2 data window at (2, -1): only its bottom-left sample lands at (2, 0). + let off = file(vec![part((2, -1), (2, 2), vec![AnyChannel::new("G", FlatSamples::F32(vec![1.0, 2.0, 3.0, 4.0]))])], display); + assert_eq!(read_exr_channels(&off).unwrap().get("G").unwrap(), [0.0, 0.0, 3.0, 0.0, 0.0, 0.0]); + // Entirely outside: all fill. + let away = file(vec![part((-5, 0), (2, 2), vec![AnyChannel::new("G", FlatSamples::F32(vec![1.0; 4]))])], display); + assert_eq!(read_exr_channels(&away).unwrap().get("G").unwrap(), [0.0; 6]); + } + + /// #474: concurrent requests for a file that isn't cached decode it once; the others wait + /// for that decode and share its planes. + #[test] + fn concurrent_requests_decode_a_file_once() { + let bytes: Arc<[u8]> = flat(&["R", "G", "B", "Z"], (64, 64), 0.5).into(); + let cache = ChannelCache::new(CACHE_BUDGET); + let reads = AtomicU64::new(0); + let barrier = std::sync::Barrier::new(8); + let got: Vec> = std::thread::scope(|s| { + let jobs: Vec<_> = (0..8) + .map(|_| { + s.spawn(|| { + barrier.wait(); + cache + .get("/474-concurrent.exr", Use::Channels, || { + reads.fetch_add(1, Ordering::Relaxed); + // Long enough for the others to arrive while this one decodes. + std::thread::sleep(std::time::Duration::from_millis(50)); + Some(bytes.clone()) + }) + .unwrap() + }) + }) + .collect(); + jobs.into_iter().map(|j| j.join().unwrap()).collect() + }); + assert_eq!(cache.decodes(), 1, "one decode"); + assert_eq!(reads.load(Ordering::Relaxed), 1, "the file is read once"); + assert!(got.iter().all(|d| Arc::ptr_eq(d, &got[0])), "every caller has the same planes"); + assert_eq!(got[0].aux.get("Z").and_then(|z| z.first()).copied(), Some(0.5)); + } + + /// #474: the cache is bounded by the bytes of its planes, least recently used out first; the + /// newest file stays even when it alone is over the budget, and unreadable files are cached + /// (as such) without counting bytes. + #[test] + fn cache_evicts_least_recently_used_by_bytes() { + // 4 float planes of 32×32: 16 KiB of samples (plus a few bytes of names) per file. + let bytes: Arc<[u8]> = flat(&["R", "G", "B", "A"], (32, 32), 0.25).into(); + let one = 4 * 32 * 32 * 4 + 4; + let cache = ChannelCache::new(2 * one); + let get = |p: &str| cache.get(p, Use::Channels, || Some(bytes.clone())).unwrap(); + assert_eq!(get("/a.exr").bytes(), one); + get("/b.exr"); + get("/a.exr"); // a is now more recent than b + get("/c.exr"); + assert_eq!(cache.cached(), ["/a.exr", "/c.exr"], "b was least recently used"); + assert_eq!(cache.decodes(), 3); + get("/a.exr"); + assert_eq!(cache.decodes(), 3, "a hit"); + // A file over the budget on its own is still kept while it is the newest. + let small = ChannelCache::new(one / 2); + assert!(small.get("/big.exr", Use::Channels, || Some(bytes.clone())).is_some()); + assert_eq!(small.cached(), ["/big.exr"]); + small.get("/big2.exr", Use::Channels, || Some(bytes.clone())); + assert_eq!(small.cached(), ["/big2.exr"]); + // An unreadable file is remembered (not read again) without bytes, and forgotten on request. + assert!(cache.get("/broken.exr", Use::Channels, || Some(Arc::from(&b"not an exr"[..]))).is_none()); + assert!(cache.get("/broken.exr", Use::Channels, || panic!("not read again")).is_none()); + cache.forget("/broken.exr"); + assert!(!cache.cached().contains(&"/broken.exr".to_string())); + // At most CACHE_FILES files, however small. + for i in 0..CACHE_FILES + 10 { + cache.get(&format!("/none{i}.exr"), Use::Channels, || None); + } + assert!(cache.cached().len() <= CACHE_FILES); + } + + /// #474: a file counts as used when its decode finishes: one asked for first but decoded + /// after another is the newer of the two, so concurrent frames don't evict each other's + /// files before their effects read them. + #[test] + fn a_file_is_used_as_of_its_decode() { + let bytes: Arc<[u8]> = flat(&["R", "G", "B", "A"], (32, 32), 0.25).into(); + let one = 4 * 32 * 32 * 4 + 4; + let cache = ChannelCache::new(2 * one); + cache.get("/first.exr", Use::Channels, || { + // Another frame's file is asked for and decoded while this one decodes. + cache.get("/second.exr", Use::Channels, || Some(bytes.clone())); + Some(bytes.clone()) + }); + cache.get("/third.exr", Use::Channels, || Some(bytes.clone())); + assert_eq!(cache.cached(), ["/first.exr", "/third.exr"], "the file decoded first went first"); + } + + /// #474: frames rendered at once (each asks for its picture, then its effects for the + /// channels while other frames decode) decode each file once, though the budget holds only + /// one: a picture's file is kept for its effects, and files in use are never dropped. + #[test] + fn concurrent_frames_decode_each_file_once() { + let bytes: Arc<[u8]> = flat(&["R", "G", "B", "Z"], (64, 64), 0.5).into(); + let cache = ChannelCache::new(4 * 64 * 64 * 4 + 4); + let (next, reads, frames) = (std::sync::atomic::AtomicUsize::new(0), AtomicU64::new(0), 24); + let read = || { + reads.fetch_add(1, Ordering::Relaxed); + Some(bytes.clone()) + }; + std::thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= frames { + break; + } + let path = format!("/474-frames/{i:04}.exr"); + drop(cache.get(&path, Use::Picture, read).unwrap()); + std::thread::sleep(std::time::Duration::from_millis(3)); + let aux = cache.get(&path, Use::Channels, read).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(2)); + assert_eq!(aux.aux.get("Z").and_then(|z| z.first()).copied(), Some(0.5)); + } + }); + } + }); + assert_eq!(cache.decodes(), frames as u64, "one decode per frame"); + assert_eq!(reads.load(Ordering::Relaxed), frames as u64); + } + + /// #474: a decode that panics doesn't leave its file "decoding" in the cache (never dropped, + /// its planes counted): the entry goes, and the next request decodes the file. + #[test] + fn a_decode_that_panics_is_not_left_in_the_cache() { + let bytes: Arc<[u8]> = flat(&["R"], (8, 8), 1.0).into(); + let cache = ChannelCache::new(CACHE_BUDGET); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cache.get("/474-panics.exr", Use::Channels, || panic!("the read failed")))); + assert!(r.is_err()); + assert!(cache.cached().is_empty()); + assert!(cache.get("/474-panics.exr", Use::Channels, || Some(bytes.clone())).is_some()); + assert_eq!(cache.cached(), ["/474-panics.exr"]); + } + + /// #474: the picture of a multi-layer file whose effects read its channels comes from the + /// cache, and from the picture's own channels when the cache has none for the file (a read + /// that failed, or a broken part the picture doesn't use). + #[test] + fn a_shared_picture_without_cached_channels_is_still_decoded() { + use effectcraft_project::Footage; + use effectcraft_render::FloatCurve; + let bytes: Arc<[u8]> = flat(&["Image.R", "Image.G", "Image.B", "depth.Z"], (4, 2), 0.5).into(); + let path = "/474-shared-fallback.exr"; + assert!(cache().get(path, Use::Channels, || None).is_none(), "a read that failed"); + let op = AlphaOp::of(&Footage::default(), FloatCurve::Linear); + let img = layered_picture(path, bytes, &ReadFile::new(path, effectcraft_render::reads::FileStamp::Virtual), op, true).unwrap(); + assert_eq!(img.get(1, 1), [0.5, 0.5, 0.5, 1.0]); + } + + /// #474: a header asking for more plane memory than one decode may allocate (16384² display + /// window, 40 channels: 43 GB) is refused with a reason before anything is allocated. + #[test] + fn a_header_asking_for_too_much_memory_is_refused() { + use exr::prelude::*; + let list: Vec> = (0..40).map(|i| AnyChannel::new(format!("pass{i:02}.Y").as_str(), FlatSamples::F32(vec![0.5]))).collect(); + let layer = Layer::new((1, 1), LayerAttributes::default(), Encoding::FAST_LOSSLESS, AnyChannels::sort(list.into())); + let bytes = file(vec![layer], IntegerBounds::new((0, 0), (16384, 16384))); + match decode(&bytes, &|_| true) { + Err(Refused::TooLarge(why)) => assert!(why.contains("16384×16384") && why.contains("GB"), "{why}"), + Err(Refused::Unreadable) => panic!("readable"), + Ok(_) => panic!("refused"), + } + assert!(read_exr_channels(&bytes).is_none()); + assert!(cached("/474-too-large.exr", || Some(bytes.as_slice().into())).is_none()); + } + + /// #474: a file forgotten (changed on disk) while it decodes isn't cached under its path when + /// that decode finishes. + #[test] + fn a_file_forgotten_while_it_decodes_is_not_cached() { + let bytes: Arc<[u8]> = flat(&["R"], (8, 8), 1.0).into(); + let cache = ChannelCache::new(CACHE_BUDGET); + let d = cache.get("/changed.exr", Use::Channels, || { + cache.forget("/changed.exr"); + Some(bytes.clone()) + }); + assert!(d.is_some()); + assert!(cache.cached().is_empty()); } /// #295: a multi-layer EXR whose colour is only in named layers (`diffuse.R`, as Blender and /// Nuke write them) failed to import ("does not contain non-deep rgb channels"); it now /// shows its colour layer and keeps every channel for EXtractoR. - /// #474: the picture and EXtractoR / Cryptomatte share one decode of a multi-layer file: - /// after the frame is decoded, the aux channels come from the cache without reading the file. + /// #474: once an effect has read a footage item's channels, the picture of each later frame + /// shares one decode with them: the frame's decode is cached and the channels come from it + /// without reading the file again. #[test] fn picture_and_aux_channels_share_one_decode() { use exr::prelude::*; let (w, h) = (2usize, 2usize); - let ch = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h])); - let channels = AnyChannels::sort(vec![ch("Image.R", 0.5), ch("Image.G", 0.5), ch("Image.B", 0.5), ch("GlossDir.R", 0.25)].into()); - let image = Image::from_layer(Layer::new((w, h), LayerAttributes::default(), Encoding::FAST_LOSSLESS, channels)); - let mut bytes = std::io::Cursor::new(Vec::new()); - image.write().to_buffered(&mut bytes).unwrap(); - let b: Arc<[u8]> = bytes.into_inner().into(); - let path = "/474-shared-decode.exr"; + let frame = |v: f32| -> Arc<[u8]> { + let ch = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h])); + let channels = AnyChannels::sort(vec![ch("Image.R", 0.5), ch("Image.G", 0.5), ch("Image.B", 0.5), ch("GlossDir.R", v)].into()); + let image = Image::from_layer(Layer::new((w, h), LayerAttributes::default(), Encoding::FAST_LOSSLESS, channels)); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut bytes).unwrap(); + bytes.into_inner().into() + }; + let paths = ["/474-shared-decode_0001.exr", "/474-shared-decode_0002.exr"]; let pool = crate::MediaPool::new(); - pool.add_bytes(path, b.clone()); - let f = crate::probe_bytes(path, b).unwrap(); + pool.add_bytes(paths[0], frame(0.25)); + pool.add_bytes(paths[1], frame(0.75)); + let mut f = crate::probe_bytes(paths[0], frame(0.25)).unwrap(); + f.kind = effectcraft_project::FootageKind::Sequence; + f.sequence = paths.iter().map(|p| p.to_string()).collect(); + let t1 = f.frame_rate.tick_of(1); + use effectcraft_render::FootageSource; + // The first frame: the picture, then an effect reads the channels. pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); - let aux = cached(path, || panic!("the frame's decode is reused, the file is not read again")).unwrap(); + let aux = pool.aux(effectcraft_project::ItemId(1), &f, effectcraft_time::Tick::ZERO).unwrap(); assert_eq!(aux.get("GlossDir.R").and_then(|p| p.first()).copied(), Some(0.25)); + // The next frame's picture decodes the file into the cache, so its channels are not read. + let px = pool.frame_at(&f, t1).unwrap().get(0, 0); + let aux = cached(paths[1], || panic!("the frame's decode is reused, the file is not read again")).unwrap(); + assert_eq!(aux.get("GlossDir.R").and_then(|p| p.first()).copied(), Some(0.75)); + assert_eq!(px, pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap().get(0, 0), "the same picture"); + } + + /// An EXR file with an unnamed RGB layer and a named `GlossDir.R` of `v` (2×2). + fn rgb_and_gloss(v: f32) -> Arc<[u8]> { + flat(&["R", "G", "B", "GlossDir.R"], (2, 2), v).into() + } + + /// #474: footage the project says effects read the channels of + /// ([`FootageSource::set_aux_footage`]) costs one decode from its first frame on: a single + /// still with EXtractoR decodes once. Without it the first frame decodes twice (the picture, + /// then the channels once `aux()` asks). + #[test] + fn given_aux_footage_decodes_once_from_the_first_frame() { + use effectcraft_render::FootageSource; + let (given, learned) = ("/474-given-still.exr", "/474-learned-still.exr"); + let pool = crate::MediaPool::new(); + let mut f = std::collections::HashMap::new(); + for p in [given, learned] { + pool.add_bytes(p, rgb_and_gloss(0.25)); + f.insert(p, crate::probe_bytes(p, rgb_and_gloss(0.25)).unwrap()); + } + pool.set_aux_footage(&[given.to_string()]); + take_decodes(); + let t = effectcraft_time::Tick::ZERO; + pool.frame_at(&f[given], t).unwrap(); + let aux = pool.aux(effectcraft_project::ItemId(1), &f[given], t).unwrap(); + assert_eq!(aux.get("GlossDir.R").and_then(|p| p.first()).copied(), Some(0.25)); + assert_eq!(take_decodes(), [0, 1], "the picture and the channels share one decode"); + // Learned only at the first `aux()`: the picture was decoded on its own before. + pool.frame_at(&f[learned], t).unwrap(); + pool.aux(effectcraft_project::ItemId(2), &f[learned], t).unwrap(); + assert_eq!(take_decodes(), [1, 1]); + } + + /// #474: once the project no longer names footage (its effect removed), later frames decode + /// only their picture again; what `aux()` learned is dropped with each new set too. + #[test] + fn a_new_aux_footage_set_returns_to_picture_only() { + use effectcraft_render::FootageSource; + let paths: Vec = (1..=4).map(|i| format!("/474-unset_{i:04}.exr")).collect(); + let pool = crate::MediaPool::new(); + for p in &paths { + pool.add_bytes(p, rgb_and_gloss(0.5)); + } + let mut f = crate::probe_bytes(&paths[0], rgb_and_gloss(0.5)).unwrap(); + f.kind = effectcraft_project::FootageKind::Sequence; + f.sequence = paths.clone(); + let at = |i: i64| f.frame_rate.tick_of(i); + // (counted on this thread, so other tests sharing the channel cache don't change them) + let frame = |i: i64| { + take_decodes(); + pool.frame_at(&f, at(i)).unwrap(); + take_decodes() + }; + pool.set_aux_footage(std::slice::from_ref(&f.path)); + assert_eq!(frame(0), [0, 1], "given: the picture comes from the channel decode"); + pool.set_aux_footage(&[]); + assert!(!cache().lock().held.iter().any(|(p, _)| *p == paths[0]), "no longer kept once no effect reads it"); + assert_eq!(frame(1), [1, 0], "no longer given: the picture alone"); + // Learned by `aux()`, then a new set without it: picture only again. + pool.aux(effectcraft_project::ItemId(1), &f, at(1)).unwrap(); + assert_eq!(frame(2), [0, 1], "learned"); + pool.set_aux_footage(&[]); + assert_eq!(frame(3), [1, 0], "a new set drops what was learned"); + } + + /// #474: the picture made of the cached planes of a file with exact R, G, B channels is the + /// `image` crate's, bit for bit (first such part, alpha or opaque, data window placed with 0 + /// around it), in every alpha interpretation and float curve. + #[test] + fn picture_from_planes_is_the_image_crates() { + use effectcraft_project::{AlphaMode, Footage}; + use effectcraft_render::FloatCurve; + use exr::prelude::*; + let half = |n: &str, v: f32, len: usize| AnyChannel::new(n, FlatSamples::F16((0..len).map(|i| f16::from_f32(v + i as f32 * 0.37 - 1.0)).collect())); + let float = |n: &str, v: f32, len: usize| AnyChannel::new(n, FlatSamples::F32((0..len).map(|i| ((i * 7) % 11) as f32 * v).collect())); + let part = |name: Option<&str>, pos: (i32, i32), size: (usize, usize), list: Vec>| { + let mut attrs = name.map_or_else(LayerAttributes::default, LayerAttributes::named); + attrs.layer_position = Vec2(pos.0, pos.1); + Layer::new(size, attrs, Encoding::SMALL_LOSSLESS, AnyChannels::sort(list.into())) + }; + let display = IntegerBounds::new((1, -1), (5, 4)); + let n = 20; + let files = [ + file( + vec![part(None, (1, -1), (5, 4), vec![half("R", 0.1, n), half("G", 0.2, n), half("B", 0.3, n), float("A", 0.1, n), float("Z", 2.0, n)])], + display, + ), + file(vec![part(None, (0, 0), (3, 2), vec![float("R", 0.4, 6), float("G", 0.5, 6), float("B", 0.6, 6), half("Image.R", 0.1, 6)])], display), + file( + vec![ + part(Some("diffuse"), (1, -1), (5, 4), vec![half("R", 0.1, n), half("G", 0.2, n), half("B", 0.3, n)]), + part(Some("beauty"), (2, 0), (2, 2), vec![half("R", 0.4, 4), half("G", 0.5, 4), half("B", 0.6, 4), half("A", 0.5, 4)]), + ], + display, + ), + ]; + let bits = |i: &effectcraft_raster::Image| i.data.iter().flat_map(|p| p.map(f32::to_bits)).collect::>(); + for (k, bytes) in files.iter().enumerate() { + let path = format!("/474-planes-{k}.exr"); + let d = cache().get(&path, Use::Channels, || Some(bytes.as_slice().into())).unwrap(); + assert!(matches!(d.rgb, Rgb::Planes(..)), "file {k}: {:?}", d.rgb); + let img = crate::probe::load_oriented(bytes, Some(image::ImageFormat::OpenExr)).unwrap(); + for alpha in [AlphaMode::Straight, AlphaMode::Premultiplied, AlphaMode::Ignore] { + for curve in [FloatCurve::Srgb, FloatCurve::Linear, FloatCurve::Gamma24] { + let op = AlphaOp::of(&Footage { alpha, premul_color: [0.2, 0.4, 0.6], ..Default::default() }, curve); + let want = crate::convert::dynamic_to_image(&img, op); + let got = cached_picture(&path, bytes.as_slice().into(), &ReadFile::new(path.as_str(), effectcraft_render::reads::FileStamp::Virtual), op) + .unwrap(); + assert_eq!((got.width, got.height), (want.width, want.height)); + assert_eq!(bits(&got), bits(&want), "file {k} {alpha:?} {curve:?}"); + } + } + } } /// #2141: one pixel of data in a 60000² display window is refused, not allocated per channel. diff --git a/crates/media/src/layered.rs b/crates/media/src/layered.rs index b259c8b7f..64ade9394 100644 --- a/crates/media/src/layered.rs +++ b/crates/media/src/layered.rs @@ -14,19 +14,20 @@ fn is_svg(path: &str, bytes: &[u8]) -> bool { } /// The vector document of an SVG / PDF / AI / EPS file (`None` for other formats): page -/// `page` of a PDF, restricted to the footage's layer when it names one. +/// `page` of a PDF framed as `framing` says, restricted to the footage's layer when it names one. pub fn vector_doc( path: &str, bytes: &[u8], layer: Option<&effectcraft_project::SourceLayer>, page: u32, + framing: effectcraft_pdf::Framing, ) -> Option> { if is_svg(path, bytes) { return Some(effectcraft_svg::parse(bytes).map_err(|e| format!("{path}: {e}"))); } effectcraft_pdf::sniff(bytes)?; Some( - effectcraft_pdf::parse_page(bytes, page as usize) + effectcraft_pdf::parse_page_framed(bytes, page as usize, framing) .map(|d| match layer { Some(l) => effectcraft_pdf::layer_doc_with_sizes(&d, l.index as usize, l.layer_size).0, None => d, @@ -111,14 +112,14 @@ pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) - return Ok(Some(straight_to_image(px.width, px.height, &px.data, op))); } if is_svg(path, bytes) || is_pdf_like(path, bytes) { - let doc = vector_doc(path, bytes, footage.layer.as_ref(), footage.page).unwrap_or(Err(String::new())).map_err(MediaError::Decode)?; - let (w, h) = doc.pixel_size(); + let doc = footage_doc(path, bytes, footage).unwrap_or(Err(String::new())).map_err(MediaError::Decode)?; + let ((w, h), to_image) = fit(&doc, footage, 1.0); // A declared size up to 30000² would be a 14 GB allocation that aborts the app (#2136): // past what Continuously Rasterize can draw, the footage reports an error instead. if u64::from(w) * u64::from(h) > u64::from(MAX_VECTOR_SIDE) * u64::from(MAX_VECTOR_SIDE) { return Err(MediaError::Decode(format!("{path}: {w}×{h} pixels is larger than vector footage can be drawn ({MAX_VECTOR_SIDE}×{MAX_VECTOR_SIDE})"))); } - let img = effectcraft_svg::rasterize(&doc, w, h, 1.0); + let img = effectcraft_svg::rasterize_with(&doc, w, h, to_image); // The rasteriser produces premultiplied pixels already. let _ = op; return Ok(Some(img)); @@ -129,12 +130,29 @@ pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) - /// The largest side vector footage is drawn at, decoded or continuously rasterised. const MAX_VECTOR_SIDE: u32 = 16384; -/// A vector file rasterised at `scale` × its pixel size (Continuously Rasterize). -pub(crate) fn rasterize_vector(path: &str, bytes: &[u8], layer: Option<&effectcraft_project::SourceLayer>, page: u32, scale: f64) -> Option { - let doc = vector_doc(path, bytes, layer, page)?.ok()?; - let (w, h) = doc.pixel_size(); - let (sw, sh) = (((w as f64 * scale).ceil() as u32).clamp(1, MAX_VECTOR_SIDE), ((h as f64 * scale).ceil() as u32).clamp(1, MAX_VECTOR_SIDE)); - Some(effectcraft_svg::rasterize(&doc, sw, sh, scale)) +/// The vector footage `footage` (of the file `path` with these `bytes`) rasterised at `scale` × +/// its size as [`effectcraft_render::vector_fit`] draws it (Continuously Rasterize). +pub(crate) fn rasterize_vector(path: &str, bytes: &[u8], footage: &Footage, scale: f64) -> Option { + let doc = footage_doc(path, bytes, footage)?.ok()?; + let ((sw, sh), to_image) = fit(&doc, footage, scale); + Some(effectcraft_svg::rasterize_with(&doc, sw.clamp(1, MAX_VECTOR_SIDE), sh.clamp(1, MAX_VECTOR_SIDE), to_image)) +} + +/// The page framing of vector footage: as After Effects places it for footage from an After +/// Effects project ([`Footage::placed_page`]), as a PDF viewer shows it otherwise. +fn framing(footage: &Footage) -> effectcraft_pdf::Framing { + if footage.placed_page { effectcraft_pdf::Framing::Placed } else { effectcraft_pdf::Framing::Viewer } +} + +/// [`vector_doc`] of `footage`'s page, layer and framing. +fn footage_doc(path: &str, bytes: &[u8], footage: &Footage) -> Option> { + vector_doc(path, bytes, footage.layer.as_ref(), footage.page, framing(footage)) +} + +/// The image size and document → image mapping of `doc` drawn for `footage` at `scale`. +fn fit(doc: &effectcraft_svg::Doc, footage: &Footage, scale: f64) -> ((u32, u32), effectcraft_svg::Affine) { + let (size, [sx, sy]) = effectcraft_render::vector_fit(footage, [doc.width, doc.height], doc.pixel_size(), scale); + (size, effectcraft_svg::Affine::scale_non_uniform(sx, sy)) } #[cfg(test)] @@ -154,4 +172,65 @@ mod tests { let img = decode("small.svg", small, &footage, AlphaOp::new(footage.alpha, footage.premul_color)).unwrap().unwrap(); assert_eq!((img.width, img.height), (40, 20)); } + + /// A 200 × 100 pt page: red left half, blue right half. + fn halves_pdf() -> Vec { + effectcraft_pdf::write::pdf( + &[ + (1, "<< /Type /Catalog /Pages 2 0 R >>".into(), None), + (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), None), + (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 4 0 R >>".into(), None), + (4, "<< >>".into(), Some(b"1 0 0 rg 0 0 100 100 re f 0 0 1 rg 100 0 100 100 re f".to_vec())), + ], + 1, + ) + } + + /// An opaque red pixel. + fn is_red(p: [f32; 4]) -> bool { + p[3] > 0.99 && p[0] > 0.9 && p[2] < 0.1 + } + + /// An opaque blue pixel. + fn is_blue(p: [f32; 4]) -> bool { + p[3] > 0.99 && p[2] > 0.9 && p[0] < 0.1 + } + + /// #3099: an After Effects project keeps the size After Effects measured for a placed .ai or + /// PDF, which can differ from this reader's page size. A placed page fills that size (the + /// layer's anchor and masks are measured against it), decoded and continuously rasterised; + /// other footage is drawn at the page's own size as before, whatever size it says. + #[test] + fn placed_vector_footage_fills_the_footage_size() { + let pdf = halves_pdf(); + let mut footage = probe("art.ai", &pdf).unwrap().unwrap(); + assert_eq!((footage.width, footage.height), (200, 100)); + assert!(!footage.placed_page); + let op = AlphaOp::new(footage.alpha, footage.premul_color); + let own = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); + assert_eq!((own.width, own.height), (200, 100)); + assert!(is_red(own.get(50, 50)) && is_blue(own.get(150, 50))); + + (footage.width, footage.height) = (100, 80); + let unplaced = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); + assert!(unplaced == own, "not placed: drawn as before"); + assert_eq!(rasterize_vector("art.ai", &pdf, &footage, 0.5).map(|i| (i.width, i.height)), Some((100, 50))); + + footage.placed_page = true; + let img = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); + assert_eq!((img.width, img.height), (100, 80)); + for (x, y) in [(25, 3), (25, 76)] { + assert!(is_red(img.get(x, y)), "red at ({x}, {y}): {:?}", img.get(x, y)); + } + for (x, y) in [(75, 3), (75, 76)] { + assert!(is_blue(img.get(x, y)), "blue at ({x}, {y}): {:?}", img.get(x, y)); + } + + let sharp = rasterize_vector("art.ai", &pdf, &footage, 2.0).unwrap(); + assert_eq!((sharp.width, sharp.height), (200, 160)); + assert!(is_red(sharp.get(50, 155)) && is_blue(sharp.get(150, 155))); + // Placed at the page's own size: 1:1. + (footage.width, footage.height) = (200, 100); + assert!(decode("art.ai", &pdf, &footage, op).unwrap().unwrap() == own, "placed at its own size: 1:1"); + } } diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index e985985b7..0b509c45f 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -25,10 +25,13 @@ mod layered; pub use layered::vector_doc; mod pool; mod probe; +mod reads; mod stream; mod wav_markers; mod webp_anim; +/// Video decoder counters (time in decoders, samples decoded, seeks, cache hits), for benchmarks. +pub use filmcraft_codecs::{GopStats, gop_stats}; pub use pool::{DEFAULT_BUDGET, MediaPool, PoolStats}; pub use probe::{DEFAULT_SEQUENCE_RATE, probe, probe_bytes, probe_model}; @@ -83,7 +86,15 @@ pub fn is_importable(path: &std::path::Path) -> bool { /// A whole file's bytes, refusing anything that isn't a regular file: a project can name /// `/dev/zero` or a FIFO as footage, and reading those never ends (#2134). pub(crate) fn read_regular_file(path: &std::path::Path) -> std::io::Result> { + read_regular_file_stamped(path).map(|(bytes, _)| bytes) +} + +/// [`read_regular_file`] with the file's identity, from the metadata of the open file (no +/// second look at the path). +pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Result<(Vec, effectcraft_render::reads::FileStamp)> { use std::io::Read; + #[cfg(test)] + count_open(path); let mut file = std::fs::File::open(path)?; let meta = file.metadata()?; if !meta.is_file() { @@ -93,7 +104,22 @@ pub(crate) fn read_regular_file(path: &std::path::Path) -> std::io::Result> = std::sync::Mutex::new(Vec::new()); + +/// Count an open of a file (tests: which files a render touched on disk). +#[cfg(test)] +pub(crate) fn count_open(path: &std::path::Path) { + OPENS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(path.to_path_buf()); +} + +/// How many times files under `dir` were opened so far (tests). +#[cfg(test)] +pub(crate) fn opens_under(dir: &std::path::Path) -> usize { + OPENS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().filter(|p| p.starts_with(dir)).count() } pub(crate) fn ext_of(path: &std::path::Path) -> String { diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 655ca4ed8..e35ff37fc 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -6,14 +6,17 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock}; use effectcraft_project::{AlphaMode, Footage, FootageKind, ItemId}; use effectcraft_raster::{Image, Px}; +use effectcraft_render::disk_cache::Frame8; +use effectcraft_render::reads::{FileStamp, ReadFile, ReadFiles, ReadLog}; use effectcraft_render::{FloatCurve, FootageSource}; use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick}; use filmcraft_media::{FrameRequest, SharedSource}; use image::metadata::Orientation; -use crate::convert::{AlphaOp, dynamic_to_image, frame_to_image_in, frame_to_image_scaled, turned}; +use crate::convert::{AlphaOp, dynamic_to_image, frame_to_image_in, frame_to_image_scaled, frame_to_rgba8, turned}; use crate::downmix::Order; use crate::gif_anim::{self, Anim}; +use crate::reads; use crate::{MediaError, Result}; /// Default frame-cache budget: 1 GiB of decoded frames. @@ -40,19 +43,41 @@ fn colour_bars(w: u32, h: u32) -> Image { struct Key { path: Arc, frame: i64, - /// The alpha interpretation (bits 0–1) and how float values are encoded (bits 2–3: sRGB, - /// as stored, a 2.4 power curve): they change the decoded pixels. + /// The alpha interpretation (bits 0–1), how float values are encoded (bits 2–3: sRGB, as + /// stored, a 2.4 power curve) and a placed PDF / Illustrator page's framing (bit 4, + /// [`Footage::placed_page`]): they change the decoded pixels. interp: u8, matte: [u32; 3], /// A movie frame made at this size for a reduced-resolution render ((0, 0): as decoded). size: (u32, u32), /// A still at a reduced `size`: the footage's nominal size, which decides whether it is - /// resampled (see `Inner::still_at_size`); (0, 0) otherwise. + /// resampled (see `Inner::still_at_size`); also at its own size for a placed PDF / + /// Illustrator page, which is drawn to fill it ([`Footage::placed_page`]); (0, 0) otherwise. nominal: (u32, u32), + /// Kept as 8-bit levels ([`FootageSource::frame8`]), not float. + q8: bool, +} + +/// A cached frame's pixels: float, or the 8-bit levels an 8 bpc render quantises it to. +#[derive(Clone)] +enum Pixels { + F32(Arc), + Q8(Arc), +} + +impl Pixels { + fn bytes(&self) -> usize { + match self { + Pixels::F32(img) => img.data.len() * std::mem::size_of::(), + Pixels::Q8(f) => f.rgba.len(), + } + } } struct Entry { - img: Arc, + img: Pixels, + /// The files the frame was decoded from (see [`crate::reads`]). + files: Arc, stamp: u64, bytes: usize, } @@ -106,18 +131,20 @@ struct Lru { } impl Lru { - fn get(&mut self, k: &Key) -> Option> { + /// The cached frame and its read files for `k`, marking the entry as most recently used. + fn get(&mut self, k: &Key) -> Option<(Pixels, Arc)> { let e = self.map.get_mut(k)?; self.order.remove(&e.stamp); self.clock += 1; e.stamp = self.clock; self.order.insert(e.stamp, k.clone()); - Some(e.img.clone()) + Some((e.img.clone(), e.files.clone())) } - fn insert(&mut self, k: Key, img: Arc, budget: usize) { - let bytes = img.data.len() * std::mem::size_of::() + 64; + /// Stores a frame with its read files under `k` and evicts the least recently used entries until the cache fits `budget` bytes. + fn insert(&mut self, k: Key, img: Pixels, files: Arc, budget: usize) { + let bytes = img.bytes() + 64; self.clock += 1; - if let Some(old) = self.map.insert(k.clone(), Entry { img, stamp: self.clock, bytes }) { + if let Some(old) = self.map.insert(k.clone(), Entry { img, files, stamp: self.clock, bytes }) { self.order.remove(&old.stamp); self.bytes -= old.bytes; } @@ -137,8 +164,10 @@ impl Lru { let Some((_, k)) = self.order.pop_first() else { break }; if let Some(e) = self.map.remove(&k) { self.bytes -= e.bytes; + // ponytail: float buffers only; add 8-bit spares if their allocation shows up in a profile if self.spare.len() < MAX_SPARE - && let Ok(img) = Arc::try_unwrap(e.img) + && let Pixels::F32(img) = e.img + && let Ok(img) = Arc::try_unwrap(img) { self.spare.push(img.data); } @@ -177,11 +206,14 @@ struct CacheState { inflight: HashSet, /// Last frame index requested per movie (sequential-playback detection). last: HashMap, i64>, + /// Movies whose frames can't be kept as 8-bit levels (more bits, or shown turned). + wide: HashSet>, } /// A movie/audio source by path ([`Opened`]), opened by the first caller while the others wait -/// for it (`None`: failed to open; not retried until `forget`). -type SourceSlot = Arc>>; +/// for it (`None`: failed to open; not retried until `forget`), with the file's identity as +/// opened. +type SourceSlot = Arc, ReadFile)>>; /// An opened movie/audio source, the turn its picture is shown with and the order its decoded /// audio channels arrive in. @@ -211,7 +243,7 @@ fn channel_order(src: &SharedSource, header: Option<&[u8]>, file: Option<&dyn fi } /// An animated GIF by path, as [`SourceSlot`] (the error message when it failed to load). -type GifSlot = Arc, String>>>; +type GifSlot = Arc, String>, ReadFile)>>; struct Inner { /// Opened movie/audio sources by path. @@ -220,8 +252,9 @@ struct Inner { opened: AtomicU64, /// In-memory files registered with `add_bytes` (web builds, tests). files: Mutex>>, - /// Parsed 3D models by path (`None`: failed to load; not retried until `forget`). - models: Mutex>>>, + /// Parsed 3D models by path (`None`: failed to load; not retried until `forget`), with the + /// files read for them (the model's and the resources it names). + models: Mutex>, Arc)>>, /// Decoded animated GIFs and WebPs by path, loaded by the first caller while the others wait (an /// `Err` is not retried until `forget`). gifs: Mutex, GifSlot>>, @@ -245,6 +278,25 @@ struct Inner { /// Movies that failed to open or decode (path to a readable reason; see /// [`FootageSource::problem`]). The first failure of a file is logged, later ones are not. problems: Mutex, String>>, + /// OpenEXR footage (by path) whose channels effects read (EXtractoR, Cryptomatte, the 3D + /// Channel effects): its pictures come from the same cached decode (#474). + aux_footage: Mutex, +} + +/// Footage whose channels effects read ([`Inner::aux_footage`]), by [`Footage::path`]. +#[derive(Default)] +struct AuxFootage { + /// What the project says ([`FootageSource::set_aux_footage`]). + given: HashSet, + /// Read through [`FootageSource::aux`] but not given (a reader the project doesn't name, or + /// a source that never gives a set). Cleared with each new set. + learned: HashSet, +} + +impl AuxFootage { + fn contains(&self, path: &str) -> bool { + self.given.contains(path) || self.learned.contains(path) + } } /// Decodes footage for the renderer: stills, image sequences and movies (FilmCraft codecs), plus @@ -315,6 +367,7 @@ impl MediaPool { conforming: Mutex::default(), conform_failed: Mutex::default(), problems: Mutex::default(), + aux_footage: Mutex::default(), }), } } @@ -377,6 +430,7 @@ impl MediaPool { c.lru.remove(&k); } c.last.remove(path); + c.wide.remove(path); drop(c); crate::exr_channels::forget(path); } @@ -392,6 +446,21 @@ impl MediaPool { Inner::frame_at(&self.inner, footage, t, true, None, FloatCurve::Srgb) } + /// [`FootageSource::frame8`]: `None` (the renderer then asks for the float frame) for + /// anything but an 8-bit movie frame shown as decoded, and on errors. + fn frame8_of(&self, footage: &Footage, t: Tick, float: FloatCurve) -> Option> { + if footage.missing || footage.kind != FootageKind::Video || gif_anim::is_animated(footage) { + return None; + } + if lock(&self.inner.cache).wide.contains(footage.path.as_str()) { + return None; + } + match Inner::frame_px(&self.inner, footage, t, true, None, float, true) { + Ok(Pixels::Q8(f)) => Some(f), + _ => None, + } + } + /// [`FootageSource::frame`] / [`FootageSource::frame_at_size`]: `None` (logged) on errors. fn frame_sized(&self, _item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { if footage.missing { @@ -419,11 +488,13 @@ impl MediaPool { } /// The conformed-audio file of `path` at `rate` (named by a hash of the path, size and - /// modification time, so an edited file conforms again, and of `CONFORM_VERSION`). + /// modification time, so an edited file conforms again, and of `CONFORM_VERSION`). Notes + /// `path` as read with that identity (see [`crate::reads`]): its samples come from it. pub fn conformed_path(&self, path: &str, rate: u32) -> Option { use std::hash::{Hash, Hasher}; let folder = lock(&self.inner.conform).clone()?; let meta = std::fs::metadata(path).ok()?; + reads::note(ReadFile::new(path, FileStamp::of_metadata(&meta))); let mut h = std::collections::hash_map::DefaultHasher::new(); (CONFORM_VERSION, path, meta.len(), meta.modified().ok()).hash(&mut h); Some(folder.join(format!("{:016x}_{rate}.ecaf", h.finish()))) @@ -592,16 +663,20 @@ impl Inner { /// A 3D model file and its sibling resources (buffers, textures, MTL files), parsed once. fn model(&self, path: &str) -> Option> { - if let Some(m) = lock(&self.models).get(path) { - return m.clone(); + let found = lock(&self.models).get(path).cloned(); + if let Some((m, files)) = found { + reads::note_all(&files); + return m; } - let loaded = self.read(path).map_err(|e| e.to_string()).and_then(|bytes| { - // Files the model names are read only when local or on the model's own network share. - let resolve = |uri: &str| -> Option> { - let p = craft_docpath::resolve_absolute(uri, Some(std::path::Path::new(path))).ok()?; - self.read(&p.to_string_lossy()).ok().map(|b| b.to_vec()) - }; - effectcraft_model::load(path, &bytes, &resolve).map_err(|e| e.to_string()) + let (loaded, files) = reads::captured(|| { + self.read(path).map_err(|e| e.to_string()).and_then(|bytes| { + // Files the model names are read only when local or on the model's own network share. + let resolve = |uri: &str| -> Option> { + let p = craft_docpath::resolve_absolute(uri, Some(std::path::Path::new(path))).ok()?; + self.read(&p.to_string_lossy()).ok().map(|b| b.to_vec()) + }; + effectcraft_model::load(path, &bytes, &resolve).map_err(|e| e.to_string()) + }) }); let m = match loaded { Ok(m) => Some(Arc::new(m)), @@ -610,14 +685,29 @@ impl Inner { None } }; - lock(&self.models).entry(path.to_string()).or_insert(m).clone() + let (m, files) = lock(&self.models).entry(path.to_string()).or_insert((m, Arc::new(files))).clone(); + reads::note_all(&files); + m } + /// The bytes of the file at `path`, noted as read (see [`crate::reads`]). fn read(&self, path: &str) -> Result> { - if let Some(b) = lock(&self.files).get(path) { - return Ok(b.clone()); + let (bytes, file) = self.read_file(path); + reads::note(file); + bytes + } + + /// The bytes of the file at `path` and its identity as read ([`FileStamp::Missing`] when it + /// can't be read), not noted. + fn read_file(&self, path: &str) -> (Result>, ReadFile) { + let in_memory = lock(&self.files).get(path).cloned(); + if let Some(b) = in_memory { + return (Ok(b), ReadFile::new(path, FileStamp::Virtual)); + } + match crate::read_regular_file_stamped(std::path::Path::new(path)) { + Ok((bytes, stamp)) => (Ok(bytes.into()), ReadFile::new(path, stamp)), + Err(e) => (Err(MediaError::Io(format!("{path}: {e}"))), ReadFile::new(path, FileStamp::Missing)), } - crate::read_regular_file(std::path::Path::new(path)).map(Into::into).map_err(|e| MediaError::Io(format!("{path}: {e}"))) } /// The opened movie/audio source for `path` ([`Opened`]). The first caller opens it, outside @@ -625,35 +715,42 @@ impl Inner { /// files are decoded whole); callers asking for the same file meanwhile wait for that instead /// of opening it again: a preview's frame workers, audio feeder, conform and waveform threads /// each decoded a long FLAC in full at once (#408). + /// Each call notes the file as read (see [`crate::reads`]), with its identity as opened. fn opened(&self, path: &Arc) -> Option { let slot = lock(&self.sources).entry(path.clone()).or_default().clone(); - slot.get_or_init(|| { - self.opened.fetch_add(1, Ordering::Relaxed); - // Files on disk are read in place (the index, then samples on demand) rather than - // whole; in-memory files (`add_bytes`) and wasm32 builds open from bytes. - let in_memory = lock(&self.files).contains_key(&**path); - let file = std::path::Path::new(&**path); - let in_place = if in_memory { None } else { crate::stream::open_source(file) }; - let in_place = in_place.map(|src| { - let (header, reader) = (crate::stream::movie_header(file), crate::stream::file_reader(file)); - src.map(|src| Opened::new(src, header.as_deref(), reader.as_deref())) + let (opened, file) = slot.get_or_init(|| self.open(path)); + reads::note(file.clone()); + opened.clone() + } + + /// Open the movie/audio file at `path` (see [`Inner::opened`]), with its identity as opened. + fn open(&self, path: &Arc) -> (Option, ReadFile) { + self.opened.fetch_add(1, Ordering::Relaxed); + // Files on disk are read in place (the index, then samples on demand) rather than + // whole; in-memory files (`add_bytes`) and wasm32 builds open from bytes. + let in_memory = lock(&self.files).contains_key(&**path); + let file = std::path::Path::new(&**path); + let in_place = if in_memory { None } else { crate::stream::open_source(file) }; + let in_place = in_place.map(|(src, stamp)| { + let (header, reader) = (crate::stream::movie_header(file), crate::stream::file_reader(file)); + (src.map(|src| Opened::new(src, header.as_deref(), reader.as_deref())), ReadFile::new(path.clone(), stamp)) + }); + let (opened, read) = in_place.unwrap_or_else(|| { + let (bytes, read) = self.read_file(path); + let opened = bytes.and_then(|bytes| { + let name = std::path::Path::new(&**path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let src = filmcraft_codecs::open_bytes(&name, bytes.clone()).map_err(MediaError::from)?; + Ok(Opened::new(src, Some(&bytes), Some(&filmcraft_media::reader::MemReader(bytes.clone())))) }); - let opened = in_place.unwrap_or_else(|| { - self.read(path).and_then(|bytes| { - let name = std::path::Path::new(&**path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - let src = filmcraft_codecs::open_bytes(&name, bytes.clone()).map_err(MediaError::from)?; - Ok(Opened::new(src, Some(&bytes), Some(&filmcraft_media::reader::MemReader(bytes.clone())))) - }) - }); - match opened { - Ok(s) => Some(s), - Err(e) => { - self.note_problem(path, "", &e); - None - } + (opened, read) + }); + match opened { + Ok(s) => (Some(s), read), + Err(e) => { + self.note_problem(path, "", &e); + (None, read) } - }) - .clone() + } } /// Remember why the movie at `path` cannot be shown (`codec` is the footage's, when known) @@ -674,13 +771,15 @@ impl Inner { /// map's lock; callers asking for the same file meanwhile wait for that. fn gif(&self, path: &Arc) -> Result> { let slot = lock(&self.gifs).entry(path.clone()).or_default().clone(); - let loaded = slot.get_or_init(|| { - let loaded = self.read(path).and_then(|bytes| Anim::load(&bytes)); - loaded.map(Arc::new).map_err(|e| { + let (loaded, file) = slot.get_or_init(|| { + let (bytes, file) = self.read_file(path); + let loaded = bytes.and_then(|bytes| Anim::load(&bytes)).map(Arc::new).map_err(|e| { log::warn!("media: cannot decode {path}: {e}"); e.to_string() - }) + }); + (loaded, file) }); + reads::note(file.clone()); loaded.clone().map_err(|e| MediaError::Decode(format!("{path}: {e}"))) } @@ -698,6 +797,8 @@ impl Inner { ((d.0 as i128 * rate.num as i128 + den / 2) / den) as i64 } + /// Where the frame of `footage` at `t` comes from (file, frame or media time) and its cache + /// key, at the footage's own size. fn locate(footage: &Footage, t: Tick, float: FloatCurve) -> Loc { let alpha = match footage.alpha { AlphaMode::Straight => 0, @@ -710,15 +811,16 @@ impl Inner { FloatCurve::Srgb => 0, FloatCurve::Linear => 1, FloatCurve::Gamma24 => 2, - } << 2); + } << 2) + | (u8::from(footage.placed_page) << 4); let matte = if footage.alpha == AlphaMode::Premultiplied { footage.premul_color.map(f32::to_bits) } else { [0; 3] }; - let key = |path: &str, frame| Key { path: path.into(), frame, interp, matte, size: (0, 0), nominal: (0, 0) }; + let key = |path: &str, frame| Key { path: path.into(), frame, interp, matte, size: (0, 0), nominal: (0, 0), q8: false }; match footage.kind { FootageKind::Sequence if !footage.sequence.is_empty() => { let i = Self::frame_index(footage.frame_rate, t, footage.sequence_frames(), footage.loop_count); - match footage.sequence_file(i) { + match footage.sequence_file_held(i) { Some(path) => Loc { key: key(path, 0), media_t: None, float }, - // A gap in the numbering: colour bars, as in After Effects. + // No file at or before the frame: colour bars. None => Loc { key: key(PLACEHOLDER, ((footage.width as i64) << 32) | footage.height as i64), media_t: None, float }, } } @@ -748,10 +850,22 @@ impl Inner { /// The frame of `footage` at `t`, resampled to `size` (see [`FootageSource::frame_at_size`]): /// a movie's made at that size directly, a still's resampled once and kept at that size. fn frame_at(self: &Arc, footage: &Footage, t: Tick, playback: bool, size: Option<(u32, u32)>, float: FloatCurve) -> Result> { + match Self::frame_px(self, footage, t, playback, size, float, false)? { + Pixels::F32(img) => Ok(img), + // (a float request's key never holds 8-bit levels) + Pixels::Q8(_) => Err(MediaError::Decode(format!("{}: 8-bit frame for a float request", footage.path))), + } + } + + /// [`Self::frame_at`], kept as 8-bit levels when `q8` is set and the frame has 8 bits (a + /// float frame under the float key otherwise, and the movie is remembered as `wide`). + #[allow(clippy::too_many_arguments)] + fn frame_px(self: &Arc, footage: &Footage, t: Tick, playback: bool, size: Option<(u32, u32)>, float: FloatCurve, q8: bool) -> Result { if !footage.has_video { return Err(MediaError::Unsupported(format!("{}: no video", footage.path))); } let mut loc = Self::locate(footage, t, float); + loc.key.q8 = q8; let movie = loc.media_t.is_some(); // A still asked for at its own size is the unsized frame (one decode, one entry). if let Some(size) = size.filter(|s| movie || *s != (footage.width, footage.height)) { @@ -760,22 +874,23 @@ impl Inner { loc.key.nominal = (footage.width, footage.height); } } + // A placed PDF / Illustrator page is drawn to fill the footage's size (`layered::decode`, + // #3099): two items of one file stored at different sizes have different pixels. + if footage.placed_page && !movie { + loc.key.nominal = (footage.width, footage.height); + } let mut c = lock(&self.cache); // sequential playback of a movie: read the next frame ahead if playback && movie { - let prev = c.last.insert(loc.key.path.clone(), loc.key.frame); - if prev == Some(loc.key.frame - 1) && self.read_ahead.load(Ordering::Relaxed) { - let next_t = t + footage.frame_rate.frame_duration(); - let mut next = Self::locate(footage, next_t, float); - next.key.size = loc.key.size; - if next.key != loc.key && !c.lru.map.contains_key(&next.key) && !c.inflight.contains(&next.key) { - self.prefetch(footage, next_t, size, float); - } - } + self.prefetch_next(&mut c, &loc, footage, t, size, float); } + // (Each exit notes the files the frame came from, see `crate::reads`; a cached frame + // notes those it was decoded from, without touching them.) loop { - if let Some(img) = c.lru.get(&loc.key) { + if let Some((img, files)) = c.lru.get(&loc.key) { self.hits.fetch_add(1, Ordering::Relaxed); + drop(c); + reads::note_all(&files); return Ok(img); } if !c.inflight.contains(&loc.key) { @@ -788,7 +903,9 @@ impl Inner { if rayon::current_thread_index().is_some() { self.misses.fetch_add(1, Ordering::Relaxed); drop(c); - return Ok(Arc::new(self.decode(&loc, footage)?)); + let (img, files) = reads::captured(|| self.decode(&loc, footage)); + reads::note_all(&files); + return img; } c = self.done.wait(c).unwrap_or_else(std::sync::PoisonError::into_inner); } @@ -796,23 +913,45 @@ impl Inner { c.inflight.insert(loc.key.clone()); drop(c); let _guard = Inflight { inner: self, key: loc.key.clone() }; - let img = Arc::new(self.decode(&loc, footage)?); - lock(&self.cache).lru.insert(loc.key, img.clone(), self.budget()); + let (img, files) = reads::captured(|| self.decode(&loc, footage)); + reads::note_all(&files); + let img = img?; + let mut c = lock(&self.cache); + if q8 && let Pixels::F32(_) = img { + // not 8-bit: kept as the float frame it is, which the renderer asks for next + c.wide.insert(loc.key.path.clone()); + loc.key.q8 = false; + } + c.lru.insert(loc.key, img.clone(), Arc::new(files), self.budget()); Ok(img) } + /// Sequential playback of a movie (`loc`, at `t`): read the frame after it ahead. + fn prefetch_next(self: &Arc, c: &mut CacheState, loc: &Loc, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) { + let prev = c.last.insert(loc.key.path.clone(), loc.key.frame); + if prev == Some(loc.key.frame - 1) && self.read_ahead.load(Ordering::Relaxed) { + let next_t = t + footage.frame_rate.frame_duration(); + let mut next = Self::locate(footage, next_t, float); + next.key.size = loc.key.size; + next.key.q8 = loc.key.q8; + if next.key != loc.key && !c.lru.map.contains_key(&next.key) && !c.inflight.contains(&next.key) { + self.prefetch(footage, next_t, size, float, loc.key.q8); + } + } + } + #[cfg(not(target_arch = "wasm32"))] - fn prefetch(self: &Arc, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) { + fn prefetch(self: &Arc, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, q8: bool) { let (me, f) = (self.clone(), footage.clone()); self.prefetched.fetch_add(1, Ordering::Relaxed); // A plain thread, not a rayon job: the decode below parallelises with rayon itself. std::thread::spawn(move || { - let _ = me.frame_at(&f, t, false, size, float); + let _ = me.frame_px(&f, t, false, size, float, q8); }); } #[cfg(target_arch = "wasm32")] - fn prefetch(self: &Arc, _footage: &Footage, _t: Tick, _size: Option<(u32, u32)>, _float: FloatCurve) {} + fn prefetch(self: &Arc, _footage: &Footage, _t: Tick, _size: Option<(u32, u32)>, _float: FloatCurve, _q8: bool) {} /// A still (image file or sequence frame) at `loc.key.size` when one is set: resampled as the /// renderer would ([`FootageSource::frame_at_size`]), so the pool keeps the reduced frame and a @@ -829,20 +968,24 @@ impl Inner { effectcraft_raster::resample(&img, w, h) } - fn decode(&self, loc: &Loc, footage: &Footage) -> Result { + fn decode(&self, loc: &Loc, footage: &Footage) -> Result { match loc.media_t { - None => self.decode_still(loc, footage).map(|img| Self::still_at_size(img, loc, footage)), + None => self.decode_still(loc, footage).map(|img| Pixels::F32(Arc::new(Self::still_at_size(img, loc, footage)))), Some(_) => self.decode_media(loc, footage), } } + /// Decodes the still image at `loc` and applies the footage alpha and float handling. + /// A placeholder path decodes to colour bars. fn decode_still(&self, loc: &Loc, footage: &Footage) -> Result { let op = AlphaOp::of(footage, loc.float); let path = &loc.key.path; if &**path == PLACEHOLDER { return Ok(colour_bars(footage.width, footage.height)); } - let bytes = self.read(path)?; + let (bytes, file) = self.read_file(path); + reads::note(file.clone()); + let bytes = bytes?; if let Some(img) = crate::dpx::decode(path, &bytes)? { return Ok(dynamic_to_image(&img, op)); } @@ -856,24 +999,34 @@ impl Inner { { return Err(MediaError::Decode(format!("{path}: {why}"))); } - let loaded = crate::probe::load_oriented(&bytes, crate::still_format(path, &bytes)); - let img = match loaded { - Ok(img) => img, + // An effect reads this footage's channels: the picture is made of the same decode (#474). + let shared = lock(&self.aux_footage).contains(&footage.path); + if shared + && path.to_ascii_lowercase().ends_with(".exr") + && let Some(img) = crate::exr_channels::cached_picture(path, bytes.clone(), &file, op) + { + return Ok(img); + } + #[cfg(test)] + crate::exr_channels::count_decode(false); + match crate::probe::load_oriented(&bytes, crate::still_format(path, &bytes)) { + Ok(img) => Ok(dynamic_to_image(&img, op)), // A multi-layer OpenEXR file without an unnamed RGB layer: its colour layer. - Err(e) => crate::exr_channels::cached_layered_image(path, bytes).ok_or_else(|| MediaError::Decode(format!("{path}: {e}")))?, - }; - Ok(dynamic_to_image(&img, op)) + Err(e) => crate::exr_channels::layered_picture(path, bytes, &file, op, shared) + .map_err(|why| MediaError::Decode(format!("{path}: {}", why.unwrap_or_else(|| e.to_string())))), + } } - fn decode_media(&self, loc: &Loc, footage: &Footage) -> Result { + fn decode_media(&self, loc: &Loc, footage: &Footage) -> Result { let op = AlphaOp::of(footage, loc.float); let path = &loc.key.path; + let f32 = |img| Pixels::F32(Arc::new(img)); match loc.media_t { - None => self.decode_still(loc, footage), + None => self.decode_still(loc, footage).map(f32), Some(mt) if gif_anim::is_animated(footage) => { let anim = self.gif(path)?; let frame = anim.frame_at(Tick(mt.0)).ok_or_else(|| MediaError::Decode(format!("{path}: no frames")))?; - Ok(dynamic_to_image(frame, op)) + Ok(f32(dynamic_to_image(frame, op))) } Some(mt) => { let Opened { src, turn, .. } = self.opened(path).ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?; @@ -891,10 +1044,16 @@ impl Inner { && (vf.width, vf.height) == side((footage.width, footage.height)) && let Some(img) = frame_to_image_scaled(&vf, w, h) { - return Ok(turned(img, turn)); + return Ok(f32(turned(img, turn))); + } + if loc.key.q8 + && turn == Orientation::NoTransforms + && let Some(f) = frame_to_rgba8(&vf, op) + { + return Ok(Pixels::Q8(Arc::new(f))); } let buf = lock(&self.cache).lru.take_spare(vf.width as usize * vf.height as usize); - Ok(turned(frame_to_image_in(&vf, op, buf), turn)) + Ok(f32(turned(frame_to_image_in(&vf, op, buf), turn))) } } } @@ -928,6 +1087,13 @@ impl FootageSource for MediaPool { fn cancellable(&self, cancel: &Arc, f: &mut dyn FnMut()) { filmcraft_media::cancel::with_cancel(cancel, f) } + /// Every read of a file notes it (see [`crate::reads`]): a frame's image file or sequence + /// frame, a movie, a model and the files it names, an EXR's channels, a movie's audio. A + /// frame (or other entry) served from memory notes the files it was made of, as they were + /// when read, without reading them again. A missing sequence frame (colour bars) reads none. + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + reads::recording(reads, f) + } fn frame(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { self.frame_sized(item, footage, t, None, FloatCurve::Srgb) } @@ -937,6 +1103,9 @@ impl FootageSource for MediaPool { fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { self.frame_sized(item, footage, t, size, float) } + fn frame8(&self, _item: ItemId, footage: &Footage, t: Tick, float: FloatCurve) -> Option> { + self.frame8_of(footage, t, float) + } fn problem(&self, footage: &Footage) -> Option { if footage.missing || footage.kind != FootageKind::Video { @@ -950,7 +1119,17 @@ impl FootageSource for MediaPool { return None; } let bytes = self.inner.read(&footage.path).ok()?; - crate::layered::rasterize_vector(&footage.path, &bytes, footage.layer.as_ref(), footage.page, scale).map(Arc::new) + crate::layered::rasterize_vector(&footage.path, &bytes, footage, scale).map(Arc::new) + } + + fn set_aux_footage(&self, paths: &[String]) { + let given: HashSet = paths.iter().cloned().collect(); + let mut wanted = lock(&self.inner.aux_footage); + if given != wanted.given || !wanted.learned.is_empty() { + crate::exr_channels::release_held(); + } + wanted.given = given; + wanted.learned.clear(); } fn aux(&self, _item: ItemId, footage: &Footage, t: Tick) -> Option> { @@ -962,6 +1141,16 @@ impl FootageSource for MediaPool { return None; } let path = loc.key.path.clone(); + { + let mut wanted = lock(&self.inner.aux_footage); + if !wanted.contains(&footage.path) { + // (a bound: names of footage items, cleared otherwise only by a new set) + if wanted.learned.len() >= 4096 { + wanted.learned.clear(); + } + wanted.learned.insert(footage.path.clone()); + } + } crate::exr_channels::cached(&path, || self.inner.read(&path).ok()) } @@ -1154,23 +1343,35 @@ mod tests { #[test] fn lru_respects_budget_and_recycles() { let mut c = Lru::default(); - let img = || Arc::new(Image::new(16, 16)); // 4 KiB + overhead - let k = |i| Key { path: "a".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0) }; + let img = || Pixels::F32(Arc::new(Image::new(16, 16))); // 4 KiB + overhead + let k = |i| Key { path: "a".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), q8: false }; let budget = 3 * (4096 + 64); for i in 0..10 { - c.insert(k(i), img(), budget); + c.insert(k(i), img(), Arc::default(), budget); } assert_eq!(c.map.len(), 3); assert!(c.get(&k(9)).is_some() && c.get(&k(6)).is_none()); // touching 7 makes 8 the oldest c.get(&k(7)); - c.insert(k(10), img(), budget); + c.insert(k(10), img(), Arc::default(), budget); assert!(c.get(&k(7)).is_some() && c.get(&k(8)).is_none()); assert_eq!(c.spare.len(), MAX_SPARE); assert_eq!(c.take_spare(256).len(), 256); assert!(c.take_spare(17).is_empty()); } + /// A frame kept as 8-bit levels is its own entry beside the float one, counted at 4 bytes + /// a pixel. + #[test] + fn lru_keeps_8_bit_frames_apart_at_a_quarter_of_the_bytes() { + let mut c = Lru::default(); + let k = |q8| Key { path: "a".into(), frame: 0, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), q8 }; + c.insert(k(false), Pixels::F32(Arc::new(Image::new(16, 16))), Arc::default(), usize::MAX); + c.insert(k(true), Pixels::Q8(Arc::new(Frame8 { width: 16, height: 16, rgba: vec![0; 16 * 16 * 4] })), Arc::default(), usize::MAX); + assert!(matches!(c.get(&k(false)), Some((Pixels::F32(_), _))) && matches!(c.get(&k(true)), Some((Pixels::Q8(_), _)))); + assert_eq!(c.bytes, (16 * 16 * 16 + 64) + (16 * 16 * 4 + 64)); + } + /// #482: an OpenEXR file with HTJ2K compression (which the decoder lacks) says so on import /// and when its frame is read, instead of "no non-deep rgb channels" or a transparent frame. #[test] diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 6bae86f5b..1fc945aa1 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -198,16 +198,21 @@ pub(crate) fn footage_from_info(path: &str, info: &filmcraft_media::MediaInfo) - missing: false, sequence: Vec::new(), color_profile: v.and_then(|v| profile_of(&v.color)), + // counted in video frames, so only with a video stream + file_timecode: v.and(info.start_timecode), ..Default::default() } } /// The colour profile a video stream declares (H.273 primaries / transfer from the bitstream or -/// container). `None` (interpreted as sRGB) for Rec. 709 primaries with an sRGB curve. +/// container). `None` (interpreted as sRGB) for Rec. 709 primaries with an sRGB curve. BT.2020 +/// with a PQ or HLG curve is Rec. 2100 (HDR10, HLG), not Rec. 2020's 2.4 gamma (#2849). fn profile_of(c: &filmcraft_color::ColorInfo) -> Option { use effectcraft_project::ColorSpace; use filmcraft_color::{Primaries, Transfer}; match (c.primaries, c.transfer) { + (Primaries::Bt2020, Transfer::Pq) => Some(ColorSpace::Rec2100Pq), + (Primaries::Bt2020, Transfer::Hlg) => Some(ColorSpace::Rec2100Hlg), (Primaries::Bt2020, _) => Some(ColorSpace::Rec2020), (Primaries::P3D65, _) => Some(ColorSpace::DisplayP3), (_, Transfer::Bt709) => Some(ColorSpace::Rec709), @@ -383,6 +388,25 @@ mod tests { (0..n).map(|k| (at(k + 1) - at(k)) as u32).collect() } + /// #2849: a stream's primaries and curve pick its profile; BT.2020 with PQ or HLG is Rec. 2100. + #[test] + fn stream_colour_picks_the_profile() { + use effectcraft_project::ColorSpace; + use filmcraft_color::{Primaries, Transfer}; + let rows = [ + (Primaries::Bt2020, Transfer::Pq, Some(ColorSpace::Rec2100Pq)), + (Primaries::Bt2020, Transfer::Hlg, Some(ColorSpace::Rec2100Hlg)), + (Primaries::Bt2020, Transfer::Bt709, Some(ColorSpace::Rec2020)), + (Primaries::P3D65, Transfer::Srgb, Some(ColorSpace::DisplayP3)), + (Primaries::Bt709, Transfer::Bt709, Some(ColorSpace::Rec709)), + (Primaries::Bt709, Transfer::Srgb, None), + ]; + for (primaries, transfer, want) in rows { + let c = filmcraft_color::ColorInfo { primaries, transfer, ..filmcraft_color::ColorInfo::REC709 }; + assert_eq!(profile_of(&c), want, "{primaries:?} + {transfer:?}"); + } + } + /// A model's side files are read from beside it; a URI to another computer is not followed. #[test] fn model_side_files_are_not_read_from_other_computers() { diff --git a/crates/media/src/reads.rs b/crates/media/src/reads.rs new file mode 100644 index 000000000..43ea209b8 --- /dev/null +++ b/crates/media/src/reads.rs @@ -0,0 +1,120 @@ +//! Which files the [`MediaPool`](crate::MediaPool) reads for a render +//! ([`FootageSource::recording`](effectcraft_render::FootageSource::recording)). +//! +//! Every read of a file notes it, with the identity it had when read, in the innermost scope open +//! on this thread. The pool's caches (decoded frames, opened movies, GIFs, models, EXR channels) +//! keep what their entries were made of and note it again on each hit, so a frame served from +//! memory reports its file without touching the disk. +//! +//! The scopes are per thread: a read noted while a render's scope is open on the thread belongs +//! to that render. A thread waiting inside a decode can run another job meanwhile (rayon); that +//! job's reads go to its own scope when it opens one, and otherwise to the scope below it, which +//! then lists a file more than it read (never fewer). + +use std::cell::RefCell; + +use effectcraft_render::reads::{ReadFile, ReadFiles, ReadLog}; + +/// Scopes nested deeper than this are not opened (a thread that keeps taking jobs while it waits +/// cannot pile them up without bound): their reads go to the scope below, and they come back +/// incomplete. +const MAX_DEPTH: usize = 64; + +thread_local! { + /// The open scopes on this thread, innermost last, each with the files noted in it. + static SCOPES: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Note `file` in the innermost open scope on this thread (nothing when none is open). +pub(crate) fn note(file: ReadFile) { + let _ = SCOPES.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() + && let Some(top) = s.last_mut() + { + top.add(file); + } + }); +} + +/// Note every file of `files` in the innermost open scope on this thread. +pub(crate) fn note_all(files: &ReadFiles) { + if files.is_empty() && files.is_complete() { + return; + } + let _ = SCOPES.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() + && let Some(top) = s.last_mut() + { + top.extend(files); + } + }); +} + +/// Closes the scope it opened, also when what runs inside panics: its files go to `out`. +struct Scope<'a> { + out: Out<'a>, + opened: bool, +} + +enum Out<'a> { + /// A render's log ([`recording`]). + Log(&'a ReadLog), + /// The caller's ([`captured`]). + Files(&'a mut ReadFiles), +} + +impl Scope<'_> { + /// Starts collecting the files read on this thread into `out`. + /// At the nesting limit the scope stays closed and reports an incomplete list. + fn open(out: Out<'_>) -> Scope<'_> { + let opened = SCOPES + .try_with(|s| match s.try_borrow_mut() { + Ok(mut s) if s.len() < MAX_DEPTH => { + s.push(ReadFiles::default()); + true + } + _ => false, + }) + .unwrap_or(false); + Scope { out, opened } + } +} + +impl Drop for Scope<'_> { + /// Ends the scope and hands the collected files to its output, marked incomplete when the scope could not be opened. + fn drop(&mut self) { + let files = if self.opened { SCOPES.try_with(|s| s.try_borrow_mut().ok().and_then(|mut s| s.pop())).ok().flatten() } else { None }; + // A scope that could not open saw nothing: what it made can't name its files. + let files = files.unwrap_or_else(|| { + let mut f = ReadFiles::default(); + f.mark_incomplete(); + f + }); + match &mut self.out { + Out::Log(log) => log.note_all(&files), + Out::Files(out) => out.extend(&files), + } + } +} + +/// Run `f` with the files it reads on this thread noted in `log` +/// ([`FootageSource::recording`](effectcraft_render::FootageSource::recording)). +pub(crate) fn recording(log: &ReadLog, f: &mut dyn FnMut()) { + let _scope = Scope::open(Out::Log(log)); + f(); +} + +/// Run `f` and return what it returns with the files it read on this thread (to keep with a +/// cache entry made of them). They are not noted in the enclosing scope: the caller notes them, +/// as it does on each later hit of the entry. +pub(crate) fn captured(f: impl FnOnce() -> T) -> (T, ReadFiles) { + let mut files = ReadFiles::default(); + let out = { + let _scope = Scope::open(Out::Files(&mut files)); + f() + }; + (out, files) +} + +#[cfg(test)] +mod tests; diff --git a/crates/media/src/reads/tests.rs b/crates/media/src/reads/tests.rs new file mode 100644 index 000000000..5dae8415a --- /dev/null +++ b/crates/media/src/reads/tests.rs @@ -0,0 +1,390 @@ +//! The files a render reads, as the media pool reports them (#3184): exactly the files the frame +//! was made of, also when its pixels come from memory. + +use std::path::{Path, PathBuf}; + +use effectcraft_color::Label; +use effectcraft_project::build::{self, Ids}; +use effectcraft_project::{Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerSource, Project, Solid, Value}; +use effectcraft_render::reads::{FileStamp, ReadFiles, ReadLog}; +use effectcraft_render::{LayerCache, RenderOpts, Renderer}; +use effectcraft_time::FrameRate; + +use crate::MediaPool; + +const RATE: FrameRate = FrameRate::FPS_30; +const SIZE: (u32, u32) = (16, 8); + +/// A fresh folder for test `name` (on the build drive, not the system temp folder). +fn folder(name: &str) -> PathBuf { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join(format!("../../target/test-reads-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A PNG at `path`, a flat grey of `level`. +fn png(path: &Path, level: u8) -> String { + image::RgbaImage::from_pixel(SIZE.0, SIZE.1, image::Rgba([level, level, level, 255])).save(path).unwrap(); + path.to_string_lossy().to_string() +} + +/// An image sequence of `n` PNG frames in `dir`. +fn sequence(dir: &Path, n: usize) -> Footage { + let files: Vec = (0..n).map(|i| png(&dir.join(format!("seq_{i:04}.png")), 20 + i as u8 * 10)).collect(); + let mut f = Footage { kind: FootageKind::Sequence, sequence: files, frame_rate: RATE, ..crate::probe(dir.join("seq_0000.png")).unwrap() }; + f.sync_sequence_duration(); + f +} + +/// A still footage item of `path`. +fn still(path: &Path, level: u8) -> Footage { + png(path, level); + crate::probe(path).unwrap() +} + +fn comp() -> Comp { + Comp::new(SIZE.0, SIZE.1, RATE, RATE.tick_of(10)) +} + +fn footage_layer(p: &mut Project, comp: &Comp, name: &str, f: Footage) -> Layer { + let item = p.add_item(name, Label::Aqua, None, ItemKind::Footage(f)); + build::layer(p, comp, name, LayerSource::Footage { item }, SIZE, Some(comp.duration)) +} + +fn add_comp(p: &mut Project, name: &str, mut comp: Comp, layers: Vec) -> ItemId { + comp.layers = layers.into(); + p.add_item(name, Label::Sandstone, None, ItemKind::Comp(comp.into())) +} + +/// Render frame `frame` of `comp` with `pool` and `cache`: the picture's top-left pixel and the +/// files the render reports. +fn render(p: &Project, pool: &MediaPool, cache: &LayerCache, comp: ItemId, frame: i64) -> ([f32; 4], ReadFiles) { + let log = ReadLog::new(); + let mut r = Renderer::new(p, pool, RenderOpts::default()); + r.cache = Some(cache); + r.reads = Some(&log); + let img = r.comp_frame(comp, RATE.tick_of(frame)); + (img.get(0, 0), log.into_files()) +} + +fn paths(files: &ReadFiles) -> Vec { + files.files().iter().map(|f| f.path.to_string()).collect() +} + +/// Every listed file has the identity it has on disk now. +fn assert_stamps_match_disk(files: &ReadFiles) { + for f in files.files() { + assert_eq!(Some(f.stamp), FileStamp::native(&f.path), "{}", f.path); + } +} + +/// (a) One frame of a comp with an image-sequence layer reads that frame's file and nothing else +/// of the sequence; a large sequence in the project that no layer uses adds nothing, not even a +/// look at its files. +#[test] +fn a_sequence_frame_reports_only_its_own_file() { + let dir = folder("sequence"); + let unused_dir = dir.join("unused"); + let mut p = Project::default(); + let c = comp(); + let seq = sequence(&dir, 5); + let (frame_2, frame_4) = (seq.sequence[2].clone(), seq.sequence[4].clone()); + let layer = footage_layer(&mut p, &c, "Seq", seq); + // 5000 frames nobody shows (they don't even exist). + let unused = Footage { + kind: FootageKind::Sequence, + sequence: (0..5000).map(|i| unused_dir.join(format!("big_{i:05}.exr")).to_string_lossy().to_string()).collect(), + frame_rate: RATE, + width: SIZE.0, + height: SIZE.1, + has_video: true, + ..Default::default() + }; + p.add_item("Unused", Label::Aqua, None, ItemKind::Footage(unused)); + let cid = add_comp(&mut p, "C", c, vec![layer]); + let (pool, cache) = (MediaPool::new(), LayerCache::default()); + let opened = crate::opens_under(&dir); + let (px, files) = render(&p, &pool, &cache, cid, 2); + assert!((px[0] - 40.0 / 255.0).abs() < 0.01, "frame 2 shows: {px:?}"); + assert_eq!(paths(&files), [frame_2]); + assert!(files.is_complete()); + assert_stamps_match_disk(&files); + assert_eq!(crate::opens_under(&dir) - opened, 1, "one file opened: the frame's"); + assert_eq!(crate::opens_under(&unused_dir), 0, "the unused sequence was not looked at"); + // Another frame reads its own file, also through the viewer's wrapper of the pool. + let viewer = effectcraft_render::CancellableFootage { inner: &pool, cancel: Default::default() }; + let log = ReadLog::new(); + let mut r = Renderer::new(&p, &viewer, RenderOpts::default()); + r.cache = Some(&cache); + r.reads = Some(&log); + r.comp_frame(cid, RATE.tick_of(4)); + let files = log.into_files(); + assert_eq!(paths(&files), [frame_4]); + assert!(files.is_complete()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (b) A precomp reports the files of what it draws, and an effect that reads another layer +/// reports that layer's files (the layer itself is hidden: its pixels come only through the +/// effect). +#[test] +fn precomps_and_layers_read_by_effects_report_their_files() { + let dir = folder("nested"); + let mut p = Project::default(); + let c = comp(); + let seq = sequence(&dir, 4); + let nested_frame = seq.sequence[3].clone(); + let inner_layer = footage_layer(&mut p, &c, "Seq", seq); + let inner = add_comp(&mut p, "Inner", c.clone(), vec![inner_layer]); + let pre = build::layer(&mut p, &c, "Inner", LayerSource::Comp { item: inner }, SIZE, Some(c.duration)); + let matte_path = dir.join("matte.png"); + let mut matte = footage_layer(&mut p, &c, "Matte", still(&matte_path, 255)); + matte.switches.video = false; + let sid = p.add_item("S", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: SIZE.0, height: SIZE.1, pixel_aspect: 1.0 })); + let mut solid = build::layer(&mut p, &c, "S", LayerSource::Solid { item: sid }, SIZE, Some(c.duration)); + let spec = effectcraft_effects::find("ec.channel.setmatte").unwrap(); + let mut next = p.next_id; + let mut fx = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [SIZE.0 as f64, SIZE.1 as f64]); + p.next_id = next; + fx.prop_mut("takeMatteFromLayer").unwrap().value = Value::Layer(Some(matte.id.0)); + solid.props.sub_mut("effects").unwrap().children.push(fx.into()); + let cid = add_comp(&mut p, "Outer", c, vec![solid, matte, pre]); + let (pool, cache) = (MediaPool::new(), LayerCache::default()); + let (_, files) = render(&p, &pool, &cache, cid, 3); + let mut want = vec![matte_path.to_string_lossy().to_string(), nested_frame]; + want.sort(); + assert_eq!(paths(&files), want); + assert!(files.is_complete()); + assert_stamps_match_disk(&files); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (c) A frame rendered again comes from memory (the sequence frame from the media pool, the +/// still layer from the layer cache) and reports the same files, with the identities they had +/// when read, without opening anything: here the files are even gone by then. +#[test] +fn a_frame_served_from_memory_reports_its_files_without_touching_them() { + let dir = folder("memory"); + let mut p = Project::default(); + let c = comp(); + // The sequence at half opacity over the still: both show. + let mut seq = footage_layer(&mut p, &c, "Seq", sequence(&dir, 3)); + seq.props.prop_mut("transform/opacity").unwrap().value = Value::Scalar(50.0); + let plate = footage_layer(&mut p, &c, "Plate", still(&dir.join("plate.png"), 128)); + let cid = add_comp(&mut p, "C", c, vec![seq, plate]); + let (pool, cache) = (MediaPool::new(), LayerCache::default()); + let (px, first) = render(&p, &pool, &cache, cid, 1); + assert_eq!(first.len(), 2, "{:?}", paths(&first)); + assert_stamps_match_disk(&first); + std::fs::remove_dir_all(&dir).unwrap(); + let opened = crate::opens_under(&dir); + let hits = cache.stats().hits; + let (again_px, again) = render(&p, &pool, &cache, cid, 1); + assert_eq!(again_px, px, "the same picture"); + assert_eq!(again, first, "the same files, as they were when read"); + assert!(cache.stats().hits > hits, "the still layer came from the layer cache"); + // The media pool alone (a new layer cache) reports them too. + let (_, from_pool) = render(&p, &pool, &LayerCache::default(), cid, 1); + assert_eq!(from_pool, first); + assert_eq!(crate::opens_under(&dir), opened, "nothing was opened on disk"); +} + +// ---------------------------------------------------------------- layer entries on disk (#3184) + +use std::sync::Arc; + +use effectcraft_render::disk_cache::{DiskCache, Kind}; + +/// A "session": a new media pool and layer cache over the disk cache in `cache` (opened anew, +/// as after a restart), writing every layer buffer however quick to render. +fn session(cache: &Path) -> (MediaPool, LayerCache, Arc) { + let dc = DiskCache::open(cache, 1 << 30).unwrap(); + dc.set_min_layer_ms(0); + let lc = LayerCache::default(); + lc.set_disk(Some(dc.clone())); + (MediaPool::new(), lc, dc) +} + +/// Give `path` a later modification time, so a rewrite within the clock's resolution counts. +fn touch_later(path: &Path) { + let t = std::fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(7); + std::fs::File::options().append(true).open(path).unwrap().set_modified(t).unwrap(); +} + +/// Two still plates (the upper one at half opacity, so both show), and a 5000-frame sequence +/// in the project that no layer uses (its files don't even exist). +fn plates(dir: &Path) -> (Project, ItemId, PathBuf) { + let mut p = Project::default(); + let c = comp(); + let a = dir.join("a.png"); + let mut top = footage_layer(&mut p, &c, "A", still(&a, 60)); + top.props.prop_mut("transform/opacity").unwrap().value = Value::Scalar(50.0); + let bottom = footage_layer(&mut p, &c, "B", still(&dir.join("b.png"), 200)); + let unused = dir.join("unused"); + let seq = Footage { + kind: FootageKind::Sequence, + sequence: (0..5000).map(|i| unused.join(format!("big_{i:05}.exr")).to_string_lossy().to_string()).collect(), + frame_rate: RATE, + width: SIZE.0, + height: SIZE.1, + has_video: true, + ..Default::default() + }; + p.add_item("Unused", Label::Aqua, None, ItemKind::Footage(seq)); + let cid = add_comp(&mut p, "C", c, vec![top, bottom]); + (p, cid, a) +} + +/// Correct and no scan: after a restart, only the layer buffer whose source file changed is +/// rendered again (only that file is opened); the other comes from disk with its file list, so +/// the frame's list is complete again (its frame entry can be stored). The disk cache checks +/// exactly the files its entries list, never the unused sequence. The re-rendered buffer +/// replaces its entry: the next restart opens nothing. +#[test] +fn a_changed_file_renders_only_the_layer_buffers_that_read_it_again() { + let dir = folder("layer-disk"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let (p, cid, a) = plates(&src); + let (pool, lc, dc) = session(&cache); + let (px, files) = render(&p, &pool, &lc, cid, 0); + assert!(files.is_complete() && files.len() == 2, "{:?}", paths(&files)); + dc.flush(); + let entries = dc.keys(Kind::Layer).len(); + assert!(entries >= 2, "both plates' buffers are on disk: {entries}"); + drop((pool, lc, dc)); + + // Restart without a change: everything from disk, nothing opened, a complete list. + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (again, files_again) = render(&p, &pool, &lc, cid, 0); + assert_eq!(again, px); + assert_eq!(files_again, files, "the files of the entries, as they were read"); + assert!(files_again.is_complete(), "a frame made of buffers from disk can be stored"); + assert_eq!(crate::opens_under(&src), opened, "nothing opened"); + let checks = dc.file_checks(); + assert!(checks >= 2 && checks as usize <= entries, "one check per entry used: {checks} of {entries}"); + drop((pool, lc, dc)); + + // a.png gets new pixels: only the top plate renders again. + png(&a, 120); + touch_later(&a); + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (changed, files_changed) = render(&p, &pool, &lc, cid, 0); + assert_ne!(changed, px, "the new pixels show"); + assert_eq!(crate::opens_under(&src) - opened, 1, "only the changed file is read"); + assert!(files_changed.is_complete() && files_changed.len() == 2); + assert_stamps_match_disk(&files_changed); + assert!(dc.file_checks() as usize <= entries, "only listed files are checked"); + assert_eq!(crate::opens_under(&src.join("unused")), 0); + dc.flush(); + drop((pool, lc, dc)); + + // Its entry was replaced: the next restart opens nothing and shows the new pixels. + let (pool, lc, _dc) = session(&cache); + let opened = crate::opens_under(&src); + let (last, _) = render(&p, &pool, &lc, cid, 0); + assert_eq!(last, changed); + assert_eq!(crate::opens_under(&src), opened, "both from disk"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Two projects whose footage items have the same ids but name different files never share a +/// layer entry: the layer key names the item's path and settings. +#[test] +fn projects_with_the_same_item_ids_never_share_a_layer_entry() { + let dir = folder("layer-disk-projects"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let mut p = Project::default(); + let c = comp(); + let layer = footage_layer(&mut p, &c, "Plate", still(&src.join("one.png"), 40)); + let LayerSource::Footage { item } = layer.source else { panic!("a footage layer") }; + let cid = add_comp(&mut p, "C", c, vec![layer]); + let mut other = p.clone(); + other.item_mut(item).unwrap().kind = ItemKind::Footage(still(&src.join("two.png"), 220)); + let (pool, lc, dc) = session(&cache); + let (one, _) = render(&p, &pool, &lc, cid, 0); + dc.flush(); + drop((pool, lc, dc)); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + let (two, files) = render(&other, &pool, &lc, cid, 0); + assert!((two[0] - 220.0 / 255.0).abs() < 0.01, "the other project's own file shows: {two:?}"); + assert_ne!(two, one); + assert_eq!(dc.stats().hits, hits, "no entry of the first project is used"); + assert_eq!(paths(&files), [src.join("two.png").to_string_lossy().to_string()]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Safe: a damaged layer entry, a source file that is missing, one replaced by something +/// unreadable (a folder), and one back with other pixels never serve a stale buffer after a +/// restart; the damaged entry is rendered again, replaced and then used. +#[test] +fn missing_unreadable_files_and_damaged_layer_entries_never_serve_stale_buffers() { + let dir = folder("layer-disk-safe"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let mut p = Project::default(); + let c = comp(); + let path = src.join("plate.png"); + let layer = footage_layer(&mut p, &c, "Plate", still(&path, 90)); + let cid = add_comp(&mut p, "C", c, vec![layer]); + let (pool, lc, dc) = session(&cache); + let (shown, _) = render(&p, &pool, &lc, cid, 0); + assert!(shown[3] > 0.99, "the plate shows: {shown:?}"); + dc.flush(); + drop((pool, lc, dc)); + + // A damaged entry: a miss, deleted, rendered again and stored anew. + let layers = cache.join("v1").join(Kind::Layer.dir()); + for shard in std::fs::read_dir(&layers).unwrap().flatten() { + for f in std::fs::read_dir(shard.path()).unwrap().flatten() { + let mut d = std::fs::read(f.path()).unwrap(); + let n = d.len() / 2; + d[n] ^= 0x5a; + std::fs::write(f.path(), d).unwrap(); + } + } + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (again, files) = render(&p, &pool, &lc, cid, 0); + assert_eq!(again, shown); + assert_eq!(crate::opens_under(&src) - opened, 1, "read again, not served from the damaged entry"); + assert!(files.is_complete()); + dc.flush(); + drop((pool, lc, dc)); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + assert_eq!(render(&p, &pool, &lc, cid, 0).0, shown); + assert!(dc.stats().hits > hits, "the rewritten entry is used"); + drop((pool, lc, dc)); + + // The file is gone: not the old plate. + std::fs::remove_file(&path).unwrap(); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + let (gone, files) = render(&p, &pool, &lc, cid, 0); + assert!(gone[3] < 0.01, "a missing file shows nothing, never the cached plate: {gone:?}"); + assert_eq!(dc.stats().hits, hits); + assert!(files.files().iter().all(|f| f.stamp == FileStamp::Missing), "{files:?}"); + dc.flush(); + drop((pool, lc, dc)); + + // Something unreadable at its path (a folder): still not the old plate. + std::fs::create_dir(&path).unwrap(); + let (pool, lc, _dc) = session(&cache); + let (unreadable, _) = render(&p, &pool, &lc, cid, 0); + assert!(unreadable[3] < 0.01, "{unreadable:?}"); + std::fs::remove_dir(&path).unwrap(); + + // Back with other pixels: those show, not the entry made of the old file. + png(&path, 240); + touch_later(&path); + let (pool, lc, _dc) = session(&cache); + let (back, _) = render(&p, &pool, &lc, cid, 0); + assert!((back[0] - 240.0 / 255.0).abs() < 0.01, "{back:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index 80db21fc4..0155b4acd 100644 --- a/crates/media/src/stream.rs +++ b/crates/media/src/stream.rs @@ -9,6 +9,7 @@ use std::path::Path; +use effectcraft_render::reads::FileStamp; use filmcraft_media::SharedSource; use crate::Result; @@ -19,17 +20,22 @@ use crate::Result; pub(crate) struct FileReader { file: std::fs::File, len: u64, + /// The file's identity when it was opened. + stamp: FileStamp, } #[cfg(any(unix, windows))] impl FileReader { + /// Opens `path` for reading and records its length and modification time. pub(crate) fn open(path: &Path) -> std::io::Result { + #[cfg(test)] + crate::count_open(path); let file = std::fs::File::open(path)?; let m = file.metadata()?; if !m.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } - Ok(Self { file, len: m.len() }) + Ok(Self { file, len: m.len(), stamp: FileStamp::of_metadata(&m) }) } } @@ -72,16 +78,19 @@ fn name_of(path: &Path) -> String { /// Open a movie/audio file for the media pool, reading only what its container needs; files the /// reader openers don't handle are read whole and opened from memory, exactly as before. `None` /// when the file can't be opened in place (the caller reads it whole, which reports the error). +/// With the file's identity as opened. #[cfg(any(unix, windows))] -pub(crate) fn open_source(path: &Path) -> Option> { +pub(crate) fn open_source(path: &Path) -> Option<(Result, FileStamp)> { let reader = FileReader::open(path).ok()?; + let stamp = reader.stamp; let reader: filmcraft_media::SharedReader = std::sync::Arc::new(reader); let opened = filmcraft_media::reader::open_reader(&name_of(path), reader, &filmcraft_codecs::reader_openers(), &filmcraft_codecs::openers()); - Some(opened.map_err(Into::into)) + Some((opened.map_err(Into::into), stamp)) } +/// Without a native file system there is no in-place source: always `None`. #[cfg(not(any(unix, windows)))] -pub(crate) fn open_source(_path: &Path) -> Option> { +pub(crate) fn open_source(_path: &Path) -> Option<(Result, FileStamp)> { None } diff --git a/crates/media/tests/it/exr_golden.rs b/crates/media/tests/it/exr_golden.rs new file mode 100644 index 000000000..f760ed7c2 --- /dev/null +++ b/crates/media/tests/it/exr_golden.rs @@ -0,0 +1,516 @@ +//! OpenEXR pictures and aux channels pinned to exact hashes (#474). +//! +//! Synthetic files (single-layer, multi-layer with and without an unnamed RGB layer, multi-part, +//! data windows smaller and larger than the display window, half / float / uint channels, RLE, +//! ZIP, PIZ and DWAA) are decoded through the media pool as the renderer asks for them: the +//! picture in each alpha interpretation, and the channels EXtractoR and Cryptomatte read. The +//! hashes were taken before the picture and the channels started sharing one decode, so a change +//! to how either is decoded must leave every bit as it was. Only bit-exact float steps are +//! pinned (linear light, no `powf`), so the hashes hold on every platform; DWAA (whose decoder +//! uses `powf`) and the sRGB / gamma 2.4 curves are checked for agreement between the two ways a +//! frame can be decoded instead. Re-pin with `EXR_GOLDEN_PRINT=1` after an intended change. + +use std::sync::Arc; + +use effectcraft_media::{MediaPool, probe_bytes}; +use effectcraft_project::{AlphaMode, Footage, ItemId}; +use effectcraft_render::{FloatCurve, FootageSource}; +use effectcraft_time::Tick; +use exr::prelude::*; + +const W: usize = 37; +const H: usize = 23; + +/// A deterministic value for pixel (x, y) of channel `c`: negative, in range and above 1. +fn value(x: usize, y: usize, c: usize) -> f32 { + ((x * 7 + y * 13 + c * 29) % 97) as f32 / 40.0 - 0.3 +} + +/// A deterministic alpha in 0..=1 (0 included, for the premultiplied divide). +fn alpha(x: usize, y: usize) -> f32 { + ((x * 3 + y * 5) % 11) as f32 / 10.0 +} + +#[derive(Clone, Copy)] +enum Kind { + Half, + Float, + Uint, +} + +/// A channel `name` of `size` filled from [`value`] (or [`alpha`] for an `A` / `a` channel). +fn channel(name: &str, kind: Kind, size: (usize, usize), c: usize) -> AnyChannel { + let is_alpha = name.rsplit('.').next().is_some_and(|n| n.eq_ignore_ascii_case("a")); + let px = |i: usize| { + let (x, y) = (i % size.0, i / size.0); + if is_alpha { alpha(x, y) } else { value(x, y, c) } + }; + let n = size.0 * size.1; + let samples = match kind { + Kind::Half => FlatSamples::F16((0..n).map(|i| f16::from_f32(px(i))).collect()), + Kind::Float => FlatSamples::F32((0..n).map(px).collect()), + Kind::Uint => FlatSamples::U32((0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) >> 8).collect()), + }; + AnyChannel::new(name, samples) +} + +fn channels(list: &[(&str, Kind)], size: (usize, usize)) -> AnyChannels { + AnyChannels::sort(list.iter().enumerate().map(|(c, (n, k))| channel(n, *k, size, c)).collect::>().into()) +} + +fn encoding(compression: Compression) -> Encoding { + Encoding { compression, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing } +} + +fn with_manifest(mut attrs: LayerAttributes) -> LayerAttributes { + attrs.other.insert(Text::from("cryptomatte/abc1234/name"), AttributeValue::Text(Text::from("CryptoObject"))); + attrs.other.insert(Text::from("cryptomatte/abc1234/manifest"), AttributeValue::Text(Text::from(r#"{"bunny":"13851a76","floor":"0a1b2c3d"}"#))); + attrs +} + +/// One part: `list` channels over a data window of `size` at `pos`. +fn part(name: Option<&str>, list: &[(&str, Kind)], size: (usize, usize), pos: (i32, i32), compression: Compression) -> Layer> { + part_with(name, list, size, pos, encoding(compression)) +} + +/// [`part`] with its own block layout (tiles) and line order. +fn part_with(name: Option<&str>, list: &[(&str, Kind)], size: (usize, usize), pos: (i32, i32), encoding: Encoding) -> Layer> { + let mut attrs = name.map_or_else(LayerAttributes::default, LayerAttributes::named); + attrs.layer_position = Vec2(pos.0, pos.1); + Layer::new(size, with_manifest(attrs), encoding, channels(list, size)) +} + +/// A tiled single-part file of `list` with mip levels down to 1×1 (each level its own values); +/// the picture and the channels are its largest level. +fn mipmapped(list: &[(&str, Kind)], compression: Compression) -> Vec { + let levels = |name: &str, kind: Kind, c: usize| { + let (mut data, mut size) = (vec![], (W, H)); + loop { + data.push(channel(name, kind, size, c + data.len()).sample_data); + if size == (1, 1) { + break; + } + size = ((size.0 / 2).max(1), (size.1 / 2).max(1)); + } + AnyChannel::new(name, Levels::Mip { rounding_mode: exr::math::RoundingMode::Down, level_data: data }) + }; + let list: Vec>> = list.iter().enumerate().map(|(c, (n, k))| levels(n, *k, c)).collect(); + let encoding = Encoding { compression, blocks: Blocks::Tiles(Vec2(16, 16)), line_order: LineOrder::Increasing }; + let layer = Layer::new((W, H), with_manifest(LayerAttributes::default()), encoding, AnyChannels::sort(list.into())); + let mut bytes = std::io::Cursor::new(Vec::new()); + Image::from_layer(layer).write().non_parallel().to_buffered(&mut bytes).unwrap(); + bytes.into_inner() +} + +/// Encode `layers` with the display window `display` (position, size). +fn write(layers: Vec>>, display: ((i32, i32), (usize, usize))) -> Vec { + let mut attrs = ImageAttributes::new(IntegerBounds::new(display.0, display.1)); + attrs.pixel_aspect = 1.0; + let image = Image::from_layers(attrs, layers); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write().non_parallel().to_buffered(&mut bytes).unwrap(); + bytes.into_inner() +} + +const RGBA_HALF: [(&str, Kind); 4] = [("R", Kind::Half), ("G", Kind::Half), ("B", Kind::Half), ("A", Kind::Half)]; +const CRYPTO: [(&str, Kind); 4] = + [("CryptoObject00.r", Kind::Float), ("CryptoObject00.g", Kind::Float), ("CryptoObject00.b", Kind::Float), ("CryptoObject00.a", Kind::Float)]; + +/// The synthetic files: (name, bytes, whether the hashes are pinned). +fn files() -> Vec<(&'static str, Vec, bool)> { + let full = (W, H); + let origin = ((0, 0), full); + let cat = |a: &[(&'static str, Kind)], b: &[(&'static str, Kind)]| -> Vec<(&'static str, Kind)> { a.iter().chain(b).copied().collect() }; + let layered: Vec<(&str, Kind)> = cat( + &[ + ("Image.R", Kind::Half), + ("Image.G", Kind::Half), + ("Image.B", Kind::Half), + ("Image.A", Kind::Half), + ("depth.Z", Kind::Float), + ("ObjectID", Kind::Uint), + ], + &CRYPTO, + ); + let unnamed_plus: Vec<(&str, Kind)> = + cat(&cat(&RGBA_HALF, &[("Diffuse.R", Kind::Half), ("Diffuse.G", Kind::Half), ("Diffuse.B", Kind::Half), ("Z", Kind::Float)]), &CRYPTO); + let rgb_float = [("R", Kind::Float), ("G", Kind::Float), ("B", Kind::Float), ("depth.Z", Kind::Float)]; + vec![ + ("rgba_half_zip16", write(vec![part(None, &RGBA_HALF, full, (0, 0), Compression::ZIP16)], origin), true), + ( + "rgb_float_piz", + write(vec![part(None, &[("R", Kind::Float), ("G", Kind::Float), ("B", Kind::Float), ("Z", Kind::Float)], full, (0, 0), Compression::PIZ)], origin), + true, + ), + ("layered_rle", write(vec![part(None, &layered, full, (0, 0), Compression::RLE)], origin), true), + ("unnamed_rgb_plus_layers_zip1", write(vec![part(None, &unnamed_plus, full, (0, 0), Compression::ZIP1)], origin), true), + ( + "multipart_zip16", + write( + vec![ + part(Some("Image"), &RGBA_HALF, full, (0, 0), Compression::ZIP16), + part(Some("depth"), &[("Z", Kind::Float)], full, (0, 0), Compression::ZIP16), + part( + Some("CryptoObject00"), + &[("r", Kind::Float), ("g", Kind::Float), ("b", Kind::Float), ("a", Kind::Float)], + full, + (0, 0), + Compression::ZIP16, + ), + ], + origin, + ), + true, + ), + ( + // The first part with R, G and B is not the beauty pass. + "multipart_diffuse_then_beauty_zip1", + write( + vec![ + part(Some("diffuse"), &[("R", Kind::Half), ("G", Kind::Half), ("B", Kind::Half)], full, (0, 0), Compression::ZIP1), + part(Some("beauty"), &RGBA_HALF, (20, 10), (5, 7), Compression::ZIP1), + part(Some("depth"), &[("Z", Kind::Float)], full, (0, 0), Compression::ZIP1), + ], + origin, + ), + true, + ), + ( + "multipart_blender5_rle", + write( + vec![ + part(Some("ViewLayer.Depth"), &[("ViewLayer.Depth.Z", Kind::Float)], full, (0, 0), Compression::RLE), + part( + Some("ViewLayer.Combined"), + &[ + ("ViewLayer.Combined.R", Kind::Half), + ("ViewLayer.Combined.G", Kind::Half), + ("ViewLayer.Combined.B", Kind::Half), + ("ViewLayer.Combined.A", Kind::Half), + ], + full, + (0, 0), + Compression::RLE, + ), + ], + origin, + ), + true, + ), + ("unnamed_rgb_window_smaller_zip16", write(vec![part(None, &unnamed_plus, (20, 10), (5, 7), Compression::ZIP16)], origin), true), + ("rgb_float_window_larger_piz", write(vec![part(None, &rgb_float, (45, 30), (-1, -5), Compression::PIZ)], ((3, -2), full)), true), + ("layered_window_smaller_zip16", write(vec![part(None, &layered, (20, 10), (5, 7), Compression::ZIP16)], origin), true), + ("layered_window_larger_piz", write(vec![part(None, &layered, (45, 30), (-4, -3), Compression::PIZ)], origin), true), + ("unnamed_rgb_plus_layers_dwaa", write(vec![part(None, &unnamed_plus, full, (0, 0), Compression::DWAA(None))], origin), false), + ("layered_dwaa", write(vec![part(None, &layered, full, (0, 0), Compression::DWAA(None))], origin), false), + ( + "unnamed_rgb_plus_layers_tiled_zip16", + write( + vec![part_with(None, &unnamed_plus, (30, 20), (3, 2), Encoding { blocks: Blocks::Tiles(Vec2(16, 8)), ..encoding(Compression::ZIP16) })], + origin, + ), + true, + ), + ( + "layered_tiled_rle", + write(vec![part_with(None, &layered, full, (0, 0), Encoding { blocks: Blocks::Tiles(Vec2(8, 8)), ..encoding(Compression::RLE) })], origin), + true, + ), + ("unnamed_rgb_plus_layers_mipmapped_zip16", mipmapped(&unnamed_plus, Compression::ZIP16), true), + ("layered_mipmapped_piz", mipmapped(&layered, Compression::PIZ), true), + ( + "unnamed_rgb_plus_layers_decreasing_zip1", + write( + vec![part_with(None, &unnamed_plus, (20, 10), (5, 7), Encoding { line_order: LineOrder::Decreasing, ..encoding(Compression::ZIP1) })], + origin, + ), + true, + ), + ( + "layered_decreasing_rle", + write(vec![part_with(None, &layered, full, (0, 0), Encoding { line_order: LineOrder::Decreasing, ..encoding(Compression::RLE) })], origin), + true, + ), + ("unnamed_rgb_plus_layers_uncompressed", write(vec![part(None, &unnamed_plus, (20, 10), (-3, 4), Compression::Uncompressed)], origin), true), + ("layered_uncompressed", write(vec![part(None, &layered, full, (0, 0), Compression::Uncompressed)], origin), true), + ( + "uint_rgb_zip16", + write( + vec![part( + None, + &[("R", Kind::Uint), ("G", Kind::Uint), ("B", Kind::Uint), ("A", Kind::Half), ("depth.Z", Kind::Float)], + full, + (0, 0), + Compression::ZIP16, + )], + origin, + ), + true, + ), + ( + // The image crate shows the part "depth" (the first with R, G and B), whose planes are + // filled with the background depth outside its data window: decoded by the image crate. + "multipart_depth_named_rgb_zip16", + write( + vec![ + part(Some("depth"), &[("R", Kind::Half), ("G", Kind::Half), ("B", Kind::Half)], (20, 10), (5, 7), Compression::ZIP16), + part(Some("beauty"), &RGBA_HALF, full, (0, 0), Compression::ZIP16), + ], + origin, + ), + true, + ), + ] +} + +/// FNV-1a over 32-bit words. +fn fnv(words: impl IntoIterator) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for w in words { + for b in w.to_le_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + } + h +} + +fn picture_hash(pool: &MediaPool, f: &Footage, float: FloatCurve, size: Option<(u32, u32)>) -> u64 { + let img = pool.frame_with(ItemId(1), f, Tick::ZERO, size, float).expect("picture"); + fnv([img.width, img.height].into_iter().chain(img.data.iter().flat_map(|p| p.map(f32::to_bits)))) +} + +fn aux_hash(pool: &MediaPool, f: &Footage) -> u64 { + let Some(aux) = pool.aux(ItemId(1), f, Tick::ZERO) else { return 0 }; + let mut words = vec![aux.width, aux.height, aux.scale.to_bits() as u32]; + for (name, plane) in &aux.channels { + words.extend(name.bytes().map(u32::from)); + words.extend(plane.iter().map(|v| v.to_bits())); + } + for (name, objects) in &aux.manifests { + words.extend(name.bytes().map(u32::from)); + for (o, h) in objects { + words.extend(o.bytes().map(u32::from)); + words.push(*h); + } + } + fnv(words) +} + +/// The interpretations a picture is decoded in: (label, footage, curve, size, pinned). +fn variants(f: &Footage) -> Vec<(String, Footage, FloatCurve, Option<(u32, u32)>, bool)> { + let mut out = vec![]; + for (mode, label) in + [(None, "probed"), (Some(AlphaMode::Straight), "straight"), (Some(AlphaMode::Premultiplied), "premul"), (Some(AlphaMode::Ignore), "ignore")] + { + let mut g = f.clone(); + if let Some(m) = mode { + g.alpha = m; + } + g.premul_color = [0.2, 0.4, 0.6]; + out.push((format!("{label}/linear"), g.clone(), FloatCurve::Linear, None, true)); + out.push((format!("{label}/srgb"), g.clone(), FloatCurve::Srgb, None, false)); + out.push((format!("{label}/gamma24"), g.clone(), FloatCurve::Gamma24, None, false)); + } + let preserve = Footage { preserve_rgb: true, ..f.clone() }; + out.push(("preserve_rgb".into(), preserve, FloatCurve::Srgb, None, true)); + out.push(("half_size/srgb".into(), f.clone(), FloatCurve::Srgb, Some((f.width.div_ceil(2), f.height.div_ceil(2))), false)); + out +} + +/// Every hash of `file`: the size and alpha import finds, each picture and the channels, decoded +/// picture first (the footage alone) or channels first (an effect reads them). +fn hashes(name: &str, bytes: &[u8], aux_first: bool) -> Vec<(String, u64, bool)> { + let order = if aux_first { "aux-first" } else { "picture-first" }; + let path = format!("/exr-golden-474/{order}/{name}.exr"); + let b: Arc<[u8]> = bytes.into(); + let pool = MediaPool::new(); + pool.add_bytes(&path, b.clone()); + let f = probe_bytes(&path, b).expect("probe"); + let mut out = vec![("probe".to_string(), fnv([f.width, f.height, f.alpha as u32]), true)]; + let aux = if aux_first { Some(aux_hash(&pool, &f)) } else { None }; + for (label, g, float, size, pinned) in variants(&f) { + out.push((label, picture_hash(&pool, &g, float, size), pinned)); + } + out.push(("aux".into(), aux.unwrap_or_else(|| aux_hash(&pool, &f)), true)); + out +} + +/// Hashes taken on main before #474's shared decode (`EXR_GOLDEN_PRINT=1`). +const PINNED: &[(&str, &str, u64)] = &[ + ("rgba_half_zip16", "probe", 0x0a32e074a28c1f66), + ("rgba_half_zip16", "probed/linear", 0xa84600283dce98f6), + ("rgba_half_zip16", "straight/linear", 0xf028e1367a2fbb30), + ("rgba_half_zip16", "premul/linear", 0xa84600283dce98f6), + ("rgba_half_zip16", "ignore/linear", 0xa90a57f9a67f7468), + ("rgba_half_zip16", "preserve_rgb", 0xc8e0050f5efe75b7), + ("rgba_half_zip16", "aux", 0xdd555e6cf67d75f3), + ("rgb_float_piz", "probe", 0x6a38346c4c5662d5), + ("rgb_float_piz", "probed/linear", 0xa6e8fbbad371a2ae), + ("rgb_float_piz", "straight/linear", 0xa6e8fbbad371a2ae), + ("rgb_float_piz", "premul/linear", 0x515f476c176229c9), + ("rgb_float_piz", "ignore/linear", 0xa6e8fbbad371a2ae), + ("rgb_float_piz", "preserve_rgb", 0xa6e8fbbad371a2ae), + ("rgb_float_piz", "aux", 0x554623d237c2e5ef), + ("layered_rle", "probe", 0x0a32e074a28c1f66), + ("layered_rle", "probed/linear", 0xa84600283dce98f6), + ("layered_rle", "straight/linear", 0xf028e1367a2fbb30), + ("layered_rle", "premul/linear", 0xa84600283dce98f6), + ("layered_rle", "ignore/linear", 0xa90a57f9a67f7468), + ("layered_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_rle", "aux", 0xa6b9bd9f02c192ad), + ("unnamed_rgb_plus_layers_zip1", "probe", 0x0a32e074a28c1f66), + ("unnamed_rgb_plus_layers_zip1", "probed/linear", 0xa84600283dce98f6), + ("unnamed_rgb_plus_layers_zip1", "straight/linear", 0xf028e1367a2fbb30), + ("unnamed_rgb_plus_layers_zip1", "premul/linear", 0xa84600283dce98f6), + ("unnamed_rgb_plus_layers_zip1", "ignore/linear", 0xa90a57f9a67f7468), + ("unnamed_rgb_plus_layers_zip1", "preserve_rgb", 0xc8e0050f5efe75b7), + ("unnamed_rgb_plus_layers_zip1", "aux", 0x27cc9b53d0862db1), + ("multipart_zip16", "probe", 0x0a32e074a28c1f66), + ("multipart_zip16", "probed/linear", 0xa84600283dce98f6), + ("multipart_zip16", "straight/linear", 0xf028e1367a2fbb30), + ("multipart_zip16", "premul/linear", 0xa84600283dce98f6), + ("multipart_zip16", "ignore/linear", 0xa90a57f9a67f7468), + ("multipart_zip16", "preserve_rgb", 0xc8e0050f5efe75b7), + ("multipart_zip16", "aux", 0x567ad99a6690d03d), + ("multipart_diffuse_then_beauty_zip1", "probe", 0x6a38346c4c5662d5), + ("multipart_diffuse_then_beauty_zip1", "probed/linear", 0xa90a57f9a67f7468), + ("multipart_diffuse_then_beauty_zip1", "straight/linear", 0xa90a57f9a67f7468), + ("multipart_diffuse_then_beauty_zip1", "premul/linear", 0x7ab18932e25c5cc8), + ("multipart_diffuse_then_beauty_zip1", "ignore/linear", 0xa90a57f9a67f7468), + ("multipart_diffuse_then_beauty_zip1", "preserve_rgb", 0xa90a57f9a67f7468), + ("multipart_diffuse_then_beauty_zip1", "aux", 0x6724d6dfd56a04cb), + ("multipart_blender5_rle", "probe", 0x0a32e074a28c1f66), + ("multipart_blender5_rle", "probed/linear", 0xa84600283dce98f6), + ("multipart_blender5_rle", "straight/linear", 0xf028e1367a2fbb30), + ("multipart_blender5_rle", "premul/linear", 0xa84600283dce98f6), + ("multipart_blender5_rle", "ignore/linear", 0xa90a57f9a67f7468), + ("multipart_blender5_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("multipart_blender5_rle", "aux", 0x522ae4819dd92e89), + ("unnamed_rgb_window_smaller_zip16", "probe", 0x0a32e074a28c1f66), + ("unnamed_rgb_window_smaller_zip16", "probed/linear", 0x19eb3b1a88d108a7), + ("unnamed_rgb_window_smaller_zip16", "straight/linear", 0x2c73f9acaa936420), + ("unnamed_rgb_window_smaller_zip16", "premul/linear", 0x19eb3b1a88d108a7), + ("unnamed_rgb_window_smaller_zip16", "ignore/linear", 0x3b86057d18a16bf0), + ("unnamed_rgb_window_smaller_zip16", "preserve_rgb", 0x5b999014e4a64bb2), + ("unnamed_rgb_window_smaller_zip16", "aux", 0x8f78d3233450acf3), + ("rgb_float_window_larger_piz", "probe", 0x6a38346c4c5662d5), + ("rgb_float_window_larger_piz", "probed/linear", 0x8e3847d48f9967a6), + ("rgb_float_window_larger_piz", "straight/linear", 0x8e3847d48f9967a6), + ("rgb_float_window_larger_piz", "premul/linear", 0x0998eefc456dcdc9), + ("rgb_float_window_larger_piz", "ignore/linear", 0x8e3847d48f9967a6), + ("rgb_float_window_larger_piz", "preserve_rgb", 0x8e3847d48f9967a6), + ("rgb_float_window_larger_piz", "aux", 0x7ccc9f86e6ff6140), + ("layered_window_smaller_zip16", "probe", 0x0a32e074a28c1f66), + ("layered_window_smaller_zip16", "probed/linear", 0x19eb3b1a88d108a7), + ("layered_window_smaller_zip16", "straight/linear", 0x2c73f9acaa936420), + ("layered_window_smaller_zip16", "premul/linear", 0x19eb3b1a88d108a7), + ("layered_window_smaller_zip16", "ignore/linear", 0x3b86057d18a16bf0), + ("layered_window_smaller_zip16", "preserve_rgb", 0x5b999014e4a64bb2), + ("layered_window_smaller_zip16", "aux", 0x443480a1d789e63c), + ("layered_window_larger_piz", "probe", 0x0a32e074a28c1f66), + ("layered_window_larger_piz", "probed/linear", 0x443afe4029748836), + ("layered_window_larger_piz", "straight/linear", 0xb32b44880f746826), + ("layered_window_larger_piz", "premul/linear", 0x443afe4029748836), + ("layered_window_larger_piz", "ignore/linear", 0xaa01706accce2cc4), + ("layered_window_larger_piz", "preserve_rgb", 0xb2cbb40b10bc56b4), + ("layered_window_larger_piz", "aux", 0xb7d91c8eea56a772), + ("unnamed_rgb_plus_layers_tiled_zip16", "probe", 0x0a32e074a28c1f66), + ("unnamed_rgb_plus_layers_tiled_zip16", "probed/linear", 0x7612f20634fe957e), + ("unnamed_rgb_plus_layers_tiled_zip16", "straight/linear", 0xaa5f42cb6a31c78a), + ("unnamed_rgb_plus_layers_tiled_zip16", "premul/linear", 0x7612f20634fe957e), + ("unnamed_rgb_plus_layers_tiled_zip16", "ignore/linear", 0xbbf236635dcaac90), + ("unnamed_rgb_plus_layers_tiled_zip16", "preserve_rgb", 0x15b555a243d79613), + ("unnamed_rgb_plus_layers_tiled_zip16", "aux", 0x3d1439eed2202e41), + ("layered_tiled_rle", "probe", 0x0a32e074a28c1f66), + ("layered_tiled_rle", "probed/linear", 0xa84600283dce98f6), + ("layered_tiled_rle", "straight/linear", 0xf028e1367a2fbb30), + ("layered_tiled_rle", "premul/linear", 0xa84600283dce98f6), + ("layered_tiled_rle", "ignore/linear", 0xa90a57f9a67f7468), + ("layered_tiled_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_tiled_rle", "aux", 0xa6b9bd9f02c192ad), + ("unnamed_rgb_plus_layers_mipmapped_zip16", "probe", 0x0a32e074a28c1f66), + ("unnamed_rgb_plus_layers_mipmapped_zip16", "probed/linear", 0xa84600283dce98f6), + ("unnamed_rgb_plus_layers_mipmapped_zip16", "straight/linear", 0xf028e1367a2fbb30), + ("unnamed_rgb_plus_layers_mipmapped_zip16", "premul/linear", 0xa84600283dce98f6), + ("unnamed_rgb_plus_layers_mipmapped_zip16", "ignore/linear", 0xa90a57f9a67f7468), + ("unnamed_rgb_plus_layers_mipmapped_zip16", "preserve_rgb", 0xc8e0050f5efe75b7), + ("unnamed_rgb_plus_layers_mipmapped_zip16", "aux", 0x27cc9b53d0862db1), + ("layered_mipmapped_piz", "probe", 0x0a32e074a28c1f66), + ("layered_mipmapped_piz", "probed/linear", 0xa84600283dce98f6), + ("layered_mipmapped_piz", "straight/linear", 0xf028e1367a2fbb30), + ("layered_mipmapped_piz", "premul/linear", 0xa84600283dce98f6), + ("layered_mipmapped_piz", "ignore/linear", 0xa90a57f9a67f7468), + ("layered_mipmapped_piz", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_mipmapped_piz", "aux", 0xa6b9bd9f02c192ad), + ("unnamed_rgb_plus_layers_decreasing_zip1", "probe", 0x0a32e074a28c1f66), + ("unnamed_rgb_plus_layers_decreasing_zip1", "probed/linear", 0x19eb3b1a88d108a7), + ("unnamed_rgb_plus_layers_decreasing_zip1", "straight/linear", 0x2c73f9acaa936420), + ("unnamed_rgb_plus_layers_decreasing_zip1", "premul/linear", 0x19eb3b1a88d108a7), + ("unnamed_rgb_plus_layers_decreasing_zip1", "ignore/linear", 0x3b86057d18a16bf0), + ("unnamed_rgb_plus_layers_decreasing_zip1", "preserve_rgb", 0x5b999014e4a64bb2), + ("unnamed_rgb_plus_layers_decreasing_zip1", "aux", 0x8f78d3233450acf3), + ("layered_decreasing_rle", "probe", 0x0a32e074a28c1f66), + ("layered_decreasing_rle", "probed/linear", 0xa84600283dce98f6), + ("layered_decreasing_rle", "straight/linear", 0xf028e1367a2fbb30), + ("layered_decreasing_rle", "premul/linear", 0xa84600283dce98f6), + ("layered_decreasing_rle", "ignore/linear", 0xa90a57f9a67f7468), + ("layered_decreasing_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_decreasing_rle", "aux", 0xa6b9bd9f02c192ad), + ("unnamed_rgb_plus_layers_uncompressed", "probe", 0x0a32e074a28c1f66), + ("unnamed_rgb_plus_layers_uncompressed", "probed/linear", 0xa27668bf31d9426b), + ("unnamed_rgb_plus_layers_uncompressed", "straight/linear", 0xfc73fe89457ce029), + ("unnamed_rgb_plus_layers_uncompressed", "premul/linear", 0xa27668bf31d9426b), + ("unnamed_rgb_plus_layers_uncompressed", "ignore/linear", 0xb3276cc5126776d4), + ("unnamed_rgb_plus_layers_uncompressed", "preserve_rgb", 0xdee1105fa6e6822a), + ("unnamed_rgb_plus_layers_uncompressed", "aux", 0x854a5e84e7aaa5c2), + ("layered_uncompressed", "probe", 0x0a32e074a28c1f66), + ("layered_uncompressed", "probed/linear", 0xa84600283dce98f6), + ("layered_uncompressed", "straight/linear", 0xf028e1367a2fbb30), + ("layered_uncompressed", "premul/linear", 0xa84600283dce98f6), + ("layered_uncompressed", "ignore/linear", 0xa90a57f9a67f7468), + ("layered_uncompressed", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_uncompressed", "aux", 0xa6b9bd9f02c192ad), + ("uint_rgb_zip16", "probe", 0x0a32e074a28c1f66), + ("uint_rgb_zip16", "probed/linear", 0xed89310ef0cdb9fd), + ("uint_rgb_zip16", "straight/linear", 0xf9fe11ab8ed97cc8), + ("uint_rgb_zip16", "premul/linear", 0xed89310ef0cdb9fd), + ("uint_rgb_zip16", "ignore/linear", 0xf78cd263c0d74f12), + ("uint_rgb_zip16", "preserve_rgb", 0x2a19d67b07cf4359), + ("uint_rgb_zip16", "aux", 0x03e42411f8521856), + ("multipart_depth_named_rgb_zip16", "probe", 0x6a38346c4c5662d5), + ("multipart_depth_named_rgb_zip16", "probed/linear", 0x3b86057d18a16bf0), + ("multipart_depth_named_rgb_zip16", "straight/linear", 0x3b86057d18a16bf0), + ("multipart_depth_named_rgb_zip16", "premul/linear", 0x869374e9b0384cea), + ("multipart_depth_named_rgb_zip16", "ignore/linear", 0x3b86057d18a16bf0), + ("multipart_depth_named_rgb_zip16", "preserve_rgb", 0x3b86057d18a16bf0), + ("multipart_depth_named_rgb_zip16", "aux", 0x0fa56884e83b4417), +]; + +#[test] +fn exr_pictures_and_channels_are_bit_identical() { + let print = std::env::var_os("EXR_GOLDEN_PRINT").is_some(); + let mut failures = vec![]; + for (name, bytes, pinned_file) in files() { + let first = hashes(name, &bytes, false); + let second = hashes(name, &bytes, true); + for ((label, h, pinned), (_, h2, _)) in first.iter().zip(&second) { + if h != h2 { + failures.push(format!("{name} {label}: picture first {h:#018x}, channels first {h2:#018x}")); + } + if print { + println!(" (\"{name}\", \"{label}\", {h:#018x}),{}", if *pinned && pinned_file { "" } else { " // not pinned" }); + continue; + } + if !(*pinned && pinned_file) { + continue; + } + match PINNED.iter().find(|(n, l, _)| *n == name && l == label) { + Some((_, _, want)) if want == h => {} + Some((_, _, want)) => failures.push(format!("{name} {label}: {h:#018x}, pinned {want:#018x}")), + None => failures.push(format!("{name} {label}: {h:#018x} is not pinned")), + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/crates/media/tests/it/file_timecode.rs b/crates/media/tests/it/file_timecode.rs new file mode 100644 index 000000000..e5cbfa92d --- /dev/null +++ b/crates/media/tests/it/file_timecode.rs @@ -0,0 +1,38 @@ +//! The start timecode a movie records is read into its footage (`Footage::file_timecode`). + +use std::io::Cursor; + +use effectcraft_project::FootageKind; +use filmcraft_isobmff::{Brand, Mp4Writer, SampleEntry, TimecodeConfig, TrackConfig, WriteSample, WriterOptions}; + +/// A two-frame 24 fps Motion JPEG MOV, with a timecode track from `start_frame` when given. +fn mov(start_frame: Option) -> Vec { + let mut jpeg = Vec::new(); + image::RgbImage::from_pixel(16, 16, image::Rgb([200, 40, 90])).write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).expect("jpeg"); + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).expect("writer"); + let v = w.add_track(TrackConfig::new(SampleEntry::jpeg(16, 16), 24)).expect("video track"); + if let Some(start) = start_frame { + let tc = TimecodeConfig { timescale: 24, frame_duration: 1, frames_per_second: 24, ..Default::default() }; + w.add_timecode_track(v, tc, start).expect("timecode track"); + } + for _ in 0..2 { + w.write_sample(v, WriteSample { data: &jpeg, duration: 1, composition_offset: 0, is_sync: true }).expect("frame"); + } + w.finish().expect("finish").into_inner() +} + +#[test] +fn a_movies_start_timecode_is_read() { + let dir = std::env::temp_dir().join(format!("effectcraft-file-timecode-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("mkdir"); + // 10:00:00:00 at 24 fps, and a movie with no timecode + for (name, start) in [("tc.mov", Some(10 * 3600 * 24)), ("none.mov", None)] { + let p = dir.join(name); + std::fs::write(&p, mov(start)).expect("write"); + let f = effectcraft_media::probe(&p).expect("probe"); + assert_eq!(f.kind, FootageKind::Video, "{name}"); + assert_eq!(f.file_timecode, start.map(i64::from), "{name}"); + assert_eq!(f.start_timecode, None, "{name}: Interpret Footage still uses the source file timecode"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 0cae33417..ed152541c 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -710,10 +710,11 @@ fn png_sequence_import() { assert_eq!(*img, load_png(&first.with_file_name("seq_0004.png"))); } -/// A gap in a sequence's numbering shows colour bars, as in After Effects; in Force -/// Alphabetical Order the files play back to back (#297). +/// A gap in a sequence's numbering holds the previous frame, as After Effects 2026 does (files +/// 1, 2, 4, 5 show frame 2 at frame 3); in Force Alphabetical Order the files play back to back +/// (#297). #[test] -fn sequence_gaps_show_placeholders() { +fn sequence_gaps_hold_the_previous_frame() { let dir = fixtures().join(format!("gap-seq-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("mkdir"); // Frames 1, 2 and 4: frame 3 is missing. Each frame is a flat grey of its number. @@ -731,11 +732,8 @@ fn sequence_gaps_show_placeholders() { let at = |f: &Footage, n: i64| pool.frame_at(f, t_of(f.frame_rate, n)).expect("frame"); let level = |img: &Image| (img.get(0, 0)[0] * 255.0).round() as u32; assert_eq!(level(&at(&f, 1)), 100); - // The placeholder: colour bars across the frame, starting with 75 % white. - let bars = at(&f, 2); - assert_eq!((bars.width, bars.height), (8, 4)); - assert_eq!(bars.get(0, 0), [0.75, 0.75, 0.75, 1.0]); - assert_eq!(bars.get(7, 3), [0.0, 0.0, 0.75, 1.0], "blue on the right"); + // The gap holds frame 2. + assert_eq!(level(&at(&f, 2)), 100); assert_eq!(level(&at(&f, 3)), 200); f.alphabetical = true; f.sync_sequence_duration(); @@ -749,8 +747,8 @@ fn sequence_gaps_show_placeholders() { /// parallax project's 21120-px plates were decoded and resampled for every frame at Quarter). #[test] fn stills_at_reduced_sizes_are_resampled_once() { - let dir = std::env::temp_dir().join(format!("ec-still-size-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("temp dir"); + let guard = tempfile::tempdir().expect("temp dir"); + let dir = guard.path().to_path_buf(); let p = dir.join("plate.png"); let px = |x: u32, y: u32| { image::Rgba([(x * 7 % 256) as u8, (y * 13 % 256) as u8, ((x ^ y) % 256) as u8, if (x + y).is_multiple_of(5) { 0 } else { 255 - (x % 128) as u8 }]) diff --git a/crates/media/tests/it/main.rs b/crates/media/tests/it/main.rs index 69bed4a9f..efa69b5a6 100644 --- a/crates/media/tests/it/main.rs +++ b/crates/media/tests/it/main.rs @@ -3,6 +3,8 @@ mod aac_layout; mod downmix; mod exif_orientation; +mod exr_golden; +mod file_timecode; mod footage; mod open_in_place; mod tga; diff --git a/crates/opusenc/src/silk.rs b/crates/opusenc/src/silk.rs index 2678a96a0..9e202c958 100644 --- a/crates/opusenc/src/silk.rs +++ b/crates/opusenc/src/silk.rs @@ -125,6 +125,48 @@ struct Coded { pulses: Vec, } +/// Noise-feedback history (decoded − input), most recent first, as a double-length ring: each +/// sample is stored at `pos` and `pos + MAX_LPC_ORDER`, so `buf[pos..pos + MAX_LPC_ORDER]` is +/// always the contiguous window and a push costs two stores instead of a shift. +struct NfRing { + buf: [f64; 2 * MAX_LPC_ORDER], + /// Index of the most recent sample, always below `MAX_LPC_ORDER`. + pos: usize, +} + +impl NfRing { + fn new(hist: &[f64; MAX_LPC_ORDER]) -> Self { + let mut buf = [0.0; 2 * MAX_LPC_ORDER]; + buf[..MAX_LPC_ORDER].copy_from_slice(hist); + buf[MAX_LPC_ORDER..].copy_from_slice(hist); + NfRing { buf, pos: 0 } + } + + /// The history, most recent first. + fn window(&self) -> &[f64] { + self.buf.get(self.pos..self.pos + MAX_LPC_ORDER).unwrap_or(&[]) + } + + /// Makes `v` the most recent sample and drops the oldest. + fn push(&mut self, v: f64) { + self.pos = self.pos.checked_sub(1).unwrap_or(MAX_LPC_ORDER - 1); + for i in [self.pos, self.pos + MAX_LPC_ORDER] { + if let Some(slot) = self.buf.get_mut(i) { + *slot = v; + } + } + } + + /// The history as a plain array, most recent first. + fn to_array(&self) -> [f64; MAX_LPC_ORDER] { + let mut out = [0.0; MAX_LPC_ORDER]; + for (o, v) in out.iter_mut().zip(self.window()) { + *o = *v; + } + out + } +} + #[derive(Clone)] struct Channel { fs_khz: usize, @@ -233,7 +275,7 @@ impl Channel { let sub = self.sub; let order = self.order; let st = &mut self.dec; - let nf = &mut self.nf; + let mut ring = NfRing::new(&self.nf); let off = if p.signal_type == 0 { offset + INACTIVE_OFFSET } else { offset }; let gamma = nf_gamma(off); let mut nf_c = [0f64; MAX_LPC_ORDER]; @@ -351,7 +393,7 @@ impl Channel { } let lpc_q14 = lpc_pred.saturating_mul(16); // Target excitation (Q14) for this sample. - let fb: f64 = (0..order).map(|j| nf_c[j] * nf[j]).sum(); + let fb: f64 = nf_c.iter().zip(ring.window()).take(order).map(|(c, e)| c * e).sum(); let tgt = (x[n] as f64 + fb).clamp(-32768.0, 32767.0) * inv_g - lpc_q14 as f64 - ltp_q14 as f64; let sgn = if seed_v < 0 { -1.0 } else { 1.0 }; let u = sgn * tgt; @@ -390,11 +432,11 @@ impl Channel { let v = res.saturating_add(lpc_q14); s_lpc[MAX_LPC_ORDER + i] = v; xq[n] = sat16(rshift_round(smulww(v, gain_q10), 8)) as i16; - nf.copy_within(0..MAX_LPC_ORDER - 1, 1); - nf[0] = xq[n] as f64 - x[n] as f64; + ring.push(xq[n] as f64 - x[n] as f64); } s_lpc.copy_within(sub..sub + MAX_LPC_ORDER, 0); } + self.nf = ring.to_array(); st.s_lpc_q14.copy_from_slice(&s_lpc[..MAX_LPC_ORDER]); st.out_buf[..l].copy_from_slice(&xq); (Coded { gain_ix, gains_q16, seed, pulses }, xq) @@ -481,6 +523,14 @@ struct Prep { pred_q13: [i32; 2], } +/// One rate-loop trial: the frame coded at gain offset `offset`. +struct Trial { + offset: f64, + bits: i32, + state: SilkEncoder, + coder: RangeEncoder, +} + /// SILK encoder for one mono or stereo (mid/side) stream. #[derive(Clone)] pub struct SilkEncoder { @@ -631,11 +681,20 @@ impl SilkEncoder { pub fn encode(&mut self, input: &[Vec], target_bits: f64, max_bits: i32, enc: &mut RangeEncoder) { let prep = self.prepare(input); let start_bits = enc.tell(); - let trial = |s: &Self, o: f64| -> i32 { - let mut t = s.clone(); - let mut e = enc.clone(); - t.code(&prep, o, &mut e); - e.tell() - start_bits + // Every trial codes the frame into a clone of the encoder and the range coder. The result + // is kept per offset: the hard-limit check below hits the memo for the chosen offset, and + // the final step adopts that trial instead of coding the frame once more. + let mut trials: Vec = Vec::new(); + let mut trial = |s: &Self, o: f64| -> i32 { + if let Some(t) = trials.iter().find(|t| t.offset == o) { + return t.bits; + } + let mut state = s.clone(); + let mut coder = enc.clone(); + state.code(&prep, o, &mut coder); + let bits = coder.tell() - start_bits; + trials.push(Trial { offset: o, bits, state, coder }); + bits }; // Bisection on the gain offset: the smallest offset (finest quantisation) within budget. let target = target_bits.min(max_bits as f64); @@ -697,8 +756,20 @@ impl SilkEncoder { while trial(self, o) > max_bits && o < 12.0 { o += 1.0; } + match trials.iter().position(|t| t.offset == o) { + Some(i) => { + let t = trials.swap_remove(i); + *self = t.state; + *enc = t.coder; + } + None => self.code(&prep, o, enc), + } + self.end_frame(&prep, o); + } + + /// Advances the input history and the frame counter after frame `prep` was coded at `o`. + fn end_frame(&mut self, prep: &Prep, o: f64) { self.last_offset = o; - self.code(&prep, o, enc); for ch in 0..self.channels { self.ch[ch].push_history(&prep.x[ch]); } @@ -708,3 +779,80 @@ impl SilkEncoder { self.frame += 1; } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic speech-like test input: two harmonics with a moving pitch, a syllable + /// envelope, noise and short silences, at the internal rate and 16-bit scale. + fn signal(len: usize, fs_khz: usize, seed: u32) -> Vec { + let mut s = seed; + let fs = (fs_khz * 1000) as f64; + (0..len) + .map(|i| { + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let noise = (s >> 8) as f64 / (1u32 << 24) as f64 - 0.5; + let t = i as f64 / fs; + let f0 = 140.0 + 40.0 * (t * 1.3).sin(); + let env = ((t * 4.0).sin().max(0.0)).powf(0.7); + let voiced = (std::f64::consts::TAU * f0 * t).sin() + 0.5 * (std::f64::consts::TAU * 2.0 * f0 * t).sin(); + (8000.0 * env * voiced + 600.0 * noise) as f32 + }) + .collect() + } + + #[test] + fn nf_ring_matches_a_shifted_history() { + let mut hist = [0f64; MAX_LPC_ORDER]; + for (i, h) in hist.iter_mut().enumerate() { + *h = i as f64 * 0.5 - 3.0; + } + let mut ring = NfRing::new(&hist); + assert_eq!(ring.window(), &hist[..]); + for n in 0..100 { + let v = (n as f64 * 0.37).sin() * 100.0; + hist.copy_within(0..MAX_LPC_ORDER - 1, 1); + hist[0] = v; + ring.push(v); + assert_eq!(ring.window(), &hist[..], "after push {n}"); + } + assert_eq!(ring.to_array(), hist); + } + + /// The rate loop adopts the memoised trial for the chosen offset. A second encoder that codes + /// every frame afresh at that offset (what the loop did before the memo) must produce the + /// same bytes, frame after frame, so the adopted encoder and range-coder states are exact. + #[test] + fn adopting_the_memoised_trial_equals_coding_the_frame_again() { + for (fs_khz, channels, target_bits, max_bits) in + [(8, 1, 200.0, 1000), (12, 1, 320.0, 1000), (16, 1, 480.0, 1000), (16, 2, 640.0, 1000), (16, 1, 900.0, 400), (8, 2, 120.0, 160)] + { + let mut memo = SilkEncoder::new(fs_khz, channels); + let mut fresh = memo.clone(); + let l = memo.frame_len(); + let frames = 40; + let left = signal(l * frames, fs_khz, 7); + let right: Vec = signal(l * frames + 37, fs_khz, 11)[37..].iter().map(|v| v * 0.6).collect(); + for f in 0..frames { + let mut input = vec![left[f * l..(f + 1) * l].to_vec()]; + if channels == 2 { + input.push(right[f * l..(f + 1) * l].to_vec()); + } + let mut enc = RangeEncoder::new(); + memo.encode(&input, target_bits, max_bits, &mut enc); + let o = memo.last_offset; + let prep = fresh.prepare(&input); + let mut enc_fresh = RangeEncoder::new(); + fresh.code(&prep, o, &mut enc_fresh); + fresh.end_frame(&prep, o); + assert_eq!(enc.tell(), enc_fresh.tell(), "{fs_khz} kHz {channels} ch frame {f}"); + assert_eq!(enc.done(1275), enc_fresh.done(1275), "{fs_khz} kHz {channels} ch frame {f}"); + for c in 0..channels { + assert_eq!(memo.ch[c].nf, fresh.ch[c].nf, "noise feedback, channel {c}, frame {f}"); + assert_eq!(memo.ch[c].dec.s_lpc_q14, fresh.ch[c].dec.s_lpc_q14, "LPC state, channel {c}, frame {f}"); + } + } + } + } +} diff --git a/crates/path/src/boolean.rs b/crates/path/src/boolean.rs index bcd395566..0323fc4ee 100644 --- a/crates/path/src/boolean.rs +++ b/crates/path/src/boolean.rs @@ -26,24 +26,19 @@ pub(crate) fn inside(rule: FillRule, w: i32) -> bool { } } -/// Winding numbers for an arbitrary number of input paths (tag = input index). -#[derive(Clone, Debug, Default)] -pub(crate) struct Multi(Vec); +/// Winding numbers for an arbitrary number of input paths (tag = input index), stored sparsely: +/// the nonzero `(tag, winding)` pairs in tag order. A segment's winding names only its own path, +/// so the topology's per-segment copies stay small however many paths take part (a dense +/// vector up to each segment's tag would grow with the square of the path count). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Multi(Vec<(usize, i32)>); impl Multi { fn get(&self, i: usize) -> i32 { - self.0.get(i).copied().unwrap_or(0) + self.0.binary_search_by_key(&i, |e| e.0).map_or(0, |k| self.0[k].1) } } -impl PartialEq for Multi { - fn eq(&self, other: &Self) -> bool { - let n = self.0.len().max(other.0.len()); - (0..n).all(|i| self.get(i) == other.get(i)) - } -} -impl Eq for Multi {} - impl std::ops::Add for Multi { type Output = Multi; fn add(mut self, rhs: Self) -> Multi { @@ -54,26 +49,51 @@ impl std::ops::Add for Multi { impl std::ops::AddAssign for Multi { fn add_assign(&mut self, rhs: Self) { - if self.0.len() < rhs.0.len() { - self.0.resize(rhs.0.len(), 0); + if rhs.0.is_empty() { + return; } - for (a, b) in self.0.iter_mut().zip(rhs.0) { - *a += b; + // Merge the two tag-ordered lists, dropping windings that cancel to zero (so equal + // windings have equal representations). + let (a, b) = (std::mem::take(&mut self.0), rhs.0); + let mut out = Vec::with_capacity(a.len() + b.len()); + let (mut i, mut j) = (0, 0); + while i < a.len() || j < b.len() { + let e = match (a.get(i), b.get(j)) { + (Some(&x), Some(&y)) if x.0 == y.0 => { + i += 1; + j += 1; + (x.0, x.1 + y.1) + } + (Some(&x), Some(&y)) if x.0 < y.0 => { + i += 1; + x + } + (Some(&x), None) => { + i += 1; + x + } + (_, Some(&y)) => { + j += 1; + y + } + (None, None) => break, + }; + if e.1 != 0 { + out.push(e); + } } + self.0 = out; } } impl WindingNumber for Multi { type Tag = usize; fn single(tag: usize, positive: bool) -> Self { - let mut v = vec![0; tag + 1]; - v[tag] = if positive { 1 } else { -1 }; - Multi(v) + Multi(vec![(tag, if positive { 1 } else { -1 })]) } fn of_tag(&self, tag: usize) -> Self { - let mut v = vec![0; tag + 1]; - v[tag] = self.get(tag); - Multi(v) + let w = self.get(tag); + Multi(if w == 0 { Vec::new() } else { vec![(tag, w)] }) } } @@ -250,6 +270,9 @@ pub(crate) fn to_seg(s: PathSeg) -> Seg { } } +/// Most segments `tidy_segments` merges into one. +const MAX_MERGE_RUN: usize = 64; + /// Merge segments of a closed loop that were split from one curve (or collinear lines) back /// together, dropping degenerate pieces. fn tidy_segments(segs: Vec, tidy: &Tidy) -> Vec { @@ -284,7 +307,9 @@ fn tidy_segments(segs: Vec, tidy: &Tidy) -> Vec { while i < n { let mut cur = segs[i]; let mut j = i + 1; - while j < n && mergeable(&segs[j - 1], &segs[j]) { + // Each attempt re-checks the whole run, so a run is capped: a long chain of redundant + // pieces costs linear, not quadratic, work and leaves at most a few extra joints. + while j < n && j - i < MAX_MERGE_RUN && mergeable(&segs[j - 1], &segs[j]) { match try_merge(&segs[i..=j], tidy) { Some(m) => { cur = m; @@ -383,3 +408,46 @@ pub fn filled_area(path: &BezPath, rule: FillRule) -> f64 { None => 0.0, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sparse_windings_add_and_restrict() { + let a = Multi::single(3, true) + Multi::single(1000, false); + assert_eq!((a.get(3), a.get(1000), a.get(7)), (1, -1, 0)); + // Only nonzero entries are stored, whatever the tag. + assert_eq!(a.0.len(), 2); + assert_eq!(a.of_tag(1000), Multi::single(1000, false)); + assert_eq!(a.of_tag(5), Multi::default()); + // Windings that cancel compare equal to none at all. + assert_eq!(a.clone() + Multi::single(3, false) + Multi::single(1000, true), Multi::default()); + } + + #[test] + fn many_paths_union_keeps_each_square() { + let squares: Vec<(BezPath, FillRule)> = + (0..400).map(|i| (kurbo::Rect::new(i as f64 * 3.0, 0.0, i as f64 * 3.0 + 2.0, 2.0).to_path(0.1), FillRule::NonZero)).collect(); + let out = boolean_n(&squares, |m| m.iter().any(|&x| x)); + assert_eq!(out.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(), 400); + assert!((out.area().abs() - 400.0 * 4.0).abs() < 1e-6); + } + + #[test] + fn long_collinear_runs_merge_in_bounded_pieces() { + // A square whose top edge is split into thousands of collinear pieces. + let n: usize = 5000; + let mut segs: Vec = (0..n).map(|k| Seg::line(Point::new(k as f64, 0.0), Point::new(k as f64 + 1.0, 0.0))).collect(); + let w = n as f64; + segs.push(Seg::line(Point::new(w, 0.0), Point::new(w, w))); + segs.push(Seg::line(Point::new(w, w), Point::new(0.0, w))); + segs.push(Seg::line(Point::new(0.0, w), Point::new(0.0, 0.0))); + let out = tidy_segments(segs, &Tidy::free(DEFAULT_PRECISION)); + // The top edge comes back as n / MAX_MERGE_RUN straight pieces on the same line. + assert!(out.len() <= n.div_ceil(MAX_MERGE_RUN) + 3, "{}", out.len()); + assert!(out.iter().all(|s| s.line)); + let top: f64 = out.iter().filter(|s| s.c.p0.y == 0.0 && s.c.p3.y == 0.0).map(|s| s.c.p3.x - s.c.p0.x).sum(); + assert_eq!(top, w); + } +} diff --git a/crates/path/src/feather.rs b/crates/path/src/feather.rs index e8e0fc4a8..47a4bda7e 100644 --- a/crates/path/src/feather.rs +++ b/crates/path/src/feather.rs @@ -70,6 +70,22 @@ fn flatten(sp: &ShapePath, m: &Mat3) -> Flat { } impl Flat { + /// Keep every other point (and the last), with their arc lengths. + fn thin(&mut self) { + let n = self.pts.len(); + let keep = |i: usize| i.is_multiple_of(2) || i + 1 == n; + let mut i = 0; + self.pts.retain(|_| { + i += 1; + keep(i - 1) + }); + let mut i = 0; + self.s.retain(|_| { + i += 1; + keep(i - 1) + }); + } + /// Arc length of a feather point. fn arc_of(&self, f: &FeatherPoint) -> Option { let table = self.seg_tables.get(f.segment)?; @@ -123,14 +139,39 @@ impl Profile { } } +/// Most pixel visits (summed over the flattened path's segments) a variable feather's distance +/// pass may take: a few seconds of work, far beyond a feathered mask at 4K with a radius of a +/// few hundred pixels. Past it the flattened path is thinned (see [`variable_feather_coverage`]). +pub const FEATHER_WORK_BUDGET: u64 = 1 << 31; + +/// Pixel visits of the distance pass over the polyline `pts`: each segment's box grown by +/// `reach`, clipped to the `w × h` mask. +fn feather_work(pts: &[[f64; 2]], reach: f64, w: u32, h: u32) -> u64 { + let span = |lo: f64, hi: f64, n: u32| -> u64 { + let a = (lo - reach).floor().max(0.0); + let b = (hi + reach).ceil().min(f64::from(n) - 1.0); + if b >= a { (b - a + 1.0) as u64 } else { 0 } + }; + pts.windows(2) + .map(|p| { + let (a, b) = (p[0], p[1]); + span(a[0].min(b[0]), a[0].max(b[0]), w).saturating_mul(span(a[1].min(b[1]), a[1].max(b[1]), h)) + }) + .fold(0u64, u64::saturating_add) +} + /// Coverage of a mask path with feather points, transformed by `m` (translate + uniform scale) /// into a `w × h` mask. `expansion` (layer pixels) grows (>0) or shrinks the mask first; /// `linear` selects the Linear feather falloff instead of Smooth. pub fn variable_feather_coverage(sp: &ShapePath, m: &Mat3, w: u32, h: u32, expansion: f64, linear: bool) -> Mask { + coverage_within(sp, m, (w, h), expansion, linear, FEATHER_WORK_BUDGET) +} + +fn coverage_within(sp: &ShapePath, m: &Mat3, (w, h): (u32, u32), expansion: f64, linear: bool, budget: u64) -> Mask { let scale = m.mean_scale(); let path = to_kurbo(sp); let hard = fill_coverage(std::slice::from_ref(&path), m, w, h, FillRule::NonZero); - let flat = flatten(sp, m); + let mut flat = flatten(sp, m); if flat.pts.len() < 2 { return hard; } @@ -148,6 +189,16 @@ pub fn variable_feather_coverage(sp: &ShapePath, m: &Mat3, w: u32, h: u32, expan let rmax = prof.pts.iter().map(|p| p.1.max(p.2)).fold(0.0, f64::max); let exp = expansion * scale; let reach = rmax + exp.abs() + 2.0; + // Each flattened segment visits its box grown by the reach, so many segments with a reach + // spanning the mask would revisit every pixel once per segment. Past the budget the + // polyline is thinned (every other point, keeping their arc lengths) until it fits: the + // distances move by a fraction of the chords, small next to a feather that wide. + while feather_work(&flat.pts, reach, w, h) > budget { + if flat.pts.len() <= 8 { + return hard; + } + flat.thin(); + } let (wu, hu) = (w as usize, h as usize); let mut dist = vec![f32::INFINITY; wu * hu]; let mut arc = vec![0.0f32; wu * hu]; @@ -218,6 +269,32 @@ mod tests { m.data[(y * m.width + x) as usize] } + #[test] + fn feather_work_is_bounded_by_thinning_the_path() { + // Thousands of vertices with a feather reaching across the mask: the polyline is thinned + // until the distance pass fits the budget, and the result is still a feathered edge. + let n = 2000; + let verts: Vec<[f64; 2]> = (0..n) + .map(|i| { + let a = i as f64 / n as f64 * std::f64::consts::TAU; + [100.0 + 50.0 * a.cos(), 100.0 + 50.0 * a.sin()] + }) + .collect(); + let mut sp = ShapePath::polygon(&verts, true); + sp.feather = vec![FeatherPoint { segment: 0, t: 0.5, radius: 40.0, tension: 0.0 }]; + let budget = 1 << 22; + let full = flatten(&sp, &Mat3::IDENTITY); + assert!(feather_work(&full.pts, 42.0, 200, 200) > budget); + let m = coverage_within(&sp, &Mat3::IDENTITY, (200, 200), 0.0, true, budget); + let unbounded = coverage_within(&sp, &Mat3::IDENTITY, (200, 200), 0.0, true, u64::MAX); + // Outside the edge: 1 at the circle falling linearly to 0 at 40 px, close to the + // unthinned result. + assert!(at(&m, 100, 100) > 0.99); + let (thin, exact) = (at(&m, 100, 30), at(&unbounded, 100, 30)); + assert!(thin > 0.4 && thin < 0.6 && (thin - exact).abs() < 0.05, "{thin} {exact}"); + assert!(at(&m, 100, 5) < 0.01); + } + #[test] fn no_points_is_the_hard_mask() { let m = variable_feather_coverage(&square(), &Mat3::IDENTITY, 200, 200, 0.0, false); diff --git a/crates/path/src/interp.rs b/crates/path/src/interp.rs index 4087b26b5..89e7edc51 100644 --- a/crates/path/src/interp.rs +++ b/crates/path/src/interp.rs @@ -311,6 +311,9 @@ fn frame(v: &[P]) -> (P, f64) { (c, r) } +/// Vertex counts above this skip the shape contexts (quadratic to build) and search the starting +/// vertex coarsely; no mask comes near it (the Add Vertices option itself stops at 2000). +const MAX_CONTEXT_VERTICES: usize = 4096; const RBINS: usize = 5; const ABINS: usize = 12; @@ -412,10 +415,18 @@ pub fn correspond(a: &ShapePath, b: &ShapePath, o: &InterpOpts) -> (ShapePath, S } if !o.first_vertices_match { let n = ra.len(); - let use_sc = o.quality > 0.0; + let large = n > MAX_CONTEXT_VERTICES; + let use_sc = o.quality > 0.0 && !large; let (sa, sb) = if use_sc { (Some(shape_contexts(&ra.vertices)), Some(shape_contexts(&rb.vertices))) } else { (None, None) }; // Quality limits the offsets examined exhaustively (coarse step), then refines. - let step = if o.quality >= 50.0 { 1 } else { ((n as f64 / 24.0).ceil() as usize).max(1) }; + // (A very large shape tries about 3 √n offsets, not n, each costing a pass over it.) + let step = if large { + (n as f64).sqrt().ceil() as usize + } else if o.quality >= 50.0 { + 1 + } else { + ((n as f64 / 24.0).ceil() as usize).max(1) + }; let mut best = (f64::MAX, 0usize); let mut k = 0; while k < n { @@ -592,4 +603,22 @@ mod tests { let l2 = (lin.vertices[1][0] - lin.vertices[0][0]).hypot(lin.vertices[1][1] - lin.vertices[0][1]); assert!(l2 < 80.0); } + + /// A shape with tens of thousands of vertices is matched without the quadratic shape contexts + /// and exhaustive offset search. + #[test] + fn very_large_shapes_are_matched_in_bounded_time() { + let n = 30_000; + let circle = |rot: f64| -> ShapePath { + let pts: Vec

= (0..n) + .map(|i| [100.0 * (rot + i as f64 * std::f64::consts::TAU / n as f64).cos(), 100.0 * (rot + i as f64 * std::f64::consts::TAU / n as f64).sin()]) + .collect(); + ShapePath::polygon(&pts, true) + }; + let o = InterpOpts { one_to_one: true, quality: 100.0, ..Default::default() }; + let t = std::time::Instant::now(); + let (a, b) = correspond(&circle(0.0), &circle(1.0), &o); + assert_eq!((a.len(), b.len()), (n, n)); + assert!(t.elapsed().as_secs() < 30, "{:?}", t.elapsed()); + } } diff --git a/crates/path/src/trace.rs b/crates/path/src/trace.rs index 01508bcaf..7b15b55c2 100644 --- a/crates/path/src/trace.rs +++ b/crates/path/src/trace.rs @@ -55,37 +55,85 @@ pub fn trace(field: &[f32], w: usize, h: usize, o: &TraceOpts) -> Vec { return vec![]; } let loops = contours(field, w, h, o.threshold); - let mut polys: Vec<(Vec<[f64; 2]>, Vec<[f64; 2]>, f64)> = loops + // (raw loop, kept raw indices, simplified loop, area) + let mut polys: Vec<(Vec<[f64; 2]>, Vec, Vec<[f64; 2]>, f64)> = loops .into_iter() .filter_map(|raw| { let a = signed_area(&raw); if a.abs() < o.min_area.max(0.0) || raw.len() < 3 { return None; } - let simp = simplify_closed(&raw, o.tolerance.max(0.01)); - if simp.len() < 3 { + let idx = simplify_idx(&raw, o.tolerance.max(0.01)); + if idx.len() < 3 { return None; } - Some((raw, simp, a)) - }) - .collect(); - // Depth: how many other loops contain a point of this loop. - let depths: Vec = (0..polys.len()) - .map(|i| { - let p = polys[i].1[0]; - (0..polys.len()).filter(|&j| j != i && polys[j].2.abs() > polys[i].2.abs() && point_in_poly(p, &polys[j].1)).count() + let simp = idx.iter().map(|&i| raw[i]).collect(); + Some((raw, idx, simp, a)) }) .collect(); + let depths = nesting_depths(&polys.iter().map(|p| (p.2.as_slice(), p.3.abs())).collect::>(), w, h); let mut out: Vec = polys .drain(..) .zip(depths) - .map(|((raw, simp, a), depth)| Traced { path: fit_loop(&raw, &simp, o.corner_roundness.clamp(0.0, 1.0)), depth, area: a }) + .map(|((raw, idx, simp, a), depth)| Traced { path: fit_loop(&raw, &idx, &simp, o.corner_roundness.clamp(0.0, 1.0)), depth, area: a }) .collect(); // Outer outlines first, then holes, islands…; larger first within a depth. out.sort_by(|a, b| a.depth.cmp(&b.depth).then(b.area.abs().total_cmp(&a.area.abs()))); out } +/// Grid cell (pixels) of the index [`nesting_depths`] finds candidate containers with. +const DEPTH_CELL: f64 = 32.0; + +/// Most grid cells one loop's box is entered into; a box covering more is kept in a short list +/// every point is tested against, so nested full-image contours can't fill the grid. +const MAX_BOX_CELLS: usize = 64; + +/// Per loop (simplified points, |area|): how many other, larger loops contain its first point. +/// Only loops whose bounding box holds that point can contain it, so each loop's box is entered +/// into a coarse grid over the `w × h` field and a point is tested against the loops of its +/// cell alone: many separate regions no longer test every pair. +fn nesting_depths(polys: &[(&[[f64; 2]], f64)], w: usize, h: usize) -> Vec { + // Loops lie within the field padded by half a pixel each side. + let (gw, gh) = (((w as f64 + 1.0) / DEPTH_CELL).ceil() as usize + 1, ((h as f64 + 1.0) / DEPTH_CELL).ceil() as usize + 1); + let cell = |v: f64, n: usize| (((v + 0.5) / DEPTH_CELL).floor().max(0.0) as usize).min(n - 1); + let boxes: Vec<[f64; 4]> = polys + .iter() + .map(|(p, _)| { + p.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, q| { + [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])] + }) + }) + .collect(); + let mut grid: Vec> = vec![Vec::new(); gw * gh]; + let mut wide: Vec = Vec::new(); + for (j, b) in boxes.iter().enumerate() { + let (x0, x1, y0, y1) = (cell(b[0], gw), cell(b[2], gw), cell(b[1], gh), cell(b[3], gh)); + if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_BOX_CELLS { + wide.push(j); + continue; + } + for cy in y0..=y1 { + for cx in x0..=x1 { + grid[cy * gw + cx].push(j); + } + } + } + (0..polys.len()) + .map(|i| { + let p = polys[i].0[0]; + grid[cell(p[1], gh) * gw + cell(p[0], gw)] + .iter() + .chain(&wide) + .filter(|&&j| { + let b = boxes[j]; + j != i && polys[j].1 > polys[i].1 && p[0] >= b[0] && p[0] <= b[2] && p[1] >= b[1] && p[1] <= b[3] && point_in_poly(p, polys[j].0) + }) + .count() + }) + .collect() +} + /// Marching squares: closed polylines (pixel coordinates). fn contours(field: &[f32], w: usize, h: usize, thr: f32) -> Vec> { // Padded grid: sample (i, j) of the padded grid is pixel (i - 1, j - 1), outside = -inf. @@ -233,23 +281,37 @@ fn seg_dist(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 { ((p[0] - a[0] - t * dx).powi(2) + (p[1] - a[1] - t * dy).powi(2)).sqrt() } -/// Douglas–Peucker on an open polyline: kept indices. -fn dp(p: &[[f64; 2]], lo: usize, hi: usize, tol: f64, keep: &mut Vec) { - if hi <= lo + 1 { - return; - } - let (mut best, mut bi) = (0.0, lo); - for (k, q) in p.iter().enumerate().take(hi).skip(lo + 1) { - let d = seg_dist(*q, p[lo], p[hi]); - if d > best { - best = d; - bi = k; +/// Distance evaluations Douglas–Peucker may spend per point of a loop. Balanced splits need +/// about log2(n); splits that keep landing next to an end would need up to n. +const DP_WORK_PER_POINT: usize = 64; + +/// Douglas–Peucker on an open polyline: kept indices (unordered). Spans wait on an explicit +/// stack (no recursion depth to overflow), and once `budget` distance evaluations are spent the +/// spans still waiting keep all their points: the outline stays exact, just less simplified. +fn dp(p: &[[f64; 2]], lo: usize, hi: usize, tol: f64, budget: &mut usize, keep: &mut Vec) { + let mut spans = vec![(lo, hi)]; + while let Some((lo, hi)) = spans.pop() { + if hi <= lo + 1 { + continue; + } + if *budget < hi - lo - 1 { + keep.extend(lo + 1..hi); + continue; + } + *budget -= hi - lo - 1; + let (mut best, mut bi) = (0.0, lo); + for (k, q) in p.iter().enumerate().take(hi).skip(lo + 1) { + let d = seg_dist(*q, p[lo], p[hi]); + if d > best { + best = d; + bi = k; + } + } + if best > tol { + keep.push(bi); + spans.push((lo, bi)); + spans.push((bi, hi)); } - } - if best > tol { - dp(p, lo, bi, tol, keep); - keep.push(bi); - dp(p, bi, hi, tol, keep); } } @@ -265,27 +327,23 @@ fn simplify_idx(p: &[[f64; 2]], tol: f64) -> Vec { let mut ext: Vec<[f64; 2]> = p.to_vec(); ext.push(p[0]); let mut keep = vec![0]; - dp(&ext, 0, far, tol, &mut keep); + let mut budget = n.saturating_mul(DP_WORK_PER_POINT); + dp(&ext, 0, far, tol, &mut budget, &mut keep); keep.push(far); - dp(&ext, far, n, tol, &mut keep); + dp(&ext, far, n, tol, &mut budget, &mut keep); keep.sort_unstable(); keep.dedup(); keep.retain(|&i| i < n); keep } -fn simplify_closed(p: &[[f64; 2]], tol: f64) -> Vec<[f64; 2]> { - simplify_idx(p, tol).into_iter().map(|i| p[i]).collect() -} - -/// Fit cubics through the simplified vertices of a loop (`raw` holds the full contour). -fn fit_loop(raw: &[[f64; 2]], simp: &[[f64; 2]], round: f64) -> ShapePath { +/// Fit cubics through the simplified vertices of a loop (`raw` holds the full contour, `idx` +/// the raw index of each simplified vertex, as [`simplify_idx`] kept them). +fn fit_loop(raw: &[[f64; 2]], idx: &[usize], simp: &[[f64; 2]], round: f64) -> ShapePath { let n = simp.len(); if round <= 1e-6 { return ShapePath::polygon(simp, true); } - // Raw index of each simplified vertex (they are raw points). - let idx: Vec = simp.iter().map(|s| raw.iter().position(|r| r == s).unwrap_or(0)).collect(); let pt = |a: [f64; 2]| Point::new(a[0], a[1]); let v = |a: [f64; 2], b: [f64; 2]| Vec2::new(b[0] - a[0], b[1] - a[1]); // Per vertex: (direction leaving, direction arriving), blended between chord and smooth. @@ -349,6 +407,86 @@ mod tests { fill_coverage(&paths, &Mat3::IDENTITY, w as u32, h as u32, FillRule::EvenOdd).data } + #[test] + fn nesting_depths_match_every_pair() { + // Rings within rings beside many separate dots: the grid lookup gives the same depths + // as testing every pair. + let (w, h) = (200, 120); + let mut field = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (fx, fy) = (x as f64 + 0.5 - 60.0, y as f64 + 0.5 - 60.0); + let r = (fx * fx + fy * fy).sqrt(); + let ring = r < 56.0 && ((r / 8.0) as usize).is_multiple_of(2); + let dot = x >= 130 && x % 6 < 3 && y % 6 < 3; + field[y * w + x] = if ring || dot { 1.0 } else { 0.0 }; + } + } + let opts = TraceOpts { min_area: 1.0, ..Default::default() }; + let t = trace(&field, w, h, &opts); + assert!(t.len() > 200, "{}", t.len()); + let polys: Vec<(Vec<[f64; 2]>, f64)> = t.iter().map(|t| (t.path.vertices.clone(), t.area.abs())).collect(); + let refs: Vec<(&[[f64; 2]], f64)> = polys.iter().map(|(p, a)| (p.as_slice(), *a)).collect(); + let fast = nesting_depths(&refs, w, h); + let pairs: Vec = + (0..refs.len()).map(|i| (0..refs.len()).filter(|&j| j != i && refs[j].1 > refs[i].1 && point_in_poly(refs[i].0[0], refs[j].0)).count()).collect(); + assert_eq!(fast, pairs); + assert_eq!(fast, t.iter().map(|t| t.depth).collect::>()); + assert!(fast.iter().max() >= Some(&5)); + } + + #[test] + fn nesting_depths_count_wide_boxes_kept_out_of_the_grid() { + // Concentric squares whose boxes each cover far more than MAX_BOX_CELLS cells. + let (w, h) = (4000, 4000); + let squares: Vec> = (0..40) + .map(|k| { + let (a, b) = (10.0 + 40.0 * k as f64, 3990.0 - 40.0 * k as f64); + vec![[a, a], [b, a], [b, b], [a, b]] + }) + .collect(); + let refs: Vec<(&[[f64; 2]], f64)> = squares.iter().map(|p| (p.as_slice(), (p[1][0] - p[0][0]).powi(2))).collect(); + assert_eq!(nesting_depths(&refs, w, h), (0..40).collect::>()); + } + + #[test] + fn simplification_work_is_bounded_and_keeps_the_outline() { + // Out of budget, the spans still waiting keep every point: nothing is lost, the outline + // is just less simplified. + let p: Vec<[f64; 2]> = (0..12).map(|i| [i as f64, if i % 2 == 0 { 0.0 } else { 5.0 }]).collect(); + let (mut budget, mut keep) = (0, vec![]); + dp(&p, 0, 11, 0.01, &mut budget, &mut keep); + keep.sort_unstable(); + assert_eq!(keep, (1..11).collect::>()); + // With a budget, the result matches the plain recursion's on an ordinary loop. + let (mut budget, mut keep) = (usize::MAX, vec![]); + dp(&p, 0, 11, 0.01, &mut budget, &mut keep); + keep.sort_unstable(); + assert_eq!(keep, (1..11).collect::>()); + // A long, finely zig-zagging loop: simplified within a budget linear in its length. + let n = 200_000; + let ring: Vec<[f64; 2]> = (0..n) + .map(|i| { + let a = i as f64 / n as f64 * std::f64::consts::TAU; + let r = 1000.0 + if i % 2 == 0 { 0.0 } else { 3.0 }; + [r * a.cos(), r * a.sin()] + }) + .collect(); + let idx = simplify_idx(&ring, 0.5); + assert!(idx.windows(2).all(|w| w[0] < w[1]) && idx.len() >= 3 && *idx.last().unwrap() < n); + } + + #[test] + fn fit_uses_the_kept_indices() { + // A contour that passes the same point twice: the fit follows the simplifier's index, + // not the first raw point with those coordinates. + let raw = vec![[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 0.0], [-10.0, 10.0], [-10.0, 0.0]]; + let idx = vec![0, 2, 3, 4]; + let simp: Vec<[f64; 2]> = idx.iter().map(|&i| raw[i]).collect(); + let path = fit_loop(&raw, &idx, &simp, 0.5); + assert_eq!(path.vertices, simp); + } + #[test] fn traces_a_disc_and_a_square_with_a_hole() { let (w, h) = (120, 80); diff --git a/crates/path/src/varstroke.rs b/crates/path/src/varstroke.rs index 61e6a1ab7..da00b02d0 100644 --- a/crates/path/src/varstroke.rs +++ b/crates/path/src/varstroke.rs @@ -220,6 +220,56 @@ fn disc(out: &mut BezPath, c: Point, r: f64) { } } +/// `path` with each curve whose extent is over 10⁷ × `tol` replaced by lines flattened at 10⁻⁷ of +/// that extent. `None` when a coordinate is not finite. +fn coarsen_huge(path: &BezPath, tol: f64) -> Option { + use kurbo::Shape as _; + let mut out = BezPath::new(); + let (mut cur, mut start) = (Point::ZERO, Point::ZERO); + for el in path.elements() { + let seg = match *el { + PathEl::MoveTo(p) => { + (cur, start) = (p, p); + out.push(*el); + continue; + } + PathEl::LineTo(p) => { + cur = p; + out.push(*el); + continue; + } + PathEl::ClosePath => { + cur = start; + out.push(*el); + continue; + } + PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => { + let mut one = BezPath::new(); + one.move_to(cur); + one.push(*el); + (one, p) + } + }; + let (one, end) = seg; + let bb = one.bounding_box(); + let extent = bb.width().max(bb.height()); + if !extent.is_finite() { + return None; + } + if extent * 1e-7 > tol { + kurbo::flatten(one.elements().iter().copied(), extent * 1e-7, |e| { + if let PathEl::LineTo(p) = e { + out.line_to(p); + } + }); + } else { + out.push(*el); + } + cur = end; + } + Some(out) +} + /// Outline of a tapered / waved stroke (local space; `res_scale` = device/local scale). pub fn outline(paths: &[BezPath], style: &StrokeStyle, res_scale: f64) -> Option { if style.width <= 0.0 { @@ -230,7 +280,11 @@ pub fn outline(paths: &[BezPath], style: &StrokeStyle, res_scale: f64) -> Option let half = style.width / 2.0; for path in paths { // Fine enough for the width profile: ½ device pixel, at most ~20 000 samples per path. - let rough = flatten(path, 0.1 / rs, f64::INFINITY); + // Curves with huge extents are first cut into lines at a tolerance of 10⁻⁷ of their own + // extent, so none subdivides into billions of points before the step below applies; + // every other segment (small curves in a large path included) keeps the ½-pixel tolerance. + let Some(path) = coarsen_huge(path, 0.1 / rs) else { continue }; + let rough = flatten(&path, 0.1 / rs, f64::INFINITY); for poly0 in rough { let len0 = poly0.len(); if len0 <= 0.0 { @@ -396,4 +450,37 @@ mod tests { let area: f32 = m.data.iter().sum(); assert!(area > 240.0 * 6.0 * 0.8 && area < 240.0 * 6.0 * 1.05, "{area}"); } + + /// A curve with enormous coordinates is approximated within a bounded number of points. + #[test] + fn huge_coordinates_do_not_explode_the_first_approximation() { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.curve_to((1e13, 0.0), (-1e13, 1e13), (1e13, 1e13)); + let st = StrokeStyle { + width: 4.0, + taper: Some(Taper { percent: true, start_len: 50.0, end_len: 50.0, start_width: 0.0, end_width: 0.0, start_ease: 0.0, end_ease: 0.0 }), + ..Default::default() + }; + let t = std::time::Instant::now(); + let o = outline(&[p], &st, 1.0).unwrap(); + assert!(o.elements().len() < 200_000, "{}", o.elements().len()); + assert!(t.elapsed().as_secs() < 20); + } + + /// Small curves keep their shape in a path that also has a huge segment. + #[test] + fn small_curves_survive_a_huge_segment() { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.curve_to((100.0, 0.0), (0.0, 100.0), (0.0, 0.0)); + p.line_to((1e10, 0.0)); + let c = coarsen_huge(&p, 0.1).unwrap(); + assert_eq!(c.elements().len(), p.elements().len(), "nothing here is huge enough to cut"); + let mut q = BezPath::new(); + q.move_to((0.0, 0.0)); + q.curve_to((1e13, 0.0), (-1e13, 1e13), (1e13, 1e13)); + let c = coarsen_huge(&q, 0.1).unwrap(); + assert!(c.elements().iter().skip(1).all(|e| matches!(e, PathEl::LineTo(_))) && c.elements().len() < 10_000); + } } diff --git a/crates/pdf/README.md b/crates/pdf/README.md index 20f655611..b38c9032e 100644 --- a/crates/pdf/README.md +++ b/crates/pdf/README.md @@ -29,7 +29,13 @@ ffmpeg elsewhere) to check the code tables against an independent implementation the app's existing object model. References retain object and generation numbers. A bounded compatibility repair recovers referenced objects from object streams when damaged xrefs omit them; every recovery or unresolved reference is reported in `Doc::skipped` (up to 64 messages). - The existing page tree preserves inherited resources, MediaBox / CropBox and `/Rotate`. + The existing page tree preserves inherited resources, MediaBox / CropBox and `/Rotate`. A page + is its CropBox (else MediaBox), turned by `/Rotate` (`Framing::Viewer`, the default). Footage + from an After Effects project is framed as After Effects places a PDF or `.ai` + (`Framing::Placed`, `parse_page_framed`): the page's own ArtBox clipped to the CropBox (else + MediaBox) when it has one, else the CropBox, else the MediaBox, with `/Rotate` ignored + (measured in After Effects 2026 with own files, #3099). Not measured: a CropBox without an + ArtBox, files saved by Illustrator itself, `.pdf` names. Content/image filters remain app-owned: Flate (with PNG predictors), LZW, ASCIIHex, ASCII85, RunLength and CCITTFax. Encrypted files remain refused; `page_count` returns zero when the reader refuses a document. @@ -138,7 +144,7 @@ ffmpeg elsewhere) to check the code tables against an independent implementation ## Shared parser setup and bounds The workspace pins `craft-pdf` to `craft-libs` Git revision -`92d392cff132eaf53e13afff77f38b5c11b73aa0`, with `default-features = false` and only the explicit `read` +`e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545`, with `default-features = false` and only the explicit `read` feature. This excludes the backend's bundled fonts and Adobe CMaps and preserves EffectCraft's font and asset policies. The shared parser does not change the supported drawing operators, image codecs, continuously rasterized SVG tree, editable shapes, or EPS interpreter. diff --git a/crates/pdf/src/build.rs b/crates/pdf/src/build.rs index 0b1586f89..0f295a045 100644 --- a/crates/pdf/src/build.rs +++ b/crates/pdf/src/build.rs @@ -7,6 +7,9 @@ use effectcraft_svg::{Affine, BezPath, FillRule, Geom, Group, Node, Paint, Shape /// PostScript program, or the PDF content stream. pub(crate) const MAX_PATH: usize = 1 << 20; +/// The deepest the open groups nest (the render tree and its consumers recurse through them). +const MAX_DEPTH: usize = 256; + #[derive(Clone, Copy, PartialEq, Eq)] enum Kind { Plain, @@ -20,6 +23,9 @@ pub(crate) struct Builder { pub top_layers: Vec, pub skipped: Vec, pub shapes: usize, + /// Groups the finished nodes will sit under once placed (an enclosing builder's open groups + /// and the pattern or mask groups around them), counted against [`MAX_DEPTH`]. + base: usize, } pub(crate) fn group(name: &str) -> Group { @@ -28,13 +34,25 @@ pub(crate) fn group(name: &str) -> Group { impl Builder { pub fn new() -> Builder { - Builder { stack: vec![(group("page"), Kind::Plain)], top_layers: vec![], skipped: vec![], shapes: 0 } + Builder { stack: vec![(group("page"), Kind::Plain)], top_layers: vec![], skipped: vec![], shapes: 0, base: 0 } + } + + /// A builder for content that will be placed inside this one's open groups and `wrap` more + /// groups (a pattern's `Pattern` and `Tile`, a soft mask's two), so its nesting limit counts + /// them. + pub fn nested(&self, wrap: usize) -> Builder { + Builder { base: self.base.saturating_add(self.stack.len()).saturating_add(wrap), ..Builder::new() } } pub fn depth(&self) -> usize { self.stack.len() } + /// `wrap` more groups fit under the open ones within [`MAX_DEPTH`]. + pub fn has_room(&self, wrap: usize) -> bool { + self.base.saturating_add(self.stack.len()).saturating_add(wrap) <= MAX_DEPTH + } + pub fn skip(&mut self, what: &str) { if !self.skipped.iter().any(|s| s == what) { self.skipped.push(what.to_string()); @@ -62,23 +80,33 @@ impl Builder { } } + /// Open `g` as the group drawn into from now on; past [`MAX_DEPTH`] the group is dropped + /// (what would have been drawn inside it goes to the open group) and noted as skipped. + fn push_group(&mut self, g: Group, kind: Kind) { + if self.base.saturating_add(self.stack.len()) >= MAX_DEPTH { + self.skip("group nesting limit"); + return; + } + self.stack.push((g, kind)); + } + /// Children drawn from now on are clipped by `path` (page space) until the group closes. pub fn clip(&mut self, path: BezPath, rule: FillRule) { let mut g = group("Clip Group"); g.clip.push((path, rule)); // Clipping is not a transparency group: blend modes inside reach the backdrop. g.isolated = false; - self.stack.push((g, Kind::Clip)); + self.push_group(g, Kind::Clip); } /// Open an optional-content layer (or a named group). pub fn open(&mut self, name: &str, layer: bool) { - self.stack.push((group(name), if layer { Kind::Layer } else { Kind::Plain })); + self.push_group(group(name), if layer { Kind::Layer } else { Kind::Plain }); } /// Open a group (blend mode, soft mask) closed with the graphics state. pub fn open_group(&mut self, g: Group) { - self.stack.push((g, Kind::Plain)); + self.push_group(g, Kind::Plain); } /// Add a finished node (an image, pattern tiles). diff --git a/crates/pdf/src/ccitt.rs b/crates/pdf/src/ccitt.rs index fa013161f..ca6a40d21 100644 --- a/crates/pdf/src/ccitt.rs +++ b/crates/pdf/src/ccitt.rs @@ -401,8 +401,10 @@ fn mode(r: &mut Reader) -> Option { /// (index parity: even indices start black runs), and the one after it. fn b1b2(refl: &[usize], a0: i64, white: bool, columns: usize) -> (usize, usize) { let want = if white { 0 } else { 1 }; - let mut i = 0; - while i < refl.len() && (refl[i] as i64 <= a0 || i % 2 != want) { + // The changing elements are in order, so the first past `a0` is found by bisection (a scan + // from the start made every row quadratic in its transitions). + let mut i = refl.partition_point(|&c| c as i64 <= a0); + if i % 2 != want { i += 1; } let b1 = refl.get(i).copied().unwrap_or(columns); @@ -804,4 +806,24 @@ pub(crate) mod tests { let _ = decode(&garbage, &Params { k, columns: 1, rows: 0, ..Params::default() }, 1 << 20); } } + + /// `b1b2` by bisection agrees with the scan it replaced, for every position and colour + /// over a dense reference row. + #[test] + fn b1b2_by_bisection_matches_the_scan() { + let scan = |refl: &[usize], a0: i64, white: bool, columns: usize| { + let want = if white { 0 } else { 1 }; + let mut i = 0; + while i < refl.len() && (refl[i] as i64 <= a0 || i % 2 != want) { + i += 1; + } + (refl.get(i).copied().unwrap_or(columns), refl.get(i + 1).copied().unwrap_or(columns)) + }; + let refl: Vec = (0..64).map(|i| i * 3 / 2).collect(); + for a0 in -1..100 { + for white in [true, false] { + assert_eq!(b1b2(&refl, a0, white, 100), scan(&refl, a0, white, 100), "a0 {a0} white {white}"); + } + } + } } diff --git a/crates/pdf/src/cff.rs b/crates/pdf/src/cff.rs index 61bb7f9eb..cb7214cc2 100644 --- a/crates/pdf/src/cff.rs +++ b/crates/pdf/src/cff.rs @@ -538,16 +538,31 @@ impl Cff { /// A glyph's outline in glyph space (`font_matrix` maps it to text space) and its advance. pub fn outline(&self, gid: u16) -> Option<(BezPath, f64)> { - self.outline_depth(gid, 0) + self.outline_depth(gid, 0, &mut { MAX_GLYPH_OPS }) } - fn outline_depth(&self, gid: u16, depth: usize) -> Option<(BezPath, f64)> { + /// `ops` is the glyph's instruction budget, shared by the base glyph and its seac components. + fn outline_depth(&self, gid: u16, depth: usize, ops: &mut usize) -> Option<(BezPath, f64)> { let r = self.charstrings.get(gid as usize)?.clone(); let fd = self.fdselect.get(gid as usize).copied().unwrap_or(0) as usize; let fd = fd.min(self.lsubrs.len() - 1); - let mut st = - T2 { cff: self, fd, path: BezPath::new(), x: 0.0, y: 0.0, stack: vec![], stems: 0, width: None, open: false, done: false, depth: 0, seac: None }; + let mut st = T2 { + cff: self, + fd, + path: BezPath::new(), + x: 0.0, + y: 0.0, + stack: vec![], + stems: 0, + width: None, + open: false, + done: false, + depth: 0, + ops: *ops, + seac: None, + }; st.run(&self.data[r]); + *ops = st.ops; if st.open { st.path.close_path(); } @@ -563,10 +578,10 @@ impl Cff { && depth < 2 { let find = |code: u8| crate::encoding::Base::Standard.name(code).and_then(|n| self.gid_by_name(&n)); - if let Some((bp, _)) = find(b).and_then(|g| self.outline_depth(g, depth + 1)) { + if let Some((bp, _)) = find(b).and_then(|g| self.outline_depth(g, depth + 1, ops)) { path.extend(bp); } - if let Some((ap, _)) = find(a).and_then(|g| self.outline_depth(g, depth + 1)) { + if let Some((ap, _)) = find(a).and_then(|g| self.outline_depth(g, depth + 1, ops)) { path.extend(kurbo::Affine::translate((adx, ady)) * ap); } } @@ -646,9 +661,16 @@ struct T2<'a> { open: bool, done: bool, depth: usize, + /// Instructions this glyph may still run, across its subroutine calls. + ops: usize, seac: Option<(f64, f64, u8, u8)>, } +/// The most charstring instructions one glyph runs: subroutines that branch (two calls each, +/// ten levels deep) would otherwise multiply a small font into unbounded work and geometry. +/// A real glyph runs a few hundred. +pub(crate) const MAX_GLYPH_OPS: usize = 100_000; + impl T2<'_> { fn move_to(&mut self, dx: f64, dy: f64) { if self.open { @@ -698,6 +720,11 @@ impl T2<'_> { } let mut i = 0; while i < cs.len() && !self.done { + let Some(left) = self.ops.checked_sub(1) else { + self.done = true; + return; + }; + self.ops = left; let b0 = cs[i]; i += 1; match b0 { @@ -958,6 +985,12 @@ impl T2<'_> { /// named by custom strings. #[cfg(test)] pub(crate) fn write_test_cff(glyphs: &[(&str, Vec)]) -> Vec { + write_test_cff_with_gsubrs(glyphs, &[]) +} + +/// [`write_test_cff`] with global subroutines. +#[cfg(test)] +pub(crate) fn write_test_cff_with_gsubrs(glyphs: &[(&str, Vec)], gsubrs: &[Vec]) -> Vec { fn idx(items: &[Vec]) -> Vec { let mut out = (items.len() as u16).to_be_bytes().to_vec(); if items.is_empty() { @@ -983,7 +1016,7 @@ pub(crate) fn write_test_cff(glyphs: &[(&str, Vec)]) -> Vec { let names = idx(&[b"Test".to_vec()]); let strings: Vec> = glyphs.iter().skip(1).map(|(n, _)| n.as_bytes().to_vec()).collect(); let strings_idx = idx(&strings); - let gsubrs = idx(&[]); + let gsubrs = idx(gsubrs); let cs = idx(&glyphs.iter().map(|(_, c)| c.clone()).collect::>()); // charset format 0: SIDs of glyphs 1.. (custom strings from 391). let mut charset = vec![0u8]; @@ -1090,6 +1123,43 @@ mod tests { assert!(p.elements().is_empty()); } + /// A global subroutine that calls itself ten times: 10^10 calls within the depth limit of + /// ten. The glyph stops at its instruction budget instead. + #[test] + fn branching_subroutines_stop_at_the_instruction_budget() { + // `-107 callgsubr` (bias 107) is subroutine 0. + let call = [32u8, 29]; + let mut subr = call.repeat(10); + subr.push(11); + let mut cs = call.to_vec(); + cs.push(14); + let font = write_test_cff_with_gsubrs(&[(".notdef", vec![14]), ("A", cs)], &[subr]); + let cff = Cff::parse(&font).unwrap(); + let (p, _) = cff.outline(cff.gid_by_name("A").unwrap()).unwrap(); + assert!(p.elements().is_empty()); + } + + /// The instruction budget is one per glyph: a seac whose base glyph spends all of it leaves + /// nothing for the accent, instead of each component getting a fresh budget. + #[test] + fn seac_components_share_the_instruction_budget() { + let call = [32u8, 29]; + let mut subr = call.repeat(10); + subr.push(11); + // A square, then the branching subroutine that exhausts the budget. + let mut a = vec![139 + 100, 139 + 100, 139 - 100, 6]; + a.extend(call); + a.push(14); + // `adx ady bchar achar endchar` with both components 'A' (standard code 65). + let seac = vec![139 + 10, 139 + 20, 139 + 65, 139 + 65, 14]; + let font = write_test_cff_with_gsubrs(&[(".notdef", vec![14]), ("A", a), ("Aacute", seac)], &[subr]); + let cff = Cff::parse(&font).unwrap(); + let (alone, _) = cff.outline(cff.gid_by_name("A").unwrap()).unwrap(); + let (both, _) = cff.outline(cff.gid_by_name("Aacute").unwrap()).unwrap(); + assert!(!alone.elements().is_empty()); + assert_eq!(both.elements().len(), alone.elements().len(), "the accent gets no budget after the base spent it"); + } + /// A CFF whose top DICT points its Private DICT at offsets near `usize::MAX`: `size` and `off` /// come from the file, and reading the Private DICT must not overflow `off + size`. #[test] diff --git a/crates/pdf/src/color.rs b/crates/pdf/src/color.rs index 6943476bc..5a7e9af86 100644 --- a/crates/pdf/src/color.rs +++ b/crates/pdf/src/color.rs @@ -215,19 +215,44 @@ pub enum PsOp { Proc(Vec), } -fn ps_parse(lx: &mut crate::object::Lexer, depth: usize) -> Vec { +/// Parse a procedure. `ops` counts the tokens read (those skipped as unsupported included); past +/// [`MAX_CALC_OPS`] the rest is not read, so an oversized program is never fully scanned or built +/// (the caller rejects it when `ops` ends past the cap). +fn ps_parse(lx: &mut crate::object::Lexer, depth: usize, ops: &mut usize) -> Vec { let mut out = vec![]; - while let Some(o) = lx.next() { - match o { - Obj::Num(n) => out.push(PsOp::Num(n)), - Obj::Bool(b) => out.push(PsOp::Num(if b { 1.0 } else { 0.0 })), - Obj::Op(op) if op == "{" && depth < 32 => out.push(PsOp::Proc(ps_parse(lx, depth + 1))), - // Nested too deep: skip the procedure's opening brace (never push it as an operator). - Obj::Op(op) if op == "{" => {} - Obj::Op(op) if op == "}" => return out, - Obj::Op(op) => out.push(PsOp::Op(op)), - _ => {} + loop { + // A calculator holds no arrays or dictionaries: one is skipped as a single token without + // being built (the lexer would allocate every element before this counted it). + if lx.at_compound() { + if *ops > MAX_CALC_OPS { + break; + } + lx.skip_compound(); + *ops += 1; + continue; } + let Some(o) = lx.next() else { break }; + if *ops > MAX_CALC_OPS { + break; + } + let op = match o { + Obj::Num(n) => PsOp::Num(n), + Obj::Bool(b) => PsOp::Num(if b { 1.0 } else { 0.0 }), + Obj::Op(op) if op == "{" && depth < 32 => PsOp::Proc(ps_parse(lx, depth + 1, ops)), + // Nested too deep: skip the procedure's opening brace (never push it as an operator). + Obj::Op(op) if op == "{" => { + *ops += 1; + continue; + } + Obj::Op(op) if op == "}" => return out, + Obj::Op(op) => PsOp::Op(op), + _ => { + *ops += 1; + continue; + } + }; + *ops += 1; + out.push(op); } out } @@ -243,6 +268,15 @@ fn ps_push(st: &mut Vec, v: f64) { } } +/// The most operators and operands a calculator program may hold (nested procedures included). +/// It has no loops, so this bounds what one evaluation runs; real programs hold a few dozen. +const MAX_CALC_OPS: usize = 4096; + +/// The operators and operands in `code`, nested procedures included. +fn ps_len(code: &[PsOp]) -> usize { + code.iter().map(|op| if let PsOp::Proc(p) = op { 1 + ps_len(p) } else { 1 }).sum() +} + fn ps_run(code: &[PsOp], st: &mut Vec, depth: usize) { if depth > 32 { return; @@ -431,6 +465,12 @@ impl Budget { Budget { nodes: MAX_NODES, samples: MAX_SAMPLES, overrun: false } } + /// Charge `n` retained values (coefficients, bounds, program operators) as nodes, eight to a + /// node, so a cached copy of a function is charged for what it holds, not just its node. + fn take_values(&mut self, n: usize) -> bool { + self.take_nodes(n.div_ceil(8)) + } + /// Charge `n` nodes; `false` (and the read is abandoned) once the cap is passed. fn take_nodes(&mut self, n: usize) -> bool { match self.nodes.checked_sub(n) { @@ -484,7 +524,8 @@ impl Func { /// [`Func::read`] nested `depth` levels deep, charging `budget`: unsupported past [`MAX_DEPTH`] /// or once the budget is spent. fn read_at(file: &File, o: &Obj, depth: usize, budget: &mut Budget) -> Func { - if depth >= MAX_DEPTH || !budget.take_nodes(1) { + // Charged first: the fallback past the depth limit is a node a copy keeps too. + if !budget.take_nodes(1) || depth >= MAX_DEPTH { return Func::Unsupported; } let o = file.resolve(o); @@ -499,12 +540,14 @@ impl Func { let dom = file.get(d, "Domain").map(|x| file.nums(x)).unwrap_or_default(); let domain = [dom.first().copied().unwrap_or(0.0), dom.get(1).copied().unwrap_or(1.0)]; match file.get_num(d, "FunctionType").unwrap_or(-1.0) as i32 { - 2 => Func::Exp { - domain, - c0: file.get(d, "C0").map(|x| file.nums(x)).unwrap_or_else(|| vec![0.0]), - c1: file.get(d, "C1").map(|x| file.nums(x)).unwrap_or_else(|| vec![1.0]), - n: file.get_num(d, "N").unwrap_or(1.0), - }, + 2 => { + let c0 = file.get(d, "C0").map(|x| file.nums(x)).unwrap_or_else(|| vec![0.0]); + let c1 = file.get(d, "C1").map(|x| file.nums(x)).unwrap_or_else(|| vec![1.0]); + if !budget.take_values(c0.len() + c1.len()) { + return Func::Unsupported; + } + Func::Exp { domain, c0, c1, n: file.get_num(d, "N").unwrap_or(1.0) } + } 3 => { // A stitching function's pieces: no element cap (a repeating gradient lists one // piece once per repeat); the budget bounds the total work. @@ -513,12 +556,12 @@ impl Func { None => Some(vec![]), }; let Some(funcs) = funcs else { return Func::Unsupported }; - Func::Stitch { - domain, - funcs, - bounds: file.get(d, "Bounds").map(|x| file.nums(x)).unwrap_or_default(), - encode: file.get(d, "Encode").map(|x| file.nums(x)).unwrap_or_default(), + let bounds = file.get(d, "Bounds").map(|x| file.nums(x)).unwrap_or_default(); + let encode = file.get(d, "Encode").map(|x| file.nums(x)).unwrap_or_default(); + if !budget.take_values(bounds.len() + encode.len()) { + return Func::Unsupported; } + Func::Stitch { domain, funcs, bounds, encode } } 0 => { let Obj::Stream(sd, raw) = o else { return Func::Unsupported }; @@ -537,6 +580,10 @@ impl Func { if !budget.take_samples(count) { return Func::Unsupported; } + // The stream must hold the table: missing bytes are not made up as zeros. + if count.checked_mul(bps).is_none_or(|bits| bits.div_ceil(8) > data.len()) { + return Func::Unsupported; + } let enc = file.get(d, "Encode").map(|x| file.nums(x)).unwrap_or_default(); let encode = [enc.first().copied().unwrap_or(0.0), enc.get(1).copied().unwrap_or(size as f64 - 1.0)]; let decode = file.get(d, "Decode").map(|x| file.nums(x)).filter(|v| v.len() >= outputs * 2).unwrap_or_else(|| range.clone()); @@ -567,10 +614,15 @@ impl Func { let Some(data) = decode_stream(file, sd, raw) else { return Func::Unsupported }; let mut lx = crate::object::Lexer::new(&data, 0); // The program is one procedure: `{ … }`. - let code = match ps_parse(&mut lx, 0).into_iter().next() { + let mut scanned = 0; + let code = match ps_parse(&mut lx, 0, &mut scanned).into_iter().next() { Some(PsOp::Proc(p)) => p, _ => return Func::Unsupported, }; + let ops = ps_len(&code); + if scanned > MAX_CALC_OPS || ops > MAX_CALC_OPS || !budget.take_values(ops) { + return Func::Unsupported; + } Func::Calc { domain: dom, range: file.get(d, "Range").map(|x| file.nums(x)).unwrap_or_default(), code } } _ => Func::Unsupported, @@ -756,12 +808,56 @@ mod tests { assert_eq!(sample_count(1 << 22, usize::MAX / (1 << 22) + 1), None); } + #[test] + fn oversized_calculator_program_is_cut_short() { + let src = format!("{{ {}}}", "1 ".repeat(MAX_CALC_OPS + 10)); + let mut lx = crate::object::Lexer::new(src.as_bytes(), 0); + let Some(PsOp::Proc(code)) = ps_parse(&mut lx, 0, &mut 0).into_iter().next() else { panic!() }; + assert_eq!(ps_len(&code), MAX_CALC_OPS + 1); + } + + #[test] + fn arrays_and_dictionaries_in_a_calculator_are_skipped_whole() { + // Strings with brackets, nested arrays and a dictionary are one skipped token each; the + // operators around them still parse. + let src = b"{ 1 [ (a]b) [1 2] << /K [3 4] /S (>>) >> 5 ] 2 add << /A 1 >> mul }"; + let mut lx = crate::object::Lexer::new(src, 0); + let Some(PsOp::Proc(code)) = ps_parse(&mut lx, 0, &mut 0).into_iter().next() else { panic!() }; + assert_eq!(code, vec![PsOp::Num(1.0), PsOp::Num(2.0), PsOp::Op("add".into()), PsOp::Op("mul".into())]); + // A huge array is skipped once the cap is passed, not read to its end. + let src = format!("{{ [ {}] 1 }}", "0 ".repeat(MAX_CALC_OPS * 100)); + let mut lx = crate::object::Lexer::new(src.as_bytes(), 0); + let mut scanned = 0; + let Some(PsOp::Proc(code)) = ps_parse(&mut lx, 0, &mut scanned).into_iter().next() else { panic!() }; + assert_eq!(code, vec![PsOp::Num(1.0)]); + // A large string inside a skipped array is passed over, not decoded: escapes, nested + // parentheses, a hexadecimal string and names all end where the lexer would end them. + let big = format!("{{ [ ({}) <{}> /{} (a\\)b(c)) 7 ] 1 }}", "x".repeat(1 << 20), "ab".repeat(1 << 19), "N".repeat(1 << 10)); + let mut lx = crate::object::Lexer::new(big.as_bytes(), 0); + let Some(PsOp::Proc(code)) = ps_parse(&mut lx, 0, &mut 0).into_iter().next() else { panic!() }; + assert_eq!(code, vec![PsOp::Num(1.0)]); + // An unclosed one ends at the end of the data. + let mut lx = crate::object::Lexer::new(b"[ 1 2 ", 0); + lx.skip_compound(); + assert_eq!(lx.pos, 6); + } + + #[test] + fn skipped_calculator_tokens_count_toward_the_cap() { + // `null` is not a calculator token: skipped, but still scanned. + let src = format!("{{ {}}}", "null ".repeat(MAX_CALC_OPS + 10)); + let mut lx = crate::object::Lexer::new(src.as_bytes(), 0); + let mut scanned = 0; + ps_parse(&mut lx, 0, &mut scanned); + assert!(scanned > MAX_CALC_OPS && scanned < MAX_CALC_OPS + 10, "parsing stops once the cap is passed ({scanned})"); + } + #[test] fn calculator_functions() { // Two inputs → three outputs: { 2 copy mul 3 1 roll add 2 div dup 0.5 gt { pop 1 } if 0 } let code = b"{ 2 copy mul 3 1 roll add 2 div dup 0.5 gt { pop 1 } { 0.25 mul } ifelse 0 }"; let mut lx = crate::object::Lexer::new(code, 0); - let Some(PsOp::Proc(code)) = ps_parse(&mut lx, 0).into_iter().next() else { panic!() }; + let Some(PsOp::Proc(code)) = ps_parse(&mut lx, 0, &mut 0).into_iter().next() else { panic!() }; let f = Func::Calc { domain: vec![0.0, 1.0, 0.0, 1.0], range: vec![0.0, 1.0, 0.0, 1.0, 0.0, 1.0], code }; assert_eq!(f.eval(&[0.5, 0.4]), vec![0.2, 0.1125, 0.0]); assert_eq!(f.eval(&[1.0, 0.8]), vec![0.8, 1.0, 0.0]); @@ -771,7 +867,7 @@ mod tests { fn run(src: &str, mut st: Vec) -> Vec { let src = format!("{{ {src} }}"); let mut lx = crate::object::Lexer::new(src.as_bytes(), 0); - let Some(PsOp::Proc(code)) = ps_parse(&mut lx, 0).into_iter().next() else { panic!() }; + let Some(PsOp::Proc(code)) = ps_parse(&mut lx, 0, &mut 0).into_iter().next() else { panic!() }; ps_run(&code, &mut st, 0); st } diff --git a/crates/pdf/src/font.rs b/crates/pdf/src/font.rs index 64b0a1c3a..8bd91831e 100644 --- a/crates/pdf/src/font.rs +++ b/crates/pdf/src/font.rs @@ -211,6 +211,12 @@ fn utf16(b: &[u8]) -> String { String::from_utf16_lossy(&u) } +/// The most code → text mappings a CMap keeps (more than Unicode has code points), and the +/// longest destination string a `bfrange` is expanded with: a range of 65,536 codes would +/// otherwise multiply a long destination into gigabytes of text. +const MAX_UNICODE_MAPPINGS: usize = 1 << 20; +const MAX_RANGE_DST: usize = 256; + fn parse_cmap(data: &[u8]) -> CMap { let mut m = CMap::default(); let mut lx = Lexer::new(data, 0); @@ -239,6 +245,9 @@ fn parse_cmap(data: &[u8]) -> CMap { } "bfchar" => { for p in a.as_chunks::<2>().0 { + if m.unicode.len() >= MAX_UNICODE_MAPPINGS { + break; + } if let (Obj::Str(src), Obj::Str(dst)) = (&p[0], &p[1]) { m.unicode.insert(be(src), utf16(dst)); } @@ -252,9 +261,12 @@ fn parse_cmap(data: &[u8]) -> CMap { continue; } match &p[2] { - Obj::Str(dst) => { + Obj::Str(dst) if dst.len() <= MAX_RANGE_DST => { let mut d = dst.clone(); for c in lo..=hi { + if m.unicode.len() >= MAX_UNICODE_MAPPINGS { + break; + } m.unicode.insert(c, utf16(&d)); if let Some(last) = d.last_mut() { *last = last.wrapping_add(1); @@ -263,6 +275,9 @@ fn parse_cmap(data: &[u8]) -> CMap { } Obj::Array(list) => { for (k, s) in list.iter().enumerate() { + if m.unicode.len() >= MAX_UNICODE_MAPPINGS { + break; + } if let (Obj::Str(s), Some(c)) = (s, lo.checked_add(k as u32)) { m.unicode.insert(c, utf16(s)); } diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 567dca9c0..ff914e759 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -92,8 +92,25 @@ pub fn parse(bytes: &[u8]) -> Result { /// Parse page `index` of a PDF (EPS files have one page). pub fn parse_page(bytes: &[u8], index: usize) -> Result { + parse_page_framed(bytes, index, Framing::Viewer) +} + +/// Which region of a PDF page becomes the document, and whether `/Rotate` turns it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Framing { + /// As a PDF viewer shows the page: its CropBox (else MediaBox), turned by `/Rotate`. + #[default] + Viewer, + /// As After Effects places a PDF or `.ai` as footage: the page's ArtBox clipped to the + /// CropBox (else MediaBox) when it has one, else the CropBox, else the MediaBox, with + /// `/Rotate` ignored (measured in After Effects 2026 with own files, #3099). + Placed, +} + +/// [`parse_page`] with the page framed as `framing` says (EPS files are their bounding box). +pub fn parse_page_framed(bytes: &[u8], index: usize, framing: Framing) -> Result { match sniff(bytes) { - Some(Format::Pdf) => parse_pdf(bytes, index), + Some(Format::Pdf) => parse_pdf(bytes, index, framing), Some(Format::Eps) => parse_eps(bytes), None => Err(Error::NotVector), } @@ -142,17 +159,22 @@ fn finish(nodes: Vec, flags: Vec, skipped: Vec, width: f64, Doc { width, height, root, skipped } } -fn parse_pdf(bytes: &[u8], index: usize) -> Result { +/// Page `index` of a PDF framed as `framing` says, as a document in points (y down). +fn parse_pdf(bytes: &[u8], index: usize, framing: Framing) -> Result { let file = object::File::parse(bytes)?; let pages = page::pages(&file); if pages.is_empty() { return Err(Error::NoPages); } let pg = pages.get(index).ok_or(Error::PageOutOfRange(index))?; - let [x0, y0, x1, y1] = pg.bbox; + let (frame, rotate) = match framing { + Framing::Viewer => (pg.bbox, pg.rotate), + Framing::Placed => (pg.art.unwrap_or(pg.bbox), 0), + }; + let [x0, y0, x1, y1] = frame; let (w, h) = (x1 - x0, y1 - y0); // Default user space (y up) → document pixels (y down), with the page's /Rotate. - let (to_doc, dw, dh) = match pg.rotate { + let (to_doc, dw, dh) = match rotate { 90 => (Affine::new([0.0, 1.0, 1.0, 0.0, -y0, -x0]), h, w), 180 => (Affine::new([-1.0, 0.0, 0.0, 1.0, x1, -y0]), w, h), 270 => (Affine::new([0.0, -1.0, -1.0, 0.0, y1, x1]), h, w), diff --git a/crates/pdf/src/object.rs b/crates/pdf/src/object.rs index 79a91dde8..df475a4bb 100644 --- a/crates/pdf/src/object.rs +++ b/crates/pdf/src/object.rs @@ -82,6 +82,91 @@ impl<'a> Lexer<'a> { } } + /// Whether the next token opens an array or a dictionary (skipping white space first). + pub fn at_compound(&mut self) -> bool { + self.skip_ws(); + match self.data.get(self.pos) { + Some(b'[') => true, + Some(b'<') => self.data.get(self.pos + 1) == Some(&b'<'), + _ => false, + } + } + + /// Skip the array or dictionary at the current position (see [`Lexer::at_compound`]) as + /// [`Lexer::next`] would read it, without building it: for readers that have no use for one + /// and must not allocate a vector per element of a hostile stream. + pub fn skip_compound(&mut self) { + let mut open = 0usize; + loop { + self.skip_ws(); + match self.data.get(self.pos) { + None => return, + Some(b'[') => { + open += 1; + self.pos += 1; + } + Some(b'<') if self.data.get(self.pos + 1) == Some(&b'<') => { + open += 1; + self.pos += 2; + } + Some(b']') | Some(b'>') if self.data[self.pos] == b']' || self.data.get(self.pos + 1) == Some(&b'>') => { + open = open.saturating_sub(1); + self.pos += if self.data[self.pos] == b']' { 1 } else { 2 }; + if open == 0 { + return; + } + } + // Anything else is one token (a string, name, number or word), passed over + // without building it. + Some(_) => self.skip_scalar(), + } + } + } + + /// Pass over one token that is not an array or dictionary bracket, as [`Lexer::next`] reads + /// it but without building its value. + fn skip_scalar(&mut self) { + let Some(&c) = self.data.get(self.pos) else { return }; + match c { + b'(' => { + // A literal string: balanced parentheses, a backslash escapes the next byte. + let mut depth = 0usize; + while let Some(&d) = self.data.get(self.pos) { + self.pos += 1; + match d { + b'\\' => self.pos += 1, + b'(' => depth += 1, + b')' => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + } + self.pos = self.pos.min(self.data.len()); + } + b'<' => { + // A hexadecimal string. + while self.data.get(self.pos).is_some_and(|d| *d != b'>') { + self.pos += 1; + } + self.pos = (self.pos + 1).min(self.data.len()); + } + b'/' => { + self.pos += 1; + self.word(); + } + b']' | b'{' | b'}' | b')' | b'>' => self.pos += 1, + _ => { + if self.word().is_empty() { + self.pos += 1; + } + } + } + } + fn word(&mut self) -> &'a [u8] { let s = self.pos; while self.pos < self.data.len() && !is_white(self.data[self.pos]) && !is_delim(self.data[self.pos]) { diff --git a/crates/pdf/src/page.rs b/crates/pdf/src/page.rs index b7eb70fe0..ba67b39aa 100644 --- a/crates/pdf/src/page.rs +++ b/crates/pdf/src/page.rs @@ -23,6 +23,9 @@ pub struct Page { pub resources: Dict, /// CropBox (else MediaBox) `[x0, y0, x1, y1]`. pub bbox: [f64; 4], + /// The page's own ArtBox clipped to [`Page::bbox`] (ISO 32000-1 §14.11.2), when it has one + /// that keeps an area there; not inherited (table 30). + pub art: Option<[f64; 4]>, pub rotate: i32, } @@ -31,13 +34,15 @@ pub fn pages(file: &File) -> Vec { let mut out = vec![]; let Some(cat) = file.catalog() else { return out }; let Some(root) = file.get_dict(cat, "Pages") else { return out }; + /// Collects the pages under `node`, passing on the attributes pages inherit (resources, + /// MediaBox, CropBox, /Rotate); bounded in depth and page count. fn walk(file: &File, node: &Dict, inherited: (Option, Option>, Option>, i32), out: &mut Vec, depth: usize) { if depth > 32 || out.len() > 10_000 { return; } let res = file.get_dict(node, "Resources").cloned().or(inherited.0); - let media = file.get(node, "MediaBox").map(|m| file.nums(m)).filter(|v| v.len() == 4).or(inherited.1); - let crop = file.get(node, "CropBox").map(|m| file.nums(m)).filter(|v| v.len() == 4).or(inherited.2); + let media = file.get(node, "MediaBox").map(|m| file.nums(m)).filter(|v| is_area(v)).or(inherited.1); + let crop = file.get(node, "CropBox").map(|m| file.nums(m)).filter(|v| is_area(v)).or(inherited.2); let rot = file.get_num(node, "Rotate").map(|r| r as i32).unwrap_or(inherited.3); match file.get(node, "Kids").and_then(Obj::array) { Some(kids) if file.get(node, "Type").and_then(Obj::name) != Some("Page") => { @@ -49,8 +54,16 @@ pub fn pages(file: &File) -> Vec { } _ => { let b = crop.or(media).unwrap_or_else(|| vec![0.0, 0.0, 612.0, 792.0]); - let bbox = [b[0].min(b[2]), b[1].min(b[3]), b[0].max(b[2]), b[1].max(b[3])]; - out.push(Page { dict: node.clone(), resources: res.unwrap_or_default(), bbox, rotate: rot.rem_euclid(360) }); + let bbox = normalized(&b).unwrap_or([0.0, 0.0, 612.0, 792.0]); + // The ArtBox is the page's own (not inherited), clipped to the crop box. + let art = file + .get(node, "ArtBox") + .map(|m| file.nums(m)) + .filter(|v| is_area(v)) + .and_then(|v| normalized(&v)) + .map(|a| [a[0].max(bbox[0]), a[1].max(bbox[1]), a[2].min(bbox[2]), a[3].min(bbox[3])]) + .filter(|a| a[2] > a[0] && a[3] > a[1]); + out.push(Page { dict: node.clone(), resources: res.unwrap_or_default(), bbox, art, rotate: rot.rem_euclid(360) }); } } } @@ -58,6 +71,26 @@ pub fn pages(file: &File) -> Vec { out } +/// A box `[x0, y0, x1, y1]` (corners in any order) with finite corners and a finite span that +/// encloses an area. +fn is_area(v: &[f64]) -> bool { + match v { + [x0, y0, x1, y1] => { + let (w, h) = (x1 - x0, y1 - y0); + v.iter().all(|c| c.is_finite()) && w.is_finite() && h.is_finite() && w.abs() > 0.0 && h.abs() > 0.0 + } + _ => false, + } +} + +/// A box with its corners ordered (`x0 < x1`, `y0 < y1`), `None` unless [`is_area`]. +fn normalized(v: &[f64]) -> Option<[f64; 4]> { + match v { + [x0, y0, x1, y1] if is_area(v) => Some([x0.min(*x1), y0.min(*y1), x0.max(*x1), y0.max(*y1)]), + _ => None, + } +} + /// The page's content streams, decoded and joined. pub fn page_content(file: &File, page: &Page) -> Vec { let mut out = vec![]; @@ -636,7 +669,12 @@ impl<'a> Interp<'a> { let bc = f.get(&sm, "BC").map(|b| f.nums(b)).unwrap_or_default(); let gcs = f.get_dict(&gd, "Group").and_then(|gr| f.get(gr, "CS")).map(|c| color_space(f, c, Some(res))).unwrap_or(Cs::Rgb); let backdrop = if bc.is_empty() { [0.0; 3] } else { gcs.to_rgb(&bc) }; - let saved_b = std::mem::replace(&mut self.b, Builder::new()); + // The mask it replaces closes first: its groups don't enclose the new one. + if let Some(d) = self.gs.mask_depth { + self.close_to(d); + } + let inner = self.b.nested(2); + let saved_b = std::mem::replace(&mut self.b, inner); let ctm = self.gs.ctm; let saved_gs = std::mem::replace(&mut self.gs, GState { ctm, ..GState::default() }); let saved_stack = std::mem::take(&mut self.saved); @@ -648,9 +686,6 @@ impl<'a> Interp<'a> { for s in sk { self.b.skip(&s); } - if let Some(d) = self.gs.mask_depth { - self.close_to(d); - } let mut content = Group::new("Soft Mask"); content.children = nodes; let mut grp = Group::new("Soft Mask Group"); @@ -751,8 +786,15 @@ impl<'a> Interp<'a> { if depth > 8 { return; } + // The `Pattern` and `Tile` wrappers must fit under the open groups too. + if !self.b.has_room(2) { + self.b.skip("group nesting limit"); + return; + } // The cell, drawn once in pattern space. - let saved_b = std::mem::replace(&mut self.b, Builder::new()); + // The cell ends up under the open groups and this pattern's `Pattern` and `Tile`. + let inner = self.b.nested(2); + let saved_b = std::mem::replace(&mut self.b, inner); let saved_gs = std::mem::take(&mut self.gs); let saved_stack = std::mem::take(&mut self.saved); let saved_path = std::mem::take(&mut self.path); diff --git a/crates/pdf/src/ps/builtin.rs b/crates/pdf/src/ps/builtin.rs index dcafa9417..a19aeb6da 100644 --- a/crates/pdf/src/ps/builtin.rs +++ b/crates/pdf/src/ps/builtin.rs @@ -1,4 +1,5 @@ use super::eps::find_from; +use super::exec::MAX_STACK; use super::scanner::Src; use super::text::encoding_array; use super::value::{Flow, V, array, matrix_of, matrix_val, new_dict}; @@ -181,8 +182,13 @@ impl Interp { match self.pop() { V::Num(k) => { let k = (k.max(0.0) as usize).min(self.st.len()); - let tail: Vec = self.st[self.st.len() - k..].to_vec(); - self.st.extend(tail); + // A copy past the operand limit copies nothing, and the values copied + // count as operations (one for eight): repeated doubling spends the budget. + if self.st.len().saturating_add(k) <= MAX_STACK { + self.charge(k / 8); + let tail: Vec = self.st[self.st.len() - k..].to_vec(); + self.st.extend(tail); + } } V::Array(dst) => { let s = self.pop().items().unwrap_or_default(); @@ -507,12 +513,16 @@ impl Interp { fn try_collection_op(&mut self, n: &str) -> bool { match n { // Arrays and strings. + // The storage made counts as operations (a value, or eight bytes, each), so a loop + // of large constructors spends the budget rather than the memory. "array" => { let k = self.popn().clamp(0.0, 1e6) as usize; + self.charge(k); self.push(array(vec![V::Null; k])); } "string" => { let k = self.popn().clamp(0.0, 1e7) as usize; + self.charge(k / 8); self.push(V::Str(Rc::new(RefCell::new(vec![0; k])))); } "length" => { diff --git a/crates/pdf/src/ps/eps.rs b/crates/pdf/src/ps/eps.rs index 90d60cfbe..8fb72698a 100644 --- a/crates/pdf/src/ps/eps.rs +++ b/crates/pdf/src/ps/eps.rs @@ -19,7 +19,8 @@ pub fn eps_parts(bytes: &[u8]) -> Option<(&[u8], [f64; 4])> { if v.len() == 4 && v[2] > v[0] && v[3] > v[1] { return Some([v[0], v[1], v[2], v[3]]); } - from = s; + // A rejected comment is done with: the scan goes on past its line, not over it again. + from = e; } None }; @@ -31,8 +32,15 @@ pub(super) fn find_from(hay: &[u8], needle: &[u8], from: usize) -> Option hay.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|p| p + from) } -fn rfind_before(hay: &[u8], needle: &[u8], to: usize) -> Option { - hay.get(..to)?.windows(needle.len()).rposition(|w| w == needle) +/// Every position of `needle` in `hay`, in order (one pass over the file). +fn positions(hay: &[u8], needle: &[u8]) -> Vec { + let mut out = vec![]; + let mut from = 0; + while let Some(p) = find_from(hay, needle, from) { + out.push(p); + from = p + needle.len(); + } + out } /// The name after `key` (`/FontName /Name`). @@ -48,20 +56,26 @@ fn name_after(b: &[u8], key: &[u8]) -> Option { /// … cleartomark`, hexadecimal or binary) and CFF font sets (`… StartData `). pub(super) fn embedded_fonts(ps: &[u8]) -> HashMap>, bool)> { let mut out = HashMap::new(); + // The headers are found once, in one pass each; every `eexec` then takes the last header + // before it that no earlier `eexec` has used, so no prefix of the file is searched again. + let mut heads = positions(ps, b"%!PS-AdobeFont"); + heads.extend(positions(ps, b"%!FontType1")); + heads.sort_unstable(); + let names = positions(ps, b"/FontName"); let mut from = 0; + let mut used = 0; while let Some(ee) = find_from(ps, b"eexec", from) { from = ee + 5; - let start = [b"%!PS-AdobeFont".as_slice(), b"%!FontType1"] - .iter() - .filter_map(|h| rfind_before(ps, h, ee)) - .max() - .or_else(|| rfind_before(ps, b"/FontName", ee).map(|p| p.saturating_sub(512))); + let last_before = |v: &[usize]| v[..v.partition_point(|&p| p < ee)].last().copied().filter(|&p| p >= used); + // The fallback look-back stops at the previous font's end, so it cannot pick up its header. + let start = last_before(&heads).or_else(|| last_before(&names).map(|p| p.saturating_sub(512).max(used))); let Some(start) = start else { continue }; let end = find_from(ps, b"cleartomark", ee).map_or(ps.len(), |p| p + 11); if let Some(name) = name_after(&ps[start..ee], b"/FontName") { out.insert(name, (Rc::new(ps[start..end].to_vec()), false)); } from = end; + used = end; } let mut from = 0; while let Some(sd) = find_from(ps, b"StartData", from) { @@ -77,3 +91,30 @@ pub(super) fn embedded_fonts(ps: &[u8]) -> HashMap>, bool)> } out } + +#[cfg(test)] +mod tests { + use super::embedded_fonts; + + #[test] + fn font_discovery_looks_back_once_per_header() { + // 20,000 `eexec` words before any font header: each used to search the whole prefix + // for a header again. The font after them is still found. + let mut ps = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); + ps.extend_from_slice("eexec ".repeat(20_000).as_bytes()); + ps.extend_from_slice(b"\n%!PS-AdobeFont-1.0: Real\n/FontName /Real def\ncurrentfile eexec\n0000\ncleartomark\n"); + let fonts = embedded_fonts(&ps); + assert_eq!(fonts.len(), 1); + assert!(fonts.contains_key("Real")); + } + + #[test] + fn header_less_font_after_a_short_one_does_not_take_its_header() { + let a = "%!PS-AdobeFont-1.0: A\n/FontName /A def\ncurrentfile eexec\n0000\ncleartomark\n"; + let b = "/FontName /B def\ncurrentfile eexec\n0000\ncleartomark\n"; + let ps = format!("%!PS-Adobe-3.0 EPSF-3.0\n{a}{b}"); + let fonts = embedded_fonts(ps.as_bytes()); + let (data, _) = fonts.get("B").expect("second font found"); + assert!(!String::from_utf8_lossy(data).contains("AdobeFont"), "{}", String::from_utf8_lossy(data)); + } +} diff --git a/crates/pdf/src/ps/exec.rs b/crates/pdf/src/ps/exec.rs index 27697527c..233ff82b0 100644 --- a/crates/pdf/src/ps/exec.rs +++ b/crates/pdf/src/ps/exec.rs @@ -6,6 +6,10 @@ use super::{Affine, BezPath, Builder, Cap, HashMap, Interp, Join}; /// The deepest procedure nesting run (deeper recursion stops the program). const MAX_CALL_DEPTH: usize = 256; +/// The most values the operand stack holds: a push past it is dropped, and `copy` copies +/// nothing rather than grow the stack past it. +pub(super) const MAX_STACK: usize = 100_000; + impl Interp { pub fn new(page: [f64; 4]) -> Interp { Interp { @@ -56,11 +60,17 @@ impl Interp { } pub(super) fn push(&mut self, v: V) { - if self.st.len() < 100_000 { + if self.st.len() < MAX_STACK { self.st.push(v); } } + /// Count `n` units of work (values copied, storage allocated) against the budget without + /// stopping the program here: once it is spent, the next operator stops it. + pub(super) fn charge(&mut self, n: usize) { + self.budget = self.budget.saturating_sub(n); + } + pub(super) fn lookup(&self, k: &str) -> Option { self.dicts.iter().rev().find_map(|d| d.borrow().get(k).cloned()) } diff --git a/crates/pdf/src/ps/paths.rs b/crates/pdf/src/ps/paths.rs index b1fe07092..30b5a7087 100644 --- a/crates/pdf/src/ps/paths.rs +++ b/crates/pdf/src/ps/paths.rs @@ -22,7 +22,7 @@ impl Interp { } /// Stop the program when a path of `len` elements would be longer than [`MAX_PATH`]. - fn path_fits(&mut self, len: usize) -> Result<(), Flow> { + pub(super) fn path_fits(&mut self, len: usize) -> Result<(), Flow> { if len <= MAX_PATH { return Ok(()); } diff --git a/crates/pdf/src/ps/text.rs b/crates/pdf/src/ps/text.rs index b138965bb..d4cee07f8 100644 --- a/crates/pdf/src/ps/text.rs +++ b/crates/pdf/src/ps/text.rs @@ -95,7 +95,14 @@ impl Interp { let ctm = self.gs.ctm; for (i, &code) in bytes.iter().enumerate() { let code = code as u32; + // Every input character costs at least one unit, so empty outlines are not free. + self.spend(1)?; if let Some(g) = font.glyph(code) { + // Each outline element counts against the path limit and the budget before it + // is copied, so a long string cannot expand into unbounded geometry. + let n = g.elements().len(); + self.path_fits(path.elements().len().saturating_add(n))?; + self.spend(n)?; path.extend(ctm * Affine::translate(p.to_vec2()) * m * (*g).clone()); } text.push_str(&font.unicode(code)); diff --git a/crates/pdf/src/shading.rs b/crates/pdf/src/shading.rs index df5e5f9c7..aa83adebf 100644 --- a/crates/pdf/src/shading.rs +++ b/crates/pdf/src/shading.rs @@ -18,6 +18,8 @@ const MAX_SIDE: f64 = 1024.0; const MAX_SCALE: f64 = 4.0; /// The most triangles one shading draws. const MAX_TRIANGLES: usize = 2_000_000; +/// How many times over the mesh raster may be covered by triangle bounding boxes in all. +const MAX_RASTER_PASSES: usize = 64; /// A mesh vertex: page-space position and its value (RGB, or `t` in `[0]` with a function). #[derive(Clone, Copy, Debug, PartialEq)] @@ -234,13 +236,17 @@ fn free_form(r: &mut Bits, l: &Layout, colors: &Colors, m: Affine) -> Vec<[V; 3] /// Type 5: a lattice of `per_row` vertices per row, two triangles per cell. fn lattice(r: &mut Bits, l: &Layout, colors: &Colors, m: Affine, per_row: usize) -> Vec<[V; 3]> { - if per_row < 2 { + if !(2..=MAX_TRIANGLES).contains(&per_row) { return vec![]; } let mut rows: Vec> = vec![]; let mut row = vec![]; while let (Some(p), Some(c)) = (l.point(r), l.comps(r)) { r.align(); + // Vertices kept, the unfinished row's included, stay within the triangle limit. + if (rows.len() * per_row).saturating_add(row.len()) >= MAX_TRIANGLES { + break; + } row.push(V { p: m * p, c: colors.value(&c) }); if row.len() == per_row { rows.push(std::mem::take(&mut row)); @@ -447,6 +453,9 @@ fn rasterize(tris: &[[V; 3]], colors: &Colors, page_box: [f64; 4]) -> Option Option Vec { + let content = "0.5 g 0 0 420 220 re f 0 0 1 rg 64 54 20 10 re f"; + pdf( + &[ + (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string(), None), + (2, format!("<< /Type /Pages /Kids [3 0 R] /Count 1 {pages} >>"), None), + (3, format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 420 220] {page} /Contents 4 0 R >>"), None), + (4, "<< >>".to_string(), Some(content.as_bytes().to_vec())), + ], + 1, + ) +} + +/// The first page of `bytes` framed as After Effects places it. +fn placed(bytes: &[u8]) -> Doc { + parse_page_framed(bytes, 0, Framing::Placed).unwrap() +} + +/// #3099: After Effects 2026 places a .ai or PDF as footage by the page's ArtBox and shows only +/// that region (a page with MediaBox 420 × 220, CropBox 410 × 210, TrimBox 380 × 180 and ArtBox +/// [60 50 300.6 170.4] imports as 241 × 121). `Framing::Placed` frames it so; the viewer framing +/// (the default, used by File ▸ Import) stays the CropBox. +#[test] +fn placed_framing_is_the_art_box() { + let bytes = boxes_pdf("/CropBox [5 5 415 215]", "/TrimBox [20 20 400 200] /ArtBox [60 50 300.6 170.4]"); + let doc = placed(&bytes); + assert!((doc.width - 240.6).abs() < 1e-9 && (doc.height - 120.4).abs() < 1e-9, "{} × {}", doc.width, doc.height); + assert_eq!(doc.pixel_size(), (241, 121)); + // The art box's top-left corner is the document's origin: the marker (PDF x 64..84, y 54..64) + // is at x 4..24, y 106.4..116.4 from the top. + let (w, h) = doc.pixel_size(); + let img = effectcraft_svg::rasterize(&doc, w, h, 1.0); + let marker = img.get(10, 110); + assert!(marker[2] > 0.99 && marker[0] < 0.01, "{marker:?}"); + assert!(img.get(30, 110)[2] < 0.6, "{:?}", img.get(30, 110)); + let viewer = parse(&bytes).unwrap(); + assert_eq!((viewer.width, viewer.height), (410.0, 210.0), "the viewer framing is unchanged"); +} + +/// The ArtBox is clipped to the crop box (ISO 32000-1 §14.11.2); one that keeps no area there, +/// a degenerate or unreadable one, or one on the /Pages node (not inherited, table 30) leaves the +/// crop box (else the media box). +#[test] +fn placed_framing_clips_the_art_box_and_falls_back() { + let size = |pages: &str, page: &str| { + let d = placed(&boxes_pdf(pages, page)); + (d.width, d.height) + }; + let crop = "/CropBox [5 5 415 215]"; + assert_eq!(size(crop, "/ArtBox [-100 -100 1000 1000]"), (410.0, 210.0), "larger than the page"); + assert_eq!(size(crop, "/ArtBox [300 100 900 900]"), (115.0, 115.0), "partly outside"); + let (w, h) = size(crop, "/ArtBox [300.6 170.4 60 50]"); + assert!((w - 240.6).abs() < 1e-9 && (h - 120.4).abs() < 1e-9, "corners in any order: {w} × {h}"); + // Finite corners whose span is not. + let big = format!("1{}", "0".repeat(308)); + let unreadable = [format!("/ArtBox [-{big} 50 {big} 170]")]; + for page in ["/ArtBox [500 300 600 400]", "/ArtBox [60 50 60 170]", "/ArtBox [60 50 300]"].map(String::from).iter().chain(&unreadable) { + assert_eq!(size(crop, page), (410.0, 210.0), "{page}"); + } + assert_eq!(size("/ArtBox [60 50 300 170]", ""), (420.0, 220.0), "an ArtBox on /Pages is not inherited"); + // A crop box that is not a box leaves the media box. + assert_eq!(size("", &format!("/CropBox [-{big} 5 {big} 215]")), (420.0, 220.0)); +} + +/// After Effects ignores /Rotate on placed footage (a page [100 50 400 150] with /Rotate 90 +/// imports as 300 × 100, drawn unturned); the viewer framing turns it. +#[test] +fn placed_framing_ignores_rotate() { + let bytes = boxes_pdf("", "/Rotate 90"); + let doc = placed(&bytes); + assert_eq!((doc.width, doc.height), (420.0, 220.0)); + // Unturned: the marker at PDF (64..84, 54..64) is at x 64..84, y 156..166 from the top. + let img = effectcraft_svg::rasterize(&doc, 420, 220, 1.0); + assert!(img.get(70, 160)[2] > 0.99, "{:?}", img.get(70, 160)); + let viewer = parse(&bytes).unwrap(); + assert_eq!((viewer.width, viewer.height), (220.0, 420.0)); +} + const EPS: &str = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n\ /m {moveto} bind def /l {lineto} bind def\n\ /cm { 6 array astore concat } bind def\n\ @@ -668,6 +748,63 @@ fn tiling_patterns_coloured_and_uncoloured() { assert_eq!(at(115, 15)[3], 0.0); } +/// A pattern cell nests under the page's open clipping groups and the pattern's own groups, and +/// the render tree stays within the group depth limit that counts all of them. +#[test] +fn a_pattern_cell_counts_the_groups_it_is_nested_in() { + fn depth(g: &effectcraft_svg::Group) -> usize { + 1 + g.children.iter().filter_map(|c| if let effectcraft_svg::Node::Group(g) = c { Some(depth(g)) } else { None }).max().unwrap_or(0) + } + let clips = "0 0 200 100 re W n ".repeat(250); + let cell = format!("{} 1 0 0 rg 0 0 10 10 re f", "0 0 20 20 re W n ".repeat(250)).into_bytes(); + let bytes = page_pdf( + &format!("{clips} /Pattern cs /P1 scn 0 0 100 100 re f"), + "/Pattern << /P1 10 0 R >>", + vec![(10, "<< /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 20 20] /XStep 20 /YStep 20 /Resources << >> >>".into(), Some(cell))], + ); + let doc = parse(&bytes).unwrap(); + assert!(depth(&doc.root) <= 260, "{}", depth(&doc.root)); + assert!(doc.skipped.iter().any(|s| s == "group nesting limit"), "{:?}", doc.skipped); +} + +/// A pattern whose `Pattern` and `Tile` wrappers would pass the depth limit is skipped, not built +/// past it. +#[test] +fn a_pattern_whose_wrappers_pass_the_depth_limit_is_skipped() { + let clips = "0 0 200 100 re W n ".repeat(255); + let bytes = page_pdf( + &format!("{clips} /Pattern cs /P1 scn 0 0 100 100 re f"), + "/Pattern << /P1 10 0 R >>", + vec![( + 10, + "<< /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 20 20] /XStep 20 /YStep 20 /Resources << >> >>".into(), + Some(b"0 0 10 10 re f".to_vec()), + )], + ); + let doc = parse(&bytes).unwrap(); + assert!(doc.skipped.iter().any(|s| s == "group nesting limit"), "{:?}", doc.skipped); +} + +/// A soft mask replacing another is nested under what is open once the old one has closed, so +/// groups inside the old mask don't count against the new mask's content. +#[test] +fn a_replaced_soft_mask_does_not_count_against_the_new_one() { + let form = |n: &str| { + ( + n.parse().unwrap(), + "<< /Type /XObject /Subtype /Form /BBox [0 0 200 100] /Group << /S /Transparency /CS /DeviceGray >> >>".to_string(), + Some(format!("{} 1 g 0 0 100 100 re f", "0 0 200 100 re W n ".repeat(250)).into_bytes()), + ) + }; + let bytes = page_pdf( + &format!("/GS1 gs {} /GS2 gs 1 0 0 rg 0 0 200 100 re f", "0 0 200 100 re W n ".repeat(250)), + "/ExtGState << /GS1 << /SMask << /S /Luminosity /G 10 0 R >> >> /GS2 << /SMask << /S /Luminosity /G 11 0 R >> >> >>", + vec![form("10"), form("11")], + ); + let doc = parse(&bytes).unwrap(); + assert!(doc.skipped.iter().all(|s| s != "group nesting limit"), "{:?}", doc.skipped); +} + /// Build isolated interpreter objects without presenting a function or colour space as a /// document catalog. Complete-document parsing is covered by the page and reader fixtures. fn object_file(objs: Objs) -> object::File { @@ -988,6 +1125,35 @@ fn a_fanning_out_reference_graph_is_refused_within_the_budget() { assert_eq!(read_function(objs), color::Func::Unsupported); } +#[test] +fn a_sampled_function_shorter_than_its_table_is_refused() { + // 4,096 8-bit samples declared, ten bytes given: the missing ones are not made up. + let f = "<< /FunctionType 0 /Domain [0 1] /Size [4096] /Range [0 1] /BitsPerSample 8 >>"; + assert_eq!(read_function(vec![(1, f.into(), Some(vec![7; 10]))]), color::Func::Unsupported); + assert_ne!(read_function(vec![(1, f.into(), Some(vec![7; 4096]))]), color::Func::Unsupported); +} + +#[test] +fn a_calculator_program_past_the_operator_limit_is_refused() { + let f = "<< /FunctionType 4 /Domain [0 1] /Range [0 1] >>"; + let long = format!("{{ {} }}", "1 pop ".repeat(3000)); + assert_eq!(read_function(vec![(1, f.into(), Some(long.into_bytes()))]), color::Func::Unsupported); + assert_ne!(read_function(vec![(1, f.into(), Some(b"{ 1 exch sub }".to_vec()))]), color::Func::Unsupported); +} + +#[test] +fn copies_of_a_function_are_charged_for_its_coefficients() { + // A stitching function listing one object 1,000 times, whose coefficient arrays hold 2,000 + // values: each copy is charged its values, so the budget refuses it instead of copying + // two million values. + let c = format!("[{}]", "0.5 ".repeat(1000)); + let objs: Objs = vec![ + (1, format!("<< /FunctionType 3 /Domain [0 1] /Functions [{}] >>", "2 0 R ".repeat(1000)), None), + (2, format!("<< /FunctionType 2 /Domain [0 1] /C0 {c} /C1 {c} /N 1 >>"), None), + ]; + assert_eq!(read_function(objs), color::Func::Unsupported); +} + #[test] fn colour_space_chain_of_depth_3() { // Indexed → Separation → ICCBased → DeviceRGB: entry 0 is tint 1 (blue), entry 1 tint 0 (white). diff --git a/crates/pdf/src/tests/import.rs b/crates/pdf/src/tests/import.rs index c7dcbee57..516ff054d 100644 --- a/crates/pdf/src/tests/import.rs +++ b/crates/pdf/src/tests/import.rs @@ -513,6 +513,9 @@ fn paths_stop_at_the_path_limit() { // The outlines of 100,000 H's, 13 elements each. "/Helvetica findfont 10 scalefont setfont /s 100000 string def 0 1 99999 { s exch 72 put } for \ 0 0 moveto s false charpath", + // The same outlines shown: the text path is bounded like the current path. + "/Helvetica findfont 10 scalefont setfont /s 100000 string def 0 1 99999 { s exch 72 put } for \ + 0 0 moveto s show", // 210,000 rectangles of five elements each. "/a 840000 array def 0 1 839999 { a exch 0 put } for a rectfill", ] { @@ -528,6 +531,45 @@ fn paths_stop_at_the_path_limit() { assert_eq!(doc.flatten().len(), 1); } +#[test] +fn copies_past_the_operand_limit_copy_nothing() { + // `count copy` doubles the operand stack: 40 doublings would be 2^40 values. A copy that would + // pass the operand limit (100,000) copies nothing, so the program runs on to its end. + let doc = eps_soon("0 0 10 10 rectfill 1 40 { count copy } repeat clear 20 20 10 10 rectfill"); + assert!(doc.skipped.is_empty(), "{:?}", doc.skipped); + assert_eq!(doc.flatten().len(), 2); +} + +#[test] +fn storage_made_in_a_loop_runs_out_of_the_budget() { + // Each value of an array and each eight bytes of a string count as an operation when they + // are made, so a loop keeping large arrays or strings spends the budget, not the memory. + for body in ["/a 1000 array def 0 1 999 { a exch 1000000 array put } for", "/a 1000 array def 0 1 999 { a exch 10000000 string put } for"] { + runs_out_of_budget(body); + } +} + +#[test] +fn groups_stop_nesting_at_the_depth_limit() { + // Every `rectclip` opens a clipping group inside the last: past 256 open groups the group is + // dropped (and noted), and what is drawn inside goes to the open one. + let doc = eps_soon("300 { 0 0 100 100 rectclip } repeat 0 0 10 10 rectfill"); + assert_eq!(doc.skipped, ["group nesting limit"]); + assert_eq!(doc.flatten().len(), 1); +} + +#[test] +fn bounding_box_comments_are_scanned_once() { + // A rejected `%%BoundingBox:` comment is not scanned again from each later marker on its + // line: 20,000 markers on one line would otherwise take quadratic work. + let mut src = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); + src.extend_from_slice("%%BoundingBox: x ".repeat(20_000).as_bytes()); + src.extend_from_slice(b"\n%%BoundingBox: 0 0 50 50\n0 0 10 10 rectfill\n"); + let doc = parse(&src).unwrap(); + assert_eq!((doc.width, doc.height), (50.0, 50.0)); + assert_eq!(doc.flatten().len(), 1); +} + #[test] fn pdf_paths_stop_at_the_path_limit() { // A content stream's current path holds at most 1,048,576 elements: `re` (five elements each) diff --git a/crates/pdf/src/tests/shading.rs b/crates/pdf/src/tests/shading.rs index 8e96193ab..4b5f9645d 100644 --- a/crates/pdf/src/tests/shading.rs +++ b/crates/pdf/src/tests/shading.rs @@ -262,3 +262,32 @@ fn corrupt_mesh_data_draws_what_parses() { let doc = parse(&bytes).unwrap(); assert!(doc.skipped.iter().any(|s| s.contains("layout")), "{:?}", doc.skipped); } + +#[test] +fn overlapping_mesh_triangles_stop_at_the_raster_budget() { + // 20,000 triangles each covering the whole page would test every sample 20,000 times; the + // raster budget stops after about 64 passes, and the shading is still drawn. + let mut m = Mesh::default(); + for _ in 0..20_000 { + m.flag(0).pt(0, 0).c(&[255, 0, 0]); + m.flag(0).pt(400, 0).c(&[255, 0, 0]); + m.flag(0).pt(0, 400).c(&[255, 0, 0]); + } + let sh = format!("<< /ShadingType 4 /ColorSpace /DeviceRGB /BitsPerCoordinate 16 /BitsPerComponent 8 /BitsPerFlag 8 {RGB_DECODE} >>"); + let bytes = page_pdf("/Sh sh", "/Shading << /Sh 10 0 R >>", vec![(10, sh, Some(m.0))]); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(parse(&bytes)).ok()); + let doc = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("the mesh finishes").unwrap(); + assert!(render(&doc).get(50, 50)[0] > 0.99); +} + +#[test] +fn a_lattice_row_longer_than_the_triangle_limit_draws_nothing() { + let mut m = Mesh::default(); + for i in 0..8 { + m.pt(i * 10, 0).c(&[255, 0, 0]); + } + let sh = format!("<< /ShadingType 5 /ColorSpace /DeviceRGB /BitsPerCoordinate 16 /BitsPerComponent 8 /VerticesPerRow 3000000 {RGB_DECODE} >>"); + let doc = parse(&page_pdf("/Sh sh", "/Shading << /Sh 10 0 R >>", vec![(10, sh, Some(m.0))])).unwrap(); + assert!(doc.flatten().is_empty()); +} diff --git a/crates/pdf/src/type1.rs b/crates/pdf/src/type1.rs index 4b3e05756..399905722 100644 --- a/crates/pdf/src/type1.rs +++ b/crates/pdf/src/type1.rs @@ -148,8 +148,9 @@ impl Type1 { }; if let Some(p) = find(&priv_, b"/Subrs", 0) { let mut q = p + 6; + // The section ends at `/CharStrings`, found once rather than for every entry. + let lim = find(&priv_, b"/CharStrings", q).unwrap_or(priv_.len()); while let Some(d) = find(&priv_, b"dup", q) { - let lim = find(&priv_, b"/CharStrings", q).unwrap_or(priv_.len()); if d > lim { break; } @@ -205,10 +206,11 @@ impl Type1 { /// A glyph's outline in glyph space and its advance width. pub fn outline(&self, name: &str) -> Option<(BezPath, f64)> { - self.outline_depth(name, 0) + self.outline_depth(name, 0, &mut { crate::cff::MAX_GLYPH_OPS }) } - fn outline_depth(&self, name: &str, depth: usize) -> Option<(BezPath, f64)> { + /// `ops` is the glyph's instruction budget, shared by the base glyph and its seac components. + fn outline_depth(&self, name: &str, depth: usize, ops: &mut usize) -> Option<(BezPath, f64)> { let cs = self.charstrings.get(name)?; let mut st = T1 { font: self, @@ -223,9 +225,11 @@ impl Type1 { flex: None, done: false, depth: 0, + ops: *ops, seac: None, }; st.run(cs); + *ops = st.ops; if st.open { st.path.close_path(); } @@ -234,10 +238,10 @@ impl Type1 { && depth < 2 { let name_of = |c: u8| crate::encoding::Base::Standard.name(c); - if let Some((bp, _)) = name_of(b).and_then(|n| self.outline_depth(&n, depth + 1)) { + if let Some((bp, _)) = name_of(b).and_then(|n| self.outline_depth(&n, depth + 1, ops)) { path.extend(bp); } - if let Some((ap, _)) = name_of(a).and_then(|n| self.outline_depth(&n, depth + 1)) { + if let Some((ap, _)) = name_of(a).and_then(|n| self.outline_depth(&n, depth + 1, ops)) { // The accent's origin: its own sidebearing is replaced by `asb`. path.extend(kurbo::Affine::translate((adx - asb + st.sbx, ady)) * ap); } @@ -270,6 +274,8 @@ struct T1<'a> { flex: Option>, done: bool, depth: usize, + /// Instructions this glyph may still run, across its subroutine calls. + ops: usize, seac: Option<(f64, f64, f64, u8, u8)>, } @@ -314,6 +320,12 @@ impl T1<'_> { } let mut i = 0; while i < cs.len() && !self.done { + // Subroutines that branch would multiply the work: the budget is shared. + let Some(left) = self.ops.checked_sub(1) else { + self.done = true; + return; + }; + self.ops = left; let b0 = cs[i]; i += 1; let s = |st: &Self, k: usize| st.stack.get(k).copied().unwrap_or(0.0); @@ -533,6 +545,25 @@ mod tests { assert_eq!(p.bounding_box(), kurbo::Rect::new(50.0, 0.0, 550.0, 500.0)); } + /// A subroutine that calls itself ten times: 10^10 calls within the depth limit of ten. The + /// glyph stops at its instruction budget instead. + #[test] + fn branching_subroutines_stop_at_the_instruction_budget() { + let mut out = b"%!PS-AdobeFont-1.0: Test 001\n/FontMatrix [0.001 0 0 0.001 0 0] readonly def\ncurrentfile eexec\n".to_vec(); + // `0 callsubr` is `139 10`; `return` is 11, `endchar` 14 (lenIV -1: charstrings in clear). + let mut subr = [139u8, 10].repeat(10); + subr.push(11); + let mut priv_ = b"dup /Private 8 dict dup begin /lenIV -1 def\n/Subrs 1 array\n".to_vec(); + priv_.extend_from_slice(format!("dup 0 {} RD ", subr.len()).as_bytes()); + priv_.extend_from_slice(&subr); + priv_.extend_from_slice(b" NP\nend\n/CharStrings 1 dict dup begin\n/A 3 RD \x8b\x0a\x0e ND\nend\nend\nmark currentfile closefile\n"); + out.extend(encrypt(&priv_, EEXEC_R, 4)); + out.extend_from_slice(b"\n0000000000000000\ncleartomark\n"); + let t = Type1::parse(&out).unwrap(); + let (p, _) = t.outline("A").unwrap(); + assert!(p.elements().is_empty()); + } + /// A `/Subrs` entry whose `RD` length is `usize::MAX`: the bytes are not in the file, and /// `q + n` must not overflow. #[test] diff --git a/crates/plugin/Cargo.toml b/crates/plugin/Cargo.toml index 4081b61b6..d9b35a91a 100644 --- a/crates/plugin/Cargo.toml +++ b/crates/plugin/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "effectcraft-plugin" -description = "EffectCraft effect plug-ins: loads sandboxed WebAssembly effect modules (plug-in API v1) into the effect registry" +description = "EffectCraft effect plug-ins: loads sandboxed WebAssembly effect modules (WebAssembly ABI v1 and v2) into the effect registry" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/plugin/src/lib.rs b/crates/plugin/src/lib.rs index 829964378..da21e22a0 100644 --- a/crates/plugin/src/lib.rs +++ b/crates/plugin/src/lib.rs @@ -1,20 +1,25 @@ //! # effectcraft-plugin (L3) //! -//! Loads **WebAssembly effect plug-ins** (plug-in API v1, see `docs/plugins.md`) into the effect -//! registry ([`effectcraft_effects::plugin`]). A plug-in is a `.wasm` (or `.wat`) module with -//! no imports that exports: +//! Loads **WebAssembly effect plug-ins** (WebAssembly ABI v1 and v2, see `docs/plugins.md`; the +//! native plug-in API 2 additions such as layer parameters and host services are not part of it) +//! into the effect registry ([`effectcraft_effects::plugin`]). A plug-in is a `.wasm` (or +//! `.wat`) module with no imports that exports: //! //! | export | signature | | //! |---|---|---| //! | `memory` | memory | linear memory shared with the host | -//! | `ec_api_version` | `() -> i32` | must return 1 | +//! | `ec_api_version` | `() -> i32` | 1 for ABI 1, 2 for ABI 2 (neighbouring frames) | //! | `ec_manifest_ptr`, `ec_manifest_len` | `() -> i32` | a UTF-8 JSON [`PluginManifest`] in memory | //! | `ec_alloc` | `(bytes: i32) -> i32` | a buffer of at least `bytes` bytes, 8-byte aligned; it may reuse the previous one | -//! | `ec_render` | `(pixels: i32, width: i32, height: i32, params: i32, nparams: i32, time: f64, scale: f64) -> i32` | process the pixels in place; 0 = ok | +//! | `ec_render` (ABI 1) | `(pixels: i32, width: i32, height: i32, params: i32, nparams: i32, time: f64, scale: f64) -> i32` | process the pixels in place; 0 = ok | +//! | `ec_render2` (ABI 2) | `ec_render`'s arguments, then `prev: i32, prev_time: f64, next: i32, next_time: f64, flags: i32` | the same, with the neighbouring frames; 0 = ok | //! //! For each render the host asks `ec_alloc` for one buffer holding the parameters (`nparams` //! little-endian `f64`s) followed by the pixels (`width × height × 4` little-endian `f32`s, -//! premultiplied RGBA, row-major), calls `ec_render`, and reads the pixels back. +//! premultiplied RGBA, row-major), calls the render export, and reads the pixels back. An ABI 2 +//! module gets two more pixel buffers after the current frame: the layer's previous and next +//! frames, resampled onto the current grid, and their layer times. The buffers are always +//! allocated (zeroed when a frame does not exist); `flags` bit 0/1 says which are real. //! //! Modules run in the [wasmi](https://github.com/wasmi-labs/wasmi) interpreter (pure Rust, //! MIT/Apache-2.0) with deterministic floats, no imports (no files, network or clock) and a @@ -25,7 +30,9 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use effectcraft_effects::EffectSpec; -pub use effectcraft_effects::plugin::{EffectPlugin, PLUGIN_API_VERSION, PluginFrame, PluginManifest, PluginParams, register_plugin}; +pub use effectcraft_effects::plugin::{ + EffectPlugin, MIN_WASM_API_VERSION, PLUGIN_API_VERSION, PluginFrame, PluginImage, PluginManifest, PluginParams, WASM_API_VERSION, register_plugin, +}; #[cfg(feature = "wasm")] mod wasm; @@ -59,11 +66,53 @@ pub fn loader(bytes: &[u8], source: &str) -> Result { "name": spec.name, "category": spec.category, "version": m.as_ref().map(|m| m.version.clone()).unwrap_or_default(), - "api": PLUGIN_API_VERSION, + "api": m.as_ref().map(|m| m.api).unwrap_or(PLUGIN_API_VERSION), "params": spec.params.len(), })) } +/// Render a module's effect without registering it (the Plug-in Library's preview): default +/// parameters, `pixels` (premultiplied RGBA, `width × height`) at each of `times` (seconds). +/// Returns the manifest as JSON and one frame per time. +pub fn preview(bytes: &[u8], width: u32, height: u32, pixels: &[[f32; 4]], times: &[f64]) -> Result<(serde_json::Value, Vec>), String> { + #[cfg(feature = "wasm")] + { + use effectcraft_effects::plugin::{EffectPlugin, PluginFrame, PluginParamKind, PluginParams}; + let p = wasm::WasmPlugin::new(bytes, "preview")?; + let m = p.manifest(); + let mut flat = Vec::with_capacity(m.flat_len()); + for param in &m.params { + match ¶m.kind { + PluginParamKind::Slider { default, .. } | PluginParamKind::Angle { default } => flat.push(*default), + PluginParamKind::Checkbox { default } => flat.push(if *default { 1.0 } else { 0.0 }), + PluginParamKind::Popup { default, .. } => flat.push(*default as f64), + // Points default to fractions of the layer: the frame is the layer. + PluginParamKind::Point { default } => flat.extend([default[0] * f64::from(width), default[1] * f64::from(height)]), + PluginParamKind::Color { default } => flat.extend(default.iter().copied()), + // API 2 kinds: a WebAssembly module can't declare them (`WasmPlugin::new` refuses them). + PluginParamKind::Point3 { default } => flat.extend(default.iter().copied()), + PluginParamKind::Layer => flat.push(-1.0), + PluginParamKind::Text { .. } | PluginParamKind::Hidden { .. } => {} + } + } + let params = PluginParams { manifest: m, flat: &flat, texts: &[] }; + let mut frames = Vec::with_capacity(times.len()); + for &t in times { + let mut px = pixels.to_vec(); + let mut frame = PluginFrame { width, height, pixels: &mut px, scale: 1.0, origin: [0.0; 2], layer_size: [f64::from(width), f64::from(height)] }; + p.render(&mut frame, ¶ms, t)?; + frames.push(px); + } + let manifest = serde_json::to_value(m).map_err(|e| e.to_string())?; + Ok((manifest, frames)) + } + #[cfg(not(feature = "wasm"))] + { + let _ = (bytes, width, height, pixels, times); + Err("WebAssembly plug-ins are not available in this build".into()) + } +} + // Two attributes, so clippy sees `cfg(test)` and treats the module as test code. #[cfg(test)] #[cfg(feature = "wasm")] diff --git a/crates/plugin/src/tests.rs b/crates/plugin/src/tests.rs index f68fde00a..a4fadb26b 100644 --- a/crates/plugin/src/tests.rs +++ b/crates/plugin/src/tests.rs @@ -163,11 +163,15 @@ fn wasm_plugins_are_sandboxed() { // No imports (files, clock, network…). let imports = r#"(module (import "env" "now" (func $now (result f64))) (memory (export "memory") 1))"#; assert!(load_err(load_wasm(imports.as_bytes(), "imports.wat")).contains("import")); - // Garbage, wrong API version, bad manifests. + // Garbage, an ABI this build doesn't implement, bad manifests. A module that claims ABI 2 + // must export `ec_render2` (this one still has only `ec_render`). assert!(load_wasm(b"\0asm nope", "bad.wasm").is_err()); let v2 = gain_module("org.test.v2", "") .replace("(func (export \"ec_api_version\") (result i32) i32.const 1)", "(func (export \"ec_api_version\") (result i32) i32.const 2)"); - assert!(load_err(load_wasm(v2.as_bytes(), "v2.wat")).contains("API 2")); + assert!(load_err(load_wasm(v2.as_bytes(), "v2.wat")).contains("ec_render2")); + let v3 = gain_module("org.test.v3", "") + .replace("(func (export \"ec_api_version\") (result i32) i32.const 1)", "(func (export \"ec_api_version\") (result i32) i32.const 3)"); + assert!(load_err(load_wasm(v3.as_bytes(), "v3.wat")).contains("ABI 3")); let reserved = gain_module("ec.blur.mine", ""); assert!(load_err(load_wasm(reserved.as_bytes(), "reserved.wat")).contains("reserved")); } @@ -194,14 +198,14 @@ fn abi_violations_fail_to_load_with_reasons() { assert!(load_err(load_wasm(m.as_bytes(), "x.wat")).contains("ec_api_version")); let m = edit(&base, "(param $scale f64) (result i32)", "(param $scale f32) (result i32)"); assert!(load_err(load_wasm(m.as_bytes(), "x.wat")).contains("ec_render")); - // API versions other than 1. - for v in ["0", "-1", "2147483647"] { + // WebAssembly ABIs other than 1 and 2. + for v in ["0", "-1", "3", "2147483647"] { let m = edit( &base, "(func (export \"ec_api_version\") (result i32) i32.const 1)", &format!("(func (export \"ec_api_version\") (result i32) i32.const {v})"), ); - assert!(load_err(load_wasm(m.as_bytes(), "x.wat")).contains(&format!("API {v}")), "{v}"); + assert!(load_err(load_wasm(m.as_bytes(), "x.wat")).contains(&format!("ABI {v}")), "{v}"); } // Manifest out of bounds, negative or absurd lengths, not JSON. let ptr = "(func (export \"ec_manifest_ptr\") (result i32) i32.const 16)"; @@ -317,3 +321,168 @@ fn wasm_rendering_is_deterministic() { let twin = load_wasm(gain_module("org.test.det2", body).as_bytes(), "det2.wat").unwrap(); assert_eq!(bits(&render(twin, 0.37, true)), first); } + +/// An ABI 2 module whose `ec_render2` writes what it got from the host into each pixel: red is +/// |next.red − prev.red|, green `flags / 8`, blue `prev_time`, alpha 1. +fn neighbour_module(id: &str) -> String { + let manifest = format!(r#"{{"api":2,"id":"{id}","name":"Neighbours {id}","category":"Test Plug-ins","version":"1","params":[]}}"#); + let len = manifest.len(); + let escaped = manifest.replace('\\', "\\\\").replace('"', "\\\""); + format!( + r#"(module + (memory (export "memory") 2) + (data (i32.const 16) "{escaped}") + (func (export "ec_api_version") (result i32) i32.const 2) + (func (export "ec_manifest_ptr") (result i32) i32.const 16) + (func (export "ec_manifest_len") (result i32) i32.const {len}) + (func (export "ec_alloc") (param i32) (result i32) i32.const 1024) + (func (export "ec_render2") + (param $px i32) (param $w i32) (param $h i32) (param $params i32) (param $np i32) + (param $t f64) (param $scale f64) + (param $prev i32) (param $prev_t f64) (param $next i32) (param $next_t f64) (param $flags i32) + (result i32) + (local $i i32) (local $n i32) + local.get $w + local.get $h + i32.mul + local.set $n + block $done + loop $per_pixel + local.get $i + local.get $n + i32.ge_u + br_if $done + local.get $px + local.get $i + i32.const 16 + i32.mul + i32.add + local.get $next + local.get $i + i32.const 16 + i32.mul + i32.add + f32.load + local.get $prev + local.get $i + i32.const 16 + i32.mul + i32.add + f32.load + f32.sub + f32.abs + f32.store + local.get $px + local.get $i + i32.const 16 + i32.mul + i32.add + local.get $flags + f32.convert_i32_s + f32.const 8 + f32.div + f32.store offset=4 + local.get $px + local.get $i + i32.const 16 + i32.mul + i32.add + local.get $prev_t + f32.demote_f64 + f32.store offset=8 + local.get $px + local.get $i + i32.const 16 + i32.mul + i32.add + f32.const 1 + f32.store offset=12 + local.get $i + i32.const 1 + i32.add + local.set $i + br $per_pixel + end + end + i32.const 0))"# + ) +} + +fn neighbour_image(red: f32) -> effectcraft_effects::plugin::PluginImage { + effectcraft_effects::plugin::PluginImage { width: 2, height: 1, pixels: vec![[red, 0.0, 0.0, 1.0]; 2], origin: [0.0; 2], scale: 1.0 } +} + +/// A host with frames at two layer times. +struct Host { + time: f64, + fps: f64, + prev: Option<(f64, effectcraft_effects::plugin::PluginImage)>, + next: Option<(f64, effectcraft_effects::plugin::PluginImage)>, +} + +impl effectcraft_effects::plugin::PluginHost for Host { + fn input_at(&self, layer_time: f64) -> Option { + if let Some((t, img)) = &self.prev + && (t - layer_time).abs() < 1e-9 + { + return Some(img.clone()); + } + if let Some((t, img)) = &self.next + && (t - layer_time).abs() < 1e-9 + { + return Some(img.clone()); + } + None + } + + fn layer_input(&self, _param_id: &str, _layer_time: f64) -> Option { + None + } + + fn params_at(&self, _layer_time: f64) -> Option<(Vec, Vec)> { + None + } + + fn frame_rate(&self) -> f64 { + self.fps + } + + fn time(&self) -> f64 { + self.time + } +} + +#[test] +fn abi_v2_receives_neighbour_frames_and_times() { + load_wasm(neighbour_module("org.test.neighbours").as_bytes(), "neighbours.wat").unwrap(); + let p = effectcraft_effects::plugin::plugin("org.test.neighbours").unwrap(); + assert!(effectcraft_effects::plugin::reads_other_times("org.test.neighbours")); + assert!(effectcraft_effects::is_time_dependent("org.test.neighbours")); + // The module has no parameters, so the flattened vector is empty. + let params = effectcraft_effects::plugin::PluginParams { manifest: p.manifest(), flat: &[], texts: &[] }; + let mut px = vec![[0.0f32; 4]; 2]; + let host = Host { time: 0.5, fps: 4.0, prev: Some((0.25, neighbour_image(0.1))), next: Some((0.75, neighbour_image(0.6))) }; + let mut frame = effectcraft_effects::plugin::PluginFrame { width: 2, height: 1, pixels: &mut px, scale: 1.0, origin: [0.0; 2], layer_size: [2.0, 1.0] }; + p.render_v2(&mut frame, ¶ms, 0.5, &host).unwrap(); + assert!((px[0][0] - 0.5).abs() < 1e-6, "|next − prev|: {px:?}"); + assert!((px[0][1] - 3.0 / 8.0).abs() < 1e-6, "both flags: {px:?}"); + assert!((px[0][2] - 0.25).abs() < 1e-6, "previous frame's time: {px:?}"); + assert_eq!(px[0][3], 1.0); +} + +#[test] +fn abi_v2_without_a_host_gets_zeroed_neighbours() { + let spec = load_wasm(neighbour_module("org.test.neighbours.empty").as_bytes(), "empty.wat").unwrap(); + let mut next_id = 1; + let g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next_id), spec.name, [2.0, 1.0]); + let params = effectcraft_effects::flatten_params(&g, &mut |p| p.value.clone()); + let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: [2.0, 1.0], seed: 1, adjustment: false, env: EffectEnv::default() }; + let buf = Buf { img: Image::filled(2, 1, [0.5, 0.5, 0.5, 1.0]), offset: [0.0; 2], scale: 1.0 }; + // No host: both neighbour buffers are zeroed and no flag is set. + assert_eq!((spec.render)(&ctx, buf).img.get(0, 0), [0.0, 0.0, 0.0, 1.0]); + // ABI 1 plug-ins keep the time-independent behaviour. + let gain = load_wasm(gain_module("org.test.neighbours.v1", "").as_bytes(), "v1.wat").unwrap(); + assert!(!effectcraft_effects::plugin::reads_other_times("org.test.neighbours.v1")); + assert!(!effectcraft_effects::is_time_dependent("org.test.neighbours.v1")); + assert!(gain.id.starts_with("org.test.")); +} diff --git a/crates/plugin/src/wasm.rs b/crates/plugin/src/wasm.rs index 1f61c6b44..18f3fb0d0 100644 --- a/crates/plugin/src/wasm.rs +++ b/crates/plugin/src/wasm.rs @@ -1,10 +1,11 @@ -//! The wasmi-backed [`EffectPlugin`] (plug-in API v1 ABI, see the crate docs). +//! The wasmi-backed [`EffectPlugin`] (WebAssembly ABI v1 and v2, see the crate docs). use std::sync::Mutex; use wasmi::{Config, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder, TypedFunc, WasmParams, WasmResults}; -use crate::{EffectPlugin, PLUGIN_API_VERSION, PluginFrame, PluginManifest, PluginParams}; +use crate::{EffectPlugin, MIN_WASM_API_VERSION, PluginFrame, PluginManifest, PluginParams, WASM_API_VERSION}; +use effectcraft_effects::plugin::{PluginHost, PluginImage}; /// Instruction budget per frame: a fixed allowance plus some per pixel. Generous for per-pixel /// work, but a runaway loop stops instead of hanging the render. @@ -12,50 +13,103 @@ const FUEL_BASE: u64 = 50_000_000; const FUEL_PER_PIXEL: u64 = 20_000; /// The most linear memory a plug-in instance may have (a 4K float frame is ~130 MB). const MAX_MEMORY: usize = 1 << 30; +/// The most elements one table of a plug-in may hold. +const MAX_TABLE_ELEMENTS: usize = 1 << 16; /// The longest manifest read. const MAX_MANIFEST: i32 = 1 << 20; +/// ABI 1: one buffer. type RenderFn = TypedFunc<(i32, i32, i32, i32, i32, f64, f64), i32>; +/// ABI 2: the same call plus the previous and next frame buffers and their layer times. +type Render2Fn = TypedFunc<(i32, i32, i32, i32, i32, f64, f64, i32, f64, i32, f64, i32), i32>; + +enum Renderer { + V1(RenderFn), + V2(Render2Fn), +} /// One instantiated module (renders running on several threads each take their own). struct Inst { + store: Store, + memory: Memory, + alloc: TypedFunc, + render: Renderer, +} + +/// An instance whose ABI version (and so its render export) is not selected yet. +struct Pending { store: Store, instance: Instance, memory: Memory, alloc: TypedFunc, - render: RenderFn, } -impl Inst { +impl Pending { + /// A typed export by name, reporting a missing or mistyped export like [`missing`]. fn func(&self, name: &str) -> Result, String> { self.instance.get_typed_func::(&self.store, name).map_err(|_| missing(name)) } + + /// Select the render export for `abi`. + fn finish(self, abi: u32) -> Result { + let render = match abi { + 1 => Renderer::V1(self.instance.get_typed_func::<_, i32>(&self.store, "ec_render").map_err(|_| missing("ec_render"))?), + 2 => Renderer::V2(self.instance.get_typed_func::<_, i32>(&self.store, "ec_render2").map_err(|_| missing("ec_render2"))?), + v => return Err(unsupported(v as i32)), + }; + Ok(Inst { store: self.store, memory: self.memory, alloc: self.alloc, render }) + } } +/// The error for a missing or mistyped export. fn missing(name: &str) -> String { format!("the module exports no `{name}` (or with the wrong signature)") } +/// The error for an ABI this build does not implement. +fn unsupported(v: i32) -> String { + format!("the module implements WebAssembly ABI {v}, this build implements ABI {MIN_WASM_API_VERSION} to {WASM_API_VERSION}") +} + +/// The module's `ec_api_version`, when this build implements it. +fn abi_of(v: i32) -> Result { + match u32::try_from(v) { + Ok(v) if (MIN_WASM_API_VERSION..=WASM_API_VERSION).contains(&v) => Ok(v), + _ => Err(unsupported(v)), + } +} + +/// The error for a wasmi or trap failure. fn err(e: impl std::fmt::Display) -> String { e.to_string() } -fn instantiate(engine: &Engine, module: &Module) -> Result { - let mut store = Store::new(engine, StoreLimitsBuilder::new().memory_size(MAX_MEMORY).instances(1).build()); +/// Instantiate `module` in a fresh, limited store and read its memory and allocator. +fn begin(engine: &Engine, module: &Module) -> Result { + // One memory and a few small tables: a module declaring many of them would otherwise make + // the host allocate and initialise each before an export or fuel check could refuse it. + let limits = StoreLimitsBuilder::new().memory_size(MAX_MEMORY).memories(1).tables(4).table_elements(MAX_TABLE_ELEMENTS).instances(1).build(); + let mut store = Store::new(engine, limits); store.limiter(|l| l); store.set_fuel(FUEL_BASE).map_err(err)?; let linker = Linker::::new(engine); let instance = linker.instantiate_and_start(&mut store, module).map_err(|e| format!("instantiation failed: {e}"))?; let memory = instance.get_memory(&store, "memory").ok_or("the module exports no `memory`")?; let alloc = instance.get_typed_func::(&store, "ec_alloc").map_err(|_| missing("ec_alloc"))?; - let render = instance.get_typed_func::<(i32, i32, i32, i32, i32, f64, f64), i32>(&store, "ec_render").map_err(|_| missing("ec_render"))?; - Ok(Inst { store, instance, memory, alloc, render }) + Ok(Pending { store, instance, memory, alloc }) +} + +/// Instantiate `module` and select the render export for `abi`. +fn instantiate(engine: &Engine, module: &Module, abi: u32) -> Result { + begin(engine, module)?.finish(abi) } /// A loaded WebAssembly effect plug-in. pub struct WasmPlugin { manifest: PluginManifest, source: String, + /// The WebAssembly ABI the module implements (`ec_api_version`). + abi: u32, engine: Engine, module: Module, /// Idle instances. @@ -63,6 +117,7 @@ pub struct WasmPlugin { } impl WasmPlugin { + /// Load `bytes` and its manifest; errors on imports, a bad manifest or a missing export. pub fn new(bytes: &[u8], source: &str) -> Result { let mut config = Config::default(); config.consume_fuel(true); @@ -71,48 +126,42 @@ impl WasmPlugin { if let Some(i) = module.imports().next() { return Err(format!("plug-ins can't import anything (the module imports `{}.{}`)", i.module(), i.name())); } - let mut inst = instantiate(&engine, &module)?; - let version = inst.func::<(), i32>("ec_api_version")?; - let v = version.call(&mut inst.store, ()).map_err(err)?; - if v != PLUGIN_API_VERSION as i32 { - return Err(format!("the module implements plug-in API {v}, this build implements API {PLUGIN_API_VERSION}")); - } - let ptr = inst.func::<(), i32>("ec_manifest_ptr")?.call(&mut inst.store, ()).map_err(err)?; - let len = inst.func::<(), i32>("ec_manifest_len")?.call(&mut inst.store, ()).map_err(err)?; + let mut pending = begin(&engine, &module)?; + let version = pending.func::<(), i32>("ec_api_version")?; + let abi = abi_of(version.call(&mut pending.store, ()).map_err(err)?)?; + let ptr = pending.func::<(), i32>("ec_manifest_ptr")?.call(&mut pending.store, ()).map_err(err)?; + let len = pending.func::<(), i32>("ec_manifest_len")?.call(&mut pending.store, ()).map_err(err)?; if !(0..=MAX_MANIFEST).contains(&len) { return Err(format!("bad manifest length {len}")); } let mut text = vec![0u8; len as usize]; - inst.memory.read(&inst.store, ptr as u32 as usize, &mut text).map_err(|e| format!("manifest out of bounds: {e}"))?; + pending.memory.read(&pending.store, ptr as u32 as usize, &mut text).map_err(|e| format!("manifest out of bounds: {e}"))?; let manifest: PluginManifest = serde_json::from_slice(&text).map_err(|e| format!("bad manifest JSON: {e}"))?; manifest.validate()?; - Ok(WasmPlugin { manifest, source: source.to_string(), engine, module, pool: Mutex::new(vec![inst]) }) + if let Some(p) = manifest.params.iter().find(|p| p.kind.needs_v2()) { + return Err(format!("parameter `{}`: WebAssembly plug-ins use plug-in API 1 parameter types (no point3, layer, text or hidden)", p.id)); + } + let inst = pending.finish(abi)?; + Ok(WasmPlugin { manifest, source: source.to_string(), abi, engine, module, pool: Mutex::new(vec![inst]) }) } + /// An idle instance, or a fresh one when the pool is empty. fn take(&self) -> Result { if let Some(i) = self.pool.lock().ok().and_then(|mut p| p.pop()) { return Ok(i); } - instantiate(&self.engine, &self.module) + instantiate(&self.engine, &self.module, self.abi) } + /// Return a working instance to the pool. fn give_back(&self, inst: Inst) { if let Ok(mut p) = self.pool.lock() { p.push(inst); } } -} -impl EffectPlugin for WasmPlugin { - fn manifest(&self) -> &PluginManifest { - &self.manifest - } - - fn source(&self) -> String { - self.source.clone() - } - - fn render(&self, frame: &mut PluginFrame, params: &PluginParams, time: f64) -> Result<(), String> { + /// ABI 1: parameters, then the pixels; `ec_render`. + fn render_v1(&self, frame: &mut PluginFrame, params: &PluginParams, time: f64) -> Result<(), String> { let n = frame.pixels.len(); let params_bytes = params.flat.len() * 8; let total = params_bytes + n * 16; @@ -127,25 +176,19 @@ impl EffectPlugin for WasmPlugin { for v in params.flat { buf.extend_from_slice(&v.to_le_bytes()); } - for px in frame.pixels.iter() { - for c in px { - buf.extend_from_slice(&c.to_le_bytes()); - } - } + push_pixels(&mut buf, frame.pixels); inst.memory.write(&mut inst.store, base, &buf).map_err(|e| format!("ec_alloc returned a buffer out of bounds: {e}"))?; let px_ptr = (base + params_bytes) as i32; - let r = inst - .render - .call(&mut inst.store, (px_ptr, frame.width as i32, frame.height as i32, base as i32, params.flat.len() as i32, time, frame.scale)) - .map_err(|e| format!("ec_render trapped: {e}")); + let r = match &inst.render { + Renderer::V1(f) => f + .call(&mut inst.store, (px_ptr, frame.width as i32, frame.height as i32, base as i32, params.flat.len() as i32, time, frame.scale)) + .map_err(|e| format!("ec_render trapped: {e}")), + Renderer::V2(_) => return Err("the module implements WebAssembly ABI 1 but exports ec_render2".into()), + }; let r = match r { Ok(0) => { inst.memory.read(&inst.store, base + params_bytes, &mut buf[params_bytes..]).map_err(err)?; - for (px, b) in frame.pixels.iter_mut().zip(buf[params_bytes..].as_chunks::<16>().0.iter()) { - for (c, v) in px.iter_mut().zip(b.as_chunks::<4>().0.iter()) { - *c = f32::from_le_bytes([v[0], v[1], v[2], v[3]]); - } - } + read_pixels(&buf[params_bytes..], frame.pixels); Ok(()) } Ok(code) => Err(format!("ec_render returned error {code}")), @@ -156,4 +199,170 @@ impl EffectPlugin for WasmPlugin { } r } + + /// ABI 2: parameters, the current frame, then the previous and next frames; `ec_render2`. + /// The neighbour buffers are always allocated (zeroed when absent), so a module can read + /// both without a null check; `flags` says which hold real frames. + fn render_v2( + &self, + frame: &mut PluginFrame, + params: &PluginParams, + time: f64, + prev: Option<(f64, &PluginImage)>, + next: Option<(f64, &PluginImage)>, + ) -> Result<(), String> { + let n = frame.pixels.len(); + let params_bytes = params.flat.len() * 8; + let frame_bytes = n * 16; + let total = params_bytes + frame_bytes * 3; + if total > i32::MAX as usize { + return Err("frame too large for a 32-bit plug-in".into()); + } + let prev_px = prev.map(|(t, img)| (t, img.on_grid(frame.width, frame.height, frame.origin, frame.scale))); + let next_px = next.map(|(t, img)| (t, img.on_grid(frame.width, frame.height, frame.origin, frame.scale))); + let prev = prev_px.as_ref().filter(|(_, px)| px.len() == n); + let next = next_px.as_ref().filter(|(_, px)| px.len() == n); + let mut inst = self.take()?; + inst.store.set_fuel(FUEL_BASE + FUEL_PER_PIXEL * (n as u64 * 3)).map_err(err)?; + let base = inst.alloc.call(&mut inst.store, total as i32).map_err(err)? as u32 as usize; + let mut buf: Vec = Vec::with_capacity(total); + for v in params.flat { + buf.extend_from_slice(&v.to_le_bytes()); + } + push_pixels(&mut buf, frame.pixels); + push_neighbour(&mut buf, prev, frame_bytes); + push_neighbour(&mut buf, next, frame_bytes); + inst.memory.write(&mut inst.store, base, &buf).map_err(|e| format!("ec_alloc returned a buffer out of bounds: {e}"))?; + let px_ptr = (base + params_bytes) as i32; + let prev_ptr = (base + params_bytes + frame_bytes) as i32; + let next_ptr = (base + params_bytes + frame_bytes * 2) as i32; + let flags = i32::from(prev.is_some()) | (i32::from(next.is_some()) << 1); + let prev_time = prev.map_or(0.0, |(t, _)| *t); + let next_time = next.map_or(0.0, |(t, _)| *t); + let r = match &inst.render { + Renderer::V2(f) => f + .call( + &mut inst.store, + ( + px_ptr, + frame.width as i32, + frame.height as i32, + base as i32, + params.flat.len() as i32, + time, + frame.scale, + prev_ptr, + prev_time, + next_ptr, + next_time, + flags, + ), + ) + .map_err(|e| format!("ec_render2 trapped: {e}")), + Renderer::V1(_) => return Err("the module implements WebAssembly ABI 2 but exports ec_render".into()), + }; + let r = match r { + Ok(0) => { + let mut out = vec![0u8; frame_bytes]; + inst.memory.read(&inst.store, base + params_bytes, &mut out).map_err(err)?; + read_pixels(&out, frame.pixels); + Ok(()) + } + Ok(code) => Err(format!("ec_render2 returned error {code}")), + Err(e) => Err(e), + }; + if r.is_ok() { + self.give_back(inst); + } + r + } +} + +/// Append pixels to the little-endian buffer the module reads. +fn push_pixels(buf: &mut Vec, px: &[[f32; 4]]) { + for p in px { + for c in p { + buf.extend_from_slice(&c.to_le_bytes()); + } + } +} + +/// The neighbour's pixels, or `frame_bytes` zeroed bytes when there is no frame. +fn push_neighbour(buf: &mut Vec, neighbour: Option<&(f64, Vec<[f32; 4]>)>, frame_bytes: usize) { + match neighbour { + Some((_, px)) => push_pixels(buf, px), + None => buf.resize(buf.len() + frame_bytes, 0), + } +} + +/// Read the little-endian pixels the module wrote back. +fn read_pixels(bytes: &[u8], pixels: &mut [[f32; 4]]) { + for (px, b) in pixels.iter_mut().zip(bytes.as_chunks::<16>().0.iter()) { + for (c, v) in px.iter_mut().zip(b.as_chunks::<4>().0.iter()) { + *c = f32::from_le_bytes([v[0], v[1], v[2], v[3]]); + } + } +} + +/// The layer times of the frames around `time` on a `fps` grid: the frame before and after it +/// at a frame boundary, the two frames that bracket it between frames. +fn neighbour_times(time: f64, fps: f64) -> (f64, f64) { + if !fps.is_finite() || fps <= 0.0 { + return (time - 1.0 / 30.0, time + 1.0 / 30.0); + } + let step = 1.0 / fps; + let at = time * fps; + // Frame times are not exact in floating point: at NTSC rates `time * fps` often lands a few + // ulps above or below an integer. Treat a near-integer as a frame boundary, so the current + // frame is never handed back as its own neighbour. + if (at - at.round()).abs() < 1e-6 { (time - step, time + step) } else { (at.floor() / fps, at.ceil() / fps) } +} + +impl EffectPlugin for WasmPlugin { + fn manifest(&self) -> &PluginManifest { + &self.manifest + } + + fn source(&self) -> String { + self.source.clone() + } + + fn reads_other_times(&self) -> bool { + self.abi >= 2 + } + + fn render(&self, frame: &mut PluginFrame, params: &PluginParams, time: f64) -> Result<(), String> { + if self.abi == 1 { self.render_v1(frame, params, time) } else { self.render_v2(frame, params, time, None, None) } + } + + fn render_v2(&self, frame: &mut PluginFrame, params: &PluginParams, time: f64, host: &dyn PluginHost) -> Result<(), String> { + if self.abi == 1 { + return self.render_v1(frame, params, time); + } + let (prev_time, next_time) = neighbour_times(time, host.frame_rate()); + let prev = host.input_at(prev_time); + let next = host.input_at(next_time); + let prev = prev.as_ref().map(|img| (prev_time, img)); + let next = next.as_ref().map(|img| (next_time, img)); + self.render_v2(frame, params, time, prev, next) + } +} + +#[cfg(test)] +mod tests { + use super::neighbour_times; + + /// NTSC frame times do not multiply back exactly; every frame boundary must still get the + /// frames either side of it, never the frame itself. + #[test] + fn frame_boundaries_get_their_neighbours_at_ntsc_rates() { + let fps = 24000.0 / 1001.0; + for n in 0..2400 { + // 24000/1001 fps at 254 016 000 000 ticks/s, as `Tick` stores it. + let time = (n * 10_594_584_000_i64) as f64 / 254_016_000_000.0; + let (prev, next) = neighbour_times(time, fps); + assert!((prev - (time - 1.0 / fps)).abs() < 1e-9, "frame {n}: prev {prev}, current {time}"); + assert!((next - (time + 1.0 / fps)).abs() < 1e-9, "frame {n}: next {next}, current {time}"); + } + } } diff --git a/crates/project/src/build.rs b/crates/project/src/build.rs index 1aa8d7c90..7a960dbfb 100644 --- a/crates/project/src/build.rs +++ b/crates/project/src/build.rs @@ -935,6 +935,7 @@ pub fn layer(project: &mut Project, comp: &Comp, name: &str, source: LayerSource Layer { id, name: comp.unique_layer_name(name), + name_follows_text: None, source, label, comment: String::new(), diff --git a/crates/project/src/comp.rs b/crates/project/src/comp.rs index aa4ff7201..c0c401c82 100644 --- a/crates/project/src/comp.rs +++ b/crates/project/src/comp.rs @@ -1,7 +1,7 @@ use super::item::LayerId; use super::layer::{Layer, LayerSource}; use super::settings::{Marker, yes}; -use super::{Deserialize, FrameRate, Node, PropGroup, Serialize, Tick, Value, essential, styles}; +use super::{Deserialize, FrameRate, Node, PropGroup, Serialize, Tick, essential, styles}; /// 3D renderer of a composition. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -265,13 +265,22 @@ impl Comp { self.layers.iter().find(|l| matches!(l.source, LayerSource::Camera) && l.switches.video && l.is_active_at(t)) } - /// Unique layer name with a numeric suffix (`Shape Layer 2`). + /// `base`, or the next free numbered name when a layer already has it (`Shape Layer 2`, + /// `v-b1.mp4 2`; see `numbered_name`). pub fn unique_layer_name(&self, base: &str) -> String { if !self.layers.iter().any(|l| l.name == base) { return base.to_string(); } - let stem = base.trim_end_matches(|c: char| c.is_ascii_digit()).trim_end(); - (2..).map(|i| format!("{stem} {i}")).find(|n| !self.layers.iter().any(|l| &l.name == n)).unwrap_or_default() + let stem = crate::item::name_stem(base); + // The suffixes in use, gathered in one pass: trying each candidate against every layer + // made importing many layers of one name cubic. + let taken: std::collections::HashSet = self + .layers + .iter() + .filter_map(|l| l.name.strip_prefix(stem)?.strip_prefix(' ')) + .filter_map(|s| s.parse::().ok().filter(|n| n.to_string() == s)) + .collect(); + (2..).find(|i| !taken.contains(i)).map(|i| format!("{stem} {i}")).unwrap_or_default() } } @@ -286,20 +295,22 @@ fn timing_markers(m: &[Marker]) -> impl Iterator + '_ { } impl Comp { - /// Draws the same pixels as `o`: equal but for its layers' Audio, Lock and Shy switches, Hide - /// Shy Layers and the viewer's Resolution. + /// Draws the same pixels as `o`: equal but for its layers' Lock and Shy switches, Hide Shy + /// Layers, the viewer's Resolution, the work area (a preview and render range only) and, as + /// nothing draws their audio, its layers' Audio switches, Audio groups and audio effects. pub fn same_pixels(&self, o: &Comp) -> bool { - self.same_pixels_with(o, true) + self.same_pixels_with(o, true, &|_| false) } /// [`Self::same_pixels`], with the comp's and its layers' markers counting only when /// `with_markers`: only expressions read them, so while none does, adding or moving a marker /// (even during playback) leaves every rendered frame valid. Protected time markers with a - /// duration set the timing (Responsive Design), so those always count. - pub fn same_pixels_with(&self, o: &Comp, with_markers: bool) -> bool { + /// duration set the timing (Responsive Design), so those always count. A layer's audio counts + /// when `heard` says something draws it ([`crate::Project::heard_layers`]). + pub fn same_pixels_with(&self, o: &Comp, with_markers: bool, heard: &dyn Fn(LayerId) -> bool) -> bool { self.same_settings(o, with_markers) && self.layers.len() == o.layers.len() - && self.layers.iter().zip(&o.layers).all(|(a, b)| a.same_pixels_with(b, with_markers)) + && self.layers.iter().zip(&o.layers).all(|(a, b)| a.same_pixels_with(b, with_markers, heard(a.id))) } /// [`Self::same_pixels_with`] but for the layers. @@ -313,7 +324,7 @@ impl Comp { duration, display_start, background, - work_area, + work_area: _, layers: _, markers, shutter_angle, @@ -340,7 +351,6 @@ impl Comp { && *duration == o.duration && *display_start == o.display_start && *background == o.background - && *work_area == o.work_area && (if with_markers { *markers == o.markers } else { timing_markers(markers).eq(timing_markers(&o.markers)) }) && *shutter_angle == o.shutter_angle && *shutter_phase == o.shutter_phase @@ -358,54 +368,139 @@ impl Comp { && *essential == o.essential } - /// The comp-time span (`in_point..out_point` of every layer changed, added or removed, - /// widened by the shutter) outside which `self` draws the same pixels as `o`, so cached - /// frames there stay valid (#1641). `None` when the edit can reach any frame: a comp setting, - /// a layer reorder, Solo turning on or off, an expression (it reads anything), or a changed - /// layer another layer parents to, mattes with or picks in an effect. - pub fn changed_span(&self, o: &Comp) -> Option<(Tick, Tick)> { - fn reads(g: &PropGroup, changed: &[LayerId]) -> bool { + /// The comp-time spans where `self` may draw other pixels than `o` after an edit of some of + /// its layers (moved, trimmed, split, edited, added, removed): where the active layers differ + /// or a changed one draws differently, widened by the shutter. A trim reaches only the part it + /// cut, a split only the copy's half (#1641). A layer that reads a changed one (its parent, + /// track matte, a layer it picks in an effect or tracker) draws differently wherever it is + /// active, and so does a layer with an expression that may read other layers or items when anything + /// changed: here or, `elsewhere`, outside these layers (markers, layers that draw nothing, + /// other comps and items). `None` when the edit can reach any frame: a comp setting, a layer + /// reorder, Solo turning on or off, an environment layer. A layer's audio counts when `heard` + /// says something draws it, a layer's markers when `with_markers`. `touched` layers draw differently in spans the caller adds (a + /// precomp whose comp changed): they reach the layers that read them, not their own frames. + pub fn changed_spans( + &self, + o: &Comp, + with_markers: bool, + heard: &dyn Fn(LayerId) -> bool, + elsewhere: bool, + touched: &[LayerId], + ) -> Option> { + // An expression that may read outside its own layer: it names another comp, layer, + // footage, the project or its precomp's source, or its layer's `index` (a layer added or + // removed above shifts it). Its parent and the layers it picks in an effect are read + // through `referenced_layers` below. + // ponytail: text heuristic; misses another layer reached through a variable from a call + // without those words. Upgrade: record reads in the expression host. + fn reads_outside(g: &PropGroup) -> bool { g.children.iter().any(|c| match c { - Node::Prop(p) => { - p.expr.is_some() - || std::iter::once(&p.value) - .chain(p.keys.iter().map(|k| &k.value)) - .any(|v| matches!(v, Value::Layer(Some(id)) if changed.contains(&LayerId(*id)))) - } - Node::Group(g) => reads(g, changed), + Node::Prop(p) => p.expr.as_ref().is_some_and(|e| { + let t = e.text.to_lowercase().replace("thislayer", ""); + ["comp", "layer", "footage", "project", "source", "index"].iter().any(|w| t.contains(w)) + }), + Node::Group(g) => reads_outside(g), }) } - // Solo hides every other layer at every frame. - if !self.same_settings(o, true) || self.any_solo() != o.any_solo() { + fn any_expression(g: &PropGroup) -> bool { + g.children.iter().any(|c| match c { + Node::Prop(p) => p.expr.is_some(), + Node::Group(g) => any_expression(g), + }) + } + // Solo hides every other layer at every frame. (Comp markers count through `elsewhere`: + // an expression reading them names `thisComp`.) + if !self.same_settings(o, false) || self.any_solo() != o.any_solo() { return None; } let common = |a: &Comp, b: &Comp| a.layers.iter().map(|l| l.id).filter(|id| b.layer(*id).is_some()).collect::>(); if common(self, o) != common(o, self) { return None; } + // Changed, added or removed layers (each from both sides: its old and its new span), and + // those that draw the same apart from their span (a trim or split). Ids count: they seed + // randomness (noise, text randomisers), so a split's copy may draw differently. let mut changed = Vec::new(); - let mut span: Option<(Tick, Tick)> = None; - // Each changed layer comes up from both sides: its old and its new span. + let mut respanned = Vec::new(); + let mut keyed = Vec::new(); + let mut cuts = Vec::new(); for (l, other) in self.layers.iter().map(|l| (l, o.layer(l.id))).chain(o.layers.iter().map(|l| (l, self.layer(l.id)))) { - if other.is_some_and(|b| l.same_pixels(b)) { + if other.is_some_and(|b| l.same_pixels_with(b, with_markers, heard(l.id))) { continue; } + if l.environment || l.environment_background { + return None; + } + // (an expression on the layer can read its own in and out points and name, `inPoint`, + // `thisLayer.name`: then a trim or rename reaches all of it) + if let Some(b) = other + && !any_expression(&l.props) + && !any_expression(&b.props) + && (Layer { in_point: b.in_point, out_point: b.out_point, name: b.name.clone(), label: b.label, comment: b.comment.clone(), ..l.clone() }) + .same_pixels_with(b, with_markers, heard(l.id)) + { + respanned.push(l.id); + } else if let Some(b) = other + && let Some(spans) = l.keyframe_spans(b, with_markers, heard(l.id)) + { + // (drawn the same outside the keys it changed) + respanned.push(l.id); + keyed.extend(spans); + } changed.push(l.id); - let (s, e) = (l.in_point.min(l.out_point), l.in_point.max(l.out_point)); - span = Some(span.map_or((s, e), |(a, b)| (a.min(s), b.max(e)))); + cuts.extend([l.in_point, l.out_point]); } - let reaches = |l: &Layer| { - l.parent.is_some_and(|p| changed.contains(&p)) || l.track_matte.as_ref().is_some_and(|m| changed.contains(&m.layer)) || reads(&l.props, &changed) - }; - if self.layers.iter().chain(&o.layers).any(reaches) { - return None; + // The layers the change reaches besides: expressions, then whatever reads a reached layer. + let both = || self.layers.iter().chain(&o.layers); + let mut reached: Vec = Vec::new(); + if !changed.is_empty() || elsewhere || !touched.is_empty() { + reached.extend(both().filter(|l| reads_outside(&l.props)).map(|l| l.id)); } - // A frame at `t` samples cameras, lights and transforms over its shutter, - // `t + (phase + angle * 0..=1) / 360` frames, and draws the layers active at `t` itself. + // (each pass adds a layer or stops: at most one pass per layer) + loop { + let read = |l: &&Layer| { + !reached.contains(&l.id) + && l.referenced_layers().iter().any(|r| *r != l.id && (changed.contains(r) || reached.contains(r) || touched.contains(r))) + }; + let more: Vec = both().filter(read).map(|l| l.id).collect(); + if more.is_empty() { + break; + } + reached.extend(more); + } + reached.sort_unstable(); + reached.dedup(); + for l in both().filter(|l| reached.contains(&l.id)) { + if l.environment || l.environment_background { + return None; + } + cuts.extend([l.in_point, l.out_point]); + } + let (before, after) = self.shutter_margin(); + // Between two cuts the same layers are active; outside them no changed layer is. + cuts.sort_unstable(); + cuts.dedup(); + let draws_same = |l: &Layer| (!changed.contains(&l.id) || respanned.contains(&l.id)) && !reached.contains(&l.id); + let spans = cuts + .windows(2) + .filter_map(|w| { + let (&s, &e) = (w.first()?, w.last()?); + let active = |c: &Comp| c.layers.iter().filter(|l| l.is_active_at(s)).map(|l| l.id).collect::>(); + let same = active(self) == active(o) && self.layers.iter().filter(|l| l.is_active_at(s)).all(draws_same); + (!same).then(|| (s - before, e + after)) + }) + .chain(keyed.into_iter().map(|(s, e)| (s - before, e + after))) + .collect(); + Some(spans) + } + + /// How far a change at a time reaches the frames before and after it through the shutter: a + /// frame at `t` samples cameras, lights and transforms over its shutter, + /// `t + (phase + angle * 0..=1) / 360` frames, and draws the layers active at `t` itself. + pub fn shutter_margin(&self) -> (Tick, Tick) { let (a, p) = (self.shutter_angle / 360.0, self.shutter_phase / 360.0); let fd = self.frame_duration().seconds(); - let (before, after) = (Tick::from_seconds_f64(p.max(p + a).max(0.0) * fd), Tick::from_seconds_f64(-p.min(p + a).min(0.0) * fd)); - span.map(|(s, e)| (s - before, e + after)) + (Tick::from_seconds_f64(p.max(p + a).max(0.0) * fd), Tick::from_seconds_f64(-p.min(p + a).min(0.0) * fd)) } /// Some layer is soloed: only the soloed layers draw. @@ -413,18 +508,21 @@ impl Comp { self.layers.iter().any(|l| l.switches.solo && l.source.is_av()) } - /// The comp with those switches and the Resolution at their defaults (borrowed when they - /// already are), for keys that hash the whole comp. + /// The comp with those switches, the Resolution and the work area at their defaults (borrowed + /// when they already are), for keys that hash the whole comp. pub fn pixel_form(&self) -> std::borrow::Cow<'_, Comp> { - self.pixel_form_with(true) + self.pixel_form_with(true, &|_| false) } /// [`Self::pixel_form`], also without the comp's plain markers and its layers' markers when not - /// `with_markers` (see [`Self::same_pixels_with`] and [`Project::reads_markers`]). - pub fn pixel_form_with(&self, with_markers: bool) -> std::borrow::Cow<'_, Comp> { + /// `with_markers` (see [`Self::same_pixels_with`] and [`Project::reads_markers`]), and with the + /// audio of the layers `heard` doesn't name at its defaults ([`Layer::picture_form`]). + pub fn pixel_form_with(&self, with_markers: bool, heard: &dyn Fn(LayerId) -> bool) -> std::borrow::Cow<'_, Comp> { + let pictures: Vec> = self.layers.iter().map(|l| l.picture_form(heard(l.id))).collect(); if !self.hide_shy && self.resolution.is_auto() - && self.layers.iter().all(|l| l.switches == l.switches.pixels()) + && self.work_area == (Tick::ZERO, Tick::ZERO) + && pictures.iter().all(Option::is_none) && (with_markers || (self.markers.iter().all(is_timing_marker) && self.layers.iter().all(|l| l.markers.is_empty()))) { return std::borrow::Cow::Borrowed(self); @@ -432,11 +530,14 @@ impl Comp { let mut c = self.clone(); c.hide_shy = false; c.resolution = Resolution::Auto; + c.work_area = (Tick::ZERO, Tick::ZERO); if !with_markers { c.markers.retain(is_timing_marker); } - for l in &mut c.layers { - l.switches = l.switches.pixels(); + for (l, picture) in c.layers.iter_mut().zip(pictures) { + if let Some(p) = picture { + *l = p; + } if !with_markers { l.markers.clear(); } diff --git a/crates/project/src/dirty.rs b/crates/project/src/dirty.rs new file mode 100644 index 000000000..a83ca35d9 --- /dev/null +++ b/crates/project/src/dirty.rs @@ -0,0 +1,112 @@ +//! Which frames of a comp an edit can change: frame caches keep the others. + +use super::comp::Comp; +use super::item::{Heard, ItemId}; +use super::layer::{Layer, LayerSource, reads_other_frames}; +use super::{Arc, GroupKind, Node, Project, Tick}; + +/// Precomps nested deeper than this count as changed wherever they show. +const MAX_DEPTH: usize = 32; + +type Seen = std::collections::HashMap>>; + +impl Project { + /// The comp-time spans of `comp` where `self` may draw other pixels than `old` (the project + /// before an edit): [`Comp::changed_spans`] of its layers, and for a precomp whose comp + /// changed, the spans that comp changed in, where the precomp shows them (#1641). Layers that + /// can't change the picture ([`Project::silent_layers`]) don't count, nor does the audio of + /// layers no effect draws it from (`heard`, best of both states). Expressions can read + /// anything, so any change (`outside` these comps too: another comp, an item's name) reaches + /// the layers that have one. `None` when the edit can reach any frame. + pub fn dirty_spans(&self, old: &Project, comp: ItemId, heard: &Heard, outside: bool) -> Option> { + self.dirty_spans_at(old, comp, heard, outside, 0, &mut std::collections::HashMap::new()) + } + + /// `seen`: the spans of the comps already walked in this call, so a precomp shared by many + /// layers is walked once. + fn dirty_spans_at(&self, old: &Project, comp: ItemId, heard: &Heard, outside: bool, depth: usize, seen: &mut Seen) -> Option> { + if depth > MAX_DEPTH { + return None; + } + if let Some(spans) = seen.get(&comp) { + return spans.clone(); + } + let spans = self.comp_dirty_spans(old, comp, heard, outside, depth, seen); + seen.insert(comp, spans.clone()); + spans + } + + fn comp_dirty_spans(&self, old: &Project, comp: ItemId, heard: &Heard, outside: bool, depth: usize, seen: &mut Seen) -> Option> { + let (new_c, old_c) = (self.comp_arc(comp)?, old.comp_arc(comp)?); + // Expressions may read what changed elsewhere, even from comps that didn't change. + let reads_elsewhere = heard.expressions && outside; + let quiet = self.silent_layers(comp, &new_c, heard); + // An edit of this comp is outside the comps it nests: their expressions may read it + // (`comp("Main").layer("Controls")`, at their own time). + let nested_outside = outside || !Arc::ptr_eq(&new_c, &old_c); + // Precomps (drawing the same comp before and after) whose comp changed: where they show it. + let mut touched = Vec::new(); + let mut nested = Vec::new(); + for l in new_c.layers.iter().filter(|l| !quiet.contains(&l.id)) { + let LayerSource::Comp { item } = l.source else { continue }; + if old_c.layer(l.id).is_none_or(|before| before.source != l.source) { + continue; + } + // (an unchanged `Arc` says nothing of the comps nested in it: walk it anyway) + let (Some(n), Some(_)) = (self.comp_arc(item), old.comp_arc(item)) else { continue }; + let inner = self.dirty_spans_at(old, item, heard, nested_outside, depth + 1, seen); + if inner.as_ref().is_some_and(Vec::is_empty) { + continue; + } + touched.push(l.id); + nested.extend(shown(l, &new_c, &n, inner)); + } + if Arc::ptr_eq(&new_c, &old_c) && touched.is_empty() && !reads_elsewhere { + return Some(vec![]); + } + let picture = |p: &Project, c: &Comp| { + let mut c = c.clone(); + let quiet = p.silent_layers(comp, &c, heard); + c.layers.retain(|l| !quiet.contains(&l.id)); + c + }; + let (a, b) = (picture(old, &old_c), picture(self, &new_c)); + let elsewhere = heard.expressions && (outside || !new_c.same_pixels_with(&old_c, true, &|l| heard.contains(comp, l)) || !touched.is_empty()); + let mut spans = b.changed_spans(&a, heard.expressions, &|l| heard.contains(comp, l), elsewhere, &touched)?; + spans.extend(nested); + Some(spans) + } +} + +/// The comp-time spans of `outer` where its precomp layer `l` shows the spans `inner` of its comp +/// `n` (`None`: all of it), widened by `outer`'s shutter. A time remap, Responsive Design +/// timing or an effect reading the layer at other times (Echo, Posterize Time…: [`reads_other_frames`], +/// or an effect picking the layer itself) can show any nested time anywhere: then the layer's +/// whole span. +fn shown(l: &Layer, outer: &Comp, n: &Comp, inner: Option>) -> Vec<(Tick, Tick)> { + let (before, after) = outer.shutter_margin(); + let whole = vec![(l.in_point - before, l.out_point + after)]; + let responsive = (l.stretch - 100.0).abs() > 1e-9 && n.markers.iter().any(|m| m.protected && m.duration > Tick::ZERO); + let Some(inner) = inner else { return whole }; + if l.props.get("timeRemap").is_some() || responsive || reads_itself_elsewhen(l) { + return whole; + } + // (a nested frame either side: Preserve Frame Rate holds nested frames, Frame Blending mixes + // neighbours) + let fd = n.frame_duration(); + inner + .into_iter() + .filter_map(|(s, e)| { + let (x, y) = (l.comp_time(s - fd), l.comp_time(e + fd)); + let (lo, hi) = (x.min(y).max(l.in_point), x.max(y).min(l.out_point)); + (lo <= hi).then(|| (lo - before, hi + after)) + }) + .collect() +} + +/// Some effect of `l` reads the layer at other times ([`reads_other_frames`]) or picks the layer +/// itself (a layer parameter set to its own layer). +fn reads_itself_elsewhen(l: &Layer) -> bool { + let time_fx = |c: &Node| matches!(c, Node::Group(f) if matches!(&f.kind, GroupKind::Effect { effect } if reads_other_frames(effect))); + l.picked_layers().contains(&l.id) || l.props.group("effects").is_some_and(|e| e.children.iter().any(time_fx)) +} diff --git a/crates/project/src/footage.rs b/crates/project/src/footage.rs index 8cf07ea2e..eeace5e81 100644 --- a/crates/project/src/footage.rs +++ b/crates/project/src/footage.rs @@ -255,14 +255,27 @@ pub struct Footage { #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub alphabetical: bool, /// Interpret Footage ▸ Start Timecode ▸ Override Start: the frame (at the footage's frame - /// rate) its timecode shows at its first frame. `None` = Use Source File Timecode (0: file - /// timecode isn't read). It only relabels source time, as in After Effects. + /// rate) its timecode shows at its first frame. `None` = Use Source File Timecode (shown + /// from 0: [`Footage::file_timecode`] isn't used here yet). It only relabels source time, as + /// in After Effects. #[serde(default, skip_serializing_if = "Option::is_none")] pub start_timecode: Option, + /// The start timecode recorded in the file, in frames at its own frame rate (`native_rate`, + /// else `frame_rate`). Read when probing; importing an EDL uses it to turn the list's source + /// timecodes into footage time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file_timecode: Option, /// Markers the file carries (a WAV's cue points and XMP markers), at footage time. A layer /// made from the footage starts with them, and Update Markers From Source copies new ones. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub markers: Vec, + /// PDF / Illustrator footage (`.pdf`, `.ai`; not EPS) from an After Effects project: the page + /// is framed as After Effects places it (the ArtBox, `/Rotate` ignored) and drawn to fill + /// `width` × `height`, the size After Effects stored, which the layers' anchors and masks are + /// measured against (#3099). Other footage (and every project saved before this field) shows + /// the page as a PDF viewer does, at its own size. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub placed_page: bool, } fn is_default(v: &T) -> bool { @@ -299,7 +312,9 @@ impl Default for Footage { page: 0, alphabetical: false, start_timecode: None, + file_timecode: None, markers: vec![], + placed_page: false, } } } diff --git a/crates/project/src/item.rs b/crates/project/src/item.rs index 1ef3d1f0a..b055c60ba 100644 --- a/crates/project/src/item.rs +++ b/crates/project/src/item.rs @@ -4,12 +4,36 @@ use super::layer::LayerSource; use super::settings::{APP_VERSION, ProjectError, ProjectSettings, SCHEMA_VERSION, SavedView}; use super::{Arc, BTreeMap, Deserialize, FrameRate, Label, Project, Serialize, Tick, file_check, limits}; +/// `base` numbered with the lowest counter from 2 for which `taken` is false: a copy of an item or +/// another layer of the same name. A number set off by a space is a counter and is replaced +/// (`Red Solid 1` → `Red Solid 2`, `shot 2` → `shot 3`); digits that end a word belong to the +/// name and stay (`v-b1.mp4` → `v-b1.mp4 2`, `clip2.mov` → `clip2.mov 2`). +/// `base` without a trailing ` N`: digits are dropped only when a space separates them from a +/// nonempty stem, so `v-b1.mp4` and `Layer1` keep theirs. +pub(crate) fn name_stem(base: &str) -> &str { + let head = base.trim_end_matches(|c: char| c.is_ascii_digit()); + match head.strip_suffix(' ') { + Some(stem) if head.len() < base.len() && !stem.trim_end().is_empty() => stem.trim_end(), + _ => base.trim_end(), + } +} + +pub(crate) fn numbered_name(base: &str, taken: impl Fn(&str) -> bool) -> String { + let stem = name_stem(base); + (2u64..).map(|k| format!("{stem} {k}")).find(|n| !taken(n)).unwrap_or_default() +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct ItemId(pub u64); #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct LayerId(pub u64); +/// An explicit "None" in a layer parameter whose unset value means the owning layer (Compound +/// Blur's Blur Layer, Displacement Map's map, Set Matte's matte): `Value::Layer(Some(NO_LAYER))`. +/// Ids start at 1, so it never names a layer; it resolves to no layer and shows as "None". +pub const NO_LAYER: u64 = 0; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type")] #[allow(clippy::large_enum_variant)] @@ -37,6 +61,13 @@ pub struct Item { } impl Item { + /// Whether an external original or proxy is known to be offline, even if the other can + /// still provide a preview. Generated items and embedded data have no external dependency. + pub fn has_missing_footage(&self) -> bool { + let missing = |f: &crate::Footage| f.missing && !f.path.is_empty() && f.kind != FootageKind::Data; + matches!(&self.kind, ItemKind::Footage(f) if missing(f)) || self.proxy.as_ref().is_some_and(|p| missing(&p.footage)) + } + pub fn type_name(&self) -> &'static str { match &self.kind { ItemKind::Folder => "Folder", @@ -113,6 +144,78 @@ impl Project { self.comps().any(|(_, c)| c.layers.iter().any(|l| any_expr(&l.props))) } + /// The layers whose audio something draws ([`Heard`]): those a layer picks in an effect (an + /// Audio Spectrum or Audio Waveform's Audio Layer, even on itself), and the layers inside a + /// picked precomp, whose audio it mixes. With an expression anywhere (it can read any layer's + /// Audio Levels) every layer may be heard ([`Heard::contains`]). + pub fn heard_layers(&self) -> Heard { + let mut layers = std::collections::BTreeSet::new(); + let mut stack: Vec<(ItemId, LayerId)> = + self.comps().flat_map(|(id, c)| c.layers.iter().flat_map(move |l| l.picked_layers().into_iter().map(move |r| (*id, r)))).collect(); + // (bounded: each (comp, layer) is visited once) + while let Some((cid, lid)) = stack.pop() { + if !layers.insert((cid, lid)) { + continue; + } + let inner = self.comp(cid).and_then(|c| c.layer(lid)).and_then(|l| match l.source { + LayerSource::Comp { item } => Some(item), + _ => None, + }); + if let Some(inner) = inner + && let Some(c) = self.comp(inner) + { + stack.extend(c.layers.iter().map(|l| (inner, l.id))); + } + } + Heard { expressions: self.reads_markers(), audio_exprs: self.reads_audio(), layers } + } + + /// Some expression may read a layer's audio: its text names it (`audio`, `"Audio Levels"`, + /// `"ADBE Audio Group"`) or walks properties by index (`layer(1)(3)`). + // ponytail: text heuristic; misses an index walk through a variable (`g = layer(1); g(3)`). + // Upgrade: record audio reads in the expression host. + fn reads_audio(&self) -> bool { + fn reads(text: &str) -> bool { + let t: String = text.chars().filter(|c| !c.is_whitespace()).collect::().to_lowercase(); + t.contains("audio") || t.match_indices(")(").any(|(i, _)| t.get(i + 2..).and_then(|r| r.chars().next()).is_some_and(|c| c.is_ascii_digit())) + } + fn any(g: &crate::PropGroup) -> bool { + g.children.iter().any(|c| match c { + crate::Node::Prop(p) => p.expr.as_ref().is_some_and(|e| reads(&e.text)), + crate::Node::Group(sub) => any(sub), + }) + } + self.comps().any(|(_, c)| c.layers.iter().any(|l| any(&l.props))) + } + + /// Layers of `comp` (item `id`) that can't change its pixels: footage layers of files without + /// video (music, voice-over) and layers with the Video switch off, unless another layer reads + /// them (a hidden track matte) or something draws their audio ([`Self::heard_layers`]: the + /// Audio Spectrum's Audio Layer, also from a comp that nests this one). Cameras, lights, + /// nulls, environment layers and soloed layers (Solo hides every other layer) are never + /// silent. Expressions, which can read any layer, are the caller's concern. + pub fn silent_layers(&self, id: ItemId, comp: &Comp, heard: &Heard) -> std::collections::BTreeSet { + let read: std::collections::BTreeSet = + comp.layers.iter().flat_map(|l| l.referenced_layers().into_iter().filter(move |r| *r != l.id)).collect(); + comp.layers + .iter() + .filter(|l| { + let no_picture = match &l.source { + LayerSource::Footage { item } => matches!(self.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if !f.has_video), + _ => false, + }; + // (environment layers light Advanced 3D scenes without being drawn) + (no_picture || l.source.is_av() && !l.switches.video) + && !l.switches.solo + && !l.environment + && !l.environment_background + && !read.contains(&l.id) + && !heard.picked(id, l.id) + }) + .map(|l| l.id) + .collect() + } + /// Allocate an id (items, layers and property uids share one counter). pub fn alloc(&mut self) -> u64 { let id = self.next_id; @@ -162,13 +265,11 @@ impl Project { pub fn find_by_name(&self, name: &str) -> Option<&Item> { self.items.values().find(|i| i.name == name) } - /// A numbered name for a copy of `base` that no project item has (Edit ▸ Duplicate): its - /// trailing number is dropped and the lowest free one from 2 is added (`Comp 1` → `Comp 2`, - /// `Name` → `Name 2`, then `Name 3`). Items for which `ignore` holds don't count. + /// A numbered name for a copy of `base` that no project item has (Edit ▸ Duplicate), as + /// `numbered_name` gives it (`Comp 1` → `Comp 2`, `Name` → `Name 2`, then `Name 3`, + /// `v-b1.mp4` → `v-b1.mp4 2`). Items for which `ignore` holds don't count. pub fn numbered_item_name(&self, base: &str, ignore: impl Fn(&Item) -> bool) -> String { - let stem = base.trim_end_matches(|c: char| c.is_ascii_digit()).trim_end(); - let taken = |n: &str| self.items.values().any(|i| i.name == n && !ignore(i)); - (2u64..).map(|k| format!("{stem} {k}")).find(|n| !taken(n)).unwrap_or_default() + numbered_name(base, |n| self.items.values().any(|i| i.name == n && !ignore(i))) } /// `base` when no project item has that name, else the next free numbered name as /// [`Project::numbered_item_name`] gives it. Items for which `ignore` holds don't count. @@ -305,6 +406,79 @@ impl Project { for item in p.items.values_mut() { limits::repair_item(item, &mut notes); } + // An item inside a composition, a solid or footage (or inside an item that is not there) is + // in no folder: it would not be listed under any parent. It moves to the top level. + let folders: std::collections::BTreeSet = p.items.values().filter(|i| i.is_folder()).map(|i| i.id).collect(); + for item in p.items.values_mut() { + if let Some(parent) = item.parent + && !folders.contains(&parent) + { + notes.push(format!("{}: its parent is not a folder, moved to the top level", item.name)); + item.parent = None; + } + } Ok((p, notes)) } } + +/// The layers whose audio something draws ([`Project::heard_layers`]): their Audio switch, Audio +/// group and audio effects change pixels. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Heard { + /// Some layer has an expression (it can read anything). + pub expressions: bool, + /// Some expression may read a layer's audio ([`Project::reads_audio`]). + audio_exprs: bool, + layers: std::collections::BTreeSet<(ItemId, LayerId)>, +} + +impl Heard { + /// Something may draw the audio of layer `layer` of comp `comp`: a layer picks it + /// ([`Self::picked`]) or an expression may read it. + pub fn contains(&self, comp: ItemId, layer: LayerId) -> bool { + self.audio_exprs || self.picked(comp, layer) + } + + /// A layer picks layer `layer` of comp `comp` in an effect (or a precomp of it), so draws its + /// audio. Expressions aside: they draw in their own layers. + pub fn picked(&self, comp: ItemId, layer: LayerId) -> bool { + self.layers.contains(&(comp, layer)) + } + + /// Heard in `self` or in `o` (the states before and after an edit). + pub fn union(mut self, o: &Heard) -> Heard { + self.expressions |= o.expressions; + self.audio_exprs |= o.audio_exprs; + self.layers.extend(o.layers.iter().copied()); + self + } +} + +#[cfg(test)] +mod availability_tests { + use super::*; + + #[test] + fn inventory_status_tracks_original_and_proxy_independently() { + let footage = crate::Footage { path: "/original.png".into(), ..Default::default() }; + let mut item = Item { + id: ItemId(1), + name: "Plate".into(), + label: Label::None, + comment: String::new(), + parent: None, + kind: ItemKind::Footage(footage.clone()), + proxy: None, + }; + assert!(!item.has_missing_footage()); + item.proxy = Some(Box::new(Proxy { footage: crate::Footage { path: "/proxy.png".into(), missing: true, ..footage.clone() }, enabled: false })); + assert!(item.has_missing_footage(), "unused missing proxies still need repair"); + item.proxy.as_mut().unwrap().footage.missing = false; + assert!(!item.has_missing_footage()); + if let ItemKind::Footage(f) = &mut item.kind { + f.missing = true; + } + item.proxy.as_mut().unwrap().enabled = true; + assert!(item.has_missing_footage(), "a working proxy does not make the original available"); + } +} diff --git a/crates/project/src/layer.rs b/crates/project/src/layer.rs index 3d7676b28..b13c1d980 100644 --- a/crates/project/src/layer.rs +++ b/crates/project/src/layer.rs @@ -1,6 +1,6 @@ use super::item::{ItemId, LayerId}; use super::settings::Marker; -use super::{BlendMode, Deserialize, Label, ParamUi, PropGroup, Property, Serialize, Tick}; +use super::{BlendMode, Deserialize, GroupKind, Label, Node, ParamUi, PropGroup, Property, Serialize, Tick, Value}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum LightKind { @@ -182,29 +182,125 @@ impl Default for Switches { } } -// What a frame's pixels depend on. Caches key on it: the Audio, Lock and Shy switches and Hide -// Shy Layers don't change pixels, so toggling them keeps cached frames (#103). +// What a frame's pixels depend on. Caches key on it: the Lock and Shy switches and Hide Shy +// Layers never change pixels, and the Audio switch, the Audio group and audio effects change them +// only when something draws the layer's audio (a waveform or spectrum picks it, see +// [`crate::Project::heard_layers`]), so editing those keeps cached frames (#103). + +/// Is `id` an audio effect (applied by the audio mix rather than the compositor)? +pub fn is_audio_effect(id: &str) -> bool { + id.starts_with("ec.audio.") +} + +/// Does effect `id` read its own layer at other times (`EffectHost::self_at`, `layer_at` on +/// itself): the time effects (Echo, Posterize Time, Timewarp…), simulations, temporal smoothing +/// and analysis (Remove Grain, Auto Levels, Color Stabilizer's reference frame, Warp Stabilizer, +/// Roto Brush…) and Clone strokes with a time offset? On a precomp layer, a change at one nested +/// time then reaches frames of the layer far from where it shows. Plug-in effects (every id +/// outside `ec.`) count too: plug-in API 2 reads the input at other times (`PluginHost`). +// ponytail: hand-kept list of the effects that call `self_at`; a new one must be added here. +pub fn reads_other_frames(id: &str) -> bool { + !id.starts_with("ec.") || id.starts_with("ec.time.") || id.starts_with("ec.sim.") || READS_OTHER_FRAMES.contains(&id) +} + +/// The effects outside `ec.time.` and `ec.sim.` that read their own layer at other times. +const READS_OTHER_FRAMES: &[&str] = &[ + "ec.noise.removegrain", + "ec.color.autolevels", + "ec.color.autocontrast", + "ec.color.autocolor", + "ec.color.shadowhighlight", + "ec.color.colorstabilizer", + "ec.matte.refinesoft", + "ec.matte.refinehard", + "ec.matte.rotobrush", + "ec.matte.objectmatte", + "ec.blur.camerashakedeblur", + "ec.distort.rollingshutterrepair", + "ec.distort.warpstabilizer", + "ec.key.ccsimplewireremoval", + "ec.paint.paint", +]; impl Switches { /// These switches with Audio, Lock and Shy at their defaults. pub fn pixels(&self) -> Switches { Switches { audio: true, locked: false, shy: false, ..self.clone() } } + + /// The switches that change the pixels of a layer: [`Self::pixels`], keeping Audio when + /// something draws the layer's audio (`heard`). + pub fn picture(&self, heard: bool) -> Switches { + Switches { audio: if heard { self.audio } else { true }, ..self.pixels() } + } +} + +/// A node only the audio mix reads: the layer's Audio group, an audio effect. +fn audio_only(n: &Node, root: bool) -> bool { + match n { + Node::Group(g) => (root && g.match_id == "audio") || matches!(&g.kind, GroupKind::Effect { effect } if is_audio_effect(effect)), + Node::Prop(_) => false, + } +} + +/// `a` and `b` are equal but for their audio-only nodes ([`audio_only`]: the root's Audio group, +/// the effects in its Effects group that are audio effects). +fn same_picture_props(a: &PropGroup, b: &PropGroup) -> bool { + fn head(a: &PropGroup, b: &PropGroup) -> bool { + // Every field (no `..`: a new field must be considered here). + let PropGroup { uid, match_id, name, kind, enabled, label, children: _ } = a; + *uid == b.uid && *match_id == b.match_id && *name == b.name && *kind == b.kind && *enabled == b.enabled && *label == b.label + } + fn children(a: &PropGroup, b: &PropGroup, root: bool) -> bool { + let mut x = a.children.iter().filter(|n| !audio_only(n, root)); + let mut y = b.children.iter().filter(|n| !audio_only(n, root)); + loop { + match (x.next(), y.next()) { + (None, None) => return true, + (Some(Node::Group(g)), Some(Node::Group(h))) if root && g.match_id == "effects" && h.match_id == "effects" => { + if !(head(g, h) && children(g, h, false)) { + return false; + } + } + (Some(m), Some(n)) if m == n => {} + _ => return false, + } + } + } + head(a, b) && children(a, b, true) +} + +/// `g` (a layer's property tree) without its audio-only nodes ([`same_picture_props`]). +fn picture_props(g: &PropGroup) -> PropGroup { + let mut g = g.clone(); + g.children.retain(|n| !audio_only(n, true)); + for n in &mut g.children { + if let Node::Group(e) = n + && e.match_id == "effects" + { + e.children.retain(|n| !audio_only(n, false)); + } + } + g } impl Layer { - /// Draws the same pixels as `o`: equal but for the Audio, Lock and Shy switches. + /// Draws the same pixels as `o`: equal but for the Audio, Lock and Shy switches and what only + /// the audio mix reads (nothing draws its audio). pub fn same_pixels(&self, o: &Layer) -> bool { - self.same_pixels_with(o, true) + self.same_pixels_with(o, true, false) } /// [`Self::same_pixels`], with the markers counting only when `with_markers` (they are read by - /// expressions alone, so a project without any can edit them freely). - pub fn same_pixels_with(&self, o: &Layer, with_markers: bool) -> bool { + /// expressions alone, so a project without any can edit them freely) and the audio (the Audio + /// switch, the Audio group, audio effects) only when `heard`: something draws it. + pub fn same_pixels_with(&self, o: &Layer, with_markers: bool, heard: bool) -> bool { // Every field (no `..`: a new field must be considered here); the property tree last. let Layer { id, name, + // Whether the name follows the text changes no pixels until the name changes. + name_follows_text: _, source, label, comment, @@ -233,7 +329,7 @@ impl Layer { && *in_point == o.in_point && *out_point == o.out_point && *stretch == o.stretch - && switches.pixels() == o.switches.pixels() + && switches.picture(heard) == o.switches.picture(heard) && *blend_mode == o.blend_mode && *preserve_transparency == o.preserve_transparency && *track_matte == o.track_matte @@ -243,7 +339,100 @@ impl Layer { && *auto_orient == o.auto_orient && *environment == o.environment && *environment_background == o.environment_background - && *props == o.props + && (if heard { *props == o.props } else { same_picture_props(props, &o.props) }) + } + + /// The comp-time spans where `self` draws differently than `o` when the two differ only in + /// the keyframes of Transform properties (a key's value, ease or interpolation moved in the + /// Timeline or Graph Editor): from two keys before the first changed key to two after the + /// last (auto-Bezier and continuous tangents reach the neighbouring segments), to the + /// layer's in or out point past the first or last key (values hold there). `None` for any + /// other difference, a static value, an expression on the layer (it can read the keyed + /// property at other times), roving or muted keys, a time remap or a time effect (it reads other + /// times): those reach the layer's whole span. + pub fn keyframe_spans(&self, o: &Layer, with_markers: bool, heard: bool) -> Option> { + let transform = |l: &Layer| l.props.group("transform").cloned(); + let (t1, t0) = (transform(self)?, transform(o)?); + let reads_time = |l: &Layer| { + l.props.get("timeRemap").is_some() + || l.props.group("effects").is_some_and(|e| { + e.children.iter().any(|n| matches!(n, Node::Group(f) if matches!(&f.kind, GroupKind::Effect { effect } if reads_other_frames(effect)))) + }) + }; + let has_expr = |l: &Layer| { + let mut any = false; + l.props.walk("", &mut |_, p| any |= p.has_expression()); + any + }; + if reads_time(self) || reads_time(o) || has_expr(self) || has_expr(o) { + return None; + } + // Everything but the Transform group draws the same. + let rest = |l: &Layer| { + let mut l = l.clone(); + l.props.children.retain(|n| !matches!(n, Node::Group(g) if g.match_id == "transform")); + l + }; + let head = |g: &PropGroup| PropGroup { children: vec![], ..g.clone() }; + if !rest(self).same_pixels_with(&rest(o), with_markers, heard) || head(&t1) != head(&t0) || t1.children.len() != t0.children.len() { + return None; + } + let mut spans = Vec::new(); + for (n1, n0) in t1.children.iter().zip(&t0.children) { + if n1 == n0 { + continue; + } + let (Node::Prop(p1), Node::Prop(p0)) = (n1, n0) else { return None }; + let bare = |p: &Property| Property { keys: vec![], value: Value::Scalar(0.0), ..p.clone() }; + // (muted keys are skipped: the keys around an edit that play can be any distance away) + if bare(p1) != bare(p0) || p1.keys.is_empty() || p0.keys.is_empty() || p1.keys.iter().chain(&p0.keys).any(|k| k.roving || k.muted) { + return None; + } + // Keys only one side has as they are (added, removed, edited, moved). + let changed: Vec = + p1.keys.iter().filter(|k| !p0.keys.contains(k)).chain(p0.keys.iter().filter(|k| !p1.keys.contains(k))).map(|k| k.time).collect(); + let (Some(first), Some(last)) = (changed.iter().min(), changed.iter().max()) else { continue }; + // Two keys before the first changed one and two after the last, on either side (the + // first or last key when there are fewer: values hold beyond it). Past the first or + // last key the change reaches the in or out point (`None`). + let mut lo = Some(Tick(i64::MAX)); + let mut hi = Some(Tick(i64::MIN)); + for keys in [&p1.keys, &p0.keys] { + let before = keys.iter().filter(|k| k.time < *first).count(); + let back = if before == 0 { None } else { keys.get(before.saturating_sub(2)) }; + lo = lo.zip(back).map(|(a, k)| a.min(k.time)); + let upto = keys.iter().filter(|k| k.time <= *last).count(); + let ahead = if upto >= keys.len() { None } else { keys.get(upto.saturating_add(1).min(keys.len().saturating_sub(1))) }; + hi = hi.zip(ahead).map(|(a, k)| a.max(k.time)); + } + let (x, y) = (lo.map_or(self.in_point, |t| self.comp_time(t)), hi.map_or(self.out_point, |t| self.comp_time(t))); + let (x, y) = (x.min(y).max(self.in_point), x.max(y).min(self.out_point)); + if x <= y { + spans.push((x, y)); + } + } + Some(spans) + } + + /// This layer with what doesn't change its pixels at its defaults (see + /// [`Self::same_pixels_with`]), for keys that hash it; `None` when it already is. + pub fn picture_form(&self, heard: bool) -> Option { + let switches = self.switches.picture(heard); + let audio = !heard + && (self.props.children.iter().any(|n| audio_only(n, true)) + || self + .props + .children + .iter() + .any(|n| matches!(n, Node::Group(e) if e.match_id == "effects" && e.children.iter().any(|n| audio_only(n, false))))); + if switches == self.switches && !audio { + return None; + } + let mut l = Layer { switches, ..self.clone() }; + if audio { + l.props = picture_props(&self.props); + } + Some(l) } } @@ -283,10 +472,29 @@ pub enum AutoOrient { TowardsPointOfInterest, } +/// A stretch written as `null` (a NaN or infinite stretch: JSON holds neither, and auto-saves +/// write it so) reads as NaN, so the project still opens and loading brings it to 100 % with a +/// note ([`crate::limits::stretch`], #3247) instead of the whole file being refused. An infinite +/// stretch therefore also reopens at 100 %, not at ±9900 %. +fn stretch_or_nan<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(Option::::deserialize(d)?.unwrap_or(f64::NAN)) +} + +/// `t × mul / div` in ticks, within [`Tick::MIN`]..=[`Tick::MAX`] (the cast saturates, NaN is 0), +/// so a layer time of an extreme stretch can't overflow later tick arithmetic. +fn scaled(t: Tick, mul: f64, div: f64) -> Tick { + Tick(((t.0 as f64 * mul / div) as i64).clamp(Tick::MIN.0, Tick::MAX.0)) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Layer { pub id: LayerId, pub name: String, + /// A text layer's name follows the first line of its Source Text until the user renames it + /// (After Effects). `Some(true)`: it follows, `Some(false)`: the user named it. `None` (older + /// projects, layers made before this was recorded): see [`Layer::name_follows_text()`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name_follows_text: Option, pub source: LayerSource, pub label: Label, #[serde(default)] @@ -297,6 +505,7 @@ pub struct Layer { pub in_point: Tick, pub out_point: Tick, /// Time stretch in percent (100 = normal, negative = reversed). + #[serde(deserialize_with = "stretch_or_nan")] pub stretch: f64, pub switches: Switches, pub blend_mode: BlendMode, @@ -325,20 +534,86 @@ pub struct Layer { pub props: PropGroup, } +/// The name a text layer takes from its text: the first 40 characters of the first line. A line +/// ends at a line feed or at a bare carriage return (After Effects' paragraph break). +pub fn text_layer_name(text: &str) -> String { + text.split(['\r', '\n']).next().unwrap_or("").chars().take(40).collect() +} + +/// A text layer's default name when its text gives none: "Text", numbered "Text 2", "Text 3"… +fn is_default_text_name(name: &str) -> bool { + name == "Text" || name.strip_prefix("Text ").is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())) +} + impl Layer { + /// Whether this text layer's name follows its Source Text, whose first line gives the name + /// `current` (see [`text_layer_name`]). Without a recorded state (an older project), a name + /// that is empty, the text's own, or the default "Text"/"Text 2"… follows; any other name was + /// given by the user. + pub fn name_follows_text(&self, current: &str) -> bool { + self.name_follows_text.unwrap_or_else(|| self.name.is_empty() || self.name == current || is_default_text_name(&self.name)) + } + + /// The layers this layer reads: its parent, track matte, layer parameters (Displacement Map, + /// Audio Spectrum's Audio Layer…) and tracker targets. + pub fn referenced_layers(&self) -> Vec { + fn walk(g: &PropGroup, depth: usize, out: &mut Vec) { + if depth > 64 { + return; + } + if let GroupKind::Tracker { settings } = &g.kind + && let Some(t) = settings.target + { + out.push(t); + } + for c in &g.children { + match c { + Node::Prop(p) => { + for v in std::iter::once(&p.value).chain(p.keys.iter().map(|k| &k.value)) { + if let Value::Layer(Some(id)) = v { + out.push(LayerId(*id)); + } + } + } + Node::Group(sub) => walk(sub, depth + 1, out), + } + } + } + let mut out: Vec = self.parent.iter().copied().chain(self.track_matte.iter().map(|m| m.layer)).collect(); + walk(&self.props, 0, &mut out); + out + } + + /// Layers this one picks in an effect or tracker (an Audio Spectrum's Audio Layer, a + /// Displacement Map's map layer…), itself included: [`Self::referenced_layers`] without the + /// parent and the track matte. + pub fn picked_layers(&self) -> Vec { + let skip = usize::from(self.parent.is_some()) + usize::from(self.track_matte.is_some()); + self.referenced_layers().into_iter().skip(skip).collect() + } + pub fn is_active_at(&self, t: Tick) -> bool { t >= self.in_point && t < self.out_point } + /// The time stretch the layer plays at: [`Layer::stretch`] within + /// [`limits::stretch`](crate::limits::stretch) (a damaged value that got past loading, 0 or + /// NaN, never divides the layer's time by zero). + pub fn effective_stretch(&self) -> f64 { + crate::limits::stretch(self.stretch) + } + /// Layer time for a comp time (stretch-aware). pub fn layer_time(&self, comp_t: Tick) -> Tick { let d = comp_t - self.start_time; - if (self.stretch - 100.0).abs() < 1e-9 { d } else { Tick((d.0 as f64 * 100.0 / self.stretch) as i64) } + let s = self.effective_stretch(); + if (s - 100.0).abs() < 1e-9 { d } else { scaled(d, 100.0, s) } } /// Comp time for a layer time. pub fn comp_time(&self, layer_t: Tick) -> Tick { - if (self.stretch - 100.0).abs() < 1e-9 { self.start_time + layer_t } else { self.start_time + Tick((layer_t.0 as f64 * self.stretch / 100.0) as i64) } + let s = self.effective_stretch(); + if (s - 100.0).abs() < 1e-9 { self.start_time + layer_t } else { self.start_time + scaled(layer_t, s, 100.0) } } pub fn transform(&self) -> Option<&PropGroup> { diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index 6cfbda344..6d0a72976 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -30,17 +30,24 @@ pub use effectcraft_keyframe as keyframe; pub use effectcraft_keyframe::{Keyframe, Value}; mod comp; +mod dirty; mod footage; mod item; mod layer; mod layers; +mod reach; mod settings; pub use comp::{Comp, Guide, Renderer, Resolution}; pub use footage::{AlphaMode, CineonSettings, CineonUnits, FieldOrder, Footage, FootageKind, Proxy, Solid, SourceLayer, VIDEO_EXTENSIONS, cineon_log_to_lin}; -pub use item::{Item, ItemId, ItemKind, LayerId}; -pub use layer::{AutoOrient, FrameBlend, Layer, LayerSource, LightKind, MatteKind, PrimitiveKind, Quality, Sampling, Switches, TrackMatte}; +pub use item::NO_LAYER; +pub use item::{Heard, Item, ItemId, ItemKind, LayerId}; +pub use layer::{ + AutoOrient, FrameBlend, Layer, LayerSource, LightKind, MatteKind, PrimitiveKind, Quality, Sampling, Switches, TrackMatte, is_audio_effect, + reads_other_frames, text_layer_name, +}; pub use layers::Layers; +pub use reach::{ExprReach, PixelReach, expression_reach}; pub use settings::{ APP_VERSION, BitDepth, ColorEngine, CuePoint, HdrMode, Marker, ProjectError, ProjectSettings, SCHEMA_EFFECT_SPACE, SCHEMA_VERSION, SavedView, TimeDisplayStyle, is_newer_version, saved_by, saved_view, diff --git a/crates/project/src/limits.rs b/crates/project/src/limits.rs index 998f40225..7a74c992b 100644 --- a/crates/project/src/limits.rs +++ b/crates/project/src/limits.rs @@ -27,6 +27,30 @@ pub const MAX_PIXEL_ASPECT: f64 = 10.0; pub const MOTION_BLUR_SAMPLES: (u32, u32) = (2, 64); /// Composition Settings ▸ Advanced ▸ Adaptive Sample Limit. pub const ADAPTIVE_SAMPLE_LIMIT: (u32, u32) = (16, 256); +/// The smallest time stretch, in percent, either way (After Effects sets a stretch between 0 and +/// 1 % to 1 %, between -1 % and 0 to -1 %; `layer.timeStretch` refuses less). +pub const MIN_STRETCH: f64 = 1.0; +/// The largest time stretch, in percent, either way (After Effects' `Layer.stretch` range is +/// -9900 to 9900). +pub const MAX_STRETCH: f64 = 9900.0; + +/// A layer's time stretch from [`MIN_STRETCH`] to [`MAX_STRETCH`] % either way, its sign (a +/// reversed layer) kept; 100 % for 0 or NaN. Layer and comp time divide by the stretch, and the +/// audio mix reads `100 / stretch` source samples per sample, so a stretch of 1e-300 % or NaN +/// from a damaged file must not reach them (#3247). +pub fn stretch(v: f64) -> f64 { + if v.is_nan() || v == 0.0 { + return 100.0; + } + // Infinity clamps to the largest stretch with its sign. + v.signum() * v.abs().clamp(MIN_STRETCH, MAX_STRETCH) +} + +/// A stretch for a note: a plain number in a readable range, scientific notation beyond it (a +/// plain 1e-300 would print 300 digits). +fn percent(v: f64) -> String { + if v == 0.0 || (1e-3..1e7).contains(&v.abs()) { format!("{v} %") } else { format!("{v:e} %") } +} /// A width or height from 1 to [`MAX_SIZE`]. pub fn size(v: u64) -> u32 { @@ -97,9 +121,11 @@ fn repair_comp(name: &str, c: &Comp, notes: &mut Vec) -> Option { let duration = c.duration.max(rate.frame_duration()); let samples = c.motion_blur_samples.clamp(MOTION_BLUR_SAMPLES.0, MOTION_BLUR_SAMPLES.1); let adaptive = c.motion_blur_adaptive_limit.clamp(ADAPTIVE_SAMPLE_LIMIT.0, ADAPTIVE_SAMPLE_LIMIT.1); + let stretch_ok = |l: &crate::Layer| stretch(l.stretch).to_bits() == l.stretch.to_bits(); let unchanged = (width, height, rate, duration, samples, adaptive) == (c.width, c.height, c.frame_rate, c.duration, c.motion_blur_samples, c.motion_blur_adaptive_limit) - && pa.to_bits() == c.pixel_aspect.to_bits(); + && pa.to_bits() == c.pixel_aspect.to_bits() + && c.layers.iter().all(stretch_ok); if unchanged { return None; } @@ -125,6 +151,12 @@ fn repair_comp(name: &str, c: &Comp, notes: &mut Vec) -> Option { } (n.width, n.height, n.pixel_aspect, n.frame_rate, n.duration) = (width, height, pa, rate, duration); (n.motion_blur_samples, n.motion_blur_adaptive_limit) = (samples, adaptive); + // Only the layers out of range are copied (the others stay shared). + for l in n.layers.iter_mut_where(|l| !stretch_ok(l)) { + let fixed = stretch(l.stretch); + note(notes, name, &format!("layer '{}' time stretch", l.name), percent(l.stretch), percent(fixed)); + l.stretch = fixed; + } Some(n) } @@ -217,6 +249,85 @@ mod tests { ); } + #[test] + fn a_stretch_is_held_to_one_to_9900_percent_with_its_sign() { + assert_eq!(stretch(f64::NAN), 100.0); + assert_eq!(stretch(0.0), 100.0); + assert_eq!(stretch(-0.0), 100.0); + assert_eq!(stretch(1e-300), MIN_STRETCH); + assert_eq!(stretch(-1e-300), -MIN_STRETCH); + assert_eq!(stretch(0.5), MIN_STRETCH); + assert_eq!(stretch(1e300), MAX_STRETCH); + assert_eq!(stretch(f64::INFINITY), MAX_STRETCH); + assert_eq!(stretch(f64::NEG_INFINITY), -MAX_STRETCH); + for v in [1.0, -1.0, 33.3, 100.0, -100.0, 200.0, 9900.0, -9900.0] { + assert_eq!(stretch(v).to_bits(), v.to_bits(), "{v} is in range"); + } + } + + /// A layer whose stretch got past loading (0, NaN, 1e-300 %, set in memory) still maps time + /// through a stretch in range: before, 0 and 1e-300 % saturated every layer time to the end of + /// time and NaN collapsed it to 0 (#3247). + #[test] + fn layer_and_comp_time_use_a_stretch_in_range() { + let mut p = crate::Project::default(); + let comp = Comp::new(64, 64, FrameRate::FPS_25, Tick::from_seconds_f64(10.0)); + let mut l = crate::build::layer(&mut p, &comp, "L", crate::LayerSource::Camera, (64, 64), None); + l.start_time = Tick::from_seconds_f64(1.0); + let at = |s: f64| Tick::from_seconds_f64(s); + for (bad, effective) in [(0.0, 100.0), (f64::NAN, 100.0), (1e-300, 1.0), (-1e-300, -1.0), (1e300, 9900.0), (f64::NEG_INFINITY, -9900.0)] { + l.stretch = bad; + assert_eq!(l.effective_stretch(), effective, "{bad}"); + // One comp second after the start is 100 / stretch layer seconds. + let want = Tick((at(1.0).0 as f64 * 100.0 / effective) as i64); + assert_eq!(l.layer_time(at(2.0)), want, "{bad}"); + // And back, within the rounding of the two conversions. + assert!((l.comp_time(l.layer_time(at(2.0))) - at(2.0)).abs() <= Tick(100), "{bad}"); + } + } + + #[test] + fn a_stretch_out_of_range_in_a_file_is_corrected_and_reported() { + let mut p = crate::Project::default(); + let comp = Comp::new(64, 64, FrameRate::FPS_25, Tick::from_seconds_f64(2.0)); + let mut c = comp.clone(); + for (name, s) in [("tiny", 1e-300), ("reversed tiny", -1e-300), ("zero", 0.0), ("huge", 1e300), ("reversed huge", -5e4), ("fine", -50.0)] { + let mut l = crate::build::layer(&mut p, &comp, name, crate::LayerSource::Camera, (64, 64), None); + l.stretch = s; + c.layers.push(l); + } + // Added through `add_item`, the comp is held to the limits too: write the values back in. + let id = p.add_item("Comp", effectcraft_color::Label::None, None, ItemKind::Comp(Arc::new(c.clone()))); + assert!(p.comp(id).unwrap().layers.iter().all(|l| l.stretch.abs() >= MIN_STRETCH && l.stretch.abs() <= MAX_STRETCH)); + let mut v: serde_json::Value = serde_json::from_str(&p.to_json()).unwrap(); + for (k, l) in c.layers.iter().enumerate() { + v["items"][id.0.to_string()]["kind"]["layers"][k]["stretch"] = serde_json::json!(l.stretch); + } + let (back, notes) = crate::Project::from_json_repaired(&v.to_string()).unwrap(); + let got: Vec = back.comp(id).unwrap().layers.iter().map(|l| l.stretch).collect(); + assert_eq!(got, [1.0, -1.0, 100.0, 9900.0, -9900.0, -50.0]); + assert_eq!( + notes, + [ + "Comp: layer 'tiny' time stretch 1e-300 % → 1 %", + "Comp: layer 'reversed tiny' time stretch -1e-300 % → -1 %", + "Comp: layer 'zero' time stretch 0 % → 100 %", + "Comp: layer 'huge' time stretch 1e300 % → 9900 %", + "Comp: layer 'reversed huge' time stretch -50000 % → -9900 %", + ] + ); + // A NaN stretch is written as null (an auto-save): the file opens, at 100 %, and says so. + // Before, the whole project was refused. + v["items"][id.0.to_string()]["kind"]["layers"][0]["stretch"] = serde_json::Value::Null; + let (back, notes) = crate::Project::from_json_repaired(&v.to_string()).unwrap(); + assert_eq!(back.comp(id).unwrap().layers.iter().next().unwrap().stretch, 100.0); + assert_eq!(notes.first().map(String::as_str), Some("Comp: layer 'tiny' time stretch NaN % → 100 %")); + let mut nan = p.clone(); + nan.comp_mut(id).unwrap().layers.iter_mut().for_each(|l| l.stretch = f64::NAN); + let (back, _) = crate::Project::from_json_repaired(&nan.to_json_compact()).unwrap(); + assert!(back.comp(id).unwrap().layers.iter().all(|l| l.stretch == 100.0)); + } + #[test] fn a_comp_in_range_is_not_copied() { let c = Comp::new(1920, 1080, FrameRate::FPS_24, Tick::from_seconds_f64(2.0)); diff --git a/crates/project/src/props.rs b/crates/project/src/props.rs index be2468c37..9b0b1853c 100644 --- a/crates/project/src/props.rs +++ b/crates/project/src/props.rs @@ -127,6 +127,13 @@ impl Property { if self.keys.is_empty() { return self.value.clone(); } + // 3D Orientation turns along the shortest arc between its keys, as in After Effects. + // Routed by `match_id`: "orientation" is only used by the Orientation property of 3D + // layers, cameras and lights (`build.rs`), always a `Vec3` of degrees. A future property + // must not reuse that id unless it is a rotation that should slerp the same way. + if self.match_id == "orientation" && matches!(self.value, Value::Vec3(_)) { + return effectcraft_keyframe::evaluate_orientation(&self.keys, t).unwrap_or_else(|| self.value.clone()); + } effectcraft_keyframe::evaluate(&self.keys, t, self.spatial).unwrap_or_else(|| self.value.clone()) } /// Set the value at `t`: adds/replaces a key when animated, else sets the static value. diff --git a/crates/project/src/reach.rs b/crates/project/src/reach.rs new file mode 100644 index 000000000..31a2ed567 --- /dev/null +++ b/crates/project/src/reach.rs @@ -0,0 +1,405 @@ +//! What a composition's pixels can depend on, from the project in memory: the items it draws +//! and, when expressions are among them, what those expressions can read (#3184). The disk +//! cache keys a comp's frames by exactly these items, so an edit elsewhere in the project keeps +//! them. +//! +//! An expression reaches its own comp's layers (`thisComp`, `thisLayer`), the sources of the +//! layers it can read (`layer.source`, a precomp's layers through it), and other items by name: +//! `comp("Name")` and `footage("Name")`. A name given as a plain string literal is followed; a +//! computed name (`comp("Shot " + index)`), the object model's constructors and internals +//! (`new Comp(7)`, `__h`), dynamic code (`eval`, `Function`) and anything the scanner can't read +//! for sure (a regular expression literal, a template string, an escape in a name) count as +//! reaching every item of the project. The scan errs on the side of reaching more: an item +//! wrongly left out would serve a stale frame, one wrongly let in only renders again. +//! +//! Known limit (`ponytail`): an expression that builds the names of the object model's private +//! fields at run time into a variable and writes them with a computed key it reads from that +//! variable could forge another comp's id. That is deliberate tampering with the internals, not +//! an expression one writes; the scan refuses every direct form of it (`__` names, the +//! constructors, `Object`, `JSON`, `call`/`apply`/`bind`, computed writes and computed keys). +//! Upgrade: have the expression host record which items an evaluation reached. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::{Comp, ItemId, ItemKind, LayerId, Node, Project, PropGroup, Value}; + +/// What an expression's text can reach outside its own comp and the layers it can read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExprReach { + /// Only items named by string literals: comps by `comp("…")`, footage by `footage("…")`. + Names { comps: Vec, footage: Vec }, + /// Any item of the project. + Anything, +} + +/// Names that hand an expression another item by id, run code built at run time, or give it the +/// tools to forge the object model's private fields. +const REACHES_ANYTHING: &[&str] = &[ + "Comp", + "Footage", + "Layer", + "Prop", + "Markers", + "eval", + "Function", + "globalThis", + "this", + "self", + "window", + "arguments", + "constructor", + "prototype", + "Object", + "Reflect", + "Proxy", + "JSON", + "call", + "apply", + "bind", + "class", + "with", + "import", + "require", + "fromCharCode", + "fromCodePoint", + "getOwnPropertyDescriptor", + "getOwnPropertyDescriptors", + "getPrototypeOf", + "setPrototypeOf", + "defineProperty", +]; + +/// Keywords after which a `/` starts a regular expression. +const BEFORE_REGEX: &[&str] = &["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]; + +/// Keywords whose `( … )` a regular expression may follow (`if (a) /x/.test(s)`). +const CONTROL: &[&str] = &["if", "while", "for", "with"]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Tok<'a> { + Ident(&'a str), + /// A string literal's text between its quotes; `plain` when it has no escape. + Str { + text: &'a str, + plain: bool, + }, + Num, + Punct(u8), +} + +/// The tokens of `text`, or `None` when it can't be read for sure. +fn tokens(text: &str) -> Option>> { + let b = text.as_bytes(); + let mut out: Vec> = Vec::new(); + // Per open `(`: whether a control keyword is before it; whether the last `)` closed one + // (only looked at right after a `)`). + let mut parens: Vec = Vec::new(); + let mut control_close = false; + let mut i = 0; + while let Some(&c) = b.get(i) { + match c { + b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c => i += 1, + b'/' if b.get(i + 1) == Some(&b'/') => { + while b.get(i).is_some_and(|c| *c != b'\n') { + i += 1; + } + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let end = text.get(i + 2..)?.find("*/")?; + i += 2 + end + 2; + } + b'/' => { + if regex_may_start(out.last(), control_close) { + return None; + } + out.push(Tok::Punct(c)); + i += 1; + } + b'"' | b'\'' => { + let start = i + 1; + let mut j = start; + let mut plain = true; + loop { + match *b.get(j)? { + q if q == c => break, + b'\n' | b'\r' => return None, + b'\\' => { + // Only escapes that can't spell a name: `\n`, `\t`, a quote... + if !matches!(b.get(j + 1)?, b'n' | b'r' | b't' | b'b' | b'f' | b'v' | b'\'' | b'"' | b'\\') { + return None; + } + plain = false; + j += 2; + } + _ => j += 1, + } + } + let s = text.get(start..j)?; + if s.contains("__") { + return None; + } + out.push(Tok::Str { text: s, plain }); + i = j + 1; + } + b'0'..=b'9' => { + while b.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'.') { + i += 1; + } + out.push(Tok::Num); + } + b'.' if b.get(i + 1).is_some_and(u8::is_ascii_digit) => { + i += 1; + while b.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'.') { + i += 1; + } + out.push(Tok::Num); + } + c if c.is_ascii_alphabetic() || c == b'_' || c == b'$' => { + let start = i; + while b.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'$') { + i += 1; + } + out.push(Tok::Ident(text.get(start..i)?)); + } + // A template string (code inside `${}`), an escaped identifier, a name in another + // alphabet: not followed. + b'`' | b'\\' => return None, + c if !c.is_ascii() => return None, + c => { + match c { + b'(' => parens.push(matches!(out.last(), Some(Tok::Ident(k)) if CONTROL.contains(k))), + b')' => control_close = parens.pop().unwrap_or(false), + _ => {} + } + out.push(Tok::Punct(c)); + i += 1; + } + } + } + Some(out) +} + +/// Whether a `/` after `prev` may start a regular expression literal (which the scanner doesn't +/// read: its text could hide a quote). +fn regex_may_start(prev: Option<&Tok<'_>>, control_close: bool) -> bool { + match prev { + None => true, + Some(Tok::Ident(k)) => BEFORE_REGEX.contains(k), + Some(Tok::Num | Tok::Str { .. }) => false, + Some(Tok::Punct(b')')) => control_close, + Some(Tok::Punct(b']')) => false, + Some(Tok::Punct(_)) => true, + } +} + +/// What the expression `text` can reach by name, or [`ExprReach::Anything`]. +pub fn expression_reach(text: &str) -> ExprReach { + expression_names(text).map_or(ExprReach::Anything, |(comps, footage)| ExprReach::Names { comps, footage }) +} + +/// The comp names and footage names an expression references by literal name. +/// Returns `None` when it can reach anything by a computed name or cannot be tokenised. +fn expression_names(text: &str) -> Option<(Vec, Vec)> { + let toks = tokens(text)?; + let (mut comps, mut footage) = (Vec::new(), Vec::new()); + // Per open `[`: a computed key (`{[k]: v}`), a computed member (`o[k]`). + let mut brackets: Vec<(bool, bool)> = Vec::new(); + for (i, t) in toks.iter().enumerate() { + let prev = i.checked_sub(1).and_then(|p| toks.get(p)); + let next = |n: usize| toks.get(i + n); + match *t { + Tok::Ident(name) if name.starts_with("__") || REACHES_ANYTHING.contains(&name) => return None, + Tok::Ident(name @ ("comp" | "footage")) => { + // Only a call with a plain literal, not a property of something else. + let (Some(Tok::Punct(b'(')), Some(Tok::Str { text, plain: true }), Some(Tok::Punct(b')'))) = (next(1), next(2), next(3)) else { return None }; + if matches!(prev, Some(Tok::Punct(b'.'))) { + return None; + } + if name == "comp" { comps.push((*text).to_string()) } else { footage.push((*text).to_string()) } + } + Tok::Punct(b'[') => { + let key = matches!(prev, Some(Tok::Punct(b'{' | b',')) | Some(Tok::Ident("get" | "set" | "static" | "async")) | Some(Tok::Punct(b'*'))); + let member = matches!(prev, Some(Tok::Ident(_) | Tok::Str { .. } | Tok::Num | Tok::Punct(b')' | b']' | b'.'))); + brackets.push((key, member)); + } + Tok::Str { .. } if brackets.last().is_some_and(|(_, member)| *member) => return None, + Tok::Punct(b']') => { + let (key, _) = brackets.pop().unwrap_or((true, true)); + // A computed key (`{[k]: v}`, `{[k]() {}}`) or a write through brackets (`o[k] = v`, + // `o[k] ||= v`, `for (o[k] in …)`, `[o[k]] = v`) could name a private field. + if key && matches!(next(1), Some(Tok::Punct(b':' | b'('))) { + return None; + } + if assigns(&toks, i + 1) || matches!(next(1), Some(Tok::Ident("in" | "of"))) { + return None; + } + } + // A destructuring write (`({a: o[k]} = v)`). + Tok::Punct(b'}') if assigns(&toks, i + 1) => return None, + _ => {} + } + } + Some((comps, footage)) +} + +/// Whether the tokens from `at` are an assignment operator (`=`, `+=`, `>>>=`, `??=`...), not a +/// comparison (`==`, `<=`) or an arrow (`=>`). +fn assigns(toks: &[Tok<'_>], at: usize) -> bool { + let mut op = Vec::new(); + for t in toks.iter().skip(at).take(5) { + match t { + Tok::Punct(c) if b"+-*/%&|^<>?=".contains(c) => op.push(*c), + _ => break, + } + } + let Some(eq) = op.iter().position(|c| *c == b'=') else { return false }; + let (before, after) = op.split_at(eq); + if after.get(1).is_some_and(|c| *c == b'=' || *c == b'>') { + return false; + } + matches!(before, b"" | b"+" | b"-" | b"*" | b"/" | b"%" | b"&" | b"|" | b"^" | b"**" | b"<<" | b">>" | b">>>" | b"&&" | b"||" | b"??") +} + +/// The items a comp's pixels can depend on ([`Project::pixel_reach`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PixelReach { + /// The items whose state counts; `None`: every item of the project. + pub items: Option>, + /// Expressions are among them: they can read every layer of the comps they reach (hidden + /// and silent ones too) and the markers, which therefore count as well (#1083). + pub expressions: bool, + /// The names expressions look items up by (`true`: a comp's, `false`: footage's), each with + /// the ids of the items of that kind that have it now, in id order (the first one is what + /// the lookup finds; another item taking or giving up the name changes it). + pub names: Vec<(bool, String, Vec)>, +} + +/// Each property of a group and its subgroups (iterative: no depth limit to hit). +fn each_prop<'a>(g: &'a PropGroup, f: &mut dyn FnMut(&'a crate::Property) -> Option<()>) -> Option<()> { + let mut stack = vec![g]; + while let Some(g) = stack.pop() { + for n in &g.children { + match n { + Node::Prop(p) => f(p)?, + Node::Group(sub) => stack.push(sub), + } + } + } + Some(()) +} + +impl Project { + /// The items comp `comp` draws ([`Self::silent_layers`] aside, with `heard`) and the + /// footage its precomp layers swap in (Essential Graphics Media Replacement); with an + /// expression in any of its comps, everything those expressions can reach + /// ([`expression_reach`]). Memory only: no file is looked at. + pub fn pixel_reach(&self, comp: ItemId, heard: &crate::Heard) -> PixelReach { + let Some(drawn) = self.reach_walk(comp, &|id, c| self.silent_layers(id, c, heard), &mut |_| Some(vec![])) else { return PixelReach::every() }; + let has_expression = |g: &PropGroup| each_prop(g, &mut |p| p.expr.is_none().then_some(())).is_none(); + if !drawn.iter().filter_map(|id| self.comp(*id)).any(|c| c.layers.iter().any(|l| has_expression(&l.props))) { + return PixelReach { items: Some(drawn), expressions: false, names: vec![] }; + } + // Expressions: every layer of a comp they reach counts, and what they name. + let mut names: BTreeMap<(bool, String), Vec> = BTreeMap::new(); + let mut scan = |p: &crate::Property| match p.expr.as_ref().map(|e| expression_reach(&e.text)) { + None => Some(vec![]), + Some(ExprReach::Anything) => None, + Some(ExprReach::Names { comps, footage }) => { + let mut found = vec![]; + for (is_comp, name) in comps.into_iter().map(|n| (true, n)).chain(footage.into_iter().map(|n| (false, n))) { + let ids = self.named(is_comp, &name); + found.extend(ids.iter().copied()); + names.insert((is_comp, name), ids); + } + Some(found) + } + }; + let Some(mut items) = self.reach_walk(comp, &|_, _| BTreeSet::new(), &mut scan) else { return PixelReach::every() }; + // A source's data is read by its name (`layer.source.sourceData`). + let footage_names: BTreeSet<&str> = + items.iter().filter_map(|id| self.item(*id)).filter(|i| matches!(i.kind, ItemKind::Footage(_))).map(|i| i.name.as_str()).collect(); + let same_name: Vec = + self.items.values().filter(|i| matches!(i.kind, ItemKind::Footage(_)) && footage_names.contains(i.name.as_str())).map(|i| i.id).collect(); + items.extend(same_name); + PixelReach { items: Some(items), expressions: true, names: names.into_iter().map(|((c, n), ids)| (c, n, ids)).collect() } + } + + /// The items of one kind (`is_comp`: comps, else footage) named `name`, in id order. + fn named(&self, is_comp: bool, name: &str) -> Vec { + self.items + .values() + .filter(|i| i.name == name && if is_comp { matches!(i.kind, ItemKind::Comp(_)) } else { matches!(i.kind, ItemKind::Footage(_)) }) + .map(|i| i.id) + .collect() + } + + /// The items reached from `comp` through its layers (but those `quiet` names) and the items + /// `scan` returns for each of their properties; `None` when something reaches every item. + /// (A stack and a visited set: each item is visited once, cycles included.) + fn reach_walk( + &self, + comp: ItemId, + quiet: &dyn Fn(ItemId, &Comp) -> BTreeSet, + scan: &mut dyn FnMut(&crate::Property) -> Option>, + ) -> Option> { + let mut seen = BTreeSet::new(); + let mut stack = vec![comp]; + while let Some(id) = stack.pop() { + if !seen.insert(id) { + continue; + } + let Some(c) = self.comp(id) else { continue }; + let quiet = quiet(id, c); + for l in c.layers.iter().filter(|l| !quiet.contains(&l.id)) { + // Every source item: a 3D model's too (it is drawn, and `layer.source` reads its + // name and size). + if let Some(item) = l.source.item() { + stack.push(item); + } + stack.extend(self.media_replacements(l)?); + let mut reached = vec![]; + each_prop(&l.props, &mut |p| { + reached.extend(scan(p)?); + Some(()) + })?; + stack.extend(reached); + } + } + Some(seen) + } + + /// The footage a precomp layer swaps in through its Essential Properties (Media Replacement): + /// the items its overridden properties name. `None` when they can't be listed (an + /// expression or keyframes choose the item over time). + fn media_replacements(&self, layer: &crate::Layer) -> Option> { + let over = crate::essential::overridden(layer); + let Some(g) = crate::essential::group(layer).filter(|_| !over.is_empty()) else { return Some(vec![]) }; + let mut out = vec![]; + each_prop(g, &mut |p| { + if !over.contains(&p.uid) { + return Some(()); + } + if p.expr.is_some() || !p.keys.is_empty() { + return None; + } + if let Value::Scalar(id) = p.value { + let item = ItemId(id.max(0.0) as u64); + if matches!(self.item(item).map(|i| &i.kind), Some(ItemKind::Footage(_))) { + out.push(item); + } + } + Some(()) + })?; + Some(out) + } +} + +impl PixelReach { + /// Every item of the project, with expressions. + fn every() -> PixelReach { + PixelReach { items: None, expressions: true, names: vec![] } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/project/src/reach/tests.rs b/crates/project/src/reach/tests.rs new file mode 100644 index 000000000..53db8172a --- /dev/null +++ b/crates/project/src/reach/tests.rs @@ -0,0 +1,198 @@ +use super::*; +use crate::{Expression, LayerSource, Solid, build}; +use effectcraft_time::{FrameRate, Tick}; + +fn names(comps: &[&str], footage: &[&str]) -> ExprReach { + ExprReach::Names { comps: comps.iter().map(|s| s.to_string()).collect(), footage: footage.iter().map(|s| s.to_string()).collect() } +} + +/// Expressions that read their own comp, or other items by literal names, are followed; every +/// way to reach items by a computed name or an id, or text the scanner can't read for sure, +/// reaches everything. +#[test] +fn expression_reach_follows_literal_names_and_refuses_the_rest() { + let follows = [ + ("wiggle(2, 20)", names(&[], &[])), + ("thisComp.layer(\"Comp 1 Layer\").transform.opacity * 2 / 3", names(&[], &[])), + ("value + [10, 0]; value[0] / 2", names(&[], &[])), + ("// comp(name) in a comment\n/* footage(x) */ value", names(&[], &[])), + ("\"a string that says comp(x) and Layer\"", names(&[], &[])), + ("comp(\"Other\").layer(1).transform.position", names(&["Other"], &[])), + ("comp( 'A' ).width + comp(\"B\").height", names(&["A", "B"], &[])), + ("footage(\"data.json\").sourceData.x", names(&[], &["data.json"])), + ("x = a[0] <= b ? a[1] : 0; y = a[0] == 1", names(&[], &[])), + ("thisLayer.source.layer(1).name", names(&[], &[])), + ("if (a) x = 1; else x = 2; (a + b) / 2", names(&[], &[])), + ("\"Ünïcödé name\"", names(&[], &[])), + ("const f = (v) => v * 2; f(1)", names(&[], &[])), + ]; + for (text, want) in follows { + assert_eq!(expression_reach(text), want, "{text}"); + } + let anything = [ + "comp(\"Shot \" + index).layer(1)", + "comp(name)", + "var n = \"Other\"; comp(n)", + "comp(\"O\\\"ther\")", + "x.comp(\"Other\")", + "var comp = 1", + "footage(thisComp.name)", + "new Comp(7).layer(1)", + "Layer(7, 3).name", + "__h(__COMP, 7)", + "o.__c = 7", + "eval('1')", + "Function('return 1')()", + "this.x", + "({}).constructor", + "Object.getPrototypeOf(thisComp)", + "JSON.parse(s)", + "thisComp.layer.call(o, 1)", + "o['_' + '_c']", + "o[k] = 7", + "o[k] ||= 7", + "o[k] += 7", + "[o[k]] = [7]", + "({a: o[k]} = {a: 7})", + "for (o[k] in x) {}", + "({[k]: 7})", + "({a: 1, [k]: 7})", + "o = {'__c': 7}", + "'\\x5f\\x5fc'", + "'\\_\\_c'", + "`${x}`", + "c\\u006fmp('A')", + "comp\u{0430}('A')", + "/\"/.test(s); comp(n); \"", + "return /x/", + "if (a) /\"/.test(s)", + "x = '", + "/* comp(n)", + "class X {}", + "String.fromCharCode(95)", + ]; + for text in anything { + assert_eq!(expression_reach(text), ExprReach::Anything, "{text}"); + } +} + +/// `a / b` divides after a name, a number, a string and a closing bracket or parenthesis. +#[test] +fn division_is_not_a_regular_expression() { + for text in ["a / b", "2 / 3", "'a' / 2", "x[0] / 2", "(a + b) / 2", "f(x) / 2 / g(y)"] { + assert_eq!(expression_reach(text), names(&[], &[]), "{text}"); + } +} + +struct Fixture { + p: Project, + main: ItemId, + other: ItemId, + third: ItemId, + unused: ItemId, + solid: ItemId, +} + +/// Comps "Main" (a solid), "Other" (a solid), "Third" (empty), an unused footage item. +fn fixture() -> Fixture { + let mut p = Project::default(); + let comp = Comp::new(64, 64, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let solid = + p.add_item("Solid", effectcraft_color::Label::None, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 64, height: 64, pixel_aspect: 1.0 })); + let main = p.add_item("Main", effectcraft_color::Label::None, None, ItemKind::Comp(comp.clone().into())); + let other = p.add_item("Other", effectcraft_color::Label::None, None, ItemKind::Comp(comp.clone().into())); + let third = p.add_item("Third", effectcraft_color::Label::None, None, ItemKind::Comp(comp.clone().into())); + let unused = p.add_item("unused.png", effectcraft_color::Label::None, None, ItemKind::Footage(crate::Footage { has_video: true, ..Default::default() })); + for c in [main, other] { + let l = build::layer(&mut p, &comp, "S", LayerSource::Solid { item: solid }, (64, 64), None); + p.comp_mut(c).unwrap().layers.push(l); + } + Fixture { p, main, other, third, unused, solid } +} + +fn set_expr(p: &mut Project, comp: ItemId, text: &str) { + let l = p.comp_mut(comp).unwrap().layers.first_mut().unwrap(); + l.props.prop_mut("transform/opacity").unwrap().expr = Some(Expression { text: text.into(), enabled: true }); +} + +fn reach(p: &Project, comp: ItemId) -> PixelReach { + p.pixel_reach(comp, &p.heard_layers()) +} + +#[test] +fn pixel_reach_is_what_the_comp_draws_and_what_its_expressions_name() { + let mut f = fixture(); + let ids = |r: &PixelReach| r.items.clone().map(|s| s.into_iter().collect::>()); + assert_eq!(reach(&f.p, f.main), PixelReach { items: Some([f.solid, f.main].into()), expressions: false, names: vec![] }); + // An expression reading only its own comp: what it draws, with expressions. + set_expr(&mut f.p, f.main, "thisComp.layer(1).transform.opacity"); + let r = reach(&f.p, f.main); + assert!(r.expressions); + assert_eq!(ids(&r), Some(vec![f.solid, f.main])); + // An expression in another comp doesn't reach this one. + set_expr(&mut f.p, f.other, "wiggle(1, 1)"); + assert_eq!(ids(&reach(&f.p, f.main)), Some(vec![f.solid, f.main])); + // A literal name: that comp and what it draws, with the name and the comps that have it. + set_expr(&mut f.p, f.main, "comp(\"Other\").layer(1).transform.opacity"); + let r = reach(&f.p, f.main); + assert_eq!(ids(&r), Some(vec![f.solid, f.main, f.other])); + assert_eq!(r.names, vec![(true, "Other".to_string(), vec![f.other])]); + // Another comp taking the name is part of it, whichever the lookup finds. + f.p.item_mut(f.third).unwrap().name = "Other".into(); + let r = reach(&f.p, f.main); + assert_eq!(r.names, vec![(true, "Other".to_string(), vec![f.other, f.third])]); + assert!(r.items.unwrap().contains(&f.third)); + // A name no item has yet still counts (with no item). + set_expr(&mut f.p, f.main, "footage(\"later.json\").sourceData"); + assert_eq!(reach(&f.p, f.main).names, vec![(false, "later.json".to_string(), vec![])]); + // A computed name reaches everything. + set_expr(&mut f.p, f.main, "comp(\"Ot\" + \"her\").width"); + assert_eq!(reach(&f.p, f.main), PixelReach { items: None, expressions: true, names: vec![] }); + // Footage reached as a layer's source brings the footage of its name (its data is read by + // name). + let comp = f.p.comp(f.main).unwrap().clone(); + let l = build::layer(&mut f.p, &comp, "U", LayerSource::Footage { item: f.unused }, (64, 64), None); + f.p.comp_mut(f.main).unwrap().layers.push(l); + let twin = f.p.add_item("unused.png", effectcraft_color::Label::None, None, ItemKind::Footage(crate::Footage::default())); + set_expr(&mut f.p, f.main, "value"); + let r = reach(&f.p, f.main).items.unwrap(); + assert!(r.contains(&f.unused) && r.contains(&twin), "{r:?}"); +} + +/// A comp nested in the reach is scanned too: its expression's names count for the outer comp. +#[test] +fn nested_comps_bring_their_expressions_reach() { + let mut f = fixture(); + let comp = f.p.comp(f.main).unwrap().clone(); + let pre = build::layer(&mut f.p, &comp, "Pre", LayerSource::Comp { item: f.other }, (64, 64), None); + f.p.comp_mut(f.main).unwrap().layers.push(pre); + set_expr(&mut f.p, f.other, "comp(\"Third\").width"); + let r = reach(&f.p, f.main); + assert!(r.expressions && r.items.unwrap().contains(&f.third)); + // A cycle through names ends. + let l = build::layer(&mut f.p, &comp, "S", LayerSource::Solid { item: f.solid }, (64, 64), None); + f.p.comp_mut(f.third).unwrap().layers.push(l); + set_expr(&mut f.p, f.third, "comp(\"Main\").width"); + assert!(reach(&f.p, f.main).items.unwrap().contains(&f.main)); +} + +/// A 3D model layer's item is reached like any other source: it is drawn, and an expression +/// reads its name and size through `layer.source` (a renamed model left the comp's disk key and +/// its old frames in place). +#[test] +fn model_sources_are_reached() { + let mut f = fixture(); + let model = f.p.add_item( + "chair.glb", + effectcraft_color::Label::None, + None, + ItemKind::Footage(crate::Footage { kind: crate::FootageKind::Model, ..Default::default() }), + ); + let comp = f.p.comp(f.main).unwrap().clone(); + let l = build::layer(&mut f.p, &comp, "Model", LayerSource::Model { item: model }, (64, 64), None); + f.p.comp_mut(f.main).unwrap().layers.push(l); + assert!(reach(&f.p, f.main).items.unwrap().contains(&model), "drawn"); + set_expr(&mut f.p, f.main, "thisComp.layer(\"Model\").source.name.length"); + let r = reach(&f.p, f.main); + assert!(r.expressions && r.items.unwrap().contains(&model), "read by an expression"); +} diff --git a/crates/project/src/render_queue.rs b/crates/project/src/render_queue.rs index c40096905..b935c2fc8 100644 --- a/crates/project/src/render_queue.rs +++ b/crates/project/src/render_queue.rs @@ -421,7 +421,12 @@ impl RenderSettings { /// The output frame rate: the Frame Rate override, unless the comp preserves its frame rate /// (Composition Settings ▸ Preserve frame rate when nested or in render queue). pub fn rate(&self, comp: &Comp) -> FrameRate { - if comp.preserve_frame_rate { comp.frame_rate } else { self.frame_rate.unwrap_or(comp.frame_rate) } + if comp.preserve_frame_rate { + return comp.frame_rate; + } + // A saved override is held to the supported rates, as a comp's own rate is: its frame count + // is the export's work. + self.frame_rate.map_or(comp.frame_rate, |r| crate::limits::frame_rate(r, comp.frame_rate)) } /// First output-rate frame starting at or after `t`. fn ceil_frame(r: FrameRate, t: Tick) -> i64 { @@ -480,6 +485,8 @@ impl RenderSettings { TimeSpan::Custom { start, end } => format!("Custom ({:.3}s – {:.3}s)", start.seconds(), end.seconds()), }; let rate = match (self.frame_rate, comp) { + // A saved override outside the supported rates renders at the clamped one: say so. + (Some(r), Some(c)) if self.rate(c) != r => format!("{:.3} fps (renders at {:.3})", r.as_f64(), self.rate(c).as_f64()), (Some(r), _) => format!("{:.3} fps", r.as_f64()), (None, Some(c)) => format!("Use comp's frame rate ({:.3})", c.frame_rate.as_f64()), (None, None) => "Use comp's frame rate".into(), @@ -779,6 +786,27 @@ pub struct Crop { pub right: i32, } +/// The largest side of a frame an output module writes (Resize is capped there too). +pub const MAX_OUTPUT_SIDE: i32 = 30_000; + +/// Crop edges `a`/`b` of one axis of `side` pixels: padding is taken back only as far as keeps +/// the result within [`MAX_OUTPUT_SIDE`], so a mixed pair that stays inside the cap is kept as +/// saved. Each edge is also bounded (what the larger of the side and the cap allows), so the +/// arithmetic on them cannot overflow. +fn bound_edges(a: i32, b: i32, side: i32) -> (i32, i32) { + let hi = side.max(MAX_OUTPUT_SIDE); + let (mut a, mut b) = (a.clamp(-MAX_OUTPUT_SIDE, hi), b.clamp(-MAX_OUTPUT_SIDE, hi)); + let excess = i64::from(side) - i64::from(a) - i64::from(b) - i64::from(MAX_OUTPUT_SIDE); + if excess > 0 { + // Only padding (negative edges) grows the side: take back as much of it as needed. + let excess = i32::try_from(excess).unwrap_or(i32::MAX); + let from_a = excess.min(-a.min(0)); + a += from_a; + b += (excess - from_a).min(-b.min(0)); + } + (a, b) +} + impl Crop { /// Edges `(top, left, bottom, right)` in pixels of a `w`×`h` frame rendered at `scale`. pub fn edges(&self, w: u32, h: u32, scale: f64) -> (i32, i32, i32, i32) { @@ -801,7 +829,12 @@ impl Crop { let b = conv((y + rh) * scale, hi).max(t); return (t, l, hi - b, wi - r); } - (self.top, self.left, self.bottom, self.right) + // Negative edges pad the frame: keep each padded side within the largest frame an + // output module writes, or a few saved integers ask for a canvas of gigapixels. + let (wi, hi) = (i32::try_from(w).unwrap_or(i32::MAX), i32::try_from(h).unwrap_or(i32::MAX)); + let (t, b) = bound_edges(self.top, self.bottom, hi); + let (l, r) = bound_edges(self.left, self.right, wi); + (t, l, b, r) } } @@ -895,6 +928,141 @@ impl ProResProfile { } } +/// OpenEXR sequence compression. Every method writes scan lines, in blocks of the method's own +/// height (1 line for None, RLE and ZIPS; 16 for ZIP and PXR24; 32 for PIZ, B44, B44A and DWAA; +/// 256 for DWAB). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ExrCompression { + None, + Rle, + /// ZIP, one scan line per block. + Zips, + /// ZIP, 16 scan lines per block. + #[default] + Zip, + Piz, + /// Lossy for 32-bit float (rounded to 24 bits), lossless for half float. + Pxr24, + /// Lossy for half float; 32-bit float channels are stored uncompressed. + B44, + /// B44 that also packs flat areas smaller; lossy for half float, 32-bit float is stored uncompressed. + B44a, + /// Lossy DCT, 32 scan lines per block. + Dwaa, + /// Lossy DCT, 256 scan lines per block. + Dwab, +} + +impl ExrCompression { + pub const ALL: [ExrCompression; 10] = [ + ExrCompression::None, + ExrCompression::Rle, + ExrCompression::Zips, + ExrCompression::Zip, + ExrCompression::Piz, + ExrCompression::Pxr24, + ExrCompression::B44, + ExrCompression::B44a, + ExrCompression::Dwaa, + ExrCompression::Dwab, + ]; + /// The parameter value (`exrCompression`). + pub fn name(self) -> &'static str { + match self { + ExrCompression::None => "none", + ExrCompression::Rle => "rle", + ExrCompression::Zips => "zips", + ExrCompression::Zip => "zip", + ExrCompression::Piz => "piz", + ExrCompression::Pxr24 => "pxr24", + ExrCompression::B44 => "b44", + ExrCompression::B44a => "b44a", + ExrCompression::Dwaa => "dwaa", + ExrCompression::Dwab => "dwab", + } + } + pub fn label(self) -> &'static str { + match self { + ExrCompression::None => "None", + ExrCompression::Rle => "RLE", + ExrCompression::Zips => "ZIPS (1 scan line)", + ExrCompression::Zip => "ZIP (16 scan lines)", + ExrCompression::Piz => "PIZ", + ExrCompression::Pxr24 => "PXR24", + ExrCompression::B44 => "B44", + ExrCompression::B44a => "B44A", + ExrCompression::Dwaa => "DWAA", + ExrCompression::Dwab => "DWAB", + } + } + /// Whether the written samples can differ from the rendered ones at `depth` (half float is + /// already rounded from the 32-bit render; that rounding is not counted here). + pub fn is_lossy(self, depth: ExrBitDepth) -> bool { + match self { + ExrCompression::None | ExrCompression::Rle | ExrCompression::Zips | ExrCompression::Zip | ExrCompression::Piz => false, + ExrCompression::Pxr24 => depth == ExrBitDepth::Float, + ExrCompression::B44 | ExrCompression::B44a => depth == ExrBitDepth::Half, + ExrCompression::Dwaa | ExrCompression::Dwab => true, + } + } + /// Whether the method leaves the samples uncompressed at `depth` (B44 and B44A pack only half + /// floats). + pub fn stores_uncompressed(self, depth: ExrBitDepth) -> bool { + self == ExrCompression::None || (matches!(self, ExrCompression::B44 | ExrCompression::B44a) && depth == ExrBitDepth::Float) + } + /// Parse a compression name: `none`/`uncompressed`, `rle`, `zips`/`zip1` (Nuke's "Zip (1 + /// scanline)"), `zip`/`zip16`, + /// `piz`, `pxr24`, `b44`, `b44a`, `dwaa`, `dwab` (any case). + pub fn from_name(s: &str) -> Option { + let n = s.to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], ""); + match n.as_str() { + "uncompressed" | "off" => Some(ExrCompression::None), + "zip1" | "zips1scanline" | "zip1scanline" | "zip1scanlines" => Some(ExrCompression::Zips), + "zip16" | "zip16scanlines" => Some(ExrCompression::Zip), + _ => ExrCompression::ALL.into_iter().find(|c| c.name() == n), + } + } +} + +/// OpenEXR sequence sample type: 16-bit half float (the usual VFX interchange) or 32-bit float. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ExrBitDepth { + Half, + #[default] + Float, +} + +impl ExrBitDepth { + pub const ALL: [ExrBitDepth; 2] = [ExrBitDepth::Half, ExrBitDepth::Float]; + /// The parameter value (`exrBitDepth`). + pub fn name(self) -> &'static str { + match self { + ExrBitDepth::Half => "half", + ExrBitDepth::Float => "float", + } + } + pub fn label(self) -> &'static str { + match self { + ExrBitDepth::Half => "16-bit Half Float", + ExrBitDepth::Float => "32-bit Float", + } + } + pub fn bits(self) -> u32 { + match self { + ExrBitDepth::Half => 16, + ExrBitDepth::Float => 32, + } + } + /// Parse `half`/`16`/`f16` or `float`/`32`/`f32` (any case). + pub fn from_name(s: &str) -> Option { + match s.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() { + "half" | "16" | "f16" | "16bit" | "halffloat" | "16bithalffloat" => Some(ExrBitDepth::Half), + "float" | "32" | "f32" | "32bit" | "full" | "fullfloat" | "32bitfloat" => Some(ExrBitDepth::Float), + _ => None, + } + } +} + /// HEVC / AV1 profile: 8-bit (HEVC Main, AV1 Main 8-bit) or 10-bit (HEVC Main 10, AV1 Main 10-bit). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum CodecProfile { @@ -1065,6 +1233,10 @@ pub struct OutputModule { /// Movies: frames between key frames (0 = automatic, two seconds). pub keyframe_interval: u32, pub prores_profile: ProResProfile, + /// OpenEXR sequence: compression (scan lines). + pub exr_compression: ExrCompression, + /// OpenEXR sequence: half or 32-bit float samples. + pub exr_bit_depth: ExrBitDepth, pub crop: Crop, pub resize: Resize, pub audio: AudioOutput, @@ -1099,6 +1271,8 @@ impl Default for OutputModule { webm_bitrate: false, keyframe_interval: 0, prores_profile: ProResProfile::Hq, + exr_compression: ExrCompression::Zip, + exr_bit_depth: ExrBitDepth::Float, crop: Crop::default(), resize: Resize::default(), audio: AudioOutput::Auto, @@ -1130,8 +1304,8 @@ impl OutputModule { // Width rules; height follows the cropped frame's aspect. rh = ((rw as f64 * ch as f64 / cw as f64).round() as u32).max(1); } - rw = rw.min(30_000); - rh = rh.min(30_000); + rw = rw.min(MAX_OUTPUT_SIDE as u32); + rh = rh.min(MAX_OUTPUT_SIDE as u32); (rw, rh) } /// The written frame size of an item (Render Settings resolution, Crop, Resize, codec @@ -1155,6 +1329,10 @@ impl OutputModule { match self.format { OutputFormat::H264 => v.push(("Bitrate", format!("{} kbps", self.bitrate_kbps))), OutputFormat::ProRes => v.push(("Codec", self.prores_profile.label().into())), + OutputFormat::ExrSequence => { + v.push(("Compression", self.exr_compression_label())); + v.push(("Bit Depth", self.exr_bit_depth.label().into())); + } OutputFormat::WebM if self.webm_bitrate => v.push(("Bitrate", format!("{} kbps", self.bitrate_kbps))), OutputFormat::WebM | OutputFormat::JpegSequence => v.push(("Quality", self.quality.to_string())), _ => {} @@ -1215,6 +1393,18 @@ impl OutputModule { } self.output = format!("{stem}.{}", format.extension()); } + /// The OpenEXR compression's label, marked when it is lossy at the module's bit depth or, for + /// B44 / B44A at 32-bit float, stores the samples uncompressed. + pub fn exr_compression_label(&self) -> String { + let (c, d) = (self.exr_compression, self.exr_bit_depth); + if c.is_lossy(d) { + format!("{} (lossy)", c.label()) + } else if c != ExrCompression::None && c.stores_uncompressed(d) { + format!("{} (uncompressed at float)", c.label()) + } else { + c.label().into() + } + } /// Whether this module can write alpha (the format can, and WebM uses VP9). pub fn supports_alpha(&self) -> bool { self.format.supports_alpha() && !(self.format == OutputFormat::WebM && self.webm_codec == WebmVideoCodec::Av1) @@ -1246,6 +1436,7 @@ impl OutputModule { if self.channels == Channels::Rgba && !self.prores_profile.is_4444() { "Apple ProRes 4444" } else { self.prores_profile.label() } ), OutputFormat::Hevc | OutputFormat::Av1 => format!("{} · {}", self.format.label(), self.codec_summary()), + OutputFormat::ExrSequence => format!("{} · {} · {} · {ch}", self.format.label(), self.exr_compression_label(), self.exr_bit_depth.label()), OutputFormat::WebM if self.webm_codec == WebmVideoCodec::Av1 => { format!("WebM (AV1 + Opus {} kbps) · {}", self.opus_bitrate_kbps, self.codec_summary()) } @@ -1529,17 +1720,71 @@ pub fn numbered_template(template: &str, n: u32) -> String { /// Make a name safe as a file name component. pub fn sanitize(name: &str) -> String { - name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect() + let mut s: String = name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect(); + // At most a file name's worth (255 UTF-8 bytes, whole characters only): a template repeating + // a long name token must not expand to gigabytes. A cut name ends in a hash of the whole + // name so long names that share a prefix stay distinct. + if s.len() > 255 { + // shortcut: 64-bit FNV-1a, not collision-resistant against crafted names; use a real hash if names become untrusted keys. + let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)); + let mut end = 255 - 17; + while !s.is_char_boundary(end) { + end -= 1; + } + s.truncate(end); + s.push_str(&format!("-{hash:016x}")); + } + // `.` and `..` would name the folder itself or its parent when the token is a path component. + if !s.is_empty() && s.chars().all(|c| c == '.') { "_".repeat(s.len()) } else { s } } #[cfg(test)] mod tests { + #[test] + fn crop_padding_stays_within_the_largest_output_frame() { + use super::*; + let crop = |top, left, bottom, right| Crop { enabled: true, top, left, bottom, right, ..Default::default() }; + let m = |c: Crop| OutputModule { crop: c, ..Default::default() }; + // Saved edges padding by billions of pixels: the frame stops at the cap. + assert_eq!(m(crop(i32::MIN, i32::MIN, i32::MIN, i32::MIN)).frame_size(100, 50, 1.0), (30_000, 30_000)); + assert_eq!(m(crop(-20_000, 0, -20_000, -1)).frame_size(100, 50, 1.0), (101, 30_000)); + // Ordinary crops and pads are unchanged. + assert_eq!(crop(1, -2, 3, 4).edges(100, 50, 1.0), (1, -2, 3, 4)); + // A mixed pair beyond the side that still ends within the cap is kept as saved (50 px). + assert_eq!(crop(0, 150, 0, -100).edges(100, 50, 1.0), (0, 150, 0, -100)); + assert_eq!(m(crop(0, 150, 0, -100)).frame_size(100, 50, 1.0), (50, 50)); + assert_eq!(m(crop(10, 10, 10, 10)).frame_size(100, 50, 1.0), (80, 30)); + assert_eq!(m(crop(i32::MAX, 0, 0, 0)).frame_size(100, 50, 1.0), (100, 1)); + } + use super::*; + #[test] + fn sanitize_limits_the_name_in_bytes() { + // 255 two-byte characters are cut to whole characters plus a 17-byte hash suffix. + let s = sanitize(&"é".repeat(255)); + assert!(s.len() <= 255 && s.len() > 235, "{}", s.len()); + assert!(s.starts_with("éé") && s.is_char_boundary(s.len() - 17)); + // Names that share their first 255 bytes stay distinct, and a name that fits is untouched. + let (a, b) = (sanitize(&format!("{}A", "界".repeat(85))), sanitize(&format!("{}B", "界".repeat(85)))); + assert_ne!(a, b); + assert!(a.len() <= 255 && b.len() <= 255); + assert_eq!(sanitize(&"n".repeat(255)), "n".repeat(255)); + assert_eq!(sanitize(&"é".repeat(127)), "é".repeat(127)); + } + #[test] fn templates_and_sequences() { let v = TemplateVars { comp_name: "Main/Title", project_name: "P", width: 1920, height: 1080, frame_rate: 29.97, start_frame: 0, end_frame: 9 }; assert_eq!(expand_template(DEFAULT_TEMPLATE, OutputFormat::H264, &v), "Main_Title.mp4"); + // A dot-only name is not a parent-folder component; a long one is cut to a file name. + for name in ["..", "."] { + let v = TemplateVars { comp_name: name, ..v }; + assert_eq!(expand_template("out/[compName]/x.[fileExtension]", OutputFormat::Gif, &v), format!("out/{}/x.gif", "_".repeat(name.len()))); + } + let long = "n".repeat(100_000); + let v2 = TemplateVars { comp_name: &long, ..v }; + assert_eq!(expand_template(&"[compName]".repeat(100), OutputFormat::Gif, &v2).len(), 255 * 100); assert_eq!(expand_template("[compName]_[width]x[height]@[frameRate].[fileExtension]", OutputFormat::Gif, &v), "Main_Title_1920x1080@29.97.gif"); assert_eq!(sequence_path("out/a_[#####].png", 42), "out/a_00042.png"); assert_eq!(sequence_path("a###.tif", 7), "a007.tif"); @@ -1689,6 +1934,22 @@ mod tests { assert_eq!(p.sample(&c, 3), FrameSample::Progressive(Tick::from_seconds_f64(0.12))); } + /// A saved Frame Rate override outside the supported rates is clamped, so a short comp cannot + /// ask for billions of output frames. + #[test] + fn frame_rate_override_is_held_to_the_supported_rates() { + let c = Comp::new(64, 48, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0)); + let s = |r| RenderSettings { frame_rate: Some(r), time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let huge = s(FrameRate::new(1_000_000_000_000, 1)); + assert_eq!(huge.rate(&c).as_f64(), crate::limits::MAX_FPS); + assert!(huge.frame_count(&c) <= 2001, "{}", huge.frame_count(&c)); + assert_eq!(s(FrameRate::new(0, 1)).rate(&c), c.frame_rate); + assert_eq!(s(FrameRate::new(60, 1)).rate(&c), FrameRate::new(60, 1)); + let shown = |r| s(r).describe(Some(&c)).into_iter().find(|l| l.0 == "Frame Rate").map(|l| l.1).unwrap_or_default(); + assert!(shown(FrameRate::new(1_000_000_000_000, 1)).contains("renders at 1000.000"), "{}", shown(FrameRate::new(1_000_000_000_000, 1))); + assert_eq!(shown(FrameRate::new(60, 1)), "60.000 fps"); + } + #[test] fn crop_and_resize_sizes() { let c = Comp::new(1920, 1080, FrameRate::new(25, 1), Tick::from_seconds_f64(1.0)); @@ -1895,4 +2156,45 @@ mod tests { let old: OutputModule = serde_json::from_str(r#"{"format":"H264","bitrate_kbps":5000}"#).unwrap(); assert_eq!((old.codec, old.webm_codec, old.opus_bitrate_kbps), (VideoCodecOptions::default(), WebmVideoCodec::Vp9, 192)); } + + /// OpenEXR compression and bit depth (#2911): names parse, lossy methods are marked for the + /// depth they lose data at, and modules saved before the settings existed load as ZIP, 32-bit + /// float (what those projects rendered). + #[test] + fn exr_compression_and_bit_depth() { + for c in ExrCompression::ALL { + assert_eq!(ExrCompression::from_name(c.name()), Some(c)); + assert_eq!(ExrCompression::from_name(&c.name().to_ascii_uppercase()), Some(c)); + } + assert_eq!(ExrCompression::from_name("uncompressed"), Some(ExrCompression::None)); + assert_eq!(ExrCompression::from_name("zip16"), Some(ExrCompression::Zip)); + assert_eq!(ExrCompression::from_name("ZIP1"), Some(ExrCompression::Zips)); + assert_eq!(ExrCompression::from_name("Zip (1 scanline)"), Some(ExrCompression::Zips)); + assert_eq!(ExrCompression::from_name("Zip (16 scanlines)"), Some(ExrCompression::Zip)); + assert_eq!(ExrCompression::from_name("htj2k"), None); + assert_eq!(ExrBitDepth::from_name("16"), Some(ExrBitDepth::Half)); + assert_eq!(ExrBitDepth::from_name("Half"), Some(ExrBitDepth::Half)); + assert_eq!(ExrBitDepth::from_name("f32"), Some(ExrBitDepth::Float)); + assert_eq!(ExrBitDepth::from_name("8"), None); + let lossy = |d| ExrCompression::ALL.into_iter().filter(|c| c.is_lossy(d)).map(ExrCompression::name).collect::>(); + assert_eq!(lossy(ExrBitDepth::Float), ["pxr24", "dwaa", "dwab"]); + assert_eq!(lossy(ExrBitDepth::Half), ["b44", "b44a", "dwaa", "dwab"]); + + let mut m = OutputModule::for_format(OutputFormat::ExrSequence); + assert_eq!((m.exr_compression, m.exr_bit_depth), (ExrCompression::Zip, ExrBitDepth::Float)); + assert_eq!(m.summary(), "OpenEXR Sequence · ZIP (16 scan lines) · 32-bit Float · RGB"); + m.exr_compression = ExrCompression::Dwaa; + m.exr_bit_depth = ExrBitDepth::Half; + assert!(m.describe().contains(&("Compression", "DWAA (lossy)".to_string())), "{:?}", m.describe()); + assert!(m.describe().contains(&("Bit Depth", "16-bit Half Float".to_string()))); + let json = serde_json::to_string(&m).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), m); + m.exr_compression = ExrCompression::B44a; + m.exr_bit_depth = ExrBitDepth::Float; + assert_eq!(m.exr_compression_label(), "B44A (uncompressed at float)"); + m.exr_bit_depth = ExrBitDepth::Half; + assert_eq!(m.exr_compression_label(), "B44A (lossy)"); + let old: OutputModule = serde_json::from_str(r#"{"format":"ExrSequence","channels":"Rgba"}"#).unwrap(); + assert_eq!((old.exr_compression, old.exr_bit_depth), (ExrCompression::Zip, ExrBitDepth::Float)); + } } diff --git a/crates/project/src/render_templates.rs b/crates/project/src/render_templates.rs index cadfab2ad..ea3560682 100644 --- a/crates/project/src/render_templates.rs +++ b/crates/project/src/render_templates.rs @@ -323,4 +323,19 @@ mod tests { t.delete(TemplateKind::OutputModule, "High Quality").unwrap(); assert_eq!(t.output_module("High Quality").unwrap().format, OutputFormat::ProRes); } + + /// An Output Module template keeps its OpenEXR compression and bit depth through a save and + /// load (#2911); the built-in EXR template stays ZIP, 32-bit float. + #[test] + fn exr_options_survive_a_template_round_trip() { + use crate::render_queue::{ExrBitDepth, ExrCompression}; + let mut t = RenderTemplates::default(); + let builtin = t.output_module("OpenEXR Sequence with Alpha").unwrap(); + assert_eq!((builtin.exr_compression, builtin.exr_bit_depth), (ExrCompression::Zip, ExrBitDepth::Float)); + let m = OutputModule { exr_compression: ExrCompression::Piz, exr_bit_depth: ExrBitDepth::Half, ..OutputModule::for_format(OutputFormat::ExrSequence) }; + t.save_output_module("EXR Half PIZ", m); + let back: RenderTemplates = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap(); + let m = back.output_module("exr half piz").unwrap(); + assert_eq!((m.format, m.exr_compression, m.exr_bit_depth), (OutputFormat::ExrSequence, ExrCompression::Piz, ExrBitDepth::Half)); + } } diff --git a/crates/project/src/sequence.rs b/crates/project/src/sequence.rs index 716c9b4fd..0b23d528f 100644 --- a/crates/project/src/sequence.rs +++ b/crates/project/src/sequence.rs @@ -114,6 +114,22 @@ impl Footage { self.sequence.get(k).filter(|p| frame_number(p) == Some(n)).map(String::as_str) } + /// The file an image sequence shows at its frame `i`, holding the last existing file across a + /// gap in the numbering (After Effects 2026: files 1, 2, 4, 5 show frame 2 at frame 3). + /// `None` only when no file precedes the frame (or there are no files). + pub fn sequence_file_held(&self, i: i64) -> Option<&str> { + if let Some(p) = self.sequence_file(i) { + return Some(p); + } + let first = self.numbered()?; + let k = self.first_file_from(first.saturating_add(i)); + // The preceding number, then the file `sequence_file` picks for it (the first with that + // number), so files sharing a number (`shot_0002`, `shot_002`) don't switch at a gap. + let prev = self.file_number(k.checked_sub(1)?)?; + let j = self.first_file_from(prev); + self.sequence.get(j).filter(|p| frame_number(p) == Some(prev)).map(String::as_str) + } + /// Set an image sequence's duration to its frames at its frame rate (after its files or /// frame rate changed). pub fn sync_sequence_duration(&mut self) { @@ -131,6 +147,17 @@ mod tests { Footage { kind: FootageKind::Sequence, sequence: numbers.iter().map(|n| format!("C:\\shots\\a_{n:04}.png")).collect(), ..Default::default() } } + #[test] + fn a_gap_holds_the_file_shown_for_the_preceding_number() { + let mut f = seq(&[]); + f.sequence = ["a_0001.png", "a_0002.png", "a_002.png", "a_0005.png"].map(String::from).to_vec(); + assert_eq!(f.sequence_file(1), Some("a_0002.png")); + // Frames 3 and 4 (numbers 3, 4) hold what number 2 shows: the first file with it. + assert_eq!(f.sequence_file_held(2), Some("a_0002.png")); + assert_eq!(f.sequence_file_held(3), Some("a_0002.png")); + assert_eq!(f.sequence_file_held(4), Some("a_0005.png")); + } + #[test] fn numbers_and_names() { assert_eq!(split_frame_number("shot_0012"), Some(("shot_", "0012"))); diff --git a/crates/project/src/tests.rs b/crates/project/src/tests.rs index a47792b89..80ba3c771 100644 --- a/crates/project/src/tests.rs +++ b/crates/project/src/tests.rs @@ -113,12 +113,51 @@ fn resolution_factors_and_scales() { assert_eq!(Resolution::Third.scale(0.1, 1.0), 1.0 / 3.0); } +/// Another layer of the same source, and a duplicated item, get a numbered name. Only a number set +/// off by a space is a counter; digits that end a word stay (`v-b1.mp4` gave `v-b1.mp 2`). +#[test] +fn numbered_names_keep_digits_that_end_a_word() { + // (the name in use, the next layer's and the item copy's name) + let rows = [ + ("v-b1.mp4", "v-b1.mp4 2"), + ("clip2.mov", "clip2.mov 2"), + ("shot 2", "shot 3"), + ("a.b.c", "a.b.c 2"), + ("Background", "Background 2"), + ("Red Solid 1", "Red Solid 2"), + ]; + for (name, next) in rows { + let mut p = Project::default(); + let mut comp = Comp::new(64, 36, FrameRate::FPS_29_97, Tick::from_seconds_f64(1.0)); + let solid = Solid { color: [0.5; 3], width: 64, height: 36, pixel_aspect: 1.0 }; + let item = p.add_item(name, effectcraft_color::Label::Red, None, ItemKind::Solid(solid)); + let first = build::layer(&mut p, &comp, name, LayerSource::Solid { item }, (64, 36), None); + assert_eq!(first.name, name, "the first layer of {name}"); + comp.layers.push(first); + let second = build::layer(&mut p, &comp, name, LayerSource::Solid { item }, (64, 36), None); + assert_eq!(second.name, next, "the second layer of {name}"); + assert_eq!(p.numbered_item_name(name, |_| false), next, "a copy of the item {name}"); + } +} + #[test] fn unique_names_and_cycles() { let (p, cid) = project_with_layer(); let c = p.comp(cid).unwrap(); assert_eq!(c.unique_layer_name("Red Solid 1"), "Red Solid 2"); assert_eq!(c.unique_layer_name("Shape Layer 1"), "Shape Layer 1"); + // A suffix written another way (`02`) is not the number taken. + let mut d = c.clone(); + for n in ["Red Solid 02", "Red Solid 3"] { + let mut l = d.layers[0].clone(); + l.name = n.into(); + d.layers.push(l); + } + assert_eq!(d.unique_layer_name("Red Solid 1"), "Red Solid 2"); + // Digits that end a word stay in the stem. + let mut e = c.clone(); + e.layers[0].name = "v-b1.mp4".into(); + assert_eq!(e.unique_layer_name("v-b1.mp4"), "v-b1.mp4 2"); assert!(p.comp_contains(cid, cid)); } @@ -383,3 +422,116 @@ fn upgrading_deeply_nested_shape_groups_fits_a_small_stack() { let ids: Vec<&str> = g.children.iter().map(|c| c.match_id()).collect(); assert_eq!(ids, ["size", "detail", "points", "speed", "correlation", "phase", "spatialPhase", "seed"]); } + +/// Music in a precomp is heard, and so not silent, when a layer of a comp nesting it picks the +/// precomp layer (an Audio Waveform drawing the precomp's mix). +#[test] +fn music_in_a_precomp_a_waveform_picks_is_not_silent() { + use crate::{Footage, FootageKind, GroupKind}; + let (mut p, inner) = project_with_layer(); + let song = p.add_item( + "song.wav", + effectcraft_color::Label::None, + None, + ItemKind::Footage(Footage { kind: FootageKind::Audio, has_video: false, has_audio: true, ..Default::default() }), + ); + let comp = p.comp(inner).unwrap().clone(); + let music = build::layer(&mut p, &comp, "Music", LayerSource::Footage { item: song }, (1920, 1080), None); + let music_id = music.id; + p.comp_mut(inner).unwrap().layers.push(music); + let outer = p.add_item("Outer", effectcraft_color::Label::None, None, ItemKind::Comp(comp.clone().into())); + let pre = build::layer(&mut p, &comp, "Pre", LayerSource::Comp { item: inner }, (1920, 1080), None); + let pre_id = pre.id; + p.comp_mut(outer).unwrap().layers.push(pre); + let silent = |p: &Project| p.silent_layers(inner, p.comp(inner).unwrap(), &p.heard_layers()).contains(&music_id); + assert!(silent(&p), "nothing draws the precomp's audio"); + let mut n = 1_000_000; + let mut ids = build::Ids(&mut n); + let mut g = ids.group("waveform", "Audio Waveform"); + g.kind = GroupKind::Effect { effect: "ec.generate.audiowaveform".into() }; + g.children.push(ids.prop("audioLayer", "Audio Layer", Value::Layer(Some(pre_id.0))).into()); + let solid = p.comp(outer).unwrap().layers[0].id; + p.comp_mut(outer).unwrap().layer_mut(solid).unwrap().props.group_mut("effects").unwrap().children.push(g.into()); + assert!(!silent(&p), "the outer comp's waveform draws the music"); +} + +/// Layers that can't change the picture: music, hidden layers nothing reads. A hidden matte is +/// read by the layer it mattes; nulls and cameras are never silent. +#[test] +fn silent_layers_are_music_and_unread_hidden_layers() { + use crate::{Footage, FootageKind, LayerId, MatteKind, TrackMatte}; + let (mut p, cid) = project_with_layer(); + let comp = p.comp(cid).unwrap().clone(); + let song = p.add_item( + "song.wav", + effectcraft_color::Label::None, + None, + ItemKind::Footage(Footage { kind: FootageKind::Audio, has_video: false, has_audio: true, ..Default::default() }), + ); + let add = |p: &mut Project, name: &str, source: LayerSource| { + let l = build::layer(p, &comp, name, source, (1920, 1080), None); + let id = l.id; + p.comp_mut(cid).unwrap().layers.push(l); + id + }; + let music = add(&mut p, "Music", LayerSource::Footage { item: song }); + let solid = p.comp(cid).unwrap().layers[0].source.clone(); + let hidden = add(&mut p, "Hidden", solid.clone()); + let matte = add(&mut p, "Matte", solid); + let null = add(&mut p, "Null", LayerSource::Null); + let first = p.comp(cid).unwrap().layers[0].id; + let c = p.comp_mut(cid).unwrap(); + for id in [hidden, matte, null] { + c.layer_mut(id).unwrap().switches.video = false; + } + c.layer_mut(first).unwrap().track_matte = Some(TrackMatte { layer: matte, kind: MatteKind::Alpha }); + let c = p.comp(cid).unwrap(); + assert_eq!(p.silent_layers(cid, c, &p.heard_layers()).into_iter().collect::>(), vec![music, hidden]); + // Solo hides every other layer, so a soloed music or hidden layer changes the picture. + for (soloed, rest) in [(music, hidden), (hidden, music)] { + let mut q = p.clone(); + q.comp_mut(cid).unwrap().layer_mut(soloed).unwrap().switches.solo = true; + assert_eq!(q.silent_layers(cid, q.comp(cid).unwrap(), &q.heard_layers()).into_iter().collect::>(), vec![rest]); + } +} + +/// Plug-in effects read their input at other times (plug-in API 2), so a precomp under one is +/// re-rendered over its whole span; built-in effects only when they are on the list. +#[test] +fn plug_in_effects_read_other_frames() { + assert!(crate::reads_other_frames("org.example.glow")); + assert!(crate::reads_other_frames("ec.time.echo")); + assert!(!crate::reads_other_frames("ec.blur.gaussian")); +} + +/// An item whose parent is a composition (or an item that is not there) lists under no folder, and +/// the AEP export lost it without a word (review finding): opening such a file moves it to the top +/// level and says so; a parent that is a folder stays. +#[test] +fn an_item_inside_a_non_folder_moves_to_the_top_level_when_a_project_is_opened() { + let mut p = Project::default(); + let folder = p.add_item("Folder", Default::default(), None, ItemKind::Folder); + let comp = p.add_item( + "Comp", + Default::default(), + None, + ItemKind::Comp(std::sync::Arc::new(Comp::new(64, 36, FrameRate::new(25, 1), Tick::from_seconds_f64(1.0)))), + ); + let inside_folder = p.add_item("Fine", Default::default(), Some(folder), ItemKind::Folder); + let inside_comp = p.add_item("Inside comp", Default::default(), None, ItemKind::Folder); + let orphan = p.add_item("Orphan", Default::default(), None, ItemKind::Folder); + if let Some(i) = p.item_mut(inside_comp) { + i.parent = Some(comp); + } + if let Some(i) = p.item_mut(orphan) { + i.parent = Some(crate::ItemId(9_999)); + } + let (q, notes) = Project::from_json_repaired(&p.to_json()).expect("opens"); + assert_eq!(q.item(inside_folder).and_then(|i| i.parent), Some(folder)); + assert_eq!(q.item(inside_comp).and_then(|i| i.parent), None); + assert_eq!(q.item(orphan).and_then(|i| i.parent), None); + assert_eq!(notes.len(), 2, "{notes:?}"); + assert!(notes.iter().all(|n| n.contains("not a folder")), "{notes:?}"); + // Nothing to repair in a sound project. + assert!(Project::from_json_repaired(&q.to_json()).expect("opens").1.is_empty()); +} diff --git a/crates/psd/src/limits.rs b/crates/psd/src/limits.rs index c1c23b390..6db366c00 100644 --- a/crates/psd/src/limits.rs +++ b/crates/psd/src/limits.rs @@ -107,7 +107,7 @@ impl Budget { /// Inflate a zlib stream to at most `limit` bytes. pub(crate) fn inflate(src: &[u8], limit: usize) -> Result> { - miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(src, limit).map_err(|e| Error::Invalid(format!("zip: {e:?}"))) + miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(src, limit).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status))) } /// Give back what a channel buffer from `Psd::channel_bytes` / `Psd::decode_plane` was charged: diff --git a/crates/psd/src/memory_tests.rs b/crates/psd/src/memory_tests.rs index 108046b66..96ac5c70c 100644 --- a/crates/psd/src/memory_tests.rs +++ b/crates/psd/src/memory_tests.rs @@ -28,10 +28,11 @@ impl Psd { } 2 | 3 => { let rest = r.bytes(r.remaining())?; - let mut v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, rowb * h).map_err(|e| Error::Invalid(format!("zip: {e:?}")))?; + let mut v = + miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, rowb * h).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))?; v.resize(rowb * h, 0); if comp == 3 { - self.unpredict(&mut v, w, h); + self.unpredict(&mut v, w, h, &mut Budget::new(u64::MAX))?; } v } @@ -128,11 +129,12 @@ impl Psd { } 2 | 3 => { let rest = r.bytes(r.remaining())?; - let v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, want * rowb * h).map_err(|e| Error::Invalid(format!("zip: {e:?}")))?; + let v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, want * rowb * h) + .map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))?; for (c, p) in planes.iter_mut().enumerate().take(want) { let mut plane = v.get(c * rowb * h..(c + 1) * rowb * h).ok_or(Error::Truncated)?.to_vec(); if comp == 3 { - self.unpredict(&mut plane, w, h); + self.unpredict(&mut plane, w, h, &mut Budget::new(u64::MAX))?; } *p = Some(self.ref_samples(&plane, w, h)); } diff --git a/crates/psd/src/pixels.rs b/crates/psd/src/pixels.rs index 21a5c8845..290a7b6f4 100644 --- a/crates/psd/src/pixels.rs +++ b/crates/psd/src/pixels.rs @@ -37,7 +37,7 @@ impl Psd { PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(&counts, 0, r, rowb, h, budget)?), PlaneStream::Zip(mut v) => { v.resize(size, 0); - self.zip_plane(comp, &mut v, 0, w, h)?; + self.zip_plane(comp, &mut v, 0, w, h, budget)?; Cow::Owned(v) } }) @@ -90,7 +90,7 @@ impl Psd { Ok(match planes { PlaneStream::Raw => Cow::Borrowed(r.bytes(size)?), PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(counts, c, r, rowb, h, budget)?), - PlaneStream::Zip(v) => Cow::Borrowed(self.zip_plane(comp, v, c, w, h)?), + PlaneStream::Zip(v) => Cow::Borrowed(self.zip_plane(comp, v, c, w, h, budget)?), }) } @@ -106,11 +106,11 @@ impl Psd { } /// Plane `c` of the inflated ZIP data of consecutive planes, un-predicted in place (`comp` 3). - pub(crate) fn zip_plane<'v>(&self, comp: u16, v: &'v mut [u8], c: usize, w: usize, h: usize) -> Result<&'v [u8]> { + pub(crate) fn zip_plane<'v>(&self, comp: u16, v: &'v mut [u8], c: usize, w: usize, h: usize, budget: &mut Budget) -> Result<&'v [u8]> { let rowb = self.row_bytes(w); let plane = v.get_mut(c * rowb * h..(c + 1) * rowb * h).ok_or(Error::Truncated)?; if comp == 3 { - self.unpredict(plane, w, h); + self.unpredict(plane, w, h, budget)?; } Ok(plane) } @@ -132,7 +132,8 @@ impl Psd { if self.depth == 1 { w.div_ceil(8) } else { w * self.bytes_per_sample() } } - pub(crate) fn unpredict(&self, v: &mut [u8], w: usize, h: usize) { + /// Undo ZIP prediction in place; the 32-bit scratch row is charged to `budget`. + pub(crate) fn unpredict(&self, v: &mut [u8], w: usize, h: usize, budget: &mut Budget) -> Result<()> { match self.depth { 16 => { for row in v.chunks_exact_mut(w * 2).take(h) { @@ -145,8 +146,9 @@ impl Psd { } } 32 => { - // One scratch row for the whole plane. - let mut planar = vec![0u8; w * 4]; + // One scratch row for the whole plane, charged: a wide, short layer passes the + // decode's peak check and would otherwise allocate it on top. + let mut planar = budget.filled(w.checked_mul(4).ok_or_else(|| too_large(w, h))?, 0u8)?; #[cfg(test)] counters::bump(&counters::SCRATCH); for row in v.chunks_exact_mut(w * 4).take(h) { @@ -161,6 +163,7 @@ impl Psd { } } } + budget.release(planar.len() as u64); } _ => { for row in v.chunks_exact_mut(w).take(h) { @@ -170,6 +173,7 @@ impl Psd { } } } + Ok(()) } /// Hand every sample of `raw` (`w`×`h`, row-major, in order) to `f` as a float. Samples a short @@ -483,15 +487,17 @@ pub(crate) fn unpack_bits(src: &[u8], row: usize, out: &mut Vec) -> Result<( while i < src.len() && out.len() - start < row { let n = src[i] as i8; i += 1; + // A packet is written only up to the row's end, so the reserved plane never grows. + let room = row - (out.len() - start); if n >= 0 { let k = n as usize + 1; let s = src.get(i..i + k).ok_or(Error::Truncated)?; - out.extend_from_slice(s); + out.extend_from_slice(&s[..k.min(room)]); i += k; } else if n != -128 { let k = (1 - n as isize) as usize; let v = *src.get(i).ok_or(Error::Truncated)?; - out.extend(std::iter::repeat_n(v, k)); + out.extend(std::iter::repeat_n(v, k.min(room))); i += 1; } } diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 074976510..fd041138a 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -493,3 +493,29 @@ fn rle_composite_matches_the_raw_one() { assert_eq!(rle.layer_pixels(2, true).unwrap().data, raw.layer_pixels(2, true).unwrap().data, "{depth} bit"); } } + +#[test] +fn packbits_packets_stop_at_the_row_end() { + // A 128-byte repeat and a 128-byte literal into 3-byte rows: the reserved row is never + // outgrown (capacity stays what was reserved). + for src in [vec![0x81u8, 7], { + let mut v = vec![0x7fu8]; + v.extend([1u8; 128]); + v + }] { + let mut out = Vec::with_capacity(3); + unpack_bits(&src, 3, &mut out).unwrap(); + assert_eq!(out.len(), 3); + assert_eq!(out.capacity(), 3); + } +} + +#[test] +fn a_failed_inflate_reports_its_status_not_its_output() { + // A stream that inflates a megabyte of zeros, then breaks its checksum. + let mut z = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 1 << 20], 6); + let n = z.len(); + z[n - 1] ^= 0xff; + let Err(Error::Invalid(msg)) = crate::limits::inflate(&z, 1 << 21) else { panic!("the checksum fails") }; + assert!(msg.len() < 100, "{} bytes", msg.len()); +} diff --git a/crates/psd/src/tests/opt.rs b/crates/psd/src/tests/opt.rs index 908026d07..44bcec071 100644 --- a/crates/psd/src/tests/opt.rs +++ b/crates/psd/src/tests/opt.rs @@ -69,7 +69,7 @@ fn ref_decode_channel(p: &Psd, offset: usize, len: usize, w: usize, h: usize) -> } 2 | 3 => { let rest = r.bytes(r.remaining())?; - let mut v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, rowb * h).map_err(|e| Error::Invalid(format!("zip: {e:?}")))?; + let mut v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, rowb * h).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))?; v.resize(rowb * h, 0); if comp == 3 { ref_unpredict(p.depth, &mut v, w, h); @@ -112,7 +112,8 @@ fn ref_composite(p: &Psd) -> Result { } 2 | 3 => { let rest = r.bytes(r.remaining())?; - let v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, want * rowb * h).map_err(|e| Error::Invalid(format!("zip: {e:?}")))?; + let v = + miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, want * rowb * h).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))?; for (c, pl) in planes.iter_mut().enumerate().take(want) { let mut plane = v.get(c * rowb * h..(c + 1) * rowb * h).ok_or(Error::Truncated)?.to_vec(); if comp == 3 { @@ -448,7 +449,7 @@ fn unpredict_matches_the_reference_and_allocates_one_scratch_row() { let mut a: Vec = (0..w * h * bps).map(|i| (i * 31 % 251) as u8).collect(); let mut b = a.clone(); counters::take(&SCRATCH); - p.unpredict(&mut a, w, h); + p.unpredict(&mut a, w, h, &mut Budget::new(u64::MAX)).unwrap(); let scratch = counters::take(&SCRATCH); let old_allocs = ref_unpredict(depth, &mut b, w, h); assert_eq!(a, b, "{depth} bit"); @@ -473,11 +474,11 @@ fn raw_planes_are_borrowed_and_zip_planes_are_unpredicted_in_place() { let mut v: Vec = (0..3 * 40 * 30).map(|i| (i % 255) as u8).collect(); let range = v.as_ptr_range(); for comp in [2, 3] { - let got = q.zip_plane(comp, &mut v, 1, 40, 30).unwrap(); + let got = q.zip_plane(comp, &mut v, 1, 40, 30, &mut Budget::new(u64::MAX)).unwrap(); assert_eq!(got.len(), 1200); assert!(range.contains(&got.as_ptr()), "compression {comp}"); } - assert!(q.zip_plane(2, &mut v, 3, 40, 30).is_err()); + assert!(q.zip_plane(2, &mut v, 3, 40, 30, &mut Budget::new(u64::MAX)).is_err()); } #[test] diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index e27d55317..7cd4fbe5a 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -13,3 +13,4 @@ workspace = true effectcraft-geom = { workspace = true } effectcraft-color = { workspace = true } rayon = { workspace = true } +tempfile = { workspace = true } diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index c8689a7b6..76e51f865 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -27,13 +27,25 @@ fn box_h_into(src: &[Px], out: &mut [Px], w: usize, r: usize, repeat: bool) { row[i as usize] } }; + // The starting window: the pixels inside the row once each, and the repeated edge pixels + // counted rather than visited (a radius far past the row would otherwise loop over it). let mut acc = [0.0f32; 4]; - for i in -(r as isize)..=(r as isize) { - let p = get(i); + let inside = r.min(w - 1); + for p in &row[..=inside] { for c in 0..4 { acc[c] += p[c]; } } + if repeat { + let (left, right) = (r as f32, (r - inside) as f32); + for c in 0..4 { + acc[c] += row[0][c] * left; + // A zero count adds nothing (0 * NaN would be NaN). + if right > 0.0 { + acc[c] += row[w - 1][c] * right; + } + } + } for x in 0..w { o[x] = acc.map(|v| v * norm); let add = get(x as isize + r as isize + 1); @@ -65,14 +77,27 @@ fn box_v_into(src: &[Px], out: &mut [Px], w: usize, h: usize, r: usize, repeat: out.par_chunks_mut(w * block).enumerate().for_each(|(bi, chunk)| { let ya = (bi * block) as isize; let mut acc = vec![[0.0f32; 4]; w]; - for i in ya - r as isize..=ya + r as isize { - if let Some(rw) = row(i) { - for (a, p) in acc.iter_mut().zip(rw) { - for c in 0..4 { - a[c] += p[c]; - } + // The starting window: rows inside the image once each, the repeated edge rows counted. + let (lo, hi) = (ya - r as isize, ya + r as isize); + let add = |acc: &mut [Px], rw: &[Px], k: f32| { + // A zero count adds nothing (0 * NaN would be NaN). + if k == 0.0 { + return; + } + for (a, p) in acc.iter_mut().zip(rw) { + for c in 0..4 { + a[c] += p[c] * k; } } + }; + for i in lo.max(0)..=hi.min(h as isize - 1) { + add(&mut acc, &src[i as usize * w..(i as usize + 1) * w], 1.0); + } + if repeat { + let above = (-lo).max(0) as f32; + let below = (hi - (h as isize - 1)).max(0) as f32; + add(&mut acc, &src[0..w], above); + add(&mut acc, &src[(h - 1) * w..h * w], below); } for (yy, o) in chunk.chunks_mut(w).enumerate() { let y = ya + yy as isize; @@ -166,6 +191,9 @@ pub fn gaussian_is_exact(sigma_x: f64, sigma_y: f64) -> bool { sigma_x.max(sigma_y) < EXACT_SIGMA_BELOW } +/// Pixels per tile of [`gauss_pass`]'s vertical pass. +const TILE: usize = 128; + /// One separable pass of a sampled Gaussian (radius 3 sigma) along x or y. fn gauss_pass(img: &Image, sigma: f64, vertical: bool, repeat: bool) -> Image { // Below 1e-3 the kernel is the identity in f64; tiny sigmas would also make 2σ² underflow to 0 (NaN taps). @@ -176,20 +204,65 @@ fn gauss_pass(img: &Image, sigma: f64, vertical: bool, repeat: bool) -> Image { let mut k: Vec = (-r..=r).map(|i| (-((i * i) as f64) / (2.0 * sigma * sigma)).exp()).collect(); let total: f64 = k.iter().sum(); k.iter_mut().for_each(|v| *v /= total); - let w = img.width as usize; + let (w, h) = (img.width as usize, img.height as usize); let mut out = Image::new(img.width, img.height); - out.rows_mut().for_each(|(y, row)| { - for x in 0..w { - let mut acc = [0.0f64; 4]; - for (i, wt) in k.iter().enumerate() { - let d = i as i64 - r; - let (sx, sy) = if vertical { (x as i64, y as i64 + d) } else { (x as i64 + d, y as i64) }; - let p = if repeat { img.get_clamped(sx, sy) } else { img.get(sx, sy) }; - for c in 0..4 { - acc[c] += p[c] as f64 * wt; + // Every output pixel adds its taps in kernel order, in f64, as a per-pixel loop would: the + // result is the same to the bit. Taps outside a transparent edge are skipped (adding `+0.0` + // leaves a sum that started at `+0.0` unchanged). + if vertical { + // Row by row: each output row adds whole input rows (contiguous, vectorises), instead of + // walking a column per pixel (a strided read per tap). + out.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { + // 128 pixels at a time: the f64 sums (4 KB) stay in L1 across the taps. + for (t, out_tile) in row.chunks_mut(TILE).enumerate() { + let x0 = t * TILE; + let mut acc = [[0.0f64; 4]; TILE]; + for (i, &wt) in k.iter().enumerate() { + let sy = y as i64 + i as i64 - r; + let sy = if repeat { + sy.clamp(0, h as i64 - 1) + } else if sy < 0 || sy >= h as i64 { + continue; + } else { + sy + }; + let start = sy as usize * w + x0; + let Some(src) = img.data.get(start..start + out_tile.len()) else { continue }; + for (a, p) in acc.iter_mut().zip(src) { + for c in 0..4 { + a[c] += p[c] as f64 * wt; + } + } + } + for (o, a) in out_tile.iter_mut().zip(acc.iter()) { + *o = a.map(|v| v as f32); } } - row[x] = acc.map(|v| v as f32); + }); + return out; + } + let n = k.len(); + out.data.par_chunks_mut(w).zip(img.data.par_chunks(w)).for_each(|(row, src)| { + for (x, o) in row.iter_mut().enumerate() { + let mut acc = [0.0f64; 4]; + // Inside the row: the taps are one slice (no per-tap edge checks). + if let Some(taps) = x.checked_sub(r as usize).and_then(|x0| src.get(x0..x0 + n)) { + for (p, wt) in taps.iter().zip(&k) { + for c in 0..4 { + acc[c] += p[c] as f64 * wt; + } + } + } else { + for (i, wt) in k.iter().enumerate() { + let sx = x as i64 + i as i64 - r; + let at = if repeat { Some(sx.clamp(0, w as i64 - 1)) } else { Some(sx) }; + let Some(p) = at.and_then(|i| usize::try_from(i).ok()).and_then(|i| src.get(i)) else { continue }; + for c in 0..4 { + acc[c] += p[c] as f64 * wt; + } + } + } + *o = acc.map(|v| v as f32); } }); out @@ -264,6 +337,107 @@ pub fn radial_blur(img: &Image, center: (f64, f64), amount: f64, zoom: bool) -> mod tests { use super::*; + /// The sampled Gaussian pass as it was (one pixel at a time, bounds-checked taps): the + /// row-wise passes must match it to the bit. + fn gauss_pass_per_pixel(img: &Image, sigma: f64, vertical: bool, repeat: bool) -> Image { + let r = (sigma * 3.0).ceil() as i64; + let mut k: Vec = (-r..=r).map(|i| (-((i * i) as f64) / (2.0 * sigma * sigma)).exp()).collect(); + let total: f64 = k.iter().sum(); + k.iter_mut().for_each(|v| *v /= total); + let mut out = Image::new(img.width, img.height); + for y in 0..img.height as i64 { + for x in 0..img.width as i64 { + let mut acc = [0.0f64; 4]; + for (i, wt) in k.iter().enumerate() { + let d = i as i64 - r; + let (sx, sy) = if vertical { (x, y + d) } else { (x + d, y) }; + let p = if repeat { img.get_clamped(sx, sy) } else { img.get(sx, sy) }; + for c in 0..4 { + acc[c] += p[c] as f64 * wt; + } + } + out.set(x as u32, y as u32, acc.map(|v| v as f32)); + } + } + out + } + + #[test] + fn gauss_pass_is_bit_identical_to_the_per_pixel_kernel() { + // Sizes narrower and shorter than the kernel too (every tap near an edge), one wider + // than three tiles (tiles past the first, and a partial last one), with negative, zero + // and HDR values. + for (w, h) in [(37, 23), (3, 2), (1, 9), (64, 1), (300, 5)] { + let mut img = Image::new(w, h); + for (i, p) in img.data.iter_mut().enumerate() { + let v = ((i * 7919) % 101) as f32 / 37.0 - 0.6; + *p = [v, -v * 0.5, if i % 5 == 0 { 0.0 } else { v * 3.0 }, (v + 0.6).min(1.0)]; + } + for sigma in [0.4, 1.3, 2.9] { + for vertical in [false, true] { + for repeat in [false, true] { + let (a, b) = (gauss_pass(&img, sigma, vertical, repeat), gauss_pass_per_pixel(&img, sigma, vertical, repeat)); + let bits = |i: &Image| i.data.iter().flat_map(|p| p.map(f32::to_bits)).collect::>(); + assert!(bits(&a) == bits(&b), "{w}×{h} sigma {sigma} vertical {vertical} repeat {repeat}"); + } + } + } + } + } + + #[test] + fn a_non_finite_edge_pixel_outside_every_window_is_not_counted() { + // 9 wide, radius 1: the last pixel is in no window of the first pixels; likewise the last row. + let mut src = vec![[1.0f32; 4]; 81]; + src[80] = [f32::NAN; 4]; + let mut out = vec![[0.0f32; 4]; 81]; + box_h_into(&src, &mut out, 9, 1, true); + assert!(out[0].iter().all(|v| v.is_finite()), "{:?}", out[0]); + box_v_into(&src, &mut out, 9, 9, 1, true); + assert!(out[0].iter().all(|v| v.is_finite()), "{:?}", out[0]); + } + + #[test] + fn box_windows_count_repeated_edges_and_take_any_radius() { + // Against a window summed pixel by pixel, for radii inside and far past the image. + let (w, h) = (7usize, 5usize); + let src: Vec = (0..w * h).map(|i| [i as f32, (i % 3) as f32, 1.0, 0.5]).collect(); + let at = |x: isize, y: isize, repeat: bool| -> Px { + if !repeat && (x < 0 || y < 0 || x >= w as isize || y >= h as isize) { + return [0.0; 4]; + } + src[y.clamp(0, h as isize - 1) as usize * w + x.clamp(0, w as isize - 1) as usize] + }; + for repeat in [true, false] { + for r in [1usize, 3, 6, 9, 40] { + let (mut hx, mut vx) = (vec![[0.0; 4]; w * h], vec![[0.0; 4]; w * h]); + box_h_into(&src, &mut hx, w, r, repeat); + box_v_into(&src, &mut vx, w, h, r, repeat); + for y in 0..h as isize { + for x in 0..w as isize { + let (mut eh, mut ev) = ([0.0f32; 4], [0.0f32; 4]); + for d in -(r as isize)..=r as isize { + for c in 0..4 { + eh[c] += at(x + d, y, repeat)[c]; + ev[c] += at(x, y + d, repeat)[c]; + } + } + let n = (2 * r + 1) as f32; + let i = y as usize * w + x as usize; + for c in 0..4 { + assert!((hx[i][c] - eh[c] / n).abs() < 1e-3, "h r={r} repeat={repeat}"); + assert!((vx[i][c] - ev[c] / n).abs() < 1e-3, "v r={r} repeat={repeat}"); + } + } + } + } + } + // A radius of 2^40 finishes at once. + let mut out = vec![[0.0; 4]; w * h]; + box_h_into(&src, &mut out, w, 1 << 40, true); + box_v_into(&src, &mut out.clone(), w, h, 1 << 40, true); + } + #[test] fn gaussian_preserves_mass() { let mut img = Image::new(64, 64); diff --git a/crates/raster/src/channels3d.rs b/crates/raster/src/channels3d.rs index 034fb50fd..ae2d38303 100644 --- a/crates/raster/src/channels3d.rs +++ b/crates/raster/src/channels3d.rs @@ -127,12 +127,7 @@ impl AuxChannels { pub fn crypto_rank_planes(&self, layer: &str) -> Vec<(&[f32], &[f32])> { let mut out = vec![]; for k in 0.. { - let (r, g, b, a) = ( - self.get(&format!("{layer}{k:02}.R")), - self.get(&format!("{layer}{k:02}.G")), - self.get(&format!("{layer}{k:02}.B")), - self.get(&format!("{layer}{k:02}.A")), - ); + let (r, g, b, a) = (self.rank(layer, k, 'R'), self.rank(layer, k, 'G'), self.rank(layer, k, 'B'), self.rank(layer, k, 'A')); let (Some(r), Some(g)) = (r, g) else { break }; out.push((r, g)); if let (Some(b), Some(a)) = (b, a) { @@ -142,6 +137,13 @@ impl AuxChannels { out } + /// The plane `{layer}{k:02}.{comp}`: the layer name matches case-sensitively (layers + /// `Crypto_A` and `crypto_a` are different layers), the component letter either case. + fn rank(&self, layer: &str, k: usize, comp: char) -> Option<&[f32]> { + let tail = format!("{k:02}.{comp}"); + self.channels.iter().find(|(n, _)| n.strip_prefix(layer).is_some_and(|rest| rest.eq_ignore_ascii_case(&tail))).map(|(_, v)| v.as_slice()) + } + /// Rank pairs (id, coverage) of Cryptomatte layer `layer` at aux pixel index `i`. For a /// loop over pixels, use [`AuxChannels::crypto_rank_planes`] once instead. pub fn crypto_ranks(&self, layer: &str, i: usize) -> Vec<(f32, f32)> { @@ -155,6 +157,20 @@ impl AuxChannels { layers.iter().find(|l| l.as_str() == want || l.ends_with(want)).or(layers.first()).cloned() } + /// [`AuxChannels::resolve_crypto_layer`] with a layer named in full first: the layer called + /// exactly `name` when it is not empty and the footage has it (`Crypto_Material`, a name an + /// imported After Effects project carries), else the layer for `want`. + /// The name as given is tried first (EXR channel names may carry spaces), then trimmed. + pub fn resolve_crypto_layer_named(&self, name: &str, want: &str) -> Option { + let layers = self.crypto_layers(); + for name in [name, name.trim()] { + if !name.is_empty() && layers.iter().any(|l| l == name) { + return Some(name.to_string()); + } + } + self.resolve_crypto_layer(want) + } + /// The ID (its hash, `f32::to_bits`) with the most coverage at aux pixel `i` of Cryptomatte /// layer `layer`, summed over the ranks it appears in. Ties go to the lower rank; IDs with /// no positive coverage don't count. `None` when nothing covers the pixel. @@ -256,6 +272,19 @@ mod tests { let at = |i| a.crypto_id_at(&l, i); assert_eq!([at(0), at(1), at(2), at(3), at(9)], [Some(crypto_hash("y")), Some(crypto_hash("x")), None, Some(crypto_hash("x")), None]); assert_eq!(AuxChannels::new(1, 1, 1.0).resolve_crypto_layer("CryptoObject"), None); + // A layer named in full wins; an empty or missing name falls back to `want`. + assert_eq!(a.resolve_crypto_layer_named("Other", "CryptoObject").as_deref(), Some("Other")); + assert_eq!(a.resolve_crypto_layer_named(" Other ", "CryptoObject").as_deref(), Some("Other")); + assert_eq!(a.resolve_crypto_layer_named("", "CryptoObject").as_deref(), Some("ViewLayer.CryptoObject")); + assert_eq!(a.resolve_crypto_layer_named("Crypto_Name", "CryptoObject").as_deref(), Some("ViewLayer.CryptoObject")); + assert_eq!(AuxChannels::new(1, 1, 1.0).resolve_crypto_layer_named("Other", "CryptoObject"), None); + // A layer whose name ends in a space is matched as named, before the trimmed name. + let mut b = AuxChannels::new(1, 1, 1.0); + for l in ["Mat", "Mat "] { + b.channels.push((format!("{l}00.R"), vec![0.0])); + } + assert_eq!(b.resolve_crypto_layer_named("Mat ", "CryptoObject").as_deref(), Some("Mat ")); + assert_eq!(b.resolve_crypto_layer_named(" Mat", "CryptoObject").as_deref(), Some("Mat")); } #[test] @@ -321,4 +350,22 @@ mod tests { } assert!(a.crypto_rank_planes("CryptoObject").is_empty()); } + + /// Layers whose names differ only in case stay separate: `Crypto_A` and `crypto_a` each read + /// their own ranks (lowercase component letters still match), and picking agrees. + #[test] + fn crypto_layers_differing_in_case_read_their_own_planes() { + let mut a = AuxChannels::new(1, 1, 1.0); + let f = |n: &str| crypto_float(crypto_hash(n)); + for (n, v) in [("Crypto_A00.R", f("upper")), ("Crypto_A00.G", 1.0), ("crypto_a00.r", f("lower")), ("crypto_a00.g", 1.0)] { + a.channels.push((n.into(), vec![v])); + } + assert_eq!(a.crypto_layers(), vec!["Crypto_A".to_string(), "crypto_a".to_string()]); + assert_eq!(a.resolve_crypto_layer_named("crypto_a", "CryptoObject").as_deref(), Some("crypto_a")); + assert_eq!(a.crypto_rank_planes("crypto_a")[0].0, &[f("lower")][..]); + assert_eq!(a.crypto_rank_planes("Crypto_A")[0].0, &[f("upper")][..]); + assert_eq!(a.crypto_id_at("crypto_a", 0), Some(crypto_hash("lower"))); + assert_eq!(a.crypto_id_at("Crypto_A", 0), Some(crypto_hash("upper"))); + assert!(a.crypto_rank_planes("CRYPTO_A").is_empty()); + } } diff --git a/crates/raster/src/flow.rs b/crates/raster/src/flow.rs index feb033d65..4fdf0e060 100644 --- a/crates/raster/src/flow.rs +++ b/crates/raster/src/flow.rs @@ -51,6 +51,21 @@ impl Flow { } } +/// The `Plane::luma` of `a` and `b` packed into one image (`a` in the red channel, `b` in the +/// green; the rest zero). A device block matcher takes this as its input rather than computing +/// the luma itself: the weighted sum is not reproducible on a device, which may contract +/// `a·b + c` into a fused multiply-add, and the search's near-tie choices would then differ. +pub fn luma_pair(a: &Image, b: &Image) -> Image { + let luma = |p: &[f32; 4]| 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2] + 0.25 * p[3]; + let mut out = Image::new(a.width, a.height); + out.data.par_iter_mut().enumerate().for_each(|(i, q)| { + let la = a.data.get(i).map(luma).unwrap_or(0.0); + let lb = b.data.get(i).map(luma).unwrap_or(0.0); + *q = [la, lb, 0.0, 0.0]; + }); + out +} + /// A single-channel plane. struct Plane { w: usize, @@ -103,7 +118,8 @@ pub fn block_flow(a: &Image, b: &Image, block: u32, radius: i32) -> Flow { /// (Timewarp's Vector Detail and Block Size). pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i32) -> Flow { let bs = tile.max(2) as usize; - let win = window.max(4) as i64; + // The matching cost per vector grows with the window's area; 512 is far above any block size the effects offer. + let win = i64::from(window.clamp(4, 512)); // Window origin relative to the tile origin. let wo = bs as i64 / 2 - win / 2; let (w, h) = (a.width as usize, a.height as usize); @@ -280,6 +296,13 @@ mod tests { s / n as f32 } + #[test] + fn a_huge_matching_window_is_held_to_the_cap() { + let (a, b) = (texture(520, 520, 0.0), texture(520, 520, 2.0)); + let capped = block_flow_window(&a, &b, 260, 512, 2); + assert_eq!(block_flow_window(&a, &b, 260, u32::MAX, 2).v, capped.v); + } + #[test] fn flow_finds_translation() { let a = texture(128, 96, 0.0); diff --git a/crates/raster/src/inpaint.rs b/crates/raster/src/inpaint.rs index c64de3375..8b7127b4d 100644 --- a/crates/raster/src/inpaint.rs +++ b/crates/raster/src/inpaint.rs @@ -34,6 +34,7 @@ use rayon::prelude::*; use crate::Image; +use crate::Px; use crate::flow::{Flow, block_flow}; /// Fill method. @@ -562,23 +563,31 @@ pub fn patch_fill(img: &Image, hole: &[bool], init: Option<&Image>, patch: usize // ------------------------------------------------------------------ flow-guided propagation -/// Block flow from `a` to `b` with the tiles that touch either hole replaced by the membrane -/// interpolation of the surrounding motion (flow completion). +/// Block flow `a` → `b` (tile 8, search radius 6) with the tiles that touch either hole replaced +/// by the membrane interpolation of the surrounding motion (flow completion). fn completed_flow(a: &Image, b: &Image, hole_a: &[bool], hole_b: &[bool]) -> Flow { - let mut f = block_flow(a, b, 8, 6); + let f = block_flow(a, b, 8, 6); + complete_flow(f, hole_a, hole_b, a.width as usize, a.height as usize) +} + +/// The completion half of `completed_flow`: the tiles of `f` (a `block_flow` of `w × h`) that +/// touch either hole become the harmonic interpolation of the surrounding motion. Split out so a +/// hardware backend can compute the block matching itself and hand the raw field here; the +/// completion is cheap (the field is a `cols × rows` grid) and stays on the CPU. +pub fn complete_flow(mut f: Flow, hole_a: &[bool], hole_b: &[bool], w: usize, h: usize) -> Flow { if f.v.is_empty() { return f; } - let (w, bs) = (a.width as usize, f.block as usize); + let bs = f.block as usize; let mut known = vec![true; f.v.len()]; for (i, k) in known.iter_mut().enumerate() { let (c, r) = (i % f.cols, i / f.cols); // A tile is unreliable when any pixel within it (and a block's margin) is a hole. let (x0, y0) = ((c * bs).saturating_sub(bs / 2), (r * bs).saturating_sub(bs / 2)); - let (x1, y1) = (((c + 1) * bs + bs / 2).min(w), ((r + 1) * bs + bs / 2).min(a.height as usize)); + let (x1, y1) = (((c + 1) * bs + bs / 2).min(w), ((r + 1) * bs + bs / 2).min(h)); 'tile: for y in y0..y1 { for x in x0..x1 { - if hole_a[y * w + x] || hole_b[y * w + x] { + if hole_a.get(y * w + x).copied().unwrap_or(true) || hole_b.get(y * w + x).copied().unwrap_or(true) { *k = false; break 'tile; } @@ -597,12 +606,469 @@ fn completed_flow(a: &Image, b: &Image, hole_a: &[bool], hole_b: &[bool]) -> Flo f } +/// A hole mask packed into 64-bit words (1 bit per pixel) to keep the per-frame cost +/// down across a whole range (#2570). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HoleMask { + pub words: Vec, + pub len: usize, +} + +impl HoleMask { + /// Pack one `bool` a pixel into 64-bit words. + pub fn from_vec(hole: &[bool]) -> Self { + let mut words = vec![0u64; hole.len().div_ceil(64)]; + for (i, &h) in hole.iter().enumerate() { + if h { + words[i / 64] |= 1u64 << (i % 64); + } + } + HoleMask { words, len: hole.len() } + } + /// An all-known mask of `n` pixels. + pub fn zeros(n: usize) -> Self { + HoleMask { words: vec![0u64; n.div_ceil(64)], len: n } + } + /// Whether pixel `i` is in the hole. `words` and `len` are public, so a mask whose words are + /// shorter than `len` reads the missing pixels as known instead of panicking. + pub fn get(&self, i: usize) -> bool { + i < self.len && self.words.get(i / 64).is_some_and(|w| (w >> (i % 64)) & 1 == 1) + } + /// Mark pixel `i` as missing (`true`) or known (`false`). A pixel outside the mask is ignored. + pub fn set(&mut self, i: usize, v: bool) { + if i >= self.len { + return; + } + let Some(w) = self.words.get_mut(i / 64) else { + return; + }; + if v { + *w |= 1u64 << (i % 64); + } else { + *w &= !(1u64 << (i % 64)); + } + } + /// Whether any pixel is in the hole. + pub fn any(&self) -> bool { + self.words.iter().any(|&w| w != 0) + } + /// Unpack to one `bool` a pixel. + pub fn to_vec(&self) -> Vec { + (0..self.len).map(|i| self.get(i)).collect() + } +} + +/// Where a fill's input frames live. `Memory` keeps them in RAM (tests, small ranges); +/// `Spilled` stores them on disk and reads them on demand, so a whole range costs ~0 RAM. +#[derive(Clone)] +pub enum Frames { + Memory(Vec), + Spilled(SpillHandle), +} + +impl Frames { + /// The number of frames in the range. + pub fn len(&self) -> usize { + match self { + Frames::Memory(v) => v.len(), + Frames::Spilled(h) => h.n, + } + } + /// Whether the range has no frames. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + /// Frame `k`: a clone from RAM, or a decode from the spill. + pub fn get(&self, k: usize) -> Image { + match self { + Frames::Memory(v) => v[k].clone(), + Frames::Spilled(h) => h.get(k), + } + } + /// Frame size without decoding a whole image. + pub fn size(&self) -> Option<(usize, usize)> { + match self { + Frames::Memory(v) => v.first().map(|i| (i.width as usize, i.height as usize)), + Frames::Spilled(h) => Some((h.w, h.h)), + } + } + /// Bilinear sample of one pixel. A spilled frame reads only the 2x2 support from disk, so + /// the hot trace path never decodes or clones a whole frame (#2570). + pub fn sample(&self, k: usize, x: f64, y: f64) -> Px { + match self { + Frames::Memory(v) => v[k].sample_bilinear_clamped(x, y), + Frames::Spilled(h) => h.sample(k, x, y), + } + } + /// Directory of the spill file, so a secondary spill can live beside it. + pub fn scratch_dir(&self) -> Option { + match self { + Frames::Memory(_) => None, + Frames::Spilled(h) => h.dir().map(std::path::Path::to_path_buf), + } + } + /// Whether a read or write of a spilled frame failed. + pub fn has_error(&self) -> bool { + match self { + Frames::Memory(_) => false, + Frames::Spilled(h) => h.has_error(), + } + } + /// Take the first spill failure, clearing it. + pub fn take_error(&self) -> Option { + match self { + Frames::Memory(_) => None, + Frames::Spilled(h) => h.take_error(), + } + } + /// The error slot shared by every spill in this fill, so a caller holding a clone of the + /// input handle also sees failures in the propagated-frame spill. + pub fn error_cell(&self) -> Option>>> { + match self { + Frames::Memory(_) => None, + Frames::Spilled(h) => Some(h.error_cell()), + } + } +} + +/// A spill file holding `n` frames of `w x h` pixels at `bpc` bits per channel. +/// Frames are read back on demand. The file is shared (reference-counted), so it lives until the +/// last clone is dropped (#2570 review). +#[derive(Clone)] +pub struct SpillHandle { + inner: std::sync::Arc, + pub w: usize, + pub h: usize, + pub n: usize, + pub bpc: u8, +} + +struct SpillInner { + /// The folder the spill was created in (`None`: the system temporary folder), so the fill's + /// other spills go beside it. + dir: Option, + /// An anonymous temporary file: it has no name in `dir`, and the system reclaims it when the + /// last handle closes, even when the app is killed or runs out of memory partway through a + /// fill, so a multi-gigabyte scratch file is never left in the user's folder (#2570 review). + /// Every read and write is positioned on this one handle: several trace threads read the same + /// file at once, and a shared file offset would need a lock around every read (#2570). + file: std::fs::File, + /// Shared with any secondary spill so one probe reports every scratch failure. + error: std::sync::Arc>>, +} + +impl SpillHandle { + /// The folder the spill lives in (`None`: the system temporary folder). + pub fn dir(&self) -> Option<&std::path::Path> { + self.inner.dir.as_deref() + } + + /// Bytes a pixel in the spill: RGBA `u8`, or four `f32` above 8 bits a channel. + fn bytes_per_px(&self) -> usize { + if self.bpc <= 8 { 4 } else { 16 } + } + + /// Record a scratch failure in the shared slot, keeping the first. + pub fn record_error(&self, message: String) { + if let Ok(mut e) = self.inner.error.lock() + && e.is_none() + { + *e = Some(message); + } + } + + /// The error slot shared with any secondary spill. + pub fn error_cell(&self) -> std::sync::Arc>> { + std::sync::Arc::clone(&self.inner.error) + } + + /// Whether a read or write failed (`true` when the slot is poisoned). + pub fn has_error(&self) -> bool { + self.inner.error.lock().map(|e| e.is_some()).unwrap_or(true) + } + + /// Take the first failure, clearing it. + pub fn take_error(&self) -> Option { + self.inner.error.lock().ok().and_then(|mut e| e.take()) + } + + /// Read one whole frame from the spill, reporting a short or failed read. + fn load_frame(&self, k: usize) -> Image { + let mut img = Image::new(self.w as u32, self.h as u32); + let Some(px) = self.w.checked_mul(self.h) else { + self.record_error("spill: pixel count overflow".into()); + return img; + }; + let bytes_per_px = self.bytes_per_px(); + let Some(off) = k.checked_mul(px).and_then(|v| v.checked_mul(bytes_per_px)) else { + self.record_error(format!("spill: offset overflow for frame {k}")); + return img; + }; + let Some(len) = px.checked_mul(bytes_per_px) else { + self.record_error("spill: frame size overflow".into()); + return img; + }; + let mut buf = vec![0u8; len]; + if let Err(e) = self.read_at(off as u64, &mut buf) { + self.record_error(format!("spill: {e}")); + return img; + } + if self.bpc <= 8 { + for (i, p) in img.data.iter_mut().enumerate() { + let j = i * 4; + p[0] = buf[j] as f32 / 255.0; + p[1] = buf[j + 1] as f32 / 255.0; + p[2] = buf[j + 2] as f32 / 255.0; + p[3] = buf[j + 3] as f32 / 255.0; + } + } else { + for (i, p) in img.data.iter_mut().enumerate() { + let base = i * 16; + for c in 0..4 { + let mut b = [0u8; 4]; + b.copy_from_slice(&buf[base + c * 4..base + c * 4 + 4]); + p[c] = f32::from_bits(u32::from_le_bytes(b)); + } + } + } + img + } + + /// Read a whole frame, decoding it. + pub fn get(&self, k: usize) -> Image { + self.load_frame(k) + } + + /// A positioned read: `pread`/`seek_read` use the shared handle without touching a shared + /// file offset, so tracing threads do not serialise on the file. + fn read_at(&self, off: u64, buf: &mut [u8]) -> std::io::Result<()> { + let file = &self.inner.file; + #[cfg(unix)] + { + use std::os::unix::fs::FileExt; + file.read_exact_at(buf, off) + } + #[cfg(windows)] + { + use std::os::windows::fs::FileExt; + let mut done = 0usize; + while done < buf.len() { + match file.seek_read(&mut buf[done..], off.saturating_add(done as u64)) { + Ok(0) => return Err(std::io::ErrorKind::UnexpectedEof.into()), + Ok(n) => done += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + Ok(()) + } + // Elsewhere, seek the shared handle. Spills are only made natively: wasm keeps the + // propagated frames in RAM and has no file system to spill the input to. + #[cfg(not(any(unix, windows)))] + { + use std::io::{Read, Seek, SeekFrom}; + let mut f = file; + f.seek(SeekFrom::Start(off))?; + f.read_exact(buf) + } + } + + /// A positioned write on the same handle as `read_at`, so the propagation workers can store + /// their frames at once and the file never needs a name to be reopened by. + fn write_at(&self, off: u64, buf: &[u8]) -> std::io::Result<()> { + let file = &self.inner.file; + #[cfg(unix)] + { + use std::os::unix::fs::FileExt; + file.write_all_at(buf, off) + } + #[cfg(windows)] + { + use std::os::windows::fs::FileExt; + let mut done = 0usize; + while done < buf.len() { + match file.seek_write(&buf[done..], off.saturating_add(done as u64)) { + Ok(0) => return Err(std::io::ErrorKind::WriteZero.into()), + Ok(n) => done += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + Ok(()) + } + #[cfg(not(any(unix, windows)))] + { + use std::io::{Seek, SeekFrom, Write}; + let mut f = file; + f.seek(SeekFrom::Start(off))?; + f.write_all(buf) + } + } + + /// One pixel decoded from `buf` at index `i` (transparent if `buf` is short). + fn px_at(&self, buf: &[u8], i: usize) -> Px { + if self.bpc <= 8 { + let j = i * 4; + [ + buf.get(j).copied().unwrap_or(0) as f32 / 255.0, + buf.get(j + 1).copied().unwrap_or(0) as f32 / 255.0, + buf.get(j + 2).copied().unwrap_or(0) as f32 / 255.0, + buf.get(j + 3).copied().unwrap_or(0) as f32 / 255.0, + ] + } else { + let base = i * 16; + let mut p = [0.0f32; 4]; + for (c, v) in p.iter_mut().enumerate() { + let at = base + c * 4; + let Some(b) = buf.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()) else { + return [0.0; 4]; + }; + *v = f32::from_bits(u32::from_le_bytes(b)); + } + p + } + } + + /// The two horizontally adjacent pixels (`x`, `x + 1`, both clamped) of row `y` (clamped), + /// read straight from the spill file. + fn edge(&self, k: usize, y: i64, x: i64) -> Option<(Px, Px)> { + let (w, h) = (self.w, self.h); + if w == 0 || h == 0 || k >= self.n { + return None; + } + let (iw, ih) = (i64::try_from(w).ok()?, i64::try_from(h).ok()?); + let y = y.clamp(0, ih - 1) as usize; + let xa = x.clamp(0, iw - 1) as usize; + let xb = x.saturating_add(1).clamp(0, iw - 1) as usize; + let bpp = self.bytes_per_px(); + let off = k + .checked_mul(w) + .and_then(|v| v.checked_mul(h)) + .and_then(|v| v.checked_add(y.checked_mul(w)?)) + .and_then(|v| v.checked_add(xa)) + .and_then(|v| v.checked_mul(bpp)); + let Some(off) = off.and_then(|v| u64::try_from(v).ok()) else { + self.record_error("spill: sample offset overflow".into()); + return None; + }; + // One read covers both pixels unless the right edge clamps them together. A stack buffer + // keeps the per-sample allocation out of the trace loop. + let len = (xb - xa + 1) * bpp; + let mut held = [0u8; 32]; + let buf = held.get_mut(..len)?; + if let Err(e) = self.read_at(off, buf) { + self.record_error(format!("spill: {e}")); + return None; + } + let a = self.px_at(buf, 0); + let b = if xb > xa { self.px_at(buf, 1) } else { a }; + Some((a, b)) + } + + /// Bilinear sample of one pixel, reading only its 2x2 support. Matches + /// `Image::sample_bilinear_clamped` exactly, with the same edge clamping. + pub fn sample(&self, k: usize, x: f64, y: f64) -> Px { + let fx = x - 0.5; + let fy = y - 0.5; + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32); + // `as i64` saturates NaN and out-of-range values, as in `sample_bilinear_clamped`. + let (x0, y0) = (x0 as i64, y0 as i64); + let (Some((a, b)), Some((c, d))) = (self.edge(k, y0, x0), self.edge(k, y0.saturating_add(1), x0)) else { + return [0.0; 4]; + }; + let mut o = [0.0; 4]; + for i in 0..4 { + let top = a[i] + (b[i] - a[i]) * tx; + let bot = c[i] + (d[i] - c[i]) * tx; + o[i] = top + (bot - top) * ty; + } + o + } + + /// Write frame `k` into the spill, reporting a disk error. + pub fn write_frame(&self, k: usize, img: &Image) -> std::result::Result<(), String> { + if k >= self.n { + return Err(format!("spill: frame {k} out of range (n = {})", self.n)); + } + if img.width as usize != self.w || img.height as usize != self.h { + return Err(format!("spill: frame {k} is {}x{}, expected {}x{}", img.width, img.height, self.w, self.h)); + } + let bytes_per_px = self.bytes_per_px(); + let px = self.w.checked_mul(self.h).ok_or("overflow")?; + let off = k.checked_mul(px).and_then(|v| v.checked_mul(bytes_per_px)).ok_or("overflow")?; + let buf = if self.bpc <= 8 { + let mut buf = vec![0u8; px * 4]; + for (i, p) in img.data.iter().enumerate() { + buf[i * 4] = (p[0] * 255.0).round().clamp(0.0, 255.0) as u8; + buf[i * 4 + 1] = (p[1] * 255.0).round().clamp(0.0, 255.0) as u8; + buf[i * 4 + 2] = (p[2] * 255.0).round().clamp(0.0, 255.0) as u8; + buf[i * 4 + 3] = (p[3] * 255.0).round().clamp(0.0, 255.0) as u8; + } + buf + } else { + let mut buf = vec![0u8; px * 16]; + for (i, p) in img.data.iter().enumerate() { + let base = i * 16; + for c in 0..4 { + buf[base + c * 4..base + c * 4 + 4].copy_from_slice(&p[c].to_le_bytes()); + } + } + buf + }; + self.write_at(off as u64, &buf).map_err(|e| format!("spill: {e}")) + } + + /// Create a spill file. `dir` lets the caller keep scratch next to the output (so a + /// RAM-backed `/tmp` does not defeat the point of spilling); `None` uses the temp dir. + pub fn create_in(dir: Option<&std::path::Path>, w: usize, h: usize, n: usize, bpc: u8) -> std::io::Result { + Self::create_in_with_error(dir, w, h, n, bpc, None) + } + + /// `error`: share an existing error slot, so a secondary spill reports through the same + /// handle the caller already watches (#2570 review). + pub fn create_in_with_error( + dir: Option<&std::path::Path>, + w: usize, + h: usize, + n: usize, + bpc: u8, + error: Option>>>, + ) -> std::io::Result { + let bytes_per_px: usize = if bpc <= 8 { 4 } else { 16 }; + let total = n + .checked_mul(w) + .and_then(|v| v.checked_mul(h)) + .and_then(|v| v.checked_mul(bytes_per_px)) + .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidInput, "overflow"))?; + // Anonymous, so nothing is left behind if `set_len` fails below or the app never gets + // to clean up. + let file = match dir { + Some(d) => { + std::fs::create_dir_all(d)?; + tempfile::tempfile_in(d)? + } + None => tempfile::tempfile()?, + }; + file.set_len(total as u64)?; + let error = error.unwrap_or_else(|| std::sync::Arc::new(std::sync::Mutex::new(None))); + let inner = std::sync::Arc::new(SpillInner { dir: dir.map(std::path::Path::to_path_buf), file, error }); + Ok(SpillHandle { inner, w, h, n, bpc }) + } + + /// Create a spill in the system temporary directory. + pub fn create(w: usize, h: usize, n: usize, bpc: u8) -> std::io::Result { + Self::create_in(None, w, h, n, bpc) + } +} + /// The input of a sequence fill. +#[derive(Clone)] pub struct FillInput { - /// Frames (premultiplied RGBA, all the same size). - pub frames: Vec, - /// Per frame, `true` where the pixel is missing. - pub holes: Vec>, + /// Frames (premultiplied RGBA, all the same size), in RAM or spilled to disk. + pub frames: Frames, + /// Per frame, packed hole mask (`true` where the pixel is missing). + pub holes: Vec, /// Complete images for some frames: (frame index, image). pub references: Vec<(usize, Image)>, } @@ -612,7 +1078,10 @@ struct TraceContext<'a> { fwd: &'a [Flow], bwd: &'a [Flow], known: &'a (dyn Fn(usize, i64, i64) -> bool + Sync), - frames: &'a [&'a Image], + frames: &'a Frames, + ref_images: &'a [Option], + w: usize, + h: usize, max: usize, } @@ -627,7 +1096,7 @@ struct TraceStart { /// Trace a point to the nearest visible frame: (sampled colour, frames travelled). fn trace(context: &TraceContext<'_>, start: TraceStart) -> Option<([f32; 4], usize)> { let n = context.frames.len(); - let (w, h) = (context.frames[0].width as f64, context.frames[0].height as f64); + let (w, h) = (context.w as f64, context.h as f64); let (mut px, mut py) = (start.x, start.y); let mut k = start.frame as i64; for d in 1..=context.max { @@ -654,136 +1123,417 @@ fn trace(context: &TraceContext<'_>, start: TraceStart) -> Option<([f32; 4], usi .iter() .all(|&(xx, yy)| (context.known)(k as usize, xx.clamp(0, w as i64 - 1), yy.clamp(0, h as i64 - 1))); if ok { - return Some((context.frames[k as usize].sample_bilinear_clamped(px, py), d)); + let img = if let Some(r) = &context.ref_images[k as usize] { + r.sample_bilinear_clamped(px, py) + } else { + // Samples a pixel; never clones a whole spilled frame (the trace hot path). + context.frames.sample(k as usize, px, py) + }; + return Some((img, d)); } } None } -/// Fill a range of frames. `progress(done, total)` returns `false` to cancel (→ `None`). +/// A hardware backend for the fill's stages (the GPU compositor implements it; see +/// `effectcraft_render::Accelerator::inpaint`). Every method has the CPU implementation as its +/// default, so a backend that cannot take a stage returns the CPU's work and the fill stays +/// correct — only slower. +/// +/// The orchestration ([`fill_sequence_with`]) stays on the CPU: the sequence's frame-to-frame +/// coupling is sequential, and only the per-frame and per-pair work is worth offloading. +/// +/// **A backend must be safe to call concurrently.** [`fill_sequence_with`] runs the stages of +/// independent frames and frame pairs in parallel (`rayon`), so `membrane`, `flow` and `patch` +/// may all be entered from several threads at once — a backend that owns a device must serialise +/// its use of it (the GPU compositor's per-call encoder does; a backend whose device cannot be +/// used from several threads must lock). +pub trait FillBackend: Send + Sync { + /// [`membrane_fill`]: the `hole` pixels take the harmonic interpolation of their border. + fn membrane(&self, img: &Image, hole: &[bool]) -> Image { + membrane_fill(img, hole) + } + /// `membrane_core`: harmonic interpolation of `data`'s unknown pixels in place (`known` is + /// true where the pixel is known). + fn membrane_known(&self, data: &mut [[f32; 4]], known: &[bool], w: usize, h: usize) { + membrane_core(data, known, w, h) + } + /// `completed_flow`: block flow `a` → `b` with the tiles touching either hole replaced by + /// the membrane interpolation of the surrounding motion. + fn flow(&self, a: &Image, b: &Image, hole_a: &[bool], hole_b: &[bool]) -> Flow { + completed_flow(a, b, hole_a, hole_b) + } + /// [`patch_fill`]: PatchMatch synthesis of `img`'s `hole` (`init`: a starting guess, e.g. the + /// previous frame's fill warped here). + fn patch(&self, img: &Image, hole: &[bool], init: Option<&Image>, patch: usize, seed: u32) -> Image { + patch_fill(img, hole, init, patch, seed) + } +} + +/// The CPU backend: every stage is the reference implementation. +pub struct CpuFill; + +impl FillBackend for CpuFill {} + +/// Holds the propagated frames between the parallel propagation pass and the sequential +/// synthesis pass. Native builds spill them beside the input, so a whole range is never +/// resident at once (#2570); wasm keeps them in memory (it has no shared file system). +enum PropStore { + #[cfg(not(target_arch = "wasm32"))] + Spilled(SpillHandle), + #[cfg(target_arch = "wasm32")] + Memory(std::sync::Mutex>>), +} + +impl PropStore { + /// Open the propagated-frame store: spilled natively, in RAM on wasm. + fn new( + dir: Option<&std::path::Path>, + w: usize, + h: usize, + n: usize, + error: Option>>>, + ) -> std::io::Result { + #[cfg(not(target_arch = "wasm32"))] + { + // 32-bit floats: propagating quantized input would lose quality (#2570). + Ok(PropStore::Spilled(SpillHandle::create_in_with_error(dir, w, h, n, 32, error)?)) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (dir, w, h, error); + Ok(PropStore::Memory(std::sync::Mutex::new((0..n).map(|_| None).collect()))) + } + } + + /// Store frame `k`, reporting a spill write failure. + fn put(&self, k: usize, img: Image) -> std::result::Result<(), String> { + match self { + #[cfg(not(target_arch = "wasm32"))] + PropStore::Spilled(h) => h.write_frame(k, &img), + #[cfg(target_arch = "wasm32")] + PropStore::Memory(v) => { + let mut v = v.lock().map_err(|_| "propagation store poisoned".to_string())?; + if let Some(slot) = v.get_mut(k) { + *slot = Some(img); + } + Ok(()) + } + } + } + + /// Read a stored frame without consuming it (a frame can be shared by two flows). + fn get(&self, k: usize) -> Image { + match self { + #[cfg(not(target_arch = "wasm32"))] + PropStore::Spilled(h) => h.get(k), + #[cfg(target_arch = "wasm32")] + PropStore::Memory(v) => v.lock().ok().and_then(|v| v.get(k).cloned()).flatten().unwrap_or_default(), + } + } + + /// Read a propagated frame once, freeing it where the backing store allows it. + fn take(&self, k: usize) -> Image { + match self { + #[cfg(not(target_arch = "wasm32"))] + PropStore::Spilled(h) => h.get(k), + #[cfg(target_arch = "wasm32")] + PropStore::Memory(v) => v.lock().ok().and_then(|mut v| v.get_mut(k).and_then(Option::take)).unwrap_or_default(), + } + } + + /// Record a failure in the spill, so the caller reports it instead of a bare cancellation. + fn record_error(&self, message: String) { + match self { + #[cfg(not(target_arch = "wasm32"))] + PropStore::Spilled(h) => h.record_error(message), + #[cfg(target_arch = "wasm32")] + PropStore::Memory(_) => { + let _ = message; + } + } + } + + /// Whether the spill failed (always `false` on wasm, which keeps frames in RAM). + fn has_error(&self) -> bool { + match self { + #[cfg(not(target_arch = "wasm32"))] + PropStore::Spilled(h) => h.has_error(), + #[cfg(target_arch = "wasm32")] + PropStore::Memory(_) => false, + } + } +} + +/// Publish a scratch failure through the input spill's shared error slot, so the caller reports +/// the disk error instead of a bare cancellation. +fn record_spill_error(cell: &Option>>>, message: String) { + if let Some(cell) = cell + && let Ok(mut e) = cell.lock() + && e.is_none() + { + *e = Some(message); + } +} + +/// Membrane-fill every frame and return the forward/backward flow for each neighbouring pair. +/// The filled frames are written to a scratch spill, so the flow pass never holds the range in +/// RAM (#2570). +#[allow(clippy::too_many_arguments)] +fn flow_pairs( + n: usize, + w: usize, + h: usize, + holes: &[HoleMask], + is_ref: &[bool], + ref_images: &[Option], + frames: &Frames, + prop_dir: Option<&std::path::Path>, + error_cell: Option>>>, + backend: &dyn FillBackend, +) -> Option> { + let store = match PropStore::new(prop_dir, w, h, n, error_cell.clone()) { + Ok(s) => s, + Err(e) => { + record_spill_error(&error_cell, format!("spill: {e}")); + return None; + } + }; + let pre = (0..n).into_par_iter().try_for_each(|t| { + let base = if is_ref[t] { ref_images[t].clone().unwrap_or_default() } else { frames.get(t) }; + let img = backend.membrane(&base, &holes[t].to_vec()); + store.put(t, img) + }); + if let Err(e) = pre { + record_spill_error(&error_cell, e); + return None; + } + if frames.has_error() { + return None; + } + let pairs: Vec<(Flow, Flow)> = (0..n.saturating_sub(1)) + .into_par_iter() + .map(|i| { + let a = store.get(i); + let b = store.get(i + 1); + let ha = holes[i].to_vec(); + let hb = holes[i + 1].to_vec(); + (backend.flow(&a, &b, &ha, &hb), backend.flow(&b, &a, &hb, &ha)) + }) + .collect(); + let store_failed = store.has_error(); + drop(store); + if store_failed || frames.has_error() { None } else { Some(pairs) } +} + +/// Fill a range of frames on the CPU. `progress(done, total)` returns `false` to cancel +/// (→ `None`). pub fn fill_sequence(input: &FillInput, o: &FillOpts, progress: &mut dyn FnMut(usize, usize) -> bool) -> Option> { + fill_sequence_with(input.clone(), o, &CpuFill, progress, None) +} + +/// [`fill_sequence`] with a hardware backend for the stages it can take (see [`FillBackend`]). +pub fn fill_sequence_with( + mut input: FillInput, + o: &FillOpts, + backend: &dyn FillBackend, + progress: &mut dyn FnMut(usize, usize) -> bool, + mut sink: Option<&mut dyn FnMut(usize, &Image) -> Result<(), String>>, +) -> Option> { let n = input.frames.len(); if n == 0 { return Some(vec![]); } - let (w, h) = (input.frames[0].width as usize, input.frames[0].height as usize); + let (w, h) = input.frames.size().unwrap_or((0, 0)); + if w == 0 || h == 0 { + return Some(vec![]); + } // Steps: flows (1) + propagation (1) + per-frame synthesis (n). let total = n + 2; + let streaming = sink.is_some(); if o.method == FillMethod::EdgeBlend { let mut out = Vec::with_capacity(n); - for (i, (f, hl)) in input.frames.iter().zip(&input.holes).enumerate() { - out.push(opaque_fill(membrane_fill(f, hl), hl)); + for i in 0..n { + let f = input.frames.get(i); + // A failed read returns a black frame, which must never reach the sink. + if input.frames.has_error() { + return None; + } + let hl = input.holes[i].to_vec(); + let img = opaque_fill(backend.membrane(&f, &hl), &hl); + if let Some(cb) = sink.as_mut() + && cb(i, &img).is_err() + { + return None; + } + if !streaming { + out.push(img); + } if !progress(i + 1, n) { return None; } } + if input.frames.has_error() { + return None; + } + if streaming { + return Some(Vec::new()); + } return Some(out); } // Reference frames make their frame fully known. - let mut frames: Vec = input.frames.clone(); - let mut holes: Vec> = input.holes.clone(); + let mut holes: Vec = std::mem::take(&mut input.holes); + let references = std::mem::take(&mut input.references); let mut is_ref = vec![false; n]; - for (k, img) in &input.references { - if *k < n && img.width as usize == w && img.height as usize == h { - frames[*k] = img.clone(); - holes[*k] = vec![false; w * h]; - is_ref[*k] = true; + let mut ref_images: Vec> = vec![None; n]; + for (k, img) in references { + if k < n && img.width as usize == w && img.height as usize == h { + ref_images[k] = Some(img); + holes[k] = HoleMask::zeros(w * h); + is_ref[k] = true; } } - // 1. Flows between membrane-filled neighbours, completed inside the holes. - let pre: Vec = frames.par_iter().zip(&holes).map(|(f, hl)| membrane_fill(f, hl)).collect(); - let pairs: Vec<(Flow, Flow)> = (0..n.saturating_sub(1)) - .into_par_iter() - .map(|i| (completed_flow(&pre[i], &pre[i + 1], &holes[i], &holes[i + 1]), completed_flow(&pre[i + 1], &pre[i], &holes[i + 1], &holes[i]))) - .collect(); + let prop_dir = input.frames.scratch_dir(); + let error_cell = input.frames.error_cell(); + // 1. Flows between membrane-filled neighbours, completed inside the holes. The + // membrane-filled frames are spilled too, so the flow pass does not hold the range. + let pairs = flow_pairs(n, w, h, &holes, &is_ref, &ref_images, &input.frames, prop_dir.as_deref(), error_cell.clone(), backend)?; let (fwd, bwd): (Vec, Vec) = pairs.into_iter().unzip(); if !progress(1, total) { return None; } - // 2. Propagation (and the lighting-correction border ring). - let refs: Vec<&Image> = frames.iter().collect(); - let known = |k: usize, x: i64, y: i64| !holes[k][y as usize * w + x as usize]; - let trace_context = TraceContext { fwd: &fwd, bwd: &bwd, known: &known, frames: &refs, max: n }; + // 2. Propagation (and the lighting-correction border ring). The filled frames are + // spilled as they are produced, so only the leftover masks stay in RAM. + let store = match PropStore::new(prop_dir.as_deref(), w, h, n, error_cell.clone()) { + Ok(s) => s, + Err(e) => { + record_spill_error(&error_cell, format!("spill: {e}")); + return None; + } + }; + let known = |k: usize, x: i64, y: i64| !holes[k].get(y as usize * w + x as usize); + let trace_context = TraceContext { fwd: &fwd, bwd: &bwd, known: &known, frames: &input.frames, ref_images: &ref_images, w, h, max: n }; let ring_r = 2usize; - let propagated: Vec<(Image, Vec)> = (0..n) + let propagated_left: Vec = (0..n) .into_par_iter() .map(|t| { - let mut img = frames[t].clone(); - let mut left = holes[t].clone(); - if is_ref[t] || !holes[t].iter().any(|b| *b) { - return (img, left); + // Once a frame failed to spill or read the fill is lost: stop tracing the rest (the + // masks are dropped below). + if store.has_error() || input.frames.has_error() { + return HoleMask::default(); } - let sample = |i: usize| -> Option<[f32; 4]> { - let (x, y) = ((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); - let f = trace(&trace_context, TraceStart { frame: t, x, y, step: 1 }); - let b = trace(&trace_context, TraceStart { frame: t, x, y, step: -1 }); - match (f, b) { - (Some((a, da)), Some((c, dc))) => { - let (wa, wc) = (1.0 / da as f32, 1.0 / dc as f32); - Some(std::array::from_fn(|k| (a[k] * wa + c[k] * wc) / (wa + wc))) + let mut img = if is_ref[t] { ref_images[t].clone().unwrap_or_default() } else { input.frames.get(t) }; + let mut left = holes[t].to_vec(); + if !is_ref[t] && holes[t].any() { + let sample = |i: usize| -> Option<[f32; 4]> { + let (x, y) = ((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + let f = trace(&trace_context, TraceStart { frame: t, x, y, step: 1 }); + let b = trace(&trace_context, TraceStart { frame: t, x, y, step: -1 }); + match (f, b) { + (Some((a, da)), Some((c, dc))) => { + let (wa, wc) = (1.0 / da as f32, 1.0 / dc as f32); + Some(std::array::from_fn(|k| (a[k] * wa + c[k] * wc) / (wa + wc))) + } + (Some((a, _)), None) | (None, Some((a, _))) => Some(a), + _ => None, } - (Some((a, _)), None) | (None, Some((a, _))) => Some(a), - _ => None, + }; + let filled: Vec<(usize, [f32; 4])> = (0..w * h).filter(|&i| holes[t].get(i)).filter_map(|i| sample(i).map(|v| (i, v))).collect(); + for (i, v) in &filled { + img.data[*i] = *v; + left[*i] = false; } - }; - let filled: Vec<(usize, [f32; 4])> = (0..w * h).filter(|&i| holes[t][i]).filter_map(|i| sample(i).map(|v| (i, v))).collect(); - for (i, v) in &filled { - img.data[*i] = *v; - left[*i] = false; - } - // Lighting correction: membrane of the border mismatch, added to propagated pixels. - if o.lighting > 0.0 && !filled.is_empty() { - let grown = dilate(&holes[t], w, h, ring_r); - let mut diff = vec![[0.0f32; 4]; w * h]; - let mut dk = vec![true; w * h]; - for i in 0..w * h { - if holes[t][i] { - dk[i] = false; - } else if grown[i] - && let Some(v) = sample(i) - { - let a = frames[t].data[i]; - diff[i] = std::array::from_fn(|c| if c < 3 { a[c] - v[c] } else { 0.0 }); + // Lighting correction: membrane of the border mismatch, added to propagated pixels. + // Non-hole pixels are untouched above, so `img` is still the original there. + if o.lighting > 0.0 && !filled.is_empty() { + let grown = dilate(&holes[t].to_vec(), w, h, ring_r); + let mut diff = vec![[0.0f32; 4]; w * h]; + let mut dk = vec![true; w * h]; + for i in 0..w * h { + if holes[t].get(i) { + dk[i] = false; + } else if grown[i] + && let Some(v) = sample(i) + { + let a = img.data[i]; + diff[i] = std::array::from_fn(|c| if c < 3 { a[c] - v[c] } else { 0.0 }); + } } - } - membrane_core(&mut diff, &dk, w, h); - for (i, _) in &filled { - for c in 0..3 { - img.data[*i][c] += o.lighting * diff[*i][c]; + backend.membrane_known(&mut diff, &dk, w, h); + for (i, _) in &filled { + for c in 0..3 { + img.data[*i][c] += o.lighting * diff[*i][c]; + } } } } - (img, left) + if let Err(e) = store.put(t, img) { + store.record_error(e); + } + HoleMask::from_vec(&left) }) .collect(); + if input.frames.has_error() || store.has_error() { + return None; + } + drop(input); if !progress(2, total) { return None; } // 3. Synthesis of what no frame shows. let mut out: Vec> = vec![None; n]; - let first = (0..n).find(|&t| propagated[t].1.iter().any(|b| *b)); + let first = (0..n).find(|&t| propagated_left[t].any()); let Some(t0) = first else { - return Some(propagated.into_iter().zip(&holes).map(|((img, _), hl)| opaque_fill(img, hl)).collect()); + if streaming { + for t in 0..n { + let img = opaque_fill(take_checked(&store, t)?, &holes[t].to_vec()); + if !stream_frame(&mut sink, t, Some(&img), &holes) { + return None; + } + } + return Some(Vec::new()); + } + let out: Vec = (0..n).map(|t| opaque_fill(store.take(t), &holes[t].to_vec())).collect(); + if store.has_error() { + return None; + } + return Some(out); }; // Frames before t0 are complete already. - for (t, slot) in out.iter_mut().enumerate().take(t0) { - *slot = Some(propagated[t].0.clone()); + for t in 0..t0 { + let img = take_checked(&store, t)?; + if streaming { + if !stream_frame(&mut sink, t, Some(&img), &holes) { + return None; + } + } else { + out[t] = Some(img); + } } let mut done = 2; - out[t0] = Some(patch_fill(&propagated[t0].0, &propagated[t0].1, None, o.patch, o.seed)); + let left0 = propagated_left[t0].to_vec(); + out[t0] = Some(backend.patch(&take_checked(&store, t0)?, &left0, None, o.patch, o.seed)); + if !stream_frame(&mut sink, t0, out[t0].as_ref(), &holes) { + return None; + } done += 1; if !progress(done, total) { return None; } for t in t0 + 1..n { - let (img, left) = &propagated[t]; - if !left.iter().any(|b| *b) { - out[t] = Some(img.clone()); + let complete = !propagated_left[t].any(); + if complete { + out[t] = Some(take_checked(&store, t)?); } else { + let img = take_checked(&store, t)?; + let left = propagated_left[t].to_vec(); // Warp the previous result here along the backward flow (t → t − 1). // Frames after `t0` are filled in order, so the previous one is set. let Some(prev) = out[t - 1].as_ref() else { - out[t] = Some(patch_fill(img, left, None, o.patch, o.seed)); + out[t] = Some(backend.patch(&img, &left, None, o.patch, o.seed)); + if !stream_frame(&mut sink, t, out[t].as_ref(), &holes) { + return None; + } continue; }; let mut warped = img.clone(); @@ -796,15 +1546,47 @@ pub fn fill_sequence(input: &FillInput, o: &FillOpts, progress: &mut dyn FnMut(u } out[t] = Some(match o.method { FillMethod::Surface => warped, - _ => patch_fill(img, left, Some(&warped), o.patch, o.seed), + _ => backend.patch(&img, &left, Some(&warped), o.patch, o.seed), }); } + // Only the streaming sink has consumed the frame; a non-streaming result returns it. + if streaming && t >= 2 { + out[t - 2] = None; + } + if !stream_frame(&mut sink, t, out[t].as_ref(), &holes) { + return None; + } done += 1; if !progress(done, total) { return None; } } - Some(out.into_iter().zip(&holes).map(|(img, hl)| opaque_fill(img.unwrap_or_default(), hl)).collect()) + if store.has_error() { + return None; + } + if streaming { + for slot in out.iter_mut() { + *slot = None; + } + return Some(Vec::new()); + } + Some(out.into_iter().enumerate().map(|(i, img)| opaque_fill(img.unwrap_or_default(), &holes[i].to_vec())).collect()) +} + +/// Take frame `k` from the store, or `None` when the spill read failed. A failed read yields a +/// black frame, which must never be emitted (#2570 review). +fn take_checked(store: &PropStore, k: usize) -> Option { + let img = store.take(k); + (!store.has_error()).then_some(img) +} + +/// Hand frame `t` to the streaming sink with its filled pixels made opaque. `true` when there is +/// no sink or it accepted the frame. +fn stream_frame(sink: &mut Option<&mut dyn FnMut(usize, &Image) -> Result<(), String>>, t: usize, img: Option<&Image>, holes: &[HoleMask]) -> bool { + let (Some(cb), Some(img)) = (sink.as_mut(), img) else { + return true; + }; + cb(t, &opaque_fill(img.clone(), &holes[t].to_vec())).is_ok() } /// Filled pixels are opaque. @@ -851,6 +1633,47 @@ mod tests { (0..w * h).map(|i| (x0..x0 + s).contains(&(i % w)) && (y0..y0 + s).contains(&(i / w))).collect() } + /// Packing and unpacking a hole mask round-trips every pixel. + #[test] + fn holemask_roundtrip() { + let v: Vec = (0..1000).map(|i| i % 3 == 0).collect(); + let m = HoleMask::from_vec(&v); + assert_eq!(m.to_vec(), v); + for i in 0..v.len() { + assert_eq!(m.get(i), v[i]); + } + } + + /// Packing round-trips where the last word is full, holds one bit or is one bit short, and + /// `set` builds the same mask; a mask whose public `words` are shorter than `len` reads and + /// writes without panicking (#2570 review). + #[test] + fn holemask_roundtrips_at_word_boundaries() { + for len in [1usize, 63, 64, 65, 127, 128, 129, 191, 192] { + let v: Vec = (0..len).map(|i| i % 3 == 0 || i == len - 1).collect(); + let m = HoleMask::from_vec(&v); + assert_eq!(m.words.len(), len.div_ceil(64), "len {len}"); + assert_eq!(m.to_vec(), v, "len {len}"); + let mut s = HoleMask::zeros(len); + for (i, &h) in v.iter().enumerate() { + s.set(i, h); + } + assert_eq!(s, m, "len {len}: set builds the packed mask"); + for i in 0..len { + s.set(i, false); + } + assert!(!s.any(), "len {len}: every pixel cleared"); + // A pixel past the end is ignored. + s.set(len, true); + assert!(!s.get(len), "len {len}"); + assert!(!s.any(), "len {len}"); + } + let mut short = HoleMask { words: vec![], len: 100 }; + assert!(!short.get(70)); + short.set(70, true); + assert!(!short.any()); + } + #[test] fn membrane_matches_a_linear_ramp() { let (w, h) = (40u32, 30u32); @@ -894,10 +1717,10 @@ mod tests { let gt = background(w, h, t as f32 * pan); let hole = rect_hole(w, h, 10 + 8 * t as u32, 22, 18); frames.push(cut(>, &hole)); - holes.push(hole); + holes.push(HoleMask::from_vec(&hole)); gts.push(gt); } - (FillInput { frames, holes, references: vec![] }, gts) + (FillInput { frames: Frames::Memory(frames), holes, references: vec![] }, gts) } #[test] @@ -906,7 +1729,7 @@ mod tests { let (input, gts) = sequence(8, pan); let out = fill_sequence(&input, &FillOpts::default(), &mut |_, _| true).expect("fill"); for t in 0..out.len() { - let db = psnr(&out[t], >s[t], Some(&input.holes[t])); + let db = psnr(&out[t], >s[t], Some(&input.holes[t].to_vec())); assert!(db > 26.0, "frame {t} pan {pan}: {db:.1} dB"); assert_eq!(out[t].data[0][3], 1.0); } @@ -914,7 +1737,7 @@ mod tests { // Temporal consistency: on a static background the filled pixels agree between // frames. for t in 1..out.len() { - let both: Vec = input.holes[t].iter().zip(&input.holes[t - 1]).map(|(a, b)| *a || *b).collect(); + let both: Vec = input.holes[t].to_vec().iter().zip(input.holes[t - 1].to_vec().iter()).map(|(a, b)| *a || *b).collect(); let db = psnr(&out[t], &out[t - 1], Some(&both)); assert!(db > 30.0, "frames {}–{t} differ: {db:.1} dB", t - 1); } @@ -928,14 +1751,14 @@ mod tests { let (w, h) = (80u32, 60u32); let gt = background(w, h, 0.0); let hole = rect_hole(w, h, 30, 20, 14); - let input = FillInput { frames: vec![cut(>, &hole); 4], holes: vec![hole.clone(); 4], references: vec![] }; + let input = FillInput { frames: Frames::Memory(vec![cut(>, &hole); 4]), holes: vec![HoleMask::from_vec(&hole); 4], references: vec![] }; let surf = fill_sequence(&input, &FillOpts { method: FillMethod::Surface, ..Default::default() }, &mut |_, _| true).expect("fill"); for t in 1..4 { // Surface carries one fill through: identical frames. assert!(psnr(&surf[t], &surf[0], Some(&hole)) > 40.0); } let edge = fill_sequence(&input, &FillOpts { method: FillMethod::EdgeBlend, ..Default::default() }, &mut |_, _| true).expect("fill"); - assert!(psnr(&edge[0], &membrane_fill(&input.frames[0], &hole), Some(&hole)) > 60.0); + assert!(psnr(&edge[0], &membrane_fill(&input.frames.get(0), &hole), Some(&hole)) > 60.0); // A clean reference frame recovers the background exactly. let mut with_ref = FillInput { frames: input.frames.clone(), holes: input.holes.clone(), references: vec![(2, gt.clone())] }; let out = fill_sequence(&with_ref, &FillOpts::default(), &mut |_, _| true).expect("fill"); @@ -951,9 +1774,13 @@ mod tests { fn lighting_correction_absorbs_a_brightness_change() { // The background brightens over time; propagated pixels come from darker frames. let (mut input, mut gts) = sequence(6, 0.0); + let mut frames = match std::mem::replace(&mut input.frames, Frames::Memory(vec![])) { + Frames::Memory(v) => v, + _ => vec![], + }; for t in 0..6 { let k = 1.0 + 0.06 * t as f32; - for img in [&mut input.frames[t], &mut gts[t]] { + for img in [&mut frames[t], &mut gts[t]] { for p in &mut img.data { for c in 0..3 { p[c] *= k; @@ -961,9 +1788,288 @@ mod tests { } } } + input.frames = Frames::Memory(frames); let plain = fill_sequence(&input, &FillOpts::default(), &mut |_, _| true).expect("fill"); let lit = fill_sequence(&input, &FillOpts { lighting: 1.0, ..Default::default() }, &mut |_, _| true).expect("fill"); - let score = |o: &[Image]| (0..6).map(|t| psnr(&o[t], >s[t], Some(&input.holes[t]))).sum::(); + let score = |o: &[Image]| (0..6).map(|t| psnr(&o[t], >s[t], Some(&input.holes[t].to_vec()))).sum::(); assert!(score(&lit) > score(&plain), "lit {} vs plain {}", score(&lit), score(&plain)); } + + /// `SpillHandle::sample` reads only the 2x2 support; it must still agree with sampling the + /// decoded frame, including the edges and coordinates outside the image (#2570 review). + #[test] + fn spilled_samples_match_the_decoded_frame() { + let (w, h, n) = (7u32, 5u32, 3usize); + for bpc in [8u8, 32] { + let mut frames = Vec::new(); + for k in 0..n { + let mut img = Image::new(w, h); + for (i, p) in img.data.iter_mut().enumerate() { + *p = [(i % 7) as f32 / 7.0, (k * 3 + i % 5) as f32 / 5.0, 0.25, 1.0]; + } + frames.push(img); + } + let spill = SpillHandle::create(w as usize, h as usize, n, bpc).expect("spill"); + for (k, img) in frames.iter().enumerate() { + spill.write_frame(k, img).expect("write"); + } + let spilled = Frames::Spilled(spill.clone()); + assert!(!spilled.has_error()); + for k in 0..n { + let decoded = spill.get(k); + for &(x, y) in &[(0.0, 0.0), (0.5, 0.5), (3.4, 2.6), (6.5, 4.5), (7.9, 5.9), (-1.0, -1.0), (2.25, 3.75)] { + let a = spilled.sample(k, x, y); + let b = decoded.sample_bilinear_clamped(x, y); + for c in 0..4 { + assert!((a[c] - b[c]).abs() <= 1e-6, "bpc {bpc} frame {k} at ({x}, {y}) channel {c}: {} vs {}", a[c], b[c]); + } + } + } + assert!(!spilled.has_error(), "sampling a valid spill records no error"); + } + } + + /// The input's error slot is shared with the membrane and propagation spills, so one probe + /// reports any scratch failure (#2570 review). + #[test] + fn a_secondary_spill_reports_through_the_input_error_slot() { + let input = SpillHandle::create(4, 4, 2, 32).expect("input spill"); + let prop = SpillHandle::create_in_with_error(None, 4, 4, 2, 32, Some(input.error_cell())).expect("prop spill"); + prop.record_error("spill: No space left on device".into()); + assert!(input.has_error()); + assert_eq!(input.take_error().as_deref(), Some("spill: No space left on device")); + assert!(!prop.has_error(), "take clears the shared slot"); + } + + /// A spill whose scratch folder cannot be created is an error, not a silent fallback. + #[test] + fn a_spill_that_cannot_create_its_folder_is_an_error() { + let dir = tempfile::tempdir().expect("temp"); + let file = dir.path().join("not-a-folder"); + std::fs::write(&file, b"x").expect("write"); + assert!(SpillHandle::create_in(Some(&file), 4, 4, 1, 32).is_err()); + } + + /// The scratch file has no name in its folder, so a fill that is killed partway through + /// leaves nothing behind, and every read and write still reaches the frames (#2570 review). + #[test] + fn a_spill_leaves_no_file_in_its_folder() { + let dir = tempfile::tempdir().expect("temp"); + let spill = SpillHandle::create_in(Some(dir.path()), 4, 3, 2, 32).expect("spill"); + let mut img = Image::new(4, 3); + for (i, p) in img.data.iter_mut().enumerate() { + *p = [i as f32 / 12.0, 0.5, 0.25, 1.0]; + } + spill.write_frame(1, &img).expect("write"); + assert_eq!(spill.get(1).data, img.data); + assert!(!spill.has_error()); + assert_eq!(spill.dir(), Some(dir.path())); + assert_eq!(Frames::Spilled(spill.clone()).scratch_dir().as_deref(), Some(dir.path())); + // Elsewhere the file is unlinked as soon as it is made; Windows keeps a delete-on-close + // file listed until its last handle closes. + #[cfg(not(windows))] + assert_eq!(std::fs::read_dir(dir.path()).expect("list").count(), 0, "the open spill has a name in the folder"); + drop(spill); + assert_eq!(std::fs::read_dir(dir.path()).expect("list").count(), 0, "scratch left in the folder"); + } + + /// The same frames spilled to 32 bpc scratch. + fn spill_frames(frames: &Frames) -> SpillHandle { + let (w, h) = frames.size().expect("size"); + let spill = SpillHandle::create(w, h, frames.len(), 32).expect("spill"); + for k in 0..frames.len() { + spill.write_frame(k, &frames.get(k)).expect("write"); + } + spill + } + + /// Every channel of every pixel, as bits. + fn bits(img: &Image) -> Vec { + img.data.iter().flatten().map(|v| v.to_bits()).collect() + } + + /// A spilled range fills bit-identically to the same frames in RAM, streamed or returned: the + /// spill keeps 32-bit floats and samples the same 2x2 support (#2570, "no quality loss"). + #[test] + fn a_spilled_range_fills_exactly_like_one_in_memory() { + let (input, _) = sequence(6, 1.0); + for method in [FillMethod::Object, FillMethod::Surface, FillMethod::EdgeBlend] { + let opts = FillOpts { method, lighting: 0.5, ..Default::default() }; + let memory = fill_sequence(&input, &opts, &mut |_, _| true).expect("memory fill"); + let spilled = FillInput { frames: Frames::Spilled(spill_frames(&input.frames)), holes: input.holes.clone(), references: vec![] }; + let returned = fill_sequence(&spilled, &opts, &mut |_, _| true).expect("spilled fill"); + let mut streamed = Vec::new(); + let mut sink = |_: usize, img: &Image| -> Result<(), String> { + streamed.push(img.clone()); + Ok(()) + }; + let rest = fill_sequence_with(spilled, &opts, &CpuFill, &mut |_, _| true, Some(&mut sink)); + assert!(rest.is_some_and(|v| v.is_empty()), "{method:?}: the sink took every frame"); + assert_eq!((memory.len(), returned.len(), streamed.len()), (6, 6, 6), "{method:?}"); + for t in 0..6 { + assert!(bits(&returned[t]) == bits(&memory[t]), "{method:?} frame {t}: spilled fill differs from RAM"); + assert!(bits(&streamed[t]) == bits(&memory[t]), "{method:?} frame {t}: streamed fill differs from RAM"); + } + } + } + + /// The sink sees every frame once and strictly in order, whichever stage finishes it: the + /// complete frames before the first synthesised one, the synthesised run, and Edge Blend. + #[test] + fn the_sink_sees_frames_in_order() { + let (input, gts) = sequence(8, 1.0); + let mut frames: Vec = (0..8).map(|k| input.frames.get(k)).collect(); + let mut holes = input.holes.clone(); + // The first two frames are clean, so they stream ahead of the first synthesised frame. + for k in 0..2 { + frames[k] = gts[k].clone(); + holes[k] = HoleMask::zeros(frames[k].data.len()); + } + let input = FillInput { frames: Frames::Spilled(spill_frames(&Frames::Memory(frames))), holes, references: vec![] }; + for method in [FillMethod::Object, FillMethod::Surface, FillMethod::EdgeBlend] { + let mut seen = Vec::new(); + let mut sink = |t: usize, _: &Image| -> Result<(), String> { + seen.push(t); + Ok(()) + }; + let out = fill_sequence_with(input.clone(), &FillOpts { method, ..Default::default() }, &CpuFill, &mut |_, _| true, Some(&mut sink)); + assert!(out.is_some(), "{method:?}"); + assert_eq!(seen, (0..8).collect::>(), "{method:?}"); + } + } + + /// A spill that cannot be read fails the fill with the disk error in the slot the caller + /// probes, and the black fallback frame never reaches the sink (#2570 review). + #[test] + fn a_spill_read_failure_is_an_error_and_never_streamed() { + let (input, _) = sequence(4, 1.0); + let spill = spill_frames(&input.frames); + // Truncate the scratch under the fill: every read comes back short. + spill.inner.file.set_len(0).expect("truncate"); + for method in [FillMethod::Object, FillMethod::Surface, FillMethod::EdgeBlend] { + let mut seen = Vec::new(); + let mut sink = |t: usize, _: &Image| -> Result<(), String> { + seen.push(t); + Ok(()) + }; + let failed = FillInput { frames: Frames::Spilled(spill.clone()), holes: input.holes.clone(), references: vec![] }; + let out = fill_sequence_with(failed, &FillOpts { method, ..Default::default() }, &CpuFill, &mut |_, _| true, Some(&mut sink)); + assert!(out.is_none(), "{method:?}"); + assert!(seen.is_empty(), "{method:?}: streamed frames {seen:?} from an unreadable spill"); + let e = spill.take_error().expect("the read failure is recorded"); + assert!(e.starts_with("spill:"), "{method:?}: {e}"); + } + } + + /// A scratch failure while the output streams stops the fill before the next frame reaches + /// the sink, and leaves the failure for the caller to report. + #[test] + fn a_spill_failure_mid_stream_stops_before_the_next_frame() { + let (input, _) = sequence(6, 1.0); + let spill = spill_frames(&input.frames); + let cell = spill.error_cell(); + let mut seen = Vec::new(); + let mut sink = |t: usize, _: &Image| -> Result<(), String> { + seen.push(t); + if t == 2 { + *cell.lock().unwrap() = Some("spill: injected".into()); + } + Ok(()) + }; + let streamed = FillInput { frames: Frames::Spilled(spill.clone()), holes: input.holes.clone(), references: vec![] }; + let out = fill_sequence_with(streamed, &FillOpts::default(), &CpuFill, &mut |_, _| true, Some(&mut sink)); + assert!(out.is_none()); + assert_eq!(seen, vec![0, 1, 2]); + assert_eq!(spill.take_error().as_deref(), Some("spill: injected")); + } + + /// Once a propagated frame fails to spill, the other propagation workers stop instead of + /// tracing the rest of a range whose fill is already lost (#2570 review). + #[test] + fn propagation_stops_after_a_spill_failure() { + /// Fails the spill from inside the propagation stage (Lighting Correction's membrane). + struct FailInPropagation { + cell: std::sync::Arc>>, + calls: std::sync::atomic::AtomicUsize, + } + impl FillBackend for FailInPropagation { + fn membrane_known(&self, data: &mut [[f32; 4]], known: &[bool], w: usize, h: usize) { + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + *self.cell.lock().unwrap() = Some("spill: injected".into()); + membrane_core(data, known, w, h); + } + } + let (input, _) = sequence(6, 1.0); + let spill = spill_frames(&input.frames); + let backend = FailInPropagation { cell: spill.error_cell(), calls: std::sync::atomic::AtomicUsize::new(0) }; + let input = FillInput { frames: Frames::Spilled(spill.clone()), holes: input.holes, references: vec![] }; + let opts = FillOpts { lighting: 1.0, ..Default::default() }; + // One worker, so the frames run one after another and the count is exact. + let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap(); + let out = pool.install(|| fill_sequence_with(input, &opts, &backend, &mut |_, _| true, None)); + assert!(out.is_none()); + assert_eq!(backend.calls.load(std::sync::atomic::Ordering::SeqCst), 1, "propagation kept going after the failure"); + assert_eq!(spill.take_error().as_deref(), Some("spill: injected")); + } + + /// Peak RSS of one synthetic fill, quoted in the PR. Ignored so CI does not run it. Run it + /// under `/usr/bin/time -v` and read `VmHWM` (`Maximum resident set size`): + /// + /// ```text + /// cargo test -p effectcraft-raster --lib measure_peak_rss --no-run + /// target/debug/deps/effectcraft_raster-* inpaint::tests::measure_peak_rss_of_a_fill \ + /// --ignored --exact --nocapture --test-threads=1 + /// ``` + /// + /// `RAYON_NUM_THREADS`, `MEASURE_LIGHTING=1` and `MEASURE_FRAMES` select the configuration. + /// Measured on 18 workers (2026-11-04): 90 frames of 640×360 peak at 340–470 MB across runs + /// (35 MB with one worker) and 600 frames at 582 MB, i.e. ~7 frames of scratch a worker, so + /// the guard budgets 8 (9 with Lighting Correction) (#2570). + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "memory measurement; run explicitly"] + fn measure_peak_rss_of_a_fill() { + let n: usize = std::env::var("MEASURE_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(90); + let (w, h) = (640u32, 360u32); + let spill = SpillHandle::create_in(None, w as usize, h as usize, n, 32).expect("spill"); + let hole = rect_hole(w, h, 240, 120, 160); + let mut holes = Vec::with_capacity(n); + for k in 0..n { + let img = background(w, h, 2.0 * k as f32); + spill.write_frame(k, &img).expect("write"); + holes.push(HoleMask::from_vec(&hole)); + } + let input = FillInput { frames: Frames::Spilled(spill), holes, references: vec![] }; + // MEASURE_LIGHTING=1 exercises the propagation ring too (one process per reading: VmHWM + // never goes down). + let lighting = std::env::var("MEASURE_LIGHTING").is_ok_and(|v| v == "1"); + let opts = FillOpts { method: FillMethod::Surface, lighting: if lighting { 1.0 } else { 0.0 }, ..Default::default() }; + let before = peak_rss_kb(); + let started = std::time::Instant::now(); + let mut sink = |_: usize, _: &Image| -> Result<(), String> { Ok(()) }; + let out = fill_sequence_with(input, &opts, &CpuFill, &mut |_, _| true, Some(&mut sink)); + eprintln!( + "measure_peak_rss: {n} frames of {w}x{h}, surface, lighting={}, {:.2}s, peak RSS {} KB -> {} KB", + if lighting { "on" } else { "off" }, + started.elapsed().as_secs_f64(), + before.unwrap_or(0), + peak_rss_kb().unwrap_or(0) + ); + assert!(out.is_some_and(|v| v.is_empty()), "the sink consumed every frame"); + } + + /// Peak resident set size of this process (`VmHWM`), in kilobytes. + #[cfg(target_os = "linux")] + fn peak_rss_kb() -> Option { + std::fs::read_to_string("/proc/self/status").ok()?.lines().find_map(|l| { + let v = l.strip_prefix("VmHWM:")?; + v.split_whitespace().next()?.parse().ok() + }) + } + + /// Peak resident set size is only measured on Linux. + #[cfg(not(target_os = "linux"))] + fn peak_rss_kb() -> Option { + None + } } diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index fd2fd183b..e18a24c63 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -31,15 +31,36 @@ pub const MAX_PADDED_SIDE: u32 = 30_000; /// Clamp (colour ≤ alpha ≤ 1, NaN → 0) and round half up to `levels` steps (`inv` = 1 / levels): /// one pixel of an 8/16 bpc buffer. Values are non-negative after the clamp, so the integer /// conversion rounds like `round()` and vectorises. -#[allow(clippy::manual_clamp)] // max/min map NaN to 0; clamp would keep NaN #[inline(always)] pub fn quantize_px(p: &mut Px, levels: f32, inv: f32) { - let a = round_half_up(p[3].max(0.0).min(1.0) * levels) * inv; + *p = quantize_levels(*p, levels, inv).map(|n| n * inv); +} + +/// [`quantize_px`]'s steps: the whole number of `levels` each channel rounds to (0..=levels). +#[allow(clippy::manual_clamp)] // max/min map NaN to 0; clamp would keep NaN +#[inline(always)] +pub fn quantize_levels(p: Px, levels: f32, inv: f32) -> [f32; 4] { + let na = round_half_up(p[3].max(0.0).min(1.0) * levels); + let a = na * inv; let hi = [a, a, a, a]; + let mut n = [0.0, 0.0, 0.0, na]; for c in 0..3 { - p[c] = round_half_up(p[c].max(0.0).min(hi[c]) * levels) * inv; + n[c] = round_half_up(p[c].max(0.0).min(hi[c]) * levels); } - p[3] = a; + n +} + +/// [`quantize_px`] at 8 bpc, as bytes: [`expand_u8`] gives back exactly the pixel +/// [`quantize_px`] writes, so an 8 bpc buffer can be kept in a quarter of the memory. +#[inline(always)] +pub fn quantize_px_u8(p: Px) -> [u8; 4] { + quantize_levels(p, 255.0, 1.0 / 255.0).map(|n| n as u8) +} + +/// The 8 bpc pixel of [`quantize_px_u8`]'s bytes. +#[inline(always)] +pub fn expand_u8(n: [u8; 4]) -> Px { + n.map(|v| f32::from(v) * (1.0 / 255.0)) } /// `v` (0..=65 535) rounded half up. The same either way; the fastest on each target: x86-64's @@ -403,6 +424,23 @@ impl Mask { mod tests { use super::*; + /// Pixels kept as `quantize_px_u8` bytes expand to the 8 bpc pixel `quantize_px` writes, bit + /// for bit: every level, exact halves, out-of-range, negative, NaN and premultiplied colour + /// brighter than its alpha. + #[test] + fn u8_levels_expand_to_the_quantised_pixel() { + let mut values: Vec = (0..=255 * 4).map(|i| i as f32 / (255.0 * 4.0)).collect(); + values.extend([-0.0, -1.0, 1.0, 1.5, f32::NAN, f32::INFINITY, 0.5 / 255.0, 254.5 / 255.0]); + for &a in &[1.0, 0.5, 0.2, 0.0, 2.0, f32::NAN] { + for &v in &values { + let p = [v, 1.0 - v, v * 0.5, a]; + let mut want = p; + quantize_px(&mut want, 255.0, 1.0 / 255.0); + assert_eq!(expand_u8(quantize_px_u8(p)).map(f32::to_bits), want.map(f32::to_bits), "{p:?}"); + } + } + } + #[test] fn dither_keeps_exact_codes_and_averages_the_rest() { // A value on an 8-bit code is that code at every position. diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index efbd1fc19..cd67e846a 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -26,3 +26,6 @@ rayon = { workspace = true } web-time = { workspace = true } serde = { workspace = true } log = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } diff --git a/crates/render/src/accel.rs b/crates/render/src/accel.rs index e6bbd2113..21f609574 100644 --- a/crates/render/src/accel.rs +++ b/crates/render/src/accel.rs @@ -21,16 +21,35 @@ pub enum Backend { } impl Backend { + /// The backend `s` names, whatever case it is written in: the project's own values (`cpu`, + /// `gpu`, `auto`), the labels Project Settings ▸ Video Rendering and Effects draws + /// (`GPU Acceleration`, `Software Rendering`) and the older After Effects wording. pub fn parse(s: &str) -> Option { match s.to_ascii_lowercase().as_str() { - "cpu" | "software" | "mercury software only" => Some(Backend::Cpu), - "gpu" | "mercury gpu acceleration" => Some(Backend::Gpu), + "cpu" | "software" | "mercury software only" | "software rendering" => Some(Backend::Cpu), + "gpu" | "mercury gpu acceleration" | "gpu acceleration" => Some(Backend::Gpu), "auto" => Some(Backend::Auto), _ => None, } } } +/// An accelerator's device memory, to size how many frames an export renders on it at once +/// (see [`Accelerator::frame_memory`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FrameMemory { + /// Bytes the accelerator may use (a conservative share of the device, not its free memory). + pub budget: u64, + /// The most its allocator has held while frames rendered (one frame's working memory + /// included). + pub peak: u64, + /// Bytes of that peak one frame needed (what it released again), or the whole budget once + /// frames have had to wait for memory. + pub frame: u64, + /// Bytes long-lived caches (uploaded layers) may still grow by. + pub reserve: u64, +} + /// One effect of a GPU effect chain (see [`Accelerator::effects`]). pub struct FxStep<'x> { pub spec: &'static effectcraft_effects::EffectSpec, @@ -76,11 +95,27 @@ pub trait Accelerator: Send + Sync { fn particles(&self) -> Option<&dyn effectcraft_effects::psim::ParticleSim> { None } + /// A hardware backend for Content-Aware Fill's stages (the GPU compositor's kernels), with + /// the CPU fill's semantics. `None` = the fill runs on the CPU. + /// + /// The fill's input frames are read back to the CPU before it runs (analyses render on the + /// CPU by design, see `effectcraft_engine::background::offload::job_accel`), so a backend + /// here is about the fill's own work — PatchMatch and the flow's block matching today, one + /// stage at a time as each pays (`effectcraft_gpu::inpaint`) — not about compositing. + fn inpaint(&self) -> Option<&dyn effectcraft_raster::inpaint::FillBackend> { + None + } /// Timing history [`Backend::Auto`] uses to send each comp's top-level frames to the /// faster compositor. `None` = Auto always tries the accelerator first. fn auto_pick(&self) -> Option<&AutoPick> { None } + /// The device memory budget and use, after at least one frame rendered: what an export + /// sizes its frames in flight by. `None` where it isn't known (no allocator report, no + /// budget): the export then renders one frame at a time. + fn frame_memory(&self) -> Option { + None + } /// Whether the accelerator can still render frames. `false` once it has stopped for good /// (its device was lost or retired): every frame it is asked for falls back to the CPU, so /// callers that limit frames in flight for it can stop doing so. @@ -96,6 +131,19 @@ pub trait Accelerator: Send + Sync { /// results, `pass_begin` clears the miss. Synchronous accelerators never miss. fn frame_begin(&self) {} fn pass_begin(&self) {} + /// A rendered comp frame is done (the GPU pool ages sizes no frame asks for, and evicts + /// only those once full). The multi-frame render paths call it once per comp frame: + /// [`crate::passes::comp_frame`] (exports; a field-rendered output frame is two), the + /// export's 4:2:0 frames ([`Accelerator::comp_frame_yuv420`]), remote frames and the + /// preview workers. One-off renders (`Session::render`, single-frame export, + /// thumbnails) don't, so they don't advance the pool's clock. Without it the pool never + /// finds a stale size and keeps its first sizes, dropping newcomers. + fn frame_end(&self) {} + /// A render of many frames (an export) is done: drop what is kept only to speed up the + /// next frame (pooled working textures). Exports call it, even when they fail, panic or + /// are dropped; other multi-frame paths (preview, remote frames) don't, so there the pool + /// keeps up to its budget until the next export ends. + fn render_end(&self) {} fn pass_missed(&self) -> bool { false } @@ -174,6 +222,13 @@ impl<'a> Renderer<'a> { self.pipe } + /// The colour pipeline of the top-level output steps: the project's, with no HDR step under + /// [`crate::RenderOpts::skip_hdr_step`] (the consumer decodes with + /// [`color::Pipe::output_linear`] or applies the step itself). + pub fn output_pipe(&self) -> color::Pipe { + if self.opts.skip_hdr_step { self.pipe.without_hdr_step() } else { self.pipe } + } + /// Nesting depth (0 = the top-level comp). pub fn depth(&self) -> usize { self.depth @@ -194,7 +249,7 @@ impl<'a> Renderer<'a> { LayerSource::Footage { item } => { let item = ctx.media_item(layer, *item); let ItemKind::Footage(f) = &self.project.item(item)?.kind else { return None }; - let a = self.footage.aux(item, f, ctx.source_time(layer))?; + let a = self.read(|| self.footage.aux(item, f, ctx.source_time(layer)))?; // Aux pixels per layer pixel (the layer is the footage at its nominal size). The // planes are only copied when that changes the scale. let scale = a.width as f64 / f.width as f64; @@ -319,20 +374,19 @@ impl<'a> Renderer<'a> { pub fn adjustment_footprint(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { // Cached, so an accelerator sees the same buffer (and uploads it once) every frame. let key = self.cache.and_then(|_| cache::footprint_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer))); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { + let key = self.mask_gate_key(ctx, layer, self.clipped_key(ctx, layer, key)); + if let Some((b, _)) = self.cached(key) { return Some(b); } - let mut foot = self.source(ctx, layer)?; - let _ = masks::apply(ctx, layer, &mut foot, self.mask_blur(ctx, layer)); - let foot = Arc::new(foot); + let (foot, files) = self.recorded(key, |r| { + // (what the masks' expressions read, at shutter times too, goes to the buffer's files) + let ctx = &r.with_reads(ctx); + let mut foot = r.source(ctx, layer)?; + let _ = masks::apply(ctx, layer, &mut foot, r.mask_blur(ctx, layer)); + Some(foot) + }); // The buffer the cache keeps (another worker's, if it kept one first). - let foot = match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, foot), - _ => foot, - }; - Some(foot) + Some(self.keep(key, Arc::new(foot?), &files).0) } /// Draw one 2D layer into `canvas` on the CPU (any kind: adjustment, wireframe, styled…). diff --git a/crates/render/src/audio.rs b/crates/render/src/audio.rs index e2861340c..00342847d 100644 --- a/crates/render/src/audio.rs +++ b/crates/render/src/audio.rs @@ -155,7 +155,9 @@ impl MixEnv<'_> { return out; } let m = b - a; - let speed = 100.0 / l.stretch; + // Within ±1 % to ±9900 % (#3247): a stretch of 1e-300 % set in memory read about + // usize::MAX source samples for one block. + let speed = 100.0 / l.effective_stretch(); let src_n = ((m as f64 * speed).ceil() as usize).max(1); let lt = l.layer_time(sample_tick(i0 + a as i64, rate)); let buf = match &l.source { @@ -291,7 +293,8 @@ fn mix_into(sources: &AudioSources<'_>, comp_id: ItemId, start: Tick, out: &mut let any_solo = comp.layers.iter().any(|l| l.switches.solo && audible(project, l)); let s0 = start.to_units_floor(rate as i64); for l in &comp.layers { - if !audible(project, l) || (any_solo && !l.switches.solo) || l.stretch <= 0.0 { + // The stretch the layer's time uses (#3247): 0 and NaN play at 100 %, as `layer_time`. + if !audible(project, l) || (any_solo && !l.switches.solo) || l.effective_stretch() <= 0.0 { continue; } // Sample range of the block that falls inside the layer's [in, out). diff --git a/crates/render/src/auto.rs b/crates/render/src/auto.rs index 39b3b02e6..ce714c1f0 100644 --- a/crates/render/src/auto.rs +++ b/crates/render/src/auto.rs @@ -10,6 +10,13 @@ //! (its first frame, with layer cache misses and texture uploads, is not counted; the fastest of //! the next ones starts the average), and the slower side is re-measured every //! [`AutoPick::REPROBE`] frames so the choice follows the comp as it changes. +//! +//! Frames render several at a time (a preview's lanes), and a frame is only measured once it +//! is done: so at most one GPU warm-up frame, or re-probe frame on either side, runs at once, +//! and the frames asked for meanwhile go to the other side. And a frame's time counts per +//! frame running on its side at once: twelve CPU frames that each take 200 ms side by side cost +//! about 17 ms a frame, against a GPU frame of 175 ms on its own. Otherwise every lane of a starting preview took a +//! warm-up frame on a GPU that turned out 2–4× slower (an integrated GPU), all at once. use std::collections::HashMap; use std::sync::Mutex; @@ -51,7 +58,36 @@ pub struct AutoStats { /// accelerator, see [`Accelerator::auto_pick`](crate::Accelerator::auto_pick)). #[derive(Default)] pub struct AutoPick { - stats: Mutex>, + stats: Mutex>, +} + +/// One key's history, when its running warm-up or re-probe frame started on each side, and +/// how many of its frames are running on each side (`[CPU, GPU]`). +#[derive(Default)] +struct Entry { + stats: AutoStats, + measuring: [Option; 2], + // Lowered by `record`, `declined` and `abandoned`: every frame asked for ends in one (an + // [`AutoTicket`] makes sure of it). + running: [u32; 2], +} + +impl Entry { + /// A warm-up or re-probe frame is running on `gpu`'s side. It counts as done once + /// [`AutoPick::MEASURING_FOR`] has passed (a frame that failed without reporting back). + fn measuring(&self, gpu: bool) -> bool { + self.measuring[usize::from(gpu)].is_some_and(|t| t.elapsed() < AutoPick::MEASURING_FOR) + } + + /// Render the next warm-up or re-probe frame on `gpu`'s side, unless one is running there: + /// then the other side's (`!gpu`). + fn measure(&mut self, gpu: bool) -> bool { + if self.measuring(gpu) { + return !gpu; + } + self.measuring[usize::from(gpu)] = Some(web_time::Instant::now()); + gpu + } } impl AutoPick { @@ -66,19 +102,43 @@ impl AutoPick { pub const MARGIN: f64 = 0.85; /// Keys remembered before the history is reset. const MAX_KEYS: usize = 1024; + /// Frames counted as running on one side at most (see `Entry::running`). + const MAX_RUNNING: u32 = 256; + /// A warm-up or re-probe frame not reported back by then no longer holds its side. + const MEASURING_FOR: std::time::Duration = std::time::Duration::from_secs(10); - /// Render the frame for `key` on the GPU? + /// [`AutoPick::choose`] for a frame that ends where it started: the ticket reports back, and + /// a ticket dropped without a time (an error, a retry elsewhere, a panic, a cancelled future) + /// ends the frame with [`AutoPick::abandoned`]. + pub fn ticket(&self, key: AutoKey) -> AutoTicket<'_> { + AutoTicket { pick: self, key, gpu: self.choose(key), open: true } + } + + /// Render the frame for `key` on the GPU? Every frame asked for reports back with + /// [`AutoPick::record`] (or [`AutoPick::declined`]), or ends with [`AutoPick::abandoned`] + /// ([`AutoPick::ticket`] does that on its own). pub fn choose(&self, key: AutoKey) -> bool { let Ok(mut m) = self.stats.lock() else { return true }; if m.len() > Self::MAX_KEYS && !m.contains_key(&key) { m.clear(); } - let s = m.entry(key).or_default(); - // Warm up both sides, alternating, GPU first. + let e = m.entry(key).or_default(); + let gpu = Self::pick(e); + let n = &mut e.running[usize::from(gpu)]; + *n = n.saturating_add(1).min(Self::MAX_RUNNING); + gpu + } + + fn pick(e: &mut Entry) -> bool { + let s = e.stats; + // Warm up both sides, alternating, CPU first: the first frames asked for are the + // ones on screen, and the CPU is the side that is never slow to start (no pipelines + // to build; an integrated GPU took 2 s for the frame at the playhead). let gpu_warm = s.declined || s.gpu_frames >= Self::WARMUP; - if !gpu_warm && s.gpu_frames <= s.cpu_frames { - return true; + if !gpu_warm && s.gpu_frames < s.cpu_frames { + return e.measure(true); } + // (CPU frames already render side by side, on lanes of their own.) if s.cpu_frames < Self::WARMUP { return false; } @@ -86,12 +146,12 @@ impl AutoPick { (Some(g), Some(c)) => c >= g * Self::MARGIN, (g, _) => g.is_some(), }; - // Periodically re-measure the slower side. - if s.since_probe >= Self::REPROBE { - s.since_probe = 0; - return !gpu_faster; + // Periodically re-measure the slower side (one frame at a time). + if s.since_probe >= Self::REPROBE && !e.measuring(!gpu_faster) { + e.stats.since_probe = 0; + return e.measure(!gpu_faster); } - s.since_probe += 1; + e.stats.since_probe = s.since_probe.saturating_add(1); gpu_faster } @@ -103,7 +163,13 @@ impl AutoPick { /// period). pub fn record(&self, key: AutoKey, gpu: bool, ms: f64) { let Ok(mut m) = self.stats.lock() else { return }; - let s = m.entry(key).or_default(); + let e = m.entry(key).or_default(); + e.measuring[usize::from(gpu)] = None; + // Per frame running on this side alongside it (itself included). + let n = &mut e.running[usize::from(gpu)]; + let ms = ms / f64::from((*n).max(1)); + *n = n.saturating_sub(1); + let s = &mut e.stats; let (avg, frames) = if gpu { (&mut s.gpu_ms, &mut s.gpu_frames) } else { (&mut s.cpu_ms, &mut s.cpu_frames) }; *frames = frames.saturating_add(1); if gpu { @@ -123,16 +189,36 @@ impl AutoPick { /// The GPU did not handle a frame for `key` (it rendered on the CPU instead). pub fn declined(&self, key: AutoKey) { if let Ok(mut m) = self.stats.lock() { - let s = m.entry(key).or_default(); + let e = m.entry(key).or_default(); + e.measuring[1] = None; + // The frame renders on the CPU instead (and reports back from there). + e.running[1] = e.running[1].saturating_sub(1); + e.running[0] = e.running[0].saturating_add(1).min(Self::MAX_RUNNING); + let s = &mut e.stats; s.declined = true; s.gpu_ms = None; s.since_probe = 0; } } + /// A frame for `key` asked of `gpu`'s side ends without a time (it failed, or was replaced + /// before it finished). Without this its side stays counted as running, and every later + /// frame there is timed as one of several running side by side: that side looks cheaper. + // ponytail: clears the side's warm-up/probe mark even when another frame holds it; that + // only lets the next probe start early. + pub fn abandoned(&self, key: AutoKey, gpu: bool) { + if let Ok(mut m) = self.stats.lock() + && let Some(e) = m.get_mut(&key) + { + e.measuring[usize::from(gpu)] = None; + let n = &mut e.running[usize::from(gpu)]; + *n = n.saturating_sub(1); + } + } + /// The history of `key`. pub fn stats(&self, key: AutoKey) -> Option { - self.stats.lock().ok()?.get(&key).copied() + self.stats.lock().ok()?.get(&key).map(|e| e.stats) } /// Forget all history (settings that change both paths' costs). @@ -142,3 +228,42 @@ impl AutoPick { } } } + +/// One frame [`AutoPick`] chose a side for ([`AutoPick::ticket`]): it reports the frame's time +/// once, and ends the frame unmeasured when dropped without one. +#[must_use = "a ticket dropped at once ends its frame unmeasured"] +pub struct AutoTicket<'a> { + pick: &'a AutoPick, + key: AutoKey, + gpu: bool, + open: bool, +} + +impl AutoTicket<'_> { + /// The frame renders on the GPU. + pub fn gpu(&self) -> bool { + self.gpu + } + + /// The frame took `ms` on its side. + pub fn record(mut self, ms: f64) { + self.open = false; + self.pick.record(self.key, self.gpu, ms); + } + + /// The GPU did not take the frame: it renders on the CPU, and the ticket reports from there. + pub fn declined(&mut self) { + if self.gpu { + self.pick.declined(self.key); + self.gpu = false; + } + } +} + +impl Drop for AutoTicket<'_> { + fn drop(&mut self) { + if self.open { + self.pick.abandoned(self.key, self.gpu); + } + } +} diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index cf1a84e82..4f72e79fa 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -22,27 +22,36 @@ use std::hash::{Hash, Hasher}; use std::sync::{Arc, Mutex}; use effectcraft_effects::Buf; +use effectcraft_keyframe::Value; use effectcraft_project::{FootageKind, ItemKind, Layer, LayerSource, Node, PropGroup}; +use crate::disk_cache::{EntryFiles, SharedVirtualFileId, VirtualFileId, layer_disk_key}; use crate::eval::EvalCtx; +use crate::reads::ReadFiles; mod dependencies; /// Thread-safe, memory-budgeted cache of processed layer buffers, optionally backed by the /// persistent [`DiskCache`](crate::disk_cache::DiskCache): a memory miss reads the disk, and -/// buffers that were slow to render are written there (keys salted per project, see -/// [`LayerCache::set_disk`]). +/// buffers that were slow to render are written there with the source files they were made of +/// (keys: [`crate::disk_cache::layer_disk_key`]; an entry is used only while its files are +/// unchanged, #3184). pub struct LayerCache { inner: Mutex, - disk: Mutex, u64)>>, + disk: Mutex>>, /// Another persistent store when there is no disk cache (the browser's, [`PrefetchStore`]). - store: Mutex, u64)>>, + store: Mutex>>, + /// Size and content hash of files served from memory (the browser file table), to store + /// and check the source files of persistent entries. + virtual_id: Mutex>, /// While set, inserts are dropped (see [`LayerCache::set_gate`]). gate: Mutex>>, } struct Entry { buf: Arc, + /// The source files the buffer was made of (see [`crate::reads`]). + files: Arc, bytes: usize, last_use: u64, } @@ -54,7 +63,9 @@ struct Inner { clock: u64, hits: u64, misses: u64, - /// When each recent miss happened (to time the render that follows it). + /// When each recent miss happened, to time the render that follows it (the drop generation + /// a render's reads started at travels with its files instead, [`ReadFiles::since`]: two + /// renders of a key may overlap). missed_at: HashMap, } @@ -80,6 +91,7 @@ impl LayerCache { inner: Mutex::new(Inner { map: HashMap::new(), bytes: 0, budget, clock: 0, hits: 0, misses: 0, missed_at: HashMap::new() }), disk: Mutex::new(None), store: Mutex::new(None), + virtual_id: Mutex::new(None), gate: Mutex::new(None), } } @@ -98,77 +110,75 @@ impl LayerCache { self.gate.lock().ok().and_then(|g| g.as_ref().map(|g| g.load(std::sync::atomic::Ordering::Relaxed))).unwrap_or(false) } - /// Attach (or detach) the disk cache. `salt` separates projects and footage versions (see - /// `footage_salt`); keys on disk are `(salt, key)`. - pub fn set_disk(&self, disk: Option<(Arc, u64)>) { + /// Attach (or detach) the disk cache. It is used at once: its entries check their own + /// source files when read, so nothing has to be looked at first. + pub fn set_disk(&self, disk: Option>) { if let Ok(mut d) = self.disk.lock() { *d = disk; } } - /// Change the disk salt (after footage changed) keeping the attached disk cache. - pub fn set_disk_salt(&self, salt: u64) { - if let Ok(mut d) = self.disk.lock() - && let Some((_, s)) = d.as_mut() - { - *s = salt; - } - } - + /// The attached disk cache, if any. pub fn disk(&self) -> Option> { - self.disk.lock().ok()?.as_ref().map(|d| d.0.clone()) + self.disk.lock().ok()?.clone() } /// Attach (or detach) a [`LayerStore`] used when no disk cache is attached (the browser's - /// Origin Private File System through a [`PrefetchStore`]); `salt` as in - /// [`LayerCache::set_disk`]. - pub fn set_store(&self, store: Option<(Arc, u64)>) { + /// Origin Private File System through a [`PrefetchStore`]). + pub fn set_store(&self, store: Option>) { if let Ok(mut s) = self.store.lock() { *s = store; } } - /// Change the store's salt (a new project or footage), keeping the store. - pub fn set_store_salt(&self, salt: u64) { - if let Ok(mut d) = self.store.lock() - && let Some((_, s)) = d.as_mut() - { - *s = salt; + /// Size and content hash of files served from memory (the browser file table): what a + /// persistent entry keeps for them and checks them against. + pub fn set_virtual_id(&self, id: Option) { + if let Ok(mut v) = self.virtual_id.lock() { + *v = id; } } - fn disk_key(&self, key: u64) -> Option<(Arc, u128)> { - let salted = |salt: u64| ((salt as u128) << 64) | key as u128; - if let Some((dc, salt)) = self.disk.lock().ok()?.as_ref() { - return Some((dc.clone() as Arc, salted(*salt))); - } - let s = self.store.lock().ok()?; - let (st, salt) = s.as_ref()?; - Some((st.clone(), salted(*salt))) + /// The attached virtual-file identity lookup, if any. + fn virtual_id(&self) -> Option { + self.virtual_id.lock().ok()?.clone() } - pub fn get(&self, key: u64) -> Option> { - let mut g = self.inner.lock().ok()?; - g.clock += 1; - let now = g.clock; - match g.map.get_mut(&key) { - Some(e) => { - e.last_use = now; - let b = e.buf.clone(); - g.hits += 1; - Some(b) - } + /// The persistent store behind the memory: the disk cache, else the other store. + fn persistent(&self) -> Option> { + if let Some(dc) = self.disk.lock().ok()?.as_ref() { + return Some(dc.clone() as Arc); + } + self.store.lock().ok()?.clone() + } + + /// The buffer kept under `key` and the source files it was made of (see [`crate::reads`]). + /// A buffer from the disk cache or another store comes with the files its entry lists, after + /// they were found unchanged. A buffer made of a file dropped since its reads began (File ▸ + /// Reload Footage) is never served: it is forgotten, and the lookup is a miss. + pub fn get(&self, key: u64) -> Option<(Arc, Arc)> { + match self.kept(key, true) { + Some(found) => Some(found), None => { + let mut g = self.inner.lock().ok()?; g.misses += 1; - if g.missed_at.len() > 4096 { - g.missed_at.clear(); - } - g.missed_at.insert(key, web_time::Instant::now()); drop(g); - // Disk cache: a hit comes back into memory. - let (dc, dk) = self.disk_key(key)?; - let buf = dc.get_layer(dk)?; - Some(self.insert_mem(key, buf)) + let store = self.persistent(); + // (before the entry is read: what it is made of may be dropped meanwhile) + let since = store.as_ref().map_or(0, |s| s.drop_generation()); + if let Ok(mut g) = self.inner.lock() { + if g.missed_at.len() > 4096 { + g.missed_at.clear(); + } + g.missed_at.insert(key, web_time::Instant::now()); + } + // Disk cache: a hit comes back into memory, read at generation `since`. + let store = store?; + let id = self.virtual_id(); + let (buf, mut files) = store.get_layer(layer_disk_key(key), id.as_deref())?; + files.note_since(since); + let files = Arc::new(files); + Some(self.insert_mem(key, buf, files)) } } } @@ -178,39 +188,118 @@ impl LayerCache { /// together each rendered every layer; sharing the first buffer, the GPU compositor uploads /// and packs it once instead of once per worker, which ran it out of memory). Renders don't /// wait for each other: on the frame workers' shared thread pool a wait can end up under - /// the very work it waits for. - pub fn insert(&self, key: u64, buf: Arc) -> Arc { + /// the very work it waits for. `files`: the source files `buf` was made of (see + /// [`crate::reads`]); a buffer whose files can't all be named stays in memory. The files + /// returned are the ones the returned buffer was made of. + /// + /// The drop generation `buf`'s reads started at comes with `files` ([`ReadFiles::since`], + /// from [`LayerCache::drop_generation`] when the render began): a buffer made of a file + /// dropped since (File ▸ Reload Footage while it rendered) is kept neither on disk nor in + /// memory. A list that doesn't say counts as made before every drop. A buffer made of values + /// its key doesn't capture ([`ReadFiles::is_unkeyed`]) stays in memory. + pub fn insert(&self, key: u64, buf: Arc, files: Arc) -> (Arc, Arc) { if self.gated() { - return buf; + return (buf, files); } - if let Some(kept) = self.inner.lock().ok().and_then(|g| g.map.get(&key).map(|e| e.buf.clone())) { + if let Some(kept) = self.kept(key, false) { return kept; } + let store = self.persistent(); + let since = files.since().unwrap_or(0); + // (before the miss's time is taken: it may time another render of the key) + if store.as_ref().is_some_and(|s| s.dropped_since(&files, since)) { + return (buf, files); + } let started = self.inner.lock().ok().and_then(|mut g| g.missed_at.remove(&key)); - if let Some((dc, dk)) = self.disk_key(key) { - let slow = started.is_some_and(|t| t.elapsed().as_secs_f64() * 1e3 >= dc.min_layer_ms() as f64); - if slow { - dc.put_layer(dk, &buf); + if let Some(store) = store { + let id = self.virtual_id(); + // (an incomplete list, or a file from memory without its identity: not stored) + if let Some(t) = started + && !files.is_unkeyed() + && t.elapsed().as_secs_f64() * 1e3 >= store.min_layer_ms() as f64 + && let Some(entry) = EntryFiles::of(&files, id.as_deref()) + { + store.put_layer(layer_disk_key(key), &buf, &entry, since); } } - self.insert_mem(key, buf) + self.insert_mem(key, buf, files) } - /// See [`LayerCache::insert`]: the buffer kept under `key` (`buf`, unless one was kept first - /// or `buf` is too large to keep). - fn insert_mem(&self, key: u64, buf: Arc) -> Arc { + /// The buffer kept in memory under `key` with its files, if it is not made of a file dropped + /// since its reads began (one that is, is forgotten). `hit`: count it as a hit and as just + /// used. (A render that started before a drop may publish its buffer after the drop's + /// purge, Reload Footage clearing the cache while the buffer was being written: the check + /// here, not the order of the two, keeps it from being served.) + /// Whether a buffer is kept in memory under `key` (a peek: no hit, no miss, no disk read). + pub(crate) fn holds(&self, key: u64) -> bool { + self.kept(key, false).is_some() + } + + fn kept(&self, key: u64, hit: bool) -> Option<(Arc, Arc)> { + let found = { + let mut g = self.inner.lock().ok()?; + g.clock += 1; + let now = g.clock; + let e = g.map.get_mut(&key)?; + if hit { + e.last_use = now; + } + (e.buf.clone(), e.files.clone()) + }; + if self.made_before_a_drop(&found.1) { + if let Ok(mut g) = self.inner.lock() + && g.map.get(&key).is_some_and(|e| Arc::ptr_eq(&e.files, &found.1)) + && let Some(e) = g.map.remove(&key) + { + g.bytes = g.bytes.saturating_sub(e.bytes); + } + return None; + } + if hit && let Ok(mut g) = self.inner.lock() { + g.hits += 1; + } + Some(found) + } + + /// Whether a buffer made of `files` holds a file as it was before a drop that came after its + /// reads began ([`ReadFiles::since`]; a list that doesn't say counts as made before every + /// drop). + fn made_before_a_drop(&self, files: &ReadFiles) -> bool { + self.persistent().is_some_and(|s| s.dropped_since(files, files.since().unwrap_or(0))) + } + + /// The persistent store's drop generation now ([`LayerStore::drop_generation`]), taken by a + /// render before it starts reading (`None` without a store). + pub fn drop_generation(&self) -> Option { + self.persistent().map(|s| s.drop_generation()) + } + + /// See [`LayerCache::insert`]: the buffer kept under `key` and its files (`buf` and `files`, + /// unless one was kept first or `buf` is too large to keep). + fn insert_mem(&self, key: u64, buf: Arc, files: Arc) -> (Arc, Arc) { let bytes = buf.img.data.len() * std::mem::size_of::(); - let Ok(mut g) = self.inner.lock() else { return buf }; + let Ok(mut g) = self.inner.lock() else { return (buf, files) }; if bytes > g.budget / 4 { - return buf; + return (buf, files); } g.clock += 1; let now = g.clock; if let Some(e) = g.map.get_mut(&key) { - e.last_use = now; - return e.buf.clone(); + // (one made before a drop gives way: see [`LayerCache::kept`]) + if !self.made_before_a_drop(&e.files) { + e.last_use = now; + return (e.buf.clone(), e.files.clone()); + } + if let Some(old) = g.map.remove(&key) { + g.bytes = g.bytes.saturating_sub(old.bytes); + } } - g.map.insert(key, Entry { buf: buf.clone(), bytes, last_use: now }); + // (checked again just before it is published: a drop may have come since `insert` + // checked; one that comes later is caught when the buffer is looked up) + if self.made_before_a_drop(&files) { + return (buf, files); + } + g.map.insert(key, Entry { buf: buf.clone(), files: files.clone(), bytes, last_use: now }); g.bytes += bytes; if g.bytes > g.budget { // Evict least-recently used entries down to 3/4 of the budget. @@ -226,7 +315,7 @@ impl LayerCache { } } } - buf + (buf, files) } /// The memory budget in bytes. @@ -264,12 +353,29 @@ impl LayerCache { } } -/// Persistent storage of layer buffers behind a [`LayerCache`] (keys salted per project). +/// Persistent storage of layer buffers behind a [`LayerCache`] (keys: +/// [`crate::disk_cache::layer_disk_key`]). Every entry keeps the source files its buffer was made +/// of and is used only while they are unchanged (#3184). pub trait LayerStore: Send + Sync { - /// A stored buffer (synchronous: mid-render). - fn get_layer(&self, key: u128) -> Option>; - /// Keep a buffer that was slow to render. - fn put_layer(&self, key: u128, buf: &Buf); + /// A stored buffer whose source files are unchanged, with those files (synchronous: + /// mid-render). An entry whose files changed, or damaged, is a miss and is dropped, so the + /// buffer rendered again replaces it. `virtual_id` names files served from memory. + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)>; + /// Keep a buffer that was slow to render, with the source files it was made of (shared, so + /// a store can encode it off the render thread). `since`: the + /// [`LayerStore::drop_generation`] when its render started (a buffer made of a file dropped + /// after that is refused). + fn put_layer(&self, key: u128, buf: &Arc, files: &EntryFiles, since: u64); + /// How many times files were dropped from the store (File ▸ Reload Footage, + /// [`crate::disk_cache::DiskCache::drop_files`]); `0` for a store that never drops. + fn drop_generation(&self) -> u64 { + 0 + } + /// Whether one of `files` was dropped after generation `since`: what was made of them is + /// from before the drop. `false` for a store that never drops. + fn dropped_since(&self, _files: &ReadFiles, _since: u64) -> bool { + false + } /// Buffers faster to render than this (ms) are not stored. fn min_layer_ms(&self) -> u64 { 0 @@ -281,9 +387,10 @@ pub const PREFETCH_MIN_LAYER_MS: u64 = 20; /// A [`LayerStore`] over storage that can't be read in the middle of a render (the browser's /// Origin Private File System, read asynchronously). Lookups are served from buffers fetched -/// before the frame ([`PrefetchStore::provide`]); the keys a render looked up and didn't find -/// are recorded ([`PrefetchStore::take_misses`]) so the transport can fetch them before the next -/// frame; buffers to store queue up as sealed entries ([`PrefetchStore::take_writes`]) for the +/// before the frame ([`PrefetchStore::provide`]), once the files their entries list are found +/// unchanged; the keys a render looked up and didn't find are recorded +/// ([`PrefetchStore::take_misses`]) so the transport can fetch them before the next frame; +/// buffers to store queue up as sealed entries ([`PrefetchStore::take_writes`]) for the /// transport to write after the frame. Fetched buffers are kept least recently used first, up /// to a byte budget. pub struct PrefetchStore { @@ -292,9 +399,21 @@ pub struct PrefetchStore { min_ms: u64, } +/// A fetched entry: the buffer, the source files it was made of, its last use. +struct Fetched { + buf: Arc, + files: Arc, + used: u64, +} + +/// The memory a buffer's pixels take, in bytes. +fn buf_bytes(b: &Buf) -> usize { + b.img.data.len().saturating_mul(std::mem::size_of::()) +} + #[derive(Default)] struct Prefetched { - ready: HashMap, u64)>, + ready: HashMap, bytes: usize, clock: u64, misses: Vec, @@ -304,6 +423,22 @@ struct Prefetched { known: std::collections::HashSet, } +impl Prefetched { + /// Records a missed key for prefetching, up to a fixed bound. + fn note_miss(&mut self, key: u128) { + if !self.misses.contains(&key) && self.misses.len() < 1024 { + self.misses.push(key); + } + } + + /// Drops the prefetched entry for `key` and frees its bytes. + fn remove(&mut self, key: u128) { + if let Some(f) = self.ready.remove(&key) { + self.bytes = self.bytes.saturating_sub(buf_bytes(&f.buf)); + } + } +} + impl Default for PrefetchStore { fn default() -> Self { PrefetchStore::new(256 << 20) @@ -327,23 +462,21 @@ impl PrefetchStore { } /// A fetched entry (sealed bytes, [`crate::disk_cache::layer_entry`]) for `key`; `false` - /// when damaged. + /// when damaged or of another format. Its files are checked when the buffer is used. pub fn provide(&self, key: u128, entry: &[u8]) -> bool { - let Some(buf) = crate::disk_cache::read_layer_entry(entry) else { return false }; - let bytes = buf.img.data.len() * std::mem::size_of::(); + let Some((buf, files)) = crate::disk_cache::read_layer_entry(entry) else { return false }; + let buf = Arc::new(buf); + let bytes = buf_bytes(&buf); let Ok(mut s) = self.st.lock() else { return false }; s.clock += 1; - let now = s.clock; - if let Some((old, _)) = s.ready.insert(key, (Arc::new(buf), now)) { - s.bytes -= old.img.data.len() * std::mem::size_of::(); - } - s.bytes += bytes; + let used = s.clock; + s.remove(key); + s.ready.insert(key, Fetched { buf, files: Arc::new(files), used }); + s.bytes = s.bytes.saturating_add(bytes); s.known.insert(key); while s.bytes > self.budget { - let Some((&k, _)) = s.ready.iter().min_by_key(|(_, (_, t))| *t) else { break }; - if let Some((b, _)) = s.ready.remove(&k) { - s.bytes -= b.img.data.len() * std::mem::size_of::(); - } + let Some(oldest) = s.ready.iter().min_by_key(|(_, f)| f.used).map(|(k, _)| *k) else { break }; + s.remove(oldest); } true } @@ -372,32 +505,46 @@ impl PrefetchStore { } impl LayerStore for PrefetchStore { - fn get_layer(&self, key: u128) -> Option> { + /// The prefetched layer for `key` with its read files, or `None` when it is not ready. + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { + let found = { + let mut s = self.st.lock().ok()?; + s.clock += 1; + let now = s.clock; + match s.ready.get_mut(&key) { + Some(f) => { + f.used = now; + Some((f.buf.clone(), f.files.clone())) + } + None => { + s.note_miss(key); + None + } + } + }; + let (buf, files) = found?; + // (looked at without the lock: one call of the hook, or one `metadata`, per file) + let unchanged = files.unchanged(virtual_id); let mut s = self.st.lock().ok()?; - s.clock += 1; - let now = s.clock; - match s.ready.get_mut(&key) { - Some((b, t)) => { - *t = now; - let b = b.clone(); - if !s.hits.contains(&key) { - s.hits.push(key); - } - Some(b) - } - None => { - if !s.misses.contains(&key) && s.misses.len() < 1024 { - s.misses.push(key); - } - None - } + if !unchanged { + // Made of files that changed since: forgotten, so the buffer rendered again is + // written over its entry. + s.remove(key); + s.known.remove(&key); + s.note_miss(key); + return None; } + if !s.hits.contains(&key) { + s.hits.push(key); + } + Some((buf, files.to_read_files())) } - fn put_layer(&self, key: u128, buf: &Buf) { + /// Queues the layer for writing to the persistent store the first time `key` is seen. + fn put_layer(&self, key: u128, buf: &Arc, files: &EntryFiles, _since: u64) { let Ok(mut s) = self.st.lock() else { return }; if s.known.insert(key) { - s.writes.push((key, crate::disk_cache::layer_entry(buf))); + s.writes.push((key, crate::disk_cache::layer_entry(buf, files))); } } @@ -470,6 +617,12 @@ fn time_dependent(layer: &Layer, effects: bool) -> bool { false } +/// A text layer with an Expression Selector: its amount is evaluated per character, and the +/// layer's key holds only the first character's (see [`crate::reads::ReadFiles::is_unkeyed`]). +pub(crate) fn per_character_expressions(layer: &Layer) -> bool { + matches!(layer.source, LayerSource::Text) && layer.props.sub("text").is_some_and(|t| group_has(t, "expressionSelector")) +} + fn group_has(g: &PropGroup, match_id: &str) -> bool { g.children.iter().any(|c| match c { Node::Group(sub) => sub.match_id == match_id || group_has(sub, match_id), @@ -542,7 +695,9 @@ fn reads_other_times(layer: &Layer, effects: Option) -> bool { fx.groups().take(effects.unwrap_or(usize::MAX)).any(|g| { g.enabled && matches!(&g.kind, effectcraft_project::GroupKind::Effect { effect } - if effect.starts_with("ec.time.") || effectcraft_effects::reads_param_history(effect)) + if effect.starts_with("ec.time.") + || effectcraft_effects::reads_param_history(effect) + || (!effect.starts_with("ec.") && effectcraft_effects::plugin::reads_other_times(effect))) }) }) } @@ -741,6 +896,21 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo Some(h.finish()) } +/// Does the layer read another layer through an enabled effect's layer parameter (Gradient Wipe, +/// Set Matte…)? Those layers are drawn by the reading layer's renderer, so the switches it +/// passes down belong in the key (`Renderer::nested_look`). +pub(crate) fn reads_layers(ctx: &EvalCtx, layer: &Layer) -> bool { + /// Whether any enabled layer-valued property of `layer` points at another layer. + fn reads(ctx: &EvalCtx, layer: &Layer, g: &PropGroup, depth: usize) -> bool { + depth < 32 + && g.children.iter().any(|n| match n { + Node::Prop(p) => matches!(p.value, Value::Layer(_)) && ctx.value(layer, p).as_layer().is_some_and(|id| id != layer.id.0), + Node::Group(sub) => sub.enabled && reads(ctx, layer, sub, depth + 1), + }) + } + layer.switches.effects && layer.effects().is_some_and(|fx| fx.groups().any(|g| g.enabled && reads(ctx, layer, g, 0))) +} + /// Does the layer run an effect that reads the comp camera or lights (Card Dance, CC Particle /// World…)? fn reads_comp_scene(layer: &Layer) -> bool { @@ -786,8 +956,211 @@ mod shared_insert_tests { let cache = LayerCache::default(); let buf = || Arc::new(Buf { img: Image::new(4, 4), offset: [0.0; 2], scale: 1.0 }); let (a, b) = (buf(), buf()); - assert!(Arc::ptr_eq(&cache.insert(3, a.clone()), &a)); - assert!(Arc::ptr_eq(&cache.insert(3, b), &a), "the later render gets the first buffer"); - assert!(Arc::ptr_eq(&cache.get(3).unwrap(), &a)); + assert!(Arc::ptr_eq(&cache.insert(3, a.clone(), Default::default()).0, &a)); + assert!(Arc::ptr_eq(&cache.insert(3, b, Default::default()).0, &a), "the later render gets the first buffer"); + assert!(Arc::ptr_eq(&cache.get(3).unwrap().0, &a)); + } + + /// The browser's store (#3184): a fetched entry is used only while the files it lists are + /// unchanged (here from memory, through the hook), and comes with them; one made of files + /// that changed is dropped and counts as a miss, so the buffer rendered again is queued over + /// it. A buffer whose files can't all be named is not queued at all. + #[test] + fn the_prefetch_store_checks_the_files_of_its_entries() { + use super::{LayerStore, PrefetchStore}; + use crate::disk_cache::{EntryFiles, layer_disk_key, layer_entry}; + use crate::reads::{FileStamp, ReadFile, ReadFiles}; + let buf = || Buf { img: Image::new(2, 2), offset: [0.0; 2], scale: 1.0 }; + let files: ReadFiles = [ReadFile::new("/v.png", FileStamp::Virtual)].into_iter().collect(); + let (one, two) = (|_: &str| Some((3, 1)), |_: &str| Some((3, 2))); + let entry = layer_entry(&buf(), &EntryFiles::of(&files, Some(&one)).unwrap()); + let store = PrefetchStore::new(1 << 20).with_min_ms(0); + assert!(store.provide(5, &entry)); + assert!(!store.provide(6, b"damaged")); + let (_, got) = store.get_layer(5, Some(&one)).unwrap(); + assert_eq!(got, files); + assert_eq!(store.take_hits(), [5]); + // The file changed: a miss, forgotten, and the new buffer is queued over it. + assert!(store.get_layer(5, Some(&two)).is_none()); + assert!(!store.has(5)); + assert_eq!(store.take_misses(), [5]); + store.put_layer(5, &Arc::new(buf()), &EntryFiles::of(&files, Some(&two)).unwrap(), 0); + assert_eq!(store.take_writes().len(), 1, "written over the changed entry"); + // Through the layer cache: a hit reports its files; incomplete lists are not queued. + let cache = LayerCache::default(); + let store = Arc::new(PrefetchStore::new(1 << 20).with_min_ms(0)); + cache.set_store(Some(store.clone())); + cache.set_virtual_id(Some(Arc::new(one))); + assert!(store.provide(layer_disk_key(9), &entry)); + let (_, from_store) = cache.get(9).unwrap(); + assert!(*from_store == files && from_store.is_complete()); + let mut incomplete = files.clone(); + incomplete.mark_incomplete(); + assert!(cache.get(10).is_none()); + cache.insert(10, Arc::new(buf()), Arc::new(incomplete)); + assert!(cache.get(11).is_none()); + cache.insert(11, Arc::new(buf()), Arc::new(files.clone())); + let written: Vec = store.take_writes().into_iter().map(|w| w.0).collect(); + assert_eq!(written, [layer_disk_key(11)], "only the buffer whose files are all named"); + } + + /// A layer buffer whose render started before Reload Footage dropped its file (#3184) is + /// not written to the disk cache when it is kept afterwards; one whose render started after + /// the drop is. + #[test] + fn a_buffer_rendered_across_a_drop_is_not_written() { + use crate::disk_cache::{DiskCache, Kind, layer_disk_key}; + use crate::reads::{FileStamp, ReadFile, ReadLog}; + let dir = tempfile::tempdir().unwrap(); + let dc = DiskCache::open(dir.path(), 1 << 30).unwrap(); + dc.set_min_layer_ms(0); + let cache = LayerCache::default(); + cache.set_disk(Some(dc.clone())); + let buf = || Arc::new(Buf { img: Image::new(2, 2), offset: [0.0; 2], scale: 1.0 }); + // A render's files, read after it took the drop generation (`Renderer::recorded`). + let render = || { + let log = ReadLog::starting_at(cache.drop_generation().unwrap()); + move || { + log.note(ReadFile::new("/a.png", FileStamp::Native { len: 3, modified: Some(1) })); + Arc::new(log.into_files()) + } + }; + // The miss starts the render; the file is reloaded before the buffer is kept. + assert!(cache.get(1).is_none()); + let a = render(); + dc.drop_files(["/a.png"]); + dc.flush(); + // Another render of the same key starts after the drop, while the first one still runs + // (its miss must not lend the first render its generation). + assert!(cache.get(1).is_none()); + let b = render(); + let (stale, _) = cache.insert(1, buf(), a()); + dc.flush(); + assert!(!dc.contains(Kind::Layer, layer_disk_key(1)), "made of the file as it was before the drop"); + // Not kept in memory either: the second render keeps its own buffer, and writes it. + let fresh = buf(); + let (kept, _) = cache.insert(1, fresh.clone(), b()); + assert!(Arc::ptr_eq(&kept, &fresh) && !Arc::ptr_eq(&kept, &stale)); + // A render of another key after the drop. + assert!(cache.get(2).is_none()); + cache.insert(2, buf(), render()()); + dc.flush(); + assert!(dc.contains(Kind::Layer, layer_disk_key(1)), "the render after the drop"); + assert!(dc.contains(Kind::Layer, layer_disk_key(2))); + // A list that doesn't say when its reads began counts as made before the drop. + assert!(cache.get(3).is_none()); + cache.insert(3, buf(), Arc::new([ReadFile::new("/a.png", FileStamp::Native { len: 3, modified: Some(1) })].into_iter().collect())); + dc.flush(); + assert!(!dc.contains(Kind::Layer, layer_disk_key(3))); + drop((cache, dc)); + } + + /// A disk cache whose layer writes stop at a barrier until the test lets them go on. + struct PausedWrites { + dc: Arc, + arrived: std::sync::Barrier, + go_on: std::sync::Barrier, + } + + impl super::LayerStore for PausedWrites { + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, crate::reads::ReadFiles)> { + super::LayerStore::get_layer(&*self.dc, key, virtual_id) + } + fn put_layer(&self, key: u128, buf: &Arc, files: &crate::disk_cache::EntryFiles, since: u64) { + self.arrived.wait(); + self.go_on.wait(); + super::LayerStore::put_layer(&*self.dc, key, buf, files, since); + } + fn drop_generation(&self) -> u64 { + self.dc.drop_generation() + } + fn dropped_since(&self, files: &crate::reads::ReadFiles, since: u64) -> bool { + self.dc.dropped_since(files, since) + } + } + + /// Reload Footage while a render from before it is writing its buffer: the cache is cleared + /// and the file dropped after the buffer passed its check, before it is kept. The buffer + /// then reaches memory after the purge, but it is never served, and a render after the drop + /// keeps its own buffer (#3191 review). + #[test] + fn a_buffer_kept_after_the_purge_of_a_reload_is_not_served() { + use crate::reads::{FileStamp, ReadFile, ReadLog}; + let dir = tempfile::tempdir().unwrap(); + let dc = crate::disk_cache::DiskCache::open(dir.path(), 1 << 30).unwrap(); + let store = Arc::new(PausedWrites { dc: dc.clone(), arrived: std::sync::Barrier::new(2), go_on: std::sync::Barrier::new(2) }); + let cache = Arc::new(LayerCache::default()); + cache.set_store(Some(store.clone())); + let buf = || Arc::new(Buf { img: Image::new(2, 2), offset: [0.0; 2], scale: 1.0 }); + let files = |cache: &LayerCache| { + let log = ReadLog::starting_at(cache.drop_generation().unwrap()); + log.note(ReadFile::new("/a.png", FileStamp::Native { len: 3, modified: Some(1) })); + Arc::new(log.into_files()) + }; + // The old render: a miss, its reads, then its insert, which stops in the disk write. + assert!(cache.get(1).is_none()); + let old_files = files(&cache); + let old = buf(); + let writer = { + let (cache, old) = (cache.clone(), old.clone()); + std::thread::spawn(move || cache.insert(1, old, old_files)) + }; + store.arrived.wait(); + // Reload Footage meanwhile: the layer cache is purged and the file dropped. + cache.clear(); + dc.drop_files(["/a.png"]); + dc.flush(); + store.go_on.wait(); + let _ = writer.join().unwrap(); + dc.flush(); + assert!(!dc.contains(crate::disk_cache::Kind::Layer, crate::disk_cache::layer_disk_key(1)), "not on disk"); + assert!(cache.get(1).is_none(), "the old pixels are not served from memory"); + // A render after the drop keeps its own buffer. + let fresh = buf(); + let new_files = files(&cache); + let mut kept = None; + std::thread::scope(|s| { + s.spawn(|| { + store.arrived.wait(); + store.go_on.wait(); + }); + kept = Some(cache.insert(1, fresh.clone(), new_files).0); + }); + let kept = kept.unwrap(); + assert!(Arc::ptr_eq(&kept, &fresh) && !Arc::ptr_eq(&kept, &old)); + assert!(Arc::ptr_eq(&cache.get(1).unwrap().0, &fresh)); + } + + /// A render that gets another render's buffer gets that buffer's files too (#3184): when a + /// file changed between the two reads, its frame lists the file with both identities, so the + /// list is incomplete and the frame is not kept on disk with the new identity and the old + /// pixels. + #[test] + fn the_buffer_kept_first_brings_its_files() { + use crate::reads::{FileStamp, ReadFile, ReadFiles, ReadLog}; + use crate::{NoFootage, RenderOpts, Renderer}; + let cache = LayerCache::default(); + let buf = || Arc::new(Buf { img: Image::new(4, 4), offset: [0.0; 2], scale: 1.0 }); + let files = |len| Arc::new([ReadFile::new("/a.png", FileStamp::Native { len, modified: Some(1) })].into_iter().collect::()); + let (first, second) = (files(1), files(2)); + let a = buf(); + cache.insert(3, a.clone(), first.clone()); + let project = effectcraft_project::Project::default(); + let log = ReadLog::new(); + let mut r = Renderer::new(&project, &NoFootage, RenderOpts::default()); + r.cache = Some(&cache); + r.reads = Some(&log); + // (what `Renderer::recorded` noted for the second render) + log.note_all(&second); + let (kept, kept_files) = r.keep(Some(3), buf(), &second); + assert!(Arc::ptr_eq(&kept, &a)); + assert_eq!(kept_files, first); + assert!(!log.files().is_complete()); + // The same files: nothing changes. + let same = ReadLog::new(); + r.reads = Some(&same); + same.note_all(&first); + let _ = r.keep(Some(3), buf(), &files(1)); + assert!(same.files().is_complete()); } } diff --git a/crates/render/src/cache/dependencies.rs b/crates/render/src/cache/dependencies.rs index db1465c07..dc4216098 100644 --- a/crates/render/src/cache/dependencies.rs +++ b/crates/render/src/cache/dependencies.rs @@ -156,7 +156,7 @@ impl Dependencies<'_> { layer.layer_time(ctx.time).0.hash(self.h); } match layer.source { - LayerSource::Solid { item } | LayerSource::Footage { item } | LayerSource::Comp { item } => { + LayerSource::Solid { item } | LayerSource::Footage { item } | LayerSource::Comp { item } | LayerSource::Model { item } => { let item = match layer.source { LayerSource::Footage { .. } => ctx.media_item(layer, item), _ => item, diff --git a/crates/render/src/color.rs b/crates/render/src/color.rs index d27526553..158dde42f 100644 --- a/crates/render/src/color.rs +++ b/crates/render/src/color.rs @@ -117,6 +117,26 @@ impl Pipe { Conversion::new(ws, self.linear, self.out, false) } + /// The pipe without the HDR step (Clip), as [`crate::RenderOpts::skip_hdr_step`] renders + /// with: [`Pipe::output`] converts to the output space as it is. + pub fn without_hdr_step(self) -> Pipe { + Pipe { hdr: HdrMode::Clip, ..self } + } + + /// The top-level frame of a [`Pipe::without_hdr_step`] render (output-encoded, straight colour) + /// → linear light in the output space's primaries: the output space's curve, or the Working + /// Gamma's when unmanaged (sRGB at 2.2, a pure 2.4 power curve at 2.4). The identity for a + /// linear output (ACES). + pub fn output_linear(&self) -> Conversion { + Conversion::linearize(self.output_linear_space()) + } + + /// The space whose primaries and white the frame of [`Pipe::output_linear`] is in: the output + /// space, or the Working Gamma's (sRGB or Rec. 709, the same primaries) when unmanaged. + pub fn output_linear_space(&self) -> ColorSpace { + if self.space.is_some() { self.out } else { self.curve() } + } + /// Output with HDR compand / tone mapping (standard-dynamic-range outputs only): working /// space → linear output primaries, the HDR curve, then the output's encoding. pub fn output_hdr(&self) -> Option<(Option, HdrMode, Conversion)> { @@ -133,6 +153,26 @@ impl Pipe { p } + /// A copy of `src` converted by `c` and quantised to the bit depth, in one pass: one read and + /// one write of the frame instead of a copy, a conversion and a quantise pass (a 1080p float + /// frame is 33 MB, and these passes are limited by memory speed). The same pixels as + /// [`convert`] then [`Pipe::quantize`]. + pub fn copy_converted(&self, src: &Image, c: Option<&Conversion>) -> Image { + let levels = self.levels; + let data = src + .data + .par_iter() + .map(|&p| { + let mut p = c.map_or(p, |c| convert_px(p, c)); + if let Some(l) = levels { + quantize_px(&mut p, l, 1.0 / l); + } + p + }) + .collect(); + Image { width: src.width, height: src.height, data } + } + /// Clamp and quantise to the bit depth (no-op in 32 bpc). pub fn quantize(&self, img: &mut Image) { self.quantize_region(img, Region::Full); @@ -245,14 +285,18 @@ fn quantize_rect(img: &mut Image, r: PxRect, levels: f32) { /// Convert premultiplied pixels (on straight colour). pub fn convert(img: &mut Image, c: &Conversion) { - img.data.par_iter_mut().for_each(|p| { - let a = p[3]; - if a <= 0.0 { - return; - } - let o = c.apply([p[0] / a, p[1] / a, p[2] / a]); - *p = [o[0] * a, o[1] * a, o[2] * a, a]; - }); + img.data.par_iter_mut().for_each(|p| *p = convert_px(*p, c)); +} + +/// [`convert`] of one pixel. +#[inline] +fn convert_px(p: [f32; 4], c: &Conversion) -> [f32; 4] { + let a = p[3]; + if a <= 0.0 { + return p; + } + let o = c.apply([p[0] / a, p[1] / a, p[2] / a]); + [o[0] * a, o[1] * a, o[2] * a, a] } /// Compand: an exponential knee from 80%, approaching 1.0 (linear light, per channel). @@ -329,6 +373,35 @@ mod tests { } } + /// The fused footage pass gives the pixels of a copy, a conversion and a quantise pass, bit + /// for bit, at every depth, with and without a conversion. + #[test] + fn copy_converted_is_convert_then_quantize() { + let mut img = Image::new(17, 5); + for (i, p) in img.data.iter_mut().enumerate() { + *p = match i % 7 { + 0 => [0.3, -0.2, 0.71, 0.9], + 1 => [-0.0, 0.0, 0.0, 0.0], + 2 => [1.7, 0.4, f32::NAN, 0.5], + 3 => [0.0; 4], + _ => [i as f32 / 90.0, 0.5, 0.25, 1.0], + }; + } + for depth in [effectcraft_project::BitDepth::Bpc8, effectcraft_project::BitDepth::Bpc16, effectcraft_project::BitDepth::Bpc32] { + let pipe = Pipe::of(&ProjectSettings { bit_depth: depth, ..Default::default() }); + for c in [None, Some(Conversion::linearize(ColorSpace::Srgb))] { + let mut want = img.clone(); + if let Some(c) = &c { + convert(&mut want, c); + } + pipe.quantize(&mut want); + let got = pipe.copy_converted(&img, c.as_ref()); + let bits = |i: &Image| i.data.iter().map(|p| p.map(f32::to_bits)).collect::>(); + assert_eq!(bits(&got), bits(&want), "{depth:?} conversion {}", c.is_some()); + } + } + } + /// Both forms `round_half_up` picks between agree on everything quantising feeds it: /// 0..=levels, exact halves included. #[test] diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 9cf5694f0..5c34348fe 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -2,13 +2,25 @@ //! and layer cache entries kept on disk between sessions, like After Effects' disk cache. //! //! * Entries are files keyed by a 128-bit content hash (`/v1//<2 hex>/<32 hex>.ecc`): -//! frames by the hash of the composition's content (the comp and everything it uses, footage -//! files' size and modification time included) plus frame, scale and view; layer buffers by -//! the layer cache's content key salted with the project's footage fingerprint. A changed -//! project therefore never reads stale pixels: its keys simply change. -//! * Payloads are LZ4-compressed (`lz4_flex`, MIT): frames as 8-bit premultiplied RGBA, layer -//! buffers as `f32` RGBA with the bytes shuffled into planes (exact, so cached and fresh -//! renders are bit-identical), Roto Brush / Object Matte segmentations as +//! frames by the hash of the composition's content as it is in memory (the comp and what it can +//! draw, footage items with their settings and paths, and what its expressions can read; no +//! file is looked at, [`comp_content_key`]) plus frame, scale and view; layer buffers by the +//! layer cache's content key (which names the footage items a buffer uses with their settings +//! and paths) and the renderer version ([`layer_disk_key`]). A changed project therefore never +//! reads stale pixels: its keys simply change, and an edit elsewhere keeps them. +//! * Frame and layer entries keep the source files they were made of (footage, and the font +//! files text is drawn with), each with the size and modification time it was read with +//! ([`EntryFiles`], #3184). An entry is used only while those files are unchanged: a handful +//! of `metadata` calls when it is read, never a scan of the project's files. A frame or +//! buffer whose files can't all be named is not stored (text in a family that isn't installed +//! or with fallback glyphs, footage refused by automation read roots, …). File ▸ Reload +//! Footage deletes the entries made of the reloaded files ([`DiskCache::drop_files`]): a file +//! replaced by one of the same size and time is read again. +//! * Payloads are LZ4-compressed (`lz4_flex`, MIT): frames as 8-bit premultiplied RGBA (or, for +//! 32 bpc viewer frames, half-float RGBA with the bytes shuffled into planes; the entry +//! header's format byte tells them apart: 2 and 3, both with their source files first), layer +//! buffers (format 4, their source files first) as `f32` RGBA with the bytes shuffled into +//! planes (exact, so cached and fresh renders are bit-identical), Roto Brush / Object Matte segmentations as //! `FrameSeg::to_bytes` (keyed by their content-keyed chain key and scale, so they are //! reused whenever the same frames, settings and prompt come back, also after a restart). Every file ends in a checksum; damaged files read as misses and //! are deleted. @@ -30,12 +42,26 @@ use std::sync::{Arc, Condvar, Mutex}; use effectcraft_effects::Buf; use effectcraft_raster::Image; +use crate::reads::ReadFiles; + +mod entry_files; +pub use entry_files::{EntryFile, EntryFiles, EntryStamp}; + /// File format version (part of the folder layout). const VERSION: &str = "v1"; const MAGIC: &[u8; 4] = b"ECDC"; -/// Pending writes before new ones are dropped. +/// Pending layer and matte writes before new ones are dropped. #[cfg(not(target_arch = "wasm32"))] const QUEUE_LIMIT: usize = 64; +/// Pending frame bytes before new frames are dropped. Frames have their own lane, written +/// before layer buffers: a burst of large layer writes used to fill the shared queue and drop +/// frames, so a fully cached comp came back with gaps in its blue bar. +#[cfg(not(target_arch = "wasm32"))] +const FRAME_QUEUE_BYTES: usize = 1 << 30; +/// Pending layer and matte bytes before new ones are dropped: a layer job holds its float +/// buffer until the writer compresses it (64 of them at 4K were ~8.5 GB). +#[cfg(not(target_arch = "wasm32"))] +const LAYER_QUEUE_BYTES: usize = 1 << 30; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Kind { @@ -71,6 +97,26 @@ pub struct Frame8 { pub rgba: Vec, } +/// A cached 32 bpc viewer frame: premultiplied RGBA half floats (IEEE binary16 bits), four +/// per pixel. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FrameF16 { + pub width: u32, + pub height: u32, + pub rgba: Vec, +} + +/// The entry header's format byte: segmentations (and 8-bit frames and layer buffers before +/// #3184). +const FORMAT_RGBA8: u8 = 0; +/// Frame entries: their source files ([`EntryFiles`]), then 8-bit or half-float pixels. The +/// formats before them (0: 8-bit, 1: half float, without files) read as misses and are deleted. +const FORMAT_RGBA8_FILES: u8 = 2; +const FORMAT_F16_FILES: u8 = 3; +/// Layer entries: their source files ([`EntryFiles`]), then the buffer. The format before it +/// (0, without files) reads as a miss and is deleted. +const FORMAT_LAYER_FILES: u8 = 4; + /// Counters for tests, the Info panel and `cache.diskStats`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct DiskStats { @@ -200,7 +246,7 @@ pub struct LayerPrefetch { const PREFETCH_RECENT: usize = 512; impl LayerPrefetch { - /// A frame's layer-cache misses (salted keys). + /// A frame's layer-cache misses (disk keys, [`layer_disk_key`]). pub fn note_misses(&mut self, keys: impl IntoIterator) { for k in keys { self.recent.retain(|x| *x != k); @@ -221,12 +267,124 @@ impl LayerPrefetch { #[cfg_attr(target_arch = "wasm32", allow(dead_code))] enum Job { - Write(Kind, u128, Vec), + /// Kind, key, header format byte, payload. + Write(Kind, u128, u8, Payload), + /// Delete the frame and layer entries made of these files ([`DiskCache::drop_files`]). + Drop(Vec>), +} + +/// What a queued write holds. 8-bit frames and layer buffers are encoded (LZ4) on the writer +/// thread, not on the render thread that queued them: encoding a 1080p frame took ~9 ms of every +/// frame's render, and a full queue no longer throws away encoding work. +enum Payload { + Encoded(Vec), + /// 8-bit premultiplied RGBA, `width * height * 4` bytes, and the files it was made of. + Frame(u32, u32, Vec, EntryFiles), + Layer(Arc, EntryFiles), +} + +impl Payload { + /// Bytes it holds (the frame queue's budget). + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + fn len(&self) -> usize { + match self { + Payload::Encoded(p) | Payload::Frame(_, _, p, _) => p.len(), + Payload::Layer(b, _) => b.img.data.len().saturating_mul(std::mem::size_of::()), + } + } + + /// The entry's payload: its source files, then its pixels. + fn encode(self) -> Vec { + match self { + Payload::Encoded(p) => p, + Payload::Frame(w, h, rgba, files) => with_files(&files, encode_frame(w, h, &rgba)), + Payload::Layer(b, files) => with_files(&files, encode_layer(&b)), + } + } } struct Queue { + /// Frame writes (taken first) and their payload bytes. + frames: std::collections::VecDeque, + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + frame_bytes: usize, + /// Layer and matte writes, and their payload bytes. jobs: std::collections::VecDeque, + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + job_bytes: usize, busy: bool, + /// Keys of frames queued or being written. + pending_frames: std::collections::HashSet, + /// The drops so far (under the queue's lock: a write is queued either before a drop, which + /// then sweeps it, or after it, when this refuses it if it was made from before). + drops: Drops, +} + +/// Files dropped from the cache files beyond this are not remembered one by one: everything made +/// before the drop that forgot them is refused instead. +const MAX_DROPPED_PATHS: usize = 1 << 16; + +/// The [`DiskCache::drop_files`] calls so far: their number (the drop generation) and the last one +/// of each file. An entry made of a file read before that file's last drop (its render started at +/// an earlier generation) holds the pixels from before and is refused. +#[derive(Default)] +struct Drops { + generation: u64, + last: HashMap, u64>, + /// Everything made before this generation is refused (the per-file record was forgotten). + floor: u64, +} + +impl Drops { + /// Notes that the given paths were dropped, bumping the generation and tracking them for later checks. + fn record(&mut self, paths: &[Arc]) { + self.generation = self.generation.saturating_add(1); + if self.last.len().saturating_add(paths.len()) > MAX_DROPPED_PATHS { + self.last.clear(); + self.floor = self.generation; + return; + } + for p in paths { + self.last.insert(p.clone(), self.generation); + } + } + + /// Whether something made of `paths`, whose reads started at generation `since`, read one of + /// them before it was dropped. + fn stale<'a>(&self, mut paths: impl Iterator>, since: u64) -> bool { + since < self.floor || paths.any(|p| self.last.get(p).is_some_and(|g| *g > since)) + } +} + +impl Queue { + /// Takes the next queued job, frames first, and releases the bytes it held. + #[cfg(not(target_arch = "wasm32"))] + fn pop(&mut self) -> Option { + if let Some(j) = self.frames.pop_front() { + if let Job::Write(_, _, _, p) = &j { + self.frame_bytes = self.frame_bytes.saturating_sub(p.len()); + } + return Some(j); + } + let j = self.jobs.pop_front()?; + if let Job::Write(_, _, _, p) = &j { + self.job_bytes = self.job_bytes.saturating_sub(p.len()); + } + Some(j) + } + + /// No room for a `kind` write of `len` bytes. A layer bigger than the whole budget is still + /// taken when nothing else is queued. + #[cfg(not(target_arch = "wasm32"))] + fn full(&self, kind: Kind, len: usize) -> bool { + match kind { + Kind::Frame => self.frame_bytes.saturating_add(len) > FRAME_QUEUE_BYTES, + _ => self.jobs.len() >= QUEUE_LIMIT || (self.job_bytes > 0 && self.job_bytes.saturating_add(len) > LAYER_QUEUE_BYTES), + } + } + fn is_empty(&self) -> bool { + self.frames.is_empty() && self.jobs.is_empty() + } } pub struct DiskCache { @@ -237,16 +395,25 @@ pub struct DiskCache { disk_cap: AtomicU64, /// Free space is limiting the cache (warned once per episode). space_limited: AtomicBool, + /// The free space the cache leaves on its disk ([`disk_reserve`]); 0 = unknown. + reserve: AtomicU64, hits: AtomicU64, misses: AtomicU64, writes: AtomicU64, evictions: AtomicU64, dropped: AtomicU64, failed: AtomicU64, + /// Source files looked at to check frame and layer entries ([`DiskCache::file_checks`]). + file_checks: AtomicU64, + /// Frame and layer entries compressed for a queued write ([`DiskCache::encodes`]). + encodes: AtomicU64, tmp_counter: AtomicU64, queue: Arc<(Mutex, Condvar)>, /// Layer buffers that took less than this to render are not written (ms). min_layer_ms: AtomicU64, + /// Files whose entries are being deleted ([`DiskCache::drop_files`]), each with the number + /// of drops of it pending: until then an entry made of one is a miss. + dropping: Mutex, u32>>, } /// FNV-1a 128-bit (content keys). @@ -283,6 +450,23 @@ fn checksum(data: &[u8]) -> u64 { h } +/// The least free space the disk cache leaves on its disk. +pub const MIN_DISK_RESERVE: u64 = 2 << 30; +/// The most free space the disk cache leaves on its disk: 5% of a large disk is far more than +/// the system needs to keep working (on a 4 TB disk it held a 20 GB cache at 0 with 190 GB free). +pub const MAX_DISK_RESERVE: u64 = 10 << 30; +/// Below this much room left by free disk space, frame and layer writes are refused before they +/// are encoded ([`DiskCache::accepts_writes`]): a few frames would fill it, and the rest would be +/// compressed only to be refused. +const MIN_WRITE_ROOM: u64 = 64 << 20; + +/// The free space the disk cache leaves on a disk of `total` bytes: 5% of it, at least 2 GB and +/// at most 10 GB. It keeps the cache from filling the disk; the cache's size is the user's +/// Maximum Disk Cache Size (After Effects has that maximum and no reserve). +pub fn disk_reserve(total: u64) -> u64 { + (total / 20).clamp(MIN_DISK_RESERVE, MAX_DISK_RESERVE) +} + /// The platform's default disk cache folder. pub fn default_folder() -> PathBuf { let home = std::env::var_os("HOME").map(PathBuf::from); @@ -313,15 +497,30 @@ impl DiskCache { max_bytes: AtomicU64::new(max_bytes), disk_cap: AtomicU64::new(u64::MAX), space_limited: AtomicBool::new(false), + reserve: AtomicU64::new(0), hits: AtomicU64::new(0), misses: AtomicU64::new(0), writes: AtomicU64::new(0), evictions: AtomicU64::new(0), dropped: AtomicU64::new(0), failed: AtomicU64::new(0), + file_checks: AtomicU64::new(0), + encodes: AtomicU64::new(0), tmp_counter: AtomicU64::new(0), - queue: Arc::new((Mutex::new(Queue { jobs: Default::default(), busy: cfg!(not(target_arch = "wasm32")) }), Condvar::new())), + queue: Arc::new(( + Mutex::new(Queue { + frames: Default::default(), + frame_bytes: 0, + jobs: Default::default(), + job_bytes: 0, + busy: cfg!(not(target_arch = "wasm32")), + pending_frames: Default::default(), + drops: Drops::default(), + }), + Condvar::new(), + )), min_layer_ms: AtomicU64::new(30), + dropping: Mutex::new(HashMap::new()), }); dc.rescan(); // Shrinking a large cache deletes many files: the writer thread does it. @@ -394,19 +593,22 @@ impl DiskCache { self.max_bytes().min(self.disk_cap.load(Ordering::Relaxed)) } - /// The cache's disk: `(total, available)` bytes, `None` = unknown. The cache leaves at least - /// 2 GB or 5% of the disk free, whichever is more (evicting when it must). + /// The cache's disk: `(total, available)` bytes, `None` = unknown. The cache leaves + /// [`disk_reserve`] free (5% of the disk, at least 2 GB and at most 10 GB), evicting when it + /// must. pub fn set_disk_space(&self, space: Option<(u64, u64)>) { + let mut reserve = 0; let cap = match space { // (a disk reported as 0 bytes, such as an automount map, is unknown) Some((total, available)) if total > 0 => { - let reserve = (2u64 << 30).max(total / 20); + reserve = disk_reserve(total); let used = self.index.lock().map(|g| g.total()).unwrap_or_default(); // The cache's own files count as free: below the reserve it gives space back. used.saturating_add(available).saturating_sub(reserve) } _ => u64::MAX, }; + self.reserve.store(reserve, Ordering::Relaxed); self.disk_cap.store(cap, Ordering::Relaxed); let limited = cap < self.max_bytes(); if self.space_limited.swap(limited, Ordering::Relaxed) != limited && limited { @@ -415,6 +617,33 @@ impl DiskCache { self.evict(); } + /// Whether frame and layer writes are worth encoding now: `false` while free disk space + /// holds the limit at 0 or under 64 MB (a limit the setting asks for is always used). Two + /// atomic reads, so writes check it before they spend time converting and compressing + /// pixels that [`DiskCache::write_format`] would refuse anyway. (Whether a given entry fits + /// is known only once it is compressed: `write_format` decides.) + pub fn accepts_writes(&self) -> bool { + let (max, limit) = (self.max_bytes(), self.limit_bytes()); + limit > 0 && (limit >= MIN_WRITE_ROOM || limit == max) + } + + /// The free space the cache leaves on its disk ([`disk_reserve`]), once the disk's size is + /// known ([`DiskCache::set_disk_space`]). + pub fn reserve_bytes(&self) -> Option { + Some(self.reserve.load(Ordering::Relaxed)).filter(|r| *r > 0) + } + + /// Frame and layer entries compressed for writing so far (tests: a write refused up front + /// costs no encode). + pub fn encodes(&self) -> u64 { + self.encodes.load(Ordering::Relaxed) + } + + /// Count one entry compressed for a queued write. + fn count_encode(&self) { + self.encodes.fetch_add(1, Ordering::Relaxed); + } + /// Layer buffers faster to render than this are not worth a disk write. pub fn set_min_layer_ms(&self, ms: u64) { self.min_layer_ms.store(ms, Ordering::Relaxed); @@ -428,6 +657,11 @@ impl DiskCache { self.index.lock().is_ok_and(|g| g.contains(kind, key)) } + /// A frame write is queued or in progress. + pub fn frame_pending(&self, key: u128) -> bool { + self.queue.0.lock().is_ok_and(|q| q.pending_frames.contains(&key)) + } + /// Keys of one kind (unordered). pub fn keys(&self, kind: Kind) -> Vec { self.index.lock().map(|g| g.keys(kind)).unwrap_or_default() @@ -467,8 +701,11 @@ impl DiskCache { #[cfg(target_arch = "wasm32")] { q.jobs.clear(); + q.job_bytes = 0; + q.frames.clear(); + q.pending_frames.clear(); } - while !q.jobs.is_empty() || q.busy { + while !q.is_empty() || q.busy { q = match cv.wait(q) { Ok(q) => q, Err(_) => return, @@ -477,36 +714,105 @@ impl DiskCache { } fn read(&self, kind: Kind, key: u128) -> Option> { + self.read_entry(kind, key).map(|(_, p)| p) + } + + /// An entry's payload and its header's format byte. + fn read_entry(&self, kind: Kind, key: u128) -> Option<(u8, Vec)> { + let entry = self.load(kind, key); + match &entry { + Some(_) => self.hit(kind, key), + None => _ = self.misses.fetch_add(1, Ordering::Relaxed), + } + entry + } + + /// An entry's payload and format byte, without counting it as a hit or miss. A damaged file + /// is deleted; a missing one forgotten. + fn load(&self, kind: Kind, key: u128) -> Option<(u8, Vec)> { if !self.contains(kind, key) { - self.misses.fetch_add(1, Ordering::Relaxed); return None; } let path = self.path(kind, key); let data = std::fs::read(&path).ok(); - let ok = data.as_deref().and_then(|d| verify(d, kind)); - match ok { - Some(payload) => { - let payload = payload.to_vec(); - self.hits.fetch_add(1, Ordering::Relaxed); - if let Ok(mut g) = self.index.lock() { - g.touch(kind, key); - } - // Persist the recency for the next session (best effort). - if let Ok(f) = std::fs::File::options().append(true).open(&path) { - let _ = f.set_modified(std::time::SystemTime::now()); - } - Some(payload) - } - None => { - self.misses.fetch_add(1, Ordering::Relaxed); - // Gone (another process evicted it) or damaged: forget it. - if data.is_some() { - let _ = std::fs::remove_file(&path); - } - self.forget(kind, key); - None + let ok = data.as_deref().and_then(|d| Some((*d.get(5)?, verify(d, kind)?.to_vec()))); + if ok.is_none() { + // Gone (another process evicted it) or damaged: forget it. + if data.is_some() { + let _ = std::fs::remove_file(&path); } + self.forget(kind, key); } + ok + } + + /// Count a hit: the entry becomes the most recently used, also for the next session. + fn hit(&self, kind: Kind, key: u128) { + self.hits.fetch_add(1, Ordering::Relaxed); + if let Ok(mut g) = self.index.lock() { + g.touch(kind, key); + } + // Persist the recency for the next session (best effort). + if let Ok(f) = std::fs::File::options().append(true).open(self.path(kind, key)) { + let _ = f.set_modified(std::time::SystemTime::now()); + } + } + + /// An entry of `kind` and `format` whose source files are unchanged, decoded by `decode`, + /// with those files. An entry whose files changed, of the format before #3184, or damaged, + /// is a miss and is deleted (it renders again and is stored anew). A frame entry of the + /// other current frame format (8-bit and half-float frames have keys of their own) is a miss + /// and stays. + fn get_checked( + &self, + kind: Kind, + key: u128, + format: u8, + virtual_id: Option>, + decode: impl FnOnce(&[u8]) -> Option, + ) -> Option<(T, ReadFiles)> { + let miss = || { + self.misses.fetch_add(1, Ordering::Relaxed); + None + }; + // (before the file is read: the writer may finish a drop's sweep between the read and the + // check below, and a drop may start meanwhile) + let drops = self.drops_now(); + let Some((found, payload)) = self.load(kind, key) else { return miss() }; + if found != format { + let other_frame_format = kind == Kind::Frame && (found == FORMAT_RGBA8_FILES || found == FORMAT_F16_FILES); + if !other_frame_format { + self.discard(kind, key); + } + return miss(); + } + let Some((files, body)) = EntryFiles::decode(&payload) else { + self.discard(kind, key); + return miss(); + }; + self.file_checks.fetch_add(files.len() as u64, Ordering::Relaxed); + if self.made_of_dropped(&files, &drops) || !files.unchanged(virtual_id) { + self.discard(kind, key); + return miss(); + } + let Some(value) = decode(body) else { + self.discard(kind, key); + return miss(); + }; + self.hit(kind, key); + Some((value, files.to_read_files())) + } + + /// Source files looked at so far to check frame and layer entries before using them (one per + /// file a read entry lists; tests). + pub fn file_checks(&self) -> u64 { + self.file_checks.load(Ordering::Relaxed) + } + + /// A valid file whose payload does not decode: delete it, as a damaged one. + fn discard(&self, kind: Kind, key: u128) { + let _ = std::fs::remove_file(self.path(kind, key)); + self.forget(kind, key); } fn forget(&self, kind: Kind, key: u128) { @@ -515,26 +821,50 @@ impl DiskCache { } } - fn enqueue(&self, kind: Kind, key: u128, payload: Vec) { + /// Queue a write; `false` when it was dropped (a full queue). + fn enqueue(&self, kind: Kind, key: u128, payload: Vec) -> bool { + self.enqueue_format(kind, key, FORMAT_RGBA8, Payload::Encoded(payload), None) + } + + /// [`DiskCache::enqueue`] with the entry's header format byte. `made`: the source files of a + /// frame or layer entry and the drop generation its reads started at + /// ([`DiskCache::drop_generation`]); refused (`false`) when one of them was dropped since. + fn enqueue_format(&self, kind: Kind, key: u128, format: u8, payload: Payload, made: Option<(&EntryFiles, u64)>) -> bool { + let stale = |q: &Queue| made.is_some_and(|(files, since)| q.drops.stale(files.files().iter().map(|f| &f.path), since)); #[cfg(target_arch = "wasm32")] { - self.write_now(kind, key, &payload); + if self.queue.0.lock().is_ok_and(|q| stale(&q)) { + return false; + } + self.write_format(kind, key, format, &payload.encode()); + true } #[cfg(not(target_arch = "wasm32"))] { let (m, cv) = &*self.queue; - let Ok(mut q) = m.lock() else { return }; - if q.jobs.len() >= QUEUE_LIMIT { + let Ok(mut q) = m.lock() else { return false }; + if stale(&q) { + return false; + } + if q.full(kind, payload.len()) { self.dropped.fetch_add(1, Ordering::Relaxed); - return; + return false; + } + if kind == Kind::Frame { + q.pending_frames.insert(key); + q.frame_bytes = q.frame_bytes.saturating_add(payload.len()); + q.frames.push_back(Job::Write(kind, key, format, payload)); + } else { + q.job_bytes = q.job_bytes.saturating_add(payload.len()); + q.jobs.push_back(Job::Write(kind, key, format, payload)); } - q.jobs.push_back(Job::Write(kind, key, payload)); cv.notify_all(); + true } } /// Write an entry now (atomic rename), then evict down to the limit. - fn write_now(&self, kind: Kind, key: u128, payload: &[u8]) { + fn write_format(&self, kind: Kind, key: u128, format: u8, payload: &[u8]) { if self.contains(kind, key) { return; } @@ -544,7 +874,7 @@ impl DiskCache { self.write_failed(&e); return; } - let data = seal(kind, payload); + let data = seal_format(kind, format, payload); // An entry that cannot fit would be evicted straight away. if data.len() as u64 > self.limit_bytes() { return; @@ -588,37 +918,246 @@ impl DiskCache { } } + /// Delete the frame and layer entries made of any of `paths` (File ▸ Reload Footage: a file + /// replaced by one with the same size and modification time must be read again, which the + /// check on hit can't tell). The index knows keys, not files, so the writer thread reads the + /// files section at the start of each frame and layer entry (no pixels) and deletes the + /// entries that list one of `paths`, after the writes queued before (those are swept too); + /// until it is done, an entry made of one of them is a miss. Entries are deleted for good, + /// so they don't come back after a restart. Nothing else in the cache is touched. + /// + /// A render that was under way meanwhile may still offer an entry made of one of `paths` as + /// it was before: it is refused, see [`DiskCache::drop_generation`]. + pub fn drop_files(&self, paths: impl IntoIterator>>) { + let paths: Vec> = paths.into_iter().map(Into::into).collect(); + if paths.is_empty() { + return; + } + { + let mut d = self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for p in &paths { + let n = d.entry(p.clone()).or_default(); + *n = n.saturating_add(1); + } + } + #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] + let (m, cv) = &*self.queue; + match m.lock() { + Ok(mut q) => { + q.drops.record(&paths); + #[cfg(not(target_arch = "wasm32"))] + { + // (never refused for a full queue) + q.jobs.push_back(Job::Drop(paths)); + cv.notify_all(); + return; + } + } + // (no writer thread to take the job any more) + Err(poisoned) => poisoned.into_inner().drops.record(&paths), + } + self.sweep(&paths); + } + + /// The number of [`DiskCache::drop_files`] calls so far. A render takes it before it starts + /// reading and hands it to `put_frame` / `put_layer` with what it made: an entry listing a + /// file dropped after that is refused (the render may have read the file as it was before). + pub fn drop_generation(&self) -> u64 { + self.queue.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).drops.generation + } + + /// Whether one of `files` was dropped after generation `since` ([`DiskCache::drop_generation`]), + /// or after the earlier generation the list's own reads started at ([`ReadFiles::since`]: a + /// buffer made by an earlier render, from memory): what was made of them then is from before + /// the drop (shown, never stored). + pub fn dropped_since(&self, files: &ReadFiles, since: u64) -> bool { + let since = files.since().map_or(since, |s| s.min(since)); + self.queue.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).drops.stale(files.files().iter().map(|f| &f.path), since) + } + + /// Whether a [`DiskCache::drop_files`] is pending. + pub fn is_dropping(&self) -> bool { + !self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_empty() + } + + /// The drop generation and the files being dropped now, taken before an entry is read + /// (see [`DiskCache::made_of_dropped`]). + fn drops_now(&self) -> (u64, Vec>) { + let generation = self.drop_generation(); + let d = self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + (generation, d.keys().cloned().collect()) + } + + /// An entry read after [`DiskCache::drops_now`] gave `drops` that is made of a file whose + /// drop was pending then (its sweep may have ended since, after the entry was read) or that + /// was dropped since. + fn made_of_dropped(&self, files: &EntryFiles, drops: &(u64, Vec>)) -> bool { + let (since, pending) = drops; + let paths = || files.files().iter().map(|f| &f.path); + paths().any(|p| pending.contains(p)) || self.queue.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).drops.stale(paths(), *since) + } + + /// The writer's part of [`DiskCache::drop_files`]: delete the entries made of `paths`, then + /// end their drop. + fn sweep(&self, paths: &[Arc]) { + let set: std::collections::HashSet<&str> = paths.iter().map(|p| &**p).collect(); + for kind in [Kind::Frame, Kind::Layer] { + for key in self.keys(kind) { + if self.entry_files(kind, key).is_some_and(|f| f.files().iter().any(|f| set.contains(&*f.path))) { + self.discard(kind, key); + } + } + } + let mut d = self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for p in paths { + if let Some(n) = d.get_mut(p) { + *n = n.saturating_sub(1); + if *n == 0 { + d.remove(p); + } + } + } + } + + /// The source files a frame or layer entry lists, read from the start of its file (the + /// whole file only when the list is longer than that). `None` when it has none to read (an + /// earlier format, gone, damaged): such an entry is never used anyway. + fn entry_files(&self, kind: Kind, key: u128) -> Option { + use std::io::Read; + const HEAD: u64 = 64 << 10; + let parse = |d: &[u8]| { + let format = *d.get(5)?; + let ours = d.get(..4)? == MAGIC && *d.get(4)? == kind.tag(); + if !ours || !matches!(format, FORMAT_RGBA8_FILES | FORMAT_F16_FILES | FORMAT_LAYER_FILES) { + return None; + } + EntryFiles::decode(d.get(8..)?).map(|(files, _)| files) + }; + let path = self.path(kind, key); + let mut head = Vec::new(); + std::fs::File::open(&path).ok()?.take(HEAD).read_to_end(&mut head).ok()?; + parse(&head).or_else(|| if head.len() as u64 == HEAD { parse(&std::fs::read(&path).ok()?) } else { None }) + } + // ------------------------------------------------------------ typed entries - pub fn get_frame(&self, key: u128) -> Option { - let p = self.read(Kind::Frame, key)?; - decode_frame(&p) + /// An 8-bit frame whose source files are unchanged (see [`DiskCache::get_checked`]), with + /// those files; `None` for a half-float entry of that key, which + /// [`DiskCache::get_frame_f16`] reads. `virtual_id` names files served from memory. + pub fn get_frame(&self, key: u128, virtual_id: Option>) -> Option<(Frame8, ReadFiles)> { + self.get_checked(Kind::Frame, key, FORMAT_RGBA8_FILES, virtual_id, decode_frame) } - /// Queue a frame for writing (8-bit premultiplied RGBA, `width * height * 4` bytes). - pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8]) { - if self.contains(Kind::Frame, key) || rgba.len() != width as usize * height as usize * 4 { + /// A half-float frame (32 bpc viewer frames), as [`DiskCache::get_frame`]. + pub fn get_frame_f16(&self, key: u128, virtual_id: Option>) -> Option<(FrameF16, ReadFiles)> { + self.get_checked(Kind::Frame, key, FORMAT_F16_FILES, virtual_id, decode_frame_f16) + } + + /// Queue a half-float frame for writing (`width * height * 4` binary16 values) with the + /// source files it was made of. `true` when it is on disk or queued; `false` when refused + /// (wrong size, a full queue, no room on the disk, files that can't be checked later: see + /// [`EntryFiles::of`]; a file dropped after `since`, the [`DiskCache::drop_generation`] the + /// render started at). + #[allow(clippy::too_many_arguments)] + pub fn put_frame_f16( + &self, + key: u128, + width: u32, + height: u32, + rgba: &[u16], + files: &ReadFiles, + virtual_id: Option>, + since: u64, + ) -> bool { + if rgba.len() as u64 != width as u64 * height as u64 * 4 { + return false; + } + let Some(files) = EntryFiles::of(files, virtual_id) else { return false }; + if self.contains(Kind::Frame, key) { + return true; + } + // (no room on the disk: refused before the pixels are compressed) + if !self.accepts_writes() { + return false; + } + self.count_encode(); + let payload = with_files(&files, encode_frame_f16(width, height, rgba)); + self.enqueue_format(Kind::Frame, key, FORMAT_F16_FILES, Payload::Encoded(payload), Some((&files, since))) + } + + /// Write a half-float frame synchronously (tests); a list that can't be stored is not. + pub fn put_frame_f16_now(&self, key: u128, width: u32, height: u32, rgba: &[u16], files: &ReadFiles) { + if let Some(files) = EntryFiles::of(files, None) { + self.write_format(Kind::Frame, key, FORMAT_F16_FILES, &with_files(&files, encode_frame_f16(width, height, rgba))); + } + } + + /// Queue a frame for writing (8-bit premultiplied RGBA, `width * height * 4` bytes) with the + /// source files it was made of. `true` when it is on disk or queued; `false` when refused + /// (wrong size, a full queue, no room on the disk, files that can't be checked later: see + /// [`EntryFiles::of`]; a file dropped after `since`, the [`DiskCache::drop_generation`] the + /// render started at). + #[allow(clippy::too_many_arguments)] + pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8], files: &ReadFiles, virtual_id: Option>, since: u64) -> bool { + self.put_frame_owned(key, width, height, rgba.to_vec(), files, virtual_id, since) + } + + /// [`DiskCache::put_frame`] of a frame the caller hands over (no copy; compressed on the + /// writer thread). + #[allow(clippy::too_many_arguments)] + pub fn put_frame_owned( + &self, + key: u128, + width: u32, + height: u32, + rgba: Vec, + files: &ReadFiles, + virtual_id: Option>, + since: u64, + ) -> bool { + if rgba.len() as u64 != width as u64 * height as u64 * 4 { + return false; + } + let Some(files) = EntryFiles::of(files, virtual_id) else { return false }; + if self.contains(Kind::Frame, key) { + return true; + } + // (no room on the disk: refused before the pixels are queued and compressed) + if !self.accepts_writes() { + return false; + } + self.count_encode(); + let made = files.clone(); + self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, Payload::Frame(width, height, rgba, files), Some((&made, since))) + } + + /// A layer buffer (key: [`layer_disk_key`]) whose source files are unchanged, with those + /// files, as [`DiskCache::get_checked`]: an entry whose files changed, damaged, or of the + /// format before #3184 is a miss and is deleted, so the buffer renders again and replaces it. + /// `virtual_id` names files served from memory. + pub fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Buf, ReadFiles)> { + self.get_checked(Kind::Layer, key, FORMAT_LAYER_FILES, virtual_id, decode_layer) + } + + /// Queue a layer buffer for writing with the source files it was made of (see + /// [`EntryFiles::of`]: a buffer whose files can't all be named must not be stored). Refused + /// when one of them was dropped after `since`, the [`DiskCache::drop_generation`] its render + /// started at. + /// The buffer is shared, and encoded on the writer thread. + pub fn put_layer(&self, key: u128, buf: &Arc, files: &EntryFiles, since: u64) { + // (no room on the disk: refused before the buffer is queued and compressed) + if self.contains(Kind::Layer, key) || !self.accepts_writes() { return; } - self.enqueue(Kind::Frame, key, encode_frame(width, height, rgba)); + self.count_encode(); + let _ = self.enqueue_format(Kind::Layer, key, FORMAT_LAYER_FILES, Payload::Layer(buf.clone(), files.clone()), Some((files, since))); } - pub fn get_layer(&self, key: u128) -> Option { - let p = self.read(Kind::Layer, key)?; - decode_layer(&p) - } - - /// Queue a layer buffer for writing. - pub fn put_layer(&self, key: u128, buf: &Buf) { - if self.contains(Kind::Layer, key) { - return; + /// Write a layer buffer synchronously (tests); a list that can't be stored is not. + pub fn put_layer_now(&self, key: u128, buf: &Buf, files: &ReadFiles) { + if let Some(files) = EntryFiles::of(files, None) { + self.write_format(Kind::Layer, key, FORMAT_LAYER_FILES, &with_files(&files, encode_layer(buf))); } - self.enqueue(Kind::Layer, key, encode_layer(buf)); - } - - /// Write a layer buffer synchronously (tests). - pub fn put_layer_now(&self, key: u128, buf: &Buf) { - self.write_now(Kind::Layer, key, &encode_layer(buf)); } /// A segmentation (chain key, scale) written by [`DiskCache::put_seg`]. @@ -634,15 +1173,59 @@ impl DiskCache { if self.contains(Kind::Matte, k) { return; } - self.enqueue(Kind::Matte, k, lz4_flex::compress_prepend_size(&seg.to_bytes())); + let _ = self.enqueue(Kind::Matte, k, lz4_flex::compress_prepend_size(&seg.to_bytes())); } - /// Write a frame synchronously (tests). - pub fn put_frame_now(&self, key: u128, width: u32, height: u32, rgba: &[u8]) { - self.write_now(Kind::Frame, key, &encode_frame(width, height, rgba)); + /// Make the frame at key `from` the frame at key `to` too (an edit that can't change it gave + /// its comp a new content key): a hard link to the same file, or a copy where the file system + /// has no links. `false` when `from` isn't cached, `to` already is, or the file system + /// refused. (Entries don't contain their key, so the same file serves both.) + pub fn link_frame(&self, from: u128, to: u128) -> bool { + // (while files are being dropped, `from` may be made of one: it renders again instead) + if !self.contains(Kind::Frame, from) || self.contains(Kind::Frame, to) || self.is_dropping() { + return false; + } + let (src, dst) = (self.path(Kind::Frame, from), self.path(Kind::Frame, to)); + let Some(parent) = dst.parent() else { return false }; + let n = self.tmp_counter.fetch_add(1, Ordering::Relaxed); + let tmp = parent.join(format!("{to:032x}.tmp.{}.{n}", std::process::id())); + let linked = std::fs::create_dir_all(parent) + .and_then(|()| std::fs::hard_link(&src, &tmp).or_else(|_| std::fs::copy(&src, &tmp).map(|_| ()))) + .and_then(|()| std::fs::metadata(&tmp)) + .and_then(|m| std::fs::rename(&tmp, &dst).map(|()| m.len())); + let bytes = match linked { + Ok(bytes) => bytes, + Err(_) => { + // (gone meanwhile: another process evicted it) + let _ = std::fs::remove_file(&tmp); + return false; + } + }; + // (a link shares its file, but counts in full: the cache only ever errs small) + self.evict_to(self.limit_bytes().saturating_sub(bytes)); + if let Ok(mut g) = self.index.lock() { + g.insert(Kind::Frame, to, bytes); + } + true + } + + /// Write a frame synchronously (tests); a list that can't be stored is not. + pub fn put_frame_now(&self, key: u128, width: u32, height: u32, rgba: &[u8], files: &ReadFiles) { + if let Some(files) = EntryFiles::of(files, None) { + self.write_format(Kind::Frame, key, FORMAT_RGBA8_FILES, &with_files(&files, encode_frame(width, height, rgba))); + } } } +/// A frame or layer entry's payload: its source files, then its pixels. +fn with_files(files: &EntryFiles, pixels: Vec) -> Vec { + let mut out = Vec::with_capacity(pixels.len() + 64); + files.encode(&mut out); + out.extend_from_slice(&pixels); + out +} + +/// The writer thread: evicts to the limit at open, then drains the job queue until the cache is dropped. #[cfg(not(target_arch = "wasm32"))] fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { let (m, cv) = &*q; @@ -659,7 +1242,7 @@ fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { let job = { let Ok(mut g) = m.lock() else { return }; loop { - if let Some(j) = g.jobs.pop_front() { + if let Some(j) = g.pop() { g.busy = true; break j; } @@ -673,49 +1256,82 @@ fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { } }; let Some(cache) = dc.upgrade() else { return }; - match job { - Job::Write(kind, key, payload) => cache.write_now(kind, key, &payload), - } + let written = match job { + Job::Write(kind, key, format, payload) => { + cache.write_format(kind, key, format, &payload.encode()); + (kind == Kind::Frame).then_some(key) + } + Job::Drop(paths) => { + cache.sweep(&paths); + None + } + }; drop(cache); if let Ok(mut g) = m.lock() { g.busy = false; + if let Some(key) = written { + g.pending_frames.remove(&key); + } } cv.notify_all(); } } -/// An entry file's bytes: header (magic, kind), payload, checksum. -pub fn seal(kind: Kind, payload: &[u8]) -> Vec { +/// An entry file's bytes: header (magic, kind, the format byte: [`FORMAT_RGBA8`] for +/// segmentations, [`FORMAT_RGBA8_FILES`] / [`FORMAT_F16_FILES`] for frames, +/// [`FORMAT_LAYER_FILES`] for layer buffers), payload, checksum. +fn seal_format(kind: Kind, format: u8, payload: &[u8]) -> Vec { let mut data = Vec::with_capacity(payload.len() + 16); data.extend_from_slice(MAGIC); data.push(kind.tag()); - data.extend_from_slice(&[0, 0, 0]); + data.extend_from_slice(&[format, 0, 0]); data.extend_from_slice(payload); let sum = checksum(&data); data.extend_from_slice(&sum.to_le_bytes()); data } -/// A sealed frame entry ([`seal`] of the encoded frame): what the browser's frame workers -/// write to the Origin Private File System. -pub fn frame_entry(width: u32, height: u32, rgba: &[u8]) -> Vec { - seal(Kind::Frame, &encode_frame(width, height, rgba)) +/// A sealed 8-bit frame entry with the source files it was made of: what the browser's frame +/// workers write to the Origin Private File System. `None` when the frame must not be stored +/// (its files can't be checked later, see [`EntryFiles::of`]; or a wrong size). +pub fn frame_entry(width: u32, height: u32, rgba: &[u8], files: &ReadFiles, virtual_id: Option>) -> Option> { + if rgba.len() as u64 != width as u64 * height as u64 * 4 { + return None; + } + let files = EntryFiles::of(files, virtual_id)?; + Some(seal_format(Kind::Frame, FORMAT_RGBA8_FILES, &with_files(&files, encode_frame(width, height, rgba)))) } -/// A frame from a sealed entry's bytes (`None` when damaged). -pub fn read_frame_entry(data: &[u8]) -> Option { - decode_frame(verify(data, Kind::Frame)?) +/// The frame of a sealed entry's bytes, if its source files are unchanged. `None` when damaged, +/// of another format, or made of files that changed since: a miss, to be rendered again. +pub fn read_frame_entry(data: &[u8], virtual_id: Option>) -> Option { + let payload = verify(data, Kind::Frame)?; + if data.get(5) != Some(&FORMAT_RGBA8_FILES) { + return None; + } + let (files, pixels) = EntryFiles::decode(payload)?; + if !files.unchanged(virtual_id) { + return None; + } + decode_frame(pixels) } -/// A sealed layer-buffer entry: what the browser's frame workers write to the Origin Private -/// File System (`layers/<32 hex>.ecc`). -pub fn layer_entry(buf: &Buf) -> Vec { - seal(Kind::Layer, &encode_layer(buf)) +/// A sealed layer-buffer entry with the source files it was made of: what the browser's frame +/// workers write to the Origin Private File System (`layers/<32 hex>.ecc`). +pub fn layer_entry(buf: &Buf, files: &EntryFiles) -> Vec { + seal_format(Kind::Layer, FORMAT_LAYER_FILES, &with_files(files, encode_layer(buf))) } -/// A layer buffer from a sealed entry's bytes (`None` when damaged). -pub fn read_layer_entry(data: &[u8]) -> Option { - decode_layer(verify(data, Kind::Layer)?) +/// A layer buffer and its source files from a sealed entry's bytes (`None` when damaged or of +/// another format). The files are not looked at here: the store checks them when the buffer is +/// used ([`EntryFiles::unchanged`]). +pub fn read_layer_entry(data: &[u8]) -> Option<(Buf, EntryFiles)> { + let payload = verify(data, Kind::Layer)?; + if data.get(5) != Some(&FORMAT_LAYER_FILES) { + return None; + } + let (files, body) = EntryFiles::decode(payload)?; + Some((decode_layer(body)?, files)) } /// The disk key of a segmentation: its chain key and scale. @@ -737,11 +1353,20 @@ impl effectcraft_effects::roto::SegStore for DiskCache { } impl crate::cache::LayerStore for DiskCache { - fn get_layer(&self, key: u128) -> Option> { - DiskCache::get_layer(self, key).map(Arc::new) + /// The layer for `key` from the disk cache, or `None` when it is missing or stale. + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { + DiskCache::get_layer(self, key, virtual_id).map(|(b, f)| (Arc::new(b), f)) } - fn put_layer(&self, key: u128, buf: &Buf) { - DiskCache::put_layer(self, key, buf); + /// Queues a layer write on the disk cache. + fn put_layer(&self, key: u128, buf: &Arc, files: &EntryFiles, since: u64) { + DiskCache::put_layer(self, key, buf, files, since); + } + /// The current drop generation of the disk cache. + fn drop_generation(&self) -> u64 { + DiskCache::drop_generation(self) + } + fn dropped_since(&self, files: &ReadFiles, since: u64) -> bool { + DiskCache::dropped_since(self, files, since) } fn min_layer_ms(&self) -> u64 { DiskCache::min_layer_ms(self) @@ -788,6 +1413,46 @@ fn decode_frame(p: &[u8]) -> Option { (rgba.len() == w as usize * h as usize * 4).then_some(Frame8 { width: w, height: h, rgba }) } +/// Half floats with their low and high bytes in planes (per channel), then LZ4: the high bytes +/// (sign, exponent) repeat a lot, mixed with the low ones LZ4 finds little. +fn encode_frame_f16(w: u32, h: u32, rgba: &[u16]) -> Vec { + use rayon::prelude::*; + let n = rgba.len() / 4; + let mut planes = vec![0u8; n * 8]; + // Plane (byte k, channel c) at (k · 4 + c) · n. + planes.par_chunks_mut(n.max(1)).enumerate().for_each(|(plane, out)| { + let (k, c) = (plane / 4, plane % 4); + for (o, px) in out.iter_mut().zip(rgba.as_chunks::<4>().0) { + *o = px[c].to_le_bytes()[k]; + } + }); + let mut out = Vec::with_capacity(planes.len() / 3 + 16); + out.extend_from_slice(&w.to_le_bytes()); + out.extend_from_slice(&h.to_le_bytes()); + out.extend_from_slice(&lz4_flex::compress_prepend_size(&planes)); + out +} + +fn decode_frame_f16(p: &[u8]) -> Option { + if p.len() < 8 { + return None; + } + let w = u32::from_le_bytes(p[0..4].try_into().ok()?); + let h = u32::from_le_bytes(p[4..8].try_into().ok()?); + let n = (w as usize).checked_mul(h as usize)?; + let planes = lz4_flex::decompress_size_prepended(&p[8..]).ok()?; + if planes.len() != n.checked_mul(8)? { + return None; + } + let mut rgba = vec![0u16; n * 4]; + for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (c, v) in px.iter_mut().enumerate() { + *v = u16::from_le_bytes([planes[c * n + i], planes[(4 + c) * n + i]]); + } + } + Some(FrameF16 { width: w, height: h, rgba }) +} + fn encode_layer(b: &Buf) -> Vec { let (w, h) = (b.img.width, b.img.height); let n = b.img.data.len(); @@ -811,6 +1476,7 @@ fn encode_layer(b: &Buf) -> Vec { out } +/// Decodes a stored layer payload into a buffer, or `None` when it is too short or damaged. fn decode_layer(p: &[u8]) -> Option { if p.len() < 32 { return None; @@ -821,8 +1487,8 @@ fn decode_layer(p: &[u8]) -> Option { let offset = [f(8)?, f(16)?]; let scale = f(24)?; let planes = lz4_flex::decompress_size_prepended(&p[32..]).ok()?; - let n = w as usize * h as usize; - if planes.len() != n * 16 { + let n = (w as usize).checked_mul(h as usize)?; + if planes.len() != n.checked_mul(16)? { return None; } let mut img = Image::new(w, h); @@ -841,8 +1507,9 @@ fn decode_layer(p: &[u8]) -> Option { // ---------------------------------------------------------------- content keys /// Bump when rendering changes in a way that makes old disk entries wrong. -const RENDER_VERSION: &str = "effectcraft-render-5"; +const RENDER_VERSION: &str = "effectcraft-render-6"; +/// Feeds the `Debug` form of `v` into the hash, followed by a separator byte. fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { h.write(format!("{v:?}").as_bytes()); h.write(&[0xff]); @@ -851,124 +1518,96 @@ fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { /// Size and content hash of a path that has no native metadata (the browser file table). pub type VirtualFileId<'a> = &'a (dyn Fn(&str) -> Option<(u64, u64)> + Send + Sync); -/// A file's size and modification time (so edited footage gets new keys). When the path has no -/// native metadata, `virtual_id` supplies a durable size and content hash instead. -fn file_stamp(h: &mut Hash128, path: &str, virtual_id: Option>) { - if path.is_empty() { - return; - } - if let Ok(md) = std::fs::metadata(path) { - h.write_u64(md.len()); - if let Ok(t) = md.modified() - && let Ok(d) = t.duration_since(std::time::UNIX_EPOCH) - { - h.write_u64(d.as_nanos() as u64); - } - return; - } - if let Some((len, hash)) = virtual_id.and_then(|id| id(path)) { - h.write_u64(len); - h.write_u64(hash); - } -} +/// A [`VirtualFileId`] a cache can keep (the browser file table's identities). +pub type SharedVirtualFileId = Arc Option<(u64, u64)> + Send + Sync>; -fn footage_stamp(h: &mut Hash128, f: &effectcraft_project::Footage, virtual_id: Option>) { - file_stamp(h, &f.path, virtual_id); - for p in &f.sequence { - file_stamp(h, p, virtual_id); - } -} +/// Layer entries with their source files (#3184), part of every layer disk key: entries of the +/// earlier format (keyed by a project-wide footage salt instead) are never looked up again; +/// least recently used, they are evicted. +const LAYER_ENTRY_VERSION: &[u8] = b"layer-entry-files-2"; -/// Salt for layer cache keys on disk: the renderer version and every footage file's identity -/// (layer keys name footage items, not file contents). -pub fn footage_salt(project: &effectcraft_project::Project) -> u64 { - footage_salt_with(project, None) -} - -/// [`footage_salt`] with [`VirtualFileId`] for paths `std::fs::metadata` cannot describe. -pub fn footage_salt_with(project: &effectcraft_project::Project, virtual_id: Option>) -> u64 { +/// Disk key of a layer buffer: the layer cache's content key ([`crate::cache::layer_key`] and +/// the keys derived from it), the layer entry format and the renderer version. The content key +/// comes from memory alone: it names the footage items the buffer uses with their settings and +/// paths, so two projects only share an entry for the same pixels of the same files; whether +/// those files still hold what the buffer was made of is checked when the entry is read +/// ([`EntryFiles`]). No file is looked at here. +pub fn layer_disk_key(key: u64) -> u128 { let mut h = Hash128::default(); + h.write(LAYER_ENTRY_VERSION); h.write(RENDER_VERSION.as_bytes()); - for (id, it) in &project.items { - if let effectcraft_project::ItemKind::Footage(f) = &it.kind { - h.write_u64(id.0); - hash_debug(&mut h, f); - footage_stamp(&mut h, f, virtual_id); - } - } - let v = h.finish(); - (v as u64) ^ ((v >> 64) as u64) + h.write_u64(key); + h.finish() } -/// Content key of a composition's pixels: project render settings, the comp and everything it -/// uses (nested comps, footage, solids, their proxies and Use Proxy switches, footage and proxy -/// files' size and time). With expressions in play (which can read any comp) the whole project -/// counts. Switches that don't change pixels (Audio, Lock, Shy, Hide Shy Layers) don't count, and -/// neither do markers unless an expression mentions them. +/// Content key of a composition's pixels, from the project in memory alone (no file is looked +/// at: the frame entries check their own source files when read, see [`EntryFiles`]): project +/// render settings, the comp and the items it can draw (nested comps, footage items with their +/// settings and paths, solids, Media Replacement footage, their proxies and Use Proxy switches; +/// [`effectcraft_project::Project::pixel_reach`]). With expressions among them, everything those +/// expressions can read counts too: every layer of their comps, markers, the comps and footage +/// they name with literal names (and which items have those names), or the whole project when +/// they compute a name or reach items another way. An edit to an item the comp can't reach keeps +/// its key and its frames on disk (#3184, #1492). Switches that don't change pixels (Audio, Lock, +/// Shy, Hide Shy Layers) don't count, and neither do markers unless an expression can read them. pub fn comp_content_key(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId) -> u128 { - comp_content_key_with(project, comp, None) + comp_content_key_for_renderer(project, comp, RENDER_VERSION) } -/// [`comp_content_key`] with [`VirtualFileId`] for paths `std::fs::metadata` cannot describe. -pub fn comp_content_key_with(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId, virtual_id: Option>) -> u128 { - comp_content_key_for_renderer(project, comp, virtual_id, RENDER_VERSION) -} - -fn comp_content_key_for_renderer( - project: &effectcraft_project::Project, - comp: effectcraft_project::ItemId, - virtual_id: Option>, - renderer: &str, -) -> u128 { - use effectcraft_project::{ItemKind, LayerSource}; +/// The content key of `comp` for one renderer: its settings, the comps and footage it uses, and the renderer name. +fn comp_content_key_for_renderer(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId, renderer: &str) -> u128 { + use effectcraft_project::ItemKind; let mut h = Hash128::default(); h.write(renderer.as_bytes()); hash_debug(&mut h, &project.settings); - let mut seen = std::collections::BTreeSet::new(); - let mut stack = vec![comp]; - let mut expressions = false; - while let Some(id) = stack.pop() { - if !seen.insert(id) { - continue; - } - let Some(it) = project.item(id) else { continue }; - if let ItemKind::Comp(c) = &it.kind { - for l in &c.layers { - if let LayerSource::Comp { item } | LayerSource::Footage { item } | LayerSource::Solid { item } = l.source { - stack.push(item); - } - if !expressions { - l.props.walk("", &mut |_, p| expressions |= p.expr.is_some()); - } - } - } + let heard = project.heard_layers(); + let reach = project.pixel_reach(comp, &heard); + // Expressions can read any layer of the comps they reach, hidden or not, and their markers + // (#1083); without them, layers that can't change the picture (music, hidden layers nothing + // reads) don't count. + let expressions = reach.expressions; + let silent = |id, c: &effectcraft_project::Comp| if expressions { Default::default() } else { project.silent_layers(id, c, &heard) }; + // (the names expressions look items up by: which items have them now) + if !reach.names.is_empty() { + hash_debug(&mut h, &reach.names); } - // Markers are pixels only to the expressions that read them (#1083). - let markers = project.reads_markers(); - let ids: Vec = if expressions { project.items.keys().copied().collect() } else { seen.into_iter().collect() }; + let ids: Vec = match reach.items { + Some(items) => items.into_iter().collect(), + None => project.items.keys().copied().collect(), + }; for id in ids { let Some(it) = project.item(id) else { continue }; h.write_u64(id.0); h.write(it.name.as_bytes()); match &it.kind { - ItemKind::Comp(c) => hash_debug(&mut h, &c.pixel_form_with(markers)), + ItemKind::Comp(c) => { + let quiet = silent(id, c); + let heard = |l| heard.contains(id, l); + if quiet.is_empty() { + hash_debug(&mut h, &c.pixel_form_with(expressions, &heard)); + } else { + let mut pic = (**c).clone(); + pic.layers.retain(|l| !quiet.contains(&l.id)); + hash_debug(&mut h, &pic.pixel_form_with(expressions, &heard)); + } + } k => hash_debug(&mut h, k), } - if let ItemKind::Footage(f) = &it.kind { - footage_stamp(&mut h, f, virtual_id); - } hash_debug(&mut h, &it.proxy); - if let Some(px) = &it.proxy { - footage_stamp(&mut h, &px.footage, virtual_id); - } } h.write_u64(comp.0); h.finish() } +/// Frame entries with their source files (#3184), part of every frame key: entries of the +/// earlier format (keyed by footage stamps instead) are never looked up again; least recently +/// used, they are evicted. +const FRAME_ENTRY_VERSION: &[u8] = b"frame-entry-files-2"; + /// Disk key of one viewer frame. pub fn frame_key(content: u128, frame: i64, scale_milli: u32, view: u64) -> u128 { let mut h = Hash128::default(); + h.write(FRAME_ENTRY_VERSION); h.write(&content.to_le_bytes()); h.write_u64(frame as u64); h.write_u64(scale_milli as u64); @@ -986,6 +1625,26 @@ mod tests { d } + /// A linked frame reads back as the original under its new key, survives the original's + /// eviction, and is never linked over an existing entry or from a missing one. + #[test] + fn link_frame_serves_a_frame_under_a_new_key() { + let dc = DiskCache::open(tmpdir("link"), 1 << 30).unwrap(); + let rgba: Vec = (0..16).collect(); + dc.put_frame_now(1, 2, 2, &rgba, &ReadFiles::default()); + assert!(dc.link_frame(1, 2)); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).map(|f| f.rgba), Some(rgba.clone())); + assert!(!dc.link_frame(1, 2), "already there"); + assert!(!dc.link_frame(3, 4), "nothing to link"); + assert!(!dc.contains(Kind::Frame, 4)); + dc.put_frame_now(5, 2, 2, &[7; 16], &ReadFiles::default()); + assert!(!dc.link_frame(5, 2), "an existing entry stays"); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).map(|f| f.rgba), Some(rgba.clone())); + let _ = std::fs::remove_file(dc.path(Kind::Frame, 1)); + dc.forget(Kind::Frame, 1); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).map(|f| f.rgba), Some(rgba), "the link outlives the original"); + } + fn buf(seed: u32, w: u32, h: u32) -> Buf { let mut img = Image::new(w, h); for (i, p) in img.data.iter_mut().enumerate() { @@ -1018,17 +1677,63 @@ mod tests { #[test] fn frame_entries_round_trip_and_names_parse() { let rgba: Vec = (0..4 * 6 * 3).map(|i| (i * 7 % 256) as u8).collect(); - let e = frame_entry(6, 3, &rgba); - assert_eq!(read_frame_entry(&e), Some(Frame8 { width: 6, height: 3, rgba: rgba.clone() })); + let files: ReadFiles = [crate::reads::ReadFile::new("/v.png", crate::reads::FileStamp::Virtual)].into_iter().collect(); + let (one, two) = (|_: &str| Some((4, 1)), |_: &str| Some((4, 2))); + assert!(frame_entry(6, 3, &rgba, &files, None).is_none(), "a file from memory needs its identity"); + assert!(frame_entry(6, 3, &rgba[1..], &files, Some(&one)).is_none(), "a wrong size"); + let e = frame_entry(6, 3, &rgba, &files, Some(&one)).unwrap(); + assert_eq!(read_frame_entry(&e, Some(&one)), Some(Frame8 { width: 6, height: 3, rgba: rgba.clone() })); + assert!(read_frame_entry(&e, Some(&two)).is_none(), "the file changed"); + let mut incomplete = files.clone(); + incomplete.mark_incomplete(); + assert!(frame_entry(6, 3, &rgba, &incomplete, Some(&one)).is_none(), "an incomplete list is not stored"); let mut bad = e.clone(); bad[20] ^= 1; - assert!(read_frame_entry(&bad).is_none()); + assert!(read_frame_entry(&bad, Some(&one)).is_none()); + // An entry of the format before #3184 (pixels without files) is never read. + assert!(read_frame_entry(&seal_format(Kind::Frame, FORMAT_RGBA8, &encode_frame(6, 3, &rgba)), Some(&one)).is_none()); let key = 0x0123_4567_89ab_cdef_0011_2233_4455_6677u128; assert_eq!(parse_entry_name(&entry_name(key)), Some(key)); assert_eq!(parse_entry_name("abc.ecc"), None); assert_eq!(parse_entry_name(&format!("{key:032x}.tmp.1")), None); } + /// Half-float frames (32 bpc viewer frames) round-trip bit for bit, over-range values, + /// negatives and odd sizes included; they and 8-bit frames never read as each other; a + /// damaged half-float entry is a miss and is deleted; they count toward the size limit. + #[test] + fn half_float_frames_round_trip() { + let dir = tmpdir("f16"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let (w, h) = (7u32, 5u32); + // 4.0, 16.0, -0.25, 65504 and a spread of bit patterns. + let rgba: Vec = (0..w * h * 4).map(|i| [0x4400, 0x4c00, 0xb400, 0x7bff][i as usize % 4] ^ ((i * 37) as u16 & 0x03ff)).collect(); + dc.put_frame_f16_now(1, w, h, &rgba, &ReadFiles::default()); + assert_eq!(dc.get_frame_f16(1, None).map(|f| f.0), Some(FrameF16 { width: w, height: h, rgba: rgba.clone() })); + assert!(dc.get_frame(1, None).map(|f| f.0).is_none(), "not an 8-bit frame"); + dc.put_frame_now(2, 2, 2, &[9; 16], &ReadFiles::default()); + assert!(dc.get_frame_f16(2, None).map(|f| f.0).is_none() && dc.contains(Kind::Frame, 2), "an 8-bit entry stays valid"); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).unwrap().rgba, vec![9; 16]); + assert!(dc.stats().bytes > 0); + // Reopened, still there (format byte persisted). + drop(dc); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + assert_eq!(dc.get_frame_f16(1, None).map(|f| f.0).unwrap().rgba, rgba); + // A sealed entry with a payload of the wrong size: deleted on read. + let p = dc.path(Kind::Frame, 3); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, seal_format(Kind::Frame, FORMAT_F16_FILES, &with_files(&EntryFiles::default(), encode_frame_f16(w, h + 1, &rgba[..])))).unwrap(); + dc.rescan(); + assert!(dc.contains(Kind::Frame, 3)); + assert!(dc.get_frame_f16(3, None).map(|f| f.0).is_none()); + assert!(!dc.contains(Kind::Frame, 3) && !p.exists()); + // Wrong lengths are not written. + dc.put_frame_f16(4, w, h, &rgba[1..], &ReadFiles::default(), None, 0); + dc.flush(); + assert!(!dc.contains(Kind::Frame, 4)); + let _ = std::fs::remove_dir_all(&dir); + } + /// Segmentations round-trip by (chain key, scale), survive a reopen (rescan), are bounded by /// the size limit like every entry, and a damaged file is a miss. #[test] @@ -1065,21 +1770,124 @@ mod tests { fn hit_miss_and_exact_round_trip() { let dir = tmpdir("hit"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - assert!(dc.get_layer(42).is_none()); + assert!(dc.get_layer(42, None).is_none()); let b = buf(1, 33, 17); - dc.put_layer(42, &b); + dc.put_layer(42, &Arc::new(b.clone()), &EntryFiles::default(), 0); dc.flush(); - let back = dc.get_layer(42).unwrap(); + let (back, files) = dc.get_layer(42, None).unwrap(); + assert!(files.is_empty() && files.is_complete()); assert_eq!(back.img, b.img); assert_eq!((back.offset, back.scale), (b.offset, b.scale)); let rgba: Vec = (0..20 * 10 * 4).map(|i| (i % 251) as u8).collect(); - dc.put_frame(7, 20, 10, &rgba); + assert!(dc.put_frame(7, 20, 10, &rgba, &ReadFiles::default(), None, 0)); + assert!(!dc.put_frame(8, 2, 2, &[0; 3], &ReadFiles::default(), None, 0), "a wrong-size frame is refused"); + // Handed over and compressed on the writer thread: the same pixels come back. + assert!(dc.put_frame_owned(9, 20, 10, rgba.clone(), &ReadFiles::default(), None, 0)); + assert!(!dc.put_frame_owned(10, 2, 2, vec![0; 3], &ReadFiles::default(), None, 0), "a wrong-size frame is refused"); dc.flush(); - assert_eq!(dc.get_frame(7).unwrap().rgba, rgba); + assert_eq!(dc.get_frame(7, None).map(|f| f.0).unwrap().rgba, rgba); + assert_eq!(dc.get_frame(9, None).map(|f| f.0).unwrap().rgba, rgba); let st = dc.stats(); - assert_eq!((st.entries, st.hits, st.misses, st.writes), (2, 2, 1, 2)); + assert_eq!((st.entries, st.hits, st.misses, st.writes), (3, 3, 1, 3)); // Wrong kind is a miss. - assert!(dc.get_frame(42).is_none()); + assert!(dc.get_frame(42, None).map(|f| f.0).is_none()); + } + + /// Music doesn't change a comp's disk keys (adding it to the timeline kept no blue frame); + /// hiding a clip does. Importing music keeps them too. + #[test] + fn music_keeps_the_disk_keys() { + use effectcraft_project::{Comp, Footage, FootageKind, ItemKind, LayerSource, Project, Solid, build}; + use effectcraft_time::{FrameRate, Tick}; + let mut p = Project::default(); + let comp = Comp::new(64, 64, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let cid = p.add_item("Main", Default::default(), None, ItemKind::Comp(comp.clone().into())); + let sid = p.add_item("Solid", Default::default(), None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 64, height: 64, pixel_aspect: 1.0 })); + let clip = build::layer(&mut p, &comp, "Clip", LayerSource::Solid { item: sid }, (64, 64), None); + let clip_id = clip.id; + p.comp_mut(cid).unwrap().layers.push(clip); + let key = comp_content_key(&p, cid); + let song = p.add_item( + "song.wav", + Default::default(), + None, + ItemKind::Footage(Footage { kind: FootageKind::Audio, has_video: false, has_audio: true, ..Default::default() }), + ); + assert_eq!(comp_content_key(&p, cid), key, "importing music"); + let music = build::layer(&mut p, &comp, "Music", LayerSource::Footage { item: song }, (64, 64), None); + p.comp_mut(cid).unwrap().layers.insert(0, music); + assert_eq!(comp_content_key(&p, cid), key, "music on the timeline"); + p.comp_mut(cid).unwrap().layer_mut(clip_id).unwrap().switches.video = false; + assert_ne!(comp_content_key(&p, cid), key, "a hidden clip"); + } + + /// An expression that reads a 3D model layer's source (`thisComp.layer("Model").source.name`) + /// gives a new key when the model item is renamed: the frames on disk hold the old name. + #[test] + fn renaming_a_model_an_expression_reads_changes_the_disk_key() { + use effectcraft_project::{Comp, Expression, Footage, FootageKind, ItemKind, LayerSource, Project, Solid, build}; + use effectcraft_time::{FrameRate, Tick}; + let mut p = Project::default(); + let comp = Comp::new(64, 64, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let cid = p.add_item("Main", Default::default(), None, ItemKind::Comp(comp.clone().into())); + let model = p.add_item("chair.glb", Default::default(), None, ItemKind::Footage(Footage { kind: FootageKind::Model, ..Default::default() })); + let sid = p.add_item("Solid", Default::default(), None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 64, height: 64, pixel_aspect: 1.0 })); + let mut m = build::layer(&mut p, &comp, "Model", LayerSource::Model { item: model }, (64, 64), None); + m.switches.video = false; + let mut s = build::layer(&mut p, &comp, "Reader", LayerSource::Solid { item: sid }, (64, 64), None); + s.props.prop_mut("transform/opacity").unwrap().expr = + Some(Expression { text: "thisComp.layer(\"Model\").source.name.length * 10".into(), enabled: true }); + p.comp_mut(cid).unwrap().layers.extend([s, m]); + let key = comp_content_key(&p, cid); + p.item_mut(model).unwrap().name = "table.glb".into(); + assert_ne!(comp_content_key(&p, cid), key, "the expression reads the model's name"); + } + + /// Layer jobs hold float buffers until they are compressed: the queue holds at most + /// [`LAYER_QUEUE_BYTES`] of them (64 at 4K held ~8.5 GB), and a single bigger one only alone. + #[test] + fn layer_writes_queue_within_a_byte_budget() { + let mut q = Queue { + frames: Default::default(), + frame_bytes: 0, + jobs: Default::default(), + job_bytes: 0, + busy: true, + pending_frames: Default::default(), + drops: Drops::default(), + }; + let layer = LAYER_QUEUE_BYTES / 4 + 1; + for _ in 0..3 { + assert!(!q.full(Kind::Layer, layer)); + q.jobs.push_back(Job::Write(Kind::Layer, 0, 0, Payload::Encoded(vec![]))); + q.job_bytes += layer; + } + assert!(q.full(Kind::Layer, layer), "a fourth would pass the budget"); + assert!(!q.full(Kind::Frame, 1024), "frames have their own budget"); + let mut empty = Queue { jobs: Default::default(), job_bytes: 0, ..q }; + assert!(!empty.full(Kind::Layer, 2 * LAYER_QUEUE_BYTES), "a single big layer, alone"); + // Taking a job gives its bytes back. + empty.job_bytes = 3; + empty.jobs.push_back(Job::Write(Kind::Layer, 0, 0, Payload::Encoded(vec![0; 3]))); + assert!(empty.pop().is_some()); + assert_eq!(empty.job_bytes, 0); + } + + /// A burst of layer writes never crowds out frames: every frame of a fully cached comp is + /// on disk afterwards (the blue bar came back with gaps). + #[test] + fn frames_are_kept_when_layer_writes_fill_the_queue() { + let dir = tmpdir("burst"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + for k in 0..300 { + dc.put_layer(10_000 + k, &Arc::new(buf(1, 64, 64)), &EntryFiles::default(), 0); + } + let rgba = vec![7u8; 32 * 32 * 4]; + for k in 0..300 { + dc.put_frame(k, 32, 32, &rgba, &ReadFiles::default(), None, 0); + } + dc.flush(); + assert!((0..300).all(|k| dc.contains(Kind::Frame, k)), "every frame written"); } #[test] @@ -1091,17 +1899,17 @@ mod tests { let comp = Comp::new(2, 2, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); let id = project.add_item("Cached composition", effectcraft_color::Label::None, None, ItemKind::Comp(comp.into())); let key = frame_key(comp_content_key(&project, id), 0, 1000, 0); - let previous_key = frame_key(comp_content_key_for_renderer(&project, id, None, "effectcraft-render-4"), 0, 1000, 0); + let previous_key = frame_key(comp_content_key_for_renderer(&project, id, "effectcraft-render-5"), 0, 1000, 0); let dir = tmpdir("previous-renderer"); { let cache = DiskCache::open(&dir, 1 << 30).unwrap(); - cache.put_frame_now(previous_key, 2, 2, &[9; 16]); + cache.put_frame_now(previous_key, 2, 2, &[9; 16], &ReadFiles::default()); } let cache = DiskCache::open(&dir, 1 << 30).unwrap(); - assert_eq!(cache.get_frame(previous_key).unwrap().rgba, vec![9; 16]); - assert!(cache.get_frame(key).is_none()); - cache.put_frame_now(key, 2, 2, &[17; 16]); - assert_eq!(cache.get_frame(key).unwrap().rgba, vec![17; 16]); + assert_eq!(cache.get_frame(previous_key, None).map(|f| f.0).unwrap().rgba, vec![9; 16]); + assert!(cache.get_frame(key, None).map(|f| f.0).is_none()); + cache.put_frame_now(key, 2, 2, &[17; 16], &ReadFiles::default()); + assert_eq!(cache.get_frame(key, None).map(|f| f.0).unwrap().rgba, vec![17; 16]); } #[test] @@ -1109,16 +1917,16 @@ mod tests { let dir = tmpdir("persist"); { let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - dc.put_layer_now(1, &buf(1, 8, 8)); - dc.put_frame_now(2, 2, 2, &[9; 16]); + dc.put_layer_now(1, &buf(1, 8, 8), &ReadFiles::default()); + dc.put_frame_now(2, 2, 2, &[9; 16], &ReadFiles::default()); } let dc = DiskCache::open(&dir, 1 << 30).unwrap(); assert_eq!(dc.stats().entries, 2); assert!(dc.contains(Kind::Layer, 1) && dc.contains(Kind::Frame, 2)); - assert_eq!(dc.get_frame(2).unwrap().rgba, vec![9; 16]); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).unwrap().rgba, vec![9; 16]); dc.clear(); assert_eq!(dc.stats().entries, 0); - assert!(dc.get_frame(2).is_none()); + assert!(dc.get_frame(2, None).map(|f| f.0).is_none()); let again = DiskCache::open(&dir, 1 << 30).unwrap(); assert_eq!(again.stats().entries, 0); } @@ -1128,11 +1936,11 @@ mod tests { let dir = tmpdir("lru"); let dc = DiskCache::open(&dir, u64::MAX).unwrap(); for k in 0..6u128 { - dc.put_layer_now(k, &buf(k as u32, 64, 64)); + dc.put_layer_now(k, &buf(k as u32, 64, 64), &ReadFiles::default()); } let per = dc.stats().bytes / 6; // Touch 0 so it is the most recently used. - assert!(dc.get_layer(0).is_some()); + assert!(dc.get_layer(0, None).is_some()); dc.set_max_bytes(per * 3 + per * 3 / 4); let st = dc.stats(); assert!(st.bytes <= per * 3 + per * 3 / 4, "{st:?}"); @@ -1144,7 +1952,7 @@ mod tests { let files = walk(&dir); assert_eq!(files, 3); // New writes keep evicting. - dc.put_layer_now(99, &buf(9, 64, 64)); + dc.put_layer_now(99, &buf(9, 64, 64), &ReadFiles::default()); assert!(dc.stats().bytes <= per * 3 + per * 3 / 4); } @@ -1169,7 +1977,7 @@ mod tests { let dir = tmpdir("space"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); for k in 0..4u128 { - dc.put_layer_now(k, &buf(k as u32, 64, 64)); + dc.put_layer_now(k, &buf(k as u32, 64, 64), &ReadFiles::default()); } let used = dc.stats().bytes; // Unknown space: the setting alone. @@ -1178,17 +1986,18 @@ mod tests { // A disk reported as 0 bytes is unknown. dc.set_disk_space(Some((0, 0))); assert_eq!(dc.stats().limit_bytes, 1 << 30); - // 100 GB disk, 5 GB reserved, exactly 5 GB free: the cache may not grow. + // 100 GB disk, 5 GB reserved (5%, between the 2 GB floor and the 10 GB cap), exactly + // 5 GB free: the cache may not grow. dc.set_disk_space(Some((100 << 30, 5 << 30))); let st = dc.stats(); assert_eq!((st.max_bytes, st.limit_bytes), (1 << 30, used)); - dc.put_layer_now(9, &buf(9, 64, 64)); + dc.put_layer_now(9, &buf(9, 64, 64), &ReadFiles::default()); let st = dc.stats(); assert!(st.bytes <= st.limit_bytes && st.bytes <= used - used / 10 && st.evictions > 0, "{st:?}"); assert!(dc.contains(Kind::Layer, 9), "the new entry is the most recently used"); // Below the reserve the cache gives its space back, and skips writes that can't fit. dc.set_disk_space(Some((100 << 30, 4 << 30))); - dc.put_layer_now(10, &buf(10, 64, 64)); + dc.put_layer_now(10, &buf(10, 64, 64), &ReadFiles::default()); let st = dc.stats(); assert_eq!((st.limit_bytes, st.entries, st.bytes), (0, 0, 0), "{st:?}"); // Plenty of space again: back to the setting. @@ -1197,14 +2006,86 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// The reserve is 5% of the disk, at least 2 GB and at most 10 GB: a large disk with plenty + /// free keeps the user's size. (A 4 TB disk with 190 GB free reserved 200 GB, held a 20 GB + /// cache at 0, and every write was refused.) + #[test] + fn a_large_disk_reserves_at_most_ten_gb() { + const GB: u64 = 1 << 30; + assert_eq!(disk_reserve(4096 * GB), 10 * GB); + assert_eq!(disk_reserve(100 * GB), 5 * GB); + assert_eq!(disk_reserve(32 * GB), 2 * GB); + assert_eq!(disk_reserve(1), 2 * GB); + let dir = tmpdir("space-large"); + let dc = DiskCache::open(&dir, 20 * GB).unwrap(); + dc.set_disk_space(Some((4096 * GB, 190 * GB))); + let st = dc.stats(); + assert_eq!((st.max_bytes, st.limit_bytes), (20 * GB, 20 * GB), "{st:?}"); + assert!(dc.accepts_writes()); + assert_eq!(dc.reserve_bytes(), Some(10 * GB)); + // Just above the 10 GB reserve: the cache may use what is left above it. + dc.set_disk_space(Some((4096 * GB, 15 * GB))); + assert_eq!(dc.stats().limit_bytes, 5 * GB); + // A small disk still keeps 2 GB free: 3 GB free leaves 1 GB for the cache. + dc.set_disk_space(Some((32 * GB, 3 * GB))); + assert_eq!(dc.stats().limit_bytes, GB); + // Below the floor: nothing. + dc.set_disk_space(Some((32 * GB, GB))); + assert_eq!(dc.stats().limit_bytes, 0); + assert!(!dc.accepts_writes()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A write the free disk space refuses is refused before its pixels are compressed: the + /// frame workers spent about 8 ms per frame and 14 ms per layer encoding entries that were + /// then refused (`limit_bytes=0`). + #[test] + fn no_encode_while_the_disk_has_no_room() { + const GB: u64 = 1 << 30; + let dir = tmpdir("space-no-encode"); + let dc = DiskCache::open(&dir, 20 * GB).unwrap(); + // 4 TB disk, 1 GB free: under the 10 GB reserve, the limit is 0. + dc.set_disk_space(Some((4096 * GB, GB))); + assert_eq!(dc.stats().limit_bytes, 0); + let rgba = vec![7u8; 16 * 16 * 4]; + assert!(!dc.put_frame(1, 16, 16, &rgba, &ReadFiles::default(), None, 0), "refused"); + assert!(!dc.put_frame_f16(2, 16, 16, &[0x3c00u16; 16 * 16 * 4], &ReadFiles::default(), None, 0), "refused"); + dc.put_layer(3, &Arc::new(buf(3, 16, 16)), &EntryFiles::default(), 0); + dc.flush(); + assert_eq!(dc.encodes(), 0, "nothing compressed"); + assert_eq!(dc.stats().entries, 0); + // 32 MB of room above the reserve: a few frames would fill it, the rest would be + // compressed only to be refused. Not worth encoding either. + dc.set_disk_space(Some((4096 * GB, 10 * GB + (32 << 20)))); + assert_eq!(dc.stats().limit_bytes, 32 << 20); + assert!(!dc.accepts_writes()); + assert!(!dc.put_frame(1, 16, 16, &rgba, &ReadFiles::default(), None, 0), "refused"); + dc.put_layer(3, &Arc::new(buf(3, 16, 16)), &EntryFiles::default(), 0); + assert_eq!(dc.encodes(), 0, "nothing compressed"); + // A small limit the setting asks for (not free space) is used. + dc.set_disk_space(None); + dc.set_max_bytes(32 << 20); + assert!(dc.accepts_writes()); + dc.set_max_bytes(20 * GB); + // Room again: the same writes are compressed and stored. + dc.set_disk_space(Some((4096 * GB, 500 * GB))); + assert!(dc.put_frame(1, 16, 16, &rgba, &ReadFiles::default(), None, 0)); + assert!(dc.put_frame_f16(2, 16, 16, &[0x3c00u16; 16 * 16 * 4], &ReadFiles::default(), None, 0)); + dc.put_layer(3, &Arc::new(buf(3, 16, 16)), &EntryFiles::default(), 0); + dc.flush(); + assert_eq!(dc.encodes(), 3); + assert_eq!(dc.stats().entries, 3); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn failed_writes_are_counted() { let dir = tmpdir("failed"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); // A file where the layers folder should be: every layer write fails. std::fs::write(dir.join(VERSION).join(Kind::Layer.dir()), b"x").unwrap(); - dc.put_layer_now(1, &buf(1, 8, 8)); - dc.put_layer_now(2, &buf(2, 8, 8)); + dc.put_layer_now(1, &buf(1, 8, 8), &ReadFiles::default()); + dc.put_layer_now(2, &buf(2, 8, 8), &ReadFiles::default()); let st = dc.stats(); assert_eq!((st.failed, st.writes, st.entries), (2, 0, 0)); let _ = std::fs::remove_dir_all(&dir); @@ -1229,13 +2110,13 @@ mod tests { fn damaged_files_are_misses() { let dir = tmpdir("damaged"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - dc.put_frame_now(5, 4, 4, &[1; 64]); + dc.put_frame_now(5, 4, 4, &[1; 64], &ReadFiles::default()); let p = dc.path(Kind::Frame, 5); let mut d = std::fs::read(&p).unwrap(); let n = d.len(); d[n / 2] ^= 0xff; std::fs::write(&p, d).unwrap(); - assert!(dc.get_frame(5).is_none()); + assert!(dc.get_frame(5, None).map(|f| f.0).is_none()); assert!(!dc.contains(Kind::Frame, 5)); assert!(!p.exists()); } @@ -1253,8 +2134,8 @@ mod tests { for i in 0..20u128 { let k = i % 5; let w = if t % 2 == 0 { &a } else { &b }; - w.put_layer_now(k, &buf(k as u32, 16, 16)); - if let Some(x) = w.get_layer(k) { + w.put_layer_now(k, &buf(k as u32, 16, 16), &ReadFiles::default()); + if let Some((x, _)) = w.get_layer(k, None) { assert_eq!(x.img, buf(k as u32, 16, 16).img); } } @@ -1263,13 +2144,16 @@ mod tests { }); b.rescan(); for k in 0..5u128 { - assert_eq!(b.get_layer(k).unwrap().img, buf(k as u32, 16, 16).img); + assert_eq!(b.get_layer(k, None).unwrap().0.img, buf(k as u32, 16, 16).img); } } - /// A path with no native metadata takes its key from the caller's size and content hash (#1253). + /// Replaced bytes of a path with no native metadata (the browser file table) change neither + /// the comp key nor a layer's disk key (both from memory): the frame and layer entries made + /// of them check the hook's size and content hash when read and are misses, deleted (#1253, + /// #3184). #[test] - fn virtual_file_bytes_change_content_keys() { + fn virtual_file_bytes_are_checked_by_the_entries_not_the_keys() { use effectcraft_project::build; use effectcraft_project::{Comp, Footage, ItemKind, LayerSource, Project}; use effectcraft_time::{FrameRate, Tick}; @@ -1283,12 +2167,335 @@ mod tests { let id = |mark: u64| move |path: &str| (path == "/virtual.mov").then_some((8, mark)); let (one, two) = (id(1), id(2)); - let a = footage_salt_with(&p, Some(&one)); - let b = footage_salt_with(&p, Some(&two)); - let ka = comp_content_key_with(&p, cid, Some(&one)); - let kb = comp_content_key_with(&p, cid, Some(&two)); - assert_ne!(a, b, "replaced virtual media must not reuse the salt"); - assert_ne!(ka, kb, "replaced virtual media must not reuse the frame key"); - assert_eq!(comp_content_key(&p, cid), comp_content_key_with(&p, cid, None)); + let dc = DiskCache::open(tmpdir("virtual"), 1 << 30).unwrap(); + let k = frame_key(comp_content_key(&p, cid), 0, 1000, 0); + let files: ReadFiles = [crate::reads::ReadFile::new("/virtual.mov", crate::reads::FileStamp::Virtual)].into_iter().collect(); + assert!(dc.put_frame(k, 1, 1, &[1, 2, 3, 4], &files, Some(&one), 0)); + dc.flush(); + assert!(dc.get_frame(k, Some(&one)).is_some_and(|(_, f)| f == files)); + assert!(dc.get_frame(k, Some(&two)).is_none() && !dc.contains(Kind::Frame, k), "replaced: a miss, deleted"); + // A layer buffer made of it. + let lk = layer_disk_key(7); + dc.put_layer(lk, &Arc::new(buf(1, 4, 4)), &EntryFiles::of(&files, Some(&one)).unwrap(), 0); + dc.flush(); + assert!(dc.get_layer(lk, Some(&one)).is_some_and(|(b, f)| b.img == buf(1, 4, 4).img && f == files && f.is_complete())); + assert!(dc.get_layer(lk, None).is_none() && !dc.contains(Kind::Layer, lk), "no identity: a miss, deleted"); + dc.put_layer(lk, &Arc::new(buf(1, 4, 4)), &EntryFiles::of(&files, Some(&one)).unwrap(), 0); + dc.flush(); + assert!(dc.get_layer(lk, Some(&two)).is_none() && !dc.contains(Kind::Layer, lk), "replaced: a miss, deleted"); + // The browser's sealed layer entries carry the same list. + let e = layer_entry(&buf(2, 3, 2), &EntryFiles::of(&files, Some(&one)).unwrap()); + let (b, list) = read_layer_entry(&e).unwrap(); + assert!(b.img == buf(2, 3, 2).img && list.unchanged(Some(&one)) && !list.unchanged(Some(&two))); + assert!(read_layer_entry(&seal_format(Kind::Layer, FORMAT_RGBA8, &encode_layer(&buf(2, 3, 2)))).is_none(), "the format before #3184"); + let mut bad = e.clone(); + bad[12] ^= 1; + assert!(read_layer_entry(&bad).is_none(), "damaged"); + } + + /// Layer disk keys come from the layer cache's key alone (no file, no project-wide salt) and + /// differ per key. + #[test] + fn layer_disk_keys_need_no_files() { + assert_eq!(layer_disk_key(1), layer_disk_key(1)); + assert_ne!(layer_disk_key(1), layer_disk_key(2)); + // Not the layout of the salted keys before #3184 (`salt << 64 | key`). + assert_ne!(layer_disk_key(1) as u64, 1); + } + + /// A layer entry is used only while the files it lists are what the buffer was made of: a + /// new size, a new time, a missing file that is back, a file replaced by a folder, a damaged + /// files section and the format before #3184 are misses, and the entry is deleted so the + /// buffer is rendered and stored again. A buffer whose files can't all be named is not + /// stored. Only the listed files are looked at. + #[test] + fn layer_entries_check_their_files() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("layer-check"); + let src = dir.join("src"); + std::fs::create_dir_all(&src).unwrap(); + let file = |name: &str, bytes: &[u8]| { + let p = src.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png", b"aa"), file("b.png", b"bb")); + let gone = src.join("gone.png").to_string_lossy().to_string(); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap_or(FileStamp::Missing))).collect() }; + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.put_layer_now(1, &buf(1, 4, 4), &read(&[&a])); + dc.put_layer_now(2, &buf(2, 4, 4), &read(&[&b, &gone])); + dc.put_layer_now(3, &buf(3, 4, 4), &read(&[&b])); + let (one, files) = dc.get_layer(1, None).unwrap(); + assert!(one.img == buf(1, 4, 4).img && files == read(&[&a]) && files.is_complete()); + assert_eq!(dc.file_checks(), 1, "only the file of that buffer"); + // a.png gets a new size: entry 1 is a miss and deleted, the others stay. + std::fs::write(&a, b"aaa").unwrap(); + assert!(dc.get_layer(1, None).is_none() && !dc.contains(Kind::Layer, 1)); + assert!(dc.get_layer(2, None).is_some() && dc.get_layer(3, None).is_some()); + // b.png gets a new time only. + let t = std::fs::metadata(&b).unwrap().modified().unwrap() + std::time::Duration::from_secs(7); + std::fs::File::options().append(true).open(&b).unwrap().set_modified(t).unwrap(); + assert!(dc.get_layer(3, None).is_none() && !dc.contains(Kind::Layer, 3)); + assert!(dc.get_layer(2, None).is_none(), "b.png is listed there too"); + // A missing file that is back. + dc.put_layer_now(4, &buf(4, 4, 4), &read(&[&gone])); + assert!(dc.get_layer(4, None).is_some(), "missing, still missing"); + file("gone.png", b"g"); + assert!(dc.get_layer(4, None).is_none() && !dc.contains(Kind::Layer, 4), "back"); + // A file replaced by a folder (unreadable). + let c = file("c.png", b"cc"); + dc.put_layer_now(5, &buf(5, 4, 4), &read(&[&c])); + std::fs::remove_file(&c).unwrap(); + std::fs::create_dir(&c).unwrap(); + assert!(dc.get_layer(5, None).is_none() && !dc.contains(Kind::Layer, 5)); + // Written again after the miss: a hit with the new identity. + dc.put_layer_now(1, &buf(9, 4, 4), &read(&[&a])); + assert_eq!(dc.get_layer(1, None).map(|l| l.0.img), Some(buf(9, 4, 4).img)); + // The format before #3184 (no files): a miss, deleted. + dc.write_format(Kind::Layer, 6, FORMAT_RGBA8, &encode_layer(&buf(6, 4, 4))); + assert!(dc.contains(Kind::Layer, 6)); + assert!(dc.get_layer(6, None).is_none() && !dc.contains(Kind::Layer, 6)); + // A valid checksum over a damaged files section, or over a cut buffer: misses, deleted. + let mut payload = vec![]; + payload.extend_from_slice(&3u32.to_le_bytes()); + payload.extend_from_slice(&encode_layer(&buf(7, 4, 4))); + dc.write_format(Kind::Layer, 7, FORMAT_LAYER_FILES, &payload); + assert!(dc.get_layer(7, None).is_none() && !dc.contains(Kind::Layer, 7)); + let mut cut = vec![]; + EntryFiles::default().encode(&mut cut); + cut.extend_from_slice(&encode_layer(&buf(8, 4, 4))[..40]); + dc.write_format(Kind::Layer, 8, FORMAT_LAYER_FILES, &cut); + assert!(dc.get_layer(8, None).is_none() && !dc.contains(Kind::Layer, 8)); + // A damaged file on disk. + dc.put_layer_now(9, &buf(9, 4, 4), &ReadFiles::default()); + let p = dc.path(Kind::Layer, 9); + let mut d = std::fs::read(&p).unwrap(); + let n = d.len(); + d[n / 2] ^= 0xff; + std::fs::write(&p, d).unwrap(); + assert!(dc.get_layer(9, None).is_none() && !dc.contains(Kind::Layer, 9) && !p.exists()); + // Buffers whose files can't all be named are not stored. + let mut incomplete = read(&[&a]); + incomplete.mark_incomplete(); + dc.put_layer_now(10, &buf(10, 4, 4), &incomplete); + assert!(!dc.contains(Kind::Layer, 10)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A frame entry is used only while the files it lists are what it was made of: a new size, + /// a new time, a missing file that is back, a file replaced by a folder are misses, and the + /// entry is deleted so the frame is rendered and stored again. Only the listed files are + /// looked at. Entries of the format before #3184 are misses and deleted. + #[test] + fn frame_entries_check_their_files() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("check"); + let src = dir.join("src"); + std::fs::create_dir_all(&src).unwrap(); + let file = |name: &str, bytes: &[u8]| { + let p = src.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png", b"aa"), file("b.png", b"bb")); + let gone = src.join("gone.png").to_string_lossy().to_string(); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap_or(FileStamp::Missing))).collect() }; + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.put_frame_now(1, 1, 1, &[1; 4], &read(&[&a])); + dc.put_frame_now(2, 1, 1, &[2; 4], &read(&[&b, &gone])); + dc.put_frame_now(3, 1, 1, &[3; 4], &read(&[&b])); + assert_eq!(dc.get_frame(1, None).map(|f| f.1), Some(read(&[&a]))); + assert_eq!(dc.file_checks(), 1, "only the file of that frame"); + // a.png gets a new size: frame 1 is a miss and deleted, the others stay. + std::fs::write(&a, b"aaa").unwrap(); + assert!(dc.get_frame(1, None).is_none() && !dc.contains(Kind::Frame, 1)); + assert!(dc.get_frame(2, None).is_some() && dc.get_frame(3, None).is_some()); + // b.png gets a new time only. + let t = std::fs::metadata(&b).unwrap().modified().unwrap() + std::time::Duration::from_secs(7); + std::fs::File::options().append(true).open(&b).unwrap().set_modified(t).unwrap(); + assert!(dc.get_frame(3, None).is_none() && !dc.contains(Kind::Frame, 3)); + assert!(dc.get_frame(2, None).is_none(), "b.png is listed there too"); + // A missing file that is back. + dc.put_frame_now(4, 1, 1, &[4; 4], &read(&[&gone])); + assert!(dc.get_frame(4, None).is_some(), "missing, still missing"); + file("gone.png", b"g"); + assert!(dc.get_frame(4, None).is_none() && !dc.contains(Kind::Frame, 4), "back"); + // A file replaced by a folder (unreadable). + let c = file("c.png", b"cc"); + dc.put_frame_now(5, 1, 1, &[5; 4], &read(&[&c])); + std::fs::remove_file(&c).unwrap(); + std::fs::create_dir(&c).unwrap(); + assert!(dc.get_frame(5, None).is_none() && !dc.contains(Kind::Frame, 5)); + // Written again after the miss: a hit with the new identity. + let fresh = file("d.png", b"dd"); + dc.put_frame_now(1, 1, 1, &[9; 4], &read(&[&fresh])); + assert_eq!(dc.get_frame(1, None).map(|f| f.0.rgba), Some(vec![9; 4])); + // The format before #3184 (no files): a miss, deleted. + dc.write_format(Kind::Frame, 6, FORMAT_RGBA8, &encode_frame(1, 1, &[6; 4])); + assert!(dc.contains(Kind::Frame, 6)); + assert!(dc.get_frame(6, None).is_none() && !dc.contains(Kind::Frame, 6)); + // A valid checksum over a damaged files section: a miss, deleted. + let mut payload = vec![]; + payload.extend_from_slice(&3u32.to_le_bytes()); + payload.extend_from_slice(&encode_frame(1, 1, &[7; 4])); + dc.write_format(Kind::Frame, 7, FORMAT_RGBA8_FILES, &payload); + assert!(dc.get_frame(7, None).is_none() && !dc.contains(Kind::Frame, 7)); + // Frames whose files can't all be named are not stored. + let mut incomplete = read(&[&fresh]); + incomplete.mark_incomplete(); + assert!(!dc.put_frame(8, 1, 1, &[8; 4], &incomplete, None, 0)); + dc.flush(); + assert!(!dc.contains(Kind::Frame, 8)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Reload Footage drops the entries made of the reloaded files (#3184): a file replaced by + /// one with the same size and modification time passes the check on hit, so only the drop + /// makes the next use a miss. Entries of other files stay; an entry written after the drop + /// is used; a layer entry and one written while the drop waits in the queue are dropped too; + /// the drop survives a restart (the files are gone). + #[test] + fn dropped_files_take_their_entries_with_them() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("drop"); + let src = dir.join("src"); + std::fs::create_dir_all(&src).unwrap(); + let file = |name: &str, bytes: &[u8]| { + let p = src.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png", b"aa"), file("b.png", b"bb")); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap())).collect() }; + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.put_frame_now(1, 1, 1, &[1; 4], &read(&[&a])); + dc.put_frame_now(2, 1, 1, &[2; 4], &read(&[&b])); + dc.put_frame_now(3, 1, 1, &[3; 4], &read(&[&a, &b])); + dc.put_layer_now(4, &buf(4, 2, 2), &read(&[&a])); + // a.png gets other bytes of the same size and its old time back: the check can't tell. + let t = std::fs::metadata(&a).unwrap().modified().unwrap(); + std::fs::write(&a, b"AA").unwrap(); + std::fs::File::options().append(true).open(&a).unwrap().set_modified(t).unwrap(); + assert!(dc.get_frame(1, None).is_some(), "same size and time: still a hit"); + // A frame queued (not written yet) when the drop comes is dropped too. + assert!(dc.put_frame(5, 1, 1, &[5; 4], &read(&[&a]), None, 0)); + dc.drop_files([a.clone()]); + dc.flush(); + assert!(!dc.is_dropping()); + for (kind, key) in [(Kind::Frame, 1), (Kind::Frame, 3), (Kind::Layer, 4), (Kind::Frame, 5)] { + assert!(!dc.contains(kind, key), "{kind:?} {key} made of a.png is gone"); + } + assert!(dc.get_frame(1, None).is_none() && dc.get_layer(4, None).is_none()); + assert_eq!(dc.get_frame(2, None).map(|f| f.0.rgba), Some(vec![2; 4]), "b.png's frame stays"); + // Written again from the reloaded file: used. + dc.put_frame_now(1, 1, 1, &[9; 4], &read(&[&a])); + assert_eq!(dc.get_frame(1, None).map(|f| f.0.rgba), Some(vec![9; 4])); + // The drop is for good: a new session on the folder finds what is left. + drop(dc); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + assert_eq!(dc.keys(Kind::Frame).into_iter().collect::>(), [1, 2].into()); + assert!(dc.keys(Kind::Layer).is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A render under way when Reload Footage drops its files offers its entries after the drop + /// (#3184), when the writer has already deleted the old ones: made of the files as they were, + /// they are refused, frames and layer buffers alike. What the same render made of other files + /// is stored, and so is what a render that started after the drop makes. + #[test] + fn entries_made_before_a_drop_are_refused_after_it() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("drop-in-flight"); + std::fs::create_dir_all(&dir).unwrap(); + let file = |name: &str| { + let p = dir.join(name); + std::fs::write(&p, name.as_bytes()).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png"), file("b.png")); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap())).collect() }; + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + // The render starts (and reads a.png and b.png), then a.png is reloaded. + let before = dc.drop_generation(); + dc.drop_files([a.clone()]); + dc.flush(); + assert!(!dc.is_dropping()); + assert!(dc.dropped_since(&read(&[&a]), before) && !dc.dropped_since(&read(&[&b]), before)); + assert!(!dc.put_frame(1, 1, 1, &[1; 4], &read(&[&a, &b]), None, before), "a frame from before the drop"); + assert!(!dc.put_frame_f16(2, 1, 1, &[1; 4], &read(&[&a]), None, before)); + dc.put_layer(3, &Arc::new(buf(3, 2, 2)), &EntryFiles::of(&read(&[&a]), None).unwrap(), before); + assert!(dc.put_frame(4, 1, 1, &[4; 4], &read(&[&b]), None, before), "b.png wasn't dropped"); + dc.flush(); + assert!(!dc.contains(Kind::Frame, 1) && !dc.contains(Kind::Frame, 2) && !dc.contains(Kind::Layer, 3)); + assert!(dc.get_frame(1, None).is_none() && dc.get_layer(3, None).is_none()); + assert_eq!(dc.get_frame(4, None).map(|f| f.0.rgba), Some(vec![4; 4])); + // A render that starts after the drop reads the reloaded file: stored and served. + let after = dc.drop_generation(); + assert!(after > before && !dc.dropped_since(&read(&[&a]), after)); + assert!(dc.put_frame(5, 1, 1, &[5; 4], &read(&[&a]), None, after)); + dc.put_layer(6, &Arc::new(buf(6, 2, 2)), &EntryFiles::of(&read(&[&a]), None).unwrap(), after); + dc.flush(); + assert_eq!(dc.get_frame(5, None).map(|f| f.0.rgba), Some(vec![5; 4])); + assert!(dc.get_layer(6, None).is_some()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The record of dropped files is bounded: past it, everything made before the drop that + /// forgot the record is refused, and what is made after it is stored. + #[test] + fn the_record_of_dropped_files_is_bounded() { + let mut d = Drops::default(); + let a: Arc = "/a.png".into(); + d.record(std::slice::from_ref(&a)); + assert!(d.stale([&a].into_iter(), 0) && !d.stale([&a].into_iter(), 1)); + let many: Vec> = (0..=MAX_DROPPED_PATHS).map(|i| format!("/f{i}").into()).collect(); + d.record(&many); + assert!(d.last.is_empty(), "forgotten, not grown"); + let other: Arc = "/other.png".into(); + assert!(d.stale([&other].into_iter(), 1), "made before the drop that forgot the record"); + assert!(!d.stale([&a].into_iter(), 2), "made after it"); + } + + /// While a drop waits, an entry made of a dropped file is a miss (and deleted), and frames + /// aren't linked to new keys. + #[test] + fn entries_of_a_pending_drop_are_misses() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("drop-pending"); + std::fs::create_dir_all(&dir).unwrap(); + let a = dir.join("a.png"); + std::fs::write(&a, b"aa").unwrap(); + let a = a.to_string_lossy().to_string(); + let files: ReadFiles = [ReadFile::new(a.as_str(), FileStamp::native(&a).unwrap())].into_iter().collect(); + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + dc.put_frame_now(1, 1, 1, &[1; 4], &files); + dc.dropping.lock().unwrap().insert(a.as_str().into(), 1); + assert!(!dc.link_frame(1, 2)); + assert!(dc.get_frame(1, None).is_none() && !dc.contains(Kind::Frame, 1)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// An entry read while its file's drop was pending is a miss even when the writer ends the + /// sweep between the read and the check (it deleted the file, but its bytes were read), and + /// so is one read before a drop that starts meanwhile. Found under load: a stale hit. + #[test] + fn a_sweep_ending_during_a_read_never_makes_a_hit() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("drop-race"); + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + let files = EntryFiles::of(&[ReadFile::new("/a.png", FileStamp::Missing)].into_iter().collect(), None).unwrap(); + // Read while the drop is pending; the sweep ends before the check. + dc.dropping.lock().unwrap().insert("/a.png".into(), 1); + let drops = dc.drops_now(); + dc.dropping.lock().unwrap().clear(); + assert!(dc.made_of_dropped(&files, &drops)); + // Read before a drop that starts (and ends) before the check. + let drops = dc.drops_now(); + dc.drop_files(["/a.png"]); + dc.flush(); + assert!(dc.made_of_dropped(&files, &drops)); + assert!(!dc.made_of_dropped(&files, &dc.drops_now()), "read after the drop: used"); + let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/render/src/disk_cache/entry_files.rs b/crates/render/src/disk_cache/entry_files.rs new file mode 100644 index 000000000..a36ca1033 --- /dev/null +++ b/crates/render/src/disk_cache/entry_files.rs @@ -0,0 +1,276 @@ +//! The source files a frame entry on disk was made of (#3184): stored with the pixels, checked +//! when the entry is used. Only the files that frame read are looked at, never every file of the +//! project. +//! +//! Layout (little endian), before the frame's pixel payload: +//! `u32 count`, then per file `u32 path length`, the path (UTF-8), a tag byte and its fields: +//! `0` a file on disk (`u64 size`, `u8 has time`, `i128 time`: nanoseconds since the Unix epoch, +//! negative before it), `1` bytes from the browser's file table (`u64 size`, `u64 content +//! hash`), `2` a file that could not be read. + +use std::sync::Arc; + +use super::VirtualFileId; +use crate::reads::{FileStamp, MAX_READ_FILES, ReadFile, ReadFiles}; + +/// Longest path an entry stores (bytes): a longer one is not a path this app opened. +const MAX_PATH_BYTES: usize = 1 << 16; + +/// A file's identity as a frame entry keeps it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EntryStamp { + /// Size and modification time (nanoseconds since the Unix epoch, negative before it) on + /// disk. + Native { len: u64, modified: Option }, + /// Size and content hash from the [`VirtualFileId`] hook (the browser's file table). + Virtual { len: u64, hash: u64 }, + /// It could not be read when the frame was made: it still must not be readable. + Missing, +} + +/// One file of a frame entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EntryFile { + pub path: Arc, + pub stamp: EntryStamp, +} + +/// Every file a frame entry was made of. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EntryFiles(Vec); + +impl EntryFiles { + /// The list to store for a frame that read `files`: `None` when the frame can't be checked + /// against its files later (the list is incomplete, or a file from memory has no identity), + /// so the frame must not be stored. Native stamps are the ones the files were read with, + /// never a fresh look at the disk (a file changed during the render keeps the old one). + pub fn of(files: &ReadFiles, virtual_id: Option>) -> Option { + if !files.is_complete() { + return None; + } + let mut out = Vec::with_capacity(files.len()); + for f in files.files() { + let stamp = match f.stamp { + FileStamp::Native { len, modified } => EntryStamp::Native { len, modified }, + FileStamp::Virtual => { + let (len, hash) = virtual_id.and_then(|id| id(&f.path))?; + EntryStamp::Virtual { len, hash } + } + FileStamp::Missing => EntryStamp::Missing, + }; + out.push(EntryFile { path: f.path.clone(), stamp }); + } + Some(EntryFiles(out)) + } + + /// The listed files. + pub fn files(&self) -> &[EntryFile] { + &self.0 + } + + /// The number of listed files. + pub fn len(&self) -> usize { + self.0.len() + } + + /// Whether no files are listed. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The files as a render reports them (to keep with the frame in memory). + pub fn to_read_files(&self) -> ReadFiles { + self.0 + .iter() + .map(|f| { + let stamp = match f.stamp { + EntryStamp::Native { len, modified } => FileStamp::Native { len, modified }, + EntryStamp::Virtual { .. } => FileStamp::Virtual, + EntryStamp::Missing => FileStamp::Missing, + }; + ReadFile::new(f.path.clone(), stamp) + }) + .collect() + } + + /// Whether every file still is what the frame was made of: one `metadata` call per file + /// (and the hook for files from memory). + pub fn unchanged(&self, virtual_id: Option>) -> bool { + self.0.iter().all(|f| file_unchanged(f, virtual_id)) + } + + /// Appends the list to `out` in little-endian binary form. + pub(super) fn encode(&self, out: &mut Vec) { + out.extend_from_slice(&(self.0.len() as u32).to_le_bytes()); + for f in &self.0 { + out.extend_from_slice(&(f.path.len() as u32).to_le_bytes()); + out.extend_from_slice(f.path.as_bytes()); + match f.stamp { + EntryStamp::Native { len, modified } => { + out.push(0); + out.extend_from_slice(&len.to_le_bytes()); + out.push(u8::from(modified.is_some())); + out.extend_from_slice(&modified.unwrap_or(0).to_le_bytes()); + } + EntryStamp::Virtual { len, hash } => { + out.push(1); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&hash.to_le_bytes()); + } + EntryStamp::Missing => out.push(2), + } + } + } + + /// The list at the start of `p` and what follows it; `None` when it is damaged. + pub(super) fn decode(p: &[u8]) -> Option<(EntryFiles, &[u8])> { + let mut r = Reader(p); + let n = r.u32()? as usize; + if n > MAX_READ_FILES { + return None; + } + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let len = r.u32()? as usize; + if len > MAX_PATH_BYTES { + return None; + } + let path: Arc = std::str::from_utf8(r.take(len)?).ok()?.into(); + let stamp = match r.u8()? { + 0 => { + let len = r.u64()?; + let has = r.u8()?; + let t = r.i128()?; + match has { + 0 => EntryStamp::Native { len, modified: None }, + 1 => EntryStamp::Native { len, modified: Some(t) }, + _ => return None, + } + } + 1 => EntryStamp::Virtual { len: r.u64()?, hash: r.u64()? }, + 2 => EntryStamp::Missing, + _ => return None, + }; + out.push(EntryFile { path, stamp }); + } + Some((EntryFiles(out), r.0)) + } +} + +/// Whether the file still matches its stored stamp, by its native stamp or by its in-memory identity. +fn file_unchanged(f: &EntryFile, virtual_id: Option>) -> bool { + let from_memory = || virtual_id.and_then(|id| id(&f.path)); + match f.stamp { + EntryStamp::Native { len, modified } => FileStamp::native(&f.path) == Some(FileStamp::Native { len, modified }), + EntryStamp::Virtual { len, hash } => from_memory() == Some((len, hash)), + // (a folder at the path is still not a file to read) + EntryStamp::Missing => !std::fs::metadata(&*f.path).is_ok_and(|m| m.is_file()) && from_memory().is_none(), + } +} + +/// Reads little-endian fields off the front of a byte slice. +struct Reader<'a>(&'a [u8]); + +impl<'a> Reader<'a> { + /// Takes the next `n` bytes, or `None` when fewer remain. + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let head = self.0.get(..n)?; + self.0 = self.0.get(n..)?; + Some(head) + } + /// Reads one byte. + fn u8(&mut self) -> Option { + self.take(1)?.first().copied() + } + /// Reads a little-endian `u32`. + fn u32(&mut self) -> Option { + Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } + /// Reads a little-endian `u64`. + fn u64(&mut self) -> Option { + Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?)) + } + /// Reads a little-endian `i128`. + fn i128(&mut self) -> Option { + Some(i128::from_le_bytes(self.take(16)?.try_into().ok()?)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A sample list of native, missing and virtual files for the tests. + fn files() -> ReadFiles { + [ + ReadFile::new("/a.png", FileStamp::Native { len: 3, modified: Some(9) }), + ReadFile::new("/b.png", FileStamp::Native { len: 4, modified: None }), + // Before 1970, and past where `u64` nanoseconds end (2554). + ReadFile::new("/d.png", FileStamp::Native { len: 5, modified: Some(-86_400_000_000_000) }), + ReadFile::new("/e.png", FileStamp::Native { len: 6, modified: Some(i128::from(u64::MAX) + 1) }), + ReadFile::new("/c.png", FileStamp::Missing), + ReadFile::new("/v.mov", FileStamp::Virtual), + ] + .into_iter() + .collect() + } + + #[test] + fn lists_round_trip_and_damage_is_caught() { + let id = |p: &str| (p == "/v.mov").then_some((8, 77)); + let list = EntryFiles::of(&files(), Some(&id)).unwrap(); + assert_eq!(list.files()[5].stamp, EntryStamp::Virtual { len: 8, hash: 77 }); + let mut bytes = vec![]; + list.encode(&mut bytes); + bytes.extend_from_slice(b"rest"); + let (back, rest) = EntryFiles::decode(&bytes).unwrap(); + assert_eq!((back, rest), (list.clone(), &b"rest"[..])); + assert_eq!(list.to_read_files(), files()); + // Every truncation is caught (never a panic, never a shorter list). + let mut plain = vec![]; + list.encode(&mut plain); + for n in 0..plain.len() { + assert!(EntryFiles::decode(&plain[..n]).is_none(), "cut at {n}"); + } + // Bad tags and counts. + let mut bad = plain.clone(); + bad[0..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(EntryFiles::decode(&bad).is_none()); + } + + #[test] + fn frames_that_cant_be_checked_are_not_stored() { + let mut incomplete = files(); + incomplete.mark_incomplete(); + let id = |_: &str| Some((1, 1)); + assert!(EntryFiles::of(&incomplete, Some(&id)).is_none(), "an incomplete list"); + assert!(EntryFiles::of(&files(), None).is_none(), "a file from memory without the hook"); + assert!(EntryFiles::of(&ReadFiles::default(), None).is_some_and(|l| l.is_empty()), "a frame that reads no file"); + } + + #[test] + fn the_check_looks_at_the_listed_files() { + let dir = std::env::temp_dir().join(format!("effectcraft-entry-files-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join("f.bin"); + std::fs::write(&p, b"abc").unwrap(); + let path = p.to_string_lossy().to_string(); + let gone = dir.join("gone.bin").to_string_lossy().to_string(); + let stamp = FileStamp::native(&path).unwrap(); + let read: ReadFiles = [ReadFile::new(path.as_str(), stamp), ReadFile::new(gone.as_str(), FileStamp::Missing)].into_iter().collect(); + let list = EntryFiles::of(&read, None).unwrap(); + assert!(list.unchanged(None)); + std::fs::write(&p, b"abcd").unwrap(); + assert!(!list.unchanged(None), "a new size"); + std::fs::write(&gone, b"x").unwrap(); + let list = EntryFiles::of(&[ReadFile::new(gone.as_str(), FileStamp::Missing)].into_iter().collect(), None).unwrap(); + assert!(!list.unchanged(None), "a missing file that is back"); + let v: ReadFiles = [ReadFile::new("/v", FileStamp::Virtual)].into_iter().collect(); + let one = |_: &str| Some((1, 1)); + let two = |_: &str| Some((1, 2)); + let list = EntryFiles::of(&v, Some(&one)).unwrap(); + assert!(list.unchanged(Some(&one)) && !list.unchanged(Some(&two)) && !list.unchanged(None)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/render/src/eval.rs b/crates/render/src/eval.rs index 81fe45d6c..41e6132d3 100644 --- a/crates/render/src/eval.rs +++ b/crates/render/src/eval.rs @@ -44,11 +44,15 @@ pub struct EvalCtx<'a> { /// Media Replacement values overridden by the Essential Properties of a collapsed precomp /// instance. pub media_overrides: &'a [crate::MediaOverride], + /// Where the source files of what expressions render (`sampleImage`) are noted: the + /// renderer's [`Renderer::reads`](crate::Renderer::reads) while rendering. + pub reads: Option<&'a crate::reads::ReadLog>, } impl<'a> EvalCtx<'a> { + /// A context for `comp` at `time` with no expressions, footage, overrides or read log. pub fn new(project: &'a Project, comp_id: ItemId, comp: &'a Comp, time: Tick) -> EvalCtx<'a> { - EvalCtx { project, comp_id, comp, time, expr: None, footage: None, property_overrides: &[], media_overrides: &[] } + EvalCtx { project, comp_id, comp, time, expr: None, footage: None, property_overrides: &[], media_overrides: &[], reads: None } } pub fn at(&self, time: Tick) -> EvalCtx<'a> { EvalCtx { time, ..*self } @@ -203,13 +207,7 @@ impl<'a> EvalCtx<'a> { // Auto-orient (along path / towards camera) replaces Orientation. let orient = crate::three_d::camera::auto_orient_3d(self, layer, p) .unwrap_or_else(|| Mat4::orientation(Vec3::from(self.v3(layer, tr, "orientation", [0.0; 3])))); - Mat4::translate(p) - * orient - * Mat4::rotate_z(rz) - * Mat4::rotate_y(ry) - * Mat4::rotate_x(rx) - * Mat4::scale(Vec3::from(scale) / 100.0) - * Mat4::translate(-Vec3::from(anchor)) + Mat4::translate(p) * orient * Mat4::rotation_xyz(rx, ry, rz) * Mat4::scale(Vec3::from(scale) / 100.0) * Mat4::translate(-Vec3::from(anchor)) } /// Layer space → comp (world) space, including parents. @@ -384,6 +382,24 @@ fn effect_bounds_of(comp: &Comp, size: (u32, u32)) -> ([f64; 2], [f64; 2]) { } } +/// The layer's source time range in layer time seconds as (first, end) for +/// [`effectcraft_effects::EffectEnv::layer_span`]: footage and nested comps last their item's +/// duration from layer time 0. With Time Remap layer time is no longer source time, so the layer's +/// visible span (in to out point, in layer time) is reported instead. `None` for sources without +/// a duration (stills, solids, text, shapes...). +pub fn layer_span(project: &Project, layer: &Layer) -> Option<(f64, f64)> { + let span = if layer.props.get("timeRemap").is_some() { + let (a, b) = (layer.layer_time(layer.in_point).seconds(), layer.layer_time(layer.out_point).seconds()); + (a.min(b), a.max(b)) + } else { + match &layer.source { + LayerSource::Footage { item } | LayerSource::Comp { item } => (0.0, project.item(*item)?.duration()?.seconds()), + _ => return None, + } + }; + (span.0.is_finite() && span.1.is_finite() && span.1 > span.0).then_some(span) +} + /// Size of a layer's source in layer pixels. pub fn source_size(project: &Project, layer: &Layer) -> (u32, u32) { match &layer.source { diff --git a/crates/render/src/footage.rs b/crates/render/src/footage.rs index db1561ad6..c14961d0f 100644 --- a/crates/render/src/footage.rs +++ b/crates/render/src/footage.rs @@ -1,4 +1,5 @@ use super::{Arc, AtomicBool, Footage, Image, ItemId, ItemKind, Ordering, Tick}; +use crate::reads::ReadLog; /// How a [`FootageSource`] hands over float footage (OpenEXR, float TIFF), whose values are /// linear light: encoded with a curve, as the compositor takes footage, or as stored. Other @@ -36,6 +37,14 @@ pub trait FootageSource: Send + Sync { None => self.frame(item, footage, t), } } + /// [`FootageSource::frame_with`]'s full-size frame as 8-bit levels: each pixel is + /// [`effectcraft_raster::quantize_px_u8`] of the float pixel `frame_with` would give, so + /// [`effectcraft_raster::expand_u8`] makes that frame quantised to 8 bpc, bit for bit, from a + /// quarter of the memory (an 8 bpc render of 8-bit footage). `None` when the source has no + /// cheaper way than the float frame; the renderer then takes that. + fn frame8(&self, _item: ItemId, _footage: &Footage, _t: Tick, _float: FloatCurve) -> Option> { + None + } /// `frames` interleaved stereo sample frames of `item`'s audio from source time `t` at /// `rate` Hz (`None` when unavailable). The first sample is `t.to_units_floor(rate)`; /// a sample boundary uses the earliest representable tick that selects that sample. @@ -48,6 +57,12 @@ pub trait FootageSource: Send + Sync { fn aux(&self, _item: ItemId, _footage: &Footage, _t: Tick) -> Option> { None } + /// The footage files (by [`Footage::path`]) whose channels effects of the project read + /// through [`FootageSource::aux`] (EXtractoR, Cryptomatte and the other 3D Channel effects), + /// replacing the set given before. A source that decodes a file's picture and its channels + /// separately can decode both at once for these from the first frame on. Sources that don't + /// ignore it. + fn set_aux_footage(&self, _paths: &[String]) {} /// The parsed 3D model of a [`effectcraft_project::FootageKind::Model`] item (Advanced 3D). fn model(&self, _item: ItemId, _footage: &Footage) -> Option> { None @@ -69,8 +84,9 @@ pub trait FootageSource: Send + Sync { fn cache_budget(&self) -> Option { None } - /// Vector footage (SVG) rasterised at `scale` × its pixel size, for Continuously Rasterize. - /// `None` when the footage is not vector or cannot be read. + /// Vector footage (SVG, PDF, Illustrator, EPS: [`is_vector_footage`]) rasterised at `scale` × + /// its size as [`vector_fit`] draws it, for Continuously Rasterize. `None` when the footage + /// is not vector or cannot be read. fn vector_frame(&self, _item: ItemId, _footage: &Footage, _scale: f64) -> Option> { None } @@ -86,6 +102,15 @@ pub trait FootageSource: Send + Sync { fn called_off(&self) -> bool { false } + /// Run `f`, which reads from this source on this thread, noting in `reads` every source file + /// those reads use, with its identity as read (see [`crate::reads`]): the file a frame was + /// decoded from, also when it comes from the source's own memory cache (without reading the + /// file again). Sources that can't tell which files they read keep the default, which marks + /// `reads` incomplete. + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + reads.mark_incomplete(); + f() + } /// Why `footage` shows no picture although its file is there: a read of it failed because /// no decoder handles its codec, profile, chroma format or bit depth, or the stream is damaged /// (e.g. "H.264 (High 4:2:2) isn't supported by the built-in decoder: ..."). `None` while it @@ -93,20 +118,38 @@ pub trait FootageSource: Send + Sync { fn problem(&self, _footage: &Footage) -> Option { None } - /// [`Self::problem`] of what `item` shows: its proxy's while Use Proxy shows the proxy + /// Missing files and [`Self::problem`] of what `item` shows: its proxy's while Use Proxy shows the proxy /// instead (the reason then says it is the proxy's), else the footage item's own. A /// composition has one only through its proxy. fn item_problem(&self, item: &effectcraft_project::Item) -> Option { match item.proxy.as_deref().filter(|px| px.enabled && px.footage.has_video) { - Some(px) => self.problem(&px.footage).map(|why| format!("Proxy: {why}")), + Some(px) => { + missing_problem(&px.footage, "Use Set Proxy to locate the proxy file.").or_else(|| self.problem(&px.footage)).map(|why| format!("Proxy: {why}")) + } None => match &item.kind { - ItemKind::Footage(f) => self.problem(f), + ItemKind::Footage(f) => missing_problem(f, "Use File ▸ Dependencies ▸ Relink Missing Footage or Replace Footage.").or_else(|| self.problem(f)), _ => None, }, } } } +/// A known offline source, without filesystem access while painting or querying. +fn missing_problem(f: &Footage, remedy: &str) -> Option { + (f.missing && !f.path.is_empty() && f.kind != effectcraft_project::FootageKind::Data).then(|| format!("Missing footage: {}. {remedy}", f.path)) +} + +/// Inventory warning, including an unused proxy or an original currently replaced by a proxy. +/// Viewer warnings instead use `item_problem`, which follows the active render source. +pub fn missing_item_problem(item: &effectcraft_project::Item) -> Option { + if let ItemKind::Footage(f) = &item.kind + && let Some(why) = missing_problem(f, "Use File ▸ Dependencies ▸ Relink Missing Footage or Replace Footage.") + { + return Some(why); + } + item.proxy.as_ref().and_then(|p| missing_problem(&p.footage, "Use Set Proxy to locate the proxy file.")).map(|why| format!("Proxy: {why}")) +} + /// A render's view of a [`FootageSource`] whose frame reads can be called off with `cancel` /// (a viewer frame nobody waits for any more, #329). Every read goes through /// [`FootageSource::cancellable`] on its own, so reads made for this render on another thread @@ -140,6 +183,9 @@ impl FootageSource for CancellableFootage<'_> { fn aux(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { self.inner.aux(item, footage, t) } + fn set_aux_footage(&self, paths: &[String]) { + self.inner.set_aux_footage(paths) + } fn model(&self, item: ItemId, footage: &Footage) -> Option> { self.inner.model(item, footage) } @@ -167,24 +213,58 @@ impl FootageSource for CancellableFootage<'_> { fn called_off(&self) -> bool { self.cancel.load(Ordering::Relaxed) || self.inner.called_off() } + /// Runs `f` with the inner source, collecting the files it reads into `reads`. + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + self.inner.recording(reads, f) + } fn problem(&self, footage: &Footage) -> Option { self.inner.problem(footage) } fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { self.read(|| self.inner.frame_with(item, footage, t, size, float)) } + fn frame8(&self, item: ItemId, footage: &Footage, t: Tick, float: FloatCurve) -> Option> { + self.read(|| self.inner.frame8(item, footage, t, float)) + } } -/// Footage that can be rasterised at any scale (SVG). +/// Footage that can be rasterised at any scale: SVG, PDF, Illustrator and EPS files, and a +/// placed page of an After Effects project (its codec is not stored there). pub fn is_vector_footage(f: &Footage) -> bool { - matches!(f.codec.as_str(), "SVG" | "PDF" | "AI" | "EPS") + matches!(f.codec.as_str(), "SVG" | "PDF" | "AI" | "EPS") || f.placed_page +} + +/// How vector footage `f` is drawn at `scale` × its size: the image size, and the x and y scale +/// from document pixels (`doc` = the document's width and height, `own` = its pixel size, the +/// size rounded up) to image pixels. +/// +/// Footage from an After Effects project ([`Footage::placed_page`]) fills its stored size, which +/// can round or measure the page differently: the layer's anchor and masks are measured against +/// that size, and the renderer resamples a reduced-resolution frame to it, so drawn at its own +/// size the art was scaled by the width ratio alone at full resolution (off against the masks) +/// and stretched to the stored aspect below 3/4 resolution (#3099). Other footage is drawn 1:1 at +/// the document's own size, as it always was. +pub fn vector_fit(f: &Footage, doc: [f64; 2], own: (u32, u32), scale: f64) -> ((u32, u32), [f64; 2]) { + let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; + let side = |px: u32| (f64::from(px) * scale).ceil().clamp(1.0, f64::from(u32::MAX)) as u32; + let size = (f.width, f.height); + let fills = f.placed_page && size != own && size.0 > 0 && size.1 > 0 && doc.iter().all(|d| d.is_finite() && *d > 0.0); + if !fills { + return ((side(own.0), side(own.1)), [scale, scale]); + } + ((side(size.0), side(size.1)), [scale * f64::from(size.0) / doc[0], scale * f64::from(size.1) / doc[1]]) } /// No footage available (renders footage layers as transparent). pub struct NoFootage; impl FootageSource for NoFootage { + /// Always `None`: there is no footage. fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option> { None } + /// Reads no files. + fn recording(&self, _: &ReadLog, f: &mut dyn FnMut()) { + f() + } } diff --git a/crates/render/src/fx_host.rs b/crates/render/src/fx_host.rs index 65bafe002..3a6f1a34c 100644 --- a/crates/render/src/fx_host.rs +++ b/crates/render/src/fx_host.rs @@ -95,6 +95,7 @@ impl EffectHost for FxHost<'_, '_, '_> { Some(self.pixels(other, buf, false)) } + /// The audio of footage layer `id` from `start`, or `None` when the layer is not footage. fn audio(&self, id: u64, start: f64, frames: usize, rate: u32) -> Option> { let other = self.ctx.layer(effectcraft_project::LayerId(id))?; let LayerSource::Footage { item } = &other.source else { return None }; @@ -104,7 +105,7 @@ impl EffectHost for FxHost<'_, '_, '_> { return None; } let st = other.layer_time(Tick::from_seconds_f64(start)); - self.r.footage.audio(item, f, st, frames, rate) + self.r.read(|| self.r.footage.audio(item, f, st, frames, rate)) } fn self_at(&self, layer_time: f64, effects: usize) -> Option { diff --git a/crates/render/src/layers.rs b/crates/render/src/layers.rs index d105c6f13..cfae5dbab 100644 --- a/crates/render/src/layers.rs +++ b/crates/render/src/layers.rs @@ -34,21 +34,43 @@ impl Shutter { } } +/// `files` (a content's) with the files of the buffers made of it that the layer cache kept: +/// `files` itself when they are all its own. +fn with_kept_files(files: Arc, kept: &[Arc]) -> Arc { + if kept.iter().all(|f| Arc::ptr_eq(f, &files)) { + return files; + } + let mut all = (*files).clone(); + kept.iter().for_each(|f| all.extend(f)); + Arc::new(all) +} + impl<'a> Renderer<'a> { /// The layer with its styles: exterior passes and body (cached per pass). pub(crate) fn styled(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option { - let (content, ckey) = self.content_buf_timed(ctx, layer, timing.as_deref_mut())?; + let (content, ckey, files) = self.content_buf_timed(ctx, layer, timing.as_deref_mut())?; if !styles::active(ctx, layer) { - return Some(StyledLayer { passes: vec![], body: content.clone(), content, key: ckey, ckey, plain: true }); + return Some(StyledLayer { passes: vec![], body: content.clone(), content, key: ckey, ckey, plain: true, files }); } let modes = styles::pass_modes(ctx, layer); let key = ckey.map(|k| cache::styles_key(ctx, layer, k)); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(body) = c.get(k) - { - let passes: Option> = modes.iter().enumerate().map(|(i, m)| c.get(cache::derive(k, i as u64 + 1)).map(|b| (b, *m))).collect(); + // (a cached body or pass may have been made of other files than the content: another + // worker's, or one from disk; the styled layer lists the files of every buffer it holds) + if let Some((body, body_files)) = self.cached(key) { + let mut kept_files = vec![body_files]; + let passes: Option> = modes + .iter() + .enumerate() + .map(|(i, m)| { + self.cached(key.map(|k| cache::derive(k, i as u64 + 1))).map(|(b, f)| { + kept_files.push(f); + (b, *m) + }) + }) + .collect(); if let Some(passes) = passes { - return Some(StyledLayer { passes, body, content, key, ckey, plain: false }); + let files = with_kept_files(files, &kept_files); + return Some(StyledLayer { passes, body, content, key, ckey, plain: false, files }); } } let t0 = web_time::Instant::now(); @@ -59,16 +81,23 @@ impl<'a> Renderer<'a> { t.cached = false; t.effects.push(("layerStyles".into(), t0.elapsed().as_secs_f64() * 1e3)); } - let mut body = Arc::new(st.body); - let mut passes: Vec<_> = st.passes.into_iter().map(|(b, m)| (Arc::new(b), m)).collect(); - // The buffers the cache keeps (another worker's, if it kept them first). - if let (Some(c), Some(k)) = (self.cache_to_keep(), key) { - body = c.insert(k, body); - for (i, (b, _)) in passes.iter_mut().enumerate() { - *b = c.insert(cache::derive(k, i as u64 + 1), b.clone()); - } - } - Some(StyledLayer { passes, body, content, key, ckey, plain: false }) + // The buffers the cache keeps (another worker's, if it kept them first), made of the + // content's files; the styled layer then lists the files of every buffer it holds. + let mut kept_files = vec![]; + let (body, f) = self.keep(key, Arc::new(st.body), &files); + kept_files.push(f); + let passes: Vec<_> = st + .passes + .into_iter() + .enumerate() + .map(|(i, (b, m))| { + let (b, f) = self.keep(key.map(|k| cache::derive(k, i as u64 + 1)), Arc::new(b), &files); + kept_files.push(f); + (b, m) + }) + .collect(); + let files = with_kept_files(files, &kept_files); + Some(StyledLayer { passes, body, content, key, ckey, plain: false, files }) } /// The styled layer's buffers in the blending space. @@ -76,9 +105,10 @@ impl<'a> Renderer<'a> { if self.pipe.to_blend().is_none() { return st; } - let body = self.to_blend(st.body, st.key); - let content = if st.plain { body.clone() } else { self.to_blend(st.content, st.ckey) }; - let passes = st.passes.into_iter().enumerate().map(|(i, (b, m))| (self.to_blend(b, st.key.map(|k| cache::derive(k, i as u64 + 1))), m)).collect(); + let body = self.to_blend(st.body, st.key, &st.files); + let content = if st.plain { body.clone() } else { self.to_blend(st.content, st.ckey, &st.files) }; + let passes = + st.passes.into_iter().enumerate().map(|(i, (b, m))| (self.to_blend(b, st.key.map(|k| cache::derive(k, i as u64 + 1)), &st.files), m)).collect(); StyledLayer { passes, body, content, ..st } } @@ -236,7 +266,11 @@ impl<'a> Renderer<'a> { /// A processed-layer cache key that also covers content motion blur (the averaged source /// depends on the content at every sub-sample). pub(crate) fn content_key(&self, ctx: &EvalCtx, layer: &Layer, key: Option) -> Option { - let k = key?; + let k = self.mask_gate_key(ctx, layer, key)?; + // A layer that reads other layers through its effects' layer parameters gets them drawn + // by this renderer: the switches it passes down (Switches Affect Nested Comps, the + // precomp layers above, motion blur on) change those pixels, not just the layers' own. + let k = if cache::reads_layers(ctx, layer) { cache::derive(k, self.nested_look()) } else { k }; let Some(times) = self.content_times(ctx, layer) else { return Some(k) }; times.iter().try_fold(cache::derive(k, 0x6d62_6c72), |d, t| Some(cache::derive(d, cache::layer_key(&ctx.at(*t), layer, 1.0, false, false)?))) } @@ -257,6 +291,23 @@ impl<'a> Renderer<'a> { } } + /// A cache key of a masked layer's buffer, told apart when mask motion blur can't run at all + /// in this render ([`Self::mask_blur`]'s gate: the render options, the precomp layers above). + /// The key has the layer's own motion blur state, but a mask set to On blurs without it. + pub(crate) fn mask_gate_key(&self, ctx: &EvalCtx, layer: &Layer, key: Option) -> Option { + // Queue jobs share this cache but may override Proxy Use differently. The item's + // proxy switch alone does not describe the source a renderer actually reads. + let k = key?; + let k = match self.opts.proxy { + effectcraft_project::render_queue::ProxyUse::CurrentSettings => k, + effectcraft_project::render_queue::ProxyUse::UseAll => cache::derive(k, 0x7072_6f78_7901), + effectcraft_project::render_queue::ProxyUse::UseCompOnly => cache::derive(k, 0x7072_6f78_7902), + effectcraft_project::render_queue::ProxyUse::UseNone => cache::derive(k, 0x7072_6f78_7903), + }; + let masked = layer.masks().is_some_and(|m| !m.children.is_empty()); + Some(if masked && !self.mask_blur(ctx, layer).allowed { cache::derive(k, 0x6d62_6f66) } else { k }) + } + /// Motion-blur sub-samples for a layer buffer (1 = no motion blur). As in After Effects, a 2D /// layer gets about one sample per output pixel its corners travel during the shutter, /// at least Samples Per Frame and at most the comp's Adaptive Sample Limit; a layer that @@ -582,6 +633,8 @@ pub struct StyledLayer { ckey: Option, /// No layer styles: composite `body` the usual way. pub plain: bool, + /// The source files the layer's buffers were made of (see [`crate::reads`]). + pub(crate) files: Arc, } /// Where a layer buffer lands (see [`Renderer::placement`]). diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index dd5335623..f47443b18 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -17,6 +17,7 @@ use color::Region; pub mod eval; pub mod masks; pub mod passes; +pub mod reads; pub mod shapes; pub mod styles; pub mod text; @@ -25,7 +26,7 @@ pub mod three_d; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -pub use auto::{AutoKey, AutoPick}; +pub use auto::{AutoKey, AutoPick, AutoTicket}; pub use cache::{CacheStats, LayerCache, LayerStore, PrefetchStore}; use effectcraft_color::BlendMode; use effectcraft_effects::{Buf, EffectCtx, EffectEnv, EffectHost, LayerPixels, Params}; @@ -45,8 +46,8 @@ mod layers; mod opts; mod pipeline; -pub use accel::{Accelerator, Backend, FxStep, FxTarget}; -pub use footage::{CancellableFootage, FloatCurve, FootageSource, NoFootage, is_vector_footage}; +pub use accel::{Accelerator, Backend, FrameMemory, FxStep, FxTarget}; +pub use footage::{CancellableFootage, FloatCurve, FootageSource, NoFootage, is_vector_footage, missing_item_problem, vector_fit}; pub use frames::{ adaptive_samples, blend_frames, cineon_frame, content_bounds, extended_region, field_frame, frame_position, frame_size, interpret_pixels, kurbo_path, render_frame, roi_inside, @@ -60,7 +61,7 @@ pub use layers::{Placement, StyledLayer}; pub(crate) use opts::Collapse3d; pub use opts::{LayerTiming, RenderOpts}; use opts::{MAX_THROUGH, Through}; -pub use pipeline::{Collapsed, MediaOverride, PropertyOverride}; +pub use pipeline::{Collapsed, FootagePicture, MediaOverride, PropertyOverride}; pub struct Renderer<'a> { pub project: &'a Project, @@ -69,6 +70,10 @@ pub struct Renderer<'a> { pub opts: RenderOpts, /// Processed-layer cache shared across frames (see [`cache`]). `None` renders everything. pub cache: Option<&'a LayerCache>, + /// Where the source files this render reads are noted (see [`reads`]): the frame's own, + /// from the footage source and from the buffers the layer cache serves. `None` records + /// nothing for the frame (buffers kept in the layer cache still record theirs). + pub reads: Option<&'a reads::ReadLog>, /// Optional per-layer timing sink (`frame --bench` / perf readouts). pub profile: Option<&'a std::sync::Mutex>>, /// GPU backend used when [`RenderOpts::backend`] asks for it. @@ -97,6 +102,8 @@ pub struct Renderer<'a> { through: [Option>; MAX_THROUGH], /// More collapsed levels than [`MAX_THROUGH`]: their motion is not blurred. through_lost: bool, + /// Layer-space consumers must not use the viewport raster optimization. + pub(crate) whole_raster: bool, } #[cfg(test)] diff --git a/crates/render/src/opts.rs b/crates/render/src/opts.rs index c6175bf39..352f85983 100644 --- a/crates/render/src/opts.rs +++ b/crates/render/src/opts.rs @@ -28,6 +28,11 @@ pub struct RenderOpts { pub nested_switches: bool, /// Realtime Shadows in Draft (Settings ▸ 3D): draft renders (`draft`) still cast shadows. pub draft_shadows: bool, + /// No HDR step: the top-level comp leaves the working space for the output space without + /// Project Settings ▸ HDR (compand / tone mapping), so over-range values stay. The consumer + /// decodes the frame with [`crate::color::Pipe::output_linear`] (float outputs: OpenEXR) + /// or applies the step itself. Part of the viewer's frame keys (`opts_hash`). + pub skip_hdr_step: bool, } impl RenderOpts { @@ -49,6 +54,7 @@ impl Default for RenderOpts { backend: Backend::Cpu, nested_switches: true, draft_shadows: true, + skip_hdr_step: false, proxy: effectcraft_project::render_queue::ProxyUse::CurrentSettings, } } diff --git a/crates/render/src/passes.rs b/crates/render/src/passes.rs index 5f0373b84..b8f94fc46 100644 --- a/crates/render/src/passes.rs +++ b/crates/render/src/passes.rs @@ -59,11 +59,25 @@ pub async fn in_passes<'a, T>(accel: Option<&'a dyn Accelerator>, mut render: im Passed { value: render(None), passes: MAX_PASSES + 1, accelerated: false } } +/// Ends the frame for the accelerator ([`Accelerator::frame_end`]) when dropped: also when the +/// render panics or the future is dropped between passes. +struct FrameEnd<'a>(&'a dyn Accelerator); +impl Drop for FrameEnd<'_> { + fn drop(&mut self) { + self.0.frame_end(); + } +} + /// A top-level comp frame through [`in_passes`] ([`Renderer::comp_frame`] in passes). Backend /// Auto picks CPU or GPU for the whole frame (all its passes) and is timed as a whole, as the -/// frame workers do. +/// frame workers do. Ends the frame for the accelerator ([`Accelerator::frame_end`]) on every +/// exit, including a panic. pub async fn comp_frame(r: &Renderer<'_>, comp: ItemId, t: Tick) -> Image { - let Some(a) = r.accel.filter(|a| a.miss_gate().is_some()) else { return r.comp_frame(comp, t) }; + let Some(a) = r.accel else { return r.comp_frame(comp, t) }; + let _end = FrameEnd(a); + if a.miss_gate().is_none() { + return r.comp_frame(comp, t); + } let mut opts = r.opts; let mut auto = None; if opts.backend == Backend::Auto { @@ -72,10 +86,10 @@ pub async fn comp_frame(r: &Renderer<'_>, comp: ItemId, t: Tick) -> Image { } else if opts.roi.is_none() && let Some(pick) = a.auto_pick() { - let key = AutoKey::new(comp, opts.scale, false); - let gpu = pick.choose(key); - opts.backend = if gpu { Backend::Gpu } else { Backend::Cpu }; - auto = Some((key, gpu)); + // (a frame cancelled or panicking between passes drops it: ended unmeasured) + let ticket = pick.ticket(AutoKey::new(comp, opts.scale, false)); + opts.backend = if ticket.gpu() { Backend::Gpu } else { Backend::Cpu }; + auto = Some(ticket); } } let t0 = web_time::Instant::now(); @@ -84,8 +98,8 @@ pub async fn comp_frame(r: &Renderer<'_>, comp: ItemId, t: Tick) -> Image { } else { in_passes(Some(a), |acc| Renderer { opts, accel: acc, ..*r }.comp_frame(comp, t)).await.value }; - if let (Some((key, chose)), Some(pick)) = (auto, a.auto_pick()) { - pick.record(key, chose, t0.elapsed().as_secs_f64() * 1e3); + if let Some(t) = auto { + t.record(t0.elapsed().as_secs_f64() * 1e3); } img } diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index a4927144f..b1ec0ca02 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -3,9 +3,11 @@ use super::footage::{FootageSource, is_vector_footage}; use super::frames::{blend_frames, cineon_frame, content_bounds, field_frame, frame_blend_mode, frame_position, frame_size, interpret_pixels, roi_inside}; use super::fx_host::{FxHost, essential_overrides}; use super::opts::{Collapse3d, LayerTiming, MAX_THROUGH, RenderOpts, Through}; +use super::reads::{ReadFiles, ReadLog}; use super::{ - Arc, AutoKey, AutoPick, BlendMode, Buf, Comp, EffectCtx, EffectEnv, EvalCtx, Footage, FootageKind, FrameBlend, FrameRate, GroupKind, Image, ItemId, - ItemKind, Layer, LayerCache, LayerSource, Params, Project, Quality, Region, Renderer, Tick, cache, color, masks, shapes, styles, text, three_d, vec2, + Arc, AutoKey, AutoPick, AutoTicket, BlendMode, Buf, Comp, EffectCtx, EffectEnv, EvalCtx, Footage, FootageKind, FrameBlend, FrameRate, GroupKind, Image, + ItemId, ItemKind, Layer, LayerCache, LayerSource, Params, Project, Quality, Region, Renderer, Tick, cache, color, masks, shapes, styles, text, three_d, + vec2, }; use effectcraft_keyframe::Value; use effectcraft_project::LayerId; @@ -18,6 +20,24 @@ pub(crate) struct EffectStack { pub origin: [f64; 2], } +/// A footage layer's source as the decoded picture itself (see [`Renderer::footage_picture`]): +/// its buffer in layer space is `img` at offset `[0, 0]` and `scale`; in effect space (what +/// [`Renderer::layer_input`] gives) at `effect_offset`. +#[derive(Clone, Debug)] +pub struct FootagePicture { + pub img: Arc, + pub scale: f64, + pub effect_offset: [f64; 2], +} + +/// How a decoded footage frame becomes a layer buffer ([`Renderer::footage_buf`]). +enum FootageLayout { + /// Its own pixels, at this buffer scale. + Native { scale: f64 }, + /// Resampled to `width`×`height` at this buffer scale. + Resample { width: u32, height: u32, scale: f64 }, +} + /// A property value an Essential Properties override gives a layer of a collapsed precomp. #[derive(Clone, Debug)] pub struct PropertyOverride { @@ -101,6 +121,7 @@ fn collapsed_instance(ctx: &EvalCtx, layer: &Layer, item: ItemId) -> Option<(Vec } impl<'a> Renderer<'a> { + /// A renderer over `project` and `footage` with the given options. pub fn new(project: &'a Project, footage: &'a dyn FootageSource, opts: RenderOpts) -> Renderer<'a> { Renderer { project, @@ -108,6 +129,7 @@ impl<'a> Renderer<'a> { expr: None, opts, cache: None, + reads: None, profile: None, accel: None, depth: 0, @@ -120,6 +142,7 @@ impl<'a> Renderer<'a> { top: true, through: [None; MAX_THROUGH], through_lost: false, + whole_raster: false, } } @@ -129,6 +152,67 @@ impl<'a> Renderer<'a> { self.cache.filter(|_| !self.footage.called_off()) } + /// `read`, a read of this render's footage source, with the files it uses noted in + /// [`Renderer::reads`] (see [`FootageSource::recording`]). + pub(crate) fn read(&self, read: impl FnOnce() -> Option) -> Option { + let Some(log) = self.reads else { return read() }; + let (mut read, mut out) = (Some(read), None); + self.footage.recording(log, &mut || out = read.take().and_then(|f| f())); + out + } + + /// `ctx` noting what it reads (fonts, `sampleImage`) in this render's [`Renderer::reads`]: + /// a context made by an outer render carries that render's log, not the one of the buffer + /// [`Renderer::recorded`] makes. + pub(crate) fn with_reads<'c>(&'c self, ctx: &EvalCtx<'c>) -> EvalCtx<'c> { + EvalCtx { reads: self.reads, ..*ctx } + } + + /// The buffer the layer cache keeps under `key`, with the files it was made of noted in + /// [`Renderer::reads`]. + pub(crate) fn cached(&self, key: Option) -> Option<(Arc, Arc)> { + let (buf, files) = self.cache?.get(key?)?; + if let Some(log) = self.reads { + log.note_all(&files); + } + Some((buf, files)) + } + + /// Keep `buf`, made of `files`, under `key` (see [`Renderer::recorded`]): the buffer the cache + /// keeps (another worker's, if it kept one first), or `buf` when nothing is kept, with the + /// files that buffer was made of. Another worker's files are noted in [`Renderer::reads`] + /// too: its pixels are the ones this render uses (a file that changed between the two reads + /// then has two identities, and the list is incomplete). + pub(crate) fn keep(&self, key: Option, buf: Arc, files: &Arc) -> (Arc, Arc) { + let (Some(c), Some(k)) = (self.cache_to_keep(), key) else { return (buf, files.clone()) }; + let (kept, kept_files) = c.insert(k, buf, files.clone()); + if !Arc::ptr_eq(&kept_files, files) + && let Some(log) = self.reads + { + log.note_all(&kept_files); + } + (kept, kept_files) + } + + /// Run `make`, which makes a buffer to keep under `key` in the layer cache, on this renderer + /// with its reads noted apart: what `make` returns and the files it read (from the footage + /// source, or the files of cached buffers it used), which go to [`Renderer::reads`] too. A + /// cached buffer then reports the files it was made of whichever render uses it. Without a + /// cache or a key, `make` runs on this renderer as it is (no files: nothing is kept). + pub(crate) fn recorded(&self, key: Option, make: impl FnOnce(&Renderer<'_>) -> T) -> (T, Arc) { + if key.is_none() || self.cache.is_none() { + return (make(self), Arc::default()); + } + // (the generation before any read: a file dropped while `make` runs makes it stale) + let log = self.cache.and_then(LayerCache::drop_generation).map_or_else(ReadLog::new, ReadLog::starting_at); + let out = make(&Renderer { reads: Some(&log), ..*self }); + let files = log.into_files(); + if let Some(own) = self.reads { + own.note_all(&files); + } + (out, Arc::new(files)) + } + /// A layer's Quality switch, limited by the precomp layers above it when /// [`RenderOpts::nested_switches`] is on. pub fn quality(&self, layer: &Layer) -> Quality { @@ -143,6 +227,24 @@ impl<'a> Renderer<'a> { } } + /// What this renderer passes down to the layers it draws beyond their own switches + /// ([`RenderOpts::nested_switches`], the switches inherited from the precomp layers above, + /// motion blur on): part of the cache key of a buffer that reads other layers. + pub(crate) fn nested_look(&self) -> u64 { + let inherited = match self.inherited { + None => 0, + Some((q, mb)) => { + let q = match q { + Quality::Best => 0, + Quality::Draft => 1, + Quality::Wireframe => 2, + }; + 1 + q * 2 + u64::from(mb) + } + }; + 0x6e65_7374_0000_0000 | inherited << 2 | u64::from(self.opts.nested_switches) << 1 | u64::from(self.opts.motion_blur) + } + /// A layer's Motion Blur switch, limited by the precomp layers above it. pub(crate) fn layer_motion_blur(&self, layer: &Layer) -> bool { layer.switches.motion_blur && self.inherited.is_none_or(|(_, mb)| mb) @@ -176,6 +278,8 @@ impl<'a> Renderer<'a> { top: false, through: [None; MAX_THROUGH], through_lost: false, + // Effects and nested renders need whole layer-space pixels. + whole_raster: true, ..*self } } @@ -316,8 +420,9 @@ impl<'a> Renderer<'a> { } let (scale, draft, blur) = (self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer)); let prev = ctx.time - ctx.comp.frame_rate.frame_duration(); - let now = cache::layer_key(ctx, layer, scale, draft, blur); - now.is_some() && now == cache::layer_key(&ctx.at(prev), layer, scale, draft, blur) + let before = ctx.at(prev); + let now = self.clipped_key(ctx, layer, cache::layer_key(ctx, layer, scale, draft, blur)); + now.is_some() && now == self.clipped_key(&before, layer, cache::layer_key(&before, layer, scale, draft, blur)) } /// Rasterisation scale of a layer's source: the output scale, or — for text and shape layers, @@ -351,14 +456,73 @@ impl<'a> Renderer<'a> { // a whole number maps the unit vectors to lengths a hair over 1, which must stay 1 (#390: // rounded up to 2^¼, unscaled text was drawn larger and resampled, softer). let mut k = 2f64.powf((k.log2() * 4.0 - 1e-6).ceil() / 4.0).clamp(1.0 / 16.0, 64.0); - // Keep the buffer within about 16 million pixels. + // Keep the buffer within about 16 million pixels (of the part the output shows, when + // only that is rasterised: see `raster_clip`). if let Some(b) = content_bounds(ctx, layer) { + let b = match self.raster_clip(ctx, layer) { + Some(c) => { + let r = kurbo::Rect::new(b[0], b[1], b[2], b[3]).intersect(c); + [r.x0, r.y0, r.x1, r.y1] + } + None => b, + }; let area = ((b[2] - b[0]) * (b[3] - b[1])).max(1.0) * s * s; k = k.min((16.0e6 / area).sqrt().max(1.0)); } s * k } + /// The layer-space part of a 3D text or shape layer the output shows, when only that part + /// needs rasterising (#1388: text close to the camera was rasterised whole at up to 16 + /// million pixels, a quarter gigabyte per frame worker, though the frame showed a fraction + /// of it; behind the camera it was rasterised and not drawn). `None` rasterises it whole: + /// whenever pixels outside the frame can matter — effects, layer styles, masks, motion blur, + /// depth of field, lights (shadows and transmission), Advanced 3D, per-character 3D, a + /// collapsed 2D transform — or the visible part can't be bounded (see + /// [`three_d::compose::visible_clip`]). + pub(crate) fn raster_clip(&self, ctx: &EvalCtx, layer: &Layer) -> Option { + if self.whole_raster || !layer.is_3d() || !matches!(layer.source, LayerSource::Text | LayerSource::Shape) || self.outer.is_some() { + return None; + } + if (layer.switches.effects && layer.effects().is_some_and(|fx| !fx.children.is_empty())) + || layer.masks().is_some_and(|m| !m.children.is_empty()) + || styles::active(ctx, layer) + || ctx.comp.layers.iter().any(|l| matches!(l.source, LayerSource::Light { .. })) + || self.is_adv3d(ctx) + || (matches!(layer.source, LayerSource::Text) && (text::per_char_3d(ctx, layer) || text::animator_blur(ctx, layer))) + { + return None; + } + let v = three_d::compose::visible_clip(self, ctx, layer)?; + if v.area() <= 0.0 { + // Behind the camera. + return Some(v); + } + let b = content_bounds(ctx, layer).map(|b| kurbo::Rect::new(b[0], b[1], b[2], b[3]))?; + if v.x0 <= b.x0 && v.y0 <= b.y0 && v.x1 >= b.x1 && v.y1 >= b.y1 { + return None; + } + // Whole cells of a layer-space grid whose cell is about a quarter of the part that shows, + // rounded down to a power of two: a moving camera keeps one raster (and its cache entry) + // while that part stays within the same cells, and a dolly changes the grid only at each + // doubling. The cells cover at most about 2.25 times the part that shows. Worth it only + // when it leaves out at least half of the content. + let c = 2f64.powf(((v.width().max(v.height()) / 4.0).max(1e-6)).log2().floor()); + let snap = |v: f64, up: bool| if up { (v / c).ceil() * c } else { (v / c).floor() * c }; + // (Not cut to the content bounds: a stroke or a glyph's padding reaches past them.) + let cells = kurbo::Rect::new(snap(v.x0, false), snap(v.y0, false), snap(v.x1, true), snap(v.y1, true)); + (cells.is_finite() && cells.intersect(b).area() <= b.area() * 0.5).then_some(cells) + } + + /// A layer content cache key that also names the part rasterised ([`Self::raster_clip`]). + pub(crate) fn clipped_key(&self, ctx: &EvalCtx, layer: &Layer, key: Option) -> Option { + let k = key?; + Some(match self.raster_clip(ctx, layer) { + Some(c) => raster_clip_key(k, c), + None => k, + }) + } + /// Draw a Wireframe-quality layer: its bounds as a one-pixel outline. pub(crate) fn draw_wireframe(&self, ctx: &EvalCtx, layer: &Layer, canvas: &mut Image) { for (x, y) in self.wireframe_pixels(ctx, layer, (canvas.width, canvas.height)) { @@ -366,8 +530,19 @@ impl<'a> Renderer<'a> { } } + /// The evaluation context of `comp` at `t`, carrying this renderer's expressions, footage and read log. pub(crate) fn ctx(&self, comp_id: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> { - EvalCtx { project: self.project, comp_id, comp, time: t, expr: self.expr, footage: Some(self.footage), property_overrides: &[], media_overrides: &[] } + EvalCtx { + project: self.project, + comp_id, + comp, + time: t, + expr: self.expr, + footage: Some(self.footage), + property_overrides: &[], + media_overrides: &[], + reads: self.reads, + } } /// This renderer with another accelerator (or none): the passes of @@ -389,32 +564,49 @@ impl<'a> Renderer<'a> { /// Render a composition at comp time `t` (transparent background, comp size × scale). /// Top-level frames go to the GPU when [`Self::active_accel`] is set and handles them. pub fn comp_frame(&self, comp_id: ItemId, t: Tick) -> Image { + self.comp_frame_with(comp_id, t, false, |a| Ok::<_, std::convert::Infallible>(a.comp_frame(self, comp_id, t))).unwrap_or_else(|never| match never {}) + } + + /// Render a frame, validating the accelerated attempt before starting any CPU fallback. + /// The caller's scope must run only the accelerator, not this whole method: a GPU fault + /// must release failed resources before a potentially large CPU render (#3357). + /// A scope error returns immediately; the caller can then retry with a fresh CPU renderer + /// without accelerator-produced cache entries. Healthy declines and Auto timing retain + /// the same behavior as [`Self::comp_frame`]. Its fallback disables acceleration for + /// effects too: GPU work must never escape the supplied error scope. + pub fn comp_frame_scoped(&self, comp_id: ItemId, t: Tick, scope: impl FnOnce(&dyn Accelerator) -> Result, E>) -> Result { + self.comp_frame_with(comp_id, t, true, scope) + } + + fn comp_frame_with(&self, comp_id: ItemId, t: Tick, scoped: bool, scope: impl FnOnce(&dyn Accelerator) -> Result, E>) -> Result { + let cpu = if scoped { self.with_accel(None) } else { self.with_accel(self.accel) }; // Classic 3D runs composite on the GPU too (M12.7), so Auto sends 3D comps there as well; // Auto renders each comp on whichever compositor measured faster ([`AutoPick`]). if self.depth == 0 && let Some(a) = self.active_accel() { - let auto = self.frame_auto(a, comp_id, false); - if auto.is_none_or(|(p, key)| p.choose(key)) { + // (an error returns with the ticket, which ends the frame unmeasured) + let mut ticket = self.frame_auto(a, comp_id, false).map(|(p, key)| p.ticket(key)); + if ticket.as_ref().is_none_or(AutoTicket::gpu) { let t0 = web_time::Instant::now(); - if let Some(img) = a.comp_frame(self, comp_id, t) { - if let Some((p, key)) = auto { - p.record(key, true, t0.elapsed().as_secs_f64() * 1e3); + if let Some(img) = scope(a)? { + if let Some(t) = ticket { + t.record(t0.elapsed().as_secs_f64() * 1e3); } - return img; + return Ok(img); } - if let Some((p, key)) = auto { - p.declined(key); + if let Some(t) = &mut ticket { + t.declined(); } } let t0 = web_time::Instant::now(); - let img = self.comp_frame_cpu(comp_id, t); - if let Some((p, key)) = auto { - p.record(key, false, t0.elapsed().as_secs_f64() * 1e3); + let img = cpu.comp_frame_cpu(comp_id, t); + if let Some(t) = ticket { + t.record(t0.elapsed().as_secs_f64() * 1e3); } - return img; + return Ok(img); } - self.comp_frame_cpu(comp_id, t) + Ok(cpu.comp_frame_cpu(comp_id, t)) } /// The Auto timing history and key for a top-level frame of `comp` (`None` unless the @@ -473,14 +665,15 @@ impl<'a> Renderer<'a> { self.pipe.quantize(&mut canvas); } // The top-level comp leaves the working space for the (sRGB) display / output. + let out = self.output_pipe(); if self.depth == 0 - && let Some(c) = self.pipe.output() + && let Some(c) = out.output() { color::convert(&mut canvas, &c); self.pipe.quantize(&mut canvas); } if self.depth == 0 - && let Some((lin, mode, enc)) = self.pipe.output_hdr() + && let Some((lin, mode, enc)) = out.output_hdr() { color::output_hdr(&mut canvas, lin, mode, enc); self.pipe.quantize(&mut canvas); @@ -615,6 +808,7 @@ impl<'a> Renderer<'a> { working_linear: self.pipe.linear, float_depth: self.pipe.levels.is_none(), shutter: self.mb_on(ctx, layer).then_some((ctx.comp.shutter_angle, ctx.comp.shutter_phase, ctx.comp.motion_blur_samples)), + layer_span: crate::eval::layer_span(self.project, layer), }; // Video effects in stack order (index, group, spec); disabled and audio effects skipped. let stack: Vec<(usize, &effectcraft_project::PropGroup, &'static effectcraft_effects::EffectSpec)> = fx @@ -686,6 +880,12 @@ impl<'a> Renderer<'a> { /// Source pixels of a layer in layer space (before masks/effects). pub(crate) fn source(&self, ctx: &EvalCtx, layer: &Layer) -> Option { + self.source_with(ctx, layer, false) + } + + /// [`Renderer::source`]; with `quantized`, footage that [`Renderer::prequantized_footage`] + /// counts comes quantised to the project depth. + fn source_with(&self, ctx: &EvalCtx, layer: &Layer, quantized: bool) -> Option { let s = self.opts.scale; match &layer.source { LayerSource::Solid { item } => { @@ -718,7 +918,7 @@ impl<'a> Renderer<'a> { && let Some(nc) = self.project.comp(*item) { let img = self.footage_frame(ctx, layer, *item, pf, lt, None)?; - return Some(self.footage_buf(&img, pf, nc.width, nc.height)); + return Some(self.footage_buf(&img, pf, nc.width, nc.height, false)); } // Essential Properties overrides render the nested comp with this instance's // values. @@ -758,7 +958,7 @@ impl<'a> Renderer<'a> { // Continuously rasterised vector footage: drawn at the on-screen scale. if layer.switches.collapse && is_vector_footage(f) { let k = self.raster_scale(ctx, layer); - if let Some(img) = self.footage.vector_frame(item, f, k) { + if let Some(img) = self.read(|| self.footage.vector_frame(item, f, k)) { let mut buf = Buf { img: (*img).clone(), offset: [0.0; 2], scale: k }; if let Some(c) = self.pipe.media_in(f) { color::convert(&mut buf.img, &c); @@ -766,16 +966,31 @@ impl<'a> Renderer<'a> { return Some(buf); } } - let lt = ctx.source_time(layer); - // The proxy is decoded instead, at its own size, and fills the footage's frame. - let proxy = self.proxy_for(item); - let pf = proxy.unwrap_or(f); - let size = self.reduced_size(f.width, f.height).filter(|_| proxy.is_none()); - let img = self.footage_frame(ctx, layer, item, pf, lt, size)?; - Some(self.footage_buf(&img, pf, f.width, f.height)) + // 8 bpc plain footage: made from the footage's 8-bit levels, no float frame. + if quantized && let Some(buf) = self.footage_buf8(ctx, layer, item, self.proxy_for(item).unwrap_or(f), f, ctx.source_time(layer)) { + return Some(buf); + } + let (img, pf) = self.footage_picture_of(ctx, layer, item, f)?; + Some(self.footage_buf(&img, pf, f.width, f.height, quantized && Self::prequantized_footage(layer))) } - LayerSource::Text => Some(self.authored(text::render(ctx, layer, self.raster_scale(ctx, layer)))), - LayerSource::Shape => layer.props.sub("contents").map(|c| self.authored(shapes::render(ctx, layer, c, self.raster_scale(ctx, layer)))), + // (the font files go to this render's log, which `ctx` may not carry: see + // [`Renderer::with_reads`]) + LayerSource::Text => { + // An Expression Selector evaluates per character: its results at other characters + // than the first are not in the layer's cache key (an amount reading a footage + // item's size by name, `textIndex == 1 ? 0 : footage("ref.png").width`), so the + // buffer is kept in memory only, never on disk (the frame's key covers them). + if cache::per_character_expressions(layer) + && let Some(log) = self.reads + { + log.mark_unkeyed(); + } + Some(self.authored(text::render_in(&self.with_reads(ctx), layer, self.raster_scale(ctx, layer), self.raster_clip(ctx, layer)))) + } + LayerSource::Shape => layer + .props + .sub("contents") + .map(|c| self.authored(shapes::render_in(ctx, layer, c, self.raster_scale(ctx, layer), self.raster_clip(ctx, layer)))), _ => None, } } @@ -789,20 +1004,147 @@ impl<'a> Renderer<'a> { /// A decoded frame of `f` as a layer buffer covering `w`×`h` layer pixels (the footage's /// nominal size; proxies are scaled up to it), converted from its colour profile. - fn footage_buf(&self, img: &Image, f: &Footage, w: u32, h: u32) -> Buf { + /// + /// `quantized`: also clamp and quantise it to the project depth, as [`Renderer::masked_source`] + /// would (fused with the copy of the cached frame: one pass over it instead of three). + fn footage_buf(&self, img: &Image, f: &Footage, w: u32, h: u32, quantized: bool) -> Buf { + let c = self.pipe.media_in(f); + match self.footage_layout(img, w, h) { + FootageLayout::Native { scale } => { + let img = match (quantized, &c) { + (true, _) => self.pipe.copy_converted(img, c.as_ref()), + (false, Some(c)) => { + let mut img = img.clone(); + color::convert(&mut img, c); + img + } + (false, None) => img.clone(), + }; + Buf { img, offset: [0.0; 2], scale } + } + FootageLayout::Resample { width, height, scale } => { + let mut img = effectcraft_raster::resample(img, width, height); + if let Some(c) = &c { + color::convert(&mut img, c); + } + if quantized { + self.pipe.quantize(&mut img); + } + Buf { img, offset: [0.0; 2], scale } + } + } + } + + /// [`Renderer::footage_buf`]'s quantised buffer made from the footage's 8-bit levels + /// ([`FootageSource::frame8`]), the same pixels to the bit, when nothing before the quantise + /// changes them: an 8 bpc render at Full size of plain footage (no masks, colour profile, + /// Separate Fields, Frame Blending, Cineon, Invert Alpha or linear light interpretation). + /// `None` otherwise, and when the source has no 8-bit frame. + // ponytail: the media pool keeps the 8-bit and the float frame as separate entries, so a + // movie shown by both a plain and a masked layer in one 8 bpc comp is decoded twice per + // frame; derive one from the other in the pool if a comp like that turns out common. + #[allow(clippy::too_many_arguments)] + fn footage_buf8(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, pf: &Footage, f: &Footage, t: Tick) -> Option { + let plain = self.pipe.levels == Some(255.0) + && Self::prequantized_footage(layer) + && self.reduced_size(f.width, f.height).is_none() + && self.pipe.media_in(pf).is_none() + && pf.fields == effectcraft_project::FieldOrder::Off + && !(pf.invert_alpha || pf.linear_light_applies() || pf.cineon_applies()) + && frame_blend_mode(ctx, layer) == FrameBlend::Off; + if !plain { + return None; + } + let fr = self.read(|| self.footage.frame8(item, pf, t, self.pipe.float_curve(pf)))?; + let n = (fr.width as usize).checked_mul(fr.height as usize)?; + let px = fr.rgba.as_chunks::<4>().0; + if px.len() != n { + return None; + } + use rayon::prelude::*; + let data = px.par_iter().map(|&p| effectcraft_raster::expand_u8(p)).collect(); + let k = if fr.width > 0 { f.width.max(1) as f64 / fr.width as f64 } else { 1.0 }; + Some(Buf { img: Image { width: fr.width, height: fr.height, data }, offset: [0.0; 2], scale: 1.0 / k }) + } + + /// The layer's source is footage that [`Renderer::source`] hands over already quantised + /// ([`Renderer::footage_buf`]): footage without masks (masks apply to unquantised pixels). + /// Collapsed layers may be vector footage, drawn elsewhere: not counted. + fn prequantized_footage(layer: &Layer) -> bool { + matches!(layer.source, LayerSource::Footage { .. }) && !layer.switches.collapse && layer.masks().is_none_or(|m| m.groups().next().is_none()) + } + + /// How [`Renderer::footage_buf`] lays out a decoded frame `img` of footage `w`×`h` layer + /// pixels: its own pixels, or resampled. + fn footage_layout(&self, img: &Image, w: u32, h: u32) -> FootageLayout { let s = self.opts.scale; let k = if img.width > 0 { w.max(1) as f64 / img.width as f64 } else { 1.0 }; // Keep native pixels when downsampling is small; resample otherwise. - let mut buf = match self.reduced_size(w, h) { + match self.reduced_size(w, h) { // The source resampled it already (`FootageSource::frame_at_size`). - Some(size) if (img.width, img.height) == size => Buf { img: img.clone(), offset: [0.0; 2], scale: s }, - Some((rw, rh)) if k <= 1.0 + 1e-9 => Buf { img: effectcraft_raster::resample(img, rw, rh), offset: [0.0; 2], scale: s }, - _ => Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 / k }, - }; - if let Some(c) = self.pipe.media_in(f) { - color::convert(&mut buf.img, &c); + Some(size) if (img.width, img.height) == size => FootageLayout::Native { scale: s }, + Some((width, height)) if k <= 1.0 + 1e-9 => FootageLayout::Resample { width, height, scale: s }, + _ => FootageLayout::Native { scale: 1.0 / k }, } - buf + } + + /// A footage layer's decoded frame at the context time (the proxy's when one is used) and + /// the footage it was decoded from: what [`Renderer::source`] makes the layer's buffer of. + fn footage_picture_of(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &'a Footage) -> Option<(Arc, &'a Footage)> { + let lt = ctx.source_time(layer); + // The proxy is decoded instead, at its own size, and fills the footage's frame. + let proxy = self.proxy_for(item); + let pf = proxy.unwrap_or(f); + let size = self.reduced_size(f.width, f.height).filter(|_| proxy.is_none()); + let img = self.footage_frame(ctx, layer, item, pf, lt, size)?; + Some((img, pf)) + } + + /// The decoded footage picture a layer's masked source is, bit for bit, with no copy: a + /// footage layer (not continuously rasterised vector footage) without masks whose frame + /// needs no colour conversion, no resampling and no quantisation (32 bpc). The buffer + /// [`Renderer::layer_input`] gives for no effects is this picture at `effect_offset` and + /// `scale`. + /// Layers showing the same frame get the same `Arc` (the footage source's cached frame), so + /// an accelerator uploads it once and shares the texture. `None`: the layer's buffer is + /// made the usual way (any of the above applies, or the frame is missing), and also when the + /// frame is made per call rather than served by the footage source (frame blending, + /// separate fields, Invert Alpha, Interpret As Linear Light, Cineon conversion: a new + /// picture each time, nothing to share) or when the layer cache already holds the layer's + /// buffer (served from memory as before, without asking the footage source). + pub fn footage_picture(&self, ctx: &EvalCtx, layer: &Layer) -> Option { + let LayerSource::Footage { item } = &layer.source else { return None }; + if self.pipe.levels.is_some() || layer.masks().is_some_and(|m| !m.children.is_empty()) || frame_blend_mode(ctx, layer) != FrameBlend::Off { + return None; + } + let item = ctx.media_item(layer, *item); + let ItemKind::Footage(f) = &self.project.item(item)?.kind else { return None }; + if !f.has_video || (layer.switches.collapse && is_vector_footage(f)) { + return None; + } + let pf = self.proxy_for(item).unwrap_or(f); + if self.pipe.media_in(pf).is_some() + || pf.fields != effectcraft_project::FieldOrder::Off + || pf.invert_alpha + || pf.linear_light_applies() + || pf.cineon_applies() + { + return None; + } + if let Some(cache) = self.cache { + let (scale, draft, blur) = (self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer)); + let content = self.content_key(ctx, layer, cache::layer_key(ctx, layer, scale, draft, blur)); + let input = self.content_key(ctx, layer, cache::input_key(ctx, layer, scale, draft, blur, 0)); + if [content, input].into_iter().flatten().any(|k| cache.holds(k)) { + return None; + } + } + let (img, _) = self.footage_picture_of(ctx, layer, item, f)?; + let FootageLayout::Native { scale } = self.footage_layout(&img, f.width, f.height) else { return None }; + // `layer_input`'s rebase into effect space (`Buf::rebase` of a buffer at the origin). + let mut at = Buf { img: Image { width: 0, height: 0, data: Vec::new() }, offset: [0.0; 2], scale }; + at.rebase(ctx.effect_bounds(layer).1); + Some(FootagePicture { img, scale, effect_offset: at.offset }) } /// The size of `w` × `h` layer pixels in this render when it is reduced enough that footage @@ -829,7 +1171,7 @@ impl<'a> Renderer<'a> { if f.fields != effectcraft_project::FieldOrder::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) { let field_rate = FrameRate::new(f.frame_rate.num * 2, f.frame_rate.den); let i = field_rate.frame_at(t).max(0); - let img = cineon_frame(self.footage.frame_with(item, f, f.frame_rate.tick_of(i / 2), None, self.pipe.float_curve(f))?, f); + let img = cineon_frame(self.read(|| self.footage.frame_with(item, f, f.frame_rate.tick_of(i / 2), None, self.pipe.float_curve(f)))?, f); let dominant_upper = f.fields == effectcraft_project::FieldOrder::UpperFirst; // Upper field = even lines (0, 2, …). let parity = if (i % 2 == 0) == dominant_upper { 0 } else { 1 }; @@ -842,6 +1184,8 @@ impl<'a> Renderer<'a> { if per_pixel { Some(Arc::new(interpret_pixels(&img, f, self.pipe.linear_footage_space(f)))) } else { Some(img) } } + /// The footage frame at source time `t` after frame blending: the average of the source frames one comp frame spans, else a blend of the two neighbouring frames, else the plain frame. + /// Log scans are converted first, and blended frames are cached. fn footage_frame_raw(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option> { let mode = frame_blend_mode(ctx, layer); let float = self.pipe.float_curve(f); @@ -853,6 +1197,9 @@ impl<'a> Renderer<'a> { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); (0x00f8_a3e5_u64, item, i, (w as f32).to_bits(), mode as u8, f.frame_rate.num, f.frame_rate.den, &f.path, float).hash(&mut h); + // Every file of a sequence: the key must tell two projects apart whose items + // share an id and a first frame (on disk, no project-wide salt does, #3184). + f.sequence.hash(&mut h); (f.alpha as u8).hash(&mut h); if f.alpha == effectcraft_project::AlphaMode::Premultiplied { f.premul_color.map(f32::to_bits).hash(&mut h); @@ -863,35 +1210,34 @@ impl<'a> Renderer<'a> { } h.finish() }); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { + if let Some((b, _)) = self.cached(key) { return Some(Arc::new(b.img.clone())); } // Log scans are converted before they blend: the conversion is not linear. - let a = self.footage.frame_with(item, f, f.frame_rate.tick_of(i), None, float).map(|a| cineon_frame(a, f)); - let b = self.footage.frame_with(item, f, f.frame_rate.tick_of(i + 1), None, float).map(|b| cineon_frame(b, f)); + let ((a, b), files) = self.recorded(key, |r| { + let frame = |i| r.read(|| r.footage.frame_with(item, f, f.frame_rate.tick_of(i), None, float)).map(|a| cineon_frame(a, f)); + (frame(i), frame(i + 1)) + }); if let (Some(a), Some(b)) = (a, b) { let img = blend_frames(mode, &a, &b, w as f32); - if let (Some(c), Some(k)) = (self.cache_to_keep(), key) { - c.insert(k, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 })); - } + let _kept = self.keep(key, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }), &files); return Some(Arc::new(img)); } } } - self.footage.frame_with(item, f, t, size, float).map(|img| cineon_frame(img, f)) + self.read(|| self.footage.frame_with(item, f, t, size, float)).map(|img| cineon_frame(img, f)) } /// Source → masks, clamped/quantised to the project depth. fn masked_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option { - let mut buf = match self.content_times(ctx, layer) { - Some(times) => self.blurred_source(ctx, layer, ×)?, - None => self.source(ctx, layer)?, + let (mut buf, quantized) = match self.content_times(ctx, layer) { + Some(times) => (self.blurred_source(ctx, layer, ×)?, false), + None => (self.source_with(ctx, layer, true)?, Self::prequantized_footage(layer)), }; - // A solid is filled with a quantised colour: only masks can take it off the grid. + // A solid is filled with a quantised colour, and plain footage comes quantised: only + // masks can take them off the grid. let solid = matches!(layer.source, LayerSource::Solid { .. }); - if masks::apply(ctx, layer, &mut buf, self.mask_blur(ctx, layer)) || !solid { + if masks::apply(ctx, layer, &mut buf, self.mask_blur(ctx, layer)) || !(solid || quantized) { self.pipe.quantize(&mut buf.img); } Some(buf) @@ -900,59 +1246,54 @@ impl<'a> Renderer<'a> { /// Fully processed layer buffer (source → masks → effects → layer styles, flattened). /// Served from the layer cache when the layer's content key matches. pub fn layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { - self.layer_buf_keyed(ctx, layer).map(|(b, _)| b) + self.layer_buf_keyed(ctx, layer).map(|(b, _, _)| b) } /// [`Self::layer_buf`] in the blending space (linear with Blend Colors Using 1.0 Gamma). pub fn blend_layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { - let (b, k) = self.layer_buf_keyed(ctx, layer)?; - Some(self.to_blend(b, k)) + let (b, k, files) = self.layer_buf_keyed(ctx, layer)?; + Some(self.to_blend(b, k, &files)) } - /// A buffer converted to the blending space (cached under a key derived from `key`). - pub(crate) fn to_blend(&self, b: Arc, key: Option) -> Arc { + /// A buffer converted to the blending space (cached under a key derived from `key`, with + /// `files`, the source files `b` was made of). + pub(crate) fn to_blend(&self, b: Arc, key: Option, files: &Arc) -> Arc { let Some(c) = self.pipe.to_blend() else { return b }; let key = key.map(|k| cache::derive(k, 0x1ea7)); - if let (Some(cache), Some(k)) = (self.cache, key) - && let Some(x) = cache.get(k) - { + if let Some((x, _)) = self.cached(key) { return x; } let mut nb = (*b).clone(); color::convert(&mut nb.img, &c); - let nb = Arc::new(nb); - // The buffer the cache keeps (another worker's, if it kept one first). - match (self.cache_to_keep(), key) { - (Some(cache), Some(k)) => cache.insert(k, nb), - _ => nb, - } + self.keep(key, Arc::new(nb), files).0 } - fn layer_buf_keyed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<(Arc, Option)> { + /// The flattened layer buffer, its cache key and the source files it was made of. + fn layer_buf_keyed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<(Arc, Option, Arc)> { let st = self.styled(ctx, layer, None)?; if st.passes.is_empty() { - return Some((st.body, st.key)); + return Some((st.body, st.key, st.files)); } let key = st.key.map(|k| cache::derive(k, 0xf1a7)); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { - return Some((b, key)); + if let Some((b, files)) = self.cached(key) { + return Some((b, key, files)); } let flat = Arc::new(styles::Styled { passes: st.passes.iter().map(|(b, m)| ((**b).clone(), *m)).collect(), body: (*st.body).clone() }.flatten()); - // The buffer the cache keeps (another worker's, if it kept one first). - let flat = match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, flat), - _ => flat, - }; - Some((flat, key)) + let (flat, files) = self.keep(key, flat, &st.files); + Some((flat, key, files)) } /// A layer's source pixels at the context time, before masks, effects and the transform /// (what the motion tracker analyses, like After Effects' Layer panel). `None` for layers /// without pixels. pub fn layer_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option { - self.source(ctx, layer) + Renderer { whole_raster: true, ..*self }.source(ctx, layer) + } + + /// Layer-space pixels after masks and effects, including content outside the viewport. + /// Expression sampleImage reads this rather than the frame-oriented clipped buffer. + pub fn layer_content(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { + Renderer { whole_raster: true, ..*self }.content_buf(ctx, layer) } /// A 3D model or primitive layer rendered on its own, through the comp's camera: what an @@ -981,28 +1322,32 @@ impl<'a> Renderer<'a> { /// Layer pixels after source → masks → effects (no layer styles). pub fn content_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { - self.content_buf_timed(ctx, layer, None).map(|(b, _)| b) + self.content_buf_timed(ctx, layer, None).map(|(b, _, _)| b) } - pub(crate) fn content_buf_timed(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option<(Arc, Option)> { + /// [`Self::content_buf`], its cache key and the source files it was made of. + pub(crate) fn content_buf_timed( + &self, + ctx: &EvalCtx, + layer: &Layer, + mut timing: Option<&mut LayerTiming>, + ) -> Option<(Arc, Option, Arc)> { let key = self.cache.and_then(|_| cache::layer_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer))); - let key = self.content_key(ctx, layer, key); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { + let key = self.content_key(ctx, layer, self.clipped_key(ctx, layer, key)); + if let Some((b, files)) = self.cached(key) { if let Some(t) = timing.as_deref_mut() { t.cached = true; } - return Some((b, key)); + return Some((b, key, files)); } - let buf = self.masked_source(ctx, layer)?; - let buf = Arc::new(self.apply_effects_timed(ctx, layer, buf, false, usize::MAX, timing.map(|t| &mut t.effects))); - // The buffer the cache keeps (another worker's, if it kept one first). - let buf = match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, buf), - _ => buf, - }; - Some((buf, key)) + let (buf, files) = self.recorded(key, |r| { + // (what expressions read while it is made, at shutter times too, goes to its files) + let ctx = &r.with_reads(ctx); + let buf = r.masked_source(ctx, layer)?; + Some(r.apply_effects_timed(ctx, layer, buf, false, usize::MAX, timing.map(|t| &mut t.effects))) + }); + let (buf, files) = self.keep(key, Arc::new(buf?), &files); + Some((buf, key, files)) } /// A layer's input at the context time: source → masks → its first `effects` effects @@ -1010,25 +1355,32 @@ impl<'a> Renderer<'a> { /// what effect `effects` sees. Served from / stored in the layer cache under its own key, /// so scrubbing reuses frames rendered for earlier output frames. pub fn layer_input(&self, ctx: &EvalCtx, layer: &Layer, effects: usize) -> Option> { + // The Layer panel, analysis tools and effect inputs read the whole layer, not the viewport. + Renderer { whole_raster: true, ..*self }.whole_layer_input(ctx, layer, effects) + } + + fn whole_layer_input(&self, ctx: &EvalCtx, layer: &Layer, effects: usize) -> Option> { let key = self.cache.and_then(|_| cache::input_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer), effects)); - let key = self.content_key(ctx, layer, key); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { + let key = self.content_key(ctx, layer, self.clipped_key(ctx, layer, key)); + if let Some((b, _)) = self.cached(key) { return Some(b); } - let mut buf = self.masked_source(ctx, layer)?; - let origin = ctx.effect_bounds(layer).1; - buf.rebase(origin); - if effects > 0 { - buf = self.effect_space_stack(ctx, layer, buf, EffectStack { adjustment: false, limit: effects, origin }, None); - } - let buf = Arc::new(buf); - // The buffer the cache keeps (another worker's, if it kept one first). - let buf = match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, buf), - _ => buf, - }; - Some(buf) + let (buf, files) = self.recorded(key, |r| { + let ctx = &r.with_reads(ctx); + let mut buf = r.masked_source(ctx, layer)?; + let origin = ctx.effect_bounds(layer).1; + buf.rebase(origin); + if effects > 0 { + buf = r.effect_space_stack(ctx, layer, buf, EffectStack { adjustment: false, limit: effects, origin }, None); + } + Some(buf) + }); + Some(self.keep(key, Arc::new(buf?), &files).0) } } + +/// Snap cells can be finer than 1/16 unit: preserve every coordinate bit so visible +/// clips cannot collide with another cell or the empty behind-camera raster. +pub(crate) fn raster_clip_key(key: u64, clip: kurbo::Rect) -> u64 { + [clip.x0, clip.y0, clip.x1, clip.y1].iter().fold(cache::derive(key, 0xc11b), |key, coordinate| cache::derive(key, coordinate.to_bits())) +} diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs new file mode 100644 index 000000000..ed97e50fd --- /dev/null +++ b/crates/render/src/reads.rs @@ -0,0 +1,348 @@ +//! The source files a render read: which footage files its pixels came from, each with its +//! identity (size and modification time) as it was when it was read. +//! +//! A [`FootageSource`](crate::FootageSource) that knows which files it opens notes them while +//! [`FootageSource::recording`](crate::FootageSource::recording) runs; the renderer collects them +//! in a [`ReadLog`] ([`Renderer::reads`](crate::Renderer::reads)). Buffers in the layer cache keep +//! the files they were made of, so a frame served from memory reports the same files as the +//! render that made it, without touching the disk. +//! +//! The list is what a cache entry on disk has to check before it is used: a handful of files per +//! frame, never every file of every footage item. + +use std::sync::{Arc, Mutex, PoisonError}; + +/// The identity of a file as a render read it (frame and layer entries on disk store it, see +/// [`EntryFiles`](crate::disk_cache::EntryFiles)). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum FileStamp { + /// A file on disk: its size in bytes and its modification time (nanoseconds since the Unix + /// epoch, negative before it; `None` only where the file system has none). + Native { len: u64, modified: Option }, + /// Bytes given from memory instead of the file system (the browser's file table): their + /// identity is the size and content hash a + /// [`VirtualFileId`](crate::disk_cache::VirtualFileId) gives for the path. + Virtual, + /// The file could not be read (missing, not a regular file, no permission). What was made + /// without it changes once it can be read again. + Missing, +} + +impl FileStamp { + /// The identity of a file from metadata the caller already has (of an open file). + pub fn of_metadata(md: &std::fs::Metadata) -> FileStamp { + FileStamp::Native { len: md.len(), modified: md.modified().ok().map(epoch_nanos) } + } + + /// The identity of the file at `path` now: one `metadata` call. `None` when the file system + /// can't describe it (missing, or a path served from memory). + pub fn native(path: &str) -> Option { + std::fs::metadata(path).ok().map(|md| FileStamp::of_metadata(&md)) + } +} + +/// `t` in nanoseconds since the Unix epoch, negative before it: every time a file system can +/// store fits (`i128` nanoseconds span far more than any `SystemTime`), saturating otherwise. +pub fn epoch_nanos(t: std::time::SystemTime) -> i128 { + let nanos = |d: std::time::Duration| i128::try_from(d.as_nanos()).unwrap_or(i128::MAX); + match t.duration_since(std::time::UNIX_EPOCH) { + Ok(after) => nanos(after), + Err(before) => nanos(before.duration()).saturating_neg(), + } +} + +/// One file a render read. +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ReadFile { + pub path: Arc, + pub stamp: FileStamp, +} + +impl ReadFile { + /// A file read with the given path and stamp. + pub fn new(path: impl Into>, stamp: FileStamp) -> ReadFile { + ReadFile { path: path.into(), stamp } + } +} + +/// At most this many files are listed per render or cached buffer; more mark the list +/// incomplete (a comp reading more files than this for one frame is not checked file by file). +pub const MAX_READ_FILES: usize = 4096; + +/// The files a render (or one cached buffer) read, each once, sorted by path. +/// +/// Incomplete when it can't say for sure: a footage source that doesn't tell what it reads, a +/// buffer from a store that doesn't keep its files, more than [`MAX_READ_FILES`] files, or one +/// file read with two identities (it changed during the render). A cache entry whose list is +/// incomplete can't be checked against the files, so it must not outlive the session. +/// +/// It also carries where its reads come from, which equality and hashing ignore: the drop +/// generation the earliest of them started at ([`ReadFiles::since`]), and whether a layer cache +/// key can't capture what it was made of ([`ReadFiles::is_unkeyed`]). +#[derive(Clone, Debug, Default)] +pub struct ReadFiles { + files: Vec, + incomplete: bool, + /// The disk cache's drop generation ([`DiskCache::drop_generation`]) when the earliest read + /// behind the list started; `None` when nothing says (a list built by hand). + /// + /// [`DiskCache::drop_generation`]: crate::disk_cache::DiskCache::drop_generation + since: Option, + /// Made of values a layer's cache key doesn't capture (a text Expression Selector evaluates + /// per character): such a buffer is not stored on disk. + unkeyed: bool, +} + +impl PartialEq for ReadFiles { + /// The same files with the same identities (where the reads come from doesn't count). + fn eq(&self, other: &Self) -> bool { + self.files == other.files && self.incomplete == other.incomplete + } +} + +impl Eq for ReadFiles {} + +impl std::hash::Hash for ReadFiles { + /// Hashes what [`PartialEq`] compares. + fn hash(&self, state: &mut H) { + self.files.hash(state); + self.incomplete.hash(state); + } +} + +impl ReadFiles { + /// Note a file read (once per path). + pub fn add(&mut self, file: ReadFile) { + match self.files.binary_search_by(|f| f.path.cmp(&file.path)) { + Ok(i) => { + if self.files.get(i).is_some_and(|f| f.stamp != file.stamp) { + self.incomplete = true; + } + } + Err(i) => { + if self.files.len() >= MAX_READ_FILES { + self.incomplete = true; + } else { + self.files.insert(i, file); + } + } + } + } + + /// Note every file of `other` (whether it is incomplete or unkeyed, and its generation). + pub fn extend(&mut self, other: &ReadFiles) { + self.incomplete |= other.incomplete; + self.unkeyed |= other.unkeyed; + if let Some(g) = other.since { + self.note_since(g); + } + for f in &other.files { + self.add(f.clone()); + } + } + + /// Some files read may be missing from the list (see [`ReadFiles`]). + pub fn mark_incomplete(&mut self) { + self.incomplete = true; + } + + /// Whether the list names every file read. + pub fn is_complete(&self) -> bool { + !self.incomplete + } + + /// The drop generation the earliest read behind the list started at (`None`: unknown). A + /// buffer made of a file dropped after it holds that file as it was before the drop. + pub fn since(&self) -> Option { + self.since + } + + /// A read behind the list started at drop generation `generation` (the earliest one counts). + pub fn note_since(&mut self, generation: u64) { + self.since = Some(self.since.map_or(generation, |s| s.min(generation))); + } + + /// Made of values a layer cache key doesn't capture (see [`ReadFiles::is_unkeyed`]). + pub fn mark_unkeyed(&mut self) { + self.unkeyed = true; + } + + /// Made of values a layer cache key doesn't capture: kept in memory, never stored on disk as + /// a layer buffer. (A frame's key captures them: frame entries are not affected.) + pub fn is_unkeyed(&self) -> bool { + self.unkeyed + } + + /// The files, sorted by path. + pub fn files(&self) -> &[ReadFile] { + &self.files + } + + /// The identity `path` was read with. + pub fn get(&self, path: &str) -> Option { + let i = self.files.binary_search_by(|f| (*f.path).cmp(path)).ok()?; + self.files.get(i).map(|f| f.stamp) + } + + /// The number of files in the list. + pub fn len(&self) -> usize { + self.files.len() + } + + /// Whether the list holds no files. + pub fn is_empty(&self) -> bool { + self.files.is_empty() + } +} + +impl FromIterator for ReadFiles { + /// Collects files into a list, adding each in turn. + fn from_iter>(iter: I) -> Self { + let mut out = ReadFiles::default(); + for f in iter { + out.add(f); + } + out + } +} + +/// Collects the files a render reads, from any thread (the layers of a frame render in +/// parallel). +#[derive(Debug, Default)] +pub struct ReadLog { + files: Mutex, +} + +impl ReadLog { + /// An empty read log. + pub fn new() -> ReadLog { + ReadLog::default() + } + + /// An empty read log for reads that start at drop generation `generation` (see + /// [`ReadFiles::since`]). + pub fn starting_at(generation: u64) -> ReadLog { + let mut files = ReadFiles::default(); + files.note_since(generation); + ReadLog { files: Mutex::new(files) } + } + + /// Locks the file list, recovering from a poisoned lock. + fn lock(&self) -> std::sync::MutexGuard<'_, ReadFiles> { + self.files.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Note a file read. + pub fn note(&self, file: ReadFile) { + self.lock().add(file); + } + + /// Note every file of `files` (and whether it is incomplete). + pub fn note_all(&self, files: &ReadFiles) { + if files.is_empty() && files.is_complete() && files.since.is_none() && !files.unkeyed { + return; + } + self.lock().extend(files); + } + + /// Some files read can't be listed (see [`ReadFiles`]). + pub fn mark_incomplete(&self) { + self.lock().mark_incomplete(); + } + + /// What is read is made of values a layer cache key doesn't capture + /// ([`ReadFiles::is_unkeyed`]). + pub fn mark_unkeyed(&self) { + self.lock().mark_unkeyed(); + } + + /// The files noted so far. + pub fn files(&self) -> ReadFiles { + self.lock().clone() + } + + /// The files noted. + pub fn into_files(self) -> ReadFiles { + self.files.into_inner().unwrap_or_else(PoisonError::into_inner) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A native file with the given length for the tests. + fn file(path: &str, len: u64) -> ReadFile { + ReadFile::new(path, FileStamp::Native { len, modified: Some(7) }) + } + + #[test] + fn files_are_listed_once_sorted_by_path() { + let files: ReadFiles = [file("/b", 1), file("/a", 2), file("/b", 1)].into_iter().collect(); + assert_eq!(files.files().iter().map(|f| &*f.path).collect::>(), ["/a", "/b"]); + assert!(files.is_complete()); + assert_eq!(files.get("/a"), Some(FileStamp::Native { len: 2, modified: Some(7) })); + assert_eq!(files.get("/c"), None); + } + + /// A file read twice with different identities changed during the render: the list can't + /// vouch for what was made of it. + #[test] + fn a_file_read_with_two_identities_makes_the_list_incomplete() { + let files: ReadFiles = [file("/a", 1), file("/a", 2)].into_iter().collect(); + assert_eq!(files.len(), 1); + assert!(!files.is_complete()); + } + + /// Modification times keep their full value: before 1970 (not "no time") and past 2554 + /// (where `u64` nanoseconds end), so two such files never look alike. + #[test] + fn modification_times_are_kept_whole() { + use std::time::{Duration, UNIX_EPOCH}; + let day = Duration::from_secs(86_400); + assert_eq!(epoch_nanos(UNIX_EPOCH), 0); + assert_eq!(epoch_nanos(UNIX_EPOCH - day), -86_400_000_000_000); + let far = 600 * 365 * day; + if let Some(t) = UNIX_EPOCH.checked_add(far) { + assert_eq!(epoch_nanos(t), i128::try_from(far.as_nanos()).unwrap()); + } + let dir = std::env::temp_dir().join(format!("effectcraft-stamp-1969-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (a, b) = (dir.join("a.bin"), dir.join("b.bin")); + let mut stamps = vec![]; + for (p, back) in [(&a, day), (&b, 2 * day)] { + std::fs::write(p, b"abc").unwrap(); + let f = std::fs::File::options().write(true).open(p).unwrap(); + if f.set_modified(UNIX_EPOCH - back).is_err() { + // (a file system that can't store times before 1970) + let _ = std::fs::remove_dir_all(&dir); + return; + } + drop(f); + stamps.push(FileStamp::native(&p.to_string_lossy()).unwrap()); + } + assert!(matches!(stamps[0], FileStamp::Native { modified: Some(t), .. } if t < 0), "{:?}", stamps[0]); + assert_ne!(stamps[0], stamps[1], "two files from before 1970 with the same size"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_list_is_bounded() { + let files: ReadFiles = (0..MAX_READ_FILES + 3).map(|i| file(&format!("/f{i:06}"), 1)).collect(); + assert_eq!(files.len(), MAX_READ_FILES); + assert!(!files.is_complete(), "files past the bound make the list incomplete, never silently short"); + } + + #[test] + fn incompleteness_carries_over() { + let mut part = ReadFiles::default(); + part.mark_incomplete(); + let log = ReadLog::new(); + log.note(file("/a", 1)); + log.note_all(&part); + let all = log.into_files(); + assert_eq!(all.len(), 1); + assert!(!all.is_complete()); + } +} diff --git a/crates/render/src/shapes.rs b/crates/render/src/shapes.rs index 2497ea807..df92846ce 100644 --- a/crates/render/src/shapes.rs +++ b/crates/render/src/shapes.rs @@ -686,6 +686,12 @@ const BATCH_PIXELS: usize = 8 << 20; /// Each draw rasterises and composites only its own pixel rectangle; coverage masks of /// consecutive draws are rasterised in parallel, then composited in stacking order. pub fn render(ctx: &EvalCtx, layer: &Layer, contents: &PropGroup, s: f64) -> Buf { + render_in(ctx, layer, contents, s, None) +} + +/// [`render`], only the part of the layer inside `clip` (layer space; the part the output shows, +/// see `Renderer::raster_clip`). +pub fn render_in(ctx: &EvalCtx, layer: &Layer, contents: &PropGroup, s: f64, clip: Option) -> Buf { let mut arena = Vec::new(); let (draws, _) = collect(ctx, layer, contents, &mut arena); // Bottom-most draw first. @@ -702,9 +708,7 @@ pub fn render(ctx: &EvalCtx, layer: &Layer, contents: &PropGroup, s: f64) -> Buf let Some(b) = resolved.iter().map(|r| r.2).reduce(|a, b| a.union(b)) else { return Buf { img: Image::new(1, 1), offset: [0.0, 0.0], scale: s } }; // Keep buffers sane for runaway geometry. let b = b.intersect(kurbo::Rect::new(-20000.0, -20000.0, 20000.0, 20000.0)); - let w = ((b.width() * s).ceil() as u32 + 4).clamp(1, 16384); - let h = ((b.height() * s).ceil() as u32 + 4).clamp(1, 16384); - let offset = [-b.x0 * s + 2.0, -b.y0 * s + 2.0]; + let Some((w, h, offset)) = crate::text::raster_window(b, s, clip) else { return Buf { img: Image::new(1, 1), offset: [0.0, 0.0], scale: s } }; let m = Mat3::translate(vec2(offset[0], offset[1])) * Mat3::scale(vec2(s, s)); let px_rect = |r: kurbo::Rect| -> Option { let x0 = (r.x0 * s + offset[0]).floor().max(0.0); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 865a4f59f..4cfa35d0b 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -11,6 +11,7 @@ mod auto; mod aux_channels; mod collapse; mod color; +mod drop_shadow_cover; mod footage_size; mod frame_blend; mod guides; @@ -20,8 +21,11 @@ mod mask_feather; mod motion_tile; mod nested; mod paint; +mod proxy_cache; +mod raster_clip; mod remap; mod roi; +mod stretch_limits; mod styles; mod time; @@ -328,7 +332,7 @@ fn card_dance_comp_camera_matches_the_default_view() { assert!(img.get(10, 50)[3] < 0.01); } -/// A black 2D solid with CC Particle World, under a camera layer panned right by `pan` px. +/// A black 2D solid with Particle Emitter 3D, under a camera layer panned right by `pan` px. fn particle_world_scene(pan: f64) -> (Project, ItemId) { let (mut p, cid, comp) = setup(); let mut l = solid(&mut p, &comp, [0.0, 0.0, 0.0], 200, 100); @@ -358,7 +362,7 @@ fn particles_x(img: &crate::Image) -> f32 { sx / m } -/// #397: CC Particle World on a 2D layer is seen through the comp's camera layer, and the layer +/// #397: Particle Emitter 3D on a 2D layer is seen through the comp's camera layer, and the layer /// cache notices the camera moving. #[test] fn particle_world_follows_the_comp_camera() { @@ -373,7 +377,7 @@ fn particle_world_follows_the_comp_camera() { assert!(b < a - 20.0, "panning the camera right moves the particles left: {a} -> {b}"); } -/// A black solid with CC Particle World whose Birth Rate is 3 until layer time `cut`, then 0 a +/// A black solid with Particle Emitter 3D whose Birth Rate is 3 until layer time `cut`, then 0 a /// frame later (`None`: 3 throughout); the layer starts at comp time `start`, stretched `stretch` %. fn burst_scene(cut: Option, start: f64, stretch: f64) -> (Project, ItemId) { burst_scene_keys(cut, start, stretch, false) @@ -482,9 +486,148 @@ impl crate::eval::ExprHost for ControllerRate { } } +/// An expression that reads a file (as `sampleImage` does, into [`EvalCtx::reads`]) and keeps +/// the value. +/// +/// [`EvalCtx::reads`]: crate::eval::EvalCtx::reads +struct ReadsAFile; + +impl crate::eval::ExprHost for ReadsAFile { + fn eval(&self, ctx: &crate::eval::EvalCtx, _: &effectcraft_project::Layer, _: &effectcraft_project::Property, value: &Value) -> Result { + if let Some(log) = ctx.reads { + log.note(crate::reads::ReadFile::new("/sampled.png", crate::reads::FileStamp::Native { len: 3, modified: Some(1) })); + } + Ok(value.clone()) + } +} + +/// What expressions read while a cached buffer is made (a mask expression, which mask motion +/// blur also runs at shutter times the cache key doesn't see) goes to that buffer's files, not +/// only to the frame's (#3184): a later render served the buffer lists the file too. Content, +/// a Time effect's input and an adjustment layer's footprint. +#[test] +fn what_expressions_read_goes_to_the_files_of_the_buffer_they_make() { + use crate::reads::ReadLog; + use crate::{NoFootage, RenderOpts, Renderer}; + let (mut p, cid, comp) = setup(); + for adjustment in [false, true] { + let mut l = solid(&mut p, &comp, [1.0, 1.0, 1.0], 200, 100); + l.switches.adjustment = adjustment; + let mut next = p.next_id; + let m = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([50.0, 50.0], 40.0, 40.0), MaskMode::Add, [255, 255, 0]); + p.next_id = next; + l.props.sub_mut("masks").unwrap().children.push(m.into()); + l.props.prop_mut("masks/#1/path").unwrap().expr = Some(effectcraft_project::Expression { text: "sampled".into(), enabled: true }); + p.comp_mut(cid).unwrap().layers.push(l); + } + let cache = crate::LayerCache::default(); + let c = p.comp(cid).unwrap(); + let (content, adjustment) = (&c.layers[0], &c.layers[1]); + // `make`, rendered once with the expressions (the files go to `log`) and then served from + // the cache to a render without them: the files that render lists. + let files_served = |what: &str, make: &dyn Fn(&Renderer, &crate::eval::EvalCtx) -> bool| { + let log = ReadLog::new(); + let mut r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + r.expr = Some(&ReadsAFile); + r.cache = Some(&cache); + r.reads = Some(&log); + assert!(make(&r, &r.ctx(cid, c, Tick::ZERO)), "{what}"); + assert!(log.files().get("/sampled.png").is_some(), "{what}: the frame lists the file"); + let hits = cache.stats().hits; + let served = ReadLog::new(); + r.expr = None; + r.reads = Some(&served); + assert!(make(&r, &r.ctx(cid, c, Tick::ZERO)), "{what}"); + assert!(cache.stats().hits > hits, "{what}: served from the cache"); + served.into_files() + }; + let files = files_served("content", &|r, ctx| r.content_buf(ctx, content).is_some()); + assert!(files.get("/sampled.png").is_some(), "content: {files:?}"); + let files = files_served("input", &|r, ctx| r.layer_input(ctx, content, 0).is_some()); + assert!(files.get("/sampled.png").is_some(), "input: {files:?}"); + let files = files_served("footprint", &|r, ctx| r.adjustment_footprint(ctx, adjustment).is_some()); + assert!(files.get("/sampled.png").is_some(), "footprint: {files:?}"); +} + +/// A text Expression Selector whose Amount is 0 for the first character and the width of the +/// footage item named `ref.png` for the others (`textIndex == 1 ? 0 : footage("ref.png").width`). +struct WidthOfRef; + +impl crate::eval::ExprHost for WidthOfRef { + fn eval(&self, _: &crate::eval::EvalCtx, _: &effectcraft_project::Layer, _: &effectcraft_project::Property, value: &Value) -> Result { + Ok(value.clone()) + } + fn eval_text_selector( + &self, + ctx: &crate::eval::EvalCtx, + _: &effectcraft_project::Layer, + _: &effectcraft_project::Property, + index: usize, + _: usize, + _: [f64; 3], + ) -> Result<[f64; 3], String> { + let width = ctx.project.items.values().find(|i| i.name == "ref.png").and_then(|i| i.dimensions()).map_or(0.0, |d| d.0 as f64); + Ok([if index == 1 { 0.0 } else { width }; 3]) + } +} + +/// A text layer whose Expression Selector reads a footage item's size for every character but +/// the first: the layer's key holds the first character's amount only, so its buffer is not +/// stored on disk. Reopened over the same disk cache after the footage's width changed (16 to +/// 64), the frame matches one rendered without a cache. +#[test] +fn a_text_expression_selector_is_not_served_from_the_disk_cache() { + use crate::disk_cache::{DiskCache, Kind}; + use crate::{LayerCache, NoFootage, RenderOpts, Renderer}; + let project = |width: u32| { + let (mut p, cid, comp) = setup(); + let f = effectcraft_project::Footage { has_video: true, width, height: 16, ..Default::default() }; + p.add_item("ref.png", Label::None, None, ItemKind::Footage(f)); + let mut l = build::layer(&mut p, &comp, "Text", LayerSource::Text, (200, 100), None); + l.props.prop_mut("text/sourceText").unwrap().value = Value::Text(Box::new(TextDoc { text: "HH".into(), size: 60.0, ..Default::default() })); + let mut next = p.next_id; + let mut ids = Ids(&mut next); + let mut props = build::text_anim_props(&mut ids, "opacity", false); + for pr in &mut props { + pr.value = Value::Scalar(0.0); + } + let mut animator = build::text_animator(&mut ids, "Animator 1", props); + let sel = build::expression_selector(&mut ids, "Expression Selector 1"); + p.next_id = next; + animator.sub_mut("selectors").unwrap().children.push(sel.into()); + l.props.group_mut("text/animators").unwrap().children.push(animator.into()); + p.comp_mut(cid).unwrap().layers.push(l); + (p, cid) + }; + let render = |p: &Project, cid: ItemId, cache: Option<&LayerCache>| { + let mut r = Renderer::new(p, &NoFootage, RenderOpts::default()); + r.expr = Some(&WidthOfRef); + r.cache = cache; + r.comp_frame(cid, Tick::ZERO) + }; + let dir = tempfile::tempdir().unwrap(); + let dc = DiskCache::open(dir.path(), 1 << 30).unwrap(); + dc.set_min_layer_ms(0); + // First session: the 16 px wide footage. + let (p16, cid) = project(16); + let cache = LayerCache::default(); + cache.set_disk(Some(dc.clone())); + let first = render(&p16, cid, Some(&cache)); + dc.flush(); + assert!(first.data.iter().any(|px| px[3] > 0.5), "the text renders"); + // Reopened with a fresh memory cache, the footage now 64 px wide. + let (p64, cid) = project(64); + let uncached = render(&p64, cid, None); + assert_ne!(uncached.data, first.data, "the second character's opacity follows the width"); + let reopened = LayerCache::default(); + reopened.set_disk(Some(dc.clone())); + assert_eq!(render(&p64, cid, Some(&reopened)).data, uncached.data, "not the buffer from before the change"); + assert!(dc.keys(Kind::Layer).is_empty(), "the text layer's buffer is not on disk"); +} + /// A Birth Rate expression reading another layer: changing that layer changes the history but /// not the current rate (0) nor this layer's properties, which is all the layer cache key sees. -/// CC Particle World layers with expressions therefore aren't layer cached. +/// Particle Emitter 3D layers with expressions therefore aren't layer cached. #[test] fn particle_world_with_a_birth_rate_expression_is_not_served_from_the_layer_cache() { let scene = |opacity: f64| { @@ -517,8 +660,8 @@ fn particle_world_with_a_birth_rate_expression_is_not_served_from_the_layer_cach assert!(light(&b) > 1.0 && light(&b) < light(&a), "fewer births: {} vs {}", light(&b), light(&a)); } -/// A grey solid (CC Mr. Mercury shades its blobs from it) with effect `id` (CC Particle Systems -/// II, CC Mr. Mercury): Birth Rate `rate`, +/// A grey solid (Liquid Particles shades its blobs from it) with effect `id` (CC Particle Systems +/// II, Liquid Particles): Birth Rate `rate`, /// or keyed 3 until 0.5 s and 0 a frame later (`None`); Longevity 1 s. fn system_scene(id: &str, rate: Option) -> (Project, ItemId) { let (mut p, cid, comp) = setup(); @@ -537,7 +680,7 @@ fn system_scene(id: &str, rate: Option) -> (Project, ItemId) { (p, cid) } -/// #1373 for CC Particle Systems II and CC Mr. Mercury through the renderer: a keyed burst +/// #1373 for Particle Emitter 2D and Liquid Particles through the renderer: a keyed burst /// draws as the constant rate during it, still draws after the rate drops to 0 (unlike a rate /// of 0 throughout), and draws as nothing born once Longevity has run out. #[test] @@ -820,6 +963,41 @@ fn effects_read_layer_params() { assert!(px[2] > 0.99 && px[0] < 0.01, "{px:?}"); } +/// A cached layer whose effect reads a precomp layer: how the precomp's layers render depends on +/// Switches Affect Nested Comps (the precomp layer's Draft quality passes down) and on the +/// switches the reading layer's own comp inherits, so the key must tell them apart (a buffer +/// made under the other setting, from memory or disk, is stale). +#[test] +fn a_cached_layer_reading_a_precomp_is_keyed_by_the_nested_switches() { + let (mut p, cid, comp) = setup(); + let mut inner = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + // A rotated square off the pixel grid: Draft (nearest) and Best (bilinear) sampling differ. + let mut dot = solid(&mut p, &inner, [1.0, 1.0, 1.0], 40, 40); + dot.props.prop_mut("transform/position").unwrap().value = Value::Vec3([100.3, 50.6, 0.0]); + dot.props.prop_mut("transform/rotation").unwrap().value = Value::Scalar(30.0); + inner.layers.push(dot); + let iid = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into())); + let mut pre = build::layer(&mut p, &comp, "Inner", LayerSource::Comp { item: iid }, (200, 100), None); + pre.switches.video = false; + pre.switches.quality = effectcraft_project::Quality::Draft; + let mut top = solid(&mut p, &comp, [1.0, 0.0, 0.0], 200, 100); + add_effect_200(&mut p, &mut top, "ec.channel.blend", &[("blendWithLayer", Value::Layer(Some(pre.id.0)))]); + let c = p.comp_mut(cid).unwrap(); + c.layers.push(top); + c.layers.push(pre); + let frame = |nested_switches: bool, cache: Option<&crate::LayerCache>| { + let mut r = crate::Renderer::new(&p, &crate::NoFootage, crate::RenderOpts { nested_switches, ..Default::default() }); + r.cache = cache; + r.comp_frame(cid, Tick::ZERO).data + }; + let (on, off) = (frame(true, None), frame(false, None)); + assert!(on != off, "the precomp layer's Draft quality passes down"); + let cache = crate::LayerCache::default(); + assert!(frame(true, Some(&cache)) == on); + assert!(frame(false, Some(&cache)) == off, "not the buffer made with switches affecting nested comps"); + assert!(frame(true, Some(&cache)) == on, "and back"); +} + /// Records whether the GPU compositor was asked to draw a frame. struct ProbeAccel(std::sync::atomic::AtomicBool); impl crate::Accelerator for ProbeAccel { @@ -838,6 +1016,71 @@ impl crate::Accelerator for ProbeAccel { } } +/// Counts [`Accelerator::frame_end`] and optionally panics inside [`Accelerator::comp_frame`]. +struct EndAccel { + ends: std::sync::atomic::AtomicUsize, + panic: std::sync::atomic::AtomicBool, +} +impl crate::Accelerator for EndAccel { + fn name(&self) -> String { + "end".into() + } + fn comp_frame(&self, _r: &crate::Renderer, _comp: ItemId, _t: Tick) -> Option { + if self.panic.load(std::sync::atomic::Ordering::SeqCst) { + panic!("comp_frame"); + } + Some(crate::Image::new(1, 1)) + } + fn supports_effect(&self, _id: &str) -> bool { + false + } + fn effects(&self, _chain: &[crate::FxStep], _buf: &crate::Buf, _levels: Option) -> Option { + None + } + fn frame_end(&self) { + self.ends.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } +} + +#[test] +fn comp_frame_ends_the_frame_when_the_render_panics() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::sync::atomic::Ordering; + let (mut p, cid, comp) = setup(); + let l = solid(&mut p, &comp, [1.0, 0.0, 0.0], 50, 50); + p.comp_mut(cid).unwrap().layers.push(l); + let a = EndAccel { ends: Default::default(), panic: true.into() }; + let mut r = crate::Renderer::new(&p, &crate::NoFootage, crate::RenderOpts { backend: crate::Backend::Gpu, ..Default::default() }); + r.accel = Some(&a); + assert!(catch_unwind(AssertUnwindSafe(|| crate::passes::block_on(crate::passes::comp_frame(&r, cid, Tick::ZERO)))).is_err()); + assert_eq!(a.ends.load(Ordering::SeqCst), 1); + a.panic.store(false, Ordering::SeqCst); + a.ends.store(0, Ordering::SeqCst); + let _ = crate::passes::block_on(crate::passes::comp_frame(&r, cid, Tick::ZERO)); + assert_eq!(a.ends.load(Ordering::SeqCst), 1); +} + +/// The renderer labels Project Settings ▸ Video Rendering and Effects draws parse back as the +/// backend they name (in any case), and the older spellings still work. +#[test] +fn renderer_labels_parse_back_and_keep_the_older_spellings() { + use crate::Backend; + for (label, backend) in [ + ("GPU Acceleration", Backend::Gpu), + ("gpu acceleration", Backend::Gpu), + ("Mercury GPU Acceleration", Backend::Gpu), + ("gpu", Backend::Gpu), + ("Software Rendering", Backend::Cpu), + ("software rendering", Backend::Cpu), + ("Mercury Software Only", Backend::Cpu), + ("cpu", Backend::Cpu), + ("Auto", Backend::Auto), + ] { + assert_eq!(Backend::parse(label), Some(backend), "{label}"); + } + assert_eq!(Backend::parse("Vulkan"), None); +} + #[test] fn auto_backend_sends_2d_and_3d_comps_to_the_gpu() { let (mut p, cid, comp) = setup(); @@ -1004,11 +1247,11 @@ fn effects_on_text_reach_past_the_text_bounds() { } assert!( painted > 50 && hi.saturating_sub(lo) > 100, - "CC Tiler tiles the glyphs across the layer region, not just its text bounds: {painted} painted, x-span {lo}..{hi}" + "Scaled Tiles tiles the glyphs across the layer region, not just its text bounds: {painted} painted, x-span {lo}..{hi}" ); } -/// #658: CC Smear drags text glyphs beyond the text layer's own bounds. Pixels smeared past +/// #658: Directional Smear drags text glyphs beyond the text layer's own bounds. Pixels smeared past /// the painted rectangle used to fall off its edge, so the liquid trail never appeared. #[test] fn cc_smear_trails_text_past_its_bounds() { @@ -1027,7 +1270,7 @@ fn cc_smear_trails_text_past_its_bounds() { ); p.comp_mut(cid).unwrap().layers = vec![l].into(); let smeared = right(&render_frame(&p, cid, Tick::ZERO, 1.0)); - assert!(plain > 40 && smeared > plain + 25, "CC Smear trails the glyphs past the text bounds: right edge {plain} → {smeared}"); + assert!(plain > 40 && smeared > plain + 25, "Directional Smear trails the glyphs past the text bounds: right edge {plain} → {smeared}"); } /// A layer parameter pointing at a shape layer sees all of it (in its effect space), and the @@ -1283,7 +1526,7 @@ fn solo_excludes_other_layers_outside_the_soloed_layers_range() { assert_eq!(second.get(100, 50), [0.0, 0.0, 1.0, 1.0], "only B inside its range"); } -/// #1252: a layer blended with a CC Particle World layer, under a camera panned by `pan` px. +/// #1252: a layer blended with a Particle Emitter 3D layer, under a camera panned by `pan` px. fn scene_reader_dependency(pan: f64) -> (Project, ItemId) { let (mut p, cid, comp) = setup(); let mut source = solid(&mut p, &comp, [0.0, 0.0, 0.0], 200, 100); diff --git a/crates/render/src/tests/auto.rs b/crates/render/src/tests/auto.rs index 22f1a6215..a53bb718a 100644 --- a/crates/render/src/tests/auto.rs +++ b/crates/render/src/tests/auto.rs @@ -14,12 +14,13 @@ struct MockAccel { handle: bool, calls: AtomicUsize, pick: AutoPick, + effect_calls: AtomicUsize, } impl MockAccel { /// Construct a renderer stand-in without making assumptions about scheduling or speed. fn new(handle: bool) -> MockAccel { - MockAccel { handle, calls: Default::default(), pick: Default::default() } + MockAccel { handle, calls: Default::default(), pick: Default::default(), effect_calls: Default::default() } } /// Number of full-frame requests dispatched to this accelerator. fn calls(&self) -> usize { @@ -42,6 +43,7 @@ impl Accelerator for MockAccel { }) } fn supports_effect(&self, _id: &str) -> bool { + self.effect_calls.fetch_add(1, Ordering::SeqCst); false } fn effects(&self, _chain: &[crate::FxStep], _buf: &crate::Buf, _levels: Option) -> Option { @@ -160,3 +162,201 @@ fn auto_pick_follows_changing_costs() { assert!(pick.stats(AutoKey::new(ItemId(7), 1.0, true)).is_none()); assert!(pick.stats(AutoKey::new(ItemId(7), 0.5, false)).is_none()); } + +/// Counts actual CPU source reads and rejects any CPU fallback inside a GPU error scope. +struct ScopedFootage { + in_scope: std::sync::atomic::AtomicBool, + reads: AtomicUsize, +} +impl crate::FootageSource for ScopedFootage { + fn frame(&self, _: ItemId, f: &effectcraft_project::Footage, _: Tick) -> Option> { + assert!(!self.in_scope.load(Ordering::SeqCst), "CPU fallback ran before GPU validation/cleanup"); + self.reads.fetch_add(1, Ordering::SeqCst); + Some(std::sync::Arc::new(crate::Image::filled(f.width, f.height, [1.0, 0.0, 0.0, 1.0]))) + } +} + +fn scoped_project() -> (Project, ItemId) { + let (mut p, cid) = project(); + let comp = p.comp(cid).unwrap().clone(); + let footage = effectcraft_project::Footage { + path: "synthetic.png".into(), + kind: effectcraft_project::FootageKind::Still, + width: 50, + height: 50, + has_video: true, + duration: Tick::from_seconds_f64(2.0), + ..Default::default() + }; + let item = p.add_item("Source", Label::Red, None, ItemKind::Footage(footage)); + let mut layer = build::layer(&mut p, &comp, "Source", LayerSource::Footage { item }, (50, 50), None); + super::add_effect_200(&mut p, &mut layer, "ec.blur.gaussian", &[]); + p.comp_mut(cid).unwrap().layers = vec![layer].into(); + (p, cid) +} + +/// #3357: a declined GPU frame must not allocate a CPU frame only to discard it when the +/// enclosing GPU scope reports a fault. The caller retries on a fresh CPU renderer once. +#[test] +fn failed_gpu_scope_returns_before_cpu_fallback() { + let (p, cid) = scoped_project(); + for handled in [false, true] { + let a = MockAccel::new(handled); + let src = ScopedFootage { in_scope: false.into(), reads: 0.into() }; + let mut r = Renderer::new(&p, &src, RenderOpts { backend: Backend::Gpu, ..Default::default() }); + r.accel = Some(&a); + let result = r.comp_frame_scoped(cid, Tick::ZERO, |a| { + src.in_scope.store(true, Ordering::SeqCst); + let frame = a.comp_frame(&r, cid, Tick::ZERO); + drop(frame); + src.in_scope.store(false, Ordering::SeqCst); + Err::, _>("device retired") + }); + assert_eq!(result.unwrap_err(), "device retired"); + assert_eq!(src.reads.load(Ordering::SeqCst), 0); + let frame = r.with_accel(None).comp_frame(cid, Tick::ZERO); + assert!(frame.get(100, 50)[3] > 0.99); + assert_eq!(src.reads.load(Ordering::SeqCst), 1); + assert_eq!(a.calls(), 1); + } +} + +/// A healthy decline closes its scope before CPU work, and still records Auto timings. +#[test] +fn healthy_gpu_decline_renders_cpu_once_outside_scope() { + let (p, cid) = scoped_project(); + let a = MockAccel::new(false); + let src = ScopedFootage { in_scope: false.into(), reads: 0.into() }; + let mut r = Renderer::new(&p, &src, RenderOpts { backend: Backend::Auto, ..Default::default() }); + r.accel = Some(&a); + // Auto warms up CPU first: the first frame renders on the CPU without a GPU scope. + r.comp_frame_scoped(cid, Tick::ZERO, |_| -> Result, ()> { panic!("Auto's CPU warm-up frame must not enter GPU error scopes") }) + .unwrap(); + assert_eq!(src.reads.load(Ordering::SeqCst), 1); + assert_eq!(a.calls(), 0); + // The next one is the GPU's warm-up frame, which the accelerator declines. + let frame = r + .comp_frame_scoped(cid, Tick::ZERO, |a| { + src.in_scope.store(true, Ordering::SeqCst); + let frame = a.comp_frame(&r, cid, Tick::ZERO); + src.in_scope.store(false, Ordering::SeqCst); + Ok::<_, ()>(frame) + }) + .unwrap(); + assert!(frame.get(100, 50)[3] > 0.99); + assert_eq!(src.reads.load(Ordering::SeqCst), 2); + assert_eq!(a.calls(), 1); + assert_eq!(a.pick.stats(AutoKey::new(cid, 1.0, false)).unwrap().cpu_frames, 2); + // Auto's next frame stays on CPU, without entering a GPU scope at all. + r.comp_frame_scoped(cid, Tick::ZERO, |_| -> Result, ()> { panic!("Auto CPU choice must not enter GPU error scopes") }).unwrap(); + assert_eq!(src.reads.load(Ordering::SeqCst), 3); + assert_eq!(a.effect_calls.load(Ordering::SeqCst), 0, "CPU effects must not use the GPU outside its scope"); +} + +/// A preview starts with every lane asking at once, before any frame is measured: the first +/// frames (the ones on screen) render on the CPU; once one is measured, one lane takes a GPU +/// warm-up frame, and the next waits for its time. (Every lane took a GPU warm-up frame on an +/// integrated GPU 2–4× slower than the CPU, and each first playback stalled at its start.) +#[test] +fn auto_pick_warms_the_gpu_up_one_frame_at_a_time() { + let pick = AutoPick::default(); + let key = AutoKey::new(ItemId(3), 1.0, false); + let first: Vec = (0..12).map(|_| pick.choose(key)).collect(); + assert!(!first.iter().any(|g| *g), "{first:?}"); + pick.record(key, false, 10.0); + let next: Vec = (0..12).map(|_| pick.choose(key)).collect(); + assert_eq!(next.iter().filter(|g| **g).count(), 1, "{next:?}"); + // The CPU frames finish first: still no second GPU frame while the first runs. + for _ in 0..22 { + pick.record(key, false, 10.0); + } + assert!(!(0..12).any(|_| pick.choose(key)), "a second GPU warm-up frame while one runs"); + // Measured: the next warm-up frame may go to the GPU. + pick.record(key, true, 40.0); + assert!(pick.choose(key)); + // A re-probe of the slow side runs one frame at a time too. + let pick = AutoPick::default(); + let mut gpu_asked = 0; + for _ in 0..(4 * AutoPick::REPROBE) { + // (sequential warm-up, then GPU frames held: as lanes that never report back) + if pick.choose(key) { + gpu_asked += 1; + if pick.stats(key).is_none_or(|s| s.gpu_frames < AutoPick::WARMUP) { + pick.record(key, true, 40.0); + } + } else { + pick.record(key, false, 10.0); + } + } + assert!(gpu_asked <= AutoPick::WARMUP as usize + 1, "asked the GPU {gpu_asked} times"); +} + +/// Frames render side by side: twelve CPU frames of 210 ms each at once cost ~18 ms a frame, +/// so a lone GPU frame of 175 ms is the slower side (it measured faster and took the comp). +#[test] +fn auto_pick_counts_frames_running_side_by_side() { + let pick = AutoPick::default(); + let key = AutoKey::new(ItemId(4), 0.5, false); + // Twelve lanes: each starts its next frame as soon as one is done. + let mut lanes: std::collections::VecDeque = (0..12).map(|_| pick.choose(key)).collect(); + for _ in 0..240 { + let Some(gpu) = lanes.pop_front() else { break }; + pick.record(key, gpu, if gpu { 175.0 } else { 210.0 }); + lanes.push_back(pick.choose(key)); + } + let s = pick.stats(key).unwrap(); + assert!(s.cpu_ms.unwrap() < 30.0 && s.gpu_ms.unwrap() > 100.0, "{s:?}"); + assert!(lanes.iter().filter(|g| **g).count() <= 1, "{lanes:?}"); +} + +/// A frame that ends without a time (a GPU failure, a remote frame replaced before it finished) +/// no longer counts as running: the frames after it are timed as one at a time. (It stayed +/// counted, and every later frame on its side was timed as half its cost.) +#[test] +fn auto_pick_abandoned_frames_stop_counting_as_running() { + let pick = AutoPick::default(); + let key = AutoKey::new(ItemId(5), 1.0, false); + let mut dropped = [false; 2]; + for _ in 0..16 { + let gpu = pick.choose(key); + if !std::mem::replace(&mut dropped[usize::from(gpu)], true) { + pick.abandoned(key, gpu); + continue; + } + pick.record(key, gpu, if gpu { 40.0 } else { 10.0 }); + } + let s = pick.stats(key).unwrap(); + assert_eq!((s.cpu_ms, s.gpu_ms), (Some(10.0), Some(40.0)), "{s:?}"); +} + +/// A ticket that never reports (dropped on an error, a retry elsewhere, a cancelled export +/// future) ends its frame like [`AutoPick::abandoned`]; one the GPU declined reports from the +/// CPU. (Each exit that skipped `record` left its frame counted as running, and every later +/// frame on that side was timed as one of several side by side.) +#[test] +fn auto_tickets_end_their_frame_on_every_exit() { + let pick = AutoPick::default(); + let key = AutoKey::new(ItemId(6), 1.0, false); + let mut dropped = [false; 2]; + for _ in 0..16 { + let t = pick.ticket(key); + let gpu = t.gpu(); + if !std::mem::replace(&mut dropped[usize::from(gpu)], true) { + drop(t); + continue; + } + t.record(if gpu { 40.0 } else { 10.0 }); + } + let s = pick.stats(key).unwrap(); + assert_eq!((s.cpu_ms, s.gpu_ms), (Some(10.0), Some(40.0)), "{s:?}"); + // Declined: the frame renders on the CPU and reports there, one frame on it. + let key = AutoKey::new(ItemId(7), 1.0, false); + pick.ticket(key).record(10.0); + let mut t = pick.ticket(key); + assert!(t.gpu(), "the GPU's warm-up frame"); + t.declined(); + assert!(!t.gpu()); + t.record(10.0); + pick.ticket(key).record(10.0); + assert_eq!(pick.stats(key).unwrap().cpu_ms, Some(10.0), "timed as one frame on the CPU"); +} diff --git a/crates/render/src/tests/collapse.rs b/crates/render/src/tests/collapse.rs index 30d2163c1..4104e0b38 100644 --- a/crates/render/src/tests/collapse.rs +++ b/crates/render/src/tests/collapse.rs @@ -161,8 +161,17 @@ fn referenced_layer_overrides_change_the_owner_cache_key() { let opacity = comp.layer(aid).unwrap().props.prop("transform/opacity").unwrap().uid; let key = |value: f64| { let overrides = [crate::PropertyOverride { layer: aid, prop: opacity, value: Value::Scalar(value), font: false }]; - let ctx = - EvalCtx { project: &p, comp_id: cid, comp, time: Tick::ZERO, expr: None, footage: None, property_overrides: &overrides, media_overrides: &[] }; + let ctx = EvalCtx { + project: &p, + comp_id: cid, + comp, + time: Tick::ZERO, + expr: None, + footage: None, + property_overrides: &overrides, + media_overrides: &[], + reads: None, + }; crate::cache::layer_key(&ctx, b, 1.0, false, false) }; let (opaque, half) = (key(100.0), key(50.0)); diff --git a/crates/render/src/tests/color.rs b/crates/render/src/tests/color.rs index 29e4d62c2..4e5cff574 100644 --- a/crates/render/src/tests/color.rs +++ b/crates/render/src/tests/color.rs @@ -339,3 +339,49 @@ fn float_footage_is_encoded_once_with_the_working_gamma() { assert_eq!(render(2.4, Some(ColorSpace::Srgb), linear_light), srgb); } } + +/// `RenderOpts::skip_hdr_step` (float outputs) skips Project Settings ▸ HDR: its top-level frame +/// is the Clip frame in every mode, while other renders keep compand / tone mapping. +#[test] +fn skip_hdr_step_frames_are_the_clip_frames() { + use effectcraft_project::HdrMode; + for depth in [BitDepth::Bpc8, BitDepth::Bpc16, BitDepth::Bpc32] { + let (mut p, cid, _) = setup(depth); + p.settings.working_space = Some(ColorSpace::Srgb); + p.settings.linearize = true; + add_solid(&mut p, cid, [4.0, 2.0, 0.5], BlendMode::Normal, 100.0); + let frame = |p: &Project, skip_hdr_step: bool| { + Renderer::new(p, &crate::NoFootage, RenderOpts { skip_hdr_step, ..Default::default() }).comp_frame(cid, Tick::ZERO) + }; + let clip = frame(&p, false); + assert_eq!(clip.data, frame(&p, true).data, "{depth:?} Clip"); + for mode in [HdrMode::Compand, HdrMode::ToneMap] { + p.settings.hdr = mode; + assert_eq!(frame(&p, true).data, clip.data, "{depth:?} {mode:?}"); + assert_ne!(frame(&p, false).data, clip.data, "{depth:?} {mode:?} keeps the HDR step"); + } + } +} + +/// `Pipe::output_linear` decodes with the output space's curve (the Working Gamma's when +/// unmanaged) and undoes `Pipe::output` exactly where the primaries match. +#[test] +fn output_linear_decodes_with_the_output_curve() { + use effectcraft_color::Conversion; + use effectcraft_project::ProjectSettings; + let pipe = |ws: Option, out: Option, gamma: f64| { + crate::color::Pipe::of(&ProjectSettings { working_space: ws, output_space: out, working_gamma: gamma, ..Default::default() }) + }; + assert_eq!(pipe(None, None, 2.2).output_linear(), Conversion::linearize(ColorSpace::Srgb)); + assert_eq!(pipe(None, Some(ColorSpace::DisplayP3), 2.4).output_linear(), Conversion::linearize(ColorSpace::Rec709), "unmanaged: the Working Gamma"); + assert_eq!(pipe(Some(ColorSpace::Srgb), None, 2.4).output_linear(), Conversion::linearize(ColorSpace::Srgb)); + assert_eq!(pipe(Some(ColorSpace::Srgb), Some(ColorSpace::Rec709), 2.2).output_linear(), Conversion::linearize(ColorSpace::Rec709)); + // Linear light in, linear light out: 4.0 stays 4.0 through output + output_linear. + let p = pipe(Some(ColorSpace::Rec709), Some(ColorSpace::Srgb), 2.2); + let p = crate::color::Pipe { linear: true, ..p }; + let enc = p.output().unwrap().apply([4.0, 1.0, 0.25]); + let lin = p.output_linear().apply(enc); + for (got, want) in lin.into_iter().zip([4.0, 1.0, 0.25]) { + assert!((got - want).abs() <= 1e-5 * want, "{lin:?}"); + } +} diff --git a/crates/render/src/tests/drop_shadow_cover.rs b/crates/render/src/tests/drop_shadow_cover.rs new file mode 100644 index 000000000..94d4ca67b --- /dev/null +++ b/crates/render/src/tests/drop_shadow_cover.rs @@ -0,0 +1,142 @@ +use super::*; +use crate::{EvalCtx, Image, NoFootage, RenderOpts, Renderer}; +use effectcraft_effects::Buf; + +// A synthetic painted source avoids installed-font dependencies and the multi-gigabyte +// allocation in #3357 while exercising the same text/shape effect-stack bounds. +fn source(scale: f64) -> Buf { + let mut img = Image::new(20, 12); + for y in 2..10 { + for x in 2..18 { + img.set(x, y, [0.8, 0.2, 0.1, 1.0]); + } + } + Buf { img, offset: [7.0, -3.0], scale } +} + +#[test] +fn drop_shadow_does_not_cover_the_zoomed_layer_rectangle() { + let (mut p, cid, comp) = setup(); + let mut layer = build::layer(&mut p, &comp, "Shape", LayerSource::Shape, (0, 0), None); + add_effect_200(&mut p, &mut layer, "ec.perspective.dropshadow", &[("distance", Value::Scalar(2.0)), ("softness", Value::Scalar(1.0))]); + let r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + let ctx = EvalCtx::new(&p, cid, &comp, Tick::ZERO); + let out = r.apply_effects(&ctx, &layer, source(4.0), false); + // The old cover makes this at least 800 x 400. Alignment and the shadow's + // own padding need less than 128 pixels per side for this source. + assert!(out.img.width < 128 && out.img.height < 128, "{} x {}", out.img.width, out.img.height); +} + +#[test] +fn drop_shadow_matches_the_covered_reference() { + for scale in [0.5, 1.0, 4.0] { + for only in [false, true] { + for direction in [0.0, 135.0, 270.0] { + let (mut p, cid, comp) = setup(); + let mut layer = build::layer(&mut p, &comp, "Text", LayerSource::Text, (0, 0), None); + add_effect_200( + &mut p, + &mut layer, + "ec.perspective.dropshadow", + &[ + ("distance", Value::Scalar(3.5)), + ("softness", Value::Scalar(2.0)), + ("direction", Value::Scalar(direction)), + ("shadowOnly", Value::Bool(only)), + ], + ); + let r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + let ctx = EvalCtx::new(&p, cid, &comp, Tick::ZERO); + let input = source(scale); + let mut covered = input.clone(); + let (size, origin) = ctx.effect_bounds(&layer); + covered.rebase(origin); + covered.cover(size); + covered.rebase([-origin[0], -origin[1]]); + let actual = r.apply_effects(&ctx, &layer, input, false); + let reference = r.apply_effects(&ctx, &layer, covered, false); + // Compare the union in layer-pixel coordinates, including the shadow outside + // the original content. Buffer origins differ by integral pixels. + let x0 = (-actual.offset[0]).min(-reference.offset[0]) as i32; + let y0 = (-actual.offset[1]).min(-reference.offset[1]) as i32; + let x1 = (f64::from(actual.img.width) - actual.offset[0]).max(f64::from(reference.img.width) - reference.offset[0]) as i32; + let y1 = (f64::from(actual.img.height) - actual.offset[1]).max(f64::from(reference.img.height) - reference.offset[1]) as i32; + for y in y0..y1 { + for x in x0..x1 { + let sample = |b: &Buf| b.img.sample_bilinear(f64::from(x) + b.offset[0] + 0.5, f64::from(y) + b.offset[1] + 0.5); + let (a, b) = (sample(&actual), sample(&reference)); + for c in 0..4 { + assert!( + (a[c] - b[c]).abs() < 1e-5, + "scale {scale}, only {only}, direction {direction}, ({x}, {y}), channel {c}: {} != {}", + a[c], + b[c] + ); + } + } + } + } + } + } +} +#[test] +fn drop_shadow_with_glow_stays_local_but_other_effects_keep_cover() { + for other in ["ec.stylize.glow", "ec.color.tint"] { + let (mut p, cid, comp) = setup(); + let mut layer = build::layer(&mut p, &comp, "Shape", LayerSource::Shape, (0, 0), None); + add_effect_200(&mut p, &mut layer, "ec.perspective.dropshadow", &[("distance", Value::Scalar(2.0)), ("softness", Value::Scalar(1.0))]); + let values = if other == "ec.stylize.glow" { vec![("radius", Value::Scalar(1.0))] } else { vec![] }; + add_effect_200(&mut p, &mut layer, other, &values); + let r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + let ctx = EvalCtx::new(&p, cid, &comp, Tick::ZERO); + let out = r.apply_effects(&ctx, &layer, source(4.0), false); + if other == "ec.stylize.glow" { + assert!(out.img.width < 192 && out.img.height < 192, "{} x {}", out.img.width, out.img.height); + } else { + assert!(out.img.width >= 800 && out.img.height >= 400); + } + } +} +#[test] +fn parented_text_and_shape_keep_small_working_images_at_2200_percent() { + for text in [false, true] { + let mut p = Project::default(); + p.settings.bit_depth = effectcraft_project::BitDepth::Bpc32; + let comp = Comp::new(80, 40, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + let mut parent = build::layer(&mut p, &comp, "Null", LayerSource::Null, (100, 100), None); + parent.props.prop_mut("transform/anchor").unwrap().value = Value::Vec3([0.0; 3]); + parent.props.prop_mut("transform/position").unwrap().value = Value::Vec3([40.0, 20.0, 0.0]); + parent.props.prop_mut("transform/scale").unwrap().value = Value::Vec3([2200.0, 2200.0, 100.0]); + let source = if text { LayerSource::Text } else { LayerSource::Shape }; + let mut layer = build::layer(&mut p, &comp, "Painted", source, (80, 40), None); + layer.parent = Some(parent.id); + layer.props.prop_mut("transform/anchor").unwrap().value = Value::Vec3([0.0; 3]); + layer.props.prop_mut("transform/position").unwrap().value = Value::Vec3([0.0; 3]); + if text { + layer.props.prop_mut("text/sourceText").unwrap().value = Value::Text(Box::new(TextDoc { text: "I".into(), size: 8.0, ..Default::default() })); + } else { + let mut next = p.next_id; + let mut ids = Ids(&mut next); + let rect = build::shape_rect(&mut ids, [4.0, 4.0], [0.0, 0.0], 0.0); + let fill = build::shape_fill(&mut ids, [1.0; 4]); + let group = build::shape_group(&mut ids, "Rectangle", vec![rect, fill]); + p.next_id = next; + layer.props.sub_mut("contents").unwrap().children.push(group.into()); + } + add_effect(&mut p, &mut layer, "ec.stylize.glow", [80.0, 40.0], &[("radius", Value::Scalar(0.1))]); + add_effect(&mut p, &mut layer, "ec.perspective.dropshadow", [80.0, 40.0], &[("distance", Value::Scalar(0.1)), ("softness", Value::Scalar(0.1))]); + p.comp_mut(cid).unwrap().layers = vec![layer, parent].into(); + let comp = p.comp(cid).unwrap(); + let layer = &comp.layers[0]; + for scale in [1.0, 0.5] { + let r = Renderer::new(&p, &NoFootage, RenderOpts { scale, ..Default::default() }); + let ctx = EvalCtx::new(&p, cid, comp, Tick::ZERO); + let input = r.layer_input(&ctx, layer, usize::MAX).unwrap(); + assert!(input.img.width < 512 && input.img.height < 512, "text={text}, output scale={scale}: {} x {}", input.img.width, input.img.height); + assert!(input.img.data.iter().any(|pixel| pixel[3] > 0.5), "the painted source is not empty"); + let frame = r.comp_frame(cid, Tick::ZERO); + assert!(frame.data.iter().any(|pixel| pixel[3] > 0.5), "the layer still draws in the composition"); + } + } +} diff --git a/crates/render/src/tests/footage_size.rs b/crates/render/src/tests/footage_size.rs index 065941d8a..6c59f3fb2 100644 --- a/crates/render/src/tests/footage_size.rs +++ b/crates/render/src/tests/footage_size.rs @@ -106,3 +106,94 @@ fn still_layers_are_cached_across_times_and_movies_are_not() { assert_eq!(src.sizes.unwrap().into_inner().unwrap().len(), fetches + 3, "{kind:?}"); } } + +/// [`Clip`] that also keeps its frames as 8-bit levels, counting the times it's asked for them. +struct Clip8 { + asked: std::sync::atomic::AtomicUsize, +} + +impl FootageSource for Clip8 { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + let mut img = (*Clip { sizes: None }.frame(item, f, t)?).clone(); + // (partly transparent, premultiplied, as decoded with alpha) + img.data.iter_mut().enumerate().for_each(|(i, p)| { + let a = (i % 7) as f32 / 6.0; + *p = [p[0] * a, p[1] * a, p[2] * a, a]; + }); + Some(Arc::new(img)) + } + fn frame8(&self, item: ItemId, f: &Footage, t: Tick, _: crate::FloatCurve) -> Option> { + self.asked.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let img = self.frame(item, f, t)?; + let rgba = img.data.iter().flat_map(|p| effectcraft_raster::quantize_px_u8(*p)).collect(); + Some(Arc::new(crate::disk_cache::Frame8 { width: img.width, height: img.height, rgba })) + } +} + +/// An 8 bpc render at Full takes plain footage as 8-bit levels and renders the same pixels to +/// the bit; other depths, reduced renders and interpreted pixels never ask for them. +#[test] +fn footage_kept_as_8_bit_levels_renders_the_same_pixels() { + struct Float(Clip8); + impl FootageSource for Float { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + self.0.frame(item, f, t) + } + } + for (depth, invert, scale, used) in [ + (BitDepth::Bpc8, false, 1.0, true), + (BitDepth::Bpc8, false, 0.75, true), + (BitDepth::Bpc8, false, 0.5, false), + (BitDepth::Bpc8, true, 1.0, false), + (BitDepth::Bpc16, false, 1.0, false), + (BitDepth::Bpc32, false, 1.0, false), + ] { + let (p, cid) = project(depth, invert); + let opts = RenderOpts { scale, ..Default::default() }; + let q8 = Clip8 { asked: Default::default() }; + let frame = Renderer::new(&p, &q8, opts).comp_frame(cid, Tick::ZERO); + let plain = Renderer::new(&p, &Float(Clip8 { asked: Default::default() }), opts).comp_frame(cid, Tick::ZERO); + assert!(frame.data.iter().zip(&plain.data).all(|(a, b)| a.map(f32::to_bits) == b.map(f32::to_bits)), "{depth:?} {invert} {scale}"); + assert_eq!(q8.asked.into_inner() > 0, used, "{depth:?} {invert} {scale}"); + } +} + +/// The 8-bit levels are read while the render records its reads: the movie is in the files the +/// frame (and a cached layer buffer) was made of. (Read outside, a buffer of a movie listed no +/// files and was still marked complete: changed on disk, it was served stale.) +#[test] +fn footage_kept_as_8_bit_levels_is_noted_as_read() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + struct Noted { + clip: Clip8, + recording: AtomicBool, + outside: AtomicUsize, + } + impl FootageSource for Noted { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + self.clip.frame(item, f, t) + } + fn frame8(&self, item: ItemId, f: &Footage, t: Tick, float: crate::FloatCurve) -> Option> { + if !self.recording.load(Ordering::SeqCst) { + self.outside.fetch_add(1, Ordering::SeqCst); + } + self.clip.frame8(item, f, t, float) + } + // (as the media pool does: the files of what `f` reads go to `reads`) + fn recording(&self, reads: &crate::reads::ReadLog, f: &mut dyn FnMut()) { + reads.note(crate::reads::ReadFile::new("clip.mov", crate::reads::FileStamp::Native { len: 1, modified: Some(1) })); + self.recording.store(true, Ordering::SeqCst); + f(); + self.recording.store(false, Ordering::SeqCst); + } + } + let (p, cid) = project(BitDepth::Bpc8, false); + let src = Noted { clip: Clip8 { asked: Default::default() }, recording: AtomicBool::new(false), outside: AtomicUsize::new(0) }; + let log = crate::reads::ReadLog::new(); + let mut r = Renderer::new(&p, &src, RenderOpts::default()); + r.reads = Some(&log); + r.comp_frame(cid, Tick::ZERO); + assert!(src.clip.asked.load(Ordering::SeqCst) > 0, "the 8-bit levels were not asked for"); + assert_eq!(src.outside.load(Ordering::SeqCst), 0, "8-bit levels read outside the render's recording"); + assert!(log.files().files().iter().any(|f| &*f.path == "clip.mov"), "the movie is not in the frame's files"); +} diff --git a/crates/render/src/tests/mask_blur.rs b/crates/render/src/tests/mask_blur.rs index 07bc1e95f..5f3ff4e2a 100644 --- a/crates/render/src/tests/mask_blur.rs +++ b/crates/render/src/tests/mask_blur.rs @@ -75,3 +75,32 @@ fn mask_motion_blur_follows_the_render_and_the_comp() { let (p, cid) = project(false); assert!(alpha_at_25(&p, cid, true) < 0.01, "the comp's switch off"); } + +/// Whether mask motion blur may run at all (the render options, Switches Affect Nested Comps with +/// a precomp layer's switch off) is part of the layer cache key, also for a layer whose own +/// switch is off: a buffer made with the gate open must not serve a render with it closed. +#[test] +fn the_mask_motion_blur_gate_keys_the_layer_cache() { + let (mut p, inner) = project(true); + let mut outer = Comp::new(100, 100, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + outer.enable_motion_blur = true; + let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: inner }, (100, 100), None); + pre.switches.motion_blur = false; + outer.layers.push(pre); + let oid = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.into())); + let half = Tick::from_seconds_f64(0.5 / 30.0); + let cache = crate::LayerCache::default(); + let render = |cid: ItemId, opts: RenderOpts, cached: bool| { + let mut r = Renderer::new(&p, &NoFootage, opts); + r.cache = cached.then_some(&cache); + r.comp_frame(cid, half).data + }; + let on = RenderOpts { motion_blur: true, nested_switches: true, ..Default::default() }; + let off = RenderOpts { nested_switches: false, ..on }; + assert!(render(oid, on, false) != render(oid, off, false), "the precomp layer's switch closes the gate"); + assert!(render(oid, off, true) == render(oid, off, false)); + assert!(render(oid, on, true) == render(oid, on, false), "not the buffer blurred with the gate open"); + let still = RenderOpts { motion_blur: false, ..on }; + assert!(render(inner, on, true) == render(inner, on, false)); + assert!(render(inner, still, true) == render(inner, still, false), "Render Settings ▸ Motion Blur off"); +} diff --git a/crates/render/src/tests/proxy_cache.rs b/crates/render/src/tests/proxy_cache.rs new file mode 100644 index 000000000..85343a25d --- /dev/null +++ b/crates/render/src/tests/proxy_cache.rs @@ -0,0 +1,45 @@ +use super::setup; +use crate::eval::EvalCtx; +use crate::{FootageSource, Image, LayerCache, RenderOpts, Renderer}; +use effectcraft_color::Label; +use effectcraft_project::{Footage, FootageKind, ItemId, ItemKind, LayerSource, Proxy, build, render_queue::ProxyUse}; +use effectcraft_time::Tick; +use std::sync::Arc; + +/// A source and its proxy deliberately have different pixels. +struct Pictures; +impl FootageSource for Pictures { + fn frame(&self, _: ItemId, footage: &Footage, _: Tick) -> Option> { + let color = if footage.path == "proxy" { [0.0, 1.0, 0.0, 1.0] } else { [1.0, 0.0, 0.0, 1.0] }; + Some(Arc::new(Image::filled(16, 16, color))) + } +} + +/// A queue run reuses its layer cache across jobs with different Proxy Use settings. +/// Time effects read layer_input, which must never serve another job's source pixels. +#[test] +fn shared_layer_cache_separates_proxy_use() { + let (mut p, cid, comp) = setup(); + let footage = Footage { path: "original".into(), kind: FootageKind::Still, width: 16, height: 16, has_video: true, ..Default::default() }; + let item = p.add_item("Footage", Label::Red, None, ItemKind::Footage(footage.clone())); + p.item_mut(item).unwrap().proxy = Some(Box::new(Proxy { footage: Footage { path: "proxy".into(), ..footage }, enabled: false })); + let layer = build::layer(&mut p, &comp, "Footage", LayerSource::Footage { item }, (16, 16), None); + p.comp_mut(cid).unwrap().layers.push(layer); + for enabled in [false, true] { + p.item_mut(item).unwrap().proxy.as_mut().unwrap().enabled = enabled; + let cache = LayerCache::default(); + let ctx = EvalCtx::new(&p, cid, p.comp(cid).unwrap(), Tick::ZERO); + let layer = &ctx.comp.layers[0]; + for proxy in [ProxyUse::UseAll, ProxyUse::UseNone, ProxyUse::CurrentSettings, ProxyUse::UseCompOnly, ProxyUse::UseAll] { + let mut r = Renderer::new(&p, &Pictures, RenderOpts { proxy, ..Default::default() }); + let input = r.layer_input(&ctx, layer, 0).unwrap(); + let content = r.content_buf(&ctx, layer).unwrap(); + r.cache = Some(&cache); + assert_eq!(r.layer_input(&ctx, layer, 0).unwrap().img.data, input.img.data, "{proxy:?}, enabled={enabled}"); + assert_eq!(r.content_buf(&ctx, layer).unwrap().img.data, content.img.data, "{proxy:?}, enabled={enabled}"); + let hits = cache.stats().hits; + r.layer_input(&ctx, layer, 0).unwrap(); + assert!(cache.stats().hits > hits, "unchanged proxy settings still reuse inputs"); + } + } +} diff --git a/crates/render/src/tests/raster_clip.rs b/crates/render/src/tests/raster_clip.rs new file mode 100644 index 000000000..c85176fca --- /dev/null +++ b/crates/render/src/tests/raster_clip.rs @@ -0,0 +1,360 @@ +//! #1388: 3D text and shape layers rasterise only the part of the layer the output shows. Where +//! the whole raster fits its pixel budget the frame is identical to rasterising the whole layer; +//! close to the camera the raster stays small instead of growing to ~16 million pixels. + +use effectcraft_color::Label; +use effectcraft_keyframe::{TextDoc, Value}; +use effectcraft_project::build::{self, Ids}; +use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, Project}; +use effectcraft_time::{FrameRate, Tick}; + +use crate::{NoFootage, RenderOpts, Renderer}; + +const W: u32 = 400; +const H: u32 = 300; + +/// The default camera's distance to the z = 0 plane. +fn zoom() -> f64 { + W as f64 * 50.0 / 36.0 +} + +fn setup() -> (Project, ItemId, Comp) { + let mut p = Project::default(); + p.settings.bit_depth = effectcraft_project::BitDepth::Bpc32; + let comp = Comp::new(W, H, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + (p, cid, comp) +} + +fn set(l: &mut Layer, path: &str, v: Value) { + l.props.prop_mut(path).unwrap_or_else(|| panic!("no {path}")).value = v; +} + +/// A 3D text layer at `pos`, turned `rot_y` degrees about Y. +fn text3(p: &mut Project, comp: &Comp, pos: [f64; 3], rot_y: f64) -> Layer { + let mut l = build::layer(p, comp, "Text", LayerSource::Text, (W, H), None); + l.props.prop_mut("text/sourceText").unwrap().value = Value::Text(Box::new(TextDoc { text: "NEAR CAMERA TEXT".into(), size: 60.0, ..Default::default() })); + l.switches.three_d = true; + set(&mut l, "transform/position", Value::Vec3(pos)); + set(&mut l, "transform/rotationY", Value::Scalar(rot_y)); + l +} + +/// A 3D shape layer (a 300×120 rectangle with a stroke) at `pos`. +fn shape3(p: &mut Project, comp: &Comp, pos: [f64; 3]) -> Layer { + let mut l = build::layer(p, comp, "Shape", LayerSource::Shape, (W, H), None); + let mut next = p.next_id; + { + let mut ids = Ids(&mut next); + let r = build::shape_rect(&mut ids, [300.0, 120.0], [0.0, 0.0], 0.0); + let f = build::shape_fill(&mut ids, [0.9, 0.4, 0.1, 1.0]); + let s = build::shape_stroke(&mut ids, [1.0, 1.0, 1.0, 1.0], 6.0); + let g = build::shape_group(&mut ids, "Box", vec![r, f, s]); + l.props.sub_mut("contents").unwrap().children.push(g.into()); + } + p.next_id = next; + l.switches.three_d = true; + set(&mut l, "transform/position", Value::Vec3(pos)); + l +} + +fn scene(l: impl FnOnce(&mut Project, &Comp) -> Layer) -> (Project, ItemId) { + let (mut p, cid, comp) = setup(); + let layer = l(&mut p, &comp); + p.comp_mut(cid).unwrap().layers.push(layer); + (p, cid) +} + +fn frame(p: &Project, cid: ItemId, whole: bool) -> effectcraft_raster::Image { + let mut r = Renderer::new(p, &NoFootage, RenderOpts::default()); + r.whole_raster = whole; + r.comp_frame(cid, Tick::ZERO) +} + +/// Pixels of the layer's processed buffer. +fn raster_px(p: &Project, cid: ItemId, whole: bool) -> u64 { + let mut r = Renderer::new(p, &NoFootage, RenderOpts::default()); + r.whole_raster = whole; + let c = p.comp(cid).unwrap(); + let ctx = r.eval_ctx(cid, Tick::ZERO).unwrap(); + let b = r.layer_buf(&ctx, &c.layers[0]).unwrap(); + b.img.width as u64 * b.img.height as u64 +} + +#[test] +fn the_visible_part_renders_the_same_frame_as_the_whole_layer() { + let cx = W as f64 / 2.0; + let cy = H as f64 / 2.0; + let cases: Vec<(&str, (Project, ItemId))> = vec![ + ("far", scene(|p, c| text3(p, c, [cx, cy, 300.0], 0.0))), + ("in the frame plane", scene(|p, c| text3(p, c, [cx, cy, 0.0], 0.0))), + ("past the frame edge", scene(|p, c| text3(p, c, [60.0, cy, -200.0], 0.0))), + ("turned", scene(|p, c| text3(p, c, [cx, cy, -150.0], 55.0))), + ("close to the camera", scene(|p, c| text3(p, c, [cx, cy, -zoom() + 40.0], 0.0))), + ("partly behind the camera", scene(|p, c| text3(p, c, [cx, cy, -zoom() + 30.0], 80.0))), + ("behind the camera", scene(|p, c| text3(p, c, [cx, cy, -zoom() - 200.0], 0.0))), + ("shape", scene(|p, c| shape3(p, c, [cx + 150.0, cy, -250.0]))), + ]; + for (label, (p, cid)) in &cases { + let clipped = frame(p, *cid, false); + let whole = frame(p, *cid, true); + assert_eq!(clipped.data, whole.data, "{label}"); + } +} + +/// Close to the camera only part of the text shows: its raster is a fraction of the whole one +/// (millions of pixels), and the frame still shows text. +#[test] +fn text_close_to_the_camera_rasterises_what_shows() { + let (p, cid) = scene(|p, c| text3(p, c, [W as f64 / 2.0, H as f64 / 2.0, -zoom() + 40.0], 0.0)); + let clipped = raster_px(&p, cid, false); + let whole = raster_px(&p, cid, true); + assert!(whole > 5_000_000, "the whole raster is huge ({whole} px)"); + eprintln!("near camera: {clipped} px rasterised, {whole} px whole"); + assert!(clipped * 10 < whole, "{clipped} px of {whole}"); + let img = frame(&p, cid, false); + let covered = img.data.iter().filter(|px| px[3] > 0.5).count(); + assert!(covered > (W * H / 20) as usize, "text shows ({covered} px)"); + // Behind the camera there is nothing to rasterise. + let (p, cid) = scene(|p, c| text3(p, c, [W as f64 / 2.0, H as f64 / 2.0, -zoom() - 200.0], 0.0)); + assert!(raster_px(&p, cid, false) <= 1); +} + +/// The #1388 case at full size: 200 pt text in a 1920 × 1080 comp, close to the camera. Rasterised +/// whole it fills the ~16 million pixel cap; clipped, it stays within a few frames' worth of pixels +/// (and the text still shows). +#[test] +fn hd_text_close_to_the_camera_stays_within_a_few_frames() { + let mut p = Project::default(); + let comp = Comp::new(1920, 1080, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + let mut l = build::layer(&mut p, &comp, "Text", LayerSource::Text, (1920, 1080), None); + l.props.prop_mut("text/sourceText").unwrap().value = Value::Text(Box::new(TextDoc { text: "NEAR CAMERA".into(), size: 200.0, ..Default::default() })); + l.switches.three_d = true; + set(&mut l, "transform/position", Value::Vec3([960.0, 540.0, -1920.0 * 50.0 / 36.0 + 60.0])); + p.comp_mut(cid).unwrap().layers.push(l); + let (clipped, whole) = (raster_px(&p, cid, false), raster_px(&p, cid, true)); + eprintln!("HD near camera: {clipped} px rasterised, {whole} px whole"); + assert!(whole > 12_000_000, "{whole}"); + assert!(clipped <= 4 * 1920 * 1080, "{clipped} px"); + assert!(frame(&p, cid, false).data.iter().any(|px| px[3] > 0.5), "the text shows"); +} + +/// A slow move of the layer against the camera (a camera move does the same) keeps the part +/// rasterised within the same grid cells for several frames: they reuse the cached raster instead +/// of drawing the text again each frame. +#[test] +fn a_slow_move_reuses_the_clipped_raster() { + let cache = crate::LayerCache::default(); + let at = |x: f64| { + let (p, cid) = scene(|p, c| text3(p, c, [x, H as f64 / 2.0, -zoom() + 40.0], 0.0)); + let mut r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + r.cache = Some(&cache); + r.comp_frame(cid, Tick::ZERO); + }; + at(W as f64 / 2.0); + let misses = cache.stats().misses; + // 16 frames, a quarter of a layer pixel apart (here about three output pixels). + for i in 1..=16 { + at(W as f64 / 2.0 + i as f64 * 0.25); + } + let rasters = cache.stats().misses - misses; + assert!(rasters <= 2, "{rasters} new rasters over 16 frames"); +} + +/// One keyframed motion: (seconds, value) pairs. +type Keys<'a> = &'a [(f64, [f64; 3])]; + +fn keyed(l: &mut Layer, path: &str, keys: Keys) { + l.props.prop_mut(path).unwrap_or_else(|| panic!("no {path}")).keys = + keys.iter().map(|(t, v)| effectcraft_keyframe::Keyframe::new(Tick::from_seconds_f64(*t), Value::Vec3(*v))).collect(); +} + +/// A camera keyed through `pos` / `poi`, and the text keyed through `text_pos` (and turning about +/// Y through `text_rot`): every frame of a second, rendered with the clipped raster and a layer +/// cache shared across the frames, matches rasterising the whole layer without a cache (or differs +/// by an anti-aliasing sub-sample or two on a few edge pixels) — except where the whole raster is held at +/// its pixel cap (softer than the clipped one, which isn't): there the text shows and the clipped +/// raster stays small. +fn moving(label: &str, pos: Keys, poi: Keys, text_pos: Keys, text_rot: &[(f64, f64)]) { + let (mut p, cid, comp) = setup(); + let mut text = text3(&mut p, &comp, [W as f64 / 2.0, H as f64 / 2.0, 0.0], 0.0); + if !text_pos.is_empty() { + keyed(&mut text, "transform/position", text_pos); + } + if !text_rot.is_empty() { + text.props.prop_mut("transform/rotationY").unwrap().keys = + text_rot.iter().map(|(t, v)| effectcraft_keyframe::Keyframe::new(Tick::from_seconds_f64(*t), Value::Scalar(*v))).collect(); + } + let mut cam = build::layer(&mut p, &comp, "Camera", LayerSource::Camera, (W, H), None); + set(&mut cam, "cameraOptions/zoom", Value::Scalar(zoom())); + keyed(&mut cam, "transform/position", pos); + keyed(&mut cam, "transform/poi", poi); + p.comp_mut(cid).unwrap().layers = vec![cam, text].into(); + let cache = crate::LayerCache::default(); + let (mut exact, mut near, mut capped) = (0, 0, 0); + for f in 0..30 { + let t = Tick::from_seconds_f64(f as f64 / 30.0); + let mut clipped = Renderer::new(&p, &NoFootage, RenderOpts::default()); + clipped.cache = Some(&cache); + let mut whole = Renderer::new(&p, &NoFootage, RenderOpts::default()); + whole.whole_raster = true; + let ctx = whole.eval_ctx(cid, t).unwrap(); + let layer = &p.comp(cid).unwrap().layers[1]; + let a = clipped.comp_frame(cid, t); + if clipped.raster_scale(&ctx, layer) == whole.raster_scale(&ctx, layer) { + let b = whole.comp_frame(cid, t); + if a.data == b.data { + exact += 1; + } else { + // The clipped raster places the glyphs at other coordinates (smaller ones: the whole + // raster can be thousands of pixels wide), and tiny-skia transforms them in f32: its + // 4 × 4 anti-aliasing may land a sub-sample or two differently on a few edge pixels. + let (n, worst) = a.data.iter().zip(&b.data).fold((0usize, 0.0f32), |(n, w), (p, q)| { + let d = (0..4).map(|i| (p[i] - q[i]).abs()).fold(0.0f32, f32::max); + (n + usize::from(d > 0.0), w.max(d)) + }); + assert!(worst <= 2.0 / 16.0 + 1e-4 && n * 1000 <= (W * H) as usize, "{label}: frame {f}: {n} px differ, by up to {worst}"); + near += 1; + } + } else { + // Held at the cap whole: the clipped raster is sharper, and small. + let buf = clipped.layer_buf(&ctx, layer).unwrap(); + assert!(buf.img.width as u64 * buf.img.height as u64 <= 16_500_000, "{label}: frame {f}"); + let shows = |img: &effectcraft_raster::Image| img.data.iter().filter(|px| px[3] > 0.5).count(); + let (sa, sb) = (shows(&a), shows(&whole.comp_frame(cid, t))); + // The same text shows (or none, the camera past it); coverage within a few percent. + assert!(sa.abs_diff(sb) * 50 <= sb.max(1) + 50, "{label}: frame {f}: {sa} px of text, {sb} rasterised whole"); + capped += 1; + } + } + eprintln!("{label}: {exact} frames identical, {near} within anti-aliasing noise, {capped} sharper than the capped whole raster"); + assert!(exact + near >= 10, "{label}: {exact} identical, {near} close, {capped} at the cap"); +} + +#[test] +fn a_camera_moving_any_way_renders_every_frame_as_the_whole_layer() { + let (cx, cy, z) = (W as f64 / 2.0, H as f64 / 2.0, -zoom()); + let still = [(0.0, [cx, cy, 0.0])]; + // In towards the text, through it and past it; and back out. + moving("dolly in through the text", &[(0.0, [cx, cy, 2.0 * z]), (1.0, [cx, cy, 150.0])], &[(0.0, [cx, cy, 400.0]), (1.0, [cx, cy, 700.0])], &[], &[]); + moving("dolly out", &[(0.0, [cx, cy, -60.0]), (1.0, [cx, cy, 3.0 * z])], &still, &[], &[]); + // Sideways and up and down close to the text, so it leaves the frame on both sides. + moving( + "pan x", + &[(0.0, [cx - 500.0, cy, -120.0]), (1.0, [cx + 500.0, cy, -120.0])], + &[(0.0, [cx - 500.0, cy, 0.0]), (1.0, [cx + 500.0, cy, 0.0])], + &[], + &[], + ); + moving("pan y", &[(0.0, [cx, cy - 300.0, -90.0]), (1.0, [cx, cy + 300.0, -90.0])], &[(0.0, [cx, cy - 300.0, 0.0]), (1.0, [cx, cy + 300.0, 0.0])], &[], &[]); + // Around the text, close, looking at it. + let orbit: Vec<(f64, [f64; 3])> = (0..=8) + .map(|i| { + let a = i as f64 / 8.0 * std::f64::consts::TAU * 0.4 - 0.8; + (i as f64 / 8.0, [cx + 150.0 * a.sin(), cy, -150.0 * a.cos()]) + }) + .collect(); + moving("orbit", &orbit, &still, &[], &[]); + // The text moves instead: towards the camera, past it, and across. + moving( + "text towards and past the camera", + &[(0.0, [cx, cy, z])], + &still, + &[(0.0, [cx + 200.0, cy - 80.0, 400.0]), (1.0, [cx - 150.0, cy + 60.0, z - 100.0])], + &[], + ); + // Turning close to the camera. + moving("text turning near the camera", &[(0.0, [cx, cy, z])], &still, &[(0.0, [cx, cy, z + 70.0])], &[(0.0, -70.0), (1.0, 70.0)]); +} + +/// Reads of a layer in its own space get the whole layer, not the part the frame shows: an effect +/// taking another layer as a parameter (Set Matte, stretched to fit, from hidden text close to the +/// camera), and the source the motion tracker analyses. +#[test] +fn layer_space_reads_get_the_whole_layer() { + let (mut p, cid, comp) = setup(); + let mut text = text3(&mut p, &comp, [W as f64 / 2.0, H as f64 / 2.0, -zoom() + 40.0], 0.0); + text.switches.video = false; + let text_id = text.id; + let sid = + p.add_item("Solid", Label::Red, None, ItemKind::Solid(effectcraft_project::Solid { color: [0.2, 0.6, 1.0], width: W, height: H, pixel_aspect: 1.0 })); + let mut solid = build::layer(&mut p, &comp, "Solid", LayerSource::Solid { item: sid }, (W, H), None); + let spec = effectcraft_effects::find("ec.channel.setmatte").unwrap(); + let mut next = p.next_id; + let mut g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [W as f64, H as f64]); + p.next_id = next; + g.prop_mut("takeMatteFromLayer").unwrap().value = Value::Layer(Some(text_id.0)); + solid.props.sub_mut("effects").unwrap().children.push(g.into()); + p.comp_mut(cid).unwrap().layers = vec![text, solid].into(); + assert_eq!(frame(&p, cid, false).data, frame(&p, cid, true).data, "Set Matte from the text"); + let r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + let ctx = r.eval_ctx(cid, Tick::ZERO).unwrap(); + let layer = &p.comp(cid).unwrap().layers[0]; + let mut whole = Renderer::new(&p, &NoFootage, RenderOpts::default()); + whole.whole_raster = true; + assert_eq!(r.layer_source(&ctx, layer).unwrap().img, whole.layer_source(&ctx, layer).unwrap().img, "the tracker's source"); +} + +/// A layer whose pixels outside the frame can matter (an effect here) is rasterised whole. +#[test] +fn layers_with_effects_rasterise_whole() { + let (mut p, cid) = scene(|p, c| text3(p, c, [W as f64 / 2.0, H as f64 / 2.0, -zoom() + 40.0], 0.0)); + let spec = effectcraft_effects::find("ec.blur.gaussian").unwrap(); + let mut next = p.next_id; + let g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [W as f64, H as f64]); + p.next_id = next; + p.comp_mut(cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(g.into()); + assert_eq!(raster_px(&p, cid, false), raster_px(&p, cid, true)); +} + +/// The Layer panel and analysis tools consume layer-space inputs, even with no effects. +#[test] +fn layer_panel_input_reads_the_whole_layer_behind_the_camera() { + let (p, cid) = scene(|p, c| shape3(p, c, [W as f64 / 2.0, H as f64 / 2.0, -zoom() - 200.0])); + let r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + let ctx = r.eval_ctx(cid, Tick::ZERO).unwrap(); + let layer = &p.comp(cid).unwrap().layers[0]; + let mut whole = Renderer::new(&p, &NoFootage, RenderOpts::default()); + whole.whole_raster = true; + let expected = whole.layer_input(&ctx, layer, 0).unwrap(); + assert!(expected.img.data.iter().any(|pixel| pixel[3] > 0.5)); + assert_eq!(r.layer_input(&ctx, layer, 0).unwrap().img, expected.img); +} + +#[test] +fn fine_clip_cells_have_distinct_cache_keys() { + let a = kurbo::Rect::new(0.0, 0.0, 1.0 / 128.0, 1.0 / 128.0); + let b = kurbo::Rect::new(1.0 / 128.0, 0.0, 2.0 / 128.0, 1.0 / 128.0); + let key = |clip| crate::pipeline::raster_clip_key(42, clip); + // All three clips rounded to identical coordinates in the old 1/16-unit key. + assert_ne!(key(a), key(b)); + assert_ne!(key(a), key(kurbo::Rect::ZERO)); + assert_ne!(key(b), key(kurbo::Rect::ZERO)); +} + +/// Text animator Blur reads beyond the fixed anti-aliasing padding of a clipped window. +#[test] +fn animated_text_blur_keeps_offscreen_glyph_pixels_while_panning() { + let (mut p, cid) = scene(|p, c| text3(p, c, [W as f64 / 2.0, H as f64 / 2.0, -zoom() + 40.0], 0.0)); + let mut next = p.next_id; + let mut ids = Ids(&mut next); + let props = build::text_anim_props(&mut ids, "blur", false); + let mut animator = build::text_animator(&mut ids, "Blur", props); + animator.prop_mut("properties/blur").unwrap().value = Value::Vec2([40.0, 40.0]); + p.next_id = next; + p.comp_mut(cid).unwrap().layers[0].props.group_mut("text/animators").unwrap().children.push(animator.into()); + let opts = RenderOpts { scale: 0.125, ..Default::default() }; + let cache = crate::LayerCache::default(); + for dx in [-10.0, 0.0, 10.0] { + set(&mut p.comp_mut(cid).unwrap().layers[0], "transform/position", Value::Vec3([W as f64 / 2.0 + dx, H as f64 / 2.0, -zoom() + 40.0])); + let mut r = Renderer::new(&p, &NoFootage, opts); + r.cache = Some(&cache); + let ctx = r.eval_ctx(cid, Tick::ZERO).unwrap(); + let layer = &p.comp(cid).unwrap().layers[0]; + assert!(r.raster_clip(&ctx, layer).is_none(), "animator blur needs off-window pixels"); + let mut whole = Renderer::new(&p, &NoFootage, opts); + whole.whole_raster = true; + assert_eq!(r.comp_frame(cid, Tick::ZERO).data, whole.comp_frame(cid, Tick::ZERO).data); + } +} diff --git a/crates/render/src/tests/remap.rs b/crates/render/src/tests/remap.rs index 67b6ebef7..8d3cd8b63 100644 --- a/crates/render/src/tests/remap.rs +++ b/crates/render/src/tests/remap.rs @@ -63,3 +63,24 @@ fn time_remap_picks_the_source_frame() { assert!(img.get(90, 50)[3] > 0.99, "frozen at the end position"); assert!(img.get(10, 50)[3] < 0.01); } + +#[test] +fn layer_span_is_the_source_duration_in_layer_time() { + let mut p = Project::default(); + let outer = Comp::new(100, 100, FrameRate::FPS_30, s(4.0)); + let inner = Comp::new(100, 100, FrameRate::FPS_30, s(2.5)); + let iid = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into())); + let sid = p.add_item("S", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 1.0, 1.0], width: 10, height: 10, pixel_aspect: 1.0 })); + let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: iid }, (100, 100), None); + let sol = build::layer(&mut p, &outer, "S", LayerSource::Solid { item: sid }, (10, 10), None); + let (first, end) = crate::eval::layer_span(&p, &pre).expect("a nested comp has a duration"); + assert!(first.abs() < 1e-9 && (end - 2.5).abs() < 1e-9); + assert_eq!(crate::eval::layer_span(&p, &sol), None, "solids have no duration"); + // Time Remap: layer time is not source time any more, the visible span is reported. + let mut next = p.next_id; + let tr = Ids(&mut next).prop("timeRemap", "Time Remap", Value::Scalar(0.0)); + p.next_id = next; + pre.props.children.push(Node::Prop(tr)); + let (first, end) = crate::eval::layer_span(&p, &pre).expect("a remapped layer has a visible span"); + assert!(end > first); +} diff --git a/crates/render/src/tests/stretch_limits.rs b/crates/render/src/tests/stretch_limits.rs new file mode 100644 index 000000000..17bdff317 --- /dev/null +++ b/crates/render/src/tests/stretch_limits.rs @@ -0,0 +1,96 @@ +//! A project file whose layers carry a time stretch outside ±1 % to ±9900 % (1e-300 %, 0, +//! 1e300 %…) opens with the stretch brought into that range, and a frame of it draws and its audio +//! mixes with bounded source reads. Before, a stretch of 1e-300 % asked the footage for about +//! `usize::MAX` samples and the mix overflowed or tried a huge allocation, aborting the app (#3247). + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use effectcraft_color::Label; +use effectcraft_project::{Footage, FootageKind, ItemId, ItemKind, LayerSource, Project, build, limits}; +use effectcraft_time::Tick; + +use super::{setup, solid}; +use crate::{FootageSource, Image, audio::mix_comp, render_frame}; + +/// Silent audio footage that records the longest read asked of it and refuses a read past a +/// thousand seconds (so a runaway read can't take the machine's memory: the mix then fills the +/// read with silence itself). +#[derive(Default)] +struct Probe { + longest: AtomicUsize, +} + +impl FootageSource for Probe { + fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option> { + None + } + fn audio(&self, _: ItemId, _: &Footage, _: Tick, frames: usize, rate: u32) -> Option> { + self.longest.fetch_max(frames, Ordering::Relaxed); + (frames <= rate as usize * 1000).then(|| vec![0.0; frames * 2]) + } +} + +/// The project file of a comp holding a red solid and a sound, both with their stretch set to +/// `stretch` in the file text. +fn file_with_stretch(stretch: f64) -> (String, ItemId) { + let (mut p, cid, comp) = setup(); + let red = solid(&mut p, &comp, [1.0, 0.0, 0.0], 200, 100); + let f = Footage { + path: "tone.wav".into(), + kind: FootageKind::Audio, + has_audio: true, + frame_rate: comp.frame_rate, + duration: Tick::from_seconds_f64(10.0), + ..Default::default() + }; + let fid = p.add_item("tone.wav", Label::SeaFoam, None, ItemKind::Footage(f)); + let sound = build::layer(&mut p, &comp, "sound", LayerSource::Footage { item: fid }, (0, 0), None); + let c = p.comp_mut(cid).unwrap(); + c.layers.push(red); + c.layers.push(sound); + // Both layers are at 100 %; `{:e}` writes a JSON number for any finite value, and NaN is + // written as null, as serializing the project writes it. + let text = p.to_json(); + assert_eq!(text.matches("\"stretch\": 100.0").count(), 2); + let value = if stretch.is_nan() { "null".to_string() } else { format!("{stretch:e}") }; + (text.replace("\"stretch\": 100.0", &format!("\"stretch\": {value}")), cid) +} + +#[test] +fn a_file_with_an_extreme_stretch_opens_in_range_draws_and_mixes_with_bounded_reads() { + for (stored, opened) in + [(1e-300, 1.0), (-1e-300, -1.0), (0.0, 100.0), (1e300, limits::MAX_STRETCH), (-1e300, -limits::MAX_STRETCH), (0.5, 1.0), (f64::NAN, 100.0)] + { + let (text, cid) = file_with_stretch(stored); + let (p, notes) = Project::from_json_repaired(&text).unwrap(); + assert!(notes.iter().filter(|n| n.contains("time stretch")).count() == 2, "{stored}: {notes:?}"); + let c = p.comp(cid).unwrap(); + assert!(c.layers.iter().all(|l| l.stretch == opened), "{stored}: {:?}", c.layers.iter().map(|l| l.stretch).collect::>()); + // A frame draws: the solid has no keys and keeps its in and out points, so it is red. + let img = render_frame(&p, cid, Tick::ZERO, 1.0); + assert_eq!(img.get(10, 10), [1.0, 0.0, 0.0, 1.0], "{stored}"); + // The audio mixes, reading at most 100 source samples per comp sample (a stretch of 1 %). + let (rate, n) = (8000, 4000); + let probe = Probe::default(); + let mixed = mix_comp(&p, &probe, None, cid, Tick::from_seconds_f64(0.5), n, rate); + assert_eq!(mixed.len(), n * 2, "{stored}"); + assert!(probe.longest.load(Ordering::Relaxed) <= 100 * n + 1, "{stored}: a read of {} samples", probe.longest.load(Ordering::Relaxed)); + } +} + +/// A stretch set in memory (not through a file, so not repaired) mixes as the clamped stretch the +/// layer's time uses: before, 1e-300 % read about `usize::MAX` source samples and overflowed. +#[test] +fn an_in_memory_extreme_stretch_mixes_with_bounded_reads() { + for stretch in [1e-300, 0.0, f64::NAN, 1e300] { + let (text, cid) = file_with_stretch(100.0); + let (mut p, _) = Project::from_json_repaired(&text).unwrap(); + p.comp_mut(cid).unwrap().layers.iter_mut().for_each(|l| l.stretch = stretch); + let (rate, n) = (8000, 4000); + let probe = Probe::default(); + let mixed = mix_comp(&p, &probe, None, cid, Tick::from_seconds_f64(0.5), n, rate); + assert_eq!(mixed.len(), n * 2, "{stretch}"); + assert!(probe.longest.load(Ordering::Relaxed) <= 100 * n + 1, "{stretch}: a read of {} samples", probe.longest.load(Ordering::Relaxed)); + } +} diff --git a/crates/render/src/tests/styles.rs b/crates/render/src/tests/styles.rs index 2450fcf64..a9de6fb52 100644 --- a/crates/render/src/tests/styles.rs +++ b/crates/render/src/tests/styles.rs @@ -507,3 +507,34 @@ fn workers_styling_a_layer_at_once_share_its_buffers() { assert!(st.passes.iter().zip(&first.passes).all(|(a, b)| std::sync::Arc::ptr_eq(&a.0, &b.0)), "one set of passes"); } } + +/// A styled layer served from the cache lists the files of the body and passes it was served, +/// not only its content's (#3184): one made of other files (another worker's, or from disk, +/// whose list can't vouch for them) passes that on to the buffers made of it (flattened, in the +/// blending space), which are then not kept on disk as complete. +#[test] +fn a_cached_styled_layer_lists_the_files_of_its_cached_buffers() { + let (p, cid) = scene([1.0; 3], None, |p, c, l| add(p, c, l, "dropShadow")); + let layer = &p.comp(cid).unwrap().layers[0]; + let styled = |cache: &crate::LayerCache| { + let mut r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + r.cache = Some(cache); + let ctx = r.eval_ctx(cid, Tick::ZERO).unwrap(); + r.styled_layer(&ctx, layer).unwrap() + }; + let first = styled(&crate::LayerCache::default()); + assert!(first.files.is_complete() && !first.passes.is_empty()); + let key = first.key.unwrap(); + // Body and passes kept with a list that can't vouch for them; the content renders again. + let cache = crate::LayerCache::default(); + let mut unsure = crate::reads::ReadFiles::default(); + unsure.mark_incomplete(); + let unsure = std::sync::Arc::new(unsure); + cache.insert(key, first.body.clone(), unsure.clone()); + for (i, (b, _)) in first.passes.iter().enumerate() { + cache.insert(crate::cache::derive(key, i as u64 + 1), b.clone(), unsure.clone()); + } + let hit = styled(&cache); + assert!(std::sync::Arc::ptr_eq(&hit.body, &first.body), "the cached body"); + assert!(!hit.files.is_complete(), "{:?}", hit.files); +} diff --git a/crates/render/src/tests/time.rs b/crates/render/src/tests/time.rs index e9599f70b..f959401bb 100644 --- a/crates/render/src/tests/time.rs +++ b/crates/render/src/tests/time.rs @@ -1,7 +1,10 @@ //! Time effects through the renderer: neighbouring frames via `EffectHost::self_at`, and the //! layer cache staying correct while scrubbing. +use std::sync::Arc; + use effectcraft_color::Label; +use effectcraft_effects::plugin::{EffectPlugin, PluginFrame, PluginManifest, PluginParams, register_plugin}; use effectcraft_keyframe::{Keyframe, ShapePath, Value}; use effectcraft_project::build::{self, Ids}; use effectcraft_project::{Comp, ItemId, ItemKind, LayerSource, MaskMode, Project, Solid}; @@ -143,6 +146,7 @@ fn input_keys_ignore_later_effects() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &comp.layers[0]; (crate::cache::input_key(&ctx, l, 1.0, false, false, 1), crate::cache::input_key(&ctx, l, 1.0, false, false, 2)) @@ -156,3 +160,89 @@ fn input_keys_ignore_later_effects() { set(&mut p, "effects/#1/blurriness", 8.0); assert_ne!(key(&p).0, one); } + +/// A plug-in that reads the layer's neighbouring frames (WebAssembly ABI 2) makes its layer's +/// cache key depend on the layer time, even when the source and every property are static. A +/// plug-in that does not keeps the old key (#1977: a static layer stays cached across a scrub). +#[test] +fn abi2_plugin_layers_key_on_layer_time() { + struct NeighbourReader { + m: PluginManifest, + } + + impl EffectPlugin for NeighbourReader { + fn manifest(&self) -> &PluginManifest { + &self.m + } + + fn render(&self, _frame: &mut PluginFrame, _params: &PluginParams, _time: f64) -> Result<(), String> { + Ok(()) + } + + fn reads_other_times(&self) -> bool { + true + } + } + + struct Plain { + m: PluginManifest, + } + + impl EffectPlugin for Plain { + fn manifest(&self) -> &PluginManifest { + &self.m + } + + fn render(&self, _frame: &mut PluginFrame, _params: &PluginParams, _time: f64) -> Result<(), String> { + Ok(()) + } + } + + /// A static white solid with one plug-in effect, registered by `plugin`. + fn plugin_scene(plugin: Arc) -> (Project, ItemId) { + let mut p = Project::default(); + let comp = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + let sid = p.add_item("Solid", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 1.0, 1.0], width: 200, height: 100, pixel_aspect: 1.0 })); + let mut l = build::layer(&mut p, &comp, "Solid", LayerSource::Solid { item: sid }, (200, 100), None); + let spec = register_plugin(plugin).unwrap(); + let mut next = p.next_id; + let g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [200.0, 100.0]); + p.next_id = next; + l.props.sub_mut("effects").unwrap().children.push(g.into()); + p.comp_mut(cid).unwrap().layers.push(l); + (p, cid) + } + + fn key(p: &Project, cid: ItemId, t: f64) -> Option { + let comp = p.comp(cid).unwrap(); + let ctx = crate::EvalCtx { + project: p, + comp_id: cid, + comp, + time: Tick::from_seconds_f64(t), + expr: None, + footage: None, + property_overrides: &[], + media_overrides: &[], + reads: None, + }; + crate::cache::layer_key(&ctx, &comp.layers[0], 1.0, false, false) + } + + let manifest = |id: &str| PluginManifest { + api: 2, + id: id.into(), + name: "Key".into(), + category: "Test Plug-ins".into(), + version: "1".into(), + author: String::new(), + description: String::new(), + params: vec![], + }; + + let (plain, c1) = plugin_scene(Arc::new(Plain { m: manifest("org.test.render.time-key.plain") })); + assert_eq!(key(&plain, c1, 0.25), key(&plain, c1, 0.5), "a plain plug-in keeps the old key"); + let (reader, c2) = plugin_scene(Arc::new(NeighbourReader { m: manifest("org.test.render.time-key.reader") })); + assert_ne!(key(&reader, c2, 0.25), key(&reader, c2, 0.5), "an ABI 2 plug-in keys on the layer time"); +} diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 19c17d53f..1e95bbc11 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -243,6 +243,13 @@ pub fn animator_selection(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: & } "expressionSelector" => { let Some(prop) = sel.get("amount") else { continue }; + // Evaluated per character (`textIndex`): the layer's cache key holds the amount + // for the first character only, so the buffer must not outlive the session. + if prop.has_expression() + && let Some(log) = ctx.reads + { + log.mark_unkeyed(); + } let stat = ctx.v3(layer, sel, "amount", [100.0; 3]); Box::new(move |i, n, prev| { let pv = prev.map(|x| x * 100.0); @@ -343,7 +350,10 @@ pub fn char_transforms(ctx: &EvalCtx, layer: &Layer, text: &PropGroup, lay: &Tex } angles.apply(c, k); if let Some(o) = op { - c.opacity *= 1.0 + (o / 100.0 - 1.0) * k; + // Blend toward this animator's value, so a later animator can show characters an + // earlier one hid (Lottie files rely on it: Opacity 0 % on every character, then + // animators at 100 % that sweep in). With one animator this is the same as before. + c.opacity += (o - c.opacity) * k; } if let Some(f) = fill { c.fill = Some(f); @@ -499,6 +509,16 @@ pub fn per_char_3d(ctx: &EvalCtx, layer: &Layer) -> bool { layer.is_3d() && layer.props.sub("text").is_some_and(|t| ctx.b(layer, t, "perChar3d")) } +/// Animator blur can read glyph pixels beyond a viewport raster window. Conservatively +/// keep the whole raster even when the current selector happens to select no characters. +pub(crate) fn animator_blur(ctx: &EvalCtx, layer: &Layer) -> bool { + layer.props.group("text/animators").is_some_and(|anims| { + anims.groups().filter(|anim| anim.enabled).any(|anim| { + anim.sub("properties").and_then(|props| props.get("blur")).is_some_and(|blur| ctx.value(layer, blur).as_vec2().iter().any(|value| *value != 0.0)) + }) + }) +} + /// One drawn character. #[derive(Clone, Debug)] pub struct PlacedGlyph { @@ -635,11 +655,73 @@ fn align_index(j: Justify) -> u8 { } } +/// Note the font files `lay` is drawn with in [`EvalCtx::reads`] (#3184), each with its identity +/// as its bytes were read, so a cache entry of the text is checked against them. What the +/// files can't vouch for makes the list incomplete: a family that is not installed (installing +/// it changes the text), a character drawn with a fallback face or with none (another installed +/// font could take it), a font from memory. +fn note_fonts(ctx: &EvalCtx, lay: &TextLayout) { + note_layout_fonts(ctx, &lay.styles, &lay.layout); +} + +/// A character put in by Character Offset or Character Value (`ch`, in style `st`), outside a +/// relayout: its outline and advance, with the font it is drawn with noted as [`note_fonts`] does +/// (the run's face may not have it: a fallback face then draws it). +fn substituted_glyph(ctx: &EvalCtx, st: &effectcraft_keyframe::CharStyle, ch: char) -> (BezPath, f64) { + if ctx.reads.is_some() { + // (the layout `char_glyph_style` makes, served from the layout cache there) + let lay = effectcraft_text::layout_text(&ch.to_string(), &effectcraft_text::text_style(st), &effectcraft_text::ParagraphStyle::default()); + note_layout_fonts(ctx, std::slice::from_ref(st), &lay); + } + char_glyph_style(st, ch) +} + +/// [`note_fonts`] for `layout`, whose glyphs' runs index `styles`. +fn note_layout_fonts(ctx: &EvalCtx, styles: &[effectcraft_keyframe::CharStyle], layout: &effectcraft_text::Layout) { + use crate::reads::{FileStamp, ReadFile}; + use effectcraft_text::fonts; + let Some(log) = ctx.reads else { return }; + let resolved: Vec = styles.iter().map(|s| fonts::resolve(&s.font, &s.style)).collect(); + if resolved.iter().any(|r| r.missing) { + log.mark_incomplete(); + } + // Each run's face, glyphs or not: an empty paragraph's face sets its line's metrics (in a + // box, the first baseline that places every later line). + let mut faces: Vec = Vec::new(); + for r in &resolved { + if !faces.contains(&r.face) { + faces.push(r.face); + } + } + for g in &layout.glyphs { + if g.id == 0 || resolved.get(g.run).is_none_or(|r| r.face != g.face) { + log.mark_incomplete(); + } + if !faces.contains(&g.face) { + faces.push(g.face); + } + } + for id in faces { + let face = fonts::face(id); + match &face.info.data { + fonts::FaceData::Static(_) => {} + fonts::FaceData::Shared(_) => log.mark_incomplete(), + fonts::FaceData::File(_) => { + if let Some((path, meta)) = face.file_read() { + let stamp = meta.map_or(FileStamp::Missing, FileStamp::of_metadata); + log.note(ReadFile::new(path.to_string_lossy().as_ref(), stamp)); + } + } + } + } +} + /// Lay out and animate a text layer. pub fn text_geom(ctx: &EvalCtx, layer: &Layer) -> Option { let doc = source_text(ctx, layer)?; let text = layer.props.sub("text")?; let lay = layout_doc(&doc); + note_fonts(ctx, &lay); let xfs = char_transforms(ctx, layer, text, &lay); let three = per_char_3d(ctx, layer); let more = text.sub("moreOptions"); @@ -662,6 +744,7 @@ pub fn text_geom(ctx: &EvalCtx, layer: &Layer) -> Option { // Same character count: the style runs still line up. let d2 = TextDoc { text: chars.into_iter().collect(), ..doc.clone() }; let l2 = layout_doc(&d2); + note_fonts(ctx, &l2); let by_char: std::collections::HashMap = lay.glyphs.iter().zip(&xfs).map(|(g, x)| (g.char_index, *x)).collect(); let x2: Vec = l2.glyphs.iter().map(|g| by_char.get(&g.char_index).copied().unwrap_or_default()).collect(); subs = vec![None; l2.glyphs.len()]; @@ -786,7 +869,7 @@ pub fn text_geom(ctx: &EvalCtx, layer: &Layer) -> Option { // Outline (substituted characters aligned in the original slot). let (outline, adv) = match subs[gi] { Some(c) => { - let (p, a) = char_glyph_style(st, c); + let (p, a) = substituted_glyph(ctx, st, c); let dx = match x.char_align { 0 => 0.0, 2 => g.advance - a, @@ -1049,8 +1132,46 @@ fn draw_glyphs(geom: &TextGeom, img: &mut Image, to_px: &Mat3, s: f64, only: Opt } } +/// Buffer pixels kept around a clip (see [`raster_window`]). +const CLIP_PAD: f64 = 24.0; + +/// The buffer for content bounds `b` (layer space) at scale `s`: (width, height, layer → buffer +/// offset), two pixels of padding around it. With `clip`, only the pixels of that grid inside +/// `clip`, padded by [`CLIP_PAD`]: a whole-pixel window of the whole buffer's grid. Its pixels are +/// the whole buffer's, except that a glyph cut by the window is rasterised from the window's edge: +/// tiny-skia's 4 × 4 anti-aliasing then lands a sub-sample differently on a few edge pixels, up to +/// a dozen rows in from that edge — inside the padding, out of the frame. `None` when `clip` +/// misses the content. +pub(crate) fn raster_window(b: kurbo::Rect, s: f64, clip: Option) -> Option<(u32, u32, [f64; 2])> { + let (full_w, full_h) = ((b.width() * s).ceil() + 4.0, (b.height() * s).ceil() + 4.0); + let full = [-b.x0 * s + 2.0, -b.y0 * s + 2.0]; + let (x0, y0, x1, y1) = match clip { + None => (0.0, 0.0, full_w, full_h), + // Nothing shows (behind the camera). + Some(c) if c.area() <= 0.0 => return None, + Some(c) => ( + (c.x0 * s + full[0] - CLIP_PAD).floor().max(0.0), + (c.y0 * s + full[1] - CLIP_PAD).floor().max(0.0), + (c.x1 * s + full[0] + CLIP_PAD).ceil().min(full_w), + (c.y1 * s + full[1] + CLIP_PAD).ceil().min(full_h), + ), + }; + if !(x1 > x0 && y1 > y0) { + return None; + } + let w = ((x1 - x0) as u32).clamp(1, 16384); + let h = ((y1 - y0) as u32).clamp(1, 16384); + Some((w, h, [full[0] - x0, full[1] - y0])) +} + /// Render a text layer into a layer-space buffer at scale `s`. pub fn render(ctx: &EvalCtx, layer: &Layer, s: f64) -> Buf { + render_in(ctx, layer, s, None) +} + +/// [`render`], only the part of the layer inside `clip` (layer space; the part the output shows, +/// see `Renderer::raster_clip`). +pub fn render_in(ctx: &EvalCtx, layer: &Layer, s: f64, clip: Option) -> Buf { let empty = || Buf { img: Image::new(1, 1), offset: [0.0; 2], scale: s }; let Some(geom) = text_geom(ctx, layer) else { return empty() }; let mut bounds: Option = None; @@ -1064,9 +1185,7 @@ pub fn render(ctx: &EvalCtx, layer: &Layer, s: f64) -> Buf { } let Some(b) = bounds else { return empty() }; let b = b.intersect(kurbo::Rect::new(-20000.0, -20000.0, 20000.0, 20000.0)); - let w = ((b.width() * s).ceil() as u32 + 4).clamp(1, 16384); - let h = ((b.height() * s).ceil() as u32 + 4).clamp(1, 16384); - let offset = [-b.x0 * s + 2.0, -b.y0 * s + 2.0]; + let Some((w, h, offset)) = raster_window(b, s, clip) else { return empty() }; let mut img = Image::new(w, h); let base = Mat3::translate(vec2(offset[0], offset[1])) * Mat3::scale(vec2(s, s)); draw_glyphs(&geom, &mut img, &base, s, None); diff --git a/crates/render/src/text/tests.rs b/crates/render/src/text/tests.rs index 503ea097c..9b52d3098 100644 --- a/crates/render/src/text/tests.rs +++ b/crates/render/src/text/tests.rs @@ -548,6 +548,22 @@ fn keyframed_selector_animates() { assert_eq!(selection(&p, cid, 1.0, 1), vec![0.0; 4]); } +#[test] +fn a_later_animator_opacity_shows_characters_an_earlier_one_hid() { + let (mut p, cid, comp) = setup(400, 200); + let mut l = text_layer(&mut p, &comp, doc("ABCD", 40.0)); + animator(&mut p, &mut l, &["opacity"], &["range"]); + set(&mut l, "text/animators/#1/properties/opacity", Value::Scalar(0.0)); + animator(&mut p, &mut l, &["opacity"], &["range"]); + set(&mut l, "text/animators/#2/properties/opacity", Value::Scalar(60.0)); + set(&mut l, "text/animators/#2/selectors/#1/end", Value::Scalar(50.0)); + p.comp_mut(cid).unwrap().layers.push(l); + let glyphs = glyph_paths(&ctx(&p, cid, 0.0), &p.comp(cid).unwrap().layers[0]); + let opacity: Vec = glyphs.iter().map(|g| (g.1.opacity * 1000.0).round() / 1000.0).collect(); + // The second animator selects "AB" only: they come back at 60 %, "CD" stay hidden. + assert_eq!(opacity, [60.0, 60.0, 0.0, 0.0]); +} + #[test] fn caret_follows_animators_and_path_text() { let (mut p, cid, comp) = setup(400, 400); @@ -699,3 +715,90 @@ fn range_bar_drag_values() { assert_eq!(range_value_of(3.6 / 7.0, 0.0, true, 7), 4.0); assert_eq!(range_value_of(3.6 / 7.0, 2.0 / 7.0, true, 7), 2.0, "less a 2-character Offset"); } + +/// Text names the font files it is drawn with (#3184), with their identity as they were read, so +/// a cache entry of it is checked against them; what the files can't vouch for (a family that +/// isn't installed) leaves the list incomplete. +#[test] +fn text_notes_the_font_files_it_draws_with() { + use crate::reads::{FileStamp, ReadLog}; + use effectcraft_text::fonts::{self, FaceData, FaceInfo, FontSource}; + struct OneFile(std::path::PathBuf); + impl FontSource for OneFile { + fn faces(&self) -> Vec { + vec![FaceInfo { + family: "Reads Test Sans".into(), + style: "Regular".into(), + weight: 400, + italic: false, + index: 0, + data: FaceData::File(self.0.clone()), + origin: "system", + native_family: None, + full_name: "Reads Test Sans Regular".into(), + postscript: None, + variable: false, + instances: vec![], + }] + } + } + // (a fresh directory, removed when the test ends, panicking or not) + let dir = tempfile::tempdir().unwrap(); + let font = dir.path().join("reads-test-sans.ttf"); + std::fs::write(&font, fonts::INTER_REGULAR).unwrap(); + fonts::add_source(&OneFile(font.clone())); + let stamp = FileStamp::native(&font.to_string_lossy()).unwrap(); + // (`value`: a Character Value animator puts that character in for every one) + let files_with = |family: &str, value: Option| { + let (mut p, cid, comp) = setup(200, 80); + let mut l = + text_layer(&mut p, &comp, TextDoc { text: "Hi there\rtwo".into(), font: family.into(), style: "Regular".into(), size: 30.0, ..Default::default() }); + if let Some(c) = value { + animator(&mut p, &mut l, &["characterValue"], &["range"]); + set(&mut l, "text/animators/#1/properties/characterValue", Value::Scalar(c as u32 as f64)); + } + p.comp_mut(cid).unwrap().layers.push(l); + let log = ReadLog::new(); + let c = EvalCtx { reads: Some(&log), ..ctx(&p, cid, 0.0) }; + assert!(text_geom(&c, &p.comp(cid).unwrap().layers[0]).is_some()); + log.into_files() + }; + let files_of = |family: &str| files_with(family, None); + let files = files_of("Reads Test Sans"); + assert!(files.is_complete(), "{files:?}"); + assert_eq!(files.files().len(), 1, "{files:?}"); + assert_eq!(files.get(&font.to_string_lossy()), Some(stamp)); + // The bundled family reads no file. + let files = files_of(effectcraft_text::fonts::DEFAULT_FAMILY); + assert!(files.is_complete() && files.is_empty(), "{files:?}"); + // A family that isn't installed falls back: installing it would change the text. + assert!(!files_of("No Such Family 3184").is_complete()); + // A substituted character the face has is drawn with it: the same one file. + let files = files_with("Reads Test Sans", Some('B')); + assert!(files.is_complete(), "{files:?}"); + assert_eq!(files.get(&font.to_string_lossy()), Some(stamp)); + // One it lacks (Inter has no CJK) is drawn with a fallback face, or none: another installed + // font could take it, so the list can't vouch for the text. + assert!(!files_with("Reads Test Sans", Some('\u{4e2d}')).is_complete()); + // An empty first paragraph in the face draws no glyph, but in a box its face sets the first + // baseline that places the lines after it: the file is read all the same. + let (mut p, cid, comp) = setup(200, 80); + let base = TextDoc { + text: "\rHi".into(), + font: fonts::DEFAULT_FAMILY.into(), + style: "Regular".into(), + size: 30.0, + box_size: Some([180.0, 60.0]), + ..Default::default() + }; + let first = effectcraft_keyframe::CharStyle { font: "Reads Test Sans".into(), ..base.base_style() }; + let runs = vec![effectcraft_keyframe::StyleRun { len: 1, style: first }, effectcraft_keyframe::StyleRun { len: 2, style: base.base_style() }]; + let l = text_layer(&mut p, &comp, TextDoc { runs, ..base }); + p.comp_mut(cid).unwrap().layers.push(l); + let log = ReadLog::new(); + let c = EvalCtx { reads: Some(&log), ..ctx(&p, cid, 0.0) }; + assert!(text_geom(&c, &p.comp(cid).unwrap().layers[0]).is_some()); + let files = log.into_files(); + assert!(files.is_complete(), "{files:?}"); + assert_eq!(files.get(&font.to_string_lossy()), Some(stamp), "{files:?}"); +} diff --git a/crates/render/src/three_d/adv/scene.rs b/crates/render/src/three_d/adv/scene.rs index 22507069e..6d2b071d5 100644 --- a/crates/render/src/three_d/adv/scene.rs +++ b/crates/render/src/three_d/adv/scene.rs @@ -477,6 +477,7 @@ fn clip_start(ctx: &EvalCtx, layer: &Layer, prop: &Property, lt: Tick) -> Tick { start } +/// Adds a model layer to the Advanced 3D scene with its material options, opacity and world transform. fn model_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, b: &mut Builder) { let lin = b.s.linear_io; let (opts, prim_mat) = model_options(ctx, layer, lin); @@ -487,7 +488,7 @@ fn model_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, b: &mut Builder) { LayerSource::Model { item } => { let Some(it) = r.project.item(*item) else { return }; let ItemKind::Footage(f) = &it.kind else { return }; - let Some(m) = r.footage.model(*item, f) else { return }; + let Some(m) = r.read(|| r.footage.model(*item, f)) else { return }; let unit = geo.map_or(1.0, |g| ctx.f(layer, g, "unitScale", 1.0)); let clip = geo.map_or(0, |g| ctx.e(layer, g, "animation")) as usize; let clip = clip.checked_sub(1).filter(|c| *c < m.animations.len()); @@ -651,12 +652,13 @@ pub fn extruded_meshes(ctx: &EvalCtx, layer: &Layer, p: &model::extrude::Extrude out } +/// Adds an extruded layer to the Advanced 3D scene with its card material, opacity and world transform. fn extruded_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, p: &model::extrude::ExtrudeParams, b: &mut Builder) { let base = card_material(ctx, layer); let opacity = (ctx.opacity(layer) as f32 * r.opacity_mul()).clamp(0.0, 1.0); let world = b.outer * ctx.world_matrix(layer); let lin = b.s.linear_io; - for (mesh, c, local) in extruded_meshes(ctx, layer, p) { + for (mesh, c, local) in extruded_meshes(&r.with_reads(ctx), layer, p) { let l = |v: f32| if lin { v } else { srgb_to_linear(v) }; let m = b.material(Material { base: [l(c[0]), l(c[1]), l(c[2]), c[3]], @@ -694,13 +696,14 @@ fn card(b: &mut Builder, buf: &Buf, world: Mat4, mut mat: Material) { b.emit(&p, m, &|_| world); } +/// Adds a flat card layer to the Advanced 3D scene with its material, opacity and world transform. fn card_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, b: &mut Builder) { let mut mat = card_material(ctx, layer); mat.opacity = (ctx.opacity(layer) as f32 * r.opacity_mul()).clamp(0.0, 1.0); let world = b.outer * ctx.world_matrix(layer); if crate::text::per_char_3d(ctx, layer) { - for (buf, m) in crate::text::per_char_planes(ctx, layer, r.opts.scale) { - let buf = r.to_blend(Arc::new(buf), None); + for (buf, m) in crate::text::per_char_planes(&r.with_reads(ctx), layer, r.opts.scale) { + let buf = r.to_blend(Arc::new(buf), None, &Arc::default()); card(b, &buf, world * m, mat); } return; diff --git a/crates/render/src/three_d/adv/tests.rs b/crates/render/src/three_d/adv/tests.rs index b2612de98..88e805882 100644 --- a/crates/render/src/three_d/adv/tests.rs +++ b/crates/render/src/three_d/adv/tests.rs @@ -822,6 +822,7 @@ fn extruded_text_renders_as_a_mesh() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &ctx.comp.layers[0]; let params = scene::extrusion_params(&ctx, l).unwrap(); @@ -870,6 +871,7 @@ fn shape_surface_items_colour_the_extruded_surfaces() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &ctx.comp.layers[0]; let params = scene::extrusion_params(&ctx, l).unwrap(); @@ -915,6 +917,7 @@ fn text_animators_colour_the_extruded_surfaces() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &ctx.comp.layers[0]; let params = scene::extrusion_params(&ctx, l).unwrap(); @@ -1122,6 +1125,7 @@ fn extruded_strokes_render_as_bevelled_meshes() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &ctx.comp.layers[0]; let params = scene::extrusion_params(&ctx, l).unwrap(); diff --git a/crates/render/src/three_d/camera.rs b/crates/render/src/three_d/camera.rs index a927e2ceb..6aee50a78 100644 --- a/crates/render/src/three_d/camera.rs +++ b/crates/render/src/three_d/camera.rs @@ -117,12 +117,15 @@ pub fn basis_view(eye: Vec3, forward: Vec3, down_hint: Vec3) -> Mat4 { Mat4([[r.x, r.y, r.z, 0.0], [d.x, d.y, d.z, 0.0], [f.x, f.y, f.z, 0.0], [0.0, 0.0, 0.0, 1.0]]) * Mat4::translate(-eye) } -/// Orientation angles (degrees, AE order X→Y→Z with Z = 0) that point +z along `dir`. +/// Orientation angles (degrees, [`Mat4::orientation`]'s order) that point +z along `dir` with +/// the layer's x axis kept level (no roll): the pitch about x, then the turn about the world's +/// vertical axis, written as Orientation. pub fn orientation_for(dir: Vec3) -> [f64; 3] { let d = dir.normalize(); - let x = (-d.y).clamp(-1.0, 1.0).asin().to_degrees(); - let y = d.x.atan2(d.z).to_degrees(); - [norm360(x), norm360(y), 0.0] + let pitch = (-d.y).clamp(-1.0, 1.0).asin().to_degrees(); + let yaw = d.x.atan2(d.z).to_degrees(); + let o = (Mat4::rotate_y(yaw) * Mat4::rotate_x(pitch)).orientation_angles(); + [norm360(o.x), norm360(o.y), norm360(o.z)] } fn norm360(a: f64) -> f64 { @@ -177,7 +180,7 @@ pub fn layer_rotation(ctx: &EvalCtx, layer: &Layer) -> Mat4 { let rx = ctx.f(layer, tr, "rotationX", 0.0); let ry = ctx.f(layer, tr, "rotationY", 0.0); let rz = ctx.f(layer, tr, "rotation", 0.0); - Mat4::orientation(Vec3::from(o)) * Mat4::rotate_z(rz) * Mat4::rotate_y(ry) * Mat4::rotate_x(rx) + Mat4::orientation(Vec3::from(o)) * Mat4::rotation_xyz(rx, ry, rz) } /// World matrix of a layer's parent chain (identity when unparented). diff --git a/crates/render/src/three_d/compose.rs b/crates/render/src/three_d/compose.rs index a5a7c170e..8713833c3 100644 --- a/crates/render/src/three_d/compose.rs +++ b/crates/render/src/three_d/compose.rs @@ -185,6 +185,52 @@ pub(crate) fn view_size(r: &Renderer, ctx: &EvalCtx) -> (f64, f64) { (c.width as f64, c.height as f64) } +/// The layer-space rectangle of a 3D layer that this render's output can show: the output frame +/// (padded by two pixels) projected back onto the layer's plane, the way [`geo`] draws it. `None` +/// when that can't be bounded: an orthographic camera, depth of field (its blur reads past the +/// frame), motion blur (each sub-sample sees another part), or a frame corner whose ray misses the +/// plane in front of the camera (a plane seen towards its horizon). An empty rectangle when the +/// whole content is behind the camera. +pub(crate) fn visible_clip(r: &Renderer, ctx: &EvalCtx, layer: &Layer) -> Option { + let cam = camera_for(r, ctx); + if cam.ortho || cam.dof.is_some() || mb_samples(r, ctx, layer) > 1 { + return None; + } + let comp = view_size(r, ctx); + let s = r.opts.scale; + let outer = r.collapse3d.map_or(Mat4::IDENTITY, |c| c.world); + let world = outer * ctx.world_matrix(layer); + let (off, w, h) = match r.roi_offset() { + Some((x, y, w, h)) => ((x, y), w as f64, h as f64), + None => ((0.0, 0.0), (comp.0 * s).round(), (comp.1 * s).round()), + }; + let proj = Mat4::translate(vec3(-off.0, -off.1, 0.0)) * Mat4::scale(vec3(s, s, 1.0)) * cam.projection(comp.0, comp.1); + let hinv = (proj * world).plane_to_mat3().inverse()?; + let cv = cam.view * world; + let depth = |u: f64, v: f64| cv.0[2][0] * u + cv.0[2][1] * v + cv.0[2][3]; + if let Some(b) = crate::content_bounds(ctx, layer) + && [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])].iter().all(|&(u, v)| depth(u, v) < NEAR) + { + return Some(kurbo::Rect::ZERO); + } + const PAD: f64 = 2.0; + let mut rect: Option = None; + for (sx, sy) in [(-PAD, -PAD), (w + PAD, -PAD), (w + PAD, h + PAD), (-PAD, h + PAD)] { + let m = &hinv.0; + let qz = m[2][0] * sx + m[2][1] * sy + m[2][2]; + if qz <= 1e-300 { + return None; + } + let (u, v) = ((m[0][0] * sx + m[0][1] * sy + m[0][2]) / qz, (m[1][0] * sx + m[1][1] * sy + m[1][2]) / qz); + if !u.is_finite() || !v.is_finite() || depth(u, v) < NEAR { + return None; + } + let p = kurbo::Rect::new(u, v, u, v); + rect = Some(rect.map_or(p, |r| r.union(p))); + } + rect +} + /// Number of motion-blur sub-samples for a layer. fn mb_samples(r: &Renderer, ctx: &EvalCtx, layer: &Layer) -> usize { if r.opts.motion_blur && ctx.comp.enable_motion_blur && r.layer_motion_blur(layer) { @@ -203,9 +249,11 @@ pub(crate) fn prepare<'a>(r: &Renderer, ctx: &EvalCtx<'_>, layer: &'a Layer, ord /// Prepare a layer as planes: one per character for per-character 3D text, else one. pub(crate) fn prepare_all<'a>(r: &Renderer, ctx: &EvalCtx<'_>, layer: &'a Layer, order: usize, out: (u32, u32), in_run: bool) -> Vec> { if crate::text::per_char_3d(ctx, layer) { - return crate::text::per_char_planes(ctx, layer, r.opts.scale) + return crate::text::per_char_planes(&r.with_reads(ctx), layer, r.opts.scale) .into_iter() - .filter_map(|(buf, m)| prepare_with(r, ctx, layer, order, out, in_run, PlaneInput { buf: r.to_blend(Arc::new(buf), None), local: m })) + .filter_map(|(buf, m)| { + prepare_with(r, ctx, layer, order, out, in_run, PlaneInput { buf: r.to_blend(Arc::new(buf), None, &Arc::default()), local: m }) + }) .collect(); } prepare(r, ctx, layer, order, out, in_run).into_iter().collect() diff --git a/crates/render/src/three_d/tests_orient.rs b/crates/render/src/three_d/tests_orient.rs index f9c72e296..bbecc7fc0 100644 --- a/crates/render/src/three_d/tests_orient.rs +++ b/crates/render/src/three_d/tests_orient.rs @@ -215,3 +215,264 @@ fn layer_cache_is_independent_of_camera_lights_and_view() { assert_ne!(third, second); assert!(cache.stats().hits > 0, "the cache was actually used"); } + +/// A 1920 × 1080 comp with a full-frame 3D solid whose transform `set` changes (and an optional +/// one-node camera at the default camera's place), as the After Effects reference cases. +fn ae_frame(set: impl Fn(&mut Layer), camera: Option<([f64; 3], [f64; 3])>) -> (Project, ItemId) { + let mut p = Project::default(); + let comp = Comp::new(1920, 1080, FrameRate::FPS_25, Tick::from_seconds_f64(5.0)); + let cid = p.add_item("C", Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + let sid = p.add_item("L", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 1920, height: 1080, pixel_aspect: 1.0 })); + let mut l = build::layer(&mut p, &comp, "L", LayerSource::Solid { item: sid }, (1920, 1080), None); + l.switches.three_d = true; + set(&mut l); + let mut layers = vec![]; + if let Some((orientation, rotation)) = camera { + let mut cam = build::layer(&mut p, &comp, "K", LayerSource::Camera, (1920, 1080), None); + cam.auto_orient = AutoOrient::Off; + cam.props.prop_mut("transform/position").unwrap().value = Value::Vec3([960.0, 540.0, -1920.0 * 50.0 / 36.0]); + cam.props.prop_mut("transform/orientation").unwrap().value = Value::Vec3(orientation); + for (m, v) in [("transform/rotationX", rotation[0]), ("transform/rotationY", rotation[1]), ("transform/rotation", rotation[2])] { + cam.props.prop_mut(m).unwrap().value = Value::Scalar(v); + } + cam.props.prop_mut("cameraOptions/zoom").unwrap().value = Value::Scalar(1920.0 * 50.0 / 36.0); + layers.push(cam); + } + layers.push(l); + p.comp_mut(cid).unwrap().layers = layers.into(); + (p, cid) +} + +/// Whether comp pixel (x, y) shows the solid, from its layer → comp mapping. +fn covers(p: &Project, cid: ItemId, secs: f64, x: u32, y: u32) -> bool { + let c = p.comp(cid).unwrap(); + let ctx = EvalCtx::new(p, cid, c, Tick::from_seconds_f64(secs)); + let l = c.layers.last().unwrap(); + let inv = ctx.layer_to_comp(l).0.inverse().unwrap(); + let u = inv.apply(effectcraft_geom::vec2(x as f64 + 0.5, y as f64 + 0.5)); + (0.0..=1920.0).contains(&u.x) && (0.0..=1080.0).contains(&u.y) +} + +fn check_points(p: &Project, cid: ItemId, secs: f64, case: &str, pts: &[(u32, u32, bool)]) { + for &(x, y, red) in pts { + assert_eq!(covers(p, cid, secs, x, y), red, "case {case}: pixel ({x}, {y}) should be {}", if red { "red" } else { "black" }); + } +} + +fn set3(l: &mut Layer, m: &str, v: [f64; 3]) { + l.props.prop_mut(m).unwrap().value = Value::Vec3(v); +} + +fn set1(l: &mut Layer, m: &str, v: f64) { + l.props.prop_mut(m).unwrap().value = Value::Scalar(v); +} + +/// Orientation and X/Y/Z Rotation compose as `Rx · Ry · Rz` (Z turns the layer first), and +/// Orientation comes before the axis rotations, in layers and cameras alike. The points are +/// sampled from After Effects 2026 renders of the synthetic cases (each at least 3 px from an +/// edge; red = the solid covers the pixel), a third of them where the old Z · Y · X order differed. +#[test] +fn rotation_order_matches_after_effects() { + // 488: Orientation [10, 20, 30]. + let (p, cid) = ae_frame(|l| set3(l, "transform/orientation", [10.0, 20.0, 30.0]), None); + check_points( + &p, + cid, + 1.0, + "488", + &[ + (328, 687, false), + (416, 764, false), + (209, 237, true), + (548, 861, false), + (1899, 425, false), + (87, 462, true), + (162, 581, false), + (662, 948, false), + (682, 849, true), + (618, 413, true), + (1380, 181, true), + (605, 378, true), + (1830, 518, true), + (559, 197, true), + (1760, 843, true), + (550, 823, true), + (572, 952, false), + (272, 963, false), + (268, 761, false), + (628, 1073, false), + (218, 721, false), + (256, 807, false), + (225, 881, false), + (167, 637, false), + ], + ); + // 800: X / Y / Z Rotation 10 / 20 / 30. + let (p, cid) = ae_frame( + |l| { + set1(l, "transform/rotationX", 10.0); + set1(l, "transform/rotationY", 20.0); + set1(l, "transform/rotation", 30.0); + }, + None, + ); + check_points( + &p, + cid, + 1.0, + "800", + &[ + (104, 450, true), + (755, 1002, false), + (1407, 149, false), + (271, 66, true), + (288, 54, true), + (113, 393, true), + (204, 174, true), + (1790, 360, false), + (1414, 324, true), + (682, 343, true), + (1147, 153, true), + (345, 446, true), + (1516, 542, true), + (666, 25, true), + (1327, 1065, true), + (778, 267, true), + (1588, 5, false), + (1706, 147, false), + (357, 978, false), + (97, 689, false), + (1483, 79, false), + (433, 848, false), + (255, 802, false), + (636, 1057, false), + ], + ); + // 801: Orientation [0, 30, 0] with X Rotation 40 (Orientation first). + let (p, cid) = ae_frame( + |l| { + set3(l, "transform/orientation", [0.0, 30.0, 0.0]); + set1(l, "transform/rotationX", 40.0); + }, + None, + ); + check_points( + &p, + cid, + 1.0, + "801", + &[ + (1356, 35, true), + (1762, 19, true), + (190, 227, true), + (108, 182, true), + (502, 832, true), + (1539, 203, true), + (722, 812, true), + (1872, 76, true), + (1166, 165, true), + (1640, 380, true), + (629, 619, true), + (1796, 574, true), + (1767, 311, true), + (1432, 421, true), + (1819, 425, true), + (283, 252, true), + (563, 1062, false), + (428, 963, false), + (77, 417, false), + (47, 833, false), + (995, 933, false), + (159, 839, false), + (827, 947, false), + (564, 908, false), + ], + ); + // 804: a one-node camera with Orientation [4, 6, 30]; 805: the same as X / Y / Z Rotation. + for (case, cam) in [("804", ([4.0, 6.0, 30.0], [0.0; 3])), ("805", ([0.0; 3], [4.0, 6.0, 30.0]))] { + let (p, cid) = ae_frame(|_| {}, Some(cam)); + check_points( + &p, + cid, + 1.0, + case, + &[ + (204, 410, false), + (1077, 38, false), + (60, 492, false), + (1732, 752, true), + (265, 475, false), + (1743, 821, true), + (1417, 1043, true), + (1559, 944, true), + (1280, 310, true), + (702, 984, true), + (1072, 893, true), + (370, 1042, true), + (1353, 570, true), + (1178, 136, true), + (1201, 289, true), + (1241, 605, true), + (75, 337, false), + (71, 138, false), + (352, 24, false), + (1764, 109, false), + (186, 338, false), + (1835, 668, false), + (211, 269, false), + (157, 143, false), + ], + ); + } +} + +/// Keyed Orientation turns along the shortest arc between the keys (case 802: [0, 0, 0] at 0 s +/// to [60, 80, 40] at 2 s, linear; points from the After Effects render at 1 s, a third of them +/// where blending each angle on its own differed). +#[test] +fn keyed_orientation_renders_as_after_effects() { + let (p, cid) = ae_frame( + |l| { + l.props.prop_mut("transform/orientation").unwrap().keys = + vec![Keyframe::new(Tick::ZERO, Value::Vec3([0.0; 3])), Keyframe::new(Tick::from_seconds_f64(2.0), Value::Vec3([60.0, 80.0, 40.0]))]; + }, + None, + ); + check_points( + &p, + cid, + 1.0, + "802", + &[ + (1880, 472, false), + (1598, 191, false), + (248, 285, true), + (1157, 51, false), + (1628, 129, false), + (357, 37, true), + (1865, 891, true), + (1915, 946, true), + (1728, 1021, true), + (1178, 665, true), + (1303, 631, true), + (1339, 954, true), + (910, 891, true), + (1257, 1002, true), + (1349, 890, true), + (1388, 551, true), + (356, 500, false), + (490, 1058, false), + (524, 829, false), + (73, 29, false), + (393, 769, false), + (1867, 124, false), + (42, 733, false), + (648, 1007, false), + ], + ); + // The value After Effects reads back half-way. + let c = p.comp(cid).unwrap(); + let v = c.layers[0].props.prop("transform/orientation").unwrap().value_at(Tick::from_seconds_f64(1.0)).as_vec3(); + let want = [30.6186, 35.7617, 28.4317]; + assert!((0..3).all(|i| (v[i] - want[i]).abs() < 1e-3), "{v:?}"); +} diff --git a/crates/sam2/examples/gpu_matmul.rs b/crates/sam2/examples/gpu_matmul.rs index 1429ebf02..29d2bcee5 100644 --- a/crates/sam2/examples/gpu_matmul.rs +++ b/crates/sam2/examples/gpu_matmul.rs @@ -67,10 +67,10 @@ fn main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_id) li: "#; fn main() -> Result<(), Box> { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); - let adapter = pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - )?; + // wgpu's environment variables apply (`WGPU_BACKEND`, `WGPU_POWER_PREF`, ...), as for SAM 2's own instance + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle().with_env()); + let power_preference = wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::HighPerformance); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference, ..Default::default() }))?; println!("adapter: {:?}", adapter.get_info().name); let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { required_limits: adapter.limits(), ..Default::default() }))?; let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); diff --git a/crates/sam2/src/decoder.rs b/crates/sam2/src/decoder.rs index d6b25a7e4..bb9f67d43 100644 --- a/crates/sam2/src/decoder.rs +++ b/crates/sam2/src/decoder.rs @@ -144,6 +144,25 @@ fn add_bias(x: Tensor, b: &Tensor) -> Result { Ok(x.broadcast_add(&b.reshape((1, b.dim(0)?, 1, 1))?)?) } +/// `conv_transpose2d` with a 2 x 2 kernel, stride 2, no padding, on tokens `[h * w, c]` (the image +/// laid out row by row) with weight `[c, o, 2, 2]`, as one matrix product plus a pixel shuffle: +/// every input pixel owns its own 2 x 2 output block, so there is no overlap to add up. Returns +/// `[1, o, 2h, 2w]` without the bias. candle's transposed convolution takes about twice as long. +fn conv_transpose_2x2(tokens: &Tensor, h: usize, w: usize, weight: &Tensor) -> Result { + let (c, o, kh, kw) = weight.dims4()?; + if (kh, kw) != (2, 2) || tokens.dims() != [h * w, c] { + return Err(Error::Input(format!("a 2x2 transposed convolution got tokens {:?} for a {c}x{o}x{kh}x{kw} weight on {h}x{w}", tokens.dims()))); + } + let y = tokens.matmul(&weight.reshape((c, o * 4))?)?; // [h * w, (o, 2, 2)] + Ok(y.reshape((h, w, o, 2, 2))?.permute((2, 0, 3, 1, 4))?.contiguous()?.reshape((1, o, 2 * h, 2 * w))?) +} + +/// The same convolution on an image `[1, c, h, w]`. +fn conv_transpose_2x2_image(x: &Tensor, weight: &Tensor) -> Result { + let (_, c, h, w) = x.dims4()?; + conv_transpose_2x2(&x.reshape((c, h * w))?.t()?.contiguous()?, h, w, weight) +} + impl MaskDecoder { pub fn load(w: &Weights) -> Result { let layers = (0..2) @@ -194,6 +213,22 @@ impl MaskDecoder { /// no-memory embedding already added when there is no memory), `sparse`: `[1, n, 256]`, /// `dense`: `[1, 256, g, g]`, `high`: the skip features from [`MaskDecoder::high_res`]. pub fn forward(&self, image: &Tensor, pos: &Tensor, sparse: &Tensor, dense: &Tensor, high: &(Tensor, Tensor), multimask: bool) -> Result { + self.forward_with(image, pos, sparse, dense, high, multimask, true) + } + + /// [`MaskDecoder::forward`]; `matmul_upscale` picks the matrix-product transposed convolutions + /// (the normal path) or candle's `conv_transpose2d` (the reference the tests compare with). + #[allow(clippy::too_many_arguments)] + fn forward_with( + &self, + image: &Tensor, + pos: &Tensor, + sparse: &Tensor, + dense: &Tensor, + high: &(Tensor, Tensor), + multimask: bool, + matmul_upscale: bool, + ) -> Result { let (_, c, g, gw) = image.dims4()?; if c != DIM || g != gw { return Err(Error::Input(format!("image embedding must be 256 x g x g, got {:?}", image.dims()))); @@ -214,13 +249,19 @@ impl MaskDecoder { let mask_tokens_out = queries.narrow(1, 2, MASK_TOKENS)?; let obj_out = queries.narrow(1, 0, 1)?.squeeze(1)?; - let emb = keys.transpose(1, 2)?.contiguous()?.reshape((1, DIM, g, g))?; let (s0, s1) = high; - let up = add_bias(emb.conv_transpose2d(&self.up1.0, 0, 0, 2, 1)?, &self.up1.1)?; + let up = if matmul_upscale { + // the keys are already the image's tokens, row by row: no transpose needed + conv_transpose_2x2(&keys.reshape((g * g, DIM))?, g, g, &self.up1.0)? + } else { + keys.transpose(1, 2)?.contiguous()?.reshape((1, DIM, g, g))?.conv_transpose2d(&self.up1.0, 0, 0, 2, 1)? + }; + let up = add_bias(up, &self.up1.1)?; let up = (up + s1)?; let up = self.up_ln.forward(&up.permute((0, 2, 3, 1))?)?.permute((0, 3, 1, 2))?.contiguous()?; let up = gelu(&up)?; - let up = (add_bias(up.conv_transpose2d(&self.up2.0, 0, 0, 2, 1)?, &self.up2.1)? + s0)?; + let up = if matmul_upscale { conv_transpose_2x2_image(&up, &self.up2.0)? } else { up.conv_transpose2d(&self.up2.0, 0, 0, 2, 1)? }; + let up = (add_bias(up, &self.up2.1)? + s0)?; let up = gelu(&up)?; let hyper: Vec = self.hyper.iter().enumerate().map(|(i, m)| m.forward(&mask_tokens_out.narrow(1, i, 1)?.squeeze(1)?)).collect::>()?; @@ -258,3 +299,101 @@ fn dynamic_single(masks: &Tensor, iou: &Tensor) -> Result<(Tensor, Tensor)> { let best = multi_iou.iter().enumerate().fold((0usize, f32::NEG_INFINITY), |b, (i, v)| if *v > b.1 { (i, *v) } else { b }).0; Ok((masks.narrow(1, 1 + best, 1)?, iou.narrow(1, 1 + best, 1)?)) } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use candle_core::{DType, Device}; + + use super::*; + + fn max_diff(a: &Tensor, b: &Tensor) -> f32 { + assert_eq!(a.dims(), b.dims()); + (a - b).unwrap().abs().unwrap().flatten_all().unwrap().max(0).unwrap().to_scalar::().unwrap() + } + + /// The matrix-product form equals `conv_transpose2d` (kernel 2, stride 2, no padding, the only + /// variant the decoder uses) to rounding, for the decoder's two sizes and for odd ones. + #[test] + fn matmul_transposed_convolution_matches_conv_transpose2d() { + let d = &Device::Cpu; + // (in channels, out channels, height, width) + let cases = + [(256, 64, 64, 64), (64, 32, 128, 128), (256, 64, 16, 16), (3, 5, 7, 11), (5, 3, 1, 9), (4, 2, 9, 1), (1, 1, 1, 1), (17, 1, 3, 5), (1, 19, 6, 2)]; + for (c, o, h, w) in cases { + for (std, scale) in [(1.0, 0.05), (30.0, 3.0)] { + let x = Tensor::randn(0f32, std, (1, c, h, w), d).unwrap(); + let k = Tensor::randn(0f32, scale, (c, o, 2, 2), d).unwrap(); + let want = x.conv_transpose2d(&k, 0, 0, 2, 1).unwrap(); + let got = conv_transpose_2x2_image(&x, &k).unwrap(); + // 1e-6 of the largest output value (at least 1e-6 absolute): float rounding only + let peak = want.abs().unwrap().flatten_all().unwrap().max(0).unwrap().to_scalar::().unwrap(); + let tol = 1e-6 * peak.max(1.0); + let diff = max_diff(&want, &got); + assert!(diff <= tol, "c{c} o{o} {h}x{w} std {std}: max diff {diff:e} > {tol:e}"); + } + } + } + + #[test] + fn matmul_transposed_convolution_edge_values() { + let d = &Device::Cpu; + // zeros, a single hot pixel and negative values land in the right 2x2 block + let k = Tensor::randn(0f32, 1.0, (3, 2, 2, 2), d).unwrap(); + let zero = Tensor::zeros((1, 3, 4, 5), DType::F32, d).unwrap(); + assert_eq!(max_diff(&zero.conv_transpose2d(&k, 0, 0, 2, 1).unwrap(), &conv_transpose_2x2_image(&zero, &k).unwrap()), 0.0); + let mut v = vec![0f32; 3 * 4 * 5]; + v[2 * 20 + 3 * 5 + 1] = -7.5; + let hot = Tensor::from_vec(v, (1, 3, 4, 5), d).unwrap(); + assert!(max_diff(&hot.conv_transpose2d(&k, 0, 0, 2, 1).unwrap(), &conv_transpose_2x2_image(&hot, &k).unwrap()) <= 1e-6); + // other kernels are refused, not computed wrongly + let k3 = Tensor::zeros((3, 2, 3, 3), DType::F32, d).unwrap(); + assert!(conv_transpose_2x2_image(&hot, &k3).is_err()); + } + + /// Random weights for every tensor the decoder asks for, found by loading until nothing is missing. + fn random_decoder() -> MaskDecoder { + let d = &Device::Cpu; + let mut map: HashMap = HashMap::new(); + for _ in 0..1000 { + match MaskDecoder::load(&Weights::from_map(map.clone()).unwrap()) { + Ok(m) => return m, + Err(Error::Weights(m)) => { + let name = m.split('`').nth(1).unwrap().to_string(); + let shape: Vec = match m.split("expected [").nth(1) { + Some(e) => e.trim_end_matches(']').split(',').map(|s| s.trim().parse().unwrap()).collect(), + None => vec![1], + }; + let t = if name.contains("layer_norm") && name.ends_with("weight") { + Tensor::ones(shape, DType::F32, d) + } else { + Tensor::randn(0f32, 0.05, shape, d) + }; + map.insert(name, t.unwrap()); + } + Err(e) => panic!("{e}"), + } + } + panic!("the decoder kept asking for tensors"); + } + + #[test] + fn decoder_output_is_the_same_with_either_transposed_convolution() { + let d = &Device::Cpu; + let dec = random_decoder(); + let g = 16; + let r = |dims: &[usize]| Tensor::randn(0f32, 1.0, dims, d).unwrap(); + let (image, pos, dense) = (r(&[1, DIM, g, g]), r(&[1, DIM, g, g]), r(&[1, DIM, g, g])); + let sparse = r(&[1, 3, DIM]); + let high = dec.high_res(&r(&[1, DIM, 4 * g, 4 * g]), &r(&[1, DIM, 2 * g, 2 * g])).unwrap(); + for multimask in [false, true] { + let a = dec.forward_with(&image, &pos, &sparse, &dense, &high, multimask, false).unwrap(); + let b = dec.forward_with(&image, &pos, &sparse, &dense, &high, multimask, true).unwrap(); + assert!(max_diff(&a.masks, &b.masks) <= 2e-5, "masks differ by {:e}", max_diff(&a.masks, &b.masks)); + assert!(max_diff(&a.iou, &b.iou) <= 1e-5); + assert!(max_diff(&a.sam_tokens, &b.sam_tokens) <= 1e-5); + assert!(max_diff(&a.object_score, &b.object_score) <= 1e-5); + } + } +} diff --git a/crates/sam2/src/gpu.rs b/crates/sam2/src/gpu.rs index bc83b605f..852cc1a08 100644 --- a/crates/sam2/src/gpu.rs +++ b/crates/sam2/src/gpu.rs @@ -99,12 +99,37 @@ pub fn half_weights() -> bool { /// The process's one GPU device, once something has asked for it. static DEVICE: std::sync::OnceLock, String>> = std::sync::OnceLock::new(); +/// The adapter SAM 2 refused and its instance, kept for the life of the process, as the device made on it used to be. +/// Dropping them crashed the tests with a segmentation fault on WSL2's OpenGL driver (Mesa 23.2 on D3D12). At most one: +/// [`Gpu::new`] runs once. +static REFUSED: std::sync::OnceLock<(wgpu::Instance, wgpu::Adapter)> = std::sync::OnceLock::new(); + +/// SAM 2's wgpu instance reads wgpu's environment variables (`WGPU_BACKEND`, `WGPU_VALIDATION`, +/// `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER`…), as the render context's does, so both choose among the same adapters. +fn instance_descriptor() -> wgpu::InstanceDescriptor { + wgpu::InstanceDescriptor::new_without_display_handle().with_env() +} + +/// Why SAM 2 does not use an adapter, if it does not: a software one (the CPU path is faster), or one without compute +/// shaders (OpenGL ES 3.0, for one), where every kernel would fail validation. Checked before a device is made there. +fn refusal(name: &str, backend: wgpu::Backend, device_type: wgpu::DeviceType, downlevel: wgpu::DownlevelFlags) -> Option { + if device_type == wgpu::DeviceType::Cpu { + return Some(format!("only a software adapter ({name}) is available")); + } + (!downlevel.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS)).then(|| format!("the GPU adapter {name} ({backend:?}) has no compute shaders")) +} + impl Gpu { /// The process's one GPU device, created on first use. Several devices at once upset some Vulkan loaders /// (a crash when two threads create or drop them together), and one is all SAM 2 needs: models come and go, /// the device stays. An error (no GPU) is remembered too. pub fn shared() -> Result> { - DEVICE.get_or_init(|| Gpu::new().map(Arc::new).map_err(|e| e.to_string())).clone().map_err(Error::Compute) + // The message alone is kept, so the error says "SAM 2 compute:" once. + let keep = |e: Error| match e { + Error::Compute(m) => m, + e => e.to_string(), + }; + DEVICE.get_or_init(|| Gpu::new().map(Arc::new).map_err(keep)).clone().map_err(Error::Compute) } /// Whether the shared device has been looked for yet, and found: `None` before anything has asked @@ -114,16 +139,17 @@ impl Gpu { DEVICE.get().map(|d| d.is_ok()) } - /// A device on the best real GPU (a software adapter is refused: the CPU path is faster). + /// A device on the best real GPU (high performance unless `WGPU_POWER_PREF` says otherwise; see [`refusal`] for the + /// adapters the CPU path runs instead of). fn new() -> Result { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); - let adapter = pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - ) - .map_err(|e| Error::Compute(format!("no GPU adapter: {e}")))?; + let instance = wgpu::Instance::new(instance_descriptor()); + let power_preference = wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::HighPerformance); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference, ..Default::default() })) + .map_err(|e| Error::Compute(format!("no GPU adapter: {e}")))?; let info = adapter.get_info(); - if info.device_type == wgpu::DeviceType::Cpu { - return Err(Error::Compute(format!("only a software adapter ({}) is available", info.name))); + if let Some(why) = refusal(&info.name, info.backend, info.device_type, adapter.get_downlevel_capabilities().flags) { + let _ = REFUSED.set((instance, adapter)); + return Err(Error::Compute(why)); } let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("effectcraft sam2"), diff --git a/crates/sam2/src/gpu/tests.rs b/crates/sam2/src/gpu/tests.rs index e974c34df..09297f542 100644 --- a/crates/sam2/src/gpu/tests.rs +++ b/crates/sam2/src/gpu/tests.rs @@ -452,3 +452,38 @@ fn half_precision_weights_give_the_same_product_to_half_precision() { assert_close(&got, &want, 2e-3 * (k as f32).sqrt(), "f16 vs f32 weights"); assert!(got != want, "the weights really were rounded to half precision"); } + +/// The instance reads wgpu's environment variables, as the render context's does (#2900): with +/// `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER=1` wgpu lists Mesa's Dozen, the only Vulkan driver on WSL2. Run in a +/// child process, which has them set. +#[test] +fn the_instance_reads_the_wgpu_environment() { + const CHILD: &str = "EFFECTCRAFT_TEST_SAM2_WGPU_ENV_CHILD"; + if std::env::var_os(CHILD).is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "gpu::tests::the_instance_reads_the_wgpu_environment", "--nocapture"]) + .env(CHILD, "1") + .env("WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER", "1") + .env("WGPU_BACKEND", "vulkan") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "{stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + return; + } + let desc = instance_descriptor(); + assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags); + assert_eq!(desc.backends, wgpu::Backends::VULKAN); +} + +/// An adapter without compute shaders (a GL one, here) is refused before a device is made on it, with one error +/// instead of a validation error per kernel; so is a software one. +#[test] +fn adapters_without_compute_shaders_are_refused() { + use wgpu::{Backend, DeviceType, DownlevelFlags}; + assert_eq!(refusal("GPU", Backend::Vulkan, DeviceType::DiscreteGpu, DownlevelFlags::all()), None); + let gl = refusal("GPU", Backend::Gl, DeviceType::Other, DownlevelFlags::all() - DownlevelFlags::COMPUTE_SHADERS); + assert_eq!(gl.as_deref(), Some("the GPU adapter GPU (Gl) has no compute shaders")); + let software = refusal("llvmpipe", Backend::Vulkan, DeviceType::Cpu, DownlevelFlags::all()); + assert_eq!(software.as_deref(), Some("only a software adapter (llvmpipe) is available")); +} diff --git a/crates/sam2/src/track.rs b/crates/sam2/src/track.rs index 7e73a1c74..d7717b5d0 100644 --- a/crates/sam2/src/track.rs +++ b/crates/sam2/src/track.rs @@ -28,6 +28,35 @@ struct Source<'a> { count: usize, fetch: RefCell>, sizes: Rc>>, + /// Prompt frames fetched only to learn their size, kept for the encoder (taken on first use). + held: RefCell, +} + +/// Most pixel data (in bytes) kept from the size check of the prompt frames; frames beyond it are +/// fetched again when the tracker needs them. +const HELD_BYTES: usize = 256 << 20; + +#[derive(Default)] +struct Held { + frames: HashMap>, + bytes: usize, +} + +impl Held { + fn keep(&mut self, index: usize, f: &Arc) { + let bytes = f.rgb.len().saturating_mul(std::mem::size_of::<[f32; 3]>()); + let fits = self.bytes.checked_add(bytes).filter(|t| *t <= HELD_BYTES); + if let (Some(total), false) = (fits, self.frames.contains_key(&index)) { + self.frames.insert(index, f.clone()); + self.bytes = total; + } + } + + fn take(&mut self, index: usize) -> Option> { + let f = self.frames.remove(&index)?; + self.bytes = self.bytes.saturating_sub(f.rgb.len().saturating_mul(std::mem::size_of::<[f32; 3]>())); + Some(f) + } } impl FrameSource for Source<'_> { @@ -41,7 +70,11 @@ impl FrameSource for Source<'_> { .filter(|_| index < self.count) .and_then(|offset| self.first.checked_add(offset)) .ok_or_else(|| Error::Input(format!("frame index {index} is outside the clip")))?; - let f = (self.fetch.borrow_mut())(number).ok_or_else(|| Error::Input(format!("frame {number} is not available")))?; + let held = self.held.borrow_mut().take(index); + let f = match held { + Some(f) => f, + None => (self.fetch.borrow_mut())(number).ok_or_else(|| Error::Input(format!("frame {number} is not available")))?, + }; self.sizes.borrow_mut().insert(index, (f.w, f.h)); preprocess(&f.rgb, f.w, f.h) } @@ -58,6 +91,36 @@ fn to_frame(m: &FrameMask, size: (usize, usize)) -> Result { /// Most objects one request may track. const MAX_OBJECTS: usize = 32; +/// Every prompt as `(object, frame index, prompt)`, in frame order (then object order), after +/// checking each prompt frame and recording its size in `source`. Frame order keeps the tracker's +/// two-frame feature cache useful: all objects prompted on a frame are encoded together, so each +/// prompt frame is encoded once however many objects there are. Objects do not influence each +/// other, so the order of prompts across objects does not change any result. +fn gather_prompts<'r>(req: &'r TrackRequest, source: &Source<'_>) -> Result> { + // Prompt coordinates are in the frame's pixels and the model works at 1024 x 1024, so the + // prompted frames' sizes are needed first. + let mut prompt_frames = vec![]; + for (oi, prompts) in req.objects.iter().enumerate() { + for (frame, p) in prompts { + let idx = frame + .checked_sub(req.first) + .and_then(|offset| usize::try_from(offset).ok()) + .filter(|i| *i < req.count) + .ok_or_else(|| Error::Input(format!("prompt frame {frame} is outside the clip")))?; + if !source.sizes.borrow().contains_key(&idx) { + let f = (source.fetch.borrow_mut())(*frame).ok_or_else(|| Error::Input(format!("frame {frame} is not available")))?; + validate_frame_size(f.w, f.h, f.rgb.len())?; + source.sizes.borrow_mut().insert(idx, (f.w, f.h)); + source.held.borrow_mut().keep(idx, &f); + } + prompt_frames.push((oi, idx, p)); + } + } + // stable: prompts of one object on one frame keep their order + prompt_frames.sort_by_key(|(oi, idx, _)| (*idx, *oi)); + Ok(prompt_frames) +} + impl Sam2Mask { fn run_track(&self, req: &TrackRequest, frames: Frames<'_>, cancel: &dyn Fn() -> bool, out: &mut dyn FnMut(usize, i64, TrackedFrame)) -> Result<()> { if req.count == 0 || req.count > MAX_CLIP { @@ -68,25 +131,8 @@ impl Sam2Mask { return Err(Error::Input(format!("tracking needs 1 to {MAX_OBJECTS} objects, each with a prompt on at least one frame"))); } let sizes = Rc::new(RefCell::new(HashMap::new())); - let source = Source { first: req.first, count: req.count, fetch: RefCell::new(frames), sizes: sizes.clone() }; - // Prompt coordinates are in the frame's pixels and the model works at 1024 x 1024, so the - // prompted frames' sizes are needed first. - let mut prompt_frames = vec![]; - for (oi, prompts) in req.objects.iter().enumerate() { - for (frame, p) in prompts { - let idx = frame - .checked_sub(req.first) - .and_then(|offset| usize::try_from(offset).ok()) - .filter(|i| *i < req.count) - .ok_or_else(|| Error::Input(format!("prompt frame {frame} is outside the clip")))?; - if !sizes.borrow().contains_key(&idx) { - let f = (source.fetch.borrow_mut())(*frame).ok_or_else(|| Error::Input(format!("frame {frame} is not available")))?; - validate_frame_size(f.w, f.h, f.rgb.len())?; - sizes.borrow_mut().insert(idx, (f.w, f.h)); - } - prompt_frames.push((oi, idx, p)); - } - } + let source = Source { first: req.first, count: req.count, fetch: RefCell::new(frames), sizes: sizes.clone(), held: RefCell::default() }; + let prompt_frames = gather_prompts(req, &source)?; let mut tracker = VideoTracker::new(self.video_model().clone(), Box::new(source))?; let object_id = |oi: usize| ObjectId(oi as u32 + 1); // each object's first prompted frame: its pass starts there, forwards and backwards @@ -174,8 +220,76 @@ mod tests { #[test] fn source_rejects_overflowing_and_out_of_range_indices_before_fetching() { let mut fetch = |_| panic!("invalid indices must not fetch a frame"); - let source = Source { first: i64::MAX, count: 2, fetch: RefCell::new(&mut fetch), sizes: Default::default() }; + let source = Source { first: i64::MAX, count: 2, fetch: RefCell::new(&mut fetch), sizes: Default::default(), held: RefCell::default() }; assert!(matches!(source.frame(1), Err(Error::Input(_)))); assert!(matches!(source.frame(usize::MAX), Err(Error::Input(_)))); } + + fn clip_frame(w: usize, h: usize) -> Arc { + Arc::new(ClipFrame { rgb: vec![[0.5, 0.25, 0.75]; w * h], w, h }) + } + + fn point_prompt() -> effectcraft_segment::Prompt { + effectcraft_segment::Prompt { points: vec![([1.0, 1.0], true)], bbox: None, mask: None } + } + + /// Several objects prompted on the same frames: prompts come out frame by frame (so the + /// two-frame feature cache holds each prompt frame for all of its objects), and each prompt + /// frame is fetched from the host once, size check and encoding together. + #[test] + fn prompts_run_frame_major_and_each_prompt_frame_is_fetched_once() { + let frames_prompted = [10i64, 13, 16]; + let req = TrackRequest { first: 10, count: 8, objects: (0..4).map(|_| frames_prompted.iter().map(|f| (*f, point_prompt())).collect()).collect() }; + let fetched = RefCell::new(vec![]); + let mut fetch = |n: i64| { + fetched.borrow_mut().push(n); + Some(clip_frame(4, 3)) + }; + let source = Source { first: req.first, count: req.count, fetch: RefCell::new(&mut fetch), sizes: Default::default(), held: RefCell::default() }; + let order: Vec<(usize, usize)> = gather_prompts(&req, &source).unwrap().into_iter().map(|(oi, idx, _)| (idx, oi)).collect(); + let expected: Vec<(usize, usize)> = [0usize, 3, 6].iter().flat_map(|f| (0..4).map(move |o| (*f, o))).collect(); + assert_eq!(order, expected); + assert_eq!(*fetched.borrow(), vec![10, 13, 16], "one size-check fetch per distinct prompt frame"); + // the tracker's first look at each prompt frame reuses the frame already fetched + for idx in [0usize, 3, 6] { + source.frame(idx).unwrap(); + } + assert_eq!(fetched.borrow().len(), 3, "encoding a prompt frame must not fetch it again"); + // a held frame is handed over once; a second look fetches again + source.frame(0).unwrap(); + assert_eq!(*fetched.borrow(), vec![10, 13, 16, 10]); + } + + #[test] + fn prompts_of_one_object_on_one_frame_keep_their_order() { + let (mut a, mut b) = (point_prompt(), point_prompt()); + a.points = vec![([1.0, 1.0], true)]; + b.points = vec![([2.0, 2.0], false)]; + let req = TrackRequest { first: 0, count: 3, objects: vec![vec![(2, a.clone()), (1, point_prompt()), (2, b.clone())]] }; + let mut fetch = |_| Some(clip_frame(2, 2)); + let source = Source { first: 0, count: 3, fetch: RefCell::new(&mut fetch), sizes: Default::default(), held: RefCell::default() }; + let got = gather_prompts(&req, &source).unwrap(); + assert_eq!(got.iter().map(|(_, i, _)| *i).collect::>(), vec![1, 2, 2]); + assert_eq!(got[1].2.points, a.points); + assert_eq!(got[2].2.points, b.points); + } + + #[test] + fn held_frames_are_bounded() { + let mut held = Held::default(); + let big = Arc::new(ClipFrame { rgb: vec![[0.0; 3]; HELD_BYTES / 12 + 1], w: 1, h: HELD_BYTES / 12 + 1 }); + held.keep(0, &big); + assert!(held.take(0).is_none(), "a frame over the cap is not kept"); + let small = clip_frame(4, 4); + held.keep(1, &small); + assert!(held.take(1).is_some()); + assert_eq!(held.bytes, 0); + // the cap is cumulative: frames that fit together are kept, the one that breaks it is not + let third = Arc::new(ClipFrame { rgb: vec![[0.0; 3]; HELD_BYTES / 12 / 3 + 1], w: 1, h: HELD_BYTES / 12 / 3 + 1 }); + for i in 0..4 { + held.keep(i, &third); + } + assert_eq!(held.frames.len(), 2); + assert!(held.bytes <= HELD_BYTES); + } } diff --git a/crates/script/src/lib.rs b/crates/script/src/lib.rs index 11d837677..21774cb24 100644 --- a/crates/script/src/lib.rs +++ b/crates/script/src/lib.rs @@ -79,6 +79,7 @@ pub fn install(s: &mut Session) { s.script = Some(runner); s.script_ui.dispatch = Some(dispatch_ui); s.script_ui.tasks = Some(run_tasks); + s.script_ui.poll_render = Some(ui::poll_render_wait); } /// Run `code` as a one-off script named `name`. diff --git a/crates/script/src/matchnames.rs b/crates/script/src/matchnames.rs index 45b10a0df..01b3258fd 100644 --- a/crates/script/src/matchnames.rs +++ b/crates/script/src/matchnames.rs @@ -149,7 +149,7 @@ const LIGHT: &[(&str, &str)] = &[ ("falloff", "ADBE Light Falloff Type"), ("radius", "ADBE Light Falloff Start"), ("falloffDistance", "ADBE Light Falloff Distance"), - ("castsShadows", "ADBE Light Casts Shadows"), + ("castsShadows", "ADBE Casts Shadows"), ("shadowDarkness", "ADBE Light Shadow Darkness"), ("shadowDiffusion", "ADBE Light Shadow Diffusion"), ]; @@ -309,12 +309,12 @@ pub const EFFECTS: &[(&str, &str)] = &[ ("ec.color.changetocolor", "ADBE Change To Color"), ("ec.color.colorama", "APC Colorama"), ("ec.color.leavecolor", "ADBE Leave Color"), - ("ec.color.photofilter", "ADBE Photo Filter"), + ("ec.color.photofilter", "ADBE PhotoFilterPS"), ("ec.color.vibrance", "ADBE Vibrance"), ("ec.color.lumetri", "ADBE Lumetri"), - ("ec.color.shadowhighlight", "ADBE Shadow/Highlight"), - ("ec.color.selectivecolor", "ADBE Selective Color"), - ("ec.color.gammapedestalgain", "ADBE Gamma/Pedestal/Gain"), + ("ec.color.shadowhighlight", "ADBE ShadowHighlight"), + ("ec.color.selectivecolor", "ADBE SelectiveColor"), + ("ec.color.gammapedestalgain", "ADBE Gamma/Pedestal/Gain2"), ("ec.color.equalize", "ADBE Equalize"), ("ec.color.autocontrast", "ADBE AutoContrast"), ("ec.color.autolevels", "ADBE AutoLevels"), @@ -351,15 +351,15 @@ pub const EFFECTS: &[(&str, &str)] = &[ ("ec.generate.grid", "ADBE Grid"), ("ec.generate.checkerboard", "ADBE Checkerboard"), ("ec.generate.circle", "ADBE Circle"), - ("ec.generate.ellipse", "ADBE Ellipse"), + ("ec.generate.ellipse", "ADBE ELLIPSE"), ("ec.generate.cellpattern", "ADBE Cell Pattern"), ("ec.generate.lensflare", "ADBE Lens Flare"), - ("ec.generate.vegas", "ADBE Vegas"), - ("ec.generate.writeon", "ADBE Write On"), + ("ec.generate.vegas", "APC Vegas"), + ("ec.generate.writeon", "ADBE Write-on"), ("ec.generate.audiospectrum", "ADBE AudSpect"), ("ec.generate.audiowaveform", "ADBE AudWave"), ("ec.generate.beam", "ADBE Laser"), - ("ec.generate.radiowaves", "ADBE Radio Waves"), + ("ec.generate.radiowaves", "APC Radio Waves"), ("ec.generate.scribble", "ADBE Scribble Fill"), ("ec.generate.paintbucket", "ADBE Paint Bucket"), ("ec.key.colorkey", "ADBE Color Key"), @@ -371,12 +371,12 @@ pub const EFFECTS: &[(&str, &str)] = &[ ("ec.key.spill", "ADBE Spill2"), ("ec.matte.simplechoker", "ADBE Simple Choker"), ("ec.matte.mattechoker", "ADBE Matte Choker"), - ("ec.noise.noise", "ADBE Noise"), + ("ec.noise.noise", "ADBE Noise2"), ("ec.noise.fractal", "ADBE Fractal Noise"), ("ec.noise.median", "ADBE Median"), ("ec.noise.addgrain", "VISINF Grain Implant"), ("ec.noise.dustscratches", "ADBE Dust & Scratches"), - ("ec.noise.turbulent", "ADBE Turbulent Noise"), + ("ec.noise.turbulent", "ADBE AIF Perlin Noise 3D"), ("ec.perspective.dropshadow", "ADBE Drop Shadow"), ("ec.perspective.radialshadow", "ADBE Radial Shadow"), ("ec.perspective.bevelalpha", "ADBE Bevel Alpha"), @@ -401,32 +401,73 @@ pub const EFFECTS: &[(&str, &str)] = &[ ("ec.time.echo", "ADBE Echo"), ("ec.time.posterizetime", "ADBE Posterize Time"), ("ec.time.timedisplacement", "ADBE Time Displacement"), - ("ec.time.timedifference", "ADBE Time Difference"), - ("ec.time.pixelmotionblur", "ADBE Pixel Motion Blur"), + ("ec.time.timedifference", "ADBE Difference"), + ("ec.time.pixelmotionblur", "ADBE OFMotionBlur"), ("ec.time.timewarp", "ADBE Timewarp"), ("ec.transition.linearwipe", "ADBE Linear Wipe"), ("ec.transition.radialwipe", "ADBE Radial Wipe"), ("ec.transition.venetian", "ADBE Venetian Blinds"), ("ec.transition.blockdissolve", "ADBE Block Dissolve"), ("ec.transition.gradientwipe", "ADBE Gradient Wipe"), - ("ec.transition.iriswipe", "ADBE Iris Wipe"), + ("ec.transition.iriswipe", "ADBE IRIS_WIPE"), ("ec.utility.applylut", "ADBE Apply Color LUT2"), ("ec.utility.cineon", "ADBE Cineon Converter2"), - ("ec.utility.growbounds", "ADBE Grow Bounds"), + ("ec.utility.growbounds", "ADBE GROW BOUNDS"), ]; fn find<'a>(t: &'a [(&str, &'a str)], k: &str) -> Option<&'a str> { t.iter().find(|(a, _)| *a == k).map(|(_, b)| *b) } +/// Effect match names that resolve to one of our effects but are not the name we emit (#3113): +/// After Effects' hidden obsolete versions (`ADBE Noise`, `ADBE Photo Filter`), which its +/// `addProperty` still accepts, and the names earlier EffectCraft versions emitted by mistake, +/// which scripts written against them may use. Lookup only: `effect()` gives the `EFFECTS` name. +const LEGACY_EFFECTS: &[(&str, &str)] = &[ + ("ADBE Noise", "ec.noise.noise"), + ("ADBE Photo Filter", "ec.color.photofilter"), + ("ADBE Shadow/Highlight", "ec.color.shadowhighlight"), + ("ADBE Selective Color", "ec.color.selectivecolor"), + ("ADBE Gamma/Pedestal/Gain", "ec.color.gammapedestalgain"), + ("ADBE Vegas", "ec.generate.vegas"), + ("ADBE Write On", "ec.generate.writeon"), + ("ADBE Radio Waves", "ec.generate.radiowaves"), + ("ADBE Turbulent Noise", "ec.noise.turbulent"), + ("ADBE Time Difference", "ec.time.timedifference"), + ("ADBE Pixel Motion Blur", "ec.time.pixelmotionblur"), + ("ADBE Iris Wipe", "ec.transition.iriswipe"), +]; + /// AE match name of an effect id (falls back to the id). pub fn effect(id: &str) -> String { find(EFFECTS, id).map(str::to_string).unwrap_or_else(|| id.to_string()) } -/// Our effect id for an AE effect match name. +/// Our effect id for an AE effect match name (or a legacy one, see `LEGACY_EFFECTS`). pub fn effect_from_match(m: &str) -> Option<&'static str> { - EFFECTS.iter().find(|(_, b)| b.eq_ignore_ascii_case(m)).map(|(a, _)| *a) + EFFECTS + .iter() + .find(|(_, b)| b.eq_ignore_ascii_case(m)) + .map(|(a, _)| *a) + .or_else(|| LEGACY_EFFECTS.iter().find(|(b, _)| b.eq_ignore_ascii_case(m)).map(|(_, a)| *a)) +} + +/// The current match name for a legacy name a script may still use: a `LEGACY_EFFECTS` effect +/// name, one of its parameters (`ADBE Noise-0001` → `ADBE Noise2-0001`), or the light's Casts +/// Shadows under its earlier name. `None` when `name` is not a legacy name. +pub fn current_name(name: &str) -> Option { + if name == "ADBE Light Casts Shadows" { + return Some("ADBE Casts Shadows".into()); + } + let legacy = |m: &str| LEGACY_EFFECTS.iter().find(|(b, _)| b.eq_ignore_ascii_case(m)).map(|(_, id)| effect(id)); + if let Some(m) = legacy(name) { + return Some(m); + } + let (fx, n) = name.rsplit_once('-')?; + if n.len() != 4 || !n.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + legacy(fx).map(|m| format!("{m}-{n}")) } /// Our shape item kind (`layer.addShapeItem`) for an AE match name, our match id or a display @@ -573,6 +614,56 @@ pub fn node(chain: &[&Node]) -> String { mod tests { use super::*; + /// After Effects 26.2's `app.effects` (first-party match names and categories), #3113. + const AE_EFFECTS: &str = include_str!("../tests/fixtures/ae-effect-match-names.tsv"); + + fn ae_effects() -> Vec<(&'static str, &'static str)> { + AE_EFFECTS.lines().filter(|l| !l.starts_with('#') && !l.is_empty()).map(|l| l.split_once('\t').unwrap_or((l, ""))).collect() + } + + /// #3113: every effect match name we emit is one After Effects lists (case matters: its + /// `addProperty("ADBE Ellipse")` fails), and the current version, not a hidden obsolete one, + /// unless After Effects only has that one. + #[test] + fn effect_names_are_after_effects_names() { + let ae = ae_effects(); + // Obsolete in After Effects without a current replacement (Puppet is added by its tool). + let only_obsolete = ["ADBE Color Key", "ADBE Luma Key", "ADBE FreePin3"]; + for (id, m) in EFFECTS { + let Some((_, cat)) = ae.iter().find(|(n, _)| n == m) else { panic!("{id}: After Effects has no effect {m:?}") }; + assert!(!cat.contains("Obsolete") || only_obsolete.contains(m), "{id}: {m:?} is After Effects' obsolete version"); + } + assert_eq!(effect("ec.noise.noise"), "ADBE Noise2"); + assert_eq!(effect("ec.time.pixelmotionblur"), "ADBE OFMotionBlur"); + assert_eq!(effect("ec.generate.ellipse"), "ADBE ELLIPSE"); + assert_eq!(effect("ec.color.photofilter"), "ADBE PhotoFilterPS"); + } + + /// #3113: the names earlier versions emitted (and After Effects' obsolete ones) still resolve, + /// but none shadows a current name. + #[test] + fn legacy_effect_names_still_resolve() { + for (old, id) in LEGACY_EFFECTS { + assert_eq!(effect_from_match(old), Some(*id)); + assert!(!EFFECTS.iter().any(|(_, m)| m.eq_ignore_ascii_case(old)), "{old} is a current name"); + assert_eq!(current_name(old), Some(effect(id))); + } + assert_eq!(effect_from_match("ADBE Pixel Motion Blur"), Some("ec.time.pixelmotionblur")); + assert_eq!(current_name("ADBE Noise-0001").as_deref(), Some("ADBE Noise2-0001")); + assert_eq!(current_name("ADBE Light Casts Shadows").as_deref(), Some("ADBE Casts Shadows")); + assert_eq!(current_name("ADBE Noise2-0001"), None); + assert_eq!(current_name("ADBE Noise-01"), None); + assert_eq!(current_name("ADBE Gaussian Blur 2"), None); + } + + #[test] + fn light_casts_shadows_is_after_effects_name() { + let n = |m: &str| Node::from(effectcraft_project::PropGroup::new(1, m, m)); + let (light, mat, casts) = (n("lightOptions"), n("materialOptions"), n("castsShadows")); + assert_eq!(node(&[&light, &casts]), "ADBE Casts Shadows"); + assert_eq!(node(&[&mat, &casts]), "ADBE Casts Shadows"); + } + #[test] fn effect_names_round_trip() { for (id, m) in EFFECTS { diff --git a/crates/script/src/model.rs b/crates/script/src/model.rs index 258a6de2d..e662c1cdc 100644 --- a/crates/script/src/model.rs +++ b/crates/script/src/model.rs @@ -451,6 +451,9 @@ fn find_child<'a>(l: &'a Layer, g: &'a PropGroup, k: &str, depth: u8) -> Option< g.children .iter() .find(|n| chain_of(n) == k) + .or_else(|| matchnames::current_name(k).and_then(|m| g.children.iter().find(|n| chain_of(n) == m))) + // Match names that changed only in case (`ADBE Ellipse` is now `ADBE ELLIPSE`, #3113). + .or_else(|| g.children.iter().find(|n| chain_of(n).eq_ignore_ascii_case(k))) .or_else(|| g.children.iter().find(|n| n.name() == k)) .or_else(|| g.children.iter().find(|n| n.match_id() == k)) .or_else(|| g.children.iter().find(|n| n.name().eq_ignore_ascii_case(k))) diff --git a/crates/script/src/prelude.js b/crates/script/src/prelude.js index b9108b2a1..5adab6eec 100644 --- a/crates/script/src/prelude.js +++ b/crates/script/src/prelude.js @@ -26,7 +26,7 @@ function __err(msg) { } function __num(v, what) { var n = Number(v); - if (typeof v === "boolean" || isNaN(n)) throw __err((what || "value") + " must be a number"); + if (typeof v === "boolean" || Number.isNaN(n)) throw __err((what || "value") + " must be a number"); return n; } function __str(v) { @@ -43,11 +43,11 @@ if (typeof String.prototype.substr !== "function") { if (this === null || this === undefined) throw new TypeError("String.substr called on null or undefined"); var text = String(this), n = text.length; var from = Number(start); - if (isNaN(from)) from = 0; + if (Number.isNaN(from)) from = 0; // ToIntegerOrInfinity, then clamp positive or negative offsets. from = from < 0 ? Math.max(n + Math.ceil(from), 0) : Math.min(Math.floor(from), n); var count = length === undefined ? n - from : Number(length); - if (isNaN(count) || count <= 0) return ""; + if (Number.isNaN(count) || count <= 0) return ""; return text.slice(from, from + count); }, writable: true, configurable: true @@ -292,6 +292,34 @@ function Folder(path) { if (!(this instanceof Folder)) return new Folder(path); this.__path = path === undefined ? "" : __str(path); } + +// ECMAScript's legacy case canonicalisation (what a `/i` regular expression compares with): the +// upper case form when it is one code unit, and not an ASCII letter for a non-ASCII one. +function __canon(ch) { + var u = ch.toUpperCase(); + if (u.length !== 1) return ch; + if (ch.charCodeAt(0) >= 128 && u.charCodeAt(0) < 128) return ch; + return u; +} + +// A case-insensitive `*` / `?` file mask match in time bounded by mask × name length (a +// regular expression of `.*` runs backtracks combinatorially on overlapping wildcards). +function __globMatch(mask, name) { + // Wildcards run over the original name (lowercasing it can change its length: "İ" becomes + // two code units); literal characters compare one at a time, case-insensitively as `/i` does + // ("ς" and "σ" and "Σ" match each other). + var p = mask, s = name; + var i = 0, j = 0, star = -1, mark = 0; + while (j < s.length) { + if (i < p.length && (p[i] === "?" || p[i] === s[j] || __canon(p[i]) === __canon(s[j]))) { i++; j++; } + else if (i < p.length && p[i] === "*") { star = i++; mark = j; } + else if (star !== -1) { i = star + 1; j = ++mark; } + else return false; + } + while (i < p.length && p[i] === "*") i++; + return i === p.length; +} + Folder.prototype = { constructor: Folder, get fsName() { return this.__path; }, @@ -310,10 +338,7 @@ Folder.prototype = { var out = []; for (var i = 0; i < names.length; i++) { var n = names[i]; - if (typeof mask === "string" && mask !== "*") { - var re = new RegExp("^" + mask.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".") + "$", "i"); - if (!re.test(n.split(/[\/\\]/).pop())) continue; - } + if (typeof mask === "string" && mask !== "*" && !__globMatch(mask, n.split(/[\/\\]/).pop())) continue; var isDir = JSON.parse(__file("isDir", n)); var f = isDir ? new Folder(n) : new File(n); if (typeof mask === "function" && !mask(f)) continue; @@ -436,7 +461,7 @@ function __callable(o) { // 1-based collections with `[n]` access. var __coll = { get: function (t, k, r) { - if (typeof k === "string" && /^[0-9]+$/.test(k)) return t.__at(parseInt(k, 10)); + if (typeof k === "string" && /^[0-9]+$/.test(k)) return t.__at(Number.parseInt(k, 10)); return Reflect.get(t, k, r); }, }; @@ -867,6 +892,12 @@ Property.prototype.property = function () { return null; }; if (!idx) return null; return this.__layer.containingComp.layer(idx).__id; } + // A string parameter (a LUT or look file, a text field) takes the text, or a File's path (#3395). + // A hidden one (Mesh Warp's mesh) stays refused by the key setters too, as by setValue. + if (info.type === "string") { + if (info.hidden) throw __err("\"" + info.name + "\" can not be set"); + return __str(v); + } if (info.type === "enum") return __num(v) - 1; if (info.type === "bool") return typeof v === "boolean" ? v : __num(v) !== 0; if (info.type === "color") { @@ -1652,7 +1683,7 @@ CompItem.prototype.constructor = CompItem; P.saveFrameToPng = function (time, file) { var f = __str(file); if (!f) throw __err("saveFrameToPng: missing file"); - __file("write", f, ""); + __file("checkWrite", f); __call("comp.saveFrameAs", { comp: this.__id, path: f, time: __num(time, "time") }); }; P.openInEssentialGraphics = function () { __call("comp.openInEssentialGraphics", { comp: this.__id }); }; @@ -1662,8 +1693,8 @@ CompItem.prototype.constructor = CompItem; if (!/\.[A-Za-z0-9]+$/.test(f)) f += ".ectemplate"; if (!overwrite && JSON.parse(__file("exists", f)) === true) return false; if (this.__controllers().length === 0) return false; - // The file gate applies to templates too. - __file("write", f, ""); + // The file gate applies to templates too (checked without touching the file). + __file("checkWrite", f); __call("essential.exportTemplate", { comp: this.__id, path: f }); return true; }; diff --git a/crates/script/src/runtime.rs b/crates/script/src/runtime.rs index 2c18039e8..28e490158 100644 --- a/crates/script/src/runtime.rs +++ b/crates/script/src/runtime.rs @@ -30,6 +30,8 @@ pub struct Outcome { /// The script is waiting in a modal ScriptUI dialog's `show()` (it goes on when the dialog /// closes; see [`crate::dispatch_ui`]). pub waiting: bool, + /// The native frontend owns the session while this host waits for its render worker. + pub render_host: Option, } /// An uncaught script error. @@ -55,6 +57,9 @@ impl Outcome { if self.waiting { j["waiting"] = json!(true); } + if let Some(host) = self.render_host { + j["renderHost"] = json!(host); + } j } } @@ -74,13 +79,16 @@ pub(crate) struct Active { /// Running on a script-host thread: modal dialogs hand the session back to the caller /// through this link while they wait. pub(crate) link: Option, + /// Captured at invocation start: the frontend resets its opt-in when the caller returns. + pub(crate) yield_renders: bool, /// The files `$.evalFile` is evaluating, outermost first. pub(crate) loading: Vec, } impl Active { pub(crate) fn new(session: Session, name: &str, host: u32) -> Active { - Active { session, output: vec![], groups: vec![], name: name.to_string(), host, link: None, loading: vec![] } + let yield_renders = session.script_ui.yield_renders; + Active { session, output: vec![], groups: vec![], name: name.to_string(), host, link: None, yield_renders, loading: vec![] } } } @@ -130,6 +138,13 @@ fn native_exec(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult exec_on_keys(&mut a.session, &id, params, k), @@ -137,7 +152,10 @@ fn native_exec(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult Ok(js_str(&v.to_string())), + Ok(Ok(v)) => { + let v = if yield_render { crate::ui::wait_for_render(ctx, v).map_err(throw)? } else { v }; + Ok(js_str(&v.to_string())) + } Ok(Err(e)) | Err(e) => Err(throw(e)), } } @@ -409,6 +427,8 @@ fn native_file(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult check_access(s, &path, true).map(|_| json!(true)), "read" | "readBinary" => { let p = check_access(s, &path, false)?; let bytes = s.services.read_file(&p.to_string_lossy()).map_err(|e| format!("Unable to read {path}: {e}"))?; @@ -512,8 +532,33 @@ fn native_eval_file(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResul r } +/// Host hooks: code a script compiles at run time (`eval`, `new Function`, …) passes the same +/// nesting check as the script itself, since the parser recurses per level and a deep string +/// built at run time would overflow the stack. +struct Hooks; + +impl boa_engine::context::HostHooks for Hooks { + fn ensure_can_compile_strings( + &self, + _realm: boa_engine::realm::Realm, + parameters: &[JsString], + body: &JsString, + _direct: bool, + _context: &mut Context, + ) -> JsResult<()> { + let mut code: String = parameters.iter().map(|p| p.to_std_string_escaped()).collect::>().join(","); + // With no parameters (`eval`) the body is the source as it stands, so a leading `#!` line + // is still its first line; with parameters it sits inside a function, where it is no comment. + if !parameters.is_empty() { + code.push('\n'); + } + code.push_str(&body.to_std_string_escaped()); + check_nesting(&code).map_err(|e| JsNativeError::syntax().with_message(e).into()) + } +} + pub(crate) fn new_context() -> Result { - let mut ctx = Context::default(); + let mut ctx = boa_engine::context::ContextBuilder::new().host_hooks(std::rc::Rc::new(Hooks)).build().map_err(|e| e.to_string())?; let limits = ctx.runtime_limits_mut(); limits.set_loop_iteration_limit(200_000_000); limits.set_recursion_limit(2000); @@ -718,6 +763,10 @@ pub fn run(session: &mut Session, req: &ScriptRequest) -> Outcome { }; let Some(x) = expanded else { return run_expanded(session, req) }; let mut out = run_expanded(session, &ScriptRequest { code: &x.code, name: req.name, console: req.console }); + if let Some(host) = out.render_host { + crate::ui::keep_render_source_map(host, x); + return out; + } if let Some(e) = out.error.as_mut() { x.locate(e); } @@ -747,19 +796,129 @@ fn run_expanded(session: &mut Session, req: &ScriptRequest) -> Outcome { /// 8 MiB thread such as the Script Console's, so deeper scripts are rejected up front. pub const MAX_NESTING: usize = 96; -/// An error when `code` nests brackets deeper than [`MAX_NESTING`] (strings, template literals -/// and comments are skipped). +/// Skip template-literal text from `*i` (just past a backtick or an interpolation's `}`). Returns +/// true when it stopped past a `${` (code follows), false at the closing backtick or the end. +fn skip_template_text(b: &[u8], i: &mut usize) -> bool { + while let Some(&d) = b.get(*i) { + match d { + b'\\' => *i += 2, + b'`' => { + *i += 1; + return false; + } + b'$' if b.get(*i + 1) == Some(&b'{') => { + *i += 2; + return true; + } + _ => *i += 1, + } + } + false +} + +/// Whether a `/` after the last significant byte `prev` (at `at` in `b`) starts a regular +/// expression literal rather than dividing: after an operator, an opening bracket, a separator, +/// a keyword that takes an expression, or at the start. After a name, a number, a string or a +/// closing bracket it divides (a regular expression after `)` is the one case this misreads). +/// `after_dot`: the word ending at `at` follows a `.` (a property name, never a keyword); a `++` +/// or `--` before the `/` is a postfix update, so it divides. +fn regex_may_start(b: &[u8], prev: u8, at: usize, after_dot: bool) -> bool { + match prev { + 0 => true, + b'+' | b'-' if at > 0 && b.get(at - 1) == Some(&prev) => false, + b'(' | b',' | b'=' | b':' | b'[' | b'!' | b'&' | b'|' | b'?' | b'{' | b';' | b'+' | b'-' | b'*' | b'%' | b'<' | b'>' | b'~' | b'^' => true, + _ if after_dot => false, + c if c.is_ascii_alphanumeric() || c == b'_' || c == b'$' => { + let start = (0..=at).rev().find(|&k| !b.get(k).is_some_and(|d| d.is_ascii_alphanumeric() || *d == b'_' || *d == b'$')).map_or(0, |k| k + 1); + let word = b.get(start..=at).unwrap_or_default(); + [&b"return"[..], b"typeof", b"instanceof", b"in", b"of", b"new", b"delete", b"void", b"throw", b"case", b"do", b"else", b"yield", b"await"] + .contains(&word) + } + _ => false, + } +} + +/// Whether the `.` at `at` is a property access: not the decimal point of a number (`1.`, `12.`) +/// that ends there. A number written `1.5.x` has a fraction before the dot, so that dot accesses. +fn dot_is_property(b: &[u8], at: usize) -> bool { + let word = |d: u8| d.is_ascii_alphanumeric() || d == b'_' || d == b'$'; + let start = (0..at).rev().find(|&k| !b.get(k).is_some_and(|d| word(*d))).map_or(0, |k| k + 1); + let before = b.get(start..at).unwrap_or_default(); + let integer = !before.is_empty() && before.iter().all(u8::is_ascii_digit); + // `1.5.x`: digits that follow another `.` are a fraction. + !(integer && !(start > 0 && b.get(start - 1) == Some(&b'.'))) +} + +/// Skip a regular expression literal that starts at `b[*i]` (a `/`), to its closing `/` (flags +/// follow as ordinary letters). A `/` inside a class `[…]` or after a backslash does not end it, +/// and neither a quote nor a backtick inside it starts a string; a line break ends it. +fn skip_regex(b: &[u8], i: &mut usize) { + *i += 1; + let mut class = false; + while let Some(&d) = b.get(*i) { + match d { + b'\\' => *i += 1, + b'[' => class = true, + b']' => class = false, + b'/' if !class => return, + b'\n' => return, + _ => {} + } + *i += 1; + } +} + +/// An error when `code` nests brackets deeper than [`MAX_NESTING`] (strings, regular expression +/// literals, template literal text and comments are skipped; the code inside `${…}` +/// interpolations is checked). pub fn check_nesting(code: &str) -> Result<(), String> { let b = code.as_bytes(); let (mut i, mut depth, mut max) = (0usize, 0usize, 0usize); + // The last significant byte (not space or comment), and where it is. + let (mut prev, mut prev_at) = (0u8, 0usize); + // A `#!` line at the very start is a comment (Boa reads it so): its text is not scanned. + if b.starts_with(b"#!") { + i = b.iter().position(|d| *d == b'\n').unwrap_or(b.len()); + } + // Whether the word that ends at `prev_at` came right after a `.` token (comments and + // whitespace between them do not matter). + let mut word_after_dot = false; + // The bracket depth of each open `${`, to tell its closing `}` from an inner one. + let mut interpolations: Vec = vec![]; while let Some(&c) = b.get(i) { match c { + b'`' => { + i += 1; + if skip_template_text(b, &mut i) { + depth += 1; + max = max.max(depth); + interpolations.push(depth); + (prev, prev_at) = (b'{', i - 1); + } else { + (prev, prev_at) = (b'`', i.saturating_sub(1)); + } + continue; + } + b'}' if interpolations.last() == Some(&depth) => { + interpolations.pop(); + depth -= 1; + i += 1; + if skip_template_text(b, &mut i) { + depth += 1; + max = max.max(depth); + interpolations.push(depth); + (prev, prev_at) = (b'{', i - 1); + } else { + (prev, prev_at) = (b'`', i.saturating_sub(1)); + } + continue; + } b'(' | b'[' | b'{' => { depth += 1; max = max.max(depth); } b')' | b']' | b'}' => depth = depth.saturating_sub(1), - b'"' | b'\'' | b'`' => { + b'"' | b'\'' => { // Skip to the closing quote (escapes skip a byte). i += 1; while let Some(&d) = b.get(i) { @@ -775,16 +934,29 @@ pub fn check_nesting(code: &str) -> Result<(), String> { while b.get(i).is_some_and(|d| *d != b'\n') { i += 1; } + continue; } b'/' if b.get(i + 1) == Some(&b'*') => { i += 2; while i < b.len() && !(b.get(i) == Some(&b'*') && b.get(i + 1) == Some(&b'/')) { i += 1; } - i += 1; + i += 2; + continue; } + b'/' if regex_may_start(b, prev, prev_at, word_after_dot) => skip_regex(b, &mut i), _ => {} } + if !c.is_ascii_whitespace() { + let word = |d: u8| d.is_ascii_alphanumeric() || d == b'_' || d == b'$'; + // A word starts where the byte before it is not a word byte (white space and comments + // end a word too): it is a property name when a `.` that is not part of a number + // comes right before it. + if word(c) && (i == 0 || !b.get(i - 1).is_some_and(|d| word(*d))) { + word_after_dot = prev == b'.' && dot_is_property(b, prev_at); + } + (prev, prev_at) = (c, i); + } i += 1; } if max > MAX_NESTING { @@ -858,6 +1030,44 @@ mod nesting_tests { assert!(check_nesting(&("(".repeat(MAX_NESTING) + &")".repeat(MAX_NESTING))).is_ok()); } + #[test] + fn regular_expression_literals_are_skipped_not_read_as_strings_or_templates() { + let deep = |n: usize| format!("{}1{}", "(".repeat(n), ")".repeat(n)); + // A backtick, a quote or a slash inside a class in a regular expression opens nothing, so + // the deep expression after it is still counted. + for re in ["/`/", "/\"/", "/'/", "/[/]/", "/\\//"] { + assert!(check_nesting(&format!("`x${{ {re}.test('x') ? {} : 0 }}`", deep(5000))).is_err(), "{re} in an interpolation"); + assert!(check_nesting(&format!("x = {re}.test(y) ? {} : 0", deep(5000))).is_err(), "{re}"); + assert!(check_nesting(&format!("x = {re}.test(y) ? {} : 0", deep(10))).is_ok(), "{re} shallow"); + } + // Division is not a regular expression: what follows it is still scanned. + assert!(check_nesting(&format!("a = 4 / 2; b = {}", deep(5000))).is_err()); + assert!(check_nesting(&format!("a = (4) / 2 / 3; b = {}", deep(5000))).is_err()); + // After a keyword that takes an expression a slash starts a regular expression. + assert!(check_nesting(&format!("typeof /`/ ; {}", deep(5000))).is_err()); + // A postfix update or a property named like a keyword is followed by a division, not a + // regular expression (the deep brackets after it must still be counted). + for head in ["i++ /", "i-- /", "obj.in /", "obj . in /", "obj . /* c */ in /", "obj.\n typeof /", "a1.in /", "1.5.in /"] { + assert!(check_nesting(&format!("x = {head} {} / 2", deep(5000))).is_err(), "{head}"); + } + // A keyword after a property name is still a keyword (`obj.in in /re/`), and the dot of a + // number does not make the word after it a property (`1. in /re/`): the regular expression + // is skipped, so the backtick inside it opens nothing and the brackets after it count. + for head in ["obj.in in", "1. in", "12. typeof"] { + assert!(check_nesting(&format!("x = {head} /`/; y = {}", deep(5000))).is_err(), "{head}"); + } + } + + #[test] + fn template_interpolations_are_checked_but_template_text_is_not() { + let deep = |n: usize| format!("`a${{{}1{}}}b`", "(".repeat(n), ")".repeat(n)); + assert!(check_nesting(&deep(5000)).is_err()); + assert!(check_nesting(&deep(10)).is_ok()); + // Brackets in the literal text, and a nested template, are fine; depth carries across `}`. + assert!(check_nesting(&format!("`{} ${{ `x${{1+(2)}}y` }} {}`", "(".repeat(500), "{".repeat(500))).is_ok()); + assert!(check_nesting(&format!("`${{1}}${{{}2{}}}`", "[".repeat(MAX_NESTING), "]".repeat(MAX_NESTING))).is_err()); + } + /// A canonical drive path and a lexical one compare once the `\\?\` prefix is gone; a UNC /// share and a Unix path are left as they are. #[test] diff --git a/crates/script/src/scriptfile.rs b/crates/script/src/scriptfile.rs index 2b6afcfbe..c3179711b 100644 --- a/crates/script/src/scriptfile.rs +++ b/crates/script/src/scriptfile.rs @@ -56,6 +56,10 @@ pub(crate) fn read(s: &Session, path: &Path) -> Result { if std::fs::metadata(path).is_ok_and(|m| m.len() > MAX_FILE_BYTES as u64) { return Err(too_big()); } + // A pipe or device reports no size and may never end: only regular files are read. + if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) { + return Err(format!("Unable to read {}: not a regular file", path.display())); + } let bytes = s.services.read_file(&path.to_string_lossy()).map_err(|e| format!("Unable to read {}: {e}", path.display()))?; if bytes.len() > MAX_FILE_BYTES { return Err(too_big()); diff --git a/crates/script/src/scriptui.js b/crates/script/src/scriptui.js index ddfbc1f3e..9c5000962 100644 --- a/crates/script/src/scriptui.js +++ b/crates/script/src/scriptui.js @@ -750,7 +750,7 @@ function __uiMouseWanted(c, inherited) { function __uiMouseEvent(type, target, v) { var num = function (x, d) { x = Number(x); - return isFinite(x) ? x : d; + return Number.isFinite(x) ? x : d; }; var keys = { alt: !!v.altKey, control: !!v.ctrlKey, ctrl: !!v.ctrlKey, meta: !!v.metaKey, shift: !!v.shiftKey }; return { diff --git a/crates/script/src/socket.rs b/crates/script/src/socket.rs index c024fcad5..ff5d6d200 100644 --- a/crates/script/src/socket.rs +++ b/crates/script/src/socket.rs @@ -142,7 +142,7 @@ mod imp { /// Fill a stream's buffer until `done(buf)` or the timeout / end of stream. Fails only when /// the read deadline can't be set. - fn fill(s: &mut TcpStream, buf: &mut Vec, eof: &mut bool, limit: Duration, done: impl Fn(&[u8]) -> bool) -> std::io::Result<()> { + fn fill(s: &mut TcpStream, buf: &mut Vec, eof: &mut bool, limit: Duration, mut done: impl FnMut(&[u8]) -> bool) -> std::io::Result<()> { let end = Instant::now() + limit; let mut chunk = [0u8; 4096]; while !done(buf) && !*eof { @@ -322,7 +322,15 @@ mod imp { } } ("readln", Sock::Stream { s, buf, eof }) => { - if let Err(e) = fill(s, buf, eof, timeout(p), |b| b.contains(&b'\n')) { + // Only the bytes that arrived since the last look are searched: a peer + // sending no newline must not make every read rescan the whole buffer. + let mut seen = 0; + let newline = |b: &[u8]| { + let hit = b.get(seen..).is_some_and(|new| new.contains(&b'\n')); + seen = b.len(); + hit + }; + if let Err(e) = fill(s, buf, eof, timeout(p), newline) { return err(format!("cannot set the read timeout: {e}")); } let line: Vec = match buf.iter().position(|&c| c == b'\n') { diff --git a/crates/script/src/tasks.rs b/crates/script/src/tasks.rs index 563f3bbc0..8b5c0cd7a 100644 --- a/crates/script/src/tasks.rs +++ b/crates/script/src/tasks.rs @@ -208,7 +208,9 @@ pub(crate) fn run_tasks_at(session: &mut Session, now: Instant) -> J { if !running { #[cfg(not(target_arch = "wasm32"))] crate::ui::tick_threaded(session, now, &mut report); - crate::ui::tick_inline(session, now, &mut report); + if session.script_ui.render_host.is_none() { + crate::ui::tick_inline(session, now, &mut report); + } crate::ui::prune_task_hosts(session); } let errors: Vec = report.errors.iter().map(|e| json!({"message": e.message, "line": e.line, "column": e.column, "file": e.file})).collect(); diff --git a/crates/script/src/tests.rs b/crates/script/src/tests.rs index eefa017f0..800ccdde7 100644 --- a/crates/script/src/tests.rs +++ b/crates/script/src/tests.rs @@ -15,6 +15,8 @@ mod ease_presets; mod evalfile; mod include; mod panels; +#[cfg(not(target_arch = "wasm32"))] +mod render_wait; #[cfg(not(windows))] mod services; mod startup; @@ -139,6 +141,42 @@ fn fill_parameters_use_documented_match_names() { assert_eq!(o.result, json!("Color|All Masks|ADBE Fill-0007")); } +/// #3113: effects carry After Effects' match names (`ADBE Noise2`, `ADBE OFMotionBlur`); the +/// names earlier versions emitted still add and find the effect and its parameters. +#[test] +fn effects_use_after_effects_match_names_and_accept_legacy_ones() { + let mut s = session(); + let o = ok( + &mut s, + r#"var c = app.project.items.addComp("N", 100, 100, 1, 1, 12); var l = c.layers.addSolid([1,1,1], "S", 100, 100, 1); + var fx = l.property("ADBE Effect Parade"); + var a = fx.addProperty("ADBE Noise2"), b = fx.addProperty("ADBE Noise"), m = fx.addProperty("ADBE OFMotionBlur"); + var p = fx.addProperty("ADBE Pixel Motion Blur"); + [a.matchName, b.matchName, m.matchName, p.matchName, a.property("ADBE Noise2-0001").name, + fx.property("ADBE Noise").matchName, a.property("ADBE Noise-0001").name, fx.numProperties]"#, + ); + assert_eq!( + o.result, + json!(["ADBE Noise2", "ADBE Noise2", "ADBE OFMotionBlur", "ADBE OFMotionBlur", "Amount of Noise", "ADBE Noise2", "Amount of Noise", 4]) + ); +} + +/// #3113: names that changed only in case (`ADBE Ellipse` → `ADBE ELLIPSE`, `ADBE Grow Bounds` → +/// `ADBE GROW BOUNDS`) still find the effect and its parameters. +#[test] +fn match_names_that_changed_case_still_find_effects_and_parameters() { + let mut s = session(); + let o = ok( + &mut s, + r#"var c = app.project.items.addComp("E", 100, 100, 1, 1, 12); var l = c.layers.addSolid([1,1,1], "S", 100, 100, 1); + var fx = l.property("ADBE Effect Parade"); + var e = fx.addProperty("ADBE Ellipse"), g = fx.addProperty("ADBE Grow Bounds"); + [e.matchName, fx.property("ADBE Ellipse").matchName, e.property("ADBE Ellipse-0001").matchName, + g.matchName, fx.property("ADBE Grow Bounds").matchName, g.property("ADBE Grow Bounds-0001").matchName]"#, + ); + assert_eq!(o.result, json!(["ADBE ELLIPSE", "ADBE ELLIPSE", "ADBE ELLIPSE-0001", "ADBE GROW BOUNDS", "ADBE GROW BOUNDS", "ADBE GROW BOUNDS-0001"])); +} + #[test] fn stroke_parameters_use_after_effects_match_names() { // #1405: `ADBE Stroke-0002` is Stroke's Color in After Effects, not All Masks. @@ -662,6 +700,56 @@ fn save_frame_to_png_writes_behind_the_file_gate() { let _ = std::fs::remove_dir_all(&dir); } +/// A script that runs the export commands itself (`app.run`, `__exec`) meets the same file-write +/// preference as the wrappers; with the preference off nothing is created or replaced. +#[test] +fn export_commands_run_directly_by_a_script_respect_the_file_gate() { + let dir = std::env::temp_dir().join(format!("ec-direct-export-{}", std::process::id())); + // A leftover dir from an interrupted run (same pid) must not feed stale absence checks. + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let png = dir.join("frame.png"); + let tpl = dir.join("card.ectemplate"); + let kept = dir.join("kept.png"); + std::fs::write(&kept, b"original").unwrap(); + let mut s = session(); + s.execute("comp.new", json!({"name": "Card", "width": 64, "height": 64, "duration": 1})).unwrap(); + s.execute("layer.newText", json!({"text": "Hi"})).unwrap(); + ok(&mut s, "var c = app.project.activeItem; c.layer(1).property('ADBE Transform Group').property('ADBE Opacity').addToMotionGraphicsTemplate(c);"); + let q = |p: &std::path::Path| serde_json::to_string(&p.to_string_lossy()).unwrap(); + let comp = s.active_comp_id().unwrap().0; + for (code, target) in [ + (format!("app.run('comp.saveFrameAs', {{comp: {comp}, path: {}}})", q(&png)), &png), + (format!("__exec('comp.saveFrameAs', JSON.stringify({{comp: {comp}, path: {}}}))", q(&png)), &png), + (format!("app.run('essential.exportTemplate', {{comp: {comp}, path: {}}})", q(&tpl)), &tpl), + (format!("app.run('comp.saveFrameAs', {{comp: {comp}, path: {}}})", q(&kept)), &kept), + ] { + let o = run_code(&mut s, &code, "direct.jsx"); + let e = o.error.unwrap_or_else(|| panic!("`{code}` was not refused")); + assert!(e.message.contains("Allow Scripts to Write Files"), "{e:?}"); + if target == &kept { + assert_eq!(std::fs::read(&kept).unwrap(), b"original"); + } else { + assert!(!target.exists(), "{} was written", target.display()); + } + } + // The wrappers check the gate without touching the file: an existing one is left as it was. + let o = run_code(&mut s, &format!("app.project.activeItem.saveFrameToPng(0, new File({}))", q(&kept)), "wrap.jsx"); + assert!(o.error.is_some()); + assert_eq!(std::fs::read(&kept).unwrap(), b"original"); + let o = run_code(&mut s, &format!("app.project.activeItem.exportAsMotionGraphicsTemplate(true, {})", q(&tpl)), "wrap.jsx"); + assert!(o.error.is_some()); + assert!(!tpl.exists()); + // The user, from the UI, is not a script: the same command writes. + s.execute("comp.saveFrameAs", json!({"comp": comp, "path": png.to_string_lossy()})).unwrap(); + assert!(png.exists()); + // With the preference on, the script's direct call writes too. + s.prefs.scripting.allow_scripts_write_files = true; + ok(&mut s, &format!("app.run('essential.exportTemplate', {{comp: {comp}, path: {}}})", q(&tpl))); + assert!(std::fs::metadata(&tpl).unwrap().len() > 100); + let _ = std::fs::remove_dir_all(&dir); +} + /// #1246: with Warn User When Executing Files on, a script that asserts `confirmed` itself still /// gets the question; only the user's answer opens the file. #[test] @@ -1911,3 +1999,77 @@ fn setting_comp_width_and_height_leaves_the_layers_where_they_are() { let (_, c) = comp_named(&s, "w"); assert_eq!(layer(c, "s").props.prop("transform/position").unwrap().value, KV::Vec3([100.0, 100.0, 0.0])); } + +#[test] +fn a_hashbang_line_does_not_hide_deep_nesting_from_eval() { + // Boa reads a leading `#!` line of eval source as a comment, so the backtick on it opens no + // template: the brackets after it are counted and refused. + let mut s = session(); + let code = "var deep = new Array(5000).join('(') + '1' + new Array(5000).join(')'); var r; \ + try { eval('#! `\\n' + deep); r = 'ran'; } catch (e) { r = 'refused'; } r"; + assert_eq!(ok(&mut s, code).result.as_str(), Some("refused")); + assert!(crate::runtime::check_nesting(&format!("#! `\n{}1{}", "(".repeat(5000), ")".repeat(5000))).is_err()); + assert!(crate::runtime::check_nesting("#! `\n(1)").is_ok()); +} + +#[test] +fn code_compiled_at_run_time_passes_the_nesting_check() { + // `eval` and `new Function` of a string nested past the limit are refused with a catchable + // error instead of overflowing the parser's stack; shallow code still compiles. + let mut s = session(); + for call in ["eval(deep)", "new Function(deep)", "Function('a', deep)"] { + let code = format!( + "var deep = new Array(5000).join('(') + '1' + new Array(5000).join(')'); var r; try {{ {call}; r = 'ran'; }} catch (e) {{ r = 'refused'; }} r" + ); + assert_eq!(ok(&mut s, &code).result.as_str(), Some("refused"), "{call}"); + } + assert_eq!(ok(&mut s, "eval('1 + (2 * 3)') + new Function('return 4')()").result.as_f64(), Some(11.0)); +} + +#[test] +fn file_masks_match_without_backtracking() { + let mut s = session(); + let r = ok( + &mut s, + "[__globMatch('*.JSX', 'a.jsx'), __globMatch('a?c*', 'abcdef'), __globMatch('*a*b', 'xaxb'), __globMatch('*.png', 'a.jsx'), __globMatch('*a*a*a*a*a*a*a*a*a*a*a*b', new Array(60).join('a'))].join()", + ); + assert_eq!(r.result.as_str(), Some("true,true,true,false,false")); + // `?` still matches one character that lowercases to two. + let r = ok(&mut s, "[__globMatch('?.txt', '\\u0130.txt'), __globMatch('\\u0130*', '\\u0130x')].join()"); + assert_eq!(r.result.as_str(), Some("true,true")); + // Greek sigma matches in every case form, as the case-insensitive regular expression did. + let r = ok( + &mut s, + "[__globMatch('\\u03bf\\u03c2.txt', '\\u039f\\u03a3.txt'), __globMatch('\\u03a3*', '\\u03c2x'), __globMatch('k', '\\u212a'), __globMatch('a', 'b')].join()", + ); + assert_eq!(r.result.as_str(), Some("true,true,false,false")); +} + +/// #3395: setValue on a string effect parameter stores the text, or a File's path, as `prop.set` +/// does. Before, every string fell through to the number check ("value must be a number"). +/// Hidden string parameters (Mesh Warp's Distortion Mesh) stay refused, keys included. +#[test] +fn set_value_stores_a_string_parameter() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var c = app.project.items.addComp("Str", 64, 36, 1, 1, 24); + var l = c.layers.addSolid([1, 0, 0], "s", 64, 36, 1); + var fx = l.property("ADBE Effect Parade"); + var lut = fx.addProperty("Apply Color LUT").property("LUT"); + lut.setValue("/luts/look.cube"); + var fromString = lut.value; + lut.setValue(new File("/luts/other.cube")); + var mesh = fx.addProperty("Mesh Warp").property("Distortion Mesh"); + function attempt(f) { try { f(); return "no error"; } catch (e) { return e.message; } } + var hidden = attempt(function () { mesh.setValue("x"); }); + var keyed = attempt(function () { mesh.setValueAtTime(0, "x"); }); + [lut.propertyValueType === PropertyValueType.CUSTOM_VALUE, fromString, lut.value, hidden, keyed, mesh.numKeys] + "#, + ); + let refused = "\"Distortion Mesh\" can not be set"; + assert_eq!(o.result, json!([true, "/luts/look.cube", "/luts/other.cube", refused, refused, 0])); + let (_, c) = comp_named(&s, "Str"); + assert_eq!(layer(c, "s").props.prop("effects/#1/lut").unwrap().value, KV::Str("/luts/other.cube".into())); +} diff --git a/crates/script/src/tests/ease_presets.rs b/crates/script/src/tests/ease_presets.rs index f075250b2..3d1f95f31 100644 --- a/crates/script/src/tests/ease_presets.rs +++ b/crates/script/src/tests/ease_presets.rs @@ -90,7 +90,7 @@ fn per_key_methods_keep_the_key_selection_and_report_eases_as_they_play() { let r = ok( &mut s, r#"var comp = app.project.activeItem, p = comp.layer(1).transform.opacity; - // A linear side reports the speed it plays at (33.3 % influence). + // A linear side reports the speed it plays at (16.67 % influence, as After Effects). var lin = p.keyInTemporalEase(3)[0]; p.setTemporalEaseAtKey(2, [new KeyframeEase(0, 50)], [new KeyframeEase(0, 75)]); p.setInterpolationTypeAtKey(3, KeyframeInterpolationType.HOLD, KeyframeInterpolationType.HOLD); @@ -98,7 +98,7 @@ fn per_key_methods_keep_the_key_selection_and_report_eases_as_they_play() { var sel = comp.selectedProperties; [lin.speed, lin.influence, p.selectedKeys, sel.length, sel.length ? sel[0].name : ""]"#, ); - assert!(close(r[0].as_f64().unwrap(), -100.0, 1e-9) && close(r[1].as_f64().unwrap(), 100.0 / 3.0, 1e-9), "{r}"); + assert!(close(r[0].as_f64().unwrap(), -100.0, 1e-9) && close(r[1].as_f64().unwrap(), 100.0 / 6.0, 1e-9), "{r}"); assert_eq!(r[2], json!([1, 3]), "the selection is the user's"); assert_eq!((r[3].clone(), r[4].clone()), (json!(1), json!("Opacity"))); assert_eq!(s.state.selected_keys, before); diff --git a/crates/script/src/tests/render_wait.rs b/crates/script/src/tests/render_wait.rs new file mode 100644 index 000000000..591bd211a --- /dev/null +++ b/crates/script/src/tests/render_wait.rs @@ -0,0 +1,243 @@ +//! #3289: a native frontend may service the event loop while a script waits for rendering. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use effectcraft_engine::project::render_queue::OutputFormat; +use effectcraft_engine::{ExportJob, ExportResult, Exporter, Session}; +use serde_json::{Value, json}; + +/// A slow exporter without expensive frames. A bounded wait makes the old blocking path +/// fail the assertions instead of hanging the test process. +struct Gate { + entered: AtomicUsize, + permits: AtomicUsize, + failed: bool, +} + +impl Exporter for Gate { + fn formats(&self) -> Vec { + vec![OutputFormat::H264] + } + fn export(&self, job: &ExportJob, progress: &mut dyn FnMut(u64, u64) -> bool) -> Result { + let call = self.entered.fetch_add(1, Ordering::SeqCst) + 1; + let end = Instant::now() + Duration::from_secs(2); + while self.permits.load(Ordering::SeqCst) < call { + if !progress(0, 1) { + return Err(effectcraft_engine::render_queue::CANCELLED.into()); + } + if Instant::now() > end { + return Err("test exporter timed out waiting for the frontend".into()); + } + std::thread::sleep(Duration::from_millis(1)); + } + if self.failed { Err("test encoder failure".into()) } else { Ok(ExportResult { path: job.path.into(), frames: 1, ..Default::default() }) } + } +} + +fn session(permits: usize, failed: bool) -> (Session, Arc) { + let gate = Arc::new(Gate { entered: AtomicUsize::new(0), permits: AtomicUsize::new(permits), failed }); + let mut s = super::session(); + s.exporter = Some(gate.clone()); + s.execute("comp.new", json!({"name": "Render", "width": 16, "height": 16, "duration": 1})).unwrap(); + let path = std::env::temp_dir().join(format!("ec-script-render-{}.mp4", std::process::id())); + s.execute("renderQueue.add", json!({"output": path.to_string_lossy()})).unwrap(); + s.prefs.auto_save.enabled = false; + (s, gate) +} + +fn finish(s: &mut Session) -> Value { + let end = Instant::now() + Duration::from_secs(3); + loop { + if let Some(result) = crate::ui::poll_render_wait(s) { + return result; + } + assert!(Instant::now() < end, "script did not resume"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn render_yields_without_finishing_the_script_or_its_undo_group() { + let (mut s, gate) = session(0, false); + s.script_ui.yield_renders = true; + let before = s.history.undo.len(); + let out = crate::run_code( + &mut s, + "app.beginUndoGroup('Render transaction'); app.project.activeItem.layers.addNull().name = 'Before'; $.writeln('before'); app.project.renderQueue.render(); app.project.activeItem.layers.addNull().name = 'After'; $.writeln('after'); app.endUndoGroup(); [42, app.project.renderQueue.rendering];", + "render.jsx", + ); + assert!(out.error.is_none(), "{out:?}"); + assert!(out.render_host.is_some(), "blocking render returned instead of yielding: {out:?}"); + assert!(!out.waiting, "a render suspension is not a modal dialog"); + assert!(out.output.is_empty(), "output belongs to the eventual reply"); + assert_eq!(s.active_comp().unwrap().layers.len(), 1, "the continuation has not run"); + assert!(crate::ui::poll_render_wait(&mut s).is_none()); + assert!(!s.undo(), "undo cannot discard the suspended script's live edits"); + assert!(s.execute("engine.batch", json!({"steps": [{"command": "layer.newNull"}]})).is_err()); + assert!(s.execute("jobs.list", json!({})).is_err(), "status polling must not apply unrelated jobs"); + // The frontend resets the invocation-only opt-in after script.run returns. + s.script_ui.yield_renders = false; + gate.permits.store(1, Ordering::SeqCst); + let done = finish(&mut s); + assert_eq!(done["ok"], true, "{done}"); + assert_eq!(done["result"], json!([42, false])); + assert_eq!(done["output"], "before\nafter"); + assert_eq!(s.project.render_queue[0].status.label(), "Done"); + assert_eq!(s.history.undo.len(), before + 1, "one undo group spans the render"); + assert_eq!(s.history.undo.last().unwrap().0, "Render transaction"); + assert!(s.script_ui.render_host.is_none()); + s.undo(); + assert!(s.active_comp().unwrap().layers.is_empty()); +} + +#[test] +fn a_second_render_keeps_the_same_script_pending() { + let (mut s, gate) = session(0, false); + s.script_ui.yield_renders = true; + let out = crate::run_code( + &mut s, + "app.project.renderQueue.render(); app.project.renderQueue.item(1).render = true; app.project.renderQueue.render(); 17;", + "twice.jsx", + ); + let host = out.render_host.unwrap(); + s.script_ui.yield_renders = false; + gate.permits.store(1, Ordering::SeqCst); + let end = Instant::now() + Duration::from_secs(3); + while gate.entered.load(Ordering::SeqCst) < 2 { + assert!(crate::ui::poll_render_wait(&mut s).is_none(), "no premature reply after the first render"); + assert!(Instant::now() < end); + std::thread::sleep(Duration::from_millis(1)); + } + assert_eq!(s.script_ui.render_host, Some(host)); + gate.permits.store(2, Ordering::SeqCst); + assert_eq!(finish(&mut s)["result"], 17); +} + +#[test] +fn cancellation_and_encoder_failure_resume_with_terminal_statuses() { + for failed in [false, true] { + let (mut s, gate) = session(0, failed); + s.script_ui.yield_renders = true; + let out = crate::run_code(&mut s, "app.project.renderQueue.render(); [9, app.project.renderQueue.rendering];", "stopped.jsx"); + assert!(out.render_host.is_some()); + if failed { + gate.permits.store(1, Ordering::SeqCst); + } else { + s.stop_render(); + } + let done = finish(&mut s); + assert_eq!(done["ok"], true, "the synchronous command reports status, not a thrown script error: {done}"); + assert_eq!(done["result"], json!([9, false])); + assert_ne!(s.project.render_queue[0].status.label(), "Done"); + } +} + +#[test] +fn headless_scripts_still_wait_and_start_errors_do_not_suspend() { + let (mut s, _) = session(1, false); + let out = crate::run_code(&mut s, "app.project.renderQueue.render(); [7, app.project.renderQueue.rendering];", "headless.jsx"); + assert!(out.error.is_none(), "{out:?}"); + assert_eq!(out.result, json!([7, false])); + assert!(out.render_host.is_none()); + assert_eq!(s.project.render_queue[0].status.label(), "Done"); + s.script_ui.yield_renders = true; + let out = crate::run_code(&mut s, "app.project.renderQueue.render();", "empty.jsx"); + assert!(out.error.is_some()); + assert!(out.render_host.is_none()); + assert!(s.script_ui.render_host.is_none()); +} + +#[test] +fn retained_palette_callbacks_can_yield_after_the_original_control_invocation() { + let (mut s, gate) = session(0, false); + s.script_ui.yield_renders = true; + let out = crate::run_code( + &mut s, + "var w = new Window('palette', 'Render'); var b = w.add('button', undefined, 'Go', {name:'go'}); b.onClick = function () { app.project.renderQueue.render(); $.writeln('resumed'); }; w.show();", + "palette-render.jsx", + ); + assert!(out.error.is_none(), "{out:?}"); + s.script_ui.yield_renders = false; + let result = s.execute("scriptui.click", json!({"widget": "go"})).unwrap(); + assert!(result["renderHost"].is_number(), "{result}"); + gate.permits.store(1, Ordering::SeqCst); + assert_eq!(finish(&mut s)["output"], "resumed"); + let window = s.script_ui.windows[0].id; + s.execute("scriptui.close", json!({"window": window})).unwrap(); +} + +#[test] +fn post_render_actions_complete_before_the_script_resumes() { + use effectcraft_engine::project::{Footage, FootageKind}; + struct Probe; + impl effectcraft_engine::Importer for Probe { + fn probe(&self, path: &str) -> Result { + Ok(Footage { path: path.into(), kind: FootageKind::Still, width: 16, height: 16, has_video: true, ..Default::default() }) + } + } + for action in ["import", "setProxy"] { + let (mut s, gate) = session(0, false); + s.importer = Some(Arc::new(Probe)); + let id = s.project.render_queue[0].id; + s.execute("renderQueue.setOutputModule", json!({"item": id, "postRenderAction": action})).unwrap(); + let before = s.project.items.len(); + let comp = s.active_comp_id().unwrap(); + s.script_ui.yield_renders = true; + let out = crate::run_code(&mut s, "app.project.renderQueue.render(); 29;", "post-render.jsx"); + assert!(out.render_host.is_some(), "{out:?}"); + gate.permits.store(1, Ordering::SeqCst); + // A query must not consume updates while the edit guard is still active. + let end = Instant::now() + Duration::from_secs(3); + while s.is_rendering() { + assert!(Instant::now() < end); + std::thread::sleep(Duration::from_millis(1)); + } + s.execute("renderQueue.list", json!({})).unwrap(); + assert_eq!(s.project.items.len(), before); + assert_eq!(finish(&mut s)["result"], 29); + if action == "import" { + assert_eq!(s.project.items.len(), before + 1); + } else { + assert!(s.project.item(comp).unwrap().proxy.is_some()); + } + } +} + +#[test] +fn deferred_errors_keep_their_included_source_location() { + let (mut s, gate) = session(0, false); + let dir = std::env::temp_dir().join(format!("ec-render-include-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("render.jsx"), "app.project.renderQueue.render();\nmissingAfterRender();").unwrap(); + std::fs::write(dir.join("main.jsx"), "#include 'render.jsx'").unwrap(); + s.script_ui.yield_renders = true; + let out = crate::run_code(&mut s, "#include 'render.jsx'", &dir.join("main.jsx").to_string_lossy()); + assert!(out.render_host.is_some(), "{out:?}"); + gate.permits.store(1, Ordering::SeqCst); + let done = finish(&mut s); + assert_eq!(done["ok"], false); + assert_eq!(done["error"]["line"], 2); + assert!(done["error"]["file"].as_str().unwrap().ends_with("render.jsx"), "{done}"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn included_error_mapping_survives_a_modal_yield_after_rendering() { + let (mut s, gate) = session(0, false); + let dir = std::env::temp_dir().join(format!("ec-render-modal-include-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("render.jsx"), "app.project.renderQueue.render();\nvar d = new Window('dialog', 'Continue'); d.add('button', undefined, 'OK', {name:'ok'}); d.show();\nmissingAfterModal();").unwrap(); + std::fs::write(dir.join("main.jsx"), "#include 'render.jsx'").unwrap(); + s.script_ui.yield_renders = true; + let out = crate::run_code(&mut s, "#include 'render.jsx'", &dir.join("main.jsx").to_string_lossy()); + assert!(out.render_host.is_some(), "{out:?}"); + gate.permits.store(1, Ordering::SeqCst); + assert_eq!(finish(&mut s)["waiting"], true); + let done = s.execute("scriptui.click", json!({"widget": "ok"})).unwrap(); + assert_eq!(done["ok"], false); + assert_eq!(done["error"]["line"], 3); + assert!(done["error"]["file"].as_str().unwrap().ends_with("render.jsx"), "{done}"); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/script/src/tests/ui_more.rs b/crates/script/src/tests/ui_more.rs index 483d686ef..c15aee0ae 100644 --- a/crates/script/src/tests/ui_more.rs +++ b/crates/script/src/tests/ui_more.rs @@ -231,6 +231,7 @@ fn position_now(s: &Session, layer: u64) -> [f64; 2] { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let v = ctx.value(l, l.props.prop("transform/position").unwrap()).components(); [v[0], v[1]] diff --git a/crates/script/src/ui.rs b/crates/script/src/ui.rs index ab6f69846..ecf4cd28b 100644 --- a/crates/script/src/ui.rs +++ b/crates/script/src/ui.rs @@ -3,7 +3,8 @@ //! //! * **Script files** (native builds) run on a *script-host thread*. The caller's session moves //! to that thread while JavaScript runs and comes back whenever the script stops: at the end, -//! or while a modal dialog waits in `show()`. Each [`ScriptUiEvent`] moves the session there +//! while a modal dialog waits in `show()`, or while an opted-in frontend waits for rendering. +//! Each [`ScriptUiEvent`] moves the session there //! again, runs the handler, and brings it back with the windows' new state. The host ends //! when its last window closes. Only one side holds the session at a time, so nothing runs //! concurrently and every edit is still an ordinary undoable engine command. @@ -137,6 +138,8 @@ pub(crate) enum ToHost { /// script-host threads). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] Tick(Session, Instant), + /// Resume the suspended native render call, never a callback or scheduled task. + ResumeRender(Session), } impl ToHost { @@ -145,7 +148,7 @@ impl ToHost { match self { #[cfg(not(target_arch = "wasm32"))] ToHost::Start(s) => s, - ToHost::Event(s, _) | ToHost::Tick(s, _) => s, + ToHost::Event(s, _) | ToHost::Tick(s, _) | ToHost::ResumeRender(s) => s, } } } @@ -159,6 +162,7 @@ pub(crate) struct FromHost { done: bool, /// When its next scheduled task is due. next_due: Option, + render_wait: bool, } /// The host thread's end of the hand-off. @@ -177,6 +181,8 @@ struct HostEnd { /// [`effectcraft_engine::scriptui::ScriptUi::project_epoch`] when the host last ran. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] epoch: u64, + /// Retained across render yields so a later error still names its included source file. + source_map: Option, } fn hosts() -> &'static std::sync::Mutex> { @@ -195,6 +201,7 @@ enum Wake { Event(ScriptUiEvent), #[cfg_attr(target_arch = "wasm32", allow(dead_code))] Tick(Instant), + Render, } /// On the host thread: hand the session (with the windows' state and what the script printed) @@ -206,18 +213,20 @@ fn yield_wait(outcome: crate::Outcome, windows: Vec, done: bool) - match yield_wake(out, windows.clone(), done, None)? { Wake::Event(ev) => return Some(ev), Wake::Tick(_) => out = crate::Outcome { waiting: true, ..Default::default() }, + Wake::Render => return None, } } } /// [`yield_wait`] that also wakes for the scheduled tasks due at `next_due`. fn yield_wake(outcome: crate::Outcome, windows: Vec, done: bool, next_due: Option) -> Option { + let render_wait = outcome.render_host.is_some(); let (session, link, name) = ACTIVE.with(|a| { let mut a = a.borrow_mut(); let a = a.as_mut()?; Some((std::mem::take(&mut a.session), a.link.take()?, a.name.clone())) })?; - if link.tx.send(FromHost { session, outcome, windows, name, done, next_due }).is_err() { + if link.tx.send(FromHost { session, outcome, windows, name, done, next_due, render_wait }).is_err() { return None; } if done { @@ -226,6 +235,7 @@ fn yield_wake(outcome: crate::Outcome, windows: Vec, done: bool, n let (s, wake) = match link.rx.recv() { Ok(ToHost::Event(s, ev)) => (s, Wake::Event(ev)), Ok(ToHost::Tick(s, now)) => (s, Wake::Tick(now)), + Ok(ToHost::ResumeRender(s)) => (s, Wake::Render), _ => return None, }; ACTIVE.with(|a| { @@ -269,8 +279,9 @@ fn host_main(host: u32, name: String, code: String, link: Link) { } Some(Wake::Tick(now)) => { let (ran, error) = crate::tasks::run_due(&mut ctx, host, now); - out = crate::Outcome { result: json!(ran), output: settle(), error, waiting: false }; + out = crate::Outcome { result: json!(ran), output: settle(), error, ..Default::default() }; } + Some(Wake::Render) => break, None => break, } } @@ -283,15 +294,30 @@ fn host_main(host: u32, name: String, code: String, link: Link) { { let message = if body.is_err() { "the script engine stopped unexpectedly" } else { "the script ended" }; let out = crate::Outcome { error: Some(ScriptError { message: message.into(), file, ..Default::default() }), ..Default::default() }; - let _ = link.tx.send(FromHost { session: std::mem::take(&mut a.session), outcome: out, windows: vec![], name, done: true, next_due: None }); + let _ = link.tx.send(FromHost { + session: std::mem::take(&mut a.session), + outcome: out, + windows: vec![], + name, + done: true, + next_due: None, + render_wait: false, + }); } } /// Wait for the host to hand the session back; keep its link while it has windows open. fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome { match end.rx.recv() { - Ok(FromHost { session: s, outcome, windows, name, done, next_due }) => { + Ok(FromHost { session: s, mut outcome, windows, name, done, next_due, render_wait }) => { *session = s; + session.script_ui.render_host = render_wait.then_some(host); + if !render_wait + && let Some(map) = &end.source_map + && let Some(error) = &mut outcome.error + { + map.locate(error); + } publish(session, host, &name, windows); if done { session.script_ui.windows.retain(|w| w.host != host); @@ -324,7 +350,61 @@ pub(crate) fn run_threaded(session: &mut Session, req: &effectcraft_engine::Scri *session = msg.into_session(); return crate::Outcome { error: Some(ScriptError { message: "the script host did not start".into(), ..Default::default() }), ..Default::default() }; } - receive(session, host, HostEnd { tx: to_tx, rx: from_rx, next_due: None, epoch: 0 }) + receive(session, host, HostEnd { tx: to_tx, rx: from_rx, next_due: None, epoch: 0, source_map: None }) +} + +/// Suspend only the JavaScript stack, not the window's event loop (#3289). Keep the output +/// and open undo groups in `Active`: settling here would split the script's undo transaction. +pub(crate) fn wait_for_render(ctx: &mut Context, mut result: J) -> Result { + let host = with_active(|a| Ok(a.host))?; + let windows = snapshot(ctx); + let out = crate::Outcome { render_host: Some(host), ..Default::default() }; + if !matches!(yield_wake(out, windows, false, None), Some(Wake::Render)) { + return Err("the frontend stopped waiting for the script's render".into()); + } + with_active(|a| { + let list = a.session.execute_for_script("renderQueue.list", json!({})).map_err(|e| e.to_string())?; + let ids: Vec = result["items"].as_array().into_iter().flatten().map(|i| i["id"].clone()).collect(); + result["items"] = json!(list["items"].as_array().into_iter().flatten().filter(|i| ids.contains(&i["id"])).collect::>()); + result["rendering"] = list["rendering"].clone(); + Ok(result) + }) +} + +pub(crate) fn keep_render_source_map(host: u32, map: crate::include::Expanded) { + if let Ok(mut h) = hosts().lock() + && let Some(end) = h.get_mut(&host) + { + end.source_map = Some(map); + } +} + +/// Called by the native frontend while its normal editing/callback tick is paused. Polling +/// applies terminal statuses and post-render actions before the suspended JS call returns. +pub(crate) fn poll_render_wait(session: &mut Session) -> Option { + let host = session.script_ui.render_host?; + // Only this completion boundary may apply the render's own import/proxy undo steps. + session.script_ui.render_host = None; + session.poll_render(); + if session.is_rendering() { + session.script_ui.render_host = Some(host); + return None; + } + session.script_ui.render_host = None; + let fail = |message: &str| crate::Outcome { error: Some(ScriptError { message: message.into(), ..Default::default() }), ..Default::default() }.to_json(); + let Some(end) = hosts().lock().ok().and_then(|mut h| h.remove(&host)) else { + return Some(fail("the script host stopped while rendering")); + }; + if end.epoch != session.script_ui.project_epoch { + return Some(fail("the project changed while the script was rendering")); + } + if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::ResumeRender(std::mem::take(session))) { + *session = msg.into_session(); + return Some(fail("the script host stopped while rendering")); + } + let out = receive(session, host, end); + // A second render in this invocation keeps the original control reply pending. + out.render_host.is_none().then(|| out.to_json()) } /// Record the windows a host published (named after the script that made them). @@ -429,6 +509,9 @@ pub(crate) fn tick_threaded(session: &mut Session, now: Instant, report: &mut cr } drop(stale); for host in due { + if session.script_ui.render_host.is_some() { + break; + } let Some(end) = hosts().lock().ok().and_then(|mut h| h.remove(&host)) else { continue }; if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::Tick(std::mem::take(session), now)) { *session = msg.into_session(); @@ -490,7 +573,7 @@ fn tick_inline_host(session: &mut Session, host: u32, name: &str, now: Instant) drop(guard); crate::tasks::set_epoch(host, session.script_ui.project_epoch); publish(session, host, name, windows); - crate::Outcome { result: json!(ran), output, error, waiting: false } + crate::Outcome { result: json!(ran), output, error, ..Default::default() } } /// Forget the session's task hosts that have ended (inline ones: that have no tasks left). diff --git a/crates/script/tests/fixtures/ae-effect-match-names.tsv b/crates/script/tests/fixtures/ae-effect-match-names.tsv new file mode 100644 index 000000000..341d82541 --- /dev/null +++ b/crates/script/tests/fixtures/ae-effect-match-names.tsv @@ -0,0 +1,343 @@ +# After Effects 26.2 app.effects: match namecategory, first-party names only (ADBE, APC, VISINF). +# Names only, read back from the running application (#3113). Categories "Obsolete"/"_Obsolete" are hidden legacy versions. "-" = no category. +ADBE 3D Glasses _Obsolete +ADBE 3D Glasses2 Perspective +ADBE 3D Tracker Perspective +ADBE 4ColorGradient Generate +ADBE AIF Perlin Noise 3D Noise & Grain +ADBE ATG Extract Keying +ADBE AUX CHANNEL EXTRACT 3D Channel +ADBE Alpha Levels2 _Obsolete +ADBE Alpha Levels3 _Obsolete +ADBE Angle Control Expression Controls +ADBE Apply Color LUT _Obsolete +ADBE Apply Color LUT2 Utility +ADBE Arithmetic Channel +ADBE Aud BT Audio +ADBE Aud Compressor Audio +ADBE Aud Delay Audio +ADBE Aud Distortion Audio +ADBE Aud Gate Audio +ADBE Aud HiLo Audio +ADBE Aud Modulator Audio +ADBE Aud Reverb Audio +ADBE Aud Reverse Audio +ADBE Aud Stereo Mixer Audio +ADBE Aud Tone Audio +ADBE AudSpect Generate +ADBE AudWave Generate +ADBE Aud_Flange Audio +ADBE AutoColor Color Correction +ADBE AutoContrast Color Correction +ADBE AutoLevels Color Correction +ADBE BEZMESH Distort +ADBE Basic 3D Obsolete +ADBE Basic Text2 Obsolete +ADBE Bevel Alpha Perspective +ADBE Bevel Edges Perspective +ADBE Bilateral Blur & Sharpen +ADBE Black&White Color Correction +ADBE Blend Channel +ADBE Block Dissolve Transition +ADBE Box Blur _Obsolete +ADBE Box Blur2 Blur & Sharpen +ADBE Brightness & Contrast _Obsolete +ADBE Brightness & Contrast 2 Color Correction +ADBE Broadcast Colors Color Correction +ADBE Brush Strokes Stylize +ADBE Bulge Distort +ADBE CHANNEL MIXER Color Correction +ADBE CM Animated Shape 2 - +ADBE CM Animated Shape 3 - +ADBE CM Animated Shape Control - +ADBE CM AutoscrollHorizontal - +ADBE CM AutoscrollVertical - +ADBE CM CornerReveal - +ADBE CM CrackedTiles - +ADBE CM CropEdges - +ADBE CM DissolveUnmelt - +ADBE CM FadeInOutFrames - +ADBE CM FadeInOutmsec - +ADBE CM FlyToInset - +ADBE CM GridWipe - +ADBE CM InsetVideoFramed - +ADBE CM InsetVideoTorn - +ADBE CM LightLeaksMarkers - +ADBE CM LightLeaksRandom - +ADBE CM MoodLightAmorph - +ADBE CM MoodLightDigital - +ADBE CM MoodLightStreaks - +ADBE CM OpacityFlashMarkers - +ADBE CM OpacityFlashRandom - +ADBE CM ScaleBounceMarkers - +ADBE CM ScaleBounceRandom - +ADBE CM SlideVariable - +ADBE CM Spin - +ADBE CM Throw - +ADBE CM TransCard - +ADBE CM TransComplete - +ADBE CM TransCorner - +ADBE CM TransDirection - +ADBE CM TransDissolve - +ADBE CM TransFade - +ADBE CM TransFadeMask - +ADBE CM TransIris - +ADBE CM TransRadial - +ADBE CM TransSlide - +ADBE CM TransStretch - +ADBE CM TransWipe - +ADBE CM TransWipeFeath - +ADBE CM WiggleGelatin - +ADBE CM WigglePosition - +ADBE CM WiggleRotation - +ADBE CM WiggleScale - +ADBE CM WiggleShear - +ADBE CM Wigglerama - +ADBE CM Zoom2DSpin - +ADBE CM Zoom3DTumble - +ADBE CM ZoomBubble - +ADBE CM ZoomSpiral - +ADBE CM ZoomWobble - +ADBE Calculations Channel +ADBE Camera Lens Blur Blur & Sharpen +ADBE CameraShakeDeblur Blur & Sharpen +ADBE Cartoonify Stylize +ADBE Cell Pattern Generate +ADBE Change Color Color Correction +ADBE Change To Color Color Correction +ADBE Channel Blur Blur & Sharpen +ADBE Channel Combiner Channel +ADBE Checkbox Control Expression Controls +ADBE Checkerboard Generate +ADBE Cineon Converter _Obsolete +ADBE Cineon Converter2 Utility +ADBE Circle Generate +ADBE Color Balance _Obsolete +ADBE Color Balance (HLS) Color Correction +ADBE Color Balance 2 Color Correction +ADBE Color Control Expression Controls +ADBE Color Difference Key Keying +ADBE Color Emboss Stylize +ADBE Color Key Obsolete +ADBE Color Link Color Correction +ADBE Color Range Keying +ADBE Color Swirl - +ADBE Compander Utility +ADBE Compound Arithmetic Channel +ADBE Compound Blur Blur & Sharpen +ADBE Corner Pin Distort +ADBE CurvesCustom Color Correction +ADBE DE Bounce - +ADBE DE Bounce At Marker - +ADBE DE Bounce On Beat - +ADBE DE Bounce Random - +ADBE DE Follow - +ADBE DE Jiggle - +ADBE DE Jiggle At Marker - +ADBE DE Jiggle On Beat - +ADBE DE Jiggle Random - +ADBE DE Opacity Pulse - +ADBE DE Opacity Pulse At Marker - +ADBE DE Opacity Pulse On Beat - +ADBE DE Opacity Pulse Random - +ADBE DE Orbit - +ADBE DE Orbit 3D - +ADBE DE Oscillate - +ADBE DE Oscillate At Marker - +ADBE DE Oscillate On Beat - +ADBE DE Oscillate Random - +ADBE DE Pendulum - +ADBE DE Pendulum At Marker - +ADBE DE Pendulum On Beat - +ADBE DE Pendulum Random - +ADBE DE Pulse - +ADBE DE Pulse At Marker - +ADBE DE Pulse On Beat - +ADBE DE Pulse Random - +ADBE DE Random Fill Color - +ADBE DE Random Motion - +ADBE DE Random Motion 1D - +ADBE DE Random Opacity - +ADBE DE Random Rotation - +ADBE DE Random Rotation 3D - +ADBE DE Random Scale - +ADBE DE Swarm - +ADBE DE Wobble Bounce - +ADBE DE Wobble Bounce At Marker - +ADBE DE Wobble Bounce On Beat - +ADBE DE Wobble Bounce Random - +ADBE DE Z Spring - +ADBE DE Z Spring At Marker - +ADBE DEPTH FIELD 3D Channel +ADBE DEPTH MATTE 3D Channel +ADBE Deflicker Color Correction +ADBE Difference Time +ADBE Difference Matte2 Keying +ADBE DigitalVideoLimiter Color Correction +ADBE Displacement Map Distort +ADBE Drop Shadow Perspective +ADBE Dropdown Control Expression Controls +ADBE Dust & Scratches Noise & Grain +ADBE ELLIPSE Generate +ADBE Easy Levels _Obsolete +ADBE Easy Levels2 Color Correction +ADBE Echo Time +ADBE Emboss Stylize +ADBE Equalize Color Correction +ADBE Exposure _Obsolete +ADBE Exposure2 Color Correction +ADBE Extract Keying +ADBE Eyedropper Fill Generate +ADBE FOG_3D 3D Channel +ADBE Fast Blur _Obsolete +ADBE Fill Generate +ADBE Find Edges Stylize +ADBE Fractal Generate +ADBE Fractal Noise Noise & Grain +ADBE FreePin3 _Obsolete +ADBE GROW BOUNDS Utility +ADBE Gamma/Pedestal/Gain2 Color Correction +ADBE Gaussian Blur Obsolete +ADBE Gaussian Blur 2 Blur & Sharpen +ADBE Geometry _Obsolete +ADBE Geometry2 Distort +ADBE Getting Jiggy - +ADBE Glo2 Stylize +ADBE Gradient Wipe Transition +ADBE Grid Generate +ADBE HDR ToneMap Utility +ADBE HUE SATURATION Color Correction +ADBE ID MATTE 3D Channel +ADBE IRIS_WIPE Transition +ADBE Invert Channel +ADBE KeyCleaner Keying +ADBE LIQUIFY Distort +ADBE Laser Generate +ADBE Layer Control Expression Controls +ADBE Leave Color Color Correction +ADBE Lens Flare Generate +ADBE Lightning Obsolete +ADBE Lightning 2 Generate +ADBE Linear Color Key2 Keying +ADBE Linear Wipe Transition +ADBE Luma Key Obsolete +ADBE Lumetri Color Correction +ADBE MESH WARP Distort +ADBE Magnify Distort +ADBE Matte Choker Matte +ADBE Median Noise & Grain +ADBE Minimax Channel +ADBE Mirror Distort +ADBE Mosaic Stylize +ADBE Motion Blur Blur & Sharpen +ADBE Noise _Obsolete +ADBE Noise Alpha _Obsolete +ADBE Noise Alpha2 Noise & Grain +ADBE Noise HLS _Obsolete +ADBE Noise HLS Auto _Obsolete +ADBE Noise HLS Auto2 Noise & Grain +ADBE Noise HLS2 Noise & Grain +ADBE Noise2 Noise & Grain +ADBE Numbers2 Text +ADBE OCIO CDL Transform Color Correction +ADBE OCIO Color Space Transform Color Correction +ADBE OCIO Display Transform Color Correction +ADBE OCIO FILE Transform Color Correction +ADBE OCIO Look Transform Color Correction +ADBE OFMotionBlur Time +ADBE Offset Distort +ADBE Optics Compensation Distort +ADBE PS Arbitrary Map Color Correction +ADBE PS Median Noise & Grain +ADBE PSL Bevel Emboss _Obsolete +ADBE PSL Drop Shadow _Obsolete +ADBE PSL Inner Glow _Obsolete +ADBE PSL Inner Shadow _Obsolete +ADBE PSL Outer Glow _Obsolete +ADBE PSL Solid Fill _Obsolete +ADBE Paint _Obsolete +ADBE Paint Bucket Generate +ADBE Param EQ Audio +ADBE Path Text Obsolete +ADBE Photo Filter _Obsolete +ADBE PhotoFilterPS Color Correction +ADBE Playgnd Simulation +ADBE Point Control Expression Controls +ADBE Point3D Control Expression Controls +ADBE Polar Coordinates Distort +ADBE Posterize Stylize +ADBE Posterize Time Time +ADBE Pro Levels _Obsolete +ADBE Pro Levels2 Color Correction +ADBE ProfileToProfile Utility +ADBE RESHAPE Distort +ADBE Radial Blur Blur & Sharpen +ADBE Radial Shadow Perspective +ADBE Radial Wipe Transition +ADBE Ramp Generate +ADBE Reduce Interlace Flicker Obsolete +ADBE RefineMatte _Obsolete +ADBE RefineMatte2 Matte +ADBE RefineRBMatte Matte +ADBE Remove Color Matting Channel +ADBE Ripple Distort +ADBE Rolling Shutter Distort +ADBE Roughen Edges Stylize +ADBE SCHMEAR Distort +ADBE Sample Image - +ADBE Samurai _Obsolete +ADBE Scatter Stylize +ADBE Scribble Fill Generate +ADBE SelectiveColor Color Correction +ADBE Separate XYZ Position - +ADBE Separate XYZ Scale - +ADBE Set Channels Channel +ADBE Set Matte2 _Obsolete +ADBE Set Matte3 Channel +ADBE ShadowHighlight Color Correction +ADBE Sharpen Blur & Sharpen +ADBE Shift Channels Channel +ADBE Simple Choker Matte +ADBE Slider Control Expression Controls +ADBE Smart Blur Blur & Sharpen +ADBE Solid Composite Channel +ADBE Spherize Distort +ADBE Spill Suppressor Obsolete +ADBE Spill2 Keying +ADBE Stereo 3D Controls - +ADBE Strobe Stylize +ADBE Stroke Generate +ADBE SubspaceStabilizer Distort +ADBE Texturize Stylize +ADBE Three-Way Color Corrector _Obsolete +ADBE Threshold _Obsolete +ADBE Threshold2 Stylize +ADBE Tile Stylize +ADBE Time Displacement Time +ADBE Timecode Text +ADBE Timewarp Time +ADBE Tint Color Correction +ADBE Tritone Color Correction +ADBE Turbulent Displace Distort +ADBE Twirl Distort +ADBE Unmult Keying +ADBE Unsharp Mask _Obsolete +ADBE Unsharp Mask2 Blur & Sharpen +ADBE Upscale Distort +ADBE Venetian Blinds Transition +ADBE Vibrance Color Correction +ADBE WRPMESH Distort +ADBE Wave Warp Distort +ADBE Write-on Generate +APC CardDanceCam Simulation +APC CardWipeCam Transition +APC Caustics Simulation +APC Colorama Color Correction +APC Foam Simulation +APC Radio Waves Generate +APC Shatter Simulation +APC Vegas Generate +APC Wave World Simulation +VISINF Grain Duplication Noise & Grain +VISINF Grain Implant Noise & Grain +VISINF Grain Removal Noise & Grain diff --git a/crates/segment/src/mobilesam.rs b/crates/segment/src/mobilesam.rs index 6599b018a..abb12fb0f 100644 --- a/crates/segment/src/mobilesam.rs +++ b/crates/segment/src/mobilesam.rs @@ -19,6 +19,9 @@ const IMG: usize = 1024; const EMB: usize = 64; const DIM: usize = 256; const LOW: usize = 256; +/// Most prompt points the decoder takes (each is an attention token, and self-attention is +/// quadratic in them); SAM is used with a handful. More are thinned evenly, keeping both ends. +const MAX_POINTS: usize = 256; const MEAN: [f32; 3] = [123.675, 116.28, 103.53]; const STD: [f32; 3] = [58.395, 57.12, 57.375]; @@ -609,7 +612,7 @@ impl MobileSam { /// Foreground probability (`w×h`) for a prompt on an embedded image, and the predicted IoU. pub fn predict(&self, e: &Embedding, prompt: &Prompt) -> (Vec, f32) { let s = e.scale; - let points: Vec<([f32; 2], bool)> = prompt.points.iter().map(|(p, fg)| ([p[0] * s, p[1] * s], *fg)).collect(); + let points: Vec<([f32; 2], bool)> = thin(&prompt.points).iter().map(|(p, fg)| ([p[0] * s, p[1] * s], *fg)).collect(); let bbox = prompt.bbox.map(|b| b.map(|v| v * s)); // A prior mask (probabilities at image size) → logits on the low-res grid. let mask: Option> = prompt.mask.as_ref().filter(|m| m.len() == e.w * e.h).map(|m| { @@ -675,3 +678,28 @@ fn sample(rgb: &[[f32; 3]], w: usize, h: usize, x: f32, y: f32, foot: f32) -> [f } s.map(|v| v / f32::max(n, 1.0)) } + +/// `points`, or `MAX_POINTS` evenly spaced ones (first and last kept) when there are more. +fn thin(points: &[([f32; 2], bool)]) -> Vec<([f32; 2], bool)> { + let n = points.len(); + if n <= MAX_POINTS { + return points.to_vec(); + } + (0..MAX_POINTS).filter_map(|i| points.get(i * (n - 1) / (MAX_POINTS - 1)).copied()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn many_prompt_points_are_thinned_to_the_budget() { + let few: Vec<_> = (0..MAX_POINTS).map(|i| ([i as f32, 0.0], i % 2 == 0)).collect(); + assert_eq!(thin(&few), few, "a prompt within the budget is untouched"); + let many: Vec<_> = (0..1_000_000).map(|i| ([i as f32, 0.0], i % 2 == 0)).collect(); + let t = thin(&many); + assert_eq!(t.len(), MAX_POINTS); + assert_eq!((t[0].0, t[MAX_POINTS - 1].0), (many[0].0, many[many.len() - 1].0)); + assert!(t.windows(2).all(|w| w[0].0[0] < w[1].0[0]), "spread in order"); + } +} diff --git a/crates/segment/src/pt.rs b/crates/segment/src/pt.rs index 35ed57297..728cc84f7 100644 --- a/crates/segment/src/pt.rs +++ b/crates/segment/src/pt.rs @@ -108,10 +108,14 @@ fn read_entry<'a>(b: &'a [u8], e: &Entry) -> Result> match e.method { 0 => Ok(std::borrow::Cow::Borrowed(raw)), 8 => { - if e.size > MAX_ENTRY_BYTES { + // Deflate expands at most about 1032:1, so a stated size past that is not this entry's. + if e.size > MAX_ENTRY_BYTES || e.size > e.stored.saturating_mul(1032).saturating_add(64) { return Err("zip entry exceeds the size limit".into()); } - miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1)).map(std::borrow::Cow::Owned).map_err(|e| format!("bad deflate data: {e:?}")) + // The status only: the error's partial output can be as large as the entry. + miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1)) + .map(std::borrow::Cow::Owned) + .map_err(|e| format!("bad deflate data: {:?}", e.status)) } m => Err(format!("unsupported zip compression {m}")), } @@ -162,6 +166,11 @@ fn nodes(o: &Obj, budget: usize) -> usize { let kids: Vec<&Obj> = match o { Obj::Tuple(v) | Obj::List(v) => v.iter().collect(), Obj::Dict(v) => v.iter().flat_map(|(k, x)| [k, x]).collect(), + // A string counts one node per 64 bytes it holds (a vector one per 8 elements): copies + // are charged for everything they own, not as one object. + Obj::Str(s) => return 1 + s.len() / 64, + Obj::Global(a, b) | Obj::Storage(a, b) => return 1 + (a.len() + b.len()) / 64, + Obj::Tensor { dtype, key, size, stride, .. } => return 1 + (dtype.len() + key.len()) / 64 + (size.len() + stride.len()) / 8, _ => return 1, }; let mut n = 1; @@ -209,6 +218,17 @@ fn memo_get(memo: &HashMap, k: u64, cloned: &mut usize) -> Result Ok(o.clone()) } +/// A copy of the stack top to memoize, charged against the clone budget like a memo read: a +/// program memoizing one large object many times keeps a copy each time. +fn memo_put(stack: &[Obj], cloned: &mut usize) -> Result { + let o = stack.last().ok_or("pickle stack underflow")?; + *cloned = cloned.saturating_add(nodes(o, MAX_PICKLE_NODES)); + if *cloned > MAX_PICKLE_NODES { + return Err("pickle exceeds the object limit".into()); + } + Ok(o.clone()) +} + fn unpickle(p: &[u8]) -> Result { let mut stack: Vec = Vec::new(); let mut memo: HashMap = HashMap::new(); @@ -310,15 +330,15 @@ fn unpickle(p: &[u8]) -> Result { } b'q' => { let k = take(&mut i, 1)?[0] as u64; - memo.insert(k, stack.last().cloned().ok_or("pickle stack underflow")?); + memo.insert(k, memo_put(&stack, &mut cloned)?); } b'r' => { let s = take(&mut i, 4)?; - memo.insert(u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as u64, stack.last().cloned().ok_or("pickle stack underflow")?); + memo.insert(u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as u64, memo_put(&stack, &mut cloned)?); } 0x94 => { let k = memo.len() as u64; - memo.insert(k, stack.last().cloned().ok_or("pickle stack underflow")?); + memo.insert(k, memo_put(&stack, &mut cloned)?); } b'h' => { let k = take(&mut i, 1)?[0] as u64; @@ -609,4 +629,34 @@ mod tests { assert_eq!(half_to_f32(0x3c00), 1.0); assert_eq!(half_to_f32(0xc000), -2.0); } + + #[test] + fn memoizing_a_long_string_again_and_again_runs_out_of_the_budget() { + // A 1 MiB string memoized 300 times would keep 300 MiB of copies. + let mut p = vec![0x80, 2, b'X']; + p.extend_from_slice(&(1u32 << 20).to_le_bytes()); + p.extend(std::iter::repeat_n(b'a', 1 << 20)); + p.extend(std::iter::repeat_n(0x94, 300)); + p.push(b'.'); + assert!(unpickle(&p).is_err_and(|e| e.contains("object limit"))); + } + + #[test] + fn every_owned_field_is_charged_to_the_clone_budget() { + let long = || "a".repeat(1 << 20); + let budget = MAX_PICKLE_NODES; + // A one-byte module with a 1 MiB name (and the same for storages and tensors). + assert!(nodes(&Obj::Global("m".into(), long()), budget) >= (1 << 20) / 64); + assert!(nodes(&Obj::Storage("m".into(), long()), budget) >= (1 << 20) / 64); + let t = Obj::Tensor { dtype: "m".into(), key: long(), offset: 0, size: vec![1; 4096], stride: vec![1; 4096] }; + assert!(nodes(&t, budget) >= (1 << 20) / 64 + 1024); + // Small ones stay cheap. + assert_eq!(nodes(&Obj::Global("a".into(), "b".into()), budget), 1); + } + + #[test] + fn an_entry_stating_more_than_deflate_can_expand_to_is_refused() { + let e = Entry { data: 0, size: 1 << 29, stored: 4, method: 8 }; + assert!(read_entry(&[0u8; 4], &e).is_err_and(|m| m.contains("size limit"))); + } } diff --git a/crates/segment/src/tflite.rs b/crates/segment/src/tflite.rs index 34e85dfab..6aafd056f 100644 --- a/crates/segment/src/tflite.rs +++ b/crates/segment/src/tflite.rs @@ -131,6 +131,8 @@ const MAX_VALUES: u64 = 1 << 30; const MAX_LIVE: u64 = 1 << 29; /// The most constant values decoded and laid out at load (a weight shared by several tensors or /// operators counts once per use). +/// Bytes of tensor names and shapes a model may carry in all (the official ones take well under 1 MB). +const MAX_META: usize = 1 << 24; const MAX_CONSTS: usize = 1 << 27; /// Tensor types (`TensorType`). @@ -261,6 +263,7 @@ impl Model { let mut ints: Vec>> = vec![None; n]; let mut data: Vec<(usize, u8, usize, &[u8])> = vec![]; let mut consts = 0usize; + let mut meta = 0usize; for (i, t) in tensors.iter().enumerate() { let shape: Vec = fb .ints(*t, 0)? @@ -269,7 +272,13 @@ impl Model { .collect::>()?; let ty = fb.byte(*t, 1, FLOAT32)?; let buf = fb.int(*t, 2, 0)? as u32 as usize; - names.push(fb.string(*t, 3)?); + let name = fb.string(*t, 3)?; + // Names and shapes are copied per tensor: bound them in all. + meta = meta.saturating_add(name.len()).saturating_add(shape.len().saturating_mul(8)); + if meta > MAX_META { + return Err("the model's tensor metadata is too large".into()); + } + names.push(name); // Every size computed from shapes later stays in range, even a product of some of the // dimensions (a zero dimension does not let the others grow without bound). let count = shape.iter().try_fold(1usize, |a, &d| a.checked_mul(d)).ok_or("a tensor is too large")?; @@ -329,6 +338,11 @@ impl Model { && let Some(i) = ins.first().copied().flatten() && let Some(len) = floats[i].as_ref().map(Vec::len) { + // The folded constant is what the graph outputs and the run's memory estimate count: + // it must be the declared size. + if shapes[output].iter().try_fold(1usize, |a, &d| a.checked_mul(d)) != Some(len) { + return Err(format!("{}: DEQUANTIZE output size disagrees with its input", names[output])); + } spend(len)?; floats[output] = floats[i].clone(); continue; diff --git a/crates/segment/src/tflite/tests.rs b/crates/segment/src/tflite/tests.rs index 29a781d34..9ba96971f 100644 --- a/crates/segment/src/tflite/tests.rs +++ b/crates/segment/src/tflite/tests.rs @@ -334,6 +334,26 @@ fn shapes_computed_at_run_time_must_match_the_declared_ones() { refused(&zero, "tensor is too large"); } +#[test] +fn a_folded_dequantize_has_its_declared_size() { + let half = |n: usize| vec![0u8; 2 * n]; + let fold = |declared: Vec| { + model(vec![half(4)], vec![(vec![1, 4], FLOAT16, Some(0)), (declared, FLOAT32, None)], vec![(op::DEQUANTIZE, vec![0], vec![1], vec![])], vec![], vec![1]) + }; + // A declared output of one value would let the folded four-value constant be copied out per reference. + refused(&fold(vec![1, 1]), "DEQUANTIZE output size"); + assert!(Model::read(&fold(vec![1, 4])).is_ok()); +} + +#[test] +fn tensor_metadata_is_bounded_in_all() { + // A rank of 4 million dimensions of 1 is a valid shape by size, but copied per tensor. + let m = model(vec![], vec![(vec![1; 1 << 22], FLOAT32, None)], vec![], vec![], vec![]); + refused(&m, "metadata is too large"); + let ok = model(vec![], (0..70).map(|_| (vec![1, 2, 3], FLOAT32, None)).collect(), vec![], vec![], vec![]); + assert!(Model::read(&ok).is_ok()); +} + #[test] fn shared_weights_count_once_per_use() { // One 128 KB buffer decoded for 2100 tensors would be 2100 copies of 2¹⁶ floats. diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 0e1af7719..03cacaa7b 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -16,3 +16,4 @@ effectcraft-path = { workspace = true } kurbo = { workspace = true } roxmltree = "0.21" rayon = { workspace = true } +log = { workspace = true } diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 95c00a91a..c31617a92 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -603,8 +603,15 @@ struct Parser<'a, 'i> { /// The `` targets being expanded, outermost first: a reference back into one is a /// cycle and is skipped. using: Vec, + /// Path elements and gradient stops kept so far, `` copies and repeated gradient + /// references included; past [`MAX_RETAINED`] the import errs. + retained: std::cell::Cell, } +/// The most path elements and gradient stops an import keeps: a complex path reused many times, +/// or a gradient with many stops referenced by many shapes, is copied for each use. +const MAX_RETAINED: usize = 8_000_000; + fn is_svg_ns(n: &roxmltree::Node) -> bool { n.is_element() } @@ -628,6 +635,13 @@ impl<'a, 'i> Parser<'a, 'i> { out } + /// Charge `n` kept path elements or gradient stops; false once [`MAX_RETAINED`] is passed. + fn charge_retained(&self, n: usize) -> bool { + let r = self.retained.get().saturating_add(n); + self.retained.set(r); + r <= MAX_RETAINED + } + /// Charge `n` units of CSS work; false once the budget is spent. fn charge_css(&self, n: usize) -> bool { let w = self.css_work.get().saturating_add(n); @@ -875,6 +889,10 @@ impl<'a, 'i> Parser<'a, 'i> { // Stops: from the first element in the chain that has any. let mut stops = vec![]; if let Some(src) = chain.iter().find(|e| e.children().any(|c| c.is_element() && c.tag_name().name() == "stop")) { + // Charged before the stops are read: every reference reads and keeps them again. + if !self.charge_retained(src.children().filter(|c| c.is_element()).count()) { + return None; + } let mut last = 0.0f64; for s in src.children().filter(|c| c.is_element() && c.tag_name().name() == "stop") { let d = self.declared(s); @@ -1026,6 +1044,11 @@ impl<'a, 'i> Parser<'a, 'i> { return; } let Some(geom) = self.geometry(n, &st) else { return }; + if let Geom::Path(p) = &geom + && !self.charge_retained(p.elements().len()) + { + return; + } let fill = if matches!(tag, "line") { None } else { st.fill.as_ref().and_then(|p| self.resolve_paint(p, &st)) }; let (fill, fill_alpha) = match fill { Some((p, a)) => (Some(p), a), @@ -1304,6 +1327,7 @@ pub fn parse(bytes: &[u8]) -> Result { work: 0, budget, using: vec![], + retained: std::cell::Cell::new(0), }; let st = Style::default(); let pct_or = |name: &str, axis: char, def: f64| -> f64 { @@ -1344,6 +1368,9 @@ pub fn parse(bytes: &[u8]) -> Result { // Never a silently partial drawing. return Err(Error::Xml(format!("its references expand to more than {} elements", p.budget))); } + if p.retained.get() > MAX_RETAINED { + return Err(Error::Xml(format!("its paths and gradients, with their copies, hold more than {MAX_RETAINED} elements"))); + } if p.css_work.get() > MAX_CSS_WORK { // Never a silently unstyled drawing. return Err(Error::Xml(format!("matching its `. Every body of the `.aep` comes back byte for byte, including large ones (`cdat`, `ldat`, `opti`). | `000` (1 183 `bdata` elements, all equal but `head`, last row), all pairs. | +| A `LIST` is an element named by its list type, holding its chunks as child elements: ``, ``, ``, ``, ``, ``. An empty list is an element without children and without `bdata` (``, ``, ``, ``). The `LIST` id itself is not written. | `000`. | +| A trailing space of an id or list type is dropped: `Pin ` is ``, `FEE ` is ``. A name shorter than 4 characters is padded with spaces to read it back. | `000` (`FEE`, and `Pin` of the solid's footage), `126`. | +| The same name can be a list or a data chunk: `sspc` is a data chunk in a footage item (``) and a list in an effect instance (`` with children). Whether an element has `bdata` decides. | `000` (footage), `071` (Slider Control). | +| The three nested ids `tdsn`, `pdnm` and `fnam` are written like lists: an element with one child, the `Utf8` chunk. | `000` (`tdsn`), `071` (`pdnm`, `fnam`). | +| A `Utf8` chunk is `` with its text as content; an empty one is ``. The text is the chunk body exactly (no trimming). | `000` (`C`, `Solids`, the JSON strings of the colour settings, 19 empty ones), `010` (`Renamed`), `060` (`wiggle(1,10)`). | +| Two numeric chunks are written as text, in a `` child: `numS` (4 bytes, big-endian) as a decimal integer (only `0` is sampled, so whether it is signed is not decided; the reader accepts -2^31 to 2^32-1), and `ppSn` (8 bytes, an `f64`) with nine decimals (`150.000000000`, `0.000000000`). A `ppSn` value that is not a multiple of 10^-9 would be rounded by the XML form (no sample). | `000`, `124` (two compositions: two of each), all pairs. | +| `LIST btdk` (the text document, raw text in the `.aep`, see 3.10) is written like a data chunk: ``, the hex of the bytes after the list type. It is read back as an opaque list. | `110`-`114`, `243`-`248`, `334`-`340`. | +| The footage alias `alas` (a JSON object in the `.aep`) is the element `` inside ``, with one attribute per JSON key, in the same (alphabetical) order: `ascendcount_base`, `ascendcount_target`, `fullpath`, `platform`, `server_name`, `server_volume_name`, `target_is_folder`. The JSON writes the two counts as numbers, `platform` `Win` as `1` and `target_is_folder` `0` / `1` as `false` / `true`, and escapes a backslash of the path as `\\`. Rebuilt this way, the JSON equals the `.aep` body byte for byte. Other platforms and non-ASCII paths were not sampled. | `125`, `126`, `350`-`354` (`352`-`354`: an image sequence, `target_is_folder` `1`). | +| The XMP packet that follows the container of an `.aep` is the CDATA content of ``, a child of the root between the top-level `string` that follows `pdvc` and ``. It is not a chunk. | All pairs. | +| Pad bytes are not written. An odd body gets a zero pad byte when the tree is written as an `.aep`, which is what every `.aep` of the corpus has. | All pairs: the rewritten tree equals the `.aep` byte for byte. | +| The only differences inside the container are save state: the save counter, a big-endian `u32` at byte 16 of `head`, is one higher in the `.aepx` (only byte 19 changes in 222 pairs; in `314` it carries from `0x000000ff` to `0x00000100`), and the XMP packet has one more history entry. | All pairs. | + +**What the XML form leaves out.** In the corpus, nothing: every chunk of every `.aep` has its +element (the count per id agrees in all 223 pairs, apart from the `` children of `numS` and +`ppSn` and the renamed `alas`), and all 239 pairs of the current corpus read into the same chunk +tree (the local test `every_corpus_pair_gives_the_same_chunk_tree`). The reader still tolerates an +`.aepx` that lacks chunks: `elab`, `cmta` and `empd` are not read by the typed view, so a missing one +changes nothing it decodes, and a missing `tdbs` cannot be told apart from a property at its default +(the sparse rule of section 2): its value reads as the default. Elements that have no chunk +counterpart (a name that is not 1 to 4 characters) are skipped with their content. + +### How the crate reads an `.aepx` + +- `read_aepx` returns the same `AepFile` as `parse`; `parse_any` picks the reader by content (a + `RIFX` header, or an optional byte order mark and white space followed by `= 1 (51 200 at 200 %, 38 400 at 150 %) and stays 25 600 at 50 % | 000, 018, 316, 317 | V | +| start | 12 / 16 | i32 / u32 | layer start time = num / den seconds; den = composition timescale (25 600), 1 in a layer made by the precomp operation | 000, 021 (12 800 / 25 600 = 0.5 s), 124 | V | +| in point | 20 / 24 | i32 / u32 | **relative to the start**: absolute = start + in * stretch (the exact ratio above). **Fractional times are exact multiples of 1/25 600 s: 0.3333 s became 8 532/25 600 = 0.33328125 s, and setting the in point moved the out point with it (duration kept)** | 000, 019 (25 600 / 25 600 = 1 s), 021 (stays 0 while the layer starts at 0.5 s), 318 | V | +| out point | 28 / 32 | i32 / u32 | same convention; 5 s = 128 000 / 25 600. **For footage layers the denominator is the footage time base, not 25 600: 48 000 / 48 000 for the 1 s audio layer (the sample rate), 3 / 30 for the three-frame image sequence (the frame rate); start and in point keep 25 600** | 000, 018 (stays 5 s, the layer ends at 10 s), 019 (6 s), 021 (5.5 s), 316, 317 (stays 5 s, ends at 2.5 s / 7.5 s), 318, 351, 353-354 | V | +| name is user-set | 37 bit `0x01` | flag | clear while the layer shows its source's name (000, 124, new solids, default-named camera and light), set when named | 000, 010, 022, 110, 113, 124, 211 | V | +| guide layer | 37 bit `0x02` | flag | | 026 | V | +| adjustment layer | 38 bit `0x02` | flag | | 025 | V | +| 3D layer | 38 bit `0x04` | flag | always set on cameras and lights | 015, 251 | V | +| solo | 38 bit `0x08` | flag | | 014 | V | +| auto-orient | 38 bit `0x40` | flag | orients towards the point of interest: set on two-node cameras (byte 38 is `0x44`) and on all lights, clear on a one-node camera (`0x04`) | 256 (`0x44`), 251 (`0x04`), 252, 254 | V | +| null object | 38 bit `0x80` | flag | set on a layer created as a null | 022, 220 | V | +| **video switch** | 39 bit `0x01` | flag | the eye icon (`enabled`); off gives byte 39 = `06` | 222 | V | +| **audio switch** | 39 bit `0x02` | flag | `audioEnabled` (also changes on a solid); off gives `05` | 223 | V | +| **effects switch** | 39 bit `0x04` | flag | `effectsActive`; off gives `03` | 224 | V | +| motion blur | 39 bit `0x08` | flag | | 017 | V | +| locked | 39 bit `0x20` | flag | | 013 | V | +| shy | 39 bit `0x40` | flag | | 012 | V | +| collapse transformations | 39 bit `0x80` | flag | continuously rasterize; set from creation on shape and text layers | 024, 238 | V | +| source id | 40 | u32 | `idta@16` of the source item (solid, footage or comp); 0 for shape, text and camera layers, `0xffff_ffff` for lights | 000, 022, 124, 126, 252 | V | +| label | 61 | u8 | label colour index (1 red, 5, 8 blue, 15, ...); a footage layer copies the label of its footage item (audio 7, image sequence 3) | 000 (1), 124 (15), 126 (5), 351 (7), 354 (3) | V | +| name copy | 64..95 | ASCII, NUL padded | copy of the user-set name; empty while the layer is unnamed | 000 (empty), 010 (`Renamed`) | V | +| **blend mode** | 99 | u8 | Normal 2, Add 4, Multiply 5, Screen 6, Overlay 7, Difference 26 (each case changes only this byte); set by name (906): Soft Light 8, Hard Light 9, Darken 10, Lighten 11, Exclusion 25, Color Dodge 27, Color Burn 28; by render (907: a script enum sweep wrote codes 2-34, each code rendered over a test image and matched one mode): Classic Difference 12, Hue 13, Saturation 14, Color 15, Luminosity 16, Stencil Alpha 17, Stencil Luma 18, Silhouette Alpha 19, Silhouette Luma 20, Linear Dodge 29, Linear Burn 30, Linear Light 31, Vivid Light 32, Pin Light 33, Hard Mix 34; 23 / 24 render as Color Dodge / Burn there (taken as the classic variants, E); 3 is written for Dissolve and Dancing Dissolve; 21 / 22 are Alpha Add / Luminescent Premul (not told apart). The reader keeps every code beyond the first six raw | 000, 016, 225-228, 906, 907 | V (6 + 22), E (23, 24) | +| layer type | 128 | u32 | 0 AV (solid, footage, precomp, null), 1 light, 2 camera, 3 text, 4 shape | AV: 000, 022, 126; text: 110, 113, 243; shape: 238-242; camera: 251, 253, 256; light: 252, 254 | V | +| parent id | 132 | u32 | 0 = no parent | 000, 022 (L gets the id of the new null layer) | V | +| **light type** | 136 | u32 | 1 = spot, 2 = point (0 on every other layer); parallel and ambient were not sampled and are kept raw | 252, 254 | V | +| **track matte mode** | 107 | u8 | 0 = none, 1 = alpha, 2 = alpha inverted, 3 = luma, 4 = luma inverted; bytes 104..106 are 0 in every file. Setting a matte changes only this byte and the matte layer id on the target layer, and turns the matte layer's video switch off (byte 39 `07` -> `06`) | 402-408 | V | +| **track matte layer** | 160 | u32 | the id (byte 0) of the matte layer, anywhere in the composition: `0x1d` (`M`, above) in 403-406 and 408, `0x1b` (`L`, below its target) in 407; 0 without a matte. A mode with id 0 has no case (After Effects 2026 writes the id; before 23.0 the matte was always the layer directly above) | 403-408 | V | + +API: `LayerHeader` (`is_video_enabled`/`is_enabled`, `is_audio_enabled`, `is_effects_enabled`, +`is_auto_oriented`, `light_type`, `blend_mode`, `stretch` / `stretch_den`, `stretch_ratio`, +`stretch_percent`, `in_point`, `out_point`); the same switches on `Layer`; `Layer::track_matte` +(`TrackMatte`, `MatteMode`; test `tests/matte.rs`). `stretch` is now the +numerator of the ratio (it was the whole multiplier before 50 % and 150 % were sampled). Tests: +`tests/header.rs`, `tests/layer_switches.rs`. The layer name itself is the `Utf8` child of the +`Layr` (empty while the name is the source's); the layer then shows the name of its source item +(`Project::layer_display_name`). + +### 3.2 Composition header (`Item/cdta`, 204 bytes; the decoder needs the first 176) and renderer + +| Field | Offset | Type | Meaning | Evidence | Conf. | +|---|---|---|---|---|---| +| frame duration | 4 | u32 | time units per frame: 1024 at 25 and 30 fps, **800 at 29.97 fps, 1000 at 23.976 fps** | 000, 031, 229, 230 | V | +| timescale | 8 | u32 | time units per second: 25 600 at 25 fps, 30 720 at 30 fps, **23 976 at 29.97 and 23.976 fps**; fps = timescale / frame duration exactly as typed (29.97 is `23976 / 800`, not `30000 / 1001`) | 000, 031, 229, 230 | V | +| work area start | 28 | u32 | in time units | 035 (25 600 = 1 s) | V | +| work area end | 36 | u32 | start + duration in time units; `0xffff_ffff` = the whole composition | 000, 035 (76 800 = 3 s) | V | +| duration | 44 | u32 | in time units. **A duration is snapped to whole frames: 5 s at 29.97 fps is 120 000 units = 150 frames = 5.005005 s, at 23.976 fps 120 frames** | 000, 031, 032 (256 000), 229, 230 | V | +| background | 52..54 | u8 R, G, B | **8 bits per channel**: 0.5 is stored as 128 and reads back as 128/255 = 0.50196 | 000, 033, 231 | V | +| motion blur | 139 bit `0x08` | flag | the composition's switch | 038 | V | +| width, height | 140, 142 | u16, u16 | | 000, 030 (1280 x 720) | V | +| pixel aspect | 144 / 148 | u32 / u32 | numerator / denominator; **0.9091 is stored as the exact ratio 10 / 11 (read-back 0.90909090909091)** | 000 (1 / 1), 037 (2 / 1), 325 (10 / 11) | V | +| frame rate | 156 | u32 | 16.16 fixed point of the float32 rate (25 = `0x0019_0000`, 29.97 = 1 964 114 = 29.9700012, 23.976 = 1 571 291) | 000, 031, 229, 230 | V | +| shutter angle | 172 | u32 | degrees | 000 (180), 034 (90) | V | +| **shutter phase** | 180 | i32 | degrees: 0 by default, -90 = `ffffffa6`; the shutter angle at 172 does not change | 000, 326 | V | +| **display start** | 164 / 168 | u32 / u32 | the comp start timecode as `num / den` seconds: 0 by default; display start frame 100 at 25 fps is 102 400 / 25 600 = 4 s (the denominator is the timescale; at other frame rates it was not sampled) | 000, 327 | V (one sample) | +| renderer | `LIST PRin` / `prin` 4 | 32 ASCII | match name: `ADBE Escher` in the base, `ADBE Calder` in 039 | 000, 039 | V | +| renderer name | `prin` 52 | 32 ASCII | display name: `Classic 3D`, `Advanced 3D` | 000, 039 | V | +| composition name | `Item/Utf8` | text | | 000 (`C`), 124 (`Pre`) | V | + +The inert `ADBE Time Remapping` record of every AV layer has `tduM` = the source's duration in seconds: 5 for 5 s compositions (124, 257, 258), 3 and 2 for a 3 s and a 2 s composition (600, 601), 1 for the 1 s WAV (351), 0.1 for the three-frame sequence (353), 0 on solids and stills (000, 126). Every property's keyframe time scale (`tdb4` bytes 12 to 15) follows the composition (23 976 in every +property of `L` after 229 and 230). The corpus manifest calls the classic renderer +`ADBE Advanced 3d`; the file stores `ADBE Escher` / `Classic 3D`. API: `CompHeader::frame_rate_exact` +(exact fraction), `duration_frames`, `shutter_phase`, `display_start`, `display_start_seconds`, +`display_start_frame`. Tests: `tests/header.rs`, `tests/layer_switches.rs`. + +### 3.3 Items, footage and precomps + +| Field | Chunk path | Offset | Type | Meaning | Evidence | Conf. | +|---|---|---|---|---|---|---| +| item kind | `Item/idta` | 0 | u16 | 1 folder, 4 composition, 7 footage | 000 | V | +| item id | `Item/idta` | 16 | u32 | what a layer's source id refers to (`iide` holds the same number little-endian) | 000 (`0x1a` solid, `0x0d` comp), 022, 124 | V | +| item label | `Item/idta` | 58 | u8 | label colour of the item | 000 (1 solid), 124 (15 for `Pre`) | V | +| used comp | `Item/idpi` | 0 | u32 **little-endian** | a composition that uses another as a precomp layer gets one `idpi` per used composition | 124 (`C` uses `Pre`) | V | +| used comp count | `Item/idpc` | 0 | u32 little-endian | the number of `idpi` chunks: one per distinct composition shown (the same one twice counts once); the order of the `idpi` carries no meaning (an After Effects re-save reverses it) | 124, 257, 258, 600, 602 (1), 601 (2) | V | +| footage type tag | `Pin /sspc` | 22 | 4 ASCII | `Soli` for a solid, `png!` for a png | 000, 126 | V | +| footage size | `Pin /sspc` | 30, 34 | u32, u32 | width, height in pixels | 000 (1920 x 1080), 022 (100 x 100 null), 126 (8 x 8), 211, 212, 259 | V | +| footage name | `Pin /opti` | 26 (solid), 58 (file) | ASCII, NUL terminated | the item's own `Utf8` name is empty for footage | 000 (`L`), 022 (`Null 1`), 126 (`test8x8.png`), 211 (`S100`), 259 (`Blue`) | V | +| **solid colour** | `Pin /opti` | 10, 14, 18, 22 | 4 x f32 | ARGB, 0..1: red [1, 0, 0] is `1, 1, 0, 0`, blue [0, 0, 1] is `1, 0, 0, 1` | 000, 259 | V | +| file path | `Pin /Als2/alas` | key `fullpath` | JSON string | alias JSON of a file footage item | 126 (the fixture holds a neutral path) | V | +| precomp linkage | `Layr/ldta` | 40 | u32 | the layer's source id is the id of the precomp's item | 124 | V | + +Footage items beyond solids and stills (`Pin /sspc`, 222 bytes; audio and image sequences, batch 3): + +| Field | `sspc` offset | Type | Meaning | Evidence | Conf. | +|---|---|---|---|---|---| +| file type tag | 22 | 4 ASCII | `png!`, `Soli`, **`WAVE`**; `TPIC` Targa (650), `8BPS` Photoshop (651), `TEXT` for both an Illustrator / PDF file (652) and an EPS (653); all four stills store the duration 0 / 600 | 126, 000, 350, 650-653 | V | +| width, height | 30, 34 | u32, u32 | 0 / 0 for audio; 64 x 64 for the sequence | 350, 352 | V | +| **duration** | 38 / 42 | u32 / u32 | seconds as `num / den`, unreduced: still 0/1, **WAV 48 000/48 000 (the sample rate is the denominator), image sequence 3/30 (the frame rate is the denominator)** | 126, 350, 352 | V | +| native frame rate | 56 | u32 | 30 for the sequence, 0 for stills, audio and solids | 126, 352 | V | +| frame rate (again) | 150 | u32 (unaligned) | the same rate as @56 for sequences and clips: 30 (353, 603), 25 (606, 612); 0 for stills and audio. Conforming a sequence to 25 fps (615 against its reference 614) changes @42 (the duration denominator), @56 and @150 from 30 to 25 together; for clips see @146 | 353, 603, 606, 612, 614, 615 | V | +| conformed rate of a clip | 146 | u32 (unaligned) | the rate a clip is conformed to (Interpret Footage), 0 when not conformed; the effective rate is then also at @150, while @38 / @42 (the duration in native frames over the native rate) and @56 stay native: the 25 fps 25-frame mp4 conformed to 30 stores 25 / 25, @56 25, @146 30, @150 30 (645 against 644), the layer's Time Remapping maximum becomes 25 / 30 s. A conformed image sequence keeps @146 at 0 and stores the new rate at @42, @56 and @150 (615) | 615, 644, 645 | V | +| bits per pixel | 60 | u32 | RGBA still 32, RGB sequence 24, 0 for solids and audio | 126, 352 | V | +| **sample rate** | 160 | f64 | 48 000.0 for the WAV; the same for an mp4 with sound (48 000.0 and 44 100.0 read back from AAC tracks of those rates), absent for an mp4 without (the importer takes a clip's audio from it) | 350, read-back vid-audio | V | +| **file size** | 208 | u32 | bytes of the source file(s): png 149, WAV 96 044 (44 + 48 000 x 2), three png of 168 bytes 504 | 126, 350, 352 | V | +| **sequence numbering** | 172, 176, 180 | u32 x 3 | first and last frame number and the digits of a sequence: 1, 3, 3 for `seq_001.png`..`seq_003.png` (353), 101, 103, 4 for `shot_0101.exr`..`shot_0103.exr` (603); 0 for single files (604, 605, 607). The name around the number is the pair of `Utf8` chunks between `Als2` and `opti` in `Pin ` (`seq_` / `.png`, `shot_` / `.exr`), absent on single files. **An empty prefix is not written**: `0001.png`..`0005.png` leave one `Utf8` (`.png`) there, so a single `Utf8` is the prefix when the first file name in `opti` (byte 58: `0001.png`) starts with it and the suffix when it ends with it; without that evidence the reader takes one starting with `.` as the suffix and reads nothing else. `Item::sequence_info`, `SequenceInfo::file_name` | 353, 603, 604, 605, 607; the prefix-less sequence of issue 3174 (After Effects 25.2) | V | +| **sequence file list** (Force alphabetical order) | `Pin /LIST StVc` | `StVS` (4 bytes, `u32` LE), then `Utf8` x count | a sequence imported with Force alphabetical order has, between `Als2` and `opti`, a `LIST StVc` instead of the prefix and suffix `Utf8`s: `StVS` holds the file count as a **little-endian** `u32` (`05 00 00 00`), followed by one `Utf8` per file name in order (`shot_0001.png`..`shot_0005.png`). The numbering at @172 / @176 is then `0xFFFFFFFF` and the digits @180 0; duration and rate are stored as for a numbered sequence (5/30, 30). The list replaces the numbering; a list without a readable `StVS` count, or with a name that is not a plain file name (`/`, `\`, `:`, a control character such as NUL, `.`, `..`), is not read. Without a stored item name the importer names the item after its first listed file (an assumption: what After Effects shows was not sampled). `SequenceInfo::files`, `SequenceInfo::nth_file_name` | the alphabetical sequence of issue 3174 (After Effects 25.2) | V | +| **sequence folder time** | 118 | u32 (unaligned) | seconds since 1904-01-01 UTC: the modification time of a sequence's folder when After Effects scanned it (860: 0xe6fb443a = 2026-10-19 03:51:22, the folder's and its files' time). With the folder's time After Effects keeps the stored numbering on open; with another (an older time, the first or the last file's time while the folder's differs: x1, x2 against x3) it scans the folder again and warns about a gap in a modal dialog | 860, `export-tests\sparse860\exp` x1-x3 | V | +| still duration denominator | 42 | u32 | 1 for png (126, 607), 600 for jpeg (605), 100 for OpenEXR (604): a still's duration is 0 over a per-format denominator | 126, 604, 605, 607 | V | + +An **image sequence is ONE item** (`opti` holds the first file name `seq_001.png` at 58, 322 bytes like +a still, with the width and height at 20 and 24 and the PNG colour type at 36); its alias JSON points +at the sequence **folder** (`"target_is_folder":true`, `ascendcount_target` 2). The audio item has its +name in the item's `Utf8` (`test-tone.wav`), label 7 (sequence 3, still 5); its `opti` has no display +name. A footage layer shows the item's name while it has no name of its own (351, 354). + +Test: `tests/header.rs` (precomp), `tests/text_markers_footage.rs` and `tests/batch3_objects.rs` +(footage), `tests/layer_switches.rs` (solid colour). API: `Footage::{duration, native_frame_rate, +bits_per_pixel, file_size, audio_sample_rate, is_sequence, sequence_frame_count}`. + +### 3.4 Properties: sparse storage, static values and units + +A layer's property tree contains a `tdbs` only for a property whose value differs from the default +that After Effects computes for the layer and composition. A reader supplies the defaults: + +| Property (match name) | Stored | Unit in the API | Default when absent | Evidence | Conf. | +|---|---|---|---|---|---| +| `ADBE Position` | f64 x, y, z | pixels | the composition centre `[width / 2, height / 2, 0]` | 000, 040 (`100, 200, 0`), 030 (the comp becomes 1280 x 720, L stays 1920 x 1080: `960, 540, 0` is now stored), 211, 212 (absent on new solids) | V | +| `ADBE Anchor Point` | f64 x, y as a **fraction of the layer's source size**, z in pixels | px = fraction * source size | `0.5, 0.5, 0` (the layer centre) | 044 (`10, 20` px on 1920 x 1080 is `10/1920, 20/1080`), **211 (100 x 100 solid: `10, 20` is stored `0.1, 0.2`), 212 (400 x 300 solid: `100, 50` is stored `0.25, 1/6`)**: the composition size is not the divisor | V | +| `ADBE Anchor Point` of a **text** layer | f64 x, y, z (a text layer has no source) | pixels, as stored | `0, 0, 0` (the text origin) | absent in every other text sample (110-114, 243-248, 334-340, 386); **385 (text anchor set to `10, 20`) stores `10, 20, 0` as f64 pixels**, not a fraction of a size; test `a_stored_text_anchor_is_pixels` | V | +| `ADBE Scale` | f64 fractions | percent (fraction * 100) | 100 % | 000, 041 (`0.5, 0.5, 1.0`) | V | +| `ADBE Rotate Z` | f64 degrees | degrees | 0 | 000, 042 | V | +| `ADBE Opacity` | f64 fraction | percent (fraction * 100) | 100 % | 000, 043 (`0.25`) | V | +| mask feather | f64 x, y | pixels | `[0, 0]` | 090, 091 (`20, 20`), 208 | V | +| mask opacity | f64 fraction | percent | 100 % | 090, 091 (`0.5`) | V | +| mask expansion `ADBE Mask Offset` | f64 | pixels | 0 | 090, 091 (5) | V | +| effect slider | f64 | as set | the `pard` default | 071 (77) | V | +| effect colour | 4 x f64, ARGB 0..255 | ARGB fractions | the `pard` default | 073 (`[0.2, 0.6, 1]` is `255, 51, 153, 255`) | V | +| shape stroke width, round corners radius, light intensity | f64 | as set (pixels, pixels, percent) | not decoded as defaults except the light (100) | 239 (8), 238 (20), 254 (50) | V | +| shape group position, gradient start and end | f64 x, y | pixels | group position `[0, 0]` | 242, 241 | V | +| camera Position, point of interest | f64 x, y, z | pixels | see 3.12 | 251, 253, 256 | V | +| camera Zoom, light colour, cone angle, cone feather | f64 / ARGB 0..255 | pixels, `[A, R, G, B]` fractions, degrees, percent | Zoom 2 666.67 (1920 px comp), colour white, cone angle 90, cone feather 50 | 341, 343-345 | V | + +`Project::layer_anchor_px` multiplies the anchor fraction by the size of the layer's source (a +solid or footage item, or the composition of a precomp). `Transform::text_anchor_px` gives the +anchor of a text layer (pixels as stored, `[0, 0, 0]` when absent). + +**Explicit defaults (batch 3).** A value record exists exactly when the value differs from the +default; setting a value to its default never creates a record and setting it back removes it. A +Gaussian Blur read back as Blurriness **25** when added (the corpus manifest's "0" for rows 214 and +216 was wrong, with a correction note in the manifest); Blurriness set to 0 writes a record, 25 -> 40 -> 25 +leaves the effect subtree byte-identical to the never-touched default (300, 301, and 214 / 078). +The same holds for Fill Opacity 1 -> 1 and 1 -> 0.5 -> 1 (302, 303) and Slider 0 -> 0 (304), and +for the five transform properties set to the value they already had (Position, Opacity, Anchor, +Scale, Rotation, 311-315: the layer tree is byte-identical to the unedited save 299). A writer may +therefore rely on "absent = default" and drop a record that equals the default. Exceptions are +records AE materialises together with a type switch (polygon, radial gradient: 3.9). +`EffectParam::is_default` returns this; `Tracked::source` tells `Default` from `Stored`. + +**Time Remapping (batch 3).** Every layer has an inert `ADBE Time Remapping` property at the root of +its tree (`tdsb` 3, static value 0, no keys). Enabling the remap turns it into a keyed property +(`tdsb` 1, `tdb4` byte 5 bit 0 cleared, byte 68 = 1, no `cdat`) with two plain 48-byte keys whose value +(seconds) is at byte 8: 0 s -> 0 and 5 s -> 5 on a precomp layer (319), 0 s -> 0 and 0.1 s -> 0.1 on an +image-sequence layer (354). It cannot be enabled on a solid. API: `Layer::time_remap` (`TimeRemap`, +`TimeRemapKey`). + +Property record (`LIST tdbs`: `tdsb`, `tdsn`, `tdb4`, then `cdat` or a `LIST list`, optionally a +`Utf8` expression, `tdum`, `tduM`): + +| Field | Chunk path | Offset | Type | Meaning | Evidence | Conf. | +|---|---|---|---|---|---|---| +| magic | `tdb4` | 0..2 | `db 99 00` | every property | all fixtures | V | +| components | `tdb4` | 3 | u8 | values in `cdat` / in each key (1, 2, 3, 4 = ARGB) | 040, 041, 043, 073, 091, 206, 208, 210 | V | +| static flag | `tdb4` | 5 bit 0 | flag | set while the property has no keys (Position: 15 static; the bit is clear on an animated property) | 040, 055, 058 | V | +| **template flag** | `tdb4` | 7 | u8 | 0 = plain keyframe template, non-zero = spatial template (3 on Position, 1 on colours and paths) | 204-206, 208, 210 | V | +| time scale | `tdb4` | 12 | u32 | units per second of the keyframe times (25 600; 30 720 at 30 fps; 23 976 at 29.97 and 23.976 fps) | 055, 058, 122, 229, 230 | V | +| has keys | `tdb4` | 68 | u8 | 1 exactly when the property has a `LIST list` | every fixture (test) | V | +| keyed spatial-template flag | `tdb4` | 79 | u8 | 1 on a static colour or point effect value, 0 once it is keyed (359 / 364, 369 / 382); 0 on keyed and static sliders (362 / 363, 391 / 397); meaning **?** | 359, 362-364, 369, 382, 391, 397 | V (values) | +| expression flags | `tdb4` | 76, 77, 120 | u8 | all three are 1 when an expression exists. 76 and 77 are also 1 on a camera's or light's computed (auto) Position, which has no expression | 060, 213, 251 | V | +| **expression disabled** | `tdb4` | 119 | u8 | 1 = the expression is disabled; the text and bytes 76, 77, 120 stay. On the built-in view layers the byte flips by itself after the first save, so it counts only together with an expression | 060 (0), 213 (1) | V | +| state | `tdsb` | 0 | u32 | 1 = written (non-default value, keys or expression), 3 = default state. **A layer, camera, light, shape or text property in the default state holds After Effects' default** or a value with no effect on that layer (survey of 839 corpus and sample files: Material Options, cone 90 / 50 and falloff 500 / 500 of point lights, Position `[0, 0, -1333.33]` of ambient and environment lights, Opacity 1 and Scale `[1, 1, 1]` of cameras and lights, a polygon's Inner Radius 50, Miter Limit 4, the inert Time Remap 0), so the importer skips it. **An effect parameter's record in the default state holds the effective value** (3.7, stored value) | 040, 071, 073 (1); 3 on the unwritten properties of 000; 1200, 1400 (effects) | V (1), E (3), V (effects) | +| static value | `cdat` | 0 | `components` x f64 | the first `components` doubles are the value | 040, 041, 043, 071 | V | +| user name | `tdsn/Utf8` | | text | `-_0_/-` means "no custom name" | 091 (`Mask 1`), 238 (`Group 1`) | V | + +Test: `tests/values.rs`, `tests/typed.rs`, `tests/keyframes.rs`. + +### 3.5 Keyframes (`tdbs/list`: `lhd3` + `ldat`) + +`lhd3` (13 `u32`): word 0 `0x00d0_0bee`, word 2 the record count, word 3 `ceil(count / 4)`, word 4 +the record size, word 7 the count rounded up to a multiple of 4, words 8 to 12 zero; `ldat` is +exactly `count * record size` bytes (cases 050, 055; every list of every fixture). In path lists +(record size 8) words 3 and 7 are allocation capacities in vertices and four times that (12 records: +4 and 16; 9 records: 4 and 16 in the shape paths of 105 and 240, 3 and 12 in the open mask path 233), +not a function of the count. + +**Record header (8 bytes, every kind).** + +| Field | Offset | Type | Meaning | Evidence | Conf. | +|---|---|---|---|---|---| +| time | 0 | i32 | in the property's time scale; **layer time** (roving moved key 2 from 25 600 to 26 509 = 1.0355078125 s) | 055 (0, 25 600, 64 000), 056, 058 | V | +| **interpolation in** | 4 | u8 | the incoming side: 1 = linear, 2 = bezier, 3 = hold | 202 (in linear, out hold: `01 03`), 203 (in hold, out linear: `03 01`), 204, 205, 052, 053 | V | +| **interpolation out** | 5 | u8 | the outgoing side, same codes | same | V | +| label | 6..7, bits 6..9 | u16 | keyframe label: label 9 turns the flags `0x0007` into `0x0247` | 057 | V | +| roving | 6..7, bit `0x0020` | u16 | `0x0007` becomes `0x0027` | 056 | V | + +A hold key has no further field (the value is unchanged); a linear key has all ease slots 0. Keys +added through the scripting interface are linear in and out. + +**The template follows the property header (`tdb4` bytes 3 and 7), not the record size.** With +`n` components: + +| Template | `tdb4[7]` | Size | Used by | Evidence | +|---|---|---|---|---| +| plain | 0 | `8 + 40 n`: 48 (n=1), 88 (n=2), 128 (n=3) | Opacity, Rotation, Slider (1); Mask Feather, Rectangle Size (2); Scale (3) | 205, 206, 208, 221 | +| spatial | non-zero | `56 + 24 n`: 128 (n=3), 152 (n=4) | Position (3), colours (4) | 204, 210 | +| mask path | | 64 | the path property of an animated mask (the path itself is in `shap`) | 093 | +| marker | | 16 | `mrst` marker times | 122, 123, 249 | + +A 128-byte record is a Scale key (plain, 3 components) or a Position key (spatial): a reader must +look at the header (206 against 204). Layout of the plain template: value (`n` x `f64`) at 8, then +`4 n` ease doubles in **type-major order**: `[in speed x n][in influence x n][out speed x n][out +influence x n]`, starting at `8 + 8 n` (for `n = 1`: **at 16 in speed, at 24 in influence, at 32 +out speed, at 40 out influence**). Scale key 1 of 305 (`n = 3`, in 0 / 33 %, out 20 / 66 %) is +`0,0,0, .33,.33,.33, .2,.2,.2, .66,.66,.66`; Mask Feather key 1 of 306 (`n = 2`, in 0 / 33, out +15 / 66) is `0,0, .33,.33, 15,15, .66,.66`. Component `i` uses slot `i` of each block (**V** for the +block layout and the units, Scale speed in fractions per second and Mask Feather speed in pixels +per second; **E** that different values per dimension sit in the slot of their dimension, because +the tool that made the corpus applies one ease to all dimensions; **V** since the exporter wrote three different eases for the three Scale dimensions and After Effects read the same three back, aep-export.md R13). `Keyframe::plain_ease_slots` +returns the doubles as stored, `Keyframe::ease_component(i)` one component's `KeyEase`. Layout of +the spatial template: `u32` at 8 (1 normally, 0 after the spatial auto-bezier and continuous +switches were turned off together, 054), `f64` arc length of the segment to the next key at 16 +(100 in 204 key 1, 0 on the last key and right after creation; safe to ignore), **ease at 24 in +speed, at 32 in influence, at 40 out speed, at 48 out influence**, value (`n` x `f64`) at 56, spatial +in tangent (`n` x `f64`, relative offset from the value) at `56 + 8 n`, out tangent at `56 + 16 n`. + +| Field | Where | Meaning | Evidence | Conf. | +|---|---|---|---|---| +| ease, Position | spatial @24..55 | 204 key 1: in speed 5 / influence 0.2, out speed 50 / influence 0.8; key 2: in 7 / 0.6, out 9 / 0.4. Speed in pixels per second, influence a fraction. **After Effects reports key 1's in speed and the last key's out speed as 0, but the file keeps the requested values (5 and 9): ignore those two slots** | 204, 052 (preset: speed 0, influence 0.33) | V | +| ease, Opacity | plain n=1 @16..47 | 205 key 1: in 0.05 / 0.2, out 0.2 / 0.8; key 2: in 0.3 / 0.6, out 0.09 / 0.4. Speed is in stored units per second, i.e. 100 times smaller than the percent per second shown in the UI; influence a fraction | 205 | V | +| value, Scale | plain n=3 @8 | 206: `[1, 1, 1]` and `[2, 1.5, 1]` (fractions of the manifest percent) | 206 | V | +| value, Rotation, Slider | plain n=1 @8 | degrees / as set (keyed slider 10 and 90) | 221 | V (slider), E (rotation, 207 is not a fixture) | +| value, Mask Feather | plain n=2 @8 | pixels `[0, 0]` and `[40, 20]` | 208 | V | +| value, colour | spatial n=4 @56 | ARGB doubles 0..255: `[255, 255, 0, 0]` and `[255, 0, 127.5, 255]`; flags `0x0001`, tangents zero; the project-level `EfdG` copy of the effect has the same list | 210 | V | +| value, Position | spatial n=3 @56 | pixels | 055 (`[0,0,0]`, `[100,0,0]`, `[200,100,0]`), 056 | V | +| tangents | spatial @`56+8n`, `56+16n` | 054: key 1 out `[30, 60, 0]`, key 2 in `[-30, -60, 0]` | 054 | V | +| arc length | spatial @16 | 100 on key 1, 0 on key 2 | 204 | E | +| **colour distance** | spatial n=4 @16 | for bezier colour keys the Euclidean ARGB distance to the next key, 255 sqrt(2) = 360.6245 for red to blue, 0 on the last key; linear colour keys have 0 (like the Position arc length, filled only for non-linear interpolation). The ease slots of a colour key are one entry (speed 0, influence 0) | 307 against 210 | V | +| **keyed Orientation** | `otst`: `tdbs` key list of 80-byte records (time, interpolation sides, flags at 0..7; `f64` 2.0 at 16 on the first key; the rest 0 for linear keys) and `otky` with one `otda` (three `f64` degrees) per key, in the same order. **After Effects interpolates by a quaternion slerp of the rotation `Rx Ry Rz`**: 703 (keys `[0,0,0]` at 0 s, `[10,20,30]` at 2 s, linear) reads back 0.5 s `[3.434, 4.469, 7.713]`, 1 s `[6.264, 9.353, 15.219]`, 1.5 s `[8.465, 14.560, 22.610]`, which slerp with that order reproduces to 0.001 degree (not per-component: 5 / 10 / 15 at 1 s; the order `Rz Ry Rx` gives `[3.58, 10.64, 14.32]`) | 703 | V (layout, linear), H (ease of bezier keys) | +| **light type** | `ldta` `u32` at 136: 0 parallel (701), 1 spot, 2 point, 3 ambient (702). A light created as an environment light by script without the Advanced 3D renderer is stored as ambient (704) | 701, 702, 704 | V | +| **ease, Anchor Point and effect points** | spatial @24..55 | the value is a fraction of the layer size, and **a speed is pixels per second divided by the layer height**: out speed 50 is 50 / 1080 = 0.046296 on the 1920 x 1080 L (597 Anchor Point, 598 Gradient Ramp Start), 50 / 800 = 0.0625 on a 400 x 800 solid (730; not the width, not the smaller side, not the composition height); influence a fraction. After Effects reads 597 back as 0.5 s [1004.41, 562.21], 1 s [1084.84, 602.42], 1.5 s [1137.13, 628.57] | 597, 598, 730 | V | +| **ease, colour switched to bezier** | spatial n=4 @24..55 | keyframe.set_interpolation bezier on two colour keys stores speed 0 and influence 0 on both sides, and After Effects interpolates them linearly (598 Start Color red to blue: 0.75 / 0.5 / 0.25 red at 0.5 / 1 / 1.5 s); a custom colour ease cannot be set by script | 598 | V | +| **ease, mask path** | 64-byte record @24..55 | in speed, in influence, out speed, out influence as in the spatial template: 599 out / in influence 0.75, 700 0.2 / 0.5, speeds 0 (the path at 0.5 s is 5.42 % / 28.0 % of the way). The `f64` at 16 is 1 (093) or 2 (599, 700) on the first key and 0 on the last (not decoded) | 093, 599, 700 | V (influence), ? (speed unit) | + +API: `Keyframe::{interpolation_in, interpolation_out, kind, value, ease, ease_component, ease_components, plain_ease_slots, color_distance, spatial}`; +`Property::keys()` hands the property's template to its records. Marker record (16 bytes): time, +`03 03` hold bytes, 8 stale bytes. Mask path record (64 bytes): the common fields and the ease at byte 24 (599, 700). Test: +`tests/values.rs`, `tests/keyframes.rs`. + +### 3.6 Expressions + +| Field | Chunk path | Meaning | Evidence | Conf. | +|---|---|---|---|---| +| source | `tdbs/Utf8`, after `cdat` / `list` and before `tdum` | raw UTF-8 text, no length prefix, no NUL, no engine tag | 060 (`wiggle(1,10)` on Opacity) | V | +| flags | `tdb4` 76, 77, 120 | all 1 when present, all 0 otherwise | 060, 040 | V | +| **disabled** | `tdb4` 119 | 1 when disabled (`expression.disable_all`); the only byte that differs between 060 and 213 | 060, 213 | V | +| static value | `cdat` | kept while an expression exists (Opacity 1.0) | 060 | V | +| **on an effect parameter** | the parameter's own value record, as on any property: Slider Control's Slider with `time*10` holds the text and the static value 0 | 534 | V | + +The expression engine is project-wide (`LIST ExEn/Utf8`, `javascript-1.0`). API: +`Property::expression_enabled`. Test: `tests/keyframes.rs`. + +### 3.7 Effects (`tdgp[ADBE Effect Parade]/sspc`) + +| Field | Chunk path | Offset | Type | Meaning | Evidence | Conf. | +|---|---|---|---|---|---|---| +| match name | the `tdmn` before the `sspc` | | text | `ADBE Slider Control`, `Pseudo/@@S1iPXtJFTHK4QaDbgJvLhw`, ... | 071, 073, 077, 080, 214 | V | +| instance name | `sspc/fnam/Utf8` | | text | the effect's own name (`Slider Control`, `Tint`); it stays the same when the instance is renamed (610) | 071, 073, 077, 080, 610 | V | +| **user name of an instance** | `sspc/tdgp/tdsn/Utf8` (the value group's name) | | text | `-_0_/-` (the placeholder every unnamed group has) while the instance shows the effect's name; the given name otherwise (610: `My Tint`, `fnam` still `Tint`). `Effect::user_name`, `Effect::display_name` | 356, 609, 610 | V | +| **fx switch** | `sspc/tdgp/tdsb` (the value group's flags, `u32`) | | flag | 1 on, 0 switched off in the Effect Controls (`fx-switch.aep`: two Gaussian Blurs on one layer in one save, the first switched off, the second on; read back `enabled` false / true). `Effect::enabled` | fx-switch | V | +| parameter count | `sspc/parT/parn` | 0 | u32 | including the implicit input layer and the built-in entry (3 for a slider) | 071 | V | +| parameter match name | `parT/tdmn` | | text | `-NNNN`; the last is `ADBE Effect Built In Params` | 071 | V | +| parameter type | `parT/pard` | 12 | u32 | 0 layer, 2 fixed slider (16.16), 3 angle, 4 checkbox, 5 colour, 6 point, 7 popup, 9 no data, 10 float slider, 12 path, **13 group start / 14 group end** (Exposure's Master, Red, Green and Blue twirl-downs; the end repeats the group's name; no value), **15 button** (Swap Colors of Tint and Gradient Ramp: empty name, label in `pdnm`) | 071, 073, 077, 080, 214, 215, 356, 368, 389 | V | +| UI flags | `pard` | 4 | u32 | 0x20 greyed out, 0x08 on a group end. **Stale:** After Effects does not reset it on undo (391-397 keep the flags of 390 although Channels is back to Master), so it is UI state and never read for meaning | 389-397 | V (values), E (meaning) | +| parameter name | `pard` | 16 | 32 ASCII | `Slider`, `Color`, `Menu`, `Blurriness`, `Shadow Color`, ... (empty for some checkboxes) | same | V | +| **default** | `pard` | 56 | by type | float slider: f64 (Slider 0, **Blurriness 25**); fixed slider and angle: 16.16 (drop shadow opacity 127.5, direction 135, distance 5, softness 0; Fill opacity 1.0 = 100 %; **Tint Amount to Tint 100, Ramp Scatter 0, Blend With Original 0**); **colour: ARGB bytes (drop shadow `ff000000` black, Fill `ffff0000` red; Ramp Start `ff000000`, End `ffffffff`; Tint Map Black To `00000000` and Map White To `00ffffff`: alpha 0, which is what After Effects reads back)**; popup: u32 index (1); **point: two 16.16 fractions of the layer size at 56 and 60 (Point Control 0.5, 0.5; Ramp Start 0.5, 0 and End 0.5, 1)** | 071, 077, 080, 214, 215, 356, 368, 383 | V | +| **valid maximum** | `pard` | 128 / 108 | 16.16 / f32 | the largest valid value of a fixed slider (128: Tint Amount 100, Ramp Scatter 512, Blend With Original **1.0**) and of a float slider (108: Blurriness 30 000; **Exposure 100, Offset 2, Gamma Correction 10**). The stored scale differs per slider (below), so this is the reader's only hint at it | 356, 368, 078, 389 | V | +| **float slider valid minimum, slider range** | `pard` | 104; 112 / 116 | f32; f32 x 2 | the smallest valid value (Exposure -100, Offset -2, Gamma Correction 0.1 as f32) and the range the slider covers (Exposure -4..4, Offset -0.5..0.5, Gamma 0.1..10); the slider range is repeated as `tdum` / `tduM` (f64) in each value record (391-394). @120 holds the default again as f32 (Gamma 1.0, Blurriness 25), u16 @124 the display decimals (**H**: Exposure 2, Offset 4) | 389, 391-394 | V | +| **definitions of a second instance** | top-level `LIST EfdG` | | | one `EfDf` per effect TYPE (`tdmn` = match name, then a copy of ONE instance's `sspc`, including that instance's value records); the `EfDC` count before them is a little-endian u32. When two layers carry the same effect type, only one instance keeps a full `parT`; **the other has an empty `LIST parT` (4 bytes)** but its own `tdgp` (input layer `-0000` with its own `tdpi`, the button record, and its value records). Its definitions come from the `EfdG` copy by match name, its values from its own records, never from the copy (383: the copy holds S100's Start [0.1, 0.2]; L's Ramp reads the 368 defaults). Which instance keeps the full `parT` is **?** (in 383 S100 is both first in the file and newest). The `EfDf` order follows the stack order (365 / 366); `Pefl/pjef` does not. **Some files have no `EfdG` at all** (seen in 17 projects, all from inside After Effects-made Motion Graphics templates). In each of them every effect type (196 in all; 2 to 14 Color Controls per file) has exactly one instance with a full `parT` and an empty one in every other instance, and the reader takes the others' definitions from that instance (`DefinitionSource::OtherInstance`, #3170). Which instance keeps it is **?** here too | 365, 366, 383; templates | V | +| popup items | `parT/pdnm/Utf8` | | text | items separated by `\|` | 077 (`Item 1\|Item 2\|Item 3`), 214 | V | +| stored value | `sspc/tdgp/-NNNN` | | `tdbs` | present only for a parameter that differs from its default; `tdsb` 1, `cdat` as in 3.4. **Absent record = the `pard` default.** Some parameters are recorded in the default state (`tdsb` 3) and the record still holds the value After Effects uses: every one of the 25 such records in the corpus and the samples differs from its `pard` default and reads back as recorded (Lumetri Color's hidden controls High Dynamic Range, HDR Specular, the second Look, Legacy Tone And Saturation, Face Detection, Auto Color, Auto Intensity and SemanticAutoTone Progress, 1200; Cryptomatte's Selection Mode on, 1400). No effect record in the default state holds a value that does not count. The reader takes the value in either state (`EffectParam::recorded_value`, `EffectParam::value`); `EffectParam::stored_value` keeps to written records, and a record in any other state (no sample has one) is not read: the importer reports it as damaged data. That other effects record values so is H (no sample shows one) | see below; 1200, 1400 | V (1200, 1400), H (other effects) | + +Stored values by type (`tdsb` 1, or 3 as above): + +| Type | Stored | Evidence | Conf. | +|---|---|---|---| +| float slider | `cdat[0]` as set (Slider 77, Blurriness 40); a keyed slider has 48-byte plain records and no `cdat`. **The value is the float32 After Effects keeps, widened to f64: Offset 0.1 is `0.10000000149011612`, Gamma 2.2 is `2.200000047683716`** | 071, 216, 221, 393, 394, 397 | V | +| **group start / end** | the record always exists (`tdsb` 1, `cdat` 0, descriptor `00010000`), `tdsn` = the group name; no value (scripting: NO_VALUE) | 389-397 | V | +| **fixed slider** | `cdat[0]` as a plain double in the parameter's own scale: Tint Amount to Tint is a **percent** (0 -> 0.0, 37.5 -> 37.5; valid max 100), Gradient Ramp Scatter is **pixels** (12, 250.5; valid max 512), Blend With Original is a **0..1 fraction** (25 % -> 0.25, 100 % -> 1.0; valid max 1.0). Keyed: 48-byte plain records with the plain value (Amount 20 / 80) | 361-363, 378-381 | V | +| colour | ARGB doubles 0..255 (Tint Map Black To [0.2, 0.4, 0.6] -> `[255, 51, 102, 153]`, float32 precision; Ramp Start Color red `[255, 255, 0, 0]`); keyed: 152-byte spatial records with the ARGB value at 56 (210 Fill, 364 Tint Map White To) | 073, 357, 371; keyed: 210, 364 | V | +| **button** | the record always exists (`tdsb` 1, `cdat` 0, descriptor `00010000`) and carries no value (scripting: NO_VALUE). An exception to the sparse rule, like the Layer Control record | 356-383 | V | +| **popup (built-in)** | 1-based index as a double: Ramp Shape Radial = `2.0`; the selection is also written to `pard` @56 (only byte 59 changes, as for the dropdown 324). Default Linear = 1, item count u16 @60 = 2, `pdnm` `Linear Ramp\|Radial Ramp` | 368, 377 | V | +| **checkbox** | `cdat[0] = 1.0` when on, `0.0` when off; **the default is the `u32` at `pard` byte 56** (0 off: Checkbox Control 217, Shadow Only 420, Bypass 389; **1 on: Repeat Edge Pixels of Fast Box Blur and Gaussian Blur, read back 1 in 412 and 417**), and a record exists only when the value differs from it (416 and 419 switch Repeat Edge Pixels off: a record with 0.0, descriptor `00010004`). The corpus manifest's "off" for the Gaussian Blur of 214 was wrong. Exposure's Bypass Linear Light Conversion has an empty `pard` name and its label in `pdnm` (like the buttons) | 217, 389, 396, 412, 416, 417, 419, 420, 426 | V | +| **integer slider** (type 1) | Fast Box Blur's Iterations: default `i32` at `pard` 56 (3), valid maximum `i32` at 128 (50), the value record a plain double (1.0 for 1) with `tdum` / `tduM` 1 / 5 (the slider range) | 412, 414 | V | +| **arbitrary data** (type 11) | the value record is a 4-byte `cdat` 0 followed by a `LIST aRbs` holding the data (`aRbp`); `parT` has the default `aRbp` after the `pard`. Hue/Saturation's Master Hue, Saturation, Lightness and Levels' Input / Output Black and White and Gamma are NOT in their visible parameters (which keep no record) but in this data; see below | 443-446, 511-516 | V | +| **point** | two doubles, a **fraction of the layer size** (`tdb4@24` = the layer's width / height: 16 / 9 in 369, 374, 218, 1 on the 100 x 100 solid of 383; `@16` = 6.25e-12 in all): `[111, 222]` is `[111/1920, 222/1080]` (`tdb4[3]` = 2, `[5]` = 15). **The default is two 16.16 fractions 0.5 in `pard` @56 and @60, relative to the layer: a Point Control on a 100x100 solid reads back [50, 50]**. Gradient Ramp Start / End are stored the same way; values outside the layer give fractions outside 0..1 (`[2000, -100]` -> `[1.0417, -0.0926]`); on a 100x100 solid `[10, 20]` is `[0.1, 0.2]`. **Keyed: 104-byte spatial records (56 + 24 x 2), flags `0x0007`, `u32@8` = 1, the two fractions at 56, tangents zero**; `f64@16` holds a derived distance on linear keys too (1.7397 in 382: ignore it) | 218, 310, 369, 374, 382, 383 | V | +| **angle** | plain degrees: 90 is `90.0` | 219 | V | +| **layer control** | the `-0001` record always exists (`cdat` 0); the sibling `tdpi` (u32) is the **id of the chosen layer** (the new Null, `0x22`). **The default ("Layer 1" on the first layer) and an explicit 1 are the owning layer's own id (320); "None" is `tdpi` 0 (321).** The manifest's "None" for the default (076, 220 rows) was wrong. In the implicit first parameter `tdpi` is the id of the layer that owns the effect | 220, 320, 321 | V | +| **layer parameter** (any effect) | as the Layer Control: the `-NNNN` record always exists with `cdat` 0 and `tdpi` = the id of the chosen layer (Set Matte, Displacement Map, Compound Blur set to the layer below: `tdpi` 340 / 354 / 368 = that layer's id); the effect's implicit `-0000` record holds the owning layer's id | 904, 905 | V | +| **dropdown** | the items are in `pdnm` (`Alpha\|Beta\|...`), `pard` u16 @60 is the item count (5), `pard` @56 the selection (1 by default). Selecting item 3 adds a value record (`cdat[0]` = 3.0, descriptor `00010004`) AND writes 3 into `pard` @56. Setting the items re-creates the effect definition under a new match name (`Pseudo/@@KbKT0rCPQi2A0ytuyGLWSw`; display name `Dropdown Menu Control`) | 077, 323, 324 | V | + +The default of Gaussian Blur: the default-only file is byte-identical to the one with Blurriness 25 +and has no value record; `pard` holds 25 (f64 @56 and f32 @120); setting 40 adds a record and leaves +`pard` at 25, so `pard@56` is the default and not the current value (a popup selection is the one +exception, it overwrites `pard@56`). The corpus manifest's default of 0 was wrong: After Effects +reads a fresh Gaussian Blur as 25 (300, **V**; the conflict is resolved). + +Because a popup selection overwrites `pard@56`, a popup whose definition comes from the `EfdG` copy +has no reliable default in the file (the slot holds the copied instance's selection); the reader +returns no default for it (`EffectParam::pard_default` is `None`), and a consumer uses the effect's +known default. Effect stack order is the order of the `sspc` children of the Effect Parade: moving an +effect (366) reorders them and the `EfDf` copies and changes nothing else (365, 366, **V**). + +**Exposure (`ADBE Exposure2`, 389-397, V).** `parn` = 24: 0 the input layer, 1 `Channels:` (popup +`Master|Individual Channels`, 1-based, default 1), then four groups of five entries, Master 2-6, +Red 7-11, Green 12-16, Blue 17-21, each `[group start (13), Exposure, Offset, Gamma Correction, +group end (14)]` (the channel groups' sliders are named `Red Exposure`, `Red Offset`, `Red Gamma +Correction`, ...), 22 Bypass Linear Light Conversion (checkbox, default off) and 23 the built-in +entry. The three sliders are float sliders with the same `pard` in every group: Exposure (stops) +default 0, valid -100..100, slider -4..4; Offset default 0, valid -2..2, slider -0.5..0.5; Gamma +Correction default **1**, valid and slider 0.1..10. Each one-change case adds exactly one value +record (twice: layer tree and `EfdG`): Channels 2 (390), Exposure 1.5 (391) and -2.25 (392), Offset +0.1 (393), Gamma 2.2 (394), Channels 2 + Red Exposure 1 (395, two records), Bypass 1.0 (396). A +keyed Exposure (397: -1 at 0 s, 2 at 2 s, linear) has plain 48-byte records. With Channels = Master +the per-channel values are stored but inactive. The other byte changes against 389 are only the +stale UI flags `pard@4` and, for a popup selection, `pard@59`. + +**Batch 5 effects (409-450, 511-516, 522-525; V).** Defaults as read back by After Effects for the +fresh effect (MANIFEST), each value change one case. The scale of a fixed slider is told by its +valid maximum (`pard` 128): + +| Effect (match name) | Parameters (`parT` index: type, valid maximum, default) | Evidence | +|---|---|---| +| `ADBE Invert` | 1 Channel: popup of 16 items **including three separators `(-`** (RGB, Red, Green, Blue, `(-`, HLS, Hue, Lightness, Saturation, `(-`, YIQ, Luminance, In Phase Chrominance, Quadrature Chrominance, `(-`, Alpha), default 1, stored 1-based over all 16 (Red = 2); 2 Blend With Original: fixed, max 100 (percent), 50 stored 50.0 | 409-411 | +| `ADBE Box Blur2` (Fast Box Blur) | 1 Blur Radius: fixed, max 30 000, pixels (20); 2 Iterations: integer slider, default 3, max 50; 3 Blur Dimensions: popup (Horizontal and Vertical, Horizontal, Vertical), default 1; 4 Repeat Edge Pixels: checkbox, **default on** | 412-416 | +| `ADBE Gaussian Blur 2` | 1 Blurriness: float, default 25, max 30 000; 2 Blur Dimensions: popup as above (Vertical = 3); 3 Repeat Edge Pixels: checkbox, **default on** | 417-419 (and 214, 216, 300, 301) | +| `ADBE Drop Shadow` | 1 Shadow Color: default black; 2 Opacity: fixed, **max 255** (default 127.5 = 50 %, 204 = 80 %); 3 Direction: angle, default 135; 4 Distance: fixed, max 4 000, pixels, default 5; 5 Softness: fixed, max 30 000, default 0; 6 Shadow Only: checkbox, default off | 420-426 | +| `ADBE Glo2` (Glow) | 1 Glow Based On: popup (Alpha Channel, Color Channels), default 2; 2 Glow Threshold: fixed, **max 255** (default 153 = 60 %); 3 Glow Radius: fixed, max 1 000, default 10; 4 Glow Intensity: fixed, max 255, default 1; 5 Composite Original: popup (On Top, Behind, None), **default 2 (Behind)**; 6 Glow Operation: popup of 25 blend modes starting None, Normal, Add, ..., default 3 (Add); 7 Glow Colors: popup (Original Colors, A & B Colors, Arbitrary Map), default 1; 8 Color Looping: popup (Sawtooth A>B, Sawtooth B>A, Triangle A>B>A, Triangle B>A>B), default 3; 9 Color Loops: fixed, max 127, default 1; 10 Color Phase: angle; 11 A & B Midpoint: fixed, **max 0.99, a 0..1 fraction**, default 0.5; 12 Color A white; 13 Color B black; 14 Glow Dimensions: popup as Blur Dimensions | 427-441 | +| `ADBE HUE SATURATION` | 1 Channel Control: popup (Master, Reds, Yellows, Greens, Cyans, Blues, Magentas); 2 Channel Range: **arbitrary data** (below); 3 Master Hue (angle), 4 Master Saturation, 5 Master Lightness (fixed, max 100): **never stored, the values are in the data**; 6 Colorize: checkbox; 7 Colorize Hue: angle; 8 Colorize Saturation: fixed, max 100, default 25; 9 Colorize Lightness: fixed, max 100 | 443-450 | +| `ADBE Timewarp` | 1 Method: popup (Whole Frames, Frame Mix, Pixel Motion), default 3; 2 Adjust Time By: popup (Speed, Source Frame), default 1; 3 Speed: fixed, max 5 000, default 50, plain (25 stored 25.0; keyed: plain 48-byte records 50 / 200); 4 Source Frame: fixed, max 5 000, plain (12); the tuning, motion blur, matte (`Matte Layer`, `Warp Layer`: layer records always present, 0 = none) and crop parameters follow | 529-533 | +| `ADBE Easy Levels2` (Levels) | 1 Channel: popup (RGB, Red, Green, Blue, Alpha); 2 Histogram: **arbitrary data** (below); 3-7 Input Black, Input White, Gamma, Output Black, Output White: float sliders (max 10 000, Gamma 5), **never stored, the values are in the data**; 8 / 9 Clip To Output Black / White: popup (**On, Off, Off for 32 bpc Color**), default 3 | 511-516 | + +Hue/Saturation data (180 bytes): `i32` master hue at 0 (444: 90), saturation at 4 (445: 50), +lightness at 8 (446: -30; V); then six colour ranges (Reds, Yellows, Greens, Cyans, Blues, +Magentas) of 28 bytes: four `i32` range points in degrees (default Reds 315, 345, 15, 45; Yellows +15, 45, 75, 105; ...; Magentas 255, 285, 315, 345) and the range's hue, saturation, lightness (E: +layout read from the default, no range was changed). The Colorize values are ordinary records +(447-450). Levels data (108 bytes): `u32` `0x000f10a7`, `u32` 1, then five channels (RGB, Red, +Green, Blue, Alpha) of five `f32` input black, input white, gamma, output black, output white; the +RGB values are V (512-516: 0.1, 0.8, 2, 0.2, 0.9 as float32), the other channels E (their defaults +0, 1, 1, 0, 1). After Effects' undo does not revert a change of these values (MANIFEST). API: +`Effect::arbitrary_data`, `HueSaturationData`, `LevelsData`; test `tests/effects_batch5.rs`. + +API: `EffectParam::{stored_value, pard_default, value, is_default, is_animated, keys, valid_max, +valid_min, slider_range, point_px, layer_ref, popup_item_count, popup_selected_index, +popup_selected_item, borrowed_definition}`, `Effect::has_own_definitions`, +`Project::{effect_params, effect_definitions, definition_source}`, `ParamValue`, +`ParamKind::{Button, GroupStart, GroupEnd}`, `DefinitionSource`, `LayerRef`. Tests: +`tests/effects.rs`, `tests/batch3_core.rs`, `tests/batch3_objects.rs`, `tests/effects_batch4.rs` +(356, 357, 361, 363, 364, 366, 368, 369, 371, 374, 377, 378, 380, 382, 383), +`tests/effects_exposure.rs` (389-391, 393-397). + +**Importer block 2026-11-05, #3110 (`1100-quickwins.aep`, After Effects 26.2.1; V for every +row: defaults from the defaults composition, the valid ranges from the minimum and maximum +compositions, the items from one composition per popup item).** Each set value is stored as set +(Decay 20 is `20.0`, Blend With Original 100 % is `1.0`); a value set to the default leaves no record +(HDR Amount 100): + +| Effect (match name) | Parameters (`parT` index: type, valid range, default) | +|---|---| +| `ADBE HDR ToneMap` (HDR Highlight Compression) | 1 Amount: float, 0..100 (slider 0..100), default 100 | +| `ADBE Echo` | 1 Echo Time (seconds): float, -30 000..30 000 (slider -5..5), default -1/30 (float32); 2 Number Of Echoes: integer, max 30 000, default 1; 3 Starting Intensity: float, 0..1, default 1; 4 Decay: float, **valid 0..100, slider 0..1**, default 1; 5 Echo Operator: popup (Add, Maximum, Minimum, Screen, Composite In Back, Composite In Front, Blend), default 1 | +| `ADBE Linear Wipe` | 1 Transition Completion: fixed, max 100, default 0; 2 Wipe Angle: angle, default 90; 3 Feather: fixed, max 32 000, default 0 | +| `ADBE Offset` | 1 Shift Center To: point, default the layer centre; 2 Blend With Original: fixed, **max 1 (a 0..1 fraction)**, default 0 | +| `ADBE Deflicker` (Color Stabilizer) | 1 Stabilize: popup (Brightness, Levels, Curves), **default 2 (Levels)**; 2 Black Point, 3 Mid Point, 4 White Point: points, defaults 0.2 / 0.5 / 0.8 of the width at half the height; 5 Sample Size: fixed, max 50, default 3. The reference frame the Set Frame button picks is not among the parameters | + +**Importer block 2026-11-05, #3112 (`1300-thirdparty.aep`; V for the parameter lists, H for the +data layouts, read from default instances only):** + +| Effect (match name, plug-in version) | Parameters (`parT` index: type, valid range, default) | +|---|---| +| `CS Color Neutralizer` (CC Color Neutralizer, 1.3) | 1 / 7 / 13 Shadows / Midtones / Highlights Unbalance: colours (black, 127 grey, white; pickers: setting one sets the range's sliders, e.g. [0.27, 0.55, 0.85] gives Red 42.94, Green 1.18, Blue -44.12 = (mean - channel) x 150 / 255 on 8-bit values, and leaves no colour record); 2-6, 8-12, 14-18 a group per range (start, Red, Green, Blue, end) with float sliders -100..100 (slider -50..50), default 0; 19 Pinning: float 0..100 (slider 0..50); 20 Blend w. Original: float 0..100; 21-25 the Special group: 22 View popup (Final Result, Correction B to W, Correction Stair), default 1, 23 Black Point float 0..49.9, default 0, 24 White Point float 50.1..100, default 100 | +| `EXtractoR` (2.6.6) | 1 Channel Info (`EXtractoR-0013`): arbitrary data, 688 bytes, below; 2-6 the Process group: 3 Black Point and 4 White Point float sliders, valid ±3.4028235e38 (the float32 range; slider ±1 000), default 0 / 1; 5 UnMult: checkbox (empty `pard` name, the label in `pdnm`), default off | +| `IDentifier` (2.6.6) | 1 Channel Info (`IDentifier-0005`): arbitrary data, 148 bytes, below; 2 Display: popup (Colors, Luma Matte, Alpha Matte, Raw), default 1; 3 ID: integer slider, max 2 147 483 647, default 0 | + +EXtractoR's Channel Info is the plug-in's own **little-endian** layout: `u32` 1 and 28 bytes, then +four 164-byte records (Red, Green, Blue, Alpha), each a kind in byte 0 (1 a channel of the footage by +name: `R`, `G`, `B` by default; 2 the input's own channel, named `(copy)`: Alpha by default) and the +channel name NUL-terminated from record byte 35. EffectCraft imports kind 2 as its EXtractoR's `(copy)`, +the effect input's channel of the same position as earlier effects left it, not as `A` (which names +an OpenEXR footage's own alpha plane). The rest is not read: it differs between instances +with the same channels (uninitialised-looking values, also in bytes 1..4 of a record: `02 00 00 32` +on Alpha in one definition's default, which is why only byte 0 is the kind). **A chosen channel** +(`extractor-07-preset-channel-z`, a preset of our own that reads `Z` into Red, Green and Blue) is kind +1 with its name (`Z`), and the `u32` at record byte 4 is then 13, which looks like the channel's +position in the EXR's sorted channel list of 14 (the defaults hold 0 there: H). IDentifier's data +differs between instances with the same settings except for **the chosen channel's name**, +NUL-terminated from byte 19, which is `Object ID` when no channel is chosen. After Effects lists +only integer (UINT) channels: in 1300's EXR (a FLOAT `ID` channel) it found none ("No ID channels +available"), so that block's preset `identifier-09-preset-channel-id` only sets ID 2; in 1310's +EXR (UINT `objectId` and `IndexOB.X` added) the preset `identifier-09-preset-channel-objectid-id2` +stores `objectId`, with 15 at byte 4 (the channel's position in the sorted list of 16, as for +EXtractoR: H). Without a chosen channel After Effects leaves the layer unchanged (1300 and 1310 +defaults). The other bytes are not read. API: `ExtractorChannels`, +`identifier_channel_type`. + +**Curves and Mesh Warp** (961-965, 985; applied from presets, the data is not scriptable): their +arbitrary-data parameter (type 11) always has a record (`tdbs` with a 4-byte `cdat`) and a `LIST +aRbs` / `aRbp`, also at the default. Curves (`ADBE CurvesCustom-0001`, 1644 bytes): `u16` 1, 1; +five 256-byte tables (RGB, Red, Green, Blue, Alpha) = the natural cubic spline through the points, +rounded (0 of 1280 entries differ); five 72-byte point records of 16 (`u16` in, `u16` out) slots, +the count at 64, an `i32` at 68 (-1 untouched, count - 2 in every edited sample: H). Mesh Warp +(`ADBE MESH WARP-0004`): `u32` rows + 1, `u32` columns + 1 (a 1 x 2-cell read-back test renders as made only in +this order, `export-tests\mesh`; AE does not rebuild the stored mesh when Rows / Columns change, 989), 12 bytes +(zeros, `0d 0d`), then per vertex row-major ten big-endian `f32`: position, handles top, right, +bottom, left as fractions of the layer (H: or of the comp), outward border handles (0, 0); Rows / +Columns / Quality are integer sliders with records only off their default (7, 7, 8). The `-NNNN` +suffix is a parameter id, not the `parT` position (Curves -0002 Channel before -0001; Mesh Warp +-0005 Quality before -0004). API: `CurvesData`, `MeshData`, `curve_lut`. [V; details: corpus FORMAT +S] + +**Lumetri Color** (`ADBE Lumetri`, 1200: 63 compositions in After Effects 2026, 32 bpc, working space +None; by script: defaults, all set, one per section, valid minima and maxima, every popup item the script +can set, checkboxes toggled, keys, an expression; from presets made by hand, `-58` ... `-62`: an Input +LUT, a Look, the RGB curve, Hue vs Sat, the colour wheels): 131 `parT` entries. The `-NNNN` suffix is a +parameter id, not the position (`-0127` ... `-0130` sit between `-0005` and `-0026`), so the importer +keys by suffix. Float sliders (type 10) store the value After Effects shows; the valid ranges (`pard` +104 / 108) are wider than the slider's (112 / 116): Temperature / Tint -300..300 (slider -100..100), +Saturation 0..300 (0..200), Exposure -7..7 (-5..5), Contrast, Highlights, Shadows, Whites, Blacks, +HDR Specular, Tint Balance -150..150 (-100..100), Faded Film 0..150 (0..100), HDR White 100..1000, +HDR Range 100..10000, Refine Blur 0..1000 (0..30), Vignette Amount -5..5 (-3..3); the read-backs of +`-19-min` / `-20-max` equal the stored numbers. **Hidden controls are recorded in the default state** +(`tdsb` 3) and still hold the value After Effects reads back: High Dynamic Range `-0062` (1.0), +HDR Specular `-0064` (22), the second Look popup `-0128` (26.16 as set, read back 26), Legacy Tone And +Saturation `-0097` (its `pard` default reads off as the script saved the project and on once the +project was opened and saved again, `versions/1200-lumetri-26`, `-25x`, `-24x`; a fresh instance reads +back off), Auto Color `-0124`, Face Detection `-0102`, the Auto Intensity `-0123` +(`EffectParam::recorded_value`). Each section has an Active checkbox (blank `pard` name; `-0003` Basic +Correction, `-0023` Creative, `-0037` Curves, `-0118` RGB Curves, `-0104` / `-0105` / `-0107` / `-0109` / +`-0111` the hue / saturation curves, `-0046` Color Wheels, `-0068` HSL Secondary, `-0050` Vignette, on +by default); off, the section does nothing (`-03-sec-basic-correction`, `-17-sec-vignette` render as +`-00-defaults`). Arbitrary data (type 11, a record and `aRbs` in every instance; empty is `fe fe`): +`-0001` an XML copy of the grade written only when the Look changes (not kept current: `-01-set-all` +holds defaults for controls set after the Look; it names the LUT file, `Fuji F125 Kodak 2393 (by +Adobe).cube`); `-0096` the Look's name, UTF-16LE (`SL BLUE ICE`, `Fuji F125 Kodak 2393 (by Adobe)` in +`-59-preset-look-lut`; the popup `-0025` itself has no record, `-0128` can disagree with it: +`-07-sec-creative` names item 20 while `-0128` holds 23), `-0095` likewise for the Input LUT +(`ALEXA_Default_LogC2Rec709`, `-58-preset-input-lut`; the popups `-0005` / `-0127` keep no record, +`-0004`, `-0024` and the assets `-0125` / `-0126` stay `fe fe`: the LUTs are After Effects' own files, +named, not embedded); `-0129` the Look colour space's 16-byte id (the GUID `LookColorSpace` of `-0001` +in Windows layout: the first 4, 2 and 2 bytes little-endian; zero for None; the Color Space popup +`-0130` writes no record of its own, `-22-pop38-1` ... `-53-pop38-33`); +`-0032` Split Toning (32 zero bytes); `-0039` the four RGB curves and `-0042`, `-0106`, `-0108`, +`-0110`, `-0112` the hue / saturation curves, 520 bytes each: `i32` type (3 for the hue curves, 2 for +Luma vs Sat and Sat vs Sat, 0 for an RGB curve), `u32` point count, then little-endian `f64` pairs x, y +sorted by x (bytes after the counted points are stale). RGB: x and y 0..1, (0, 0), (1, 1) by default; +the first of the four is the master curve (`-60-preset-curves-rgb`: (0.491, 0.787) lifts R, G and B +alike, and the render follows a natural cubic spline through the points within 0.003); the order of +the other three is H (the `-0001` XML names `ToneCurvesLuma`, `Red`, `Green`, `Blue`; no sample moves +one). Hue / saturation: x the hue (0 red, 1/3 green) or the luma / saturation 0..1, y the offset from +neutral 0; a fresh curve has no points, the selector colours `-0113` ... `-0117` add three at y = 0, +the hue picked +- 0.0556. Hue vs Sat's y scales the saturation by 1 + y in linear light +(`-61-preset-curves-huesat`: (0.0155, 0.97) takes pure red's linear saturation to 1.96 times, (0.263, +-0.03) and (0.765, -0.02) green, cyan and blue to 0.97); the other four curves' scale is H. `-0047` +Color Wheels, 4 `f64` triples: hue in degrees (0 red, 120 green), brightness slider 0..1 (0.5 +neutral), distance from the centre 0..1; 0, 0.5, 0 each by default; Shadows, Midtones, Highlights, then +a fourth wheel of unknown role (`-62-preset-wheels`: Shadows 229.1, 0.370, 0.547 towards blue with the +slider down; Midtones 0.1, 0.5, 0.395 towards red; Highlights 93.4, 0.727, 0.319 towards yellow-green +with the slider up; the fourth at its default); `-0085` the HSL correction wheels (8 triples, the same +default; layout H); `-0073` the HSL key, 40 bytes: a flag byte (1 once a colour was picked), then hue, +saturation, lightness, each centre, range, tolerance (`f32` LE, fractions) and an enabled byte (fresh: +0.5, 0, 0, on; picking RGB 0.02 0.55 0.85 gives hue centre 0.5605 = that colour's hue and lightness +centre 0.435 = its HSL lightness, range 0.05, tolerance 0.1: `-01-set-all`; whether range is the half +or full width is H); `-0122` the Auto Tone analysis (UTF-16 JSON). The project saved as 25.x and 24.x +copies (`versions/1200-lumetri-25x`, `-24x`: the 58 scripted compositions, saved by After Effects +2026) stores every Lumetri definition, valid range and value as the 26 save does. [V for the sliders, +checkboxes, popups, the `tdsb` 3 values, the master RGB curve, Hue vs Sat, the colour wheels and the +LUT names; H where marked] + +**Cryptomatte plug-in** (match name `Cryptomatte`, the free Cryptomatte plug-in, 2.6.6 in our +sample; read from 88 instances in one production project, not made by us, and from our own After +Effects 2026 sample 1400 (corpus `aep/cryptomatte.aep`: a fresh instance, Selection Mode on, each +Output item, and two presets of our own that choose a layer and pick one object or material in the +plug-in's UI; scripting read-backs and renders per composition); H for what neither varies): +`parT` 0 the input layer; 1 Settings: **arbitrary data** (type 11, `Cryptomatte-0001`, a record and +`aRbs` / `aRbp` in every instance); 2 Output: popup (Colors, Matted Colors, Matted RGBA, Matte +Only), **`pard` default 1 = Colors** (bytes 56..64 `00000001 0004 0001`, in the instance's own and +the project's shared definition; scripting reads 1 from a fresh effect: 1400 `crypto-00-defaults`), +a written record (`tdsb` 1) holding the item number when set (1400: 2, 3, 4; production: 3 in 81, +4 in 7); 3 Selection Mode: checkbox (`pdnm` `fnord!`), no record when off, and when on **a +default-state record (`tdsb` 3) holding 1.0** that After Effects reads back as on and renders +(1400 `crypto-01-set-all`, `crypto-02-chk-toggled`; the general reader takes only `tdsb` 1 +values, so the importer reads this one itself); the built-in entry. As in every project, only the +first instance has its own `parT`; the others borrow the project's (1400). The Settings data is +the plug-in's own layout, **little-endian**: `cry1`; bytes 4..32 differ between instances with +the same settings (zeros in one, pointer-like values in others: not read); the layer name at 32, +NUL-padded to 64 bytes (`CryptoObject`, `CryptoMaterial` in 1400: the EXR layer's name, which is +also its channel prefix there, so the sample cannot tell which of the two the plug-in stores); at +96 a `u32` 1 and a `u32` that is the same in every instance; at 104 the `u32` length of the +selection text including its NUL; at 108 **the MurmurHash3 (x86, 32-bit, seed 0) of the selection +text with its NUL** (V on the three texts of 1400: `<11a97486>` `0x27880767`, `` +`0xf7374a5b`, the empty text `0x514e28b7`; not read); a zero byte at 112; the selection text from +113, the matte list as comma-and-space separated ID hashes `<11a97486>, ` (303 tokens in +production, all in that form). Each token is the 8-digit hash of a picked name as the EXR's +manifest lists it, i.e. the MurmurHash3 of the name (1400: `box_red` `11a97486` picked on +CryptoObject, `mat_paint` `a5deeb9e` on CryptoMaterial). After the text 2 to 3 bytes, zeros or +left-overs of a longer earlier text (1400's presets: 127 bytes, three zeros after the text). **A fresh effect** (the `parT` +default and the record alike, 116 bytes, 1400) is `cry1`, zeros to 96, then `u32`s 1, +`0x514e28b7`, 1, `0x514e28b7` and four zero bytes: no layer and an empty text (length 1, its NUL). +`0x514e28b7` is the hash of a single NUL byte, so the `u32` at 100 looks like the hash of a first +text that is empty in every sample, its length the `u32` 1 at 96 and its NUL the zero byte at 112 +(H: one value). Layer and selection decode the same in the production project and in 1400's two +presets, and After Effects draws exactly the picked objects as selected (`crypto-06`: the box, +`crypto-07`: box and disc, the two objects of `mat_paint`). API: `CryptomatteData` (refuses data without `cry1`, a length past the end or +a non-zero byte at 112). + +**Puppet (`ADBE FreePin3`; ?: external listing, not the corpus, #3093).** No file of the +corpus, the committed fixtures or the samples holds a Puppet. The tree below comes from outside +the corpus: a public scripting listing of the effect's properties (a forum post, an After Effects +release from before the Advanced and Bend pins and Density). It is not bytes we have seen; that +After Effects writes it by the general rule (a `tdmn` and the `LIST tdgp` or `tdbs` it names, +nested in the instance's value group `sspc/tdgp`, as masks, shapes and layer styles are) is +**H**: + +```text +Puppet ADBE FreePin3 + On Transparent ADBE FreePin3 On Transparent + arap ADBE FreePin3 ARAP Group (hidden) + Auto-traced Shapes ADBE FreePin3 Outlines + Mesh ADBE FreePin3 Mesh Group (hidden) + Mesh 1 ADBE FreePin3 Mesh Atom + Mesh ADBE FreePin3 Mesh (hidden: the triangulation) + Triangles ADBE FreePin3 Mesh Tri Count + Expansion ADBE FreePin3 Mesh Expansion + Deform ADBE FreePin3 PosPins + Puppet Pin 1 ADBE FreePin3 PosPin Atom + Vertex Offset ADBE FreePin3 PosPin Vtx Offset (hidden, 2 values) + Vertex Index ADBE FreePin3 PosPin Vtx Index (hidden; 4294967295 = none) + Position ADBE FreePin3 PosPin Position + Overlap ADBE FreePin3 HghtPins (hidden while empty) + Stiffness ADBE FreePin3 StarchPins (hidden while empty) +``` + +A pin's rest place is not a property: it is a vertex of the hidden mesh (Vertex Index) plus an +offset, so it cannot be read without decoding the mesh data. The unit of Position (layer pixels, +or a fraction of the layer as effect points are) is **?**. The match names of the Overlap and +Starch pin atoms and their properties, of the Advanced and Bend pins (Scale, Rotation) and of +Density, Mesh Rotation Refinement and the Puppet Engine are **?**, and so is which of them are +`parT` parameters; whether After Effects stores some `parT` parameters of a fresh Puppet even at +their defaults (the importer would then report them every time) is **?**; whether a Puppet +without pins has an (empty) Mesh Group, or no ARAP group at all, is **?**. The importer +(`import/puppet.rs`) therefore brings the effect in as EffectCraft's Puppet without meshes or +pins and reports, per mesh, Triangles, Expansion and per pin group the pins, how many are keyed +or carry an expression, and their atom match names; every entry outside this tree is named in the +report. The sample that settles it: a fresh Puppet with no pins in one composition and, in +another, a 400 x 800 solid in a larger composition (pixels against fractions) with a Puppet of +three Position pins (one keyed, one moved off its rest place without +keys), one Advanced, one Bend, one Starch and one Overlap pin, Triangles, Expansion and Density +off their defaults, a second mesh, and a scripting read-back of every property's match name and +value, the hidden ones included. Pins added by script are reported to come out disabled, so the +pins are placed by hand or by a preset. + +### 3.8 Masks and bezier paths (`tdgp[ADBE Mask Parade]`) + +| Field | Chunk path | Offset | Type | Meaning | Evidence | Conf. | +|---|---|---|---|---|---|---| +| inverted | `Mask Parade/mkif` | 0 | u8 | | 090 (0), 091 (1) | V | +| **mode** | `mkif` | 4 | u32 | Add 1, Subtract 2, **Intersect 3, Lighten 4, Darken 5, Difference 6, None 0** (329: the same ellipse path as 232) | 090, 091, 234-237, 329 | V | +| name | `tdgp[ADBE Mask Atom]/tdsn/Utf8` | | text | `Mask 1` | 090 | V | +| feather, opacity, expansion | `ADBE Mask Feather`, `ADBE Mask Opacity`, `ADBE Mask Offset` | | see 3.4 | stored only when not at the default; feather can be keyed (plain n=2 records) | 090, 091, 208 | V | +| path property | `om-s[ADBE Mask Shape]/tdbs` | | | animated: `tdb4` byte 68 = 1 and a `list` of 64-byte records (time and common fields only) | 090, 093 | V | +| path shapes | `om-s/omks/LIST shap` | | | one per keyframe, one for a static path | 090, 093 | V | +| path never set | (no `ADBE Mask Shape` entry in the atom) | | | a mask added without a path (scripted `addProperty`) stores no Mask Path at all, also no `om-s`; After Effects reads it back, also after reopening, as the **source rectangle** `[0,0] [0,h] [w,h] [w,0]` (clockwise from the top left, no tangents) and renders it so (901: expansion -100 leaves a 100 px border) | 900, 901 | V | +| box | `shap/shph` | 4, 8, 12, 16 | 4 x f32 | left, top, right, bottom **normalised to the layer (source) size** for masks (560 / 1920, 340 / 1080, 1360 / 1920, 740 / 1080; on a 100x100 solid a 60x40 rectangle has the box 0.2, 0.3, 0.8, 0.7 and decodes exactly with the layer size, not the 1920x1080 composition). It is the box of the vertices **and** of the handles | 090, 232, 309 | V | +| **open path** | `shph` | 3 | u8 | bit `0x08` set = open path (`0x09` against `0x01`); byte 20 is 1 in every sample, open or closed | 233 against 090, 232, 234 | V | +| points | `shap/list` (`lhd3` record size 8) | | f32 x, y | three per vertex in the order **vertex i, out handle i, in handle i + 1**, normalised inside the box (u = (x - left) / (right - left)); the last record is the in handle of vertex 0. A **tangent is the handle minus the vertex**, without a sign change | 090 (rect), 093 (two rects), 232 (ellipse: tangents `0.5523 x radius`, `[-220.91, 0]`, `[0, -110.46]`, ...), 233 (open path, 3 vertices) | V | + +**There is one `mkif` per mask**, placed directly before its atom (two masks: `mkif tdgp mkif tdgp`, +328), so mode and inverted are reported per mask. `mkif` byte 8 is the running mask id counter of the +**layer** in the session (1, 2 for the two masks of 328; 329 then gets 3; undo does not reset it; a new +layer starts at 1 again): exposed as `Mask::counter`, a session counter and not a stable id. API: +`Mask::{mode, inverted, counter}`, `Project::mask_vertices_px` (vertices in layer pixels), `Layer::mask_atoms` (`MaskAtom`: the mask with its atom group, its path property and its shapes by position, for the keys and expressions of the mask properties). Tests: +`tests/masks.rs` (with a synthetic check of the handle order), `tests/batch3_objects.rs`. + +### 3.9 Shape layers (`tdgp[ADBE Root Vectors Group]`) + +A shape layer (type 4) holds `ADBE Vector Group` (user name `Group 1`) with `ADBE Vectors Group` +(the contents, in z-order, `tdsb` 0x401) and `ADBE Vector Transform Group`. Items are named by their +match name and carry their own user name. Colours are ARGB doubles 0..255. All sizes, positions and +path points are in pixels. **An item's eye switch is bit 0 of its group's `tdsb`** (1 on; 986: a +Fill at 0 is not drawn, 987: the same file at 1 draws it; both saved by After Effects from a patched +copy of 850, the switch is not scriptable) [V]. + +| Item (match name) | Property | Stored | Evidence | Conf. | +|---|---|---|---|---| +| `ADBE Vector Shape - Rect` ("Rectangle Path 1") | `ADBE Vector Rect Size` | f64 `[400, 300]` (2 components) | 238-242 | V | +| `ADBE Vector Shape - Group` ("Path 1") | `om-s[ADBE Vector Shape]` | the same `shph` + point list as a mask, with a box in **pixels** relative to the layer origin; vertices `[0,-100] [100,100] [-100,100]`, in tangents `[-10,-20] [30,20] [-60,10]`, out tangents `[40,0] [-20,30] [0,-50]`; the box covers vertices and handles: `-160, -120, 130, 130` | 240 | V | +| `ADBE Vector Graphic - Fill` | `ADBE Vector Fill Color` | `[255, 0, 255, 0]` | 238, 240, 242 | V | +| `ADBE Vector Graphic - Stroke` | `Stroke Color` `[255, 0, 255, 0]`, `Stroke Width` 8, **`Stroke Line Cap` 2.0 (round; butt = 1 is absent)**, **`Stroke Line Join` 2.0 (round; miter = 1 is absent)**, `Stroke Miter Limit` 4 with `tdsb` 3 once the join was touched | doubles | 239 | V | +| `ADBE Vector Filter - RC` ("Round Corners 1") | `ADBE Vector RoundCorner Radius` | f64 20 | 238 | V | +| `ADBE Vector Graphic - G-Fill` ("Gradient Fill 1") | `ADBE Vector Grad Start Pt` `[-200, 0]`, `ADBE Vector Grad End Pt` `[200, 0]` | 2 components, class 15; the gradient type (linear) and the colour stops stay at After Effects' default and are not stored | 241 | V (points) | +| `ADBE Vector Transform Group` | `ADBE Vector Position` | f64 `[50, 50]`; absent = `[0, 0]`, as are all other transform properties at default | 242 | V | + +Batch 3 (all **V**; shape layer `Shape`, label 8): + +| Item | Stored | Evidence | +|---|---|---| +| `ADBE Vector Shape - Star` ("Polystar Path 1") | After Effects' defaults are star, 5 points, outer radius 100, inner radius 50, rotation 0, roundness 0, so **a default star has no property record at all** (the 150 / 70 of batch 1 were stored). A **polygon** stores `ADBE Vector Star Type` 2.0 (`tdsb` 1, descriptor `00020000`) plus `Inner Radius` 50 and `Inner Roundess` 0 (After Effects' own spelling) as `tdsb` 3 default-state records; Points 5 and Outer Radius 100 stay absent | 330, 331 | +| `ADBE Vector Graphic - G-Fill` | `ADBE Vector Grad Type` 2.0 for radial (`tdsb` 1, descriptor `00020000`; linear is 1 and absent); Start Point `[0, 0]` is the default and absent, End Point `[200, 0]` stored; the radial-only `Grad HiLite Length` and `Grad HiLite Angle` are written with `tdsb` 1 and value 0 (absent in the linear 241). Colour stops are in no property | 241, 332 | +| two siblings with one match name | one group holds `Rectangle Path 1` (Size `[400, 300]` stored), `Rectangle Path 2` (Size `[100, 100]` is the default, no record; `ADBE Vector Rect Position` `[300, 0]`, 2 components, class 15) and `Fill 1`, in z-order: a reader keys the items by occurrence, not by match name | 333 | + +Batch 5 (all **V**; shape layer `S`, Group 1 = Ellipse Path 1 [400,300] + Fill 1 green in 451, one change each): every value is stored **as After Effects shows it**, in the shape's own record (`tdsb` 1), and absent at its default: + +| Property (match name) | Stored | Evidence | +|---|---|---| +| `ADBE Vector Shape - Ellipse`: `ADBE Vector Ellipse Size`, `... Ellipse Position` | pixels `[500,200]`, `[100,50]` | 452, 453 | +| `ADBE Vector Graphic - Fill`: `ADBE Vector Fill Opacity`, `ADBE Vector Fill Rule` | percent 50; popup 1-based, even-odd = 2 | 454, 455 | +| `ADBE Vector Transform Group` of a group: `ADBE Vector Anchor`, `Scale`, `Rotation`, `Group Opacity`, `Skew`, `Skew Axis` | pixels `[10,20]`; **percent** `[50,80]` (not a fraction as the layer's Scale); degrees 30; percent 40; 20; degrees 45 | 456-461 | +| layer `ADBE Anchor Point` of a shape layer | pixels `[10,20,0]` as stored (no source size), as on a text layer | 462 | +| `ADBE Vector Graphic - Stroke`: `ADBE Vector Stroke Opacity` | percent 50 (colour `[255,255,0,0]` and width 6 as in 239) | 463, 464 | +| `ADBE Vector Filter - Trim`: `Trim Start`, `Trim End`, `Trim Offset`, `Trim Type` | percent 20, 70; degrees 45; popup 1-based, individually = 2; a new Trim Paths has no record | 465-469 | +| `ADBE Vector Rect Roundness` | pixels 30 | 470, 471 | +| `ADBE Vector Shape - Star`: `Points`, `Rotation`, `Inner Roundess`, `Outer Roundess`, `Position`, `Outer Radius`, `Inner Radius` | 6; degrees 30; percent 20, 40; pixels `[50,-20]`, 150, 30 | 472-479 | +| `ADBE Vector Graphic - G-Fill` added: Start `[0,0]` and End `[100,0]` are the defaults, no record; **the colour stops have no record at their default**, which renders white to black, linear in the encoded values (481: 0.75 / 0.5 / 0.25 at a quarter, half and three quarters) | 480, 481 | +| a second top-level group, a group nested in a group (`ADBE Vector Group` inside `ADBE Vectors Group`), `ADBE Vector Graphic - G-Stroke` (width 10) | the same records as at the top level, in z-order | 482, 483, 484 | +| defaults of every item (519: AE read-back with no record stored): rectangle and ellipse size 100 x 100, position 0, roundness 0; star 5 points, radii 100 / 50, rotation and roundness 0; fill red `[1,0,0]`, opacity 100, rule 1; stroke white, width 2, cap / join 1, miter 4; gradients linear, start `[0,0]`, end `[100,0]`; trim 0 / 100 / 0, type 1; round corners radius 10; group transform anchor / position 0, scale 100, opacity 100; blend mode, composite order, shape direction 1 | none of them has a record | 519 | + +The 3D-extrusion `ADBE Vector Materials Group` of a group changes its `tdsb` from 1 to 3 when a polystar or a gradient is added (472-484), with no property record. + +API: `Layer::shape_groups` (`ShapeGroup`, `ShapeItem`, `Stroke`, and `ShapeGroup::details` with +`ShapeDetail::{Polystar, Gradient, RectPosition}`, `PolystarType`, `GradientType`). Other items +(ellipse, trim paths, repeater, dashes, ...) are listed as `ShapeItem::Other` with their match name; +the polystar is listed as `Other` and the gradient fill as `GradientFill`; both carry their extra +fields in `details` (indexed by `item_index`); see section 4. Tests: `tests/shapes.rs`, +`tests/batch3_objects.rs`. + +### 3.10 Text documents (`btds[ADBE Text Document]/LIST btdk`) + +`btdk` is not a chunk sequence but a PostScript-like dictionary (`/key value` pairs, `<< >>`, `[ ]`, +numbers, `true` / `false`, `/names`, strings as `(` + `fe ff` + UTF-16BE + `)` with `\` escapes). The +verified paths from the top level (keys `/98 /0 /1`; `RUN` = `/1/1[0]/0`): + +| What | Path | Evidence | Conf. | +|---|---|---|---| +| text | `RUN/0`; a trailing `\r` ends the paragraph. **A hard line break is `\r` too: `A\rB` is stored `A\rB\r`** | 110 (`A`), 113 (`Hello`), 243 | V | +| **U+0003 in the text** | stored as it is (`A`, U+0003, `B` is `A\u{3}B\r`), with the paragraph runs of a CR (`[2, 2]`). After Effects lays it out exactly like `A\rB` (387): two composed lines, two paragraphs, baselines at y 0 and 98 (`text.measure` in AE). So U+0003 is a line break that starts a new paragraph; the importer maps it to `\r` | 386, 387; test `etx_is_stored_as_it_is_and_splits_the_paragraph_runs` | V | +| font size | `RUN/6/0[n]/0/0/6/1` (100 by default) | 110, 113 (60) | V | +| fill colour | `RUN/6/0[n]/0/0/6/53/0/1` = `[A R G B]` floats 0..1 | 110 (white), 113 (`[1 1 0.5 0]`), 248 | V | +| **paragraph runs** | `RUN/5/0[n]/1` = characters including the `\r` (`A\rB\r`: `[2, 2]`; `Hello\r`: `[6]`) | 243, 245 | V | +| **style runs** | `RUN/6/0[n]/1` = characters per style run (`A\rB\r`: `[4]`). **A range style splits `Hello\r`: characters 1 to 3 red gives `[1, 2, 3]` with the fills white, `[1 1 0 0]`, white** | 243, 248 | V | +| **justification** | `RUN/5/0[n]/0/0/5/0`: 0 = left, **1 = right (334)**, 2 = centre, **3 = justified with the last line left, 4 = last line right, 5 = last line centred, 6 = every line justified**; the scripting enum value of right (7414) is not what is stored | 245 (0), 246 (2), 334 (1), 565 (3), 567 (4), 566 (5), 568 (6) | V | +| **character settings (S17)** | one `text.set_style` change each against the point text 538 (`HHHH`, Times New Roman 100 px, normal baseline), the slot named is the only one that changes: `/6` horizontal scale as a factor (539: 1.0 -> 0.9), `/7` vertical scale (540: 1.5), `/9` baseline shift in px (541: 41), `/11` automatic kerning **0 none, 1 metrics (default), 2 optical** (542, 543), `/18` ligatures (off by default, 555; switching ligatures off in 551 changes nothing), `/35` baseline direction **1 with the stream (default), 2 rotated (573), 3 across the stream / tate-chu-yoko (576)**, `/36` tsume as a fraction (553: 0.5), `/52` no break (552), `/56` fill drawn (on by default, 546), `/57` stroke drawn (off by default, 544), `/58` **stroke over fill (on by default: 547 setting it on changes nothing, 550 setting it off gives false)**, `/62` line join **0 miter, 1 round** (548), `/63` stroke width in px (**1.0 by default**, 545: 5), `/70` digit set **0 default, 1 Arabic (571), 2 Hindi (578)**; with digit set Arabic the text `1234` has the same layer bounds as with the default (S17, not saved) | 538-578, 595, 596; tests `tests/text_style_slots.rs` | V | +| **manual kerning** | `RUN/8/0` (beside the style runs): one entry `<< /0 << /0 amount >> /1 length >>` per run of characters, amount in 1/1000 em; kerning 50 on `HHHH` gives four entries of length 1 with 50 and one for the closing `\r` without an amount, `RUN/7` = 50, and switches automatic kerning `/11` to 0 | 554 | V | +| **paragraph settings (S17)** | `RUN/5/0[n]/0/0/5/`, one change each against 538: `/1` first-line indent (560: 20), `/2` start indent (561: 30), `/3` end indent (562: 40), `/4` space before (563: 10), `/5` space after (564: 12), all in px; `/8` leading model **0 Roman, 1 Japanese** (572); `/9` automatic hyphenation (**on by default**, 556 off); `/21` Roman hanging punctuation (558); `/29` **every-line composer, off by default** (559 on; 557 setting it off changes nothing, so a new text uses the single-line composer); `/33` direction **0 left to right, 1 right to left** (569). Setting the Universal composer (570) changes nothing; the Latin/CJK composer cannot be set by script | 556-572 | V | +| **vertical text** | `lineOrientation` vertical right to left adds `/0/8/0[0]/0/2/1` = 2 to the frame dictionary (absent for horizontal text) | 575 | V | +| **box (paragraph) text** | frame dictionary `/0/8/0[0]/0`: `/1/0` = 32 floats = 16 x, y pairs tracing the rectangle (corners `[-200,-100] [200,-100] [200,100] [-200,100]`), `/2/0` = 1; both keys are absent for point text. Alignment changes only the glyph geometry, not the frame | 245, 246 (box 400 x 200, top-left `[-200, -100]`), 247 (point text: absent) | V | +| **tracking** | `RUN/6/0[n]/0/0/6/8` = 0, 100 in 247 | 247 | V | +| **faux bold / faux italic** | style slots `.../6/2` and `.../6/3`, `false` -> `true`; the font style stays Regular. **Side effect: the font list `/0/1/0` gains a new first entry (4 -> 5 fonts) with property `/3` = 2 (bold) or 1 (italic), the old entries shift up and the style's font index `/6/0` becomes 1** | 335, 336 | V | +| **caps** | style slot `.../6/12`: 0 normal, **1 small caps, 2 all caps** | 337, 338 | V | +| **superscript / subscript** | style slot `.../6/13`: **1 superscript, 0 normal, 2 subscript** (the only slot that changes between 526, 527 and 528). After Effects lays superscript and subscript out at 58.3 % of the size, 33.3 % of the size above / below the baseline: `HHHH` in Times New Roman 100 px is 288.9 px wide with its baseline at 0 when normal, 168.4 px with its baseline at -33.3 / +33.3 when superscript / subscript (`text.measure`, layer bounds). **Every scripted text of the corpus is superscript** (526: the character state After Effects was in; 243, 517 and the reference 244 too), which is why this slot never showed up as undecoded | 526-528, 243, 517 | V | +| **wrapping box text** | a 600 x 400 box at `[-300, -200]` (as in 245) with a sentence of 70 characters: the document holds the text, size and box only; After Effects composes four lines (`The quick brown fox ` / `jumps over the lazy dog ` / `and keeps running far ` / `away`), the line breaks are not stored | 517 | V | +| **leading** | style slot `.../6/5`: the scripted samples have the explicit leading 98.0 (100 px Times New Roman; `/4` false), leading 60 is 60.0; with automatic leading on, 400 stores 0.01 (see "automatic leading" below) | 339, 400 | V | +| **last run** | the last style run reaches the paragraph end and includes the final `\r` (two range styles on `Hello`: runs `[1, 2, 3]`, fills white / `[1 1 0 0]` / `[1 0 0 1]`, sizes 100 / 100 / 60) | 340 | V | +| font | `.../6/0` = index into the font list `/0/1/0[i]/0/0/0` (`TimesNewRomanPSMT`, ...). The list always holds entries no run uses (`Myriad-Roman`, `MyriadPro-Regular`, `AdobeInvisFont`), so only the fonts the runs point at matter | 110, 335 (index 1 is still `TimesNewRomanPSMT`) | E | +| **stroke colour** | `.../6/54/0/1` = `[A R G B]`, the fill's layout; white in the untouched samples, red `[1 1 0 0]` in 574, blue in 595. The stroke switch, width and order are slots `/57`, `/63`, `/58` (see "character settings") | 110, 113, 574, 595 | V | +| **automatic leading** | style slot `.../6/4`: `true` = automatic leading (lines advance by 1.2 x the size; `/5` is then not used), `false` = `/5` is the leading. **243: `/4` false, `/5` 98, the second line's baseline is stored 98 px below the first (`/1/1[0]/1/2[0]/6[0]/6[0]/6[0]/6[1]/0/0[1]`)**. **400 (Auto Leading switched on for `A` CR `B`, size 100, leading 98; against its unedited save 399): the run style changes in `/4` (false -> true) and `/5` (98 -> 0.01) only, the stored second baseline moves from 98 to 120 px below the first (1.2 x 100), and After Effects measures the same 120 px (`text.measure`)**; the rest of the diff is save noise (`head`, the comp's modification time, the text's `btgu/pgui`). That `/5` holds 0.01 under automatic leading is seen in 400 only | 243, 339 (`/5`); 400 (`/4`); test `automatic_leading_is_slot_4` | V | +| **undecoded slots** | the run style and paragraph dictionaries of an untouched document (244; 110 stores the same bytes) are the reference: a slot that is not decoded and differs from it is listed (`TextDocument::undecoded_style_fields`, `undecoded_paragraph_fields`); a slot the reference lacks is listed only when it is not 0, `false`, empty or `/nil` (a neutral value is taken to carry nothing, so it is not reported as a loss; `/nil` is how 244 stores its paragraph slots `/27`, `/28` and `/36`). Decoded style slots: `/0 /1 /2 /3 /4 /5 /6 /7 /8 /9 /11 /12 /13 /18 /35 /36 /52 /53 /54 /56 /57 /58 /62 /63 /70`; paragraph slots: `/0 /1 /2 /3 /4 /5 /8 /9 /21 /29 /33`. Not found by any scriptable setting (none of the `text.set_style` attributes tried in S17 changes them): style `/20 /38 /78 /87 /88`, paragraph `/31 /32`. **Paragraph `/24`, `/35` and style `/68`** (1, 1 and 0 in a scripted text) were edited in place in the wrapping box text 517 (732: `/24` 0, 733: `/35` 0, 734: `/68` 1, same length); After Effects opens each without a dialog, keeps the value on a re-save and composes the same four lines, baselines and bounds (`text.measure`, `layer.bounds`; 734 renders like 517), so 0 and 1 are not listed (`NEUTRAL_PARAGRAPH_VALUES`, `NEUTRAL_STYLE_VALUES`; their meaning stays unknown, Latin text only). **Paragraph `/34`** is 0 in a scripted text and 7 after Reset Paragraph (727: the only slot that changes); a justified 600 px box text of 88 characters composes the same four lines, baselines and bounds with both values (S18), so 0 and 7 are not listed (`NEUTRAL_PARAGRAPH_VALUES`), other values are | every text sample lists none; 725, 727 | V (reference), E (/34) | +| **Source Text record** | the `tdbs` in `btds[ADBE Text Document]` (next to the `btdk`) has no keys and no expression in every sample; Source Text keyframes (presumably one `btdk` per key) and expressions were not sampled, the reader only reports them (`Layer::source_text_property`, `Layer::text_document_count`) | 110-114, 243-248, 334-340 | E | + +API: `TextDocument` (`paragraphs`, `style_runs`, `text_box`, `paragraph_texts`, `font_of`, +`incomplete_runs`, `undecoded_style_fields`, `undecoded_paragraph_fields`, `kerning`, +`line_orientation`), `StyleRun::{faux_bold, faux_italic, caps, auto_leading, leading, stroke_argb, +font_index, horizontal_scale, vertical_scale, baseline_shift, auto_kern, ligatures, +baseline_direction, tsume, no_break, apply_fill, apply_stroke, stroke_over_fill, line_join, +stroke_width, digit_set}`, `ParagraphRun::{first_line_indent, start_indent, end_indent, space_before, +space_after, leading_type, auto_hyphenate, hanging_roman, every_line_composer, direction}`, `Caps`, +`AutoKern`, `KernRun`, `Justification`. +A damaged run is never dropped silently: a run without a readable length is left out, a run with a +missing size, fill or font index takes them from the run before it, and both count in +`incomplete_runs`. Tests: `tests/text_markers_footage.rs`, `tests/batch3_objects.rs`, +`tests/text_fields.rs`. + +### 3.11 Markers + +`mrst[ADBE Marker]` holds a `tdbs` with a `list` of 16-byte records (the times; `tdb4` byte 12 is the +time scale) and one `LIST mrky/LIST Nmrd` per marker. Layer markers live in the layer's own tree, +composition markers in the `SecL` list named `Markers`. + +| What | Chunk path | Meaning | Evidence | Conf. | +|---|---|---|---|---| +| time | the key list | 25 600 = 1 s | 122, 123, 249 | V | +| **duration** | `Nmrd/NmHd` (20 bytes: u32 4, u32 0, u32 duration, u32 600, u32 0) | duration / 600 = the marker duration in seconds (1 s is 600; 0 for none); 600 is the units per second; **0.5 s and 0.3 s read back exactly (509, 510)** | 249 (1 s), 122 (0), 509, 510 | V | +| **several markers** | the key records and the `Nmrd` lists in the same (time) order: 509 has two composition markers, 1 s `M1` label 2 and 2.5 s `M2` duration 0.5; a fractional time is a plain key time (0.52 s = 13 312 / 25 600, 510) | | 509, 510; test `tests/batch5.rs` | V | +| **strings** | five `Utf8` children of `Nmrd`, in the order **comment, chapter, URL, frame target, cue point name**; unused ones are empty | `LM`, `Chap`, `http://a.example/u`, `_blank`, `CueX` | 249 | V | +| **cue type** | `NmHd` u32 @0: **4 = event cue (also for markers without a cue point name), 5 = navigation cue** | 347 (4), 348 (5) | V | +| **cue parameters** | `NmHd` u32 @4 = the number of key / value pairs; the pairs follow the five fixed strings as `2 x pairs` extra `Utf8` (key, value, key, value): `speaker` = `A`, `n` = `2` with the cue point name `CueE` | 349 | V | +| **label** | `NmHd` u8 @16 (followed by three pad bytes): label 3 is `03 00 00 00`. The label is not in the keyframe flags (unlike the keyframe label of 057) | 347 | V | + +API: `Marker::{label, cue_type, cue_params}`, `CueType`. Tests: `tests/text_markers_footage.rs`, +`tests/batch3_objects.rs`. + +### 3.12 Cameras and lights + +Both have no source item (`ldta@40` is 0 for a camera, `0xffff_ffff` for a light), type 2 or 1, the 3D +bit and byte 38 bit `0x40` (3.1); `ldta@136` is the light type. Their properties sit in the same +groups as on other layers, with these conventions: + +| What | Path | Stored | Evidence | Conf. | +|---|---|---|---|---| +| camera Position, default (auto state) | `ADBE Transform Group/ADBE Position`, `tdb4` 76 and 77 = 1 although no expression exists | `[0, 0, -2666.67]` (x and y are 0 whatever the composition size; z = -zoom). A **one-node** camera reports `[0, 0, -2666.67]` (251). **Correction (S16): a reopened two-node camera reports `[0, 0, -2666.67]` too (256 read back), and After Effects renders it there**: the default two-node camera of 537 above the 3D solid of 486 renders from `[0, 0, -2666.67]` towards the point of interest, not like the composition's default view (537 differs from 486 in 24 % of the grid points, and EffectCraft's import with the stored position matches 537 but for 4 edge points). The `[960, 540, ...]` of the batch-3 notes was not reproduced (535 and 537, created by script, read back the stored value too); `CameraPosition::reported` keeps the old rule and is marked as contradicted | 256, 251, 537 | V | +| camera Position, set by the user | same, `tdb4` 76 and 77 = 0 | the absolute value `[100, 200, -1000]` | 253 | V | +| camera point of interest | `ADBE Anchor Point` | `[960, 540, 0]` in **pixels** (not a fraction); the record's `tdsb` is 1 on a two-node and 3 on the one-node camera (not asserted) | 251, 253, 256 | V (value), E (`tdsb`) | +| light Position, default | same as the camera | `[0, 0, -1333.33]`, as After Effects reports it (255 read back); the point of interest `[960, 540, 0]` | 254, 255 | V | +| light intensity | `ADBE Light Options Group/ADBE Light Intensity` | f64 50.0 percent, `tdsb` 1; absent at the default 100 | 254 (50), 252 (absent) | V | +| light type | `ldta@136` | 1 spot, 2 point | 254, 252 | V | +| **camera Zoom** | `ADBE Camera Options Group/ADBE Camera Zoom` | plain pixels (`tdsb` 1), absent at the default 2 666.67; the auto Position keeps `[0, 0, -2666.67]` and is not recomputed from the zoom | 341 (2000) | V | +| **camera depth of field** | same group: `ADBE Camera Depth of Field` 1.0 (checkbox descriptor `ffff0004`), `ADBE Camera Focus Distance` 800, `ADBE Camera Aperture` 30 (plain numbers), all `tdsb` 1. **Defaults (256 read back): Depth of Field off, Focus Distance = Zoom = 2 666.67, Aperture 25.309 336 332 958 4, Blur Level 100** | 342, 256 | V | +| **light Casts Shadows** | `ADBE Light Options Group/ADBE Casts Shadows` | a set record (`tdsb` 1) holding 0.0 (off) in every light | 252, 254, 255 | V | +| **3D rotations** | `ADBE Rotate X`, `ADBE Rotate Y` | plain degrees, absent at 0 | 486, 487 | V | +| **Orientation** | `LIST otst` = `tdbs` + `LIST otky/otda`: `otda` is three big-endian `f64` degrees; absent at `[0, 0, 0]`. Keyed orientation is not sampled | 488, 485 | V | +| **light colour** | `ADBE Light Options Group/ADBE Light Color` | ARGB doubles 0..255 (`[255, 255, 0, 0]` for red; 4 components, descriptor `0002ffff`), absent = white | 343 | V | +| **light cone** | same group: `ADBE Light Cone Angle` 60 and `ADBE Light Cone Feather 2` 30 (percent), each `tdsb` 1 and absent in the default spot light (90 and 50). Every point light stores them as `tdsb` 3 records with 90 and 50 (a point light created directly equals the converted one of 252, so the "odd" property set is not a conversion artefact) | 344, 345, 346, 252 | V | + +A point light made by converting a spot light has a different property set (`Orientation`, `Rotate +X/Y/Z`, `Cone Angle`, `Cone Feather 2` in the default state) that a spot light lacks (252); whether that +is an artefact of the conversion is untested. API: `Layer::camera_position`, +`CameraPosition::reported`, `Layer::camera_point_of_interest`, `Layer::light_intensity`, +`Layer::{camera_zoom, camera_depth_of_field, camera_focus_distance, camera_aperture, light_color, +light_cone_angle, light_cone_feather}`, `DEFAULT_CAMERA_ZOOM` (2 666.67 is verified for the 1920 px +composition only), `Layer::orientation` (`Orientation`; test `orientation_is_otst_otda` in +`tests/batch5.rs`). Render checks against After Effects (20 px grid, 5 184 points): 486 1 point +off, 535 2, 536 0, 537 4 (anti-aliased edges); **488 (Orientation `[10, 20, 30]`): 272 points +(5.25 %) differ; the import carries the stored angles, and permuted or negated inputs match worse +(6.2 % to 34 %), so the cause is in EffectCraft's renderer and not isolated.** Tests: `tests/layer_switches.rs`, `tests/batch3_objects.rs`. + +### 3.12a Project settings (top-level chunks; cases 620-634) + +Each case is the base reopened and saved with one setting changed (`project.set_settings`), compared +with 620 (the base saved the same way); apart from the save noise (`head` byte 19, `nhed` / `nnhd` +bytes 20-27 / 28-35, `fdta`) only the bytes below changed. + +| setting | where | stored | cases | conf | +|---|---|---|---|---| +| colour depth | `nhed` byte 15 (and `nnhd` byte 24) | 0 = 8, 1 = 16, 2 = 32 bits per channel (the base is 32) | 620, 621, 622, 631 | V | +| working space | `cpid` (16 bytes) and the `Utf8` right after `PwCs` | None: `cpid` all `0xff` and the JSON `{}`; a profile: JSON `{"baseColorProfile":{"colorProfileData":"","colorProfileName":""},"baseProfileType":2}` (`sRGB IEC61966-2.1` in the base, `Rec.709 Gamma 2.4` in 624) and `cpid` a 16-byte id of the profile; After Effects 26.2.1 leaves `colorProfileName` out in a fresh save (settings-c), and the name is then the profile's ICC `desc` tag (v2 `desc` or v4 `mluc`) | 620, 623, 624, 631, 902 | V (None, the name), ? (`cpid`) | +| working gamma | `dwga` `u32` @0 | 0 = 2.2, 1 = 2.4 | 625, 631 | V | +| Linearize Working Space | `lnrp` (1 byte, 1) inserted after `cpid` | absent when off | 626, 632 | V | +| Blend Colors Using 1.0 Gamma | `lnrb` (1 byte, 1) inserted after `cpid`, before `lnrp` | absent when off | 627, 632 | V | +| Compensate for Scene-referred Profiles | `acer` byte 0 | 1 on (base), 0 off | 628 | V | +| time display | `nhed` (and `nnhd`) byte 8 | 0 timecode, 1 frames; feet + frames: byte 8 = 1 and byte 11 = 1, byte 13 = frames per foot (16 = 35 mm, 40 = 16 mm; the base holds 16) | 629, 633, 634 | V | +| frame count start | `nhed` byte 14 (`nnhd` byte 20) | 2 for a count from 0 (base), 1 for a count from 1 | 630 | E (one value each) | + +The audio sample rate of the project is `adfr` (`f64` 48 000 in every case, not varied). API: +`ProjectSettings::read` (`TimeDisplay`, `WorkingSpace`). Test: `tests/it/container/cases_600.rs`. The +fixture of 624 is not in the repository: its working-space JSON holds the profile data After +Effects embeds for that space. + +### 3.12b Layer styles (`tdgp[ADBE Layer Styles]`; cases 950-980) + +Every layer's root group holds `ADBE Layer Styles` (third, after Time Remapping and Transform), also +when no style is used (950). Inside: `ADBE Blend Options Group` (Global Light Angle `ADBE Global +Angle2`, Altitude `ADBE Global Altitude2`, and `ADBE Adv Blend Group` with `ADBE Layer Fill +Opacity2`, `ADBE R/G/B Channel Blend`, `ADBE Blend Interior`, `ADBE Blend Ranges`; 977), then one +switch group per style, `