mirror of
https://github.com/storytold/effectcraft.git
synced 2026-12-05 05:23:39 -05:00
Merge main into fix/plugin-library-file-url-unc
This commit is contained in:
commit
765fd76552
798 files changed
+91231
-51980
No files matched your search
+6
-6
@@ -1,6 +1,6 @@
|
||||
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
|
||||
reviews:
|
||||
auto_review:
|
||||
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
|
||||
ignore_usernames:
|
||||
- "dependabot[bot]"
|
||||
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
|
||||
reviews:
|
||||
auto_review:
|
||||
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
|
||||
ignore_usernames:
|
||||
- "dependabot[bot]"
|
||||
@@ -1,3 +1,14 @@
|
||||
# Minimum cargo-nextest for this repository: GHSA-vc25-qg58-w57c is fixed in 0.9.150 and CI
|
||||
# installs exactly that version, so an older nextest refuses to run (exit 92 REQUIRED_VERSION_NOT_MET).
|
||||
nextest-version = "0.9.150"
|
||||
|
||||
[test-groups]
|
||||
gpu = { max-threads = 1 }
|
||||
|
||||
# Coverage runs each test in a separate process, so the GPU suite's in-process lock
|
||||
# cannot protect software adapters from competing devices and readback timeouts.
|
||||
# UI harnesses can create a device lazily when rendering a screenshot, so include
|
||||
# the whole UI package instead of an incomplete list of GPU-named tests.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(effectcraft-gpu) | package(effectcraft-ui-egui) | package(effectcraft-sam2) | (package(effectcraft-cli) & test(/^cli::gpu_adapter_name_/))'
|
||||
test-group = 'gpu'
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
# A nightly dry run on main: every release build except macOS, nothing signed or released
|
||||
# (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
|
||||
schedule:
|
||||
- cron: "32 1 * * *"
|
||||
push:
|
||||
branches: [release]
|
||||
workflow_dispatch:
|
||||
@@ -15,16 +19,25 @@ 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
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: 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 }}
|
||||
|
||||
+11
-11
@@ -1,11 +1,11 @@
|
||||
*~
|
||||
plan/
|
||||
target/
|
||||
/dist
|
||||
/log
|
||||
.DS_Store
|
||||
.claude/worktrees/
|
||||
__pycache__/
|
||||
|
||||
# After Effects test corpus fetched by `cargo xtask aep-corpus`
|
||||
/corpus/
|
||||
*~
|
||||
plan/
|
||||
target/
|
||||
/dist
|
||||
/log
|
||||
.DS_Store
|
||||
.claude/worktrees/
|
||||
__pycache__/
|
||||
|
||||
# After Effects test corpus fetched by `cargo xtask aep-corpus`
|
||||
/corpus/
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"effectcraft": {
|
||||
"command": "cargo",
|
||||
"args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--demo"]
|
||||
},
|
||||
"effectcraft-app": {
|
||||
"command": "cargo",
|
||||
"args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--bridge", "9877"]
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
"mcpServers": {
|
||||
"effectcraft": {
|
||||
"command": "cargo",
|
||||
"args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--demo"]
|
||||
},
|
||||
"effectcraft-app": {
|
||||
"command": "cargo",
|
||||
"args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--bridge", "9877"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,147 +1,210 @@
|
||||
# EffectCraft — rules for agents and contributors
|
||||
|
||||
These rules apply to every human and AI contributor. `CLAUDE.md` holds the working instructions; this
|
||||
file holds the rules that must never be broken. When the two disagree, this file wins.
|
||||
|
||||
## Never crash
|
||||
|
||||
People trust EffectCraft with hours of work. A malformed project, PSD, SVG, Lottie or media file, a bad
|
||||
expression or script, a broken plug-in, a bad control-channel or MCP argument, a corrupt preferences file
|
||||
or a full disk must produce an error the user (or agent) can act on, never a crash and never lost work.
|
||||
**This rule outranks feature work:** don't ship a feature by adding a panic path, and fix a crash before
|
||||
building on top of it.
|
||||
|
||||
- **Fail with `Result<T, E>`** through the crate's error type and propagate with `?`; add context
|
||||
(`map_err`, an error variant) rather than discarding it. Lenient readers fall back and record the repair.
|
||||
- **No panicking shortcuts in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`,
|
||||
`todo!` or `unimplemented!`. Use `?`, `ok_or(..)?`, `let … else`, `if let`, or `unwrap_or*` where a
|
||||
fallback is genuinely correct (never where it would silently corrupt a document). Unfinished features
|
||||
return an "unsupported" error. The only exception is a provably infallible literal, written as
|
||||
`#[allow(clippy::expect_used)]` + `.expect("why this cannot fail")`.
|
||||
- **No `unsafe`** (`unsafe_code = "forbid"` for the workspace).
|
||||
- **Every input-derived number is hostile.** Use `get()` instead of `[i]`/`[a..b]` when the position
|
||||
comes from a file, a user, an agent or arithmetic on those; slice strings only at char boundaries; use
|
||||
checked or saturating arithmetic for lengths, offsets and counts; guard division by zero and NaN/inf
|
||||
casts; cap allocations sized by input.
|
||||
- **Bound recursion:** projects, precomps, expressions and SVG/PSD trees can be cyclic or deeply nested;
|
||||
walk them with seen-sets or depth limits.
|
||||
- **Don't cascade:** handle lock poisoning (`lock().unwrap_or_else(PoisonError::into_inner)` or an
|
||||
error), and treat worker-thread join results as `Result`s.
|
||||
- **Last-resort guard:** the app wraps command execution and file import/export in a panic hook /
|
||||
`catch_unwind` boundary that turns an escaped panic into an error and keeps the document. It is a
|
||||
safety net, not a substitute for the rules above; keep `panic = "unwind"`.
|
||||
- **Prove it:** every crash fix comes with a small synthetic regression test that panicked before the fix.
|
||||
|
||||
Tests, benches, fuzz targets and `xtask` may `unwrap()`; `clippy.toml` allows it in tests. Crates that are
|
||||
clean carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented,
|
||||
clippy::todo, clippy::unreachable)]`; new crates start with it.
|
||||
|
||||
## 1. Assets: no Adobe artwork, every asset licensed and attributed
|
||||
|
||||
This rule is absolute. Breaking it is the most serious mistake a contributor can make on this project.
|
||||
|
||||
**What counts as an asset:** any image, icon, cursor, logo, illustration, screenshot, font, colour LUT,
|
||||
preset, template, sound, music, video, 3D model, or other non-code media. This covers files in the
|
||||
repository, bytes embedded in code (`include_bytes!`, base64, data URIs), and data hard-coded to
|
||||
reproduce an image (for example, point lists traced from someone else's icon).
|
||||
|
||||
1. **Never use Adobe iconography, images or other Adobe assets**, in any form:
|
||||
- no icons, cursors, logos, splash screens, UI artwork or screenshots from any Adobe product;
|
||||
- no Adobe fonts, LUTs, presets, templates, sound effects, stock media or sample projects;
|
||||
- no traced, redrawn, recoloured or "inspired-by" copies of Adobe icons. Our icons may follow generic
|
||||
conventions (a play triangle, a razor blade, a stopwatch), but each must be drawn from scratch
|
||||
without reference to Adobe's artwork.
|
||||
2. **Every asset must be open**: open-source licensed (MIT, Apache-2.0, BSD, ISC, zlib, SIL OFL…),
|
||||
public domain / CC0, or Creative Commons (CC BY or CC BY-SA; no NC/ND licences), **or** created by a
|
||||
contributor who owns it and licenses it to the project under the project licence (MIT OR Apache-2.0).
|
||||
If the licence is unknown or unclear, the asset does not go in.
|
||||
3. **Every asset needs an attribution sidecar.** Next to each asset file `X`, add `X.attribution` with:
|
||||
```text
|
||||
asset: <file name>
|
||||
title: <what it is>
|
||||
author: <creator / copyright holder>
|
||||
source: <URL, or "original work" for contributor-made assets>
|
||||
license: <SPDX id or licence name>
|
||||
license-file: <path to the licence text, if the licence requires shipping it>
|
||||
added: <YYYY-MM-DD> by <contributor>
|
||||
notes: <how it was made or modified; for screenshots, what is shown>
|
||||
```
|
||||
Also add one line for the asset to [`ATTRIBUTION.md`](ATTRIBUTION.md). `cargo xtask assets` (part of
|
||||
`cargo xtask ci`) fails if any asset lacks a sidecar or index entry.
|
||||
4. **Screenshots** in the repo may show only EffectCraft (or other open projects), with media we generated
|
||||
or media that is itself openly licensed. Never commit screenshots of Adobe products.
|
||||
5. **Local reference material stays local.** After Effects reference screenshots and notes live only in
|
||||
`plan/aftereffects/` (gitignored). They must never be committed, bundled, embedded, traced or shipped.
|
||||
6. **Code-drawn assets** (icons in `crates/ui-egui/src/icons.rs`, procedural demo content in
|
||||
`crates/engine/src/demo.rs`, generators in `crates/effects`) are original work under the project licence
|
||||
and are listed in `ATTRIBUTION.md`.
|
||||
7. **When in doubt, leave it out** and draw or generate it yourself.
|
||||
8. **The one exception: first-party ArtCraft brand marks.** The ArtCraft name and logos in `docs/brand/`
|
||||
are trademarks of the ArtCraft Team, not open source, usable only unmodified and only in the context of
|
||||
EffectCraft under `docs/brand/LICENSE-brand.txt` (forks and modified versions must remove them). They still
|
||||
need a sidecar and an `ATTRIBUTION.md` row (licence `LicenseRef-ArtCraft-Trademark`). No other
|
||||
non-open asset is allowed, and this exception never covers third-party marks (Adobe, Discord, GitHub
|
||||
and other logos stay out; draw a generic icon instead).
|
||||
|
||||
## 2. Clean-room code
|
||||
|
||||
- Never read, disassemble or copy anything inside Adobe application bundles; file names and listings only.
|
||||
Observe behaviour by using the app; never capture its Home screen, recent projects, account info or
|
||||
file browsers.
|
||||
- Never copy GPL/LGPL/AGPL code (FFmpeg, Natron, Blender, Glaxnimate, Synfig, Friction, Olive, MLT, frei0r, G'MIC…).
|
||||
- Never read or copy Adobe expression/scripting implementations, `.ffx` presets or effect plug-ins; the public Expression Language Reference and Scripting Guide describe *behaviour* only.
|
||||
- Implement codecs and formats from public specifications (ITU-T/ISO/IEC standards, IETF RFCs, the VP9
|
||||
and AV1 bitstream specs, SMPTE documents, published container specs). Do not read the source of
|
||||
reference or third-party decoders/encoders while implementing a format, even permissively licensed
|
||||
ones (libvpx, libopus, libaom, dav1d, openh264…); spec text and conformance vectors only. Record the
|
||||
spec edition used in the crate README.
|
||||
- ffmpeg/ffprobe may be used only as external test oracles and fixture generators. They are never
|
||||
linked, bundled or shipped.
|
||||
- Dependencies must use permissive licences: MIT/Apache-2.0/BSD/ISC/Zlib/Unicode/CC0/BSL-1.0, or
|
||||
MPL-2.0 used unmodified.
|
||||
|
||||
## 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.
|
||||
|
||||
- **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).
|
||||
Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified,
|
||||
as PhotoCraft does with `cargo xtask corpus`.
|
||||
|
||||
|
||||
## See also
|
||||
|
||||
- [ROADMAP.md](ROADMAP.md): stage, headline numbers and what's next
|
||||
- [docs/gaps.md](docs/gaps.md): every known shortfall against After Effects, ranked, and the prioritised workstreams (G1–G9); read it before choosing work
|
||||
- [docs/target-app-parity.md](docs/target-app-parity.md): the parity numbers and how they were measured, with the per-area docs it links (UI, file formats, hardware, localization, effects, scripting)
|
||||
- [CONTRIBUTING.md](CONTRIBUTING.md): setup, gates, commits, how to add things
|
||||
- [docs/architecture.md](docs/architecture.md): layers, data model, commands, pipeline
|
||||
- [docs/testing.md](docs/testing.md): oracle tests, criteria, benchmarks
|
||||
- [docs/agents.md](docs/agents.md): driving EffectCraft over MCP / the control channel, and the agent work loop
|
||||
- [docs/control-protocol.md](docs/control-protocol.md): control-channel method reference
|
||||
- [docs/contributors.md](docs/contributors.md): the About window's contributor and model credits
|
||||
- [ATTRIBUTION.md](ATTRIBUTION.md): asset index
|
||||
|
||||
## Contributor credits (About window)
|
||||
|
||||
- About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json`
|
||||
(commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for
|
||||
themselves). See `docs/contributors.md`.
|
||||
- **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub
|
||||
username has a `[people.<username>]` entry in `contributors/people.toml`. If not, ask them once
|
||||
whether they want to be credited by more than their username: a real name, a display name, and/or
|
||||
their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry
|
||||
(copy the template at the top of the file)
|
||||
and include it in their PR, committed as them. If no, change nothing: they are credited as
|
||||
`@username` anyway.
|
||||
- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or
|
||||
GitHub profiles). Never hand-edit `contributors.json`.
|
||||
|
||||
## 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.
|
||||
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
|
||||
## House rules
|
||||
|
||||
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
|
||||
|
||||
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
|
||||
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
|
||||
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
|
||||
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
|
||||
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
|
||||
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
|
||||
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
|
||||
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
|
||||
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
|
||||
10. **Keep secrets and personal details out** of the repository, logs and requests.
|
||||
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
|
||||
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
|
||||
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
|
||||
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
|
||||
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
|
||||
<!-- craft-house-rules:end -->
|
||||
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
|
||||
## Rust Craft repositories
|
||||
|
||||
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
|
||||
|
||||
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
|
||||
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
|
||||
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
|
||||
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
|
||||
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
|
||||
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
|
||||
|
||||
## Licence allowlist
|
||||
|
||||
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
|
||||
|
||||
- `ISC`
|
||||
- `MIT`
|
||||
- `BSD-2-Clause`
|
||||
- `BSD-3-Clause`
|
||||
- `Apache-2.0`
|
||||
- `OFL-1.1`
|
||||
- `Ubuntu-font-1.0`
|
||||
- `Bitstream-Vera`
|
||||
- `CC0-1.0`
|
||||
- `CC-BY-4.0`
|
||||
- `CC-BY-SA-4.0`
|
||||
- `LicenseRef-Public-Domain`
|
||||
|
||||
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
|
||||
<!-- craft-house-rules:end -->
|
||||
|
||||
# EffectCraft — rules for agents and contributors
|
||||
|
||||
These rules apply to every human and AI contributor. `CLAUDE.md` holds the working instructions; this
|
||||
file holds the rules that must never be broken. When the two disagree, this file wins.
|
||||
|
||||
## Never crash
|
||||
|
||||
People trust EffectCraft with hours of work. A malformed project, PSD, SVG, Lottie or media file, a bad
|
||||
expression or script, a broken plug-in, a bad control-channel or MCP argument, a corrupt preferences file
|
||||
or a full disk must produce an error the user (or agent) can act on, never a crash and never lost work.
|
||||
**This rule outranks feature work:** don't ship a feature by adding a panic path, and fix a crash before
|
||||
building on top of it.
|
||||
|
||||
- **Fail with `Result<T, E>`** through the crate's error type and propagate with `?`; add context
|
||||
(`map_err`, an error variant) rather than discarding it. Lenient readers fall back and record the repair.
|
||||
- **No panicking shortcuts in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`,
|
||||
`todo!` or `unimplemented!`. Use `?`, `ok_or(..)?`, `let … else`, `if let`, or `unwrap_or*` where a
|
||||
fallback is genuinely correct (never where it would silently corrupt a document). Unfinished features
|
||||
return an "unsupported" error. The only exception is a provably infallible literal, written as
|
||||
`#[allow(clippy::expect_used)]` + `.expect("why this cannot fail")`.
|
||||
- **No `unsafe`** (`unsafe_code = "forbid"` for the workspace).
|
||||
- **Every input-derived number is hostile.** Use `get()` instead of `[i]`/`[a..b]` when the position
|
||||
comes from a file, a user, an agent or arithmetic on those; slice strings only at char boundaries; use
|
||||
checked or saturating arithmetic for lengths, offsets and counts; guard division by zero and NaN/inf
|
||||
casts; cap allocations sized by input.
|
||||
- **Bound recursion:** projects, precomps, expressions and SVG/PSD trees can be cyclic or deeply nested;
|
||||
walk them with seen-sets or depth limits.
|
||||
- **Don't cascade:** handle lock poisoning (`lock().unwrap_or_else(PoisonError::into_inner)` or an
|
||||
error), and treat worker-thread join results as `Result`s.
|
||||
- **Last-resort guard:** the app wraps command execution and file import/export in a panic hook /
|
||||
`catch_unwind` boundary that turns an escaped panic into an error and keeps the document. It is a
|
||||
safety net, not a substitute for the rules above; keep `panic = "unwind"`.
|
||||
- **Prove it:** every crash fix comes with a small synthetic regression test that panicked before the fix.
|
||||
|
||||
Tests, benches, fuzz targets and `xtask` may `unwrap()`; `clippy.toml` allows it in tests. Crates that are
|
||||
clean carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented,
|
||||
clippy::todo, clippy::unreachable)]`; new crates start with it.
|
||||
|
||||
## 1. Assets: no Adobe artwork, every asset licensed and attributed
|
||||
|
||||
This rule is absolute. Breaking it is the most serious mistake a contributor can make on this project.
|
||||
|
||||
**What counts as an asset:** any image, icon, cursor, logo, illustration, screenshot, font, colour LUT,
|
||||
preset, template, sound, music, video, 3D model, or other non-code media. This covers files in the
|
||||
repository, bytes embedded in code (`include_bytes!`, base64, data URIs), and data hard-coded to
|
||||
reproduce an image (for example, point lists traced from someone else's icon).
|
||||
|
||||
1. **Never use Adobe iconography, images or other Adobe assets**, in any form:
|
||||
- no icons, cursors, logos, splash screens, UI artwork or screenshots from any Adobe product;
|
||||
- no Adobe fonts, LUTs, presets, templates, sound effects, stock media or sample projects;
|
||||
- no traced, redrawn, recoloured or "inspired-by" copies of Adobe icons. Our icons may follow generic
|
||||
conventions (a play triangle, a razor blade, a stopwatch), but each must be drawn from scratch
|
||||
without reference to Adobe's artwork.
|
||||
2. **Every asset must be open**: open-source licensed (MIT, Apache-2.0, BSD, ISC, zlib, SIL OFL…),
|
||||
public domain / CC0, or Creative Commons (CC BY or CC BY-SA; no NC/ND licences), **or** created by a
|
||||
contributor who owns it and licenses it to the project under the project licence (MIT OR Apache-2.0).
|
||||
If the licence is unknown or unclear, the asset does not go in.
|
||||
3. **Every asset needs an attribution sidecar.** Next to each asset file `X`, add `X.attribution` with:
|
||||
```text
|
||||
asset: <file name>
|
||||
title: <what it is>
|
||||
author: <creator / copyright holder>
|
||||
source: <URL, or "original work" for contributor-made assets>
|
||||
license: <SPDX id or licence name>
|
||||
license-file: <path to the licence text, if the licence requires shipping it>
|
||||
added: <YYYY-MM-DD> by <contributor>
|
||||
notes: <how it was made or modified; for screenshots, what is shown>
|
||||
```
|
||||
Also add one line for the asset to [`ATTRIBUTION.md`](ATTRIBUTION.md). `cargo xtask assets` (part of
|
||||
`cargo xtask ci`) fails if any asset lacks a sidecar or index entry.
|
||||
4. **Screenshots** in the repo may show only EffectCraft (or other open projects), with media we generated
|
||||
or media that is itself openly licensed. Never commit screenshots of Adobe products.
|
||||
5. **Local reference material stays local.** After Effects reference screenshots and notes live only in
|
||||
`plan/aftereffects/` (gitignored). They must never be committed, bundled, embedded, traced or shipped.
|
||||
6. **Code-drawn assets** (icons in `crates/ui-egui/src/icons.rs`, procedural demo content in
|
||||
`crates/engine/src/demo.rs`, generators in `crates/effects`) are original work under the project licence
|
||||
and are listed in `ATTRIBUTION.md`.
|
||||
7. **When in doubt, leave it out** and draw or generate it yourself.
|
||||
8. **The one exception: first-party ArtCraft brand marks.** The ArtCraft name and logos in `docs/brand/`
|
||||
are trademarks of the ArtCraft Team, not open source, usable only unmodified and only in the context of
|
||||
EffectCraft under `docs/brand/LICENSE-brand.txt` (forks and modified versions must remove them). They still
|
||||
need a sidecar and an `ATTRIBUTION.md` row (licence `LicenseRef-ArtCraft-Trademark`). No other
|
||||
non-open asset is allowed, and this exception never covers third-party marks (Adobe, Discord, GitHub
|
||||
and other logos stay out; draw a generic icon instead).
|
||||
|
||||
## 2. Clean-room code
|
||||
|
||||
- Never read, disassemble or copy anything inside Adobe application bundles; file names and listings only.
|
||||
Observe behaviour by using the app; never capture its Home screen, recent projects, account info or
|
||||
file browsers.
|
||||
- Never copy GPL/LGPL/AGPL code (FFmpeg, Natron, Blender, Glaxnimate, Synfig, Friction, Olive, MLT, frei0r, G'MIC…).
|
||||
- Never read or copy Adobe expression/scripting implementations, `.ffx` presets or effect plug-ins; the public Expression Language Reference and Scripting Guide describe *behaviour* only.
|
||||
- Implement codecs and formats from public specifications (ITU-T/ISO/IEC standards, IETF RFCs, the VP9
|
||||
and AV1 bitstream specs, SMPTE documents, published container specs). Do not read the source of
|
||||
reference or third-party decoders/encoders while implementing a format, even permissively licensed
|
||||
ones (libvpx, libopus, libaom, dav1d, openh264…); spec text and conformance vectors only. Record the
|
||||
spec edition used in the crate README.
|
||||
- ffmpeg/ffprobe may be used only as external test oracles and fixture generators. They are never
|
||||
linked, bundled or shipped.
|
||||
- Dependencies must use permissive licences: MIT/Apache-2.0/BSD/ISC/Zlib/Unicode/CC0/BSL-1.0, or
|
||||
MPL-2.0 used unmodified.
|
||||
|
||||
## 3. Engineering rules
|
||||
|
||||
- **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.
|
||||
|
||||
|
||||
Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in
|
||||
[`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus).
|
||||
Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified,
|
||||
as PhotoCraft does with `cargo xtask corpus`.
|
||||
|
||||
|
||||
## See also
|
||||
|
||||
- [ROADMAP.md](ROADMAP.md): stage, headline numbers and what's next
|
||||
- [docs/gaps.md](docs/gaps.md): every known shortfall against After Effects, ranked, and the prioritised workstreams (G1–G9); read it before choosing work
|
||||
- [docs/target-app-parity.md](docs/target-app-parity.md): the parity numbers and how they were measured, with the per-area docs it links (UI, file formats, hardware, localization, effects, scripting)
|
||||
- [CONTRIBUTING.md](CONTRIBUTING.md): setup, gates, commits, how to add things
|
||||
- [docs/architecture.md](docs/architecture.md): layers, data model, commands, pipeline
|
||||
- [docs/testing.md](docs/testing.md): oracle tests, criteria, benchmarks
|
||||
- [docs/agents.md](docs/agents.md): driving EffectCraft over MCP / the control channel, and the agent work loop
|
||||
- [docs/control-protocol.md](docs/control-protocol.md): control-channel method reference
|
||||
- [docs/contributors.md](docs/contributors.md): the About window's contributor and model credits
|
||||
- [ATTRIBUTION.md](ATTRIBUTION.md): asset index
|
||||
|
||||
## Contributor credits (About window)
|
||||
|
||||
- About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json`
|
||||
(commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for
|
||||
themselves). See `docs/contributors.md`.
|
||||
- **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub
|
||||
username has a `[people.<username>]` entry in `contributors/people.toml`. If not, ask them once
|
||||
whether they want to be credited by more than their username: a real name, a display name, and/or
|
||||
their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry
|
||||
(copy the template at the top of the file)
|
||||
and include it in their PR, committed as them. If no, change nothing: they are credited as
|
||||
`@username` anyway.
|
||||
- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or
|
||||
GitHub profiles). Never hand-edit `contributors.json`.
|
||||
|
||||
## 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.
|
||||
+158
-150
@@ -1,150 +1,158 @@
|
||||
# Attribution
|
||||
|
||||
Every non-code asset in EffectCraft, with its author, source and licence. Each repository file listed here also has
|
||||
a `<file>.attribution` sidecar with full details. The rules are in [AGENTS.md](AGENTS.md) §1: no Adobe
|
||||
iconography, images or other Adobe assets; open licences only; every asset attributed.
|
||||
`cargo xtask assets` checks that this index and the sidecars cover every asset in the repository.
|
||||
The complete licence texts and copyright notices for the bundled fonts, including the fonts embedded
|
||||
by the pinned egui dependency, are reproduced in [`NOTICE`](NOTICE), which every package ships; the
|
||||
`assets/fonts/OFL-*.txt` files are the upstream copies kept beside the fonts.
|
||||
|
||||
## Bundled dependency fonts
|
||||
|
||||
These fonts are embedded by the pinned egui dependency (epaint_default_fonts 0.37 at
|
||||
`6d518fc799681571963842f95b55a6b68431b15a`); no font file is added to this repository.
|
||||
egui-icons is always embedded, `default_fonts` adds Ubuntu Light and Hack, and
|
||||
`monochrome_emoji_fonts` adds Noto Emoji and emoji-icon-font. The complete copyright notices
|
||||
and licence texts are in [`NOTICE`](NOTICE).
|
||||
|
||||
| Asset | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `epaint_default_fonts/fonts/egui-icons.ttf` | John Slegers (emoji-icon-font) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; original https://github.com/jslegers/emoji-icon-font | MIT (complete copyright and permission text in `NOTICE`) |
|
||||
| `epaint_default_fonts/fonts/emoji-icon-font.ttf` | John Slegers | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/emoji-icon-font-mit-license.txt; original https://github.com/jslegers/emoji-icon-font | MIT (complete copyright and permission text in `NOTICE`) |
|
||||
| `epaint_default_fonts/fonts/NotoEmoji-Regular.ttf` | Google Inc. (The Noto Project Authors) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/OFL.txt | OFL-1.1 (complete text in `NOTICE`) |
|
||||
| `epaint_default_fonts/fonts/Ubuntu-Light.ttf` | Canonical Ltd. and Dalton Maag | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/UFL.txt | Ubuntu Font Licence 1.0 (complete text in `NOTICE`) |
|
||||
| `epaint_default_fonts/fonts/Hack-Regular.ttf` | Source Foundry Authors; Bitstream Inc. | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/Hack-Regular.txt; original https://github.com/source-foundry/Hack | MIT AND Bitstream-Vera (complete texts in `NOTICE`) |
|
||||
|
||||
## Asset files
|
||||
|
||||
| Asset | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `assets/fonts/Inter-Regular.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/Inter-Medium.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/Inter-SemiBold.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/Inter-Bold.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/Inter-Italic.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/NotoSerif-Regular.ttf` | The Noto Project Authors | https://github.com/notofonts/latin-greek-cyrillic | OFL-1.1 (`assets/fonts/OFL-NotoSerif.txt`) |
|
||||
| `assets/fonts/NotoSansSymbols2-Regular.ttf` | The Noto Project Authors | https://github.com/notofonts/symbols | OFL-1.1 (`assets/fonts/OFL-NotoSansSymbols2.txt`) |
|
||||
| `assets/fonts/JetBrainsMono-Regular.ttf` | The JetBrains Mono Project Authors | https://github.com/JetBrains/JetBrainsMono | OFL-1.1 (`assets/fonts/OFL-JetBrainsMono.txt`) |
|
||||
| `apps/effectcraft-web/web/favicon.svg` | EffectCraft contributors | Original work: web app icon, a copy of `assets/app-icon/effectcraft-small.svg` (the unicorn app icon) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `packaging/macos/dmg/background.svg` | @XusBadia | Original work: macOS DMG Finder window background, derived from the EffectCraft app icon (`assets/app-icon/effectcraft.svg`); rendered to a TIFF by `packaging/macos/package.sh` at package time | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) |
|
||||
| `assets/app-icon/effectcraft-1024.png` | EffectCraft contributors | Original work: effectCraft app icon, 1024 px (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft-macos-512.png` | EffectCraft contributors | Original work: effectCraft runtime Dock icon (macOS) (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft-small.svg` | EffectCraft contributors | Original work: effectCraft app icon, light vector (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft.icns` | EffectCraft contributors | Original work: effectCraft macOS app icon (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft.ico` | EffectCraft contributors | Original work: effectCraft Windows app icon (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft.svg` | EffectCraft contributors | Original work: effectCraft app icon, master vector (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/128x128/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 128x128 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 16x16 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/24x24/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 24x24 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 256x256 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/32x32/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 32x32 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 48x48 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 512x512 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 64x64 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.effectcraft.svg` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor scalable (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `crates/lottie/tests/fixtures/bouncing-ball.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (bouncing ball, eased position keys) | MIT OR Apache-2.0 |
|
||||
| `crates/lottie/tests/fixtures/shapes-gradient.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (star, rectangle, gradient fill, dashed stroke, trim paths) | MIT OR Apache-2.0 |
|
||||
| `crates/lottie/tests/fixtures/precomp-matte-text.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (precomp, track matte, parented text) | MIT OR Apache-2.0 |
|
||||
| `crates/lottie/tests/fixtures/legacy-masks.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (legacy keyframes, masks) | MIT OR Apache-2.0 |
|
||||
| `crates/svg/tests/fixtures/basic-shapes.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (basic shapes, groups, transforms) | MIT OR Apache-2.0 |
|
||||
| `crates/svg/tests/fixtures/paths-gradients.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (path data, gradients, CSS, use) | MIT OR Apache-2.0 |
|
||||
| `crates/model/tests/fixtures/quad.gltf` | EffectCraft contributors | Original work: glTF 2.0 test fixture (textured quad, node hierarchy, translation animation; data URIs) | MIT OR Apache-2.0 |
|
||||
| `crates/model/tests/fixtures/quad.glb` | EffectCraft contributors | Original work: binary glTF test fixture (the same quad with its texture in the BIN chunk) | MIT OR Apache-2.0 |
|
||||
| `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 |
|
||||
|
||||
One small After Effects test project of `crates/aep` is 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). 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.
|
||||
|
||||
| Asset | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `docs/images/effectcraft-hero.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft main window) | MIT OR Apache-2.0 |
|
||||
| `docs/images/effectcraft-3d.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Classic 3D) | MIT OR Apache-2.0 |
|
||||
| `docs/images/effectcraft-graph-editor.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Graph Editor) | MIT OR Apache-2.0 |
|
||||
| `docs/images/effectcraft-effects.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft effects) | MIT OR Apache-2.0 |
|
||||
| `docs/images/effectcraft-render-queue.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Render Queue panel with the demo compositions queued for H.264 and ProRes export) | MIT OR Apache-2.0 |
|
||||
|
||||
## Code-drawn assets (original work, MIT OR Apache-2.0)
|
||||
|
||||
- UI icons drawn in code: `crates/ui-egui/src/icons.rs`, including the original filled favorite star (2026-10-11, EffectCraft contributors).
|
||||
- Procedural demo content (solids, shapes, gradients, text animations): `crates/engine/src/demo.rs`.
|
||||
- Built-in project templates (Lower Third, Title Card, Logo Reveal, Kinetic Type, Social Square, Vertical Story,
|
||||
Slideshow, 3D Text Orbit) built from engine commands, and their thumbnails rendered by our own renderer:
|
||||
`crates/engine/src/templates.rs`.
|
||||
- Text animator presets (Typewriter, Fade Up Characters, Bounce In Words, Tracking In, Scramble, Blur In, Jitter,
|
||||
Drop In Lines): `crates/engine/presets/text_animators.json` (sidecar `.attribution`).
|
||||
- Transition animation presets (23: wipes, clock and fan reveals, blinds, dissolves, card flips, CC wipes, fades):
|
||||
`crates/engine/presets/transitions.json` (sidecar `.attribution`).
|
||||
- Backgrounds animation presets (23: drifting gradients, fog, cloud and smoke, plasma and magma, cells and crystals, scrolling grids
|
||||
and checks, pulse rings, bokeh, light sweep): `crates/engine/presets/backgrounds.json` (sidecar `.attribution`).
|
||||
- Behaviors animation presets (22: wiggle, shake, float, orbit, bounce, drift, pendulum, spin, pulse, heartbeat, blink, strobe, flicker):
|
||||
`crates/engine/presets/behaviors.json` (sidecar `.attribution`).
|
||||
- Sample scripts (File ▸ Scripts) and ScriptUI panel: `crates/engine/scripts/Rename Layers.jsx`,
|
||||
`crates/engine/scripts/Sort Layers by In Point.jsx`, `crates/engine/scripts/Create Null at Selected Layers.jsx`,
|
||||
`crates/engine/scripts/Render Queue Batch.jsx`, `crates/engine/scripts/ScriptUI Panels/Layer Tools.jsx`
|
||||
(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).
|
||||
|
||||
## Trained models (optional downloads, not bundled)
|
||||
|
||||
The repository and the installers contain no model weights. These models are downloaded only when
|
||||
a user asks (Settings ▸ Roto Brush, Settings ▸ Face Tracking, or the `roto.model.*` /
|
||||
`face.model.*` commands), unmodified from their authors' official location, checked against a
|
||||
pinned SHA-256 and stored in the user's `models` folder with a `<file>.NOTICE.txt` naming their
|
||||
authors, licence and source. EffectCraft runs them with its own Rust implementation and is not
|
||||
affiliated with or endorsed by their authors.
|
||||
|
||||
| Model | Authors | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| MobileSAM (`mobile_sam.pt`) | Chaoning Zhang et al., building on Meta AI's Segment Anything and Microsoft's TinyViT | https://github.com/ChaoningZhang/MobileSAM | Apache-2.0 |
|
||||
| MediaPipe Face Landmarker (`face_landmarker.task`: BlazeFace short-range detector, Face Mesh V2, blendshapes) | Google LLC | https://developers.google.com/edge/mediapipe/solutions/vision/face_landmarker (model cards: https://storage.googleapis.com/mediapipe-assets/MediaPipe%20BlazeFace%20Model%20Card%20(Short%20Range).pdf, https://storage.googleapis.com/mediapipe-assets/Model%20Card%20MediaPipe%20Face%20Mesh%20V2.pdf) | Apache-2.0 |
|
||||
|
||||
## Formats and parameters from other open-source projects
|
||||
|
||||
Written in Rust for EffectCraft; no code is copied. They follow published specifications and
|
||||
configuration from these Apache-2.0 projects:
|
||||
|
||||
- `crates/segment/src/tflite.rs` reads TensorFlow Lite files using the field layout of TensorFlow
|
||||
Lite's `schema.fbs` (The TensorFlow Authors, https://github.com/tensorflow/tensorflow,
|
||||
Apache-2.0).
|
||||
- `crates/segment/src/mediapipe.rs` follows MediaPipe's published face landmarker graph: the SSD
|
||||
anchor layout, detection decoding, crop sizes and the face-mesh point indices it uses (Google
|
||||
LLC, https://github.com/google-ai-edge/mediapipe, Apache-2.0).
|
||||
- `crates/segment/src/mobilesam.rs` follows the MobileSAM, TinyViT and Segment Anything
|
||||
architectures and their Apache-2.0 reference code.
|
||||
|
||||
## First-party brand marks
|
||||
|
||||
The ArtCraft name, wordmark and logos are trademarks of the ArtCraft Team. They are not open source and are not
|
||||
covered by the project licence; they may be used only unmodified and only as part of this repository and EffectCraft,
|
||||
under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Forks and modified versions must remove them
|
||||
(AGENTS.md §1.8).
|
||||
|
||||
| File | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark, light ink for dark backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark, light ink for dark backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-logo.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark (symbol + "ARTCRAFT"), dark ink for light backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-logo.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark (symbol + "ARTCRAFT"), dark ink for light backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-mark.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
|
||||
- Appearance theme previews, drawn procedurally from original shapes: `crates/ui-egui/src/panels/settings.rs` (original work, MIT OR Apache-2.0).
|
||||
# Attribution
|
||||
|
||||
Every non-code asset in EffectCraft, with its author, source and licence. Each repository file listed here also has
|
||||
a `<file>.attribution` sidecar with full details. The rules are in [AGENTS.md](AGENTS.md) §1: no Adobe
|
||||
iconography, images or other Adobe assets; open licences only; every asset attributed.
|
||||
`cargo xtask assets` checks that this index and the sidecars cover every asset in the repository.
|
||||
The complete licence texts and copyright notices for the bundled fonts, including the fonts embedded
|
||||
by the pinned egui dependency, are reproduced in [`NOTICE`](NOTICE), which every package ships; the
|
||||
`assets/fonts/OFL-*.txt` files are the upstream copies kept beside the fonts.
|
||||
|
||||
## Bundled dependency fonts
|
||||
|
||||
These fonts are embedded by the pinned egui dependency (epaint_default_fonts 0.37 at
|
||||
`6d518fc799681571963842f95b55a6b68431b15a`); no font file is added to this repository.
|
||||
egui-icons is always embedded, `default_fonts` adds Ubuntu Light and Hack, and
|
||||
`monochrome_emoji_fonts` adds Noto Emoji and emoji-icon-font. The complete copyright notices
|
||||
and licence texts are in [`NOTICE`](NOTICE).
|
||||
|
||||
| Asset | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `epaint_default_fonts/fonts/egui-icons.ttf` | John Slegers (emoji-icon-font) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; original https://github.com/jslegers/emoji-icon-font | MIT (complete copyright and permission text in `NOTICE`) |
|
||||
| `epaint_default_fonts/fonts/emoji-icon-font.ttf` | John Slegers | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/emoji-icon-font-mit-license.txt; original https://github.com/jslegers/emoji-icon-font | MIT (complete copyright and permission text in `NOTICE`) |
|
||||
| `epaint_default_fonts/fonts/NotoEmoji-Regular.ttf` | Google Inc. (The Noto Project Authors) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/OFL.txt | OFL-1.1 (complete text in `NOTICE`) |
|
||||
| `epaint_default_fonts/fonts/Ubuntu-Light.ttf` | Canonical Ltd. and Dalton Maag | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/UFL.txt | Ubuntu Font Licence 1.0 (complete text in `NOTICE`) |
|
||||
| `epaint_default_fonts/fonts/Hack-Regular.ttf` | Source Foundry Authors; Bitstream Inc. | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/Hack-Regular.txt; original https://github.com/source-foundry/Hack | MIT AND Bitstream-Vera (complete texts in `NOTICE`) |
|
||||
|
||||
## Asset files
|
||||
|
||||
| Asset | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `assets/fonts/Inter-Regular.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/Inter-Medium.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/Inter-SemiBold.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/Inter-Bold.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/Inter-Italic.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) |
|
||||
| `assets/fonts/NotoSerif-Regular.ttf` | The Noto Project Authors | https://github.com/notofonts/latin-greek-cyrillic | OFL-1.1 (`assets/fonts/OFL-NotoSerif.txt`) |
|
||||
| `assets/fonts/NotoSansSymbols2-Regular.ttf` | The Noto Project Authors | https://github.com/notofonts/symbols | OFL-1.1 (`assets/fonts/OFL-NotoSansSymbols2.txt`) |
|
||||
| `assets/fonts/JetBrainsMono-Regular.ttf` | The JetBrains Mono Project Authors | https://github.com/JetBrains/JetBrainsMono | OFL-1.1 (`assets/fonts/OFL-JetBrainsMono.txt`) |
|
||||
| `apps/effectcraft-web/web/favicon.svg` | EffectCraft contributors | Original work: web app icon, a copy of `assets/app-icon/effectcraft-small.svg` (the unicorn app icon) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `packaging/macos/dmg/background.svg` | @XusBadia | Original work: macOS DMG Finder window background, derived from the EffectCraft app icon (`assets/app-icon/effectcraft.svg`); rendered to a TIFF by `packaging/macos/package.sh` at package time | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) |
|
||||
| `assets/app-icon/effectcraft-1024.png` | EffectCraft contributors | Original work: effectCraft app icon, 1024 px (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft-macos-512.png` | EffectCraft contributors | Original work: effectCraft runtime Dock icon (macOS) (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft-small.svg` | EffectCraft contributors | Original work: effectCraft app icon, light vector (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft.icns` | EffectCraft contributors | Original work: effectCraft macOS app icon (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft.ico` | EffectCraft contributors | Original work: effectCraft Windows app icon (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/effectcraft.svg` | EffectCraft contributors | Original work: effectCraft app icon, master vector (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/128x128/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 128x128 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 16x16 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/24x24/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 24x24 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 256x256 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/32x32/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 32x32 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 48x48 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 512x512 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 64x64 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.effectcraft.svg` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor scalable (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `crates/lottie/tests/fixtures/bouncing-ball.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (bouncing ball, eased position keys) | MIT OR Apache-2.0 |
|
||||
| `crates/lottie/tests/fixtures/shapes-gradient.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (star, rectangle, gradient fill, dashed stroke, trim paths) | MIT OR Apache-2.0 |
|
||||
| `crates/lottie/tests/fixtures/precomp-matte-text.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (precomp, track matte, parented text) | MIT OR Apache-2.0 |
|
||||
| `crates/lottie/tests/fixtures/legacy-masks.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (legacy keyframes, masks) | MIT OR Apache-2.0 |
|
||||
| `crates/svg/tests/fixtures/basic-shapes.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (basic shapes, groups, transforms) | MIT OR Apache-2.0 |
|
||||
| `crates/svg/tests/fixtures/paths-gradients.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (path data, gradients, CSS, use) | MIT OR Apache-2.0 |
|
||||
| `crates/model/tests/fixtures/quad.gltf` | EffectCraft contributors | Original work: glTF 2.0 test fixture (textured quad, node hierarchy, translation animation; data URIs) | MIT OR Apache-2.0 |
|
||||
| `crates/model/tests/fixtures/quad.glb` | EffectCraft contributors | Original work: binary glTF test fixture (the same quad with its texture in the BIN chunk) | MIT OR Apache-2.0 |
|
||||
| `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 |
|
||||
|
||||
Three 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), `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) and `crates/aep/tests/fixtures/text-synthetic.aep` (original work, made with After Effects 2026 by script from own data, working space None, no colour profile embedded, nothing changed after the save; 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.
|
||||
|
||||
| Asset | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `docs/images/effectcraft-hero.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft main window) | MIT OR Apache-2.0 |
|
||||
| `docs/images/effectcraft-3d.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Classic 3D) | MIT OR Apache-2.0 |
|
||||
| `docs/images/effectcraft-graph-editor.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Graph Editor) | MIT OR Apache-2.0 |
|
||||
| `docs/images/effectcraft-effects.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft effects) | MIT OR Apache-2.0 |
|
||||
| `docs/images/effectcraft-render-queue.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Render Queue panel with the demo compositions queued for H.264 and ProRes export) | MIT OR Apache-2.0 |
|
||||
|
||||
## Code-drawn assets (original work, MIT OR Apache-2.0)
|
||||
|
||||
- UI icons drawn in code: `crates/ui-egui/src/icons.rs`, including the original filled favorite star (2026-10-11, EffectCraft contributors).
|
||||
- Procedural demo content (solids, shapes, gradients, text animations): `crates/engine/src/demo.rs`.
|
||||
- Built-in project templates (Lower Third, Title Card, Logo Reveal, Kinetic Type, Social Square, Vertical Story,
|
||||
Slideshow, 3D Text Orbit) built from engine commands, and their thumbnails rendered by our own renderer:
|
||||
`crates/engine/src/templates.rs`.
|
||||
- Text animator presets (Typewriter, Fade Up Characters, Bounce In Words, Tracking In, Scramble, Blur In, Jitter,
|
||||
Drop In Lines): `crates/engine/presets/text_animators.json` (sidecar `.attribution`).
|
||||
- Transition animation presets (23: wipes, clock and fan reveals, blinds, dissolves, card flips, CC wipes, fades):
|
||||
`crates/engine/presets/transitions.json` (sidecar `.attribution`).
|
||||
- Backgrounds animation presets (23: drifting gradients, fog, cloud and smoke, plasma and magma, cells and crystals, scrolling grids
|
||||
and checks, pulse rings, bokeh, light sweep): `crates/engine/presets/backgrounds.json` (sidecar `.attribution`).
|
||||
- Behaviors animation presets (22: wiggle, shake, float, orbit, bounce, drift, pendulum, spin, pulse, heartbeat, blink, strobe, flicker):
|
||||
`crates/engine/presets/behaviors.json` (sidecar `.attribution`).
|
||||
- Sample scripts (File ▸ Scripts) and ScriptUI panel: `crates/engine/scripts/Rename Layers.jsx`,
|
||||
`crates/engine/scripts/Sort Layers by In Point.jsx`, `crates/engine/scripts/Create Null at Selected Layers.jsx`,
|
||||
`crates/engine/scripts/Render Queue Batch.jsx`, `crates/engine/scripts/ScriptUI Panels/Layer Tools.jsx`
|
||||
(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` (WebAssembly ABI 1).
|
||||
|
||||
## Trained models (optional downloads, not bundled)
|
||||
|
||||
The repository and the installers contain no model weights. These models are downloaded only when
|
||||
a user asks (Settings ▸ Roto Brush, Settings ▸ Face Tracking, or the `roto.model.*` /
|
||||
`face.model.*` commands), unmodified from their authors' official location, checked against a
|
||||
pinned SHA-256 and stored in the user's `models` folder with a `<file>.NOTICE.txt` naming their
|
||||
authors, licence and source. EffectCraft runs them with its own Rust implementation and is not
|
||||
affiliated with or endorsed by their authors.
|
||||
|
||||
| Model | Authors | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| MobileSAM (`mobile_sam.pt`) | Chaoning Zhang et al., building on Meta AI's Segment Anything and Microsoft's TinyViT | https://github.com/ChaoningZhang/MobileSAM | Apache-2.0 |
|
||||
| MediaPipe Face Landmarker (`face_landmarker.task`: BlazeFace short-range detector, Face Mesh V2, blendshapes) | Google LLC | https://developers.google.com/edge/mediapipe/solutions/vision/face_landmarker (model cards: https://storage.googleapis.com/mediapipe-assets/MediaPipe%20BlazeFace%20Model%20Card%20(Short%20Range).pdf, https://storage.googleapis.com/mediapipe-assets/Model%20Card%20MediaPipe%20Face%20Mesh%20V2.pdf) | Apache-2.0 |
|
||||
|
||||
## Formats and parameters from other open-source projects
|
||||
|
||||
Written in Rust for EffectCraft; no code is copied. They follow published specifications and
|
||||
configuration from these Apache-2.0 projects:
|
||||
|
||||
- `crates/segment/src/tflite.rs` reads TensorFlow Lite files using the field layout of TensorFlow
|
||||
Lite's `schema.fbs` (The TensorFlow Authors, https://github.com/tensorflow/tensorflow,
|
||||
Apache-2.0).
|
||||
- `crates/segment/src/mediapipe.rs` follows MediaPipe's published face landmarker graph: the SSD
|
||||
anchor layout, detection decoding, crop sizes and the face-mesh point indices it uses (Google
|
||||
LLC, https://github.com/google-ai-edge/mediapipe, Apache-2.0).
|
||||
- `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/analysed-0.24.ecproj` | arnav-hiwarkar | Original work, synthetic project keyed by EffectCraft 0.24.1 | MIT OR Apache-2.0 |
|
||||
| `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 |
|
||||
| `crates/engine/src/tests/fixtures/tracked-0.22.ecproj` | arnav-hiwarkar | 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
|
||||
covered by the project licence; they may be used only unmodified and only as part of this repository and EffectCraft,
|
||||
under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Forks and modified versions must remove them
|
||||
(AGENTS.md §1.8).
|
||||
|
||||
| File | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark, light ink for dark backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark, light ink for dark backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-logo.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark (symbol + "ARTCRAFT"), dark ink for light backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-logo.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark (symbol + "ARTCRAFT"), dark ink for light backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-mark.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
|
||||
|
||||
- Appearance theme previews, drawn procedurally from original shapes: `crates/ui-egui/src/panels/settings.rs` (original work, MIT OR Apache-2.0).
|
||||
@@ -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 <windowid>`); 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-<name>`; 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
|
||||
+109
-109
@@ -1,109 +1,109 @@
|
||||
# Contributing to EffectCraft
|
||||
|
||||
Thanks for helping. Please read [AGENTS.md](AGENTS.md) first: its rules on assets and clean-room
|
||||
work apply to everyone, people and AI agents alike, and they are not negotiable.
|
||||
|
||||
## Setup
|
||||
|
||||
You need [Rust](https://rustup.rs/) 1.95 or newer.
|
||||
|
||||
On Linux the desktop app plays preview sound through `cpal`, so the build needs a usable ALSA
|
||||
pkg-config package: an `alsa.pc` that pkg-config can find, naming the linkable ALSA runtime
|
||||
library (usually `libasound.so.2`). `alsa-sys` runs pkg-config at build time; it does not compile
|
||||
ALSA's headers. Without a usable package the build fails at link time with an unrelated-looking
|
||||
error; `cargo xtask ci` probes pkg-config up front and names the package:
|
||||
|
||||
```sh
|
||||
sudo dnf install alsa-lib-devel # Fedora
|
||||
sudo apt install libasound2-dev # Debian / Ubuntu
|
||||
sudo pacman -S alsa-lib # Arch
|
||||
```
|
||||
|
||||
If you cannot install the package, point `PKG_CONFIG_PATH` at a directory holding an `alsa.pc`
|
||||
whose `Libs` line names your system's `libasound` (usually `libasound.so.2`); every CI run needs
|
||||
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
|
||||
```
|
||||
|
||||
The default `dev` profile keeps debug info to line tables: builds are fast and panics/backtraces
|
||||
still name the file and line, but a debugger cannot show local variables. For an interactive
|
||||
debugger session use the `dev-full` profile, which is the same build with full debug info:
|
||||
|
||||
```sh
|
||||
cargo run --profile dev-full -p effectcraft -- --demo
|
||||
```
|
||||
|
||||
### Windows
|
||||
|
||||
The MSVC toolchain, rustup's default on Windows, is what the releases use: with the Visual Studio
|
||||
C++ build tools installed, the commands above work as they are.
|
||||
|
||||
The GNU toolchain (`x86_64-pc-windows-gnu`) needs a current mingw-w64 GCC and binutils first on
|
||||
`PATH`. They provide the linker and the Windows import libraries, such as `libshlwapi.a` for
|
||||
opening links from the app. With MSYS2:
|
||||
|
||||
```powershell
|
||||
C:\msys64\usr\bin\pacman.exe -S --needed mingw-w64-x86_64-gcc
|
||||
$env:PATH = "C:\msys64\mingw64\bin;$env:PATH"
|
||||
cargo +stable-x86_64-pc-windows-gnu run -p effectcraft -- --demo
|
||||
```
|
||||
|
||||
An older MinGW earlier on `PATH` can break the build: CodeBlocks' GCC 8.1 fails to link
|
||||
`boa_engine` ([#1882](https://github.com/storytold/effectcraft/issues/1882)).
|
||||
|
||||
Rust's bundled LLD and self-contained libraries don't include every import library EffectCraft
|
||||
needs, so on their own they stop with `unable to find library` for `-lshlwapi`, `-lktmw32`,
|
||||
`-lpropsys` and `-lversion` ([#1886](https://github.com/storytold/effectcraft/issues/1886)). To
|
||||
link that way, copy those four from mingw-w64 into a folder of its own and add that folder to the
|
||||
search path in your own Cargo config (`%USERPROFILE%\.cargo\config.toml`). Don't add all of
|
||||
mingw-w64's `lib` folder: its C runtime clashes with Rust's bundled one
|
||||
(`undefined symbol: DllEntryPoint`).
|
||||
|
||||
```powershell
|
||||
New-Item -ItemType Directory -Force C:\gnu-import-libs
|
||||
foreach ($lib in "shlwapi", "ktmw32", "propsys", "version") {
|
||||
Copy-Item "C:\msys64\mingw64\lib\lib$lib.a" C:\gnu-import-libs\
|
||||
}
|
||||
```
|
||||
|
||||
```toml
|
||||
[target.x86_64-pc-windows-gnu]
|
||||
linker = "rust-lld"
|
||||
rustflags = ["-C", "link-self-contained=yes", "-L", "native=C:/gnu-import-libs"]
|
||||
```
|
||||
|
||||
## Ground rules
|
||||
|
||||
- **Clean room.** Work from After Effects' public documentation and its observable behaviour only.
|
||||
Never use Adobe artwork, presets or code, and never copy GPL/LGPL/AGPL code.
|
||||
- **Every asset is attributed.** Add a `.attribution` sidecar and an [ATTRIBUTION.md](ATTRIBUTION.md)
|
||||
row; `cargo xtask assets` checks it.
|
||||
- **Layering.** Nothing below the interface layer depends on UI or OS crates; see
|
||||
[docs/architecture.md](docs/architecture.md).
|
||||
- **Everything is a command.** New features are engine commands with an id, label, menu path,
|
||||
shortcut and parameters, so the UI, the CLI and the MCP server get them at once. Interactive
|
||||
widgets register an automation id.
|
||||
- **Never crash.** Non-test code returns errors instead of panicking: no `unwrap()`, `expect()`,
|
||||
`panic!`, `unreachable!`, `todo!`, `unimplemented!` or `unsafe`, checked indexing and arithmetic on
|
||||
input-derived values, and a regression test with every crash fix. See the "Never crash" section of
|
||||
[AGENTS.md](AGENTS.md).
|
||||
- **Tests with every change**, and green `cargo xtask ci` before every commit. One task per commit.
|
||||
|
||||
## How to add…
|
||||
|
||||
- **An effect:** add an `EffectSpec` in `crates/effects` (AE display name, category, parameters
|
||||
with AE's names, defaults and ranges) and its render function, with a determinism test and a
|
||||
behaviour test. If it reads the clock directly, add it to `TIME_DEPENDENT`.
|
||||
- **A command:** register it with `cmd!` in `crates/engine/src/commands/`, place it in the menu
|
||||
tree in `crates/engine/src/menus.rs`, and test it including undo.
|
||||
- **A panel or dialog:** `crates/ui-egui/src/panels/`; look at the result with the headless
|
||||
snapshot tool described in [docs/testing.md](docs/testing.md).
|
||||
|
||||
## Talk to us
|
||||
|
||||
Questions, ideas and bug reports are welcome on [Discord](https://discord.gg/artcraft) and in
|
||||
GitHub issues.
|
||||
# Contributing to EffectCraft
|
||||
|
||||
Thanks for helping. Please read [AGENTS.md](AGENTS.md) first: its rules on assets and clean-room
|
||||
work apply to everyone, people and AI agents alike, and they are not negotiable.
|
||||
|
||||
## Setup
|
||||
|
||||
You need [Rust](https://rustup.rs/) 1.95 or newer.
|
||||
|
||||
On Linux the desktop app plays preview sound through `cpal`, so the build needs a usable ALSA
|
||||
pkg-config package: an `alsa.pc` that pkg-config can find, naming the linkable ALSA runtime
|
||||
library (usually `libasound.so.2`). `alsa-sys` runs pkg-config at build time; it does not compile
|
||||
ALSA's headers. Without a usable package the build fails at link time with an unrelated-looking
|
||||
error; `cargo xtask ci` probes pkg-config up front and names the package:
|
||||
|
||||
```sh
|
||||
sudo dnf install alsa-lib-devel # Fedora
|
||||
sudo apt install libasound2-dev # Debian / Ubuntu
|
||||
sudo pacman -S alsa-lib # Arch
|
||||
```
|
||||
|
||||
If you cannot install the package, point `PKG_CONFIG_PATH` at a directory holding an `alsa.pc`
|
||||
whose `Libs` line names your system's `libasound` (usually `libasound.so.2`); every CI run needs
|
||||
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 (dev-profile checks and tests)
|
||||
```
|
||||
|
||||
The default `dev` profile keeps debug info to line tables: builds are fast and panics/backtraces
|
||||
still name the file and line, but a debugger cannot show local variables. For an interactive
|
||||
debugger session use the `dev-full` profile, which is the same build with full debug info:
|
||||
|
||||
```sh
|
||||
cargo run --profile dev-full -p effectcraft -- --demo
|
||||
```
|
||||
|
||||
### Windows
|
||||
|
||||
The MSVC toolchain, rustup's default on Windows, is what the releases use: with the Visual Studio
|
||||
C++ build tools installed, the commands above work as they are.
|
||||
|
||||
The GNU toolchain (`x86_64-pc-windows-gnu`) needs a current mingw-w64 GCC and binutils first on
|
||||
`PATH`. They provide the linker and the Windows import libraries, such as `libshlwapi.a` for
|
||||
opening links from the app. With MSYS2:
|
||||
|
||||
```powershell
|
||||
C:\msys64\usr\bin\pacman.exe -S --needed mingw-w64-x86_64-gcc
|
||||
$env:PATH = "C:\msys64\mingw64\bin;$env:PATH"
|
||||
cargo +stable-x86_64-pc-windows-gnu run -p effectcraft -- --demo
|
||||
```
|
||||
|
||||
An older MinGW earlier on `PATH` can break the build: CodeBlocks' GCC 8.1 fails to link
|
||||
`boa_engine` ([#1882](https://github.com/storytold/effectcraft/issues/1882)).
|
||||
|
||||
Rust's bundled LLD and self-contained libraries don't include every import library EffectCraft
|
||||
needs, so on their own they stop with `unable to find library` for `-lshlwapi`, `-lktmw32`,
|
||||
`-lpropsys` and `-lversion` ([#1886](https://github.com/storytold/effectcraft/issues/1886)). To
|
||||
link that way, copy those four from mingw-w64 into a folder of its own and add that folder to the
|
||||
search path in your own Cargo config (`%USERPROFILE%\.cargo\config.toml`). Don't add all of
|
||||
mingw-w64's `lib` folder: its C runtime clashes with Rust's bundled one
|
||||
(`undefined symbol: DllEntryPoint`).
|
||||
|
||||
```powershell
|
||||
New-Item -ItemType Directory -Force C:\gnu-import-libs
|
||||
foreach ($lib in "shlwapi", "ktmw32", "propsys", "version") {
|
||||
Copy-Item "C:\msys64\mingw64\lib\lib$lib.a" C:\gnu-import-libs\
|
||||
}
|
||||
```
|
||||
|
||||
```toml
|
||||
[target.x86_64-pc-windows-gnu]
|
||||
linker = "rust-lld"
|
||||
rustflags = ["-C", "link-self-contained=yes", "-L", "native=C:/gnu-import-libs"]
|
||||
```
|
||||
|
||||
## Ground rules
|
||||
|
||||
- **Clean room.** Work from After Effects' public documentation and its observable behaviour only.
|
||||
Never use Adobe artwork, presets or code, and never copy GPL/LGPL/AGPL code.
|
||||
- **Every asset is attributed.** Add a `.attribution` sidecar and an [ATTRIBUTION.md](ATTRIBUTION.md)
|
||||
row; `cargo xtask assets` checks it.
|
||||
- **Layering.** Nothing below the interface layer depends on UI or OS crates; see
|
||||
[docs/architecture.md](docs/architecture.md).
|
||||
- **Everything is a command.** New features are engine commands with an id, label, menu path,
|
||||
shortcut and parameters, so the UI, the CLI and the MCP server get them at once. Interactive
|
||||
widgets register an automation id.
|
||||
- **Never crash.** Non-test code returns errors instead of panicking: no `unwrap()`, `expect()`,
|
||||
`panic!`, `unreachable!`, `todo!`, `unimplemented!` or `unsafe`, checked indexing and arithmetic on
|
||||
input-derived values, and a regression test with every crash fix. See the "Never crash" section of
|
||||
[AGENTS.md](AGENTS.md).
|
||||
- **Tests with every change**, and green `cargo xtask ci` before every commit. One task per commit.
|
||||
|
||||
## How to add…
|
||||
|
||||
- **An effect:** add an `EffectSpec` in `crates/effects` (AE display name, category, parameters
|
||||
with AE's names, defaults and ranges) and its render function, with a determinism test and a
|
||||
behaviour test. If it reads the clock directly, add it to `TIME_DEPENDENT`.
|
||||
- **A command:** register it with `cmd!` in `crates/engine/src/commands/`, place it in the menu
|
||||
tree in `crates/engine/src/menus.rs`, and test it including undo.
|
||||
- **A panel or dialog:** `crates/ui-egui/src/panels/`; look at the result with the headless
|
||||
snapshot tool described in [docs/testing.md](docs/testing.md).
|
||||
|
||||
## Talk to us
|
||||
|
||||
Questions, ideas and bug reports are welcome on [Discord](https://discord.gg/artcraft) and in
|
||||
GitHub issues.
|
||||
Generated
+8262
-8061
File diff suppressed because it is too large.
Load diff
+249
-260
@@ -1,260 +1,249 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.21.0"
|
||||
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-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"] }
|
||||
# internal
|
||||
effectcraft-time = { path = "crates/time" }
|
||||
effectcraft-geom = { path = "crates/geom" }
|
||||
effectcraft-color = { path = "crates/color" }
|
||||
effectcraft-raster = { path = "crates/raster" }
|
||||
effectcraft-path = { path = "crates/path" }
|
||||
effectcraft-keyframe = { path = "crates/keyframe" }
|
||||
effectcraft-project = { path = "crates/project" }
|
||||
effectcraft-text = { path = "crates/text" }
|
||||
effectcraft-effects = { path = "crates/effects" }
|
||||
effectcraft-track = { path = "crates/track" }
|
||||
effectcraft-segment = { path = "crates/segment" }
|
||||
effectcraft-sam2 = { path = "crates/sam2" }
|
||||
effectcraft-model = { path = "crates/model" }
|
||||
effectcraft-render = { path = "crates/render" }
|
||||
effectcraft-gpu = { path = "crates/gpu" }
|
||||
effectcraft-media = { path = "crates/media" }
|
||||
effectcraft-export = { path = "crates/export" }
|
||||
effectcraft-expr = { path = "crates/expr" }
|
||||
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" }
|
||||
effectcraft-host = { path = "crates/host" }
|
||||
effectcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
effectcraft-automation = { path = "crates/automation" }
|
||||
effectcraft-opusenc = { path = "crates/opusenc" }
|
||||
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"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
rayon = "1"
|
||||
# std::time::Instant/SystemTime on native; the browser clock on wasm32 (std's panic there).
|
||||
web-time = "1"
|
||||
gif = "0.14"
|
||||
proptest = "1"
|
||||
|
||||
# scripting (expressions)
|
||||
boa_engine = { version = "0.22", default-features = false }
|
||||
# WebAssembly effect plug-ins (sandboxed interpreter; MIT/Apache-2.0, pure Rust)
|
||||
wasmi = { version = "2", default-features = false, features = ["std", "validate", "wat", "deterministic", "portable-dispatch"] }
|
||||
|
||||
# geometry / fonts
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd"] }
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
harfrust = { version = "0.12", default-features = false, features = ["std"] }
|
||||
exr = "1.74"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
same-file = "1.0"
|
||||
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 = "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 = "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 = "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 = "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 = "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 = "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"
|
||||
|
||||
# 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"] }
|
||||
# `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"
|
||||
# The operating system's interface language (MIT/Apache-2.0, no dependencies on desktop).
|
||||
sys-locale = "0.3"
|
||||
|
||||
# Local co-development against a FilmCraft checkout next to this repo: uncomment.
|
||||
# [patch."https://github.com/storytold/filmcraft"]
|
||||
# filmcraft-codecs = { path = "../filmcraft/crates/codecs" }
|
||||
# filmcraft-media = { path = "../filmcraft/crates/media" }
|
||||
# filmcraft-frame = { path = "../filmcraft/crates/frame" }
|
||||
# filmcraft-color = { path = "../filmcraft/crates/color" }
|
||||
# filmcraft-time = { path = "../filmcraft/crates/time" }
|
||||
# filmcraft-h264enc = { path = "../filmcraft/crates/h264enc" }
|
||||
# filmcraft-prores = { path = "../filmcraft/crates/prores" }
|
||||
# filmcraft-aac = { path = "../filmcraft/crates/aac" }
|
||||
# filmcraft-isobmff = { path = "../filmcraft/crates/isobmff" }
|
||||
# filmcraft-matroska = { path = "../filmcraft/crates/matroska" }
|
||||
# filmcraft-mpegts = { path = "../filmcraft/crates/mpegts" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
too_many_arguments = "deny"
|
||||
wildcard_imports = "deny"
|
||||
dbg_macro = "warn"
|
||||
todo = "warn"
|
||||
needless_range_loop = "allow"
|
||||
type_complexity = "allow"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
debug = false
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
# Panics and backtraces keep file and line; full debug info only made the many test binaries large.
|
||||
debug = "line-tables-only"
|
||||
|
||||
# Same settings as `dev`, but with full debug info for interactive debugger sessions: local
|
||||
# variables, parameters and column breakpoints work. Use `--profile dev-full` when debugging;
|
||||
# everything else stays on the fast default. See CONTRIBUTING.md, "Setup".
|
||||
[profile.dev-full]
|
||||
inherits = "dev"
|
||||
debug = true
|
||||
|
||||
# Pixel hot loops: keep debug builds interactive.
|
||||
[profile.dev.package.effectcraft-raster]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-render]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-gpu]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-effects]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-track]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-path]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-media]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-opusenc]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-export]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-vp9enc]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-hevcenc]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-av1enc]
|
||||
opt-level = 3
|
||||
|
||||
# FilmCraft codec hot loops (same settings as FilmCraft's own workspace).
|
||||
[profile.dev.package.filmcraft-h264]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-h264enc]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-hevc]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-vp9]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-prores]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-dnx]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-av1]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-aac]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-opus]
|
||||
opt-level = 3
|
||||
|
||||
[profile.release]
|
||||
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" }
|
||||
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" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
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" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/*"]
|
||||
|
||||
[workspace.package]
|
||||
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 = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.1.0", default-features = false, features = ["read"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
|
||||
craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
|
||||
# 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 = "47107f660191de2f0b425569506f4daa4faadac9", features = ["egui"] }
|
||||
# internal
|
||||
effectcraft-time = { path = "crates/time" }
|
||||
effectcraft-geom = { path = "crates/geom" }
|
||||
effectcraft-color = { path = "crates/color" }
|
||||
effectcraft-raster = { path = "crates/raster" }
|
||||
effectcraft-path = { path = "crates/path" }
|
||||
effectcraft-keyframe = { path = "crates/keyframe" }
|
||||
effectcraft-project = { path = "crates/project" }
|
||||
effectcraft-text = { path = "crates/text" }
|
||||
effectcraft-effects = { path = "crates/effects" }
|
||||
effectcraft-track = { path = "crates/track" }
|
||||
effectcraft-segment = { path = "crates/segment" }
|
||||
effectcraft-sam2 = { path = "crates/sam2" }
|
||||
effectcraft-model = { path = "crates/model" }
|
||||
effectcraft-render = { path = "crates/render" }
|
||||
effectcraft-gpu = { path = "crates/gpu" }
|
||||
effectcraft-media = { path = "crates/media" }
|
||||
effectcraft-export = { path = "crates/export" }
|
||||
effectcraft-expr = { path = "crates/expr" }
|
||||
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-svg = { path = "crates/svg" }
|
||||
effectcraft-engine = { path = "crates/engine" }
|
||||
effectcraft-host = { path = "crates/host" }
|
||||
effectcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
effectcraft-automation = { path = "crates/automation" }
|
||||
effectcraft-opusenc = { path = "crates/opusenc" }
|
||||
effectcraft-script = { path = "crates/script" }
|
||||
effectcraft-plugin = { path = "crates/plugin" }
|
||||
effectcraft-helper-host = { path = "crates/helper-host" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
rayon = "1"
|
||||
# std::time::Instant/SystemTime on native; the browser clock on wasm32 (std's panic there).
|
||||
web-time = "1"
|
||||
gif = "0.14"
|
||||
proptest = "1"
|
||||
|
||||
# scripting (expressions)
|
||||
boa_engine = { version = "0.22", default-features = false }
|
||||
# WebAssembly effect plug-ins (sandboxed interpreter; MIT/Apache-2.0, pure Rust)
|
||||
wasmi = { version = "2", default-features = false, features = ["std", "validate", "wat", "deterministic", "portable-dispatch"] }
|
||||
|
||||
# geometry / fonts
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd"] }
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
harfrust = { version = "0.12", default-features = false, features = ["std"] }
|
||||
exr = "1.74"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
same-file = "1.0"
|
||||
tempfile = "3.27"
|
||||
|
||||
# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all three on one rev.
|
||||
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["isobmff", "matroska"] }
|
||||
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] }
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
|
||||
|
||||
# footage decoding: 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 = "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" }
|
||||
# MPEG TS / PS headers read for AAC channel layouts (crates/media); craft-media has no MPEG TS reader
|
||||
filmcraft-mpegts = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
|
||||
# decoders used as the round-trip oracles of craft-video's VP9, HEVC and AV1 encoders (crates/export
|
||||
# dev-dependencies only); craft-video has no decoder for them
|
||||
filmcraft-vp9 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
|
||||
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 = "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 = "47107f660191de2f0b425569506f4daa4faadac9", 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"
|
||||
# The operating system's interface language (MIT/Apache-2.0, no dependencies on desktop).
|
||||
sys-locale = "0.3"
|
||||
|
||||
# Local co-development against a FilmCraft checkout next to this repo: uncomment.
|
||||
# [patch."https://github.com/storytold/filmcraft"]
|
||||
# filmcraft-codecs = { path = "../filmcraft/crates/codecs" }
|
||||
# filmcraft-media = { path = "../filmcraft/crates/media" }
|
||||
# filmcraft-frame = { path = "../filmcraft/crates/frame" }
|
||||
# filmcraft-color = { path = "../filmcraft/crates/color" }
|
||||
# filmcraft-time = { path = "../filmcraft/crates/time" }
|
||||
# filmcraft-mpegts = { path = "../filmcraft/crates/mpegts" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
too_many_arguments = "deny"
|
||||
wildcard_imports = "deny"
|
||||
dbg_macro = "warn"
|
||||
todo = "warn"
|
||||
needless_range_loop = "allow"
|
||||
type_complexity = "allow"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
debug = false
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
# Panics and backtraces keep file and line; full debug info only made the many test binaries large.
|
||||
debug = "line-tables-only"
|
||||
|
||||
# Same settings as `dev`, but with full debug info for interactive debugger sessions: local
|
||||
# variables, parameters and column breakpoints work. Use `--profile dev-full` when debugging;
|
||||
# everything else stays on the fast default. See CONTRIBUTING.md, "Setup".
|
||||
[profile.dev-full]
|
||||
inherits = "dev"
|
||||
debug = true
|
||||
|
||||
# Pixel hot loops: keep debug builds interactive.
|
||||
[profile.dev.package.effectcraft-raster]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-render]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-gpu]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-effects]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-track]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-path]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-media]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-opusenc]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-export]
|
||||
opt-level = 3
|
||||
|
||||
# craft-libs codec hot loops.
|
||||
[profile.dev.package.craft-video]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.craft-audio]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.craft-media]
|
||||
opt-level = 3
|
||||
|
||||
# FilmCraft codec hot loops (same settings as FilmCraft's own workspace).
|
||||
[profile.dev.package.filmcraft-h264]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-hevc]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-vp9]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-dnx]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-av1]
|
||||
opt-level = 3
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.7.2" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", 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" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
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" }
|
||||
eframe = { 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" }
|
||||
+177
-177
@@ -1,177 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
+21
-21
@@ -1,21 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,322 +1,322 @@
|
||||
EffectCraft
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors.
|
||||
Licensed under the MIT License or the Apache License, Version 2.0, at your option
|
||||
(LICENSE-MIT, LICENSE-APACHE).
|
||||
|
||||
The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are
|
||||
not open source and are not covered by the license above; their terms are in
|
||||
docs/brand/LICENSE-brand.txt.
|
||||
|
||||
Third-party material
|
||||
|
||||
This product bundles third-party material under its own licenses, listed below. The per-file
|
||||
list (author, source, license) is in ATTRIBUTION.md.
|
||||
|
||||
Bundled fonts
|
||||
|
||||
EffectCraft embeds Inter, Noto Serif, JetBrains Mono and Noto Sans Symbols 2 from
|
||||
assets/fonts/. The pinned egui dependency (epaint_default_fonts, revision
|
||||
6d518fc799681571963842f95b55a6b68431b15a) additionally embeds Ubuntu Light, Hack,
|
||||
Noto Emoji, egui-icons and emoji-icon-font through EffectCraft's enabled `default_fonts`
|
||||
and `monochrome_emoji_fonts` features; no font file from that dependency is added to
|
||||
this repository. The complete copyright notices and licence texts required for all of
|
||||
these fonts follow.
|
||||
|
||||
The optional PDF document reader uses craft-pdf and Hayro-syntax 0.7.2, MIT OR Apache-2.0.
|
||||
The shared patched syntax source is centralized in storytold/craft-libs, transferred from
|
||||
PdfCraft revision 9ed3abe4907a127d36b12fbfeee71d7e26248da1. This parser-only use embeds no
|
||||
Hayro fonts, CMaps or image codecs; EffectCraft keeps its existing fonts and drawing filters.
|
||||
|
||||
Linux Wayland window decorations
|
||||
-------------------------------
|
||||
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
|
||||
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
|
||||
for vector window controls. Its title-font features are disabled: no Cantarell
|
||||
font is embedded by this dependency and no font file is added to this repo.
|
||||
|
||||
sctk-adwaita's MIT licence:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Bartłomiej Maryńczak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
SIL Open Font License 1.1
|
||||
|
||||
Applies to Inter (assets/fonts/Inter-*.ttf), Noto Serif (assets/fonts/NotoSerif-Regular.ttf),
|
||||
JetBrains Mono (assets/fonts/JetBrainsMono-Regular.ttf), Noto Sans Symbols 2
|
||||
(assets/fonts/NotoSansSymbols2-Regular.ttf) and Noto Emoji (NotoEmoji-Regular.ttf).
|
||||
Copyright notices:
|
||||
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
|
||||
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
|
||||
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols)
|
||||
Copyright 2013 Google Inc. All Rights Reserved.
|
||||
|
||||
The fonts in assets/fonts/ also keep their upstream licence files at
|
||||
assets/fonts/OFL-<family>.txt. The complete licence text follows.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License,
|
||||
Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font
|
||||
creation efforts of academic and linguistic communities, and to
|
||||
provide a free and open framework in which fonts may be shared and
|
||||
improved in partnership with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply to
|
||||
any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software
|
||||
components as distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to,
|
||||
deleting, or substituting -- in part or in whole -- any of the
|
||||
components of the Original Version, by changing formats or by porting
|
||||
the Font Software to a new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed,
|
||||
modify, redistribute, and sell modified and unmodified copies of the
|
||||
Font Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components, in
|
||||
Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the
|
||||
corresponding Copyright Holder. This restriction only applies to the
|
||||
primary font name as presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created using
|
||||
the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Ubuntu Font Licence 1.0
|
||||
|
||||
Applies to Ubuntu Light (Ubuntu-Light.ttf). Copyright notice:
|
||||
|
||||
Copyright 2011 Canonical Ltd. Licensed under the Ubuntu Font Licence 1.0
|
||||
|
||||
-------------------------------
|
||||
UBUNTU FONT LICENCE Version 1.0
|
||||
-------------------------------
|
||||
|
||||
PREAMBLE
|
||||
This licence allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely. The fonts, including any derivative works, can be
|
||||
bundled, embedded, and redistributed provided the terms of this licence
|
||||
are met. The fonts and derivatives, however, cannot be released under
|
||||
any other licence. The requirement for fonts to remain under this
|
||||
licence does not require any document created using the fonts or their
|
||||
derivatives to be published under this licence, as long as the primary
|
||||
purpose of the document is not to be a vehicle for the distribution of
|
||||
the fonts.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this licence and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Original Version" refers to the collection of Font Software components
|
||||
as received under this licence.
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to
|
||||
a new environment.
|
||||
|
||||
"Copyright Holder(s)" refers to all individuals and companies who have a
|
||||
copyright ownership of the Font Software.
|
||||
|
||||
"Substantially Changed" refers to Modified Versions which can be easily
|
||||
identified as dissimilar to the Font Software by users of the Font
|
||||
Software comparing the Original Version with the Modified Version.
|
||||
|
||||
To "Propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification and with or without charging
|
||||
a redistribution fee), making available to the public, and in some
|
||||
countries other activities as well.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
This licence does not grant any rights under trademark law and all such
|
||||
rights are reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of the Font Software, to propagate the Font Software, subject to
|
||||
the below conditions:
|
||||
|
||||
1) Each copy of the Font Software must contain the above copyright
|
||||
notice and this licence. These can be included either as stand-alone
|
||||
text files, human-readable headers or in the appropriate machine-
|
||||
readable metadata fields within text or binary files as long as those
|
||||
fields can be easily viewed by the user.
|
||||
|
||||
2) The font name complies with the following:
|
||||
(a) The Original Version must retain its name, unmodified.
|
||||
(b) Modified Versions which are Substantially Changed must be renamed to
|
||||
avoid use of the name of the Original Version or similar names entirely.
|
||||
(c) Modified Versions which are not Substantially Changed must be
|
||||
renamed to both (i) retain the name of the Original Version and (ii) add
|
||||
additional naming elements to distinguish the Modified Version from the
|
||||
Original Version. The name of such Modified Versions must be the name of
|
||||
the Original Version, with "derivative X" where X represents the name of
|
||||
the new work, appended to that name.
|
||||
|
||||
3) The name(s) of the Copyright Holder(s) and any contributor to the
|
||||
Font Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except (i) as required by this licence, (ii) to
|
||||
acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with
|
||||
their explicit written permission.
|
||||
|
||||
4) The Font Software, modified or unmodified, in part or in whole, must
|
||||
be distributed entirely under this licence, and must not be distributed
|
||||
under any other licence. The requirement for fonts to remain under this
|
||||
licence does not affect any document created using the Font Software,
|
||||
except any version of the Font Software extracted from a document
|
||||
created using the Font Software may only be distributed under this
|
||||
licence.
|
||||
|
||||
TERMINATION
|
||||
This licence becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
|
||||
COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
|
||||
DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Hack: MIT License and Bitstream Vera License
|
||||
|
||||
Applies to Hack (Hack-Regular.ttf). Upstream notice and both licence texts:
|
||||
|
||||
The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License
|
||||
|
||||
The work in the DejaVu project was committed to the public domain.
|
||||
|
||||
Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera"
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Source Foundry Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
BITSTREAM VERA LICENSE
|
||||
|
||||
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
|
||||
|
||||
The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".
|
||||
|
||||
This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.
|
||||
|
||||
The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
|
||||
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
|
||||
|
||||
MIT License (egui-icons and emoji-icon-font)
|
||||
|
||||
Applies to egui-icons.ttf, a five-glyph subset of emoji-icon-font, and the parent
|
||||
emoji-icon-font.ttf, both by John Slegers, https://github.com/jslegers/emoji-icon-font.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014 John Slegers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
EffectCraft
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors.
|
||||
Licensed under the MIT License or the Apache License, Version 2.0, at your option
|
||||
(LICENSE-MIT, LICENSE-APACHE).
|
||||
|
||||
The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are
|
||||
not open source and are not covered by the license above; their terms are in
|
||||
docs/brand/LICENSE-brand.txt.
|
||||
|
||||
Third-party material
|
||||
|
||||
This product bundles third-party material under its own licenses, listed below. The per-file
|
||||
list (author, source, license) is in ATTRIBUTION.md.
|
||||
|
||||
Bundled fonts
|
||||
|
||||
EffectCraft embeds Inter, Noto Serif, JetBrains Mono and Noto Sans Symbols 2 from
|
||||
assets/fonts/. The pinned egui dependency (epaint_default_fonts, revision
|
||||
6d518fc799681571963842f95b55a6b68431b15a) additionally embeds Ubuntu Light, Hack,
|
||||
Noto Emoji, egui-icons and emoji-icon-font through EffectCraft's enabled `default_fonts`
|
||||
and `monochrome_emoji_fonts` features; no font file from that dependency is added to
|
||||
this repository. The complete copyright notices and licence texts required for all of
|
||||
these fonts follow.
|
||||
|
||||
The optional PDF document reader uses craft-pdf and Hayro-syntax 0.7.2, MIT OR Apache-2.0.
|
||||
The shared patched syntax source is centralized in storytold/craft-libs, transferred from
|
||||
PdfCraft revision 9ed3abe4907a127d36b12fbfeee71d7e26248da1. This parser-only use embeds no
|
||||
Hayro fonts, CMaps or image codecs; EffectCraft keeps its existing fonts and drawing filters.
|
||||
|
||||
Linux Wayland window decorations
|
||||
-------------------------------
|
||||
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
|
||||
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
|
||||
for vector window controls. Its title-font features are disabled: no Cantarell
|
||||
font is embedded by this dependency and no font file is added to this repo.
|
||||
|
||||
sctk-adwaita's MIT licence:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Bartłomiej Maryńczak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
SIL Open Font License 1.1
|
||||
|
||||
Applies to Inter (assets/fonts/Inter-*.ttf), Noto Serif (assets/fonts/NotoSerif-Regular.ttf),
|
||||
JetBrains Mono (assets/fonts/JetBrainsMono-Regular.ttf), Noto Sans Symbols 2
|
||||
(assets/fonts/NotoSansSymbols2-Regular.ttf) and Noto Emoji (NotoEmoji-Regular.ttf).
|
||||
Copyright notices:
|
||||
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
|
||||
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
|
||||
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols)
|
||||
Copyright 2013 Google Inc. All Rights Reserved.
|
||||
|
||||
The fonts in assets/fonts/ also keep their upstream licence files at
|
||||
assets/fonts/OFL-<family>.txt. The complete licence text follows.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License,
|
||||
Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font
|
||||
creation efforts of academic and linguistic communities, and to
|
||||
provide a free and open framework in which fonts may be shared and
|
||||
improved in partnership with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply to
|
||||
any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software
|
||||
components as distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to,
|
||||
deleting, or substituting -- in part or in whole -- any of the
|
||||
components of the Original Version, by changing formats or by porting
|
||||
the Font Software to a new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed,
|
||||
modify, redistribute, and sell modified and unmodified copies of the
|
||||
Font Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components, in
|
||||
Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the
|
||||
corresponding Copyright Holder. This restriction only applies to the
|
||||
primary font name as presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created using
|
||||
the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Ubuntu Font Licence 1.0
|
||||
|
||||
Applies to Ubuntu Light (Ubuntu-Light.ttf). Copyright notice:
|
||||
|
||||
Copyright 2011 Canonical Ltd. Licensed under the Ubuntu Font Licence 1.0
|
||||
|
||||
-------------------------------
|
||||
UBUNTU FONT LICENCE Version 1.0
|
||||
-------------------------------
|
||||
|
||||
PREAMBLE
|
||||
This licence allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely. The fonts, including any derivative works, can be
|
||||
bundled, embedded, and redistributed provided the terms of this licence
|
||||
are met. The fonts and derivatives, however, cannot be released under
|
||||
any other licence. The requirement for fonts to remain under this
|
||||
licence does not require any document created using the fonts or their
|
||||
derivatives to be published under this licence, as long as the primary
|
||||
purpose of the document is not to be a vehicle for the distribution of
|
||||
the fonts.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this licence and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Original Version" refers to the collection of Font Software components
|
||||
as received under this licence.
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to
|
||||
a new environment.
|
||||
|
||||
"Copyright Holder(s)" refers to all individuals and companies who have a
|
||||
copyright ownership of the Font Software.
|
||||
|
||||
"Substantially Changed" refers to Modified Versions which can be easily
|
||||
identified as dissimilar to the Font Software by users of the Font
|
||||
Software comparing the Original Version with the Modified Version.
|
||||
|
||||
To "Propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification and with or without charging
|
||||
a redistribution fee), making available to the public, and in some
|
||||
countries other activities as well.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
This licence does not grant any rights under trademark law and all such
|
||||
rights are reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of the Font Software, to propagate the Font Software, subject to
|
||||
the below conditions:
|
||||
|
||||
1) Each copy of the Font Software must contain the above copyright
|
||||
notice and this licence. These can be included either as stand-alone
|
||||
text files, human-readable headers or in the appropriate machine-
|
||||
readable metadata fields within text or binary files as long as those
|
||||
fields can be easily viewed by the user.
|
||||
|
||||
2) The font name complies with the following:
|
||||
(a) The Original Version must retain its name, unmodified.
|
||||
(b) Modified Versions which are Substantially Changed must be renamed to
|
||||
avoid use of the name of the Original Version or similar names entirely.
|
||||
(c) Modified Versions which are not Substantially Changed must be
|
||||
renamed to both (i) retain the name of the Original Version and (ii) add
|
||||
additional naming elements to distinguish the Modified Version from the
|
||||
Original Version. The name of such Modified Versions must be the name of
|
||||
the Original Version, with "derivative X" where X represents the name of
|
||||
the new work, appended to that name.
|
||||
|
||||
3) The name(s) of the Copyright Holder(s) and any contributor to the
|
||||
Font Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except (i) as required by this licence, (ii) to
|
||||
acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with
|
||||
their explicit written permission.
|
||||
|
||||
4) The Font Software, modified or unmodified, in part or in whole, must
|
||||
be distributed entirely under this licence, and must not be distributed
|
||||
under any other licence. The requirement for fonts to remain under this
|
||||
licence does not affect any document created using the Font Software,
|
||||
except any version of the Font Software extracted from a document
|
||||
created using the Font Software may only be distributed under this
|
||||
licence.
|
||||
|
||||
TERMINATION
|
||||
This licence becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
|
||||
COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
|
||||
DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Hack: MIT License and Bitstream Vera License
|
||||
|
||||
Applies to Hack (Hack-Regular.ttf). Upstream notice and both licence texts:
|
||||
|
||||
The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License
|
||||
|
||||
The work in the DejaVu project was committed to the public domain.
|
||||
|
||||
Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera"
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Source Foundry Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
BITSTREAM VERA LICENSE
|
||||
|
||||
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
|
||||
|
||||
The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".
|
||||
|
||||
This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.
|
||||
|
||||
The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
|
||||
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
|
||||
|
||||
MIT License (egui-icons and emoji-icon-font)
|
||||
|
||||
Applies to egui-icons.ttf, a five-glyph subset of emoji-icon-font, and the parent
|
||||
emoji-icon-font.ttf, both by John Slegers, https://github.com/jslegers/emoji-icon-font.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014 John Slegers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,403 +1,399 @@
|
||||
<p align="center">
|
||||
<a href="https://getartcraft.com/">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/brand/artcraft-logo-white.svg">
|
||||
<img alt="ArtCraft" src="docs/brand/artcraft-logo.svg" width="200">
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.effectcraft.png" width="128" height="128" alt="EffectCraft icon: an engraved unicorn on a pink tile">
|
||||
</p>
|
||||
|
||||
<h1 align="center">EffectCraft</h1>
|
||||
|
||||
<p align="center">
|
||||
<b>Motion graphics and visual effects; an open-source, professional motion graphics and visual effects studio, built in pure Rust.</b>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
A free, open-source compositor: compositions, layers,
|
||||
keyframes, 308 effects, layer styles, expressions, 3D cameras and lights, and a render queue, native on macOS,
|
||||
Windows and Linux, and in the browser. Young, moving fast, and already usable.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="Status: young and moving fast" src="https://img.shields.io/badge/status-young%20and%20moving%20fast-e0368f?style=flat-square">
|
||||
<img alt="Written in Rust" src="https://img.shields.io/badge/rust-1.95%2B-b0206c?style=flat-square&logo=rust&logoColor=white">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-555?style=flat-square">
|
||||
<br>
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_effectcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/effectcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://getartcraft.com/apps/effectcraft"><b>EffectCraft on getartcraft.com</b></a> ·
|
||||
<a href="https://getartcraft.com/">ArtCraft</a> ·
|
||||
<a href="https://getartcraft.com/apps">All Crafting Apps</a>
|
||||
</p>
|
||||
|
||||
<br>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-hero.png" alt="EffectCraft's main window: the animated demo composition in the Composition panel, the Project panel, a Timeline with text, shape and solid layers, and the Properties panel showing the selected text layer's transform, font and paragraph settings" width="100%">
|
||||
</p>
|
||||
|
||||
> [!NOTE]
|
||||
> **ArtCraft is a community of artists from all walks of life.** Digital, generative, music,
|
||||
> games — if you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).**
|
||||
|
||||
<p align="center">
|
||||
<a href="#what-effectcraft-is">What it is</a> ·
|
||||
<a href="#animate">Animate</a> ·
|
||||
<a href="#effects">Effects</a> ·
|
||||
<a href="#3d">3D</a> ·
|
||||
<a href="#export">Export</a> ·
|
||||
<a href="#built-for-agents">Agents</a> ·
|
||||
<a href="#get-started">Get started</a> ·
|
||||
<a href="#where-it-stands">Status</a> ·
|
||||
<a href="#how-its-made">How it's made</a> ·
|
||||
<a href="#downloads">Downloads</a> ·
|
||||
<a href="#the-crafting-apps">The Crafting Apps</a> ·
|
||||
<a href="#license-and-credits">License</a>
|
||||
</p>
|
||||
|
||||
## What EffectCraft is
|
||||
|
||||
EffectCraft is for animated titles, motion graphics and compositing work: the kind of thing
|
||||
motion designers and VFX artists need. You build a composition out of layers (solids, shapes,
|
||||
text, footage, other compositions), animate their properties with keyframes, stack effects on
|
||||
them and render the result.
|
||||
|
||||
The interface feels natural and responsive, with dedicated panels (Project, Composition, Timeline,
|
||||
Layer, Footage, Effect Controls, Tools, Preview, Effects & Presets, Audio, Info, Paragraph,
|
||||
Character, Align, Progress, Render Queue) and standard motion graphics shortcuts, going further in
|
||||
a few places where it matters to us:
|
||||
|
||||
- **Lottie import and export built in**, so animations can go straight to the web and apps
|
||||
without a plugin.
|
||||
- **A project file you can read.** Projects are versioned JSON (`.ecproj`), so they diff cleanly
|
||||
in version control.
|
||||
- **Everything is scriptable.** Menu actions, timeline edits and property changes are exposed as
|
||||
commands. Engine commands are available through the CLI, JSON control channel and MCP;
|
||||
UI-only commands use the frontend dispatcher and can be invoked through the control channel
|
||||
or an attached MCP bridge.
|
||||
- **No FFmpeg.** Video and audio decoding and encoding are pure Rust: FilmCraft's codecs and
|
||||
EffectCraft's own VP9, AV1, HEVC and Opus encoders.
|
||||
|
||||
## Animate
|
||||
|
||||
The panels, menus and shortcuts follow standard motion design conventions:
|
||||
Project, Composition, Timeline, Effect Controls, Properties, Effects & Presets, Character,
|
||||
Paragraph, Align, Info, Preview, Audio and the Render Queue, docked the way you expect. Drag
|
||||
footage, comps and effects between them: onto the comp viewer, where they land under the pointer,
|
||||
or into the Timeline, between layers and at the time you point to.
|
||||
|
||||
- **Layers of every kind:** solids, shapes, text, footage, nested compositions, nulls,
|
||||
adjustment layers, cameras and lights; parenting, track mattes, all 38 blend modes, motion blur.
|
||||
- **Keyframes that behave the same:** linear, Bezier, hold, auto and continuous Bezier, roving
|
||||
keys, Easy Ease (F9), Keyframe Velocity and Interpolation dialogs, copy and paste at the current
|
||||
time, and a **Graph Editor** with value and speed graphs and draggable handles.
|
||||
- **Time:** time remapping, time stretch, time-reverse, freeze frame, work area, markers, exact
|
||||
frame-accurate timing at every frame rate including 29.97 drop-frame.
|
||||
- **Shapes and masks:** shape layers with trim paths, repeaters, round corners, offset, zig zag,
|
||||
twist, wiggle, merge paths and gradient strokes; masks drawn with the pen tool, with modes,
|
||||
feather, expansion and vertex editing in the viewer.
|
||||
- **Text:** point and paragraph text with real shaping in any font installed on your machine, the
|
||||
Character and Paragraph panels, and text animators with range selectors.
|
||||
- **Expressions:** JavaScript with the standard motion expressions model (`wiggle`, `loopOut`,
|
||||
`thisComp.layer("…")`, vector maths on arrays), an inline editor and the pick-whip.
|
||||
- **Timeline like you know it:** twirl layers open to Transform, masks, effects and the rest; drag
|
||||
rows to reorder layers; rename with Enter or a double-click; the property shortcuts (A, P, S,
|
||||
R, T, M, F, E, L, U and their double presses AA, PP, SS, RR, TT, MM, FF, EE, LL, UU), Shift to
|
||||
add properties, Alt+Shift+A/P/S/R/T to key the current time, Ctrl+` to twirl selected layers.
|
||||
- **Puppet tools:** Position, Advanced, Bend, Starch and Overlap pins on a mesh built from the
|
||||
layer, real-time pin recording, rotate/scale handles, pins driven by (or carrying) nulls for
|
||||
rigging, and follow-through for hair and cloth.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-graph-editor.png" alt="The Graph Editor showing an eased value curve for a text animator's Range Start, with the graph editor's button bar for hold, linear, auto Bezier and Easy Ease" width="100%">
|
||||
</p>
|
||||
|
||||
## Effects
|
||||
|
||||
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,
|
||||
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…),
|
||||
**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.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-effects.png" alt="A CC Particle World burst with Glow, and the Effect Controls panel listing the particle system's parameters" width="100%">
|
||||
</p>
|
||||
|
||||
## 3D
|
||||
|
||||
Classic 3D compositing: 3D layers with orientation and material options,
|
||||
one- and two-node **cameras** with depth of field, **lights** (parallel, spot, point, ambient)
|
||||
with soft ray-traced shadows, layers that intersect correctly, orbit, pan and dolly camera
|
||||
tools, and Front, Top, Left and Custom views.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-3d.png" alt="The 3D Showcase demo in Custom View 1: intersecting cards lit by a spot light with soft shadows on a gridded floor, with the camera frustum and light drawn as wireframes" width="100%">
|
||||
</p>
|
||||
|
||||
## Export
|
||||
|
||||
A dedicated Render Queue, with Render Settings and Output Modules: **H.264** MP4 and
|
||||
**ProRes** MOV (Proxy to 4444 XQ with alpha) with audio, **HEVC** (Main / Main 10) and **AV1**
|
||||
MP4, **WebM** (VP9 with inter frames and alpha, or AV1; Opus audio), PNG, JPEG, TIFF, Targa and 32-bit EXR sequences, animated GIF and WAV/AIFF. Field
|
||||
rendering with 3:2 pulldown, effect/solo/guide/depth overrides, crop, region of interest and
|
||||
resize, Render Settings and Output Module templates with defaults, post-render actions, storage
|
||||
overflow and render logs. The same queue runs from the command line. Every encoder is pure
|
||||
Rust (FilmCraft's H.264, ProRes and AAC; EffectCraft's own VP9, AV1, HEVC and Opus); there is no
|
||||
FFmpeg inside.
|
||||
|
||||
**Lottie** goes both ways: File ▸ Export ▸ Lottie JSON… writes a composition (precomps, shape,
|
||||
solid, image, text and null layers, eased and spatial keyframes, masks, track mattes, blend
|
||||
modes, time remapping, optionally expressions) as `.json` or `.lottie`, and lists anything Lottie
|
||||
cannot express; File ▸ Import ▸ Lottie… opens one as a new composition.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-render-queue.png" alt="The Render Queue panel with two compositions queued" width="100%">
|
||||
</p>
|
||||
|
||||
## Built for agents
|
||||
|
||||
Engine commands are available through the CLI, JSON control channel and MCP. UI-only commands
|
||||
need the running app's frontend dispatcher: complete menu access requires the app's control
|
||||
channel or an attached MCP bridge. Headless MCP sessions expose supported engine commands,
|
||||
but not UI-only commands or bridge-only `ui_*` tools.
|
||||
|
||||
- **MCP server:** `effectcraft-cli mcp` speaks the Model Context Protocol over stdio, headless
|
||||
or bridged to the running app (`--bridge 9877`). Tools cover commands, the project and property
|
||||
tree, keyframes and rendered frames. This repository ships a ready [`.mcp.json`](.mcp.json).
|
||||
- **Command line:** one-shot calls with JSON output, for example
|
||||
`effectcraft-cli set Main '#1' transform/position '[100,360]' --time 0 main.ecproj --save`
|
||||
or `effectcraft-cli render --comp Main --out main.mp4`, or
|
||||
`effectcraft-cli exec file.exportLottie '{"comp":"Main","path":"main.json"}' main.ecproj`.
|
||||
- **Control channel:** `effectcraft --control 9877` accepts JSON lines to run commands, inspect
|
||||
and click any widget by its automation id, and take screenshots.
|
||||
|
||||
See [docs/agents.md](docs/agents.md) and [docs/control-protocol.md](docs/control-protocol.md).
|
||||
|
||||
## Get started
|
||||
|
||||
Installers for each version are on the [Releases](https://github.com/storytold/effectcraft/releases)
|
||||
page: a universal macOS app; Windows MSIs and portable zips for x64, x86 and ARM64; Linux
|
||||
AppImage, Flatpak, deb, rpm and tar.gz for x86_64 and aarch64, plus a riscv64 tar.gz; a FreeBSD x86_64 tarball; and the
|
||||
web build. [Downloads](#downloads) lists every file. The Windows ARM64 build runs natively on
|
||||
Windows on ARM, without x64 emulation. CI installs that MSI on Windows 11 ARM64 hardware, checks
|
||||
both programs are ARM64 and runs the command-line tool there, but it doesn't open the app's window
|
||||
or run the test suite natively on ARM64 yet, so please report anything that behaves differently.
|
||||
|
||||
On Gentoo, the community [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages
|
||||
the Linux release as `media-video/effectcraft-bin` (not maintained by the EffectCraft team):
|
||||
|
||||
```sh
|
||||
eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git
|
||||
emaint sync -r snakebyte
|
||||
echo 'media-video/effectcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/effectcraft
|
||||
emerge --ask media-video/effectcraft-bin
|
||||
```
|
||||
|
||||
To build it yourself you need [Rust](https://rustup.rs/) 1.95 or newer.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/storytold/effectcraft
|
||||
cd effectcraft
|
||||
cargo run --release -p effectcraft # the app (add `-- --demo` to open the demo project)
|
||||
cargo run --release -p effectcraft-cli -- render --out intro.mp4 # render the demo headless
|
||||
cargo xtask web --serve 8765 # the browser build on http://127.0.0.1:8765/ (docs/web.md)
|
||||
```
|
||||
|
||||
New to it? [docs/footage.md](docs/footage.md) covers importing footage and image sequences and
|
||||
Interpret Footage.
|
||||
|
||||
To work on it: `cargo test --workspace`, and `cargo xtask ci` before every commit (format, lints,
|
||||
tests, layering, asset attribution and the WebAssembly build). See [CONTRIBUTING.md](CONTRIBUTING.md),
|
||||
[docs/architecture.md](docs/architecture.md) and [docs/testing.md](docs/testing.md).
|
||||
|
||||
## Where it stands
|
||||
|
||||
EffectCraft is young: its first commit was on 1 October 2026. A comprehensive feature set
|
||||
exists, including 308 effects, but breadth is not the same as full maturity across every edge
|
||||
case. Today it's a good place to try things and to tell us what breaks. It isn't yet recommended
|
||||
for production client work. In particular:
|
||||
|
||||
- **Native project format.** Projects are saved as `.ecproj`, readable versioned JSON. Proprietary
|
||||
project formats and After Effects SDK plug-ins are not supported.
|
||||
- **Fidelity is still being refined.** Automated rendering tests currently focus on small
|
||||
compositions, so please report visual discrepancies or unexpected behaviour.
|
||||
- **macOS is the most tested platform.** Linux and Windows users have hit basic interaction
|
||||
bugs, which we're fixing first.
|
||||
- **The trained models are new.** Roto Brush can use MobileSAM (an optional 40 MB download in
|
||||
Settings ▸ Roto Brush) and face tracking can use Google's MediaPipe Face Landmarker (an optional
|
||||
3.8 MB download in Settings ▸ Face Tracking). Both are actively undergoing evaluation and tuning.
|
||||
|
||||
EffectCraft is in **alpha**: about 91% of the features tracked in
|
||||
[docs/target-app-parity.md](docs/target-app-parity.md) exist, and we estimate it is about 45% of the
|
||||
way to being ready for full professional production work. The [ROADMAP](ROADMAP.md) has the plan,
|
||||
[docs/target-app-parity.md](docs/target-app-parity.md) the measurement and [docs/gaps.md](docs/gaps.md)
|
||||
every known shortfall. The web build ([docs/web.md](docs/web.md)) runs the full app in the browser.
|
||||
[Bug reports](https://github.com/storytold/effectcraft/issues) are the most useful thing you can
|
||||
send us right now.
|
||||
|
||||
## How it's made
|
||||
|
||||
- **Engine first.** A stack of small crates with strict layering. The interface (egui) sits on
|
||||
top and nothing underneath depends on it.
|
||||
- **Clean room.** We work from public documentation and observable behavior, never
|
||||
from proprietary files, icons, presets or code. No code is copied from GPL projects. The full rules
|
||||
are in [AGENTS.md](AGENTS.md).
|
||||
- **Private by default.** No telemetry, and no network access unless you ask for it.
|
||||
- **One family.** EffectCraft shares its time model and text engine design with FilmCraft, and
|
||||
gets its video and audio codecs from it.
|
||||
|
||||
## Downloads
|
||||
|
||||
**New to EffectCraft?** Download it from the [EffectCraft page on getartcraft.com](https://getartcraft.com/apps/effectcraft). That's the easiest way to install it.
|
||||
|
||||
**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/effectcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/effectcraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
|
||||
|
||||
### Windows
|
||||
|
||||
| Build | Installer | Portable |
|
||||
|---|---|---|
|
||||
| x64 (64-bit Intel/AMD) | `effectcraft-<ver>-windows-x64.msi` | `effectcraft-<ver>-windows-x64-portable.zip` |
|
||||
| arm64 (Snapdragon and other ARM PCs) | `effectcraft-<ver>-windows-arm64.msi` | `effectcraft-<ver>-windows-arm64-portable.zip` |
|
||||
| x86 (32-bit) | `effectcraft-<ver>-windows-x86.msi` | `effectcraft-<ver>-windows-x86-portable.zip` |
|
||||
|
||||
Installers and executables are code-signed. The installer asks who to install EffectCraft for and where. By default it installs for your
|
||||
account only, into `%LOCALAPPDATA%\Programs\ArtCraft\EffectCraft`, without an administrator prompt;
|
||||
"Everyone on this computer" installs into `C:\Program Files\ArtCraft\EffectCraft` (`Program Files (x86)` for the 32-bit build). Later versions
|
||||
install into the same folder. To install silently
|
||||
into a folder of your choice: `msiexec /i effectcraft-<ver>-windows-x64.msi /qn INSTALLFOLDER="D:\Apps\EffectCraft"`.
|
||||
A silent install is per-user by default. `INSTALLFOLDER` chooses the folder, not who it is installed for;
|
||||
add `ALLUSERS=1`, from an elevated terminal or deployment tool, for an all-users install.
|
||||
|
||||
### macOS
|
||||
|
||||
| Build | File | Notes |
|
||||
|---|---|---|
|
||||
| App, universal (Apple silicon + Intel) | `effectcraft-<ver>-macos-universal.dmg` | Signed and notarized |
|
||||
| Command-line tool, universal | `effectcraft-cli-<ver>-macos-universal.zip` | Signed and notarized |
|
||||
|
||||
### Linux
|
||||
|
||||
| Format | x86_64 | aarch64 (ARM64) | Notes |
|
||||
|---|---|---|---|
|
||||
| AppImage | `effectcraft-<ver>-linux-x86_64.AppImage` | `effectcraft-<ver>-linux-aarch64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) |
|
||||
| Flatpak | `effectcraft-<ver>-linux-x86_64.flatpak` | `effectcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
|
||||
| Debian/Ubuntu | `effectcraft-<ver>-linux-x86_64.deb` | `effectcraft-<ver>-linux-aarch64.deb` | |
|
||||
| Fedora/RHEL/openSUSE | `effectcraft-<ver>-linux-x86_64.rpm` | `effectcraft-<ver>-linux-aarch64.rpm` | |
|
||||
| Tarball | `effectcraft-<ver>-linux-x86_64.tar.gz` | `effectcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
|
||||
|
||||
RISC-V 64-bit: `effectcraft-<ver>-linux-riscv64.tar.gz` (tarball only; needs glibc 2.39+, e.g. Ubuntu 24.04+ or Debian 13+).
|
||||
|
||||
**File drag-and-drop on Linux:** The current eframe/winit 0.30 native Wayland backend does not
|
||||
deliver file-hover or file-drop events. On Hyprland and other native Wayland sessions, use
|
||||
**File ▸ Import ▸ File…** (which accepts multiple files), or start EffectCraft via XWayland if
|
||||
XWayland is installed and `DISPLAY` is set:
|
||||
|
||||
```sh
|
||||
env -u WAYLAND_DISPLAY effectcraft
|
||||
```
|
||||
|
||||
When the backend delivers events (X11/XWayland, Windows and macOS), dropping media anywhere
|
||||
in the window imports it, and a drop-target hint appears while hovering. On native Wayland the
|
||||
app cannot detect an attempt that generates no event; it shows a startup notice with the
|
||||
File ▸ Import fallback instead.
|
||||
|
||||
### FreeBSD
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `effectcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
|
||||
### Web (WebAssembly)
|
||||
|
||||
| Build | File | Notes |
|
||||
|---|---|---|
|
||||
| Static site | `effectcraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
|
||||
|
||||
## The Crafting Apps
|
||||
|
||||
EffectCraft is one of the **Crafting Apps**: free, open-source creative tools from the
|
||||
[ArtCraft](https://getartcraft.com/) team, each written from scratch in Rust and each able to
|
||||
stand on its own.
|
||||
|
||||
| | App | What it's for | Code | Learn more |
|
||||
|:-:|---|---|---|---|
|
||||
| <img src="https://raw.githubusercontent.com/storytold/photocraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png" alt="" width="32" height="32"> | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
|
||||
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
|
||||
|
||||
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
|
||||
|
||||
<br>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
|
||||
</p>
|
||||
|
||||
<h3 align="center">Come make things with us</h3>
|
||||
|
||||
<p align="center">
|
||||
Our Discord is where artists of every kind hang out: people who paint, shoot, draw, cut film,
|
||||
set type, and people still figuring out what they like to make. Share what you're working on,
|
||||
ask for help, tell us what's broken, or tell us what you wish these tools could do.
|
||||
Whatever your medium and however long you've been at it, you're welcome here.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://discord.gg/artcraft"><b>discord.gg/artcraft</b></a> ·
|
||||
<a href="https://getartcraft.com/">getartcraft.com</a> ·
|
||||
<a href="https://getartcraft.com/apps">The Crafting Apps</a> ·
|
||||
<a href="https://getartcraft.com/apps/effectcraft">EffectCraft</a>
|
||||
</p>
|
||||
|
||||
## License and credits
|
||||
|
||||
EffectCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option.
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. Required notices are in [NOTICE](NOTICE).
|
||||
|
||||
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
|
||||
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
|
||||
|
||||
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
|
||||
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
|
||||
part of this repository and EffectCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
Forks and modified versions must remove them.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
|
||||
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
|
||||
</p>
|
||||
|
||||
## Star history
|
||||
|
||||
[](https://www.star-history.com/?repos=storytold%2Feffectcraft&type=date&legend=top-left)
|
||||
<p align="center">
|
||||
<a href="https://getartcraft.com/">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/brand/artcraft-logo-white.svg">
|
||||
<img alt="ArtCraft" src="docs/brand/artcraft-logo.svg" width="200">
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.effectcraft.png" width="128" height="128" alt="EffectCraft icon: an engraved unicorn on a pink tile">
|
||||
</p>
|
||||
|
||||
<h1 align="center">EffectCraft</h1>
|
||||
|
||||
<p align="center">
|
||||
<b>Motion graphics and visual effects; an open-source, professional motion graphics and visual effects studio, built in pure Rust.</b>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
A free, open-source compositor: compositions, layers,
|
||||
keyframes, 308 effects, layer styles, expressions, 3D cameras and lights, and a render queue, native on macOS,
|
||||
Windows and Linux, and in the browser. Young, moving fast, and already usable.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="Status: young and moving fast" src="https://img.shields.io/badge/status-young%20and%20moving%20fast-e0368f?style=flat-square">
|
||||
<img alt="Written in Rust" src="https://img.shields.io/badge/rust-1.95%2B-b0206c?style=flat-square&logo=rust&logoColor=white">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-555?style=flat-square">
|
||||
<br>
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_effectcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/effectcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://getartcraft.com/apps/effectcraft"><b>EffectCraft on getartcraft.com</b></a> ·
|
||||
<a href="https://getartcraft.com/">ArtCraft</a> ·
|
||||
<a href="https://getartcraft.com/apps">All Crafting Apps</a>
|
||||
</p>
|
||||
|
||||
<br>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-hero.png" alt="EffectCraft's main window: the animated demo composition in the Composition panel, the Project panel, a Timeline with text, shape and solid layers, and the Properties panel showing the selected text layer's transform, font and paragraph settings" width="100%">
|
||||
</p>
|
||||
|
||||
> [!NOTE]
|
||||
> **ArtCraft is a community of artists from all walks of life.** Digital, generative, music,
|
||||
> games — if you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).**
|
||||
|
||||
<p align="center">
|
||||
<a href="#what-effectcraft-is">What it is</a> ·
|
||||
<a href="#animate">Animate</a> ·
|
||||
<a href="#effects">Effects</a> ·
|
||||
<a href="#3d">3D</a> ·
|
||||
<a href="#export">Export</a> ·
|
||||
<a href="#built-for-agents">Agents</a> ·
|
||||
<a href="#get-started">Get started</a> ·
|
||||
<a href="#where-it-stands">Status</a> ·
|
||||
<a href="#how-its-made">How it's made</a> ·
|
||||
<a href="#downloads">Downloads</a> ·
|
||||
<a href="#the-crafting-apps">The Crafting Apps</a> ·
|
||||
<a href="#license-and-credits">License</a>
|
||||
</p>
|
||||
|
||||
## What EffectCraft is
|
||||
|
||||
EffectCraft is for animated titles, motion graphics and compositing work: the kind of thing
|
||||
motion designers and VFX artists need. You build a composition out of layers (solids, shapes,
|
||||
text, footage, other compositions), animate their properties with keyframes, stack effects on
|
||||
them and render the result.
|
||||
|
||||
The interface feels natural and responsive, with dedicated panels (Project, Composition, Timeline,
|
||||
Layer, Footage, Effect Controls, Tools, Preview, Effects & Presets, Audio, Info, Paragraph,
|
||||
Character, Align, Progress, Render Queue) and standard motion graphics shortcuts, going further in
|
||||
a few places where it matters to us:
|
||||
|
||||
- **Lottie import and export built in**, so animations can go straight to the web and apps
|
||||
without a plugin.
|
||||
- **A project file you can read.** Projects are versioned JSON (`.ecproj`), so they diff cleanly
|
||||
in version control.
|
||||
- **Everything is scriptable.** Menu actions, timeline edits and property changes are exposed as
|
||||
commands. Engine commands are available through the CLI, JSON control channel and MCP;
|
||||
UI-only commands use the frontend dispatcher and can be invoked through the control channel
|
||||
or an attached MCP bridge.
|
||||
- **No FFmpeg.** Video and audio decoding and encoding are pure Rust: FilmCraft's codecs and
|
||||
EffectCraft's own VP9, AV1, HEVC and Opus encoders.
|
||||
|
||||
## Animate
|
||||
|
||||
The panels, menus and shortcuts follow standard motion design conventions:
|
||||
Project, Composition, Timeline, Effect Controls, Properties, Effects & Presets, Character,
|
||||
Paragraph, Align, Info, Preview, Audio and the Render Queue, docked the way you expect. Drag
|
||||
footage, comps and effects between them: onto the comp viewer, where they land under the pointer,
|
||||
or into the Timeline, between layers and at the time you point to.
|
||||
|
||||
- **Layers of every kind:** solids, shapes, text, footage, nested compositions, nulls,
|
||||
adjustment layers, cameras and lights; parenting, track mattes, all 38 blend modes, motion blur.
|
||||
- **Keyframes that behave the same:** linear, Bezier, hold, auto and continuous Bezier, roving
|
||||
keys, Easy Ease (F9), Keyframe Velocity and Interpolation dialogs, copy and paste at the current
|
||||
time, and a **Graph Editor** with value and speed graphs and draggable handles.
|
||||
- **Time:** time remapping, time stretch, time-reverse, freeze frame, work area, markers, exact
|
||||
frame-accurate timing at every frame rate including 29.97 drop-frame.
|
||||
- **Shapes and masks:** shape layers with trim paths, repeaters, round corners, offset, zig zag,
|
||||
twist, wiggle, merge paths and gradient strokes; masks drawn with the pen tool, with modes,
|
||||
feather, expansion and vertex editing in the viewer.
|
||||
- **Text:** point and paragraph text with real shaping in any font installed on your machine, the
|
||||
Character and Paragraph panels, and text animators with range selectors.
|
||||
- **Expressions:** JavaScript with the standard motion expressions model (`wiggle`, `loopOut`,
|
||||
`thisComp.layer("…")`, vector maths on arrays), an inline editor and the pick-whip.
|
||||
- **Timeline like you know it:** twirl layers open to Transform, masks, effects and the rest; drag
|
||||
rows to reorder layers; rename with Enter or a double-click; the property shortcuts (A, P, S,
|
||||
R, T, M, F, E, L, U and their double presses AA, PP, SS, RR, TT, MM, FF, EE, LL, UU), Shift to
|
||||
add properties, Alt+Shift+A/P/S/R/T to key the current time, Ctrl+` to twirl selected layers.
|
||||
- **Puppet tools:** Position, Advanced, Bend, Starch and Overlap pins on a mesh built from the
|
||||
layer, real-time pin recording, rotate/scale handles, pins driven by (or carrying) nulls for
|
||||
rigging, and follow-through for hair and cloth.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-graph-editor.png" alt="The Graph Editor showing an eased value curve for a text animator's Range Start, with the graph editor's button bar for hold, linear, auto Bezier and Easy Ease" width="100%">
|
||||
</p>
|
||||
|
||||
## Effects
|
||||
|
||||
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, Perspective Pin…), generate (Fractal Noise,
|
||||
Gradient Ramp, Stroke, Write-on, Audio Spectrum…), keying, matte, noise and grain, perspective,
|
||||
**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.
|
||||
|
||||
## 3D
|
||||
|
||||
Classic 3D compositing: 3D layers with orientation and material options,
|
||||
one- and two-node **cameras** with depth of field, **lights** (parallel, spot, point, ambient)
|
||||
with soft ray-traced shadows, layers that intersect correctly, orbit, pan and dolly camera
|
||||
tools, and Front, Top, Left and Custom views.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-3d.png" alt="The 3D Showcase demo in Custom View 1: intersecting cards lit by a spot light with soft shadows on a gridded floor, with the camera frustum and light drawn as wireframes" width="100%">
|
||||
</p>
|
||||
|
||||
## Export
|
||||
|
||||
A dedicated Render Queue, with Render Settings and Output Modules: **H.264** MP4 and
|
||||
**ProRes** MOV (Proxy to 4444 XQ with alpha) with audio, **HEVC** (Main / Main 10) and **AV1**
|
||||
MP4, **WebM** (VP9 with inter frames and alpha, or AV1; Opus audio), PNG, JPEG, TIFF, Targa and 32-bit EXR sequences, animated GIF and WAV/AIFF. Field
|
||||
rendering with 3:2 pulldown, effect/solo/guide/depth overrides, crop, region of interest and
|
||||
resize, Render Settings and Output Module templates with defaults, post-render actions, storage
|
||||
overflow and render logs. The same queue runs from the command line. Every encoder is pure
|
||||
Rust (craft-libs' H.264, ProRes, HEVC, VP9, AV1 and AAC; EffectCraft's own Opus); there is no
|
||||
FFmpeg inside.
|
||||
|
||||
**Lottie** goes both ways: File ▸ Export ▸ Lottie JSON… writes a composition (precomps, shape,
|
||||
solid, image, text and null layers, eased and spatial keyframes, masks, track mattes, blend
|
||||
modes, time remapping, optionally expressions) as `.json` or `.lottie`, and lists anything Lottie
|
||||
cannot express; File ▸ Import ▸ Lottie… opens one as a new composition.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/effectcraft-render-queue.png" alt="The Render Queue panel with two compositions queued" width="100%">
|
||||
</p>
|
||||
|
||||
## Built for agents
|
||||
|
||||
Engine commands are available through the CLI, JSON control channel and MCP. UI-only commands
|
||||
need the running app's frontend dispatcher: complete menu access requires the app's control
|
||||
channel or an attached MCP bridge. Headless MCP sessions expose supported engine commands,
|
||||
but not UI-only commands or bridge-only `ui_*` tools.
|
||||
|
||||
- **MCP server:** `effectcraft-cli mcp` speaks the Model Context Protocol over stdio, headless
|
||||
or bridged to the running app (`--bridge 9877`). Tools cover commands, the project and property
|
||||
tree, keyframes and rendered frames. This repository ships a ready [`.mcp.json`](.mcp.json).
|
||||
- **Command line:** one-shot calls with JSON output, for example
|
||||
`effectcraft-cli set Main '#1' transform/position '[100,360]' --time 0 main.ecproj --save`
|
||||
or `effectcraft-cli render --comp Main --out main.mp4`, or
|
||||
`effectcraft-cli exec file.exportLottie '{"comp":"Main","path":"main.json"}' main.ecproj`.
|
||||
- **Control channel:** `effectcraft --control 9877` accepts JSON lines to run commands, inspect
|
||||
and click any widget by its automation id, and take screenshots.
|
||||
|
||||
See [docs/agents.md](docs/agents.md) and [docs/control-protocol.md](docs/control-protocol.md).
|
||||
|
||||
## Get started
|
||||
|
||||
Installers for each version are on the [Releases](https://github.com/storytold/effectcraft/releases)
|
||||
page: a universal macOS app; Windows MSIs and portable zips for x64, x86 and ARM64; Linux
|
||||
AppImage, Flatpak, deb, rpm and tar.gz for x86_64 and aarch64, plus a riscv64 tar.gz; a FreeBSD x86_64 tarball; and the
|
||||
web build. [Downloads](#downloads) lists every file. The Windows ARM64 build runs natively on
|
||||
Windows on ARM, without x64 emulation. CI installs that MSI on Windows 11 ARM64 hardware, checks
|
||||
both programs are ARM64 and runs the command-line tool there, but it doesn't open the app's window
|
||||
or run the test suite natively on ARM64 yet, so please report anything that behaves differently.
|
||||
|
||||
On Gentoo, the community [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages
|
||||
the Linux release as `media-video/effectcraft-bin` (not maintained by the EffectCraft team):
|
||||
|
||||
```sh
|
||||
eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git
|
||||
emaint sync -r snakebyte
|
||||
echo 'media-video/effectcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/effectcraft
|
||||
emerge --ask media-video/effectcraft-bin
|
||||
```
|
||||
|
||||
To build it yourself you need [Rust](https://rustup.rs/) 1.95 or newer.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/storytold/effectcraft
|
||||
cd effectcraft
|
||||
cargo run --release -p effectcraft # the app (add `-- --demo` to open the demo project)
|
||||
cargo run --release -p effectcraft-cli -- render --out intro.mp4 # render the demo headless
|
||||
cargo xtask web --serve 8765 # the browser build on http://127.0.0.1:8765/ (docs/web.md)
|
||||
```
|
||||
|
||||
New to it? [docs/footage.md](docs/footage.md) covers importing footage and image sequences and
|
||||
Interpret Footage.
|
||||
|
||||
To work on it: `cargo test --workspace`, and `cargo xtask ci` before every commit (format, lints,
|
||||
tests, layering, asset attribution and the WebAssembly build). See [CONTRIBUTING.md](CONTRIBUTING.md),
|
||||
[docs/architecture.md](docs/architecture.md) and [docs/testing.md](docs/testing.md).
|
||||
|
||||
## Where it stands
|
||||
|
||||
EffectCraft is young: its first commit was on 1 October 2026. A comprehensive feature set
|
||||
exists, including 308 effects, but breadth is not the same as full maturity across every edge
|
||||
case. Today it's a good place to try things and to tell us what breaks. It isn't yet recommended
|
||||
for production client work. In particular:
|
||||
|
||||
- **Native project format.** Projects are saved as `.ecproj`, readable versioned JSON. Proprietary
|
||||
project formats and After Effects SDK plug-ins are not supported.
|
||||
- **Fidelity is still being refined.** Automated rendering tests currently focus on small
|
||||
compositions, so please report visual discrepancies or unexpected behaviour.
|
||||
- **macOS is the most tested platform.** Linux and Windows users have hit basic interaction
|
||||
bugs, which we're fixing first.
|
||||
- **The trained models are new.** Roto Brush can use MobileSAM (an optional 40 MB download in
|
||||
Settings ▸ Roto Brush) and face tracking can use Google's MediaPipe Face Landmarker (an optional
|
||||
3.8 MB download in Settings ▸ Face Tracking). Both are actively undergoing evaluation and tuning.
|
||||
|
||||
EffectCraft is in **alpha**: about 91% of the features tracked in
|
||||
[docs/target-app-parity.md](docs/target-app-parity.md) exist, and we estimate it is about 45% of the
|
||||
way to being ready for full professional production work. The [ROADMAP](ROADMAP.md) has the plan,
|
||||
[docs/target-app-parity.md](docs/target-app-parity.md) the measurement and [docs/gaps.md](docs/gaps.md)
|
||||
every known shortfall. The web build ([docs/web.md](docs/web.md)) runs the full app in the browser.
|
||||
[Bug reports](https://github.com/storytold/effectcraft/issues) are the most useful thing you can
|
||||
send us right now.
|
||||
|
||||
## How it's made
|
||||
|
||||
- **Engine first.** A stack of small crates with strict layering. The interface (egui) sits on
|
||||
top and nothing underneath depends on it.
|
||||
- **Clean room.** We work from public documentation and observable behavior, never
|
||||
from proprietary files, icons, presets or code. No code is copied from GPL projects. The full rules
|
||||
are in [AGENTS.md](AGENTS.md).
|
||||
- **Private by default.** No telemetry, and no network access unless you ask for it.
|
||||
- **One family.** EffectCraft shares its time model and text engine design with FilmCraft, and
|
||||
gets its video and audio codecs from it.
|
||||
|
||||
## Downloads
|
||||
|
||||
**New to EffectCraft?** Download it from the [EffectCraft page on getartcraft.com](https://getartcraft.com/apps/effectcraft). That's the easiest way to install it.
|
||||
|
||||
**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/effectcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/effectcraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
|
||||
|
||||
### Windows
|
||||
|
||||
| Build | Installer | Portable |
|
||||
|---|---|---|
|
||||
| x64 (64-bit Intel/AMD) | `effectcraft-<ver>-windows-x64.msi` | `effectcraft-<ver>-windows-x64-portable.zip` |
|
||||
| arm64 (Snapdragon and other ARM PCs) | `effectcraft-<ver>-windows-arm64.msi` | `effectcraft-<ver>-windows-arm64-portable.zip` |
|
||||
| x86 (32-bit) | `effectcraft-<ver>-windows-x86.msi` | `effectcraft-<ver>-windows-x86-portable.zip` |
|
||||
|
||||
Installers and executables are code-signed. The installer asks who to install EffectCraft for and where. By default it installs for your
|
||||
account only, into `%LOCALAPPDATA%\Programs\ArtCraft\EffectCraft`, without an administrator prompt;
|
||||
"Everyone on this computer" installs into `C:\Program Files\ArtCraft\EffectCraft` (`Program Files (x86)` for the 32-bit build). Later versions
|
||||
install into the same folder. To install silently
|
||||
into a folder of your choice: `msiexec /i effectcraft-<ver>-windows-x64.msi /qn INSTALLFOLDER="D:\Apps\EffectCraft"`.
|
||||
A silent install is per-user by default. `INSTALLFOLDER` chooses the folder, not who it is installed for;
|
||||
add `ALLUSERS=1`, from an elevated terminal or deployment tool, for an all-users install.
|
||||
|
||||
### macOS
|
||||
|
||||
| Build | File | Notes |
|
||||
|---|---|---|
|
||||
| App, universal (Apple silicon + Intel) | `effectcraft-<ver>-macos-universal.dmg` | Signed and notarized |
|
||||
| Command-line tool, universal | `effectcraft-cli-<ver>-macos-universal.zip` | Signed and notarized |
|
||||
|
||||
### Linux
|
||||
|
||||
| Format | x86_64 | aarch64 (ARM64) | Notes |
|
||||
|---|---|---|---|
|
||||
| AppImage | `effectcraft-<ver>-linux-x86_64.AppImage` | `effectcraft-<ver>-linux-aarch64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) |
|
||||
| Flatpak | `effectcraft-<ver>-linux-x86_64.flatpak` | `effectcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
|
||||
| Debian/Ubuntu | `effectcraft-<ver>-linux-x86_64.deb` | `effectcraft-<ver>-linux-aarch64.deb` | |
|
||||
| Fedora/RHEL/openSUSE | `effectcraft-<ver>-linux-x86_64.rpm` | `effectcraft-<ver>-linux-aarch64.rpm` | |
|
||||
| Tarball | `effectcraft-<ver>-linux-x86_64.tar.gz` | `effectcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
|
||||
|
||||
RISC-V 64-bit: `effectcraft-<ver>-linux-riscv64.tar.gz` (tarball only; needs glibc 2.39+, e.g. Ubuntu 24.04+ or Debian 13+).
|
||||
|
||||
**File drag-and-drop on Linux:** The current eframe/winit 0.30 native Wayland backend does not
|
||||
deliver file-hover or file-drop events. On Hyprland and other native Wayland sessions, use
|
||||
**File ▸ Import ▸ File…** (which accepts multiple files), or start EffectCraft via XWayland if
|
||||
XWayland is installed and `DISPLAY` is set:
|
||||
|
||||
```sh
|
||||
env -u WAYLAND_DISPLAY effectcraft
|
||||
```
|
||||
|
||||
When the backend delivers events (X11/XWayland, Windows and macOS), dropping media anywhere
|
||||
in the window imports it, and a drop-target hint appears while hovering. On native Wayland the
|
||||
app cannot detect an attempt that generates no event; it shows a startup notice with the
|
||||
File ▸ Import fallback instead.
|
||||
|
||||
### FreeBSD
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `effectcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
|
||||
### Web (WebAssembly)
|
||||
|
||||
| Build | File | Notes |
|
||||
|---|---|---|
|
||||
| Static site | `effectcraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
|
||||
|
||||
## The Crafting Apps
|
||||
|
||||
EffectCraft is one of the **Crafting Apps**: free, open-source creative tools from the
|
||||
[ArtCraft](https://getartcraft.com/) team, each written from scratch in Rust and each able to
|
||||
stand on its own.
|
||||
|
||||
| | App | What it's for | Code | Learn more |
|
||||
|:-:|---|---|---|---|
|
||||
| <img src="https://raw.githubusercontent.com/storytold/photocraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png" alt="" width="32" height="32"> | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
|
||||
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
|
||||
|
||||
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
|
||||
|
||||
<br>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
|
||||
</p>
|
||||
|
||||
<h3 align="center">Come make things with us</h3>
|
||||
|
||||
<p align="center">
|
||||
Our Discord is where artists of every kind hang out: people who paint, shoot, draw, cut film,
|
||||
set type, and people still figuring out what they like to make. Share what you're working on,
|
||||
ask for help, tell us what's broken, or tell us what you wish these tools could do.
|
||||
Whatever your medium and however long you've been at it, you're welcome here.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://discord.gg/artcraft"><b>discord.gg/artcraft</b></a> ·
|
||||
<a href="https://getartcraft.com/">getartcraft.com</a> ·
|
||||
<a href="https://getartcraft.com/apps">The Crafting Apps</a> ·
|
||||
<a href="https://getartcraft.com/apps/effectcraft">EffectCraft</a>
|
||||
</p>
|
||||
|
||||
## License and credits
|
||||
|
||||
EffectCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option.
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. Required notices are in [NOTICE](NOTICE).
|
||||
|
||||
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
|
||||
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
|
||||
|
||||
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
|
||||
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
|
||||
part of this repository and EffectCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
Forks and modified versions must remove them.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
|
||||
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
|
||||
</p>
|
||||
|
||||
## Star history
|
||||
|
||||
[](https://www.star-history.com/?repos=storytold%2Feffectcraft&type=date&legend=top-left)
|
||||
+193
-193
@@ -1,193 +1,193 @@
|
||||
# EffectCraft Roadmap
|
||||
|
||||
**Stage: alpha** · next: beta, ~30 points of "ready for real work" and ~350–620 h away
|
||||
|
||||
> **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
|
||||
[docs/target-app-parity.md](docs/target-app-parity.md), the work list in
|
||||
[docs/gaps.md](docs/gaps.md), and the plan in [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
## Headline numbers
|
||||
|
||||
| | Value | Kind |
|
||||
|---|---|---|
|
||||
| **Feature breadth** | **≈ 91%** | Estimated, weighted by area; the self-graded 92-item checklist says ≈ 99% |
|
||||
| **Ready for real work** | **≈ 45%** (40–50%) | Estimated; one live fidelity measurement so far |
|
||||
| **Mainstream practitioner** | **≈ 47%** | Estimated: the typical motion designer's weekly work ([how](docs/target-app-parity.md#mainstream-practitioner-and-essentials-user)) |
|
||||
| **Essentials user** | **≈ 52%** | Estimated: core features only ([how](docs/target-app-parity.md#essentials-user)) |
|
||||
| Remaining to **beta** | **≈ 350–620 Opus 5.5 agent-hours** | Estimated |
|
||||
| Remaining to **full parity** | **≈ 850–1,500 Opus 5.5 agent-hours** | Estimated; ≈ 70% parallelises |
|
||||
|
||||
| Audience | Ready % | Hours to ~95% | Work that dominates |
|
||||
|---|---:|---:|---|
|
||||
| Full target | ≈ 45% | ≈ 850–1,500 h | `.aep`, fidelity corpus, bug backlog, performance, formats, hardware, localization |
|
||||
| Mainstream practitioner | ≈ 47% | ≈ 280–530 h | `.aep` exchange, stability, everyday fidelity and bugs, preview speed |
|
||||
| Essentials user | ≈ 52% | ≈ 150–300 h | Opening tutorial `.aep` files, start-up stability, core bugs, preview with sound |
|
||||
|
||||
About 60–70% of these hours parallelise ([detail](docs/target-app-parity.md#readiness-by-audience)).
|
||||
|
||||
Hours are one Opus 5.5 agent working sequentially, calibrated on this repository's history
|
||||
([how](docs/target-app-parity.md#calibration-of-the-hours)).
|
||||
|
||||
### Stage
|
||||
|
||||
**Alpha**, because all six core workflows of the [alpha gate](docs/roadmap.md#alpha-gate)
|
||||
(set up, animate, text and shapes, composite, preview, save and deliver) work end to end on macOS
|
||||
and the work saves and reopens, and ready for real work (≈ 45%) is above the ≈ 40% bar. But: After Effects projects (`.aep`) can't be opened, which
|
||||
alone rules out beta; fidelity against After Effects is measured for one narrow case (scalar ease,
|
||||
168 samples); 216 issues are open on 12 October, six of them crash reports (#580, #501, #426, #341, #234, #879). Beta needs ≈ 75% ready and `.aep`
|
||||
opening reliably: the `.aep` owner decision and importer (80–160 h), the fidelity harness and
|
||||
P0/P1 corpus (60–100 h), the crash and bug backlog (40–80 h), performance (40–70 h),
|
||||
Linux/Windows reliability (30–50 h) and depth in animation, masks, effects and text (100–160 h).
|
||||
|
||||
## By dimension
|
||||
|
||||
| Dimension | % | Hours | Doc |
|
||||
|---|---:|---:|---|
|
||||
| Features: breadth | 91% | — | [target-app-parity.md](docs/target-app-parity.md#by-feature-area) |
|
||||
| Features: ready for real work | 50% | 360–660 | [target-app-parity.md](docs/target-app-parity.md#by-feature-area) |
|
||||
| UI/UX fidelity | 65% | 60–120 | [ui-parity.md](docs/ui-parity.md) |
|
||||
| File formats | 50% | 130–230 | [file-format-parity.md](docs/file-format-parity.md) |
|
||||
| Hardware | 40% | 60–120 | [hardware-parity.md](docs/hardware-parity.md) |
|
||||
| Localization | 24% | 60–110 + review | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Performance | 35% | 50–100 | [gaps.md](docs/gaps.md#g5-performance-at-real-world-scale) |
|
||||
| Stability | 45% | 40–80 | [gaps.md](docs/gaps.md#g3-stability-and-a-green-main) |
|
||||
| Platforms | 65% | 30–60 | [gaps.md](docs/gaps.md#g2-real-user-reliability-on-every-platform) |
|
||||
| Ecosystem and plug-ins | 20% | 40–80 | [plugins.md](docs/plugins.md), [scripting-parity.md](docs/scripting-parity.md) |
|
||||
| AI features | 35% | 40–80 | [gaps.md](docs/gaps.md) |
|
||||
| Agent control (beyond After Effects) | ahead | — | [agents.md](docs/agents.md) |
|
||||
|
||||
## Features
|
||||
|
||||
| Area | Breadth | Ready | Hours |
|
||||
|---|---:|---:|---:|
|
||||
| Project, footage and import | 92% | 55% | 25–45 |
|
||||
| Compositions, layers and compositing | 98% | 60% | 30–55 |
|
||||
| Animation: keyframes, graph editor, motion paths, puppet | 97% | 55% | 35–60 |
|
||||
| Expressions and scripting ([detail](docs/scripting-parity.md)) | 93% | 65% | 20–40 |
|
||||
| Shapes, masks and roto | 93% | 45% | 30–50 |
|
||||
| Text and typography | 94% | 50% | 20–35 |
|
||||
| Effects and animation presets ([detail](docs/effects-parity.md)) | 85% | 40% | 70–130 |
|
||||
| 3D (Classic and Advanced) | 82% | 35% | 35–65 |
|
||||
| Tracking and AI-assisted tools | 80% | 35% | 35–70 |
|
||||
| Preview and cache | 92% | 40% | 25–50 |
|
||||
| Render queue and export | 85% | 55% | 25–45 |
|
||||
| Audio | 85% | 45% | 6–12 |
|
||||
|
||||
Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#by-feature-area).
|
||||
|
||||
## Languages
|
||||
|
||||
UI strings translated out of ≈ 4,200 (detail: [localization-parity.md](docs/localization-parity.md)).
|
||||
|
||||
| Language | Status | % |
|
||||
|---|---|---:|
|
||||
| English | full | 100% |
|
||||
| Simplified Chinese | partial (menus, most of the panels) | 46% |
|
||||
| Spanish | menus only | 29% |
|
||||
| Hindi | none | 0% |
|
||||
| Arabic | none | 0% |
|
||||
| French | menus only | 16% |
|
||||
| Portuguese (Brazil) | partial (menus, part of the panels) | 34% |
|
||||
| Indonesian | none | 0% |
|
||||
| Japanese | partial (menus, most of the panels) | 46% |
|
||||
| German | menus only | 16% |
|
||||
| Korean | none | 0% |
|
||||
| Vietnamese | none | 0% |
|
||||
|
||||
Also shipped: Traditional Chinese (partial, 38%), Ukrainian (partial, 29%), Czech (partial, 29%), Polish (partial, 34%), Georgian (partial, 39%; native-speaker reviewed), Russian (menus only, 15%) and Swedish (menus, panels and effect names; not yet measured). No other language has had
|
||||
native-speaker review.
|
||||
|
||||
## Upcoming
|
||||
|
||||
Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gaps.md).
|
||||
|
||||
| | Next | Hours |
|
||||
|---|---|---:|
|
||||
| 1 | Fix the open crash reports; run `cargo xtask ci` on every pull request (G3) | 15–30 |
|
||||
| 2 | Fidelity harness against After Effects: rendered frames, a corpus case per P0/P1 feature (G1) | 60–100 |
|
||||
| 3 | Real-user reliability on Linux and Windows; the open mask, effect, text and 3D bugs (G2) | 100–190 |
|
||||
| 4 | `.aep` / `.aepx` import, after the owner's clean-room decision (G4) | 80–160 |
|
||||
| 5 | Performance: benchmarks at 1080p / 4K, real-time cached playback, hardware video (G5) | 50–100 |
|
||||
| 6 | Localization depth: effect names, all panels, Korean / Italian (G9) | 60–110 |
|
||||
|
||||
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
|
||||
animation preset can hold several (#2552). The Composition panel pans while a mask vertex is
|
||||
held at its edge (#999). Effect buffers that pad a small layer stay within a memory budget
|
||||
(#2261); an MP4 lasts as long as its edit list shows (#2592); the Render Queue's times tick
|
||||
between frames (#2593). ScriptUI drags keep their control past the window edge with
|
||||
`MouseEvent.buttons` (#2584), and docked panels get their dock's size and `onResize` (#2585).
|
||||
- 2026-10-28: A shape layer's Rectangle and Ellipse Size get the Constrain Proportions chain
|
||||
that Scale has, so a circle stays a circle while its size is typed, scrubbed or keyed; it
|
||||
starts off, so existing shapes behave as before (#2489).
|
||||
- 2026-10-24: Shape layers have the Wiggle Transform path operation (Contents ▸ Add, or
|
||||
`layer.addShapeItem {kind: "wiggler"}`): it wiggles the anchor point, position, scale and
|
||||
rotation of the paths above it by random amounts that change over time, up to the Transform
|
||||
values it holds. The copies of a Repeater above it wiggle independently as far as its
|
||||
Correlation allows; with the Repeater below it, they wiggle together.
|
||||
- 2026-10-22: Localization: the panel/dialog catalogs gain 303 rows in Japanese, Simplified
|
||||
Chinese and Traditional Chinese — panel tabs, form and dialog labels, panel context menus,
|
||||
tracker/graph/text-panel controls, File-panel footers and credits. Recounted after #1774:
|
||||
Japanese is 1,923 of ≈ 4,200 interface strings (46%, with 297 effect names); the Chinese
|
||||
panel catalogs hold 998 (Simplified) and 951 (Traditional) rows, and Simplified Chinese is
|
||||
46% with its 307 effect names; the overall share is ≈ 24%.
|
||||
- 2026-10-16: Convert To Bezier Path turns a shape layer's Rectangle, Ellipse or Polystar
|
||||
path into an editable Path 1 with the same geometry, as After Effects does; it used to
|
||||
apply to mask RotoBezier only, so a parametric shape path could not be converted at all
|
||||
and its vertices could not be edited or animated (#932).
|
||||
- 2026-10-14: Georgian (`ka`): every menu row, every panel-catalog row the Chinese catalogs have plus 195 Georgian-only ones, and the effect names and categories; Match System for `ka` / `ka-GE` / `ka_GE.UTF-8` locales. Reviewed by a native speaker.
|
||||
- 2026-10-12: Roto Brush span edits report strokes outside a trimmed layer without panicking;
|
||||
strokes and undo history are preserved so restoring the timing allows the span edit again.
|
||||
- 2026-10-11: Ukrainian panels caught up with the Chinese catalogs. The 95 rows the panel
|
||||
catalog gained since 9 October are translated: the Home screen (recent files, their Kind and
|
||||
Opened columns, the empty and no-match states), the viewer's toolbar tooltips, magnification,
|
||||
resolution, grid, channel and Fast Previews popups, the Appearance settings, the solid dialog
|
||||
and the project, import, export and colour-management forms. `uk` now carries 495 of the 496
|
||||
panel rows — `RGB` reads the same in Ukrainian, so it falls back to the English source by
|
||||
design — alongside its 618/618 menus.
|
||||
- 2026-10-10: Full parity re-measure against After Effects 2026 26.5 (installed bundle, 26.2–26.5
|
||||
release notes, repository counts): breadth ≈ 91%, ready ≈ 45%, stage alpha. Progress docs
|
||||
restructured: `docs/parity.md` became `docs/target-app-parity.md`; new
|
||||
`docs/roadmap.md`, `localization-parity.md`, `file-format-parity.md`, `hardware-parity.md`,
|
||||
`ui-parity.md`, `effects-parity.md` and `scripting-parity.md`.
|
||||
- 2026-10-10: Spanish (#460) and Brazilian Portuguese (#217) menu translations.
|
||||
- 2026-10-10: Japanese now translates the interface below the menu bar too: `crates/ui-egui/src/i18n/ui.rs` has a Japanese table with the same 396 rows as the Chinese ones (panels, dialogs, buttons and tooltips; the shape test keeps the three catalogs listing the same source strings). Menus were already Japanese.
|
||||
- 2026-10-09: Ukrainian now covers all 396 current panel-catalog strings, including dialogs, buttons and tooltips, alongside its menu translation. The catalog keeps the same source keys and placeholder counts as the Chinese catalogs; missing or engine-generated text still falls back to English.
|
||||
|
||||
- UI.6: Viewer breadcrumbs use theme colors for readable active text. The bottom control row scrolls horizontally at compact widths; keyboard focus reveals the selected control while dropdowns, exposure adjustments and snapshot holds retain their behavior.
|
||||
- UI.3: Shared docking transactions and pointer targets now handle panel moves, splits, tab ordering and floating groups, preserving accordion metadata and the saved workspace schema. Dock dividers use bounded shared geometry and keyboard-accessible resize handles. Tiny layouts no longer reach an invalid floating-point clamp; workspace trees and saved layouts are retained.
|
||||
|
||||
- 2026-10-09: Settings ▸ General ▸ Language now translates the interface below the menu bar as well: panels, dialogs, buttons and tooltips read their text through `crates/ui-egui/src/i18n/ui.rs`, keyed by the English source string. Simplified and Traditional Chinese are complete (384 strings); Japanese rows can follow in the same file. A test fails when a converted panel gains a hard-coded string, and another keeps the catalog free of unused rows.
|
||||
- 2026-10-08: `effectcraft-cli render --out` resolves a relative path against the working directory, like `--project` (it used the project's folder, which doubled a path that already named it). Render Queue outputs set in a project are unchanged.
|
||||
- 2026-10-08: Long-press a grouped toolbar button to choose its tools, including Horizontal/Vertical Type; releasing the hold keeps the menu open. Existing point/paragraph text creation is unchanged.
|
||||
- 2026-10-06: Settings ▸ General ▸ Language persists English/Japanese menu labels (`general.language`); native UI reuses installed Japanese font fallback, with no bundled CJK font. Dialog and panel contents remain English.
|
||||
- 2026-10-05: Honest assessment ([docs/gaps.md](docs/gaps.md)): breadth ≈ 99% by our own checklist, real use ≈ 30–50%; workstreams G1–G9.
|
||||
- 2026-10-04: Checklist audit at `d39c0e8`: 89 done / 3 partial / 0 missing of 92 features.
|
||||
- 2026-10-01: First commit.
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-30 | minor | Progress log: text Line Join, Timeline drag-reorder and Shift multi-select of effects, viewer edge pan, effect padding budget, MP4 edit-list duration, Render Queue clock, ScriptUI drag capture and docked-panel size |
|
||||
| 2026-10-22 | minor | Localization: 300 more panel/dialog rows in Japanese and the Chinese catalogs, plus the review's three missing rows (Basic, Advanced, Play/Stop) — panel tabs, form and dialog labels, context menus, tracker/graph/text-panel controls, File-panel footers, credits; language shares recounted after #1774 (Japanese 27% → 46% with 297 effect names, Simplified Chinese 29% → 46% with 307 effect names, Traditional Chinese 29% → 38%, overall 18% → 24%) |
|
||||
| 2026-10-12 | minor | Open-issue count (134 to 216), crash list and localization share (12% to 18%) updated to match docs/gaps.md |
|
||||
| 2026-10-12 | patch | Roto Brush span validation after trimming; command regressions for both layer edges |
|
||||
| 2026-10-12 | minor | Shared PDF object/xref parsing with bounded app-owned conversion and preserved stream budgets; drawing, EPS and image/font policy remain unchanged |
|
||||
| 2026-10-10 | minor | Hours to ≈ 95% for each audience |
|
||||
| 2026-10-10 | minor | Headline adds mainstream practitioner (≈ 47%) and essentials user (≈ 52%) |
|
||||
| 2026-10-10 | major | Progress docs restructured: stage, two numbers, dimensions, features, languages, upcoming, progress log; milestones moved to docs/roadmap.md |
|
||||
| 2026-10-10 | minor | Stage checked against the new core-workflow gate (all six pass; still alpha) |
|
||||
| 2026-10-05 | major | Two numbers (breadth vs real use) and workstreams G1–G9 |
|
||||
# EffectCraft Roadmap
|
||||
|
||||
**Stage: alpha** · next: beta, ~30 points of "ready for real work" and ~350–620 h away
|
||||
|
||||
> **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
|
||||
[docs/target-app-parity.md](docs/target-app-parity.md), the work list in
|
||||
[docs/gaps.md](docs/gaps.md), and the plan in [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
## Headline numbers
|
||||
|
||||
| | Value | Kind |
|
||||
|---|---|---|
|
||||
| **Feature breadth** | **≈ 91%** | Estimated, weighted by area; the self-graded 92-item checklist says ≈ 99% |
|
||||
| **Ready for real work** | **≈ 45%** (40–50%) | Estimated; one live fidelity measurement so far |
|
||||
| **Mainstream practitioner** | **≈ 47%** | Estimated: the typical motion designer's weekly work ([how](docs/target-app-parity.md#mainstream-practitioner-and-essentials-user)) |
|
||||
| **Essentials user** | **≈ 52%** | Estimated: core features only ([how](docs/target-app-parity.md#essentials-user)) |
|
||||
| Remaining to **beta** | **≈ 350–620 Opus 5.5 agent-hours** | Estimated |
|
||||
| Remaining to **full parity** | **≈ 850–1,500 Opus 5.5 agent-hours** | Estimated; ≈ 70% parallelises |
|
||||
|
||||
| Audience | Ready % | Hours to ~95% | Work that dominates |
|
||||
|---|---:|---:|---|
|
||||
| Full target | ≈ 45% | ≈ 850–1,500 h | `.aep`, fidelity corpus, bug backlog, performance, formats, hardware, localization |
|
||||
| Mainstream practitioner | ≈ 47% | ≈ 280–530 h | `.aep` exchange, stability, everyday fidelity and bugs, preview speed |
|
||||
| Essentials user | ≈ 52% | ≈ 150–300 h | Opening tutorial `.aep` files, start-up stability, core bugs, preview with sound |
|
||||
|
||||
About 60–70% of these hours parallelise ([detail](docs/target-app-parity.md#readiness-by-audience)).
|
||||
|
||||
Hours are one Opus 5.5 agent working sequentially, calibrated on this repository's history
|
||||
([how](docs/target-app-parity.md#calibration-of-the-hours)).
|
||||
|
||||
### Stage
|
||||
|
||||
**Alpha**, because all six core workflows of the [alpha gate](docs/roadmap.md#alpha-gate)
|
||||
(set up, animate, text and shapes, composite, preview, save and deliver) work end to end on macOS
|
||||
and the work saves and reopens, and ready for real work (≈ 45%) is above the ≈ 40% bar. But: After Effects projects (`.aep`) can't be opened, which
|
||||
alone rules out beta; fidelity against After Effects is measured for one narrow case (scalar ease,
|
||||
168 samples); 216 issues are open on 12 October, six of them crash reports (#580, #501, #426, #341, #234, #879). Beta needs ≈ 75% ready and `.aep`
|
||||
opening reliably: the `.aep` owner decision and importer (80–160 h), the fidelity harness and
|
||||
P0/P1 corpus (60–100 h), the crash and bug backlog (40–80 h), performance (40–70 h),
|
||||
Linux/Windows reliability (30–50 h) and depth in animation, masks, effects and text (100–160 h).
|
||||
|
||||
## By dimension
|
||||
|
||||
| Dimension | % | Hours | Doc |
|
||||
|---|---:|---:|---|
|
||||
| Features: breadth | 91% | — | [target-app-parity.md](docs/target-app-parity.md#by-feature-area) |
|
||||
| Features: ready for real work | 50% | 360–660 | [target-app-parity.md](docs/target-app-parity.md#by-feature-area) |
|
||||
| UI/UX fidelity | 65% | 60–120 | [ui-parity.md](docs/ui-parity.md) |
|
||||
| File formats | 50% | 130–230 | [file-format-parity.md](docs/file-format-parity.md) |
|
||||
| Hardware | 40% | 60–120 | [hardware-parity.md](docs/hardware-parity.md) |
|
||||
| Localization | 24% | 60–110 + review | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Performance | 35% | 50–100 | [gaps.md](docs/gaps.md#g5-performance-at-real-world-scale) |
|
||||
| Stability | 45% | 40–80 | [gaps.md](docs/gaps.md#g3-stability-and-a-green-main) |
|
||||
| Platforms | 65% | 30–60 | [gaps.md](docs/gaps.md#g2-real-user-reliability-on-every-platform) |
|
||||
| Ecosystem and plug-ins | 20% | 40–80 | [plugins.md](docs/plugins.md), [scripting-parity.md](docs/scripting-parity.md) |
|
||||
| AI features | 35% | 40–80 | [gaps.md](docs/gaps.md) |
|
||||
| Agent control (beyond After Effects) | ahead | — | [agents.md](docs/agents.md) |
|
||||
|
||||
## Features
|
||||
|
||||
| Area | Breadth | Ready | Hours |
|
||||
|---|---:|---:|---:|
|
||||
| Project, footage and import | 92% | 55% | 25–45 |
|
||||
| Compositions, layers and compositing | 98% | 60% | 30–55 |
|
||||
| Animation: keyframes, graph editor, motion paths, puppet | 97% | 55% | 35–60 |
|
||||
| Expressions and scripting ([detail](docs/scripting-parity.md)) | 93% | 65% | 20–40 |
|
||||
| Shapes, masks and roto | 93% | 45% | 30–50 |
|
||||
| Text and typography | 94% | 50% | 20–35 |
|
||||
| Effects and animation presets ([detail](docs/effects-parity.md)) | 85% | 40% | 70–130 |
|
||||
| 3D (Classic and Advanced) | 82% | 35% | 35–65 |
|
||||
| Tracking and AI-assisted tools | 80% | 35% | 35–70 |
|
||||
| Preview and cache | 92% | 40% | 25–50 |
|
||||
| Render queue and export | 85% | 55% | 25–45 |
|
||||
| Audio | 85% | 45% | 6–12 |
|
||||
|
||||
Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#by-feature-area).
|
||||
|
||||
## Languages
|
||||
|
||||
UI strings translated out of ≈ 4,200 (detail: [localization-parity.md](docs/localization-parity.md)).
|
||||
|
||||
| Language | Status | % |
|
||||
|---|---|---:|
|
||||
| English | full | 100% |
|
||||
| Simplified Chinese | partial (menus, most of the panels) | 46% |
|
||||
| Spanish | menus only | 29% |
|
||||
| Hindi | none | 0% |
|
||||
| Arabic | none | 0% |
|
||||
| French | menus only | 16% |
|
||||
| Portuguese (Brazil) | partial (menus, part of the panels) | 34% |
|
||||
| Indonesian | none | 0% |
|
||||
| Japanese | partial (menus, most of the panels) | 46% |
|
||||
| German | menus only | 16% |
|
||||
| Korean | none | 0% |
|
||||
| Vietnamese | none | 0% |
|
||||
|
||||
Also shipped: Traditional Chinese (partial, 38%), Ukrainian (partial, 29%), Czech (partial, 29%), Polish (partial, 34%), Georgian (partial, 39%; native-speaker reviewed), Russian (menus only, 15%) and Swedish (menus, panels and effect names; not yet measured). No other language has had
|
||||
native-speaker review.
|
||||
|
||||
## Upcoming
|
||||
|
||||
Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gaps.md).
|
||||
|
||||
| | Next | Hours |
|
||||
|---|---|---:|
|
||||
| 1 | Fix the open crash reports; run `cargo xtask ci` on every pull request (G3) | 15–30 |
|
||||
| 2 | Fidelity harness against After Effects: rendered frames, a corpus case per P0/P1 feature (G1) | 60–100 |
|
||||
| 3 | Real-user reliability on Linux and Windows; the open mask, effect, text and 3D bugs (G2) | 100–190 |
|
||||
| 4 | `.aep` / `.aepx` import, after the owner's clean-room decision (G4) | 80–160 |
|
||||
| 5 | Performance: benchmarks at 1080p / 4K, real-time cached playback, hardware video (G5) | 50–100 |
|
||||
| 6 | Localization depth: effect names, all panels, Korean / Italian (G9) | 60–110 |
|
||||
|
||||
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
|
||||
animation preset can hold several (#2552). The Composition panel pans while a mask vertex is
|
||||
held at its edge (#999). Effect buffers that pad a small layer stay within a memory budget
|
||||
(#2261); an MP4 lasts as long as its edit list shows (#2592); the Render Queue's times tick
|
||||
between frames (#2593). ScriptUI drags keep their control past the window edge with
|
||||
`MouseEvent.buttons` (#2584), and docked panels get their dock's size and `onResize` (#2585).
|
||||
- 2026-10-28: A shape layer's Rectangle and Ellipse Size get the Constrain Proportions chain
|
||||
that Scale has, so a circle stays a circle while its size is typed, scrubbed or keyed; it
|
||||
starts off, so existing shapes behave as before (#2489).
|
||||
- 2026-10-24: Shape layers have the Wiggle Transform path operation (Contents ▸ Add, or
|
||||
`layer.addShapeItem {kind: "wiggler"}`): it wiggles the anchor point, position, scale and
|
||||
rotation of the paths above it by random amounts that change over time, up to the Transform
|
||||
values it holds. The copies of a Repeater above it wiggle independently as far as its
|
||||
Correlation allows; with the Repeater below it, they wiggle together.
|
||||
- 2026-10-22: Localization: the panel/dialog catalogs gain 303 rows in Japanese, Simplified
|
||||
Chinese and Traditional Chinese — panel tabs, form and dialog labels, panel context menus,
|
||||
tracker/graph/text-panel controls, File-panel footers and credits. Recounted after #1774:
|
||||
Japanese is 1,923 of ≈ 4,200 interface strings (46%, with 297 effect names); the Chinese
|
||||
panel catalogs hold 998 (Simplified) and 951 (Traditional) rows, and Simplified Chinese is
|
||||
46% with its 307 effect names; the overall share is ≈ 24%.
|
||||
- 2026-10-16: Convert To Bezier Path turns a shape layer's Rectangle, Ellipse or Polystar
|
||||
path into an editable Path 1 with the same geometry, as After Effects does; it used to
|
||||
apply to mask RotoBezier only, so a parametric shape path could not be converted at all
|
||||
and its vertices could not be edited or animated (#932).
|
||||
- 2026-10-14: Georgian (`ka`): every menu row, every panel-catalog row the Chinese catalogs have plus 195 Georgian-only ones, and the effect names and categories; Match System for `ka` / `ka-GE` / `ka_GE.UTF-8` locales. Reviewed by a native speaker.
|
||||
- 2026-10-12: Roto Brush span edits report strokes outside a trimmed layer without panicking;
|
||||
strokes and undo history are preserved so restoring the timing allows the span edit again.
|
||||
- 2026-10-11: Ukrainian panels caught up with the Chinese catalogs. The 95 rows the panel
|
||||
catalog gained since 9 October are translated: the Home screen (recent files, their Kind and
|
||||
Opened columns, the empty and no-match states), the viewer's toolbar tooltips, magnification,
|
||||
resolution, grid, channel and Fast Previews popups, the Appearance settings, the solid dialog
|
||||
and the project, import, export and colour-management forms. `uk` now carries 495 of the 496
|
||||
panel rows — `RGB` reads the same in Ukrainian, so it falls back to the English source by
|
||||
design — alongside its 618/618 menus.
|
||||
- 2026-10-10: Full parity re-measure against After Effects 2026 26.5 (installed bundle, 26.2–26.5
|
||||
release notes, repository counts): breadth ≈ 91%, ready ≈ 45%, stage alpha. Progress docs
|
||||
restructured: `docs/parity.md` became `docs/target-app-parity.md`; new
|
||||
`docs/roadmap.md`, `localization-parity.md`, `file-format-parity.md`, `hardware-parity.md`,
|
||||
`ui-parity.md`, `effects-parity.md` and `scripting-parity.md`.
|
||||
- 2026-10-10: Spanish (#460) and Brazilian Portuguese (#217) menu translations.
|
||||
- 2026-10-10: Japanese now translates the interface below the menu bar too: `crates/ui-egui/src/i18n/ui.rs` has a Japanese table with the same 396 rows as the Chinese ones (panels, dialogs, buttons and tooltips; the shape test keeps the three catalogs listing the same source strings). Menus were already Japanese.
|
||||
- 2026-10-09: Ukrainian now covers all 396 current panel-catalog strings, including dialogs, buttons and tooltips, alongside its menu translation. The catalog keeps the same source keys and placeholder counts as the Chinese catalogs; missing or engine-generated text still falls back to English.
|
||||
|
||||
- UI.6: Viewer breadcrumbs use theme colors for readable active text. The bottom control row scrolls horizontally at compact widths; keyboard focus reveals the selected control while dropdowns, exposure adjustments and snapshot holds retain their behavior.
|
||||
- UI.3: Shared docking transactions and pointer targets now handle panel moves, splits, tab ordering and floating groups, preserving accordion metadata and the saved workspace schema. Dock dividers use bounded shared geometry and keyboard-accessible resize handles. Tiny layouts no longer reach an invalid floating-point clamp; workspace trees and saved layouts are retained.
|
||||
|
||||
- 2026-10-09: Settings ▸ General ▸ Language now translates the interface below the menu bar as well: panels, dialogs, buttons and tooltips read their text through `crates/ui-egui/src/i18n/ui.rs`, keyed by the English source string. Simplified and Traditional Chinese are complete (384 strings); Japanese rows can follow in the same file. A test fails when a converted panel gains a hard-coded string, and another keeps the catalog free of unused rows.
|
||||
- 2026-10-08: `effectcraft-cli render --out` resolves a relative path against the working directory, like `--project` (it used the project's folder, which doubled a path that already named it). Render Queue outputs set in a project are unchanged.
|
||||
- 2026-10-08: Long-press a grouped toolbar button to choose its tools, including Horizontal/Vertical Type; releasing the hold keeps the menu open. Existing point/paragraph text creation is unchanged.
|
||||
- 2026-10-06: Settings ▸ General ▸ Language persists English/Japanese menu labels (`general.language`); native UI reuses installed Japanese font fallback, with no bundled CJK font. Dialog and panel contents remain English.
|
||||
- 2026-10-05: Honest assessment ([docs/gaps.md](docs/gaps.md)): breadth ≈ 99% by our own checklist, real use ≈ 30–50%; workstreams G1–G9.
|
||||
- 2026-10-04: Checklist audit at `d39c0e8`: 89 done / 3 partial / 0 missing of 92 features.
|
||||
- 2026-10-01: First commit.
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-30 | minor | Progress log: text Line Join, Timeline drag-reorder and Shift multi-select of effects, viewer edge pan, effect padding budget, MP4 edit-list duration, Render Queue clock, ScriptUI drag capture and docked-panel size |
|
||||
| 2026-10-22 | minor | Localization: 300 more panel/dialog rows in Japanese and the Chinese catalogs, plus the review's three missing rows (Basic, Advanced, Play/Stop) — panel tabs, form and dialog labels, context menus, tracker/graph/text-panel controls, File-panel footers, credits; language shares recounted after #1774 (Japanese 27% → 46% with 297 effect names, Simplified Chinese 29% → 46% with 307 effect names, Traditional Chinese 29% → 38%, overall 18% → 24%) |
|
||||
| 2026-10-12 | minor | Open-issue count (134 to 216), crash list and localization share (12% to 18%) updated to match docs/gaps.md |
|
||||
| 2026-10-12 | patch | Roto Brush span validation after trimming; command regressions for both layer edges |
|
||||
| 2026-10-12 | minor | Shared PDF object/xref parsing with bounded app-owned conversion and preserved stream budgets; drawing, EPS and image/font policy remain unchanged |
|
||||
| 2026-10-10 | minor | Hours to ≈ 95% for each audience |
|
||||
| 2026-10-10 | minor | Headline adds mainstream practitioner (≈ 47%) and essentials user (≈ 52%) |
|
||||
| 2026-10-10 | major | Progress docs restructured: stage, two numbers, dimensions, features, languages, upcoming, progress log; milestones moved to docs/roadmap.md |
|
||||
| 2026-10-10 | minor | Stage checked against the new core-workflow gate (all six pass; still alpha) |
|
||||
| 2026-10-05 | major | Two numbers (breadth vs real use) and workstreams G1–G9 |
|
||||
@@ -31,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)
|
||||
//! ```
|
||||
@@ -97,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 <info|commands|exec|run|props|get|set|render-frame|render|script|mcp> [args] [--json]
|
||||
const USAGE: &str = "usage: effectcraft-cli <info|commands|exec|run|props|get|set|render-frame|render|script|replay|mcp> [args] [--json]
|
||||
info project + engine summary
|
||||
commands [--filter TEXT] [--enabled] list engine commands
|
||||
exec <command-id> [--params JSON] run one engine command (exec --list: list them, as `commands`)
|
||||
@@ -138,6 +139,9 @@ const USAGE: &str = "usage: effectcraft-cli <info|commands|exec|run|props|get|se
|
||||
script FILE.jsx [F.ecproj] | --eval CODE run JavaScript with the After Effects-style object model
|
||||
(app.project, comps, layers, properties…); prints writeLn
|
||||
output and the result; errors exit 1 with file:line:col
|
||||
replay SCRIPT.jsonl [--keep-going] replay a repro script headless (journal.export, crash repros):
|
||||
per-step ok/error and the first failure; exits 1 when a step
|
||||
fails, an expectation is not met or a command panics
|
||||
mcp [--autosave | --bridge PORT] MCP server (JSON-RPC over stdio); --autosave preserves unsaved headless work
|
||||
[--automation-read-root DIR] [--automation-write-root DIR]
|
||||
confine the agent's file access: reads under a read or write root,
|
||||
@@ -222,6 +226,7 @@ const FLAGS: &[&str] = &[
|
||||
"--small",
|
||||
"--adv3d",
|
||||
"--autosave",
|
||||
"--keep-going",
|
||||
"--progress",
|
||||
];
|
||||
|
||||
@@ -466,7 +471,7 @@ fn backend(args: &Args, default_demo: bool) -> Result<Backend, Failure> {
|
||||
}
|
||||
|
||||
/// 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<effectcraft_engine::Session, Failure> {
|
||||
let mut s = effectcraft_host::session();
|
||||
if args.flag("--autosave") {
|
||||
@@ -552,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 {
|
||||
@@ -614,6 +672,7 @@ 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)) {
|
||||
@@ -1443,7 +1502,7 @@ fn adv3d_bench_comp(p: &mut effectcraft_engine::project::Project) -> Option<Item
|
||||
/// `bench --gpu`: CPU vs GPU ms/frame for every comp (or `--comp`) at Full and Half. "cold"
|
||||
/// renders everything (no layer cache); "warm" reuses the layer cache (playback / scrubbing of
|
||||
/// unchanged layers: compositing cost); "viewer" is the GPU display path without readback;
|
||||
/// "auto" is Backend::Auto (Mercury GPU Acceleration) choosing per comp from measured times,
|
||||
/// "auto" is Backend::Auto (GPU Acceleration) choosing per comp from measured times,
|
||||
/// warm; "up/dn MB" are the GPU's uploads / readbacks per warm GPU frame.
|
||||
fn bench_gpu(s: &Session, args: &Args) -> Result<(), Failure> {
|
||||
use effectcraft_render::Backend;
|
||||
|
||||
@@ -1223,3 +1223,39 @@ fn render_exr_compression_and_depth() {
|
||||
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);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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<disk_cache::Frame8> {
|
||||
let name = disk_cache::entry_name(key);
|
||||
let bytes = JsFuture::from(cache_read(&name)).await.ok().and_then(|b| b.dyn_into::<js_sys::Uint8Array>().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() {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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<fn()>,
|
||||
/// Clock in milliseconds since the Unix epoch (tests pin it).
|
||||
pub clock: OnceLock<fn() -> f64>,
|
||||
/// Bumped when a virtual file is written. Preview cache lookups key on it; they do not hash.
|
||||
media_epoch: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
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<AtomicU64> {
|
||||
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).
|
||||
|
||||
@@ -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.
|
||||
@@ -38,6 +41,9 @@ zbus = "5.19"
|
||||
# Icon + VERSIONINFO for effectcraft.exe; build.rs only uses it when targeting Windows.
|
||||
winresource = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Keep the control channel responsive when the window is covered (App Nap / occlusion throttling).
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSProcessInfo", "NSString", "NSObject"] }
|
||||
|
||||
@@ -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::<chrono::Utc>::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<u64>,
|
||||
total: u64,
|
||||
last_at: Option<String>,
|
||||
last_uptime_secs: Option<u64>,
|
||||
}
|
||||
|
||||
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<u64>,
|
||||
started: Instant,
|
||||
started_at: String,
|
||||
detected_at: Option<String>,
|
||||
last_sample: Instant,
|
||||
memory: Memory,
|
||||
// Only Windows can retrieve an unrelated process's ExitStatus through a retained handle.
|
||||
exit: Receiver<Option<std::process::ExitStatus>>,
|
||||
status: Option<std::process::ExitStatus>,
|
||||
alive: Option<bool>,
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,803 @@
|
||||
//! 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<std::sync::Mutex<Option<Reporter>>>);
|
||||
|
||||
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<Reporter> {
|
||||
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<Reporter> {
|
||||
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::<u32>().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<Message> {
|
||||
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<bool> {
|
||||
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<String>,
|
||||
) -> io::Result<PathBuf> {
|
||||
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<PathBuf>, 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<PathBuf> {
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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<AtomicU8>,
|
||||
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"]);
|
||||
}
|
||||
}
|
||||
@@ -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<File> {
|
||||
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<Backends>,
|
||||
pub source: BackendSource,
|
||||
/// Switched to OpenGL because the previous launch stopped as its window opened: the message
|
||||
/// to show.
|
||||
pub notice: Option<String>,
|
||||
marker: Option<PathBuf>,
|
||||
/// 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<File>,
|
||||
/// When the window drew its first frame, until the launch settles.
|
||||
first_frame: Option<Instant>,
|
||||
@@ -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();
|
||||
@@ -136,12 +214,13 @@ mod tests {
|
||||
/// A launch that never drew switches the next one to OpenGL, which then stays (#243).
|
||||
#[test]
|
||||
fn a_launch_that_never_drew_switches_the_next_to_opengl() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-launch-guard-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("never-drew");
|
||||
// A first launch that draws: nothing changes. Its first frames don't settle it (a driver
|
||||
// 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);
|
||||
}
|
||||
@@ -176,8 +259,8 @@ mod tests {
|
||||
/// normal quit in that time doesn't.
|
||||
#[test]
|
||||
fn a_launch_that_stops_after_its_first_frame_switches_the_next_to_opengl() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-launch-guard-3-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("first-frame");
|
||||
let mut l = Launch::begin(Some(&dir), false);
|
||||
assert!(l.frame_drawn().is_some());
|
||||
drop(l);
|
||||
@@ -203,8 +286,8 @@ mod tests {
|
||||
/// open a window either goes back to Automatic instead of failing every launch.
|
||||
#[test]
|
||||
fn a_second_copy_or_failed_opengl_doesnt_strand_window_graphics() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-launch-guard-2-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("second-copy");
|
||||
let _first = Launch::begin(Some(&dir), false);
|
||||
assert_eq!(Launch::begin(Some(&dir), false).backends, None);
|
||||
assert_eq!(window_graphics(&dir), "auto");
|
||||
@@ -217,4 +300,240 @@ mod tests {
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A fresh settings folder for one test.
|
||||
fn fresh_dir(case: &str) -> PathBuf {
|
||||
tempfile::Builder::new().prefix(&format!("ec-launch-guard-{case}-")).tempdir().unwrap().keep()
|
||||
}
|
||||
|
||||
/// 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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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 _spawn_lock = crate::test_child_spawn_lock();
|
||||
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);
|
||||
}
|
||||
}
|
||||
+111
-16
@@ -8,7 +8,9 @@
|
||||
//! `--demo` opens the demo project instead (also Help ▸ Open Demo Project).
|
||||
//!
|
||||
//! `--control <port>` (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;
|
||||
@@ -31,6 +35,17 @@ mod window;
|
||||
use effectcraft_ui_egui::EffectcraftApp;
|
||||
use serde_json::json;
|
||||
|
||||
// On Unix, a subprocess briefly inherits every non-CLOFORK descriptor between fork and exec.
|
||||
// The app's guard-lock tests hold an advisory lock while crash-reporter tests spawn child
|
||||
// processes; coordinate just those intervals so an unrelated test child cannot extend a lock.
|
||||
#[cfg(test)]
|
||||
static TEST_CHILD_SPAWN_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
#[cfg(test)]
|
||||
fn test_child_spawn_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
TEST_CHILD_SPAWN_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The app icon for the window, taskbar and Dock (assets/app-icon, regenerated by
|
||||
/// `packaging/icons.sh`). macOS gets the padded variant so it sits on Apple's icon grid in the Dock.
|
||||
/// The 256 px app icon (Windows, Linux; the AppImage's desktop integration installs it too).
|
||||
@@ -112,6 +127,13 @@ fn parse_args(args: impl IntoIterator<Item = String>, env_port: Result<String, s
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// Whether the app looks for a newer release when it starts. Not when started for an agent
|
||||
/// (`--control`): the "update available" prompt is modal and would block the run until a person
|
||||
/// dismisses it. Help ▸ Check for Updates still works.
|
||||
fn startup_update_check(control_port: Option<u16>) -> 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<u16, String> {
|
||||
@@ -171,6 +193,23 @@ fn start_helpers_if_opted_in(session: &mut effectcraft_engine::Session) {
|
||||
/// 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::<Vec<_>>()) {
|
||||
@@ -196,20 +235,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 {
|
||||
@@ -236,22 +293,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}");
|
||||
@@ -259,6 +334,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);
|
||||
});
|
||||
}
|
||||
@@ -310,7 +386,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 {
|
||||
@@ -389,6 +465,7 @@ fn main() -> eframe::Result {
|
||||
window: window::Tracker::new(opened, saved_window, control_port.is_none()),
|
||||
launch,
|
||||
drawn: false,
|
||||
reporter: desktop_reporter,
|
||||
}))
|
||||
}),
|
||||
);
|
||||
@@ -482,6 +559,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 {
|
||||
@@ -516,15 +594,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();
|
||||
effectcraft_host::stop_helpers();
|
||||
// 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) {
|
||||
@@ -666,6 +749,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]
|
||||
|
||||
+8
-8
@@ -1,8 +1,8 @@
|
||||
allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
@@ -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
|
||||
@@ -134,3 +135,6 @@ display_name = "Jonathan Cardoso"
|
||||
|
||||
[people.nazar-gavrylyk]
|
||||
sync_github_name = true
|
||||
|
||||
[people.andreaaazo]
|
||||
sync_github_name = true
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "effectcraft-aep"
|
||||
description = "After Effects projects: the .aep (RIFX 'Egg!') / .aepx container as a lossless chunk tree with a typed view, and its import into an EffectCraft project, which reports everything it does not carry over"
|
||||
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
|
||||
@@ -10,18 +10,15 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-aep = { workspace = true }
|
||||
effectcraft-time = { workspace = true }
|
||||
effectcraft-color = { workspace = true }
|
||||
effectcraft-keyframe = { workspace = true }
|
||||
effectcraft-project = { workspace = true }
|
||||
effectcraft-effects = { workspace = true }
|
||||
log = { 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
|
||||
+31
-18
@@ -3,11 +3,13 @@
|
||||
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);
|
||||
view (below). This is `craft-aep` from [storytold/craft-libs](https://github.com/storytold/craft-libs),
|
||||
re-exported at the crate root; its container tests and the `aepdump`/`stubicc` tools are there.
|
||||
Only `effect_map` and `style_map` (After Effects effects and layer styles to EffectCraft's) are here;
|
||||
- `import`: maps the typed view into an EffectCraft project and reports everything it does not
|
||||
import ([`docs/aep-import.md`](../../docs/aep-import.md)).
|
||||
|
||||
Writing an EffectCraft project as an `.aep` (export) is not part of this crate yet.
|
||||
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.
|
||||
|
||||
@@ -21,7 +23,9 @@ tree; pad bytes, odd bodies and the bytes after the container, an XMP packet, ar
|
||||
|
||||
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.
|
||||
importer take either form. The mapping is in `docs/aep-format.md`, section 1. The importer, which
|
||||
only reads, does not build the owned tree: it reads either form through the flat index
|
||||
`TreeIndex`, an `.aep` in place and an `.aepx` decoded into one buffer first.
|
||||
|
||||
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
|
||||
@@ -46,7 +50,11 @@ 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.
|
||||
- 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
|
||||
|
||||
@@ -65,25 +73,30 @@ tests reach them only through `tests/it/common/mod.rs`, which hands a test its c
|
||||
of its own cut from the combined file; a test whose fixture is missing (or with the variable not
|
||||
set) prints `SKIPPED: fixture <name> missing` and passes.
|
||||
|
||||
`tests/fixtures/synthetic.aep` (115 KB) is the one project in the repository: made in After Effects 2026
|
||||
`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/text-synthetic.aep` is the other: made in After Effects 2026 the same way (working
|
||||
space None, nothing changed after the save), one composition with two text layers that hold a
|
||||
text animator's Stroke Opacity (static and keyed) and Source Text expressions (enabled and
|
||||
disabled); `tests/it/import/text_synthetic.rs` reads it (#3170).
|
||||
|
||||
`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).
|
||||
- `aepdump` (prints the chunk tree of a file) and `stubicc` (replaces every embedded ICC profile of a
|
||||
saved project by a stub) are examples of `craft-aep` in
|
||||
[storytold/craft-libs](https://github.com/storytold/craft-libs):
|
||||
`cargo run -p craft-aep --example stubicc -- in.aep out.aep` there. 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).
|
||||
@@ -1,75 +0,0 @@
|
||||
//! 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<T> {
|
||||
fn or_exit(self, what: &str) -> T;
|
||||
}
|
||||
|
||||
impl<T> OrExit<T> for Option<T> {
|
||||
fn or_exit(self, what: &str) -> T {
|
||||
match self {
|
||||
Some(v) => v,
|
||||
None => exit(what),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E: std::fmt::Debug> OrExit<T> for Result<T, E> {
|
||||
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<String> = 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());
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
//! 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": "<base64>"` 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="<hex>"` 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<T> {
|
||||
fn or_exit(self, what: &str) -> T;
|
||||
}
|
||||
|
||||
impl<T> OrExit<T> for Option<T> {
|
||||
fn or_exit(self, what: &str) -> T {
|
||||
match self {
|
||||
Some(v) => v,
|
||||
None => exit(what),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E: std::fmt::Debug> OrExit<T> for Result<T, E> {
|
||||
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<Vec<u8>> {
|
||||
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<u8> {
|
||||
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<usize> {
|
||||
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<String> {
|
||||
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<u16> = 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<Vec<u8>> {
|
||||
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 `<string>` 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<String>,
|
||||
}
|
||||
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<u8> {
|
||||
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="<hex>"`
|
||||
/// attribute that holds a raw profile.
|
||||
fn stub_text(text: &[u8], tally: &mut Tally) -> Vec<u8> {
|
||||
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<u8> = 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<String> = std::env::args().collect();
|
||||
let (Some(input), Some(output)) = (args.get(1), args.get(2)) else { exit("usage: stubicc <in.aep|in.aepx> <out>") };
|
||||
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<u8> {
|
||||
// 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<u8>, 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!("<icc bdata=\"{hex}\"/><PwCs bdata=\"01\"/><cdta bdata=\"{}\"/>", "ab".repeat(200));
|
||||
let (out, tally) = stubbed(text.as_bytes());
|
||||
assert_eq!(String::from_utf8(out).unwrap(), format!("<icc bdata=\"{want}\"/><PwCs bdata=\"01\"/><cdta bdata=\"{}\"/>", "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));
|
||||
}
|
||||
}
|
||||
@@ -1,57 +1,7 @@
|
||||
//! 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.
|
||||
//! The `.aep` / `.aepx` container and its typed view come from `craft-aep`; only the tables that map
|
||||
//! After Effects effects and layer styles onto EffectCraft's are kept here.
|
||||
|
||||
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 write;
|
||||
|
||||
pub use aepx::{is_aepx, parse_any, read_aepx, read_aepx_with_limits};
|
||||
pub use arbitrary::{CURVE_IDENTITY, CurvesData, HueSaturationData, LevelsData, MeshData, curve_lut};
|
||||
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 write::{write, write_to};
|
||||
pub use craft_aep::*;
|
||||
@@ -1,640 +0,0 @@
|
||||
//! 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 `<string>`, the numbers `numS` and `ppSn`, the footage
|
||||
//! alias `alas` as `<fileReference>`), and the XMP packet that follows the container of an `.aep`
|
||||
//! is the element `<ProjectXMPMetadata>`. 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"<?xml") || rest.starts_with(b"<AfterEffectsProject")
|
||||
}
|
||||
|
||||
/// Reads an `.aep` or an `.aepx`, chosen by content: a `RIFX` file goes to [`parse`], an XML file
|
||||
/// (see [`is_aepx`]) to [`read_aepx`].
|
||||
///
|
||||
/// # Errors
|
||||
/// The errors of [`parse`] or [`read_aepx`].
|
||||
pub fn parse_any(data: &[u8]) -> Result<AepFile<'_>, 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<AepFile<'static>, 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<AepFile<'static>, 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<Vec<u8>>,
|
||||
/// The attributes of a `fileReference`, in document order.
|
||||
attrs: Vec<(String, String)>,
|
||||
/// Collected text (only for `string` and the XMP packet).
|
||||
text: Vec<u8>,
|
||||
children: Vec<Chunk<'static>>,
|
||||
}
|
||||
|
||||
struct Reader<'d> {
|
||||
data: &'d [u8],
|
||||
pos: usize,
|
||||
limits: Limits,
|
||||
count: usize,
|
||||
stack: Vec<Frame>,
|
||||
/// The top-level chunks once the root element has closed.
|
||||
top: Option<Vec<Chunk<'static>>>,
|
||||
trailer: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
fn run(mut self) -> Result<AepFile<'static>, 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<usize> {
|
||||
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<usize, AepError> {
|
||||
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"<?") {
|
||||
self.skip_past(b"?>", "a processing instruction is not closed")?;
|
||||
} else if rest.starts_with(b"<!--") {
|
||||
self.skip_past(b"-->", "a comment is not closed")?;
|
||||
} else if rest.starts_with(b"<![CDATA[") {
|
||||
let start = self.pos.saturating_add(9);
|
||||
self.pos = start;
|
||||
let end = self.skip_past(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"<!") {
|
||||
return Err(xml(self.pos, "document type declarations are not supported"));
|
||||
} else if rest.starts_with(b"</") {
|
||||
self.end_tag()?;
|
||||
} else {
|
||||
self.start_tag()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_name_byte(b: u8) -> 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<u8>)> = 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<Kind, AepError> {
|
||||
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<Chunk<'static>, 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: `<numS><string>0</string></numS>` and `<ppSn><string>150.000000000</string></ppSn>`.
|
||||
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::<i64>().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::<f64>().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<u8>) -> 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::<u32>().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<Vec<u8>, 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::<Option<Vec<u8>>>()
|
||||
.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::<i64>().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!("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<AfterEffectsProject xmlns=\"x\">{body}</AfterEffectsProject>\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_elements_to_chunks() {
|
||||
let x = doc(concat!(
|
||||
"<head bdata=\"00ff\"/><Pin><sspc bdata=\"01\"/></Pin><Pefl>\n</Pefl>",
|
||||
"<tdsn><string>A & BA</string></tdsn><numS><string>-3</string></numS>",
|
||||
"<ppSn><string>150.000000000</string></ppSn><btdk bdata=\"414243\"/><Comment>x<a bdata=\"00\"/></Comment>",
|
||||
"<ProjectXMPMetadata><![CDATA[<?xpacket begin?>]]></ProjectXMPMetadata>"
|
||||
));
|
||||
let f = read_aepx(x.as_bytes()).unwrap();
|
||||
assert_eq!(f.trailer.as_ref(), b"<?xpacket begin?>");
|
||||
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!(
|
||||
"<Als2><fileReference ascendcount_base=\"1\" ascendcount_target=\"1\" fullpath=\"C:\\a\\"b.png\" ",
|
||||
"platform=\"Win\" server_name=\"N\" server_volume_name=\"V\" target_is_folder=\"0\"/></Als2>"
|
||||
));
|
||||
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!("<numS><string>{text}</string></numS>")).as_bytes()).unwrap();
|
||||
assert_eq!(f.chunks[0].bytes(), Some(&bytes[..]), "{text}");
|
||||
}
|
||||
for text in ["-2147483649", "4294967296", "1.5"] {
|
||||
assert!(read_aepx(doc(&format!("<numS><string>{text}</string></numS>")).as_bytes()).is_err(), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection() {
|
||||
assert!(is_aepx(b"\xef\xbb\xbf <?xml version=\"1.0\"?>"));
|
||||
assert!(is_aepx(b"<AfterEffectsProject>"));
|
||||
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("<a bdata=\"0\"/>"),
|
||||
doc("<a bdata=\"zz\"/>"),
|
||||
doc("<string> </string>"),
|
||||
doc("<string>�</string>"),
|
||||
doc("<string>&</string>"),
|
||||
doc("<a>"),
|
||||
doc("<a></b>"),
|
||||
doc("<numS><string>x</string></numS>"),
|
||||
doc("<numS></numS>"),
|
||||
doc("<a b></a>"),
|
||||
doc("<a b=c></a>"),
|
||||
"<?xml version=\"1.0\"?><!DOCTYPE x [<!ENTITY a \"b\">]><AfterEffectsProject/>".into(),
|
||||
"<?xml version=\"1.0\"?><Other/>".into(),
|
||||
"<?xml version=\"1.0\"?>".into(),
|
||||
"<AfterEffectsProject/><AfterEffectsProject/>".into(),
|
||||
"<AfterEffectsProject/>junk".into(),
|
||||
"<AfterEffectsProject><!-- x".into(),
|
||||
];
|
||||
for b in &bad {
|
||||
assert!(matches!(read_aepx(b.as_bytes()), Err(AepError::Xml { .. })), "{b}");
|
||||
}
|
||||
assert!(matches!(read_aepx(b"<AfterEffectsProject>\xff</AfterEffectsProject>"), Err(AepError::Xml { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_hold() {
|
||||
let deep = format!("<AfterEffectsProject>{}{}</AfterEffectsProject>", "<a>".repeat(100_000), "</a>".repeat(100_000));
|
||||
assert_eq!(read_aepx(deep.as_bytes()), Err(AepError::TooDeep));
|
||||
let ok = format!("<AfterEffectsProject>{}{}</AfterEffectsProject>", "<a>".repeat(64), "</a>".repeat(64));
|
||||
assert!(read_aepx(ok.as_bytes()).is_ok());
|
||||
let many = format!("<AfterEffectsProject>{}</AfterEffectsProject>", "<a/>".repeat(10));
|
||||
assert_eq!(read_aepx_with_limits(many.as_bytes(), Limits { max_depth: 64, max_chunks: 9 }), Err(AepError::TooManyChunks));
|
||||
}
|
||||
}
|
||||
@@ -1,309 +0,0 @@
|
||||
//! Arbitrary-data effect parameters (type 11): the values of Hue/Saturation and Levels that are not
|
||||
//! ordinary parameters.
|
||||
//!
|
||||
//! In the effect's value group (`sspc/tdgp`) the parameter's `tdbs` (`tdsb` 1, a 4-byte `cdat`) is
|
||||
//! followed by a `LIST aRbs` holding one `aRbp`: the data. The `aRbp` in `parT` right after the
|
||||
//! parameter's `pard` holds the default (443, 511). Setting Master Hue, Saturation or Lightness of
|
||||
//! Hue/Saturation (444-446) or a Levels value (512-516) changes only bytes of this `aRbp` (and stale
|
||||
//! UI bytes of `pard`); the visible parameters of the same names keep no record.
|
||||
|
||||
use crate::container::Chunk;
|
||||
use crate::container::bytes::{be_f32, be_i32, be_u16, be_u32};
|
||||
use crate::container::effects::Effect;
|
||||
|
||||
impl<'f, 'a> Effect<'f, 'a> {
|
||||
/// The arbitrary data stored for the parameter with this match name (`<effect>-NNNN`): the
|
||||
/// `aRbp` of the `LIST aRbs` that follows the parameter's value record. `None` when there is
|
||||
/// none.
|
||||
pub fn arbitrary_data(&self, match_name: &str) -> Option<&'f [u8]> {
|
||||
let values = self.chunk().child_list(b"tdgp")?;
|
||||
let kids = values.children();
|
||||
let at = kids.iter().position(|c| c.is(b"tdmn") && c.bytes().is_some_and(|b| name_is(b, match_name)))?;
|
||||
// The value record, then the data list (no match name of its own).
|
||||
let rest = kids.get(at.checked_add(1)?..)?;
|
||||
let mut it = rest.iter().take(3);
|
||||
let _record = it.next().filter(|c| c.is_list(b"tdbs"))?;
|
||||
it.find(|c| c.is_list(b"aRbs")).and_then(|l| l.child(b"aRbp")).and_then(Chunk::bytes)
|
||||
}
|
||||
}
|
||||
|
||||
fn name_is(body: &[u8], name: &str) -> bool {
|
||||
let end = body.iter().position(|c| *c == 0).unwrap_or(body.len());
|
||||
body.get(..end) == Some(name.as_bytes())
|
||||
}
|
||||
|
||||
/// Hue/Saturation's data (180 bytes, `ADBE HUE SATURATION-0003`): the master hue, saturation and
|
||||
/// lightness as `i32` at bytes 0, 4 and 8 (444: hue 90 is `0x5a`; 445: saturation 50; 446:
|
||||
/// lightness -30), then six colour ranges (Reds, Yellows, Greens, Cyans, Blues, Magentas) of 28
|
||||
/// bytes each: four `i32` range points in degrees (Reds 315, 345, 15, 45 by default) and the
|
||||
/// range's hue, saturation and lightness. Only the master values are sampled; the ranges' layout is
|
||||
/// read from the default data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct HueSaturationData {
|
||||
/// Master hue (degrees), saturation and lightness (-100..100).
|
||||
pub master: [i32; 3],
|
||||
/// Per colour range: the four range points (degrees) and its hue, saturation and lightness.
|
||||
pub ranges: [([i32; 4], [i32; 3]); 6],
|
||||
}
|
||||
|
||||
impl HueSaturationData {
|
||||
/// The default data (443): master 0, 0, 0 and every range at its default points.
|
||||
pub const DEFAULT_RANGES: [[i32; 4]; 6] =
|
||||
[[315, 345, 15, 45], [15, 45, 75, 105], [75, 105, 135, 165], [135, 165, 195, 225], [195, 225, 255, 285], [255, 285, 315, 345]];
|
||||
|
||||
/// Decodes the data; `None` when it is not 180 bytes.
|
||||
pub fn parse(data: &[u8]) -> Option<Self> {
|
||||
if data.len() != 180 {
|
||||
return None;
|
||||
}
|
||||
let i = |at: usize| be_i32(data, at);
|
||||
let master = [i(0)?, i(4)?, i(8)?];
|
||||
let mut ranges = [([0; 4], [0; 3]); 6];
|
||||
for (k, r) in ranges.iter_mut().enumerate() {
|
||||
let base = 12usize.checked_add(k.checked_mul(28)?)?;
|
||||
r.0 = [i(base)?, i(base + 4)?, i(base + 8)?, i(base + 12)?];
|
||||
r.1 = [i(base + 16)?, i(base + 20)?, i(base + 24)?];
|
||||
}
|
||||
Some(Self { master, ranges })
|
||||
}
|
||||
|
||||
/// Whether every colour range is at its default (points as in 443, no adjustment).
|
||||
pub fn ranges_are_default(&self) -> bool {
|
||||
self.ranges.iter().zip(Self::DEFAULT_RANGES).all(|((points, hsl), d)| *points == d && *hsl == [0, 0, 0])
|
||||
}
|
||||
}
|
||||
|
||||
/// Levels' data (108 bytes, `ADBE Easy Levels2-0002`): a `u32` 0x000f10a7 and a `u32` 1 (511, in
|
||||
/// every sample), then five channels (RGB, Red, Green, Blue, Alpha) of five `f32`: input black,
|
||||
/// input white, gamma, output black, output white. The RGB values are sampled (512 input black
|
||||
/// 0.1, 513 input white 0.8, 514 gamma 2, 515 output black 0.2, 516 output white 0.9); the other
|
||||
/// channels' layout is read from the default data (0, 1, 1, 0, 1).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct LevelsData {
|
||||
pub header: [u32; 2],
|
||||
/// RGB, Red, Green, Blue, Alpha: input black, input white, gamma, output black, output white.
|
||||
pub channels: [[f32; 5]; 5],
|
||||
}
|
||||
|
||||
impl LevelsData {
|
||||
/// The values of a channel at its default.
|
||||
pub const DEFAULT_CHANNEL: [f32; 5] = [0.0, 1.0, 1.0, 0.0, 1.0];
|
||||
|
||||
/// Decodes the data; `None` when it is not 108 bytes.
|
||||
pub fn parse(data: &[u8]) -> Option<Self> {
|
||||
if data.len() != 108 {
|
||||
return None;
|
||||
}
|
||||
let header = [be_u32(data, 0)?, be_u32(data, 4)?];
|
||||
let mut channels = [[0.0; 5]; 5];
|
||||
for (k, c) in channels.iter_mut().enumerate() {
|
||||
let base = 8usize.checked_add(k.checked_mul(20)?)?;
|
||||
for (j, v) in c.iter_mut().enumerate() {
|
||||
*v = be_f32(data, base.checked_add(j.checked_mul(4)?)?)?;
|
||||
}
|
||||
}
|
||||
Some(Self { header, channels })
|
||||
}
|
||||
}
|
||||
|
||||
/// Curves' data (1644 bytes, `ADBE CurvesCustom-0001`; FORMAT S.1, 961-964): `u16` 1, `u16` 1,
|
||||
/// five 256-byte lookup tables (RGB, Red, Green, Blue, Alpha: output 0..255 per input 0..255),
|
||||
/// then five 72-byte point records: 16 slots of (`u16` input, `u16` output), both 0..255, the
|
||||
/// number of points as `u32` at 64 and an `i32` at 68 (-1 at the default; the point count - 2 in
|
||||
/// every edited sample, H: the active point). Every stored table is the natural cubic spline
|
||||
/// through its points ([`curve_lut`]).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurvesData {
|
||||
/// RGB, Red, Green, Blue, Alpha: the points (input, output), as stored.
|
||||
pub curves: [Vec<(u8, u8)>; 5],
|
||||
}
|
||||
|
||||
/// The points of an untouched curve.
|
||||
pub const CURVE_IDENTITY: [(u8, u8); 2] = [(0, 0), (255, 255)];
|
||||
|
||||
impl CurvesData {
|
||||
pub const SIZE: usize = 1644;
|
||||
const POINTS: usize = 1284;
|
||||
|
||||
/// Decodes the data; `None` when it is not 1644 bytes or a point count is beyond 16.
|
||||
pub fn parse(data: &[u8]) -> Option<Self> {
|
||||
if data.len() != Self::SIZE {
|
||||
return None;
|
||||
}
|
||||
let mut curves: [Vec<(u8, u8)>; 5] = Default::default();
|
||||
for (c, pts) in curves.iter_mut().enumerate() {
|
||||
let base = Self::POINTS.checked_add(c.checked_mul(72)?)?;
|
||||
let n = usize::try_from(be_u32(data, base.checked_add(64)?)?).ok()?;
|
||||
if n > 16 {
|
||||
return None;
|
||||
}
|
||||
for k in 0..n {
|
||||
let at = base.checked_add(k.checked_mul(4)?)?;
|
||||
let x = u8::try_from(be_u16(data, at)?).ok()?;
|
||||
let y = u8::try_from(be_u16(data, at.checked_add(2)?)?).ok()?;
|
||||
pts.push((x, y));
|
||||
}
|
||||
}
|
||||
Some(Self { curves })
|
||||
}
|
||||
|
||||
/// Whether every curve is the identity.
|
||||
pub fn is_default(&self) -> bool {
|
||||
self.curves.iter().all(|c| c.as_slice() == CURVE_IDENTITY)
|
||||
}
|
||||
|
||||
/// The data After Effects stores for these curves: the tables rebuilt from the points.
|
||||
/// `None` when a curve has fewer than 2 or more than 16 points or inputs that do not rise.
|
||||
pub fn to_bytes(&self) -> Option<Vec<u8>> {
|
||||
let mut out = vec![0u8; Self::SIZE];
|
||||
out.get_mut(0..4)?.copy_from_slice(&[0, 1, 0, 1]);
|
||||
for (c, pts) in self.curves.iter().enumerate() {
|
||||
if pts.len() > 16 {
|
||||
return None;
|
||||
}
|
||||
let lut = curve_lut(pts)?;
|
||||
out.get_mut(4 + 256 * c..4 + 256 * (c + 1))?.copy_from_slice(&lut);
|
||||
let base = Self::POINTS + 72 * c;
|
||||
for (k, (x, y)) in pts.iter().enumerate() {
|
||||
out.get_mut(base + 4 * k..base + 4 * k + 4)?.copy_from_slice(&[0, *x, 0, *y]);
|
||||
}
|
||||
let n = u32::try_from(pts.len()).ok()?;
|
||||
out.get_mut(base + 64..base + 68)?.copy_from_slice(&n.to_be_bytes());
|
||||
let active: i32 = if pts.as_slice() == CURVE_IDENTITY { -1 } else { i32::try_from(pts.len()).ok()? - 2 };
|
||||
out.get_mut(base + 68..base + 72)?.copy_from_slice(&active.to_be_bytes());
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn rising(points: &[(u8, u8)]) -> bool {
|
||||
points.windows(2).all(|w| matches!(w, [a, b] if a.0 < b.0))
|
||||
}
|
||||
|
||||
/// The lookup table After Effects stores for a curve: the natural cubic spline (second derivative
|
||||
/// 0 at both ends) through the points, at the integers 0..255, rounded to the nearest integer and
|
||||
/// clamped to 0..255; flat outside the first and last point (961-964: 0 of 1280 entries differ).
|
||||
/// `None` for fewer than 2 points or inputs that do not rise.
|
||||
pub fn curve_lut(points: &[(u8, u8)]) -> Option<[u8; 256]> {
|
||||
let n = points.len();
|
||||
if n < 2 || !rising(points) {
|
||||
return None;
|
||||
}
|
||||
let xs: Vec<f64> = points.iter().map(|p| f64::from(p.0)).collect();
|
||||
let ys: Vec<f64> = points.iter().map(|p| f64::from(p.1)).collect();
|
||||
let x = |i: usize| xs.get(i).copied().unwrap_or(0.0);
|
||||
let y = |i: usize| ys.get(i).copied().unwrap_or(0.0);
|
||||
let h = |i: usize| (x(i + 1) - x(i)).max(1.0);
|
||||
let slope = |i: usize| (y(i + 1) - y(i)) / h(i);
|
||||
// Second derivatives: the tridiagonal system of the natural spline (Thomas algorithm).
|
||||
let mut m = vec![0.0f64; n];
|
||||
let k = n - 2;
|
||||
if k > 0 {
|
||||
let mut diag: Vec<f64> = (0..k).map(|i| 2.0 * (h(i) + h(i + 1))).collect();
|
||||
let upper: Vec<f64> = (0..k).map(|i| h(i + 1)).collect();
|
||||
let mut rhs: Vec<f64> = (0..k).map(|i| 6.0 * (slope(i + 1) - slope(i))).collect();
|
||||
for i in 1..k {
|
||||
let (Some(&dp), Some(&up), Some(&rp)) = (diag.get(i - 1), upper.get(i - 1), rhs.get(i - 1)) else { return None };
|
||||
let w = h(i) / dp;
|
||||
if let (Some(d), Some(r)) = (diag.get_mut(i), rhs.get_mut(i)) {
|
||||
*d -= w * up;
|
||||
*r -= w * rp;
|
||||
}
|
||||
}
|
||||
for i in (0..k).rev() {
|
||||
let next = m.get(i + 2).copied().unwrap_or(0.0);
|
||||
let (Some(&r), Some(&u), Some(&d)) = (rhs.get(i), upper.get(i), diag.get(i)) else { return None };
|
||||
if let Some(slot) = m.get_mut(i + 1) {
|
||||
*slot = (r - u * next) / d;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut lut = [0u8; 256];
|
||||
for (xi, slot) in lut.iter_mut().enumerate() {
|
||||
let xf = xi as f64;
|
||||
let v = if xf <= x(0) {
|
||||
y(0)
|
||||
} else if xf >= x(n - 1) {
|
||||
y(n - 1)
|
||||
} else {
|
||||
let i = (0..n - 1).find(|&i| xf >= x(i) && xf <= x(i + 1)).unwrap_or(0);
|
||||
let hh = h(i);
|
||||
let (a, b) = ((x(i + 1) - xf) / hh, (xf - x(i)) / hh);
|
||||
let (mi, mj) = (m.get(i).copied().unwrap_or(0.0), m.get(i + 1).copied().unwrap_or(0.0));
|
||||
a * y(i) + b * y(i + 1) + ((a * a * a - a) * mi + (b * b * b - b) * mj) * hh * hh / 6.0
|
||||
};
|
||||
*slot = (v + 0.5).floor().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
Some(lut)
|
||||
}
|
||||
|
||||
/// Mesh Warp's data (`ADBE MESH WARP-0004`; FORMAT S.2, 965, 985): `u32` rows plus one, `u32`
|
||||
/// columns plus one (a 1 x 2-cell read-back test renders as made only in this order, `export-tests\mesh`;
|
||||
/// the vertices run row-major, columns plus one per row), 12 more bytes (zero, then
|
||||
/// `0d 0d`),
|
||||
/// then per vertex, row-major, ten `f32`: the position and the handles top, right, bottom and
|
||||
/// left, all as fractions 0..1 of the layer; a handle pointing out of the mesh is stored (0, 0).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct MeshData {
|
||||
pub columns: u32,
|
||||
pub rows: u32,
|
||||
/// Bytes 8..20 as stored.
|
||||
pub tail: [u8; 12],
|
||||
/// Per vertex: position, top, right, bottom, left.
|
||||
pub vertices: Vec<[[f32; 2]; 5]>,
|
||||
}
|
||||
|
||||
impl MeshData {
|
||||
/// Decodes the data; `None` when the size does not fit the grid or the grid is beyond 31 x 31
|
||||
/// cells.
|
||||
pub fn parse(data: &[u8]) -> Option<Self> {
|
||||
let (r1, c1) = (be_u32(data, 0)?, be_u32(data, 4)?);
|
||||
if !(2..=32).contains(&c1) || !(2..=32).contains(&r1) {
|
||||
return None;
|
||||
}
|
||||
let count = usize::try_from(c1.checked_mul(r1)?).ok()?;
|
||||
if data.len() != 20usize.checked_add(count.checked_mul(40)?)? {
|
||||
return None;
|
||||
}
|
||||
let mut tail = [0u8; 12];
|
||||
tail.copy_from_slice(data.get(8..20)?);
|
||||
let mut vertices = Vec::with_capacity(count);
|
||||
for v in 0..count {
|
||||
let base = 20 + 40 * v;
|
||||
let mut rec = [[0.0f32; 2]; 5];
|
||||
for (j, p) in rec.iter_mut().enumerate() {
|
||||
*p = [be_f32(data, base + 8 * j)?, be_f32(data, base + 8 * j + 4)?];
|
||||
}
|
||||
vertices.push(rec);
|
||||
}
|
||||
Some(Self { columns: c1 - 1, rows: r1 - 1, tail, vertices })
|
||||
}
|
||||
|
||||
/// The vertex at column `i`, row `j` of an undistorted mesh with its default handles (one
|
||||
/// third of a cell along the grid lines; those pointing out of the mesh are (0, 0)).
|
||||
pub fn default_vertex(columns: u32, rows: u32, i: u32, j: u32) -> [[f32; 2]; 5] {
|
||||
let (cw, rh) = (1.0 / f64::from(columns.max(1)), 1.0 / f64::from(rows.max(1)));
|
||||
let (x, y) = (f64::from(i) * cw, f64::from(j) * rh);
|
||||
let p = |dx: f64, dy: f64, out: bool| if out { [0.0, 0.0] } else { [(x + dx) as f32, (y + dy) as f32] };
|
||||
[[x as f32, y as f32], p(0.0, -rh / 3.0, j == 0), p(cw / 3.0, 0.0, i == columns), p(0.0, rh / 3.0, j == rows), p(-cw / 3.0, 0.0, i == 0)]
|
||||
}
|
||||
|
||||
/// The bytes After Effects stores for this mesh.
|
||||
pub fn to_bytes(&self) -> Option<Vec<u8>> {
|
||||
let count = usize::try_from(self.columns.checked_add(1)?.checked_mul(self.rows.checked_add(1)?)?).ok()?;
|
||||
if self.vertices.len() != count {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(20 + 40 * count);
|
||||
out.extend((self.rows + 1).to_be_bytes());
|
||||
out.extend((self.columns + 1).to_be_bytes());
|
||||
out.extend(self.tail);
|
||||
for v in &self.vertices {
|
||||
for p in v {
|
||||
out.extend(p[0].to_be_bytes());
|
||||
out.extend(p[1].to_be_bytes());
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
//! Bounds-checked big-endian readers shared by the typed views. Every read returns `None` when the
|
||||
//! bytes are not there; nothing here indexes a slice directly.
|
||||
|
||||
pub(crate) fn text(b: &[u8]) -> String {
|
||||
String::from_utf8_lossy(b).into_owned()
|
||||
}
|
||||
|
||||
/// The bytes up to the first NUL (all of them when there is none).
|
||||
pub(crate) fn until_nul(b: &[u8]) -> &[u8] {
|
||||
let end = b.iter().position(|c| *c == 0).unwrap_or(b.len());
|
||||
b.get(..end).unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// A NUL-terminated ASCII (or Latin-1) string at `at`, at most `max` bytes long.
|
||||
pub(crate) fn cstr(b: &[u8], at: usize, max: usize) -> Option<String> {
|
||||
let end = at.checked_add(max)?.min(b.len());
|
||||
let field = b.get(at..end)?;
|
||||
Some(until_nul(field).iter().map(|c| char::from(*c)).collect())
|
||||
}
|
||||
|
||||
pub(crate) fn array<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
|
||||
let s = b.get(at..at.checked_add(N)?)?;
|
||||
let mut a = [0u8; N];
|
||||
a.copy_from_slice(s);
|
||||
Some(a)
|
||||
}
|
||||
|
||||
pub(crate) fn be_u16(b: &[u8], at: usize) -> Option<u16> {
|
||||
array::<2>(b, at).map(u16::from_be_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn be_u32(b: &[u8], at: usize) -> Option<u32> {
|
||||
array::<4>(b, at).map(u32::from_be_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn be_i32(b: &[u8], at: usize) -> Option<i32> {
|
||||
array::<4>(b, at).map(i32::from_be_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn le_u32(b: &[u8], at: usize) -> Option<u32> {
|
||||
array::<4>(b, at).map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn be_f32(b: &[u8], at: usize) -> Option<f32> {
|
||||
array::<4>(b, at).map(f32::from_be_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn be_f64(b: &[u8], at: usize) -> Option<f64> {
|
||||
array::<8>(b, at).map(f64::from_be_bytes)
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
//! Cameras and lights.
|
||||
//!
|
||||
//! Both are layers without a source (`ldta` byte 40 is 0 for a camera and `0xffff_ffff` for a light)
|
||||
//! whose type is 2 (camera) or 1 (light). Their `ldta` carries the auto-orient bit (byte 38, `0x40`)
|
||||
//! and, for a light, the light type (see [`LayerHeader::light_type`](crate::container::LayerHeader)). The
|
||||
//! properties sit in the same Transform group as on other layers but follow other conventions:
|
||||
//!
|
||||
//! * **Position** is stored as given once the user has set it. While it is at its computed default
|
||||
//! the record is an "auto state" (`tdb4` bytes 76 and 77 are 1 although there is no expression)
|
||||
//! that holds `[0, 0, -zoom]`. After Effects reports and renders the stored value, also for a
|
||||
//! two-node camera (256 read back `[0, 0, -2666.67]` in session S16; 537 renders from there). An
|
||||
//! earlier batch-3 note had a two-node camera report the composition centre; that was not
|
||||
//! reproduced.
|
||||
//! * **Anchor Point** of a camera is its point of interest, in pixels (not a fraction).
|
||||
//! * A light's **Intensity** (`ADBE Light Options Group/ADBE Light Intensity`, percent) is stored
|
||||
//! only when it is not the default 100.
|
||||
|
||||
use crate::container::typed::{Layer, PropNode};
|
||||
use crate::container::values::{Tracked, ValueSource, read, read_opt};
|
||||
|
||||
/// The Position of a camera or light layer as stored.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CameraPosition {
|
||||
/// `[x, y, z]` in pixels as stored: the absolute position once set by the user, `[0, 0, -zoom]`
|
||||
/// in the auto state (camera) or `[0, 0, -1333.33]` (default light).
|
||||
pub stored: [f64; 3],
|
||||
/// True while the position is derived (`tdb4` bytes 76 and 77 are 1 without an expression).
|
||||
pub auto_state: bool,
|
||||
}
|
||||
|
||||
impl CameraPosition {
|
||||
/// The position as the batch-3 notes had After Effects report it: in the auto state of a
|
||||
/// two-node camera (`two_node`) x and y are the composition centre; otherwise the stored
|
||||
/// value. **Contradicted by 256 and 537 (session S16): After Effects reports and renders the
|
||||
/// stored value**; use `stored` for what After Effects shows.
|
||||
pub fn reported(&self, comp_width: u32, comp_height: u32, two_node: bool) -> [f64; 3] {
|
||||
if self.auto_state && two_node { [f64::from(comp_width) / 2.0, f64::from(comp_height) / 2.0, self.stored[2]] } else { self.stored }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The Position record of a camera or light layer.
|
||||
pub fn camera_position(&self) -> Option<CameraPosition> {
|
||||
let Some(PropNode::Group(transform)) = self.properties()?.get("ADBE Transform Group") else { return None };
|
||||
let Some(PropNode::Property(position)) = transform.get("ADBE Position") else { return None };
|
||||
let v = position.static_value()?;
|
||||
let stored = *v.as_slice().first_chunk::<3>()?;
|
||||
let h = position.header()?;
|
||||
let derived = h.get(76) == Some(&1) && h.get(77) == Some(&1) && position.expression().is_none();
|
||||
Some(CameraPosition { stored, auto_state: derived })
|
||||
}
|
||||
|
||||
/// The point of interest of a camera in pixels (its Anchor Point record); `None` when absent.
|
||||
pub fn camera_point_of_interest(&self) -> Option<[f64; 3]> {
|
||||
let Some(PropNode::Group(transform)) = self.properties()?.get("ADBE Transform Group") else { return None };
|
||||
let tracked = read(&transform, "ADBE Anchor Point", [0.0; 3], 1.0);
|
||||
matches!(tracked.source, ValueSource::Stored | ValueSource::Keyframed).then_some(tracked.value)
|
||||
}
|
||||
|
||||
/// A light's intensity in percent; the default 100 when the property is absent.
|
||||
pub fn light_intensity(&self) -> Option<Tracked<f64>> {
|
||||
let root = self.properties()?;
|
||||
let Some(PropNode::Group(options)) = root.get("ADBE Light Options Group") else { return None };
|
||||
let t = read(&options, "ADBE Light Intensity", [100.0], 1.0);
|
||||
Some(Tracked { value: t.value[0], source: t.source })
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera zoom After Effects uses when `ADBE Camera Zoom` is absent: 2666.67 px for the 50 mm
|
||||
/// default camera in the 1920 px wide corpus composition. Whether it follows other composition
|
||||
/// widths was not sampled.
|
||||
pub const DEFAULT_CAMERA_ZOOM: f64 = 2_666.666_666_666_666_5;
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
fn camera_options(&self) -> Option<crate::container::typed::PropGroup<'f, 'a>> {
|
||||
match self.properties()?.get("ADBE Camera Options Group") {
|
||||
Some(PropNode::Group(g)) => Some(g),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn light_options(&self) -> Option<crate::container::typed::PropGroup<'f, 'a>> {
|
||||
match self.properties()?.get("ADBE Light Options Group") {
|
||||
Some(PropNode::Group(g)) => Some(g),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A camera's zoom in pixels (`ADBE Camera Options Group/ADBE Camera Zoom`); absent = the
|
||||
/// default, [`DEFAULT_CAMERA_ZOOM`] (341: 2000 is stored). The auto Position keeps `-2666.67` and
|
||||
/// is not recomputed from the zoom.
|
||||
pub fn camera_zoom(&self) -> Option<Tracked<f64>> {
|
||||
let t = read(&self.camera_options()?, "ADBE Camera Zoom", [DEFAULT_CAMERA_ZOOM], 1.0);
|
||||
Some(Tracked { value: t.value[0], source: t.source })
|
||||
}
|
||||
|
||||
/// The depth of field switch (`ADBE Camera Depth of Field`, a checkbox; off by default, 342).
|
||||
pub fn camera_depth_of_field(&self) -> Option<Tracked<bool>> {
|
||||
let t = read(&self.camera_options()?, "ADBE Camera Depth of Field", [0.0], 1.0);
|
||||
Some(Tracked { value: t.value[0] != 0.0, source: t.source })
|
||||
}
|
||||
|
||||
/// A camera's focus distance in pixels (`ADBE Camera Focus Distance`); `None` while absent (its
|
||||
/// default is not known).
|
||||
pub fn camera_focus_distance(&self) -> Option<Tracked<f64>> {
|
||||
let t = read_opt::<1>(&self.camera_options()?, "ADBE Camera Focus Distance", 1.0)?;
|
||||
Some(Tracked { value: t.value[0], source: t.source })
|
||||
}
|
||||
|
||||
/// A camera's aperture (`ADBE Camera Aperture`); `None` while absent (its default is not known).
|
||||
pub fn camera_aperture(&self) -> Option<Tracked<f64>> {
|
||||
let t = read_opt::<1>(&self.camera_options()?, "ADBE Camera Aperture", 1.0)?;
|
||||
Some(Tracked { value: t.value[0], source: t.source })
|
||||
}
|
||||
|
||||
/// A light's colour as `[A, R, G, B]` fractions (`ADBE Light Options Group/ADBE Light Color`,
|
||||
/// stored as doubles 0..255); white when absent (343 stores red).
|
||||
pub fn light_color(&self) -> Option<Tracked<[f64; 4]>> {
|
||||
Some(read(&self.light_options()?, "ADBE Light Color", [1.0; 4], 1.0 / 255.0))
|
||||
}
|
||||
|
||||
/// A spot light's cone angle in degrees (`ADBE Light Cone Angle`); 90 when absent (344 stores 60).
|
||||
/// A point light stores 90 with `tdsb` 3.
|
||||
pub fn light_cone_angle(&self) -> Option<Tracked<f64>> {
|
||||
let t = read(&self.light_options()?, "ADBE Light Cone Angle", [90.0], 1.0);
|
||||
Some(Tracked { value: t.value[0], source: t.source })
|
||||
}
|
||||
|
||||
/// A spot light's cone feather in percent (`ADBE Light Cone Feather 2`); 50 when absent (345
|
||||
/// stores 30).
|
||||
pub fn light_cone_feather(&self) -> Option<Tracked<f64>> {
|
||||
let t = read(&self.light_options()?, "ADBE Light Cone Feather 2", [50.0], 1.0);
|
||||
Some(Tracked { value: t.value[0], source: t.source })
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
//! The lossless chunk tree.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// The id of a list chunk.
|
||||
pub const LIST: [u8; 4] = *b"LIST";
|
||||
|
||||
/// Non-`LIST` chunk ids whose body is itself a sequence of chunks (observed: each holds one `Utf8`
|
||||
/// chunk). They are parsed as [`Body::Chunks`] when the body is a well-formed chunk sequence and
|
||||
/// kept as [`Body::Data`] otherwise.
|
||||
pub const NESTED_IDS: [[u8; 4]; 3] = [*b"tdsn", *b"pdnm", *b"fnam"];
|
||||
|
||||
/// One chunk: a 4-byte id, a body and an optional pad byte.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Chunk<'a> {
|
||||
/// The 4-byte id, as stored (case matters; some ids end in a space, e.g. `seq `).
|
||||
pub id: [u8; 4],
|
||||
/// The body.
|
||||
pub body: Body<'a>,
|
||||
/// The pad byte that followed an odd-sized body (normally `0`). `None` when the body is even,
|
||||
/// or when an odd body is the last thing of its parent and the file has no pad byte there.
|
||||
/// On writing, an odd body that is not the last sibling always gets a pad byte (`0` if this is
|
||||
/// `None`); the last sibling gets one only if this is `Some`.
|
||||
pub pad: Option<u8>,
|
||||
}
|
||||
|
||||
/// The body of a [`Chunk`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Body<'a> {
|
||||
/// Opaque bytes (the content of nearly all chunks).
|
||||
Data(Cow<'a, [u8]>),
|
||||
/// A body that is a sequence of chunks although the id is not `LIST` (see [`NESTED_IDS`]).
|
||||
Chunks(Vec<Chunk<'a>>),
|
||||
/// A `LIST`: a 4-byte list type followed by chunks.
|
||||
List { list_type: [u8; 4], children: Vec<Chunk<'a>> },
|
||||
/// A `LIST` whose content is not a well-formed chunk sequence (or is nested deeper than the
|
||||
/// limit), kept as bytes after the list type (observed: `LIST btdk` holds raw text).
|
||||
OpaqueList { list_type: [u8; 4], data: Cow<'a, [u8]> },
|
||||
}
|
||||
|
||||
impl<'a> Chunk<'a> {
|
||||
/// A data chunk with the pad byte its length needs.
|
||||
pub fn data(id: [u8; 4], data: impl Into<Cow<'a, [u8]>>) -> Self {
|
||||
let data = data.into();
|
||||
let pad = if data.len() % 2 == 1 { Some(0) } else { None };
|
||||
Self { id, body: Body::Data(data), pad }
|
||||
}
|
||||
|
||||
/// A `LIST` chunk.
|
||||
pub fn list(list_type: [u8; 4], children: Vec<Chunk<'a>>) -> Self {
|
||||
Self { id: LIST, body: Body::List { list_type, children }, pad: None }
|
||||
}
|
||||
|
||||
/// The raw bytes of a [`Body::Data`] chunk, or the bytes after the list type of an opaque list.
|
||||
pub fn bytes(&self) -> Option<&[u8]> {
|
||||
match &self.body {
|
||||
Body::Data(d) => Some(d),
|
||||
Body::OpaqueList { data, .. } => Some(data),
|
||||
Body::Chunks(_) | Body::List { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The child chunks of a list or nested chunk; empty for data.
|
||||
pub fn children(&self) -> &[Chunk<'a>] {
|
||||
match &self.body {
|
||||
Body::Chunks(c) | Body::List { children: c, .. } => c,
|
||||
Body::Data(_) | Body::OpaqueList { .. } => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Mutable child chunks; empty for data.
|
||||
pub fn children_mut(&mut self) -> &mut [Chunk<'a>] {
|
||||
match &mut self.body {
|
||||
Body::Chunks(c) | Body::List { children: c, .. } => c,
|
||||
Body::Data(_) | Body::OpaqueList { .. } => &mut [],
|
||||
}
|
||||
}
|
||||
|
||||
/// The list type when this is a `LIST` (parsed or opaque).
|
||||
pub fn list_type(&self) -> Option<[u8; 4]> {
|
||||
match &self.body {
|
||||
Body::List { list_type, .. } | Body::OpaqueList { list_type, .. } => Some(*list_type),
|
||||
Body::Data(_) | Body::Chunks(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when this is a `LIST` of the given type.
|
||||
pub fn is_list(&self, list_type: &[u8; 4]) -> bool {
|
||||
self.id == LIST && self.list_type().is_some_and(|t| &t == list_type)
|
||||
}
|
||||
|
||||
/// True when this is a `LIST` whose content could not be read as chunks (see
|
||||
/// [`Body::OpaqueList`]): damaged, or nested deeper than the limit.
|
||||
pub fn is_opaque_list(&self) -> bool {
|
||||
matches!(self.body, Body::OpaqueList { .. })
|
||||
}
|
||||
|
||||
/// True when this is a chunk (not a `LIST`) with the given id.
|
||||
pub fn is(&self, id: &[u8; 4]) -> bool {
|
||||
&self.id == id
|
||||
}
|
||||
|
||||
/// The first child (non-list) chunk with this id.
|
||||
pub fn child(&self, id: &[u8; 4]) -> Option<&Chunk<'a>> {
|
||||
self.children().iter().find(|c| c.is(id))
|
||||
}
|
||||
|
||||
/// The first child `LIST` of this type.
|
||||
pub fn child_list(&self, list_type: &[u8; 4]) -> Option<&Chunk<'a>> {
|
||||
self.children().iter().find(|c| c.is_list(list_type))
|
||||
}
|
||||
|
||||
/// Visits every chunk below this one depth-first (children before later siblings), without
|
||||
/// recursion; the depth counts from 1 for the children of this chunk.
|
||||
pub fn descendants(&self) -> Walk<'_, 'a> {
|
||||
Walk { stack: vec![(self.children().iter(), 1)] }
|
||||
}
|
||||
|
||||
/// The first descendant `LIST` of this type, searching depth-first.
|
||||
pub fn find_list(&self, list_type: &[u8; 4]) -> Option<&Chunk<'a>> {
|
||||
self.descendants().map(|(_, c)| c).find(|c| c.is_list(list_type))
|
||||
}
|
||||
|
||||
/// Copies all borrowed bytes so the tree no longer borrows the input.
|
||||
pub fn into_owned(self) -> Chunk<'static> {
|
||||
let body = match self.body {
|
||||
Body::Data(d) => Body::Data(Cow::Owned(d.into_owned())),
|
||||
Body::Chunks(c) => Body::Chunks(c.into_iter().map(Chunk::into_owned).collect()),
|
||||
Body::List { list_type, children } => Body::List { list_type, children: children.into_iter().map(Chunk::into_owned).collect() },
|
||||
Body::OpaqueList { list_type, data } => Body::OpaqueList { list_type, data: Cow::Owned(data.into_owned()) },
|
||||
};
|
||||
Chunk { id: self.id, body, pad: self.pad }
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed `.aep`: the `RIFX` container's chunks and the bytes after its declared end.
|
||||
///
|
||||
/// Writing it back with [`crate::container::write`] reproduces the input byte for byte (the container size
|
||||
/// and every list size are recomputed from the tree and equal what the file declared).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AepFile<'a> {
|
||||
/// The top-level chunks (after the `Egg!` form type).
|
||||
pub chunks: Vec<Chunk<'a>>,
|
||||
/// The bytes after the container's declared end. After Effects puts an XMP packet there.
|
||||
pub trailer: Cow<'a, [u8]>,
|
||||
}
|
||||
|
||||
impl<'a> AepFile<'a> {
|
||||
/// The first top-level chunk with this id.
|
||||
pub fn chunk(&self, id: &[u8; 4]) -> Option<&Chunk<'a>> {
|
||||
self.chunks.iter().find(|c| c.is(id))
|
||||
}
|
||||
|
||||
/// The first top-level `LIST` of this type.
|
||||
pub fn list(&self, list_type: &[u8; 4]) -> Option<&Chunk<'a>> {
|
||||
self.chunks.iter().find(|c| c.is_list(list_type))
|
||||
}
|
||||
|
||||
/// The XMP packet in the trailer (from `<?xpacket begin` to the end of `<?xpacket end ...?>`).
|
||||
pub fn xmp(&self) -> Option<&[u8]> {
|
||||
let start = find(&self.trailer, b"<?xpacket begin")?;
|
||||
let rest = self.trailer.get(start..)?;
|
||||
let end_marker = find(rest, b"<?xpacket end")?;
|
||||
let tail = rest.get(end_marker..)?;
|
||||
let close = find(tail, b"?>")?;
|
||||
rest.get(..end_marker.checked_add(close)?.checked_add(2)?)
|
||||
}
|
||||
|
||||
/// Visits every chunk depth-first with its nesting depth (the top level is 1), without recursion.
|
||||
pub fn walk(&self) -> Walk<'_, 'a> {
|
||||
Walk { stack: vec![(self.chunks.iter(), 1)] }
|
||||
}
|
||||
|
||||
/// Copies all borrowed bytes so the file no longer borrows the input.
|
||||
pub fn into_owned(self) -> AepFile<'static> {
|
||||
AepFile { chunks: self.chunks.into_iter().map(Chunk::into_owned).collect(), trailer: Cow::Owned(self.trailer.into_owned()) }
|
||||
}
|
||||
}
|
||||
|
||||
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
if needle.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
hay.windows(needle.len()).position(|w| w == needle)
|
||||
}
|
||||
|
||||
/// Depth-first iterator over all chunks, see [`AepFile::walk`].
|
||||
pub struct Walk<'f, 'a> {
|
||||
stack: Vec<(std::slice::Iter<'f, Chunk<'a>>, usize)>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Iterator for Walk<'f, 'a> {
|
||||
type Item = (usize, &'f Chunk<'a>);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
loop {
|
||||
let (iter, depth) = self.stack.last_mut()?;
|
||||
let depth = *depth;
|
||||
match iter.next() {
|
||||
Some(chunk) => {
|
||||
let kids = chunk.children();
|
||||
if !kids.is_empty() {
|
||||
self.stack.push((kids.iter(), depth.saturating_add(1)));
|
||||
}
|
||||
return Some((depth, chunk));
|
||||
}
|
||||
None => {
|
||||
self.stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
//! The effect table of the importer (`crate::import`): an After Effects effect (its match name) and its parameters (by
|
||||
//! The effect table shared by the importer (`crate::import`) and the exporter
|
||||
//! (`crate::export`): an After Effects effect (its match name) and its parameters (by
|
||||
//! their index in `parT`) map to an EffectCraft effect, a parameter id and a unit conversion.
|
||||
//! Plain data; the evidence for each row is in `docs/aep-format.md` 3.7 and the case numbers in
|
||||
//! the comments.
|
||||
//! the comments. The importer reads a file through it, the exporter writes the inverse.
|
||||
|
||||
use crate::container::effects::ParamKind;
|
||||
use ParamKind as K;
|
||||
use craft_aep::ParamKind;
|
||||
|
||||
/// How a stored parameter value becomes an EffectCraft value.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -37,6 +38,19 @@ pub enum Conv {
|
||||
Skip,
|
||||
}
|
||||
|
||||
impl Conv {
|
||||
/// For a number (`Percent`, `Plain`, `Factor`): what a stored value is multiplied by to give
|
||||
/// the value here. `None` for every other conversion.
|
||||
pub fn number_scale(self) -> Option<f64> {
|
||||
match self {
|
||||
Conv::Percent { valid_max } => Some(100.0 / valid_max),
|
||||
Conv::Plain { .. } => Some(1.0),
|
||||
Conv::Factor { factor, .. } => Some(factor),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// After Effects' popup items as the corpus stores them (`pdnm`).
|
||||
/// 368.
|
||||
pub const RAMP_SHAPE: &[&str] = &["Linear Ramp", "Radial Ramp"];
|
||||
@@ -109,6 +123,8 @@ pub const HUE_SAT_CHANNEL: &[&str] = &["Master", "Reds", "Yellows", "Greens", "C
|
||||
pub const LEVELS_CHANNEL: &[&str] = &["RGB", "Red", "Green", "Blue", "Alpha"];
|
||||
/// 511.
|
||||
pub const LEVELS_CLIP: &[&str] = &["On", "Off", "Off for 32 bpc Color"];
|
||||
/// The Cryptomatte plug-in's Output (`Cryptomatte-0002`).
|
||||
pub const CRYPTOMATTE_OUTPUT: &[&str] = &["Colors", "Matted Colors", "Matted RGBA", "Matte Only"];
|
||||
|
||||
/// One mapped parameter.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -120,6 +136,10 @@ pub struct ParamMap {
|
||||
/// The EffectCraft parameter id.
|
||||
pub target: &'static str,
|
||||
pub conv: Conv,
|
||||
/// The range EffectCraft's effect works in when it is narrower than the range After Effects
|
||||
/// accepts (the effect limits the value there): a stored value or key outside it is imported
|
||||
/// as it is and reported. `None`: no narrower range.
|
||||
pub limit: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
/// Values of an effect that are not ordinary parameters.
|
||||
@@ -134,6 +154,17 @@ pub enum Extra {
|
||||
Curves,
|
||||
/// Mesh Warp's Distortion Mesh (965, 985, `MeshData`).
|
||||
MeshWarp,
|
||||
/// Lumetri Color: every parameter goes through its own table, keyed by match name
|
||||
/// (`import/lumetri.rs`, 1200).
|
||||
Lumetri,
|
||||
/// EXtractoR's Channel Info (`ExtractorChannels`): the channels by name.
|
||||
Extractor,
|
||||
/// IDentifier's Channel Info (`identifier_channel_type`): the chosen channel by name.
|
||||
Identifier,
|
||||
/// The Cryptomatte plug-in: the layer and selection in its Settings data
|
||||
/// (`CryptomatteData`), Output split over EffectCraft's Display and Matte Only; every
|
||||
/// parameter is handled by the importer's Cryptomatte step, none by the table.
|
||||
Cryptomatte,
|
||||
}
|
||||
|
||||
/// One mapped effect.
|
||||
@@ -147,7 +178,12 @@ pub struct EffectMap {
|
||||
}
|
||||
|
||||
const fn pm(index: usize, kind: ParamKind, target: &'static str, conv: Conv) -> ParamMap {
|
||||
ParamMap { index, kind, target, conv }
|
||||
ParamMap { index, kind, target, conv, limit: None }
|
||||
}
|
||||
|
||||
/// [`pm`] for a parameter EffectCraft's effect limits to `lo..=hi` (see [`ParamMap::limit`]).
|
||||
const fn pm_limited(index: usize, kind: ParamKind, target: &'static str, conv: Conv, lo: f64, hi: f64) -> ParamMap {
|
||||
ParamMap { index, kind, target, conv, limit: Some((lo, hi)) }
|
||||
}
|
||||
|
||||
const fn fx(match_name: &'static str, effect: &'static str, params: &'static [ParamMap]) -> EffectMap {
|
||||
@@ -339,6 +375,15 @@ pub const MATTE_USE: &[&str] = &["Red Channel", "Green Channel", "Blue Channel",
|
||||
/// 903.
|
||||
pub const SHUTTER_CONTROL: &[&str] = &["Manual", "Automatic"];
|
||||
|
||||
// After Effects' popup items of the #3110 effects as the 2026-11-05 importer block stores them
|
||||
// (`pdnm`; the `echo-*` and `colstab-*` compositions).
|
||||
/// Echo's Echo Operator (`echo-05` ... `echo-10`).
|
||||
pub const ECHO_OPERATOR: &[&str] = &["Add", "Maximum", "Minimum", "Screen", "Composite In Back", "Composite In Front", "Blend"];
|
||||
/// Color Stabilizer's Stabilize (`colstab-02`, `colstab-03`; the fresh default is Levels).
|
||||
pub const STABILIZE: &[&str] = &["Brightness", "Levels", "Curves"];
|
||||
/// IDentifier's Display (`identifier-04` ... `identifier-06`, `1300-thirdparty.aep`).
|
||||
pub const IDENTIFIER_DISPLAY: &[&str] = &["Colors", "Luma Matte", "Alpha Matte", "Raw"];
|
||||
|
||||
/// The effects the importer converts.
|
||||
pub const EFFECTS: &[EffectMap] = &[
|
||||
// Tint (356-364): Map Black To, Map White To, Amount to Tint; 4 = Swap Colors (a button).
|
||||
@@ -509,6 +554,12 @@ pub const EFFECTS: &[EffectMap] = &[
|
||||
],
|
||||
extra: Extra::MeshWarp,
|
||||
},
|
||||
// Lumetri Color (1200): the parameters are mapped by match name, not by `parT` index
|
||||
// (`import/lumetri.rs`).
|
||||
EffectMap { match_name: "ADBE Lumetri", effect: "ec.color.lumetri", params: &[], extra: Extra::Lumetri },
|
||||
// The Cryptomatte plug-in (docs/aep-format.md 3.7): 1 Settings data, 2 Output, 3 Selection
|
||||
// Mode, imported by the Cryptomatte step (`Extra::Cryptomatte`).
|
||||
EffectMap { match_name: "Cryptomatte", effect: "ec.3d.cryptomatte", params: &[], extra: Extra::Cryptomatte },
|
||||
// Expression controls (070-077, 217-221, 310).
|
||||
// Directional Blur (711): Direction in degrees, Blur Length in pixels (valid max 1 000).
|
||||
fx(
|
||||
@@ -1006,6 +1057,84 @@ pub const EFFECTS: &[EffectMap] = &[
|
||||
pm(4, K::FloatSlider, "vectorDetail", Conv::Plain { valid_max: 100.0 }),
|
||||
],
|
||||
),
|
||||
// HDR Highlight Compression (importer block 2026-11-05, `hdr-*`): Amount a float slider in
|
||||
// percent (valid 0..100, default 100).
|
||||
fx("ADBE HDR ToneMap", "ec.utility.hdrcompression", &[pm(1, K::FloatSlider, "amount", Conv::Plain { valid_max: 100.0 })]),
|
||||
// Echo (`echo-*`): Echo Time in seconds (valid -30 000..30 000), Number Of Echoes an integer
|
||||
// (valid 0..30 000), Starting Intensity 0..1, Decay (valid 0..100, slider 0..1), Echo
|
||||
// Operator. EffectCraft's Echo uses at most 255 echoes and a Decay up to 1.
|
||||
fx(
|
||||
"ADBE Echo",
|
||||
"ec.time.echo",
|
||||
&[
|
||||
pm(1, K::FloatSlider, "echoTime", Conv::Plain { valid_max: 30000.0 }),
|
||||
pm_limited(2, K::IntSlider, "numberOfEchoes", Conv::Plain { valid_max: 30000.0 }, 0.0, 255.0),
|
||||
pm(3, K::FloatSlider, "startingIntensity", Conv::Plain { valid_max: 1.0 }),
|
||||
pm_limited(4, K::FloatSlider, "decay", Conv::Plain { valid_max: 100.0 }, 0.0, 1.0),
|
||||
pm(5, K::Popup, "echoOperator", Conv::Popup { default: 1, items: ECHO_OPERATOR }),
|
||||
],
|
||||
),
|
||||
// Linear Wipe (`linwipe-*`): Transition Completion and Feather fixed sliders (valid 100 and
|
||||
// 32 000), Wipe Angle in degrees.
|
||||
fx(
|
||||
"ADBE Linear Wipe",
|
||||
"ec.transition.linearwipe",
|
||||
&[
|
||||
pm(1, K::FixedSlider, "completion", Conv::Plain { valid_max: 100.0 }),
|
||||
pm(2, K::Angle, "angle", Conv::Angle),
|
||||
pm(3, K::FixedSlider, "feather", Conv::Plain { valid_max: 32000.0 }),
|
||||
],
|
||||
),
|
||||
// Offset (`offset-*`): Blend With Original is a 0..1 fraction, a percentage here.
|
||||
fx("ADBE Offset", "ec.distort.offset", &[pm(1, K::Point, "shift", Conv::Point), pm(2, K::FixedSlider, "blend", Conv::Percent { valid_max: 1.0 })]),
|
||||
// Color Stabilizer (`colstab-*`): Stabilize (fresh default Levels), the three sample points,
|
||||
// Sample Size a fixed slider (valid 50, default 3). The reference frame (Set Frame) is not a
|
||||
// parameter in the file and is not imported.
|
||||
fx(
|
||||
"ADBE Deflicker",
|
||||
"ec.color.colorstabilizer",
|
||||
&[
|
||||
pm(1, K::Popup, "stabilize", Conv::Popup { default: 2, items: STABILIZE }),
|
||||
pm(2, K::Point, "blackPoint", Conv::Point),
|
||||
pm(3, K::Point, "midPoint", Conv::Point),
|
||||
pm(4, K::Point, "whitePoint", Conv::Point),
|
||||
pm(5, K::FixedSlider, "sampleSize", Conv::Plain { valid_max: 50.0 }),
|
||||
],
|
||||
),
|
||||
// CC Color Neutralizer (importer block 2026-11-05, `ccneutral-*`): Pinning and Blend w.
|
||||
// Original are float sliders in percent (valid 0..100). After Effects' correction is the Red /
|
||||
// Green / Blue slider of each range (3-5, 9-11, 15-17; the Unbalance colours are pickers that
|
||||
// set them and keep no record), then View (22) and Black / White Point (23, 24):
|
||||
// EffectCraft's CC Color Neutralizer has none of them, so they are reported when stored.
|
||||
fx(
|
||||
"CS Color Neutralizer",
|
||||
"ec.color.cccolorneutralizer",
|
||||
&[pm(19, K::FloatSlider, "pinning", Conv::Plain { valid_max: 100.0 }), pm(20, K::FloatSlider, "blendWOriginal", Conv::Plain { valid_max: 100.0 })],
|
||||
),
|
||||
// EXtractoR (`extractor-*`): 1 Channel Info (arbitrary data, `Extra::Extractor`), 2 / 6 the
|
||||
// Process group, Black and White Point float sliders (valid ±3.4e38, the float32 range),
|
||||
// UnMult. EffectCraft's Clip has no counterpart and stays off.
|
||||
EffectMap {
|
||||
match_name: "EXtractoR",
|
||||
effect: "ec.3d.extractor",
|
||||
params: &[
|
||||
pm(3, K::FloatSlider, "blackPoint", Conv::Plain { valid_max: F32_MAX }),
|
||||
pm(4, K::FloatSlider, "whitePoint", Conv::Plain { valid_max: F32_MAX }),
|
||||
pm(5, K::Checkbox, "unMult", Conv::Checkbox),
|
||||
],
|
||||
extra: Extra::Extractor,
|
||||
},
|
||||
// IDentifier (`identifier-*`): 1 Channel Info (arbitrary data, `Extra::Identifier`), 2 Display,
|
||||
// 3 ID an integer slider (valid 0..2 147 483 647).
|
||||
EffectMap {
|
||||
match_name: "IDentifier",
|
||||
effect: "ec.3d.identifier",
|
||||
params: &[
|
||||
pm(2, K::Popup, "display", Conv::Popup { default: 1, items: IDENTIFIER_DISPLAY }),
|
||||
pm(3, K::IntSlider, "id", Conv::Plain { valid_max: 2_147_483_647.0 }),
|
||||
],
|
||||
extra: Extra::Identifier,
|
||||
},
|
||||
// Layer Control (076, 220, 320, 321): the default is the owning layer, None is unset.
|
||||
fx("ADBE Layer Control", "ec.control.layer", &[pm(1, K::Layer, "layer", Conv::LayerRef { own: true })]),
|
||||
fx("ADBE Slider Control", "ec.control.slider", &[pm(1, K::FloatSlider, "slider", Conv::Plain { valid_max: 1_000_000.0 })]),
|
||||
@@ -1019,16 +1148,54 @@ pub const EFFECTS: &[EffectMap] = &[
|
||||
pub const EXPOSURE: Conv = Conv::Plain { valid_max: 100.0 };
|
||||
pub const OFFSET: Conv = Conv::Plain { valid_max: 2.0 };
|
||||
pub const GAMMA: Conv = Conv::Plain { valid_max: 10.0 };
|
||||
/// The largest float32, the valid maximum of EXtractoR's Black and White Point.
|
||||
pub const F32_MAX: f64 = f32::MAX as f64;
|
||||
/// The valid maximum of Glow's A & B Midpoint (16.16 of 0.99, 427).
|
||||
pub const GLOW_MIDPOINT_MAX: f64 = 0.990_005_493_164_062_5;
|
||||
|
||||
/// The key a popup item is matched by between the two programs: trimmed, lower case, and
|
||||
/// Set Matte's "Red Channel" ... "Alpha Channel" are EffectCraft's "Red" ... "Alpha" (904 E24).
|
||||
///
|
||||
/// Lower case is Unicode's, not only ASCII's: After Effects stores popup items in its UI
|
||||
/// language, so an item can start with a capital outside ASCII (French "Écran"), and its key must
|
||||
/// be the same as for the same word in lower case.
|
||||
pub fn popup_key(item: &str) -> String {
|
||||
let s = item.trim().to_ascii_lowercase();
|
||||
let s = item.trim().to_lowercase();
|
||||
s.strip_suffix(" channel").map(str::to_string).unwrap_or(s)
|
||||
}
|
||||
|
||||
/// The English [`popup_key`] a non-English After Effects popup item name stands for, when this
|
||||
/// table knows it; `None` otherwise. EffectCraft's own popup options are English only, so a
|
||||
/// project saved by an After Effects set to another UI language never matches them by name and
|
||||
/// the parameter falls back to its default (observed on a real "Niveaux" project, French After
|
||||
/// Effects 2026 26.0.0x67: Levels' Channel and Clip to Output Black / White). Add an entry only
|
||||
/// from a confirmed After Effects label, never a guess at a whole menu's translation.
|
||||
pub fn popup_alias(key: &str) -> Option<&'static str> {
|
||||
Some(match key {
|
||||
// French: Levels' Channel popup (`ADBE Easy Levels2-0001`). "Alpha" is the same word in
|
||||
// both languages, so it needs no entry.
|
||||
"rvb" => "rgb",
|
||||
"rouge" => "red",
|
||||
"vert" => "green",
|
||||
"bleu" => "blue",
|
||||
// French: Levels' Clip to Output Black / White popups (`-0008`, `-0009`).
|
||||
"activé" => "on",
|
||||
"désactivé" => "off",
|
||||
"désactivé pour la couleur 32 bpc" => "off for 32 bpc color",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The table row of an After Effects match name.
|
||||
pub fn by_match_name(match_name: &str) -> Option<&'static EffectMap> {
|
||||
EFFECTS.iter().find(|m| m.match_name == match_name)
|
||||
}
|
||||
|
||||
/// The table row of an EffectCraft effect id.
|
||||
pub fn by_effect(effect: &str) -> Option<&'static EffectMap> {
|
||||
EFFECTS.iter().find(|m| m.effect == effect)
|
||||
}
|
||||
|
||||
/// The EffectCraft parameters Hue/Saturation's master values (`Extra::HueSaturation`) go to,
|
||||
/// in the order of the data (hue, saturation, lightness: 444-446).
|
||||
pub const HUE_SATURATION_MASTER: [&str; 3] = ["hue", "saturation", "lightness"];
|
||||
@@ -1036,3 +1203,17 @@ pub const HUE_SATURATION_MASTER: [&str; 3] = ["hue", "saturation", "lightness"];
|
||||
/// The EffectCraft parameters Levels' RGB channel values (`Extra::Levels`) go to, in the order of
|
||||
/// the data (input black, input white, gamma, output black, output white: 512-516).
|
||||
pub const LEVELS_RGB: [&str; 5] = ["inBlack", "inWhite", "gamma", "outBlack", "outWhite"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A capital outside ASCII has the same key as its lower case; ASCII keys are unchanged.
|
||||
#[test]
|
||||
fn popup_key_lowers_non_ascii_capitals() {
|
||||
assert_eq!(popup_key("ÉCRAN"), popup_key("écran"));
|
||||
assert_eq!(popup_key(" Désactivé "), "désactivé");
|
||||
assert_eq!(popup_key("Off for 32 bpc Color"), "off for 32 bpc color");
|
||||
assert_eq!(popup_key("Red Channel"), "red");
|
||||
}
|
||||
}
|
||||
@@ -1,675 +0,0 @@
|
||||
//! Effect instances: match name, instance name, the parameter list from `parT`/`pard` and the
|
||||
//! values stored with the instance.
|
||||
//!
|
||||
//! An effect on a layer is a `LIST sspc` under `ADBE Effect Parade`. It holds `fnam` (the
|
||||
//! instance name), `LIST parT` (the parameter definitions: `parn`, then a `tdmn` and a 148-byte
|
||||
//! `pard` per parameter, a `pdnm` after a popup), `LIST tdgp` (the values) and `pgui`. Only
|
||||
//! parameters that differ from their `pard` default have a value record in the `tdgp` (the Layer
|
||||
//! Control and button records are the exceptions: they always exist).
|
||||
//!
|
||||
//! When several layers carry an effect of the same type, only one instance has a full `parT`; the
|
||||
//! others have an empty `LIST parT` (case 383). Their parameter definitions are the ones in the
|
||||
//! project-level `LIST EfdG` (one `EfDf` per effect type: a `tdmn` with the match name, then a copy
|
||||
//! of one instance's `sspc`), see [`Project::effect_params`]. That copy also carries the values of
|
||||
//! the instance it was copied from, so values are only ever read from the instance's own `tdgp`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::container::Chunk;
|
||||
use crate::container::bytes::{array, be_f32, be_f64, be_i32, be_u16, be_u32, cstr, text, until_nul};
|
||||
use crate::container::typed::{KeyList, Layer, Project, PropGroup, PropNode, Property};
|
||||
|
||||
/// The parameter type, the `u32` at byte 12 of `pard`. The numbering matches the plug-in
|
||||
/// parameter types of the After Effects effect interface.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ParamKind {
|
||||
/// `0`: a layer reference (also the implicit first parameter, the input layer).
|
||||
Layer,
|
||||
/// `1`: an integer slider (Fast Box Blur's Iterations, 412-414): the default is an `i32` at
|
||||
/// `pard` byte 56 (3), the valid maximum an `i32` at byte 128 (50), the value record a plain
|
||||
/// `f64` (1.0).
|
||||
IntSlider,
|
||||
/// `2`: a fixed-point (16.16) slider.
|
||||
FixedSlider,
|
||||
/// `3`: an angle (16.16 degrees).
|
||||
Angle,
|
||||
/// `4`
|
||||
Checkbox,
|
||||
/// `5`
|
||||
Color,
|
||||
/// `6`
|
||||
Point,
|
||||
/// `7`: a popup menu (the items are in the `pdnm` chunk).
|
||||
Popup,
|
||||
/// `9`: no data (the group-end entry `ADBE Effect Built In Params`).
|
||||
NoData,
|
||||
/// `10`: a floating-point slider.
|
||||
FloatSlider,
|
||||
/// `11`: arbitrary data (Hue/Saturation's Channel Range, Levels' Histogram, 443, 511): the
|
||||
/// value record is a 4-byte `cdat`, the data itself the `aRbp` of the `LIST aRbs` after it,
|
||||
/// see [`Effect::arbitrary_data`].
|
||||
ArbitraryData,
|
||||
/// `12`: a path / mask reference.
|
||||
Path,
|
||||
/// `13`: the start of a twirl-down group (Exposure's Master, Red, Green and Blue, 389). It
|
||||
/// holds no value; its value record always exists with `cdat` 0.
|
||||
GroupStart,
|
||||
/// `14`: the end of a twirl-down group (its name repeats the group's name, 389). It holds no
|
||||
/// value; its value record always exists with `cdat` 0.
|
||||
GroupEnd,
|
||||
/// `15`: a button (Tint's and Gradient Ramp's Swap Colors). It holds no value; its value
|
||||
/// record always exists with `cdat` 0 (356, 368).
|
||||
Button,
|
||||
/// Any other value.
|
||||
Other(u32),
|
||||
}
|
||||
|
||||
impl ParamKind {
|
||||
fn from_u32(v: u32) -> Self {
|
||||
match v {
|
||||
0 => Self::Layer,
|
||||
1 => Self::IntSlider,
|
||||
2 => Self::FixedSlider,
|
||||
3 => Self::Angle,
|
||||
4 => Self::Checkbox,
|
||||
5 => Self::Color,
|
||||
6 => Self::Point,
|
||||
7 => Self::Popup,
|
||||
9 => Self::NoData,
|
||||
10 => Self::FloatSlider,
|
||||
11 => Self::ArbitraryData,
|
||||
12 => Self::Path,
|
||||
13 => Self::GroupStart,
|
||||
14 => Self::GroupEnd,
|
||||
15 => Self::Button,
|
||||
other => Self::Other(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoded parameter value.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum ParamValue {
|
||||
/// A slider or angle value as stored: float sliders, fixed sliders and angles keep a plain
|
||||
/// `f64` in their value record (an angle in degrees; a fixed slider in its own scale, see
|
||||
/// [`EffectParam::valid_max`]); defaults read from `pard` are 16.16 decoded for fixed sliders
|
||||
/// and angles.
|
||||
Number(f64),
|
||||
/// A checkbox: stored as 1.0 when on; an absent record means off.
|
||||
Bool(bool),
|
||||
/// A point control as stored: a fraction of the layer size (`[111, 222]` px on a 1920x1080
|
||||
/// layer is `[111/1920, 222/1080]`).
|
||||
Point([f64; 2]),
|
||||
/// A layer control: the id of the chosen layer (the `tdpi` chunk next to the value record).
|
||||
/// In the implicit first parameter it is the id of the layer that owns the effect.
|
||||
Layer(u32),
|
||||
/// A colour as ARGB fractions 0..1 (stored as doubles 0..255 in the order alpha, red, green,
|
||||
/// blue: a colour `[0.2, 0.6, 1]` is `[255, 51, 153, 255]`, with float rounding).
|
||||
Argb([f64; 4]),
|
||||
/// A popup's item index, 1-based (Gradient Ramp's Radial Ramp is 2, 377): the default in
|
||||
/// `pard`, or the stored selection.
|
||||
Index(u32),
|
||||
}
|
||||
|
||||
/// What a Layer Control points at, given the id of the layer that owns the effect.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LayerRef {
|
||||
/// The layer itself (the default, "Layer 1" on the first layer): the stored `tdpi` equals the
|
||||
/// owning layer's id.
|
||||
This,
|
||||
/// None: the stored `tdpi` is 0.
|
||||
Nothing,
|
||||
/// Another layer, by id.
|
||||
Layer(u32),
|
||||
}
|
||||
|
||||
/// An effect instance on a layer.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Effect<'f, 'a> {
|
||||
match_name: String,
|
||||
chunk: &'f Chunk<'a>,
|
||||
}
|
||||
|
||||
/// Where the parameter definitions of an effect instance come from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DefinitionSource {
|
||||
/// The instance's own `parT`.
|
||||
Instance,
|
||||
/// The project-level `EfdG/EfDf` copy for the effect's match name (the instance's own `parT`
|
||||
/// is empty, 383).
|
||||
Project,
|
||||
/// Neither has any: the effect has no readable parameter definitions.
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// One parameter of an effect.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EffectParam<'f, 'a> {
|
||||
/// The position in `parT` (0 is the implicit input layer).
|
||||
pub index: usize,
|
||||
/// The `tdmn` match name (`<effect match name>-NNNN`, the last one is
|
||||
/// `ADBE Effect Built In Params`).
|
||||
pub match_name: String,
|
||||
pub kind: ParamKind,
|
||||
/// The parameter name (`Blurriness`, `Slider`, ...; empty for the implicit parameters).
|
||||
pub name: String,
|
||||
/// The popup items (`pdnm`, split at `|`; for a button its label, e.g. `Swap Colors`).
|
||||
pub items: Option<Vec<String>>,
|
||||
/// True when the definition is the project-level copy (see [`DefinitionSource::Project`]).
|
||||
pub borrowed_definition: bool,
|
||||
pard: &'f [u8],
|
||||
stored: Option<Property<'f, 'a>>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Effect<'f, 'a> {
|
||||
/// The effect's match name (`ADBE Slider Control`, `ADBE Gaussian Blur 2`, ...).
|
||||
pub fn match_name(&self) -> &str {
|
||||
&self.match_name
|
||||
}
|
||||
|
||||
/// The underlying `LIST sspc` chunk.
|
||||
pub fn chunk(&self) -> &'f Chunk<'a> {
|
||||
self.chunk
|
||||
}
|
||||
|
||||
/// The instance name shown in the effect controls (`fnam`).
|
||||
pub fn name(&self) -> Option<String> {
|
||||
self.chunk.child(b"fnam")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text)
|
||||
}
|
||||
|
||||
/// The name the user gave the instance: the `tdsn` of the instance's value group when it is
|
||||
/// not the placeholder `-_0_/-` (610: `My Tint`; `fnam` keeps the effect's own name `Tint`).
|
||||
/// `None` while the instance shows the effect's name.
|
||||
pub fn user_name(&self) -> Option<String> {
|
||||
let values = self.chunk.child_list(b"tdgp")?;
|
||||
let name = values.child(b"tdsn")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text)?;
|
||||
(name != "-_0_/-" && !name.is_empty()).then_some(name)
|
||||
}
|
||||
|
||||
/// The instance's fx switch: the `tdsb` of its value group is 1 when on and 0 when switched
|
||||
/// off (`fx-switch` cases: one instance on, one off, both in one save). `None` for another
|
||||
/// value or a missing group.
|
||||
pub fn enabled(&self) -> Option<bool> {
|
||||
match be_u32(self.chunk.child_list(b"tdgp")?.child(b"tdsb")?.bytes()?, 0)? {
|
||||
1 => Some(true),
|
||||
0 => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The name After Effects shows for the instance: [`Effect::user_name`], else [`Effect::name`].
|
||||
pub fn display_name(&self) -> Option<String> {
|
||||
self.user_name().or_else(|| self.name())
|
||||
}
|
||||
|
||||
/// The number of parameters declared by `parn` (the implicit input layer and the built-in
|
||||
/// entry included).
|
||||
pub fn declared_param_count(&self) -> Option<u32> {
|
||||
be_u32(self.chunk.child_list(b"parT")?.child(b"parn")?.bytes()?, 0)
|
||||
}
|
||||
|
||||
/// True when the instance's own `parT` holds parameter definitions (a `pard`). A second
|
||||
/// instance of an effect type has an empty `parT` (383).
|
||||
pub fn has_own_definitions(&self) -> bool {
|
||||
self.chunk.child_list(b"parT").is_some_and(has_pard)
|
||||
}
|
||||
|
||||
/// The parameters in the order of the instance's own `parT`. Empty for an instance whose
|
||||
/// `parT` is empty; [`Project::effect_params`] falls back to the project's definitions.
|
||||
pub fn params(&self) -> Vec<EffectParam<'f, 'a>> {
|
||||
match self.chunk.child_list(b"parT") {
|
||||
Some(part) => self.params_from(part, false),
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters described by `part` (a `LIST parT`) with the values of this instance.
|
||||
fn params_from(&self, part: &'f Chunk<'a>, borrowed: bool) -> Vec<EffectParam<'f, 'a>> {
|
||||
let mut out: Vec<EffectParam<'f, 'a>> = Vec::new();
|
||||
// The stored values by match name: the first entry of a name, as `PropGroup::get` finds it
|
||||
// (a group of that name means no stored value). Indexed once: a lookup per parameter
|
||||
// would scan the whole group for each of them.
|
||||
let mut values: HashMap<String, Option<Property<'f, 'a>>> = HashMap::new();
|
||||
for e in self.chunk.child_list(b"tdgp").and_then(PropGroup::from_chunk).map(|g| g.entries()).unwrap_or_default() {
|
||||
let stored = if let PropNode::Property(p) = e.node { Some(p) } else { None };
|
||||
values.entry(e.match_name).or_insert(stored);
|
||||
}
|
||||
let mut pending: Option<String> = None;
|
||||
for c in part.children() {
|
||||
if c.is(b"tdmn") {
|
||||
pending = c.bytes().map(|b| text(until_nul(b)));
|
||||
} else if c.is(b"pard") {
|
||||
let Some(pard) = c.bytes() else { continue };
|
||||
let match_name = pending.take().unwrap_or_default();
|
||||
let stored = values.get(&match_name).copied().flatten();
|
||||
out.push(EffectParam {
|
||||
index: out.len(),
|
||||
match_name,
|
||||
kind: ParamKind::from_u32(be_u32(pard, 12).unwrap_or(u32::MAX)),
|
||||
name: cstr(pard, 16, 32).unwrap_or_default(),
|
||||
items: None,
|
||||
borrowed_definition: borrowed,
|
||||
pard,
|
||||
stored,
|
||||
});
|
||||
} else if c.is(b"pdnm")
|
||||
&& let Some(last) = out.last_mut()
|
||||
&& let Some(u) = c.children().iter().find(|u| u.is(b"Utf8"))
|
||||
&& let Some(b) = u.bytes()
|
||||
{
|
||||
last.items = Some(text(b).split('|').map(str::to_string).collect());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn has_pard(part: &Chunk<'_>) -> bool {
|
||||
part.children().iter().any(|c| c.is(b"pard"))
|
||||
}
|
||||
|
||||
impl<'f, 'a> Project<'f, 'a> {
|
||||
/// The project-level effect definitions (`LIST EfdG`): one entry per effect type, the match
|
||||
/// name and the `LIST parT` of the copied instance, in file order (the stack order of the
|
||||
/// types, 365/366). The `EfDC` count before them is little-endian and is not needed to read
|
||||
/// them. A type whose copy has no definitions is left out.
|
||||
pub fn effect_definitions(&self) -> Vec<(String, &'f Chunk<'a>)> {
|
||||
let mut out: Vec<(String, &'f Chunk<'a>)> = Vec::new();
|
||||
let Some(defs) = self.effect_defs else { return out };
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
for df in defs.children().iter().filter(|c| c.is_list(b"EfDf")) {
|
||||
let mut name: Option<String> = None;
|
||||
for c in df.children() {
|
||||
if c.is(b"tdmn") {
|
||||
name = c.bytes().map(|b| text(until_nul(b)));
|
||||
} else if c.is_list(b"sspc")
|
||||
&& let Some(n) = name.take()
|
||||
&& let Some(part) = c.child_list(b"parT").filter(|p| has_pard(p))
|
||||
&& seen.insert(n.clone())
|
||||
{
|
||||
out.push((n, part));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [`Self::effect_definitions`] indexed by match name, for looking up many effects: build it
|
||||
/// once per file, not once per effect (a file can hold many definitions and many instances).
|
||||
pub fn effect_definition_index(&self) -> EffectDefinitions<'f, 'a> {
|
||||
EffectDefinitions { by_name: self.effect_definitions().into_iter().collect() }
|
||||
}
|
||||
|
||||
/// Where the parameter definitions of `effect` come from. Builds the index each call: use
|
||||
/// [`Self::effect_definition_index`] for more than one effect.
|
||||
pub fn definition_source(&self, effect: &Effect<'f, 'a>) -> DefinitionSource {
|
||||
self.effect_definition_index().source(effect)
|
||||
}
|
||||
|
||||
/// The parameters of `effect` ([`EffectDefinitions::params`]). Builds the index each call:
|
||||
/// use [`Self::effect_definition_index`] for more than one effect.
|
||||
pub fn effect_params(&self, effect: &Effect<'f, 'a>) -> Vec<EffectParam<'f, 'a>> {
|
||||
self.effect_definition_index().params(effect)
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-level effect definitions by match name ([`Project::effect_definition_index`]).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct EffectDefinitions<'f, 'a> {
|
||||
by_name: HashMap<String, &'f Chunk<'a>>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> EffectDefinitions<'f, 'a> {
|
||||
/// Where the parameter definitions of `effect` come from.
|
||||
pub fn source(&self, effect: &Effect<'f, 'a>) -> DefinitionSource {
|
||||
if effect.has_own_definitions() {
|
||||
DefinitionSource::Instance
|
||||
} else if self.by_name.contains_key(effect.match_name()) {
|
||||
DefinitionSource::Project
|
||||
} else {
|
||||
DefinitionSource::Missing
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of `effect`: from its own `parT`, or, when that is empty, from the
|
||||
/// project-level definition of its match name ([`EffectParam::borrowed_definition`]). Values
|
||||
/// always come from the instance's own records (absent = the `pard` default); the project
|
||||
/// copy's values belong to another instance and are never read.
|
||||
pub fn params(&self, effect: &Effect<'f, 'a>) -> Vec<EffectParam<'f, 'a>> {
|
||||
if effect.has_own_definitions() {
|
||||
return effect.params();
|
||||
}
|
||||
match self.by_name.get(effect.match_name()) {
|
||||
Some(part) => effect.params_from(part, true),
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> EffectParam<'f, 'a> {
|
||||
/// The raw 148-byte `pard` record (it contains stale memory after the name).
|
||||
pub fn pard(&self) -> &'f [u8] {
|
||||
self.pard
|
||||
}
|
||||
|
||||
/// The value record stored with the instance (`<match>-NNNN` in the instance's `tdgp`), which
|
||||
/// exists only for parameters that differ from the default.
|
||||
pub fn stored(&self) -> Option<Property<'f, 'a>> {
|
||||
self.stored
|
||||
}
|
||||
|
||||
/// True when the parameter's value record has keyframes ([`EffectParam::keys`]); then
|
||||
/// [`EffectParam::stored_value`] is `None` and [`EffectParam::value`] is not the value.
|
||||
pub fn is_animated(&self) -> bool {
|
||||
self.stored.is_some_and(|p| p.is_animated())
|
||||
}
|
||||
|
||||
/// The keyframes of an animated parameter: plain 48-byte records for sliders (363), 152-byte
|
||||
/// colour records (364) and 104-byte spatial records for points (382), with the values in the
|
||||
/// stored units of [`EffectParam::stored_value`].
|
||||
pub fn keys(&self) -> Option<KeyList<'f>> {
|
||||
self.stored?.keys()
|
||||
}
|
||||
|
||||
/// The value in the value record: float and fixed sliders, angles, checkboxes, points,
|
||||
/// colours, popups and layer controls. A record counts when its `tdsb` is 1 and it has no
|
||||
/// keyframes; a layer control reads the `tdpi` chunk; a button has no value.
|
||||
pub fn stored_value(&self) -> Option<ParamValue> {
|
||||
let p = self.stored?;
|
||||
if self.kind != ParamKind::Layer && p.flags() != Some(1) {
|
||||
return None;
|
||||
}
|
||||
self.recorded_value()
|
||||
}
|
||||
|
||||
/// The value in the value record when the record is written (`tdsb` 1) or in the default
|
||||
/// state (`tdsb` 3): what [`EffectParam::stored_value`] reads, also from a default-state
|
||||
/// record. Lumetri Color writes the values of its hidden parameters so (High Dynamic Range,
|
||||
/// HDR Specular, Look: 1200 `lumetri-01-set-all`, `-02-sec-top`, `-06-sec-light`; After
|
||||
/// Effects reads back the recorded values). `None` with keyframes, without a record or for a
|
||||
/// record in any other state (no sample has one; the importer reports it as damaged).
|
||||
pub fn recorded_value(&self) -> Option<ParamValue> {
|
||||
let p = self.stored?;
|
||||
if self.kind == ParamKind::Layer {
|
||||
return be_u32(p.chunk().child(b"tdpi")?.bytes()?, 0).map(ParamValue::Layer);
|
||||
}
|
||||
if !matches!(p.flags(), Some(1 | 3)) || p.is_animated() {
|
||||
return None;
|
||||
}
|
||||
let v = p.static_value()?;
|
||||
match self.kind {
|
||||
ParamKind::FloatSlider | ParamKind::FixedSlider | ParamKind::Angle | ParamKind::IntSlider => v.first().copied().map(ParamValue::Number),
|
||||
ParamKind::Checkbox => v.first().map(|x| ParamValue::Bool(*x != 0.0)),
|
||||
ParamKind::Point => {
|
||||
let [x, y] = *v.as_slice().first_chunk::<2>()?;
|
||||
Some(ParamValue::Point([x, y]))
|
||||
}
|
||||
ParamKind::Popup => {
|
||||
let index = v.first().copied()?;
|
||||
(0.0..=f64::from(u32::MAX)).contains(&index).then(|| ParamValue::Index(index.round() as u32))
|
||||
}
|
||||
ParamKind::Color => {
|
||||
let [a, r, g, b] = *v.as_slice().first_chunk::<4>()?;
|
||||
Some(ParamValue::Argb([a / 255.0, r / 255.0, g / 255.0, b / 255.0]))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The default stored in `pard` at byte 56: a float slider's `f64`, a fixed slider's or angle's
|
||||
/// 16.16 value, a colour's ARGB bytes, a popup's item index, a point's two 16.16 fractions of
|
||||
/// the layer size (Point Control 0.5, 0.5: the layer centre, also on a 100x100 layer;
|
||||
/// Gradient Ramp Start 0.5, 0 and End 0.5, 1), an integer slider's `i32` (Iterations 3, 412),
|
||||
/// a checkbox's `u32` (1 = on: Repeat Edge Pixels of Fast Box Blur and Gaussian Blur, read back
|
||||
/// on, 412, 417; 0 = off: Shadow Only 420, Bypass Linear Light Conversion 389); other types:
|
||||
/// `None`.
|
||||
///
|
||||
/// It is the default and not the current value: Gaussian Blur with Blurriness 40 still has 25
|
||||
/// here and a value record with 40 (After Effects itself reads a fresh Gaussian Blur back as 25).
|
||||
/// Exception: selecting a popup item also writes the selection to this slot. So a popup whose
|
||||
/// definition was borrowed from the project copy ([`EffectParam::borrowed_definition`]) has no
|
||||
/// reliable default here (the slot holds the copied instance's selection): `None`.
|
||||
pub fn pard_default(&self) -> Option<ParamValue> {
|
||||
match self.kind {
|
||||
ParamKind::Popup if self.borrowed_definition => None,
|
||||
ParamKind::FloatSlider => be_f64(self.pard, 56).map(ParamValue::Number),
|
||||
ParamKind::FixedSlider | ParamKind::Angle => be_i32(self.pard, 56).map(|v| ParamValue::Number(f64::from(v) / 65536.0)),
|
||||
ParamKind::IntSlider => be_i32(self.pard, 56).map(|v| ParamValue::Number(f64::from(v))),
|
||||
ParamKind::Checkbox => be_u32(self.pard, 56).map(|v| ParamValue::Bool(v != 0)),
|
||||
ParamKind::Popup => be_u32(self.pard, 56).map(ParamValue::Index),
|
||||
ParamKind::Point => {
|
||||
let p = [f64::from(be_i32(self.pard, 56)?) / 65536.0, f64::from(be_i32(self.pard, 60)?) / 65536.0];
|
||||
// A fresh instance stores fractions of the layer (0.5, 0.5); After Effects' save of
|
||||
// a project it opened stores percent (50, 50: the re-saves of read-back tests e1 and
|
||||
// e2, where Gradient Ramp's Start and End and every other point default came back
|
||||
// as 50 / 0 and 50 / 100). Point
|
||||
// defaults lie inside the layer, so a component beyond 1 tells percent.
|
||||
let percent = p.iter().any(|c| c.abs() > 1.0 + 1e-9);
|
||||
Some(ParamValue::Point(if percent { p.map(|c| c / 100.0) } else { p }))
|
||||
}
|
||||
ParamKind::Color => {
|
||||
let [a, r, g, b] = array::<4>(self.pard, 56)?.map(|c| f64::from(c) / 255.0);
|
||||
Some(ParamValue::Argb([a, r, g, b]))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the parameter is at its default: it has no value record (a record exists exactly
|
||||
/// when the value differs from the `pard` default; setting a value back to the default removes
|
||||
/// the record again), or the record equals the default. A record in the default state (`tdsb`
|
||||
/// 3) counts with its value ([`EffectParam::recorded_value`]). `None` when that cannot be
|
||||
/// decided (unknown parameter type, keyframes).
|
||||
pub fn is_default(&self) -> Option<bool> {
|
||||
match (self.stored, self.kind) {
|
||||
// A Layer Control always has its record, and a popup selection overwrites the default
|
||||
// in `pard`. Buttons and group markers hold no value at all.
|
||||
(_, ParamKind::Layer | ParamKind::Button | ParamKind::GroupStart | ParamKind::GroupEnd) => None,
|
||||
(None, _) => Some(true),
|
||||
(Some(_), ParamKind::Popup) => Some(false),
|
||||
(Some(_), _) => {
|
||||
let stored = self.recorded_value()?;
|
||||
// A checkbox's default is in `pard` too (on for Repeat Edge Pixels, 412).
|
||||
Some(self.pard_default().is_some_and(|d| d == stored))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A point control in pixels of a layer of this size (the stored point is a fraction of the
|
||||
/// layer size; the default is the layer centre). `None` for other parameter types.
|
||||
pub fn point_px(&self, layer_width: f64, layer_height: f64) -> Option<[f64; 2]> {
|
||||
match self.value()? {
|
||||
ParamValue::Point([x, y]) if self.kind == ParamKind::Point => Some([x * layer_width, y * layer_height]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// For a Layer Control: what the stored layer id means for the layer that owns the effect.
|
||||
/// `None` for other types and for the implicit first parameter of an effect.
|
||||
pub fn layer_ref(&self, owner_layer_id: u32) -> Option<LayerRef> {
|
||||
if self.kind != ParamKind::Layer || self.index == 0 {
|
||||
return None;
|
||||
}
|
||||
match self.stored_value()? {
|
||||
ParamValue::Layer(0) => Some(LayerRef::Nothing),
|
||||
ParamValue::Layer(id) if id == owner_layer_id => Some(LayerRef::This),
|
||||
ParamValue::Layer(id) => Some(LayerRef::Layer(id)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest valid value of a slider, from `pard`: a fixed slider's 16.16 at byte 128 (Tint
|
||||
/// Amount to Tint 100, Gradient Ramp Ramp Scatter 512 and Blend With Original 1.0, Drop Shadow
|
||||
/// Opacity 255), a float slider's `f32` at byte 108 (Blurriness 30000, Exposure 100, Exposure's
|
||||
/// Gamma Correction 10). The stored scale of a
|
||||
/// slider differs per parameter (Amount 37.5 % is stored 37.5, Blend 25 % is stored 0.25), so
|
||||
/// this is what tells a reader the scale. `None` for other types.
|
||||
pub fn valid_max(&self) -> Option<f64> {
|
||||
match self.kind {
|
||||
ParamKind::FixedSlider => be_i32(self.pard, 128).map(|v| f64::from(v) / 65536.0),
|
||||
ParamKind::FloatSlider => be_f32(self.pard, 108).map(f64::from),
|
||||
ParamKind::IntSlider => be_i32(self.pard, 128).map(f64::from),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest valid value of a float slider, the `f32` at byte 104 of `pard` (Exposure
|
||||
/// -100, Offset -2, Gamma Correction 0.1: 389). `None` for other types (a fixed slider's
|
||||
/// minimum is not decoded).
|
||||
pub fn valid_min(&self) -> Option<f64> {
|
||||
match self.kind {
|
||||
ParamKind::FloatSlider => be_f32(self.pard, 104).map(f64::from),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of a float slider's slider (what the control's drag covers, inside the valid
|
||||
/// range): the `f32` pair at bytes 112 and 116 of `pard` (Exposure -4..4, Offset -0.5..0.5,
|
||||
/// Gamma Correction 0.1..10: 389). Each value record repeats it as `tdum` / `tduM`. `None`
|
||||
/// for other types.
|
||||
pub fn slider_range(&self) -> Option<(f64, f64)> {
|
||||
match self.kind {
|
||||
ParamKind::FloatSlider => Some((f64::from(be_f32(self.pard, 112)?), f64::from(be_f32(self.pard, 116)?))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// For a popup: the number of items (`u16` at byte 60 of `pard`).
|
||||
pub fn popup_item_count(&self) -> Option<u16> {
|
||||
if self.kind != ParamKind::Popup {
|
||||
return None;
|
||||
}
|
||||
be_u16(self.pard, 60)
|
||||
}
|
||||
|
||||
/// For a popup: the selected item index (1-based): the stored selection, else the default.
|
||||
pub fn popup_selected_index(&self) -> Option<u32> {
|
||||
match self.value()? {
|
||||
ParamValue::Index(i) if self.kind == ParamKind::Popup => Some(i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// For a popup: the text of the selected item.
|
||||
pub fn popup_selected_item(&self) -> Option<&str> {
|
||||
let index = usize::try_from(self.popup_selected_index()?).ok()?.checked_sub(1)?;
|
||||
self.items.as_ref()?.get(index).map(String::as_str)
|
||||
}
|
||||
|
||||
/// The effective value: the value in the record when there is one, also in a record in the
|
||||
/// default state (`tdsb` 3, [`EffectParam::recorded_value`]), else the `pard` default (absent =
|
||||
/// default); a checkbox without a record is off.
|
||||
pub fn value(&self) -> Option<ParamValue> {
|
||||
self.recorded_value().or_else(|| self.pard_default()).or(match self.kind {
|
||||
ParamKind::Checkbox if self.stored.is_none() => Some(ParamValue::Bool(false)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The effects on the layer, in stack order (`ADBE Effect Parade`).
|
||||
pub fn effects(&self) -> Vec<Effect<'f, 'a>> {
|
||||
let Some(root) = self.properties() else { return Vec::new() };
|
||||
let Some(PropNode::Group(parade)) = root.get("ADBE Effect Parade") else { return Vec::new() };
|
||||
parade
|
||||
.entries()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e.node {
|
||||
PropNode::Other(chunk) if chunk.is_list(b"sspc") => Some(Effect { match_name: e.match_name, chunk }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tdmn(name: &str) -> Chunk<'static> {
|
||||
let mut b = name.as_bytes().to_vec();
|
||||
b.resize(40, 0);
|
||||
Chunk::data(*b"tdmn", b)
|
||||
}
|
||||
|
||||
fn pard() -> Chunk<'static> {
|
||||
Chunk::data(*b"pard", vec![0u8; 48])
|
||||
}
|
||||
|
||||
fn tdbs() -> Chunk<'static> {
|
||||
Chunk::list(*b"tdbs", Vec::new())
|
||||
}
|
||||
|
||||
/// An effect instance whose `parT` names `defs` and whose `tdgp` stores `stored` (in order).
|
||||
fn instance(defs: &[String], stored: &[(String, Chunk<'static>)]) -> Chunk<'static> {
|
||||
let part = defs.iter().flat_map(|n| [tdmn(n), pard()]).collect();
|
||||
let values = stored.iter().flat_map(|(n, c)| [tdmn(n), c.clone()]).collect();
|
||||
Chunk::list(*b"sspc", vec![Chunk::list(*b"parT", part), Chunk::list(*b"tdgp", values)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_takes_the_first_stored_entry_of_its_name() {
|
||||
let names: Vec<String> = ["A", "B", "C"].map(String::from).to_vec();
|
||||
// `A` is stored twice (the first wins), `B` names a group (no stored value), `C` is absent.
|
||||
let stored = vec![
|
||||
("A".to_string(), tdbs()),
|
||||
("B".to_string(), Chunk::list(*b"tdgp", Vec::new())),
|
||||
("A".to_string(), Chunk::list(*b"tdbs", vec![Chunk::data(*b"cdat", vec![0u8; 8])])),
|
||||
];
|
||||
let chunk = instance(&names, &stored);
|
||||
let fx = Effect { match_name: "X".into(), chunk: &chunk };
|
||||
let params = fx.params();
|
||||
assert_eq!(params.iter().map(|p| p.match_name.as_str()).collect::<Vec<_>>(), ["A", "B", "C"]);
|
||||
let first = params.first().and_then(|p| p.stored).expect("A stored");
|
||||
assert!(first.chunk.children().is_empty(), "the first A (the second has a cdat)");
|
||||
assert!(params.get(1).is_some_and(|p| p.stored.is_none()), "a group of that name is no stored value");
|
||||
assert!(params.get(2).is_some_and(|p| p.stored.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_parameters_are_read_in_linear_time() {
|
||||
// 100 000 parameters with 100 000 stored values: a lookup per parameter that scans the
|
||||
// group (as before) is 1e10 entry builds; one index is instant.
|
||||
let n = 100_000;
|
||||
let names: Vec<String> = (0..n).map(|i| format!("P{i}")).collect();
|
||||
let stored: Vec<(String, Chunk<'static>)> = names.iter().map(|m| (m.clone(), tdbs())).collect();
|
||||
let chunk = instance(&names, &stored);
|
||||
let fx = Effect { match_name: "X".into(), chunk: &chunk };
|
||||
let params = fx.params();
|
||||
assert_eq!(params.len(), n);
|
||||
assert!(params.iter().all(|p| p.stored.is_some()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_project_definitions_are_indexed_once() {
|
||||
// 50 000 definitions, each twice (the first copy wins), then 1000 instances without
|
||||
// their own definitions looked up through one index.
|
||||
let n = 50_000;
|
||||
let mut defs = Vec::new();
|
||||
for round in 0..2 {
|
||||
for i in 0..n {
|
||||
let part = Chunk::list(*b"parT", vec![tdmn(&format!("R{round}")), pard()]);
|
||||
defs.push(Chunk::list(*b"EfDf", vec![tdmn(&format!("FX{i}")), Chunk::list(*b"sspc", vec![part])]));
|
||||
}
|
||||
}
|
||||
let efdg = Chunk::list(*b"EfdG", defs);
|
||||
let fold = Chunk::list(*b"Fold", Vec::new());
|
||||
let project = Project { fold: &fold, effect_defs: Some(&efdg) };
|
||||
let all = project.effect_definitions();
|
||||
assert_eq!(all.len(), n);
|
||||
let index = project.effect_definition_index();
|
||||
let bare = Chunk::list(*b"sspc", vec![Chunk::list(*b"parT", Vec::new())]);
|
||||
for i in (0..n).step_by(50) {
|
||||
let fx = Effect { match_name: format!("FX{i}"), chunk: &bare };
|
||||
assert_eq!(index.source(&fx), DefinitionSource::Project);
|
||||
let params = index.params(&fx);
|
||||
assert_eq!(params.iter().map(|p| p.match_name.as_str()).collect::<Vec<_>>(), ["R0"], "the first copy's definitions");
|
||||
assert!(params.iter().all(|p| p.borrowed_definition));
|
||||
}
|
||||
let unknown = Effect { match_name: "nope".into(), chunk: &bare };
|
||||
assert_eq!(index.source(&unknown), DefinitionSource::Missing);
|
||||
assert!(index.params(&unknown).is_empty());
|
||||
assert_eq!(project.definition_source(&unknown), DefinitionSource::Missing);
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
//! Errors of the container reader and writer.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Why a file could not be read or written.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AepError {
|
||||
/// The input is shorter than the 12-byte `RIFX` header, or does not start with `RIFX`.
|
||||
NotRifx,
|
||||
/// The form type after the declared size is not `Egg!`.
|
||||
BadFormType([u8; 4]),
|
||||
/// The declared container size runs past the end of the input.
|
||||
Truncated { declared: u64, available: u64 },
|
||||
/// A chunk declares more body bytes than remain in its parent (`offset` is the chunk header).
|
||||
ChunkTooLarge { offset: usize, size: u64, available: u64 },
|
||||
/// The chunk structure is not well formed at `offset` (what is wrong is in `what`).
|
||||
Malformed { offset: usize, what: &'static str },
|
||||
/// Nesting is deeper than the allowed maximum.
|
||||
TooDeep,
|
||||
/// More chunks than the allowed maximum.
|
||||
TooManyChunks,
|
||||
/// A chunk or the whole file would not fit the 32-bit size fields when writing.
|
||||
TooLarge,
|
||||
/// An `.aepx` is not well-formed XML of the subset After Effects writes, at byte `offset`
|
||||
/// (what is wrong is in `what`).
|
||||
Xml { offset: usize, what: &'static str },
|
||||
}
|
||||
|
||||
impl AepError {
|
||||
/// Structural problems of the input that a lenient caller may repair by keeping a body opaque;
|
||||
/// limits (`TooDeep`, `TooManyChunks`) are never repaired.
|
||||
pub(crate) fn is_structural(&self) -> bool {
|
||||
matches!(self, Self::ChunkTooLarge { .. } | Self::Malformed { .. } | Self::Truncated { .. })
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for AepError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NotRifx => write!(f, "not an After Effects project: no RIFX header"),
|
||||
Self::BadFormType(t) => write!(f, "RIFX form type {:?} is not \"Egg!\"", String::from_utf8_lossy(t)),
|
||||
Self::Truncated { declared, available } => {
|
||||
write!(f, "truncated file: the container declares {declared} bytes, {available} are available")
|
||||
}
|
||||
Self::ChunkTooLarge { offset, size, available } => {
|
||||
write!(f, "chunk at offset {offset} declares {size} bytes, only {available} remain")
|
||||
}
|
||||
Self::Malformed { offset, what } => write!(f, "malformed chunk structure at offset {offset}: {what}"),
|
||||
Self::TooDeep => write!(f, "chunks are nested too deeply"),
|
||||
Self::TooManyChunks => write!(f, "too many chunks"),
|
||||
Self::TooLarge => write!(f, "chunk too large for the 32-bit size field"),
|
||||
Self::Xml { offset, what } => write!(f, "not a readable After Effects XML project (.aepx): {what} at byte {offset}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AepError {}
|
||||
@@ -1,332 +0,0 @@
|
||||
//! Item ids and labels, footage items (solids and files), precomp linkage, and the name and size
|
||||
//! of a layer's source.
|
||||
|
||||
use crate::container::bytes::{be_f32, be_f64, be_u32, cstr, le_u32, text};
|
||||
use crate::container::header::Rational;
|
||||
use crate::container::typed::{Item, ItemKind, Layer, Project};
|
||||
|
||||
/// The footage data of an item (`LIST Pin ` with `sspc`, `opti` and, for files, `Als2/alas`).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Footage {
|
||||
/// The 4-character file type tag at byte 22 of `sspc` (`Soli` for a solid, `png!` for a png).
|
||||
pub file_type: String,
|
||||
/// The width in pixels (`u32` at byte 30 of `sspc`).
|
||||
pub width: u32,
|
||||
/// The height in pixels (`u32` at byte 34 of `sspc`).
|
||||
pub height: u32,
|
||||
/// The display name stored in `opti` (the item's own `Utf8` name is empty for footage): at byte
|
||||
/// 26 for a solid and at byte 58 for a file.
|
||||
pub name: Option<String>,
|
||||
/// True for a solid (tag `Soli` at the start of `opti`).
|
||||
pub is_solid: bool,
|
||||
/// The colour of a solid as ARGB floats 0..1 (`opti` bytes 10, 14, 18, 22); a red solid is
|
||||
/// `[1, 1, 0, 0]`.
|
||||
pub solid_argb: Option<[f32; 4]>,
|
||||
/// The file path from the alias JSON (`Als2/alas`, key `fullpath`); none for solids. For an
|
||||
/// image sequence it is the sequence **folder**.
|
||||
pub path: Option<String>,
|
||||
/// The duration in seconds as stored (`sspc` `u32` at byte 38 over `u32` at byte 42; unreduced):
|
||||
/// 0/1 for stills, 48000/48000 for the 1 s WAV (the sample rate is the denominator), 3/30 for
|
||||
/// the three-frame image sequence (the frame rate is the denominator).
|
||||
pub duration: Option<Rational>,
|
||||
/// The native frame rate (`sspc` `u32` at byte 56): 30 for the image sequence, 0 for stills,
|
||||
/// audio and solids (also 0 when the byte is missing).
|
||||
pub native_frame_rate: u32,
|
||||
/// The bits per pixel (`sspc` `u32` at byte 60): 32 for an RGBA still, 24 for an RGB sequence,
|
||||
/// 0 for solids and audio.
|
||||
pub bits_per_pixel: u32,
|
||||
/// The size in bytes of the source file(s) (`sspc` `u32` at byte 208): 149 for the png, 96044
|
||||
/// for the WAV (44 + 48000 x 2), 504 for three 168-byte png files.
|
||||
pub file_size: u32,
|
||||
/// The audio sample rate (`sspc` `f64` at byte 160, 48000.0 for the WAV and for an mp4 with
|
||||
/// 48 kHz sound); `None` for footage without audio.
|
||||
pub audio_sample_rate: Option<f64>,
|
||||
/// True when the alias points at a folder (`"target_is_folder":true`): an image sequence is ONE
|
||||
/// item whose alias is its folder and whose `opti` holds the first file name.
|
||||
pub is_sequence: bool,
|
||||
}
|
||||
|
||||
impl Footage {
|
||||
/// The number of frames of an image sequence (`duration * native_frame_rate`: 3/30 s at 30 fps is
|
||||
/// 3); `None` for anything else.
|
||||
pub fn sequence_frame_count(&self) -> Option<u32> {
|
||||
if !self.is_sequence {
|
||||
return None;
|
||||
}
|
||||
let d = self.duration?;
|
||||
let frames = i128::from(d.num).checked_mul(i128::from(self.native_frame_rate))?;
|
||||
let den = i128::from(d.den);
|
||||
if den <= 0 || frames % den != 0 {
|
||||
return None;
|
||||
}
|
||||
u32::try_from(frames / den).ok()
|
||||
}
|
||||
|
||||
/// The solid's colour as fractions R, G, B.
|
||||
pub fn solid_rgb(&self) -> Option<[f32; 3]> {
|
||||
let [_, r, g, b] = self.solid_argb?;
|
||||
Some([r, g, b])
|
||||
}
|
||||
}
|
||||
|
||||
/// The boolean value of `"key"` in a flat JSON object (`true` / `false`); `None` when missing.
|
||||
pub(crate) fn json_bool(json: &[u8], key: &str) -> Option<bool> {
|
||||
let needle = format!("\"{key}\":");
|
||||
let needle = needle.as_bytes();
|
||||
let at = json.windows(needle.len()).position(|w| w == needle)?;
|
||||
let rest = json.get(at.checked_add(needle.len())?..)?;
|
||||
if rest.starts_with(b"true") {
|
||||
Some(true)
|
||||
} else if rest.starts_with(b"false") {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The string value of `"key"` in a flat JSON object, with the standard escapes decoded.
|
||||
/// Returns `None` when the key is missing or the value is not a string. The key is the first
|
||||
/// occurrence of `"key"` that is followed by `:` (the same text as a value is skipped).
|
||||
pub(crate) fn json_string(json: &[u8], key: &str) -> Option<String> {
|
||||
let needle = format!("\"{key}\"");
|
||||
let needle = needle.as_bytes();
|
||||
let mut from = 0usize;
|
||||
loop {
|
||||
let at = from.checked_add(json.get(from..)?.windows(needle.len()).position(|w| w == needle)?)?;
|
||||
let after = at.checked_add(needle.len())?;
|
||||
if let Some(v) = json_string_at(json, after) {
|
||||
return Some(v);
|
||||
}
|
||||
from = at.checked_add(1)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The string value right after a key ending at `i` (`: "…"`), or `None` when none follows.
|
||||
fn json_string_at(json: &[u8], mut i: usize) -> Option<String> {
|
||||
let skip_ws = |i: &mut usize| {
|
||||
while json.get(*i).is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
*i = i.saturating_add(1);
|
||||
}
|
||||
};
|
||||
skip_ws(&mut i);
|
||||
if json.get(i) != Some(&b':') {
|
||||
return None;
|
||||
}
|
||||
i = i.saturating_add(1);
|
||||
skip_ws(&mut i);
|
||||
if json.get(i) != Some(&b'"') {
|
||||
return None;
|
||||
}
|
||||
i = i.saturating_add(1);
|
||||
let mut out: Vec<u8> = Vec::new();
|
||||
loop {
|
||||
let c = *json.get(i)?;
|
||||
i = i.saturating_add(1);
|
||||
match c {
|
||||
b'"' => return Some(text(&out)),
|
||||
b'\\' => {
|
||||
let e = *json.get(i)?;
|
||||
i = i.saturating_add(1);
|
||||
match e {
|
||||
b'n' => out.push(b'\n'),
|
||||
b't' => out.push(b'\t'),
|
||||
b'r' => out.push(b'\r'),
|
||||
b'b' => out.push(8),
|
||||
b'f' => out.push(12),
|
||||
b'u' => {
|
||||
let hex4 = |at: usize| {
|
||||
json.get(at..at.checked_add(4)?).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u32::from_str_radix(h, 16).ok())
|
||||
};
|
||||
let mut code = hex4(i)?;
|
||||
i = i.saturating_add(4);
|
||||
// A character outside the BMP is a high surrogate and a `\u` low surrogate.
|
||||
if (0xd800..0xdc00).contains(&code)
|
||||
&& json.get(i..i.saturating_add(2)) == Some(b"\\u")
|
||||
&& let Some(lo) = hex4(i.saturating_add(2)).filter(|lo| (0xdc00..0xe000).contains(lo))
|
||||
{
|
||||
code = 0x10000 + ((code - 0xd800) << 10) + (lo - 0xdc00);
|
||||
i = i.saturating_add(6);
|
||||
}
|
||||
let ch = char::from_u32(code).unwrap_or('\u{fffd}');
|
||||
let mut buf = [0u8; 4];
|
||||
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The numbering of an image sequence item (353, 603).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SequenceInfo {
|
||||
/// The file name before the frame number (`seq_`, `shot_`): the first `Utf8` after the alias.
|
||||
pub prefix: String,
|
||||
/// The file name after the frame number (`.png`, `.exr`): the second `Utf8` after the alias.
|
||||
pub suffix: String,
|
||||
/// The first and last frame number (`sspc` `u32` at 172 and 176: 1 and 3 in 353, 101 and 103
|
||||
/// in 603).
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
/// The digits of the frame number (`sspc` `u32` at 180: 3 for `seq_001`, 4 for `shot_0101`).
|
||||
pub digits: u32,
|
||||
}
|
||||
|
||||
impl SequenceInfo {
|
||||
/// The file name of frame `n` (`shot_0101.exr`).
|
||||
pub fn file_name(&self, n: u32) -> String {
|
||||
let width = usize::try_from(self.digits.min(16)).unwrap_or(0);
|
||||
format!("{}{n:0width$}{}", self.prefix, self.suffix)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Item<'f, 'a> {
|
||||
/// The numbering of an image sequence (an item whose alias is a folder); `None` for anything
|
||||
/// else.
|
||||
pub fn sequence_info(&self) -> Option<SequenceInfo> {
|
||||
let f = self.footage()?;
|
||||
if !f.is_sequence {
|
||||
return None;
|
||||
}
|
||||
let pin = self.chunk.child_list(b"Pin ")?;
|
||||
let sspc = pin.child(b"sspc")?.bytes()?;
|
||||
let kids = pin.children();
|
||||
let after = kids.iter().position(|c| c.is_list(b"Als2"))?;
|
||||
let mut names = kids.iter().skip(after + 1).take_while(|c| !c.is(b"opti")).filter(|c| c.is(b"Utf8")).filter_map(|c| c.bytes()).map(text);
|
||||
let prefix = names.next()?;
|
||||
let suffix = names.next()?;
|
||||
Some(SequenceInfo { prefix, suffix, start: be_u32(sspc, 172)?, end: be_u32(sspc, 176)?, digits: be_u32(sspc, 180)? })
|
||||
}
|
||||
|
||||
/// The rate a clip is conformed to (Interpret Footage ▸ Conform to frame rate; `sspc` `u32` at
|
||||
/// byte 146): 30 for the 25 fps mp4 conformed to 30 (645), `None` when not conformed (0 in 644,
|
||||
/// 606) or for an item without footage data. The effective rate is then also at byte 150 while
|
||||
/// the stored duration (bytes 38 / 42) and byte 56 stay native. A conformed image sequence
|
||||
/// stores the new rate in bytes 42, 56 and 150 instead and keeps 0 here (615).
|
||||
pub fn conform_frame_rate(&self) -> Option<u32> {
|
||||
let sspc = self.chunk.child_list(b"Pin ")?.child(b"sspc")?.bytes()?;
|
||||
be_u32(sspc, 146).filter(|r| *r > 0)
|
||||
}
|
||||
|
||||
/// The item id: the big-endian `u32` at byte 16 of `idta` (what a layer's source id refers to).
|
||||
pub fn id(&self) -> Option<u32> {
|
||||
be_u32(self.chunk.child(b"idta")?.bytes()?, 16)
|
||||
}
|
||||
|
||||
/// The label colour index, byte 58 of `idta` (15 for a composition made by precomposing).
|
||||
pub fn label(&self) -> Option<u8> {
|
||||
self.chunk.child(b"idta")?.bytes()?.get(58).copied()
|
||||
}
|
||||
|
||||
/// The ids of the compositions this item uses as precomp layers: the little-endian `u32` of
|
||||
/// each `idpi` chunk.
|
||||
pub fn used_item_ids(&self) -> Vec<u32> {
|
||||
self.chunk.children().iter().filter(|c| c.is(b"idpi")).filter_map(|c| le_u32(c.bytes()?, 0)).collect()
|
||||
}
|
||||
|
||||
/// The footage data of a footage item.
|
||||
pub fn footage(&self) -> Option<Footage> {
|
||||
if self.kind()? != ItemKind::Footage {
|
||||
return None;
|
||||
}
|
||||
let pin = self.chunk.child_list(b"Pin ")?;
|
||||
let sspc = pin.child(b"sspc")?.bytes()?;
|
||||
let opti = pin.child(b"opti")?.bytes()?;
|
||||
let is_solid = opti.get(..4) == Some(&b"Soli"[..]);
|
||||
let alias = pin.child_list(b"Als2").and_then(|als| als.child(b"alas")).and_then(|alas| alas.bytes());
|
||||
let path = alias.and_then(|json| json_string(json, "fullpath"));
|
||||
let is_sequence = alias.and_then(|json| json_bool(json, "target_is_folder")).unwrap_or(false);
|
||||
let solid_argb = if is_solid { Some([be_f32(opti, 10)?, be_f32(opti, 14)?, be_f32(opti, 18)?, be_f32(opti, 22)?]) } else { None };
|
||||
Some(Footage {
|
||||
file_type: cstr(sspc, 22, 4)?,
|
||||
width: be_u32(sspc, 30)?,
|
||||
height: be_u32(sspc, 34)?,
|
||||
name: cstr(opti, if is_solid { 26 } else { 58 }, 256).filter(|n| !n.is_empty()),
|
||||
is_solid,
|
||||
solid_argb,
|
||||
path,
|
||||
duration: be_u32(sspc, 38).zip(be_u32(sspc, 42)).map(|(num, den)| Rational { num: i64::from(num), den: i64::from(den) }),
|
||||
native_frame_rate: be_u32(sspc, 56).unwrap_or(0),
|
||||
bits_per_pixel: be_u32(sspc, 60).unwrap_or(0),
|
||||
file_size: be_u32(sspc, 208).unwrap_or(0),
|
||||
audio_sample_rate: be_f64(sspc, 160).filter(|r| r.is_finite() && *r > 0.0),
|
||||
is_sequence,
|
||||
})
|
||||
}
|
||||
|
||||
/// The name this item shows in the project: the item name, or for footage the name stored in
|
||||
/// `opti`.
|
||||
pub fn display_name(&self) -> Option<String> {
|
||||
self.name().or_else(|| self.footage().and_then(|f| f.name))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Project<'f, 'a> {
|
||||
/// The item with this id (`idta` byte 16), searching every item including those in folders.
|
||||
pub fn item_by_id(&self, id: u32) -> Option<Item<'f, 'a>> {
|
||||
self.all_items().into_iter().find(|i| i.id() == Some(id))
|
||||
}
|
||||
|
||||
/// The item a layer is made from (its source id), e.g. the solid, the footage or the precomp.
|
||||
pub fn layer_source(&self, layer: &Layer<'f, 'a>) -> Option<Item<'f, 'a>> {
|
||||
self.item_by_id(layer.header()?.source_id?)
|
||||
}
|
||||
|
||||
/// The name a layer shows: its own name, or its source's name when it has none.
|
||||
pub fn layer_display_name(&self, layer: &Layer<'f, 'a>) -> Option<String> {
|
||||
layer.name().or_else(|| self.layer_source(layer)?.display_name())
|
||||
}
|
||||
|
||||
/// The pixel size of a layer's source: a footage item's width and height, or a precomp's
|
||||
/// composition size.
|
||||
pub fn layer_source_size(&self, layer: &Layer<'f, 'a>) -> Option<(u32, u32)> {
|
||||
let source = self.layer_source(layer)?;
|
||||
match source.kind()? {
|
||||
ItemKind::Footage => source.footage().map(|f| (f.width, f.height)),
|
||||
ItemKind::Composition => source.comp()?.header().map(|h| (u32::from(h.width), u32::from(h.height))),
|
||||
ItemKind::Folder | ItemKind::Other(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::json_string;
|
||||
|
||||
#[test]
|
||||
fn reads_a_string_with_escapes() {
|
||||
let json = br#"{"a":1,"fullpath":"C:\\dir\\f\u00e9.png","b":"x"}"#;
|
||||
assert_eq!(json_string(json, "fullpath").as_deref(), Some(r"C:\dir\fé.png"));
|
||||
assert_eq!(json_string(json, "b").as_deref(), Some("x"));
|
||||
assert_eq!(json_string(json, "missing"), None);
|
||||
assert_eq!(json_string(br#"{"a" : "spaced"}"#, "a").as_deref(), Some("spaced"));
|
||||
// The key's text as an earlier value is not the key.
|
||||
assert_eq!(json_string(br#"{"a":"fullpath","fullpath":"x"}"#, "fullpath").as_deref(), Some("x"));
|
||||
// A surrogate pair is one character; a lone half stays U+FFFD.
|
||||
assert_eq!(json_string(br#"{"a":"x\ud83d\ude00y"}"#, "a").as_deref(), Some("x😀y"));
|
||||
assert_eq!(json_string(br#"{"a":"\ud83dz"}"#, "a").as_deref(), Some("\u{fffd}z"));
|
||||
assert_eq!(json_string(br#"{"a":"\ude00"}"#, "a").as_deref(), Some("\u{fffd}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_json_never_panics() {
|
||||
for json in [
|
||||
&br#"{"fullpath":"#[..],
|
||||
br#"{"fullpath":"abc"#,
|
||||
br#"{"fullpath":"ab\"#,
|
||||
br#"{"fullpath":"\u12"}"#,
|
||||
br#"{"fullpath":"\uzzzz"}"#,
|
||||
br#"{"fullpath":5}"#,
|
||||
br#"{"fullpath"}"#,
|
||||
b"\"fullpath\"",
|
||||
b"",
|
||||
b"\"",
|
||||
br#"{"fullpath":"\ud800"}"#,
|
||||
] {
|
||||
let _ = json_string(json, "fullpath");
|
||||
}
|
||||
assert_eq!(json_string(br#"{"fullpath":"\ud800"}"#, "fullpath").as_deref(), Some("\u{fffd}"));
|
||||
}
|
||||
}
|
||||
@@ -1,549 +0,0 @@
|
||||
//! The layer header (`ldta`) and the composition header (`cdta`, `PRin`).
|
||||
//!
|
||||
//! Every field here has a verified layout: the decoded value equals the value the generated corpus
|
||||
//! was made with (see `docs/aep-format.md`, sections 4 and 5, for the evidence per field). Fields that
|
||||
//! the corpus does not decide are not decoded; the raw bytes stay reachable through the chunk.
|
||||
|
||||
use crate::container::bytes::{array, be_i32, be_u16, be_u32, cstr, text, until_nul};
|
||||
use crate::container::typed::{Comp, Item, Layer, TimeBase, utf8_child};
|
||||
|
||||
/// An exact fraction. Used for times (`seconds = num / den`) and for the pixel aspect ratio. The
|
||||
/// fields hold the stored values unreduced; [`Rational::reduced`] normalises.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Rational {
|
||||
pub num: i64,
|
||||
pub den: i64,
|
||||
}
|
||||
|
||||
impl Rational {
|
||||
/// A fraction with a positive denominator, reduced; `None` for a zero denominator.
|
||||
pub fn new(num: i64, den: i64) -> Option<Self> {
|
||||
Self { num, den }.reduced()
|
||||
}
|
||||
|
||||
/// The value as `f64`, `None` for a zero denominator.
|
||||
pub fn to_f64(&self) -> Option<f64> {
|
||||
(self.den != 0).then(|| self.num as f64 / self.den as f64)
|
||||
}
|
||||
|
||||
/// The same value in lowest terms with a positive denominator, `None` for a zero denominator.
|
||||
pub fn reduced(&self) -> Option<Self> {
|
||||
if self.den == 0 {
|
||||
return None;
|
||||
}
|
||||
let (mut a, mut b) = (i128::from(self.num).unsigned_abs(), i128::from(self.den).unsigned_abs());
|
||||
let (mut x, mut y) = (a, b);
|
||||
while y != 0 {
|
||||
(x, y) = (y, x % y);
|
||||
}
|
||||
if x == 0 {
|
||||
x = 1;
|
||||
}
|
||||
a /= x;
|
||||
b /= x;
|
||||
let negative = (self.num < 0) != (self.den < 0);
|
||||
let num = i64::try_from(a).ok()?;
|
||||
let den = i64::try_from(b).ok()?;
|
||||
Some(Self { num: if negative { num.checked_neg()? } else { num }, den })
|
||||
}
|
||||
|
||||
/// `self + other * factor`, exact, `None` on a zero denominator or overflow.
|
||||
fn plus_scaled(&self, other: &Rational, factor: &Rational) -> Option<Rational> {
|
||||
if self.den == 0 || other.den == 0 || factor.den == 0 {
|
||||
return None;
|
||||
}
|
||||
// other * factor = (other.num * factor.num) / (other.den * factor.den)
|
||||
let scaled_num = i128::from(other.num).checked_mul(i128::from(factor.num))?;
|
||||
let scaled_den = i128::from(other.den).checked_mul(i128::from(factor.den))?;
|
||||
let den = i128::from(self.den).checked_mul(scaled_den)?;
|
||||
let num = i128::from(self.num).checked_mul(scaled_den)?.checked_add(scaled_num.checked_mul(i128::from(self.den))?)?;
|
||||
Rational { num: i64::try_from(num).ok()?, den: i64::try_from(den).ok()? }.reduced()
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer quality switch, `ldta` byte 5.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Quality {
|
||||
/// `1`
|
||||
Draft,
|
||||
/// `2`
|
||||
Best,
|
||||
/// Any other value (`0` on cameras and lights; wireframe was not sampled).
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
/// The blend mode, `ldta` byte 99. Six modes were sampled; any other mode is kept as its raw code.
|
||||
/// The codes 2, 4, 5, 6 and 7 coincide with the numbers of the After Effects plug-in transfer
|
||||
/// modes; Difference is 26.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BlendMode {
|
||||
/// `2`
|
||||
Normal,
|
||||
/// `4`
|
||||
Add,
|
||||
/// `5`
|
||||
Multiply,
|
||||
/// `6`
|
||||
Screen,
|
||||
/// `7`
|
||||
Overlay,
|
||||
/// `26`
|
||||
Difference,
|
||||
/// Any other value (not sampled; `0` on cameras and lights).
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl BlendMode {
|
||||
/// The mode for a code.
|
||||
pub fn from_code(code: u8) -> Self {
|
||||
match code {
|
||||
2 => Self::Normal,
|
||||
4 => Self::Add,
|
||||
5 => Self::Multiply,
|
||||
6 => Self::Screen,
|
||||
7 => Self::Overlay,
|
||||
26 => Self::Difference,
|
||||
other => Self::Other(other),
|
||||
}
|
||||
}
|
||||
|
||||
/// The code as stored.
|
||||
pub fn code(&self) -> u8 {
|
||||
match self {
|
||||
Self::Normal => 2,
|
||||
Self::Add => 4,
|
||||
Self::Multiply => 5,
|
||||
Self::Screen => 6,
|
||||
Self::Overlay => 7,
|
||||
Self::Difference => 26,
|
||||
Self::Other(code) => *code,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The light type, `ldta` `u32` at byte 136 of a light layer (0 on every other layer).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LightType {
|
||||
/// `0` (701)
|
||||
Parallel,
|
||||
/// `1`
|
||||
Spot,
|
||||
/// `2`
|
||||
Point,
|
||||
/// `3` (702; a light created as an environment light by script without the Advanced 3D
|
||||
/// renderer is stored as an ambient light too, 704)
|
||||
Ambient,
|
||||
/// Any other value (an environment light was not sampled).
|
||||
Other(u32),
|
||||
}
|
||||
|
||||
/// The layer type, `ldta` `u32` at byte 128.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LayerType {
|
||||
/// `0`: solid, footage, precomp or null object (an AV layer).
|
||||
Av,
|
||||
/// `1`
|
||||
Light,
|
||||
/// `2`
|
||||
Camera,
|
||||
/// `3`
|
||||
Text,
|
||||
/// `4`
|
||||
Shape,
|
||||
/// Any other value.
|
||||
Other(u32),
|
||||
}
|
||||
|
||||
/// The decoded fields of a layer's `ldta` chunk (164 bytes; the fields below need the first 140).
|
||||
///
|
||||
/// Times are stored as a numerator and a denominator (the denominator is the composition's
|
||||
/// timescale, 1 in a precomp layer). The in and out points are stored **relative to the start**:
|
||||
/// the absolute in point is `start + in * stretch`, see [`LayerHeader::in_point`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LayerHeader {
|
||||
/// The layer id (unique in the project); parent links use it.
|
||||
pub id: u32,
|
||||
pub quality: Quality,
|
||||
/// The numerator of the time stretch (signed `i32` at byte 8). The stretch is the exact ratio
|
||||
/// `stretch / stretch_den`: `1/1` = 100 %, `2/1` = 200 %, `1/2` = 50 %, `3/2` = 150 %, `-1/1` =
|
||||
/// -100 % (a time-reversed layer, 981), `-1/2` = -50 % (983), see
|
||||
/// [`LayerHeader::stretch_ratio`].
|
||||
pub stretch: i32,
|
||||
/// The denominator of the time stretch (`u32` at byte 108; 1 in every file before 50 % was
|
||||
/// sampled).
|
||||
pub stretch_den: u32,
|
||||
/// The layer start time, as stored.
|
||||
pub start: Rational,
|
||||
/// The in point relative to the start, as stored.
|
||||
pub in_relative: Rational,
|
||||
/// The out point relative to the start, as stored.
|
||||
pub out_relative: Rational,
|
||||
/// Bytes 37, 38 and 39 of `ldta`: the switch bits (see the `is_*` methods).
|
||||
pub flag_bytes: [u8; 3],
|
||||
/// The id of the source item (`ldta` byte 40), `None` for the values `0` (shape, text, camera)
|
||||
/// and `0xffff_ffff` (light).
|
||||
pub source_id: Option<u32>,
|
||||
/// The label colour index (`ldta` byte 61: 1 red, 5, 8 blue, ...).
|
||||
pub label: u8,
|
||||
/// The copy of the layer name at byte 64 (31 characters at most; the layer's `Utf8` child holds
|
||||
/// the full name).
|
||||
pub name_copy: String,
|
||||
pub blend_mode: BlendMode,
|
||||
pub layer_type: LayerType,
|
||||
/// The id of the parent layer, `None` when there is none.
|
||||
pub parent_id: Option<u32>,
|
||||
/// The `u32` at byte 136 (the light type of a light layer, 0 elsewhere), see
|
||||
/// [`LayerHeader::light_type`].
|
||||
pub light_type_code: u32,
|
||||
}
|
||||
|
||||
impl LayerHeader {
|
||||
/// Decodes an `ldta` body; `None` when it is shorter than 140 bytes.
|
||||
pub fn parse(ldta: &[u8]) -> Option<Self> {
|
||||
let time = |at: usize| Some(Rational { num: i64::from(be_i32(ldta, at)?), den: i64::from(be_u32(ldta, at.checked_add(4)?)?) });
|
||||
let source = be_u32(ldta, 40)?;
|
||||
let parent = be_u32(ldta, 132)?;
|
||||
Some(Self {
|
||||
id: be_u32(ldta, 0)?,
|
||||
quality: match *ldta.get(5)? {
|
||||
1 => Quality::Draft,
|
||||
2 => Quality::Best,
|
||||
other => Quality::Other(other),
|
||||
},
|
||||
stretch: be_i32(ldta, 8)?,
|
||||
stretch_den: be_u32(ldta, 108)?,
|
||||
start: time(12)?,
|
||||
in_relative: time(20)?,
|
||||
out_relative: time(28)?,
|
||||
flag_bytes: array::<3>(ldta, 37)?,
|
||||
source_id: (source != 0 && source != u32::MAX).then_some(source),
|
||||
label: *ldta.get(61)?,
|
||||
name_copy: text(until_nul(ldta.get(64..96)?)),
|
||||
blend_mode: BlendMode::from_code(*ldta.get(99)?),
|
||||
layer_type: match be_u32(ldta, 128)? {
|
||||
0 => LayerType::Av,
|
||||
1 => LayerType::Light,
|
||||
2 => LayerType::Camera,
|
||||
3 => LayerType::Text,
|
||||
4 => LayerType::Shape,
|
||||
other => LayerType::Other(other),
|
||||
},
|
||||
parent_id: (parent != 0).then_some(parent),
|
||||
light_type_code: be_u32(ldta, 136)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn flag(&self, byte: usize, mask: u8) -> bool {
|
||||
self.flag_bytes.get(byte).is_some_and(|b| b & mask != 0)
|
||||
}
|
||||
|
||||
/// Byte 37 bit `0x01`: the layer has a name set by the user (clear on a default-named camera or
|
||||
/// light and on a precomp layer, whose name is the source's).
|
||||
pub fn name_is_user_set(&self) -> bool {
|
||||
self.flag(0, 0x01)
|
||||
}
|
||||
|
||||
/// Byte 37 bit `0x02`: guide layer.
|
||||
pub fn is_guide(&self) -> bool {
|
||||
self.flag(0, 0x02)
|
||||
}
|
||||
|
||||
/// Byte 38 bit `0x02`: adjustment layer.
|
||||
pub fn is_adjustment(&self) -> bool {
|
||||
self.flag(1, 0x02)
|
||||
}
|
||||
|
||||
/// Byte 38 bit `0x04`: the 3D layer switch.
|
||||
pub fn is_three_d(&self) -> bool {
|
||||
self.flag(1, 0x04)
|
||||
}
|
||||
|
||||
/// Byte 38 bit `0x40`: the layer orients itself towards its point of interest. Set on two-node
|
||||
/// cameras (byte 38 is `0x44`) and on all lights, clear on a one-node camera (`0x04`).
|
||||
pub fn is_auto_oriented(&self) -> bool {
|
||||
self.flag(1, 0x40)
|
||||
}
|
||||
|
||||
/// Byte 38 bit `0x08`: solo.
|
||||
pub fn is_solo(&self) -> bool {
|
||||
self.flag(1, 0x08)
|
||||
}
|
||||
|
||||
/// Byte 38 bit `0x80`: the layer was created as a null object.
|
||||
pub fn is_null_object(&self) -> bool {
|
||||
self.flag(1, 0x80)
|
||||
}
|
||||
|
||||
/// Byte 39 bit `0x01`: the video switch (the layer's eye icon; `enabled` in the scripting API).
|
||||
pub fn is_video_enabled(&self) -> bool {
|
||||
self.flag(2, 0x01)
|
||||
}
|
||||
|
||||
/// The same as [`LayerHeader::is_video_enabled`].
|
||||
pub fn is_enabled(&self) -> bool {
|
||||
self.is_video_enabled()
|
||||
}
|
||||
|
||||
/// Byte 39 bit `0x02`: the audio switch (`audioEnabled`).
|
||||
pub fn is_audio_enabled(&self) -> bool {
|
||||
self.flag(2, 0x02)
|
||||
}
|
||||
|
||||
/// Byte 39 bit `0x04`: the effects switch (`effectsActive`).
|
||||
pub fn is_effects_enabled(&self) -> bool {
|
||||
self.flag(2, 0x04)
|
||||
}
|
||||
|
||||
/// Byte 39 bit `0x08`: the motion blur switch.
|
||||
pub fn is_motion_blur(&self) -> bool {
|
||||
self.flag(2, 0x08)
|
||||
}
|
||||
|
||||
/// Byte 39 bit `0x20`: locked.
|
||||
pub fn is_locked(&self) -> bool {
|
||||
self.flag(2, 0x20)
|
||||
}
|
||||
|
||||
/// Byte 39 bit `0x40`: shy.
|
||||
pub fn is_shy(&self) -> bool {
|
||||
self.flag(2, 0x40)
|
||||
}
|
||||
|
||||
/// Byte 39 bit `0x80`: collapse transformations / continuously rasterize. Shape and text
|
||||
/// layers have it set from creation.
|
||||
pub fn collapses_transformations(&self) -> bool {
|
||||
self.flag(2, 0x80)
|
||||
}
|
||||
|
||||
/// The light type of a light layer: parallel 0, spot 1, point 2, ambient 3 (`None` for any
|
||||
/// other layer type).
|
||||
pub fn light_type(&self) -> Option<LightType> {
|
||||
(self.layer_type == LayerType::Light).then_some(match self.light_type_code {
|
||||
0 => LightType::Parallel,
|
||||
1 => LightType::Spot,
|
||||
2 => LightType::Point,
|
||||
3 => LightType::Ambient,
|
||||
other => LightType::Other(other),
|
||||
})
|
||||
}
|
||||
|
||||
/// The time stretch as an exact reduced ratio (`stretch / stretch_den`: 50 % is `1/2`, 150 %
|
||||
/// is `3/2`); `None` for a zero denominator.
|
||||
pub fn stretch_ratio(&self) -> Option<Rational> {
|
||||
Rational::new(i64::from(self.stretch), i64::from(self.stretch_den))
|
||||
}
|
||||
|
||||
/// The time stretch in percent (`stretch / stretch_den * 100`); a zero denominator reads as 1.
|
||||
pub fn stretch_percent(&self) -> f64 {
|
||||
let den = if self.stretch_den == 0 { 1.0 } else { f64::from(self.stretch_den) };
|
||||
f64::from(self.stretch) / den * 100.0
|
||||
}
|
||||
|
||||
/// The start time in seconds, `None` for a zero denominator.
|
||||
pub fn start_seconds(&self) -> Option<f64> {
|
||||
self.start.to_f64()
|
||||
}
|
||||
|
||||
/// The absolute in point, `start + in * stretch`, exact and reduced.
|
||||
pub fn in_point(&self) -> Option<Rational> {
|
||||
self.start.plus_scaled(&self.in_relative, &self.stretch_ratio()?)
|
||||
}
|
||||
|
||||
/// The absolute out point, `start + out * stretch`, exact and reduced. For a footage layer the
|
||||
/// stored denominator is the footage time base (the sample rate of an audio layer, the frame
|
||||
/// rate of an image sequence), not the composition timescale.
|
||||
pub fn out_point(&self) -> Option<Rational> {
|
||||
self.start.plus_scaled(&self.out_relative, &self.stretch_ratio()?)
|
||||
}
|
||||
|
||||
/// The absolute in point in seconds.
|
||||
pub fn in_point_seconds(&self) -> Option<f64> {
|
||||
self.in_point()?.to_f64()
|
||||
}
|
||||
|
||||
/// The absolute out point in seconds.
|
||||
pub fn out_point_seconds(&self) -> Option<f64> {
|
||||
self.out_point()?.to_f64()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The layer id (`ldta` byte 0).
|
||||
pub fn id(&self) -> Option<u32> {
|
||||
be_u32(self.chunk.child(b"ldta")?.bytes()?, 0)
|
||||
}
|
||||
|
||||
/// The decoded `ldta`, see [`LayerHeader`].
|
||||
pub fn header(&self) -> Option<LayerHeader> {
|
||||
LayerHeader::parse(self.chunk.child(b"ldta")?.bytes()?)
|
||||
}
|
||||
|
||||
/// The video switch (byte 39 bit `0x01`), `enabled` in the scripting API.
|
||||
pub fn is_enabled(&self) -> Option<bool> {
|
||||
self.header().map(|h| h.is_video_enabled())
|
||||
}
|
||||
|
||||
/// The audio switch (byte 39 bit `0x02`), `audioEnabled`.
|
||||
pub fn is_audio_enabled(&self) -> Option<bool> {
|
||||
self.header().map(|h| h.is_audio_enabled())
|
||||
}
|
||||
|
||||
/// The effects switch (byte 39 bit `0x04`), `effectsActive`.
|
||||
pub fn is_effects_enabled(&self) -> Option<bool> {
|
||||
self.header().map(|h| h.is_effects_enabled())
|
||||
}
|
||||
}
|
||||
|
||||
/// The renderer of a composition (`LIST PRin` / `prin`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Renderer {
|
||||
/// The match name (`ADBE Escher` for the Classic 3D renderer in the base project,
|
||||
/// `ADBE Calder` for Advanced 3D).
|
||||
pub match_name: String,
|
||||
/// The display name (`Classic 3D`, `Advanced 3D`).
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
/// The decoded fields of a composition's `cdta` chunk (204 bytes; the fields below need 176).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CompHeader {
|
||||
/// Frame duration (`u32` at byte 4) and timescale (`u32` at byte 8).
|
||||
pub time_base: TimeBase,
|
||||
/// The frame rate as 16.16 fixed point (`u32` at byte 156).
|
||||
pub frame_rate_fixed: u32,
|
||||
/// The composition duration in time units.
|
||||
pub duration_units: u32,
|
||||
/// The work area start in time units.
|
||||
pub work_area_start_units: u32,
|
||||
/// The work area end (start + duration) in time units; `None` when it is the whole
|
||||
/// composition (stored as `0xffff_ffff`).
|
||||
pub work_area_end_units: Option<u32>,
|
||||
/// The background colour as R, G, B (bytes 52 to 54), 8 bits per channel: 0.5 is stored as 128
|
||||
/// and reads back as 128/255.
|
||||
pub background: [u8; 3],
|
||||
/// The shutter angle in degrees.
|
||||
pub shutter_angle: u32,
|
||||
pub width: u16,
|
||||
pub height: u16,
|
||||
/// The pixel aspect ratio as stored: numerator and denominator.
|
||||
pub pixel_aspect: Rational,
|
||||
/// The composition's motion blur switch.
|
||||
pub motion_blur: bool,
|
||||
/// The shutter phase in degrees (`i32` at byte 180, 0 by default, -90 in the sample); `None`
|
||||
/// when the chunk ends before byte 184.
|
||||
pub shutter_phase: Option<i32>,
|
||||
/// The display start time (the comp start timecode) as `num / den` seconds: `u32` at byte 164
|
||||
/// over `u32` at byte 168 (0/1 by default; display start frame 100 at 25 fps is 102400/25600).
|
||||
/// `None` when the chunk ends before byte 172.
|
||||
pub display_start: Option<Rational>,
|
||||
}
|
||||
|
||||
impl CompHeader {
|
||||
/// Decodes a `cdta` body; `None` when it is shorter than 176 bytes.
|
||||
pub fn parse(cdta: &[u8]) -> Option<Self> {
|
||||
let work_end = be_u32(cdta, 36)?;
|
||||
Some(Self {
|
||||
time_base: TimeBase { frame_duration: be_u32(cdta, 4)?, timescale: be_u32(cdta, 8)? },
|
||||
frame_rate_fixed: be_u32(cdta, 156)?,
|
||||
duration_units: be_u32(cdta, 44)?,
|
||||
work_area_start_units: be_u32(cdta, 28)?,
|
||||
work_area_end_units: (work_end != u32::MAX).then_some(work_end),
|
||||
background: array::<3>(cdta, 52)?,
|
||||
shutter_angle: be_u32(cdta, 172)?,
|
||||
width: be_u16(cdta, 140)?,
|
||||
height: be_u16(cdta, 142)?,
|
||||
pixel_aspect: Rational { num: i64::from(be_u32(cdta, 144)?), den: i64::from(be_u32(cdta, 148)?) },
|
||||
motion_blur: cdta.get(139)? & 0x08 != 0,
|
||||
shutter_phase: be_i32(cdta, 180),
|
||||
display_start: be_u32(cdta, 164).zip(be_u32(cdta, 168)).map(|(num, den)| Rational { num: i64::from(num), den: i64::from(den) }),
|
||||
})
|
||||
}
|
||||
|
||||
/// Frames per second from the time base (`timescale / frame_duration`).
|
||||
pub fn frame_rate(&self) -> Option<f64> {
|
||||
self.time_base.frame_rate()
|
||||
}
|
||||
|
||||
/// The frame rate from the 16.16 fixed-point field (25 is `0x0019_0000`).
|
||||
pub fn frame_rate_from_fixed(&self) -> f64 {
|
||||
f64::from(self.frame_rate_fixed) / 65536.0
|
||||
}
|
||||
|
||||
/// The duration in seconds.
|
||||
pub fn duration_seconds(&self) -> Option<f64> {
|
||||
self.time_base.seconds(i32::try_from(self.duration_units).ok()?)
|
||||
}
|
||||
|
||||
/// The work area start in seconds.
|
||||
pub fn work_area_start_seconds(&self) -> Option<f64> {
|
||||
self.time_base.seconds(i32::try_from(self.work_area_start_units).ok()?)
|
||||
}
|
||||
|
||||
/// The work area end in seconds; the composition duration when the work area is the whole
|
||||
/// composition.
|
||||
pub fn work_area_end_seconds(&self) -> Option<f64> {
|
||||
match self.work_area_end_units {
|
||||
Some(end) => self.time_base.seconds(i32::try_from(end).ok()?),
|
||||
None => self.duration_seconds(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The background colour as fractions 0..1 (`byte / 255`).
|
||||
pub fn background_rgb(&self) -> [f64; 3] {
|
||||
self.background.map(|c| f64::from(c) / 255.0)
|
||||
}
|
||||
|
||||
/// The pixel aspect ratio as a number.
|
||||
pub fn pixel_aspect_ratio(&self) -> Option<f64> {
|
||||
self.pixel_aspect.to_f64()
|
||||
}
|
||||
|
||||
/// The display start time in seconds (the start timecode), `None` when absent or the
|
||||
/// denominator is zero.
|
||||
pub fn display_start_seconds(&self) -> Option<f64> {
|
||||
self.display_start?.to_f64()
|
||||
}
|
||||
|
||||
/// The display start as a frame number (`display start * frame rate`, rounded); 100 at 25 fps
|
||||
/// for a display start of 4 s.
|
||||
pub fn display_start_frame(&self) -> Option<i64> {
|
||||
let rate = self.frame_rate()?;
|
||||
Some((self.display_start_seconds()? * rate).round() as i64)
|
||||
}
|
||||
|
||||
/// The frame rate as an exact fraction `timescale / frame_duration`, as typed: 29.97 fps is
|
||||
/// `23976 / 800` (not `30000 / 1001`), 23.976 fps is `23976 / 1000`.
|
||||
pub fn frame_rate_exact(&self) -> Option<Rational> {
|
||||
Rational::new(i64::from(self.time_base.timescale), i64::from(self.time_base.frame_duration))
|
||||
}
|
||||
|
||||
/// The duration in whole frames (`duration / frame_duration`). After Effects snaps a duration
|
||||
/// to a whole number of frames: 5 s at 29.97 fps becomes 150 frames (5.005 s).
|
||||
pub fn duration_frames(&self) -> Option<u32> {
|
||||
self.duration_units.checked_div(self.time_base.frame_duration)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Comp<'f, 'a> {
|
||||
/// The decoded `cdta`, see [`CompHeader`].
|
||||
pub fn header(&self) -> Option<CompHeader> {
|
||||
CompHeader::parse(self.item.child(b"cdta")?.bytes()?)
|
||||
}
|
||||
|
||||
/// The composition name (the item's `Utf8` child).
|
||||
pub fn name(&self) -> Option<String> {
|
||||
utf8_child(self.item).filter(|n| !n.is_empty())
|
||||
}
|
||||
|
||||
/// The item this composition data belongs to.
|
||||
pub fn item(&self) -> Item<'f, 'a> {
|
||||
Item { chunk: self.item }
|
||||
}
|
||||
|
||||
/// The renderer (`LIST PRin` / `prin`: match name at byte 4, display name at byte 52, 32
|
||||
/// bytes each).
|
||||
pub fn renderer(&self) -> Option<Renderer> {
|
||||
let prin = self.item.child_list(b"PRin")?.child(b"prin")?.bytes()?;
|
||||
Some(Renderer { match_name: cstr(prin, 4, 32)?, display_name: cstr(prin, 52, 32)? })
|
||||
}
|
||||
}
|
||||
@@ -1,361 +0,0 @@
|
||||
//! Keyframe records, property flags and expressions.
|
||||
//!
|
||||
//! Keyframe times are **layer time**, in units of the property's own time scale
|
||||
//! ([`Property::time_scale`], equal to the composition's timescale in every sample).
|
||||
//!
|
||||
//! Every record starts with an 8-byte header: `i32` time, `u8` at byte 4 = the interpolation of the
|
||||
//! **incoming** side, `u8` at byte 5 = the **outgoing** side (1 linear, 2 bezier, 3 hold), and a
|
||||
//! `u16` of flags (label, roving). The rest depends on the property header (`tdb4`), which selects
|
||||
//! one of two templates for `n` value components:
|
||||
//!
|
||||
//! * **plain** (`tdb4` byte 7 = 0; Opacity, Rotation, Scale, 2-D properties, sliders): the value
|
||||
//! (`n` x `f64`) at byte 8, then four `f64` per component of ease, type-major (`[in speed x n]
|
||||
//! [in influence x n][out speed x n][out influence x n]`). Size `8 + 40 n`.
|
||||
//! * **spatial** (`tdb4` byte 7 != 0; Position with `n` = 3, colours with `n` = 4): a `u32` at 8, the
|
||||
//! arc length (`f64`) at 16, the four ease slots at 24 to 55, the value (`n` x `f64`) at 56, then
|
||||
//! the spatial in tangent and out tangent (`n` x `f64` each). Size `56 + 24 n`.
|
||||
|
||||
use crate::container::bytes::{be_f64, be_u16, be_u32, text};
|
||||
use crate::container::typed::{Keyframe, Property};
|
||||
|
||||
/// A keyframe interpolation type (a byte of the record header).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Interpolation {
|
||||
/// `1`
|
||||
Linear,
|
||||
/// `2`
|
||||
Bezier,
|
||||
/// `3`
|
||||
Hold,
|
||||
/// Any other value.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl Interpolation {
|
||||
fn from_byte(b: u8) -> Self {
|
||||
match b {
|
||||
1 => Self::Linear,
|
||||
2 => Self::Bezier,
|
||||
3 => Self::Hold,
|
||||
other => Self::Other(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a keyframe record is, judged by the property header (when the list belongs to a property)
|
||||
/// and the record size.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum KeyframeKind {
|
||||
/// The plain template: `8 + 40 n` bytes, 48 for one component (Opacity, Rotation, Slider), 88 for
|
||||
/// two (Mask Feather, Rectangle Size), 128 for three (Scale).
|
||||
Plain { components: usize },
|
||||
/// The spatial template: `56 + 24 n` bytes, 128 for Position (3 components), 152 for a colour (4).
|
||||
Spatial { components: usize },
|
||||
/// 64 bytes: a mask path key; the path itself is in the matching `shap` chunk. The ease sits at
|
||||
/// byte 24 as in the spatial template (599, 700: speed 0, influences 0.75 / 0.20 / 0.50); the
|
||||
/// `f64` at byte 16 is 1 or 2 on a first key and 0 on a last one (093, 599, 700; meaning not
|
||||
/// decoded).
|
||||
MaskPath,
|
||||
/// 16 bytes: a marker (time and two hold bytes).
|
||||
Marker,
|
||||
/// Any other size.
|
||||
Other(usize),
|
||||
}
|
||||
|
||||
/// The ease of a key: speed and influence of the incoming and outgoing side. Speed is in stored
|
||||
/// value units per second (for Opacity a fraction, so 100 times smaller than the percent shown in
|
||||
/// the UI; for Position pixels per second); influence is a fraction (20 % is `0.2`). After Effects
|
||||
/// reports the first key's incoming speed and the last key's outgoing speed as 0, but the file
|
||||
/// keeps the requested values, so these two slots are not meaningful.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct KeyEase {
|
||||
pub in_speed: f64,
|
||||
pub in_influence: f64,
|
||||
pub out_speed: f64,
|
||||
pub out_influence: f64,
|
||||
}
|
||||
|
||||
/// The fields of a spatial keyframe record.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct SpatialKey {
|
||||
/// The `u32` at byte 8: `1` normally, `0` after the spatial interpolation was changed to
|
||||
/// non-auto-bezier / non-continuous (the two switches were changed together).
|
||||
pub auto_bezier_flag: u32,
|
||||
/// The `f64` at byte 16: the arc length of the segment to the next key, updated lazily by
|
||||
/// After Effects (0 right after creation). Safe to ignore.
|
||||
pub segment_length: f64,
|
||||
/// The four `f64` at bytes 24, 32, 40 and 48 as stored: in speed, in influence, out speed, out
|
||||
/// influence (see [`KeyEase`]).
|
||||
pub ease: [f64; 4],
|
||||
/// The value (x, y, z in pixels for Position; ARGB 0..255 for a colour), from byte 56.
|
||||
pub value: Vec<f64>,
|
||||
/// The spatial in tangent as an offset from the value.
|
||||
pub in_tangent: Vec<f64>,
|
||||
/// The spatial out tangent as an offset from the value.
|
||||
pub out_tangent: Vec<f64>,
|
||||
}
|
||||
|
||||
fn doubles(b: &[u8], at: usize, n: usize) -> Option<Vec<f64>> {
|
||||
(0..n).map(|i| be_f64(b, at.checked_add(i.checked_mul(8)?)?)).collect()
|
||||
}
|
||||
|
||||
fn ease_at(b: &[u8], at: usize) -> Option<KeyEase> {
|
||||
Some(KeyEase {
|
||||
in_speed: be_f64(b, at)?,
|
||||
in_influence: be_f64(b, at.checked_add(8)?)?,
|
||||
out_speed: be_f64(b, at.checked_add(16)?)?,
|
||||
out_influence: be_f64(b, at.checked_add(24)?)?,
|
||||
})
|
||||
}
|
||||
|
||||
impl<'f> Keyframe<'f> {
|
||||
/// The record kind. For a list that belongs to a property, the header's component count and
|
||||
/// template flag decide; without a property, 48 bytes is read as plain with one component and
|
||||
/// 128 bytes as spatial with three.
|
||||
pub fn kind(&self) -> KeyframeKind {
|
||||
let len = self.record.len();
|
||||
if let Some(layout) = self.layout {
|
||||
let n = usize::from(layout.components);
|
||||
if n > 0 {
|
||||
if layout.spatial && Some(len) == n.checked_mul(24).and_then(|v| v.checked_add(56)) {
|
||||
return KeyframeKind::Spatial { components: n };
|
||||
}
|
||||
if !layout.spatial && Some(len) == n.checked_mul(40).and_then(|v| v.checked_add(8)) {
|
||||
return KeyframeKind::Plain { components: n };
|
||||
}
|
||||
}
|
||||
}
|
||||
match (len, self.layout) {
|
||||
(64, _) => KeyframeKind::MaskPath,
|
||||
(16, _) => KeyframeKind::Marker,
|
||||
(48, None) => KeyframeKind::Plain { components: 1 },
|
||||
(128, None) => KeyframeKind::Spatial { components: 3 },
|
||||
(other, _) => KeyframeKind::Other(other),
|
||||
}
|
||||
}
|
||||
|
||||
/// The time in seconds given the property's time scale (units per second).
|
||||
pub fn seconds(&self, time_scale: u32) -> Option<f64> {
|
||||
if time_scale == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(f64::from(self.time_units()?) / f64::from(time_scale))
|
||||
}
|
||||
|
||||
/// The interpolation of the incoming side: the byte at offset 4.
|
||||
pub fn interpolation_in(&self) -> Option<Interpolation> {
|
||||
self.record.get(4).copied().map(Interpolation::from_byte)
|
||||
}
|
||||
|
||||
/// The interpolation of the outgoing side: the byte at offset 5.
|
||||
pub fn interpolation_out(&self) -> Option<Interpolation> {
|
||||
self.record.get(5).copied().map(Interpolation::from_byte)
|
||||
}
|
||||
|
||||
/// The flags word at byte 6.
|
||||
pub fn flags(&self) -> Option<u16> {
|
||||
be_u16(self.record, 6)
|
||||
}
|
||||
|
||||
/// The keyframe label: bits 6 to 9 of the flags (label 9 gives `0x0247` on a spatial key).
|
||||
pub fn label(&self) -> Option<u8> {
|
||||
u8::try_from((self.flags()? >> 6) & 0x0f).ok()
|
||||
}
|
||||
|
||||
/// True when the key is roving: bit `0x20` of the flags.
|
||||
pub fn is_roving(&self) -> Option<bool> {
|
||||
Some(self.flags()? & 0x0020 != 0)
|
||||
}
|
||||
|
||||
/// The number of value components of a plain or spatial record.
|
||||
pub fn components(&self) -> Option<usize> {
|
||||
match self.kind() {
|
||||
KeyframeKind::Plain { components } | KeyframeKind::Spatial { components } => Some(components),
|
||||
KeyframeKind::MaskPath | KeyframeKind::Marker | KeyframeKind::Other(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored value of a plain (from byte 8) or spatial (from byte 56) record, in the units of
|
||||
/// the property's static value (fractions for Opacity and Scale, ARGB 0..255 for colours).
|
||||
pub fn value(&self) -> Option<Vec<f64>> {
|
||||
match self.kind() {
|
||||
KeyframeKind::Plain { components } => doubles(self.record, 8, components),
|
||||
KeyframeKind::Spatial { components } => doubles(self.record, 56, components),
|
||||
KeyframeKind::MaskPath | KeyframeKind::Marker | KeyframeKind::Other(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of a record with one component (Opacity, Rotation, a slider).
|
||||
pub fn scalar_value(&self) -> Option<f64> {
|
||||
match self.kind() {
|
||||
KeyframeKind::Plain { components: 1 } => be_f64(self.record, 8),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of a 3-component spatial keyframe (Position), x, y and z in pixels.
|
||||
pub fn spatial_value(&self) -> Option<[f64; 3]> {
|
||||
let v = self.value()?;
|
||||
if !matches!(self.kind(), KeyframeKind::Spatial { components: 3 }) {
|
||||
return None;
|
||||
}
|
||||
Some([*v.first()?, *v.get(1)?, *v.get(2)?])
|
||||
}
|
||||
|
||||
/// The ease of the key: the four slots at byte 16 of a one-component plain record or at byte 24
|
||||
/// of a spatial record or a mask path record. For linear and hold keys all four are 0 (a bezier key stores what
|
||||
/// `setTemporalEase` was given). Plain records with several components keep four slots per
|
||||
/// component, see [`Keyframe::ease_component`] and [`Keyframe::plain_ease_slots`].
|
||||
pub fn ease(&self) -> Option<KeyEase> {
|
||||
match self.kind() {
|
||||
KeyframeKind::Plain { components: 1 } => ease_at(self.record, 16),
|
||||
KeyframeKind::Spatial { .. } | KeyframeKind::MaskPath => ease_at(self.record, 24),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `4 n` ease `f64` of a plain record as stored (from byte `8 + 8 n`). With one component
|
||||
/// they are [`Keyframe::ease`]; with several they are type-major, see
|
||||
/// [`Keyframe::ease_component`].
|
||||
pub fn plain_ease_slots(&self) -> Option<Vec<f64>> {
|
||||
match self.kind() {
|
||||
KeyframeKind::Plain { components } => doubles(self.record, components.checked_mul(8)?.checked_add(8)?, components.checked_mul(4)?),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ease of one value component. A plain record with `n` components stores the `4 n` ease
|
||||
/// doubles **type-major**: `[in speed x n][in influence x n][out speed x n][out influence x n]`
|
||||
/// starting at byte `8 + 8 n`, and component `i` uses slot `i` of each block (verified for the
|
||||
/// block layout with Scale `n = 3` and Mask Feather `n = 2` keys whose ease was the same in
|
||||
/// every dimension; that different values sit in the slots of their dimension is inferred).
|
||||
/// A spatial record (Position, colours) has one ease entry for all components, so only
|
||||
/// `component == 0` returns it. For one component this is [`Keyframe::ease`].
|
||||
pub fn ease_component(&self, component: usize) -> Option<KeyEase> {
|
||||
match self.kind() {
|
||||
KeyframeKind::Plain { components } if component < components => {
|
||||
let block = components.checked_mul(8)?;
|
||||
let first = block.checked_add(8)?;
|
||||
let at = |k: usize| first.checked_add(block.checked_mul(k)?)?.checked_add(component.checked_mul(8)?);
|
||||
Some(KeyEase {
|
||||
in_speed: be_f64(self.record, at(0)?)?,
|
||||
in_influence: be_f64(self.record, at(1)?)?,
|
||||
out_speed: be_f64(self.record, at(2)?)?,
|
||||
out_influence: be_f64(self.record, at(3)?)?,
|
||||
})
|
||||
}
|
||||
KeyframeKind::Spatial { .. } if component == 0 => ease_at(self.record, 24),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ease of every value component of a plain record, see [`Keyframe::ease_component`]
|
||||
/// (one entry for a spatial record).
|
||||
pub fn ease_components(&self) -> Option<Vec<KeyEase>> {
|
||||
let n = match self.kind() {
|
||||
KeyframeKind::Plain { components } => components,
|
||||
KeyframeKind::Spatial { .. } => 1,
|
||||
KeyframeKind::MaskPath | KeyframeKind::Marker | KeyframeKind::Other(_) => return None,
|
||||
};
|
||||
(0..n).map(|i| self.ease_component(i)).collect()
|
||||
}
|
||||
|
||||
/// The Euclidean ARGB distance to the next key that After Effects writes at byte 16 of a colour
|
||||
/// (4-component spatial) record whose interpolation is not linear: 255 sqrt(2) = 360.6245 for
|
||||
/// red to blue; 0 on the last key and on linear keys. `None` for other records.
|
||||
pub fn color_distance(&self) -> Option<f64> {
|
||||
match self.kind() {
|
||||
KeyframeKind::Spatial { components: 4 } => be_f64(self.record, 16),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoded spatial record (Position: 128 bytes, colour: 152 bytes).
|
||||
pub fn spatial(&self) -> Option<SpatialKey> {
|
||||
let KeyframeKind::Spatial { components: n } = self.kind() else { return None };
|
||||
let r = self.record;
|
||||
let span = n.checked_mul(8)?;
|
||||
let ease = ease_at(r, 24)?;
|
||||
Some(SpatialKey {
|
||||
auto_bezier_flag: be_u32(r, 8)?,
|
||||
segment_length: be_f64(r, 16)?,
|
||||
ease: [ease.in_speed, ease.in_influence, ease.out_speed, ease.out_influence],
|
||||
value: doubles(r, 56, n)?,
|
||||
in_tangent: doubles(r, 56usize.checked_add(span)?, n)?,
|
||||
out_tangent: doubles(r, 56usize.checked_add(span.checked_mul(2)?)?, n)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of a property header that mark an expression: bytes 76, 77 and 120 of `tdb4` are all 1
|
||||
/// when the property has an expression (76 and 77 are also 1 on a camera's auto-computed Position,
|
||||
/// which has none). Byte 119 is 1 when the expression is disabled.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ExpressionFlags {
|
||||
pub byte_76: u8,
|
||||
pub byte_77: u8,
|
||||
/// 1 when the expression is disabled (`expression.disable_all`); the text stays in the file.
|
||||
pub byte_119: u8,
|
||||
pub byte_120: u8,
|
||||
}
|
||||
|
||||
impl ExpressionFlags {
|
||||
/// True when bytes 76, 77 and 120 are all 1.
|
||||
pub fn all_set(&self) -> bool {
|
||||
self.byte_76 == 1 && self.byte_77 == 1 && self.byte_120 == 1
|
||||
}
|
||||
|
||||
/// True when byte 119 is 1.
|
||||
pub fn disabled(&self) -> bool {
|
||||
self.byte_119 == 1
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Property<'f, 'a> {
|
||||
/// The time scale (units per second) of this property's keyframe times: the `u32` at byte 12
|
||||
/// of `tdb4` (25600 at 25 fps, 30720 at 30 fps, 23976 at 29.97 and 23.976 fps).
|
||||
pub fn time_scale(&self) -> Option<u32> {
|
||||
be_u32(self.header()?, 12)
|
||||
}
|
||||
|
||||
/// The property's `tdsb` flags: `1` for a property that was written (non-default), `3` for
|
||||
/// the default state.
|
||||
pub fn flags(&self) -> Option<u32> {
|
||||
be_u32(self.chunk.child(b"tdsb")?.bytes()?, 0)
|
||||
}
|
||||
|
||||
/// True when `tdb4` byte 5 has bit 0 set: the property is static, it has no keyframes.
|
||||
pub fn is_static_flag_set(&self) -> Option<bool> {
|
||||
Some(self.header()?.get(5)? & 1 != 0)
|
||||
}
|
||||
|
||||
/// The expression source: the raw UTF-8 text of the `Utf8` child that follows the value in the
|
||||
/// property (no length prefix, no engine tag; the engine is project-wide).
|
||||
pub fn expression(&self) -> Option<String> {
|
||||
self.chunk.child(b"Utf8").and_then(|c| c.bytes()).map(text)
|
||||
}
|
||||
|
||||
/// The expression flag bytes of `tdb4`.
|
||||
pub fn expression_flags(&self) -> Option<ExpressionFlags> {
|
||||
let h = self.header()?;
|
||||
Some(ExpressionFlags { byte_76: *h.get(76)?, byte_77: *h.get(77)?, byte_119: *h.get(119)?, byte_120: *h.get(120)? })
|
||||
}
|
||||
|
||||
/// Whether the expression is enabled: `None` when the property has no expression (byte 120 is
|
||||
/// not 1 or there is no `Utf8` text), else `Some(false)` when byte 119 marks it disabled. Byte
|
||||
/// 119 also changes by itself on built-in view layers after a save, so it only counts together
|
||||
/// with an expression.
|
||||
pub fn expression_enabled(&self) -> Option<bool> {
|
||||
let flags = self.expression_flags()?;
|
||||
if flags.byte_120 != 1 || self.expression().is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(!flags.disabled())
|
||||
}
|
||||
|
||||
/// The value of the first keyframe (plain or spatial record), for reading an animated property
|
||||
/// at its first key.
|
||||
pub fn first_key_value(&self) -> Option<Vec<f64>> {
|
||||
self.keys()?.keyframes().next()?.value()
|
||||
}
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
//! Masks and bezier paths.
|
||||
//!
|
||||
//! A layer's masks are in `tdgp[ADBE Mask Parade]`: one `mkif` chunk (mode and invert switch) next
|
||||
//! to one `tdgp[ADBE Mask Atom]` per mask. The atom holds the optional properties feather, opacity
|
||||
//! and expansion (stored only when not at their defaults) and `om-s[ADBE Mask Shape]`: the path
|
||||
//! property (`tdbs`, with a key list when animated) and `omks` with one `LIST shap` per keyframe (a
|
||||
//! single one when the path is static).
|
||||
|
||||
use crate::container::Chunk;
|
||||
use crate::container::bytes::{be_f32, be_u32, until_nul};
|
||||
use crate::container::typed::{KeyList, Layer, Project, PropGroup, PropNode, Property};
|
||||
use crate::container::values::{Tracked, read};
|
||||
|
||||
/// The mask mode (`mkif` `u32` at byte 4).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MaskMode {
|
||||
/// `0` (329)
|
||||
None,
|
||||
/// `1`
|
||||
Add,
|
||||
/// `2`
|
||||
Subtract,
|
||||
/// `3`
|
||||
Intersect,
|
||||
/// `4`
|
||||
Lighten,
|
||||
/// `5`
|
||||
Darken,
|
||||
/// `6`
|
||||
Difference,
|
||||
/// Any other value (not sampled).
|
||||
Other(u32),
|
||||
}
|
||||
|
||||
impl MaskMode {
|
||||
/// The mode for a stored id.
|
||||
pub fn from_id(id: u32) -> Self {
|
||||
match id {
|
||||
0 => Self::None,
|
||||
1 => Self::Add,
|
||||
2 => Self::Subtract,
|
||||
3 => Self::Intersect,
|
||||
4 => Self::Lighten,
|
||||
5 => Self::Darken,
|
||||
6 => Self::Difference,
|
||||
other => Self::Other(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A vertex of a bezier path with its two control points as absolute positions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PathVertex {
|
||||
pub position: [f64; 2],
|
||||
/// The control point of the incoming segment.
|
||||
pub in_handle: [f64; 2],
|
||||
/// The control point of the outgoing segment.
|
||||
pub out_handle: [f64; 2],
|
||||
}
|
||||
|
||||
impl PathVertex {
|
||||
/// The in tangent: the in handle minus the vertex (what the scripting API calls `inTangents`).
|
||||
pub fn in_tangent(&self) -> [f64; 2] {
|
||||
[self.in_handle[0] - self.position[0], self.in_handle[1] - self.position[1]]
|
||||
}
|
||||
|
||||
/// The out tangent: the out handle minus the vertex (`outTangents`).
|
||||
pub fn out_tangent(&self) -> [f64; 2] {
|
||||
[self.out_handle[0] - self.position[0], self.out_handle[1] - self.position[1]]
|
||||
}
|
||||
}
|
||||
|
||||
/// One path shape (`LIST shap`): a bounding box and the control points normalised inside it.
|
||||
///
|
||||
/// The `shph` chunk holds a magic word whose last byte carries the flags (`0x01` closed, `0x09` open:
|
||||
/// bit `0x08`), the box (left, top, right, bottom) as four `f32`, and the byte at offset 20 (`1` in
|
||||
/// every sample). The box is the box of the vertices **and** their handles. The `list` holds three
|
||||
/// points per vertex, each as two `f32` in [0, 1] of the box, in the order `[vertex i, out handle i,
|
||||
/// in handle i + 1]`; the last record is the in handle of vertex 0. For masks the box is normalised
|
||||
/// to the **layer** size (the size of the layer's source, not the composition's: on a 100x100 solid
|
||||
/// a 60x40 mask rectangle at the centre has the box `0.2, 0.3, 0.8, 0.7`, 309); for the paths of shape layers it is in pixels. Handles equal their vertex when a
|
||||
/// vertex has no tangents; a tangent is the handle minus the vertex, without a sign change.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ShapePath {
|
||||
/// Left, top, right, bottom.
|
||||
pub bbox: [f32; 4],
|
||||
/// The byte at offset 20 of `shph` (`1` in every sample, also for the open path).
|
||||
pub closed_flag: u8,
|
||||
/// True for an open path: bit `0x08` of the last byte of the first `shph` word.
|
||||
pub open: bool,
|
||||
/// The normalised points as stored, three per vertex.
|
||||
pub points: Vec<[f32; 2]>,
|
||||
}
|
||||
|
||||
impl ShapePath {
|
||||
/// Decodes a `LIST shap`; `None` when `shph` or the point list is malformed.
|
||||
pub fn from_chunk(shap: &Chunk<'_>) -> Option<Self> {
|
||||
let shph = shap.child(b"shph")?.bytes()?;
|
||||
let bbox = [be_f32(shph, 4)?, be_f32(shph, 8)?, be_f32(shph, 12)?, be_f32(shph, 16)?];
|
||||
let closed_flag = *shph.get(20)?;
|
||||
let open = shph.get(3)? & 0x08 != 0;
|
||||
let list = KeyList::from_chunk(shap.child_list(b"list")?)?;
|
||||
if list.header.record_size != 8 {
|
||||
return None;
|
||||
}
|
||||
let points = list.records().map(|r| Some([be_f32(r, 0)?, be_f32(r, 4)?])).collect::<Option<Vec<_>>>()?;
|
||||
Some(Self { bbox, closed_flag, open, points })
|
||||
}
|
||||
|
||||
/// The number of vertices (`points / 3`).
|
||||
pub fn vertex_count(&self) -> usize {
|
||||
self.points.len() / 3
|
||||
}
|
||||
|
||||
/// The vertices with absolute control points: `box.left + u * (box.right - box.left)` (and the
|
||||
/// same for y), multiplied by `scale` (the layer size in pixels for a mask, `(1, 1)` for a
|
||||
/// shape layer path).
|
||||
pub fn vertices(&self, scale: (f64, f64)) -> Vec<PathVertex> {
|
||||
let [left, top, right, bottom] = self.bbox.map(f64::from);
|
||||
let abs = |p: Option<&[f32; 2]>| -> [f64; 2] {
|
||||
let [u, v] = p.copied().unwrap_or([0.0, 0.0]).map(f64::from);
|
||||
[(left + u * (right - left)) * scale.0, (top + v * (bottom - top)) * scale.1]
|
||||
};
|
||||
let n = self.vertex_count();
|
||||
let total = n.saturating_mul(3);
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let base = i.saturating_mul(3);
|
||||
PathVertex {
|
||||
position: abs(self.points.get(base)),
|
||||
out_handle: abs(self.points.get(base.saturating_add(1))),
|
||||
// The in handle of vertex i is the record before vertex i (the last one for vertex 0).
|
||||
in_handle: abs(self.points.get(base.saturating_add(total).saturating_sub(1) % total.max(1))),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// One mask of a layer.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Mask {
|
||||
/// The mask name (`Mask 1`).
|
||||
pub name: Option<String>,
|
||||
/// The mode, from this mask's `mkif` (there is one `mkif` per mask, directly before its atom).
|
||||
pub mode: Option<MaskMode>,
|
||||
/// The invert switch (`mkif` byte 0).
|
||||
pub inverted: Option<bool>,
|
||||
/// The running mask id counter of the layer (`mkif` `u32` at byte 8): 1 for the first mask
|
||||
/// created on a layer, +1 per mask created later on the same layer (undo does not reset it).
|
||||
/// A session counter, not a stable id.
|
||||
pub counter: Option<u32>,
|
||||
/// Feather in pixels `[x, y]`; absent = `[0, 0]`.
|
||||
pub feather: Tracked<[f64; 2]>,
|
||||
/// Opacity in percent (stored as a fraction); absent = 100.
|
||||
pub opacity_percent: Tracked<f64>,
|
||||
/// Expansion in pixels; absent = 0.
|
||||
pub expansion: Tracked<f64>,
|
||||
/// True when the path has keyframes.
|
||||
pub path_animated: bool,
|
||||
/// The path keyframe times in seconds (empty for a static path).
|
||||
pub path_key_seconds: Vec<f64>,
|
||||
/// The path shapes: one for a static path, one per keyframe otherwise.
|
||||
pub shapes: Vec<ShapePath>,
|
||||
}
|
||||
|
||||
fn mask_from_atom(atom: &PropGroup<'_, '_>, mkif: Option<&[u8]>) -> Mask {
|
||||
let opacity = read(atom, "ADBE Mask Opacity", [100.0], 100.0);
|
||||
let expansion = read(atom, "ADBE Mask Offset", [0.0], 1.0);
|
||||
let mut mask = Mask {
|
||||
name: atom.user_name(),
|
||||
mode: mkif.and_then(|m| be_u32(m, 4)).map(MaskMode::from_id),
|
||||
inverted: mkif.and_then(|m| m.first()).map(|b| *b != 0),
|
||||
counter: mkif.and_then(|m| be_u32(m, 8)),
|
||||
feather: read(atom, "ADBE Mask Feather", [0.0, 0.0], 1.0),
|
||||
opacity_percent: Tracked { value: opacity.value[0], source: opacity.source },
|
||||
expansion: Tracked { value: expansion.value[0], source: expansion.source },
|
||||
path_animated: false,
|
||||
path_key_seconds: Vec::new(),
|
||||
shapes: Vec::new(),
|
||||
};
|
||||
if let Some(PropNode::Other(oms)) = atom.get("ADBE Mask Shape") {
|
||||
if let Some(prop) = oms.child_list(b"tdbs").and_then(Property::from_chunk) {
|
||||
mask.path_animated = prop.is_animated();
|
||||
if let (Some(keys), Some(scale)) = (prop.keys(), prop.time_scale()) {
|
||||
mask.path_key_seconds = keys.keyframes().filter_map(|k| k.seconds(scale)).collect();
|
||||
}
|
||||
}
|
||||
if let Some(omks) = oms.child_list(b"omks") {
|
||||
mask.shapes = omks.children().iter().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect();
|
||||
}
|
||||
}
|
||||
mask
|
||||
}
|
||||
|
||||
impl<'f, 'a> Project<'f, 'a> {
|
||||
/// The vertices of every path shape of a mask in pixels of the layer: mask boxes are normalised
|
||||
/// to the **layer** size (the size of its source), not the composition's. `None` when the layer
|
||||
/// has no source with a size.
|
||||
pub fn mask_vertices_px(&self, layer: &Layer<'f, 'a>, mask: &Mask) -> Option<Vec<Vec<PathVertex>>> {
|
||||
let (width, height) = self.layer_source_size(layer)?;
|
||||
Some(mask.shapes.iter().map(|s| s.vertices((f64::from(width), f64::from(height)))).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// One mask with the views of its records, for readers that need more than [`Mask`]: the
|
||||
/// keyframes and expressions of the mask properties (in [`MaskAtom::atom`]: `ADBE Mask Feather`,
|
||||
/// `ADBE Mask Opacity`, `ADBE Mask Offset`) and the path keyframes paired with their shapes.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MaskAtom<'f, 'a> {
|
||||
/// The decoded mask (as [`Layer::masks`] returns it).
|
||||
pub mask: Mask,
|
||||
/// The atom group (`tdgp[ADBE Mask Atom]`).
|
||||
pub atom: PropGroup<'f, 'a>,
|
||||
/// The path property (`om-s[ADBE Mask Shape]/tdbs`): its key list holds one 64-byte record
|
||||
/// per path keyframe (time, interpolation, label and roving flags; 093).
|
||||
pub path: Option<Property<'f, 'a>>,
|
||||
/// Every `LIST shap` of `omks` in file order, `None` where one is malformed, so that index `i`
|
||||
/// stays the shape of path keyframe `i` (one entry for a static path).
|
||||
pub path_shapes: Vec<Option<ShapePath>>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The layer's masks, in stack order.
|
||||
pub fn masks(&self) -> Vec<Mask> {
|
||||
self.mask_atoms().into_iter().map(|m| m.mask).collect()
|
||||
}
|
||||
|
||||
/// The layer's masks with the views of their records, in stack order.
|
||||
pub fn mask_atoms(&self) -> Vec<MaskAtom<'f, 'a>> {
|
||||
let Some(root) = self.properties() else { return Vec::new() };
|
||||
let Some(PropNode::Group(parade)) = root.get("ADBE Mask Parade") else { return Vec::new() };
|
||||
// Per mask: `tdmn` (Mask Atom), `mkif`, then the atom's `tdgp`.
|
||||
let mut masks = Vec::new();
|
||||
let (mut name, mut mkif): (Option<&[u8]>, Option<&[u8]>) = (None, None);
|
||||
for c in parade.chunk().children() {
|
||||
if c.is(b"tdmn") {
|
||||
name = c.bytes();
|
||||
} else if c.is(b"mkif") {
|
||||
mkif = c.bytes();
|
||||
} else if c.is_list(b"tdgp") {
|
||||
let is_atom = name.take().is_some_and(|n| until_nul(n) == b"ADBE Mask Atom");
|
||||
if is_atom && let Some(atom) = PropGroup::from_chunk(c) {
|
||||
let mask = mask_from_atom(&atom, mkif.take());
|
||||
let (mut path, mut path_shapes) = (None, Vec::new());
|
||||
if let Some(PropNode::Other(oms)) = atom.get("ADBE Mask Shape") {
|
||||
path = oms.child_list(b"tdbs").and_then(Property::from_chunk);
|
||||
if let Some(omks) = oms.child_list(b"omks") {
|
||||
path_shapes = omks.children().iter().filter(|c| c.is_list(b"shap")).map(ShapePath::from_chunk).collect();
|
||||
}
|
||||
}
|
||||
masks.push(MaskAtom { mask, atom, path, path_shapes });
|
||||
}
|
||||
}
|
||||
}
|
||||
masks
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
//! Track mattes: the matte mode and the matte layer, two fields of the layer header `ldta`.
|
||||
//!
|
||||
//! Cases 402-408 (a 960x540 grey solid `M` above the red solid `L`): setting a track matte on a
|
||||
//! layer changes exactly two fields of that layer's `ldta` (and the video switch of the matte
|
||||
//! layer, which After Effects turns off by itself):
|
||||
//!
|
||||
//! * byte 107 (`u8`; bytes 104..106 are 0 in every file of the corpus): the matte mode, 1 alpha
|
||||
//! (403), 2 alpha inverted (404), 3 luma (405), 4 luma inverted (406), 0 no matte (every other
|
||||
//! case);
|
||||
//! * the `u32` at byte 160: the id of the matte layer (`ldta` byte 0 of that layer), `0x1d` = `M`
|
||||
//! in 403-406 and 408, `0x1b` = `L` in 407, where the matte layer is BELOW the layer it mattes.
|
||||
//! 0 in every file without a matte.
|
||||
//!
|
||||
//! A matte mode with a matte layer id of 0 (or an `ldta` too short to hold the id) has no case in
|
||||
//! the corpus: After Effects 2026 writes the id. Before After Effects 23.0 a track matte always
|
||||
//! used the layer directly above (the documented behaviour of those versions), so such a matte is
|
||||
//! returned with [`TrackMatte::layer`] `None` and the caller decides.
|
||||
|
||||
use crate::container::Layer;
|
||||
use crate::container::bytes::be_u32;
|
||||
|
||||
/// The matte mode (`ldta` byte 107).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MatteMode {
|
||||
/// `1` (403)
|
||||
Alpha,
|
||||
/// `2` (404)
|
||||
AlphaInverted,
|
||||
/// `3` (405)
|
||||
Luma,
|
||||
/// `4` (406)
|
||||
LumaInverted,
|
||||
/// Any other non-zero value (not sampled).
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl MatteMode {
|
||||
/// The mode for a stored code; `None` for 0 (no matte).
|
||||
pub fn from_code(code: u8) -> Option<Self> {
|
||||
Some(match code {
|
||||
0 => return None,
|
||||
1 => Self::Alpha,
|
||||
2 => Self::AlphaInverted,
|
||||
3 => Self::Luma,
|
||||
4 => Self::LumaInverted,
|
||||
other => Self::Other(other),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The track matte of a layer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TrackMatte {
|
||||
pub mode: MatteMode,
|
||||
/// The id of the matte layer (`u32` at `ldta` byte 160); `None` when it is 0 or the header is
|
||||
/// too short to hold it (the older "layer above" form, see the module documentation).
|
||||
pub layer: Option<u32>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The track matte of the layer, `None` when it has none (or the header is unreadable).
|
||||
pub fn track_matte(&self) -> Option<TrackMatte> {
|
||||
let ldta = self.chunk().child(b"ldta")?.bytes()?;
|
||||
let mode = MatteMode::from_code(*ldta.get(107)?)?;
|
||||
let layer = be_u32(ldta, 160).filter(|id| *id != 0);
|
||||
Some(TrackMatte { mode, layer })
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
//! Parsing the `RIFX` container into an [`AepFile`].
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::container::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS};
|
||||
use crate::container::error::AepError;
|
||||
|
||||
/// Bounds for hostile input.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
/// Deepest list nesting that is parsed (the top level is depth 1). A list or nested chunk
|
||||
/// whose children would be deeper is kept opaque instead.
|
||||
pub max_depth: usize,
|
||||
/// Most chunks a file may contain (counted across all parse attempts) before parsing fails.
|
||||
pub max_chunks: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self { max_depth: 64, max_chunks: 10_000_000 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses an `.aep` with the default [`Limits`].
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error when the input is not a well-formed `RIFX`/`Egg!` container at the top level.
|
||||
/// Odd bodies *inside* the container (a `LIST` whose content is not a chunk sequence) do not
|
||||
/// fail the parse: they are kept opaque.
|
||||
pub fn parse(data: &[u8]) -> Result<AepFile<'_>, AepError> {
|
||||
parse_with_limits(data, Limits::default())
|
||||
}
|
||||
|
||||
/// Parses an `.aep` with explicit [`Limits`].
|
||||
///
|
||||
/// # Errors
|
||||
/// See [`parse`]; also fails with [`AepError::TooManyChunks`].
|
||||
pub fn parse_with_limits(data: &[u8], limits: Limits) -> Result<AepFile<'_>, AepError> {
|
||||
if id4(data, 0) != Some(*b"RIFX") {
|
||||
return Err(AepError::NotRifx);
|
||||
}
|
||||
let declared = u64::from(be32(data, 4).ok_or(AepError::NotRifx)?);
|
||||
let form = id4(data, 8).ok_or(AepError::NotRifx)?;
|
||||
if &form != b"Egg!" {
|
||||
return Err(AepError::BadFormType(form));
|
||||
}
|
||||
let available = (data.len() as u64).saturating_sub(8);
|
||||
if declared < 4 || declared > available {
|
||||
return Err(AepError::Truncated { declared, available });
|
||||
}
|
||||
// `declared <= available < data.len()`, so the end is inside the input.
|
||||
let end = usize::try_from(declared).map_err(|_| AepError::TooLarge)?.checked_add(8).ok_or(AepError::TooLarge)?;
|
||||
let mut parser = Parser { data, limits, count: 0 };
|
||||
let chunks = parser.sequence(12, end, 1)?;
|
||||
let trailer = data.get(end..).unwrap_or(&[]);
|
||||
Ok(AepFile { chunks, trailer: Cow::Borrowed(trailer) })
|
||||
}
|
||||
|
||||
fn be32(data: &[u8], at: usize) -> Option<u32> {
|
||||
id4(data, at).map(u32::from_be_bytes)
|
||||
}
|
||||
|
||||
fn id4(data: &[u8], at: usize) -> Option<[u8; 4]> {
|
||||
let b = data.get(at..at.checked_add(4)?)?;
|
||||
Some([*b.first()?, *b.get(1)?, *b.get(2)?, *b.get(3)?])
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
data: &'a [u8],
|
||||
limits: Limits,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// Parses the sibling chunks that exactly fill `start..end`.
|
||||
fn sequence(&mut self, start: usize, end: usize, depth: usize) -> Result<Vec<Chunk<'a>>, AepError> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = start;
|
||||
while pos < end {
|
||||
let short = AepError::Malformed { offset: pos, what: "bytes left over that are too short for a chunk header" };
|
||||
let body_start = pos.checked_add(8).filter(|b| *b <= end).ok_or(short)?;
|
||||
let id = id4(self.data, pos).ok_or(AepError::Malformed { offset: pos, what: "short read" })?;
|
||||
let size = be32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize;
|
||||
let avail = end - body_start;
|
||||
if size > avail {
|
||||
return Err(AepError::ChunkTooLarge { offset: pos, size: size as u64, available: avail as u64 });
|
||||
}
|
||||
self.count = self.count.saturating_add(1);
|
||||
if self.count > self.limits.max_chunks {
|
||||
return Err(AepError::TooManyChunks);
|
||||
}
|
||||
let body_end = body_start + size;
|
||||
let body = self.body(id, body_start, body_end, depth)?;
|
||||
let mut next = body_end;
|
||||
let mut pad = None;
|
||||
if size % 2 == 1 && next < end {
|
||||
pad = Some(self.data.get(next).copied().ok_or(AepError::Malformed { offset: next, what: "missing pad byte" })?);
|
||||
next += 1;
|
||||
}
|
||||
out.push(Chunk { id, body, pad });
|
||||
pos = next;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Like [`Self::sequence`] but a structural problem yields `None` (the caller keeps bytes).
|
||||
fn tentative(&mut self, start: usize, end: usize, depth: usize) -> Result<Option<Vec<Chunk<'a>>>, AepError> {
|
||||
match self.sequence(start, end, depth) {
|
||||
Ok(v) => Ok(Some(v)),
|
||||
Err(e) if e.is_structural() => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn slice(&self, start: usize, end: usize) -> &'a [u8] {
|
||||
self.data.get(start..end).unwrap_or(&[])
|
||||
}
|
||||
|
||||
fn body(&mut self, id: [u8; 4], start: usize, end: usize, depth: usize) -> Result<Body<'a>, AepError> {
|
||||
let len = end - start;
|
||||
if id == LIST && len >= 4 {
|
||||
let list_type = id4(self.data, start).ok_or(AepError::Malformed { offset: start, what: "short read" })?;
|
||||
let opaque = |p: &Self| Body::OpaqueList { list_type, data: Cow::Borrowed(p.slice(start + 4, end)) };
|
||||
if depth >= self.limits.max_depth {
|
||||
return Ok(opaque(self));
|
||||
}
|
||||
return Ok(match self.tentative(start + 4, end, depth + 1)? {
|
||||
Some(children) => Body::List { list_type, children },
|
||||
None => opaque(self),
|
||||
});
|
||||
}
|
||||
if NESTED_IDS.contains(&id)
|
||||
&& len >= 8
|
||||
&& depth < self.limits.max_depth
|
||||
&& let Some(children) = self.tentative(start, end, depth + 1)?
|
||||
&& !children.is_empty()
|
||||
{
|
||||
return Ok(Body::Chunks(children));
|
||||
}
|
||||
Ok(Body::Data(Cow::Borrowed(self.slice(start, end))))
|
||||
}
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
//! Project settings (File ▸ Project Settings): colour depth, working space, working gamma, the two
|
||||
//! linear-light switches, the time display and the frame count start. Cases 620-634: one change
|
||||
//! each against the base project 620; every field below is the only byte (or chunk) that changes.
|
||||
|
||||
use crate::container::chunk::AepFile;
|
||||
use crate::container::footage::json_string;
|
||||
|
||||
/// The time display style (`nhed` byte 8, feet + frames byte 11, film type byte 13).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TimeDisplay {
|
||||
/// Timecode (the base, 620): byte 8 = 0.
|
||||
Timecode,
|
||||
/// Frames (629): byte 8 = 1.
|
||||
Frames,
|
||||
/// Feet + frames (633, 634): byte 8 = 1 and byte 11 = 1; byte 13 is the frames per foot,
|
||||
/// 16 for 35 mm (633) and 40 for 16 mm (634).
|
||||
FeetFrames { frames_per_foot: u8 },
|
||||
}
|
||||
|
||||
/// The working colour space (`cpid` and the JSON `Utf8` after `PwCs`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum WorkingSpace {
|
||||
/// No colour management (623): `cpid` is 16 bytes of `0xff` and the JSON is `{}`.
|
||||
None,
|
||||
/// A colour profile, named as After Effects lists it (`baseColorProfile/colorProfileName`):
|
||||
/// `sRGB IEC61966-2.1` in the base (620), `Rec.709 Gamma 2.4` in 624. The profile data next to
|
||||
/// the name is kept as stored.
|
||||
Profile(String),
|
||||
}
|
||||
|
||||
/// The project settings that are decoded.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProjectSettings {
|
||||
/// Bits per channel: 8, 16 or 32 (`nhed` byte 15 = 0 / 1 / 2: 621, 622, 620; the same byte
|
||||
/// is `nnhd` byte 24). `None` for another value.
|
||||
pub bits_per_channel: Option<u8>,
|
||||
/// The working space; `None` when the chunks are missing or unreadable.
|
||||
pub working_space: Option<WorkingSpace>,
|
||||
/// Working gamma 2.4 (`dwga` `u32` @0 = 1, 625) or 2.2 (0, 620).
|
||||
pub working_gamma_24: Option<bool>,
|
||||
/// Linearize Working Space: a 1-byte `lnrp` chunk holding 1 exists (626, 632).
|
||||
pub linearize: bool,
|
||||
/// Blend Colors Using 1.0 Gamma: a 1-byte `lnrb` chunk holding 1 exists (627, 632).
|
||||
pub blend_linear: bool,
|
||||
/// Compensate for Scene-referred Profiles (`acer` = 1 in the base, 0 in 628).
|
||||
pub scene_compensation: Option<bool>,
|
||||
/// The time display style.
|
||||
pub time_display: Option<TimeDisplay>,
|
||||
/// Frame count start: `nhed` byte 14 holds 2 for a count from 0 (620) and 1 for a count from
|
||||
/// 1 (630); this maps 2 to 0 and 1 to 1, anything else to `None`.
|
||||
pub frame_start: Option<u8>,
|
||||
}
|
||||
|
||||
impl ProjectSettings {
|
||||
/// Reads the settings from the top-level chunks.
|
||||
pub fn read(file: &AepFile<'_>) -> ProjectSettings {
|
||||
let nhed = file.chunk(b"nhed").and_then(|c| c.bytes());
|
||||
let byte = |i: usize| nhed.and_then(|b| b.get(i).copied());
|
||||
let bits_per_channel = byte(15).and_then(|v| match v {
|
||||
0 => Some(8),
|
||||
1 => Some(16),
|
||||
2 => Some(32),
|
||||
_ => None,
|
||||
});
|
||||
let time_display = match (byte(8), byte(11), byte(13)) {
|
||||
(Some(0), _, _) => Some(TimeDisplay::Timecode),
|
||||
(Some(1), Some(0), _) => Some(TimeDisplay::Frames),
|
||||
(Some(1), Some(1), Some(fpf)) => Some(TimeDisplay::FeetFrames { frames_per_foot: fpf }),
|
||||
_ => None,
|
||||
};
|
||||
let frame_start = byte(14).and_then(|v| match v {
|
||||
2 => Some(0),
|
||||
1 => Some(1),
|
||||
_ => None,
|
||||
});
|
||||
let flag = |id: &[u8; 4]| file.chunk(id).and_then(|c| c.bytes()).and_then(|b| b.first().copied()) == Some(1);
|
||||
let working_gamma_24 = file.chunk(b"dwga").and_then(|c| c.bytes()).and_then(|b| b.get(..4)).map(|b| b != [0, 0, 0, 0]);
|
||||
let scene_compensation = file.chunk(b"acer").and_then(|c| c.bytes()).and_then(|b| b.first().copied()).map(|v| v != 0);
|
||||
ProjectSettings {
|
||||
bits_per_channel,
|
||||
working_space: working_space(file),
|
||||
working_gamma_24,
|
||||
linearize: flag(b"lnrp"),
|
||||
blend_linear: flag(b"lnrb"),
|
||||
scene_compensation,
|
||||
time_display,
|
||||
frame_start,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The working space: the `Utf8` right after `PwCs`.
|
||||
fn working_space(file: &AepFile<'_>) -> Option<WorkingSpace> {
|
||||
let at = file.chunks.iter().position(|c| c.is(b"PwCs"))?;
|
||||
let json = file.chunks.get(at.checked_add(1)?).filter(|c| c.is(b"Utf8"))?.bytes()?;
|
||||
let trimmed: Vec<u8> = json.iter().copied().filter(|b| !b.is_ascii_whitespace() && *b != 0).collect();
|
||||
if trimmed == b"{}" {
|
||||
return Some(WorkingSpace::None);
|
||||
}
|
||||
// After Effects 26.2.1 saves the profile data without the name (settings-c, 902): the name is
|
||||
// then the profile's own description (ICC.1 `desc`).
|
||||
json_string(json, "colorProfileName")
|
||||
.or_else(|| json_string(json, "colorProfileData").and_then(|b| base64_decode(&b)).and_then(|icc| icc_description(&icc)))
|
||||
.map(WorkingSpace::Profile)
|
||||
}
|
||||
|
||||
/// Standard base64 (RFC 4648) with or without padding; `None` for any other character.
|
||||
fn base64_decode(text: &str) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(text.len() / 4 * 3);
|
||||
let (mut acc, mut bits) = (0u32, 0u32);
|
||||
for c in text.bytes().filter(|c| *c != b'=') {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
_ => return None,
|
||||
};
|
||||
acc = (acc << 6 | u32::from(v)) & 0x00ff_ffff;
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push(((acc >> bits) & 0xff) as u8);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The profile description (ICC.1 tag `desc`): a v2 `desc` (ASCII) or a v4 `mluc` (its first
|
||||
/// record, UTF-16BE). `None` when the profile or the tag is cut short.
|
||||
fn icc_description(icc: &[u8]) -> Option<String> {
|
||||
let be32 = |at: usize| icc.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes);
|
||||
let count = be32(128)?;
|
||||
let tag = (0..count.min(1024)).find_map(|i| {
|
||||
let at = 132usize.checked_add(usize::try_from(i).ok()?.checked_mul(12)?)?;
|
||||
(icc.get(at..at.checked_add(4)?)? == b"desc").then_some(at)
|
||||
})?;
|
||||
let off = usize::try_from(be32(tag.checked_add(4)?)?).ok()?;
|
||||
let len = usize::try_from(be32(tag.checked_add(8)?)?).ok()?;
|
||||
let body = icc.get(off..off.checked_add(len)?)?;
|
||||
let text = match body.get(..4)? {
|
||||
b"desc" => {
|
||||
let n = usize::try_from(u32::from_be_bytes(body.get(8..12)?.try_into().ok()?)).ok()?;
|
||||
let ascii = body.get(12..12usize.checked_add(n)?)?;
|
||||
String::from_utf8_lossy(ascii.split(|b| *b == 0).next().unwrap_or_default()).into_owned()
|
||||
}
|
||||
b"mluc" => {
|
||||
let n = usize::try_from(u32::from_be_bytes(body.get(20..24)?.try_into().ok()?)).ok()?;
|
||||
let at = usize::try_from(u32::from_be_bytes(body.get(24..28)?.try_into().ok()?)).ok()?;
|
||||
let units: Vec<u16> = body.get(at..at.checked_add(n)?)?.as_chunks::<2>().0.iter().map(|p| u16::from_be_bytes(*p)).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let text = text.trim_end_matches('\0').trim().to_owned();
|
||||
(!text.is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base64_decodes_with_and_without_padding() {
|
||||
assert_eq!(base64_decode("Zm9vYmFy").as_deref(), Some(&b"foobar"[..]));
|
||||
assert_eq!(base64_decode("Zm9vYmE=").as_deref(), Some(&b"fooba"[..]));
|
||||
assert_eq!(base64_decode("Zm9vYg").as_deref(), Some(&b"foob"[..]));
|
||||
assert_eq!(base64_decode("Zm9v*"), None);
|
||||
}
|
||||
|
||||
/// A profile with one tag, `desc`, holding `body`.
|
||||
fn profile(body: &[u8]) -> Vec<u8> {
|
||||
let mut icc = vec![0u8; 128];
|
||||
icc.extend_from_slice(&1u32.to_be_bytes());
|
||||
icc.extend_from_slice(b"desc");
|
||||
icc.extend_from_slice(&144u32.to_be_bytes());
|
||||
icc.extend_from_slice(&u32::try_from(body.len()).unwrap().to_be_bytes());
|
||||
icc.extend_from_slice(body);
|
||||
icc
|
||||
}
|
||||
|
||||
/// A version 2 `desc` body.
|
||||
fn desc(text: &str) -> Vec<u8> {
|
||||
let mut b = b"desc\0\0\0\0".to_vec();
|
||||
b.extend_from_slice(&u32::try_from(text.len() + 1).unwrap().to_be_bytes());
|
||||
b.extend_from_slice(text.as_bytes());
|
||||
b.push(0);
|
||||
b
|
||||
}
|
||||
|
||||
/// A version 4 `mluc` body with one record.
|
||||
fn mluc(text: &str) -> Vec<u8> {
|
||||
let units: Vec<u8> = text.encode_utf16().flat_map(u16::to_be_bytes).collect();
|
||||
let mut b = b"mluc\0\0\0\0".to_vec();
|
||||
b.extend_from_slice(&1u32.to_be_bytes());
|
||||
b.extend_from_slice(&12u32.to_be_bytes());
|
||||
b.extend_from_slice(b"enUS");
|
||||
b.extend_from_slice(&u32::try_from(units.len()).unwrap().to_be_bytes());
|
||||
b.extend_from_slice(&28u32.to_be_bytes());
|
||||
b.extend_from_slice(&units);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_description_of_a_profile_is_read() {
|
||||
assert_eq!(icc_description(&profile(&desc("Rec.709 Gamma 2.4"))).as_deref(), Some("Rec.709 Gamma 2.4"));
|
||||
assert_eq!(icc_description(&profile(&mluc("sRGB IEC61966-2.1"))).as_deref(), Some("sRGB IEC61966-2.1"));
|
||||
assert_eq!(icc_description(&profile(&desc(""))), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_or_damaged_profile_gives_no_description() {
|
||||
let icc = profile(&mluc("Rec.709 Gamma 2.4"));
|
||||
for n in 0..icc.len() {
|
||||
let mut cut = icc.get(..n).unwrap_or_default().to_vec();
|
||||
let _ = icc_description(&cut);
|
||||
cut.iter_mut().for_each(|b| *b = 0xff);
|
||||
let _ = icc_description(&cut);
|
||||
}
|
||||
assert_eq!(icc_description(&icc[..150]), None);
|
||||
assert_eq!(icc_description(&[]), None);
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
//! Shape layers: the groups under `ADBE Root Vectors Group` and the items in them.
|
||||
//!
|
||||
//! A shape layer (layer type 4) holds `tdgp[ADBE Root Vectors Group]` with one `ADBE Vector Group`
|
||||
//! per shape group; the group holds `ADBE Vectors Group` (the contents, in z-order) and
|
||||
//! `ADBE Vector Transform Group` (the group transform, only the properties that differ from the
|
||||
//! default). Only the items and properties whose layout was verified are decoded; anything else is
|
||||
//! listed as [`ShapeItem::Other`] with its match name.
|
||||
//!
|
||||
//! Colours are stored as ARGB doubles 0..255 and returned as fractions. Sizes, positions and path
|
||||
//! points are in pixels relative to the layer origin.
|
||||
|
||||
use crate::container::masks::ShapePath;
|
||||
use crate::container::typed::{Layer, PropGroup, PropNode, Property};
|
||||
use crate::container::values::{Tracked, read, read_opt};
|
||||
|
||||
/// The stroke line cap (`ADBE Vector Stroke Line Cap`, stored as a double; butt is the default and
|
||||
/// is not stored).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum StrokeCap {
|
||||
/// `1`
|
||||
Butt,
|
||||
/// `2`
|
||||
Round,
|
||||
/// Any other value (projecting square was not sampled).
|
||||
Other(i64),
|
||||
}
|
||||
|
||||
/// The stroke line join (`ADBE Vector Stroke Line Join`; miter is the default and is not stored).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum StrokeJoin {
|
||||
/// `1`
|
||||
Miter,
|
||||
/// `2`
|
||||
Round,
|
||||
/// Any other value (bevel was not sampled).
|
||||
Other(i64),
|
||||
}
|
||||
|
||||
/// A stroke item.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Stroke {
|
||||
/// The color as `[A, R, G, B]` fractions; `None` while the property is absent (its default is
|
||||
/// not verified).
|
||||
pub color: Option<Tracked<[f64; 4]>>,
|
||||
/// The width in pixels; `None` while absent.
|
||||
pub width: Option<Tracked<f64>>,
|
||||
pub cap: Tracked<StrokeCap>,
|
||||
pub join: Tracked<StrokeJoin>,
|
||||
/// The miter limit; after the join was touched it is stored in its default state (4).
|
||||
pub miter_limit: Option<Tracked<f64>>,
|
||||
}
|
||||
|
||||
/// An item of a shape group's contents.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ShapeItem {
|
||||
/// `ADBE Vector Shape - Rect`: the rectangle path.
|
||||
Rect { name: Option<String>, size: Option<Tracked<[f64; 2]>> },
|
||||
/// `ADBE Vector Shape - Group`: a bezier path (one shape per keyframe), points in pixels.
|
||||
Path { name: Option<String>, paths: Vec<ShapePath> },
|
||||
/// `ADBE Vector Graphic - Fill`: the color as `[A, R, G, B]` fractions.
|
||||
Fill { name: Option<String>, color: Option<Tracked<[f64; 4]>> },
|
||||
/// `ADBE Vector Graphic - Stroke`
|
||||
Stroke { name: Option<String>, stroke: Stroke },
|
||||
/// `ADBE Vector Graphic - G-Fill`: the start and end point of the gradient in pixels (the
|
||||
/// gradient type and the colour stops are not stored while they are at After Effects' default
|
||||
/// and their encoding is not known).
|
||||
GradientFill { name: Option<String>, start: Option<Tracked<[f64; 2]>>, end: Option<Tracked<[f64; 2]>> },
|
||||
/// `ADBE Vector Filter - RC`: rounded corners, the radius in pixels.
|
||||
RoundCorners { name: Option<String>, radius: Option<Tracked<f64>> },
|
||||
/// Any other item (ellipse, polystar, trim, repeater, ...: not ported).
|
||||
Other { match_name: String, name: Option<String> },
|
||||
}
|
||||
|
||||
/// The polystar type (`ADBE Vector Star Type`; star is the default and is not stored).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PolystarType {
|
||||
/// `1`
|
||||
Star,
|
||||
/// `2`
|
||||
Polygon,
|
||||
/// Any other value.
|
||||
Other(i64),
|
||||
}
|
||||
|
||||
/// The gradient type (`ADBE Vector Grad Type`; linear is the default and is not stored).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum GradientType {
|
||||
/// `1`
|
||||
Linear,
|
||||
/// `2`
|
||||
Radial,
|
||||
/// Any other value.
|
||||
Other(i64),
|
||||
}
|
||||
|
||||
/// Fields of shape items that [`ShapeItem`] does not carry, in the order of the group's items.
|
||||
/// `item_index` is the index into [`ShapeGroup::items`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ShapeDetail {
|
||||
/// `ADBE Vector Shape - Star` (listed as [`ShapeItem::Other`]). The defaults After Effects
|
||||
/// applies when a property is absent are star, outer radius 100, inner radius 50, so a default
|
||||
/// star has no property at all (330); a polygon stores the type and writes the inner radius and
|
||||
/// the inner roundness (`ADBE Vector Star Inner Roundess`, After Effects' own spelling) in their
|
||||
/// default state (331).
|
||||
Polystar {
|
||||
item_index: usize,
|
||||
star_type: Tracked<PolystarType>,
|
||||
outer_radius: Tracked<f64>,
|
||||
inner_radius: Tracked<f64>,
|
||||
/// `None` unless the roundness is stored.
|
||||
inner_roundness: Option<Tracked<f64>>,
|
||||
},
|
||||
/// `ADBE Vector Graphic - G-Fill`: the gradient type and, for a radial gradient, the highlight
|
||||
/// length and angle (written as stored records with value 0 when the type is radial, 332).
|
||||
Gradient { item_index: usize, gradient_type: Tracked<GradientType>, highlight_length: Option<Tracked<f64>>, highlight_angle: Option<Tracked<f64>> },
|
||||
/// The `ADBE Vector Rect Position` of a rectangle path (absent = `[0, 0]`), in pixels (333).
|
||||
RectPosition { item_index: usize, position: Tracked<[f64; 2]> },
|
||||
}
|
||||
|
||||
/// A shape group (`ADBE Vector Group`).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ShapeGroup {
|
||||
/// The group's name (`Group 1`).
|
||||
pub name: Option<String>,
|
||||
/// The group transform's Position in pixels; absent = `[0, 0]`.
|
||||
pub position: Tracked<[f64; 2]>,
|
||||
/// The contents in z-order (top first, as in the file). Two siblings with the same match name
|
||||
/// (two rectangles) are two items.
|
||||
pub items: Vec<ShapeItem>,
|
||||
/// More fields of the items (polystar, gradient type, rectangle position), see [`ShapeDetail`].
|
||||
pub details: Vec<ShapeDetail>,
|
||||
}
|
||||
|
||||
const COLOR_SCALE: f64 = 1.0 / 255.0;
|
||||
|
||||
fn number(group: &PropGroup<'_, '_>, name: &str) -> Option<Tracked<f64>> {
|
||||
read_opt::<1>(group, name, 1.0).map(|t| Tracked { value: t.value[0], source: t.source })
|
||||
}
|
||||
|
||||
fn paths_of(group: &PropGroup<'_, '_>) -> Vec<ShapePath> {
|
||||
let Some(PropNode::Other(oms)) = group.get("ADBE Vector Shape") else { return Vec::new() };
|
||||
let Some(omks) = oms.child_list(b"omks") else { return Vec::new() };
|
||||
omks.children().iter().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect()
|
||||
}
|
||||
|
||||
fn item(match_name: String, group: &PropGroup<'_, '_>) -> ShapeItem {
|
||||
let name = group.user_name();
|
||||
match match_name.as_str() {
|
||||
"ADBE Vector Shape - Rect" => ShapeItem::Rect { name, size: read_opt::<2>(group, "ADBE Vector Rect Size", 1.0) },
|
||||
"ADBE Vector Shape - Group" => ShapeItem::Path { name, paths: paths_of(group) },
|
||||
"ADBE Vector Graphic - Fill" => ShapeItem::Fill { name, color: read_opt::<4>(group, "ADBE Vector Fill Color", COLOR_SCALE) },
|
||||
"ADBE Vector Graphic - Stroke" => {
|
||||
let cap = read(group, "ADBE Vector Stroke Line Cap", [1.0], 1.0);
|
||||
let join = read(group, "ADBE Vector Stroke Line Join", [1.0], 1.0);
|
||||
let stroke = Stroke {
|
||||
color: read_opt::<4>(group, "ADBE Vector Stroke Color", COLOR_SCALE),
|
||||
width: number(group, "ADBE Vector Stroke Width"),
|
||||
cap: Tracked {
|
||||
value: match cap.value[0].round() as i64 {
|
||||
1 => StrokeCap::Butt,
|
||||
2 => StrokeCap::Round,
|
||||
other => StrokeCap::Other(other),
|
||||
},
|
||||
source: cap.source,
|
||||
},
|
||||
join: Tracked {
|
||||
value: match join.value[0].round() as i64 {
|
||||
1 => StrokeJoin::Miter,
|
||||
2 => StrokeJoin::Round,
|
||||
other => StrokeJoin::Other(other),
|
||||
},
|
||||
source: join.source,
|
||||
},
|
||||
miter_limit: number(group, "ADBE Vector Stroke Miter Limit"),
|
||||
};
|
||||
ShapeItem::Stroke { name, stroke }
|
||||
}
|
||||
"ADBE Vector Graphic - G-Fill" => ShapeItem::GradientFill {
|
||||
name,
|
||||
start: read_opt::<2>(group, "ADBE Vector Grad Start Pt", 1.0),
|
||||
end: read_opt::<2>(group, "ADBE Vector Grad End Pt", 1.0),
|
||||
},
|
||||
"ADBE Vector Filter - RC" => ShapeItem::RoundCorners { name, radius: number(group, "ADBE Vector RoundCorner Radius") },
|
||||
_ => ShapeItem::Other { match_name, name },
|
||||
}
|
||||
}
|
||||
|
||||
fn detail(match_name: &str, group: &PropGroup<'_, '_>, item_index: usize) -> Option<ShapeDetail> {
|
||||
let tracked = |name: &str, default: f64| {
|
||||
let t = read(group, name, [default], 1.0);
|
||||
Tracked { value: t.value[0], source: t.source }
|
||||
};
|
||||
match match_name {
|
||||
"ADBE Vector Shape - Star" => {
|
||||
let star_type = tracked("ADBE Vector Star Type", 1.0);
|
||||
Some(ShapeDetail::Polystar {
|
||||
item_index,
|
||||
star_type: Tracked {
|
||||
value: match star_type.value.round() as i64 {
|
||||
1 => PolystarType::Star,
|
||||
2 => PolystarType::Polygon,
|
||||
other => PolystarType::Other(other),
|
||||
},
|
||||
source: star_type.source,
|
||||
},
|
||||
outer_radius: tracked("ADBE Vector Star Outer Radius", 100.0),
|
||||
inner_radius: tracked("ADBE Vector Star Inner Radius", 50.0),
|
||||
inner_roundness: number(group, "ADBE Vector Star Inner Roundess"),
|
||||
})
|
||||
}
|
||||
"ADBE Vector Graphic - G-Fill" => {
|
||||
let gradient_type = tracked("ADBE Vector Grad Type", 1.0);
|
||||
Some(ShapeDetail::Gradient {
|
||||
item_index,
|
||||
gradient_type: Tracked {
|
||||
value: match gradient_type.value.round() as i64 {
|
||||
1 => GradientType::Linear,
|
||||
2 => GradientType::Radial,
|
||||
other => GradientType::Other(other),
|
||||
},
|
||||
source: gradient_type.source,
|
||||
},
|
||||
highlight_length: number(group, "ADBE Vector Grad HiLite Length"),
|
||||
highlight_angle: number(group, "ADBE Vector Grad HiLite Angle"),
|
||||
})
|
||||
}
|
||||
"ADBE Vector Shape - Rect" => Some(ShapeDetail::RectPosition { item_index, position: read(group, "ADBE Vector Rect Position", [0.0, 0.0], 1.0) }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn group_of(group: &PropGroup<'_, '_>) -> ShapeGroup {
|
||||
let (mut items, mut details) = (Vec::new(), Vec::new());
|
||||
if let Some(PropNode::Group(contents)) = group.get("ADBE Vectors Group") {
|
||||
for e in contents.entries() {
|
||||
if let PropNode::Group(g) = e.node {
|
||||
details.extend(detail(&e.match_name, &g, items.len()));
|
||||
items.push(item(e.match_name, &g));
|
||||
}
|
||||
}
|
||||
}
|
||||
let position = match group.get("ADBE Vector Transform Group") {
|
||||
Some(PropNode::Group(t)) => read(&t, "ADBE Vector Position", [0.0, 0.0], 1.0),
|
||||
_ => Tracked { value: [0.0, 0.0], source: crate::container::values::ValueSource::Default },
|
||||
};
|
||||
ShapeGroup { name: group.user_name(), position, items, details }
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The shape groups of a shape layer (`ADBE Root Vectors Group`), top group first.
|
||||
pub fn shape_groups(&self) -> Vec<ShapeGroup> {
|
||||
let Some(root) = self.properties() else { return Vec::new() };
|
||||
let Some(PropNode::Group(vectors)) = root.get("ADBE Root Vectors Group") else { return Vec::new() };
|
||||
vectors
|
||||
.entries()
|
||||
.into_iter()
|
||||
.filter(|e| e.match_name == "ADBE Vector Group")
|
||||
.filter_map(|e| match e.node {
|
||||
PropNode::Group(g) => Some(group_of(&g)),
|
||||
PropNode::Property(_) | PropNode::Other(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Property<'f, 'a> {
|
||||
/// The ARGB fractions of a static colour property (4 components stored as doubles 0..255).
|
||||
pub fn color_argb(&self) -> Option<[f64; 4]> {
|
||||
let v = self.static_value()?;
|
||||
let [a, r, g, b] = *v.as_slice().first_chunk::<4>()?;
|
||||
Some([a / 255.0, r / 255.0, g / 255.0, b / 255.0])
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! The layer-style table of the importer (`crate::import`): the After Effects layer styles (`ADBE Layer Styles`, docs
|
||||
//! The layer-style table shared by the importer (`crate::import`) and the exporter
|
||||
//! (`crate::export`): the After Effects layer styles (`ADBE Layer Styles`, docs
|
||||
//! `aep-format.md` 3.14) and their parameters, the EffectCraft style and parameter each maps to,
|
||||
//! the unit conversion and After Effects' default as it would be stored.
|
||||
//!
|
||||
@@ -321,6 +322,11 @@ pub fn by_ae(prefix: &str) -> Option<&'static StyleMap> {
|
||||
STYLES.iter().find(|s| s.ae == prefix)
|
||||
}
|
||||
|
||||
/// The style with this EffectCraft id.
|
||||
pub fn by_ec(id: &str) -> Option<&'static StyleMap> {
|
||||
STYLES.iter().find(|s| s.ec == id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,539 +0,0 @@
|
||||
//! A small typed view over the chunk tree: project items, compositions, layers, the property
|
||||
//! tree and keyframe lists. The field decoders for headers, values, keyframes, effects, masks, text,
|
||||
//! markers and footage are in the sibling modules and extend these types.
|
||||
//!
|
||||
//! Only facts that were established from our own one-change-per-file corpus and are checked by
|
||||
//! tests against it are decoded (see `docs/aep-format.md` for the evidence). Everything else
|
||||
//! stays reachable through the raw [`Chunk`] tree. Views borrow the file and never fail loudly:
|
||||
//! a chunk that does not have the expected shape yields `None` or is skipped.
|
||||
|
||||
use crate::container::bytes::{be_f64, be_u16, be_u32, text, until_nul};
|
||||
use crate::container::chunk::{AepFile, Chunk};
|
||||
|
||||
/// The name a user gave a property or group: the `Utf8` inside its `tdsn` chunk. `None` for the
|
||||
/// sentinel `-_0_/-` ("no custom name") and for empty names.
|
||||
pub(crate) fn user_name(chunk: &Chunk<'_>) -> Option<String> {
|
||||
let name = chunk.child(b"tdsn")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text)?;
|
||||
(!name.is_empty() && name != "-_0_/-").then_some(name)
|
||||
}
|
||||
|
||||
/// The content of a `Utf8` child as text (not trimmed).
|
||||
pub(crate) fn utf8_child(chunk: &Chunk<'_>) -> Option<String> {
|
||||
chunk.child(b"Utf8").and_then(Chunk::bytes).map(text)
|
||||
}
|
||||
|
||||
/// The project: the top-level `LIST Fold`, which holds the project items.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Project<'f, 'a> {
|
||||
pub(crate) fold: &'f Chunk<'a>,
|
||||
/// The top-level `LIST EfdG` (project-level effect definitions), when there is one.
|
||||
pub(crate) effect_defs: Option<&'f Chunk<'a>>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Project<'f, 'a> {
|
||||
/// The project view of a file, or `None` when it has no `LIST Fold`.
|
||||
pub fn new(file: &'f AepFile<'a>) -> Option<Self> {
|
||||
file.list(b"Fold").map(|fold| Self { fold, effect_defs: file.list(b"EfdG") })
|
||||
}
|
||||
|
||||
/// The top-level items (the project panel's root; folders hold their children, see
|
||||
/// [`Item::children`]).
|
||||
pub fn items(&self) -> impl Iterator<Item = Item<'f, 'a>> + 'f {
|
||||
self.fold.children().iter().filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk })
|
||||
}
|
||||
|
||||
/// True when the `LIST Fold` could not be read as chunks (damaged): its items cannot be seen.
|
||||
pub fn items_unreadable(&self) -> bool {
|
||||
self.fold.is_opaque_list()
|
||||
}
|
||||
|
||||
/// Every item including those inside folders, depth-first, without recursion.
|
||||
pub fn all_items(&self) -> Vec<Item<'f, 'a>> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack: Vec<Item<'f, 'a>> = self.items().collect();
|
||||
stack.reverse();
|
||||
while let Some(item) = stack.pop() {
|
||||
let mut kids: Vec<Item<'f, 'a>> = item.children().collect();
|
||||
kids.reverse();
|
||||
out.push(item);
|
||||
stack.extend(kids);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// What a project item is (the first 16-bit word of its `idta` chunk).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ItemKind {
|
||||
/// `1`
|
||||
Folder,
|
||||
/// `4`
|
||||
Composition,
|
||||
/// `7`
|
||||
Footage,
|
||||
/// Any other value.
|
||||
Other(u16),
|
||||
}
|
||||
|
||||
/// A project item (`LIST Item`).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Item<'f, 'a> {
|
||||
pub(crate) chunk: &'f Chunk<'a>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Item<'f, 'a> {
|
||||
/// The underlying chunk.
|
||||
pub fn chunk(&self) -> &'f Chunk<'a> {
|
||||
self.chunk
|
||||
}
|
||||
|
||||
/// The item kind, from `idta`.
|
||||
pub fn kind(&self) -> Option<ItemKind> {
|
||||
let idta = self.chunk.child(b"idta")?.bytes()?;
|
||||
Some(match be_u16(idta, 0)? {
|
||||
1 => ItemKind::Folder,
|
||||
4 => ItemKind::Composition,
|
||||
7 => ItemKind::Footage,
|
||||
other => ItemKind::Other(other),
|
||||
})
|
||||
}
|
||||
|
||||
/// The item name (the `Utf8` child). `None` when absent or empty: a solid's footage item
|
||||
/// stores no name there.
|
||||
pub fn name(&self) -> Option<String> {
|
||||
utf8_child(self.chunk).filter(|n| !n.is_empty())
|
||||
}
|
||||
|
||||
/// The items inside a folder (`LIST Sfdr`).
|
||||
pub fn children(&self) -> impl Iterator<Item = Item<'f, 'a>> + 'f {
|
||||
self.chunk.child_list(b"Sfdr").into_iter().flat_map(|sfdr| sfdr.children().iter()).filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk })
|
||||
}
|
||||
|
||||
/// Whether the item has the `LIST Sfdr` of a folder's contents (After Effects writes an empty
|
||||
/// one for an empty folder).
|
||||
pub fn has_folder_contents(&self) -> bool {
|
||||
self.chunk.child_list(b"Sfdr").is_some()
|
||||
}
|
||||
|
||||
/// True when the folder's `LIST Sfdr` is there but could not be read as chunks (damaged).
|
||||
pub fn folder_contents_unreadable(&self) -> bool {
|
||||
self.chunk.child_list(b"Sfdr").is_some_and(Chunk::is_opaque_list)
|
||||
}
|
||||
|
||||
/// The composition view when this item has composition data (`cdta`).
|
||||
pub fn comp(&self) -> Option<Comp<'f, 'a>> {
|
||||
self.chunk.child(b"cdta").map(|_| Comp { item: self.chunk })
|
||||
}
|
||||
}
|
||||
|
||||
/// The time base of a composition: one frame lasts `frame_duration` units and a second has
|
||||
/// `timescale` units. Keyframe times are counted in these units.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TimeBase {
|
||||
pub frame_duration: u32,
|
||||
pub timescale: u32,
|
||||
}
|
||||
|
||||
impl TimeBase {
|
||||
/// Frames per second (`timescale / frame_duration`), `None` for a zero duration.
|
||||
pub fn frame_rate(&self) -> Option<f64> {
|
||||
(self.frame_duration != 0).then(|| f64::from(self.timescale) / f64::from(self.frame_duration))
|
||||
}
|
||||
|
||||
/// Converts time units to seconds, `None` for a zero timescale.
|
||||
pub fn seconds(&self, units: i32) -> Option<f64> {
|
||||
(self.timescale != 0).then(|| f64::from(units) / f64::from(self.timescale))
|
||||
}
|
||||
}
|
||||
|
||||
/// A composition item (an [`Item`] with `cdta`).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Comp<'f, 'a> {
|
||||
pub(crate) item: &'f Chunk<'a>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Comp<'f, 'a> {
|
||||
/// The time base from `cdta` (`u32` at byte 4 is the frame duration, `u32` at byte 8 the
|
||||
/// timescale).
|
||||
pub fn time_base(&self) -> Option<TimeBase> {
|
||||
let cdta = self.item.child(b"cdta")?.bytes()?;
|
||||
Some(TimeBase { frame_duration: be_u32(cdta, 4)?, timescale: be_u32(cdta, 8)? })
|
||||
}
|
||||
|
||||
/// The layers, top layer first (`LIST Layr`; the `DLay`/`SLay`/`CLay`/`SecL` lists next to
|
||||
/// them are not layers).
|
||||
pub fn layers(&self) -> impl Iterator<Item = Layer<'f, 'a>> + 'f {
|
||||
self.item.children().iter().filter(|c| c.is_list(b"Layr")).map(|chunk| Layer { chunk })
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer (`LIST Layr`).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Layer<'f, 'a> {
|
||||
pub(crate) chunk: &'f Chunk<'a>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The underlying chunk.
|
||||
pub fn chunk(&self) -> &'f Chunk<'a> {
|
||||
self.chunk
|
||||
}
|
||||
|
||||
/// The layer name when it was set (the `Utf8` child); `None` when empty, in which case the
|
||||
/// layer shows its source's name.
|
||||
pub fn name(&self) -> Option<String> {
|
||||
utf8_child(self.chunk).filter(|n| !n.is_empty())
|
||||
}
|
||||
|
||||
/// The 3D layer switch: bit `0x04` of byte 38 of `ldta`.
|
||||
pub fn is_three_d(&self) -> Option<bool> {
|
||||
let ldta = self.chunk.child(b"ldta")?.bytes()?;
|
||||
Some(ldta.get(38)? & 0x04 != 0)
|
||||
}
|
||||
|
||||
/// The root of the layer's property tree.
|
||||
pub fn properties(&self) -> Option<PropGroup<'f, 'a>> {
|
||||
self.chunk.child_list(b"tdgp").map(|chunk| PropGroup { chunk })
|
||||
}
|
||||
}
|
||||
|
||||
/// A node of the property tree.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum PropNode<'f, 'a> {
|
||||
/// A property group (`LIST tdgp`).
|
||||
Group(PropGroup<'f, 'a>),
|
||||
/// A property (`LIST tdbs`).
|
||||
Property(Property<'f, 'a>),
|
||||
/// Any other list that follows a match name (observed: `otst`, the effect instance `sspc`).
|
||||
Other(&'f Chunk<'a>),
|
||||
}
|
||||
|
||||
impl<'f, 'a> PropNode<'f, 'a> {
|
||||
/// The node a `LIST` after a match name is.
|
||||
fn of(c: &'f Chunk<'a>) -> Self {
|
||||
if c.is_list(b"tdgp") {
|
||||
PropNode::Group(PropGroup { chunk: c })
|
||||
} else if c.is_list(b"tdbs") {
|
||||
PropNode::Property(Property { chunk: c })
|
||||
} else {
|
||||
PropNode::Other(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A match name with the node it names.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PropEntry<'f, 'a> {
|
||||
pub match_name: String,
|
||||
pub node: PropNode<'f, 'a>,
|
||||
}
|
||||
|
||||
/// A property group (`LIST tdgp`): after its `tdsb` and `tdsn` chunks come pairs of a `tdmn`
|
||||
/// (the 40-byte NUL-padded ASCII match name) and the list it names; a `tdmn` named
|
||||
/// `ADBE Group End` closes the group and names nothing.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PropGroup<'f, 'a> {
|
||||
pub(crate) chunk: &'f Chunk<'a>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> PropGroup<'f, 'a> {
|
||||
/// A group view of a `LIST tdgp` chunk.
|
||||
pub fn from_chunk(chunk: &'f Chunk<'a>) -> Option<Self> {
|
||||
chunk.is_list(b"tdgp").then_some(Self { chunk })
|
||||
}
|
||||
|
||||
/// The underlying chunk.
|
||||
pub fn chunk(&self) -> &'f Chunk<'a> {
|
||||
self.chunk
|
||||
}
|
||||
|
||||
/// The name the user gave the group (e.g. `Mask 1`, `Group 1`); `None` when it has none.
|
||||
pub fn user_name(&self) -> Option<String> {
|
||||
user_name(self.chunk)
|
||||
}
|
||||
|
||||
/// The group's flags (`tdsb`, a `u32`).
|
||||
pub fn flags(&self) -> Option<u32> {
|
||||
be_u32(self.chunk.child(b"tdsb")?.bytes()?, 0)
|
||||
}
|
||||
|
||||
/// The entries in file order.
|
||||
pub fn entries(&self) -> Vec<PropEntry<'f, 'a>> {
|
||||
let mut out = Vec::new();
|
||||
let mut pending: Option<String> = None;
|
||||
for c in self.chunk.children() {
|
||||
if c.is(b"tdmn") {
|
||||
pending = c.bytes().map(match_name);
|
||||
} else if c.id == crate::container::chunk::LIST
|
||||
&& let Some(name) = pending.take()
|
||||
{
|
||||
out.push(PropEntry { match_name: name, node: PropNode::of(c) });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The match names of the entries, in file order.
|
||||
pub fn names(&self) -> Vec<String> {
|
||||
self.entries().into_iter().map(|e| e.match_name).collect()
|
||||
}
|
||||
|
||||
/// The first entry with this match name. One pass that stops at it, without collecting the
|
||||
/// group's entries (callers look names up in loops).
|
||||
pub fn get(&self, name: &str) -> Option<PropNode<'f, 'a>> {
|
||||
let mut pending: Option<&[u8]> = None;
|
||||
for c in self.chunk.children() {
|
||||
if c.is(b"tdmn") {
|
||||
pending = c.bytes();
|
||||
} else if c.id == crate::container::chunk::LIST
|
||||
&& let Some(body) = pending.take()
|
||||
&& match_name(body) == name
|
||||
{
|
||||
return Some(PropNode::of(c));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Follows a path of match names through nested groups.
|
||||
pub fn find(&self, path: &[&str]) -> Option<PropNode<'f, 'a>> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
let node = self.get(first)?;
|
||||
if rest.is_empty() {
|
||||
return Some(node);
|
||||
}
|
||||
match node {
|
||||
PropNode::Group(g) => g.find(rest),
|
||||
PropNode::Property(_) | PropNode::Other(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The match name in a `tdmn` body: ASCII up to the first NUL.
|
||||
fn match_name(body: &[u8]) -> String {
|
||||
text(until_nul(body))
|
||||
}
|
||||
|
||||
/// A property (`LIST tdbs`): `tdsb`, `tdsn`, the 124-byte header `tdb4`, then either the static
|
||||
/// value `cdat` or a keyframe `LIST list`.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Property<'f, 'a> {
|
||||
pub(crate) chunk: &'f Chunk<'a>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Property<'f, 'a> {
|
||||
/// A property view of a `LIST tdbs` chunk.
|
||||
pub fn from_chunk(chunk: &'f Chunk<'a>) -> Option<Self> {
|
||||
chunk.is_list(b"tdbs").then_some(Self { chunk })
|
||||
}
|
||||
|
||||
/// The underlying chunk.
|
||||
pub fn chunk(&self) -> &'f Chunk<'a> {
|
||||
self.chunk
|
||||
}
|
||||
|
||||
/// The name the user gave the property; `None` when it has none.
|
||||
pub fn user_name(&self) -> Option<String> {
|
||||
user_name(self.chunk)
|
||||
}
|
||||
|
||||
/// The raw 124-byte `tdb4` header.
|
||||
pub fn header(&self) -> Option<&'f [u8]> {
|
||||
self.chunk.child(b"tdb4")?.bytes()
|
||||
}
|
||||
|
||||
/// The number of value components: byte 3 of `tdb4`.
|
||||
pub fn dims(&self) -> Option<u8> {
|
||||
self.header()?.get(3).copied()
|
||||
}
|
||||
|
||||
/// True when the property has keyframes, i.e. its value is a `LIST list` instead of `cdat`.
|
||||
/// `tdb4` byte 68 is 1 in exactly these properties.
|
||||
pub fn is_animated(&self) -> bool {
|
||||
self.chunk.child_list(b"list").is_some()
|
||||
}
|
||||
|
||||
/// The static value: the first `dims` big-endian `f64` of `cdat`. `None` for animated
|
||||
/// properties and for values that are not `f64` arrays.
|
||||
pub fn static_value(&self) -> Option<Vec<f64>> {
|
||||
let dims = usize::from(self.dims()?);
|
||||
let cdat = self.chunk.child(b"cdat")?.bytes()?;
|
||||
(0..dims).map(|i| be_f64(cdat, i.checked_mul(8)?)).collect()
|
||||
}
|
||||
|
||||
/// The keyframe list of an animated property, with the record layout the property header
|
||||
/// selects (`tdb4` byte 3 = components, byte 7 non-zero = spatial template, unless the record
|
||||
/// size tells).
|
||||
pub fn keys(&self) -> Option<KeyList<'f>> {
|
||||
let list = KeyList::from_chunk(self.chunk.child_list(b"list")?)?;
|
||||
let header = self.header();
|
||||
// The record size decides where the two templates differ in size: a shape colour's keys
|
||||
// are spatial (152 bytes for 4 components) although its `tdb4` byte 7 is 0 (854). For 3
|
||||
// components both templates are 128 bytes; byte 7 decides.
|
||||
let size = list.header.record_size;
|
||||
let layout = header.and_then(|h| {
|
||||
let components = *h.get(3)?;
|
||||
let n = u32::from(components);
|
||||
let (spatial_size, plain_size) = (56 + 24 * n, 8 + 40 * n);
|
||||
let spatial = if size == spatial_size && size != plain_size {
|
||||
true
|
||||
} else if size == plain_size && size != spatial_size {
|
||||
false
|
||||
} else {
|
||||
*h.get(7)? != 0
|
||||
};
|
||||
Some(KeyLayout { components, spatial })
|
||||
});
|
||||
Some(KeyList { layout, ..list })
|
||||
}
|
||||
}
|
||||
|
||||
/// The header `lhd3` of a `LIST list`: 13 big-endian `u32`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ListHeader {
|
||||
/// Word 0, `0x00d00bee` in every list.
|
||||
pub magic: u32,
|
||||
/// Word 2: the number of records.
|
||||
pub count: u32,
|
||||
/// Word 4: the size of one record in bytes.
|
||||
pub record_size: u32,
|
||||
/// All 13 words.
|
||||
pub words: [u32; 13],
|
||||
}
|
||||
|
||||
impl ListHeader {
|
||||
/// Parses a 52-byte `lhd3` body.
|
||||
pub fn parse(body: &[u8]) -> Option<Self> {
|
||||
if body.len() != 52 {
|
||||
return None;
|
||||
}
|
||||
let mut words = [0u32; 13];
|
||||
for (i, w) in words.iter_mut().enumerate() {
|
||||
*w = be_u32(body, i * 4)?;
|
||||
}
|
||||
Some(Self { magic: words[0], count: words[2], record_size: words[4], words })
|
||||
}
|
||||
}
|
||||
|
||||
/// A `LIST list`: `lhd3` and `ldat`, where `len(ldat) == count * record_size`.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct KeyList<'f> {
|
||||
pub header: ListHeader,
|
||||
ldat: &'f [u8],
|
||||
layout: Option<KeyLayout>,
|
||||
}
|
||||
|
||||
/// What the property header says about its keyframe records: how many value components each
|
||||
/// record holds and which of the two record templates applies (see [`KeyframeKind`]).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct KeyLayout {
|
||||
/// `tdb4` byte 3.
|
||||
pub components: u8,
|
||||
/// `tdb4` byte 7 is non-zero: the spatial template (Position, colours) instead of the plain one.
|
||||
pub spatial: bool,
|
||||
}
|
||||
|
||||
impl<'f> KeyList<'f> {
|
||||
/// A view of a `LIST list` chunk. `None` when `lhd3` is not 52 bytes or `ldat` is not exactly
|
||||
/// `count * record_size` bytes (a list without `ldat` must have no records).
|
||||
pub fn from_chunk<'a>(chunk: &'f Chunk<'a>) -> Option<Self> {
|
||||
if !chunk.is_list(b"list") {
|
||||
return None;
|
||||
}
|
||||
let header = ListHeader::parse(chunk.child(b"lhd3")?.bytes()?)?;
|
||||
let ldat: &[u8] = chunk.child(b"ldat").and_then(Chunk::bytes).unwrap_or(&[]);
|
||||
let expected = usize::try_from(header.count).ok()?.checked_mul(usize::try_from(header.record_size).ok()?)?;
|
||||
(ldat.len() == expected).then_some(Self { header, ldat, layout: None })
|
||||
}
|
||||
|
||||
/// The number of records actually present (what [`Self::records`] yields). Not the declared
|
||||
/// count: a list with record size 0 and no data passes [`Self::from_chunk`] whatever count it
|
||||
/// declares, and a caller sizing an allocation by that count would abort.
|
||||
pub fn len(&self) -> usize {
|
||||
self.records().count()
|
||||
}
|
||||
|
||||
/// True when there are no records.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.ldat.is_empty()
|
||||
}
|
||||
|
||||
/// The records as byte slices.
|
||||
pub fn records(&self) -> impl Iterator<Item = &'f [u8]> {
|
||||
let size = usize::try_from(self.header.record_size).unwrap_or(0);
|
||||
self.ldat.chunks_exact(size.max(1))
|
||||
}
|
||||
|
||||
/// The record layout from the property header, `None` for a list that does not belong to a
|
||||
/// property (the point list of a path).
|
||||
pub fn layout(&self) -> Option<KeyLayout> {
|
||||
self.layout
|
||||
}
|
||||
|
||||
/// The records of a keyframe list as [`Keyframe`]s.
|
||||
pub fn keyframes(&self) -> impl Iterator<Item = Keyframe<'f>> {
|
||||
let layout = self.layout;
|
||||
self.records().map(move |record| Keyframe { record, layout })
|
||||
}
|
||||
}
|
||||
|
||||
/// One keyframe record: the time is the `i32` at byte 0, in the composition's time units
|
||||
/// ([`TimeBase`]).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Keyframe<'f> {
|
||||
pub(crate) record: &'f [u8],
|
||||
pub(crate) layout: Option<KeyLayout>,
|
||||
}
|
||||
|
||||
impl<'f> Keyframe<'f> {
|
||||
/// The whole record.
|
||||
pub fn raw(&self) -> &'f [u8] {
|
||||
self.record
|
||||
}
|
||||
|
||||
/// The keyframe time in time units (layer time).
|
||||
pub fn time_units(&self) -> Option<i32> {
|
||||
be_u32(self.record, 0).map(|u| i32::from_be_bytes(u.to_be_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn key_list(count: u32, record_size: u32, ldat: &[u8]) -> Chunk<'static> {
|
||||
let mut lhd3 = vec![0u8; 52];
|
||||
lhd3[8..12].copy_from_slice(&count.to_be_bytes());
|
||||
lhd3[16..20].copy_from_slice(&record_size.to_be_bytes());
|
||||
Chunk::list(*b"list", vec![Chunk::data(*b"lhd3", lhd3), Chunk::data(*b"ldat", ldat.to_vec())])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_list_counts_the_records_it_holds() {
|
||||
let two = key_list(2, 4, &[0; 8]);
|
||||
assert_eq!(KeyList::from_chunk(&two).map(|l| l.len()), Some(2));
|
||||
// Record size 0 with no data passes the size check whatever count is declared; the length
|
||||
// is what is there, so no caller sizes an allocation by 4 billion records.
|
||||
let hostile = key_list(u32::MAX, 0, &[]);
|
||||
let list = KeyList::from_chunk(&hostile).expect("a well-formed empty list");
|
||||
assert_eq!((list.len(), list.is_empty(), list.records().count()), (0, true, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_finds_the_first_entry_of_a_name() {
|
||||
let tdmn = |n: &str| {
|
||||
let mut b = n.as_bytes().to_vec();
|
||||
b.resize(40, 0);
|
||||
Chunk::data(*b"tdmn", b)
|
||||
};
|
||||
let group = Chunk::list(
|
||||
*b"tdgp",
|
||||
vec![tdmn("A"), Chunk::list(*b"tdgp", Vec::new()), tdmn("B"), Chunk::list(*b"tdbs", Vec::new()), tdmn("A"), Chunk::list(*b"tdbs", Vec::new())],
|
||||
);
|
||||
let g = PropGroup::from_chunk(&group).expect("group");
|
||||
assert!(matches!(g.get("A"), Some(PropNode::Group(_))), "the first A is the group");
|
||||
assert!(matches!(g.get("B"), Some(PropNode::Property(_))));
|
||||
assert!(g.get("C").is_none());
|
||||
assert_eq!(g.names(), ["A", "B", "A"]);
|
||||
}
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
//! Static transform values with their units, and the "absent = default" rule.
|
||||
//!
|
||||
//! After Effects stores a property only when it differs from the default it computes for the layer
|
||||
//! and composition (sparse storage), so a reader has to supply the defaults: Position defaults to
|
||||
//! the composition centre `[width / 2, height / 2, 0]` (verified: after the composition is resized
|
||||
//! without moving the layer, the old centre appears as a stored value), Anchor Point to the layer
|
||||
//! centre (`0.5, 0.5` of the layer **source** size), Scale to 100 %, Rotation to 0 and Opacity to
|
||||
//! 100 %. These defaults are verified for AV layers (solids); cameras and lights use other
|
||||
//! conventions (see the `camera` module).
|
||||
|
||||
use crate::container::typed::{Layer, Project, PropGroup, PropNode};
|
||||
|
||||
/// Where a [`Tracked`] value came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueSource {
|
||||
/// The property is absent from the file: the value is the computed default.
|
||||
Default,
|
||||
/// The property stores a static value.
|
||||
Stored,
|
||||
/// The property has keyframes: the value is that of the first keyframe.
|
||||
Keyframed,
|
||||
/// The property is present but its value could not be read: the value is the default.
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
/// A value and where it came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Tracked<T> {
|
||||
pub value: T,
|
||||
pub source: ValueSource,
|
||||
}
|
||||
|
||||
/// The five basic transform properties of an AV layer, in the units After Effects shows.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Transform {
|
||||
/// Pixels `[x, y, z]`.
|
||||
pub position: Tracked<[f64; 3]>,
|
||||
/// Stored as a fraction of the layer's **source** size for x and y (`10, 20` px on a 100x100
|
||||
/// solid in a 1920x1080 composition is `0.1, 0.2`; on a 400x300 solid `100, 50` is `0.25, 1/6`)
|
||||
/// and in pixels for z; see [`Transform::anchor_px`] and [`Project::layer_anchor_px`].
|
||||
pub anchor_fraction: Tracked<[f64; 3]>,
|
||||
/// Percent `[x, y, z]` (stored as fractions: 50 % is `0.5`).
|
||||
pub scale_percent: Tracked<[f64; 3]>,
|
||||
/// Degrees (Rotation, the Z rotation).
|
||||
pub rotation_degrees: Tracked<f64>,
|
||||
/// Percent (stored as a fraction: 25 % is `0.25`).
|
||||
pub opacity_percent: Tracked<f64>,
|
||||
}
|
||||
|
||||
impl Transform {
|
||||
/// The anchor point in pixels for a layer whose source has this size.
|
||||
pub fn anchor_px(&self, width: f64, height: f64) -> [f64; 3] {
|
||||
let [x, y, z] = self.anchor_fraction.value;
|
||||
[x * width, y * height, z]
|
||||
}
|
||||
|
||||
/// The anchor point of a **text** layer in layer pixels. A text layer has no source, so the
|
||||
/// stored value is not a fraction: it is pixels as stored (385: Anchor Point `10, 20` is stored
|
||||
/// `10, 20`), and an
|
||||
/// absent anchor is the text origin `[0, 0, 0]` (After Effects' default for new text, absent in
|
||||
/// every other text sample 110-114, 243-248, 334-340, 386).
|
||||
pub fn text_anchor_px(&self) -> [f64; 3] {
|
||||
match self.anchor_fraction.source {
|
||||
ValueSource::Stored | ValueSource::Keyframed => self.anchor_fraction.value,
|
||||
ValueSource::Default | ValueSource::Unreadable => [0.0; 3],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `N` components from the property `name` of `group` and multiplies them by `scale` (stored
|
||||
/// fractions to percent); `default` is in the output units and used when the property is absent.
|
||||
pub(crate) fn read<const N: usize>(group: &PropGroup<'_, '_>, name: &str, default: [f64; N], scale: f64) -> Tracked<[f64; N]> {
|
||||
let unreadable = Tracked { value: default, source: ValueSource::Unreadable };
|
||||
let property = match group.get(name) {
|
||||
None => return Tracked { value: default, source: ValueSource::Default },
|
||||
Some(PropNode::Property(p)) => p,
|
||||
Some(PropNode::Group(_) | PropNode::Other(_)) => return unreadable,
|
||||
};
|
||||
let (values, source) =
|
||||
if property.is_animated() { (property.first_key_value(), ValueSource::Keyframed) } else { (property.static_value(), ValueSource::Stored) };
|
||||
let Some(values) = values else { return unreadable };
|
||||
if values.len() < N {
|
||||
return unreadable;
|
||||
}
|
||||
let mut out = default;
|
||||
for (slot, v) in out.iter_mut().zip(&values) {
|
||||
*slot = *v * scale;
|
||||
}
|
||||
Tracked { value: out, source }
|
||||
}
|
||||
|
||||
/// Like [`read`] but `None` when the property is absent or unreadable (for properties whose default
|
||||
/// is not known), keeping the value's source.
|
||||
pub(crate) fn read_opt<const N: usize>(group: &PropGroup<'_, '_>, name: &str, scale: f64) -> Option<Tracked<[f64; N]>> {
|
||||
let tracked = read(group, name, [0.0; N], scale);
|
||||
matches!(tracked.source, ValueSource::Stored | ValueSource::Keyframed).then_some(tracked)
|
||||
}
|
||||
|
||||
impl<'f, 'a> Project<'f, 'a> {
|
||||
/// The anchor point of an AV layer in pixels: the stored fraction times the size of the layer's
|
||||
/// source (a solid or footage item, or a precomp's composition), z unchanged. `None` when the
|
||||
/// layer has no source (shape, text, camera, light) or no Transform group.
|
||||
pub fn layer_anchor_px(&self, layer: &Layer<'f, 'a>) -> Option<Tracked<[f64; 3]>> {
|
||||
let (width, height) = self.layer_source_size(layer)?;
|
||||
let Some(PropNode::Group(group)) = layer.properties()?.get("ADBE Transform Group") else { return None };
|
||||
let fraction = read(&group, "ADBE Anchor Point", [0.5, 0.5, 0.0], 1.0);
|
||||
let [x, y, z] = fraction.value;
|
||||
Some(Tracked { value: [x * f64::from(width), y * f64::from(height), z], source: fraction.source })
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The transform of an AV layer in a composition of this size (pixels), with absent
|
||||
/// properties replaced by their defaults. `None` when the layer has no Transform group.
|
||||
pub fn transform(&self, comp_width: u32, comp_height: u32) -> Option<Transform> {
|
||||
let Some(PropNode::Group(group)) = self.properties()?.get("ADBE Transform Group") else { return None };
|
||||
let centre = [f64::from(comp_width) / 2.0, f64::from(comp_height) / 2.0, 0.0];
|
||||
let rotation = read(&group, "ADBE Rotate Z", [0.0], 1.0);
|
||||
let opacity = read(&group, "ADBE Opacity", [100.0], 100.0);
|
||||
Some(Transform {
|
||||
position: read(&group, "ADBE Position", centre, 1.0),
|
||||
anchor_fraction: read(&group, "ADBE Anchor Point", [0.5, 0.5, 0.0], 1.0),
|
||||
scale_percent: read(&group, "ADBE Scale", [100.0, 100.0, 100.0], 100.0),
|
||||
rotation_degrees: Tracked { value: rotation.value[0], source: rotation.source },
|
||||
opacity_percent: Tracked { value: opacity.value[0], source: opacity.source },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of a layer's Time Remapping property: the layer time of the key and the source time it
|
||||
/// maps to, both in seconds.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TimeRemapKey {
|
||||
/// The key time in the property's time units.
|
||||
pub time_units: i32,
|
||||
/// The key time in seconds (layer time).
|
||||
pub time_seconds: Option<f64>,
|
||||
/// The value in seconds (the plain record's value at byte 8).
|
||||
pub value_seconds: f64,
|
||||
}
|
||||
|
||||
/// The state of a layer's `ADBE Time Remapping` property. Every layer has the property; while the
|
||||
/// remap is off it is an inert record (`tdsb` 3, static value 0, no keys). Enabling the remap turns
|
||||
/// it into a keyed property (`tdsb` 1, `tdb4` byte 68 = 1, no `cdat`) with two keys: the layer's in
|
||||
/// and out time mapped to the source time (319: 0 s and 5 s; 354: 0 s and 0.1 s).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct TimeRemap {
|
||||
/// True when the property has keys.
|
||||
pub enabled: bool,
|
||||
pub keys: Vec<TimeRemapKey>,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The Time Remapping state; `None` when the layer has no such property.
|
||||
pub fn time_remap(&self) -> Option<TimeRemap> {
|
||||
let Some(PropNode::Property(p)) = self.properties()?.get("ADBE Time Remapping") else { return None };
|
||||
let scale = p.time_scale().unwrap_or(0);
|
||||
let keys = match p.keys() {
|
||||
Some(list) => list
|
||||
.keyframes()
|
||||
.filter_map(|k| Some(TimeRemapKey { time_units: k.time_units()?, time_seconds: k.seconds(scale), value_seconds: k.scalar_value()? }))
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
Some(TimeRemap { enabled: p.is_animated(), keys })
|
||||
}
|
||||
}
|
||||
|
||||
/// The Orientation of a 3D layer (`ADBE Orientation`, 488): a `LIST otst` holding a `tdbs` and a
|
||||
/// `LIST otky` whose `otda` is three big-endian `f64` degrees `[x, y, z]`; absent at `[0, 0, 0]`
|
||||
/// (485-487).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Orientation {
|
||||
/// Degrees `[x, y, z]`: the static value (for a keyed Orientation the first `otda`, whose
|
||||
/// meaning is not sampled).
|
||||
pub degrees: [f64; 3],
|
||||
/// The `tdbs` of the `otst` has keys (see [`Layer::orientation_keys`]).
|
||||
pub animated: bool,
|
||||
/// The `tdbs` of the `otst` has an expression.
|
||||
pub has_expression: bool,
|
||||
}
|
||||
|
||||
impl<'f, 'a> Layer<'f, 'a> {
|
||||
/// The Orientation; `None` when it is absent (the default `[0, 0, 0]`) or unreadable.
|
||||
pub fn orientation(&self) -> Option<Orientation> {
|
||||
let Some(PropNode::Group(group)) = self.properties()?.get("ADBE Transform Group") else { return None };
|
||||
let Some(PropNode::Other(otst)) = group.get("ADBE Orientation") else { return None };
|
||||
if !otst.is_list(b"otst") {
|
||||
return None;
|
||||
}
|
||||
let property = otst.child_list(b"tdbs").and_then(crate::container::typed::Property::from_chunk);
|
||||
let otda = otst.child_list(b"otky")?.child(b"otda")?.bytes()?;
|
||||
let mut degrees = [0.0; 3];
|
||||
for (i, slot) in degrees.iter_mut().enumerate() {
|
||||
let b = otda.get(i * 8..i * 8 + 8)?;
|
||||
*slot = f64::from_be_bytes(b.try_into().ok()?);
|
||||
}
|
||||
Some(Orientation {
|
||||
degrees,
|
||||
animated: property.as_ref().is_some_and(|p| p.is_animated()),
|
||||
has_expression: property.as_ref().is_some_and(|p| p.expression().is_some()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The time scale of the Orientation's key times (`tdb4` bytes 12..15), which follows the
|
||||
/// layer's stretch like every property of the layer.
|
||||
pub fn orientation_time_scale(&self) -> Option<u32> {
|
||||
let Some(PropNode::Group(group)) = self.properties().and_then(|p| p.get("ADBE Transform Group")) else { return None };
|
||||
let Some(PropNode::Other(otst)) = group.get("ADBE Orientation") else { return None };
|
||||
otst.child_list(b"tdbs").and_then(crate::container::typed::Property::from_chunk).and_then(|p| p.time_scale())
|
||||
}
|
||||
|
||||
/// The keyframes of a keyed Orientation (703): the `tdbs` of the `otst` holds one 80-byte
|
||||
/// record per key (time, interpolation sides, flags; the rest is not decoded) and `otky` one
|
||||
/// `otda` (three `f64` degrees) per key, in the same order. Empty when the Orientation is not
|
||||
/// keyed or the counts differ. After Effects interpolates between the keys by a quaternion slerp
|
||||
/// of the rotations `Rx Ry Rz`, not per component (703's values at 0.5 / 1 / 1.5 s).
|
||||
pub fn orientation_keys(&self) -> Vec<OrientationKey> {
|
||||
let Some(PropNode::Group(group)) = self.properties().and_then(|p| p.get("ADBE Transform Group")) else { return Vec::new() };
|
||||
let Some(PropNode::Other(otst)) = group.get("ADBE Orientation") else { return Vec::new() };
|
||||
let Some(list) = otst.child_list(b"tdbs").and_then(crate::container::typed::Property::from_chunk).and_then(|p| p.keys()) else { return Vec::new() };
|
||||
let values: Vec<Option<[f64; 3]>> = otst
|
||||
.child_list(b"otky")
|
||||
.map(|k| {
|
||||
k.children()
|
||||
.iter()
|
||||
.filter(|c| c.is(b"otda"))
|
||||
.map(|c| {
|
||||
let b = c.bytes()?;
|
||||
let at = |i: usize| b.get(i * 8..i * 8 + 8).and_then(|s| s.try_into().ok()).map(f64::from_be_bytes);
|
||||
Some([at(0)?, at(1)?, at(2)?])
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let keys: Vec<_> = list.keyframes().collect();
|
||||
if keys.len() != values.len() {
|
||||
return Vec::new();
|
||||
}
|
||||
keys.iter()
|
||||
.zip(values)
|
||||
.filter_map(|(k, v)| {
|
||||
Some(OrientationKey {
|
||||
time_units: k.time_units()?,
|
||||
interpolation_in: k.interpolation_in()?,
|
||||
interpolation_out: k.interpolation_out()?,
|
||||
degrees: v?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A keyframe of a keyed Orientation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct OrientationKey {
|
||||
/// The time in the property's time units (layer time).
|
||||
pub time_units: i32,
|
||||
pub interpolation_in: crate::container::Interpolation,
|
||||
pub interpolation_out: crate::container::Interpolation,
|
||||
/// Degrees `[x, y, z]`.
|
||||
pub degrees: [f64; 3],
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
//! Writing an [`AepFile`] back to bytes.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use crate::container::chunk::{AepFile, Body, Chunk};
|
||||
use crate::container::error::AepError;
|
||||
|
||||
/// Deepest tree [`write`] accepts (a hand-built tree may be deeper than any parsed one).
|
||||
const MAX_WRITE_DEPTH: usize = 256;
|
||||
|
||||
/// Serialises `file`: `RIFX`, the recomputed container size, `Egg!`, the chunks and the trailer.
|
||||
/// Sizes of the container and of every chunk are recomputed from the tree; an unmodified parsed
|
||||
/// file comes back byte for byte.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`AepError::TooLarge`] when a chunk or the container exceeds the 32-bit size field,
|
||||
/// [`AepError::TooDeep`] for an absurdly deep hand-built tree.
|
||||
pub fn write(file: &AepFile<'_>) -> Result<Vec<u8>, AepError> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(b"RIFX");
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
out.extend_from_slice(b"Egg!");
|
||||
write_sequence(&mut out, &file.chunks, 1)?;
|
||||
let size = u32::try_from(out.len().saturating_sub(8)).map_err(|_| AepError::TooLarge)?;
|
||||
patch_u32(&mut out, 4, size)?;
|
||||
out.extend_from_slice(&file.trailer);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Like [`write`], into any writer.
|
||||
///
|
||||
/// # Errors
|
||||
/// A size or depth error of [`write`] becomes `ErrorKind::InvalidData`; otherwise I/O errors.
|
||||
pub fn write_to(file: &AepFile<'_>, w: &mut impl Write) -> std::io::Result<()> {
|
||||
let bytes = write(file).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
w.write_all(&bytes)
|
||||
}
|
||||
|
||||
fn patch_u32(out: &mut [u8], at: usize, v: u32) -> Result<(), AepError> {
|
||||
let end = at.checked_add(4).ok_or(AepError::TooLarge)?;
|
||||
let dst = out.get_mut(at..end).ok_or(AepError::TooLarge)?;
|
||||
for (d, s) in dst.iter_mut().zip(v.to_be_bytes()) {
|
||||
*d = s;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_sequence(out: &mut Vec<u8>, chunks: &[Chunk<'_>], depth: usize) -> Result<(), AepError> {
|
||||
if depth > MAX_WRITE_DEPTH {
|
||||
return Err(AepError::TooDeep);
|
||||
}
|
||||
let count = chunks.len();
|
||||
for (i, chunk) in chunks.iter().enumerate() {
|
||||
write_chunk(out, chunk, i + 1 == count, depth)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_chunk(out: &mut Vec<u8>, chunk: &Chunk<'_>, is_last: bool, depth: usize) -> Result<(), AepError> {
|
||||
out.extend_from_slice(&chunk.id);
|
||||
let size_at = out.len();
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
let body_start = out.len();
|
||||
match &chunk.body {
|
||||
Body::Data(d) => out.extend_from_slice(d),
|
||||
Body::Chunks(c) => write_sequence(out, c, depth + 1)?,
|
||||
Body::List { list_type, children } => {
|
||||
out.extend_from_slice(list_type);
|
||||
write_sequence(out, children, depth + 1)?;
|
||||
}
|
||||
Body::OpaqueList { list_type, data } => {
|
||||
out.extend_from_slice(list_type);
|
||||
out.extend_from_slice(data);
|
||||
}
|
||||
}
|
||||
let len = out.len().saturating_sub(body_start);
|
||||
patch_u32(out, size_at, u32::try_from(len).map_err(|_| AepError::TooLarge)?)?;
|
||||
if len % 2 == 1 {
|
||||
match chunk.pad {
|
||||
Some(b) => out.push(b),
|
||||
None if !is_last => out.push(0),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! After Effects project (`.aep`) export: an EffectCraft [`Project`] written as an `.aep` that
|
||||
//! After Effects 2026 opens.
|
||||
//!
|
||||
//! Every chunk is built in code: the project skeleton, the item, layer and property records are
|
||||
//! prototypes in the layout After Effects writes (`template.rs` gathers them), and the exporter
|
||||
//! clones them and writes only the fields whose layout is verified (`docs/aep-format.md` section 3, `docs/aep-export.md`):
|
||||
//! item and layer ids, project settings, the composition header, the layer header (switches
|
||||
//! including 3D, time stretch, blend modes, track mattes), solid colour and size, the Transform
|
||||
//! properties (static values, keyframes with interpolation and ease, expressions), layer masks,
|
||||
//! markers, time remapping, precomposition, footage, text (with animators), shape, camera and
|
||||
//! light layers, footage items and image sequences, layer styles, and the effects of the table
|
||||
//! shared with the importer (`crate::effect_map`). `docs/aep-export.md` has the full
|
||||
//! list and the rules After Effects needs.
|
||||
//!
|
||||
//! What cannot be written is **reported**, never dropped silently ([`ExportReport`]); by default an
|
||||
//! export that would lose anything is refused ([`ExportOptions::allow_losses`]).
|
||||
//!
|
||||
//! The crate sits at L3 (above `effectcraft-project`, next to the importer) and builds for wasm32:
|
||||
//! it does no file access, the caller gets the bytes.
|
||||
|
||||
mod base;
|
||||
mod camlight;
|
||||
mod effects;
|
||||
mod emit;
|
||||
mod footage;
|
||||
mod fx_defs;
|
||||
mod fxsynth;
|
||||
pub(crate) mod icc;
|
||||
mod keys;
|
||||
mod markers;
|
||||
mod masks;
|
||||
mod plan;
|
||||
mod report;
|
||||
mod settings;
|
||||
mod shapes;
|
||||
mod skeleton;
|
||||
mod style_defs;
|
||||
mod styles;
|
||||
mod synth;
|
||||
mod template;
|
||||
mod text;
|
||||
mod textanim;
|
||||
mod textdoc;
|
||||
mod textproto;
|
||||
mod timebase;
|
||||
mod tree;
|
||||
mod tree_defs;
|
||||
mod tree_spec;
|
||||
|
||||
use effectcraft_project::Project;
|
||||
|
||||
pub use report::{ExportReport, Exported, LIMITATIONS, Loss, LossCategory, MAX_DETAILS};
|
||||
|
||||
/// Why an `.aep` was not written.
|
||||
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
|
||||
pub enum AepExportError {
|
||||
/// Parts of the project cannot be exported and losses were not allowed. Nothing was written;
|
||||
/// the report says what would be lost.
|
||||
#[error("exporting would lose {}; allow losses to export anyway", .0.summary())]
|
||||
Refused(Box<ExportReport>),
|
||||
/// A prototype built in code does not have the shape the exporter expects (a bug in the crate).
|
||||
#[error("internal error: {0}")]
|
||||
Internal(&'static str),
|
||||
/// The container could not be written (a chunk or the file exceeds the format's 4 GB limit).
|
||||
#[error("{0}")]
|
||||
Container(#[from] crate::AepError),
|
||||
}
|
||||
|
||||
/// Options of [`export`].
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct ExportOptions {
|
||||
/// Export even when [`ExportReport::losses`] is not empty.
|
||||
pub allow_losses: bool,
|
||||
}
|
||||
|
||||
/// An exported project.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ExportResult {
|
||||
/// The `.aep` file.
|
||||
pub bytes: Vec<u8>,
|
||||
pub report: ExportReport,
|
||||
}
|
||||
|
||||
/// A neutral XMP packet for the end of the file (After Effects writes one; it only holds metadata).
|
||||
const XMP: &[u8] = b"<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <dc:format>application/vnd.adobe.aftereffects.project</dc:format>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>";
|
||||
|
||||
/// Exports `project` as an `.aep`.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`AepExportError::Refused`] when something would be lost and `allow_losses` is not set (nothing
|
||||
/// is written), [`AepExportError::Container`] for a file beyond the container's size limits.
|
||||
pub fn export(project: &Project, options: &ExportOptions) -> Result<ExportResult, AepExportError> {
|
||||
export_with(project, options, &|_| None)
|
||||
}
|
||||
|
||||
/// [`export`] with the modification times of the image-sequence folders: `folder_time` is asked
|
||||
/// with a sequence's first file path as the project stores it and answers with the modification
|
||||
/// time of the folder that holds it, in whole seconds since 1970 (UTC), or `None`. The caller
|
||||
/// decides whether that path may be followed (the engine applies its document-path policy) before
|
||||
/// it looks at the folder.
|
||||
///
|
||||
/// After Effects keeps a sequence's stored numbering only while the stored folder time
|
||||
/// (`sspc@118`) equals the folder's; otherwise it scans the folder again when the project opens
|
||||
/// and warns about every gap in the numbering in a modal dialog (860, `export-tests` x1-x3).
|
||||
/// Without a time it is written as 0, and such a folder is scanned again.
|
||||
///
|
||||
/// # Errors
|
||||
/// As [`export`].
|
||||
pub fn export_with(project: &Project, options: &ExportOptions, folder_time: &dyn Fn(&str) -> Option<u64>) -> Result<ExportResult, AepExportError> {
|
||||
let mut col = report::Collector::default();
|
||||
let mut plan = plan::plan(project, &mut col);
|
||||
let report = col.finish();
|
||||
if !options.allow_losses && !report.is_lossless() {
|
||||
return Err(AepExportError::Refused(Box::new(report)));
|
||||
}
|
||||
footage::stamp_sequences(&mut plan.root, folder_time);
|
||||
let bytes = emit::emit(&plan, XMP)?;
|
||||
Ok(ExportResult { bytes, report })
|
||||
}
|
||||
|
||||
/// The report an export would produce, without writing anything (a dry run).
|
||||
pub fn analyze(project: &Project) -> ExportReport {
|
||||
let mut col = report::Collector::default();
|
||||
let _ = plan::plan(project, &mut col);
|
||||
col.finish()
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! The project skeleton built in code (aep-format.md 3.1-3.3, 3.12a): the top-level chunks, the
|
||||
//! composition shell with its view layers, the `Solids` folder, a solid item and the records that
|
||||
//! follow a composition. Fields the exporter sets per item are left zero here; the bytes that are
|
||||
//! not decoded are named constants, each with the value it has in every generated test file of
|
||||
//! that kind (cases 000, 022, 211, 259, 620-634) and kept because After Effects refuses the file without them
|
||||
//! (read-backs t-no<id>, t-zcdta, u-zsspc, u-noclrs, u-noftgi, u-nofrec, u-nocdrp).
|
||||
|
||||
use crate::Chunk;
|
||||
use crate::export::synth::{GROUP_END, tdmn, tdsn};
|
||||
use crate::export::tree::Fixed;
|
||||
|
||||
/// A zero buffer of `len` bytes with `fields` (offset, bytes) written into it. The layouts are
|
||||
/// fixed in code ([`Fixed`]).
|
||||
pub(crate) fn bytes(len: usize, fields: &[(usize, &[u8])]) -> Vec<u8> {
|
||||
layout(len, fields).finish(|| format!("base::bytes ({len} bytes, fields at {:?})", fields.iter().map(|(at, v)| (*at, v.len())).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
/// The fixed layout of `len` zero bytes with `fields` written at their offsets.
|
||||
fn layout(len: usize, fields: &[(usize, &[u8])]) -> Fixed {
|
||||
let mut b = Fixed::zeroed(len);
|
||||
for (at, v) in fields {
|
||||
b.put(*at, v);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
pub(crate) fn utf8(text: &str) -> Chunk<'static> {
|
||||
Chunk::data(*b"Utf8", text.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// The After Effects version the file claims (`svap`, `head` 4..7): 26.x, the version every
|
||||
/// sample was saved with.
|
||||
const VERSION: [u8; 4] = [0x0f, 0x11, 0x0e, 0x02];
|
||||
/// `head` 0..3 and byte 8: the same in every sample (not decoded; a zero `head` is refused as
|
||||
/// "created with an older version", read-back u-zhead).
|
||||
const HEAD_FORMAT: [u8; 4] = [0x00, 0x61, 0x00, 0x05];
|
||||
/// The code page of the project's strings (`nhed` 18, `nnhd` 26): 65001, UTF-8.
|
||||
const UTF8_CODE_PAGE: [u8; 2] = 65001u16.to_be_bytes();
|
||||
/// The size of the render-queue settings blocks (`AFsi`, `ARsi`); zero bodies of this size are
|
||||
/// read (read-back e1-zafsi), a missing one is refused (e1-noafsi).
|
||||
const RQ_SETTINGS_LEN: usize = 1872;
|
||||
/// The record size of the render-queue item list (`LRdr/list/lhd3` word 4).
|
||||
const RQ_ITEM_LEN: u32 = 2246;
|
||||
/// The id of the `Solids` folder, which `sfnm/sfid` names.
|
||||
pub(crate) const SOLIDS_FOLDER_ID: u32 = 0x19;
|
||||
/// The default end time of a view layer (5 s in 25 600 units): view layers keep it whatever the
|
||||
/// composition's duration (000, 031, 032).
|
||||
const VIEW_OUT: u32 = 128_000;
|
||||
|
||||
/// The top-level chunks of a project: the headers (`settings::emit` writes the settings into
|
||||
/// them, `emit` the next free id), the project lists (`effects::put_project_lists` fills `Pefl`),
|
||||
/// an empty `Fold` with its `fdta`, the workspace name and the render queue.
|
||||
pub(crate) fn project_chunks() -> Vec<Chunk<'static>> {
|
||||
let head = bytes(20, &[(0, &HEAD_FORMAT), (4, &VERSION), (8, &[0x80])]);
|
||||
// nhed / nnhd: bytes 7 and 9 the same in every sample, byte 12 / 15 the timecode base (30),
|
||||
// 13 / 19 the frames per foot (16), 14 / 20 the frame count start (2: from 0), 15 / 24 the
|
||||
// colour depth (2: 32 bits); the save noise after the code page is left zero.
|
||||
let nhed = bytes(32, &[(7, &[5]), (9, &[1]), (12, &[0x1e, 16, 2, 2]), (18, &UTF8_CODE_PAGE)]);
|
||||
let nnhd = bytes(40, &[(7, &[5]), (9, &[1]), (15, &[0x1e]), (19, &[16, 2]), (24, &[2]), (26, &UTF8_CODE_PAGE)]);
|
||||
let one = 1u32.to_be_bytes();
|
||||
let lhd3 = bytes(52, &[(0, &0x00d0_0bee_u32.to_be_bytes()), (12, &one), (16, &RQ_ITEM_LEN.to_be_bytes()), (20, &one), (24, &one), (28, &one)]);
|
||||
let wsnm: Vec<u8> = "Default".encode_utf16().flat_map(u16::to_be_bytes).collect();
|
||||
vec![
|
||||
Chunk::data(*b"svap", VERSION.to_vec()),
|
||||
Chunk::data(*b"head", head),
|
||||
Chunk::data(*b"nhed", nhed),
|
||||
Chunk::data(*b"nnhd", nnhd),
|
||||
// The project's audio sample rate.
|
||||
Chunk::data(*b"adfr", 48_000f64.to_be_bytes().to_vec()),
|
||||
Chunk::list(*b"Pefl", Vec::new()),
|
||||
Chunk::data(*b"qtlg", vec![0]),
|
||||
Chunk::list(*b"sfnm", vec![utf8("Solids"), Chunk::data(*b"sfid", SOLIDS_FOLDER_ID.to_le_bytes().to_vec())]),
|
||||
Chunk::data(*b"mrid", vec![0; 4]),
|
||||
// Compensate for Scene-referred Profiles: on.
|
||||
Chunk::data(*b"acer", vec![1]),
|
||||
Chunk::list(*b"CPPl", Vec::new()),
|
||||
Chunk::data(*b"cpid", vec![0xff; 16]),
|
||||
Chunk::data(*b"dwga", vec![0; 4]),
|
||||
Chunk::data(*b"pcms", vec![1]),
|
||||
utf8("{\"ocioConfigurationFile\":\"ACES 1.2\"}"),
|
||||
Chunk::data(*b"PwCs", vec![1]),
|
||||
utf8("{}"),
|
||||
Chunk::data(*b"pdvc", vec![1]),
|
||||
utf8("{}"),
|
||||
Chunk::list(*b"ExEn", vec![utf8("javascript-1.0")]),
|
||||
Chunk::list(*b"Fold", vec![Chunk::data(*b"fdta", vec![0; 14])]),
|
||||
Chunk::data(*b"wsns", vec![0, 0x0e]),
|
||||
Chunk::data(*b"wsnm", wsnm),
|
||||
utf8("Default"),
|
||||
Chunk::data(*b"fcid", vec![0; 4]),
|
||||
Chunk::data(*b"oacc", vec![0; 2]),
|
||||
Chunk::list(*b"LSIf", vec![Chunk::data(*b"AFsi", vec![0; RQ_SETTINGS_LEN])]),
|
||||
Chunk::list(
|
||||
*b"LRdr",
|
||||
vec![
|
||||
Chunk::data(*b"Rhed", vec![0; 20]),
|
||||
Chunk::data(*b"Rout", vec![0; 4]),
|
||||
Chunk::list(*b"list", vec![Chunk::data(*b"lhd3", lhd3)]),
|
||||
Chunk::list(*b"LItm", Vec::new()),
|
||||
Chunk::list(*b"LSIf", vec![Chunk::data(*b"ARsi", vec![0; RQ_SETTINGS_LEN])]),
|
||||
],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// `idta` of an item: the kind at 0, byte 23 per kind (0x20 composition, 0x30 footage, 0 folder;
|
||||
/// After Effects renders differently without it, read-backs t-zidta and u-zidta2); `emit` writes
|
||||
/// the id and the label.
|
||||
pub(crate) fn idta(kind: u16, byte23: u8) -> Chunk<'static> {
|
||||
Chunk::data(*b"idta", bytes(84, &[(0, &kind.to_be_bytes()), (23, &[byte23])]))
|
||||
}
|
||||
|
||||
/// The guides of a layer or item (`Gide`: `gdta` zero and an empty list header).
|
||||
pub(crate) fn guides() -> Chunk<'static> {
|
||||
let header = crate::export::synth::key_list(16, 0, Vec::new()).children().iter().filter(|c| c.is(b"lhd3")).cloned().collect();
|
||||
Chunk::list(*b"Gide", vec![Chunk::data(*b"gdta", vec![0; 8]), Chunk::list(*b"list", header)])
|
||||
}
|
||||
|
||||
/// `cdta` with the bytes `emit::build_comp` does not write: 0..3, the shutter angle and phase
|
||||
/// limits (360 at 176 and 184), the motion blur samples per frame (16 at 200) and the adaptive
|
||||
/// sample limit (128 at 196); the same in every sample, and a `cdta` without them crashes After
|
||||
/// Effects (read-back t-zcdta).
|
||||
fn cdta() -> Chunk<'static> {
|
||||
Chunk::data(
|
||||
*b"cdta",
|
||||
bytes(
|
||||
204,
|
||||
&[(0, &[0, 1, 0, 1]), (176, &360u32.to_be_bytes()), (184, &360u32.to_be_bytes()), (196, &128u32.to_be_bytes()), (200, &16u32.to_be_bytes())],
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// The renderer (`PRin`): the Classic 3D match name and display name (aep-format.md 3.2).
|
||||
fn renderer() -> Chunk<'static> {
|
||||
let prin = bytes(104, &[(4, b"ADBE Escher"), (52, b"Classic 3D"), (103, &[1])]);
|
||||
Chunk::list(*b"PRin", vec![Chunk::data(*b"prin", prin), Chunk::data(*b"prda", vec![0; 12])])
|
||||
}
|
||||
|
||||
/// The built-in view layers of a composition: list type, name, `ldta` byte 61 (label) and byte
|
||||
/// 128 (layer type: 2 camera, 4 for the markers layer).
|
||||
const VIEWS: [(&[u8; 4], &str, u8, u8); 11] = [
|
||||
(b"DLay", "Default", 4, 2),
|
||||
(b"SLay", "Front", 4, 2),
|
||||
(b"SLay", "Left", 4, 2),
|
||||
(b"SLay", "Top", 4, 2),
|
||||
(b"SLay", "Back", 4, 2),
|
||||
(b"SLay", "Right", 4, 2),
|
||||
(b"SLay", "Bottom", 4, 2),
|
||||
(b"CLay", "Custom View 1", 4, 2),
|
||||
(b"CLay", "Custom View 2", 4, 2),
|
||||
(b"CLay", "Custom View 3", 4, 2),
|
||||
(b"SecL", "Markers", 8, 4),
|
||||
];
|
||||
|
||||
/// One view layer: `ldta` with the decoded fields only (read-back t-zldta), an empty property
|
||||
/// tree (t-vempty), the guides, `Ewst` and the two f-record sets. `emit` writes the id.
|
||||
fn view_layer(ty: &[u8; 4], name: &str, label: u8, kind: u8) -> Vec<Chunk<'static>> {
|
||||
let markers = kind == 4;
|
||||
let mut name_copy = name.as_bytes().to_vec();
|
||||
name_copy.truncate(31);
|
||||
// Byte 38: 3D and auto-orient on the cameras; byte 39: the video switch (and on the markers
|
||||
// layer also effects, locked and collapse); quality Draft and blend mode Normal on the
|
||||
// markers layer.
|
||||
let flags: &[(usize, &[u8])] = if markers { &[(5, &[2]), (39, &[0x87]), (99, &[2])] } else { &[(38, &[0x44]), (39, &[1])] };
|
||||
let (one, scale, kind_word) = (1u32.to_be_bytes(), 25_600u32.to_be_bytes(), u32::from(kind).to_be_bytes());
|
||||
let (base, out, label) = (600u32.to_be_bytes(), VIEW_OUT.to_be_bytes(), [label]);
|
||||
let mut fields: Vec<(usize, &[u8])> =
|
||||
vec![(8, &one), (16, &base), (24, &scale), (28, &out), (32, &scale), (61, &label), (64, &name_copy), (108, &one), (128, &kind_word)];
|
||||
fields.extend_from_slice(flags);
|
||||
let ldta = bytes(164, &fields);
|
||||
let root = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(""), tdmn(GROUP_END)];
|
||||
let layer = Chunk::list(*ty, vec![Chunk::data(*b"ldta", ldta), utf8(name), Chunk::list(*b"tdgp", root), guides()]);
|
||||
let mut out = vec![layer, Chunk::list(*b"Ewst", Vec::new())];
|
||||
out.extend(crate::export::skeleton::f_records());
|
||||
out.extend(crate::export::skeleton::f_records());
|
||||
out
|
||||
}
|
||||
|
||||
/// The composition item without layers, and the index of its children where the layer blocks go.
|
||||
pub(crate) fn comp_shell() -> (Chunk<'static>, usize) {
|
||||
let mut kids = vec![
|
||||
Chunk::data(*b"iide", vec![0; 4]),
|
||||
Chunk::data(*b"idpc", vec![0; 8]),
|
||||
idta(4, 0x20),
|
||||
utf8(""),
|
||||
Chunk::list(*b"dats", vec![Chunk::data(*b"numS", vec![0; 4])]),
|
||||
cdta(),
|
||||
Chunk::data(*b"cdrp", vec![0]),
|
||||
Chunk::data(*b"comr", vec![0]),
|
||||
renderer(),
|
||||
];
|
||||
let layer_at = kids.len();
|
||||
for (ty, name, label, kind) in VIEWS {
|
||||
kids.extend(view_layer(ty, name, label, kind));
|
||||
}
|
||||
kids.push(guides());
|
||||
(Chunk::list(*b"Item", kids), layer_at)
|
||||
}
|
||||
|
||||
/// The list that follows a composition item (`FEE `, `ppSn` zero: read-back u-zppsn).
|
||||
pub(crate) fn fee() -> Chunk<'static> {
|
||||
Chunk::list(*b"FEE ", vec![Chunk::data(*b"ppSn", vec![0; 8])])
|
||||
}
|
||||
|
||||
/// An empty folder item (`sfdt` 1 in every sample).
|
||||
pub(crate) fn folder_item() -> Chunk<'static> {
|
||||
Chunk::list(
|
||||
*b"Item",
|
||||
vec![
|
||||
Chunk::data(*b"iide", vec![0; 4]),
|
||||
Chunk::data(*b"idpc", vec![0; 8]),
|
||||
idta(1, 0),
|
||||
utf8(""),
|
||||
Chunk::data(*b"sfdt", 1u32.to_be_bytes().to_vec()),
|
||||
Chunk::list(*b"Sfdr", Vec::new()),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// `ftgi` of a footage item, the same in every sample (required, read-back u-noftgi).
|
||||
pub(crate) fn ftgi() -> Chunk<'static> {
|
||||
Chunk::data(*b"ftgi", bytes(16, &[(7, &[1]), (8, &[0xff; 4]), (12, &600u32.to_be_bytes())]))
|
||||
}
|
||||
|
||||
/// The `sspc` bytes of a solid that are not decoded, the same in every solid (000, 022, 211, 259);
|
||||
/// After Effects refuses a solid with only the decoded fields (read-back u-zsspc).
|
||||
const SOLID_SSPC: [(usize, &[u8]); 11] = [
|
||||
(50, &[0, 0, 0x02, 0x58]),
|
||||
(73, &[3]),
|
||||
(105, &[1]),
|
||||
(109, &[1]),
|
||||
(125, &[0x0c]),
|
||||
(129, &[1]),
|
||||
(134, &[1]),
|
||||
(139, &[1]),
|
||||
(143, &[1]),
|
||||
(188, &[0xff; 8]),
|
||||
(212, &[1]),
|
||||
];
|
||||
|
||||
/// A solid's footage item: `sspc` (type `Soli`, duration 0 / 1), `opti` (`Soli`; `emit` writes
|
||||
/// the colour and the name), `pgui`, the colour-management list (no profile, the defaults of
|
||||
/// every sample; required, read-back u-noclrs), `ftgi` (required, u-noftgi) and the guides. The
|
||||
/// solid of a null layer is the same item.
|
||||
pub(crate) fn solid_item() -> Chunk<'static> {
|
||||
let mut sspc_fields: Vec<(usize, &[u8])> = vec![(22, b"Soli"), (45, &[1])];
|
||||
sspc_fields.extend(SOLID_SSPC);
|
||||
let clrs = Chunk::list(
|
||||
*b"CLRS",
|
||||
vec![
|
||||
Chunk::data(*b"epid", vec![0xff; 16]),
|
||||
Chunk::data(*b"apid", vec![0xff; 16]),
|
||||
Chunk::data(*b"linl", vec![2, 0, 0, 0]),
|
||||
Chunk::data(*b"embp", vec![1]),
|
||||
Chunk::data(*b"ipws", vec![1]),
|
||||
Chunk::data(*b"dcui", vec![1]),
|
||||
Chunk::data(*b"prgb", vec![1]),
|
||||
Chunk::data(*b"Mcsp", vec![1]),
|
||||
utf8(""),
|
||||
Chunk::data(*b"ocsp", vec![1]),
|
||||
utf8(""),
|
||||
Chunk::data(*b"hdrm", vec![1]),
|
||||
utf8("{}"),
|
||||
],
|
||||
);
|
||||
let pin = Chunk::list(
|
||||
*b"Pin ",
|
||||
vec![
|
||||
Chunk::data(*b"sspc", bytes(222, &sspc_fields)),
|
||||
utf8(""),
|
||||
Chunk::data(*b"opti", bytes(282, &[(0, b"Soli")])),
|
||||
Chunk::data(*b"pgui", vec![0; 16]),
|
||||
clrs,
|
||||
utf8(""),
|
||||
],
|
||||
);
|
||||
Chunk::list(*b"Item", vec![Chunk::data(*b"iide", vec![0; 4]), Chunk::data(*b"idpc", vec![0; 8]), idta(7, 0x30), utf8(""), pin, ftgi(), utf8(""), guides()])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A field out of range is an error.
|
||||
#[test]
|
||||
fn a_field_out_of_range_is_an_error() {
|
||||
let ok = layout(4, &[(0, &[1]), (3, &[2])]);
|
||||
assert!(ok.error().is_none());
|
||||
assert_eq!(ok.finish(String::new), [1, 0, 0, 2]);
|
||||
assert!(layout(4, &[(3, &[1, 2])]).error().is_some());
|
||||
assert!(layout(4, &[(usize::MAX, &[1])]).error().is_some());
|
||||
}
|
||||
|
||||
/// The chunks After Effects refuses a file without, or crashes on (aep-export.md, "What After
|
||||
/// Effects needs").
|
||||
#[test]
|
||||
fn the_skeleton_has_what_after_effects_needs() {
|
||||
let top = project_chunks();
|
||||
for id in [b"adfr", b"qtlg", b"mrid", b"acer", b"fcid", b"oacc", b"head", b"nhed"] {
|
||||
assert!(top.iter().any(|c| c.is(id)), "{}", String::from_utf8_lossy(id));
|
||||
}
|
||||
assert!(top.iter().any(|c| c.is_list(b"CPPl")));
|
||||
let head = top.iter().find(|c| c.is(b"head")).and_then(|c| c.bytes()).unwrap();
|
||||
assert_eq!(&head[..8], &[0x00, 0x61, 0x00, 0x05, 0x0f, 0x11, 0x0e, 0x02]);
|
||||
let rq = top.iter().find(|c| c.is_list(b"LRdr")).unwrap();
|
||||
let arsi = rq.child_list(b"LSIf").and_then(|l| l.child(b"ARsi")).and_then(|c| c.bytes()).unwrap();
|
||||
assert_eq!(arsi.len(), RQ_SETTINGS_LEN);
|
||||
let afsi = top.iter().find(|c| c.is_list(b"LSIf")).and_then(|l| l.child(b"AFsi")).and_then(|c| c.bytes()).unwrap();
|
||||
assert_eq!(afsi.len(), RQ_SETTINGS_LEN);
|
||||
|
||||
let (comp, at) = comp_shell();
|
||||
let kids = comp.children();
|
||||
assert!(comp.child_list(b"dats").is_some(), "no dats: After Effects crashes");
|
||||
assert!(kids.iter().any(|c| c.is(b"cdrp")) && kids.iter().any(|c| c.is(b"comr")));
|
||||
let cdta = comp.child(b"cdta").and_then(|c| c.bytes()).unwrap();
|
||||
for at in [1usize, 3, 179, 187, 199, 203] {
|
||||
assert_ne!(cdta[at], 0, "cdta byte {at}: a zero cdta crashes After Effects");
|
||||
}
|
||||
let views = kids.iter().filter(|c| [*b"DLay", *b"SLay", *b"CLay", *b"SecL"].iter().any(|t| c.is_list(t))).count();
|
||||
assert_eq!(views, 11);
|
||||
assert!(kids.get(at).is_some_and(|c| c.is_list(b"DLay")), "the layers go before the view layers");
|
||||
|
||||
let solid = solid_item();
|
||||
let pin = solid.child_list(b"Pin ").unwrap();
|
||||
assert!(pin.child_list(b"CLRS").is_some() && solid.child(b"ftgi").is_some());
|
||||
let sspc = pin.child(b"sspc").and_then(|c| c.bytes()).unwrap();
|
||||
assert!(SOLID_SSPC.iter().all(|(at, v)| &sspc[*at..*at + v.len()] == *v));
|
||||
assert_eq!(solid.child(b"idta").and_then(|c| c.bytes()).unwrap()[23], 0x30);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Camera and light layers (`docs/aep-format.md` 3.12; cases 251-256, 342-346).
|
||||
//!
|
||||
//! Both are written from a layer block of our own cases: the default two-node camera 256 and the
|
||||
//! spot (254, its Intensity record removed) and point (252) lights. The layer header keeps the
|
||||
//! case's type (`ldta@128` 2 camera, 1 light), source id (0 / `0xffffffff`), 3D bit and light type
|
||||
//! (`ldta@136` 1 spot, 2 point); the exporter sets the auto-orient bit (`ldta@38` 0x40: a two-node
|
||||
//! camera and a spot light orient towards their point of interest, 251 vs 256). The point of
|
||||
//! interest is the Anchor Point in pixels and the Position an explicit value (253: 76 / 77 = 0),
|
||||
//! both through the Transform writer. Options records are cloned from the one-change cases.
|
||||
|
||||
use crate::Chunk;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{Layer, LightKind};
|
||||
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::synth::{GROUP_END, is_tdmn, tdmn};
|
||||
use crate::export::tree::{R, child_data, kids_mut, list_mut, put_f64, split_group, tpl};
|
||||
|
||||
/// A camera's options in the file's units (pixels, percent, a switch).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct CameraPlan {
|
||||
pub two_node: bool,
|
||||
pub zoom: f64,
|
||||
pub dof: bool,
|
||||
pub focus: f64,
|
||||
pub aperture: f64,
|
||||
pub blur: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct LightPlan {
|
||||
/// `ldta@136`: 1 spot, 2 point (252, 254).
|
||||
pub kind: u32,
|
||||
pub intensity: f64,
|
||||
/// `[A, R, G, B]` 0..255 (343).
|
||||
pub color: [f64; 4],
|
||||
pub cone_angle: f64,
|
||||
pub cone_feather: f64,
|
||||
}
|
||||
|
||||
/// The finite scalar at `path`; a property there that is not one is reported (its default is
|
||||
/// written), an absent one is not.
|
||||
fn scalar(layer: &Layer, path: &str, what: &str, col: &mut Collector) -> Option<f64> {
|
||||
match layer.props.prop(path).map(|p| &p.value) {
|
||||
Some(Value::Scalar(v)) if v.is_finite() => Some(*v),
|
||||
None => None,
|
||||
Some(_) => {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: {path} is not a number, the default is written"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_keys_or_expr(layer: &Layer, path: &str) -> bool {
|
||||
layer.props.prop(path).is_some_and(|p| !p.keys.is_empty() || p.expr.as_ref().is_some_and(|e| !e.text.is_empty()))
|
||||
}
|
||||
|
||||
/// The camera's options; keys and expressions on them are reported (the static value is written).
|
||||
pub(crate) fn plan_camera(layer: &Layer, comp_width: u32, what: &str, col: &mut Collector) -> CameraPlan {
|
||||
let default_zoom = f64::from(comp_width) * 50.0 / 36.0;
|
||||
if matches!(layer.auto_orient, effectcraft_project::AutoOrient::AlongPath | effectcraft_project::AutoOrient::TowardsCamera) {
|
||||
col.lose(LossCategory::Cameras, format!("{what}: the camera's Auto-Orient {:?} is not written (written as a one-node camera)", layer.auto_orient));
|
||||
}
|
||||
for id in ["zoom", "dof", "focusDistance", "aperture", "blurLevel"] {
|
||||
if has_keys_or_expr(layer, &format!("cameraOptions/{id}")) {
|
||||
col.lose(LossCategory::Cameras, format!("{what}: keys or an expression on the camera's {id} (the static value is written)"));
|
||||
}
|
||||
}
|
||||
let iris_default = [
|
||||
("irisShape", 0.0),
|
||||
("irisRotation", 0.0),
|
||||
("irisRoundness", 0.0),
|
||||
("irisAspectRatio", 1.0),
|
||||
("irisDiffractionFringe", 0.0),
|
||||
("highlightGain", 0.0),
|
||||
("highlightThreshold", 255.0),
|
||||
("highlightSaturation", 0.0),
|
||||
];
|
||||
for (id, d) in iris_default {
|
||||
let v = match layer.props.prop(&format!("cameraOptions/{id}")).map(|p| &p.value) {
|
||||
Some(Value::Scalar(v)) => Some(*v),
|
||||
Some(Value::Enum(e)) => Some(f64::from(*e)),
|
||||
_ => None,
|
||||
};
|
||||
if v.is_some_and(|v| (v - d).abs() > 1e-9) || has_keys_or_expr(layer, &format!("cameraOptions/{id}")) {
|
||||
col.lose(LossCategory::Cameras, format!("{what}: the camera's {id} is not written (not sampled)"));
|
||||
}
|
||||
}
|
||||
let dof = matches!(layer.props.prop("cameraOptions/dof").map(|p| &p.value), Some(Value::Bool(true)));
|
||||
CameraPlan {
|
||||
two_node: layer.auto_orient == effectcraft_project::AutoOrient::TowardsPointOfInterest,
|
||||
zoom: scalar(layer, "cameraOptions/zoom", what, col).unwrap_or(default_zoom),
|
||||
dof,
|
||||
focus: scalar(layer, "cameraOptions/focusDistance", what, col).unwrap_or(default_zoom),
|
||||
aperture: scalar(layer, "cameraOptions/aperture", what, col).unwrap_or(25.3 * f64::from(comp_width) / 1920.0),
|
||||
blur: scalar(layer, "cameraOptions/blurLevel", what, col).unwrap_or(100.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The light's options, or `None` (reported) for a type without a sampled case.
|
||||
pub(crate) fn plan_light(layer: &Layer, kind: LightKind, what: &str, col: &mut Collector) -> Option<LightPlan> {
|
||||
let code = match kind {
|
||||
LightKind::Spot => 1,
|
||||
LightKind::Point => 2,
|
||||
other => {
|
||||
col.lose(LossCategory::Lights, format!("{what}: a {} light is not written (not sampled)", other.label()));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// A spot light is written oriented towards its point of interest (a point light has no
|
||||
// orientation that shows).
|
||||
if code == 1 && layer.auto_orient != effectcraft_project::AutoOrient::TowardsPointOfInterest {
|
||||
col.lose(LossCategory::Lights, format!("{what}: the light's Auto-Orient {:?} is written as towards the point of interest", layer.auto_orient));
|
||||
}
|
||||
for id in ["intensity", "color", "coneAngle", "coneFeather"] {
|
||||
if has_keys_or_expr(layer, &format!("lightOptions/{id}")) {
|
||||
col.lose(LossCategory::Lights, format!("{what}: keys or an expression on the light's {id} (the static value is written)"));
|
||||
}
|
||||
}
|
||||
let defaults = [("radius", 500.0), ("falloffDistance", 500.0), ("shadowDarkness", 100.0), ("shadowDiffusion", 0.0)];
|
||||
for (id, d) in defaults {
|
||||
if scalar(layer, &format!("lightOptions/{id}"), what, col).is_some_and(|v| (v - d).abs() > 1e-9)
|
||||
|| has_keys_or_expr(layer, &format!("lightOptions/{id}"))
|
||||
{
|
||||
col.lose(LossCategory::Lights, format!("{what}: the light's {id} is not written (not sampled)"));
|
||||
}
|
||||
}
|
||||
// Options that are not written at all: a value other than the default, or keys or an expression
|
||||
// (which change the render even when the static value is the default).
|
||||
if matches!(layer.props.prop("lightOptions/falloff").map(|p| &p.value), Some(Value::Enum(e)) if *e != 0) || has_keys_or_expr(layer, "lightOptions/falloff")
|
||||
{
|
||||
col.lose(LossCategory::Lights, format!("{what}: the light's falloff type is not written (not sampled)"));
|
||||
}
|
||||
if matches!(layer.props.prop("lightOptions/castsShadows").map(|p| &p.value), Some(Value::Bool(true)))
|
||||
|| has_keys_or_expr(layer, "lightOptions/castsShadows")
|
||||
{
|
||||
col.lose(LossCategory::Lights, format!("{what}: Casts Shadows is not written (not sampled)"));
|
||||
}
|
||||
let color = match layer.props.prop("lightOptions/color").map(|p| &p.value) {
|
||||
Some(Value::Color(c)) => {
|
||||
let out = [255.0, c[0] * 255.0, c[1] * 255.0, c[2] * 255.0].map(|v| if v.is_finite() { v.clamp(0.0, 255.0) } else { 255.0 });
|
||||
if c.iter().take(3).zip(&out[1..]).any(|(v, o)| (v * 255.0).to_bits() != o.to_bits()) {
|
||||
col.lose(LossCategory::Lights, format!("{what}: a light colour channel outside 0 to 1 is written as the nearest limit"));
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => [255.0; 4],
|
||||
};
|
||||
Some(LightPlan {
|
||||
kind: code,
|
||||
intensity: scalar(layer, "lightOptions/intensity", what, col).unwrap_or(100.0),
|
||||
color,
|
||||
cone_angle: scalar(layer, "lightOptions/coneAngle", what, col).unwrap_or(90.0),
|
||||
cone_feather: scalar(layer, "lightOptions/coneFeather", what, col).unwrap_or(50.0),
|
||||
})
|
||||
}
|
||||
|
||||
/// The option records: per match name the `tdbs` After Effects wrote when it was changed alone.
|
||||
pub(crate) struct OptionProtos {
|
||||
pub records: Vec<(String, Chunk<'static>)>,
|
||||
}
|
||||
|
||||
impl OptionProtos {
|
||||
fn get(&self, name: &str) -> R<Chunk<'static>> {
|
||||
self.records.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()).ok_or_else(|| tpl("camera / light option prototype missing"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The order of the properties inside the Camera and Light Options groups (After Effects' own,
|
||||
/// as in 342 and 254 / 343: a record only where the value is not the default).
|
||||
const CAMERA_ORDER: &[&str] =
|
||||
&["ADBE Camera Zoom", "ADBE Camera Depth of Field", "ADBE Camera Focus Distance", "ADBE Camera Aperture", "ADBE Camera Blur Level"];
|
||||
const LIGHT_ORDER: &[&str] = &[
|
||||
"ADBE Light Env Atom",
|
||||
"ADBE Light Backgd Visible",
|
||||
"ADBE Light Backgd Opacity",
|
||||
"ADBE Light Backgd Blur",
|
||||
"ADBE Light Intensity",
|
||||
"ADBE Light Color",
|
||||
"ADBE Light Cone Angle",
|
||||
"ADBE Light Cone Feather 2",
|
||||
"ADBE Light Falloff Start",
|
||||
"ADBE Light Falloff Distance",
|
||||
"ADBE Casts Shadows",
|
||||
];
|
||||
|
||||
/// Sets (or inserts) the records of an options group (`tdmn` named `group`) of a layer.
|
||||
fn put_group(layr: &mut Chunk<'static>, group: &str, order: &[&str], set: Vec<(&str, Chunk<'static>)>, remove: &[&str]) -> R<()> {
|
||||
let root = list_mut(layr, b"tdgp")?;
|
||||
let kids = kids_mut(root)?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, group)).ok_or_else(|| tpl("options group missing"))?;
|
||||
let g = kids.get_mut(at + 1).ok_or_else(|| tpl("options group without a list"))?;
|
||||
let gk = kids_mut(g)?;
|
||||
// An atom group (Light Env Atom) carries its own Group End inside its list.
|
||||
let (header, mut pairs) = split_group(gk)?;
|
||||
pairs.retain(|(n, _)| !remove.contains(&n.as_str()));
|
||||
for (name, rec) in set {
|
||||
let entry = vec![tdmn(name), rec];
|
||||
match pairs.iter_mut().find(|(n, _)| n == name) {
|
||||
Some(slot) => slot.1 = entry,
|
||||
None => pairs.push((name.to_string(), entry)),
|
||||
}
|
||||
}
|
||||
let rank = |n: &str| if n == GROUP_END { usize::MAX } else { order.iter().position(|g| *g == n).unwrap_or(order.len()) };
|
||||
pairs.sort_by_key(|(n, _)| rank(n));
|
||||
gk.extend(header);
|
||||
gk.extend(pairs.into_iter().flat_map(|(_, v)| v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A copy of `proto` with the plain value `v` (`cdat` @0).
|
||||
fn with_value(mut proto: Chunk<'static>, v: f64) -> R<Chunk<'static>> {
|
||||
put_f64(child_data(&mut proto, b"cdat")?, 0, v)?;
|
||||
Ok(proto)
|
||||
}
|
||||
|
||||
pub(crate) fn put_camera(layr: &mut Chunk<'static>, protos: &OptionProtos, p: &CameraPlan) -> R<()> {
|
||||
// Every option is written explicitly (After Effects' defaults depend on the composition
|
||||
// width); Zoom and Blur Level take the plain-double layout of Focus Distance (342).
|
||||
let plain = protos.get("ADBE Camera Focus Distance")?;
|
||||
let set = vec![
|
||||
("ADBE Camera Zoom", with_value(plain.clone(), p.zoom)?),
|
||||
("ADBE Camera Depth of Field", with_value(protos.get("ADBE Camera Depth of Field")?, if p.dof { 1.0 } else { 0.0 })?),
|
||||
("ADBE Camera Focus Distance", with_value(plain.clone(), p.focus)?),
|
||||
("ADBE Camera Aperture", with_value(protos.get("ADBE Camera Aperture")?, p.aperture)?),
|
||||
("ADBE Camera Blur Level", with_value(plain, p.blur)?),
|
||||
];
|
||||
put_group(layr, "ADBE Camera Options Group", CAMERA_ORDER, set, &[])
|
||||
}
|
||||
|
||||
pub(crate) fn put_light(layr: &mut Chunk<'static>, protos: &OptionProtos, p: &LightPlan) -> R<()> {
|
||||
let mut set = Vec::new();
|
||||
let mut remove = Vec::new();
|
||||
if (p.intensity - 100.0).abs() > 1e-9 {
|
||||
set.push(("ADBE Light Intensity", with_value(protos.get("ADBE Light Intensity")?, p.intensity)?));
|
||||
} else {
|
||||
remove.push("ADBE Light Intensity");
|
||||
}
|
||||
if p.color != [255.0; 4] {
|
||||
let mut rec = protos.get("ADBE Light Color")?;
|
||||
let d = child_data(&mut rec, b"cdat")?;
|
||||
for (i, v) in p.color.iter().enumerate() {
|
||||
put_f64(d, i * 8, *v)?;
|
||||
}
|
||||
set.push(("ADBE Light Color", rec));
|
||||
}
|
||||
// A spot light stores its cone only when it differs (343-345); a point light keeps the inert
|
||||
// records of its block (252).
|
||||
if p.kind == 1 {
|
||||
if (p.cone_angle - 90.0).abs() > 1e-9 {
|
||||
set.push(("ADBE Light Cone Angle", with_value(protos.get("ADBE Light Cone Angle")?, p.cone_angle)?));
|
||||
}
|
||||
if (p.cone_feather - 50.0).abs() > 1e-9 {
|
||||
set.push(("ADBE Light Cone Feather 2", with_value(protos.get("ADBE Light Cone Feather 2")?, p.cone_feather)?));
|
||||
}
|
||||
}
|
||||
put_group(layr, "ADBE Light Options Group", LIGHT_ORDER, set, &remove)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,653 @@
|
||||
//! Footage items (files), built in code per kind ([`FtProtos::build`]) with the layout of the items
|
||||
//! After Effects writes when it imports a file of that kind: png still 607, jpeg 605, OpenEXR 604,
|
||||
//! TIFF 613, H.264 mp4 606, QuickTime mov 612, WAV 351, png sequence 353, OpenEXR sequence 603,
|
||||
//! jpeg sequence 611, Targa, Photoshop, Illustrator and EPS 650-653. The colour management names
|
||||
//! our own sRGB profile (`icc.rs`). The exporter then writes the decoded fields
|
||||
//! (`docs/aep-format.md` 3.3, `docs/aep-export.md` R28):
|
||||
//!
|
||||
//! * the alias JSON (`Als2/alas`): the full path, for a sequence its folder with
|
||||
//! `target_is_folder`;
|
||||
//! * `sspc`: width, height, duration (`num / den`), native frame rate, for sequences the first and
|
||||
//! last frame number and the digits, and the folder's modification time when the caller gives
|
||||
//! it ([`crate::export::export_with`]); the two `Utf8` around the number;
|
||||
//! * `opti` of png: width, height and the first file's name;
|
||||
//! * the item header: id, label, name; a fresh `pgui`.
|
||||
//!
|
||||
//! After Effects reads the format options of the other kinds from the file (their `opti` beyond
|
||||
//! the header can be zero: read-backs v-fN-zoptiA).
|
||||
|
||||
use effectcraft_project::{Footage, FootageKind};
|
||||
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
|
||||
/// The prototype a footage item is cloned from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum FtKind {
|
||||
Png,
|
||||
Jpeg,
|
||||
Exr,
|
||||
Mp4,
|
||||
Wav,
|
||||
PngSeq,
|
||||
ExrSeq,
|
||||
JpegSeq,
|
||||
Mov,
|
||||
Tiff,
|
||||
Tga,
|
||||
Psd,
|
||||
Ai,
|
||||
Eps,
|
||||
}
|
||||
|
||||
impl FtKind {
|
||||
/// The key a kind's prototype is found under.
|
||||
pub(crate) fn key(self) -> [u8; 4] {
|
||||
match self {
|
||||
FtKind::Png => *b"png ",
|
||||
FtKind::Jpeg => *b"jpg ",
|
||||
FtKind::Exr => *b"exr ",
|
||||
FtKind::Mp4 => *b"mp4 ",
|
||||
FtKind::Wav => *b"wav ",
|
||||
FtKind::PngSeq => *b"pngS",
|
||||
FtKind::ExrSeq => *b"exrS",
|
||||
FtKind::JpegSeq => *b"jpgS",
|
||||
FtKind::Mov => *b"mov ",
|
||||
FtKind::Tiff => *b"tif ",
|
||||
FtKind::Tga => *b"tga ",
|
||||
FtKind::Psd => *b"psd ",
|
||||
FtKind::Ai => *b"ai ",
|
||||
FtKind::Eps => *b"eps ",
|
||||
}
|
||||
}
|
||||
|
||||
/// The denominator of a still's duration (`sspc@42`: png 1, jpeg 600, OpenEXR 100).
|
||||
fn still_den(self) -> u32 {
|
||||
match self {
|
||||
FtKind::Jpeg | FtKind::Tiff | FtKind::Tga | FtKind::Psd | FtKind::Ai | FtKind::Eps => 600,
|
||||
FtKind::Exr => 100,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_sequence(self) -> bool {
|
||||
matches!(self, FtKind::PngSeq | FtKind::ExrSeq | FtKind::JpegSeq)
|
||||
}
|
||||
}
|
||||
|
||||
/// The numbering of a sequence.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Numbering {
|
||||
pub prefix: String,
|
||||
pub suffix: String,
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
pub digits: u32,
|
||||
}
|
||||
|
||||
/// A footage item in the file's units.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct FootagePlan {
|
||||
pub kind: FtKind,
|
||||
/// The alias target: the file, or a sequence's folder.
|
||||
pub alias: String,
|
||||
/// The (first) file's path as the project stores it: what the caller of
|
||||
/// [`crate::export::export_with`] checks before it reads the sequence folder's time.
|
||||
pub source: String,
|
||||
/// The (first) file's name.
|
||||
pub file_name: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Duration as stored, `num / den` seconds.
|
||||
pub duration: (u32, u32),
|
||||
/// Native frame rate (sequences and clips), 0 otherwise.
|
||||
pub fps: u32,
|
||||
/// The rate a clip is conformed to (`sspc@146`, also the effective rate at @150; 645), 0 when
|
||||
/// it plays at its native rate.
|
||||
pub conform: u32,
|
||||
pub numbering: Option<Numbering>,
|
||||
/// The duration in seconds (the Time Remapping maximum of a layer showing it).
|
||||
pub seconds: f64,
|
||||
/// A sequence's folder modification time as stored (`sspc@118`, seconds since 1904, UTC; 860),
|
||||
/// when the caller supplied it ([`crate::export::export_with`]).
|
||||
pub folder_time: Option<u32>,
|
||||
}
|
||||
|
||||
/// Seconds between 1904-01-01 (the stored time's epoch) and 1970-01-01.
|
||||
const SECONDS_1904_TO_1970: u64 = 2_082_844_800;
|
||||
|
||||
/// Fills in the folder time of every image sequence in `root` (folders included) from
|
||||
/// `folder_time`, asked with the sequence's first file as the project stores it (seconds since
|
||||
/// 1970); a time that does not fit the stored field is left out.
|
||||
pub(crate) fn stamp_sequences(root: &mut [crate::export::plan::Entry], folder_time: &dyn Fn(&str) -> Option<u64>) {
|
||||
use crate::export::plan::ItemPlan;
|
||||
// Folders were planned with a bounded depth; walk them with an explicit stack anyway.
|
||||
let mut stack: Vec<&mut [crate::export::plan::Entry]> = vec![root];
|
||||
while let Some(entries) = stack.pop() {
|
||||
for e in entries.iter_mut() {
|
||||
match &mut e.plan {
|
||||
ItemPlan::Folder(kids) => stack.push(kids),
|
||||
ItemPlan::Footage(fp) if fp.kind.is_sequence() => {
|
||||
fp.folder_time = folder_time(&fp.source).and_then(|t| u32::try_from(t.checked_add(SECONDS_1904_TO_1970)?).ok());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ext(path: &str) -> String {
|
||||
let name = path.rsplit(['\\', '/']).next().unwrap_or_default();
|
||||
match name.rsplit_once('.') {
|
||||
Some((_, e)) => e.to_ascii_lowercase(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn split_dir(path: &str) -> (&str, &str) {
|
||||
match path.rfind(['\\', '/']) {
|
||||
Some(i) => (path.get(..i).unwrap_or_default(), path.get(i + 1..).unwrap_or_default()),
|
||||
None => ("", path),
|
||||
}
|
||||
}
|
||||
|
||||
/// `shot_0101.exr` -> (`shot_`, 101, 4, `.exr`): the last run of digits before the extension.
|
||||
fn parse_numbered(name: &str) -> Option<(String, u32, u32, String)> {
|
||||
let dot = name.rfind('.').unwrap_or(name.len());
|
||||
let stem = name.get(..dot)?;
|
||||
let digits = stem.chars().rev().take_while(char::is_ascii_digit).count();
|
||||
if digits == 0 || digits > 9 {
|
||||
return None;
|
||||
}
|
||||
let split = stem.len().checked_sub(digits)?;
|
||||
let number: u32 = stem.get(split..)?.parse().ok()?;
|
||||
Some((stem.get(..split)?.to_string(), number, u32::try_from(digits).ok()?, name.get(dot..)?.to_string()))
|
||||
}
|
||||
|
||||
/// Whole frames at an integer rate, or `None` (a rate After Effects' footage header stores as an
|
||||
/// integer: 30 in 353 and 603, 25 in 606).
|
||||
fn integer_rate(f: &Footage) -> Option<u32> {
|
||||
let r = f.frame_rate;
|
||||
(r.den == 1 && r.num > 0).then(|| u32::try_from(r.num).ok()).flatten()
|
||||
}
|
||||
|
||||
/// Plans one footage item, or reports why it cannot be written.
|
||||
pub(crate) fn plan_footage(name: &str, f: &Footage, col: &mut Collector) -> Option<FootagePlan> {
|
||||
let what = |why: &str| format!("footage '{name}': {why}");
|
||||
if f.layer.is_some() {
|
||||
col.lose(LossCategory::FootageItems, what("one layer of a layered file is not exported"));
|
||||
return None;
|
||||
}
|
||||
// Interpret Footage settings other than the defaults are not written (After Effects
|
||||
// interprets the file itself).
|
||||
let d = Footage::default();
|
||||
let unwritten = [
|
||||
((f.pixel_aspect - d.pixel_aspect).abs() > 1e-9, "pixel aspect"),
|
||||
(f.alpha != d.alpha || f.premul_color != d.premul_color, "alpha interpretation"),
|
||||
(f.invert_alpha, "Invert Alpha"),
|
||||
(f.loop_count != d.loop_count, "loop count"),
|
||||
(f.color_profile.is_some(), "colour profile"),
|
||||
(f.fields != d.fields, "field order"),
|
||||
(f.linear_light != d.linear_light, "Interpret As Linear Light"),
|
||||
(f.preserve_rgb != d.preserve_rgb, "Preserve RGB"),
|
||||
(f.cineon != d.cineon, "Cineon settings"),
|
||||
];
|
||||
for (_, setting) in unwritten.iter().filter(|(on, _)| *on) {
|
||||
col.lose(LossCategory::FootageItems, what(&format!("the Interpret Footage {setting} is not written (the default is)")));
|
||||
}
|
||||
let e = ext(&f.path);
|
||||
let kind = match (f.kind, e.as_str()) {
|
||||
(FootageKind::Still, "png") => FtKind::Png,
|
||||
(FootageKind::Still, "jpg" | "jpeg") => FtKind::Jpeg,
|
||||
(FootageKind::Still, "exr") => FtKind::Exr,
|
||||
(FootageKind::Still, "tif" | "tiff") => FtKind::Tiff,
|
||||
(FootageKind::Still, "tga") => FtKind::Tga,
|
||||
(FootageKind::Still, "psd") => FtKind::Psd,
|
||||
(FootageKind::Still, "ai") => FtKind::Ai,
|
||||
(FootageKind::Still, "eps") => FtKind::Eps,
|
||||
(FootageKind::Sequence, "jpg" | "jpeg") => FtKind::JpegSeq,
|
||||
(FootageKind::Video, "mov") => FtKind::Mov,
|
||||
(FootageKind::Sequence, "png") => FtKind::PngSeq,
|
||||
(FootageKind::Sequence, "exr") => FtKind::ExrSeq,
|
||||
(FootageKind::Video, "mp4" | "m4v") => FtKind::Mp4,
|
||||
(FootageKind::Audio, "wav") => FtKind::Wav,
|
||||
_ => {
|
||||
col.lose(LossCategory::FootageItems, what(&format!("{:?} footage of type '.{e}' is not exported (no prototype)", f.kind)));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if f.path.is_empty() || f.path.chars().any(char::is_control) {
|
||||
col.lose(LossCategory::FootageItems, what("no usable path"));
|
||||
return None;
|
||||
}
|
||||
if f.width > crate::export::plan::MAX_SIDE || f.height > crate::export::plan::MAX_SIDE {
|
||||
col.lose(
|
||||
LossCategory::FootageItems,
|
||||
what(&format!("size {} x {} is larger than {}, written smaller", f.width, f.height, crate::export::plan::MAX_SIDE)),
|
||||
);
|
||||
}
|
||||
let width = f.width.min(crate::export::plan::MAX_SIDE);
|
||||
let height = f.height.min(crate::export::plan::MAX_SIDE);
|
||||
let (dir, file) = split_dir(&f.path);
|
||||
let mut plan = FootagePlan {
|
||||
kind,
|
||||
alias: f.path.clone(),
|
||||
source: f.path.clone(),
|
||||
file_name: file.to_string(),
|
||||
width,
|
||||
height,
|
||||
duration: (0, kind.still_den()),
|
||||
fps: 0,
|
||||
conform: 0,
|
||||
numbering: None,
|
||||
seconds: 0.0,
|
||||
folder_time: None,
|
||||
};
|
||||
match kind {
|
||||
FtKind::PngSeq | FtKind::ExrSeq | FtKind::JpegSeq => {
|
||||
let Some(fps) = integer_rate(f) else {
|
||||
col.lose(
|
||||
LossCategory::FootageItems,
|
||||
what(&format!("a sequence at {} fps is not exported (only whole rates are sampled)", f.frame_rate.label())),
|
||||
);
|
||||
return None;
|
||||
};
|
||||
let Some((prefix, start, digits, suffix)) = parse_numbered(file) else {
|
||||
col.lose(LossCategory::FootageItems, what("a sequence whose first file has no frame number"));
|
||||
return None;
|
||||
};
|
||||
// The files must be the run start, start + 1, ... with the same name around the number.
|
||||
let files: Vec<&str> = if f.sequence.is_empty() { vec![file] } else { f.sequence.iter().map(|p| split_dir(p).1).collect() };
|
||||
let mut expect = start;
|
||||
for name in &files {
|
||||
let ok = parse_numbered(name).is_some_and(|(p, n, _, s)| p == prefix && s == suffix && n == expect);
|
||||
if !ok {
|
||||
col.lose(LossCategory::FootageItems, what("a sequence with gaps or mixed names is not exported"));
|
||||
return None;
|
||||
}
|
||||
expect = expect.saturating_add(1);
|
||||
}
|
||||
let count = u32::try_from(files.len()).unwrap_or(u32::MAX);
|
||||
plan.alias = dir.to_string();
|
||||
plan.fps = fps;
|
||||
plan.duration = (count, fps);
|
||||
plan.seconds = f64::from(count) / f64::from(fps.max(1));
|
||||
plan.numbering = Some(Numbering { prefix, suffix, start, end: start.saturating_add(count.saturating_sub(1)), digits });
|
||||
if dir.is_empty() {
|
||||
col.lose(LossCategory::FootageItems, what("a sequence without a folder"));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
FtKind::Mp4 | FtKind::Mov => {
|
||||
let Some(fps) = integer_rate(f) else {
|
||||
col.lose(LossCategory::FootageItems, what(&format!("a clip at {} fps is not exported (only whole rates are sampled)", f.frame_rate.label())));
|
||||
return None;
|
||||
};
|
||||
// A conformed clip (645): the frames play at `fps`, the stored duration stays in the
|
||||
// native rate's frames, and the conformed rate goes to @146 and @150.
|
||||
let native = match f.native_rate {
|
||||
Some(n) if n != f.frame_rate => {
|
||||
if n.den == 1 && n.num > 0 && n.num <= i64::from(u32::MAX) {
|
||||
u32::try_from(n.num).ok()
|
||||
} else {
|
||||
col.lose(
|
||||
LossCategory::FootageItems,
|
||||
what(&format!("a clip with the native rate {} fps is written at its conformed rate only", n.label())),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let frames = (f.duration.seconds() * f64::from(fps)).round();
|
||||
let frames = if frames.is_finite() && frames >= 1.0 && frames < f64::from(u32::MAX) {
|
||||
frames as u32
|
||||
} else {
|
||||
col.lose(LossCategory::FootageItems, what("a duration that cannot be stored, written as 1 frame"));
|
||||
1
|
||||
};
|
||||
plan.seconds = f64::from(frames) / f64::from(fps.max(1));
|
||||
match native {
|
||||
Some(n) => {
|
||||
plan.fps = n;
|
||||
plan.conform = fps;
|
||||
plan.duration = (frames, n);
|
||||
}
|
||||
None => {
|
||||
plan.fps = fps;
|
||||
plan.duration = (frames, fps);
|
||||
}
|
||||
}
|
||||
}
|
||||
FtKind::Wav => {
|
||||
// The sample rate is the denominator (351: 48 000 / 48 000 for 1 s).
|
||||
let secs = f.duration.seconds();
|
||||
let samples = (secs * 48_000.0).round();
|
||||
let samples = if samples.is_finite() && samples >= 1.0 && samples < f64::from(u32::MAX) {
|
||||
samples as u32
|
||||
} else {
|
||||
col.lose(LossCategory::FootageItems, what("a duration that cannot be stored, written as 1 second"));
|
||||
48_000
|
||||
};
|
||||
plan.duration = (samples, 48_000);
|
||||
plan.seconds = f64::from(samples) / 48_000.0;
|
||||
}
|
||||
FtKind::Png | FtKind::Jpeg | FtKind::Exr | FtKind::Tiff | FtKind::Tga | FtKind::Psd | FtKind::Ai | FtKind::Eps => {}
|
||||
}
|
||||
col.exported.footage = col.exported.footage.saturating_add(1);
|
||||
Some(plan)
|
||||
}
|
||||
|
||||
/// The alias JSON After Effects reads (`Als2/alas`, 126, 351, 353, 603), with the path escaped.
|
||||
pub(crate) fn alias_json(p: &FootagePlan) -> Vec<u8> {
|
||||
let mut path = String::with_capacity(p.alias.len() + 8);
|
||||
for c in p.alias.chars() {
|
||||
match c {
|
||||
'"' => path.push_str("\\\""),
|
||||
'\\' => path.push_str("\\\\"),
|
||||
c if (c as u32) < 0x20 => path.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => path.push(c),
|
||||
}
|
||||
}
|
||||
let folder = p.kind.is_sequence();
|
||||
format!(
|
||||
"{{\"ascendcount_base\":1,\"ascendcount_target\":{},\"fullpath\":\"{path}\",\"platform\":1,\"server_name\":\"\",\"server_volume_name\":\"\",\"target_is_folder\":{folder}}}",
|
||||
if folder { 2 } else { 1 }
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Emit.
|
||||
|
||||
use crate::Chunk;
|
||||
|
||||
use crate::export::tree::{R, child_data, kids_mut, list_mut, put, put_cstr, put_u8, put_u16, put_u32, tpl};
|
||||
|
||||
/// The footage prototypes: per kind the item and the f-records that follow it.
|
||||
pub(crate) struct FtProtos {
|
||||
items: Vec<([u8; 4], Vec<Chunk<'static>>)>,
|
||||
}
|
||||
|
||||
/// Every kind the exporter writes.
|
||||
const KINDS: [FtKind; 14] = [
|
||||
FtKind::Png,
|
||||
FtKind::Jpeg,
|
||||
FtKind::Exr,
|
||||
FtKind::Mp4,
|
||||
FtKind::Wav,
|
||||
FtKind::PngSeq,
|
||||
FtKind::ExrSeq,
|
||||
FtKind::JpegSeq,
|
||||
FtKind::Mov,
|
||||
FtKind::Tiff,
|
||||
FtKind::Tga,
|
||||
FtKind::Psd,
|
||||
FtKind::Ai,
|
||||
FtKind::Eps,
|
||||
];
|
||||
|
||||
/// The colour management a kind's item carries (`Pin /CLRS`, 351, 353, 603-607, 611-613, 650-653).
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Clrs {
|
||||
/// Stills, sequences and audio: interpreted in the sRGB profile (`apid` its id).
|
||||
Assigned,
|
||||
/// A file with an embedded profile (TIFF, Photoshop): `epid` its id, the profile twice.
|
||||
Embedded,
|
||||
/// Video and JPEG: Rec. 709 with the codec's colour description.
|
||||
Video(&'static str),
|
||||
}
|
||||
|
||||
/// The colour description After Effects gives a JPEG, a jpeg sequence and a ProRes clip.
|
||||
const BT709_FULL: &str = r#"{"baseColorProfile":{"colorProfileName":"BT.709 RGB Full"},"baseProfileType":1}"#;
|
||||
/// The colour description of an H.264 clip.
|
||||
const BT709_DISPLAY: &str =
|
||||
r#"{"baseColorProfile":{"colorProfileData":"AQAAAP////8=","colorProfileName":"BT.709,8-bit,Display-Referred"},"baseProfileType":1}"#;
|
||||
|
||||
/// What a kind's item stores beyond the decoded fields: the file type tag (`sspc` 22, `opti` 0),
|
||||
/// `idta` byte 23, the bits per pixel of the sampled file (`sspc` 63), `sspc` byte 73 (3, 1 for
|
||||
/// OpenEXR, 0 for Illustrator and EPS), the `opti` size and its header bytes 4, 5 and 10 (the rest of
|
||||
/// `opti` can be zero: read-back v-fN-zoptiA), and the colour management.
|
||||
struct KindSpec {
|
||||
tag: [u8; 4],
|
||||
idta23: u8,
|
||||
bpp: u8,
|
||||
b73: u8,
|
||||
opti: (u16, u8, u8, u8),
|
||||
clrs: Clrs,
|
||||
}
|
||||
|
||||
fn spec(kind: FtKind) -> KindSpec {
|
||||
let (tag, idta23, bpp, b73, opti, clrs) = match kind {
|
||||
FtKind::Png => (*b"png!", 0x30, 24, 3, (322, 0, 1, 1), Clrs::Assigned),
|
||||
FtKind::Jpeg => (*b"ZPEG", 0x30, 24, 3, (58, 0, 5, 0), Clrs::Video(BT709_FULL)),
|
||||
FtKind::Exr => (*b"oEXR", 0x30, 128, 1, (9750, 0, 1, 1), Clrs::Assigned),
|
||||
FtKind::Mp4 => (*b"XCEX", 0x20, 24, 3, (58, 0, 5, 0), Clrs::Video(BT709_DISPLAY)),
|
||||
FtKind::Wav => (*b"WAVE", 0x04, 0, 3, (58, 0, 5, 0), Clrs::Assigned),
|
||||
FtKind::PngSeq => (*b"png!", 0x20, 24, 3, (322, 0, 1, 1), Clrs::Assigned),
|
||||
FtKind::ExrSeq => (*b"oEXR", 0x20, 128, 1, (9750, 0, 1, 1), Clrs::Assigned),
|
||||
FtKind::JpegSeq => (*b"ZPEG", 0x20, 24, 3, (58, 0, 5, 0), Clrs::Video(BT709_FULL)),
|
||||
FtKind::Mov => (*b"MOoV", 0x20, 48, 3, (58, 0, 5, 0), Clrs::Video(BT709_FULL)),
|
||||
FtKind::Tiff => (*b"TIF ", 0x30, 24, 3, (602, 1, 9, 0), Clrs::Embedded),
|
||||
FtKind::Tga => (*b"TPIC", 0x30, 24, 3, (30, 0, 46, 5), Clrs::Assigned),
|
||||
FtKind::Psd => (*b"8BPS", 0x30, 24, 3, (602, 1, 9, 0), Clrs::Embedded),
|
||||
FtKind::Ai | FtKind::Eps => (*b"TEXT", 0x30, 32, 0, (596, 0, 8, 0), Clrs::Assigned),
|
||||
};
|
||||
KindSpec { tag, idta23, bpp, b73, opti, clrs }
|
||||
}
|
||||
|
||||
/// The colour-management list of a kind (the order After Effects writes).
|
||||
fn clrs(kind: Clrs) -> Chunk<'static> {
|
||||
use crate::export::base::utf8;
|
||||
let icc = crate::export::icc::srgb();
|
||||
let id = crate::export::icc::profile_id(&icc).to_vec();
|
||||
let json = crate::export::icc::profile_json(&icc, crate::export::icc::SRGB_NAME);
|
||||
let none = vec![0xffu8; 16];
|
||||
let one = |id: &[u8; 4]| Chunk::data(*id, vec![1u8]);
|
||||
let tail = |kids: &mut Vec<Chunk<'static>>| {
|
||||
kids.push(one(b"hdrm"));
|
||||
kids.push(utf8("{}"));
|
||||
};
|
||||
let mut kids = match kind {
|
||||
Clrs::Assigned => vec![
|
||||
Chunk::data(*b"epid", none),
|
||||
Chunk::data(*b"apid", id),
|
||||
Chunk::data(*b"linl", vec![2, 0, 0, 0]),
|
||||
one(b"embp"),
|
||||
Chunk::data(*b"ipws", vec![0]),
|
||||
one(b"Mcsp"),
|
||||
utf8(""),
|
||||
one(b"ocsp"),
|
||||
utf8(&json),
|
||||
],
|
||||
Clrs::Embedded => vec![
|
||||
Chunk::data(*b"epid", id),
|
||||
Chunk::data(*b"apid", none),
|
||||
Chunk::data(*b"linl", vec![2, 0, 0, 0]),
|
||||
one(b"embp"),
|
||||
Chunk::data(*b"ipws", vec![0]),
|
||||
one(b"mcsp"),
|
||||
utf8(&json),
|
||||
one(b"Mcsp"),
|
||||
utf8(&json),
|
||||
one(b"ocsp"),
|
||||
utf8(""),
|
||||
],
|
||||
Clrs::Video(desc) => vec![
|
||||
Chunk::data(*b"epid", none.clone()),
|
||||
Chunk::data(*b"apid", none),
|
||||
one(b"empd"),
|
||||
utf8("Rec. 709"),
|
||||
Chunk::data(*b"linl", vec![0; 4]),
|
||||
one(b"embp"),
|
||||
Chunk::data(*b"ipws", vec![0]),
|
||||
one(b"mcsp"),
|
||||
utf8(desc),
|
||||
one(b"Mcsp"),
|
||||
utf8(desc),
|
||||
one(b"ocsp"),
|
||||
utf8(""),
|
||||
],
|
||||
};
|
||||
tail(&mut kids);
|
||||
Chunk::list(*b"CLRS", kids)
|
||||
}
|
||||
|
||||
/// The item of a kind with zero ids and an empty alias (`build_footage` fills them), and the
|
||||
/// f-records after it. `sspc` holds the tag, the bits per pixel, the time base of a still (600:
|
||||
/// a clip's is its rate, written per item) and the bytes that have the same value in every
|
||||
/// generated test file of the kind (125, 129,
|
||||
/// 139, 143, 188..195; a sequence also 168, 184, 186, 187; a WAV its sample rate at 160); the bytes
|
||||
/// left zero were zero in read-backs v-fN-zsspc1..3. `mnfo` is left out (v-fN-nomnfo).
|
||||
fn kind_item(kind: FtKind) -> Vec<Chunk<'static>> {
|
||||
use crate::export::base::{bytes, utf8};
|
||||
let s = spec(kind);
|
||||
let mut fields: Vec<(usize, Vec<u8>)> = vec![
|
||||
(22, s.tag.to_vec()),
|
||||
(50, 600u32.to_be_bytes().to_vec()),
|
||||
(63, vec![s.bpp]),
|
||||
(73, vec![s.b73]),
|
||||
(125, vec![0x0c]),
|
||||
(129, vec![1]),
|
||||
(139, vec![1]),
|
||||
(143, vec![1]),
|
||||
(188, vec![0xff; 8]),
|
||||
];
|
||||
if kind.is_sequence() {
|
||||
fields.extend([(168, 2u32.to_be_bytes().to_vec()), (184, vec![1]), (186, vec![1, 1])]);
|
||||
}
|
||||
if kind == FtKind::Wav {
|
||||
fields.push((160, 48_000f64.to_be_bytes().to_vec()));
|
||||
}
|
||||
let refs: Vec<(usize, &[u8])> = fields.iter().map(|(at, v)| (*at, v.as_slice())).collect();
|
||||
let (len, b4, b5, b10) = s.opti;
|
||||
let opti = bytes(usize::from(len), &[(0, &s.tag), (4, &[b4, b5]), (8, &len.to_be_bytes()), (10, &[b10])]);
|
||||
let mut pin = vec![Chunk::data(*b"sspc", bytes(222, &refs)), utf8(""), Chunk::list(*b"Als2", vec![Chunk::data(*b"alas", b"{}".to_vec())])];
|
||||
if kind.is_sequence() {
|
||||
pin.extend([utf8(""), utf8("")]);
|
||||
}
|
||||
pin.extend([Chunk::data(*b"opti", opti), Chunk::data(*b"pgui", vec![0; 16]), clrs(s.clrs), utf8("")]);
|
||||
let item = Chunk::list(
|
||||
*b"Item",
|
||||
vec![
|
||||
Chunk::data(*b"iide", vec![0; 4]),
|
||||
Chunk::data(*b"idpc", vec![0; 8]),
|
||||
crate::export::base::idta(7, s.idta23),
|
||||
utf8(""),
|
||||
Chunk::list(*b"Pin ", pin),
|
||||
crate::export::base::ftgi(),
|
||||
utf8(""),
|
||||
crate::export::base::guides(),
|
||||
],
|
||||
);
|
||||
let mut out = vec![item];
|
||||
out.extend(crate::export::skeleton::f_records());
|
||||
out
|
||||
}
|
||||
|
||||
impl FtProtos {
|
||||
/// The items of every kind, built in code.
|
||||
pub(crate) fn build() -> FtProtos {
|
||||
FtProtos { items: KINDS.iter().map(|k| (k.key(), kind_item(*k))).collect() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The item (and its f-records) for `p`, with the id, label and name, and a fresh `pgui`.
|
||||
pub(crate) fn build_footage(protos: &FtProtos, id: u32, label: u8, name: &str, p: &FootagePlan, guid: [u8; 16]) -> R<Vec<Chunk<'static>>> {
|
||||
let key = p.kind.key();
|
||||
let mut chunks = protos.items.iter().find(|(k, _)| *k == key).map(|(_, v)| v.clone()).ok_or_else(|| tpl("footage prototype missing"))?;
|
||||
let item = chunks.get_mut(0).ok_or_else(|| tpl("empty footage prototype"))?;
|
||||
put(child_data(item, b"iide")?, 0, &id.to_le_bytes())?;
|
||||
{
|
||||
let idta = child_data(item, b"idta")?;
|
||||
put_u32(idta, 16, id)?;
|
||||
put_u8(idta, 58, label)?;
|
||||
}
|
||||
// After Effects names a footage item after its file and then stores no name of its own (126,
|
||||
// 603-607); a name of the user's is the item's `Utf8`. The WAV prototype keeps the name (351).
|
||||
let default = match &p.numbering {
|
||||
Some(n) => format!("{}[{:0w$}-{:0w$}]{}", n.prefix, n.start, n.end, n.suffix, w = usize::try_from(n.digits.min(16)).unwrap_or(0)),
|
||||
None => p.file_name.clone(),
|
||||
};
|
||||
let stored = if name == default && p.kind != FtKind::Wav { "" } else { name };
|
||||
crate::export::tree::set_utf8(item, stored)?;
|
||||
let pin = list_mut(item, b"Pin ")?;
|
||||
{
|
||||
let sspc = child_data(pin, b"sspc")?;
|
||||
put_u32(sspc, 30, p.width)?;
|
||||
put_u32(sspc, 34, p.height)?;
|
||||
put_u32(sspc, 38, p.duration.0)?;
|
||||
put_u32(sspc, 42, p.duration.1)?;
|
||||
if p.fps > 0 {
|
||||
// A clip counts its time in its native rate (606, 612: 25); stills, sequences and
|
||||
// audio in 600ths.
|
||||
if matches!(p.kind, FtKind::Mp4 | FtKind::Mov) {
|
||||
put_u32(sspc, 50, p.fps)?;
|
||||
}
|
||||
put_u32(sspc, 56, p.fps)?;
|
||||
put_u32(sspc, 150, if p.conform > 0 { p.conform } else { p.fps })?;
|
||||
}
|
||||
if p.conform > 0 {
|
||||
put_u32(sspc, 146, p.conform)?;
|
||||
}
|
||||
if let Some(n) = &p.numbering {
|
||||
put_u32(sspc, 172, n.start)?;
|
||||
put_u32(sspc, 176, n.end)?;
|
||||
put_u32(sspc, 180, n.digits)?;
|
||||
}
|
||||
if let (true, Some(t)) = (p.kind.is_sequence(), p.folder_time) {
|
||||
put_u32(sspc, 118, t)?;
|
||||
}
|
||||
}
|
||||
{
|
||||
let als = list_mut(pin, b"Als2")?;
|
||||
let alas = kids_mut(als)?.iter_mut().find(|c| c.is(b"alas")).ok_or_else(|| tpl("footage prototype without alias"))?;
|
||||
*alas = Chunk::data(*b"alas", alias_json(p));
|
||||
}
|
||||
if let Some(n) = &p.numbering {
|
||||
// The two Utf8 between the alias and opti: the name around the number (353, 603).
|
||||
let kids = kids_mut(pin)?;
|
||||
let at = kids.iter().position(|c| c.is_list(b"Als2")).ok_or_else(|| tpl("footage prototype without alias"))?;
|
||||
let mut names = [n.prefix.as_str(), n.suffix.as_str()].into_iter();
|
||||
for c in kids.iter_mut().skip(at + 1).take_while(|c| !c.is(b"opti")) {
|
||||
if c.is(b"Utf8")
|
||||
&& let Some(text) = names.next()
|
||||
{
|
||||
*c = Chunk::data(*b"Utf8", text.as_bytes().to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(p.kind, FtKind::Png | FtKind::PngSeq) {
|
||||
// png options: width and height (u16 at 20 and 24) and the (first) file's name at 58
|
||||
// (126, 353, 607).
|
||||
let opti = child_data(pin, b"opti")?;
|
||||
put_u16(opti, 20, u16::try_from(p.width).unwrap_or(u16::MAX))?;
|
||||
put_u16(opti, 24, u16::try_from(p.height).unwrap_or(u16::MAX))?;
|
||||
put_cstr(opti, 58, 256, &p.file_name)?;
|
||||
}
|
||||
put(child_data(pin, b"pgui")?, 0, &guid)?;
|
||||
Ok(chunks)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every kind's item has the chunks After Effects refuses it without (`CLRS`, `ftgi`: read-backs
|
||||
/// u-noclrs, u-noftgi) and the f-records after it; `opti` has its header and its size.
|
||||
#[test]
|
||||
fn every_kind_has_what_after_effects_needs() {
|
||||
let protos = FtProtos::build();
|
||||
assert_eq!(protos.items.len(), KINDS.len());
|
||||
for (key, chunks) in &protos.items {
|
||||
let what = String::from_utf8_lossy(key).into_owned();
|
||||
let item = &chunks[0];
|
||||
let pin = item.child_list(b"Pin ").unwrap();
|
||||
assert!(pin.child_list(b"CLRS").is_some() && item.child(b"ftgi").is_some(), "{what}");
|
||||
assert_eq!(chunks.len(), 8, "{what}: the item and seven f-records");
|
||||
let opti = pin.child(b"opti").and_then(|c| c.bytes()).unwrap();
|
||||
assert_eq!(usize::from(u16::from_be_bytes([opti[8], opti[9]])), opti.len(), "{what}");
|
||||
let sspc = pin.child(b"sspc").and_then(|c| c.bytes()).unwrap();
|
||||
assert_eq!(&sspc[22..26], &opti[0..4], "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,805 @@
|
||||
//! The effects the exporter writes and the parameters of each, in `parT` order: what After
|
||||
//! Effects shows for an effect (its match name and name, each parameter's id, type, default, slider
|
||||
//! range and valid maximum; aep-format.md 3.7). The exporter builds an effect's `parT` and value
|
||||
//! group from this table (`synth`); After Effects takes the full parameter definitions from the
|
||||
//! effect itself (read-back e1-zpardfull).
|
||||
//!
|
||||
//! The rows were listed from our effect cases (356-397 and the later effect batches) through the
|
||||
//! reader; `effect_map` names the parameters the importer and exporter convert.
|
||||
|
||||
/// The id of the `ADBE Effect Built In Params` entry, the last of every effect.
|
||||
pub(crate) const BUILT_IN: u16 = u16::MAX;
|
||||
|
||||
/// One parameter: its id (the `-NNNN` of its match name, not its position), its type (`pard`
|
||||
/// code: 0 layer, 1 integer slider, 2 fixed slider, 3 angle, 4 checkbox, 5 colour, 6 point, 7
|
||||
/// popup, 9 no data, 10 float slider, 11 arbitrary data, 12 path, 13 / 14 group start / end, 15
|
||||
/// button), its default in stored units, its slider range and its valid maximum.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct PDef {
|
||||
pub id: u16,
|
||||
pub code: u8,
|
||||
pub default: &'static [f64],
|
||||
pub range: Option<(f64, f64)>,
|
||||
pub valid_max: Option<f64>,
|
||||
/// The valid minimum of a slider.
|
||||
pub valid_min: Option<f64>,
|
||||
/// The display word of a slider: the decimals and the percent switch (fixed and integer
|
||||
/// `pard@144`, float `pard@124`: aep-format.md 3.7); of a popup, its item count.
|
||||
pub display: u32,
|
||||
}
|
||||
|
||||
/// One effect.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct FxDef {
|
||||
pub match_name: &'static str,
|
||||
/// The effect's name (`fnam`).
|
||||
pub name: &'static str,
|
||||
pub params: &'static [PDef],
|
||||
}
|
||||
|
||||
impl FxDef {
|
||||
/// The match name of parameter `p` (`ADBE Tint-0003`).
|
||||
pub fn record(&self, p: &PDef) -> String {
|
||||
if p.id == BUILT_IN { "ADBE Effect Built In Params".to_string() } else { format!("{}-{:04}", self.match_name, p.id) }
|
||||
}
|
||||
}
|
||||
|
||||
const fn p(id: u16, code: u8, default: &'static [f64], range: Option<(f64, f64)>, valid_max: Option<f64>, valid_min: Option<f64>, display: u32) -> PDef {
|
||||
PDef { id, code, default, range, valid_max, valid_min, display }
|
||||
}
|
||||
|
||||
const fn fx(match_name: &'static str, name: &'static str, params: &'static [PDef]) -> FxDef {
|
||||
FxDef { match_name, name, params }
|
||||
}
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub(crate) static FX_DEFS: &[FxDef] = &[
|
||||
fx("ADBE Tint", "Tint", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 5, &[0.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(2, 5, &[0.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
|
||||
p(3, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(4, 15, &[], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Ramp", "Gradient Ramp", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.5, 0.0], None, None, None, 0x00000000),
|
||||
p(2, 5, &[255.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(3, 6, &[0.5, 1.0], None, None, None, 0x00000000),
|
||||
p(4, 5, &[255.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
|
||||
p(5, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(6, 2, &[0.0], Some((0.0, 50.0)), Some(512.0), Some(0.0), 0x00010000),
|
||||
p(7, 2, &[0.0], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
|
||||
p(8, 15, &[], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Exposure2", "Exposure", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(2, 13, &[], None, None, None, 0x00000000),
|
||||
p(3, 10, &[0.0], Some((-4.0, 4.0)), Some(100.0), Some(-100.0), 0x00020000),
|
||||
p(4, 10, &[0.0], Some((-0.5, 0.5)), Some(2.0), Some(-2.0), 0x00040000),
|
||||
p(5, 10, &[1.0], Some((0.10000000149011612, 10.0)), Some(10.0), Some(0.10000000149011612), 0x00020000),
|
||||
p(6, 14, &[], None, None, None, 0x00000000),
|
||||
p(7, 13, &[], None, None, None, 0x00000000),
|
||||
p(8, 10, &[0.0], Some((-4.0, 4.0)), Some(100.0), Some(-100.0), 0x00020000),
|
||||
p(9, 10, &[0.0], Some((-0.5, 0.5)), Some(2.0), Some(-2.0), 0x00040000),
|
||||
p(10, 10, &[1.0], Some((0.10000000149011612, 10.0)), Some(10.0), Some(0.10000000149011612), 0x00020000),
|
||||
p(11, 14, &[], None, None, None, 0x00000000),
|
||||
p(12, 13, &[], None, None, None, 0x00000000),
|
||||
p(13, 10, &[0.0], Some((-4.0, 4.0)), Some(100.0), Some(-100.0), 0x00020000),
|
||||
p(14, 10, &[0.0], Some((-0.5, 0.5)), Some(2.0), Some(-2.0), 0x00040000),
|
||||
p(15, 10, &[1.0], Some((0.10000000149011612, 10.0)), Some(10.0), Some(0.10000000149011612), 0x00020000),
|
||||
p(16, 14, &[], None, None, None, 0x00000000),
|
||||
p(17, 13, &[], None, None, None, 0x00000000),
|
||||
p(18, 10, &[0.0], Some((-4.0, 4.0)), Some(100.0), Some(-100.0), 0x00020000),
|
||||
p(19, 10, &[0.0], Some((-0.5, 0.5)), Some(2.0), Some(-2.0), 0x00040000),
|
||||
p(20, 10, &[1.0], Some((0.10000000149011612, 10.0)), Some(10.0), Some(0.10000000149011612), 0x00020000),
|
||||
p(21, 14, &[], None, None, None, 0x00000000),
|
||||
p(22, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Invert", "Invert", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000010),
|
||||
p(2, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00000001),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Box Blur2", "Fast Box Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((0.0, 127.0)), Some(30000.0), Some(0.0), 0x00010000),
|
||||
p(2, 1, &[3.0], Some((1.0, 5.0)), Some(50.0), Some(1.0), 0x00000000),
|
||||
p(3, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(4, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Gaussian Blur 2", "Gaussian Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 10, &[25.0], Some((0.0, 50.0)), Some(30000.0), Some(0.0), 0x00010000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(3, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Drop Shadow", "Drop Shadow", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 5, &[255.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(2, 2, &[127.5], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000001),
|
||||
p(3, 3, &[135.0], None, None, None, 0x00000000),
|
||||
p(4, 2, &[5.0], Some((0.0, 120.0)), Some(4000.0), Some(0.0), 0x00010000),
|
||||
p(5, 2, &[0.0], Some((0.0, 250.0)), Some(30000.0), Some(0.0), 0x00010000),
|
||||
p(6, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Timewarp", "Timewarp", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[3.0], None, None, None, 0x00000003),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(3, 2, &[50.0], Some((-100.0, 100.0)), Some(5000.0), Some(-5000.0), 0x00020000),
|
||||
p(4, 2, &[0.0], Some((0.0, 1000.0)), Some(5000.0), Some(-5000.0), 0x00020000),
|
||||
p(5, 13, &[], None, None, None, 0x00000000),
|
||||
p(6, 2, &[20.0], Some((5.0, 100.0)), Some(100.0), Some(5.0), 0x00020000),
|
||||
p(7, 13, &[], None, None, None, 0x00000000),
|
||||
p(8, 2, &[500.0], Some((-1000.0, 1000.0)), Some(5000.0), Some(-5000.0), 0x00020000),
|
||||
p(9, 2, &[500.0], Some((-1000.0, 1000.0)), Some(5000.0), Some(-5000.0), 0x00020000),
|
||||
p(10, 1, &[5.0], Some((1.0, 50.0)), Some(300.0), Some(1.0), 0x00000000),
|
||||
p(11, 14, &[], None, None, None, 0x00000000),
|
||||
p(12, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(13, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(14, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(15, 2, &[1.0], Some((0.0, 10.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(16, 1, &[6.0], Some((4.0, 40.0)), Some(1000.0), Some(4.0), 0x00000000),
|
||||
p(17, 13, &[], None, None, None, 0x00000000),
|
||||
p(18, 2, &[29.899993896484375], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(19, 2, &[58.69999694824219], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(20, 2, &[11.44000244140625], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(277, 14, &[], None, None, None, 0x00000000),
|
||||
p(278, 14, &[], None, None, None, 0x00000000),
|
||||
p(23, 13, &[], None, None, None, 0x00000000),
|
||||
p(24, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(25, 7, &[2.0], None, None, None, 0x00000002),
|
||||
p(26, 2, &[180.0], Some((0.0, 360.0)), Some(5000.0), Some(0.0), 0x00020000),
|
||||
p(27, 1, &[5.0], Some((1.0, 20.0)), Some(1000.0), Some(1.0), 0x00000000),
|
||||
p(28, 14, &[], None, None, None, 0x00000000),
|
||||
p(29, 0, &[], None, None, None, 0x00000000),
|
||||
p(30, 7, &[3.0], None, None, None, 0x00000004),
|
||||
p(31, 0, &[], None, None, None, 0x00000000),
|
||||
p(32, 7, &[1.0], None, None, None, 0x00000004),
|
||||
p(33, 13, &[], None, None, None, 0x00000000),
|
||||
p(34, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(35, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(36, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(37, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(38, 14, &[], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Glo2", "Glow", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[2.0], None, None, None, 0x00000002),
|
||||
p(2, 2, &[153.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00010001),
|
||||
p(3, 2, &[10.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010000),
|
||||
p(4, 2, &[1.0], Some((0.0, 4.0)), Some(255.0), Some(0.0), 0x00010000),
|
||||
p(5, 7, &[2.0], None, None, None, 0x00000003),
|
||||
p(6, 7, &[3.0], None, None, None, 0x00000019),
|
||||
p(7, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(8, 7, &[3.0], None, None, None, 0x00000004),
|
||||
p(9, 2, &[1.0], Some((1.0, 10.0)), Some(127.0), Some(1.0), 0x00010000),
|
||||
p(10, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(11, 2, &[0.5], Some((0.0099945068359375, 0.9900054931640625)), Some(0.9900054931640625), Some(0.0099945068359375), 0x00000001),
|
||||
p(12, 5, &[255.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
|
||||
p(13, 5, &[255.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(14, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Fill", "Fill", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 12, &[], None, None, None, 0x00000000),
|
||||
p(7, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(2, 5, &[255.0, 255.0, 0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(6, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(3, 2, &[0.0], Some((0.0, 50.0)), Some(999.0), Some(0.0), 0x00010000),
|
||||
p(4, 2, &[0.0], Some((0.0, 50.0)), Some(999.0), Some(0.0), 0x00010000),
|
||||
p(5, 2, &[1.0], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE HUE SATURATION", "Hue/Saturation", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000007),
|
||||
p(3, 11, &[], None, None, None, 0x00000000),
|
||||
p(4, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(5, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00000000),
|
||||
p(6, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00000000),
|
||||
p(7, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(8, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(9, 2, &[25.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00000000),
|
||||
p(10, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Easy Levels2", "Levels", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000005),
|
||||
p(2, 11, &[], None, None, None, 0x00000000),
|
||||
p(3, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(4, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(5, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
|
||||
p(6, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(7, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(8, 7, &[3.0], None, None, None, 0x00000003),
|
||||
p(9, 7, &[3.0], None, None, None, 0x00000003),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Motion Blur", "Directional Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 3, &[90.0], None, None, None, 0x00000000),
|
||||
p(2, 2, &[10.0], Some((0.0, 20.0)), Some(1000.0), Some(0.0), 0x00010000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Radial Blur", "Radial Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(5, 9, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[10.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010000),
|
||||
p(2, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(3, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(4, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(6, 1, &[0.0], Some((0.0, 1000.0)), Some(10000.0), Some(0.0), 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("CC Radial Blur", "CC Radial Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[6.0], None, None, None, 0x00000007),
|
||||
p(2, 2, &[0.0], Some((-100.0, 100.0)), Some(250.0), Some(-250.0), 0x00010000),
|
||||
p(3, 2, &[50.0], Some((25.0, 100.0)), Some(100.0), Some(10.0), 0x00010000),
|
||||
p(4, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Venetian Blinds", "Venetian Blinds", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00000001),
|
||||
p(2, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(3, 2, &[20.0], Some((1.0, 127.0)), Some(32000.0), Some(1.0), 0x00000000),
|
||||
p(4, 2, &[0.0], Some((0.0, 100.0)), Some(32000.0), Some(0.0), 0x00010000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Channel Blur", "Channel Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((0.0, 127.0)), Some(32767.0), Some(0.0), 0x00010000),
|
||||
p(2, 2, &[0.0], Some((0.0, 127.0)), Some(32767.0), Some(0.0), 0x00010000),
|
||||
p(3, 2, &[0.0], Some((0.0, 127.0)), Some(32767.0), Some(0.0), 0x00010000),
|
||||
p(4, 2, &[0.0], Some((0.0, 127.0)), Some(32767.0), Some(0.0), 0x00010000),
|
||||
p(5, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(6, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Black&White", "Black & White", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 10, &[40.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
|
||||
p(2, 10, &[60.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
|
||||
p(3, 10, &[40.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
|
||||
p(4, 10, &[60.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
|
||||
p(5, 10, &[20.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
|
||||
p(6, 10, &[80.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
|
||||
p(7, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(8, 5, &[255.0, 225.0, 211.0, 179.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Tritone", "Tritone", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 5, &[0.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
|
||||
p(2, 5, &[0.0, 127.0, 100.0, 70.0], None, None, None, 0x00000000),
|
||||
p(3, 5, &[0.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(4, 10, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Luma Key", "Luma Key", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[2.0], None, None, None, 0x00000004),
|
||||
p(2, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
|
||||
p(3, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
|
||||
p(4, 1, &[0.0], Some((-5.0, 5.0)), Some(5.0), Some(-5.0), 0x00000000),
|
||||
p(5, 2, &[0.0], Some((0.0, 10.0)), Some(100.0), Some(0.0), 0x00010000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Simple Choker", "Simple Choker", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(2, 2, &[0.0], Some((-10.0, 10.0)), Some(100.0), Some(-100.0), 0x00020000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Matte Choker", "Matte Choker", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[4.0], Some((0.0, 10.0)), Some(100.0), Some(0.0), 0x00010000),
|
||||
p(2, 1, &[75.0], Some((-127.0, 127.0)), Some(127.0), Some(-127.0), 0x00000000),
|
||||
p(3, 2, &[0.100006103515625], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00000001),
|
||||
p(4, 2, &[0.0], Some((0.0, 10.0)), Some(100.0), Some(0.0), 0x00020000),
|
||||
p(5, 1, &[0.0], Some((-127.0, 127.0)), Some(127.0), Some(-127.0), 0x00000000),
|
||||
p(6, 2, &[1.0], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
|
||||
p(7, 1, &[1.0], Some((1.0, 10.0)), Some(100.0), Some(1.0), 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Geometry2", "Transform", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(2, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(11, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(3, 2, &[100.0], Some((-200.0, 200.0)), Some(30000.0), Some(-30000.0), 0x00010000),
|
||||
p(4, 2, &[100.0], Some((-200.0, 200.0)), Some(30000.0), Some(-30000.0), 0x00010000),
|
||||
p(5, 2, &[0.0], Some((-70.0, 70.0)), Some(70.0), Some(-70.0), 0x00010000),
|
||||
p(6, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(7, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(8, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010000),
|
||||
p(9, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(10, 2, &[0.0], Some((0.0, 360.0)), Some(360.0), Some(0.0), 0x00020000),
|
||||
p(12, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Brightness & Contrast 2", "Brightness & Contrast", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((-150.0, 150.0)), Some(150.0), Some(-150.0), 0x00000000),
|
||||
p(2, 2, &[0.0], Some((-50.0, 100.0)), Some(100.0), Some(-100.0), 0x00000000),
|
||||
p(3, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Turbulent Displace", "Turbulent Displace", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x0000000b),
|
||||
p(2, 2, &[50.0], Some((0.0, 100.0)), Some(10000.0), Some(-10000.0), 0x00010000),
|
||||
p(3, 2, &[100.0], Some((5.0, 400.0)), Some(1000.0), Some(2.0), 0x00010000),
|
||||
p(4, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(5, 2, &[1.0], Some((1.0, 5.0)), Some(10.0), Some(1.0), 0x00010000),
|
||||
p(6, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(7, 13, &[], None, None, None, 0x00000000),
|
||||
p(8, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(9, 1, &[1.0], Some((1.0, 30.0)), Some(88.0), Some(1.0), 0x00000000),
|
||||
p(10, 1, &[0.0], Some((0.0, 1000.0)), Some(100000.0), Some(0.0), 0x00000000),
|
||||
p(11, 14, &[], None, None, None, 0x00000000),
|
||||
p(12, 7, &[3.0], None, None, None, 0x00000011),
|
||||
p(13, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(14, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Fractal Noise", "Fractal Noise", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000014),
|
||||
p(2, 7, &[3.0], None, None, None, 0x00000004),
|
||||
p(3, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(4, 2, &[100.0], Some((0.0, 400.0)), Some(10000.0), Some(0.0), 0x00010000),
|
||||
p(5, 2, &[0.0], Some((-100.0, 100.0)), Some(10000.0), Some(-10000.0), 0x00010000),
|
||||
p(6, 7, &[4.0], None, None, None, 0x00000004),
|
||||
p(7, 13, &[], None, None, None, 0x00000000),
|
||||
p(8, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(9, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(10, 2, &[100.0], Some((20.0, 600.0)), Some(10000.0), Some(1.0), 0x00010000),
|
||||
p(11, 2, &[100.0], Some((20.0, 600.0)), Some(10000.0), Some(1.0), 0x00010000),
|
||||
p(12, 2, &[100.0], Some((20.0, 600.0)), Some(10000.0), Some(1.0), 0x00010000),
|
||||
p(13, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(31, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(14, 14, &[], None, None, None, 0x00000000),
|
||||
p(15, 2, &[6.0], Some((1.0, 10.0)), Some(20.0), Some(1.0), 0x00010000),
|
||||
p(16, 13, &[], None, None, None, 0x00000000),
|
||||
p(17, 2, &[70.0], Some((25.0, 100.0)), Some(10000.0), Some(1.52587890625e-05), 0x00010000),
|
||||
p(18, 2, &[56.0], Some((25.0, 100.0)), Some(10000.0), Some(10.0), 0x00010000),
|
||||
p(19, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(20, 6, &[0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(21, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(22, 14, &[], None, None, None, 0x00000000),
|
||||
p(23, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(24, 13, &[], None, None, None, 0x00000000),
|
||||
p(25, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(26, 1, &[1.0], Some((1.0, 30.0)), Some(88.0), Some(1.0), 0x00000000),
|
||||
p(27, 1, &[0.0], Some((0.0, 1000.0)), Some(100000.0), Some(0.0), 0x00000000),
|
||||
p(28, 14, &[], None, None, None, 0x00000000),
|
||||
p(29, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(30, 7, &[2.0], None, None, None, 0x00000015),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Laser", "Beam", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.100006103515625, 0.5], None, None, None, 0x00000000),
|
||||
p(2, 6, &[0.899993896484375, 0.5], None, None, None, 0x00000000),
|
||||
p(3, 2, &[0.25], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
|
||||
p(4, 2, &[0.5], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
|
||||
p(5, 2, &[8.0], Some((0.0, 50.0)), Some(4000.0), Some(0.0), 0x00020000),
|
||||
p(6, 2, &[8.0], Some((0.0, 50.0)), Some(4000.0), Some(0.0), 0x00020000),
|
||||
p(7, 2, &[0.5], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
|
||||
p(8, 5, &[185.0, 255.0, 190.0, 250.0], None, None, None, 0x00000000),
|
||||
p(9, 5, &[150.0, 255.0, 25.0, 25.0], None, None, None, 0x00000000),
|
||||
p(10, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(11, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("CC Radial Fast Blur", "CC Radial Fast Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(2, 2, &[50.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010000),
|
||||
p(3, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Noise2", "Noise", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(2, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(3, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Pro Levels2", "Levels (Individual Controls)", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000005),
|
||||
p(2, 11, &[], None, None, None, 0x00000000),
|
||||
p(3, 13, &[], None, None, None, 0x00000000),
|
||||
p(4, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(5, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(6, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
|
||||
p(7, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(8, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(9, 14, &[], None, None, None, 0x00000000),
|
||||
p(10, 13, &[], None, None, None, 0x00000000),
|
||||
p(11, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(12, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(13, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
|
||||
p(14, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(15, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(16, 14, &[], None, None, None, 0x00000000),
|
||||
p(17, 13, &[], None, None, None, 0x00000000),
|
||||
p(18, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(19, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(20, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
|
||||
p(21, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(22, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(23, 14, &[], None, None, None, 0x00000000),
|
||||
p(24, 13, &[], None, None, None, 0x00000000),
|
||||
p(25, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(26, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(27, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
|
||||
p(28, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(29, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(30, 14, &[], None, None, None, 0x00000000),
|
||||
p(31, 13, &[], None, None, None, 0x00000000),
|
||||
p(32, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(33, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(34, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
|
||||
p(35, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(36, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
|
||||
p(37, 14, &[], None, None, None, 0x00000000),
|
||||
p(38, 7, &[3.0], None, None, None, 0x00000003),
|
||||
p(39, 7, &[3.0], None, None, None, 0x00000003),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Corner Pin", "Corner Pin", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(2, 6, &[1.0, 0.0], None, None, None, 0x00000000),
|
||||
p(3, 6, &[0.0, 1.0], None, None, None, 0x00000000),
|
||||
p(4, 6, &[1.0, 1.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Grid", "Grid", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(3, 6, &[0.600006103515625, 0.600006103515625], None, None, None, 0x00000000),
|
||||
p(4, 2, &[32.0], Some((4.0, 200.0)), Some(4000.0), Some(1.0), 0x00010000),
|
||||
p(5, 2, &[24.0], Some((4.0, 200.0)), Some(4000.0), Some(1.0), 0x00010000),
|
||||
p(6, 2, &[5.0], Some((0.0, 100.0)), Some(2000.0), Some(0.0), 0x00010000),
|
||||
p(7, 13, &[], None, None, None, 0x00000000),
|
||||
p(8, 2, &[0.0], Some((0.0, 20.0)), Some(400.0), Some(0.0), 0x00010000),
|
||||
p(9, 2, &[0.0], Some((0.0, 20.0)), Some(400.0), Some(0.0), 0x00010000),
|
||||
p(10, 14, &[], None, None, None, 0x00000000),
|
||||
p(11, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(12, 5, &[255.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
|
||||
p(13, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(14, 7, &[1.0], None, None, None, 0x00000017),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Sharpen", "Sharpen", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 1, &[0.0], Some((0.0, 100.0)), Some(4000.0), Some(0.0), 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Linear Color Key2", "Linear Color Key", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 9, &[], None, None, None, 0x00000000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(3, 5, &[255.0, 0.0, 0.0, 255.0], None, None, None, 0x00000000),
|
||||
p(4, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(5, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(6, 2, &[10.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(7, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Radial Wipe", "Radial Wipe", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00000001),
|
||||
p(2, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(3, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(4, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(5, 2, &[0.0], Some((0.0, 100.0)), Some(32000.0), Some(0.0), 0x00010000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Remove Color Matting", "Remove Color Matting", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 5, &[0.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(2, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("CC Bend It", "CC Bend It", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((-100.0, 100.0)), Some(250.0), Some(-250.0), 0x00010000),
|
||||
p(2, 6, &[0.5, 0.75], None, None, None, 0x00000000),
|
||||
p(3, 6, &[0.5, 0.25], None, None, None, 0x00000000),
|
||||
p(4, 7, &[3.0], None, None, None, 0x00000004),
|
||||
p(5, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("CC Power Pin", "CC Power Pin", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(2, 6, &[0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(3, 6, &[1.0, 0.0], None, None, None, 0x00000000),
|
||||
p(4, 6, &[0.0, 1.0], None, None, None, 0x00000000),
|
||||
p(5, 6, &[1.0, 1.0], None, None, None, 0x00000000),
|
||||
p(6, 2, &[1.0], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
|
||||
p(7, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(8, 13, &[], None, None, None, 0x00000000),
|
||||
p(9, 2, &[0.0], Some((0.0, 50.0)), Some(200.0), Some(-200.0), 0x00010000),
|
||||
p(10, 2, &[0.0], Some((0.0, 50.0)), Some(200.0), Some(-200.0), 0x00010000),
|
||||
p(11, 2, &[0.0], Some((0.0, 50.0)), Some(200.0), Some(-200.0), 0x00010000),
|
||||
p(12, 2, &[0.0], Some((0.0, 50.0)), Some(200.0), Some(-200.0), 0x00010000),
|
||||
p(13, 14, &[], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE 4ColorGradient", "4-Color Gradient", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(11, 13, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.100006103515625, 0.100006103515625], None, None, None, 0x00000000),
|
||||
p(2, 5, &[255.0, 255.0, 255.0, 0.0], None, None, None, 0x00000000),
|
||||
p(3, 6, &[0.899993896484375, 0.100006103515625], None, None, None, 0x00000000),
|
||||
p(4, 5, &[255.0, 0.0, 255.0, 0.0], None, None, None, 0x00000000),
|
||||
p(5, 6, &[0.100006103515625, 0.899993896484375], None, None, None, 0x00000000),
|
||||
p(6, 5, &[255.0, 255.0, 0.0, 255.0], None, None, None, 0x00000000),
|
||||
p(7, 6, &[0.899993896484375, 0.899993896484375], None, None, None, 0x00000000),
|
||||
p(8, 5, &[255.0, 0.0, 0.0, 255.0], None, None, None, 0x00000000),
|
||||
p(12, 14, &[], None, None, None, 0x00000000),
|
||||
p(9, 2, &[100.0], Some((10.0, 500.0)), Some(10000.0), Some(5.0), 0x00010000),
|
||||
p(10, 2, &[0.0], Some((0.0, 100.0)), Some(500.0), Some(0.0), 0x00010001),
|
||||
p(13, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(14, 7, &[1.0], None, None, None, 0x00000016),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Change Color", "Change Color", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(2, 2, &[0.0], Some((-180.0, 180.0)), Some(1800.0), Some(-1800.0), 0x00010000),
|
||||
p(3, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00010000),
|
||||
p(4, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00010000),
|
||||
p(5, 5, &[255.0, 0.0, 0.0, 255.0], None, None, None, 0x00000000),
|
||||
p(6, 2, &[15.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(7, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
|
||||
p(8, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(9, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Extract", "Extract", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 9, &[], None, None, None, 0x00000000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000005),
|
||||
p(3, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
|
||||
p(4, 1, &[255.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
|
||||
p(5, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
|
||||
p(6, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
|
||||
p(7, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Noise HLS2", "Noise HLS", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(2, 10, &[0.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010001),
|
||||
p(3, 10, &[0.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010001),
|
||||
p(4, 10, &[0.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010001),
|
||||
p(5, 2, &[1.0], Some((0.0, 4.0)), Some(10.0), Some(0.0), 0x00020000),
|
||||
p(6, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Scatter", "Scatter", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((0.0, 127.0)), Some(1000.0), Some(0.0), 0x00010000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(3, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("CC Light Sweep", "CC Light Sweep", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.5, 0.25], None, None, None, 0x00000000),
|
||||
p(2, 3, &[-30.0], None, None, None, 0x00000000),
|
||||
p(3, 7, &[3.0], None, None, None, 0x00000003),
|
||||
p(4, 2, &[50.0], Some((0.0, 200.0)), Some(4000.0), Some(0.0), 0x00010000),
|
||||
p(5, 2, &[25.0], Some((0.0, 100.0)), Some(500.0), Some(0.0), 0x00010000),
|
||||
p(6, 2, &[50.0], Some((0.0, 100.0)), Some(500.0), Some(0.0), 0x00010000),
|
||||
p(7, 2, &[4.0], Some((0.0, 10.0)), Some(20.0), Some(0.0), 0x00020000),
|
||||
p(8, 5, &[255.0, 255.0, 250.0, 240.0], None, None, None, 0x00000000),
|
||||
p(9, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Compound Blur", "Compound Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 0, &[], None, None, None, 0x00000000),
|
||||
p(2, 2, &[20.0], Some((0.0, 100.0)), Some(4000.0), Some(0.0), 0x00010000),
|
||||
p(3, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(4, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Displacement Map", "Displacement Map", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 0, &[], None, None, None, 0x00000000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x0000000b),
|
||||
p(3, 2, &[5.0], Some((-100.0, 100.0)), Some(32000.0), Some(-32000.0), 0x00010000),
|
||||
p(4, 7, &[2.0], None, None, None, 0x0000000b),
|
||||
p(5, 2, &[5.0], Some((-100.0, 100.0)), Some(32000.0), Some(-32000.0), 0x00010000),
|
||||
p(6, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(7, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(8, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Set Matte3", "Set Matte", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 0, &[], None, None, None, 0x00000000),
|
||||
p(2, 7, &[4.0], None, None, None, 0x0000000a),
|
||||
p(3, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(4, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(5, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(6, 4, &[1.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Gaussian Blur", "Gaussian Blur (Legacy)", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 2, &[0.0], Some((0.0, 50.0)), Some(30000.0), Some(0.0), 0x00010000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000003),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE OFMotionBlur", "Pixel Motion Blur", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 7, &[1.0], None, None, None, 0x00000002),
|
||||
p(2, 10, &[180.0], Some((0.0, 360.0)), Some(5000.0), Some(0.0), 0x00020000),
|
||||
p(3, 1, &[5.0], Some((1.0, 20.0)), Some(256.0), Some(1.0), 0x00000000),
|
||||
p(4, 10, &[20.0], Some((5.0, 100.0)), Some(100.0), Some(5.0), 0x00010000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Layer Control", "Layer Control", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 0, &[], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Slider Control", "Slider Control", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 10, &[0.0], Some((0.0, 100.0)), Some(1000000.0), Some(-1000000.0), 0x00020000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Angle Control", "Angle Control", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 3, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Checkbox Control", "Checkbox Control", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 4, &[0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Color Control", "Color Control", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 5, &[255.0, 255.0, 0.0, 0.0], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE Point Control", "Point Control", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 6, &[0.5, 0.5], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE CurvesCustom", "Curves", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(2, 7, &[1.0], None, None, None, 0x00000005),
|
||||
p(1, 11, &[], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
fx("ADBE MESH WARP", "Mesh Warp", &[
|
||||
p(0, 0, &[], None, None, None, 0x00000000),
|
||||
p(1, 1, &[7.0], Some((1.0, 31.0)), Some(31.0), Some(1.0), 0x00000000),
|
||||
p(2, 1, &[7.0], Some((1.0, 31.0)), Some(31.0), Some(1.0), 0x00000000),
|
||||
p(5, 1, &[8.0], Some((1.0, 10.0)), Some(10.0), Some(1.0), 0x00000000),
|
||||
p(4, 11, &[], None, None, None, 0x00000000),
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::container::effect_map::by_match_name;
|
||||
use effectcraft_project::ParamUi;
|
||||
|
||||
/// Effect parameters whose hard range (`ParamUi::Slider` min..max, which `prop.set` and the
|
||||
/// value editors clamp to) is still narrower than After Effects' recorded valid range, each
|
||||
/// with the open issue that tracks it: (effect, parameter, issue). Remove a row when its
|
||||
/// issue is fixed; the test fails on a row that is no longer needed.
|
||||
#[rustfmt::skip]
|
||||
const KNOWN_NARROWER: &[(&str, &str, u32)] = &[
|
||||
("ec.blur.gaussian", "blurriness", 3460),
|
||||
("ec.blur.fastbox", "radius", 3461),
|
||||
("ec.blur.channel", "redBlurriness", 3462),
|
||||
("ec.blur.channel", "greenBlurriness", 3462),
|
||||
("ec.blur.channel", "blueBlurriness", 3462),
|
||||
("ec.blur.channel", "alphaBlurriness", 3462),
|
||||
("ec.obsolete.gaussianlegacy", "blurriness", 3463),
|
||||
("ec.perspective.dropshadow", "softness", 3464),
|
||||
("ec.blur.compound", "maximumBlur", 3465),
|
||||
("ec.blur.sharpen", "amount", 3466),
|
||||
("ec.blur.radial", "amount", 3467),
|
||||
("ec.blur.ccradial", "amount", 3468),
|
||||
("ec.distort.turbulentdisplace", "amount", 3469),
|
||||
("ec.time.pixelmotionblur", "shutterAngle", 3481),
|
||||
("ec.time.pixelmotionblur", "shutterSamples", 3482),
|
||||
("ec.noise.fractal", "subSettings/subInfluence", 3485),
|
||||
("ec.noise.fractal", "subSettings/subScaling", 3486),
|
||||
("ec.distort.ccpowerpin", "expandTop", 3492),
|
||||
("ec.distort.ccpowerpin", "expandLeft", 3492),
|
||||
("ec.distort.ccpowerpin", "expandRight", 3492),
|
||||
("ec.distort.ccpowerpin", "expandBottom", 3492),
|
||||
];
|
||||
|
||||
/// `a` is at most `b`, allowing for the `f32` the recorded bounds were read from.
|
||||
fn at_most(a: f64, b: f64) -> bool {
|
||||
a <= b + 1e-6 * a.abs().max(b.abs()).max(1.0)
|
||||
}
|
||||
|
||||
/// Every effect parameter the .aep table maps to a recorded After Effects definition accepts
|
||||
/// at least After Effects' valid range, converted to EffectCraft's units the way the importer
|
||||
/// converts values (`Conv::number_scale`). Only `ParamUi::Slider` limits values (`prop.set`,
|
||||
/// the Effect Controls and Timeline editors); other controls take any number. A mapping with
|
||||
/// a declared narrower range (`ParamMap::limit`) must match the effect's range instead.
|
||||
#[test]
|
||||
fn effect_hard_ranges_cover_recorded_after_effects_ranges() {
|
||||
let mut problems = Vec::new();
|
||||
let mut narrower = Vec::new();
|
||||
for fx in FX_DEFS {
|
||||
let Some(map) = by_match_name(fx.match_name) else { continue };
|
||||
let Some(spec) = effectcraft_effects::find(map.effect) else {
|
||||
problems.push(format!("{}: no effect {}", fx.match_name, map.effect));
|
||||
continue;
|
||||
};
|
||||
for pm in map.params {
|
||||
let Some(scale) = pm.conv.number_scale() else { continue };
|
||||
let at = format!("{} {}", map.effect, pm.target);
|
||||
let Some(ps) = spec.params.iter().find(|p| p.id == pm.target) else {
|
||||
problems.push(format!("{at}: not a parameter of the effect"));
|
||||
continue;
|
||||
};
|
||||
// Other controls take any number.
|
||||
let ParamUi::Slider { min, max, .. } = &ps.ui else { continue };
|
||||
let Some(def) = fx.params.get(pm.index) else {
|
||||
problems.push(format!("{at}: no recorded definition at parT {}", pm.index));
|
||||
continue;
|
||||
};
|
||||
let (Some(lo), Some(hi)) = (def.valid_min, def.valid_max) else {
|
||||
problems.push(format!("{at}: no recorded valid range"));
|
||||
continue;
|
||||
};
|
||||
let (lo, hi) = (lo * scale, hi * scale);
|
||||
if let Some(limit) = pm.limit {
|
||||
if limit != (*min, *max) {
|
||||
problems.push(format!("{at}: declared limit {limit:?} is not the effect's range {min}..{max}"));
|
||||
}
|
||||
} else if !(at_most(*min, lo) && at_most(hi, *max)) {
|
||||
narrower.push((map.effect, pm.target, format!("{at}: {min}..{max} excludes After Effects' {lo}..{hi}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (effect, param, why) in &narrower {
|
||||
if !KNOWN_NARROWER.iter().any(|(e, p, _)| e == effect && p == param) {
|
||||
problems.push(why.clone());
|
||||
}
|
||||
}
|
||||
for (effect, param, issue) in KNOWN_NARROWER {
|
||||
if !narrower.iter().any(|(e, p, _)| e == effect && p == param) {
|
||||
problems.push(format!("{effect} {param}: covers After Effects' range now (or is not mapped); remove it from KNOWN_NARROWER (#{issue})"));
|
||||
}
|
||||
}
|
||||
assert!(problems.is_empty(), "{}", problems.join("\n"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Effect instances built in code from the effect table (`fx_defs`): the default `sspc` of every
|
||||
//! effect type the exporter writes, its project copy (`EfDf`) and the value records of each
|
||||
//! parameter type (aep-format.md 3.7).
|
||||
//!
|
||||
//! What After Effects needs (read-backs in `docs/aep-export.md`, "Built in code"): a `parT` entry
|
||||
//! per parameter (`tdmn` + a 148-byte `pard`) whose bytes may be zero, since After Effects takes
|
||||
//! the definitions from the effect itself (e1-zpardfull); no `sdat` (e2-nosdat). The `pard` fields
|
||||
//! the importer reads back (type, default, valid maximum, slider range, popup item count) are
|
||||
//! written from the table so that an exported file imports again.
|
||||
|
||||
use crate::Chunk;
|
||||
use crate::effect_map::{Conv, by_match_name};
|
||||
use crate::export::fx_defs::{BUILT_IN, FxDef, PDef};
|
||||
use crate::export::synth::{GROUP_END, KeyTemplate, NO_NAME, RecSpec, class, tdmn, tdsn, utf8_in};
|
||||
use crate::export::tree::Fixed;
|
||||
use crate::{CURVE_IDENTITY, CurvesData, MeshData};
|
||||
|
||||
/// The layer a prototype's layer parameters name when their default is the owning layer; the
|
||||
/// exporter replaces it with the owning layer's id (`effects::instance`).
|
||||
pub(crate) const PROTO_OWNER: u32 = 1;
|
||||
|
||||
/// Layer parameters whose default is None instead of the owning layer (Timewarp's Matte Layer and
|
||||
/// Warp Layer, 529).
|
||||
const LAYER_NONE: &[&str] = &["ADBE Timewarp-0029", "ADBE Timewarp-0031"];
|
||||
|
||||
/// The record of a parameter type (`pard` code): its components, key template and class word.
|
||||
pub(crate) fn value_spec(code: u8, range: Option<(f64, f64)>) -> Option<RecSpec> {
|
||||
let scalar = |class| RecSpec { dims: 1, template: KeyTemplate::Plain, class, limits: None, byte5: None };
|
||||
Some(match code {
|
||||
// Sliders carry their range as `tdum` / `tduM`.
|
||||
1 | 2 | 10 => RecSpec { limits: Some(range.unwrap_or((0.0, 0.0))), ..scalar(class::EFFECT_NUMBER) },
|
||||
3 => scalar(class::EFFECT_NUMBER),
|
||||
4 | 7 => scalar(class::EFFECT_CHOICE),
|
||||
5 => RecSpec { dims: 4, template: KeyTemplate::Spatial(1), class: class::COLOR, limits: None, byte5: None },
|
||||
6 => RecSpec { dims: 2, template: KeyTemplate::Spatial(3), class: class::SPATIAL, limits: None, byte5: None },
|
||||
0 | 13 | 14 | 15 => scalar(class::EFFECT_OTHER),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn fixed(v: f64) -> [u8; 4] {
|
||||
((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes()
|
||||
}
|
||||
|
||||
/// The 148-byte `pard` of a parameter: the type at 12, the default at 56 and the copies After
|
||||
/// Effects reads it from (s8-e1..s12-e2), a popup's item count at 60, the valid range, slider
|
||||
/// range and display word of a slider (float: `f32` at 104 / 108 / 112 / 116, default 120,
|
||||
/// display 124; fixed and integer: 124 / 128 / 132 / 136, default 140, display 144). Every other
|
||||
/// byte is zero (the switches at 48 are not needed: s12-e2-nofl).
|
||||
pub(crate) fn pard(p: &PDef, popup_items: Option<u16>) -> Vec<u8> {
|
||||
pard_layout(p, popup_items).finish(|| format!("pard (type {})", p.code))
|
||||
}
|
||||
|
||||
/// The 148-byte `pard` layout of a parameter definition: type, name and defaults.
|
||||
fn pard_layout(p: &PDef, popup_items: Option<u16>) -> Fixed {
|
||||
let mut b = Fixed::zeroed(148);
|
||||
b.put(12, &u32::from(p.code).to_be_bytes());
|
||||
let d = |i: usize| p.default.get(i).copied().unwrap_or(0.0);
|
||||
// After Effects takes the default of a parameter without a value record from here (s8-e1:
|
||||
// the copies below are the ones it reads).
|
||||
match p.code {
|
||||
10 => {
|
||||
b.put(56, &d(0).to_be_bytes());
|
||||
// The default again as `f32` at 120, the display word (decimals) at 124.
|
||||
b.put(120, &(d(0) as f32).to_be_bytes());
|
||||
b.put(124, &p.display.to_be_bytes());
|
||||
}
|
||||
2 => b.put(56, &fixed(d(0))),
|
||||
// An angle: the default again at 60.
|
||||
3 => {
|
||||
b.put(56, &fixed(d(0)));
|
||||
b.put(60, &fixed(d(0)));
|
||||
}
|
||||
1 => b.put(56, &(d(0).round() as i32).to_be_bytes()),
|
||||
// A checkbox: the default again as a byte at 60.
|
||||
4 => {
|
||||
b.put(56, &(d(0).round().max(0.0) as u32).to_be_bytes());
|
||||
b.put(60, &[u8::from(d(0) != 0.0)]);
|
||||
}
|
||||
// A popup: the default again as `u16` at 62 (the item count is at 60).
|
||||
7 => {
|
||||
let sel = d(0).round().clamp(0.0, f64::from(u16::MAX));
|
||||
b.put(56, &(sel as u32).to_be_bytes());
|
||||
b.put(62, &(sel as u16).to_be_bytes());
|
||||
}
|
||||
6 => {
|
||||
// Fractions of the layer at 56 / 60 and the same in percent at 68 / 72.
|
||||
b.put(56, &fixed(d(0)));
|
||||
b.put(60, &fixed(d(1)));
|
||||
b.put(68, &fixed(d(0) * 100.0));
|
||||
b.put(72, &fixed(d(1) * 100.0));
|
||||
}
|
||||
5 => {
|
||||
// ARGB at 56 and the same at 60.
|
||||
let c: Vec<u8> = (0..4).map(|i| d(i).round().clamp(0.0, 255.0) as u8).collect();
|
||||
b.put(56, &c);
|
||||
b.put(60, &c);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if p.code == 7 {
|
||||
let n = popup_items.unwrap_or_else(|| u16::try_from(p.display).unwrap_or(0));
|
||||
b.put(60, &n.to_be_bytes());
|
||||
}
|
||||
match p.code {
|
||||
10 => {
|
||||
if let Some(m) = p.valid_min {
|
||||
b.put(104, &(m as f32).to_be_bytes());
|
||||
}
|
||||
if let Some(m) = p.valid_max {
|
||||
b.put(108, &(m as f32).to_be_bytes());
|
||||
}
|
||||
if let Some((lo, hi)) = p.range {
|
||||
b.put(112, &(lo as f32).to_be_bytes());
|
||||
b.put(116, &(hi as f32).to_be_bytes());
|
||||
}
|
||||
}
|
||||
1 | 2 => {
|
||||
let enc = |v: f64| if p.code == 2 { fixed(v) } else { (v.round() as i32).to_be_bytes() };
|
||||
if let Some(m) = p.valid_min {
|
||||
b.put(124, &enc(m));
|
||||
}
|
||||
if let Some(m) = p.valid_max {
|
||||
b.put(128, &enc(m));
|
||||
}
|
||||
if let Some((lo, hi)) = p.range {
|
||||
b.put(132, &enc(lo));
|
||||
b.put(136, &enc(hi));
|
||||
}
|
||||
// The default again at 140, the display word (decimals, percent) at 144.
|
||||
b.put(140, &enc(d(0)));
|
||||
b.put(144, &p.display.to_be_bytes());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The default arbitrary data of an effect (its type-11 parameter), from the decoded layouts
|
||||
/// (aep-format.md 3.7).
|
||||
pub(crate) fn default_data(match_name: &str) -> Option<Vec<u8>> {
|
||||
match match_name {
|
||||
// Master hue, saturation, lightness (0), then six colour ranges of four hue bounds and
|
||||
// their hue, saturation and lightness (0): Reds centred at 0 degrees, then every 60, each
|
||||
// range 30 degrees wide with 30 degree fall-off (443-446).
|
||||
"ADBE HUE SATURATION" => {
|
||||
let mut out = vec![0u8; 12];
|
||||
for c in 0..6i32 {
|
||||
let centre = 60 * c;
|
||||
for off in [-45, -15, 15, 45] {
|
||||
out.extend((centre + off).rem_euclid(360).to_be_bytes());
|
||||
}
|
||||
out.extend([0u8; 12]);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
// A header word `0x000f10a7` and the version 1, then five channels (RGB, red, green, blue,
|
||||
// alpha) of input black, input white, gamma, output black, output white as `f32`
|
||||
// (511-516).
|
||||
"ADBE Easy Levels2" | "ADBE Pro Levels2" => {
|
||||
let mut out = Vec::with_capacity(108);
|
||||
out.extend(0x000f_10a7_u32.to_be_bytes());
|
||||
out.extend(1u32.to_be_bytes());
|
||||
for _ in 0..5 {
|
||||
for v in [0.0f32, 1.0, 1.0, 0.0, 1.0] {
|
||||
out.extend(v.to_be_bytes());
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
"ADBE CurvesCustom" => CurvesData { curves: std::array::from_fn(|_| CURVE_IDENTITY.to_vec()) }.to_bytes(),
|
||||
// 7 x 7 cells, undistorted (Rows / Columns default 7, 985).
|
||||
"ADBE MESH WARP" => {
|
||||
let (columns, rows) = (7, 7);
|
||||
let vertices = (0..=rows).flat_map(|j| (0..=columns).map(move |i| MeshData::default_vertex(columns, rows, i, j))).collect();
|
||||
MeshData { columns, rows, tail: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x0d, 0x0d], vertices }.to_bytes()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The popup item count of parameter position `index` from the shared effect table.
|
||||
fn popup_items(fx: &FxDef, index: usize) -> Option<u16> {
|
||||
let map = by_match_name(fx.match_name)?;
|
||||
let pm = map.params.iter().find(|p| p.index == index)?;
|
||||
match pm.conv {
|
||||
Conv::Popup { items, .. } => u16::try_from(items.len()).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A record without a value of its own (layer parameters, groups, buttons): `tdsb` `state`, no
|
||||
/// user name, the header and a zero `cdat`.
|
||||
fn plain_record(state: u32, extra: Vec<Chunk<'static>>) -> Chunk<'static> {
|
||||
let spec = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_OTHER, limits: None, byte5: None };
|
||||
let mut kids = vec![
|
||||
Chunk::data(*b"tdsb", state.to_be_bytes().to_vec()),
|
||||
tdsn(NO_NAME),
|
||||
Chunk::data(*b"tdb4", crate::export::synth::tdb4(&spec, false, 25_600)),
|
||||
Chunk::data(*b"cdat", vec![0u8; spec.cdat_len()]),
|
||||
];
|
||||
kids.extend(extra);
|
||||
Chunk::list(*b"tdbs", kids)
|
||||
}
|
||||
|
||||
/// The arbitrary-data record (4-byte `cdat`, class `0x00060007`, colour-like template 1) and the
|
||||
/// `LIST aRbs` with the data after it (443, 961).
|
||||
fn data_record(data: Vec<u8>) -> [Chunk<'static>; 2] {
|
||||
let spec = RecSpec { dims: 1, template: KeyTemplate::Spatial(1), class: class::ARBITRARY, limits: None, byte5: None };
|
||||
let rec = Chunk::list(
|
||||
*b"tdbs",
|
||||
vec![
|
||||
Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()),
|
||||
tdsn(NO_NAME),
|
||||
Chunk::data(*b"tdb4", crate::export::synth::tdb4(&spec, false, 25_600)),
|
||||
Chunk::data(*b"cdat", vec![0u8; 4]),
|
||||
],
|
||||
);
|
||||
[rec, Chunk::list(*b"aRbs", vec![Chunk::data(*b"aRbp", data)])]
|
||||
}
|
||||
|
||||
/// The default `sspc` of an effect: its name (`fnam`), the parameter list (`parT`: the count,
|
||||
/// then `tdmn` + `pard` per parameter, the default arbitrary data after its `pard`), the value
|
||||
/// group (records only for layer parameters, groups, buttons and arbitrary data, the built-in
|
||||
/// group) and `pgui` (zero).
|
||||
pub(crate) fn default_sspc(fx: &FxDef) -> Chunk<'static> {
|
||||
let fnam = utf8_in(*b"fnam", fx.name);
|
||||
let count = u32::try_from(fx.params.len()).unwrap_or(u32::MAX);
|
||||
let mut part = vec![Chunk::data(*b"parn", count.to_be_bytes().to_vec())];
|
||||
let mut values = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(NO_NAME)];
|
||||
for (i, p) in fx.params.iter().enumerate() {
|
||||
let record = fx.record(p);
|
||||
part.push(tdmn(&record));
|
||||
part.push(Chunk::data(*b"pard", pard(p, popup_items(fx, i))));
|
||||
if matches!(p.code, 4 | 7 | 15) {
|
||||
// Checkboxes, popups and buttons have a `pdnm` (their label or items); its text may
|
||||
// be empty.
|
||||
part.push(utf8_in(*b"pdnm", ""));
|
||||
}
|
||||
if p.id == BUILT_IN {
|
||||
values.push(tdmn(&record));
|
||||
values.push(Chunk::list(*b"tdgp", vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(NO_NAME), tdmn(GROUP_END)]));
|
||||
continue;
|
||||
}
|
||||
match p.code {
|
||||
0 => {
|
||||
let id = if LAYER_NONE.contains(&record.as_str()) { 0 } else { PROTO_OWNER };
|
||||
// The input layer (position 0) and every layer parameter name a layer (`tdpi`);
|
||||
// `tdps` 0 (320, 529).
|
||||
let state = if i == 0 { 3 } else { 1 };
|
||||
values.push(tdmn(&record));
|
||||
values.push(plain_record(state, vec![Chunk::data(*b"tdpi", id.to_be_bytes().to_vec()), Chunk::data(*b"tdps", 0u32.to_be_bytes().to_vec())]));
|
||||
}
|
||||
9 | 13..=15 => {
|
||||
values.push(tdmn(&record));
|
||||
values.push(plain_record(1, Vec::new()));
|
||||
}
|
||||
11 => {
|
||||
if let Some(data) = default_data(fx.match_name) {
|
||||
part.push(Chunk::data(*b"aRbp", data.clone()));
|
||||
values.push(tdmn(&record));
|
||||
values.extend(data_record(data));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
values.push(tdmn(GROUP_END));
|
||||
Chunk::list(*b"sspc", vec![fnam, Chunk::list(*b"parT", part), Chunk::list(*b"tdgp", values), Chunk::data(*b"pgui", vec![0u8; 16])])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::export::fx_defs::FX_DEFS;
|
||||
|
||||
/// The `pard` of every parameter of the effect table fits its 148 bytes.
|
||||
#[test]
|
||||
fn every_parameter_definition_fits() {
|
||||
for fx in FX_DEFS {
|
||||
for (i, p) in fx.params.iter().enumerate() {
|
||||
let b = pard_layout(p, popup_items(fx, i));
|
||||
assert!(b.error().is_none(), "{} {}", fx.match_name, i);
|
||||
assert_eq!(b.finish(String::new).len(), 148);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
//! Colour profiles for the working spaces the exporter writes, authored here from the standards
|
||||
//! so that no profile of another party is copied: "Rec.709 Gamma 2.4" (ITU-R BT.709 primaries,
|
||||
//! a pure 2.4 power curve) and "sRGB IEC61966-2.1" (the same primaries, the IEC 61966-2-1
|
||||
//! curve), both D65, ICC.1:2010 v4 with a D50 PCS and a Bradford adaptation. After Effects keeps
|
||||
//! a working space as the profile's data (base64) and its profile ID (`cpid`, 624: the MD5
|
||||
//! profile ID of the v4 header), R49.
|
||||
|
||||
/// The profile's description and the name After Effects lists the working space under (624).
|
||||
pub(crate) const REC709_NAME: &str = "Rec.709 Gamma 2.4";
|
||||
/// The name After Effects lists the sRGB working space under (620).
|
||||
pub(crate) const SRGB_NAME: &str = "sRGB IEC61966-2.1";
|
||||
|
||||
fn s15(v: f64) -> [u8; 4] {
|
||||
let x = (v * 65536.0).round();
|
||||
let x = if x.is_finite() { x.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) } else { 0.0 };
|
||||
(x as i32).to_be_bytes()
|
||||
}
|
||||
|
||||
type M3 = [[f64; 3]; 3];
|
||||
|
||||
fn mul(a: &M3, b: &M3) -> M3 {
|
||||
let mut o = [[0.0; 3]; 3];
|
||||
for (i, row) in o.iter_mut().enumerate() {
|
||||
for (j, v) in row.iter_mut().enumerate() {
|
||||
*v = (0..3).map(|k| a[i][k] * b[k][j]).sum();
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
fn mulv(a: &M3, v: [f64; 3]) -> [f64; 3] {
|
||||
[0, 1, 2].map(|i| (0..3).map(|k| a[i][k] * v[k]).sum())
|
||||
}
|
||||
|
||||
fn inv(m: &M3) -> M3 {
|
||||
let [[a, b, c], [d, e, f], [g, h, i]] = *m;
|
||||
let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
|
||||
let det = if det.abs() < 1e-12 { 1.0 } else { det };
|
||||
[
|
||||
[(e * i - f * h) / det, (c * h - b * i) / det, (b * f - c * e) / det],
|
||||
[(f * g - d * i) / det, (a * i - c * g) / det, (c * d - a * f) / det],
|
||||
[(d * h - e * g) / det, (b * g - a * h) / det, (a * e - b * d) / det],
|
||||
]
|
||||
}
|
||||
|
||||
fn xyz(x: f64, y: f64) -> [f64; 3] {
|
||||
[x / y, 1.0, (1.0 - x - y) / y]
|
||||
}
|
||||
|
||||
fn mluc(text: &str) -> Vec<u8> {
|
||||
let t: Vec<u8> = text.encode_utf16().flat_map(u16::to_be_bytes).collect();
|
||||
let mut v = b"mluc\0\0\0\0".to_vec();
|
||||
v.extend(1u32.to_be_bytes());
|
||||
v.extend(12u32.to_be_bytes());
|
||||
v.extend(b"enUS");
|
||||
v.extend(u32::try_from(t.len()).unwrap_or(0).to_be_bytes());
|
||||
v.extend(28u32.to_be_bytes());
|
||||
v.extend(t);
|
||||
v
|
||||
}
|
||||
|
||||
fn xyz_tag(v: [f64; 3]) -> Vec<u8> {
|
||||
let mut o = b"XYZ \0\0\0\0".to_vec();
|
||||
for c in v {
|
||||
o.extend(s15(c));
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// The Rec.709 Gamma 2.4 display profile (ICC v4.3) with its profile ID filled in.
|
||||
pub(crate) fn rec709_gamma24() -> Vec<u8> {
|
||||
// A pure power curve: `para` function type 0.
|
||||
let mut trc = b"para\0\0\0\0".to_vec();
|
||||
trc.extend([0, 0, 0, 0]);
|
||||
trc.extend(s15(2.4));
|
||||
profile("Rec.709 Gamma 2.4 (EffectCraft)", trc)
|
||||
}
|
||||
|
||||
/// The sRGB display profile (ICC v4.3): IEC 61966-2-1's curve as `para` function type 3, `Y =
|
||||
/// ((X + 0.055) / 1.055) ^ 2.4` from 0.04045 and `X / 12.92` below.
|
||||
pub(crate) fn srgb() -> Vec<u8> {
|
||||
let mut trc = b"para\0\0\0\0".to_vec();
|
||||
trc.extend([0, 3, 0, 0]);
|
||||
for v in [2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045] {
|
||||
trc.extend(s15(v));
|
||||
}
|
||||
profile(SRGB_NAME, trc)
|
||||
}
|
||||
|
||||
/// A display profile with BT.709 primaries and D65 white, tone curve `trc` and description
|
||||
/// `desc`, its profile ID filled in.
|
||||
fn profile(desc: &str, trc: Vec<u8>) -> Vec<u8> {
|
||||
let prim = [(0.640, 0.330), (0.300, 0.600), (0.150, 0.060)];
|
||||
let w65 = xyz(0.3127, 0.3290);
|
||||
let w50 = [0.9642, 1.0, 0.8249];
|
||||
let cols = prim.map(|(x, y)| xyz(x, y));
|
||||
let p: M3 = [0, 1, 2].map(|r| [0, 1, 2].map(|c| cols[c][r]));
|
||||
let s = mulv(&inv(&p), w65);
|
||||
let m: M3 = [0, 1, 2].map(|r| [0, 1, 2].map(|c| p[r][c] * s[c]));
|
||||
let brad: M3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]];
|
||||
let (cs, cd) = (mulv(&brad, w65), mulv(&brad, w50));
|
||||
let d: M3 = [[cd[0] / cs[0], 0.0, 0.0], [0.0, cd[1] / cs[1], 0.0], [0.0, 0.0, cd[2] / cs[2]]];
|
||||
let chad = mul(&inv(&brad), &mul(&d, &brad));
|
||||
let m50 = mul(&chad, &m);
|
||||
let mut sf32 = b"sf32\0\0\0\0".to_vec();
|
||||
for row in chad {
|
||||
for v in row {
|
||||
sf32.extend(s15(v));
|
||||
}
|
||||
}
|
||||
let tags: [(&[u8; 4], Vec<u8>); 10] = [
|
||||
(b"desc", mluc(desc)),
|
||||
(b"cprt", mluc("No copyright, use freely (EffectCraft)")),
|
||||
(b"wtpt", xyz_tag(w50)),
|
||||
(b"chad", sf32),
|
||||
(b"rXYZ", xyz_tag([m50[0][0], m50[1][0], m50[2][0]])),
|
||||
(b"gXYZ", xyz_tag([m50[0][1], m50[1][1], m50[2][1]])),
|
||||
(b"bXYZ", xyz_tag([m50[0][2], m50[1][2], m50[2][2]])),
|
||||
(b"rTRC", trc.clone()),
|
||||
(b"gTRC", trc.clone()),
|
||||
(b"bTRC", trc),
|
||||
];
|
||||
let start = 128 + 4 + 12 * tags.len();
|
||||
let mut table = Vec::new();
|
||||
let mut body: Vec<u8> = Vec::new();
|
||||
let mut placed: Vec<(Vec<u8>, usize)> = Vec::new();
|
||||
for (sig, data) in &tags {
|
||||
let off = match placed.iter().find(|(d, _)| d == data) {
|
||||
Some((_, off)) => *off,
|
||||
None => {
|
||||
let off = start + body.len();
|
||||
body.extend(data);
|
||||
body.resize(body.len().div_ceil(4) * 4, 0);
|
||||
placed.push((data.clone(), off));
|
||||
off
|
||||
}
|
||||
};
|
||||
table.extend(*sig);
|
||||
table.extend(u32::try_from(off).unwrap_or(0).to_be_bytes());
|
||||
table.extend(u32::try_from(data.len()).unwrap_or(0).to_be_bytes());
|
||||
}
|
||||
let size = start + body.len();
|
||||
let mut icc = vec![0u8; 128];
|
||||
icc[0..4].copy_from_slice(&u32::try_from(size).unwrap_or(0).to_be_bytes());
|
||||
icc[8..12].copy_from_slice(&[4, 0x30, 0, 0]);
|
||||
icc[12..16].copy_from_slice(b"mntr");
|
||||
icc[16..20].copy_from_slice(b"RGB ");
|
||||
icc[20..24].copy_from_slice(b"XYZ ");
|
||||
for (i, v) in [2026u16, 10, 19, 0, 0, 0].iter().enumerate() {
|
||||
icc[24 + 2 * i..26 + 2 * i].copy_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
icc[36..40].copy_from_slice(b"acsp");
|
||||
for (i, c) in w50.iter().enumerate() {
|
||||
icc[68 + 4 * i..72 + 4 * i].copy_from_slice(&s15(*c));
|
||||
}
|
||||
icc.extend(u32::try_from(tags.len()).unwrap_or(0).to_be_bytes());
|
||||
icc.extend(table);
|
||||
icc.extend(body);
|
||||
// Profile ID (ICC.1:2010 7.2.18): the MD5 with flags, rendering intent and the ID zeroed (all
|
||||
// zero here already).
|
||||
let id = md5(&icc);
|
||||
icc[84..100].copy_from_slice(&id);
|
||||
icc
|
||||
}
|
||||
|
||||
/// The profile ID of a v4 profile (header bytes 84..100).
|
||||
pub(crate) fn profile_id(icc: &[u8]) -> [u8; 16] {
|
||||
let mut id = [0u8; 16];
|
||||
if let Some(src) = icc.get(84..100) {
|
||||
id.copy_from_slice(src);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// MD5 (RFC 1321).
|
||||
pub(crate) fn md5(data: &[u8]) -> [u8; 16] {
|
||||
const S: [u32; 64] = [
|
||||
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4,
|
||||
11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
|
||||
];
|
||||
let k: [u32; 64] = std::array::from_fn(|i| ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32);
|
||||
let mut msg = data.to_vec();
|
||||
let bits = (data.len() as u64).wrapping_mul(8);
|
||||
msg.push(0x80);
|
||||
while msg.len() % 64 != 56 {
|
||||
msg.push(0);
|
||||
}
|
||||
msg.extend(bits.to_le_bytes());
|
||||
let (mut a0, mut b0, mut c0, mut d0) = (0x6745_2301u32, 0xefcd_ab89u32, 0x98ba_dcfeu32, 0x1032_5476u32);
|
||||
let (blocks, _) = msg.as_chunks::<64>();
|
||||
for chunk in blocks {
|
||||
let m: [u32; 16] = std::array::from_fn(|i| u32::from_le_bytes([chunk[4 * i], chunk[4 * i + 1], chunk[4 * i + 2], chunk[4 * i + 3]]));
|
||||
let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
|
||||
for i in 0..64 {
|
||||
let (f, g) = match i / 16 {
|
||||
0 => ((b & c) | (!b & d), i),
|
||||
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
|
||||
2 => (b ^ c ^ d, (3 * i + 5) % 16),
|
||||
_ => (c ^ (b | !d), (7 * i) % 16),
|
||||
};
|
||||
let f = f.wrapping_add(a).wrapping_add(k[i]).wrapping_add(m[g]);
|
||||
a = d;
|
||||
d = c;
|
||||
c = b;
|
||||
b = b.wrapping_add(f.rotate_left(S[i]));
|
||||
}
|
||||
a0 = a0.wrapping_add(a);
|
||||
b0 = b0.wrapping_add(b);
|
||||
c0 = c0.wrapping_add(c);
|
||||
d0 = d0.wrapping_add(d);
|
||||
}
|
||||
let mut out = [0u8; 16];
|
||||
for (i, w) in [a0, b0, c0, d0].iter().enumerate() {
|
||||
out[4 * i..4 * i + 4].copy_from_slice(&w.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The colour profile JSON After Effects stores for a working space or a footage item (620, 624):
|
||||
/// the profile's data and its name.
|
||||
pub(crate) fn profile_json(icc: &[u8], name: &str) -> String {
|
||||
format!("{{\"baseColorProfile\":{{\"colorProfileData\":\"{}\",\"colorProfileName\":\"{}\"}},\"baseProfileType\":2}}", base64(icc), name)
|
||||
}
|
||||
|
||||
/// Standard base64 with padding.
|
||||
pub(crate) fn base64(data: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for c in data.chunks(3) {
|
||||
let n = (u32::from(c[0]) << 16) | (u32::from(c.get(1).copied().unwrap_or(0)) << 8) | u32::from(c.get(2).copied().unwrap_or(0));
|
||||
for (i, shift) in [18u32, 12, 6, 0].iter().enumerate() {
|
||||
if i <= c.len() {
|
||||
out.push(char::from(T[((n >> shift) & 63) as usize]));
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn md5_and_base64_match_their_specifications() {
|
||||
// RFC 1321 test suite and RFC 4648.
|
||||
assert_eq!(md5(b"").iter().map(|b| format!("{b:02x}")).collect::<String>(), "d41d8cd98f00b204e9800998ecf8427e");
|
||||
assert_eq!(md5(b"abc").iter().map(|b| format!("{b:02x}")).collect::<String>(), "900150983cd24fb0d6963f7d28e17f72");
|
||||
let long = b"12345678901234567890123456789012345678901234567890123456789012345678901234567890";
|
||||
assert_eq!(md5(long).iter().map(|b| format!("{b:02x}")).collect::<String>(), "57edf4a22be3c955ac49da2e2107b67a");
|
||||
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
|
||||
assert_eq!(base64(b"fooba"), "Zm9vYmE=");
|
||||
assert_eq!(base64(b"foob"), "Zm9vYg==");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_srgb_profile_carries_the_iec_curve() {
|
||||
let icc = srgb();
|
||||
assert_eq!(u32::from_be_bytes(icc[0..4].try_into().unwrap()) as usize, icc.len());
|
||||
let mut z = icc.clone();
|
||||
z[84..100].fill(0);
|
||||
assert_eq!(profile_id(&icc), md5(&z));
|
||||
let at = icc.windows(8).position(|w| w == b"para\0\0\0\0").unwrap();
|
||||
assert_eq!(&icc[at + 8..at + 12], &[0, 3, 0, 0]);
|
||||
// AE shows its own name for the space only when the description is exactly this.
|
||||
let name: Vec<u8> = SRGB_NAME.encode_utf16().flat_map(u16::to_be_bytes).collect();
|
||||
let at = icc.windows(name.len()).position(|w| w == name.as_slice()).unwrap();
|
||||
assert_ne!(&icc[at + name.len()..at + name.len() + 2], b"\0 ", "no suffix after the name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rec709_profile_is_a_valid_v4_display_profile() {
|
||||
let icc = rec709_gamma24();
|
||||
assert_eq!(u32::from_be_bytes(icc[0..4].try_into().unwrap()) as usize, icc.len());
|
||||
assert_eq!(&icc[36..40], b"acsp");
|
||||
// The ID is the MD5 of the profile with the ID zeroed.
|
||||
let mut z = icc.clone();
|
||||
z[84..100].fill(0);
|
||||
assert_eq!(profile_id(&icc), md5(&z));
|
||||
// D50 red primary of BT.709 (0.4361, 0.2225, 0.0139).
|
||||
let tags = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize;
|
||||
let r = (0..tags).find(|t| &icc[132 + 12 * t..136 + 12 * t] == b"rXYZ").unwrap();
|
||||
let off = u32::from_be_bytes(icc[136 + 12 * r..140 + 12 * r].try_into().unwrap()) as usize;
|
||||
let x = f64::from(i32::from_be_bytes(icc[off + 8..off + 12].try_into().unwrap())) / 65536.0;
|
||||
assert!((x - 0.4361).abs() < 2e-4, "{x}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Key lists shared by the exporters: the times of a property's keys in the file's units, the
|
||||
//! spatial key record, and the rewrite of a key list (`LIST list`: `lhd3` + `ldat`, aep-format.md
|
||||
//! 3.5).
|
||||
|
||||
use effectcraft_keyframe::Keyframe;
|
||||
|
||||
use crate::Chunk;
|
||||
use crate::export::plan::KeyPlan;
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::timebase::TimeBase;
|
||||
use crate::export::tree::{R, child_data, kids_mut, list_mut, put, put_f64, put_u8, put_u16, put_u32, tpl};
|
||||
|
||||
/// The keys of a property at their times in the file's units, in time order. A key that does not
|
||||
/// fall on the time base is reported as moved; keys that end up at the same time are merged (the
|
||||
/// first one is kept) and reported once. `noun` names the key in the report ("key", "path key").
|
||||
pub(crate) fn timed_keys<'k>(keys: &'k [Keyframe], tb: &TimeBase, what: &str, noun: &str, col: &mut Collector) -> Vec<(i64, &'k Keyframe)> {
|
||||
let mut timed: Vec<(i64, &Keyframe)> = Vec::with_capacity(keys.len());
|
||||
for k in keys {
|
||||
let (u, inexact) = tb.units(k.time);
|
||||
if inexact {
|
||||
col.lose(LossCategory::RoundedTimes, format!("{what}: {noun} at {:.4} s moved to the time base", k.time.seconds()));
|
||||
}
|
||||
timed.push((u, k));
|
||||
}
|
||||
timed.sort_by_key(|(u, _)| *u);
|
||||
let before = timed.len();
|
||||
timed.dedup_by_key(|(u, _)| *u);
|
||||
if timed.len() != before {
|
||||
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: {noun}s at the same time were merged"));
|
||||
}
|
||||
timed
|
||||
}
|
||||
|
||||
/// A key of a point (flags `0x0007`, `u32@8` the automatic tangent switch; the spatial layout of
|
||||
/// a 2D Position, 853) or a colour (flags `0x0001`, 854): the temporal ease of a point at 24..55,
|
||||
/// then the `n` values at 56 and, for a point, the spatial in and out tangents after them.
|
||||
pub(crate) fn spatial_record(k: &KeyPlan, n: usize, point: bool, size: usize) -> R<Vec<u8>> {
|
||||
let mut r = vec![0u8; size];
|
||||
put(&mut r, 0, &k.time.to_be_bytes())?;
|
||||
put_u8(&mut r, 4, k.in_interp)?;
|
||||
put_u8(&mut r, 5, k.out_interp)?;
|
||||
let base: u16 = if point { 0x0007 } else { 0x0001 };
|
||||
put_u16(&mut r, 6, base | (u16::from(k.label) << 6))?;
|
||||
if point {
|
||||
put_u32(&mut r, 8, u32::from(k.spatial_auto))?;
|
||||
let (i, o) = (k.in_ease.first().copied().unwrap_or_default(), k.out_ease.first().copied().unwrap_or_default());
|
||||
put_f64(&mut r, 24, i.speed)?;
|
||||
put_f64(&mut r, 32, i.influence)?;
|
||||
put_f64(&mut r, 40, o.speed)?;
|
||||
put_f64(&mut r, 48, o.influence)?;
|
||||
}
|
||||
for j in 0..n {
|
||||
put_f64(&mut r, 56 + 8 * j, k.value.get(j).copied().unwrap_or(0.0))?;
|
||||
if point {
|
||||
put_f64(&mut r, 56 + 8 * n + 8 * j, k.spatial_in.get(j).copied().unwrap_or(0.0))?;
|
||||
put_f64(&mut r, 56 + 16 * n + 8 * j, k.spatial_out.get(j).copied().unwrap_or(0.0))?;
|
||||
}
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Fills a key list (`LIST list`) with `count` records of `size` bytes: the count words of `lhd3`
|
||||
/// and `ldat` (added when the list has none).
|
||||
pub(crate) fn fill_key_list(list: &mut Chunk<'static>, records: Vec<u8>, count: usize, size: usize) -> R<()> {
|
||||
let n = u32::try_from(count).map_err(|_| tpl("too many keys"))?;
|
||||
let size = u32::try_from(size).map_err(|_| tpl("record size"))?;
|
||||
crate::export::synth::put_key_counts(child_data(list, b"lhd3")?, n, size)?;
|
||||
let kids = kids_mut(list)?;
|
||||
match kids.iter_mut().find(|c| c.is(b"ldat")) {
|
||||
Some(c) => *c = Chunk::data(*b"ldat", records),
|
||||
None => kids.push(Chunk::data(*b"ldat", records)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrites the key list of a keyed property record (`LIST tdbs`), see [`fill_key_list`].
|
||||
pub(crate) fn set_key_list(tdbs: &mut Chunk<'static>, records: Vec<u8>, count: usize, size: usize) -> R<()> {
|
||||
fill_key_list(list_mut(tdbs, b"list")?, records, count, size)
|
||||
}
|
||||
|
||||
/// Puts the key list `list` in the place of the static value (`cdat`) of a property record.
|
||||
pub(crate) fn replace_cdat(tdbs: &mut Chunk<'static>, list: Chunk<'static>) -> R<()> {
|
||||
let slot = kids_mut(tdbs)?.iter_mut().find(|c| c.is(b"cdat")).ok_or_else(|| tpl("record without cdat"))?;
|
||||
*slot = list;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::export::synth::key_list;
|
||||
|
||||
/// Keys are timed sorted merged and reported.
|
||||
#[test]
|
||||
fn keys_are_timed_sorted_merged_and_reported() {
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_time::{TICKS_PER_SECOND, Tick};
|
||||
let tb = TimeBase { frame_duration: 1024, timescale: 25600 };
|
||||
// Out of order; 1/3 s is not on the time base; two keys meet at 1 s (the first one kept).
|
||||
let keys = [
|
||||
Keyframe::new(Tick(TICKS_PER_SECOND), Value::Scalar(1.0)),
|
||||
Keyframe::new(Tick(TICKS_PER_SECOND / 3), Value::Scalar(2.0)),
|
||||
Keyframe::new(Tick(0), Value::Scalar(3.0)),
|
||||
Keyframe::new(Tick(TICKS_PER_SECOND), Value::Scalar(4.0)),
|
||||
];
|
||||
let mut col = Collector::default();
|
||||
let timed = timed_keys(&keys, &tb, "L", "path key", &mut col);
|
||||
let got: Vec<(i64, f64)> = timed.iter().map(|(u, k)| (*u, if let Value::Scalar(v) = k.value { v } else { f64::NAN })).collect();
|
||||
assert_eq!(got, [(0, 3.0), (8533, 2.0), (25600, 1.0)]);
|
||||
// The report lists its categories in a fixed order; one merge report for the pair.
|
||||
let report = col.finish();
|
||||
let lines: Vec<(LossCategory, &str)> = report.losses.iter().flat_map(|l| l.details.iter().map(move |d| (l.category, d.as_str()))).collect();
|
||||
assert_eq!(
|
||||
lines,
|
||||
[
|
||||
(LossCategory::ApproximatedKeyframes, "L: path keys at the same time were merged"),
|
||||
(LossCategory::RoundedTimes, "L: path key at 0.3333 s moved to the time base"),
|
||||
]
|
||||
);
|
||||
// No keys, no report.
|
||||
let mut col = Collector::default();
|
||||
assert!(timed_keys(&[], &tb, "L", "key", &mut col).is_empty());
|
||||
assert!(col.finish().losses.is_empty());
|
||||
}
|
||||
|
||||
/// Two keys at different times that round to the same time unit are merged too: the first
|
||||
/// one is kept, and both the rounding and the merge are reported.
|
||||
#[test]
|
||||
fn keys_that_round_to_the_same_time_are_merged() {
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_time::Tick;
|
||||
let tb = TimeBase { frame_duration: 1024, timescale: 25600 };
|
||||
// One tick is far below one unit (1/25600 s): it rounds to unit 0, where the first key is.
|
||||
let keys = [Keyframe::new(Tick(0), Value::Scalar(1.0)), Keyframe::new(Tick(1), Value::Scalar(2.0))];
|
||||
let mut col = Collector::default();
|
||||
let timed = timed_keys(&keys, &tb, "L", "key", &mut col);
|
||||
let got: Vec<(i64, f64)> = timed.iter().map(|(u, k)| (*u, if let Value::Scalar(v) = k.value { v } else { f64::NAN })).collect();
|
||||
assert_eq!(got, [(0, 1.0)]);
|
||||
let report = col.finish();
|
||||
let lines: Vec<(LossCategory, &str)> = report.losses.iter().flat_map(|l| l.details.iter().map(move |d| (l.category, d.as_str()))).collect();
|
||||
assert_eq!(
|
||||
lines,
|
||||
[
|
||||
(LossCategory::ApproximatedKeyframes, "L: keys at the same time were merged"),
|
||||
(LossCategory::RoundedTimes, "L: key at 0.0000 s moved to the time base"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A key list is filled and replaces the value.
|
||||
#[test]
|
||||
fn a_key_list_is_filled_and_replaces_the_value() {
|
||||
let mut list = Chunk::list(*b"list", vec![Chunk::data(*b"lhd3", vec![0; 52])]);
|
||||
fill_key_list(&mut list, vec![7; 96], 2, 48).unwrap();
|
||||
let h = list.child(b"lhd3").and_then(|c| c.bytes()).unwrap();
|
||||
assert_eq!((h[11], h[19]), (2, 48));
|
||||
assert_eq!(list.child(b"ldat").and_then(|c| c.bytes()).map(<[u8]>::len), Some(96));
|
||||
// A second fill replaces the records instead of adding a second `ldat`.
|
||||
fill_key_list(&mut list, vec![1; 48], 1, 48).unwrap();
|
||||
assert_eq!(list.children().iter().filter(|c| c.is(b"ldat")).count(), 1);
|
||||
|
||||
let mut rec = Chunk::list(*b"tdbs", vec![Chunk::data(*b"tdb4", vec![0; 124]), Chunk::data(*b"cdat", vec![0; 8])]);
|
||||
replace_cdat(&mut rec, key_list(48, 0, Vec::new())).unwrap();
|
||||
assert!(rec.child(b"cdat").is_none() && rec.child_list(b"list").is_some());
|
||||
// A record without a value is an error, not a quiet no-op.
|
||||
assert!(replace_cdat(&mut rec, key_list(48, 0, Vec::new())).is_err());
|
||||
set_key_list(&mut rec, vec![0; 48], 1, 48).unwrap();
|
||||
assert!(set_key_list(&mut Chunk::list(*b"tdbs", Vec::new()), Vec::new(), 0, 48).is_err());
|
||||
}
|
||||
|
||||
/// A spatial record holds the point layout.
|
||||
#[test]
|
||||
fn a_spatial_record_holds_the_point_layout() {
|
||||
let k = KeyPlan {
|
||||
time: 5,
|
||||
value: vec![1.0, 2.0],
|
||||
in_interp: 2,
|
||||
out_interp: 1,
|
||||
in_ease: Vec::new(),
|
||||
out_ease: Vec::new(),
|
||||
spatial_in: [3.0; 3],
|
||||
spatial_out: [4.0; 3],
|
||||
spatial_auto: true,
|
||||
roving: false,
|
||||
label: 1,
|
||||
};
|
||||
let r = spatial_record(&k, 2, true, 56 + 24 * 2).unwrap();
|
||||
assert_eq!(&r[..12], &[0, 0, 0, 5, 2, 1, 0, 0x47, 0, 0, 0, 1]);
|
||||
assert_eq!(&r[64..72], &2.0f64.to_be_bytes());
|
||||
assert_eq!(&r[96..104], &4.0f64.to_be_bytes());
|
||||
// A colour has no tangents and flags 0x0001.
|
||||
let c = spatial_record(&k, 2, false, 56 + 24 * 2).unwrap();
|
||||
assert_eq!((c[7], c[11]), (0x41, 0));
|
||||
assert!(c[72..].iter().all(|b| *b == 0));
|
||||
// A record shorter than its layout is an error.
|
||||
assert!(spatial_record(&k, 2, true, 64).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Layer and composition markers (`docs/aep-format.md` 3.11; cases 122, 123, 249, 347-349, 509,
|
||||
//! 510). A marker group is `tdmn ADBE Marker` + `LIST mrst`: a `tdbs` whose key list holds one
|
||||
//! 16-byte record per marker (the time in the owner's time units, bytes 4 and 5 = 3, the rest
|
||||
//! written 0: After Effects leaves session bytes there) and a `LIST mrky` with one `LIST Nmrd` per
|
||||
//! marker (`NmHd`: cue type, number of cue parameters, duration in 1/600 s, 600, label; then the
|
||||
//! comment, chapter, URL, frame target and cue point name and the parameter pairs as `Utf8`).
|
||||
|
||||
use crate::Chunk;
|
||||
use effectcraft_project::Marker;
|
||||
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::timebase::TimeBase;
|
||||
use crate::export::tree::{R, child_data, kids_mut, list_mut, put, put_u8, put_u32, tpl};
|
||||
|
||||
/// The units per second of a marker duration (`NmHd` @12, 249).
|
||||
const DURATION_UNITS: f64 = 600.0;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct MarkerPlan {
|
||||
pub time: i32,
|
||||
pub duration: u32,
|
||||
pub label: u8,
|
||||
/// 4 event cue (also without a cue point), 5 navigation cue (347, 348).
|
||||
pub cue: u32,
|
||||
/// Comment, chapter, URL, frame target, cue point name (249).
|
||||
pub strings: [String; 5],
|
||||
pub params: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The markers in the file's units (`tb` is the owner's time base: the composition's, or the
|
||||
/// layer's for layer markers); what cannot be written is reported.
|
||||
pub(crate) fn plan(markers: &[Marker], tb: &TimeBase, what: &str, col: &mut Collector) -> Vec<MarkerPlan> {
|
||||
let mut out: Vec<MarkerPlan> = Vec::with_capacity(markers.len());
|
||||
for m in markers {
|
||||
let (u, inexact) = tb.units(m.time);
|
||||
let Ok(time) = i32::try_from(u) else {
|
||||
col.lose(LossCategory::Markers, format!("{what}: a marker time out of range is not written"));
|
||||
continue;
|
||||
};
|
||||
if inexact {
|
||||
col.lose(LossCategory::RoundedTimes, format!("{what}: marker at {:.4} s moved to the time base", m.time.seconds()));
|
||||
}
|
||||
let d = m.duration.seconds() * DURATION_UNITS;
|
||||
let duration = if d.is_finite() && d > 0.0 { d.round().min(f64::from(u32::MAX)) as u32 } else { 0 };
|
||||
if d.is_finite() && d > 0.0 && (d - d.round()).abs() > 1e-6 {
|
||||
col.lose(LossCategory::RoundedTimes, format!("{what}: a marker duration is rounded to 1/600 s"));
|
||||
}
|
||||
if m.protected {
|
||||
col.lose(LossCategory::Markers, format!("{what}: the protected-region switch of a marker is not written"));
|
||||
}
|
||||
let (cue, cue_name, params) = match &m.cue_point {
|
||||
Some(c) => (if c.navigation { 5 } else { 4 }, c.name.clone(), c.params.clone()),
|
||||
None => (4, String::new(), Vec::new()),
|
||||
};
|
||||
out.push(MarkerPlan {
|
||||
time,
|
||||
duration,
|
||||
label: crate::export::plan::label_index(m.label),
|
||||
cue,
|
||||
strings: [m.comment.clone(), m.chapter.clone(), m.url.clone(), m.frame_target.clone(), cue_name],
|
||||
params,
|
||||
});
|
||||
}
|
||||
out.sort_by_key(|m| m.time);
|
||||
col.exported.markers = col.exported.markers.saturating_add(out.len());
|
||||
out
|
||||
}
|
||||
|
||||
/// The marker group (`tdmn` + `LIST mrst`) for `plans`, cloned from the prototype (249).
|
||||
pub(crate) fn build(proto: &[Chunk<'static>], plans: &[MarkerPlan]) -> R<Vec<Chunk<'static>>> {
|
||||
let mut group = proto.to_vec();
|
||||
let mrst = group.get_mut(1).filter(|c| c.is_list(b"mrst")).ok_or_else(|| tpl("marker prototype"))?;
|
||||
let n = u32::try_from(plans.len()).map_err(|_| tpl("too many markers"))?;
|
||||
{
|
||||
let tdbs = list_mut(mrst, b"tdbs")?;
|
||||
let list = list_mut(tdbs, b"list")?;
|
||||
let lhd3 = child_data(list, b"lhd3")?;
|
||||
crate::export::synth::put_key_counts(lhd3, n, 16)?;
|
||||
let ldat = child_data(list, b"ldat")?;
|
||||
ldat.clear();
|
||||
for p in plans {
|
||||
let mut rec = [0u8; 16];
|
||||
put(&mut rec, 0, &p.time.to_be_bytes())?;
|
||||
rec[4] = 3;
|
||||
rec[5] = 3;
|
||||
ldat.extend_from_slice(&rec);
|
||||
}
|
||||
}
|
||||
let mrky = list_mut(mrst, b"mrky")?;
|
||||
let nmrd_proto = kids_mut(mrky)?.first().cloned().ok_or_else(|| tpl("marker prototype without Nmrd"))?;
|
||||
let mut entries = Vec::with_capacity(plans.len());
|
||||
for p in plans {
|
||||
let mut nmrd = nmrd_proto.clone();
|
||||
{
|
||||
let h = child_data(&mut nmrd, b"NmHd")?;
|
||||
put_u32(h, 0, p.cue)?;
|
||||
put_u32(h, 4, u32::try_from(p.params.len()).unwrap_or(0))?;
|
||||
put_u32(h, 8, p.duration)?;
|
||||
put_u32(h, 12, 600)?;
|
||||
put_u8(h, 16, p.label)?;
|
||||
}
|
||||
let kids = kids_mut(&mut nmrd)?;
|
||||
kids.retain(|c| !c.is(b"Utf8"));
|
||||
for s in &p.strings {
|
||||
kids.push(Chunk::data(*b"Utf8", s.as_bytes().to_vec()));
|
||||
}
|
||||
for (k, v) in &p.params {
|
||||
kids.push(Chunk::data(*b"Utf8", k.as_bytes().to_vec()));
|
||||
kids.push(Chunk::data(*b"Utf8", v.as_bytes().to_vec()));
|
||||
}
|
||||
entries.push(nmrd);
|
||||
}
|
||||
*kids_mut(mrky)? = entries;
|
||||
Ok(group)
|
||||
}
|
||||
|
||||
/// Inserts the marker group as the first property of a top property group (`tdgp`): right after
|
||||
/// its `tdsb` / `tdsn` header, before Time Remapping or the Transform group (123, 509).
|
||||
pub(crate) fn insert(tdgp: &mut Chunk<'static>, group: Vec<Chunk<'static>>) -> R<()> {
|
||||
let kids = kids_mut(tdgp)?;
|
||||
let at = kids.iter().position(|c| c.is(b"tdmn")).unwrap_or(kids.len());
|
||||
for (i, c) in group.into_iter().enumerate() {
|
||||
kids.insert(at.saturating_add(i), c);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,665 @@
|
||||
//! Layer masks: the plan (file units, losses reported) and the chunks, cloned from the mask
|
||||
//! prototypes built in code ([`MaskProtos::build`], with the layout of our fixtures 091, 093 and
|
||||
//! 208).
|
||||
//!
|
||||
//! What is written, each with its verified layout (`docs/aep-format.md` 3.4, 3.5 and 3.8):
|
||||
//! - per mask a `mkif` (inverted at byte 0, mode `u32` at 4, the layer's running mask counter at
|
||||
//! 8; the other bytes are zero, read-back t-zmkif) and an atom with the user name;
|
||||
//! - the path as `LIST shap` (`shph`: open bit `0x08` of byte 3, the box of vertices and handles
|
||||
//! normalised to the layer source size; `list`: three `f32` points per vertex, vertex `i`, out
|
||||
//! handle `i`, in handle `i + 1`, normalised inside the box);
|
||||
//! - path keys as 64-byte records (time, interpolation, label, the rest copied from the prototype)
|
||||
//! with one `shap` per key;
|
||||
//! - Feather (static or keyed, plain template with two components), Opacity (fraction) and
|
||||
//! Expansion (pixels), each only when it is not at its default.
|
||||
|
||||
use crate::Chunk;
|
||||
use effectcraft_keyframe::{Ease, Interp, ShapePath, Value};
|
||||
use effectcraft_project::{FeatherFalloff, GroupKind, Layer, MaskMode, MaskMotionBlur, PropGroup};
|
||||
|
||||
use crate::export::keys::{set_key_list, timed_keys};
|
||||
use crate::export::plan::{CompPlan, EaseSlot, KeyPlan, LIMIT, cut_name};
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::synth::GROUP_END;
|
||||
use crate::export::tree::{Fixed, R, child_data, child_mut, kids_mut, list_mut, put_f32, put_f64, put_i32, put_u8, put_u16, put_u32, split_group, tpl};
|
||||
|
||||
/// The most vertices one mask path may have (as the importer).
|
||||
pub(crate) const MAX_VERTICES: usize = 65_536;
|
||||
|
||||
/// One path shape in the file's units.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct ShapePlan {
|
||||
/// Left, top, right, bottom as fractions of the layer source size.
|
||||
pub bbox: [f32; 4],
|
||||
pub open: bool,
|
||||
/// Three points per vertex, normalised inside the box.
|
||||
pub points: Vec<[f32; 2]>,
|
||||
}
|
||||
|
||||
/// One path keyframe.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct PathKeyPlan {
|
||||
pub time: i32,
|
||||
/// 1 linear, 2 bezier, 3 hold.
|
||||
pub in_interp: u8,
|
||||
pub out_interp: u8,
|
||||
/// The ease of a bezier side: speed (as stored) and influence (a fraction), at bytes 24..55
|
||||
/// as in the spatial template (599, 700).
|
||||
pub in_ease: (f64, f64),
|
||||
pub out_ease: (f64, f64),
|
||||
pub label: u8,
|
||||
pub shape: ShapePlan,
|
||||
}
|
||||
|
||||
/// A mask in the file's units.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct MaskPlan {
|
||||
pub name: String,
|
||||
/// `mkif` mode id: None 0, Add 1, Subtract 2, Intersect 3, Lighten 4, Darken 5, Difference 6.
|
||||
pub mode: u32,
|
||||
pub inverted: bool,
|
||||
/// The static path (the first key's when the path is keyed).
|
||||
pub shape: ShapePlan,
|
||||
pub path_keys: Vec<PathKeyPlan>,
|
||||
/// Pixels; `None` at the default `[0, 0]`.
|
||||
pub feather: Option<[f64; 2]>,
|
||||
pub feather_keys: Vec<KeyPlan>,
|
||||
/// A fraction; `None` at the default 1.
|
||||
pub opacity: Option<f64>,
|
||||
/// Pixels; `None` at the default 0.
|
||||
pub expansion: Option<f64>,
|
||||
}
|
||||
|
||||
fn mode_id(m: MaskMode) -> u32 {
|
||||
match m {
|
||||
MaskMode::None => 0,
|
||||
MaskMode::Add => 1,
|
||||
MaskMode::Subtract => 2,
|
||||
MaskMode::Intersect => 3,
|
||||
MaskMode::Lighten => 4,
|
||||
MaskMode::Darken => 5,
|
||||
MaskMode::Difference => 6,
|
||||
}
|
||||
}
|
||||
|
||||
fn finite(v: f64) -> Option<f64> {
|
||||
(v.is_finite() && v.abs() <= LIMIT).then_some(v)
|
||||
}
|
||||
|
||||
/// A project path (layer pixels) in the file's units for a layer source of `size` pixels.
|
||||
pub(crate) fn shape_plan(p: &ShapePath, size: (u32, u32)) -> Result<ShapePlan, &'static str> {
|
||||
let n = p.vertices.len();
|
||||
if n == 0 {
|
||||
return Err("its path has no vertices");
|
||||
}
|
||||
if n > MAX_VERTICES {
|
||||
return Err("its path has more than 65 536 vertices");
|
||||
}
|
||||
let (w, h) = (f64::from(size.0.max(1)), f64::from(size.1.max(1)));
|
||||
let at = |i: usize| -> Option<([f64; 2], [f64; 2], [f64; 2])> {
|
||||
let v = *p.vertices.get(i)?;
|
||||
let t_in = p.in_tangents.get(i).copied().unwrap_or([0.0; 2]);
|
||||
let t_out = p.out_tangents.get(i).copied().unwrap_or([0.0; 2]);
|
||||
let add = |a: [f64; 2], b: [f64; 2]| [a[0] + b[0], a[1] + b[1]];
|
||||
Some((v, add(v, t_in), add(v, t_out)))
|
||||
};
|
||||
// Absolute points in layer pixels: vertex i, out handle i, in handle i + 1.
|
||||
let mut abs: Vec<[f64; 2]> = Vec::with_capacity(n.saturating_mul(3));
|
||||
for i in 0..n {
|
||||
let (v, _, out) = at(i).ok_or("its path is incomplete")?;
|
||||
let (_, next_in, _) = at((i + 1) % n).ok_or("its path is incomplete")?;
|
||||
abs.extend([v, out, next_in]);
|
||||
}
|
||||
if !abs.iter().flatten().all(|c| finite(*c).is_some()) {
|
||||
return Err("its path holds a number that is not valid");
|
||||
}
|
||||
// Normalised to the layer size, then the box of all points.
|
||||
let norm: Vec<[f64; 2]> = abs.iter().map(|[x, y]| [x / w, y / h]).collect();
|
||||
let (mut left, mut top, mut right, mut bottom) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
for [x, y] in &norm {
|
||||
left = left.min(*x);
|
||||
right = right.max(*x);
|
||||
top = top.min(*y);
|
||||
bottom = bottom.max(*y);
|
||||
}
|
||||
let bbox = [left as f32, top as f32, right as f32, bottom as f32];
|
||||
let [l, t, r, b] = bbox.map(f64::from);
|
||||
// A box without width or height (all points on one line) stores 0 for that coordinate.
|
||||
let unit = |v: f64, lo: f64, hi: f64| if hi - lo > 0.0 { ((v - lo) / (hi - lo)) as f32 } else { 0.0 };
|
||||
let points = norm.iter().map(|[x, y]| [unit(*x, l, r), unit(*y, t, b)]).collect();
|
||||
Ok(ShapePlan { bbox, open: !p.closed, points })
|
||||
}
|
||||
|
||||
/// Plans the masks of a layer whose source is `size` pixels.
|
||||
pub(crate) fn plan_masks(layer: &Layer, size: (u32, u32), cp: &CompPlan, comp_name: &str, col: &mut Collector) -> Vec<MaskPlan> {
|
||||
let Some(masks) = layer.masks() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for g in masks.groups() {
|
||||
let what = format!("{comp_name}: '{}' {}", layer.name, g.name);
|
||||
if let Some(m) = plan_mask(g, size, cp, &what, col) {
|
||||
col.exported.masks = col.exported.masks.saturating_add(1);
|
||||
out.push(m);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn plan_mask(g: &PropGroup, size: (u32, u32), cp: &CompPlan, what: &str, col: &mut Collector) -> Option<MaskPlan> {
|
||||
let GroupKind::Mask { mode, inverted, locked, motion_blur, feather_falloff, roto_bezier, .. } = g.kind else {
|
||||
col.lose(LossCategory::Masks, format!("{what}: not a mask, not exported"));
|
||||
return None;
|
||||
};
|
||||
if !g.enabled {
|
||||
col.lose(LossCategory::Masks, format!("{what}: a disabled mask is not exported"));
|
||||
return None;
|
||||
}
|
||||
let Some(path_prop) = g.get("path") else {
|
||||
col.lose(LossCategory::Masks, format!("{what}: no path, not exported"));
|
||||
return None;
|
||||
};
|
||||
let Value::Path(static_path) = &path_prop.value else {
|
||||
col.lose(LossCategory::Masks, format!("{what}: the path is not a path, not exported"));
|
||||
return None;
|
||||
};
|
||||
// Switches the file layout does not hold (not decoded).
|
||||
if locked {
|
||||
col.lose(LossCategory::Masks, format!("{what}: the lock is not written"));
|
||||
}
|
||||
if motion_blur != MaskMotionBlur::SameAsLayer {
|
||||
col.lose(LossCategory::Masks, format!("{what}: mask motion blur is written as Same As Layer"));
|
||||
}
|
||||
if feather_falloff != FeatherFalloff::Smooth {
|
||||
col.lose(LossCategory::Masks, format!("{what}: Linear feather falloff is written as Smooth"));
|
||||
}
|
||||
if roto_bezier {
|
||||
col.lose(LossCategory::Masks, format!("{what}: RotoBezier is not written (the tangents are)"));
|
||||
}
|
||||
for id in ["path", "feather", "opacity", "expansion"] {
|
||||
if g.get(id).is_some_and(|p| p.has_expression()) {
|
||||
col.lose(LossCategory::Masks, format!("{what}: the expression on Mask {id} is not written"));
|
||||
}
|
||||
}
|
||||
// The path and its keys.
|
||||
let mut path_keys: Vec<PathKeyPlan> = Vec::new();
|
||||
let keys = timed_keys(&path_prop.keys, &cp.tb, what, "path key", col);
|
||||
let side = |i: Interp| -> u8 {
|
||||
match i {
|
||||
Interp::Linear => 1,
|
||||
Interp::Hold => 3,
|
||||
Interp::Bezier => 2,
|
||||
}
|
||||
};
|
||||
let ease = |e: &[effectcraft_keyframe::Ease], on: bool| -> (f64, f64) {
|
||||
if !on {
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
let e = e.first().copied().unwrap_or(effectcraft_keyframe::Ease { speed: 0.0, influence: 1.0 / 3.0 });
|
||||
let speed = finite(e.speed).filter(|v| v.abs() <= 1e9).unwrap_or(0.0);
|
||||
let influence = if e.influence.is_finite() { e.influence.clamp(0.001, 1.0) } else { 1.0 / 3.0 };
|
||||
(speed, influence)
|
||||
};
|
||||
let mut feather_points = !static_path.feather.is_empty();
|
||||
for (u, k) in &keys {
|
||||
let Ok(time) = i32::try_from(*u) else {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: path key time out of range, key dropped"));
|
||||
continue;
|
||||
};
|
||||
let Value::Path(p) = &k.value else {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: a path key without a path was dropped"));
|
||||
continue;
|
||||
};
|
||||
feather_points |= !p.feather.is_empty();
|
||||
let shape = match shape_plan(p, size) {
|
||||
Ok(s) => s,
|
||||
Err(why) => {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: a path key was dropped, {why}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if k.roving {
|
||||
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a roving path key is written as a normal key"));
|
||||
}
|
||||
let (in_interp, out_interp) = (side(k.in_interp), side(k.out_interp));
|
||||
if (in_interp == 2 && k.in_ease.first().is_some_and(|e| e.speed != 0.0)) || (out_interp == 2 && k.out_ease.first().is_some_and(|e| e.speed != 0.0)) {
|
||||
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a path key ease speed other than 0 is written as stored (its unit is not sampled)"));
|
||||
}
|
||||
let (in_ease, out_ease) = (ease(&k.in_ease, in_interp == 2), ease(&k.out_ease, out_interp == 2));
|
||||
path_keys.push(PathKeyPlan { time, in_interp, out_interp, in_ease, out_ease, label: k.label.min(16), shape });
|
||||
col.exported.keyframes = col.exported.keyframes.saturating_add(1);
|
||||
}
|
||||
if feather_points {
|
||||
col.lose(LossCategory::Masks, format!("{what}: variable-width feather points are not written"));
|
||||
}
|
||||
let shape = match path_keys.first() {
|
||||
Some(k) => k.shape.clone(),
|
||||
None => match shape_plan(static_path, size) {
|
||||
Ok(s) => s,
|
||||
Err(why) => {
|
||||
col.lose(LossCategory::Masks, format!("{what}: not exported, {why}"));
|
||||
return None;
|
||||
}
|
||||
},
|
||||
};
|
||||
// Feather, opacity, expansion.
|
||||
let feather_prop = g.get("feather");
|
||||
let feather_value = match feather_prop.map(|p| &p.value) {
|
||||
Some(Value::Vec2(v)) => *v,
|
||||
_ => [0.0, 0.0],
|
||||
};
|
||||
let feather = match (finite(feather_value[0]), finite(feather_value[1])) {
|
||||
(Some(x), Some(y)) if (0.0..=MASK_LIMIT).contains(&x) && (0.0..=MASK_LIMIT).contains(&y) => ([x, y] != [0.0, 0.0]).then_some([x, y]),
|
||||
_ => {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: feather {feather_value:?} is not valid, the default was written"));
|
||||
None
|
||||
}
|
||||
};
|
||||
let feather_keys = feather_prop.map_or_else(Vec::new, |p| plan_feather_keys(&p.keys, cp, what, col));
|
||||
let scalar = |id: &str, default: f64, lo: f64, hi: f64, col: &mut Collector| -> Option<f64> {
|
||||
let p = g.get(id)?;
|
||||
if !p.keys.is_empty() {
|
||||
col.lose(LossCategory::Masks, format!("{what}: keys on Mask {id} are not written (no keyed prototype), the static value is"));
|
||||
}
|
||||
let Value::Scalar(v) = p.value else { return None };
|
||||
match finite(v) {
|
||||
Some(v) if (lo..=hi).contains(&v) => ((v - default).abs() > 1e-12).then_some(v),
|
||||
_ => {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: Mask {id} {v} is not valid, the default was written"));
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let opacity = scalar("opacity", 100.0, 0.0, 100.0, col).map(|v| v / 100.0);
|
||||
// The record holds -32 000 to 32 000, as for the feather (`tduM`, 091).
|
||||
let expansion = scalar("expansion", 0.0, -MASK_LIMIT, MASK_LIMIT, col);
|
||||
let name = cut_name(&g.name, 255, what, col);
|
||||
Some(MaskPlan { name, mode: mode_id(mode), inverted, shape, path_keys, feather, feather_keys, opacity, expansion })
|
||||
}
|
||||
|
||||
/// Feather keys (plain template, two components, speed in pixels per second).
|
||||
fn plan_feather_keys(src: &[effectcraft_keyframe::Keyframe], cp: &CompPlan, what: &str, col: &mut Collector) -> Vec<KeyPlan> {
|
||||
let keys = timed_keys(src, &cp.tb, what, "feather key", col);
|
||||
let mut out = Vec::with_capacity(keys.len());
|
||||
let beyond = std::cell::Cell::new(false);
|
||||
for (u, k) in &keys {
|
||||
let Ok(time) = i32::try_from(*u) else {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: feather key time out of range, key dropped"));
|
||||
continue;
|
||||
};
|
||||
let value = match &k.value {
|
||||
Value::Vec2([x, y]) => match (finite(*x), finite(*y)) {
|
||||
(Some(x), Some(y)) if (0.0..=MASK_LIMIT).contains(&x) && (0.0..=MASK_LIMIT).contains(&y) => vec![x, y],
|
||||
_ => {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: a feather key that is not valid was dropped"));
|
||||
continue;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: a feather key that is not a pair was dropped"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let code = |i: Interp| match i {
|
||||
Interp::Linear => 1u8,
|
||||
Interp::Bezier => 2,
|
||||
Interp::Hold => 3,
|
||||
};
|
||||
let (in_interp, out_interp) = (code(k.in_interp), code(k.out_interp));
|
||||
let ease = |eases: &[Ease], i: usize, on: bool| -> EaseSlot {
|
||||
if !on {
|
||||
return EaseSlot::default();
|
||||
}
|
||||
let e = crate::export::plan::key_ease(eases, i);
|
||||
let speed = finite(e.speed).filter(|v| v.abs() <= 1e9).unwrap_or_else(|| {
|
||||
beyond.set(true);
|
||||
0.0
|
||||
});
|
||||
EaseSlot { speed, influence: if e.influence.is_finite() { e.influence.clamp(0.001, 1.0) } else { 1.0 / 3.0 } }
|
||||
};
|
||||
out.push(KeyPlan {
|
||||
time,
|
||||
value,
|
||||
in_interp,
|
||||
out_interp,
|
||||
in_ease: (0..2).map(|i| ease(&k.in_ease, i, in_interp == 2)).collect(),
|
||||
out_ease: (0..2).map(|i| ease(&k.out_ease, i, out_interp == 2)).collect(),
|
||||
spatial_in: [0.0; 3],
|
||||
spatial_out: [0.0; 3],
|
||||
spatial_auto: false,
|
||||
roving: false,
|
||||
label: k.label.min(16),
|
||||
});
|
||||
if k.roving {
|
||||
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a roving feather key is written as a normal key"));
|
||||
}
|
||||
col.exported.keyframes = col.exported.keyframes.saturating_add(1);
|
||||
}
|
||||
crate::export::plan::report_beyond(beyond.get(), what, col);
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- chunks
|
||||
|
||||
/// The mask prototypes.
|
||||
pub(crate) struct MaskProtos {
|
||||
/// `tdmn ADBE Mask Parade`.
|
||||
pub parade_name: Chunk<'static>,
|
||||
/// The parade group children before its first match name (`tdsb`, `tdsn`).
|
||||
pub parade_header: Vec<Chunk<'static>>,
|
||||
/// `tdmn ADBE Mask Atom`, `mkif`, the atom `tdgp` (with static Feather, Opacity, Offset).
|
||||
pub atom_name: Chunk<'static>,
|
||||
pub mkif: Chunk<'static>,
|
||||
pub atom: Chunk<'static>,
|
||||
/// `tdmn ADBE Group End`.
|
||||
pub group_end: Chunk<'static>,
|
||||
/// The keyed path property (`tdbs`, two 64-byte records).
|
||||
pub keyed_path: Chunk<'static>,
|
||||
/// The keyed Mask Feather property (`tdbs`, two 88-byte records).
|
||||
pub keyed_feather: Chunk<'static>,
|
||||
}
|
||||
|
||||
/// The limit of a mask's feather and expansion (`tduM` 32 000, 091).
|
||||
const MASK_LIMIT: f64 = 32_000.0;
|
||||
|
||||
/// A shape header (`shph`, 24 bytes, aep-format.md 3.8): bytes 0..2 `b3 de 02` (in every
|
||||
/// sample; meaning not decoded, and zero there is "an internally damaged shape" for After Effects,
|
||||
/// s13-m1), byte 3 `0x01` (`0x09` once the path is open), the box at 4..19 (written per shape),
|
||||
/// byte 20 1.
|
||||
pub(crate) fn shph() -> Vec<u8> {
|
||||
shph_layout().finish(|| "shph".to_string())
|
||||
}
|
||||
|
||||
/// The 24-byte `shph` layout of a closed path with a unit box.
|
||||
fn shph_layout() -> Fixed {
|
||||
let mut b = Fixed::zeroed(24);
|
||||
b.put(0, &[0xb3, 0xde, 0x02, 0x01]);
|
||||
b.put(20, &[1]);
|
||||
b
|
||||
}
|
||||
|
||||
/// The two prototype records of a keyed path (093): 64 bytes each, flags `0x0001`, the `f64` at
|
||||
/// 16 1 in the first (the rest is zero: its last bytes were uninitialised).
|
||||
fn path_key_records() -> Fixed {
|
||||
let mut b = Fixed::zeroed(128);
|
||||
for at in [6, 64 + 6] {
|
||||
b.put(at, &0x0001u16.to_be_bytes());
|
||||
}
|
||||
b.put(16, &1.0f64.to_be_bytes());
|
||||
b
|
||||
}
|
||||
|
||||
impl MaskProtos {
|
||||
/// The prototypes built in code (aep-format.md 3.8): the parade and atom groups, `mkif` with
|
||||
/// only its decoded fields (bytes 12..47 zero, read-back t-zmkif), the path, feather, opacity
|
||||
/// and expansion records, and the keyed path and feather records.
|
||||
pub(crate) fn build() -> MaskProtos {
|
||||
use crate::export::synth::{KeyTemplate, NO_NAME, RecSpec, class, key_list, tdb4, tdbs, tdmn, tdsn};
|
||||
let state = || Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec());
|
||||
// The path property: one component of the path template (`tdb4` byte 7 = 1), a 4-byte
|
||||
// `cdat`; the shapes follow in `omks`.
|
||||
let path = RecSpec { dims: 1, template: KeyTemplate::Spatial(1), class: class::PATH, limits: None, byte5: None };
|
||||
let path_rec = |keyed: bool| {
|
||||
let mut kids = vec![state(), tdsn(NO_NAME), Chunk::data(*b"tdb4", tdb4(&path, keyed, 25_600))];
|
||||
if keyed {
|
||||
kids.push(key_list(64, 2, path_key_records().finish(|| "the keyed path records".to_string())));
|
||||
} else {
|
||||
kids.push(Chunk::data(*b"cdat", vec![0u8; 4]));
|
||||
}
|
||||
Chunk::list(*b"tdbs", kids)
|
||||
};
|
||||
let shap = Chunk::list(*b"shap", vec![Chunk::data(*b"shph", shph()), key_list(8, 0, Vec::new()), Chunk::data(*b"omtn", Vec::new())]);
|
||||
let feather = RecSpec { dims: 2, template: KeyTemplate::Plain, class: class::EFFECT_NUMBER, limits: Some((0.0, MASK_LIMIT)), byte5: None };
|
||||
let opacity = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_NUMBER, limits: Some((0.0, 100.0)), byte5: None };
|
||||
let offset = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_NUMBER, limits: Some((-MASK_LIMIT, MASK_LIMIT)), byte5: None };
|
||||
let atom = Chunk::list(
|
||||
*b"tdgp",
|
||||
vec![
|
||||
state(),
|
||||
tdsn("Mask 1"),
|
||||
tdmn("ADBE Mask Shape"),
|
||||
Chunk::list(*b"om-s", vec![path_rec(false), Chunk::list(*b"omks", vec![shap])]),
|
||||
tdmn("ADBE Mask Feather"),
|
||||
tdbs(&feather, false, 25_600),
|
||||
tdmn("ADBE Mask Opacity"),
|
||||
tdbs(&opacity, false, 25_600),
|
||||
tdmn("ADBE Mask Offset"),
|
||||
tdbs(&offset, false, 25_600),
|
||||
tdmn(GROUP_END),
|
||||
],
|
||||
);
|
||||
MaskProtos {
|
||||
parade_name: tdmn("ADBE Mask Parade"),
|
||||
parade_header: vec![state(), tdsn(NO_NAME)],
|
||||
atom_name: tdmn("ADBE Mask Atom"),
|
||||
mkif: Chunk::data(*b"mkif", vec![0u8; 48]),
|
||||
atom,
|
||||
group_end: tdmn(GROUP_END),
|
||||
keyed_path: path_rec(true),
|
||||
keyed_feather: tdbs(&feather, true, 25_600),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `tdmn` + `ADBE Mask Parade` group for the masks of a layer (source `size` pixels).
|
||||
pub(crate) fn build_parade(t: &MaskProtos, masks: &[MaskPlan], size: (u32, u32)) -> R<[Chunk<'static>; 2]> {
|
||||
let mut kids = t.parade_header.clone();
|
||||
for (i, m) in masks.iter().enumerate() {
|
||||
let mut mkif = t.mkif.clone();
|
||||
{
|
||||
let d = crate::export::tree::data_mut(&mut mkif)?;
|
||||
put_u8(d, 0, u8::from(m.inverted))?;
|
||||
put_u32(d, 4, m.mode)?;
|
||||
put_u32(d, 8, u32::try_from(i.saturating_add(1)).map_err(|_| tpl("too many masks"))?)?;
|
||||
}
|
||||
kids.push(t.atom_name.clone());
|
||||
kids.push(mkif);
|
||||
kids.push(build_atom(t, m, size)?);
|
||||
}
|
||||
kids.push(t.group_end.clone());
|
||||
Ok([t.parade_name.clone(), Chunk::list(*b"tdgp", kids)])
|
||||
}
|
||||
|
||||
fn build_atom(t: &MaskProtos, m: &MaskPlan, size: (u32, u32)) -> R<Chunk<'static>> {
|
||||
let mut atom = t.atom.clone();
|
||||
{
|
||||
let tdsn = child_mut(&mut atom, b"tdsn")?;
|
||||
crate::export::tree::set_utf8(tdsn, &m.name)?;
|
||||
}
|
||||
let (mut out, entries) = split_group(kids_mut(&mut atom)?)?;
|
||||
let mut has_shape = false;
|
||||
for (name, entry) in entries {
|
||||
// The closing Group End (no node) is kept as it is.
|
||||
let [tdmn, mut node]: [Chunk<'static>; 2] = match entry.try_into() {
|
||||
Ok(pair) => pair,
|
||||
Err(end) => {
|
||||
out.extend(end);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let keep = match name.as_str() {
|
||||
"ADBE Mask Shape" => {
|
||||
build_shape(t, &mut node, m, size)?;
|
||||
has_shape = true;
|
||||
true
|
||||
}
|
||||
"ADBE Mask Feather" => {
|
||||
if !m.feather_keys.is_empty() {
|
||||
node = keyed_feather(t, &m.feather_keys)?;
|
||||
true
|
||||
} else if let Some([x, y]) = m.feather {
|
||||
set_cdat(&mut node, &[x, y])?;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
"ADBE Mask Opacity" => match m.opacity {
|
||||
Some(v) => {
|
||||
set_cdat(&mut node, &[v])?;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
"ADBE Mask Offset" => match m.expansion {
|
||||
Some(v) => {
|
||||
set_cdat(&mut node, &[v])?;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
_ => true,
|
||||
};
|
||||
if keep {
|
||||
out.push(tdmn);
|
||||
out.push(node);
|
||||
}
|
||||
}
|
||||
// A prototype without the path would drop every mask's shape.
|
||||
if !has_shape {
|
||||
return Err(tpl("mask atom without its path"));
|
||||
}
|
||||
*kids_mut(&mut atom)? = out;
|
||||
Ok(atom)
|
||||
}
|
||||
|
||||
fn set_cdat(tdbs: &mut Chunk<'static>, values: &[f64]) -> R<()> {
|
||||
let cdat = child_data(tdbs, b"cdat")?;
|
||||
cdat.iter_mut().for_each(|b| *b = 0);
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
put_f64(cdat, i * 8, *v)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn keyed_feather(t: &MaskProtos, keys: &[KeyPlan]) -> R<Chunk<'static>> {
|
||||
let mut tdbs = t.keyed_feather.clone();
|
||||
// The plain template with two components (208): 8 + 40 * 2 bytes.
|
||||
let size = 88;
|
||||
let mut ldat = Vec::with_capacity(size * keys.len());
|
||||
for k in keys {
|
||||
ldat.extend(crate::export::emit::plain_record(2, k, size)?);
|
||||
}
|
||||
set_key_list(&mut tdbs, ldat, keys.len(), size)?;
|
||||
Ok(tdbs)
|
||||
}
|
||||
|
||||
/// The `om-s` of the path: the property (static or keyed) and one `shap` per shape.
|
||||
fn build_shape(t: &MaskProtos, oms: &mut Chunk<'static>, m: &MaskPlan, size: (u32, u32)) -> R<()> {
|
||||
let aspect = f64::from(size.0.max(1)) / f64::from(size.1.max(1));
|
||||
let shapes: Vec<&ShapePlan> = if m.path_keys.is_empty() { vec![&m.shape] } else { m.path_keys.iter().map(|k| &k.shape).collect() };
|
||||
let kids = kids_mut(oms)?;
|
||||
// The shape prototype (one static `shap`).
|
||||
let omks = kids.iter_mut().find(|c| c.is_list(b"omks")).ok_or_else(|| tpl("mask path without omks"))?;
|
||||
let proto = kids_mut(omks)?.iter().find(|c| c.is_list(b"shap")).cloned().ok_or_else(|| tpl("mask path without a shape"))?;
|
||||
let mut list = Vec::with_capacity(shapes.len());
|
||||
for s in &shapes {
|
||||
list.push(build_shap(&proto, s)?);
|
||||
}
|
||||
*kids_mut(omks)? = list;
|
||||
let tdbs = kids.iter_mut().find(|c| c.is_list(b"tdbs")).ok_or_else(|| tpl("mask path without its property"))?;
|
||||
if !m.path_keys.is_empty() {
|
||||
let mut keyed = t.keyed_path.clone();
|
||||
// The two prototype records (093). Only the common fields are decoded; the rest of the 64
|
||||
// bytes is copied: the first key from the first record, every later key from the second
|
||||
// (093 differs there: an `f64` 1 at byte 16 of the first record, 0 in the second).
|
||||
let protos: Vec<Vec<u8>> = {
|
||||
let list = keyed.child_list(b"list").ok_or_else(|| tpl("keyed path without keys"))?;
|
||||
let ldat = list.child(b"ldat").and_then(|c| c.bytes()).ok_or_else(|| tpl("keyed path without records"))?;
|
||||
ldat.as_chunks::<64>().0.iter().map(|r| r.to_vec()).collect()
|
||||
};
|
||||
let (first_rec, later_rec) = match protos.as_slice() {
|
||||
[a, b, ..] => (a.clone(), b.clone()),
|
||||
_ => return Err(tpl("keyed path prototype without two records")),
|
||||
};
|
||||
let mut ldat = Vec::with_capacity(64 * m.path_keys.len());
|
||||
for (i, k) in m.path_keys.iter().enumerate() {
|
||||
let mut r = if i == 0 { first_rec.clone() } else { later_rec.clone() };
|
||||
let flags = u16::from_be_bytes([r.get(6).copied().unwrap_or(0), r.get(7).copied().unwrap_or(1)]) & !0x03e0;
|
||||
put_i32(&mut r, 0, k.time)?;
|
||||
put_u8(&mut r, 4, k.in_interp)?;
|
||||
put_u8(&mut r, 5, k.out_interp)?;
|
||||
put_u16(&mut r, 6, flags | (u16::from(k.label) << 6))?;
|
||||
// The ease of bezier sides at 24..55 (599, 700); linear and hold sides keep the
|
||||
// prototype's zeros.
|
||||
if k.in_interp == 2 {
|
||||
put_f64(&mut r, 24, k.in_ease.0)?;
|
||||
put_f64(&mut r, 32, k.in_ease.1)?;
|
||||
}
|
||||
if k.out_interp == 2 {
|
||||
put_f64(&mut r, 40, k.out_ease.0)?;
|
||||
put_f64(&mut r, 48, k.out_ease.1)?;
|
||||
}
|
||||
ldat.extend(r);
|
||||
}
|
||||
set_key_list(&mut keyed, ldat, m.path_keys.len(), 64)?;
|
||||
*tdbs = keyed;
|
||||
}
|
||||
// The width / height of the layer source, as for the Anchor Point (090, 093: 16 / 9 on a
|
||||
// 1920 x 1080 solid; 309: 1 on a 100 x 100 solid).
|
||||
put_f64(child_data(tdbs, b"tdb4")?, 24, aspect)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn build_shap(proto: &Chunk<'static>, s: &ShapePlan) -> R<Chunk<'static>> {
|
||||
let mut shap = proto.clone();
|
||||
{
|
||||
let shph = child_data(&mut shap, b"shph")?;
|
||||
crate::export::tree::put_bits(shph, 3, 0x08, s.open)?;
|
||||
for (i, v) in s.bbox.iter().enumerate() {
|
||||
put_f32(shph, 4 + 4 * i, *v)?;
|
||||
}
|
||||
}
|
||||
let list = list_mut(&mut shap, b"list")?;
|
||||
let records = s.points.len();
|
||||
let vertices = u32::try_from(records / 3).map_err(|_| tpl("too many vertices"))?;
|
||||
{
|
||||
// Point lists: word 2 the record count, words 3 and 7 the vertex count and four times it
|
||||
// (090: 12 records, 4 and 16; 233: 9 records, 3 and 12), word 4 the record size 8.
|
||||
let lhd3 = child_data(list, b"lhd3")?;
|
||||
crate::export::synth::put_counts(lhd3, u32::try_from(records).map_err(|_| tpl("too many points"))?, vertices, 8, vertices, vertices.saturating_mul(4))?;
|
||||
}
|
||||
let mut ldat = vec![0u8; records.saturating_mul(8)];
|
||||
for (i, [u, v]) in s.points.iter().enumerate() {
|
||||
put_f32(&mut ldat, i * 8, *u)?;
|
||||
put_f32(&mut ldat, i * 8 + 4, *v)?;
|
||||
}
|
||||
let ld = kids_mut(list)?;
|
||||
match ld.iter_mut().find(|c| c.is(b"ldat")) {
|
||||
Some(c) => *c = Chunk::data(*b"ldat", ldat),
|
||||
None => ld.push(Chunk::data(*b"ldat", ldat)),
|
||||
}
|
||||
Ok(shap)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::export::synth::is_tdmn;
|
||||
|
||||
/// A closed three-point mask.
|
||||
fn mask() -> MaskPlan {
|
||||
let shape = ShapePlan { bbox: [0.0, 0.0, 1.0, 1.0], open: false, points: vec![[0.0, 0.0]; 3] };
|
||||
MaskPlan {
|
||||
name: "M".into(),
|
||||
mode: 1,
|
||||
inverted: false,
|
||||
shape,
|
||||
path_keys: Vec::new(),
|
||||
feather: None,
|
||||
feather_keys: Vec::new(),
|
||||
opacity: None,
|
||||
expansion: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An atom without its path is an error.
|
||||
#[test]
|
||||
fn an_atom_without_its_path_is_an_error() {
|
||||
let mut t = MaskProtos::build();
|
||||
assert!(build_atom(&t, &mask(), (100, 100)).is_ok());
|
||||
// Without the Mask Shape pair the path of every mask would be dropped quietly.
|
||||
let kids = kids_mut(&mut t.atom).unwrap();
|
||||
let at = kids.iter().position(|c| is_tdmn(c, "ADBE Mask Shape")).unwrap();
|
||||
kids.drain(at..at + 2);
|
||||
assert!(build_atom(&t, &mask(), (100, 100)).is_err());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,312 @@
|
||||
//! The export report: what was written (counts) and everything that was not, per category.
|
||||
//!
|
||||
//! Plain data (`serde`), so it round-trips through JSON: the engine command returns it and agents
|
||||
//! read it. Nothing the exporter leaves out is missing from it.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Most example lines kept per loss category (the count is always exact); the same as the import
|
||||
/// report's.
|
||||
pub const MAX_DETAILS: usize = crate::import::MAX_DETAILS;
|
||||
|
||||
/// Why a piece of the project did not arrive in the `.aep`, or arrived changed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum LossCategory {
|
||||
/// Effects on layers that are not written (not in the table, a parameter
|
||||
/// without a counterpart, an expression on a parameter).
|
||||
Effects,
|
||||
/// Mask data that is not written: a disabled mask or one without a usable path, keys on Mask
|
||||
/// Opacity or Expansion, expressions on mask properties, the lock, mask motion blur other than
|
||||
/// Same As Layer, Linear feather falloff, RotoBezier and variable-width feather points.
|
||||
Masks,
|
||||
/// Layer and composition markers.
|
||||
Markers,
|
||||
/// Text layer features that are not written (animators, Source Text keys, strokes, ...), and
|
||||
/// text layers without a text document.
|
||||
TextLayers,
|
||||
/// Shape layer contents that are not written.
|
||||
ShapeLayers,
|
||||
/// Camera settings that are not written, Auto-Orient Along Path or Towards Camera included.
|
||||
Cameras,
|
||||
/// Light settings that are not written, a spot light not oriented towards its point of
|
||||
/// interest included.
|
||||
Lights,
|
||||
/// 3D model and primitive layers (skipped as a whole).
|
||||
ModelLayers,
|
||||
/// Footage items that are not written (a file type without a prototype, a layered file's
|
||||
/// layer, a sequence with gaps or at a fractional rate), and items in a folder loop.
|
||||
FootageItems,
|
||||
/// Layers whose source is not exported (footage that is not written, a precomposition that is
|
||||
/// missing or closes a loop, other).
|
||||
UnsupportedLayers,
|
||||
/// Blend modes After Effects has no code for (written as Normal).
|
||||
BlendModes,
|
||||
/// Track mattes.
|
||||
TrackMattes,
|
||||
/// 3D features that are not written (per-character 3D of a text layer, Material Options other
|
||||
/// than the defaults; the layer's 3D switch itself is written).
|
||||
ThreeD,
|
||||
/// A time stretch that is not an exact small ratio (the layer is written unstretched).
|
||||
TimeStretch,
|
||||
/// Transform properties other than Anchor Point, Position, Scale, Rotation and Opacity.
|
||||
TransformProperties,
|
||||
/// Expression on a property that is not exported.
|
||||
Expressions,
|
||||
/// Keyframes written in a simpler form (see the detail lines).
|
||||
ApproximatedKeyframes,
|
||||
/// A value that is not a finite number or beyond the range of the format (default written).
|
||||
InvalidValues,
|
||||
/// Frame rate that the format cannot hold exactly, composition size or duration out of range.
|
||||
CompositionSettings,
|
||||
/// Parent links to a layer that was not exported.
|
||||
ParentLinks,
|
||||
/// Times rounded to the composition's time base.
|
||||
RoundedTimes,
|
||||
/// Composition options that are not exported (guides, essential graphics, advanced renderer),
|
||||
/// and settings that change rendered frames but are written at After Effects' defaults:
|
||||
/// Preserve Frame Rate or Preserve Resolution switched on, motion blur samples per frame and
|
||||
/// adaptive sample limit other than 16 and 128.
|
||||
CompositionOptions,
|
||||
/// Names longer than the format's name field (the name is kept in full where verified), and
|
||||
/// item comments (not written).
|
||||
Names,
|
||||
/// Layer timing After Effects does not keep: a layer of a clip, sequence or sound that runs
|
||||
/// past the end of its source (After Effects ends it there).
|
||||
LayerTiming,
|
||||
/// Project settings that are not written: a working space other than None, sRGB and Rec.709
|
||||
/// Gamma 2.4, the OCIO
|
||||
/// colour engine, HDR handling and output space, a frame count start other than 0 and 1.
|
||||
ProjectSettings,
|
||||
/// Time remapping on a layer After Effects cannot remap (a solid, a text): not written.
|
||||
TimeRemapping,
|
||||
/// Layer-style data that is not written: a style or Layer Styles switched off, edited
|
||||
/// gradients, keys on colours, points, popups and checkboxes, Knockout.
|
||||
LayerStyles,
|
||||
/// Layer switches and options that are not written: Wireframe quality, Bicubic sampling,
|
||||
/// frame blending, Preserve Transparency, Auto-Orient on a layer other than a camera or light
|
||||
/// (theirs is reported as [`Cameras`](Self::Cameras) / [`Lights`](Self::Lights)), an
|
||||
/// environment layer, locked markers.
|
||||
LayerSwitches,
|
||||
/// Render queue items (the render queue is not written).
|
||||
RenderQueue,
|
||||
}
|
||||
|
||||
impl LossCategory {
|
||||
/// A short readable name.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
LossCategory::Effects => "effects",
|
||||
LossCategory::Masks => "masks",
|
||||
LossCategory::Markers => "markers",
|
||||
LossCategory::TextLayers => "text layers",
|
||||
LossCategory::ShapeLayers => "shape layers",
|
||||
LossCategory::Cameras => "cameras",
|
||||
LossCategory::Lights => "lights",
|
||||
LossCategory::ModelLayers => "3D model layers",
|
||||
LossCategory::FootageItems => "footage items",
|
||||
LossCategory::UnsupportedLayers => "unsupported layers",
|
||||
LossCategory::BlendModes => "blend modes",
|
||||
LossCategory::TrackMattes => "track mattes",
|
||||
LossCategory::ThreeD => "3D layers",
|
||||
LossCategory::TimeStretch => "time stretch",
|
||||
LossCategory::TransformProperties => "transform properties",
|
||||
LossCategory::Expressions => "expressions",
|
||||
LossCategory::ApproximatedKeyframes => "approximated keyframes",
|
||||
LossCategory::InvalidValues => "invalid values",
|
||||
LossCategory::CompositionSettings => "composition settings",
|
||||
LossCategory::ParentLinks => "parent links",
|
||||
LossCategory::RoundedTimes => "rounded times",
|
||||
LossCategory::CompositionOptions => "composition options",
|
||||
LossCategory::Names => "names",
|
||||
LossCategory::LayerTiming => "layer timing",
|
||||
LossCategory::ProjectSettings => "project settings",
|
||||
LossCategory::TimeRemapping => "time remapping",
|
||||
LossCategory::LayerStyles => "layer styles",
|
||||
LossCategory::LayerSwitches => "layer switches",
|
||||
LossCategory::RenderQueue => "render queue",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One category of things that were not exported: the import report's loss entry with the
|
||||
/// export categories.
|
||||
pub type Loss = crate::import::Loss<LossCategory>;
|
||||
|
||||
/// What was written to the file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Exported {
|
||||
pub folders: usize,
|
||||
pub compositions: usize,
|
||||
pub solids: usize,
|
||||
/// All layers.
|
||||
pub layers: usize,
|
||||
pub solid_layers: usize,
|
||||
pub null_layers: usize,
|
||||
pub adjustment_layers: usize,
|
||||
/// Transform properties written with a value that differs from the default.
|
||||
pub properties: usize,
|
||||
/// Keyframes written.
|
||||
pub keyframes: usize,
|
||||
/// Expressions written (source text and enable switch).
|
||||
pub expressions: usize,
|
||||
/// Layer masks written.
|
||||
#[serde(default)]
|
||||
pub masks: usize,
|
||||
/// Precomposition layers (a composition shown as a layer).
|
||||
#[serde(default)]
|
||||
pub precomp_layers: usize,
|
||||
/// Effect instances written.
|
||||
#[serde(default)]
|
||||
pub effects: usize,
|
||||
/// Footage items (files) written.
|
||||
#[serde(default)]
|
||||
pub footage: usize,
|
||||
/// Footage layers written.
|
||||
#[serde(default)]
|
||||
pub footage_layers: usize,
|
||||
/// Text layers written.
|
||||
#[serde(default)]
|
||||
pub text_layers: usize,
|
||||
/// Layer and composition markers written.
|
||||
#[serde(default)]
|
||||
pub markers: usize,
|
||||
/// Camera layers written.
|
||||
#[serde(default)]
|
||||
pub cameras: usize,
|
||||
/// Light layers written.
|
||||
#[serde(default)]
|
||||
pub lights: usize,
|
||||
/// Shape layers written.
|
||||
#[serde(default)]
|
||||
pub shape_layers: usize,
|
||||
/// Layers written with an enabled Time Remap.
|
||||
#[serde(default)]
|
||||
pub time_remaps: usize,
|
||||
/// Text animators written.
|
||||
#[serde(default)]
|
||||
pub text_animators: usize,
|
||||
/// Layer styles written (one per style on a layer).
|
||||
#[serde(default)]
|
||||
pub layer_styles: usize,
|
||||
}
|
||||
|
||||
/// Standing limitations of the exporter (what it cannot write at all), listed in every report.
|
||||
pub const LIMITATIONS: &[&str] = &[
|
||||
"The render queue (its items are reported), render templates and project settings other than colour depth, working space (None, sRGB or Rec.709 Gamma 2.4), working gamma, the two linear-light switches, time display and frame count start are not exported.",
|
||||
"Composition options other than size, frame rate, duration, work area, background, pixel aspect, shutter, motion blur switch and display start are written at After Effects' defaults: other values of preserve frame rate, preserve resolution, motion blur samples and adaptive sample limit are reported; draft 3D, hide shy, the viewer resolution, the poster time and the composition's frame blending switch (layer frame blending is reported, and no layer blends without it) are not exported. The background is stored with 8 bits per channel.",
|
||||
"Footage is linked, not embedded: png, jpeg, OpenEXR, TIFF, Targa, Photoshop, Illustrator and EPS stills, png, OpenEXR and jpeg sequences, mp4 and mov clips and WAV audio are written with their path, size, duration and frame rate (a conformed clip rate too); the rest of their interpretation (alpha, colour management, fields, loops) is the default.",
|
||||
"Layer comments, a 3D layer's X / Y rotation, orientation and material options (each reported when it is not at its default), parallel and ambient lights, and shape items outside groups, rectangles, ellipses, polystars, paths, fills, strokes, gradients, trim paths, round corners, merge and offset paths and repeaters (wiggle, twist, zig-zag, pucker and bloat, ...) are not written.",
|
||||
"Mask colours are not written: After Effects shows its own colour for every exported mask.",
|
||||
];
|
||||
|
||||
/// The result of planning/writing an `.aep`: counts of what was written, the losses per category
|
||||
/// and the standing limitations of the exporter.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExportReport {
|
||||
pub exported: Exported,
|
||||
/// Only categories that occurred, in category order.
|
||||
pub losses: Vec<Loss>,
|
||||
pub limitations: Vec<String>,
|
||||
}
|
||||
|
||||
impl ExportReport {
|
||||
/// The sum of all loss counts.
|
||||
pub fn total_losses(&self) -> usize {
|
||||
Loss::total(&self.losses)
|
||||
}
|
||||
|
||||
/// True when nothing was lost.
|
||||
pub fn is_lossless(&self) -> bool {
|
||||
self.losses.is_empty()
|
||||
}
|
||||
|
||||
/// The loss count of a category.
|
||||
pub fn count(&self, category: LossCategory) -> usize {
|
||||
Loss::count_of(&self.losses, category)
|
||||
}
|
||||
|
||||
/// `effects: 3, masks: 1` (empty when lossless).
|
||||
pub fn summary(&self) -> String {
|
||||
Loss::summary(&self.losses, LossCategory::label)
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects losses while planning.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Collector {
|
||||
pub exported: Exported,
|
||||
losses: BTreeMap<LossCategory, Loss>,
|
||||
}
|
||||
|
||||
impl Collector {
|
||||
/// Records one loss.
|
||||
pub fn lose(&mut self, category: LossCategory, detail: impl Into<String>) {
|
||||
Loss::record(&mut self.losses, category, move || detail.into());
|
||||
}
|
||||
|
||||
pub fn finish(self) -> ExportReport {
|
||||
ExportReport {
|
||||
exported: self.exported,
|
||||
losses: self.losses.into_values().collect(),
|
||||
limitations: LIMITATIONS.iter().map(|s| (*s).to_string()).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A report with losses in two categories, as the collector finishes it.
|
||||
fn collected() -> ExportReport {
|
||||
let mut col = Collector::default();
|
||||
col.exported.layers = 2;
|
||||
col.lose(LossCategory::RoundedTimes, "time 1");
|
||||
col.lose(LossCategory::Effects, String::from("fx 1"));
|
||||
col.lose(LossCategory::Effects, "fx 2");
|
||||
let mut report = col.finish();
|
||||
report.limitations.truncate(1);
|
||||
report.limitations[0] = "limit".into();
|
||||
report
|
||||
}
|
||||
|
||||
/// The JSON shape agents read: field names, category spelling, order and the loss entries.
|
||||
#[test]
|
||||
fn the_json_shape_is_pinned() {
|
||||
let json = serde_json::to_string(&collected()).unwrap();
|
||||
assert_eq!(
|
||||
json,
|
||||
r#"{"exported":{"folders":0,"compositions":0,"solids":0,"layers":2,"solidLayers":0,"nullLayers":0,"adjustmentLayers":0,"properties":0,"keyframes":0,"expressions":0,"masks":0,"precompLayers":0,"effects":0,"footage":0,"footageLayers":0,"textLayers":0,"markers":0,"cameras":0,"lights":0,"shapeLayers":0,"timeRemaps":0,"textAnimators":0,"layerStyles":0},"losses":[{"category":"effects","count":2,"details":["fx 1","fx 2"],"unlisted":0},{"category":"rounded_times","count":1,"details":["time 1"],"unlisted":0}],"limitations":["limit"]}"#
|
||||
);
|
||||
let back: ExportReport = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, collected());
|
||||
}
|
||||
|
||||
/// The queries read the losses.
|
||||
#[test]
|
||||
fn the_queries_read_the_losses() {
|
||||
let report = collected();
|
||||
assert_eq!((report.total_losses(), report.is_lossless()), (3, false));
|
||||
assert_eq!((report.count(LossCategory::Effects), report.count(LossCategory::Lights)), (2, 0));
|
||||
assert_eq!(report.summary(), "effects: 2, rounded times: 1");
|
||||
let empty = Collector::default().finish();
|
||||
assert_eq!((empty.total_losses(), empty.is_lossless(), empty.summary()), (0, true, String::new()));
|
||||
}
|
||||
|
||||
/// Details stop at the cap.
|
||||
#[test]
|
||||
fn details_stop_at_the_cap() {
|
||||
let mut col = Collector::default();
|
||||
for i in 0..MAX_DETAILS + 5 {
|
||||
col.lose(LossCategory::Masks, format!("mask {i}"));
|
||||
}
|
||||
let report = col.finish();
|
||||
assert_eq!(report.count(LossCategory::Masks), MAX_DETAILS + 5);
|
||||
assert_eq!(report.losses[0].details.len(), MAX_DETAILS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Project settings (`docs/aep-format.md` 3.12a, cases 620-634): colour depth, working space
|
||||
//! (None, sRGB or Rec.709 Gamma 2.4, with profiles authored here), working gamma, the two linear-light switches, time display and
|
||||
//! frame count start, written into the template's top-level chunks.
|
||||
|
||||
use crate::{AepFile, Chunk};
|
||||
use effectcraft_color::ColorSpace;
|
||||
use effectcraft_project::{BitDepth, ColorEngine, HdrMode, ProjectSettings, TimeDisplayStyle};
|
||||
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::tree::{R, data_mut, put_u8, tpl};
|
||||
|
||||
/// The settings in the file's terms.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct SettingsPlan {
|
||||
/// `nhed` byte 15: 0 / 1 / 2 for 8 / 16 / 32 bits per channel.
|
||||
pub depth: u8,
|
||||
/// No working space (623); otherwise sRGB unless `rec709`.
|
||||
pub no_working_space: bool,
|
||||
/// Rec.709 Gamma 2.4, written with a profile authored here (`icc.rs`, R49).
|
||||
pub rec709: bool,
|
||||
/// `dwga` byte 0: 1 for a working gamma of 2.4.
|
||||
pub gamma_24: bool,
|
||||
pub linearize: bool,
|
||||
pub blend_linear: bool,
|
||||
/// `nhed` bytes 8, 11, 13: frames, feet + frames, frames per foot.
|
||||
pub frames: bool,
|
||||
pub feet: Option<u8>,
|
||||
/// `nhed` byte 14: 2 for a count from 0, 1 for a count from 1.
|
||||
pub frame_start: u8,
|
||||
}
|
||||
|
||||
pub(crate) fn plan(s: &ProjectSettings, col: &mut Collector) -> SettingsPlan {
|
||||
let depth = match s.bit_depth {
|
||||
BitDepth::Bpc8 => 0,
|
||||
BitDepth::Bpc16 => 1,
|
||||
BitDepth::Bpc32 => 2,
|
||||
};
|
||||
let (no_working_space, rec709) = match s.working_space {
|
||||
None => (true, false),
|
||||
Some(ColorSpace::Srgb) => (false, false),
|
||||
Some(ColorSpace::Rec709) => (false, true),
|
||||
Some(other) => {
|
||||
col.lose(
|
||||
LossCategory::ProjectSettings,
|
||||
format!("the working space {other:?} is written as sRGB (only None, sRGB and Rec.709 Gamma 2.4 are written)"),
|
||||
);
|
||||
(false, false)
|
||||
}
|
||||
};
|
||||
if s.color_engine != ColorEngine::Adobe {
|
||||
col.lose(LossCategory::ProjectSettings, "the OCIO colour engine is not written".to_string());
|
||||
}
|
||||
if s.hdr != HdrMode::Clip {
|
||||
col.lose(LossCategory::ProjectSettings, "the HDR handling is not written".to_string());
|
||||
}
|
||||
// After Effects renders in the working space (902): an output space equal to the working
|
||||
// space is its normal case (the importer sets it so for Rec.709 Gamma 2.4); another one has
|
||||
// no place in the file.
|
||||
if s.output_space.is_some_and(|o| Some(o) != s.working_space) {
|
||||
col.lose(LossCategory::ProjectSettings, "an output space other than the working space is not written".to_string());
|
||||
}
|
||||
let (frames, feet) = match s.time_display {
|
||||
TimeDisplayStyle::Timecode => (false, None),
|
||||
TimeDisplayStyle::Frames => (true, None),
|
||||
TimeDisplayStyle::Feet35 => (true, Some(16)),
|
||||
TimeDisplayStyle::Feet16 => (true, Some(40)),
|
||||
};
|
||||
let frame_start = match s.frame_start {
|
||||
0 => 2,
|
||||
1 => 1,
|
||||
other => {
|
||||
col.lose(LossCategory::ProjectSettings, format!("a frame count start of {other} is written as 0 (only 0 and 1 exist)"));
|
||||
2
|
||||
}
|
||||
};
|
||||
SettingsPlan {
|
||||
depth,
|
||||
no_working_space,
|
||||
rec709,
|
||||
gamma_24: s.working_gamma_24(),
|
||||
linearize: s.linearize,
|
||||
blend_linear: s.blend_linear,
|
||||
frames,
|
||||
feet,
|
||||
frame_start,
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `p` into the template's top-level chunks.
|
||||
pub(crate) fn emit(file: &mut AepFile<'static>, p: &SettingsPlan) -> R<()> {
|
||||
let top = &mut file.chunks;
|
||||
let header =
|
||||
|top: &mut Vec<Chunk<'static>>, id: &[u8; 4]| -> R<usize> { top.iter().position(|c| c.is(id)).ok_or_else(|| tpl("template header chunk missing")) };
|
||||
// nhed and its copy nnhd (byte offsets per field: 620-634).
|
||||
for (id, at_depth, at_display, at_feet, at_fpf, at_start) in [(b"nhed", 15, 8, 11, 13, 14), (b"nnhd", 24, 8, 11, 19, 20)] {
|
||||
let i = header(top, id)?;
|
||||
let d = data_mut(top.get_mut(i).ok_or_else(|| tpl("header"))?)?;
|
||||
put_u8(d, at_depth, p.depth)?;
|
||||
put_u8(d, at_display, u8::from(p.frames))?;
|
||||
put_u8(d, at_feet, u8::from(p.feet.is_some()))?;
|
||||
put_u8(d, at_fpf, p.feet.unwrap_or(16))?;
|
||||
put_u8(d, at_start, p.frame_start)?;
|
||||
}
|
||||
{
|
||||
let i = header(top, b"dwga")?;
|
||||
put_u8(data_mut(top.get_mut(i).ok_or_else(|| tpl("dwga"))?)?, 0, u8::from(p.gamma_24))?;
|
||||
}
|
||||
// Blend Colors Using 1.0 Gamma (lnrb) and Linearize Working Space (lnrp): one-byte chunks
|
||||
// right after cpid, in that order (626, 627, 632).
|
||||
top.retain(|c| !c.is(b"lnrb") && !c.is(b"lnrp"));
|
||||
let cpid = header(top, b"cpid")?;
|
||||
let mut at = cpid.saturating_add(1);
|
||||
if p.blend_linear {
|
||||
top.insert(at, Chunk::data(*b"lnrb", vec![1u8]));
|
||||
at = at.saturating_add(1);
|
||||
}
|
||||
if p.linearize {
|
||||
top.insert(at, Chunk::data(*b"lnrp", vec![1u8]));
|
||||
}
|
||||
if !p.no_working_space {
|
||||
// 620, 624: `cpid` is the profile ID, the JSON after PwCs holds the profile's data and the
|
||||
// working space's name; the profiles are our own (R49).
|
||||
let (icc, name) = if p.rec709 {
|
||||
(crate::export::icc::rec709_gamma24(), crate::export::icc::REC709_NAME)
|
||||
} else {
|
||||
(crate::export::icc::srgb(), crate::export::icc::SRGB_NAME)
|
||||
};
|
||||
*top.get_mut(cpid).ok_or_else(|| tpl("cpid"))? = Chunk::data(*b"cpid", crate::export::icc::profile_id(&icc).to_vec());
|
||||
let pw = header(top, b"PwCs")?;
|
||||
let json = top.get_mut(pw.saturating_add(1)).filter(|c| c.is(b"Utf8")).ok_or_else(|| tpl("template without the working-space JSON"))?;
|
||||
let text = crate::export::icc::profile_json(&icc, name);
|
||||
*json = Chunk::data(*b"Utf8", text.into_bytes());
|
||||
}
|
||||
if p.no_working_space {
|
||||
// 623: cpid all 0xff, the working-space JSON after PwCs is `{}`.
|
||||
*top.get_mut(cpid).ok_or_else(|| tpl("cpid"))? = Chunk::data(*b"cpid", vec![0xffu8; 16]);
|
||||
let pw = header(top, b"PwCs")?;
|
||||
let json = top.get_mut(pw.saturating_add(1)).filter(|c| c.is(b"Utf8")).ok_or_else(|| tpl("template without the working-space JSON"))?;
|
||||
*json = Chunk::data(*b"Utf8", b"{}".to_vec());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,766 @@
|
||||
//! Shape layers (`docs/aep-format.md` 3.9; cases 238-242, 451-471, 519, 707-710, 731, 851-857):
|
||||
//! groups (nested), rectangle, ellipse, polystar and freeform paths, fills, strokes, gradient
|
||||
//! fills and strokes, trim paths, round corners, merge paths, offset paths and repeaters, the
|
||||
//! group transform, with keys and expressions on their properties.
|
||||
//!
|
||||
//! The layer block is the shape layer of 519 with its contents removed; every item is the item
|
||||
//! of 519 or 731 (all at After Effects' defaults, no value records) or the path item of 240, and
|
||||
//! every property that differs from After Effects' default (or carries keys or an expression)
|
||||
//! gets a value record, in After Effects' order (a record only for a non-default value, P.5):
|
||||
//! sizes and positions in pixels relative to the layer, colours `[A, R, G, B]` 0..255,
|
||||
//! opacities, percentages and the group scale in percent, popups 1-based (fill rule 455, line
|
||||
//! cap / join 239, trim type 469, polystar type 331, merge type 707, offset line join 710),
|
||||
//! angles in degrees. A record is the record After Effects wrote for the property in a
|
||||
//! one-change case, else the record of its property's type (R46): over the corpus every shape
|
||||
//! value record of a type has the same bytes but for its match name, the time scale and, for
|
||||
//! sliders, the slider range in `tdum` / `tduM` (0..100 for every slider but Skew -85..85 and
|
||||
//! Highlight Length -100..100; sizes and scales -32 000..32 000). A keyed record clears `tdb4`
|
||||
//! bit 0 of byte 5, sets byte 68 and holds the key list (851-855, 857, 209): one-component and
|
||||
//! two-component sizes plain records (48 / 88 bytes), points spatial records (104 bytes),
|
||||
//! colours the colour records of effects (152 bytes). An expression is stored as on the
|
||||
//! Transform properties (856, R15).
|
||||
|
||||
use crate::Chunk;
|
||||
use effectcraft_keyframe::{Gradient, Interp, Keyframe, Value};
|
||||
use effectcraft_project::{Node, PropGroup, Property};
|
||||
|
||||
use crate::export::keys::{fill_key_list, replace_cdat, spatial_record, timed_keys};
|
||||
use crate::export::masks::ShapePlan;
|
||||
use crate::export::plan::{CompPlan, EaseSlot, KeyPlan};
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::synth::{GROUP_END, is_tdmn, tdmn};
|
||||
use crate::export::tree::{R, child_data, kids_mut, list_mut, put_f64, put_u8, set_utf8, tpl};
|
||||
|
||||
/// The deepest group nesting written.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// A property's value in the file's units: the static value, the keys (layer time) and the
|
||||
/// expression with its enable switch.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct RecVal {
|
||||
pub value: Vec<f64>,
|
||||
pub keys: Vec<KeyPlan>,
|
||||
pub expr: Option<(String, bool)>,
|
||||
}
|
||||
|
||||
type Records = Vec<(&'static str, RecVal)>;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum ShItem {
|
||||
Group {
|
||||
name: String,
|
||||
items: Vec<ShItem>,
|
||||
transform: Records,
|
||||
},
|
||||
/// Any other item but a path: the item's match name, name, value records and the records of
|
||||
/// its sub-groups (a repeater's transform).
|
||||
Simple {
|
||||
kind: &'static str,
|
||||
name: String,
|
||||
records: Records,
|
||||
subs: Vec<(&'static str, Records)>,
|
||||
},
|
||||
Path {
|
||||
name: String,
|
||||
shape: ShapePlan,
|
||||
},
|
||||
/// An item switched off (its eye): written with bit 0 of its group's `tdsb` cleared.
|
||||
Off(Box<ShItem>),
|
||||
}
|
||||
|
||||
/// The prototypes, by match name.
|
||||
pub(crate) struct ShapeProtos {
|
||||
/// The shape layer's block (519) with an empty `ADBE Root Vectors Group`.
|
||||
pub block: Vec<Chunk<'static>>,
|
||||
/// Item nodes (`tdmn` + node) at their defaults.
|
||||
pub items: Vec<(String, [Chunk<'static>; 2])>,
|
||||
/// Value records (`tdmn` + `tdbs`) by match name.
|
||||
pub records: Vec<(String, [Chunk<'static>; 2])>,
|
||||
/// The key list (`LIST list`) of a keyed property, whose header is rewritten.
|
||||
pub key_list: Chunk<'static>,
|
||||
}
|
||||
|
||||
/// How a shape property is stored.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Layout {
|
||||
/// One component (sliders, angles, popups): plain keys of 48 bytes.
|
||||
One,
|
||||
/// A size or scale of two or three components: plain keys of 88 / 128 bytes.
|
||||
Size,
|
||||
/// A point: spatial keys of 104 bytes (853; 128 bytes for a 3D point).
|
||||
Point,
|
||||
/// A colour: the 152-byte colour keys (854).
|
||||
Color,
|
||||
/// A popup (keys not sampled).
|
||||
Popup,
|
||||
}
|
||||
|
||||
/// The record whose layout a property takes, the slider range its record repeats in `tdum` /
|
||||
/// `tduM` (R46), and the key layout.
|
||||
#[derive(Clone, Copy)]
|
||||
struct RecKind {
|
||||
proto: &'static str,
|
||||
range: Option<(f64, f64)>,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
const SLIDER: RecKind = RecKind { proto: "ADBE Vector Fill Opacity", range: Some((0.0, 100.0)), layout: Layout::One };
|
||||
const ANGLE: RecKind = RecKind { proto: "ADBE Vector Rotation", range: None, layout: Layout::One };
|
||||
const POPUP: RecKind = RecKind { proto: "ADBE Vector Fill Rule", range: None, layout: Layout::Popup };
|
||||
const POINT: RecKind = RecKind { proto: "ADBE Vector Ellipse Position", range: None, layout: Layout::Point };
|
||||
const SIZE: RecKind = RecKind { proto: "ADBE Vector Scale", range: Some((-32_000.0, 32_000.0)), layout: Layout::Size };
|
||||
const COLOR: RecKind = RecKind { proto: "ADBE Vector Fill Color", range: None, layout: Layout::Color };
|
||||
|
||||
/// Every property the exporter writes, in After Effects' order within an item (455, 464, 239,
|
||||
/// 331, 332, 828, 709), with its record type (sampled: 451-471, 238-242, 331, 332, 468, 469,
|
||||
/// 473-477, 707-710, 828; Offset Paths' Miter Limit, the Repeater's Offset, Composite, Anchor and
|
||||
/// Start Opacity are not sampled and take the type of their kind, E).
|
||||
const KINDS: &[(&str, RecKind)] = &[
|
||||
("ADBE Vector Rect Size", SIZE),
|
||||
("ADBE Vector Rect Position", POINT),
|
||||
("ADBE Vector Rect Roundness", SLIDER),
|
||||
("ADBE Vector Ellipse Size", SIZE),
|
||||
("ADBE Vector Ellipse Position", POINT),
|
||||
("ADBE Vector Star Type", POPUP),
|
||||
("ADBE Vector Star Points", SLIDER),
|
||||
("ADBE Vector Star Position", POINT),
|
||||
("ADBE Vector Star Rotation", ANGLE),
|
||||
("ADBE Vector Star Inner Radius", SLIDER),
|
||||
("ADBE Vector Star Outer Radius", SLIDER),
|
||||
("ADBE Vector Star Inner Roundess", SLIDER),
|
||||
("ADBE Vector Star Outer Roundess", SLIDER),
|
||||
("ADBE Vector Fill Rule", POPUP),
|
||||
("ADBE Vector Grad Type", POPUP),
|
||||
("ADBE Vector Grad Start Pt", POINT),
|
||||
("ADBE Vector Grad End Pt", POINT),
|
||||
("ADBE Vector Grad HiLite Length", RecKind { proto: "ADBE Vector Fill Opacity", range: Some((-100.0, 100.0)), layout: Layout::One }),
|
||||
("ADBE Vector Grad HiLite Angle", ANGLE),
|
||||
("ADBE Vector Fill Color", COLOR),
|
||||
("ADBE Vector Fill Opacity", SLIDER),
|
||||
("ADBE Vector Stroke Color", COLOR),
|
||||
("ADBE Vector Stroke Opacity", SLIDER),
|
||||
("ADBE Vector Stroke Width", SLIDER),
|
||||
("ADBE Vector Stroke Line Cap", POPUP),
|
||||
("ADBE Vector Stroke Line Join", POPUP),
|
||||
("ADBE Vector Stroke Miter Limit", SLIDER),
|
||||
("ADBE Vector Trim Start", SLIDER),
|
||||
("ADBE Vector Trim End", SLIDER),
|
||||
("ADBE Vector Trim Offset", ANGLE),
|
||||
("ADBE Vector Trim Type", POPUP),
|
||||
("ADBE Vector RoundCorner Radius", SLIDER),
|
||||
("ADBE Vector Merge Type", POPUP),
|
||||
("ADBE Vector Offset Amount", SLIDER),
|
||||
("ADBE Vector Offset Line Join", POPUP),
|
||||
("ADBE Vector Offset Miter Limit", SLIDER),
|
||||
("ADBE Vector Offset Copies", SLIDER),
|
||||
("ADBE Vector Offset Copy Offset", SLIDER),
|
||||
("ADBE Vector Repeater Copies", SLIDER),
|
||||
("ADBE Vector Repeater Offset", SLIDER),
|
||||
("ADBE Vector Repeater Order", POPUP),
|
||||
("ADBE Vector Repeater Anchor", POINT),
|
||||
("ADBE Vector Repeater Position", POINT),
|
||||
("ADBE Vector Repeater Scale", SIZE),
|
||||
("ADBE Vector Repeater Rotation", ANGLE),
|
||||
("ADBE Vector Repeater Opacity 1", SLIDER),
|
||||
("ADBE Vector Repeater Opacity 2", SLIDER),
|
||||
("ADBE Vector Anchor", POINT),
|
||||
("ADBE Vector Position", POINT),
|
||||
("ADBE Vector Scale", SIZE),
|
||||
// Skew has its own record (460: a slider of the angle layout, -85..85).
|
||||
("ADBE Vector Skew", RecKind { proto: "ADBE Vector Skew", range: Some((-85.0, 85.0)), layout: Layout::One }),
|
||||
("ADBE Vector Skew Axis", ANGLE),
|
||||
("ADBE Vector Rotation", ANGLE),
|
||||
("ADBE Vector Group Opacity", SLIDER),
|
||||
];
|
||||
|
||||
fn kind_of(name: &str) -> Option<RecKind> {
|
||||
KINDS.iter().find(|(n, _)| *n == name).map(|(_, k)| *k)
|
||||
}
|
||||
|
||||
impl ShapeProtos {
|
||||
fn item(&self, name: &str) -> R<[Chunk<'static>; 2]> {
|
||||
self.items.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()).ok_or_else(|| tpl("shape item prototype missing"))
|
||||
}
|
||||
|
||||
/// The static value record of `name`: the one After Effects wrote for it in a one-change
|
||||
/// case, else the record of its type (R46).
|
||||
fn record(&self, name: &'static str) -> R<[Chunk<'static>; 2]> {
|
||||
if let Some((_, c)) = self.records.iter().find(|(n, _)| n == name) {
|
||||
return Ok(c.clone());
|
||||
}
|
||||
let kind = kind_of(name).ok_or_else(|| tpl("shape property without a record type"))?;
|
||||
let [_, mut node] = self.records.iter().find(|(n, _)| n == kind.proto).map(|(_, c)| c.clone()).ok_or_else(|| tpl("shape record prototype missing"))?;
|
||||
if let Some((lo, hi)) = kind.range {
|
||||
put_f64(child_data(&mut node, b"tdum")?, 0, lo)?;
|
||||
put_f64(child_data(&mut node, b"tduM")?, 0, hi)?;
|
||||
}
|
||||
Ok([tdmn(name), node])
|
||||
}
|
||||
}
|
||||
|
||||
fn finite(v: &[f64]) -> bool {
|
||||
v.iter().all(|x| x.is_finite() && x.abs() <= 1e9)
|
||||
}
|
||||
|
||||
/// The stored components of a value.
|
||||
pub(crate) type Conv = fn(&Value) -> Option<Vec<f64>>;
|
||||
|
||||
pub(crate) fn c_scalar(v: &Value) -> Option<Vec<f64>> {
|
||||
match v {
|
||||
Value::Scalar(s) => Some(vec![*s]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Offset Paths' Copy Offset: EffectCraft's value + 1 (826-828).
|
||||
fn c_copy_offset(v: &Value) -> Option<Vec<f64>> {
|
||||
match v {
|
||||
Value::Scalar(s) => Some(vec![*s + 1.0]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn c_point(v: &Value) -> Option<Vec<f64>> {
|
||||
match v {
|
||||
Value::Vec2(p) => Some(p.to_vec()),
|
||||
Value::Vec3(p) => Some(vec![p[0], p[1]]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A colour as the file stores it (alpha 255, then red, green and blue from 0 to 255). A channel
|
||||
/// outside 0 to 1 is written as the nearest limit, as for lights (`rec_value` reports it); a
|
||||
/// value that is not finite stays so and is reported as invalid.
|
||||
pub(crate) fn c_color(v: &Value) -> Option<Vec<f64>> {
|
||||
let ch = |x: f64| if x.is_finite() { x.clamp(0.0, 1.0) * 255.0 } else { x };
|
||||
match v {
|
||||
Value::Color(c) => Some(vec![255.0, ch(c[0]), ch(c[1]), ch(c[2])]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a colour that is written has a channel outside 0 to 1: the keys of an animated
|
||||
/// property (its static value is not written then), else the static value.
|
||||
fn colour_beyond(p: &Property, keyed: bool) -> bool {
|
||||
let beyond = |v: &Value| matches!(v, Value::Color(c) if c.iter().take(3).any(|x| x.is_finite() && !(0.0..=1.0).contains(x)));
|
||||
if keyed { p.keys.iter().any(|k| beyond(&k.value)) } else { beyond(&p.value) }
|
||||
}
|
||||
|
||||
/// Whether a colour that is written has an alpha other than 1 (a colour property of After Effects
|
||||
/// has no alpha): the keys of an animated property, else the static value.
|
||||
fn colour_alpha(p: &Property, keyed: bool) -> bool {
|
||||
let alpha = |v: &Value| matches!(v, Value::Color(c) if c[3].is_finite() && (c[3] - 1.0).abs() > 1e-9);
|
||||
if keyed { p.keys.iter().any(|k| alpha(&k.value)) } else { alpha(&p.value) }
|
||||
}
|
||||
|
||||
/// A popup stored 1-based (EffectCraft's items in After Effects' order).
|
||||
pub(crate) fn c_popup(v: &Value) -> Option<Vec<f64>> {
|
||||
match v {
|
||||
Value::Enum(e) => Some(vec![f64::from(*e) + 1.0]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What planning a shape layer needs: the layer's time base and the report.
|
||||
pub(crate) struct ShCx<'a> {
|
||||
pub cp: &'a CompPlan,
|
||||
pub col: &'a mut Collector,
|
||||
}
|
||||
|
||||
/// The keys of `p` in the file's units.
|
||||
fn plan_keys(p: &Property, conv: Conv, layout: Layout, what: &str, cx: &mut ShCx<'_>) -> Vec<KeyPlan> {
|
||||
let timed = timed_keys(&p.keys, &cx.cp.tb, what, "key", cx.col);
|
||||
let all: Vec<Keyframe> = timed.iter().map(|(_, k)| (*k).clone()).collect();
|
||||
let mut out = Vec::with_capacity(timed.len());
|
||||
let beyond = std::cell::Cell::new(false);
|
||||
for (i, (u, k)) in timed.iter().enumerate() {
|
||||
let Ok(time) = i32::try_from(*u) else {
|
||||
cx.col.lose(LossCategory::InvalidValues, format!("{what}: key time out of range, key dropped"));
|
||||
continue;
|
||||
};
|
||||
let Some(value) = conv(&k.value).filter(|v| finite(v)) else {
|
||||
cx.col.lose(LossCategory::InvalidValues, format!("{what}: a key value that cannot be stored, key dropped"));
|
||||
continue;
|
||||
};
|
||||
let mut side = |interp: Interp| -> u8 {
|
||||
match interp {
|
||||
Interp::Linear => 1,
|
||||
Interp::Hold => 3,
|
||||
// The ease of colour keys is sampled only as speed 0 / influence 0 (598).
|
||||
Interp::Bezier if layout == Layout::Color => {
|
||||
cx.col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: bezier ease of a colour key is written as linear (not sampled)"));
|
||||
1
|
||||
}
|
||||
Interp::Bezier => 2,
|
||||
}
|
||||
};
|
||||
let (in_i, out_i) = (side(k.in_interp), side(k.out_interp));
|
||||
let slots = if layout == Layout::Size { value.len().max(1) } else { 1 };
|
||||
let ease = |eases: &[effectcraft_keyframe::Ease], on: bool| -> Vec<EaseSlot> {
|
||||
(0..slots)
|
||||
.map(|s| {
|
||||
if !on {
|
||||
return EaseSlot::default();
|
||||
}
|
||||
let e = crate::export::plan::key_ease(eases, s);
|
||||
let speed = if e.speed.is_finite() && e.speed.abs() <= 1e9 {
|
||||
e.speed
|
||||
} else {
|
||||
beyond.set(true);
|
||||
0.0
|
||||
};
|
||||
let influence = if e.influence.is_finite() { e.influence.clamp(0.001, 1.0) } else { 1.0 / 3.0 };
|
||||
EaseSlot { speed, influence }
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let (mut tin, mut tout) = if layout == Layout::Point { effectcraft_keyframe::spatial_tangents(&all, i) } else { ([0.0; 3], [0.0; 3]) };
|
||||
for t in tin.iter_mut().chain(tout.iter_mut()) {
|
||||
if !t.is_finite() || t.abs() > 1e9 {
|
||||
beyond.set(true);
|
||||
*t = 0.0;
|
||||
}
|
||||
}
|
||||
if k.roving {
|
||||
cx.col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a roving key is written as a normal key"));
|
||||
}
|
||||
out.push(KeyPlan {
|
||||
time,
|
||||
value,
|
||||
in_interp: in_i,
|
||||
out_interp: out_i,
|
||||
in_ease: ease(&k.in_ease, in_i == 2),
|
||||
out_ease: ease(&k.out_ease, out_i == 2),
|
||||
spatial_in: tin,
|
||||
spatial_out: tout,
|
||||
spatial_auto: k.spatial_auto,
|
||||
roving: false,
|
||||
label: k.label.min(16),
|
||||
});
|
||||
}
|
||||
cx.col.exported.keyframes = cx.col.exported.keyframes.saturating_add(out.len());
|
||||
crate::export::plan::report_beyond(beyond.get(), what, cx.col);
|
||||
out
|
||||
}
|
||||
|
||||
/// A property's value, keys and expression in the file's units; `None` when it needs no record:
|
||||
/// at `default` (when given) with no keys and no expression. Keys on a popup are not sampled:
|
||||
/// the first key's value is written (reported in `category`).
|
||||
pub(crate) fn rec_value(
|
||||
p: &Property,
|
||||
conv: Conv,
|
||||
layout: Layout,
|
||||
default: Option<&[f64]>,
|
||||
w: &str,
|
||||
category: LossCategory,
|
||||
cx: &mut ShCx<'_>,
|
||||
) -> Option<RecVal> {
|
||||
let expr = p.expr.as_ref().filter(|e| !e.text.is_empty()).map(|e| (e.text.clone(), e.enabled));
|
||||
if expr.is_some() {
|
||||
cx.col.exported.expressions = cx.col.exported.expressions.saturating_add(1);
|
||||
}
|
||||
let Some(value) = conv(&p.value) else {
|
||||
cx.col.lose(category, format!("{w} holds a value of another type, not written"));
|
||||
return None;
|
||||
};
|
||||
if !finite(&value) {
|
||||
cx.col.lose(LossCategory::InvalidValues, format!("{w} is not a valid number (the default is written)"));
|
||||
return None;
|
||||
}
|
||||
let differs = |v: &[f64]| default.is_none_or(|d| v.iter().zip(d).any(|(a, b)| (a - b).abs() > 1e-9));
|
||||
let mut keys = Vec::new();
|
||||
if !p.keys.is_empty() {
|
||||
if layout == Layout::Popup {
|
||||
cx.col.lose(category, format!("{w}: keys on a popup are not written (not sampled), the first key's value is written"));
|
||||
let first = p.keys.first().and_then(|k| conv(&k.value)).unwrap_or(value);
|
||||
return (differs(&first) || expr.is_some()).then_some(RecVal { value: first, keys: Vec::new(), expr });
|
||||
}
|
||||
keys = plan_keys(p, conv, layout, w, cx);
|
||||
}
|
||||
// Shape and text animator colours alike (both are planned here).
|
||||
if layout == Layout::Color && colour_beyond(p, !keys.is_empty()) {
|
||||
cx.col.lose(category, format!("{w}: a colour channel outside 0 to 1 is written as the nearest limit"));
|
||||
}
|
||||
if layout == Layout::Color && colour_alpha(p, !keys.is_empty()) {
|
||||
cx.col.lose(category, format!("{w}: the colour's alpha is not written (After Effects colours have none; written opaque)"));
|
||||
}
|
||||
if keys.is_empty() && expr.is_none() && !differs(&value) {
|
||||
return None;
|
||||
}
|
||||
let value = keys.first().map(|k| k.value.clone()).unwrap_or(value);
|
||||
Some(RecVal { value, keys, expr })
|
||||
}
|
||||
|
||||
/// Plans property `id` of `g` as the record `name` (`names`: `(name, id)`) unless it is at After
|
||||
/// Effects' default with no keys and no expression.
|
||||
fn rec(out: &mut Records, g: &PropGroup, names: (&'static str, &str), conv: Conv, default: &[f64], what: &str, cx: &mut ShCx<'_>) {
|
||||
let (name, id) = names;
|
||||
let Some(p) = g.get(id) else { return };
|
||||
let Some(kind) = kind_of(name) else { return };
|
||||
let w = format!("{what}: {name}");
|
||||
if let Some(v) = rec_value(p, conv, kind.layout, Some(default), &w, LossCategory::ShapeLayers, cx) {
|
||||
out.push((name, v));
|
||||
}
|
||||
}
|
||||
|
||||
fn en(g: &PropGroup, id: &str) -> Option<u32> {
|
||||
match g.get(id).map(|p| &p.value) {
|
||||
Some(Value::Enum(e)) => Some(*e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opacity, width, cap, join and miter limit of a stroke or gradient stroke; dashes, taper and
|
||||
/// wave are reported when they hold values.
|
||||
fn stroke_common(r: &mut Records, g: &PropGroup, w: &str, cx: &mut ShCx<'_>) {
|
||||
rec(r, g, ("ADBE Vector Stroke Opacity", "opacity"), c_scalar, &[100.0], w, cx);
|
||||
rec(r, g, ("ADBE Vector Stroke Width", "width"), c_scalar, &[2.0], w, cx);
|
||||
rec(r, g, ("ADBE Vector Stroke Line Cap", "cap"), c_popup, &[1.0], w, cx);
|
||||
rec(r, g, ("ADBE Vector Stroke Line Join", "join"), c_popup, &[1.0], w, cx);
|
||||
rec(r, g, ("ADBE Vector Stroke Miter Limit", "miter"), c_scalar, &[4.0], w, cx);
|
||||
// Dashes, a taper or a wave change the stroke (After Effects' defaults: no dash, no taper
|
||||
// length, no wave amount).
|
||||
let nonzero = |sub: &str, ids: &[&str]| {
|
||||
g.sub(sub).is_some_and(|s| s.props().any(|p| ids.iter().any(|i| p.match_id.starts_with(i)) && matches!(p.value, Value::Scalar(v) if v != 0.0)))
|
||||
};
|
||||
if nonzero("dashes", &["dash", "gap"]) || nonzero("taper", &["startLength", "endLength"]) || nonzero("wave", &["amount"]) {
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: dashes, taper and wave of a stroke are not written"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient part of a gradient fill or stroke: type, start, end, highlight; the colour
|
||||
/// stops are not decoded (only the default white to black is written).
|
||||
fn gradient(r: &mut Records, g: &PropGroup, w: &str, cx: &mut ShCx<'_>) {
|
||||
rec(r, g, ("ADBE Vector Grad Type", "type"), c_popup, &[1.0], w, cx);
|
||||
rec(r, g, ("ADBE Vector Grad Start Pt", "start"), c_point, &[0.0, 0.0], w, cx);
|
||||
rec(r, g, ("ADBE Vector Grad End Pt", "end"), c_point, &[100.0, 0.0], w, cx);
|
||||
rec(r, g, ("ADBE Vector Grad HiLite Length", "highlightLength"), c_scalar, &[0.0], w, cx);
|
||||
rec(r, g, ("ADBE Vector Grad HiLite Angle", "highlightAngle"), c_scalar, &[0.0], w, cx);
|
||||
if let Some(p) = g.get("colors")
|
||||
&& (matches!(&p.value, Value::Gradient(gr) if *gr != Gradient::default()) || !p.keys.is_empty() || p.has_expression())
|
||||
{
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: the colour stops of a gradient are not written (not decoded), white to black"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The items of a `contents` group, top first, in the file's terms.
|
||||
pub(crate) fn plan_contents(contents: &PropGroup, what: &str, depth: usize, cx: &mut ShCx<'_>) -> Vec<ShItem> {
|
||||
let mut out = Vec::new();
|
||||
if depth > MAX_DEPTH {
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{what}: shape groups nested deeper than {MAX_DEPTH} levels are not written"));
|
||||
return out;
|
||||
}
|
||||
for node in &contents.children {
|
||||
let Node::Group(g) = node else { continue };
|
||||
let w = format!("{what} / {}", g.name);
|
||||
// A switched-off item keeps its node with bit 0 of its group flags cleared (986, 987).
|
||||
let wrap = |item: ShItem| if g.enabled { item } else { ShItem::Off(Box::new(item)) };
|
||||
if en(g, "direction").is_some_and(|d| d != 0) {
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: the path direction is not written"));
|
||||
}
|
||||
// A repeater writes its `composite` as Repeater Order.
|
||||
let composite_lost = g.match_id != "repeater" && en(g, "composite").is_some_and(|d| d != 0);
|
||||
if en(g, "blend").is_some_and(|d| d != 0) || composite_lost {
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: blend mode and composite order are not written"));
|
||||
}
|
||||
let mut r = Vec::new();
|
||||
let mut subs = Vec::new();
|
||||
let kind = match g.match_id.as_str() {
|
||||
"group" => {
|
||||
let items = g.sub("contents").map(|c| plan_contents(c, &w, depth + 1, cx)).unwrap_or_default();
|
||||
let mut transform = Vec::new();
|
||||
if let Some(t) = g.sub("transform") {
|
||||
rec(&mut transform, t, ("ADBE Vector Anchor", "anchor"), c_point, &[0.0, 0.0], &w, cx);
|
||||
rec(&mut transform, t, ("ADBE Vector Position", "position"), c_point, &[0.0, 0.0], &w, cx);
|
||||
rec(&mut transform, t, ("ADBE Vector Scale", "scale"), c_point, &[100.0, 100.0], &w, cx);
|
||||
rec(&mut transform, t, ("ADBE Vector Skew", "skew"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut transform, t, ("ADBE Vector Skew Axis", "skewAxis"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut transform, t, ("ADBE Vector Rotation", "rotation"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut transform, t, ("ADBE Vector Group Opacity", "opacity"), c_scalar, &[100.0], &w, cx);
|
||||
}
|
||||
out.push(wrap(ShItem::Group { name: g.name.clone(), items, transform }));
|
||||
continue;
|
||||
}
|
||||
"path" => {
|
||||
let p = g.get("path");
|
||||
if p.is_some_and(|p| !p.keys.is_empty() || p.has_expression()) {
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: keys or an expression on the path (the static path is written)"));
|
||||
}
|
||||
match p.map(|p| &p.value) {
|
||||
Some(Value::Path(sp)) => match crate::export::masks::shape_plan(sp, (1, 1)) {
|
||||
Ok(shape) => out.push(wrap(ShItem::Path { name: g.name.clone(), shape })),
|
||||
Err(why) => cx.col.lose(LossCategory::ShapeLayers, format!("{w}: the path is not written: {why}")),
|
||||
},
|
||||
_ => cx.col.lose(LossCategory::ShapeLayers, format!("{w}: a path item without a path is not written")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
"rect" => {
|
||||
rec(&mut r, g, ("ADBE Vector Rect Size", "size"), c_point, &[100.0, 100.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Rect Position", "position"), c_point, &[0.0, 0.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Rect Roundness", "roundness"), c_scalar, &[0.0], &w, cx);
|
||||
if g.get("perCorner").is_some_and(|p| p.value == Value::Bool(true) || !p.keys.is_empty() || p.has_expression()) {
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: per-corner roundness is not written (the uniform Roundness is)"));
|
||||
}
|
||||
"ADBE Vector Shape - Rect"
|
||||
}
|
||||
"ellipse" => {
|
||||
rec(&mut r, g, ("ADBE Vector Ellipse Size", "size"), c_point, &[100.0, 100.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Ellipse Position", "position"), c_point, &[0.0, 0.0], &w, cx);
|
||||
"ADBE Vector Shape - Ellipse"
|
||||
}
|
||||
// Polystar (104, 331, 473-477): After Effects' defaults are a 5-point star with radii
|
||||
// 100 / 50 (519).
|
||||
"star" => {
|
||||
rec(&mut r, g, ("ADBE Vector Star Type", "type"), c_popup, &[1.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Star Points", "points"), c_scalar, &[5.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Star Position", "position"), c_point, &[0.0, 0.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Star Rotation", "rotation"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Star Inner Radius", "innerRadius"), c_scalar, &[50.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Star Outer Radius", "outerRadius"), c_scalar, &[100.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Star Inner Roundess", "innerRoundness"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Star Outer Roundess", "outerRoundness"), c_scalar, &[0.0], &w, cx);
|
||||
"ADBE Vector Shape - Star"
|
||||
}
|
||||
"fill" => {
|
||||
rec(&mut r, g, ("ADBE Vector Fill Rule", "rule"), c_popup, &[1.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Fill Color", "color"), c_color, &[255.0, 255.0, 0.0, 0.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Fill Opacity", "opacity"), c_scalar, &[100.0], &w, cx);
|
||||
"ADBE Vector Graphic - Fill"
|
||||
}
|
||||
"stroke" => {
|
||||
rec(&mut r, g, ("ADBE Vector Stroke Color", "color"), c_color, &[255.0, 255.0, 255.0, 255.0], &w, cx);
|
||||
stroke_common(&mut r, g, &w, cx);
|
||||
"ADBE Vector Graphic - Stroke"
|
||||
}
|
||||
"gfill" => {
|
||||
rec(&mut r, g, ("ADBE Vector Fill Rule", "rule"), c_popup, &[1.0], &w, cx);
|
||||
gradient(&mut r, g, &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Fill Opacity", "opacity"), c_scalar, &[100.0], &w, cx);
|
||||
"ADBE Vector Graphic - G-Fill"
|
||||
}
|
||||
"gstroke" => {
|
||||
gradient(&mut r, g, &w, cx);
|
||||
stroke_common(&mut r, g, &w, cx);
|
||||
"ADBE Vector Graphic - G-Stroke"
|
||||
}
|
||||
// Trim Paths (101, 465-469, 851-856).
|
||||
"trim" => {
|
||||
rec(&mut r, g, ("ADBE Vector Trim Start", "start"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Trim End", "end"), c_scalar, &[100.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Trim Offset", "offset"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Trim Type", "mode"), c_popup, &[1.0], &w, cx);
|
||||
"ADBE Vector Filter - Trim"
|
||||
}
|
||||
// Round Corners (238; default radius 10, 519).
|
||||
"round" => {
|
||||
rec(&mut r, g, ("ADBE Vector RoundCorner Radius", "radius"), c_scalar, &[10.0], &w, cx);
|
||||
"ADBE Vector Filter - RC"
|
||||
}
|
||||
// Merge Paths (707, 708, 731).
|
||||
"merge" => {
|
||||
rec(&mut r, g, ("ADBE Vector Merge Type", "mode"), c_popup, &[1.0], &w, cx);
|
||||
"ADBE Vector Filter - Merge"
|
||||
}
|
||||
// Offset Paths (710, 828; defaults 731: amount 10, miter 4, one copy, copy offset 1).
|
||||
"offset" => {
|
||||
rec(&mut r, g, ("ADBE Vector Offset Amount", "amount"), c_scalar, &[10.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Offset Line Join", "join"), c_popup, &[1.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Offset Miter Limit", "miter"), c_scalar, &[4.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Offset Copies", "copies"), c_scalar, &[1.0], &w, cx);
|
||||
// EffectCraft offsets copy i by Amount x (i + 1 + copyOffset), After Effects by
|
||||
// Amount x (i + Copy Offset) (826-828): Copy Offset = copyOffset + 1, the
|
||||
// importer's inverse.
|
||||
rec(&mut r, g, ("ADBE Vector Offset Copy Offset", "copyOffset"), c_copy_offset, &[1.0], &w, cx);
|
||||
if g.get("copyOffset").is_some_and(|p| p.has_expression()) {
|
||||
cx.col.lose(
|
||||
LossCategory::ShapeLayers,
|
||||
format!("{w}: the expression on Offset Paths' Copy Offset is written as it is (After Effects' value is 1 more than EffectCraft's)"),
|
||||
);
|
||||
}
|
||||
"ADBE Vector Filter - Offset"
|
||||
}
|
||||
// Repeater (102, 709; defaults 731: one copy, offset 0, below, identity transform).
|
||||
"repeater" => {
|
||||
rec(&mut r, g, ("ADBE Vector Repeater Copies", "copies"), c_scalar, &[1.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Repeater Offset", "offset"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut r, g, ("ADBE Vector Repeater Order", "composite"), c_popup, &[1.0], &w, cx);
|
||||
let mut t = Vec::new();
|
||||
if let Some(tr) = g.sub("transform") {
|
||||
rec(&mut t, tr, ("ADBE Vector Repeater Anchor", "anchor"), c_point, &[0.0, 0.0], &w, cx);
|
||||
rec(&mut t, tr, ("ADBE Vector Repeater Position", "position"), c_point, &[0.0, 0.0], &w, cx);
|
||||
rec(&mut t, tr, ("ADBE Vector Repeater Scale", "scale"), c_point, &[100.0, 100.0], &w, cx);
|
||||
rec(&mut t, tr, ("ADBE Vector Repeater Rotation", "rotation"), c_scalar, &[0.0], &w, cx);
|
||||
rec(&mut t, tr, ("ADBE Vector Repeater Opacity 1", "startOpacity"), c_scalar, &[100.0], &w, cx);
|
||||
rec(&mut t, tr, ("ADBE Vector Repeater Opacity 2", "endOpacity"), c_scalar, &[100.0], &w, cx);
|
||||
}
|
||||
subs.push(("ADBE Vector Repeater Transform", t));
|
||||
"ADBE Vector Filter - Repeater"
|
||||
}
|
||||
other => {
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: the shape item '{other}' is not written"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
out.push(wrap(ShItem::Simple { kind, name: g.name.clone(), records: r, subs }));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The value record of `name` holding `v`.
|
||||
fn value_record(t: &ShapeProtos, name: &'static str, v: &RecVal) -> R<[Chunk<'static>; 2]> {
|
||||
let [m, node] = t.record(name)?;
|
||||
let layout = kind_of(name).map_or(Layout::One, |k| k.layout);
|
||||
build_record(m, node, layout, v, &t.key_list)
|
||||
}
|
||||
|
||||
/// A static value record (`node`, after its `tdmn` `m`) turned into the record of `v`: its value,
|
||||
/// its keys (`key_list` the list prototype) and its expression.
|
||||
pub(crate) fn build_record(m: Chunk<'static>, mut node: Chunk<'static>, layout: Layout, v: &RecVal, key_list: &Chunk<'static>) -> R<[Chunk<'static>; 2]> {
|
||||
if v.keys.is_empty() {
|
||||
let d = child_data(&mut node, b"cdat")?;
|
||||
for (i, x) in v.value.iter().enumerate() {
|
||||
put_f64(d, i * 8, *x)?;
|
||||
}
|
||||
} else {
|
||||
let n = v.value.len().max(1);
|
||||
let size = match layout {
|
||||
Layout::Point | Layout::Color => 56 + 24 * n,
|
||||
_ => 8 + 40 * n,
|
||||
};
|
||||
{
|
||||
let tdb4 = child_data(&mut node, b"tdb4")?;
|
||||
let b5 = tdb4.get(5).copied().ok_or_else(|| tpl("short tdb4"))?;
|
||||
put_u8(tdb4, 5, b5 & !0x01)?;
|
||||
put_u8(tdb4, 68, 1)?;
|
||||
// A keyed point or colour clears byte 79 too (853, 854; as on effects, R25).
|
||||
if matches!(layout, Layout::Point | Layout::Color) {
|
||||
put_u8(tdb4, 79, 0)?;
|
||||
}
|
||||
}
|
||||
let mut ldat = Vec::with_capacity(size * v.keys.len());
|
||||
for k in &v.keys {
|
||||
ldat.extend(match layout {
|
||||
Layout::Point => spatial_record(k, n, true, size)?,
|
||||
Layout::Color => spatial_record(k, n, false, size)?,
|
||||
_ => crate::export::emit::plain_record(n, k, size)?,
|
||||
});
|
||||
}
|
||||
let mut list = key_list.clone();
|
||||
fill_key_list(&mut list, ldat, v.keys.len(), size)?;
|
||||
replace_cdat(&mut node, list)?;
|
||||
}
|
||||
if let Some((text, enabled)) = &v.expr {
|
||||
// As on the Transform properties (R15; 856).
|
||||
{
|
||||
let tdb4 = child_data(&mut node, b"tdb4")?;
|
||||
put_u8(tdb4, 76, 1)?;
|
||||
put_u8(tdb4, 77, 1)?;
|
||||
put_u8(tdb4, 120, 1)?;
|
||||
put_u8(tdb4, 119, u8::from(!*enabled))?;
|
||||
}
|
||||
let kids = kids_mut(&mut node)?;
|
||||
let at = kids.iter().position(|c| c.is(b"tdum")).unwrap_or(kids.len());
|
||||
kids.insert(at, Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
|
||||
}
|
||||
Ok([m, node])
|
||||
}
|
||||
|
||||
/// Inserts value records into an item's `tdgp` (between its header and its sub-groups / end),
|
||||
/// in the order of [`KINDS`].
|
||||
fn put_records(t: &ShapeProtos, tdgp: &mut Chunk<'static>, records: &[(&'static str, RecVal)]) -> R<()> {
|
||||
let kids = kids_mut(tdgp)?;
|
||||
let mut at = kids.iter().position(|c| c.is(b"tdmn")).unwrap_or(kids.len());
|
||||
let mut sorted: Vec<&(&'static str, RecVal)> = records.iter().collect();
|
||||
sorted.sort_by_key(|(n, _)| KINDS.iter().position(|(o, _)| o == n).unwrap_or(KINDS.len()));
|
||||
for (name, v) in sorted {
|
||||
let [m, node] = value_record(t, name, v)?;
|
||||
kids.insert(at, m);
|
||||
kids.insert(at.saturating_add(1), node);
|
||||
at = at.saturating_add(2);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The item nodes (`tdmn` + `tdgp` pairs) for `items`, top first.
|
||||
pub(crate) fn build_items(t: &ShapeProtos, items: &[ShItem], depth: usize) -> R<Vec<Chunk<'static>>> {
|
||||
let mut out = Vec::new();
|
||||
if depth > MAX_DEPTH {
|
||||
return Ok(out);
|
||||
}
|
||||
let pos = |kids: &[Chunk<'static>], n: &str| kids.iter().position(|c| is_tdmn(c, n));
|
||||
for item in items {
|
||||
match item {
|
||||
ShItem::Off(inner) => {
|
||||
let mut built = build_items(t, std::slice::from_ref(inner.as_ref()), depth)?;
|
||||
if let Some(node) = built.get_mut(1) {
|
||||
let tdsb = child_data(node, b"tdsb")?;
|
||||
let flags = tdsb.get(3).copied().ok_or_else(|| tpl("short tdsb"))?;
|
||||
put_u8(tdsb, 3, flags & !1)?;
|
||||
}
|
||||
out.extend(built);
|
||||
}
|
||||
ShItem::Group { name, items, transform } => {
|
||||
let [m, mut node] = t.item("ADBE Vector Group")?;
|
||||
set_name(&mut node, name)?;
|
||||
let children = build_items(t, items, depth + 1)?;
|
||||
let kids = kids_mut(&mut node)?;
|
||||
let vg = pos(kids, "ADBE Vectors Group").ok_or_else(|| tpl("group prototype without contents"))?;
|
||||
let contents = kids.get_mut(vg + 1).ok_or_else(|| tpl("group prototype without contents"))?;
|
||||
let ck = kids_mut(contents)?;
|
||||
let end = ck.iter().position(|c| is_tdmn(c, GROUP_END)).unwrap_or(ck.len());
|
||||
ck.splice(end..end, children);
|
||||
let tg = pos(kids, "ADBE Vector Transform Group").ok_or_else(|| tpl("group prototype without transform"))?;
|
||||
let tnode = kids.get_mut(tg + 1).ok_or_else(|| tpl("group prototype without transform"))?;
|
||||
put_records(t, tnode, transform)?;
|
||||
out.extend([m, node]);
|
||||
}
|
||||
ShItem::Simple { kind, name, records, subs } => {
|
||||
let [m, mut node] = t.item(kind)?;
|
||||
set_name(&mut node, name)?;
|
||||
for (sub, recs) in subs {
|
||||
if recs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let kids = kids_mut(&mut node)?;
|
||||
let at = pos(kids, sub).ok_or_else(|| tpl("shape item prototype without its sub-group"))?;
|
||||
let group = kids.get_mut(at + 1).ok_or_else(|| tpl("shape item prototype without its sub-group"))?;
|
||||
put_records(t, group, recs)?;
|
||||
}
|
||||
put_records(t, &mut node, records)?;
|
||||
out.extend([m, node]);
|
||||
}
|
||||
ShItem::Path { name, shape } => {
|
||||
let [m, mut node] = t.item("ADBE Vector Shape - Group")?;
|
||||
set_name(&mut node, name)?;
|
||||
let kids = kids_mut(&mut node)?;
|
||||
let oms = kids.iter_mut().find(|c| c.is_list(b"om-s")).ok_or_else(|| tpl("path prototype without its shape"))?;
|
||||
let omks = list_mut(oms, b"omks")?;
|
||||
let proto = kids_mut(omks)?.iter().find(|c| c.is_list(b"shap")).cloned().ok_or_else(|| tpl("path prototype without a shape"))?;
|
||||
*kids_mut(omks)? = vec![crate::export::masks::build_shap(&proto, shape)?];
|
||||
out.extend([m, node]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The item's user name (`tdsn/Utf8`).
|
||||
fn set_name(node: &mut Chunk<'static>, name: &str) -> R<()> {
|
||||
let kids = kids_mut(node)?;
|
||||
let tdsn = kids.iter_mut().find(|c| c.is(b"tdsn")).ok_or_else(|| tpl("shape item without a name"))?;
|
||||
set_utf8(tdsn, name)
|
||||
}
|
||||
|
||||
/// Fills the layer's `ADBE Root Vectors Group` with `items`.
|
||||
pub(crate) fn put_contents(layr: &mut Chunk<'static>, t: &ShapeProtos, items: &[ShItem]) -> R<()> {
|
||||
let built = build_items(t, items, 0)?;
|
||||
let root = list_mut(layr, b"tdgp")?;
|
||||
let kids = kids_mut(root)?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, "ADBE Root Vectors Group")).ok_or_else(|| tpl("shape layer without contents"))?;
|
||||
let rv = kids.get_mut(at + 1).ok_or_else(|| tpl("shape layer without contents"))?;
|
||||
let rk = kids_mut(rv)?;
|
||||
let end = rk.iter().position(|c| is_tdmn(c, GROUP_END)).unwrap_or(rk.len());
|
||||
rk.splice(end..end, built);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! The layer, item and project skeletons the exporter fills, built in code (aep-format.md 3.1-3.4):
|
||||
//! only the property groups the exporter writes into, the default records it edits, and the small
|
||||
//! fixed records each layer carries. After Effects adds the groups that are left out (read-back
|
||||
//! e1-sparse).
|
||||
|
||||
use crate::Chunk;
|
||||
use crate::export::synth::{GROUP_END, KeyTemplate, NO_NAME, RecSpec, class, tdbs, tdmn, tdmn_name, tdsn};
|
||||
|
||||
/// A group: its match name and a `tdgp` with the state `state` (`tdsb`), no user name, `kids` and
|
||||
/// the closing `ADBE Group End`.
|
||||
pub(crate) fn group(name: &str, state: u32, kids: Vec<Chunk<'static>>) -> [Chunk<'static>; 2] {
|
||||
let mut body = vec![Chunk::data(*b"tdsb", state.to_be_bytes().to_vec()), tdsn(NO_NAME)];
|
||||
body.extend(kids);
|
||||
body.push(tdmn(GROUP_END));
|
||||
[tdmn(name), Chunk::list(*b"tdgp", body)]
|
||||
}
|
||||
|
||||
/// The seven records that follow a layer or item block (`fvdv` 3, the others zero; the same in
|
||||
/// every sample, meaning not decoded).
|
||||
pub(crate) fn f_records() -> Vec<Chunk<'static>> {
|
||||
vec![
|
||||
Chunk::data(*b"fvdv", 3u32.to_be_bytes().to_vec()),
|
||||
Chunk::data(*b"fiop", vec![0]),
|
||||
Chunk::data(*b"ftts", vec![0; 4]),
|
||||
Chunk::data(*b"foac", vec![0]),
|
||||
Chunk::data(*b"fiac", vec![0]),
|
||||
Chunk::data(*b"fipc", vec![0; 2]),
|
||||
Chunk::data(*b"fifl", vec![0; 4]),
|
||||
]
|
||||
}
|
||||
|
||||
/// The layer styles in the order After Effects keeps their switch groups (950).
|
||||
const STYLE_ORDER: [&str; 10] =
|
||||
["dropShadow", "innerShadow", "outerGlow", "innerGlow", "bevelEmboss", "chromeFX", "solidFill", "gradientFill", "patternFill", "frameFX"];
|
||||
|
||||
/// The empty `ADBE Layer Styles` group (state 3), Blending Options with the advanced group, and
|
||||
/// the switch group of every style (state 2: not applied), for `styles::put_styles` to fill.
|
||||
pub(crate) fn layer_styles() -> [Chunk<'static>; 2] {
|
||||
let mut kids: Vec<Chunk<'static>> = group("ADBE Blend Options Group", 3, group("ADBE Adv Blend Group", 1, Vec::new()).into()).into();
|
||||
for s in STYLE_ORDER {
|
||||
kids.extend(group(&format!("{s}/enabled"), 2, Vec::new()));
|
||||
}
|
||||
group("ADBE Layer Styles", 3, kids)
|
||||
}
|
||||
|
||||
/// The inert Time Remapping record every layer has (`tdsb` 3, value 0, the maximum written per
|
||||
/// layer: aep-format.md 3.4).
|
||||
fn time_remap() -> Chunk<'static> {
|
||||
let spec = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: Some((0.0, 0.0)), byte5: None };
|
||||
let mut rec = tdbs(&spec, false, 25_600);
|
||||
if let Some(state) = rec.children_mut().iter_mut().find(|c| c.is(b"tdsb")) {
|
||||
*state = Chunk::data(*b"tdsb", 3u32.to_be_bytes().to_vec());
|
||||
}
|
||||
rec
|
||||
}
|
||||
|
||||
/// The block of an AV layer (solid, footage, precomposition): `Layr` (a zero `ldta` the exporter
|
||||
/// fills with the decoded fields, read-back t-zldta; the name; the property tree with Time
|
||||
/// Remapping, an empty Transform group and the layer styles), `Ewst` and the f-records.
|
||||
pub(crate) fn av_layer() -> Vec<Chunk<'static>> {
|
||||
let mut root = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(""), tdmn("ADBE Time Remapping"), time_remap()];
|
||||
root.extend(group("ADBE Transform Group", 1, crate::export::tree_spec::build(crate::export::tree_defs::AV_TRANSFORM)));
|
||||
root.extend(layer_styles());
|
||||
root.push(tdmn(GROUP_END));
|
||||
let layr = Chunk::list(
|
||||
*b"Layr",
|
||||
vec![Chunk::data(*b"ldta", vec![0; 164]), Chunk::data(*b"Utf8", Vec::new()), Chunk::list(*b"tdgp", root), crate::export::base::guides()],
|
||||
);
|
||||
let mut out = vec![layr, Chunk::list(*b"Ewst", Vec::new())];
|
||||
// Two sets of f-records follow every layer (000).
|
||||
out.extend(f_records());
|
||||
out.extend(f_records());
|
||||
out
|
||||
}
|
||||
|
||||
/// The block of a layer whose property tree is `nodes` (cameras, lights, shapes: `tree_defs`),
|
||||
/// with a zero `ldta`, the guides, `Ewst` and the f-records.
|
||||
pub(crate) fn layer_block(nodes: &[crate::export::tree_spec::Node]) -> Vec<Chunk<'static>> {
|
||||
let mut root = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn("")];
|
||||
root.extend(crate::export::tree_spec::build(nodes));
|
||||
root.push(tdmn(GROUP_END));
|
||||
let layr = Chunk::list(
|
||||
*b"Layr",
|
||||
vec![Chunk::data(*b"ldta", vec![0; 164]), Chunk::data(*b"Utf8", Vec::new()), Chunk::list(*b"tdgp", root), crate::export::base::guides()],
|
||||
);
|
||||
let mut out = vec![layr, Chunk::list(*b"Ewst", Vec::new())];
|
||||
// Two sets of f-records follow every layer (000).
|
||||
out.extend(f_records());
|
||||
out.extend(f_records());
|
||||
out
|
||||
}
|
||||
|
||||
/// The Source Text record (`btds/tdbs`, 110): one component, class `0x00010004`, a 4-byte zero
|
||||
/// `cdat`.
|
||||
const SOURCE_TEXT: crate::export::tree_spec::Rec = crate::export::tree_spec::Rec {
|
||||
state: 1,
|
||||
label: NO_NAME,
|
||||
dims: 1,
|
||||
template: 0,
|
||||
class: class::EFFECT_CHOICE,
|
||||
byte5: 0x01,
|
||||
header: &[],
|
||||
cdat_len: 4,
|
||||
cdat: &[],
|
||||
key_size: 0,
|
||||
limits: None,
|
||||
tdpi: None,
|
||||
};
|
||||
|
||||
/// The block of a text layer (110, 245): `ADBE Text Properties` with the text document (the
|
||||
/// Source Text record, the document `doc` as `LIST btdk`, and `btgu` with the document's id and
|
||||
/// a zero one), the empty Path and More Options groups; the inert Transform records and the layer
|
||||
/// styles; a zero `ldta`, the guides, `Ewst` and the f-records.
|
||||
pub(crate) fn text_layer(doc: &[u8]) -> Vec<Chunk<'static>> {
|
||||
use crate::export::tree_spec::{Node, build};
|
||||
let btdk = Chunk { id: *b"LIST", body: crate::Body::OpaqueList { list_type: *b"btdk", data: doc.to_vec().into() }, pad: None };
|
||||
// The record without its match name (`build` gives the pair).
|
||||
let mut btds_kids: Vec<Chunk<'static>> = build(&[Node::R("ADBE Text Document", SOURCE_TEXT)]).into_iter().filter(|c| c.is_list(b"tdbs")).collect();
|
||||
btds_kids.push(btdk);
|
||||
let btgu = Chunk::list(*b"btgu", vec![Chunk::data(*b"pgui", vec![0; 16]), Chunk::data(*b"pgui", vec![0; 16])]);
|
||||
let mut props = vec![tdmn("ADBE Text Document"), Chunk::list(*b"btds", btds_kids), btgu];
|
||||
props.extend(group("ADBE Text Path Options", 1, Vec::new()));
|
||||
props.extend(group("ADBE Text More Options", 1, Vec::new()));
|
||||
let mut root = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn("")];
|
||||
root.extend(group("ADBE Text Properties", 1, props));
|
||||
root.extend(group("ADBE Transform Group", 1, crate::export::tree_spec::build(crate::export::tree_defs::AV_TRANSFORM)));
|
||||
root.extend(layer_styles());
|
||||
root.push(tdmn(GROUP_END));
|
||||
let layr = Chunk::list(
|
||||
*b"Layr",
|
||||
vec![Chunk::data(*b"ldta", vec![0; 164]), Chunk::data(*b"Utf8", Vec::new()), Chunk::list(*b"tdgp", root), crate::export::base::guides()],
|
||||
);
|
||||
let mut out = vec![layr, Chunk::list(*b"Ewst", Vec::new())];
|
||||
out.extend(f_records());
|
||||
out.extend(f_records());
|
||||
out
|
||||
}
|
||||
|
||||
/// `tdmn` + node pairs of `nodes`, by match name.
|
||||
pub(crate) fn pairs(nodes: &[crate::export::tree_spec::Node]) -> Vec<(String, [Chunk<'static>; 2])> {
|
||||
let mut out = Vec::new();
|
||||
let mut it = crate::export::tree_spec::build(nodes).into_iter();
|
||||
while let (Some(m), Some(n)) = (it.next(), it.next()) {
|
||||
let name = tdmn_name(&m).unwrap_or_default();
|
||||
out.push((name, [m, n]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The marker group (`tdmn ADBE Marker` + `LIST mrst`, aep-format.md 3.11) for
|
||||
/// `markers::build`: the marker property as a keyed one-component record (class `0x00010004`,
|
||||
/// 16-byte keys, 249) and `mrky` with one `Nmrd` whose header (`NmHd`) and strings are written
|
||||
/// per marker.
|
||||
pub(crate) fn marker_group() -> Vec<Chunk<'static>> {
|
||||
let spec = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_CHOICE, limits: None, byte5: None };
|
||||
let record = tdbs(&spec, true, 25_600);
|
||||
let nmrd = Chunk::list(*b"Nmrd", vec![Chunk::data(*b"NmHd", vec![0; 20])]);
|
||||
vec![tdmn("ADBE Marker"), Chunk::list(*b"mrst", vec![record, Chunk::list(*b"mrky", vec![nmrd])])]
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! The layer-style records the exporter writes, one per parameter (aep-format.md 3.12b): the
|
||||
//! match name, the components, the key template (`tdb4` byte 7), the class word (`tdb4` 8..11)
|
||||
//! and the limits (`tdum` / `tduM`), as After Effects shows them for each style parameter. The
|
||||
//! rows were listed from our style cases (950-980) through the reader.
|
||||
|
||||
/// One record: match name, components, key template, class word, limits.
|
||||
pub(crate) type StyleRec = (&'static str, u8, u8, u32, Option<(f64, f64)>);
|
||||
|
||||
const fn s(name: &'static str, dims: u8, template: u8, class: u32, limits: Option<(f64, f64)>) -> StyleRec {
|
||||
(name, dims, template, class, limits)
|
||||
}
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub(crate) static STYLE_RECORDS: &[StyleRec] = &[
|
||||
s("ADBE B Channel Blend", 1, 0, 0xffff0004, None),
|
||||
s("ADBE Blend Interior", 1, 0, 0xffff0004, None),
|
||||
s("ADBE Blend Ranges", 1, 0, 0xffff0004, None),
|
||||
s("ADBE G Channel Blend", 1, 0, 0xffff0004, None),
|
||||
s("ADBE Global Altitude2", 1, 0, 0x0002ffff, None),
|
||||
s("ADBE Global Angle2", 1, 0, 0x0002ffff, None),
|
||||
s("ADBE Layer Fill Opacity2", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("ADBE R Channel Blend", 1, 0, 0xffff0004, None),
|
||||
s("bevelEmboss/bevelDirection", 1, 0, 0x00010004, None),
|
||||
s("bevelEmboss/bevelStyle", 1, 0, 0x00010004, None),
|
||||
s("bevelEmboss/bevelTechnique", 1, 0, 0x00010004, None),
|
||||
s("bevelEmboss/blur", 1, 0, 0xffffffff, Some((0.0, 250.0))),
|
||||
s("bevelEmboss/highlightColor", 4, 1, 0x0002ffff, None),
|
||||
s("bevelEmboss/highlightMode", 1, 0, 0x00010004, None),
|
||||
s("bevelEmboss/highlightOpacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("bevelEmboss/localLightingAltitude", 1, 0, 0xffffffff, None),
|
||||
s("bevelEmboss/localLightingAngle", 1, 0, 0xffffffff, None),
|
||||
s("bevelEmboss/shadowColor", 4, 1, 0x0002ffff, None),
|
||||
s("bevelEmboss/shadowMode", 1, 0, 0x00010004, None),
|
||||
s("bevelEmboss/shadowOpacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("bevelEmboss/softness", 1, 0, 0xffffffff, Some((0.0, 16.0))),
|
||||
s("bevelEmboss/strengthRatio", 1, 0, 0xffffffff, Some((1.0, 1000.0))),
|
||||
s("bevelEmboss/useGlobalAngle", 1, 0, 0x00010004, None),
|
||||
s("chromeFX/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("chromeFX/color", 4, 1, 0x0002ffff, None),
|
||||
s("chromeFX/distance", 1, 0, 0xffffffff, Some((1.0, 100.0))),
|
||||
s("chromeFX/invert", 1, 0, 0x00010004, None),
|
||||
s("chromeFX/localLightingAngle", 1, 0, 0xffffffff, None),
|
||||
s("chromeFX/mode2", 1, 0, 0x00010004, None),
|
||||
s("chromeFX/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("dropShadow/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("dropShadow/chokeMatte", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("dropShadow/color", 4, 1, 0x0002ffff, None),
|
||||
s("dropShadow/distance", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("dropShadow/layerConceals", 1, 0, 0x00010004, None),
|
||||
s("dropShadow/localLightingAngle", 1, 0, 0xffffffff, None),
|
||||
s("dropShadow/mode2", 1, 0, 0x00010004, None),
|
||||
s("dropShadow/noise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("dropShadow/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("dropShadow/useGlobalAngle", 1, 0, 0x00010004, None),
|
||||
s("frameFX/color", 4, 1, 0x0002ffff, None),
|
||||
s("frameFX/mode2", 1, 0, 0x00010004, None),
|
||||
s("frameFX/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("frameFX/size", 1, 0, 0xffffffff, Some((1.0, 100.0))),
|
||||
s("frameFX/style", 1, 0, 0x00010004, None),
|
||||
s("gradientFill/align", 1, 0, 0x00010004, None),
|
||||
s("gradientFill/angle", 1, 0, 0xffffffff, None),
|
||||
s("gradientFill/gradientSmoothness", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("gradientFill/mode2", 1, 0, 0x00010004, None),
|
||||
s("gradientFill/offset", 2, 3, 0xffffffff, None),
|
||||
s("gradientFill/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("gradientFill/reverse", 1, 0, 0x00010004, None),
|
||||
s("gradientFill/scale", 1, 0, 0xffffffff, Some((10.0, 150.0))),
|
||||
s("gradientFill/type", 1, 0, 0x00010004, None),
|
||||
s("innerGlow/AEColorChoice", 1, 0, 0x00010004, None),
|
||||
s("innerGlow/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerGlow/chokeMatte", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerGlow/color", 4, 1, 0x0002ffff, None),
|
||||
s("innerGlow/glowTechnique", 1, 0, 0x00010004, None),
|
||||
s("innerGlow/gradientSmoothness", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerGlow/innerGlowSource", 1, 0, 0x00010004, None),
|
||||
s("innerGlow/inputRange", 1, 0, 0xffffffff, Some((1.0, 100.0))),
|
||||
s("innerGlow/mode2", 1, 0, 0x00010004, None),
|
||||
s("innerGlow/noise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerGlow/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerGlow/shadingNoise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerShadow/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerShadow/chokeMatte", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerShadow/color", 4, 1, 0x0002ffff, None),
|
||||
s("innerShadow/distance", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerShadow/localLightingAngle", 1, 0, 0xffffffff, None),
|
||||
s("innerShadow/mode2", 1, 0, 0x00010004, None),
|
||||
s("innerShadow/noise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerShadow/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("innerShadow/useGlobalAngle", 1, 0, 0x00010004, None),
|
||||
s("outerGlow/AEColorChoice", 1, 0, 0x00010004, None),
|
||||
s("outerGlow/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("outerGlow/chokeMatte", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("outerGlow/color", 4, 1, 0x0002ffff, None),
|
||||
s("outerGlow/glowTechnique", 1, 0, 0x00010004, None),
|
||||
s("outerGlow/gradientSmoothness", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("outerGlow/inputRange", 1, 0, 0xffffffff, Some((1.0, 100.0))),
|
||||
s("outerGlow/mode2", 1, 0, 0x00010004, None),
|
||||
s("outerGlow/noise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("outerGlow/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("outerGlow/shadingNoise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
s("solidFill/color", 4, 1, 0x0002ffff, None),
|
||||
s("solidFill/mode2", 1, 0, 0x00010004, None),
|
||||
s("solidFill/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
|
||||
];
|
||||
@@ -0,0 +1,372 @@
|
||||
//! Layer styles: the inverse of the importer, through the shared table
|
||||
//! [`crate::style_map`].
|
||||
//!
|
||||
//! Every layer block already holds the `ADBE Layer Styles` group with Blending Options
|
||||
//! and the ten switch groups at rest (950). A style is applied by setting its switch group's
|
||||
//! `tdsb` to 1 and Layer Styles and Blending Options to 1 (951-960); a parameter that differs
|
||||
//! from After Effects' default gets a record, built from the table of the record
|
||||
//! After Effects writes for that parameter (`style_defs`, from 977) with the value, in After Effects'
|
||||
//! property order (970). Keys on a scalar take the keyed form of 976 (`tdb4` bytes 5, 68 and 79
|
||||
//! from it, plain 48-byte key records); an expression is stored as on an effect parameter
|
||||
//! (`tdb4@120` 1, `@119` the disabled switch, the text before `tdum`).
|
||||
//!
|
||||
//! A style switched off keeps its records with its switch group's `tdsb` 0 (988). Not written,
|
||||
//! reported: the whole Layer Styles group switched off (not sampled), gradients that differ from the default (`GCst` is not decoded), keys on
|
||||
//! colours, points, popups and checkboxes (not sampled), Knockout (After Effects has none).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::Chunk;
|
||||
use crate::style_map::{self as sm, StyleConv, StyleParam};
|
||||
use effectcraft_keyframe::{Interp, Value};
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::styles::{self as st, STYLE_BLEND_MODES};
|
||||
use effectcraft_project::{Comp, Layer, PropGroup, Property};
|
||||
|
||||
use crate::export::keys::{fill_key_list, replace_cdat, timed_keys};
|
||||
use crate::export::plan::{CompPlan, EaseSlot, KeyPlan};
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::synth::{GROUP_END, is_tdmn};
|
||||
use crate::export::tree::{R, child_data, kids_mut, put_f64, put_u8, put_u32, tpl};
|
||||
|
||||
/// A record's value.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum RecValue {
|
||||
Static(Vec<f64>),
|
||||
Keys(Vec<KeyPlan>),
|
||||
}
|
||||
|
||||
/// One parameter record to write.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Record {
|
||||
/// The full match name (`dropShadow/opacity`, `ADBE Global Angle2`).
|
||||
pub name: String,
|
||||
pub value: RecValue,
|
||||
/// Expression text and its enabled switch.
|
||||
pub expr: Option<(String, bool)>,
|
||||
}
|
||||
|
||||
/// The layer styles of one layer.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct StylesPlan {
|
||||
/// Applied styles (switch-group prefix) with their records and their switch, in menu order.
|
||||
pub styles: Vec<(&'static str, Vec<Record>, bool)>,
|
||||
/// Global Light Angle / Altitude records (Blending Options).
|
||||
pub global: Vec<Record>,
|
||||
/// Advanced Blending records.
|
||||
pub adv: Vec<Record>,
|
||||
}
|
||||
|
||||
fn sane(v: f64) -> Option<f64> {
|
||||
(v.is_finite() && v.abs() <= crate::export::plan::LIMIT).then_some(v)
|
||||
}
|
||||
|
||||
/// An EffectCraft value in the file's units.
|
||||
pub(crate) fn stored(conv: StyleConv, v: &Value) -> Option<Vec<f64>> {
|
||||
let out = match (conv, v) {
|
||||
(StyleConv::Number, Value::Scalar(x)) => vec![sane(*x)?],
|
||||
(StyleConv::Color, Value::Color(c)) => vec![255.0, sane(c[0] * 255.0)?, sane(c[1] * 255.0)?, sane(c[2] * 255.0)?],
|
||||
(StyleConv::Mode, Value::Enum(i)) => {
|
||||
let name = STYLE_BLEND_MODES.get(usize::try_from(*i).ok()?)?.0;
|
||||
vec![f64::from(sm::mode_code(name)?)]
|
||||
}
|
||||
(StyleConv::Popup(map), Value::Enum(i)) => vec![f64::from(sm::popup_code(map, *i)?)],
|
||||
(StyleConv::Checkbox, Value::Bool(b)) => vec![if *b { 1.0 } else { 0.0 }],
|
||||
(StyleConv::Vec2, Value::Vec2(p)) => vec![sane(p[0])?, sane(p[1])?],
|
||||
_ => return None,
|
||||
};
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Whether an expression on a style popup would mean something else in After Effects. Both
|
||||
/// programs count popup items from 1 in expressions, so only a popup whose stored item numbers are
|
||||
/// not EffectCraft's items in the same order (Inner Glow Source is stored reversed) or a blend
|
||||
/// mode whose After Effects item number differs from its place in EffectCraft's list is reported.
|
||||
fn popup_expression_differs(conv: StyleConv) -> bool {
|
||||
match conv {
|
||||
StyleConv::Popup(map) => map.iter().enumerate().any(|(i, m)| usize::try_from(*m).ok() != Some(i)),
|
||||
StyleConv::Mode => STYLE_BLEND_MODES.iter().enumerate().any(|(i, (name, _))| sm::mode_code(name).and_then(|c| usize::try_from(c).ok()) != Some(i + 1)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn same(a: &[f64], b: &[f64]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-9 * x.abs().max(1.0))
|
||||
}
|
||||
|
||||
/// The record of one parameter, `None` when it stays at After Effects' default (no record).
|
||||
fn plan_record(spec: &StyleParam, full: String, prop: &Property, cp: &CompPlan, what: &str, col: &mut Collector) -> Option<Record> {
|
||||
let here = format!("{what}: {full}");
|
||||
let expr = prop.expr.as_ref().filter(|e| !e.text.is_empty()).map(|e| (e.text.clone(), e.enabled));
|
||||
if expr.is_some() {
|
||||
col.exported.expressions = col.exported.expressions.saturating_add(1);
|
||||
if popup_expression_differs(spec.conv) {
|
||||
col.lose(
|
||||
LossCategory::LayerStyles,
|
||||
format!("{here}: an expression on a popup whose items are in another order in After Effects means something else there (written unchanged)"),
|
||||
);
|
||||
}
|
||||
}
|
||||
if !prop.keys.is_empty() {
|
||||
if spec.conv == StyleConv::Number {
|
||||
let keys = plan_number_keys(prop, cp, &here, col);
|
||||
if !keys.is_empty() {
|
||||
return Some(Record { name: full, value: RecValue::Keys(keys), expr });
|
||||
}
|
||||
} else {
|
||||
col.lose(LossCategory::LayerStyles, format!("{here}: keys are not written (not sampled for this kind), the current value is"));
|
||||
}
|
||||
}
|
||||
let Some(value) = stored(spec.conv, &prop.value) else {
|
||||
col.lose(LossCategory::InvalidValues, format!("{here}: a value that cannot be stored, After Effects' default written"));
|
||||
return None;
|
||||
};
|
||||
if same(&value, spec.default) && expr.is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(Record { name: full, value: RecValue::Static(value), expr })
|
||||
}
|
||||
|
||||
/// The keys of a scalar in the layer's time base: linear, hold and bezier sides with the ease in
|
||||
/// stored units per second (the plain template of 976).
|
||||
fn plan_number_keys(prop: &Property, cp: &CompPlan, what: &str, col: &mut Collector) -> Vec<KeyPlan> {
|
||||
let timed = timed_keys(&prop.keys, &cp.tb, what, "key", col);
|
||||
let mut out = Vec::with_capacity(timed.len());
|
||||
let beyond = std::cell::Cell::new(false);
|
||||
for (u, k) in timed {
|
||||
let (Ok(time), Some(v)) = (
|
||||
i32::try_from(u),
|
||||
match &k.value {
|
||||
Value::Scalar(x) => sane(*x),
|
||||
_ => None,
|
||||
},
|
||||
) else {
|
||||
col.lose(LossCategory::InvalidValues, format!("{what}: a key that cannot be stored, key dropped"));
|
||||
continue;
|
||||
};
|
||||
let side = |i: Interp| -> u8 {
|
||||
match i {
|
||||
Interp::Linear => 1,
|
||||
Interp::Bezier => 2,
|
||||
Interp::Hold => 3,
|
||||
}
|
||||
};
|
||||
let (in_i, out_i) = (side(k.in_interp), side(k.out_interp));
|
||||
let ease = |eases: &[effectcraft_keyframe::Ease], on: bool| -> Vec<EaseSlot> {
|
||||
if !on {
|
||||
return vec![EaseSlot::default()];
|
||||
}
|
||||
let e = crate::export::plan::key_ease(eases, 0);
|
||||
let influence = if e.influence.is_finite() { e.influence.clamp(0.001, 1.0) } else { 1.0 / 3.0 };
|
||||
let speed = sane(e.speed).unwrap_or_else(|| {
|
||||
beyond.set(true);
|
||||
0.0
|
||||
});
|
||||
vec![EaseSlot { speed, influence }]
|
||||
};
|
||||
out.push(KeyPlan {
|
||||
time,
|
||||
value: vec![v],
|
||||
in_interp: in_i,
|
||||
out_interp: out_i,
|
||||
in_ease: ease(&k.in_ease, in_i == 2),
|
||||
out_ease: ease(&k.out_ease, out_i == 2),
|
||||
spatial_in: [0.0; 3],
|
||||
spatial_out: [0.0; 3],
|
||||
spatial_auto: true,
|
||||
roving: false,
|
||||
label: k.label.min(16),
|
||||
});
|
||||
if k.roving {
|
||||
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a roving key is written as a normal key"));
|
||||
}
|
||||
}
|
||||
crate::export::plan::report_beyond(beyond.get(), what, col);
|
||||
out
|
||||
}
|
||||
|
||||
/// EffectCraft's default of a style parameter (to tell an edited gradient).
|
||||
fn model_default(style: &str, id: &str) -> Option<Value> {
|
||||
let mut next = 1;
|
||||
let g = st::style(&mut Ids(&mut next), style)?;
|
||||
g.get(id).map(|p| p.value.clone())
|
||||
}
|
||||
|
||||
/// The layer styles of `layer`; `None` when it has none applied.
|
||||
pub(crate) fn plan_styles(layer: &Layer, comp: &Comp, cp: &CompPlan, what: &str, col: &mut Collector) -> Option<StylesPlan> {
|
||||
let ls = layer.layer_styles()?;
|
||||
let mut plan = StylesPlan::default();
|
||||
let groups: Vec<&PropGroup> = ls.groups().filter(|g| g.match_id != st::BLENDING).collect();
|
||||
if groups.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if !layer.can_have_styles() {
|
||||
col.lose(LossCategory::LayerStyles, format!("{what}: layer styles on a layer that takes none, not written"));
|
||||
return None;
|
||||
}
|
||||
if !ls.enabled {
|
||||
col.lose(LossCategory::LayerStyles, format!("{what}: Layer Styles switched off (the stored switch is not sampled), not written"));
|
||||
return None;
|
||||
}
|
||||
for g in groups {
|
||||
let Some(spec) = sm::by_ec(&g.match_id) else {
|
||||
col.lose(LossCategory::LayerStyles, format!("{what}: style {} has no After Effects counterpart", g.name));
|
||||
continue;
|
||||
};
|
||||
let mut recs = Vec::new();
|
||||
for prm in spec.params {
|
||||
let Some(prop) = g.get(prm.ec) else { continue };
|
||||
let full = spec.param_name(prm);
|
||||
if prm.conv == StyleConv::Gradient {
|
||||
let edited = !prop.keys.is_empty() || prop.expr.is_some() || model_default(spec.ec, prm.ec).is_some_and(|d| d != prop.value);
|
||||
if edited {
|
||||
col.lose(LossCategory::LayerStyles, format!("{what}: {full} (gradient colours are not decoded; After Effects' default gradient)"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(r) = plan_record(prm, full, prop, cp, what, col) {
|
||||
recs.push(r);
|
||||
}
|
||||
}
|
||||
plan.styles.push((spec.ae, recs, g.enabled));
|
||||
}
|
||||
if plan.styles.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Global Light: the composition's, on every styled layer.
|
||||
const ANGLE: &[f64] = &[st::DEFAULT_ANGLE];
|
||||
const ALTITUDE: &[f64] = &[st::DEFAULT_ALTITUDE];
|
||||
for (name, p, default) in [(sm::GLOBAL_ANGLE, &comp.global_light.angle, ANGLE), (sm::GLOBAL_ALTITUDE, &comp.global_light.altitude, ALTITUDE)] {
|
||||
let spec = StyleParam { ae: name, ec: name, conv: StyleConv::Number, default };
|
||||
if let Some(r) = plan_record(&spec, name.to_string(), p, cp, what, col) {
|
||||
plan.global.push(r);
|
||||
}
|
||||
}
|
||||
if let Some(adv) = ls.sub(st::BLENDING).and_then(|b| b.sub("advancedBlending")) {
|
||||
for prm in sm::ADVANCED_BLENDING {
|
||||
if let Some(p) = adv.get(prm.ec)
|
||||
&& let Some(r) = plan_record(prm, prm.ae.to_string(), p, cp, what, col)
|
||||
{
|
||||
plan.adv.push(r);
|
||||
}
|
||||
}
|
||||
if adv.get("knockout").is_some_and(|p| p.value != Value::Enum(0) || !p.keys.is_empty()) {
|
||||
col.lose(LossCategory::LayerStyles, format!("{what}: Knockout (After Effects has none)"));
|
||||
}
|
||||
}
|
||||
col.exported.layer_styles += plan.styles.len();
|
||||
Some(plan)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Emit.
|
||||
|
||||
/// The style record prototypes, built in code: full match name -> (`tdmn`, `tdbs`), and
|
||||
/// the keyed scalar record.
|
||||
pub(crate) struct StyleProtos {
|
||||
records: HashMap<String, (Chunk<'static>, Chunk<'static>)>,
|
||||
keyed: Chunk<'static>,
|
||||
}
|
||||
|
||||
impl StyleProtos {
|
||||
/// The records built in code from the style table (`style_defs`); the keyed form of a scalar
|
||||
/// takes `tdb4` bytes 5, 68 and 79 and the key list of a keyed one-component record.
|
||||
pub(crate) fn from_table() -> StyleProtos {
|
||||
use crate::export::synth::{KeyTemplate, RecSpec, class, tdbs, tdmn};
|
||||
let records = crate::export::style_defs::STYLE_RECORDS
|
||||
.iter()
|
||||
.map(|(name, dims, template, cls, limits)| {
|
||||
let template = if *template == 0 { KeyTemplate::Plain } else { KeyTemplate::Spatial(*template) };
|
||||
let spec = RecSpec { dims: *dims, template, class: *cls, limits: *limits, byte5: None };
|
||||
(name.to_string(), (tdmn(name), tdbs(&spec, false, 25_600)))
|
||||
})
|
||||
.collect();
|
||||
let scalar = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_NUMBER, limits: Some((0.0, 100.0)), byte5: None };
|
||||
StyleProtos { records, keyed: tdbs(&scalar, true, 25_600) }
|
||||
}
|
||||
|
||||
/// The `tdmn` + `tdbs` of one record.
|
||||
fn build(&self, r: &Record) -> R<[Chunk<'static>; 2]> {
|
||||
let (m, proto) = self.records.get(&r.name).ok_or_else(|| tpl("style record prototype missing"))?;
|
||||
let mut rec = proto.clone();
|
||||
match &r.value {
|
||||
RecValue::Static(v) => {
|
||||
let cdat = child_data(&mut rec, b"cdat")?;
|
||||
cdat.iter_mut().for_each(|b| *b = 0);
|
||||
for (i, x) in v.iter().enumerate() {
|
||||
put_f64(cdat, i * 8, *x)?;
|
||||
}
|
||||
}
|
||||
RecValue::Keys(keys) => {
|
||||
let ktdb4 = self.keyed.child(b"tdb4").and_then(|c| c.bytes()).ok_or_else(|| tpl("keyed style prototype without tdb4"))?;
|
||||
{
|
||||
let tdb4 = child_data(&mut rec, b"tdb4")?;
|
||||
for at in [5usize, 68, 79] {
|
||||
put_u8(tdb4, at, *ktdb4.get(at).ok_or_else(|| tpl("short tdb4"))?)?;
|
||||
}
|
||||
}
|
||||
let mut list = self.keyed.child_list(b"list").cloned().ok_or_else(|| tpl("keyed style prototype without keys"))?;
|
||||
let size = 48usize;
|
||||
let mut ldat = Vec::with_capacity(size * keys.len());
|
||||
for k in keys {
|
||||
ldat.extend(crate::export::emit::plain_record(1, k, size)?);
|
||||
}
|
||||
fill_key_list(&mut list, ldat, keys.len(), size)?;
|
||||
replace_cdat(&mut rec, list)?;
|
||||
}
|
||||
}
|
||||
if let Some((text, enabled)) = &r.expr {
|
||||
{
|
||||
let tdb4 = child_data(&mut rec, b"tdb4")?;
|
||||
put_u8(tdb4, 120, 1)?;
|
||||
put_u8(tdb4, 119, u8::from(!*enabled))?;
|
||||
}
|
||||
let kids = kids_mut(&mut rec)?;
|
||||
let at = kids.iter().position(|c| c.is(b"tdum")).unwrap_or(kids.len());
|
||||
kids.insert(at, Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
|
||||
}
|
||||
Ok([m.clone(), rec])
|
||||
}
|
||||
}
|
||||
|
||||
/// The node after the `tdmn` named `name` among `kids`.
|
||||
fn named_mut<'a>(kids: &'a mut [Chunk<'static>], name: &str) -> R<&'a mut Chunk<'static>> {
|
||||
let i = kids.iter().position(|c| is_tdmn(c, name)).ok_or_else(|| tpl("layer styles group incomplete"))?;
|
||||
kids.get_mut(i + 1).ok_or_else(|| tpl("layer styles group incomplete"))
|
||||
}
|
||||
|
||||
fn set_flags(g: &mut Chunk<'static>, flags: u32) -> R<()> {
|
||||
put_u32(child_data(g, b"tdsb")?, 0, flags)
|
||||
}
|
||||
|
||||
/// Inserts `recs` before the `tdmn` named `before` (or before `ADBE Group End`).
|
||||
fn insert_records(protos: &StyleProtos, g: &mut Chunk<'static>, recs: &[Record], before: &str) -> R<()> {
|
||||
let mut built = Vec::with_capacity(recs.len() * 2);
|
||||
for r in recs {
|
||||
built.extend(protos.build(r)?);
|
||||
}
|
||||
let kids = kids_mut(g)?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, before)).ok_or_else(|| tpl("layer styles group incomplete"))?;
|
||||
kids.splice(at..at, built);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies `plan` to the layer's `ADBE Layer Styles` group.
|
||||
pub(crate) fn put_styles(protos: &StyleProtos, layr: &mut Chunk<'static>, plan: &StylesPlan) -> R<()> {
|
||||
let root = crate::export::tree::list_mut(layr, b"tdgp")?;
|
||||
let ls = named_mut(kids_mut(root)?, sm::GROUP)?;
|
||||
set_flags(ls, sm::FLAGS_ON)?;
|
||||
{
|
||||
let bo = named_mut(kids_mut(ls)?, sm::BLEND_OPTIONS)?;
|
||||
set_flags(bo, sm::FLAGS_ON)?;
|
||||
insert_records(protos, bo, &plan.global, sm::ADV_BLEND)?;
|
||||
let adv = named_mut(kids_mut(bo)?, sm::ADV_BLEND)?;
|
||||
insert_records(protos, adv, &plan.adv, GROUP_END)?;
|
||||
}
|
||||
for (prefix, recs, on) in &plan.styles {
|
||||
let g = named_mut(kids_mut(ls)?, &format!("{prefix}/enabled"))?;
|
||||
set_flags(g, if *on { sm::FLAGS_ON } else { sm::FLAGS_OFF })?;
|
||||
insert_records(protos, g, recs, GROUP_END)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
//! Chunks the exporter builds in code instead of copying them from projects After Effects saved.
|
||||
//!
|
||||
//! Every byte written here is a decoded field (`docs/aep-format.md`), a named constant with its
|
||||
//! evidence, or zero where After Effects was shown to accept zero (the read-backs listed in
|
||||
//! `docs/aep-export.md`, "Built in code").
|
||||
|
||||
use crate::export::tree::{Fixed, R, put_u32};
|
||||
use crate::{Body, Chunk};
|
||||
|
||||
/// `tdmn`: a match name padded to 40 bytes (at most 39 bytes of the name, so that a NUL remains).
|
||||
pub(crate) fn tdmn(name: &str) -> Chunk<'static> {
|
||||
let mut b = vec![0u8; 40];
|
||||
for (slot, c) in b.iter_mut().zip(name.bytes().take(39)) {
|
||||
*slot = c;
|
||||
}
|
||||
Chunk::data(*b"tdmn", b)
|
||||
}
|
||||
|
||||
/// The match name that closes a property group.
|
||||
pub(crate) const GROUP_END: &str = "ADBE Group End";
|
||||
|
||||
/// The match name in a `tdmn`: the bytes up to the first NUL as UTF-8, invalid sequences
|
||||
/// replaced, as the importer reads it (`container::typed`). After Effects writes ASCII here
|
||||
/// (aep-format.md 3.4; every `tdmn` of the corpus is ASCII); `None` when `c` is not a data chunk.
|
||||
pub(crate) fn tdmn_name(c: &Chunk<'_>) -> Option<String> {
|
||||
let b = c.bytes()?;
|
||||
let end = b.iter().position(|x| *x == 0).unwrap_or(b.len());
|
||||
Some(String::from_utf8_lossy(b.get(..end)?).into_owned())
|
||||
}
|
||||
|
||||
/// Whether `c` is a `tdmn` naming `name`.
|
||||
pub(crate) fn is_tdmn(c: &Chunk<'_>, name: &str) -> bool {
|
||||
c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(name)
|
||||
}
|
||||
|
||||
/// The user name of a property that has none (`-_0_/-`, aep-format.md 3.4).
|
||||
pub(crate) const NO_NAME: &str = "-_0_/-";
|
||||
|
||||
/// `tdsn`: the user name, a nested chunk holding one `Utf8`.
|
||||
pub(crate) fn tdsn(name: &str) -> Chunk<'static> {
|
||||
utf8_in(*b"tdsn", name)
|
||||
}
|
||||
|
||||
/// A nested chunk `id` holding one `Utf8` with `text` (`tdsn`, `fnam`, `pdnm`).
|
||||
pub(crate) fn utf8_in(id: [u8; 4], text: &str) -> Chunk<'static> {
|
||||
Chunk { id, body: Body::Chunks(vec![Chunk::data(*b"Utf8", text.as_bytes().to_vec())]), pad: None }
|
||||
}
|
||||
|
||||
/// How a property's keys are stored (`tdb4` byte 7, aep-format.md 3.5).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum KeyTemplate {
|
||||
/// Value and type-major ease doubles: Opacity, Rotation, Scale, sliders.
|
||||
Plain,
|
||||
/// Ease, value and tangents; byte 7 is 3 on positions and points, 1 on colours and paths.
|
||||
Spatial(u8),
|
||||
}
|
||||
|
||||
/// The u32 at `tdb4` bytes 8..11. Its two u16 halves follow the kind of property (aep-format.md
|
||||
/// 3.4, "class word"); without it After Effects drops a property's keys (read-back e1-bz5).
|
||||
pub(crate) mod class {
|
||||
/// Transform Scale, Rotation and Opacity; the other one-dimensional layer properties.
|
||||
pub const LAYER_SCALAR: u32 = 0x0001_ffff;
|
||||
/// Positions and points (spatial, no limits); effect sliders and angles.
|
||||
pub const SPATIAL: u32 = 0xffff_ffff;
|
||||
/// Effect sliders (integer, fixed, float) and angles.
|
||||
pub const EFFECT_NUMBER: u32 = 0xffff_ffff;
|
||||
/// Effect checkboxes and popups.
|
||||
pub const EFFECT_CHOICE: u32 = 0x0001_0004;
|
||||
/// Colours.
|
||||
pub const COLOR: u32 = 0x0002_ffff;
|
||||
/// Effect layer parameters, groups and buttons.
|
||||
pub const EFFECT_OTHER: u32 = 0x0001_0000;
|
||||
/// Arbitrary data (Hue/Saturation, Levels, Curves, Mesh Warp).
|
||||
pub const ARBITRARY: u32 = 0x0006_0007;
|
||||
/// Mask and shape paths.
|
||||
pub const PATH: u32 = 0x0002_0007;
|
||||
}
|
||||
|
||||
/// Byte 5 bits 1..3 of a spatial property, next to the static bit 0: `0x0e` on positions and
|
||||
/// points (`0x0f` static, `0x0e` keyed: Anchor Point, Position, Gradient Ramp's points), `0x06` on
|
||||
/// colours (`0x07` / `0x06`: Tint's colours). Meaning not decoded.
|
||||
fn spatial_byte5(template: u8) -> u8 {
|
||||
if template == 3 { 0x0e } else { 0x06 }
|
||||
}
|
||||
|
||||
/// What a property record needs to know about its property.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct RecSpec {
|
||||
/// Components of a value (`tdb4` byte 3).
|
||||
pub dims: u8,
|
||||
pub template: KeyTemplate,
|
||||
/// `tdb4` bytes 8..11 (see [`class`]).
|
||||
pub class: u32,
|
||||
/// `tdum` / `tduM`, written when the property has them (Scale `0, 0`, Opacity `0, 100`).
|
||||
pub limits: Option<(f64, f64)>,
|
||||
/// `tdb4` byte 5 of the static record when it is not the one [`tdb4`] derives (bits 1..3 are
|
||||
/// not decoded; the keyed record clears bit 0).
|
||||
pub byte5: Option<u8>,
|
||||
}
|
||||
|
||||
impl RecSpec {
|
||||
/// Bytes of a static value (`cdat`): the key record without its 8-byte header, value first,
|
||||
/// the rest zero (aep-format.md 3.4 / 3.5: `40 n` plain, `24 n` spatial).
|
||||
pub fn cdat_len(&self) -> usize {
|
||||
let n = usize::from(self.dims);
|
||||
match self.template {
|
||||
KeyTemplate::Plain => 40 * n,
|
||||
KeyTemplate::Spatial(_) => 24 * n,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of one key record (aep-format.md 3.5).
|
||||
pub fn key_len(&self) -> usize {
|
||||
let n = usize::from(self.dims);
|
||||
match self.template {
|
||||
KeyTemplate::Plain => 8 + 40 * n,
|
||||
KeyTemplate::Spatial(_) => 56 + 24 * n,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 124-byte `tdb4` header of a property (aep-format.md 3.4). The decoded bytes, the class
|
||||
/// word and the constant doubles at 16..56 are written; After Effects reads the other bytes as
|
||||
/// zero (read-back e1-ztdb4d).
|
||||
pub(crate) fn tdb4(spec: &RecSpec, keyed: bool, time_scale: u32) -> Vec<u8> {
|
||||
tdb4_layout(spec, keyed, time_scale).finish(|| "tdb4".to_string())
|
||||
}
|
||||
|
||||
/// The 124-byte `tdb4` property header layout for a record spec.
|
||||
fn tdb4_layout(spec: &RecSpec, keyed: bool, time_scale: u32) -> Fixed {
|
||||
let mut b = Fixed::zeroed(124);
|
||||
b.put(0, &[0xdb, 0x99, 0x00, spec.dims]);
|
||||
let spatial = match spec.template {
|
||||
KeyTemplate::Plain => 0,
|
||||
KeyTemplate::Spatial(t) => t,
|
||||
};
|
||||
let byte5 = match spec.byte5 {
|
||||
Some(b) => (b & !0x01) | u8::from(!keyed),
|
||||
None => (if spatial == 0 { 0 } else { spatial_byte5(spatial) }) | u8::from(!keyed),
|
||||
};
|
||||
b.put(5, &[byte5]);
|
||||
b.put(7, &[spatial]);
|
||||
b.put(8, &spec.class.to_be_bytes());
|
||||
b.put(12, &time_scale.to_be_bytes());
|
||||
// Every record After Effects writes carries 0.0001 and four 1.0 here; without them a roving
|
||||
// key reads back at time zero instead of its retimed place (read-back s14-re-keyframes).
|
||||
b.put(16, &1e-4f64.to_be_bytes());
|
||||
for at in [24, 32, 40, 48] {
|
||||
b.put(at, &1.0f64.to_be_bytes());
|
||||
}
|
||||
b.put(68, &[u8::from(keyed)]);
|
||||
// Set on a static spatial property, cleared once it is keyed (aep-format.md 3.4, byte 79).
|
||||
b.put(79, &[u8::from(spatial != 0 && !keyed)]);
|
||||
b
|
||||
}
|
||||
|
||||
/// A key list (`LIST list`: `lhd3` + `ldat`) of `count` records of `size` bytes (aep-format.md
|
||||
/// 3.5): word 0 `0x00d00bee`, word 2 the count, word 3 the blocks of four (at least one), word 4
|
||||
/// the size, words 5 and 7 the capacity (the count rounded up to four, at least two), word 6 one.
|
||||
pub(crate) fn key_list(size: u32, count: u32, records: Vec<u8>) -> Chunk<'static> {
|
||||
let lhd3 = key_list_header(size, count).finish(|| "lhd3".to_string());
|
||||
Chunk::list(*b"list", vec![Chunk::data(*b"lhd3", lhd3), Chunk::data(*b"ldat", records)])
|
||||
}
|
||||
|
||||
/// The 52-byte `lhd3` key list header for `count` records of `size` bytes.
|
||||
fn key_list_header(size: u32, count: u32) -> Fixed {
|
||||
let mut lhd3 = Fixed::zeroed(52);
|
||||
lhd3.put(0, &0x00d0_0bee_u32.to_be_bytes());
|
||||
lhd3.put(24, &1u32.to_be_bytes());
|
||||
lhd3.apply(|d| put_key_counts(d, count, size));
|
||||
lhd3
|
||||
}
|
||||
|
||||
/// Sets the count words of a key list header for `count` keys of `size` bytes.
|
||||
pub(crate) fn put_key_counts(lhd3: &mut [u8], count: u32, size: u32) -> R<()> {
|
||||
let capacity = count.div_ceil(4).saturating_mul(4).max(2);
|
||||
put_counts(lhd3, count, count.div_ceil(4).max(1), size, capacity, capacity)
|
||||
}
|
||||
|
||||
/// Sets the count words of a list header: word 2 the record count, word 3 `blocks`, word 4 the
|
||||
/// record size, word 5 `w5`, word 7 the capacity. A key list has `w5` = the capacity; a path
|
||||
/// list counts vertices: `blocks` = `w5` = the vertex count, the capacity four times it (090:
|
||||
/// 12 points, 4, 4 and 16; aep-format.md 3.5).
|
||||
pub(crate) fn put_counts(lhd3: &mut [u8], count: u32, blocks: u32, size: u32, w5: u32, capacity: u32) -> R<()> {
|
||||
put_u32(lhd3, 8, count)?;
|
||||
put_u32(lhd3, 12, blocks)?;
|
||||
put_u32(lhd3, 16, size)?;
|
||||
put_u32(lhd3, 20, w5)?;
|
||||
put_u32(lhd3, 28, capacity)
|
||||
}
|
||||
|
||||
/// A property record (`LIST tdbs`) with a zero static value or an empty key list, for the
|
||||
/// exporter to fill: `tdsb` 1 (written), no user name, the header, then `cdat` or the key list,
|
||||
/// then the limits.
|
||||
pub(crate) fn tdbs(spec: &RecSpec, keyed: bool, time_scale: u32) -> Chunk<'static> {
|
||||
let mut kids = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(NO_NAME), Chunk::data(*b"tdb4", tdb4(spec, keyed, time_scale))];
|
||||
if keyed {
|
||||
kids.push(key_list(u32::try_from(spec.key_len()).unwrap_or(u32::MAX), 0, Vec::new()));
|
||||
} else {
|
||||
kids.push(Chunk::data(*b"cdat", vec![0u8; spec.cdat_len()]));
|
||||
}
|
||||
if let Some((lo, hi)) = spec.limits {
|
||||
kids.push(Chunk::data(*b"tdum", lo.to_be_bytes().to_vec()));
|
||||
kids.push(Chunk::data(*b"tduM", hi.to_be_bytes().to_vec()));
|
||||
}
|
||||
Chunk::list(*b"tdbs", kids)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_record_has_the_decoded_layout() {
|
||||
let pos = RecSpec { dims: 3, template: KeyTemplate::Spatial(3), class: class::SPATIAL, limits: None, byte5: None };
|
||||
let h = tdb4(&pos, false, 25_600);
|
||||
assert_eq!(&h[..8], &[0xdb, 0x99, 0, 3, 0, 0x0f, 0, 3]);
|
||||
assert_eq!(&h[8..16], &[0xff, 0xff, 0xff, 0xff, 0, 0, 0x64, 0]);
|
||||
assert_eq!((h[68], h[79]), (0, 1));
|
||||
// A roving key needs these to keep its time (read-back s14-re-keyframes).
|
||||
assert_eq!(&h[16..24], &1e-4f64.to_be_bytes());
|
||||
assert!(h[24..56].chunks(8).all(|d| d == 1.0f64.to_be_bytes()));
|
||||
assert_eq!(pos.cdat_len(), 72);
|
||||
assert_eq!(pos.key_len(), 128);
|
||||
let opacity = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: Some((0.0, 100.0)), byte5: None };
|
||||
let k = tdb4(&opacity, true, 25_600);
|
||||
assert_eq!((k[5], k[7], k[68]), (0, 0, 1));
|
||||
let rec = tdbs(&opacity, false, 25_600);
|
||||
let ids: Vec<[u8; 4]> = rec.children().iter().map(|c| c.id).collect();
|
||||
assert_eq!(ids, [*b"tdsb", *b"tdsn", *b"tdb4", *b"cdat", *b"tdum", *b"tduM"]);
|
||||
assert_eq!(rec.child(b"cdat").and_then(|c| c.bytes()).map(<[u8]>::len), Some(40));
|
||||
}
|
||||
|
||||
/// Every record header fits.
|
||||
#[test]
|
||||
fn every_record_header_fits() {
|
||||
for dims in 0..=u8::MAX {
|
||||
for template in [KeyTemplate::Plain, KeyTemplate::Spatial(1), KeyTemplate::Spatial(3), KeyTemplate::Spatial(u8::MAX)] {
|
||||
for byte5 in [None, Some(0xff)] {
|
||||
let spec = RecSpec { dims, template, class: u32::MAX, limits: None, byte5 };
|
||||
assert!(tdb4_layout(&spec, false, u32::MAX).error().is_none() && tdb4_layout(&spec, true, 0).error().is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (size, count) in [(0, 0), (u32::MAX, u32::MAX), (48, 5)] {
|
||||
let h = key_list_header(size, count);
|
||||
assert!(h.error().is_none());
|
||||
assert_eq!(h.finish(String::new).len(), 52);
|
||||
}
|
||||
}
|
||||
|
||||
/// A match name reads as the importer reads it.
|
||||
#[test]
|
||||
fn a_match_name_reads_as_the_importer_reads_it() {
|
||||
let m = tdmn("ADBE Group End");
|
||||
assert_eq!(tdmn_name(&m).as_deref(), Some(GROUP_END));
|
||||
assert!(is_tdmn(&m, GROUP_END) && !is_tdmn(&m, "ADBE Group") && !is_tdmn(&tdsn(GROUP_END), GROUP_END));
|
||||
// At most 39 bytes, so that a NUL remains.
|
||||
let long = "x".repeat(50);
|
||||
assert_eq!(tdmn_name(&tdmn(&long)).map(|n| n.len()), Some(39));
|
||||
// Not ASCII (After Effects writes ASCII): UTF-8, invalid bytes replaced, as on import.
|
||||
let odd = Chunk::data(*b"tdmn", vec![b'A', 0xc3, 0xa9, 0xff, 0, b'B']);
|
||||
assert_eq!(tdmn_name(&odd).as_deref(), Some("A\u{e9}\u{fffd}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_list_header_counts_and_rounds() {
|
||||
let l = key_list(48, 5, vec![0; 240]);
|
||||
let h = l.child(b"lhd3").and_then(|c| c.bytes()).unwrap();
|
||||
let w = |i: usize| u32::from_be_bytes(h[i * 4..i * 4 + 4].try_into().unwrap());
|
||||
assert_eq!((w(0), w(2), w(3), w(4), w(5), w(6), w(7)), (0x00d0_0bee, 5, 2, 48, 8, 1, 8));
|
||||
assert_eq!(h.len(), 52);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! The prototypes the exporter clones and edits, all built in code: the project skeleton
|
||||
//! (`base`), the layer blocks (`skeleton`, `tree_defs`), and the records of Transform, masks,
|
||||
//! effects, layer styles, footage, text and text animators (see `docs/aep-export.md`). Nothing is
|
||||
//! read from a file After Effects wrote; each layout was checked by After Effects reading the
|
||||
//! export back.
|
||||
|
||||
use crate::{AepFile, Chunk};
|
||||
|
||||
use crate::export::tree::{R, tpl};
|
||||
|
||||
/// The chunks cloned by the exporter.
|
||||
pub(crate) struct Template {
|
||||
/// The whole base project; its `Fold` children are replaced by the export.
|
||||
pub file: AepFile<'static>,
|
||||
/// The base composition item without its layer blocks.
|
||||
pub comp_shell: Chunk<'static>,
|
||||
/// Index in the shell's children where the layer blocks go.
|
||||
pub layer_at: usize,
|
||||
/// `Layr`, `Ewst` and the f-records that follow the layer `L`.
|
||||
pub layer_block: Vec<Chunk<'static>>,
|
||||
/// The footage item of the solid `L` (inside `Solids`).
|
||||
pub solid_item: Chunk<'static>,
|
||||
/// The `Solids` folder item.
|
||||
pub folder_item: Chunk<'static>,
|
||||
/// The f-records that follow a footage item inside a folder.
|
||||
pub fset: Vec<Chunk<'static>>,
|
||||
/// The `FEE ` list that follows a composition item.
|
||||
pub fee: Chunk<'static>,
|
||||
/// `tdmn`, `tdbs` pairs of the five Transform properties with a static value.
|
||||
pub stat: Vec<Chunk<'static>>,
|
||||
/// The same with two keys.
|
||||
pub keyd: Vec<Chunk<'static>>,
|
||||
/// The layer block of a null layer.
|
||||
pub null_block: Vec<Chunk<'static>>,
|
||||
/// The hidden solid item of a null layer.
|
||||
pub null_item: Chunk<'static>,
|
||||
/// The mask prototypes (fixtures 091, 093, 208).
|
||||
pub masks: crate::export::masks::MaskProtos,
|
||||
/// The effect prototypes (cases 356-397).
|
||||
pub effects: crate::export::effects::FxProtos,
|
||||
/// The footage item prototypes (cases 351, 353, 603-607).
|
||||
pub footage: crate::export::footage::FtProtos,
|
||||
/// The layer blocks of a point (110) and a box (245) text layer.
|
||||
pub text_point: Vec<Chunk<'static>>,
|
||||
pub text_box: Vec<Chunk<'static>>,
|
||||
/// The text animator prototypes (579, 580-592, 728).
|
||||
pub anims: crate::export::textanim::AnimProtos,
|
||||
/// The marker group (`tdmn ADBE Marker` + `LIST mrst`) of fixture 249.
|
||||
pub marker_group: Vec<Chunk<'static>>,
|
||||
/// The layer blocks of a two-node camera (256), a spot (254) and a point light (252).
|
||||
pub camera_block: Vec<Chunk<'static>>,
|
||||
pub spot_block: Vec<Chunk<'static>>,
|
||||
pub point_block: Vec<Chunk<'static>>,
|
||||
/// Camera and light option records (342-345, 254).
|
||||
pub options: crate::export::camlight::OptionProtos,
|
||||
/// Shape layer, item and record prototypes (519, 240, 451-471, 239, 242).
|
||||
pub shapes: crate::export::shapes::ShapeProtos,
|
||||
/// Layer-style record prototypes (977, 976).
|
||||
pub styles: crate::export::styles::StyleProtos,
|
||||
}
|
||||
|
||||
/// The `tdmn`, `tdbs` pairs of the five Transform properties, static or keyed, built in code
|
||||
/// (aep-format.md 3.4): Anchor Point and Position spatial, Scale, Rotation and Opacity plain;
|
||||
/// Scale and Opacity carry their limits.
|
||||
fn transform_records(keyed: bool) -> Vec<Chunk<'static>> {
|
||||
use crate::export::plan::PropKind;
|
||||
use crate::export::synth::{KeyTemplate, RecSpec, class};
|
||||
PropKind::ALL
|
||||
.iter()
|
||||
.flat_map(|k| {
|
||||
let spec = match k {
|
||||
PropKind::Anchor | PropKind::Position => {
|
||||
RecSpec { dims: 3, template: KeyTemplate::Spatial(3), class: class::SPATIAL, limits: None, byte5: None }
|
||||
}
|
||||
PropKind::Scale => RecSpec { dims: 3, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: Some((0.0, 0.0)), byte5: None },
|
||||
PropKind::Rotation => RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: None, byte5: None },
|
||||
PropKind::Opacity => RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: Some((0.0, 100.0)), byte5: None },
|
||||
};
|
||||
[crate::export::synth::tdmn(k.match_name()), crate::export::synth::tdbs(&spec, keyed, 25_600)]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The template every export clones from: built by the first export of the process and kept, as
|
||||
/// [`Template::load`] always builds the same prototypes and nothing changes them afterwards (the
|
||||
/// exporter only reads them through `&Template` and clones what it edits).
|
||||
///
|
||||
/// Concurrent exports are safe: the `static` requires `Template: Send + Sync`, which the compiler
|
||||
/// checks. Exports that race on the first call each build a template; one is kept and the others
|
||||
/// are dropped, and all of them are equal. A failed build is not kept, so the next export tries
|
||||
/// again and reports the same error.
|
||||
pub(crate) fn shared() -> R<&'static Template> {
|
||||
static SHARED: std::sync::OnceLock<Template> = std::sync::OnceLock::new();
|
||||
if let Some(t) = SHARED.get() {
|
||||
return Ok(t);
|
||||
}
|
||||
// A failed build returns here, before `get_or_init`, so it is never kept.
|
||||
let t = Template::load()?;
|
||||
Ok(SHARED.get_or_init(|| t))
|
||||
}
|
||||
|
||||
impl Template {
|
||||
pub fn load() -> R<Template> {
|
||||
let file = AepFile { chunks: crate::export::base::project_chunks(), trailer: std::borrow::Cow::Borrowed(&[]) };
|
||||
let fee = crate::export::base::fee();
|
||||
let fset = crate::export::skeleton::f_records();
|
||||
let folder_item = crate::export::base::folder_item();
|
||||
let solid_item = crate::export::base::solid_item();
|
||||
let (comp_shell, first) = crate::export::base::comp_shell();
|
||||
let layer_block = crate::export::skeleton::av_layer();
|
||||
let stat = transform_records(false);
|
||||
let keyd = transform_records(true);
|
||||
// A null layer has the AV layer's block; `ldta` marks it (byte 38 bit 0x80).
|
||||
let null_block = crate::export::skeleton::av_layer();
|
||||
// The hidden solid of a null layer is an ordinary solid item (022).
|
||||
let null_item = crate::export::base::solid_item();
|
||||
let masks = crate::export::masks::MaskProtos::build();
|
||||
let effects = crate::export::effects::FxProtos::build();
|
||||
let styles = crate::export::styles::StyleProtos::from_table();
|
||||
let footage = crate::export::footage::FtProtos::build();
|
||||
// Point (110) and box (245) text layers with a document built in code.
|
||||
use crate::export::{textdoc, textproto};
|
||||
let text_point = crate::export::skeleton::text_layer(&textdoc::write(&textproto::document(false)));
|
||||
let text_box = crate::export::skeleton::text_layer(&textdoc::write(&textproto::document(true)));
|
||||
let anims = crate::export::textanim::AnimProtos {
|
||||
group: crate::export::tree_spec::build(crate::export::tree_defs::TEXT_ANIMATORS),
|
||||
animator: crate::export::tree_spec::build(crate::export::tree_defs::TEXT_ANIMATOR),
|
||||
records: crate::export::skeleton::pairs(crate::export::tree_defs::TEXT_ANIMATOR_RECORDS),
|
||||
};
|
||||
let marker_group = crate::export::skeleton::marker_group();
|
||||
use crate::export::{skeleton, tree_defs};
|
||||
let camera_block = skeleton::layer_block(tree_defs::CAMERA_ROOT);
|
||||
let spot_block = skeleton::layer_block(tree_defs::SPOT_ROOT);
|
||||
let point_block = skeleton::layer_block(tree_defs::POINT_ROOT);
|
||||
let records = skeleton::pairs(tree_defs::OPTIONS).into_iter().map(|(name, [_, node])| (name, node)).collect();
|
||||
let options = crate::export::camlight::OptionProtos { records };
|
||||
// The key list of the keyed Opacity prototype (one-component plain keys; its header is
|
||||
// rewritten for every keyed shape property).
|
||||
let key_list = keyd
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|c| c.is_list(b"tdbs"))
|
||||
.and_then(|c| c.child_list(b"list"))
|
||||
.cloned()
|
||||
.ok_or_else(|| tpl("keyed prototype without a key list"))?;
|
||||
let shapes = crate::export::shapes::ShapeProtos {
|
||||
block: skeleton::layer_block(tree_defs::SHAPE_ROOT),
|
||||
items: skeleton::pairs(tree_defs::SHAPE_ITEMS),
|
||||
records: skeleton::pairs(tree_defs::SHAPE_RECORDS),
|
||||
key_list,
|
||||
};
|
||||
Ok(Template {
|
||||
file,
|
||||
comp_shell,
|
||||
layer_at: first,
|
||||
layer_block,
|
||||
solid_item,
|
||||
folder_item,
|
||||
fset,
|
||||
fee,
|
||||
stat,
|
||||
keyd,
|
||||
null_block,
|
||||
null_item,
|
||||
masks,
|
||||
effects,
|
||||
footage,
|
||||
text_point,
|
||||
text_box,
|
||||
anims,
|
||||
marker_group,
|
||||
camera_block,
|
||||
spot_block,
|
||||
point_block,
|
||||
options,
|
||||
shapes,
|
||||
styles,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! Text layers: the layer block of a point (110) or box (245) text layer, built in code
|
||||
//! (`skeleton::text_layer`, `textproto`), with its text document rewritten from the layer's Source
|
||||
//! Text (`docs/aep-format.md` 3.10, `docs/aep-export.md` R32-R34):
|
||||
//!
|
||||
//! * the text (paragraphs end with `\r`, the last one too), the paragraph runs with their
|
||||
//! justification, the style runs with font, size, faux bold / italic, automatic or explicit
|
||||
//! leading, tracking, caps, fill and stroke colour;
|
||||
//! * fonts other than the prototype's are appended to the font list (its own entries, which the
|
||||
//! rest of the document refers to by index, keep their places);
|
||||
//! * a box text's frame (16 points tracing the rectangle, 245);
|
||||
//! * the composed layout (`/1/1[0]/1/2`) is left empty: After Effects lays the text out again
|
||||
//! when it opens the project (t1-t3).
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_keyframe::text_doc::{BaselineOption, Composer, Direction, Justify, Kerning, TextDoc};
|
||||
use effectcraft_project::{Layer, Node, PropGroup};
|
||||
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::textdoc::{TNode, boolean, int, number, string};
|
||||
|
||||
/// The prototype's own font (index 0 of its font list).
|
||||
const PROTO_FONT: &str = "TimesNewRomanPSMT";
|
||||
/// The longest text written (characters).
|
||||
const MAX_CHARS: usize = 1 << 20;
|
||||
|
||||
/// One style run in the file's terms.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct StyleOut {
|
||||
pub font: String,
|
||||
pub size: f64,
|
||||
pub fill: [f64; 3],
|
||||
pub stroke: [f64; 3],
|
||||
pub tracking: f64,
|
||||
/// `None` = automatic leading.
|
||||
pub leading: Option<f64>,
|
||||
pub faux_bold: bool,
|
||||
pub faux_italic: bool,
|
||||
/// 0 normal, 1 small caps, 2 all caps.
|
||||
pub caps: i64,
|
||||
/// Style slot `/13`: 0 normal, 1 superscript, 2 subscript (526-528).
|
||||
pub script: i64,
|
||||
/// Slots `/6` and `/7`: horizontal and vertical scale as factors (539, 540).
|
||||
pub h_scale: f64,
|
||||
pub v_scale: f64,
|
||||
/// Slot `/9`: baseline shift in pixels.
|
||||
pub baseline_shift: f64,
|
||||
/// Slot `/11`: automatic kerning, 0 none, 1 metrics, 2 optical (541-543).
|
||||
pub auto_kern: i64,
|
||||
/// Slot `/18`: standard ligatures (555).
|
||||
pub ligatures: bool,
|
||||
/// Slot `/36`: tsume as a fraction (553).
|
||||
pub tsume: f64,
|
||||
/// Slots `/56`, `/57`: whether fill and stroke are drawn (544-546).
|
||||
pub apply_fill: bool,
|
||||
pub apply_stroke: bool,
|
||||
/// Slot `/63`: stroke width in pixels; `None` keeps the prototype's value.
|
||||
pub stroke_width: Option<f64>,
|
||||
/// Slot `/58`: stroke over fill (one switch for the whole text in EffectCraft; 550).
|
||||
pub stroke_over_fill: bool,
|
||||
}
|
||||
|
||||
/// One paragraph in the file's terms (paragraph dictionary `RUN/5/0[n]/0/0/5`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct ParaOut {
|
||||
/// `/0`: 0 left, 1 right, 2 centre, 3-6 justified with the last line left / right / centre /
|
||||
/// justified.
|
||||
pub justify: i64,
|
||||
/// `/1` first-line indent, `/2` start indent, `/3` end indent, `/4` space before, `/5` space
|
||||
/// after, in pixels.
|
||||
pub indents: [f64; 5],
|
||||
/// `/21`: Roman hanging punctuation (558).
|
||||
pub hanging: bool,
|
||||
/// `/29`: the every-line composer (557, 559).
|
||||
pub every_line: bool,
|
||||
/// `/33`: 0 left to right, 1 right to left (569).
|
||||
pub direction: i64,
|
||||
}
|
||||
|
||||
/// A text document in the file's terms.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct TextPlan {
|
||||
/// The stored text: paragraphs separated and ended by `\r`.
|
||||
pub text: String,
|
||||
/// (characters, style), covering the text including the final `\r`.
|
||||
pub runs: Vec<(usize, StyleOut)>,
|
||||
/// (characters including the `\r`, paragraph settings).
|
||||
pub paras: Vec<(usize, ParaOut)>,
|
||||
/// Box text: left, top, width, height in layer pixels.
|
||||
pub frame: Option<[f64; 4]>,
|
||||
/// The text animators (planned with the layer's time base, `textanim.rs`).
|
||||
pub animators: Vec<crate::export::textanim::AnimPlan>,
|
||||
/// The Source Text expression and its enable switch.
|
||||
pub expr: Option<(String, bool)>,
|
||||
}
|
||||
|
||||
/// Where a text value is written, for the loss report.
|
||||
struct At<'a, 'c> {
|
||||
what: &'a str,
|
||||
col: &'c mut Collector,
|
||||
}
|
||||
|
||||
impl At<'_, '_> {
|
||||
/// `v` limited to `lo..=hi` (a value that is not a number becomes `default`); a change is reported.
|
||||
fn fit(&mut self, v: f64, (lo, hi): (f64, f64), default: f64, field: &str) -> f64 {
|
||||
let out = if v.is_finite() { v.clamp(lo, hi) } else { default };
|
||||
if out.to_bits() != v.to_bits() {
|
||||
self.col.lose(LossCategory::TextLayers, format!("{}: {field} {v} is outside {lo} to {hi}, written as {out}", self.what));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The colour channels limited to 0..1, without alpha (a text colour in After Effects has none);
|
||||
/// a change is reported.
|
||||
fn rgb(&mut self, c: [f32; 4], field: &str) -> [f64; 3] {
|
||||
let [r, g, b, a] = c.map(f64::from);
|
||||
if a.to_bits() != 1f64.to_bits() {
|
||||
self.col.lose(LossCategory::TextLayers, format!("{}: the {field} opacity {a} is not written (text colours have no alpha)", self.what));
|
||||
}
|
||||
let name = format!("{field} channel");
|
||||
[self.fit(r, (0.0, 1.0), 0.0, &name), self.fit(g, (0.0, 1.0), 0.0, &name), self.fit(b, (0.0, 1.0), 0.0, &name)]
|
||||
}
|
||||
}
|
||||
|
||||
/// Plans the text of a text layer and reports what the document cannot hold.
|
||||
pub(crate) fn plan_text(layer: &Layer, comp_name: &str, col: &mut Collector) -> Option<TextPlan> {
|
||||
let what = format!("{comp_name}: '{}'", layer.name);
|
||||
let Some(text) = layer.props.sub("text") else {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: a text layer without text properties"));
|
||||
return None;
|
||||
};
|
||||
let Some(st) = text.prop("sourceText") else {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: a text layer without Source Text"));
|
||||
return None;
|
||||
};
|
||||
if !st.keys.is_empty() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not written (the first key's text is)"));
|
||||
}
|
||||
let value = st.keys.first().map(|k| &k.value).unwrap_or(&st.value);
|
||||
let Value::Text(doc) = value else {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text holds no text document"));
|
||||
return None;
|
||||
};
|
||||
report_extras(text, &what, col);
|
||||
let mut plan = plan_doc(doc, &what, col);
|
||||
// Written enabled or disabled, as on any other property.
|
||||
plan.expr = st.expr.as_ref().filter(|e| !e.text.is_empty()).map(|e| (e.text.clone(), e.enabled));
|
||||
if plan.expr.is_some() {
|
||||
col.exported.expressions = col.exported.expressions.saturating_add(1);
|
||||
}
|
||||
Some(plan)
|
||||
}
|
||||
|
||||
/// Path / More Options that hold anything other than a new text layer's defaults are not
|
||||
/// written (animators are, `textanim.rs`).
|
||||
fn report_extras(text: &PropGroup, what: &str, col: &mut Collector) {
|
||||
let mut next = 1u64;
|
||||
let reference = effectcraft_project::build::text(&mut effectcraft_project::build::Ids(&mut next), TextDoc::default());
|
||||
for node in &text.children {
|
||||
let Node::Group(g) = node else { continue };
|
||||
match g.match_id.as_str() {
|
||||
"pathOptions" | "moreOptions" => {
|
||||
let def = reference.children.iter().find_map(|n| match n {
|
||||
Node::Group(r) if r.match_id == g.match_id => Some(r),
|
||||
_ => None,
|
||||
});
|
||||
if differs(g, def, 0) {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: {} are not written", g.name));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `g` holds keys, expressions or values other than those of `def` (the same group of a
|
||||
/// new text layer).
|
||||
fn differs(g: &PropGroup, def: Option<&PropGroup>, depth: usize) -> bool {
|
||||
if depth > 32 {
|
||||
return true;
|
||||
}
|
||||
g.children.iter().any(|n| match n {
|
||||
Node::Group(s) => {
|
||||
let d = def.and_then(|d| {
|
||||
d.children.iter().find_map(|x| match x {
|
||||
Node::Group(r) if r.match_id == s.match_id => Some(r),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
differs(s, d, depth + 1)
|
||||
}
|
||||
Node::Prop(p) => {
|
||||
let d = def.and_then(|d| d.prop(&p.match_id));
|
||||
!p.keys.is_empty() || p.has_expression() || d.is_none_or(|d| d.value != p.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The text document `doc` in the file's terms (text, style runs, paragraphs, box); what the file
|
||||
/// cannot hold is reported for `what`.
|
||||
fn plan_doc(doc: &TextDoc, what: &str, col: &mut Collector) -> TextPlan {
|
||||
let base = doc.base_style();
|
||||
let runs = doc.runs();
|
||||
// Characters in EffectCraft's text, each with its run, CRLF and LF made After Effects' CR.
|
||||
let chars: Vec<char> = doc.text.chars().collect();
|
||||
let mut style_of: Vec<usize> = Vec::with_capacity(chars.len());
|
||||
for (ri, r) in runs.iter().enumerate() {
|
||||
style_of.extend(std::iter::repeat_n(ri, r.len));
|
||||
}
|
||||
let mut text = String::with_capacity(doc.text.len() + 1);
|
||||
let mut out_style: Vec<usize> = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < chars.len() && out_style.len() < MAX_CHARS {
|
||||
let c = chars.get(i).copied().unwrap_or(' ');
|
||||
let ri = style_of.get(i).copied().unwrap_or(runs.len().saturating_sub(1));
|
||||
if c == '\r' && chars.get(i + 1) == Some(&'\n') {
|
||||
i += 1;
|
||||
}
|
||||
text.push(if c == '\n' { '\r' } else { c });
|
||||
out_style.push(ri);
|
||||
i += 1;
|
||||
}
|
||||
if i < chars.len() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: the text is longer than {MAX_CHARS} characters and was cut"));
|
||||
}
|
||||
// The final paragraph end belongs to the last run.
|
||||
text.push('\r');
|
||||
out_style.push(out_style.last().copied().unwrap_or(0));
|
||||
|
||||
let mut styles: Vec<StyleOut> = Vec::with_capacity(runs.len().max(1));
|
||||
for r in &runs {
|
||||
styles.push(style_out(&r.style, what, col));
|
||||
}
|
||||
if styles.is_empty() {
|
||||
styles.push(style_out(&base, what, col));
|
||||
}
|
||||
for st in &mut styles {
|
||||
st.stroke_over_fill = doc.stroke_over_fill;
|
||||
}
|
||||
let mut out_runs: Vec<(usize, StyleOut)> = Vec::new();
|
||||
for ri in out_style {
|
||||
let s = styles.get(ri).or(styles.last()).cloned();
|
||||
let Some(s) = s else { continue };
|
||||
match out_runs.last_mut() {
|
||||
Some((n, last)) if *last == s => *n += 1,
|
||||
_ => out_runs.push((1, s)),
|
||||
}
|
||||
}
|
||||
|
||||
let paras_in = doc.paras();
|
||||
let mut paras = Vec::new();
|
||||
for (pi, part) in text.split_inclusive('\r').enumerate() {
|
||||
let len = part.chars().count();
|
||||
// A paragraph without its own settings takes the document's (every-line composer by
|
||||
// default, as a new text in After Effects' Paragraph panel).
|
||||
let base = doc.base_para();
|
||||
let p = paras_in.get(pi).or(paras_in.last()).unwrap_or(&base);
|
||||
// The stored code is relative to the direction: right-to-left swaps left / right and
|
||||
// the two justified variants with a left / right last line (t7, as the importer).
|
||||
let rtl = p.direction == Direction::Rtl;
|
||||
let j = match p.justify {
|
||||
Justify::Left if rtl => 1,
|
||||
Justify::Right if rtl => 0,
|
||||
Justify::JustifyLastLeft if rtl => 4,
|
||||
Justify::JustifyLastRight if rtl => 3,
|
||||
Justify::Left => 0,
|
||||
Justify::Right => 1,
|
||||
Justify::Center => 2,
|
||||
// The justified variants, as the importer reads them (paragraph `/0`, 3-6).
|
||||
Justify::JustifyLastLeft => 3,
|
||||
Justify::JustifyLastRight => 4,
|
||||
Justify::JustifyLastCenter => 5,
|
||||
Justify::JustifyAll => 6,
|
||||
};
|
||||
let mut at = At { what, col: &mut *col };
|
||||
let mut px = |v: f64, field: &str| at.fit(v, (-100_000.0, 100_000.0), 0.0, field);
|
||||
let indents = [
|
||||
px(p.indent_first, "first-line indent"),
|
||||
px(p.indent_left, "left indent"),
|
||||
px(p.indent_right, "right indent"),
|
||||
px(p.space_before, "space before"),
|
||||
px(p.space_after, "space after"),
|
||||
];
|
||||
let po = ParaOut { justify: j, indents, hanging: p.hanging_punctuation, every_line: p.composer == Composer::EveryLine, direction: i64::from(rtl) };
|
||||
paras.push((len, po));
|
||||
}
|
||||
if doc.vertical {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: vertical text is written horizontally"));
|
||||
}
|
||||
let mut at = At { what, col };
|
||||
let frame = doc.box_size.map(|[w, h]| {
|
||||
[
|
||||
at.fit(doc.box_pos[0], (-1e6, 1e6), 0.0, "box left"),
|
||||
at.fit(doc.box_pos[1], (-1e6, 1e6), 0.0, "box top"),
|
||||
at.fit(w, (1.0, 1e6), 1.0, "box width"),
|
||||
at.fit(h, (1.0, 1e6), 1.0, "box height"),
|
||||
]
|
||||
});
|
||||
TextPlan { text, runs: out_runs, paras, frame, animators: Vec::new(), expr: None }
|
||||
}
|
||||
|
||||
fn style_out(s: &effectcraft_keyframe::text_doc::CharStyle, what: &str, col: &mut Collector) -> StyleOut {
|
||||
let auto_kern = match s.kerning {
|
||||
Kerning::Metrics => 1,
|
||||
Kerning::Optical => 2,
|
||||
// No automatic kerning is a manual amount of 0 (542).
|
||||
Kerning::Manual(k) => {
|
||||
if k != 0.0 {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: a manual kerning amount is not written (written without automatic kerning)"));
|
||||
}
|
||||
0
|
||||
}
|
||||
};
|
||||
if !s.opentype.is_default() || !s.variations.is_empty() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: OpenType features and variable font axes are not written"));
|
||||
}
|
||||
if s.style != "Regular" && !s.style.is_empty() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: the font style '{}' is not written (the font is named by its PostScript name)", s.style));
|
||||
}
|
||||
if s.font.is_empty() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: a run without a font name is written in {PROTO_FONT}"));
|
||||
}
|
||||
let mut at = At { what, col };
|
||||
StyleOut {
|
||||
font: if s.font.is_empty() { PROTO_FONT.to_string() } else { s.font.clone() },
|
||||
size: at.fit(s.size, (0.1, 10_000.0), 100.0, "font size"),
|
||||
fill: at.rgb(s.fill, "fill colour"),
|
||||
stroke: at.rgb(s.stroke, "stroke colour"),
|
||||
tracking: at.fit(s.tracking, (-100_000.0, 100_000.0), 0.0, "tracking"),
|
||||
leading: s.leading.map(|l| at.fit(l, (0.0, 100_000.0), 0.0, "leading")),
|
||||
faux_bold: s.faux_bold,
|
||||
faux_italic: s.faux_italic,
|
||||
caps: if s.all_caps {
|
||||
2
|
||||
} else if s.small_caps {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
},
|
||||
script: match s.baseline {
|
||||
BaselineOption::Normal => 0,
|
||||
BaselineOption::Superscript => 1,
|
||||
BaselineOption::Subscript => 2,
|
||||
},
|
||||
h_scale: at.fit(s.h_scale, (1.0, 10_000.0), 100.0, "horizontal scale") / 100.0,
|
||||
v_scale: at.fit(s.v_scale, (1.0, 10_000.0), 100.0, "vertical scale") / 100.0,
|
||||
baseline_shift: at.fit(s.baseline_shift, (-100_000.0, 100_000.0), 0.0, "baseline shift"),
|
||||
auto_kern,
|
||||
ligatures: s.ligatures,
|
||||
tsume: at.fit(s.tsume, (0.0, 100.0), 0.0, "tsume") / 100.0,
|
||||
apply_fill: s.apply_fill,
|
||||
apply_stroke: s.apply_stroke,
|
||||
stroke_width: (s.apply_stroke || s.stroke_width > 0.0).then(|| at.fit(s.stroke_width, (0.0, 10_000.0), 1.0, "stroke width")),
|
||||
stroke_over_fill: true,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The document.
|
||||
|
||||
/// The number an atom holds (`1`, `1.0`, `.5`).
|
||||
fn atom_f64(n: Option<&TNode>) -> Option<f64> {
|
||||
match n? {
|
||||
TNode::Atom(a) => std::str::from_utf8(a).ok()?.trim().parse::<f64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets a number slot unless it already holds `v` (`absent` when the slot is missing).
|
||||
fn set_num_if(d: &mut TNode, key: &str, v: f64, absent: f64) {
|
||||
let cur = match d.get(key) {
|
||||
None => Some(absent),
|
||||
n => atom_f64(n),
|
||||
};
|
||||
if cur.is_none_or(|c| (c - v).abs() > 1e-9) {
|
||||
d.set(key, number(v));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets a boolean slot unless it already holds `v` (`absent` when the slot is missing).
|
||||
fn set_bool_if(d: &mut TNode, key: &str, v: bool, absent: bool) {
|
||||
let cur = match d.get(key) {
|
||||
None => Some(absent),
|
||||
Some(TNode::Atom(a)) if a.as_slice() == b"true" => Some(true),
|
||||
Some(TNode::Atom(a)) if a.as_slice() == b"false" => Some(false),
|
||||
Some(_) => None,
|
||||
};
|
||||
if cur != Some(v) {
|
||||
d.set(key, boolean(v));
|
||||
}
|
||||
}
|
||||
|
||||
fn num_or_int(v: f64) -> TNode {
|
||||
if v.fract() == 0.0 && v.abs() < 1e12 { int(v as i64) } else { number(v) }
|
||||
}
|
||||
|
||||
fn paint(rgb: [f64; 3]) -> TNode {
|
||||
TNode::Array(vec![number(1.0), number(rgb[0]), number(rgb[1]), number(rgb[2])])
|
||||
}
|
||||
|
||||
/// The rectangle as After Effects traces it: each corner twice at the ends of the list and four
|
||||
/// times in between (245: top-left, top-right, bottom-right, bottom-left).
|
||||
fn frame_points(f: [f64; 4]) -> TNode {
|
||||
let [x, y, w, h] = f;
|
||||
let (l, t, r, b) = (x, y, x + w, y + h);
|
||||
let corners = [(l, t), (l, t), (r, t), (r, t), (r, t), (r, t), (r, b), (r, b), (r, b), (r, b), (l, b), (l, b), (l, b), (l, b), (l, t), (l, t)];
|
||||
TNode::Array(corners.iter().flat_map(|(px, py)| [number(*px), number(*py)]).collect())
|
||||
}
|
||||
|
||||
/// The prototype's document (110 or 245) rewritten for `tp`; `None` when the prototype does not
|
||||
/// have the expected shape.
|
||||
pub(crate) fn build_doc(proto: &TNode, tp: &TextPlan) -> Option<TNode> {
|
||||
let mut doc = proto.clone();
|
||||
// Fonts: the prototype's own stay where the document refers to them; others are appended.
|
||||
let mut font_index: Vec<(String, usize)> = Vec::new();
|
||||
{
|
||||
let list = doc.path_mut("0/1/0")?;
|
||||
let TNode::Array(entries) = list else { return None };
|
||||
let template = entries.first()?.clone();
|
||||
// Font names compare as the stored atoms (UTF-16 bytes): a lossy text conversion would
|
||||
// make two non-ASCII names equal.
|
||||
let name_of = |e: &TNode| -> Option<Vec<u8>> {
|
||||
match e.path("0/0/0")? {
|
||||
TNode::Atom(a) => Some(a.clone()),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
for (_, s) in &tp.runs {
|
||||
if font_index.iter().any(|(f, _)| f == &s.font) {
|
||||
continue;
|
||||
}
|
||||
let TNode::Atom(atom) = string(&s.font) else { continue };
|
||||
let at = match entries.iter().position(|e| name_of(e).as_ref() == Some(&atom)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let mut e = template.clone();
|
||||
let inner = e.path_mut("0/0")?;
|
||||
inner.set("0", string(&s.font));
|
||||
inner.set("2", int(0));
|
||||
inner.remove("5");
|
||||
entries.push(e);
|
||||
entries.len() - 1
|
||||
}
|
||||
};
|
||||
font_index.push((s.font.clone(), at));
|
||||
}
|
||||
}
|
||||
{
|
||||
let run = doc.path_mut("1/1[0]/0")?;
|
||||
run.set("0", string(&tp.text));
|
||||
let p0 = run.path("5/0[0]")?.clone();
|
||||
let paras: Vec<TNode> = tp
|
||||
.paras
|
||||
.iter()
|
||||
.map(|(len, po)| {
|
||||
let mut p = p0.clone();
|
||||
p.set("1", int(i64::try_from(*len).unwrap_or(i64::MAX)));
|
||||
if let Some(d) = p.path_mut("0/0/5") {
|
||||
d.set("0", int(po.justify));
|
||||
// The paragraph settings decoded by the importer (560-569), written only
|
||||
// where they differ from the prototype.
|
||||
for (k, v) in ["1", "2", "3", "4", "5"].iter().zip(po.indents) {
|
||||
set_num_if(d, k, v, 0.0);
|
||||
}
|
||||
set_bool_if(d, "21", po.hanging, false);
|
||||
set_bool_if(d, "29", po.every_line, false);
|
||||
if atom_f64(d.get("33")).unwrap_or(0.0) != po.direction as f64 {
|
||||
d.set("33", int(po.direction));
|
||||
}
|
||||
}
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
*run.path_mut("5/0")? = TNode::Array(paras);
|
||||
let s0 = run.path("6/0[0]")?.clone();
|
||||
let mut styles = Vec::with_capacity(tp.runs.len());
|
||||
for (len, s) in &tp.runs {
|
||||
let mut r = s0.clone();
|
||||
r.set("1", int(i64::try_from(*len).unwrap_or(i64::MAX)));
|
||||
let d = r.path_mut("0/0/6")?;
|
||||
let fi = font_index.iter().find(|(f, _)| f == &s.font).map_or(0, |(_, i)| *i);
|
||||
d.set("0", int(i64::try_from(fi).unwrap_or(0)));
|
||||
d.set("1", number(s.size));
|
||||
d.set("2", boolean(s.faux_bold));
|
||||
d.set("3", boolean(s.faux_italic));
|
||||
// Automatic leading: /4 true and /5 0.01 (400); explicit: /4 false, /5 the leading.
|
||||
d.set("4", boolean(s.leading.is_none()));
|
||||
d.set("5", number(s.leading.unwrap_or(0.01)));
|
||||
d.set("8", num_or_int(s.tracking));
|
||||
d.set("12", int(s.caps));
|
||||
// Normal text must store 0: the prototypes (and every text After Effects creates by
|
||||
// script) hold 1, superscript, which After Effects draws at 58.3 % size (526-528).
|
||||
d.set("13", int(s.script));
|
||||
// The character settings decoded by the importer (539-555): written only where they
|
||||
// differ from what the slot holds, so a document in the default state keeps the
|
||||
// prototype's bytes.
|
||||
set_num_if(d, "6", s.h_scale, 1.0);
|
||||
set_num_if(d, "7", s.v_scale, 1.0);
|
||||
set_num_if(d, "9", s.baseline_shift, 0.0);
|
||||
if atom_f64(d.get("11")).unwrap_or(1.0) != s.auto_kern as f64 {
|
||||
d.set("11", int(s.auto_kern));
|
||||
}
|
||||
set_bool_if(d, "18", s.ligatures, false);
|
||||
set_num_if(d, "36", s.tsume, 0.0);
|
||||
set_bool_if(d, "56", s.apply_fill, true);
|
||||
set_bool_if(d, "57", s.apply_stroke, false);
|
||||
set_bool_if(d, "58", s.stroke_over_fill, true);
|
||||
if let Some(w) = s.stroke_width {
|
||||
set_num_if(d, "63", w, 1.0);
|
||||
}
|
||||
if let Some(fill) = d.path_mut("53/0") {
|
||||
fill.set("1", paint(s.fill));
|
||||
}
|
||||
if let Some(stroke) = d.path_mut("54/0") {
|
||||
stroke.set("1", paint(s.stroke));
|
||||
}
|
||||
styles.push(r);
|
||||
}
|
||||
*run.path_mut("6/0")? = TNode::Array(styles);
|
||||
}
|
||||
if let Some(f) = tp.frame {
|
||||
doc.path_mut("0/8/0[0]/0/1")?.set("0", frame_points(f));
|
||||
}
|
||||
// The composed layout is dropped: After Effects lays the text out again (t3).
|
||||
doc.path_mut("1/1[0]/1")?.set("2", TNode::Array(Vec::new()));
|
||||
Some(doc)
|
||||
}
|
||||
|
||||
/// The Source Text expression into the `tdbs` of `btds` (`docs/aep-format.md` 3.10, read back from
|
||||
/// `tests/fixtures/text-synthetic.aep`): `tdb4` byte 120 = 1, byte 119 = 1 when disabled, and the
|
||||
/// text as a `Utf8` after the record's `cdat`.
|
||||
fn put_source_text_expression(layr: &mut crate::Chunk<'static>, text: &str, enabled: bool) -> crate::export::tree::R<()> {
|
||||
use crate::Body;
|
||||
use crate::export::tree::tpl;
|
||||
/// The `tdbs` of the first `btds` below `c`, at most 32 levels down.
|
||||
fn find<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> {
|
||||
if depth > 32 {
|
||||
return None;
|
||||
}
|
||||
if c.is_list(b"btds") {
|
||||
return match &mut c.body {
|
||||
Body::List { children, .. } => children.iter_mut().find(|k| k.is_list(b"tdbs")),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
match &mut c.body {
|
||||
Body::List { children, .. } | Body::Chunks(children) => children.iter_mut().find_map(|k| find(k, depth + 1)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let tdbs = find(layr, 0).ok_or_else(|| tpl("text prototype without a Source Text record"))?;
|
||||
let Body::List { children, .. } = &mut tdbs.body else { return Err(tpl("text prototype without a Source Text record")) };
|
||||
let tdb4 = children.iter_mut().find(|k| k.is(b"tdb4")).ok_or_else(|| tpl("Source Text record without tdb4"))?;
|
||||
let Body::Data(d) = &mut tdb4.body else { return Err(tpl("Source Text record without tdb4")) };
|
||||
let d = d.to_mut();
|
||||
*d.get_mut(120).ok_or_else(|| tpl("short Source Text tdb4"))? = 1;
|
||||
*d.get_mut(119).ok_or_else(|| tpl("short Source Text tdb4"))? = u8::from(!enabled);
|
||||
children.retain(|k| !k.is(b"Utf8"));
|
||||
let at = children.iter().position(|k| k.is(b"tdum")).unwrap_or(children.len());
|
||||
children.insert(at, crate::Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrites the text document of a text layer block's `Layr` for `tp`, writes its Source Text
|
||||
/// expression and gives the document a fresh `btgu/pgui`.
|
||||
pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8; 16]) -> crate::export::tree::R<()> {
|
||||
use crate::Body;
|
||||
use crate::export::tree::tpl;
|
||||
/// The first `LIST btdk` below `c`, at most 32 levels down.
|
||||
fn find<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> {
|
||||
if depth > 32 {
|
||||
return None;
|
||||
}
|
||||
if matches!(&c.body, Body::OpaqueList { list_type, .. } if list_type == b"btdk") {
|
||||
return Some(c);
|
||||
}
|
||||
match &mut c.body {
|
||||
Body::List { children, .. } | Body::Chunks(children) => children.iter_mut().find_map(|k| find(k, depth + 1)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The first `pgui` of the first `btgu` below `c`, at most 32 levels down.
|
||||
fn find_pgui<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> {
|
||||
if depth > 32 {
|
||||
return None;
|
||||
}
|
||||
if c.is_list(b"btgu") {
|
||||
return match &mut c.body {
|
||||
Body::List { children, .. } => children.iter_mut().find(|k| k.is(b"pgui")),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
match &mut c.body {
|
||||
Body::List { children, .. } | Body::Chunks(children) => children.iter_mut().find_map(|k| find_pgui(k, depth + 1)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let btdk = find(layr, 0).ok_or_else(|| tpl("text prototype without a document"))?;
|
||||
let Body::OpaqueList { data, .. } = &mut btdk.body else { return Err(tpl("text prototype without a document")) };
|
||||
let proto = crate::export::textdoc::parse(data.as_ref()).ok_or_else(|| tpl("the text prototype's document does not parse"))?;
|
||||
let doc = build_doc(&proto, tp).ok_or_else(|| tpl("the text prototype's document has another shape"))?;
|
||||
*data = std::borrow::Cow::Owned(crate::export::textdoc::write(&doc));
|
||||
if let Some((text, enabled)) = &tp.expr {
|
||||
put_source_text_expression(layr, text, *enabled)?;
|
||||
}
|
||||
if let Some(p) = find_pgui(layr, 0) {
|
||||
*p = crate::Chunk::data(*b"pgui", guid.to_vec());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! Text animators (`docs/aep-format.md` 3.10; cases 114, 579-594, 728): the animators of a text
|
||||
//! layer with their properties and range selectors, the inverse of the importer's
|
||||
//! `text_anim.rs`.
|
||||
//!
|
||||
//! The layer's `ADBE Text Animators` group is the one of 579 emptied; every animator is its first
|
||||
//! animator (one range selector) with the properties and selectors of the EffectCraft animator.
|
||||
//! An animator property is written whenever the animator has it (its presence is what After
|
||||
//! Effects shows: Animate > Position adds the entry), a range selector property only when it
|
||||
//! differs from After Effects' default or carries keys or an expression. Every record has the layout
|
||||
//! After Effects writes for that property in a one-change case (579-592, 728; `tree_defs`):
|
||||
//! positions, anchor points, stroke widths and line spacing in pixels, scales, opacity, Start /
|
||||
//! End / Offset, Amount, Smoothness and the eases in percent, angles in degrees, tracking in 1/1000
|
||||
//! em, colours ARGB 0..255, popups 1-based (Units, Based On, Mode, Shape in EffectCraft's item
|
||||
//! order). With Units = Index the selector's range is `Index Start / End / Offset` (583). Keys
|
||||
//! and expressions are written as on shape properties (R46; 593, 594).
|
||||
|
||||
use crate::Chunk;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{Layer, Node, PropGroup};
|
||||
|
||||
use crate::export::plan::CompPlan;
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::shapes::{Conv, Layout, RecVal, ShCx, build_record, c_color, c_popup, c_scalar, rec_value};
|
||||
use crate::export::synth::{GROUP_END, is_tdmn};
|
||||
use crate::export::tree::{R, kids_mut, set_utf8, tpl};
|
||||
|
||||
/// More animators or selectors than this on one layer are not written (and reported).
|
||||
const MAX_ITEMS: usize = 1024;
|
||||
|
||||
/// A range selector in the file's terms.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct SelPlan {
|
||||
pub name: String,
|
||||
pub records: Vec<(&'static str, RecVal)>,
|
||||
pub advanced: Vec<(&'static str, RecVal)>,
|
||||
}
|
||||
|
||||
/// An animator in the file's terms.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct AnimPlan {
|
||||
pub name: String,
|
||||
pub props: Vec<(&'static str, RecVal)>,
|
||||
pub selectors: Vec<SelPlan>,
|
||||
}
|
||||
|
||||
/// The prototypes, built in code (`tree_defs`).
|
||||
pub(crate) struct AnimProtos {
|
||||
/// `tdmn ADBE Text Animators` + the emptied group.
|
||||
pub group: Vec<Chunk<'static>>,
|
||||
/// `tdmn ADBE Text Animator` + the animator with one range selector and no properties.
|
||||
pub animator: Vec<Chunk<'static>>,
|
||||
/// Value records by match name.
|
||||
pub records: Vec<(String, [Chunk<'static>; 2])>,
|
||||
}
|
||||
|
||||
fn c_vec3(v: &Value) -> Option<Vec<f64>> {
|
||||
match v {
|
||||
Value::Vec3(p) => Some(p.to_vec()),
|
||||
Value::Vec2(p) => Some(vec![p[0], p[1], 0.0]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn c_vec2(v: &Value) -> Option<Vec<f64>> {
|
||||
match v {
|
||||
Value::Vec2(p) => Some(p.to_vec()),
|
||||
Value::Vec3(p) => Some(vec![p[0], p[1]]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn c_bool(v: &Value) -> Option<Vec<f64>> {
|
||||
match v {
|
||||
Value::Bool(b) => Some(vec![if *b { 1.0 } else { 0.0 }]),
|
||||
Value::Scalar(s) => Some(vec![if *s != 0.0 { 1.0 } else { 0.0 }]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// EffectCraft animator property -> stored match name, conversion, key layout (the importer's
|
||||
/// `PROPS`, 579-592, 728).
|
||||
const PROPS: &[(&str, &str, Conv, Layout)] = &[
|
||||
("anchor", "ADBE Text Anchor Point 3D", c_vec3, Layout::Point),
|
||||
("position", "ADBE Text Position 3D", c_vec3, Layout::Point),
|
||||
("scale", "ADBE Text Scale 3D", c_vec3, Layout::Size),
|
||||
("skew", "ADBE Text Skew", c_scalar, Layout::One),
|
||||
("skewAxis", "ADBE Text Skew Axis", c_scalar, Layout::One),
|
||||
("rotation", "ADBE Text Rotation", c_scalar, Layout::One),
|
||||
("opacity", "ADBE Text Opacity", c_scalar, Layout::One),
|
||||
("fillColor", "ADBE Text Fill Color", c_color, Layout::Color),
|
||||
("strokeColor", "ADBE Text Stroke Color", c_color, Layout::Color),
|
||||
("strokeOpacity", "ADBE Text Stroke Opacity", c_scalar, Layout::One),
|
||||
("strokeWidth", "ADBE Text Stroke Width", c_scalar, Layout::One),
|
||||
("tracking", "ADBE Text Tracking Amount", c_scalar, Layout::One),
|
||||
("lineSpacing", "ADBE Text Line Spacing", c_vec2, Layout::Size),
|
||||
("blur", "ADBE Text Blur", c_vec2, Layout::Size),
|
||||
("characterOffset", "ADBE Text Character Offset", c_scalar, Layout::One),
|
||||
];
|
||||
|
||||
/// Properties After Effects adds with another one and EffectCraft keeps at their default: written
|
||||
/// by After Effects itself (Tracking Type with Tracking, Character Range and Alignment with
|
||||
/// Character Offset, 728); a value other than the default is reported.
|
||||
const DEPENDENT: &[(&str, Value)] = &[("trackingType", Value::Enum(0)), ("characterRange", Value::Enum(0)), ("characterAlignment", Value::Enum(1))];
|
||||
|
||||
/// Range selector properties: EffectCraft id, stored match names (percent units, index units),
|
||||
/// conversion, default (stored).
|
||||
const RANGE: &[(&str, &str, &str, f64)] = &[
|
||||
("start", "ADBE Text Percent Start", "ADBE Text Index Start", 0.0),
|
||||
("end", "ADBE Text Percent End", "ADBE Text Index End", 100.0),
|
||||
("offset", "ADBE Text Percent Offset", "ADBE Text Index Offset", 0.0),
|
||||
];
|
||||
|
||||
const ADVANCED: &[(&str, &str, Conv, Layout, f64)] = &[
|
||||
("units", "ADBE Text Range Units", c_popup, Layout::Popup, 1.0),
|
||||
("basedOn", "ADBE Text Range Type2", c_popup, Layout::Popup, 1.0),
|
||||
("mode", "ADBE Text Selector Mode", c_popup, Layout::Popup, 1.0),
|
||||
("amount", "ADBE Text Selector Max Amount", c_scalar, Layout::One, 100.0),
|
||||
("shape", "ADBE Text Range Shape", c_popup, Layout::Popup, 1.0),
|
||||
("smoothness", "ADBE Text Selector Smoothness", c_scalar, Layout::One, 100.0),
|
||||
("easeHigh", "ADBE Text Levels Max Ease", c_scalar, Layout::One, 0.0),
|
||||
("easeLow", "ADBE Text Levels Min Ease", c_scalar, Layout::One, 0.0),
|
||||
("randomize", "ADBE Text Randomize Order", c_bool, Layout::Popup, 0.0),
|
||||
("randomSeed", "ADBE Text Random Seed", c_scalar, Layout::One, 0.0),
|
||||
];
|
||||
|
||||
fn layout_of(name: &str) -> Layout {
|
||||
if let Some((_, _, _, l)) = PROPS.iter().find(|(_, n, ..)| *n == name) {
|
||||
return *l;
|
||||
}
|
||||
if let Some((_, _, _, l, _)) = ADVANCED.iter().find(|(_, n, ..)| *n == name) {
|
||||
return *l;
|
||||
}
|
||||
Layout::One
|
||||
}
|
||||
|
||||
/// The animators of `layer` (its `text/animators` group) in the file's terms; what cannot be
|
||||
/// written is reported.
|
||||
pub(crate) fn plan(layer: &Layer, cp: &CompPlan, what: &str, col: &mut Collector) -> Vec<AnimPlan> {
|
||||
let Some(group) = layer.props.sub("text").and_then(|t| t.sub("animators")) else { return Vec::new() };
|
||||
let mut cx = ShCx { cp, col };
|
||||
let mut out = Vec::new();
|
||||
for (i, node) in group.children.iter().enumerate() {
|
||||
if i >= MAX_ITEMS {
|
||||
cx.col.lose(LossCategory::TextLayers, format!("{what}: more than {MAX_ITEMS} text animators, the rest are not written"));
|
||||
break;
|
||||
}
|
||||
let Node::Group(a) = node else { continue };
|
||||
let here = format!("{what}: animator '{}'", a.name);
|
||||
if !a.enabled {
|
||||
cx.col.lose(LossCategory::TextLayers, format!("{here}: a switched-off animator is written switched on (the switch is not decoded)"));
|
||||
}
|
||||
let mut props = Vec::new();
|
||||
if let Some(pg) = a.sub("properties") {
|
||||
for n in &pg.children {
|
||||
let Node::Prop(p) = n else { continue };
|
||||
if let Some((_, name, conv, layout)) = PROPS.iter().find(|(id, ..)| *id == p.match_id) {
|
||||
let w = format!("{here}: {name}");
|
||||
if let Some(v) = rec_value(p, *conv, *layout, None, &w, LossCategory::TextLayers, &mut cx) {
|
||||
props.push((*name, v));
|
||||
}
|
||||
} else if let Some((_, def)) = DEPENDENT.iter().find(|(id, _)| *id == p.match_id) {
|
||||
if p.value != *def || !p.keys.is_empty() || p.has_expression() {
|
||||
cx.col.lose(LossCategory::TextLayers, format!("{here}: {} is not written (only its default is sampled)", p.name));
|
||||
}
|
||||
} else {
|
||||
cx.col.lose(LossCategory::TextLayers, format!("{here}: the animator property {} is not written", p.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut selectors = Vec::new();
|
||||
if let Some(sg) = a.sub("selectors") {
|
||||
for (k, n) in sg.children.iter().enumerate() {
|
||||
if k >= MAX_ITEMS {
|
||||
cx.col.lose(LossCategory::TextLayers, format!("{here}: more than {MAX_ITEMS} selectors, the rest are not written"));
|
||||
break;
|
||||
}
|
||||
let Node::Group(s) = n else { continue };
|
||||
if s.match_id != "rangeSelector" {
|
||||
cx.col.lose(LossCategory::TextLayers, format!("{here}: the selector '{}' ({}) is not written (only range selectors)", s.name, s.match_id));
|
||||
continue;
|
||||
}
|
||||
if !s.enabled {
|
||||
cx.col.lose(
|
||||
LossCategory::TextLayers,
|
||||
format!("{here}: the switched-off selector '{}' is written switched on (the switch is not decoded)", s.name),
|
||||
);
|
||||
}
|
||||
selectors.push(plan_selector(s, &here, &mut cx));
|
||||
}
|
||||
}
|
||||
cx.col.exported.text_animators = cx.col.exported.text_animators.saturating_add(1);
|
||||
out.push(AnimPlan { name: crate::export::plan::cut_name(&a.name, 255, &here, cx.col), props, selectors });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn plan_selector(s: &PropGroup, animator: &str, cx: &mut ShCx<'_>) -> SelPlan {
|
||||
let here = format!("{animator} '{}'", s.name);
|
||||
let adv = s.sub("advanced");
|
||||
let index = adv.and_then(|a| a.get("units")).is_some_and(|u| u.value == Value::Enum(1));
|
||||
let mut records = Vec::new();
|
||||
for (id, percent, idx, default) in RANGE {
|
||||
let Some(p) = s.get(id) else { continue };
|
||||
let name = if index { *idx } else { *percent };
|
||||
// With Units = Index After Effects stores the range in characters, records for all three
|
||||
// (583).
|
||||
let default = if index { None } else { Some(std::slice::from_ref(default)) };
|
||||
if let Some(v) = rec_value(p, c_scalar, Layout::One, default, &format!("{here}: {name}"), LossCategory::TextLayers, cx) {
|
||||
records.push((name, v));
|
||||
}
|
||||
}
|
||||
let mut advanced = Vec::new();
|
||||
if let Some(a) = adv {
|
||||
for (id, name, conv, layout, default) in ADVANCED {
|
||||
let Some(p) = a.get(id) else { continue };
|
||||
if let Some(v) = rec_value(p, *conv, *layout, Some(std::slice::from_ref(default)), &format!("{here}: {name}"), LossCategory::TextLayers, cx) {
|
||||
advanced.push((*name, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
SelPlan { name: crate::export::plan::cut_name(&s.name, 255, &here, cx.col), records, advanced }
|
||||
}
|
||||
|
||||
fn pos(kids: &[Chunk<'static>], n: &str) -> Option<usize> {
|
||||
kids.iter().position(|c| is_tdmn(c, n))
|
||||
}
|
||||
|
||||
/// The item's user name (`tdsn/Utf8`).
|
||||
fn set_name(node: &mut Chunk<'static>, name: &str) -> R<()> {
|
||||
let kids = kids_mut(node)?;
|
||||
let tdsn = kids.iter_mut().find(|c| c.is(b"tdsn")).ok_or_else(|| tpl("animator prototype without a name"))?;
|
||||
set_utf8(tdsn, name)
|
||||
}
|
||||
|
||||
/// Inserts records before the group's first sub-group or end.
|
||||
fn put_records(t: &AnimProtos, group: &mut Chunk<'static>, records: &[(&'static str, RecVal)], key_list: &Chunk<'static>) -> R<()> {
|
||||
let kids = kids_mut(group)?;
|
||||
let mut at = kids.iter().position(|c| c.is(b"tdmn")).unwrap_or(kids.len());
|
||||
for (name, v) in records {
|
||||
let [m, node] = t.records.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()).ok_or_else(|| tpl("text animator record prototype missing"))?;
|
||||
let [m, node] = build_record(m, node, layout_of(name), v, key_list)?;
|
||||
kids.insert(at, m);
|
||||
kids.insert(at.saturating_add(1), node);
|
||||
at = at.saturating_add(2);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds the `ADBE Text Animators` group with `anims` to the text layer `layr` (after More
|
||||
/// Options, as 579 stores it).
|
||||
pub(crate) fn put_animators(layr: &mut Chunk<'static>, t: &AnimProtos, anims: &[AnimPlan], key_list: &Chunk<'static>) -> R<()> {
|
||||
if anims.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let [gm, mut group] = <[Chunk<'static>; 2]>::try_from(t.group.clone()).map_err(|_| tpl("animators prototype incomplete"))?;
|
||||
let [am, anim_proto] = <[Chunk<'static>; 2]>::try_from(t.animator.clone()).map_err(|_| tpl("animator prototype incomplete"))?;
|
||||
let mut built = Vec::with_capacity(anims.len() * 2);
|
||||
for a in anims {
|
||||
let mut node = anim_proto.clone();
|
||||
set_name(&mut node, &a.name)?;
|
||||
let kids = kids_mut(&mut node)?;
|
||||
// Selectors: one copy of the prototype's selector each.
|
||||
let si = pos(kids, "ADBE Text Selectors").ok_or_else(|| tpl("animator prototype without selectors"))?;
|
||||
{
|
||||
let sels = kids.get_mut(si + 1).ok_or_else(|| tpl("animator prototype without selectors"))?;
|
||||
let sk = kids_mut(sels)?;
|
||||
let at = pos(sk, "ADBE Text Selector").ok_or_else(|| tpl("animator prototype without a selector"))?;
|
||||
let sm = sk.get(at).cloned().ok_or_else(|| tpl("animator prototype without a selector"))?;
|
||||
let sproto = sk.get(at + 1).cloned().ok_or_else(|| tpl("animator prototype without a selector"))?;
|
||||
sk.drain(at..at + 2);
|
||||
let mut sel_nodes = Vec::with_capacity(a.selectors.len() * 2);
|
||||
for s in &a.selectors {
|
||||
let mut sn = sproto.clone();
|
||||
set_name(&mut sn, &s.name)?;
|
||||
if !s.advanced.is_empty() {
|
||||
let snk = kids_mut(&mut sn)?;
|
||||
let ai = pos(snk, "ADBE Text Range Advanced").ok_or_else(|| tpl("selector prototype without Advanced"))?;
|
||||
let adv = snk.get_mut(ai + 1).ok_or_else(|| tpl("selector prototype without Advanced"))?;
|
||||
put_records(t, adv, &s.advanced, key_list)?;
|
||||
}
|
||||
put_records(t, &mut sn, &s.records, key_list)?;
|
||||
sel_nodes.push(sm.clone());
|
||||
sel_nodes.push(sn);
|
||||
}
|
||||
sk.splice(at..at, sel_nodes);
|
||||
}
|
||||
let pi = pos(kids, "ADBE Text Animator Properties").ok_or_else(|| tpl("animator prototype without properties"))?;
|
||||
let props = kids.get_mut(pi + 1).ok_or_else(|| tpl("animator prototype without properties"))?;
|
||||
put_records(t, props, &a.props, key_list)?;
|
||||
built.push(am.clone());
|
||||
built.push(node);
|
||||
}
|
||||
{
|
||||
let gk = kids_mut(&mut group)?;
|
||||
let end = pos(gk, GROUP_END).unwrap_or(gk.len());
|
||||
gk.splice(end..end, built);
|
||||
}
|
||||
// Into the layer's `ADBE Text Properties`, before its Group End.
|
||||
let root = crate::export::tree::list_mut(layr, b"tdgp")?;
|
||||
let rk = kids_mut(root)?;
|
||||
let ti = pos(rk, "ADBE Text Properties").ok_or_else(|| tpl("text layer without text properties"))?;
|
||||
let tp = rk.get_mut(ti + 1).ok_or_else(|| tpl("text layer without text properties"))?;
|
||||
let tk = kids_mut(tp)?;
|
||||
let end = pos(tk, GROUP_END).unwrap_or(tk.len());
|
||||
tk.splice(end..end, [gm, group]);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! The text document dictionary (`LIST btdk`, `docs/aep-format.md` 3.10) as an editable tree:
|
||||
//! `/key value` pairs, `<< >>` dictionaries, `[ ]` arrays, and atoms (numbers, names, booleans,
|
||||
//! strings) kept as their raw bytes. Writing it back uses After Effects' own spacing (one space
|
||||
//! between tokens, ` /key value` at the top level), so an unedited tree writes the bytes it was
|
||||
//! read from.
|
||||
|
||||
/// Deepest nesting read (After Effects' documents nest about 16 deep).
|
||||
const MAX_DEPTH: usize = 64;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum TNode {
|
||||
Dict(Vec<(String, TNode)>),
|
||||
Array(Vec<TNode>),
|
||||
/// A number, name, boolean or string, as stored.
|
||||
Atom(Vec<u8>),
|
||||
}
|
||||
|
||||
impl TNode {
|
||||
pub(crate) fn get(&self, key: &str) -> Option<&TNode> {
|
||||
match self {
|
||||
TNode::Dict(kv) => kv.iter().find(|(k, _)| k == key).map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_mut(&mut self, key: &str) -> Option<&mut TNode> {
|
||||
match self {
|
||||
TNode::Dict(kv) => kv.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn at_mut(&mut self, i: usize) -> Option<&mut TNode> {
|
||||
match self {
|
||||
TNode::Array(v) => v.get_mut(i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The node at a `/`-separated path of keys and `[n]` indices (`1/1[0]/0`).
|
||||
pub(crate) fn path_mut(&mut self, path: &str) -> Option<&mut TNode> {
|
||||
let mut at = self;
|
||||
for step in path.split('/').filter(|s| !s.is_empty()) {
|
||||
let (key, idx) = match step.split_once('[') {
|
||||
Some((k, rest)) => (k, rest.strip_suffix(']').and_then(|n| n.parse::<usize>().ok())),
|
||||
None => (step, None),
|
||||
};
|
||||
at = at.get_mut(key)?;
|
||||
if let Some(i) = idx {
|
||||
at = at.at_mut(i)?;
|
||||
}
|
||||
}
|
||||
Some(at)
|
||||
}
|
||||
|
||||
pub(crate) fn path(&self, path: &str) -> Option<&TNode> {
|
||||
let mut at = self;
|
||||
for step in path.split('/').filter(|s| !s.is_empty()) {
|
||||
let (key, idx) = match step.split_once('[') {
|
||||
Some((k, rest)) => (k, rest.strip_suffix(']').and_then(|n| n.parse::<usize>().ok())),
|
||||
None => (step, None),
|
||||
};
|
||||
at = at.get(key)?;
|
||||
if let Some(i) = idx {
|
||||
at = match at {
|
||||
TNode::Array(v) => v.get(i)?,
|
||||
_ => return None,
|
||||
};
|
||||
}
|
||||
}
|
||||
Some(at)
|
||||
}
|
||||
|
||||
/// Sets (or adds) `key` in a dictionary.
|
||||
pub(crate) fn set(&mut self, key: &str, value: TNode) {
|
||||
if let TNode::Dict(kv) = self {
|
||||
match kv.iter_mut().find(|(k, _)| k == key) {
|
||||
Some((_, v)) => *v = value,
|
||||
None => kv.push((key.to_string(), value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remove(&mut self, key: &str) {
|
||||
if let TNode::Dict(kv) = self {
|
||||
kv.retain(|(k, _)| k != key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_ws(c: u8) -> bool {
|
||||
matches!(c, b' ' | b'\t' | b'\r' | b'\n' | 0)
|
||||
}
|
||||
|
||||
fn is_delim(c: u8) -> bool {
|
||||
is_ws(c) || matches!(c, b'/' | b'[' | b']' | b'(' | b')' | b'<' | b'>')
|
||||
}
|
||||
|
||||
struct P<'a> {
|
||||
b: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl P<'_> {
|
||||
fn ws(&mut self) {
|
||||
while self.b.get(self.i).copied().is_some_and(is_ws) {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.b.get(self.i).copied()
|
||||
}
|
||||
|
||||
fn starts(&self, s: &[u8]) -> bool {
|
||||
self.b.get(self.i..).is_some_and(|r| r.starts_with(s))
|
||||
}
|
||||
|
||||
fn name(&mut self) -> Option<String> {
|
||||
if self.peek() != Some(b'/') {
|
||||
return None;
|
||||
}
|
||||
self.i += 1;
|
||||
let start = self.i;
|
||||
while self.peek().is_some_and(|c| !is_delim(c)) {
|
||||
self.i += 1;
|
||||
}
|
||||
Some(String::from_utf8_lossy(self.b.get(start..self.i)?).to_string())
|
||||
}
|
||||
|
||||
fn value(&mut self, depth: usize) -> Option<TNode> {
|
||||
if depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
self.ws();
|
||||
if self.starts(b"<<") {
|
||||
self.i += 2;
|
||||
let mut kv = Vec::new();
|
||||
loop {
|
||||
self.ws();
|
||||
if self.starts(b">>") {
|
||||
self.i += 2;
|
||||
return Some(TNode::Dict(kv));
|
||||
}
|
||||
let k = self.name()?;
|
||||
let v = self.value(depth + 1)?;
|
||||
kv.push((k, v));
|
||||
}
|
||||
}
|
||||
match self.peek()? {
|
||||
b'[' => {
|
||||
self.i += 1;
|
||||
let mut v = Vec::new();
|
||||
loop {
|
||||
self.ws();
|
||||
if self.peek()? == b']' {
|
||||
self.i += 1;
|
||||
return Some(TNode::Array(v));
|
||||
}
|
||||
v.push(self.value(depth + 1)?);
|
||||
}
|
||||
}
|
||||
b'(' => {
|
||||
let start = self.i;
|
||||
self.i += 1;
|
||||
loop {
|
||||
match self.peek()? {
|
||||
b'\\' => self.i += 2,
|
||||
b')' => {
|
||||
self.i += 1;
|
||||
break;
|
||||
}
|
||||
_ => self.i += 1,
|
||||
}
|
||||
}
|
||||
Some(TNode::Atom(self.b.get(start..self.i)?.to_vec()))
|
||||
}
|
||||
b'/' => {
|
||||
// A name used as a value (`/CoolTypeFont`, `/nil`).
|
||||
let start = self.i;
|
||||
self.name()?;
|
||||
Some(TNode::Atom(self.b.get(start..self.i)?.to_vec()))
|
||||
}
|
||||
_ => {
|
||||
let start = self.i;
|
||||
while self.peek().is_some_and(|c| !is_delim(c)) {
|
||||
self.i += 1;
|
||||
}
|
||||
if self.i == start {
|
||||
return None;
|
||||
}
|
||||
Some(TNode::Atom(self.b.get(start..self.i)?.to_vec()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a whole document (a top-level sequence of `/key value` pairs); `None` when it is not
|
||||
/// well formed.
|
||||
pub(crate) fn parse(b: &[u8]) -> Option<TNode> {
|
||||
let mut p = P { b, i: 0 };
|
||||
let mut kv = Vec::new();
|
||||
loop {
|
||||
p.ws();
|
||||
if p.i >= b.len() {
|
||||
return Some(TNode::Dict(kv));
|
||||
}
|
||||
let k = p.name()?;
|
||||
let v = p.value(0)?;
|
||||
kv.push((k, v));
|
||||
}
|
||||
}
|
||||
|
||||
fn write_value(n: &TNode, out: &mut Vec<u8>, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
out.extend_from_slice(b"<< >>");
|
||||
return;
|
||||
}
|
||||
match n {
|
||||
TNode::Atom(a) => out.extend_from_slice(a),
|
||||
TNode::Array(v) => {
|
||||
out.push(b'[');
|
||||
for x in v {
|
||||
out.push(b' ');
|
||||
write_value(x, out, depth + 1);
|
||||
}
|
||||
out.extend_from_slice(b" ]");
|
||||
}
|
||||
TNode::Dict(kv) => {
|
||||
out.extend_from_slice(b"<<");
|
||||
for (k, v) in kv {
|
||||
out.extend_from_slice(b" /");
|
||||
out.extend_from_slice(k.as_bytes());
|
||||
out.push(b' ');
|
||||
write_value(v, out, depth + 1);
|
||||
}
|
||||
out.extend_from_slice(b" >>");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's bytes.
|
||||
pub(crate) fn write(doc: &TNode) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
if let TNode::Dict(kv) = doc {
|
||||
for (k, v) in kv {
|
||||
out.extend_from_slice(b" /");
|
||||
out.extend_from_slice(k.as_bytes());
|
||||
out.push(b' ');
|
||||
write_value(v, &mut out, 0);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A string atom: `(` + `fe ff` + UTF-16BE + `)`, with `(`, `)` and `\` escaped.
|
||||
pub(crate) fn string(s: &str) -> TNode {
|
||||
let mut out = vec![b'('];
|
||||
let mut push = |b: u8| {
|
||||
if matches!(b, b'(' | b')' | b'\\') {
|
||||
out.push(b'\\');
|
||||
}
|
||||
out.push(b);
|
||||
};
|
||||
push(0xfe);
|
||||
push(0xff);
|
||||
for u in s.encode_utf16() {
|
||||
let [hi, lo] = u.to_be_bytes();
|
||||
push(hi);
|
||||
push(lo);
|
||||
}
|
||||
out.push(b')');
|
||||
TNode::Atom(out)
|
||||
}
|
||||
|
||||
/// A number as After Effects writes it: integers without a point, others with one (`60.0`,
|
||||
/// `.5`, `-49.05029`).
|
||||
pub(crate) fn number(v: f64) -> TNode {
|
||||
let v = if v.is_finite() { v } else { 0.0 };
|
||||
let mut s = if v.fract() == 0.0 && v.abs() < 1e15 { format!("{v:.1}") } else { format!("{}", (v * 1e5).round() / 1e5) };
|
||||
// `.5` and `-.25`, but `0.0` (113: `[ 1.0 1.0 .5 0.0 ]`).
|
||||
if v != 0.0 {
|
||||
if let Some(rest) = s.strip_prefix("0.") {
|
||||
s = format!(".{rest}");
|
||||
} else if let Some(rest) = s.strip_prefix("-0.") {
|
||||
s = format!("-.{rest}");
|
||||
}
|
||||
}
|
||||
TNode::Atom(s.into_bytes())
|
||||
}
|
||||
|
||||
pub(crate) fn int(v: i64) -> TNode {
|
||||
TNode::Atom(v.to_string().into_bytes())
|
||||
}
|
||||
|
||||
pub(crate) fn boolean(v: bool) -> TNode {
|
||||
TNode::Atom(if v { b"true".to_vec() } else { b"false".to_vec() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_and_writes_back() {
|
||||
let src = b" /98 << /0 13 >> /0 << /1 [ 1.0 .5 (\xfe\xff\x00A\\)) /nil << >> [ ] ] >>";
|
||||
let t = parse(src).expect("parse");
|
||||
assert_eq!(write(&t), src.to_vec());
|
||||
assert_eq!(t.path("0/1[1]"), Some(&TNode::Atom(b".5".to_vec())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_and_strings_as_after_effects_writes_them() {
|
||||
assert_eq!(number(60.0), TNode::Atom(b"60.0".to_vec()));
|
||||
assert_eq!(number(0.5), TNode::Atom(b".5".to_vec()));
|
||||
assert_eq!(number(0.0), TNode::Atom(b"0.0".to_vec()));
|
||||
assert_eq!(number(-0.25), TNode::Atom(b"-.25".to_vec()));
|
||||
assert_eq!(number(98.123456), TNode::Atom(b"98.12346".to_vec()));
|
||||
assert_eq!(string("A)"), TNode::Atom(b"(\xfe\xff\x00A\x00\\))".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_documents_are_none_not_a_panic() {
|
||||
for bad in [&b"/a << /b"[..], b"/a [ 1 2", b"/a (unterminated", b"<<", b"/", b"/a >>", b"/a ]"] {
|
||||
let _ = parse(bad);
|
||||
}
|
||||
let deep: Vec<u8> = std::iter::once(b"/a ".to_vec()).chain(std::iter::repeat_n(b"[ ".to_vec(), 500)).flatten().collect();
|
||||
assert_eq!(parse(&deep), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! The text document a text layer starts from, built in code (`docs/aep-format.md` 3.10): the
|
||||
//! smallest dictionary After Effects reads back unchanged (read-backs t2-*, t3-*). `text::build_doc`
|
||||
//! then writes the text, the runs, the fonts and the box frame into it.
|
||||
//!
|
||||
//! What stays and why: the font list (`/0/1`, names only), the style and paragraph sheets with
|
||||
//! their name only (`/0/5`, `/0/6`; without them the layer is skipped), one text frame (`/0/8`: a
|
||||
//! point text's, or a box text's with its outline), the document settings (`/1/0`: the line-break
|
||||
//! classes of seven characters, the superscript and subscript size and offset, the small caps
|
||||
//! size; without them, or with `/1/0/0` cut down, After Effects refuses or crashes), the composer
|
||||
//! (`/1/5`; without it After Effects rewrites the document on open) and one run with one
|
||||
//! paragraph and one style (`/1/1`) and an empty layout.
|
||||
|
||||
use crate::export::textdoc::{TNode, boolean, int, number, string};
|
||||
|
||||
fn dict(kv: Vec<(&str, TNode)>) -> TNode {
|
||||
TNode::Dict(kv.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
|
||||
}
|
||||
|
||||
fn name(n: &str) -> TNode {
|
||||
TNode::Atom(format!("/{n}").into_bytes())
|
||||
}
|
||||
|
||||
fn numbers(v: &[f64]) -> TNode {
|
||||
TNode::Array(v.iter().map(|x| number(*x)).collect())
|
||||
}
|
||||
|
||||
/// The fonts of a new document (the first is the one the runs use until `build_doc` sets theirs).
|
||||
const FONTS: [&str; 4] = ["TimesNewRomanPSMT", "Myriad-Roman", "MyriadPro-Regular", "AdobeInvisFont"];
|
||||
|
||||
/// The line-break class of the characters the text engine treats specially: space, carriage
|
||||
/// return, tab, paragraph separator, end of text, ideographic space, soft hyphen.
|
||||
const BREAK_CLASSES: [(char, &str); 7] = [(' ', "1"), ('\r', "6"), ('\t', "0"), ('\u{2029}', "5"), ('\u{3}', "5"), ('\u{3000}', "1"), ('\u{ad}', "3")];
|
||||
|
||||
/// A sheet list with one sheet named `Normal RGB`, used by every run (`/1 [ << /0 0 >> ]`).
|
||||
fn sheets() -> TNode {
|
||||
dict(vec![("0", TNode::Array(vec![dict(vec![("0", dict(vec![("0", string("Normal RGB"))]))])])), ("1", TNode::Array(vec![dict(vec![("0", int(0))])]))])
|
||||
}
|
||||
|
||||
/// The text frame: a point text's (no outline, size -1), or a box text's with an outline that
|
||||
/// `build_doc` replaces with the layer's box.
|
||||
fn frame(boxed: bool) -> TNode {
|
||||
let (kind, size) = if boxed { (Some(1), -2.0) } else { (None, -1.0) };
|
||||
let mut settings = vec![("6", numbers(&[size, size])), ("11", dict(vec![("4", int(size as i64)), ("18", number(size)), ("22", number(0.025))]))];
|
||||
if let Some(k) = kind {
|
||||
settings.insert(0, ("0", int(k)));
|
||||
}
|
||||
let mut entry = Vec::new();
|
||||
if boxed {
|
||||
entry.push(("1", dict(vec![("0", numbers(&[0.0; 32]))])));
|
||||
}
|
||||
entry.push(("2", dict(settings)));
|
||||
dict(vec![("0", TNode::Array(vec![dict(vec![("0", dict(entry))])]))])
|
||||
}
|
||||
|
||||
fn paint() -> TNode {
|
||||
dict(vec![("99", name("SimplePaint")), ("0", dict(vec![("0", int(1)), ("1", numbers(&[1.0, 1.0, 1.0, 1.0]))]))])
|
||||
}
|
||||
|
||||
/// The run: an empty text with one paragraph and one style run (the keys `build_doc` writes, at
|
||||
/// the values it treats as unset) and an empty layout.
|
||||
fn run() -> TNode {
|
||||
let para = dict(vec![
|
||||
("0", int(0)),
|
||||
("1", number(0.0)),
|
||||
("2", number(0.0)),
|
||||
("3", number(0.0)),
|
||||
("4", number(0.0)),
|
||||
("5", number(0.0)),
|
||||
("21", boolean(false)),
|
||||
("29", boolean(false)),
|
||||
("33", int(0)),
|
||||
]);
|
||||
let style = dict(vec![
|
||||
("0", int(0)),
|
||||
("1", number(12.0)),
|
||||
("2", boolean(false)),
|
||||
("3", boolean(false)),
|
||||
("4", boolean(true)),
|
||||
("5", number(0.01)),
|
||||
("6", number(1.0)),
|
||||
("7", number(1.0)),
|
||||
("8", int(0)),
|
||||
("9", number(0.0)),
|
||||
("11", int(1)),
|
||||
("12", int(0)),
|
||||
("13", int(0)),
|
||||
("18", boolean(false)),
|
||||
("36", number(0.0)),
|
||||
("53", paint()),
|
||||
("54", paint()),
|
||||
("56", boolean(true)),
|
||||
("57", boolean(false)),
|
||||
("58", boolean(true)),
|
||||
("63", number(1.0)),
|
||||
]);
|
||||
// Each run names its sheet (`/0`) and the other sheet's index (0), in key order.
|
||||
let entry = |kv: Vec<(&str, TNode)>| {
|
||||
let mut inner = vec![("0", string(""))];
|
||||
inner.extend(kv);
|
||||
TNode::Array(vec![dict(vec![("0", dict(vec![("0", dict(inner))])), ("1", int(0))])])
|
||||
};
|
||||
let text = dict(vec![
|
||||
("0", string("")),
|
||||
("5", dict(vec![("0", entry(vec![("5", para), ("6", int(0))]))])),
|
||||
("6", dict(vec![("0", entry(vec![("5", int(0)), ("6", style)]))])),
|
||||
]);
|
||||
let layout = dict(vec![("0", TNode::Array(vec![dict(vec![("0", int(0))])])), ("2", TNode::Array(Vec::new()))]);
|
||||
dict(vec![("0", text), ("1", layout)])
|
||||
}
|
||||
|
||||
/// A new document, for a box text when `boxed`.
|
||||
pub(crate) fn document(boxed: bool) -> TNode {
|
||||
let fonts = FONTS.iter().map(|f| dict(vec![("0", dict(vec![("99", name("CoolTypeFont")), ("0", dict(vec![("0", string(f))]))]))])).collect();
|
||||
let resources = dict(vec![("1", dict(vec![("0", TNode::Array(fonts))])), ("5", sheets()), ("6", sheets()), ("8", frame(boxed))]);
|
||||
let classes = BREAK_CLASSES.iter().map(|(c, class)| dict(vec![("0", string(&c.to_string())), ("1", string(class))])).collect();
|
||||
let settings = dict(vec![
|
||||
("0", dict(vec![("0", int(3)), ("1", TNode::Array(classes))])),
|
||||
("1", int(0)),
|
||||
("2", int(0)),
|
||||
// Superscript size and offset, subscript size and offset, small caps size.
|
||||
("3", number(0.583)),
|
||||
("4", number(0.333)),
|
||||
("5", number(0.583)),
|
||||
("6", number(0.333)),
|
||||
("7", number(0.7)),
|
||||
("8", boolean(true)),
|
||||
("16", boolean(false)),
|
||||
("17", int(0)),
|
||||
]);
|
||||
let composer = TNode::Array(vec![dict(vec![
|
||||
("0", int(0)),
|
||||
("1", dict(vec![("0", int(7)), ("1", int(10)), ("2", int(0)), ("3", string("DVA"))])),
|
||||
("2", string_bits("10000001000001010001100000000011101000000000000110000000")),
|
||||
("3", string_bits("00110")),
|
||||
("4", TNode::Array(vec![dict(vec![("0", int(0)), ("1", string("Version 7.12"))])])),
|
||||
])]);
|
||||
let doc_body = dict(vec![("0", settings), ("5", composer), ("1", TNode::Array(vec![run()]))]);
|
||||
dict(vec![("0", resources), ("1", doc_body)])
|
||||
}
|
||||
|
||||
/// A string of bits as the composer stores its flags: plain ASCII between parentheses.
|
||||
fn string_bits(bits: &str) -> TNode {
|
||||
TNode::Atom(format!("({bits})").into_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn the_document_parses_back_and_has_the_paths_build_doc_writes() {
|
||||
for boxed in [false, true] {
|
||||
let doc = super::document(boxed);
|
||||
let bytes = crate::export::textdoc::write(&doc);
|
||||
assert_eq!(crate::export::textdoc::parse(&bytes), Some(doc.clone()));
|
||||
for path in ["0/1/0", "1/1[0]/0/5/0[0]/0/0/5", "1/1[0]/0/6/0[0]/0/0/6/53/0", "1/1[0]/1"] {
|
||||
assert!(doc.path(path).is_some(), "{path}");
|
||||
}
|
||||
assert_eq!(doc.path("0/8/0[0]/0/1").is_some(), boxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod needed {
|
||||
/// The parts After Effects skips the layer without, or crashes on (read-backs t2-*, t3-*).
|
||||
#[test]
|
||||
fn the_document_keeps_what_after_effects_needs() {
|
||||
for boxed in [false, true] {
|
||||
let doc = super::document(boxed);
|
||||
for path in ["0/5", "0/6", "0/8", "1/0", "1/5", "1/0/0/0"] {
|
||||
assert!(doc.path(path).is_some(), "{path}");
|
||||
}
|
||||
match doc.path("1/0/0/1") {
|
||||
Some(crate::export::textdoc::TNode::Array(classes)) => assert_eq!(classes.len(), 7),
|
||||
other => panic!("line-break classes: {other:?}"),
|
||||
}
|
||||
assert!(doc.path("1/1[0]/0/5/0[0]/0/0/6").is_some() && doc.path("1/1[0]/0/6/0[0]/0/0/5").is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The composition time base: the pair (frame duration, time scale) After Effects stores for a
|
||||
//! frame rate, and conversions between [`Tick`]s and time units.
|
||||
//!
|
||||
//! Evidence (generated compositions saved by After Effects, see `docs/aep-export.md`): the time
|
||||
//! scale is 23 976 for the NTSC rates (frame duration 1000, 800, 400, 200 for 23.976, 29.97,
|
||||
//! 59.94, 119.88); for every other rate the frame duration is the smallest power of two for which
|
||||
//! `rate x frame duration >= 24 576` (25 fps: 1024 and 25 600; 12 fps: 2048 and 24 576; 1 fps:
|
||||
//! 32 768 and 32 768; 240 fps: 128 and 30 720).
|
||||
|
||||
use crate::container::TimeBase as ContainerTimeBase;
|
||||
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
|
||||
|
||||
/// Frame duration and time scale in units; one frame lasts `frame_duration` units and a second
|
||||
/// has `timescale` units.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct TimeBase {
|
||||
pub frame_duration: u32,
|
||||
pub timescale: u32,
|
||||
}
|
||||
|
||||
/// The 16.16 fixed-point rate After Effects stores next to the time base (a float32 rate).
|
||||
pub(crate) fn fixed_rate(rate: FrameRate) -> u32 {
|
||||
let fps = ntsc_typed(rate).unwrap_or(rate.as_f64() as f32);
|
||||
let v = (f64::from(fps) * 65536.0).round();
|
||||
if v.is_finite() && v >= 0.0 && v <= f64::from(u32::MAX) { v as u32 } else { 0 }
|
||||
}
|
||||
|
||||
/// The typed value of an NTSC rate (23.976, 29.97, 59.94, 119.88), which After Effects stores as
|
||||
/// a float32 of exactly these decimals.
|
||||
pub(crate) fn ntsc_typed(rate: FrameRate) -> Option<f32> {
|
||||
ContainerTimeBase::NTSC.into_iter().find(|((num, den), _)| FrameRate::new(i64::from(*num), i64::from(*den)) == rate).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
/// The time base for `rate`, or `None` for a rate After Effects cannot hold (non-positive, or not
|
||||
/// representable with a frame duration that is a power of two).
|
||||
pub(crate) fn time_base(rate: FrameRate) -> Option<TimeBase> {
|
||||
if rate.num <= 0 || rate.den <= 0 {
|
||||
return None;
|
||||
}
|
||||
if let Some(v) = ntsc_typed(rate) {
|
||||
let fd = if v < 24.0 {
|
||||
1000
|
||||
} else if v < 30.0 {
|
||||
800
|
||||
} else if v < 60.0 {
|
||||
400
|
||||
} else {
|
||||
200
|
||||
};
|
||||
return Some(TimeBase { frame_duration: fd, timescale: 23976 });
|
||||
}
|
||||
let (num, den) = (i128::from(rate.num), i128::from(rate.den));
|
||||
let mut fd: i128 = 1;
|
||||
while fd <= 65536 {
|
||||
let ts = num.checked_mul(fd)?;
|
||||
if ts % den == 0 {
|
||||
let ts = ts / den;
|
||||
if ts >= 24576 {
|
||||
return Some(TimeBase { frame_duration: u32::try_from(fd).ok()?, timescale: u32::try_from(ts).ok()? });
|
||||
}
|
||||
}
|
||||
fd *= 2;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl TimeBase {
|
||||
/// `tick` in time units, rounded to the nearest unit; the second value tells whether it was
|
||||
/// not exact.
|
||||
pub fn units(&self, tick: Tick) -> (i64, bool) {
|
||||
let n = i128::from(tick.0) * i128::from(self.timescale);
|
||||
let d = i128::from(TICKS_PER_SECOND);
|
||||
let q = n.div_euclid(d);
|
||||
let r = n.rem_euclid(d);
|
||||
let rounded = if r * 2 >= d { q + 1 } else { q };
|
||||
(i64::try_from(rounded).unwrap_or(if rounded < 0 { i64::MIN } else { i64::MAX }), r != 0)
|
||||
}
|
||||
|
||||
/// Whole frames of `tick` (nearest).
|
||||
pub fn frames(&self, tick: Tick, rate: FrameRate) -> i64 {
|
||||
let n = i128::from(tick.0) * i128::from(rate.num);
|
||||
let d = i128::from(TICKS_PER_SECOND) * i128::from(rate.den.max(1));
|
||||
let q = n.div_euclid(d);
|
||||
let r = n.rem_euclid(d);
|
||||
let f = if r * 2 >= d { q + 1 } else { q };
|
||||
i64::try_from(f).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rates_match_after_effects() {
|
||||
let tb = |n, d| time_base(FrameRate::new(n, d)).map(|t| (t.frame_duration, t.timescale));
|
||||
assert_eq!(tb(25, 1), Some((1024, 25600)));
|
||||
assert_eq!(tb(30, 1), Some((1024, 30720)));
|
||||
assert_eq!(tb(24, 1), Some((1024, 24576)));
|
||||
assert_eq!(tb(12, 1), Some((2048, 24576)));
|
||||
assert_eq!(tb(25, 2), Some((2048, 25600)));
|
||||
assert_eq!(tb(15, 1), Some((2048, 30720)));
|
||||
assert_eq!(tb(48, 1), Some((512, 24576)));
|
||||
assert_eq!(tb(50, 1), Some((512, 25600)));
|
||||
assert_eq!(tb(60, 1), Some((512, 30720)));
|
||||
assert_eq!(tb(240, 1), Some((128, 30720)));
|
||||
assert_eq!(tb(1, 1), Some((32768, 32768)));
|
||||
assert_eq!(tb(30000, 1001), Some((800, 23976)));
|
||||
assert_eq!(tb(24000, 1001), Some((1000, 23976)));
|
||||
assert_eq!(tb(60000, 1001), Some((400, 23976)));
|
||||
assert_eq!(tb(120000, 1001), Some((200, 23976)));
|
||||
assert_eq!(tb(0, 1), None);
|
||||
assert_eq!(tb(1, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_point_rates() {
|
||||
assert_eq!(fixed_rate(FrameRate::new(25, 1)), 0x19_0000);
|
||||
assert_eq!(fixed_rate(FrameRate::FPS_29_97), 1_964_114);
|
||||
assert_eq!(fixed_rate(FrameRate::FPS_23_976), 1_571_291);
|
||||
assert_eq!(fixed_rate(FrameRate::new(12, 1)), 0xc0000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_round_to_the_nearest() {
|
||||
let tb = TimeBase { frame_duration: 1024, timescale: 25600 };
|
||||
assert_eq!(tb.units(Tick(TICKS_PER_SECOND)), (25600, false));
|
||||
assert_eq!(tb.units(Tick(TICKS_PER_SECOND / 3)).0, 8533);
|
||||
assert!(tb.units(Tick(TICKS_PER_SECOND / 3)).1);
|
||||
assert_eq!(tb.frames(Tick(TICKS_PER_SECOND * 2), FrameRate::new(25, 1)), 50);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Small helpers to edit a chunk tree without panicking: every accessor returns a `Result` with
|
||||
//! [`crate::export::AepExportError::Internal`] when a prototype does not have the expected shape.
|
||||
|
||||
use crate::{Body, Chunk};
|
||||
|
||||
use crate::export::AepExportError;
|
||||
|
||||
pub(crate) type R<T> = Result<T, AepExportError>;
|
||||
|
||||
pub(crate) fn tpl(msg: &'static str) -> AepExportError {
|
||||
AepExportError::Internal(msg)
|
||||
}
|
||||
|
||||
/// The bytes of a data chunk, owned and mutable.
|
||||
pub(crate) fn data_mut<'a>(c: &'a mut Chunk<'static>) -> R<&'a mut Vec<u8>> {
|
||||
match &mut c.body {
|
||||
Body::Data(d) => Ok(d.to_mut()),
|
||||
_ => Err(tpl("expected a data chunk")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The child vector of a list or nested chunk.
|
||||
pub(crate) fn kids_mut<'a>(c: &'a mut Chunk<'static>) -> R<&'a mut Vec<Chunk<'static>>> {
|
||||
match &mut c.body {
|
||||
Body::List { children, .. } | Body::Chunks(children) => Ok(children),
|
||||
_ => Err(tpl("expected a list chunk")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn child_mut<'a>(c: &'a mut Chunk<'static>, id: &[u8; 4]) -> R<&'a mut Chunk<'static>> {
|
||||
kids_mut(c)?.iter_mut().find(|k| k.is(id)).ok_or_else(|| tpl("missing child chunk"))
|
||||
}
|
||||
|
||||
pub(crate) fn list_mut<'a>(c: &'a mut Chunk<'static>, list_type: &[u8; 4]) -> R<&'a mut Chunk<'static>> {
|
||||
kids_mut(c)?.iter_mut().find(|k| k.is_list(list_type)).ok_or_else(|| tpl("missing child list"))
|
||||
}
|
||||
|
||||
/// Mutable bytes of the data child `id`.
|
||||
pub(crate) fn child_data<'a>(c: &'a mut Chunk<'static>, id: &[u8; 4]) -> R<&'a mut Vec<u8>> {
|
||||
data_mut(child_mut(c, id)?)
|
||||
}
|
||||
|
||||
/// The one byte writer of the exporter: `bytes` at `at`, or an error when they do not fit.
|
||||
pub(crate) fn put(d: &mut [u8], at: usize, bytes: &[u8]) -> R<()> {
|
||||
let end = at.checked_add(bytes.len()).ok_or_else(|| tpl("offset overflow"))?;
|
||||
let dst = d.get_mut(at..end).ok_or_else(|| tpl("chunk shorter than its layout"))?;
|
||||
dst.copy_from_slice(bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn put_u8(d: &mut [u8], at: usize, v: u8) -> R<()> {
|
||||
put(d, at, &[v])
|
||||
}
|
||||
pub(crate) fn put_u16(d: &mut [u8], at: usize, v: u16) -> R<()> {
|
||||
put(d, at, &v.to_be_bytes())
|
||||
}
|
||||
pub(crate) fn put_u32(d: &mut [u8], at: usize, v: u32) -> R<()> {
|
||||
put(d, at, &v.to_be_bytes())
|
||||
}
|
||||
pub(crate) fn put_i32(d: &mut [u8], at: usize, v: i32) -> R<()> {
|
||||
put(d, at, &v.to_be_bytes())
|
||||
}
|
||||
pub(crate) fn put_f32(d: &mut [u8], at: usize, v: f32) -> R<()> {
|
||||
put(d, at, &v.to_be_bytes())
|
||||
}
|
||||
pub(crate) fn put_f64(d: &mut [u8], at: usize, v: f64) -> R<()> {
|
||||
put(d, at, &v.to_be_bytes())
|
||||
}
|
||||
|
||||
/// Sets or clears the bits `mask` of byte `at`.
|
||||
pub(crate) fn put_bits(d: &mut [u8], at: usize, mask: u8, on: bool) -> R<()> {
|
||||
let b = d.get_mut(at).ok_or_else(|| tpl("chunk shorter than its layout"))?;
|
||||
if on {
|
||||
*b |= mask;
|
||||
} else {
|
||||
*b &= !mask;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes `text` NUL padded into `d[at..at + len]` (cut at a character boundary so that at least
|
||||
/// one NUL remains).
|
||||
pub(crate) fn put_cstr(d: &mut [u8], at: usize, len: usize, text: &str) -> R<()> {
|
||||
let end = at.checked_add(len).ok_or_else(|| tpl("offset overflow"))?;
|
||||
let dst = d.get_mut(at..end).ok_or_else(|| tpl("chunk shorter than its layout"))?;
|
||||
dst.fill(0);
|
||||
let mut n = 0;
|
||||
for ch in text.chars() {
|
||||
let l = ch.len_utf8();
|
||||
if n + l >= len {
|
||||
break;
|
||||
}
|
||||
let mut buf = [0u8; 4];
|
||||
put(dst, n, ch.encode_utf8(&mut buf).as_bytes())?;
|
||||
n += l;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// How many fixed layouts on this thread did not fit their buffer (see [`Fixed`]); the tests
|
||||
/// keep it at zero.
|
||||
static FIXED_LAYOUT_ERRORS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A buffer whose layout is fixed in code (constant size and offsets, no input from a project).
|
||||
/// Every write goes through [`put`]; a write that does not fit is skipped and its error kept, the
|
||||
/// others are written. Such an error is a bug in the layout, never something a project can cause:
|
||||
/// the tests build every one of these layouts and require no error. The builders keep their
|
||||
/// infallible signatures because files outside this module call them without a `Result`; if a
|
||||
/// layout ever broke, [`Fixed::finish`] logs it once and returns what fit.
|
||||
pub(crate) struct Fixed {
|
||||
bytes: Vec<u8>,
|
||||
error: Option<AepExportError>,
|
||||
}
|
||||
|
||||
impl Fixed {
|
||||
/// `len` zero bytes.
|
||||
pub(crate) fn zeroed(len: usize) -> Fixed {
|
||||
Fixed { bytes: vec![0u8; len], error: None }
|
||||
}
|
||||
|
||||
/// Writes `bytes` at `at`, or keeps the error (the first one) when they do not fit.
|
||||
pub(crate) fn put(&mut self, at: usize, bytes: &[u8]) {
|
||||
self.apply(|d| put(d, at, bytes));
|
||||
}
|
||||
|
||||
/// Runs a writer on the buffer, keeping its error (the first one).
|
||||
pub(crate) fn apply(&mut self, write: impl FnOnce(&mut [u8]) -> R<()>) {
|
||||
if let Err(e) = write(&mut self.bytes) {
|
||||
self.error.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of the first write that did not fit (for the tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn error(&self) -> Option<&AepExportError> {
|
||||
self.error.as_ref()
|
||||
}
|
||||
|
||||
/// The bytes; a write that did not fit is logged once, with what `layout` says.
|
||||
pub(crate) fn finish(self, layout: impl FnOnce() -> String) -> Vec<u8> {
|
||||
if let Some(e) = self.error {
|
||||
FIXED_LAYOUT_ERRORS.with(|n| n.set(n.get().saturating_add(1)));
|
||||
log::error!("aep export: the fixed layout of {} does not fit: {e}", layout());
|
||||
}
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// How many fixed layouts have failed on this thread (for the tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn fixed_layout_errors() -> usize {
|
||||
FIXED_LAYOUT_ERRORS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The entries of a property group by match name (see [`split_group`]).
|
||||
pub(crate) type Entries = Vec<(String, Vec<Chunk<'static>>)>;
|
||||
|
||||
/// Splits the children of a property group into the header (up to the first `tdmn`) and its
|
||||
/// entries by match name: `[tdmn, node]`, or `[tdmn]` for the closing `ADBE Group End`. A match
|
||||
/// name without a node is an error.
|
||||
pub(crate) fn split_group(kids: &mut Vec<Chunk<'static>>) -> R<(Vec<Chunk<'static>>, Entries)> {
|
||||
let first = kids.iter().position(|c| c.is(b"tdmn")).unwrap_or(kids.len());
|
||||
let header: Vec<Chunk<'static>> = kids.drain(..first).collect();
|
||||
let mut entries = Entries::new();
|
||||
let mut it = std::mem::take(kids).into_iter();
|
||||
while let Some(m) = it.next() {
|
||||
let name = crate::export::synth::tdmn_name(&m).unwrap_or_default();
|
||||
if name == crate::export::synth::GROUP_END {
|
||||
entries.push((name, vec![m]));
|
||||
continue;
|
||||
}
|
||||
let node = it.next().ok_or_else(|| tpl("match name without a node"))?;
|
||||
entries.push((name, vec![m, node]));
|
||||
}
|
||||
Ok((header, entries))
|
||||
}
|
||||
|
||||
/// Replaces the `Utf8` child of an item or layer with `text`.
|
||||
pub(crate) fn set_utf8(c: &mut Chunk<'static>, text: &str) -> R<()> {
|
||||
let k = child_mut(c, b"Utf8")?;
|
||||
*k = Chunk::data(*b"Utf8", text.as_bytes().to_vec());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The writer errors instead of dropping.
|
||||
#[test]
|
||||
fn the_writer_errors_instead_of_dropping() {
|
||||
let mut d = [0u8; 4];
|
||||
assert!(put(&mut d, 2, &[1, 2]).is_ok());
|
||||
assert_eq!(d, [0, 0, 1, 2]);
|
||||
// Out of range, partly or wholly, and an offset that overflows: an error, nothing written.
|
||||
assert!(put(&mut d, 3, &[9, 9]).is_err());
|
||||
assert!(put(&mut d, 8, &[9]).is_err());
|
||||
assert!(put(&mut d, usize::MAX, &[9]).is_err());
|
||||
assert_eq!(d, [0, 0, 1, 2]);
|
||||
}
|
||||
|
||||
/// A cut string keeps a nul and whole characters.
|
||||
#[test]
|
||||
fn a_cut_string_keeps_a_nul_and_whole_characters() {
|
||||
let mut d = [0xffu8; 6];
|
||||
put_cstr(&mut d, 0, 6, "ab\u{e9}\u{e9}").unwrap();
|
||||
assert_eq!(d, [b'a', b'b', 0xc3, 0xa9, 0, 0]);
|
||||
assert!(put_cstr(&mut d, 4, 6, "x").is_err());
|
||||
}
|
||||
|
||||
/// Every layout fixed in code fits its buffer: the prototypes of every export (the project
|
||||
/// skeleton, layers, Transform, masks, effects of the whole table, footage of every kind,
|
||||
/// text, cameras, lights, shapes, styles) are built and no write went out of range.
|
||||
#[test]
|
||||
fn every_fixed_layout_fits() {
|
||||
// A delta: other tests on this thread may have counted a broken layout on purpose.
|
||||
let before = fixed_layout_errors();
|
||||
assert!(crate::export::template::Template::load().is_ok());
|
||||
assert_eq!(fixed_layout_errors(), before);
|
||||
}
|
||||
|
||||
/// A broken fixed layout writes what fits and is counted.
|
||||
#[test]
|
||||
fn a_broken_fixed_layout_writes_what_fits_and_is_counted() {
|
||||
let before = fixed_layout_errors();
|
||||
let mut b = Fixed::zeroed(4);
|
||||
b.put(0, &[1]);
|
||||
b.put(3, &[2, 2]);
|
||||
b.put(2, &[3]);
|
||||
assert!(b.error().is_some());
|
||||
assert_eq!(b.finish(|| "a test layout".to_string()), [1, 0, 3, 0]);
|
||||
assert_eq!(fixed_layout_errors(), before + 1);
|
||||
}
|
||||
|
||||
/// A group splits into header and entries.
|
||||
#[test]
|
||||
fn a_group_splits_into_header_and_entries() {
|
||||
use crate::export::synth::{tdmn, tdsn};
|
||||
let rec = || Chunk::list(*b"tdbs", Vec::new());
|
||||
let mut kids = vec![tdsn("h"), tdmn("A"), rec(), tdmn("ADBE Group End")];
|
||||
let (header, entries) = split_group(&mut kids).unwrap();
|
||||
assert_eq!(header.len(), 1);
|
||||
let names: Vec<(&str, usize)> = entries.iter().map(|(n, v)| (n.as_str(), v.len())).collect();
|
||||
assert_eq!(names, [("A", 2), ("ADBE Group End", 1)]);
|
||||
// A match name without its node is an error, not a quiet stop.
|
||||
let mut broken = vec![tdmn("A")];
|
||||
assert!(split_group(&mut broken).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
//! The camera, light, shape and text animator skeletons as tables of [`Node`]s: match names, states, default
|
||||
//! names and the decoded fields of each record (`tree_spec`). The rows were listed from our own
|
||||
//! cases (the case numbers in each doc comment) through the decoded fields only.
|
||||
|
||||
#![cfg_attr(rustfmt, rustfmt::skip)]
|
||||
|
||||
use crate::export::tree_spec::{Node, Node::{G, O, P, R}, Rec};
|
||||
|
||||
/// The property tree of a two-node camera layer (256): Transform with its records and the Camera Options group.
|
||||
pub(crate) static CAMERA_ROOT: &[Node] = &[
|
||||
G("ADBE Transform Group", 1, "-_0_/-", &[
|
||||
R("ADBE Anchor Point", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[960.0, 540.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Position", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[(76, 1), (77, 1)], cdat_len: 72, cdat: &[0.0, 0.0, -2666.6666666], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Position_2", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Scale", Rec { state: 3, label: "-_0_/-", dims: 3, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 120, cdat: &[1.0, 1.0, 1.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Rotate Z", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
]),
|
||||
G("ADBE Camera Options Group", 1, "-_0_/-", &[
|
||||
]),
|
||||
];
|
||||
|
||||
/// The property tree of a spot light layer (254).
|
||||
pub(crate) static SPOT_ROOT: &[Node] = &[
|
||||
G("ADBE Transform Group", 1, "-_0_/-", &[
|
||||
R("ADBE Anchor Point", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[960.0, 540.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Position", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[(76, 1), (77, 1)], cdat_len: 72, cdat: &[0.0, 0.0, -1333.3333333], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Position_2", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Scale", Rec { state: 3, label: "-_0_/-", dims: 3, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 120, cdat: &[1.0, 1.0, 1.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Rotate Z", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
]),
|
||||
G("ADBE Light Options Group", 1, "-_0_/-", &[
|
||||
G("ADBE Light Env Atom", 3, "-_0_/-", &[
|
||||
]),
|
||||
R("ADBE Light Backgd Visible", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Light Backgd Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Light Backgd Blur", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Light Intensity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Light Falloff Start", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[500.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Light Falloff Distance", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[500.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Casts Shadows", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
]),
|
||||
];
|
||||
|
||||
/// The property tree of a point light layer (252).
|
||||
pub(crate) static POINT_ROOT: &[Node] = &[
|
||||
G("ADBE Transform Group", 1, "-_0_/-", &[
|
||||
R("ADBE Anchor Point", Rec { state: 3, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[960.0, 540.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Position", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[(76, 1), (77, 1)], cdat_len: 72, cdat: &[0.0, 0.0, -1333.3333333], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Position_2", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Scale", Rec { state: 3, label: "-_0_/-", dims: 3, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 120, cdat: &[1.0, 1.0, 1.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
O("ADBE Orientation", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x00060007, byte5: 0x07, header: &[(79, 1)], cdat_len: 24, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Rotate X", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Rotate Y", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Rotate Z", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
]),
|
||||
G("ADBE Light Options Group", 1, "-_0_/-", &[
|
||||
G("ADBE Light Env Atom", 3, "-_0_/-", &[
|
||||
]),
|
||||
R("ADBE Light Backgd Visible", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Light Backgd Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Light Backgd Blur", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Light Cone Angle", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[90.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Light Cone Feather 2", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Light Falloff Start", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[500.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Light Falloff Distance", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[500.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Casts Shadows", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
]),
|
||||
];
|
||||
|
||||
/// The property tree of a shape layer (519) apart from Time Remapping and the contents.
|
||||
pub(crate) static SHAPE_ROOT: &[Node] = &[
|
||||
G("ADBE Root Vectors Group", 1025, "-_0_/-", &[
|
||||
]),
|
||||
G("ADBE Transform Group", 1, "-_0_/-", &[
|
||||
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
O("ADBE Orientation", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x00060007, byte5: 0x07, header: &[(79, 1)], cdat_len: 24, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Rotate X", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Rotate Y", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
]),
|
||||
G("ADBE Layer Styles", 3, "-_0_/-", &[
|
||||
G("ADBE Blend Options Group", 3, "-_0_/-", &[
|
||||
G("ADBE Adv Blend Group", 1, "-_0_/-", &[
|
||||
]),
|
||||
]),
|
||||
G("dropShadow/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("innerShadow/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("outerGlow/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("innerGlow/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("bevelEmboss/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("chromeFX/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("solidFill/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("gradientFill/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("patternFill/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
G("frameFX/enabled", 2, "-_0_/-", &[
|
||||
]),
|
||||
]),
|
||||
G("ADBE Extrsn Options Group", 3, "-_0_/-", &[
|
||||
R("ADBE Bevel Direction", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
]),
|
||||
G("ADBE Material Options Group", 3, "-_0_/-", &[
|
||||
R("ADBE Casts Shadows", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Light Transmission", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Accepts Shadows", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Accepts Lights", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Shadow Color", Rec { state: 3, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Appears in Reflections", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Ambient Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Diffuse Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Specular Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Shininess Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[5.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Metal Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Reflection Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Glossiness Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Fresnel Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Transparency Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Transp Rolloff", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Index of Refraction", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: Some((1.0, 2.0)), tdpi: None }),
|
||||
]),
|
||||
G("ADBE Audio Group", 3, "-_0_/-", &[
|
||||
]),
|
||||
G("ADBE Layer Sets", 3, "-_0_/-", &[
|
||||
]),
|
||||
];
|
||||
|
||||
/// The camera and light option records the exporter writes (342-345, 254).
|
||||
pub(crate) static OPTIONS: &[Node] = &[
|
||||
R("ADBE Camera Depth of Field", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Camera Focus Distance", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[800.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Camera Aperture", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Light Intensity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Light Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 255.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Light Cone Angle", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[60.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Light Cone Feather 2", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
];
|
||||
|
||||
/// The shape items the exporter writes, as empty groups with their default names (240, 451-471).
|
||||
pub(crate) static SHAPE_ITEMS: &[Node] = &[
|
||||
G("ADBE Vector Group", 1, "Group 1", &[
|
||||
G("ADBE Vectors Group", 1025, "-_0_/-", &[
|
||||
]),
|
||||
G("ADBE Vector Transform Group", 1, "-_0_/-", &[
|
||||
]),
|
||||
G("ADBE Vector Materials Group", 1, "-_0_/-", &[
|
||||
]),
|
||||
]),
|
||||
G("ADBE Vector Shape - Rect", 1, "Rectangle Path 1", &[
|
||||
]),
|
||||
G("ADBE Vector Shape - Ellipse", 1, "Ellipse Path 1", &[
|
||||
]),
|
||||
G("ADBE Vector Shape - Star", 1, "Polystar Path 1", &[
|
||||
]),
|
||||
G("ADBE Vector Graphic - Fill", 1, "Fill 1", &[
|
||||
]),
|
||||
G("ADBE Vector Graphic - Stroke", 1, "Stroke 1", &[
|
||||
G("ADBE Vector Stroke Dashes", 1, "-_0_/-", &[
|
||||
]),
|
||||
G("ADBE Vector Stroke Taper", 1, "-_0_/-", &[
|
||||
]),
|
||||
G("ADBE Vector Stroke Wave", 1, "-_0_/-", &[
|
||||
]),
|
||||
]),
|
||||
G("ADBE Vector Graphic - G-Fill", 1, "Gradient Fill 1", &[
|
||||
]),
|
||||
G("ADBE Vector Graphic - G-Stroke", 1, "Gradient Stroke 1", &[
|
||||
G("ADBE Vector Stroke Dashes", 1, "-_0_/-", &[
|
||||
]),
|
||||
G("ADBE Vector Stroke Taper", 1, "-_0_/-", &[
|
||||
]),
|
||||
G("ADBE Vector Stroke Wave", 1, "-_0_/-", &[
|
||||
]),
|
||||
]),
|
||||
G("ADBE Vector Filter - Trim", 1, "Trim Paths 1", &[
|
||||
]),
|
||||
G("ADBE Vector Filter - RC", 1, "Round Corners 1", &[
|
||||
]),
|
||||
G("ADBE Vector Filter - Merge", 1, "Merge Paths 1", &[
|
||||
]),
|
||||
G("ADBE Vector Filter - Offset", 1, "Offset Paths 1", &[
|
||||
]),
|
||||
G("ADBE Vector Filter - Repeater", 1, "Repeater 1", &[
|
||||
G("ADBE Vector Repeater Transform", 1, "-_0_/-", &[
|
||||
]),
|
||||
]),
|
||||
G("ADBE Vector Shape - Group", 1, "Path 1", &[
|
||||
P("ADBE Vector Shape", Rec { state: 1, label: "-_0_/-", dims: 1, template: 1, class: 0x00020007, byte5: 0x07, header: &[], cdat_len: 4, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
]),
|
||||
];
|
||||
|
||||
/// The shape value records (239, 242).
|
||||
pub(crate) static SHAPE_RECORDS: &[Node] = &[
|
||||
R("ADBE Vector Ellipse Size", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[400.0, 300.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Vector Fill Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Ellipse Position", Rec { state: 1, label: "-_0_/-", dims: 2, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 48, cdat: &[100.0, 50.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Fill Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Vector Fill Rule", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Anchor", Rec { state: 1, label: "-_0_/-", dims: 2, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 48, cdat: &[10.0, 20.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Scale", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[50.0, 80.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Vector Rotation", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Group Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[40.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Vector Skew", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[20.0], key_size: 0, limits: Some((-85.0, 85.0)), tdpi: None }),
|
||||
R("ADBE Vector Skew Axis", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[45.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Stroke Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 255.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Stroke Width", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[6.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Vector Stroke Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Vector Rect Size", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[200.0, 100.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Vector Rect Roundness", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Vector Stroke Line Cap", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Stroke Line Join", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Vector Stroke Miter Limit", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[4.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Vector Position", Rec { state: 1, label: "-_0_/-", dims: 2, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 48, cdat: &[50.0, 50.0], key_size: 0, limits: None, tdpi: None }),
|
||||
];
|
||||
|
||||
/// The empty text animator group of a text layer (579).
|
||||
pub(crate) static TEXT_ANIMATORS: &[Node] = &[
|
||||
G("ADBE Text Animators", 1, "-_0_/-", &[
|
||||
]),
|
||||
];
|
||||
|
||||
/// One text animator with a range selector and an empty property group (579, 580).
|
||||
pub(crate) static TEXT_ANIMATOR: &[Node] = &[
|
||||
G("ADBE Text Animator", 1, "Animator 1", &[
|
||||
G("ADBE Text Selectors", 1, "-_0_/-", &[
|
||||
G("ADBE Text Selector", 1, "Range Selector 1", &[
|
||||
G("ADBE Text Range Advanced", 1, "-_0_/-", &[
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
G("ADBE Text Animator Properties", 1, "-_0_/-", &[
|
||||
]),
|
||||
]),
|
||||
];
|
||||
|
||||
/// The text animator property records (580-592, 728).
|
||||
pub(crate) static TEXT_ANIMATOR_RECORDS: &[Node] = &[
|
||||
R("ADBE Text Position 3D", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[0.0, -50.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Anchor Point 3D", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[3.0, 4.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Scale 3D", Rec { state: 1, label: "-_0_/-", dims: 3, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 120, cdat: &[150.0, 120.0, 100.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Text Skew", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[10.0], key_size: 0, limits: Some((-70.0, 70.0)), tdpi: None }),
|
||||
R("ADBE Text Skew Axis", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[20.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Rotation", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[45.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[37.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Fill Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Stroke Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }),
|
||||
// text-synthetic.aep (#3170): the record After Effects wrote for Stroke Opacity 40 %.
|
||||
R("ADBE Text Stroke Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[40.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Stroke Width", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[3.0], key_size: 0, limits: Some((-1000.0, 1000.0)), tdpi: None }),
|
||||
R("ADBE Text Tracking Amount", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[20.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Text Line Spacing", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[10.0, 20.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Text Blur", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[5.0, 6.0], key_size: 0, limits: Some((0.0, 10000.0)), tdpi: None }),
|
||||
R("ADBE Text Percent Start", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[25.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Percent End", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[75.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Percent Offset", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[10.0], key_size: 0, limits: Some((-100.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Range Units", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Index Start", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Text Index End", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[4.0], key_size: 0, limits: Some((0.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Text Index Offset", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Text Range Type2", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[3.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Selector Mode", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Selector Max Amount", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((-100.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Range Shape", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Selector Smoothness", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Levels Max Ease", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: Some((-100.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Levels Min Ease", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[40.0], key_size: 0, limits: Some((-100.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Randomize Order", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Random Seed", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[7.0], key_size: 0, limits: Some((0.0, 10000.0)), tdpi: None }),
|
||||
R("ADBE Text Character Offset", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[3.0], key_size: 0, limits: Some((-65535.0, 65535.0)), tdpi: None }),
|
||||
];
|
||||
|
||||
/// The inert Transform records of an AV layer (000): split Position, Orientation, X and Y
|
||||
/// Rotation, Appears in Reflections, all at their defaults (state 3).
|
||||
pub(crate) static AV_TRANSFORM: &[Node] = &[
|
||||
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
|
||||
O("ADBE Orientation", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x00060007, byte5: 0x07, header: &[(79, 1)], cdat_len: 24, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Rotate X", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Rotate Y", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
|
||||
];
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Property trees described as data: groups and records by match name with their decoded fields
|
||||
//! (aep-format.md 3.4), built into chunks by [`build`]. The camera, light, shape and text
|
||||
//! skeletons the exporter fills are tables of these (`tree_defs`).
|
||||
|
||||
use crate::Chunk;
|
||||
use crate::export::synth::{KeyTemplate, RecSpec, key_list, tdb4, tdmn, tdsn};
|
||||
|
||||
/// A property record: its state (`tdsb`), user name, the `tdb4` header fields (components, key
|
||||
/// template, class word, byte 5, decoded bytes that differ from what [`tdb4`] derives), the
|
||||
/// static value (`cdat`: its length and the leading values, the rest zero) or the record size of
|
||||
/// an empty key list, the limits, and a layer id (`tdpi` / `tdps`).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Rec {
|
||||
pub state: u32,
|
||||
pub label: &'static str,
|
||||
pub dims: u8,
|
||||
pub template: u8,
|
||||
pub class: u32,
|
||||
pub byte5: u8,
|
||||
pub header: &'static [(u8, u8)],
|
||||
pub cdat_len: u16,
|
||||
pub cdat: &'static [f64],
|
||||
pub key_size: u16,
|
||||
pub limits: Option<(f64, f64)>,
|
||||
pub tdpi: Option<u32>,
|
||||
}
|
||||
|
||||
/// A node of a property tree.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum Node {
|
||||
/// A group: match name, state, user name, children (the closing `ADBE Group End` is added).
|
||||
G(&'static str, u32, &'static str, &'static [Node]),
|
||||
/// A property record under its match name.
|
||||
R(&'static str, Rec),
|
||||
/// Orientation: its record in an `otst` with `otky` holding one zero `otda` (three degrees)
|
||||
/// per key (aep-format.md 3.5, keyed Orientation).
|
||||
O(&'static str, Rec),
|
||||
/// A path property (`om-s`): its record and `omks` with one empty shape (aep-format.md 3.8).
|
||||
P(&'static str, Rec),
|
||||
}
|
||||
|
||||
fn record(r: &Rec) -> Chunk<'static> {
|
||||
let template = if r.template == 0 { KeyTemplate::Plain } else { KeyTemplate::Spatial(r.template) };
|
||||
let spec = RecSpec { dims: r.dims, template, class: r.class, limits: r.limits, byte5: Some(r.byte5) };
|
||||
let keyed = r.key_size > 0;
|
||||
let mut header = tdb4(&spec, keyed, 25_600);
|
||||
for (at, v) in r.header {
|
||||
if let Some(slot) = header.get_mut(usize::from(*at)) {
|
||||
*slot = *v;
|
||||
}
|
||||
}
|
||||
let mut kids = vec![Chunk::data(*b"tdsb", r.state.to_be_bytes().to_vec()), tdsn(r.label), Chunk::data(*b"tdb4", header)];
|
||||
if keyed {
|
||||
kids.push(key_list(u32::from(r.key_size), 0, Vec::new()));
|
||||
} else {
|
||||
let mut cdat = vec![0u8; usize::from(r.cdat_len)];
|
||||
for (slot, v) in cdat.as_chunks_mut::<8>().0.iter_mut().zip(r.cdat) {
|
||||
slot.copy_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
kids.push(Chunk::data(*b"cdat", cdat));
|
||||
}
|
||||
if let Some((lo, hi)) = r.limits {
|
||||
kids.push(Chunk::data(*b"tdum", lo.to_be_bytes().to_vec()));
|
||||
kids.push(Chunk::data(*b"tduM", hi.to_be_bytes().to_vec()));
|
||||
}
|
||||
if let Some(id) = r.tdpi {
|
||||
kids.push(Chunk::data(*b"tdpi", id.to_be_bytes().to_vec()));
|
||||
kids.push(Chunk::data(*b"tdps", vec![0; 4]));
|
||||
}
|
||||
Chunk::list(*b"tdbs", kids)
|
||||
}
|
||||
|
||||
/// The chunks of `nodes` (each a `tdmn` and its list).
|
||||
pub(crate) fn build(nodes: &[Node]) -> Vec<Chunk<'static>> {
|
||||
let mut out = Vec::with_capacity(nodes.len() * 2);
|
||||
for n in nodes {
|
||||
match n {
|
||||
Node::G(name, state, label, kids) => {
|
||||
let mut body = vec![Chunk::data(*b"tdsb", state.to_be_bytes().to_vec()), tdsn(label)];
|
||||
body.extend(build(kids));
|
||||
body.push(tdmn("ADBE Group End"));
|
||||
out.push(tdmn(name));
|
||||
out.push(Chunk::list(*b"tdgp", body));
|
||||
}
|
||||
Node::R(name, r) => {
|
||||
out.push(tdmn(name));
|
||||
out.push(record(r));
|
||||
}
|
||||
Node::P(name, r) => {
|
||||
let shap = Chunk::list(
|
||||
*b"shap",
|
||||
vec![Chunk::data(*b"shph", crate::export::masks::shph()), key_list(8, 0, Vec::new()), Chunk::data(*b"omtn", Vec::new())],
|
||||
);
|
||||
out.push(tdmn(name));
|
||||
out.push(Chunk::list(*b"om-s", vec![record(r), Chunk::list(*b"omks", vec![shap])]));
|
||||
}
|
||||
Node::O(name, r) => {
|
||||
out.push(tdmn(name));
|
||||
out.push(Chunk::list(*b"otst", vec![record(r), Chunk::list(*b"otky", vec![Chunk::data(*b"otda", vec![0; 24])])]));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
+158
-7
@@ -1,6 +1,6 @@
|
||||
//! After Effects project (`.aep`) import: the typed view of [`effectcraft_aep`] mapped into an
|
||||
//! EffectCraft [`Project`]. The XML form (`.aepx`) is accepted as well: it is read into the same
|
||||
//! chunk tree ([`crate::parse_any`] picks the reader by content).
|
||||
//! EffectCraft [`Project`]. The XML form (`.aepx`) is accepted as well: both are read into the same
|
||||
//! flat chunk index (an `.aep` in place, an `.aepx` decoded into one buffer first).
|
||||
//!
|
||||
//! What arrives: the project item tree (folders), project settings (depth, working space, time
|
||||
//! display), compositions (size, exact frame rate, duration, work area, background, pixel
|
||||
@@ -14,7 +14,8 @@
|
||||
//! missing-footage placeholders). `docs/aep-import.md` has the full list.
|
||||
//!
|
||||
//! What does not arrive is **reported**, never dropped silently: [`ImportReport`] counts other
|
||||
//! effects (by match name) and unimported effect parameters, unusable masks, layer style
|
||||
//! effects (by match name; they arrive as placeholders that render nothing, with their parameters
|
||||
//! for expressions) and unimported effect parameters, unusable masks, layer style
|
||||
//! features, text layer features, shape items, unsupported blend modes and transform
|
||||
//! properties, simplified keyframes and unreadable data per [`LossCategory`]. By default the import
|
||||
//! is refused when anything would be lost ([`ImportOptions::allow_losses`] lifts that); a refusal
|
||||
@@ -27,9 +28,12 @@
|
||||
mod build;
|
||||
mod camera;
|
||||
mod effects;
|
||||
mod lumetri;
|
||||
mod markers;
|
||||
mod masks;
|
||||
mod placeholder;
|
||||
mod props;
|
||||
mod puppet;
|
||||
mod report;
|
||||
mod settings;
|
||||
mod shapes;
|
||||
@@ -40,8 +44,11 @@ mod time;
|
||||
|
||||
use effectcraft_project::{ItemId, Project, ProjectSettings};
|
||||
|
||||
use crate::container::index::{Root, TreeIndex};
|
||||
use crate::container::{AepxDrafts, Limits, index_aepx};
|
||||
|
||||
pub use effects::supported_effects;
|
||||
pub use report::{ImportReport, Imported, LIMITATIONS, Loss, LossCategory, MAX_DETAILS};
|
||||
pub use report::{AeVersionInfo, ImportReport, Imported, LIMITATIONS, Loss, LossCategory, MAX_DETAILS, TESTED_MAJORS, UNKNOWN};
|
||||
|
||||
/// Why an `.aep` was not imported.
|
||||
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
|
||||
@@ -113,13 +120,30 @@ pub struct ImportResult {
|
||||
/// [`AepImportError::Refused`] when something would be lost and `allow_losses` is not set. On any
|
||||
/// error `project` is unchanged.
|
||||
pub fn import(project: &mut Project, bytes: &[u8], options: &ImportOptions<'_>) -> Result<ImportResult, AepImportError> {
|
||||
let file = crate::parse_any(bytes)?;
|
||||
let view = crate::Project::new(&file).ok_or(AepImportError::NoProject)?;
|
||||
// The importer only reads: an `.aep` is indexed in place (one flat array that borrows the
|
||||
// bytes); an `.aepx` is decoded into one buffer, which the index borrows.
|
||||
if crate::is_aepx(bytes) {
|
||||
let AepxDrafts { buffer, nodes, trailer } = index_aepx(bytes, Limits::default())?;
|
||||
let index = TreeIndex::from_drafts(&buffer, nodes, trailer);
|
||||
import_root(project, Root::from(&index), options)
|
||||
} else {
|
||||
let index = TreeIndex::parse(bytes)?;
|
||||
import_root(project, Root::from(&index), options)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`import`] of a file read into either tree.
|
||||
fn import_root(project: &mut Project, file: Root<'_, '_>, options: &ImportOptions<'_>) -> Result<ImportResult, AepImportError> {
|
||||
let view = crate::Project::of(file).ok_or(AepImportError::NoProject)?;
|
||||
// Work on a copy so a refusal leaves the project untouched (compositions are shared, cheap).
|
||||
let mut work = project.clone();
|
||||
let (folder, comps, items, mut report) = build::run(&mut work, &view, options);
|
||||
report.ae_version = report::AeVersionInfo::of_root(file);
|
||||
if let Some(line) = report.ae_version.limitation() {
|
||||
report.limitations.push(line);
|
||||
}
|
||||
let mut col = report::Collector::default();
|
||||
let settings = settings::map(&file, &work.settings, &mut col);
|
||||
let settings = settings::map(file, &work.settings, &mut col);
|
||||
for loss in col.finish().losses.into_iter().filter(|_| options.settings) {
|
||||
let at = report.losses.iter().position(|l| l.category > loss.category).unwrap_or(report.losses.len());
|
||||
report.losses.insert(at, loss);
|
||||
@@ -151,3 +175,130 @@ pub fn analyze_with(bytes: &[u8], options: &ImportOptions<'_>) -> Result<ImportR
|
||||
let options = ImportOptions { allow_losses: true, ..*options };
|
||||
Ok(import(&mut scratch, bytes, &options)?.report)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::container::{AepFile, Body, Chunk, parse, write};
|
||||
|
||||
/// Asserts the two destination projects are structurally equal and serialize identically (layers,
|
||||
/// properties and values included, which `ImportResult` does not carry). Nothing is normalized:
|
||||
/// the import is deterministic, ids and timestamps included.
|
||||
fn same_project(a: &Project, b: &Project, name: &str) {
|
||||
assert!(a == b, "{name}: the imported projects differ through the index");
|
||||
let (ja, jb) = (serde_json::to_string(a).ok(), serde_json::to_string(b).ok());
|
||||
assert!(ja.is_some() && ja == jb, "{name}: the serialized projects differ through the index");
|
||||
}
|
||||
|
||||
/// Imports `bytes` through the owned chunk tree and through the index: the same project, report
|
||||
/// and settings, or the same error.
|
||||
fn both(bytes: &[u8], name: &str) {
|
||||
let exists = |_: &str| true;
|
||||
let options = ImportOptions { allow_losses: true, ..ImportOptions::new(&exists) };
|
||||
match (parse(bytes), TreeIndex::parse(bytes)) {
|
||||
(Ok(file), Ok(index)) => {
|
||||
let (mut pa, mut pb) = (Project::default(), Project::default());
|
||||
let a = import_root(&mut pa, Root::from(&file), &options);
|
||||
let b = import_root(&mut pb, Root::from(&index), &options);
|
||||
assert!(a == b, "{name}: the import differs through the index");
|
||||
same_project(&pa, &pb, name);
|
||||
}
|
||||
(Err(a), Err(b)) => assert_eq!(a, b, "{name}"),
|
||||
(a, b) => panic!("{name}: {:?} vs {:?}", a.err(), b.err()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 40-byte NUL-padded match name.
|
||||
fn tdmn(name: &str) -> Chunk<'static> {
|
||||
let mut b = name.as_bytes().to_vec();
|
||||
b.resize(40, 0);
|
||||
Chunk::data(*b"tdmn", b)
|
||||
}
|
||||
|
||||
/// A synthetic project imports the same through the index.
|
||||
#[test]
|
||||
fn a_synthetic_project_imports_the_same_through_the_index() {
|
||||
// A composition with a layer whose effect stores arbitrary data and a named value group.
|
||||
let utf8 = |id: [u8; 4], t: &str| Chunk { id, body: Body::Chunks(vec![Chunk::data(*b"Utf8", t.as_bytes().to_vec())]), pad: None };
|
||||
let record = Chunk::list(*b"tdbs", vec![Chunk::data(*b"tdsb", vec![0, 0, 0, 1]), Chunk::data(*b"cdat", vec![0, 0, 0, 1])]);
|
||||
let values = Chunk::list(
|
||||
*b"tdgp",
|
||||
vec![
|
||||
utf8(*b"tdsn", "Mine"),
|
||||
tdmn("ADBE Easy Levels2-0001"),
|
||||
record,
|
||||
Chunk::list(*b"aRbs", vec![Chunk::data(*b"aRbp", vec![0u8; 108])]),
|
||||
tdmn("ADBE Group End"),
|
||||
],
|
||||
);
|
||||
let part = Chunk::list(*b"parT", vec![Chunk::data(*b"parn", vec![0, 0, 0, 2]), tdmn("ADBE Easy Levels2-0001"), Chunk::data(*b"pard", vec![0u8; 148])]);
|
||||
let sspc = Chunk::list(*b"sspc", vec![utf8(*b"fnam", "Levels"), part, values]);
|
||||
let parade = Chunk::list(*b"tdgp", vec![tdmn("ADBE Easy Levels2"), sspc, tdmn("ADBE Group End")]);
|
||||
let root = Chunk::list(*b"tdgp", vec![tdmn("ADBE Effect Parade"), parade, tdmn("ADBE Group End")]);
|
||||
let layer = Chunk::list(*b"Layr", vec![Chunk::data(*b"ldta", vec![0u8; 160]), Chunk::data(*b"Utf8", b"Layer".to_vec()), root]);
|
||||
let mut idta = vec![0u8; 64];
|
||||
idta[..2].copy_from_slice(&4u16.to_be_bytes());
|
||||
let mut cdta = vec![0u8; 200];
|
||||
cdta[4..12].copy_from_slice(&[0, 0, 0, 1, 0, 0, 0, 30]);
|
||||
let item = Chunk::list(*b"Item", vec![Chunk::data(*b"idta", idta), Chunk::data(*b"Utf8", b"Comp".to_vec()), Chunk::data(*b"cdta", cdta), layer]);
|
||||
let file = AepFile { chunks: vec![Chunk::data(*b"head", vec![0u8; 20]), Chunk::list(*b"Fold", vec![item])], trailer: std::borrow::Cow::Borrowed(&[]) };
|
||||
both(&write(&file).expect("write"), "synthetic");
|
||||
}
|
||||
|
||||
/// Every `.aep` of the fixture directory (skipped without `EFFECTCRAFT_AEP_FIXTURES`).
|
||||
#[test]
|
||||
fn every_fixture_imports_the_same_through_the_index() {
|
||||
let Some(dir) = std::env::var_os("EFFECTCRAFT_AEP_FIXTURES").filter(|d| !d.is_empty()) else { return };
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
let mut paths: Vec<std::path::PathBuf> =
|
||||
entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aep")).collect();
|
||||
paths.sort();
|
||||
for path in paths {
|
||||
let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
both(&bytes, &path.display().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Imports an `.aepx` through the owned tree ([`crate::read_aepx`]) and through the index
|
||||
/// ([`import`]): the same project, report and settings, or the same error.
|
||||
fn both_aepx(bytes: &[u8], name: &str) -> Result<ImportResult, AepImportError> {
|
||||
let exists = |_: &str| true;
|
||||
let options = ImportOptions { allow_losses: true, ..ImportOptions::new(&exists) };
|
||||
let (mut pa, mut pb) = (Project::default(), Project::default());
|
||||
let a = crate::read_aepx(bytes).map_err(AepImportError::from).and_then(|file| import_root(&mut pa, Root::from(&file), &options));
|
||||
let b = import(&mut pb, bytes, &options);
|
||||
assert!(a == b, "{name}: the .aepx import differs through the index");
|
||||
same_project(&pa, &pb, name);
|
||||
b
|
||||
}
|
||||
|
||||
/// A synthetic `.aepx` imports the same through the index as through the owned tree.
|
||||
#[test]
|
||||
fn a_synthetic_aepx_imports_the_same_through_the_index() {
|
||||
// The comp of the owned-tree test above (`idta` type 4, `cdta` 1/30 s frame duration).
|
||||
let idta = format!("0004{}", "00".repeat(62));
|
||||
let cdta = format!("00000000000000010000001e{}", "00".repeat(188));
|
||||
let x = format!(
|
||||
"<?xml version=\"1.0\"?><AfterEffectsProject><head bdata=\"{}\"/><Fold><Item><idta bdata=\"{idta}\"/><string>Comp</string><cdta bdata=\"{cdta}\"/></Item></Fold><ProjectXMPMetadata>x</ProjectXMPMetadata></AfterEffectsProject>",
|
||||
"00".repeat(20)
|
||||
);
|
||||
let imported = both_aepx(x.as_bytes(), "synthetic").expect("the synthetic project imports");
|
||||
assert_eq!(imported.comps.len(), 1);
|
||||
assert_eq!(both_aepx(b"<AfterEffectsProject/>", "empty").err(), Some(AepImportError::NoProject));
|
||||
assert!(matches!(both_aepx(b"<AfterEffectsProject><a>", "broken"), Err(AepImportError::Container(crate::AepError::Xml { .. }))));
|
||||
}
|
||||
|
||||
/// Every `.aepx` of the fixture directory (skipped without `EFFECTCRAFT_AEP_FIXTURES`).
|
||||
#[test]
|
||||
fn every_fixture_aepx_imports_the_same_through_the_index() {
|
||||
let Some(dir) = std::env::var_os("EFFECTCRAFT_AEP_FIXTURES").filter(|d| !d.is_empty()) else { return };
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
let mut paths: Vec<std::path::PathBuf> =
|
||||
entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aepx")).collect();
|
||||
paths.sort();
|
||||
for path in paths {
|
||||
let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
let _ = both_aepx(&bytes, &path.display().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
-20
@@ -12,7 +12,8 @@ use effectcraft_color::{BlendMode, Label};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{
|
||||
AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, TrackMatte,
|
||||
AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, SourceLayer,
|
||||
TrackMatte,
|
||||
};
|
||||
use effectcraft_time::Tick;
|
||||
|
||||
@@ -25,7 +26,7 @@ use crate::import::props::{AnchorUnit, import_transform};
|
||||
use crate::import::report::{Collector, ImportReport, LossCategory};
|
||||
use crate::import::shapes::import_shapes;
|
||||
use crate::import::styles::import_layer_styles;
|
||||
use crate::import::text::{report_text_extras, text_doc};
|
||||
use crate::import::text::{import_source_text_expression, report_text_extras, text_doc};
|
||||
use crate::import::text_anim::import_animators;
|
||||
use crate::import::time::{TimeMap, frame_rate};
|
||||
|
||||
@@ -206,6 +207,8 @@ fn new_comp(h: &CompHeader, renderer: Option<AepRenderer>, map: &TimeMap, name:
|
||||
comp
|
||||
}
|
||||
|
||||
/// Adds one footage item to the project under the given parent.
|
||||
/// Unreadable footage is recorded as a loss, solids and null placeholders are handled separately, and file and sequence footage is linked to its files.
|
||||
fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_>, name: String, label: Label, parent: ItemId, null_only: &HashSet<u32>) {
|
||||
let Some(f) = item.footage() else {
|
||||
cx.col.lose(LossCategory::DamagedData, format!("footage '{name}': data unreadable, not imported"));
|
||||
@@ -214,7 +217,17 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
|
||||
let aep_id = item.id();
|
||||
// An item without a stored name shows its file's name, a sequence `shot_[0101-0103].exr`
|
||||
// (126, 603-607).
|
||||
let name = if name.is_empty() { default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string()) } else { name };
|
||||
// One layer of a Photoshop file is `<layer>/<file>`, as EffectCraft's own Photoshop import
|
||||
// names it (#3087).
|
||||
let name = if name.is_empty() {
|
||||
let file = default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string());
|
||||
match &f.psd_layer {
|
||||
Some(l) if !l.name.is_empty() => format!("{}/{file}", l.name),
|
||||
_ => file,
|
||||
}
|
||||
} else {
|
||||
name
|
||||
};
|
||||
if f.is_solid {
|
||||
// A null object's placeholder solid is not an item here.
|
||||
if aep_id.is_some_and(|i| null_only.contains(&i)) {
|
||||
@@ -240,31 +253,42 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
|
||||
}
|
||||
let mut path = f.path.clone().unwrap_or_default();
|
||||
// An image sequence's alias is its folder; its files are named by the stored numbering
|
||||
// (353, 603). The first file stands for the sequence, as in EffectCraft.
|
||||
// (353, 603), or listed one by one when imported with Force alphabetical order. The first
|
||||
// file stands for the sequence, as in EffectCraft.
|
||||
let mut sequence = Vec::new();
|
||||
if let Some(seq) = item.sequence_info().filter(|s| !path.is_empty() && s.end >= s.start) {
|
||||
let frames = (seq.end - seq.start).saturating_add(1);
|
||||
if let Some(seq) = item.sequence_info().filter(|s| !path.is_empty() && s.frame_count() > 0) {
|
||||
let frames = seq.frame_count();
|
||||
let sep = if path.contains('\\') { '\\' } else { '/' };
|
||||
let folder = path.trim_end_matches(['\\', '/']).to_string();
|
||||
// One name is the folder, a separator and the file name; the number is as wide as the stored
|
||||
// digits or as the largest number, whichever is longer (an upper bound for every frame).
|
||||
let name_bytes = (folder.len() + 1 + seq.prefix.len() + seq.suffix.len() + usize::try_from(seq.digits.min(16)).unwrap_or(16).max(10)) as u64;
|
||||
let bytes = name_bytes.saturating_mul(u64::from(frames));
|
||||
// One name is the folder, a separator and the file name. A numbered name is as wide as the
|
||||
// stored digits or as the largest number, whichever is longer (an upper bound for every
|
||||
// frame); listed names are counted as they are.
|
||||
let len = |n: usize| u64::try_from(n).unwrap_or(u64::MAX);
|
||||
let file_bytes = if seq.files.is_empty() {
|
||||
len(seq.prefix.len().saturating_add(seq.suffix.len()).saturating_add(usize::try_from(seq.digits.min(16)).unwrap_or(16).max(10)))
|
||||
.saturating_mul(u64::from(frames))
|
||||
} else {
|
||||
seq.files.iter().fold(0u64, |sum, n| sum.saturating_add(len(n.len())))
|
||||
};
|
||||
let bytes = len(folder.len().saturating_add(1)).saturating_mul(u64::from(frames)).saturating_add(file_bytes);
|
||||
if frames > MAX_SEQUENCE_FRAMES || frames > cx.sequence_budget || bytes > cx.sequence_bytes {
|
||||
// Not expanded: the item keeps its first file (a still standing for the sequence).
|
||||
cx.col.lose(
|
||||
LossCategory::DamagedData,
|
||||
format!("footage '{name}': a sequence of {frames} frames is longer than the import expands; only its first file is linked"),
|
||||
);
|
||||
path = format!("{folder}{sep}{}", seq.file_name(seq.start));
|
||||
path = format!("{folder}{sep}{}", seq.nth_file_name(0).unwrap_or_default());
|
||||
} else {
|
||||
cx.sequence_budget -= frames;
|
||||
cx.sequence_bytes -= bytes;
|
||||
sequence = (seq.start..=seq.end).map(|n| format!("{folder}{sep}{}", seq.file_name(n))).collect();
|
||||
sequence = (0..frames).filter_map(|i| seq.nth_file_name(i)).map(|n| format!("{folder}{sep}{n}")).collect();
|
||||
}
|
||||
if let Some(first) = sequence.first() {
|
||||
path = first.clone();
|
||||
}
|
||||
} else if f.is_sequence && !path.is_empty() {
|
||||
// The alias is a folder, but the file names could not be read: the item links the folder.
|
||||
cx.col.lose(LossCategory::DamagedData, format!("footage '{name}': image sequence naming not read, linked to its folder"));
|
||||
}
|
||||
let present = !path.is_empty() && (cx.options.exists)(&path);
|
||||
if !present {
|
||||
@@ -272,6 +296,8 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
|
||||
cx.col.missing_footage.push(shown);
|
||||
}
|
||||
let kind = if sequence.is_empty() { footage_kind(&path, f.native_frame_rate, f.audio_sample_rate.is_some()) } else { FootageKind::Sequence };
|
||||
// A placed PDF / Illustrator file keeps After Effects' framing and size (#3099).
|
||||
let placed_page = kind == FootageKind::Still && is_placed_page_path(&path);
|
||||
let mut footage = Footage {
|
||||
path,
|
||||
kind,
|
||||
@@ -282,7 +308,9 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
|
||||
// footage), and only then.
|
||||
has_audio: kind == FootageKind::Audio || (kind == FootageKind::Video && f.audio_sample_rate.is_some()),
|
||||
missing: !present,
|
||||
placed_page,
|
||||
sequence,
|
||||
layer: source_layer(&f, &name, &mut cx.col),
|
||||
..Footage::default()
|
||||
};
|
||||
// The native frame rate and the stored duration of sequences and clips (352, 603, 606).
|
||||
@@ -314,10 +342,51 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` names a file whose page is framed as After Effects places it
|
||||
/// ([`Footage::placed_page`]): an Illustrator or PDF file, by its extension. EPS files keep
|
||||
/// their bounding box at their own size: how After Effects sizes them was not measured (#3099).
|
||||
fn is_placed_page_path(path: &str) -> bool {
|
||||
let ext = path.rsplit(['/', '\\']).next().and_then(|name| name.rsplit_once('.')).map(|(_, ext)| ext.to_ascii_lowercase());
|
||||
matches!(ext.as_deref(), Some("pdf" | "ai"))
|
||||
}
|
||||
|
||||
/// The Photoshop layer a footage item shows (#3087): at its own bounds when the item is as big
|
||||
/// as they are (Retain Layer Sizes), else on the document. A layer without pixels (an adjustment
|
||||
/// layer) keeps the merged image and is reported. So is a layer as big as the document but not at
|
||||
/// its corner (the item's size fits both framings; its bounds are used), and an item as big as
|
||||
/// neither (the document is used).
|
||||
fn source_layer(f: &crate::Footage, name: &str, col: &mut Collector) -> Option<SourceLayer> {
|
||||
let l = f.psd_layer.as_ref()?;
|
||||
let Some(size) = l.size() else {
|
||||
col.lose(LossCategory::UnsupportedItems, format!("footage '{name}': a Photoshop layer without pixels (an adjustment layer), the merged image used"));
|
||||
return None;
|
||||
};
|
||||
let layer_size = size == (f.width, f.height);
|
||||
if !layer_size && l.document.iter().all(|side| *side > 0) && !l.document_is((f.width, f.height)) {
|
||||
col.lose(
|
||||
LossCategory::UnsupportedItems,
|
||||
format!("footage '{name}': {} x {} is neither the Photoshop layer's size nor the document's, shown on the document", f.width, f.height),
|
||||
);
|
||||
}
|
||||
let [top, left, ..] = l.bounds;
|
||||
if layer_size && (top, left) != (0, 0) && l.document_is(size) {
|
||||
col.lose(
|
||||
LossCategory::UnsupportedItems,
|
||||
format!("footage '{name}': a Photoshop layer as big as the document but at ({left}, {top}), shown at its own bounds (Retain Layer Sizes assumed)"),
|
||||
);
|
||||
}
|
||||
Some(SourceLayer { index: l.index, name: l.name.clone(), layer_size, ..SourceLayer::default() })
|
||||
}
|
||||
|
||||
/// The name After Effects shows for a footage item that stores none: the file's name, or for a
|
||||
/// sequence the name with the frame range (`shot_[0101-0103].exr`).
|
||||
fn default_footage_name(item: &AepItem<'_, '_>, f: &crate::Footage) -> Option<String> {
|
||||
if let Some(s) = item.sequence_info() {
|
||||
// A listed sequence (Force alphabetical order) has no numbering: its first file names it.
|
||||
// Assumption: what After Effects shows for such an item without a stored name was not sampled.
|
||||
if let Some(first) = s.files.first() {
|
||||
return Some(first.clone());
|
||||
}
|
||||
let w = usize::try_from(s.digits.min(16)).unwrap_or(0);
|
||||
return Some(format!("{}[{:0w$}-{:0w$}]{}", s.prefix, s.start, s.end, s.suffix));
|
||||
}
|
||||
@@ -435,11 +504,13 @@ fn camera_light_orient(auto_oriented: bool, light: Option<LightKind>) -> AutoOri
|
||||
}
|
||||
|
||||
/// The unit a layer's anchor is stored in.
|
||||
fn anchor_unit(camera_or_light: bool, text_or_shape: bool, size: (u32, u32)) -> AnchorUnit {
|
||||
fn anchor_unit(camera_or_light: bool, text_or_shape: bool, null: bool, size: (u32, u32)) -> AnchorUnit {
|
||||
if camera_or_light {
|
||||
AnchorUnit::PointOfInterest
|
||||
} else if text_or_shape {
|
||||
AnchorUnit::Pixels
|
||||
} else if null {
|
||||
AnchorUnit::Null(size.0, size.1)
|
||||
} else {
|
||||
AnchorUnit::Source(size.0, size.1)
|
||||
}
|
||||
@@ -479,7 +550,12 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
|
||||
.map(|d| crate::import::text::first_paragraph(&d.raw_text))
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
};
|
||||
let name = aep_name.clone().or_else(|| src.as_ref().map(|s| s.name.clone())).or_else(text_name).unwrap_or_else(|| "Layer".to_string());
|
||||
let name = aep_name
|
||||
.clone()
|
||||
.or_else(|| src.as_ref().map(|s| s.name.clone()))
|
||||
.or_else(text_name)
|
||||
// An empty text layer without a name is named as a new one is (#3233).
|
||||
.unwrap_or_else(|| if h.layer_type == LayerType::Text { "Text" } else { "Layer" }.to_string());
|
||||
let skip = |cx: &mut Ctx<'_>, skipped: &mut HashMap<u32, String>, category: LossCategory, what: &str| {
|
||||
cx.col.lose(category, format!("{comp_name}: {what} '{name}'"));
|
||||
skipped.insert(h.id, what.to_string());
|
||||
@@ -537,6 +613,10 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
|
||||
};
|
||||
let mut l: Layer = build::layer(project, &comp, &name, source.clone(), size, None);
|
||||
l.name = name.clone();
|
||||
// A text layer without a stored name follows its text; a stored name is the user's (#3233).
|
||||
if is_text {
|
||||
l.name_follows_text = Some(aep_name.is_none());
|
||||
}
|
||||
l.label = Label::ALL.get(usize::from(h.label)).copied().unwrap_or(Label::None);
|
||||
apply_timing(&mut l, &h, &tm, &name, &mut cx.col);
|
||||
apply_switches(&mut l, &h);
|
||||
@@ -555,7 +635,7 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
|
||||
import_layer_styles(&layer, &mut l, &comp.global_light, &mut Ids(&mut project.next_id), &tm, &what, &mut cx.col);
|
||||
// Text and shape layers store their anchor in pixels (385, 462); cameras and lights their
|
||||
// point of interest.
|
||||
let anchor = anchor_unit(is_camera || light.is_some(), is_text || is_shape, size);
|
||||
let anchor = anchor_unit(is_camera || light.is_some(), is_text || is_shape, is_null, size);
|
||||
if let Some(tr) = l.props.sub_mut("transform") {
|
||||
import_transform(&layer, &name, comp_size, anchor, &tm, tr, &mut cx.col);
|
||||
}
|
||||
@@ -627,8 +707,8 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
|
||||
}
|
||||
}
|
||||
|
||||
/// The Source Text of a text layer from its text document, and the reports of what is not
|
||||
/// imported.
|
||||
/// The Source Text of a text layer from its text document and its expression, and the reports
|
||||
/// of what is not imported.
|
||||
fn import_source_text(l: &mut Layer, layer: &AepLayer<'_, '_>, what: &str, cx: &mut Ctx<'_>) {
|
||||
match layer.text_document() {
|
||||
Some(doc) => {
|
||||
@@ -640,6 +720,7 @@ fn import_source_text(l: &mut Layer, layer: &AepLayer<'_, '_>, what: &str, cx: &
|
||||
}
|
||||
None => cx.col.lose(LossCategory::DamagedData, format!("{what}: the text document is unreadable, the layer is imported with empty text")),
|
||||
}
|
||||
import_source_text_expression(layer, l.props.prop_mut("text/sourceText"), what, &mut cx.col);
|
||||
report_text_extras(layer, what, &mut cx.col);
|
||||
}
|
||||
|
||||
@@ -681,7 +762,14 @@ fn apply_timing(l: &mut Layer, h: &LayerHeader, tm: &TimeMap, name: &str, col: &
|
||||
col.lose(LossCategory::DamagedData, format!("layer '{name}': the time stretch is zero or unreadable, 100 % is used"));
|
||||
Rational { num: 1, den: 1 }
|
||||
});
|
||||
l.stretch = stretch.to_f64().map_or(100.0, |r| r * 100.0);
|
||||
let stored = stretch.to_f64().map_or(100.0, |r| r * 100.0);
|
||||
// A ratio such as 1/2^31 (5e-8 %) or 2^31/1 is outside what After Effects allows (±1 % to
|
||||
// ±9900 %); taken as stored, the layer and audio time would divide by ~0 (#3247). The in and
|
||||
// out points keep the comp times the file stores.
|
||||
l.stretch = effectcraft_project::limits::stretch(stored);
|
||||
if l.stretch.to_bits() != stored.to_bits() {
|
||||
col.lose(LossCategory::DamagedData, format!("layer '{name}': the time stretch of {stored:e} % is outside ±1 % to ±9900 %, {} % is used", l.stretch));
|
||||
}
|
||||
// A stored time with a zero denominator (or a sum that overflows) has no value; it is read as 0
|
||||
// and reported, so the layer's timing never changes silently.
|
||||
let unreadable: Vec<&str> = [("start", h.start), ("in point", h.in_relative), ("out point", h.out_relative)]
|
||||
@@ -704,8 +792,9 @@ fn apply_timing(l: &mut Layer, h: &LayerHeader, tm: &TimeMap, name: &str, col: &
|
||||
}
|
||||
|
||||
/// After Effects ends a layer of timed footage (a clip, a sequence, a sound) at its source's end
|
||||
/// when it opens a project, whatever out point the file stores (f1: layers stored 5 s long over a
|
||||
/// 1 s clip, a 3-frame sequence and a 1 s WAV read back 1, 0.1 and 1 s long). A remapped or looped layer keeps its out point, and so does one that runs
|
||||
/// when it opens a project, whatever out point the file stores (export test f1: layers written
|
||||
/// 5 s long over a 1 s clip, a 3-frame sequence and a 1 s WAV read back 1, 0.1 and 1 s long; R31
|
||||
/// of aep-export.md). A remapped or looped layer keeps its out point, and so does one that runs
|
||||
/// less than a composition frame past (`frame`): a clip's duration need not be whole frames.
|
||||
fn end_at_source(project: &Project, l: &mut Layer, frame: Tick) {
|
||||
let LayerSource::Footage { item } = &l.source else { return };
|
||||
@@ -871,6 +960,18 @@ fn resolve_parents(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #3099: an `.ai` or `.pdf` from an `.aep` is a placed page; an EPS (not measured in After
|
||||
/// Effects) and other files are not.
|
||||
#[test]
|
||||
fn only_illustrator_and_pdf_files_are_placed_pages() {
|
||||
for path in [r"C:\fixture\x\logo.ai", "/work/Logo.AI", "art.pdf", r"C:\a.b\page.PDF"] {
|
||||
assert!(is_placed_page_path(path), "{path}");
|
||||
}
|
||||
for path in [r"C:\fixture\x\still.eps", "a.epsf", "a.epsi", "still.png", r"C:\dir.ai\file", "ai", ""] {
|
||||
assert!(!is_placed_page_path(path), "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlisted_extensions_follow_what_the_file_stores() {
|
||||
assert_eq!(footage_kind("C:/clips/a.MP4", 0, false), FootageKind::Video);
|
||||
|
||||
@@ -83,8 +83,8 @@ fn import_group(group: &AepGroup<'_, '_>, table: &[(&str, &str, Kind)], what: &s
|
||||
if !is_stored(&node) {
|
||||
continue;
|
||||
}
|
||||
// Blur Level at 100 (the default) is neutral: stored explicitly, After Effects reads it
|
||||
// back as 100 % (read-back o1); other values are not sampled.
|
||||
// Blur Level at 100 (the default) is neutral: the exporter writes it explicitly and After
|
||||
// Effects reads it back as 100 % (export read-back o1); other values are not sampled.
|
||||
if name == "ADBE Camera Blur Level"
|
||||
&& !node.is_animated()
|
||||
&& node.expression().is_none()
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Effects: a table maps an After Effects effect (its match name) and its parameters (by their
|
||||
//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Effects and
|
||||
//! parameters outside the table are reported in [`LossCategory::Effects`] by match name, never
|
||||
//! dropped silently.
|
||||
//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Parameters
|
||||
//! outside the table are reported in [`LossCategory::Effects`] by match name, never dropped
|
||||
//! silently. An effect outside it arrives as a placeholder holding its parameters (`placeholder.rs`)
|
||||
//! and is reported too.
|
||||
//!
|
||||
//! Every conversion is backed by the corpus (`docs/aep-format.md` 3.7, cases 356-450, 511-516):
|
||||
//!
|
||||
@@ -34,10 +35,10 @@
|
||||
//! import. Hue/Saturation's master values and Levels' values are arbitrary data, decoded by the
|
||||
//! reader (444-446, 512-516).
|
||||
|
||||
use crate::effect_map::{Conv, EFFECTS, EffectMap, Extra, HUE_SATURATION_MASTER, LEVELS_RGB, popup_key};
|
||||
use crate::effect_map::{CRYPTOMATTE_OUTPUT, Conv, EFFECTS, EffectMap, Extra, HUE_SATURATION_MASTER, LEVELS_RGB, ParamMap, popup_alias, popup_key};
|
||||
use crate::{
|
||||
CurvesData, DefinitionSource, Effect as AepEffect, EffectDefinitions, EffectParam, HueSaturationData, Layer as AepLayer, LayerRef, LevelsData, MeshData,
|
||||
ParamKind, ParamValue,
|
||||
CryptomatteData, CurvesData, DefinitionSource, Effect as AepEffect, EffectDefinitions, EffectParam, ExtractorChannels, HueSaturationData,
|
||||
Layer as AepLayer, LayerRef, LevelsData, MeshData, ParamKind, ParamValue,
|
||||
};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::Ids;
|
||||
@@ -76,39 +77,82 @@ pub(crate) fn import_effects<'f, 'a>(
|
||||
col: &mut Collector,
|
||||
) {
|
||||
for fx in layer.effects() {
|
||||
let shown = fx.display_name().unwrap_or_else(|| fx.match_name().to_string());
|
||||
let Some(map) = EFFECTS.iter().find(|m| m.match_name == fx.match_name()) else {
|
||||
col.lose(LossCategory::Effects, format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()));
|
||||
continue;
|
||||
};
|
||||
let Some(spec) = effectcraft_effects::find(map.effect) else {
|
||||
col.lose(LossCategory::Effects, format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()));
|
||||
continue;
|
||||
};
|
||||
if defs.source(&fx) == DefinitionSource::Missing {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{}: '{}' has the effect '{shown}' ({}) without readable parameter definitions, not imported", cx.comp, cx.layer, fx.match_name()),
|
||||
);
|
||||
// Puppet keeps its meshes and pins in nested groups, not in `parT` (its own step).
|
||||
if fx.match_name() == crate::import::puppet::MATCH_NAME {
|
||||
crate::import::puppet::import_puppet(defs, &fx, cx, ids, target, col);
|
||||
continue;
|
||||
}
|
||||
let size = [f64::from(cx.size.0), f64::from(cx.size.1)];
|
||||
let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size);
|
||||
match fx.enabled() {
|
||||
Some(on) => group.enabled = on,
|
||||
None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)),
|
||||
let shown = fx.display_name().unwrap_or_else(|| fx.match_name().to_string());
|
||||
let found = EFFECTS.iter().find(|m| m.match_name == fx.match_name()).and_then(|m| Some((m, effectcraft_effects::find(m.effect)?)));
|
||||
let lost = format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
|
||||
if defs.source(&fx) == DefinitionSource::Missing {
|
||||
match found {
|
||||
Some(_) => col.lose(LossCategory::Effects, format!("{lost} without readable parameter definitions, not imported")),
|
||||
None => col.lose_unmapped_effect(fx.match_name(), lost),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if found.is_none() && col.placeholder_cost >= crate::import::placeholder::MAX_COST {
|
||||
// The import's placeholder budget is spent: the definitions (shared by many instances)
|
||||
// are not read again. Named like any effect without a counterpart, in a group of its
|
||||
// own (with the kept instances it would read as kept).
|
||||
let key = format!("{} (not kept)", fx.match_name());
|
||||
col.lose_unmapped_effect(&key, format!("{lost}, not kept (past the import's placeholder parameters)"));
|
||||
continue;
|
||||
}
|
||||
let params = defs.params(&fx);
|
||||
for p in ¶ms {
|
||||
import_param(&fx, map, p, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
|
||||
report_records_without_definition(&fx, ¶ms, cx, &shown, col);
|
||||
let Some((map, spec)) = found else {
|
||||
// No counterpart: kept as a placeholder that renders nothing, for expressions (#3087).
|
||||
let mut group = crate::import::placeholder::placeholder(&fx, ¶ms, cx, &shown, ids, refs, col);
|
||||
set_enabled(&fx, &mut group, cx, &shown, col);
|
||||
col.lose_unmapped_effect(fx.match_name(), format!("{lost}, kept without rendering"));
|
||||
col.imported.placeholder_effects = col.imported.placeholder_effects.saturating_add(1);
|
||||
target.children.push(Node::Group(group));
|
||||
continue;
|
||||
};
|
||||
let size = [f64::from(cx.size.0), f64::from(cx.size.1)];
|
||||
let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size);
|
||||
set_enabled(&fx, &mut group, cx, &shown, col);
|
||||
if map.extra == Extra::Lumetri {
|
||||
crate::import::lumetri::import_lumetri(&fx, ¶ms, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
|
||||
} else if map.extra == Extra::Cryptomatte {
|
||||
import_cryptomatte(&fx, ¶ms, cx, &shown, &mut group, col);
|
||||
} else {
|
||||
for p in ¶ms {
|
||||
import_param(&fx, map, p, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
|
||||
}
|
||||
}
|
||||
col.imported.effects = col.imported.effects.saturating_add(1);
|
||||
target.children.push(Node::Group(group));
|
||||
}
|
||||
}
|
||||
|
||||
/// The effect's fx switch.
|
||||
fn set_enabled(fx: &AepEffect<'_, '_>, group: &mut PropGroup, cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) {
|
||||
match fx.enabled() {
|
||||
Some(on) => group.enabled = on,
|
||||
None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed definitions (another instance's or the project copy) may not name every value record
|
||||
/// this instance has: such a record has nothing to import into, so it is reported.
|
||||
fn report_records_without_definition(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) {
|
||||
if !params.first().is_some_and(|p| p.borrowed_definition) {
|
||||
return;
|
||||
}
|
||||
let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect();
|
||||
for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported", cx.comp, cx.layer, fx.match_name()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters that never carry a value to import.
|
||||
fn carries_nothing(p: &EffectParam<'_, '_>) -> bool {
|
||||
pub(crate) fn carries_nothing(p: &EffectParam<'_, '_>) -> bool {
|
||||
matches!(p.kind, ParamKind::Button | ParamKind::NoData | ParamKind::GroupStart | ParamKind::GroupEnd) || (p.index == 0 && p.kind == ParamKind::Layer)
|
||||
}
|
||||
|
||||
@@ -127,10 +171,15 @@ pub(crate) struct PendingLayerRef {
|
||||
|
||||
/// Where a parameter is imported to: the effect's group, the layer parameters still to resolve
|
||||
/// and the report.
|
||||
struct ParamOut<'a> {
|
||||
group: &'a mut PropGroup,
|
||||
refs: &'a mut Vec<PendingLayerRef>,
|
||||
col: &'a mut Collector,
|
||||
pub(crate) struct ParamOut<'a> {
|
||||
pub group: &'a mut PropGroup,
|
||||
pub refs: &'a mut Vec<PendingLayerRef>,
|
||||
pub col: &'a mut Collector,
|
||||
}
|
||||
|
||||
/// How a parameter is named in the report: its name and match name.
|
||||
pub(crate) fn param_label(p: &EffectParam<'_, '_>) -> String {
|
||||
if p.name.trim().is_empty() { p.match_name.clone() } else { format!("{} ({})", p.name.trim(), p.match_name) }
|
||||
}
|
||||
|
||||
/// Imports one parameter of `fx` into its EffectCraft property: its keyframes, the value in its
|
||||
@@ -140,7 +189,7 @@ fn import_param(fx: &AepEffect<'_, '_>, map: &EffectMap, p: &EffectParam<'_, '_>
|
||||
if carries_nothing(p) {
|
||||
return;
|
||||
}
|
||||
let label = if p.name.is_empty() { p.match_name.clone() } else { format!("{} ({})", p.name, p.match_name) };
|
||||
let label = param_label(p);
|
||||
let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
|
||||
if p.kind == ParamKind::ArbitraryData && map.extra != Extra::None {
|
||||
import_extra(fx, map.extra, p, &here, cx.size, group, col);
|
||||
@@ -154,6 +203,14 @@ fn import_param(fx: &AepEffect<'_, '_>, map: &EffectMap, p: &EffectParam<'_, '_>
|
||||
}
|
||||
return;
|
||||
};
|
||||
import_mapped(p, m, cx, (&here, &label), ParamOut { group, refs, col });
|
||||
}
|
||||
|
||||
/// Imports parameter `p` into the property `m` names, converted by `m.conv`. `names` is
|
||||
/// `(here, label)`, the effect and the parameter for the report.
|
||||
pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) {
|
||||
let (here, label) = names;
|
||||
let ParamOut { group, refs, col } = out;
|
||||
if p.kind != m.kind {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} has type {:?}, expected {:?}; not imported", p.kind, m.kind));
|
||||
return;
|
||||
@@ -161,7 +218,7 @@ fn import_param(fx: &AepEffect<'_, '_>, map: &EffectMap, p: &EffectParam<'_, '_>
|
||||
match m.conv {
|
||||
Conv::Skip => return,
|
||||
Conv::LayerRef { own } => {
|
||||
import_layer_ref(p, m.target, own, cx, (&here, &label), ParamOut { group, refs, col });
|
||||
import_layer_ref(p, m.target, own, cx, (here, label), ParamOut { group, refs, col });
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
@@ -202,23 +259,12 @@ fn import_param(fx: &AepEffect<'_, '_>, map: &EffectMap, p: &EffectParam<'_, '_>
|
||||
Conv::Checkbox => Kind::EffectBool,
|
||||
// Handled above.
|
||||
Conv::LayerRef { .. } | Conv::Skip => return,
|
||||
Conv::Percent { valid_max } => {
|
||||
Conv::Percent { valid_max } | Conv::Plain { valid_max } | Conv::Factor { valid_max, .. } => {
|
||||
if !checked(valid_max, col) {
|
||||
return;
|
||||
}
|
||||
Kind::EffectNumber(100.0 / valid_max)
|
||||
}
|
||||
Conv::Plain { valid_max } => {
|
||||
if !checked(valid_max, col) {
|
||||
return;
|
||||
}
|
||||
Kind::EffectNumber(1.0)
|
||||
}
|
||||
Conv::Factor { valid_max, factor } => {
|
||||
if !checked(valid_max, col) {
|
||||
return;
|
||||
}
|
||||
Kind::EffectNumber(factor)
|
||||
let Some(scale) = m.conv.number_scale() else { return };
|
||||
Kind::EffectNumber(scale)
|
||||
}
|
||||
};
|
||||
// Grouped parameters are addressed by path (`master/exposure`).
|
||||
@@ -266,8 +312,9 @@ fn import_param(fx: &AepEffect<'_, '_>, map: &EffectMap, p: &EffectParam<'_, '_>
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} has no readable keyframe, default used"));
|
||||
}
|
||||
if let Some(map) = &popup_map {
|
||||
remap_popup_keys(prop, map, &here, &label, col);
|
||||
remap_popup_keys(prop, map, here, label, col);
|
||||
}
|
||||
report_beyond_limit(m.limit, prop.keys.iter().map(|k| &k.value), here, label, col);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -302,15 +349,28 @@ fn import_param(fx: &AepEffect<'_, '_>, map: &EffectMap, p: &EffectParam<'_, '_>
|
||||
_ => convert(value, kind),
|
||||
};
|
||||
match converted {
|
||||
Some(v) => prop.value = v,
|
||||
Some(v) => {
|
||||
report_beyond_limit(m.limit, std::iter::once(&v), here, label, col);
|
||||
prop.value = v;
|
||||
}
|
||||
None => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?}), default used")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports a value After Effects accepts but EffectCraft's effect limits (`ParamMap::limit`): it is
|
||||
/// imported as it is, and the effect renders it as the nearest end of its range.
|
||||
fn report_beyond_limit<'v>(limit: Option<(f64, f64)>, values: impl Iterator<Item = &'v Value>, here: &str, label: &str, col: &mut Collector) {
|
||||
let Some((lo, hi)) = limit else { return };
|
||||
let beyond: Vec<f64> = values.filter_map(|v| if let Value::Scalar(x) = v { Some(*x) } else { None }).filter(|x| *x < lo || *x > hi).collect();
|
||||
if let Some(x) = beyond.first() {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} is {x}, EffectCraft's effect uses {lo} to {hi} (rendered as the nearest of them)"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer parameter: None stays unset, the owning layer is itself (`own`) or unset, another layer
|
||||
/// is resolved by [`resolve_layer_refs`] once the composition's layers exist.
|
||||
/// `names` is `(here, label)`, the effect and the parameter for the report.
|
||||
fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) {
|
||||
pub(crate) fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) {
|
||||
let (here, label) = names;
|
||||
let ParamOut { group, refs, col } = out;
|
||||
// After Effects hands the named layer's source to the effect, without its masks and effects
|
||||
@@ -359,8 +419,8 @@ pub(crate) fn resolve_layer_refs(
|
||||
}
|
||||
}
|
||||
|
||||
/// The EffectCraft item of each file item (by name, ignoring case and separators); `None` when
|
||||
/// the parameter here is not a popup.
|
||||
/// The EffectCraft item of each file item (by name, ignoring case and separators, and a known
|
||||
/// non-English name for it, [`popup_alias`]); `None` when the parameter here is not a popup.
|
||||
fn popup_mapping(file_items: &[String], ui: &ParamUi) -> Option<Vec<Option<u32>>> {
|
||||
let ParamUi::Popup { options } = ui else { return None };
|
||||
let norm = popup_key;
|
||||
@@ -371,7 +431,12 @@ fn popup_mapping(file_items: &[String], ui: &ParamUi) -> Option<Vec<Option<u32>>
|
||||
if item.trim() == "(-" {
|
||||
return None;
|
||||
}
|
||||
options.iter().position(|o| norm(o) == norm(item)).and_then(|i| u32::try_from(i).ok())
|
||||
let key = norm(item);
|
||||
options
|
||||
.iter()
|
||||
.position(|o| norm(o) == key)
|
||||
.or_else(|| popup_alias(&key).and_then(|a| options.iter().position(|o| norm(o) == a)))
|
||||
.and_then(|i| u32::try_from(i).ok())
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
@@ -404,7 +469,15 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
|
||||
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {} are not imported", p.name));
|
||||
}
|
||||
let Some(data) = fx.arbitrary_data(&p.match_name) else {
|
||||
// No data: every value is at its default.
|
||||
// No record: every value is at its default. A Channel Info value record without its
|
||||
// aRbs/aRbp payload (every sampled record has it) is damaged: the payload may have chosen
|
||||
// other channels (`Z`), so the defaults are not what After Effects renders.
|
||||
if p.stored().is_some() && matches!(extra, Extra::Extractor | Extra::Identifier) {
|
||||
col.lose(
|
||||
LossCategory::DamagedData,
|
||||
format!("{here}: the Channel Info data is missing (a value record without its data), the default channels used"),
|
||||
);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let mut set = |id: &str, v: f64| {
|
||||
@@ -455,10 +528,205 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
|
||||
Some(m) => import_mesh(&m, here, size, group, col),
|
||||
None => col.lose(LossCategory::DamagedData, format!("{here}: the Distortion Mesh is unreadable, defaults used")),
|
||||
},
|
||||
Extra::None => {}
|
||||
Extra::Extractor => match ExtractorChannels::parse(data).map(|c| (c.sources(effectcraft_effects::EXTRACTOR_COPY), c)) {
|
||||
// Each output channel reads the footage's channel of the stored name, which
|
||||
// EffectCraft's EXtractoR finds by the same name (`Z`); After Effects' `(copy)` is the
|
||||
// input's own channel, EffectCraft's `(copy)` (not `A`, which EffectCraft reads from an
|
||||
// OpenEXR footage's alpha plane, losing what earlier effects did to it).
|
||||
Some((Ok(names), _)) => {
|
||||
for (id, name) in ["red", "green", "blue", "alpha"].into_iter().zip(names) {
|
||||
if let Some(prop) = group.prop_mut(id) {
|
||||
prop.value = Value::Str(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((Err(k), c)) => {
|
||||
let names: Vec<&str> = c.channels.iter().map(|(_, n)| n.as_str()).collect();
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!(
|
||||
"{here}: the channels {} are not imported (record {} is of an unknown kind or names no channel), R, G, B, A used",
|
||||
names.join(", "),
|
||||
k.saturating_add(1)
|
||||
),
|
||||
);
|
||||
}
|
||||
None => col.lose(LossCategory::Effects, format!("{here}: the Channel Info data is not in the sampled layout, R, G, B, A used")),
|
||||
},
|
||||
Extra::Identifier => match crate::identifier_channel_type(data) {
|
||||
// No channel chosen (the type's label): After Effects lists only the footage's integer
|
||||
// (UINT) channels and, with none chosen, leaves the layer unchanged, where EffectCraft
|
||||
// draws the footage's object ID channel.
|
||||
Some("Object ID") => {
|
||||
if let Some(prop) = group.prop_mut("channelType") {
|
||||
prop.value = Value::Enum(0);
|
||||
}
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: no ID channel is chosen (Channel Info), so After Effects leaves the layer unchanged; EffectCraft draws the footage's object ID channel"),
|
||||
);
|
||||
}
|
||||
// A chosen channel, by name. EffectCraft's IDentifier has no channel of its own: it
|
||||
// reads the footage's first `ObjectID` (`MaterialID`) channel, names compared without
|
||||
// regard to case, so a channel of that name is the one After Effects reads.
|
||||
Some(name) => match IDENTIFIER_OWN.iter().position(|own| own.eq_ignore_ascii_case(name.trim())) {
|
||||
Some(kind) => {
|
||||
if let Some(prop) = group.prop_mut("channelType") {
|
||||
prop.value = Value::Enum(u32::try_from(kind).unwrap_or(0));
|
||||
}
|
||||
}
|
||||
None => col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: the ID channel '{name}' (Channel Info) is not imported; EffectCraft reads the footage's object ID channel (ObjectID, object_id, objectId, id)"),
|
||||
),
|
||||
},
|
||||
None => col.lose(LossCategory::Effects, format!("{here}: the Channel Info data is not in the sampled layout, the object ID channel used")),
|
||||
},
|
||||
Extra::None | Extra::Lumetri | Extra::Cryptomatte => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Cryptomatte plug-in (`Extra::Cryptomatte`, docs/aep-format.md 3.7): 1 Settings data
|
||||
/// (the layer by name and the selection, both carried as text), 2 Output (EffectCraft's Display
|
||||
/// and Matte Only), 3 Selection Mode (reported when on). Anything else stored is reported.
|
||||
fn import_cryptomatte(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx: &LayerCtx<'_>, shown: &str, group: &mut PropGroup, col: &mut Collector) {
|
||||
let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
|
||||
let set = |group: &mut PropGroup, id: &str, v: Value| {
|
||||
if let Some(prop) = group.prop_mut(id) {
|
||||
prop.value = v;
|
||||
}
|
||||
};
|
||||
// The plug-in's Output starts at Colors (EffectCraft's Display starts at Preview); an Output
|
||||
// that cannot be imported keeps it.
|
||||
let (display, matte_only) = CRYPTO_COLORS;
|
||||
set(group, "display", Value::Enum(display));
|
||||
set(group, "matteOnly", Value::Bool(matte_only));
|
||||
for p in params {
|
||||
if carries_nothing(p) {
|
||||
continue;
|
||||
}
|
||||
let label = if p.name.is_empty() { p.match_name.clone() } else { format!("{} ({})", p.name, p.match_name) };
|
||||
let moving = p.is_animated() || p.stored().is_some_and(|s| s.expression().is_some());
|
||||
match (p.index, p.kind) {
|
||||
(1, ParamKind::ArbitraryData) => {
|
||||
if moving {
|
||||
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported"));
|
||||
}
|
||||
// No record: the definition's default, no layer and no selection. A record
|
||||
// without its data (every sampled record has it) is damaged.
|
||||
let Some(data) = fx.arbitrary_data(&p.match_name) else {
|
||||
if p.stored().is_some() {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: the Cryptomatte settings (layer, selection) have no data, none used"));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
match CryptomatteData::parse(data) {
|
||||
Some(d) => {
|
||||
set(group, "layerName", Value::Str(d.layer));
|
||||
set(group, "selection", Value::Str(d.selection));
|
||||
}
|
||||
None => col.lose(LossCategory::DamagedData, format!("{here}: the Cryptomatte settings (layer, selection) are unreadable, none used")),
|
||||
}
|
||||
}
|
||||
(2, ParamKind::Popup) => {
|
||||
if moving {
|
||||
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported, Colors used"));
|
||||
continue;
|
||||
}
|
||||
let (display, matte_only) = crypto_output(p, &here, &label, col);
|
||||
set(group, "display", Value::Enum(display));
|
||||
set(group, "matteOnly", Value::Bool(matte_only));
|
||||
}
|
||||
(3, ParamKind::Checkbox) => {
|
||||
if moving {
|
||||
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported"));
|
||||
} else {
|
||||
match selection_mode_on(p) {
|
||||
// A picking switch of the plug-in; EffectCraft picks with its own tool.
|
||||
Some(true) => col.lose(LossCategory::Effects, format!("{here}: parameter {label} is on and has no counterpart")),
|
||||
Some(false) => {}
|
||||
None => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value, off used")),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if p.stored().is_some() && !matches!(p.stored_value(), Some(ParamValue::Layer(0))) {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} ({:?}) not imported", p.kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// EffectCraft's (Display, Matte Only) for the plug-in's Output Colors, its default.
|
||||
const CRYPTO_COLORS: (u32, bool) = (0, false);
|
||||
|
||||
/// Is Selection Mode on? The plug-in writes it, when on, as a record in the default state
|
||||
/// (`tdsb` 3) holding 1.0, which [`EffectParam::stored_value`] does not read; After Effects
|
||||
/// reads it back as on and renders it (1400 `crypto-01-set-all`, `crypto-02-chk-toggled`). So
|
||||
/// the record's value counts whatever its state; no record is off (the `pard` default). `None`
|
||||
/// when a record is there but its value cannot be read (never the definition's default then).
|
||||
fn selection_mode_on(p: &EffectParam<'_, '_>) -> Option<bool> {
|
||||
match p.stored() {
|
||||
Some(s) => s.static_value().and_then(|v| v.first().copied()).map(|v| v != 0.0),
|
||||
None => Some(p.value() == Some(ParamValue::Bool(true))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cryptomatte's Output as EffectCraft's (Display, Matte Only): Colors is Colors, Matted RGBA
|
||||
/// is Matte (the layer keyed by the selection), Matte Only is Matte Only. Matted Colors (the
|
||||
/// ID colours keyed by the selection) becomes Matte, the same matte over the layer's own
|
||||
/// colours, and is reported; a value that cannot be read is reported and Colors used.
|
||||
fn crypto_output(p: &EffectParam<'_, '_>, here: &str, label: &str, col: &mut Collector) -> (u32, bool) {
|
||||
let items: Vec<String> = match &p.items {
|
||||
Some(items) => items.clone(),
|
||||
None if p.popup_item_count().map(usize::from) == Some(CRYPTOMATTE_OUTPUT.len()) => CRYPTOMATTE_OUTPUT.iter().map(|s| s.to_string()).collect(),
|
||||
None => {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: parameter {label}: the file names no popup items and has {:?} of them, not imported, Colors used", p.popup_item_count()),
|
||||
);
|
||||
return CRYPTO_COLORS;
|
||||
}
|
||||
};
|
||||
let index = match (p.stored(), p.stored_value()) {
|
||||
(Some(_), Some(ParamValue::Index(i))) => i,
|
||||
(Some(_), _) => {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value, Colors used"));
|
||||
return CRYPTO_COLORS;
|
||||
}
|
||||
// No record: the default. The plug-in's is Colors (1): the `pard` default of the
|
||||
// instance's own and of the project's shared definition, and what scripting reads from a
|
||||
// fresh effect (1400 `crypto-00-defaults`). An instance's own definition with another
|
||||
// default keeps it; a borrowed one has no reliable popup default.
|
||||
(None, _) => match p.pard_default() {
|
||||
Some(ParamValue::Index(i)) if i != 0 && !p.borrowed_definition => i,
|
||||
_ => return CRYPTO_COLORS,
|
||||
},
|
||||
};
|
||||
let item = usize::try_from(index).ok().and_then(|i| i.checked_sub(1)).and_then(|i| items.get(i)).map(String::as_str).unwrap_or_default();
|
||||
match popup_key(item).as_str() {
|
||||
"colors" => CRYPTO_COLORS,
|
||||
"matted rgba" => (1, false),
|
||||
"matte only" => (1, true),
|
||||
"matted colors" => {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: parameter {label}: item '{item}' ({index}) has no counterpart, imported as Matte (the layer's colours keyed by the selection, not the ID colours)"),
|
||||
);
|
||||
(1, false)
|
||||
}
|
||||
_ => {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item '{item}' ({index}) has no counterpart, Colors used"));
|
||||
CRYPTO_COLORS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The channels EffectCraft's IDentifier reads first for its Channel Type Object ID and Material
|
||||
/// ID (`AuxChannels::object_id`, `material_id`).
|
||||
const IDENTIFIER_OWN: [&str; 2] = ["ObjectID", "MaterialID"];
|
||||
|
||||
/// Curves' EffectCraft parameters, in the stored order (RGB, Red, Green, Blue, Alpha).
|
||||
const CURVE_IDS: [&str; 5] = ["rgb", "red", "green", "blue", "alpha"];
|
||||
|
||||
@@ -507,7 +775,7 @@ fn import_mesh(m: &MeshData, here: &str, size: (u32, u32), group: &mut PropGroup
|
||||
return;
|
||||
}
|
||||
// EffectCraft's mesh reads the first two numbers of a vertex; moved handles follow as
|
||||
// eight more (kept in the project, not drawn).
|
||||
// eight more (kept for the export, not drawn).
|
||||
let mut token = format!("{},{}", px(dx * w), px(dy * h));
|
||||
if own.iter().any(|x| x.abs() > 0.01) {
|
||||
handles_moved = true;
|
||||
@@ -520,7 +788,7 @@ fn import_mesh(m: &MeshData, here: &str, size: (u32, u32), group: &mut PropGroup
|
||||
if handles_moved {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: Distortion Mesh Bezier handles moved on their own are not drawn (EffectCraft's mesh is bilinear; they are kept in the project)"),
|
||||
format!("{here}: Distortion Mesh Bezier handles moved on their own are not drawn (EffectCraft's mesh is bilinear; they are kept for the export)"),
|
||||
);
|
||||
}
|
||||
if let Some(p) = group.prop_mut("rows") {
|
||||
@@ -542,7 +810,7 @@ fn px(v: f64) -> String {
|
||||
|
||||
/// A decoded value in EffectCraft's units, `None` when it does not fit the kind or is not a valid
|
||||
/// number.
|
||||
fn convert(value: ParamValue, kind: Kind) -> Option<Value> {
|
||||
pub(crate) fn convert(value: ParamValue, kind: Kind) -> Option<Value> {
|
||||
let raw = match (value, kind) {
|
||||
// The reader gives colours as ARGB fractions; `Kind` takes the stored 0..255.
|
||||
(ParamValue::Argb(c), Kind::EffectColor) => c.map(|x| x * 255.0).to_vec(),
|
||||
|
||||
@@ -0,0 +1,803 @@
|
||||
//! Lumetri Color (`ADBE Lumetri`) to EffectCraft's Lumetri Color (`ec.color.lumetri`).
|
||||
//!
|
||||
//! The parameters are found by their match name (`ADBE Lumetri-0011` is Exposure), not by their
|
||||
//! place in `parT`: After Effects has added parameters in the middle of the list over the
|
||||
//! versions (`-0127` ... `-0130` sit between older ones), and several sliders share a valid range
|
||||
//! (Contrast, Highlights, Shadows, Whites and Blacks are all -150..150), so a shifted index
|
||||
//! would map silently to the wrong control. Evidence: the 1200 samples (After Effects 2026,
|
||||
//! `docs/aep-format.md` 3.7).
|
||||
//!
|
||||
//! - **Values in any record state.** Lumetri writes the values of its hidden controls (High
|
||||
//! Dynamic Range, HDR Specular, the second Look popup, ...) in records in the default state
|
||||
//! (`tdsb` 3); After Effects reads them back as set, so every record counts here
|
||||
//! ([`EffectParam::recorded_value`]).
|
||||
//! - **Section switches.** Each section (Basic Correction, Creative, Curves, RGB Curves, the five
|
||||
//! hue / saturation curves, Color Wheels, HSL Secondary, Vignette) has an on / off checkbox in
|
||||
//! After Effects; EffectCraft's Lumetri has none. A section that is off does nothing in After
|
||||
//! Effects (1200 `lumetri-03-sec-basic-correction`, `-17-sec-vignette` render as `-00-defaults`),
|
||||
//! so its values are not imported (the effect looks the same) and are listed in the report.
|
||||
//! - **Arbitrary data** (`ParamKind::ArbitraryData`, every instance stores it). Curves are a
|
||||
//! curve type, a point count and points as `f64` x, y ([`curve_points`]).
|
||||
//! - The RGB curve (`-0039`) holds four curves; the first is the master (white) curve (1200
|
||||
//! `lumetri-60-preset-curves-rgb`), imported. The other three are reported when moved: no
|
||||
//! sample tells which is which channel.
|
||||
//! - Hue vs Sat (`-0042`): y is an offset from neutral, 1 doubling the saturation (`-61`), so
|
||||
//! EffectCraft's y is `0.5 + y / 2`. The other four hue / saturation curves have no sample
|
||||
//! of their scale and are reported when moved.
|
||||
//! - Color Wheels (`-0047`): Shadows, Midtones, Highlights and a fourth wheel, each hue,
|
||||
//! brightness slider, distance ([`import_wheels`], `-62`).
|
||||
//! - The HSL Secondary key ([`HslKey`]) is imported; Split Toning and the correction wheels are
|
||||
//! reported when they are not the default (not sampled).
|
||||
//! - **LUTs and looks.** The Input LUT and the Look are files After Effects names (the Look's name
|
||||
//! is UTF-16 text in `-0096`, the popups only index a list of the installed ones); they are not
|
||||
//! in the project, so a set one is reported by name and EffectCraft's popup stays None.
|
||||
//! - **Eyedropper colours** (White Balance, the hue curve selectors, the key's Set / Add /
|
||||
//! Remove colours) only set other controls in After Effects; they are reported when set.
|
||||
//! - The `Blob` (`-0001`, an XML copy of the grade After Effects writes when a Look changes and does
|
||||
//! not keep current: 1200 `-01-set-all` holds the defaults of controls set after the Look) and
|
||||
//! the Auto Tone analysis (`-0121`, `-0122`) are derived data and not read.
|
||||
|
||||
use crate::effect_map::{Conv, ParamMap};
|
||||
use crate::{Effect as AepEffect, EffectParam, ParamKind, ParamValue};
|
||||
use effectcraft_keyframe::Value;
|
||||
|
||||
use crate::import::effects::{LayerCtx, ParamOut, carries_nothing, import_mapped, param_label};
|
||||
use crate::import::report::LossCategory;
|
||||
use ParamKind as K;
|
||||
|
||||
/// After Effects' Show Mask styles (`-0075`, `pdnm`), EffectCraft's in the same order.
|
||||
pub const MASK_STYLE: &[&str] = &["Color/Gray", "Color/Black", "White/Black"];
|
||||
|
||||
/// A part of the effect with its own on / off switch.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Section {
|
||||
/// No switch (High Dynamic Range and the controls outside the sections).
|
||||
Always,
|
||||
BasicCorrection,
|
||||
Creative,
|
||||
RgbCurves,
|
||||
/// The five hue / saturation curves (0 Hue vs Sat ... 4 Sat vs Sat).
|
||||
HueSat(u8),
|
||||
ColorWheels,
|
||||
HslSecondary,
|
||||
Vignette,
|
||||
SpeedGradeCustom,
|
||||
}
|
||||
|
||||
impl Section {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Section::Always => "",
|
||||
Section::BasicCorrection => "Basic Correction",
|
||||
Section::Creative => "Creative",
|
||||
Section::RgbCurves => "RGB Curves",
|
||||
Section::HueSat(0) => "Hue vs Sat",
|
||||
Section::HueSat(1) => "Hue vs Hue",
|
||||
Section::HueSat(2) => "Hue vs Luma",
|
||||
Section::HueSat(3) => "Luma vs Sat",
|
||||
Section::HueSat(_) => "Sat vs Sat",
|
||||
Section::ColorWheels => "Color Wheels",
|
||||
Section::HslSecondary => "HSL Secondary",
|
||||
Section::Vignette => "Vignette",
|
||||
Section::SpeedGradeCustom => "SpeedGrade Custom",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Arbitrary data the importer reads.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Data {
|
||||
/// The four RGB curves (4 x 520 bytes).
|
||||
RgbCurves,
|
||||
/// One hue / saturation curve (520 bytes); the EffectCraft parameter when the scale of its y
|
||||
/// is known (Hue vs Sat).
|
||||
HueSatCurve(Option<&'static str>),
|
||||
/// Color Wheels (4 x 3 `f64`, each wheel 0, 0.5, 0 by default).
|
||||
Wheels,
|
||||
/// HSL Secondary's correction wheels (8 x 3 `f64`, the same default).
|
||||
CorrectionWheels,
|
||||
/// Split Toning (32 zero bytes by default).
|
||||
SplitToning,
|
||||
/// HSL Secondary's key ([`HslKey`]).
|
||||
HslKey,
|
||||
/// Data without a counterpart, empty by default (`fe fe` or zero bytes).
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What a Lumetri parameter is.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Role {
|
||||
/// An EffectCraft parameter and the conversion.
|
||||
To(&'static str, Conv),
|
||||
/// The on / off switch of a section.
|
||||
Switch,
|
||||
/// No counterpart: reported when not at the default.
|
||||
Missing,
|
||||
/// A checkbox without counterpart whose `pard` default is not reliable: reported when a
|
||||
/// record says on. Legacy Tone And Saturation (`-0097`) is off in a fresh instance, but its
|
||||
/// `pard` default reads off in 1200 as saved by the script and on after the project was
|
||||
/// opened and saved again (`versions/1200-lumetri-26`, `-25x`, `-24x`).
|
||||
MissingWhenOn,
|
||||
/// An eyedropper colour: reported when set.
|
||||
Eyedropper,
|
||||
/// The Input LUT (`lut` true) or the Look: a popup, a name or an asset.
|
||||
Lut {
|
||||
lut: bool,
|
||||
},
|
||||
/// The Look's colour space (its popup and the space's id): goes with the Look.
|
||||
LookSpace,
|
||||
Data(Data),
|
||||
/// Derived data, not read.
|
||||
Derived,
|
||||
}
|
||||
|
||||
struct Row {
|
||||
suffix: u16,
|
||||
section: Section,
|
||||
kind: Option<ParamKind>,
|
||||
role: Role,
|
||||
}
|
||||
|
||||
const fn row(suffix: u16, section: Section, kind: Option<ParamKind>, role: Role) -> Row {
|
||||
Row { suffix, section, kind, role }
|
||||
}
|
||||
|
||||
const fn to(suffix: u16, section: Section, kind: ParamKind, target: &'static str, conv: Conv) -> Row {
|
||||
row(suffix, section, Some(kind), Role::To(target, conv))
|
||||
}
|
||||
|
||||
const fn plain(valid_max: f64) -> Conv {
|
||||
Conv::Plain { valid_max }
|
||||
}
|
||||
|
||||
use Section as S;
|
||||
|
||||
/// Every Lumetri parameter by match-name suffix (1200: `dump.props` and the `pard` of
|
||||
/// `lumetri-00-defaults`). The valid maxima are After Effects 2026's; the stored numbers are the
|
||||
/// values After Effects shows (read back in every variant).
|
||||
const ROWS: &[Row] = &[
|
||||
to(62, S::Always, K::Checkbox, "highDynamicRange", Conv::Checkbox),
|
||||
// Basic Correction: 3 the switch; 4 / 95 the Input LUT's name data, 5 / 127 its popups.
|
||||
row(3, S::BasicCorrection, Some(K::Checkbox), Role::Switch),
|
||||
row(4, S::BasicCorrection, Some(K::ArbitraryData), Role::Lut { lut: true }),
|
||||
row(95, S::BasicCorrection, Some(K::ArbitraryData), Role::Lut { lut: true }),
|
||||
row(5, S::BasicCorrection, Some(K::Popup), Role::Lut { lut: true }),
|
||||
row(127, S::BasicCorrection, Some(K::Popup), Role::Lut { lut: true }),
|
||||
to(63, S::BasicCorrection, K::FloatSlider, "basicCorrection/tone/hdrWhite", plain(1000.0)),
|
||||
// The Auto tone's Intensity (next to the Auto and Reset buttons 120, 119).
|
||||
row(123, S::BasicCorrection, Some(K::FloatSlider), Role::Missing),
|
||||
row(94, S::BasicCorrection, Some(K::Color), Role::Eyedropper),
|
||||
to(7, S::BasicCorrection, K::FloatSlider, "basicCorrection/whiteBalance/temperature", plain(300.0)),
|
||||
to(8, S::BasicCorrection, K::FloatSlider, "basicCorrection/whiteBalance/tint", plain(300.0)),
|
||||
to(20, S::BasicCorrection, K::FloatSlider, "basicCorrection/saturation", plain(300.0)),
|
||||
to(11, S::BasicCorrection, K::FloatSlider, "basicCorrection/tone/exposure", plain(7.0)),
|
||||
to(12, S::BasicCorrection, K::FloatSlider, "basicCorrection/tone/contrast", plain(150.0)),
|
||||
to(13, S::BasicCorrection, K::FloatSlider, "basicCorrection/tone/highlights", plain(150.0)),
|
||||
to(14, S::BasicCorrection, K::FloatSlider, "basicCorrection/tone/shadows", plain(150.0)),
|
||||
to(15, S::BasicCorrection, K::FloatSlider, "basicCorrection/tone/whites", plain(150.0)),
|
||||
to(16, S::BasicCorrection, K::FloatSlider, "basicCorrection/tone/blacks", plain(150.0)),
|
||||
to(64, S::BasicCorrection, K::FloatSlider, "basicCorrection/tone/hdrSpecular", plain(150.0)),
|
||||
// Creative: 23 the switch; 24 / 96 the Look's name, 25 / 128 its popups, 129 / 130 its colour
|
||||
// space.
|
||||
row(23, S::Creative, Some(K::Checkbox), Role::Switch),
|
||||
row(24, S::Creative, Some(K::ArbitraryData), Role::Lut { lut: false }),
|
||||
row(96, S::Creative, Some(K::ArbitraryData), Role::Lut { lut: false }),
|
||||
row(25, S::Creative, Some(K::Popup), Role::Lut { lut: false }),
|
||||
row(128, S::Creative, Some(K::Popup), Role::Lut { lut: false }),
|
||||
row(129, S::Creative, Some(K::ArbitraryData), Role::LookSpace),
|
||||
row(130, S::Creative, Some(K::Popup), Role::LookSpace),
|
||||
to(26, S::Creative, K::FloatSlider, "creative/lookIntensity", plain(200.0)),
|
||||
to(28, S::Creative, K::FloatSlider, "creative/adjustments/fadedFilm", plain(150.0)),
|
||||
to(29, S::Creative, K::FloatSlider, "creative/adjustments/sharpen", plain(100.0)),
|
||||
to(30, S::Creative, K::FloatSlider, "creative/adjustments/vibrance", plain(100.0)),
|
||||
to(31, S::Creative, K::FloatSlider, "creative/adjustments/creativeSaturation", plain(300.0)),
|
||||
row(32, S::Creative, Some(K::ArbitraryData), Role::Data(Data::SplitToning)),
|
||||
to(33, S::Creative, K::FloatSlider, "creative/adjustments/tintBalance", plain(150.0)),
|
||||
// Curves: 37 switches all curves, 118 the RGB curves, 104 ... 111 each hue / saturation curve.
|
||||
row(37, S::RgbCurves, Some(K::Checkbox), Role::Switch),
|
||||
row(118, S::RgbCurves, Some(K::Checkbox), Role::Switch),
|
||||
row(65, S::RgbCurves, Some(K::FloatSlider), Role::Missing),
|
||||
row(39, S::RgbCurves, Some(K::ArbitraryData), Role::Data(Data::RgbCurves)),
|
||||
row(104, S::HueSat(0), Some(K::Checkbox), Role::Switch),
|
||||
row(113, S::HueSat(0), Some(K::Color), Role::Eyedropper),
|
||||
row(42, S::HueSat(0), Some(K::ArbitraryData), Role::Data(Data::HueSatCurve(Some("curves/hueSaturationCurves/hueVsSat")))),
|
||||
row(105, S::HueSat(1), Some(K::Checkbox), Role::Switch),
|
||||
row(114, S::HueSat(1), Some(K::Color), Role::Eyedropper),
|
||||
row(106, S::HueSat(1), Some(K::ArbitraryData), Role::Data(Data::HueSatCurve(None))),
|
||||
row(107, S::HueSat(2), Some(K::Checkbox), Role::Switch),
|
||||
row(115, S::HueSat(2), Some(K::Color), Role::Eyedropper),
|
||||
row(108, S::HueSat(2), Some(K::ArbitraryData), Role::Data(Data::HueSatCurve(None))),
|
||||
row(109, S::HueSat(3), Some(K::Checkbox), Role::Switch),
|
||||
row(116, S::HueSat(3), Some(K::Color), Role::Eyedropper),
|
||||
row(110, S::HueSat(3), Some(K::ArbitraryData), Role::Data(Data::HueSatCurve(None))),
|
||||
row(111, S::HueSat(4), Some(K::Checkbox), Role::Switch),
|
||||
row(117, S::HueSat(4), Some(K::Color), Role::Eyedropper),
|
||||
row(112, S::HueSat(4), Some(K::ArbitraryData), Role::Data(Data::HueSatCurve(None))),
|
||||
// Color Wheels: 46 the switch, 102 Face Detection (on by default), 66 HDR White, 47 the wheels.
|
||||
row(46, S::ColorWheels, Some(K::Checkbox), Role::Switch),
|
||||
row(102, S::ColorWheels, Some(K::Checkbox), Role::Missing),
|
||||
row(66, S::ColorWheels, Some(K::FloatSlider), Role::Missing),
|
||||
row(47, S::ColorWheels, Some(K::ArbitraryData), Role::Data(Data::Wheels)),
|
||||
// HSL Secondary: 68 the switch; the key (70-76), Refine (81, 82), Correction (85-90).
|
||||
row(68, S::HslSecondary, Some(K::Checkbox), Role::Switch),
|
||||
row(70, S::HslSecondary, Some(K::Color), Role::Eyedropper),
|
||||
row(71, S::HslSecondary, Some(K::Color), Role::Eyedropper),
|
||||
row(72, S::HslSecondary, Some(K::Color), Role::Eyedropper),
|
||||
row(73, S::HslSecondary, Some(K::ArbitraryData), Role::Data(Data::HslKey)),
|
||||
to(74, S::HslSecondary, K::Checkbox, "hslSecondary/key/showMask", Conv::Checkbox),
|
||||
to(75, S::HslSecondary, K::Popup, "hslSecondary/key/maskStyle", Conv::Popup { default: 1, items: MASK_STYLE }),
|
||||
to(76, S::HslSecondary, K::Checkbox, "hslSecondary/key/invertMask", Conv::Checkbox),
|
||||
to(81, S::HslSecondary, K::FloatSlider, "hslSecondary/refine/denoise", plain(100.0)),
|
||||
to(82, S::HslSecondary, K::FloatSlider, "hslSecondary/refine/blur", plain(1000.0)),
|
||||
row(85, S::HslSecondary, Some(K::ArbitraryData), Role::Data(Data::CorrectionWheels)),
|
||||
// The correction wheel's mode (4 zero bytes by default).
|
||||
row(93, S::HslSecondary, Some(K::ArbitraryData), Role::Data(Data::Other)),
|
||||
to(86, S::HslSecondary, K::FloatSlider, "hslSecondary/correction/temperature", plain(300.0)),
|
||||
to(87, S::HslSecondary, K::FloatSlider, "hslSecondary/correction/tint", plain(300.0)),
|
||||
to(88, S::HslSecondary, K::FloatSlider, "hslSecondary/correction/contrast", plain(150.0)),
|
||||
to(89, S::HslSecondary, K::FloatSlider, "hslSecondary/correction/sharpen", plain(100.0)),
|
||||
to(90, S::HslSecondary, K::FloatSlider, "hslSecondary/correction/saturation", plain(300.0)),
|
||||
// Vignette: 50 the switch.
|
||||
row(50, S::Vignette, Some(K::Checkbox), Role::Switch),
|
||||
to(51, S::Vignette, K::FloatSlider, "vignette/vignetteAmount", plain(5.0)),
|
||||
to(52, S::Vignette, K::FloatSlider, "vignette/vignetteMidpoint", plain(100.0)),
|
||||
to(53, S::Vignette, K::FloatSlider, "vignette/vignetteRoundness", plain(100.0)),
|
||||
to(54, S::Vignette, K::FloatSlider, "vignette/vignetteFeather", plain(100.0)),
|
||||
// SpeedGrade Custom: 57 Custom Layer (on by default), 60 its data.
|
||||
row(57, S::SpeedGradeCustom, Some(K::Checkbox), Role::Switch),
|
||||
row(60, S::SpeedGradeCustom, Some(K::ArbitraryData), Role::Data(Data::Other)),
|
||||
// Outside the sections: Legacy Tone And Saturation, the embedded LUTs, Auto Tone, Auto Color,
|
||||
// the LUT and Look assets.
|
||||
row(97, S::Always, Some(K::Checkbox), Role::MissingWhenOn),
|
||||
row(98, S::Always, Some(K::ArbitraryData), Role::Data(Data::Other)),
|
||||
row(99, S::Always, Some(K::ArbitraryData), Role::Data(Data::Other)),
|
||||
row(100, S::Always, Some(K::ArbitraryData), Role::Data(Data::Other)),
|
||||
row(124, S::Always, Some(K::Checkbox), Role::Missing),
|
||||
row(125, S::Always, Some(K::ArbitraryData), Role::Lut { lut: true }),
|
||||
row(126, S::Always, Some(K::ArbitraryData), Role::Lut { lut: false }),
|
||||
row(1, S::Always, Some(K::ArbitraryData), Role::Derived),
|
||||
row(121, S::Always, Some(K::FloatSlider), Role::Derived),
|
||||
row(122, S::Always, Some(K::ArbitraryData), Role::Derived),
|
||||
];
|
||||
|
||||
/// The names After Effects shows for the parameters whose `pard` name is blank (`dump.props`).
|
||||
fn blank_name(suffix: u16) -> Option<&'static str> {
|
||||
Some(match suffix {
|
||||
62 => "High Dynamic Range",
|
||||
3 | 23 | 37 | 118 | 104 | 105 | 107 | 109 | 111 | 46 | 68 | 50 => "Active",
|
||||
4 | 95 => "Input LUT data",
|
||||
24 | 96 => "Look name",
|
||||
102 => "Face Detection",
|
||||
74 => "Show Mask",
|
||||
75 => "Mask style",
|
||||
76 => "Invert Mask",
|
||||
97 => "Legacy Tone And Saturation",
|
||||
124 => "Auto Color Active",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The parameter's name for the report: its own, else the one After Effects shows.
|
||||
fn name_of(p: &EffectParam<'_, '_>) -> String {
|
||||
match (p.name.trim(), suffix(&p.match_name).and_then(blank_name)) {
|
||||
("", Some(n)) => n.to_string(),
|
||||
("", None) => p.match_name.clone(),
|
||||
(n, _) => n.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The match-name suffix of a Lumetri parameter (`ADBE Lumetri-0011` is 11).
|
||||
fn suffix(match_name: &str) -> Option<u16> {
|
||||
match_name.strip_prefix("ADBE Lumetri-")?.parse().ok()
|
||||
}
|
||||
|
||||
/// The parameter's value: the recorded one, else the `pard` default.
|
||||
fn value_of(p: &EffectParam<'_, '_>) -> Option<ParamValue> {
|
||||
p.recorded_value().or_else(|| p.pard_default())
|
||||
}
|
||||
|
||||
/// True when the parameter has keyframes, an expression, or a recorded value other than its
|
||||
/// default (a record without a readable default counts as set).
|
||||
fn is_set(p: &EffectParam<'_, '_>) -> bool {
|
||||
if p.is_animated() || p.stored().is_some_and(|s| s.expression().is_some()) {
|
||||
return true;
|
||||
}
|
||||
match (p.recorded_value(), p.pard_default()) {
|
||||
(Some(v), Some(d)) => !same(v, d),
|
||||
(Some(_), None) => true,
|
||||
(None, _) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Equal within the float noise of a stored `f64` / `f32`.
|
||||
fn same(a: ParamValue, b: ParamValue) -> bool {
|
||||
let close = |x: f64, y: f64| (x - y).abs() <= 1e-6 * x.abs().max(y.abs()).max(1.0);
|
||||
match (a, b) {
|
||||
(ParamValue::Number(x), ParamValue::Number(y)) => close(x, y),
|
||||
(ParamValue::Argb(x), ParamValue::Argb(y)) => x.iter().zip(y).skip(1).all(|(x, y)| close(*x, y)),
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// A value as the report shows it.
|
||||
fn shown_value(v: Option<ParamValue>) -> String {
|
||||
match v {
|
||||
Some(ParamValue::Number(n)) => {
|
||||
let s = format!("{n:.3}");
|
||||
s.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
}
|
||||
Some(ParamValue::Bool(b)) => if b { "on" } else { "off" }.to_string(),
|
||||
Some(ParamValue::Index(i)) => format!("item {i}"),
|
||||
Some(ParamValue::Argb([_, r, g, b])) => format!("RGB {:.3} {:.3} {:.3}", r, g, b),
|
||||
Some(other) => format!("{other:?}"),
|
||||
None => "set".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty data: absent, `fe fe` (no text, no asset) or only zero bytes.
|
||||
fn is_empty_data(d: Option<&[u8]>) -> bool {
|
||||
match d {
|
||||
None => true,
|
||||
Some(d) => d == [0xfe, 0xfe] || d.iter().all(|b| *b == 0),
|
||||
}
|
||||
}
|
||||
|
||||
fn le_u32(d: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(*d.get(at..at.checked_add(4)?)?.first_chunk::<4>()?))
|
||||
}
|
||||
|
||||
fn le_f32(d: &[u8], at: usize) -> Option<f32> {
|
||||
Some(f32::from_le_bytes(*d.get(at..at.checked_add(4)?)?.first_chunk::<4>()?))
|
||||
}
|
||||
|
||||
fn le_f64(d: &[u8], at: usize) -> Option<f64> {
|
||||
Some(f64::from_le_bytes(*d.get(at..at.checked_add(8)?)?.first_chunk::<8>()?))
|
||||
}
|
||||
|
||||
/// A UTF-16LE text up to its NUL (the Look's name, `-0096`: `SL BLUE ICE` in 1200 `-01-set-all`);
|
||||
/// `None` for empty data.
|
||||
fn utf16_text(d: &[u8]) -> Option<String> {
|
||||
if is_empty_data(Some(d)) {
|
||||
return None;
|
||||
}
|
||||
let units: Vec<u16> = d.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0).collect();
|
||||
let s = String::from_utf16_lossy(&units);
|
||||
let s = s.trim();
|
||||
(!s.is_empty()).then(|| s.to_string())
|
||||
}
|
||||
|
||||
/// A Lumetri curve (520 bytes): `i32` curve type at 0 (3 for the hue curves, which wrap; 2 for
|
||||
/// Luma vs Sat and Sat vs Sat; 0 for an RGB curve), the `u32` point count at 4, then the points
|
||||
/// as little-endian `f64` pairs x, y from byte 8 (at most 32), sorted by x. Bytes after the
|
||||
/// counted points are stale (a fresh hue curve has count 0 and old points behind it). An RGB
|
||||
/// curve's x and y are 0..1 (2 points 0,0 and 1,1 by default); a hue / saturation curve's x is
|
||||
/// the hue (0 red, 1/3 green) or the luma / saturation, 0..1, and y its offset from neutral.
|
||||
/// `None` when the count does not fit.
|
||||
fn curve_points(d: &[u8]) -> Option<Vec<(f64, f64)>> {
|
||||
let n = usize::try_from(le_u32(d, 4)?).ok()?;
|
||||
if n > d.len().saturating_sub(8) / 16 {
|
||||
return None;
|
||||
}
|
||||
(0..n).map(|i| Some((le_f64(d, 8 + 16 * i)?, le_f64(d, 16 + 16 * i)?))).collect()
|
||||
}
|
||||
|
||||
/// HSL Secondary's key (`-0073`, 40 bytes): a flag byte (1 once a key colour was picked, 0 for a
|
||||
/// fresh effect), then hue, saturation and lightness, each three little-endian `f32` (centre,
|
||||
/// range, tolerance; fractions of the full hue circle / of 0..1) and an enabled byte. A fresh effect
|
||||
/// stores flag 0 and centre 0.5, range 0, tolerance 0, enabled for each (1200 `-00-defaults`);
|
||||
/// After Effects' own copy in `-0001` names the same fields (`middleHLS`, `rangeHLS`,
|
||||
/// `toleranceHLS`, `enableHLS`, hue in degrees: centre 180). Picking Set color RGB 0.02 0.55 0.85
|
||||
/// gives hue centre 0.5605 (that colour's hue, 201.8 degrees) and lightness centre 0.435 (its
|
||||
/// HSL lightness) with range 0.05 and tolerance 0.1 (`-01-set-all`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct HslKey {
|
||||
pub picked: bool,
|
||||
/// Hue, saturation, lightness: centre, range, tolerance, enabled.
|
||||
pub channels: [(f32, f32, f32, bool); 3],
|
||||
}
|
||||
|
||||
impl HslKey {
|
||||
pub fn parse(d: &[u8]) -> Option<HslKey> {
|
||||
if d.len() != 40 {
|
||||
return None;
|
||||
}
|
||||
let picked = match d.first()? {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => return None,
|
||||
};
|
||||
let ch = |at: usize| -> Option<(f32, f32, f32, bool)> {
|
||||
let (c, r, t) = (le_f32(d, at)?, le_f32(d, at + 4)?, le_f32(d, at + 8)?);
|
||||
let on = match d.get(at + 12)? {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => return None,
|
||||
};
|
||||
(c.is_finite() && r.is_finite() && t.is_finite()).then_some((c, r, t, on))
|
||||
};
|
||||
Some(HslKey { picked, channels: [ch(1)?, ch(14)?, ch(27)?] })
|
||||
}
|
||||
|
||||
fn is_default(&self) -> bool {
|
||||
!self.picked && self.channels.iter().all(|c| *c == (0.5, 0.0, 0.0, true))
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour wheel data: triples of `f64`, each wheel `0, 0.5, 0` by default.
|
||||
fn wheels_default(d: &[u8], wheels: usize) -> bool {
|
||||
d.len() == wheels * 24 && (0..wheels).all(|w| le_f64(d, w * 24) == Some(0.0) && le_f64(d, w * 24 + 8) == Some(0.5) && le_f64(d, w * 24 + 16) == Some(0.0))
|
||||
}
|
||||
|
||||
/// Is the data of `data` at After Effects' default (as far as it can be told)?
|
||||
fn data_default(data: Data, d: Option<&[u8]>) -> bool {
|
||||
let Some(d) = d else { return true };
|
||||
match data {
|
||||
Data::RgbCurves => {
|
||||
d.len() == 4 * 520 && d.as_chunks::<520>().0.iter().all(|c| curve_points(c).is_some_and(|pts| pts.iter().all(|(x, y)| (x - y).abs() < 1e-9)))
|
||||
}
|
||||
Data::HueSatCurve(_) => curve_points(d).is_some_and(|pts| pts.iter().all(|(_, y)| *y == 0.0)),
|
||||
Data::Wheels => wheels_default(d, 4),
|
||||
Data::CorrectionWheels => wheels_default(d, 8),
|
||||
Data::SplitToning | Data::Other => is_empty_data(Some(d)),
|
||||
Data::HslKey => HslKey::parse(d).is_some_and(|k| k.is_default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Input LUT or the Look holds: names, a popup item, an asset.
|
||||
#[derive(Default)]
|
||||
struct LutState {
|
||||
names: Vec<String>,
|
||||
item: Option<String>,
|
||||
asset: bool,
|
||||
}
|
||||
|
||||
/// How a set parameter of a section that does nothing is listed in the report; `None` when it is
|
||||
/// at its default.
|
||||
fn off_text(p: &EffectParam<'_, '_>, role: Role, data: Option<&[u8]>) -> Option<String> {
|
||||
match role {
|
||||
Role::Data(d) => (!data_default(d, data)).then(|| name_of(p)),
|
||||
// A LUT by its name (the popups index the same choice).
|
||||
Role::Lut { lut } if p.kind == K::ArbitraryData => {
|
||||
let what = if lut { "Input LUT" } else { "Look" };
|
||||
data.and_then(utf16_text).map(|n| format!("{what} '{n}'")).or_else(|| (!is_empty_data(data)).then(|| what.to_string()))
|
||||
}
|
||||
// The Look's colour space goes with the Look.
|
||||
Role::Lut { .. } | Role::LookSpace | Role::Derived => None,
|
||||
_ => is_set(p).then(|| format!("{} {}", name_of(p), shown_value(p.recorded_value()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Notes what an Input LUT or Look parameter holds: a popup item, an asset or a name.
|
||||
fn note_lut(p: &EffectParam<'_, '_>, suffix: u16, data: Option<&[u8]>, st: &mut LutState) {
|
||||
if p.kind == K::Popup {
|
||||
// The popup indexes the LUTs installed with After Effects; item 1 is None.
|
||||
if let Some(ParamValue::Index(i)) = p.recorded_value()
|
||||
&& i > 1
|
||||
{
|
||||
st.item = usize::try_from(i).ok().and_then(|i| p.items.as_ref()?.get(i - 1).cloned()).or(Some(format!("item {i}")));
|
||||
}
|
||||
} else if suffix == 125 || suffix == 126 {
|
||||
st.asset |= !is_empty_data(data);
|
||||
} else if let Some(name) = data.and_then(utf16_text)
|
||||
&& !st.names.contains(&name)
|
||||
{
|
||||
st.names.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Imports a Lumetri Color instance's parameters into `out.group` and reports what does not arrive.
|
||||
pub(crate) fn import_lumetri(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx: &LayerCtx<'_>, shown: &str, out: ParamOut<'_>) {
|
||||
let ParamOut { group, refs, col } = out;
|
||||
let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
|
||||
let find = |s: u16| params.iter().find(|p| suffix(&p.match_name) == Some(s));
|
||||
// The switches: on unless a record says off. Keys or an expression on a switch are not
|
||||
// imported (the static value counts).
|
||||
let switch_on = |s: u16| -> bool {
|
||||
match find(s) {
|
||||
Some(p) => !matches!(value_of(p), Some(ParamValue::Bool(false))),
|
||||
None => true,
|
||||
}
|
||||
};
|
||||
// HSL Secondary without a picked key colour selects nothing: After Effects applies none of
|
||||
// its correction (1200 `-16-sec-correction`, `-15-sec-refine` render as `-00-defaults`);
|
||||
// EffectCraft's default key is the whole image, so the values are left out too.
|
||||
// Unreadable or missing key data does not count as unpicked (it is reported or older).
|
||||
let key_picked = find(73).and_then(|p| fx.arbitrary_data(&p.match_name)).and_then(HslKey::parse).is_none_or(|k| k.picked);
|
||||
let section_on = |sec: Section| -> bool {
|
||||
match sec {
|
||||
Section::Always => true,
|
||||
Section::BasicCorrection => switch_on(3),
|
||||
Section::Creative => switch_on(23),
|
||||
Section::RgbCurves => switch_on(37) && switch_on(118),
|
||||
Section::HueSat(i) => switch_on(37) && switch_on([104, 105, 107, 109, 111].get(usize::from(i)).copied().unwrap_or(104)),
|
||||
Section::ColorWheels => switch_on(46),
|
||||
Section::HslSecondary => switch_on(68) && key_picked,
|
||||
Section::Vignette => switch_on(50),
|
||||
// Custom Layer off is itself reported (a switch without counterpart).
|
||||
Section::SpeedGradeCustom => true,
|
||||
}
|
||||
};
|
||||
let mut off: Vec<(Section, Vec<String>)> = Vec::new();
|
||||
let mut eyedroppers: Vec<String> = Vec::new();
|
||||
let mut luts = [LutState::default(), LutState::default()];
|
||||
for p in params {
|
||||
if carries_nothing(p) || p.match_name == "ADBE Effect Built In Params" {
|
||||
continue;
|
||||
}
|
||||
let label = if p.name.trim().is_empty() { format!("{} ({})", name_of(p), p.match_name) } else { param_label(p) };
|
||||
let Some(row) = suffix(&p.match_name).and_then(|s| ROWS.iter().find(|r| r.suffix == s)) else {
|
||||
// A parameter this table does not know (a newer version): lost when set.
|
||||
if p.stored().is_some()
|
||||
&& (p.kind != K::ArbitraryData && is_set(p) || p.kind == K::ArbitraryData && !is_empty_data(fx.arbitrary_data(&p.match_name)))
|
||||
{
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} not imported"));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
if row.kind.is_some_and(|k| k != p.kind) {
|
||||
if p.stored().is_some() {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} has type {:?}, expected {:?}; not imported", p.kind, row.kind));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let data = || fx.arbitrary_data(&p.match_name);
|
||||
// A switched-off section: its set values are listed, not imported.
|
||||
if !matches!(row.role, Role::Switch) && !section_on(row.section) {
|
||||
let text = off_text(p, row.role, data());
|
||||
if let Some(text) = text {
|
||||
match off.iter_mut().find(|(s, _)| *s == row.section) {
|
||||
Some((_, list)) => {
|
||||
if !list.contains(&text) {
|
||||
list.push(text);
|
||||
}
|
||||
}
|
||||
None => off.push((row.section, vec![text])),
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match row.role {
|
||||
Role::To(target, conv) => {
|
||||
let m = ParamMap { index: p.index, kind: p.kind, target, conv, limit: None };
|
||||
import_mapped(p, &m, cx, (&here, &label), ParamOut { group: &mut *group, refs: &mut *refs, col: &mut *col });
|
||||
}
|
||||
Role::Switch => {
|
||||
if p.is_animated() || p.stored().is_some_and(|s| s.expression().is_some()) {
|
||||
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on the switch {label} are not imported"));
|
||||
}
|
||||
if row.section == Section::SpeedGradeCustom && !switch_on(row.suffix) {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} is off and has no counterpart"));
|
||||
}
|
||||
}
|
||||
Role::MissingWhenOn => {
|
||||
if p.is_animated() || matches!(p.recorded_value(), Some(ParamValue::Bool(true))) {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} is on and has no counterpart, not imported"));
|
||||
}
|
||||
}
|
||||
Role::Missing => {
|
||||
if is_set(p) {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: parameter {label} is {} and has no counterpart, not imported", shown_value(p.recorded_value())),
|
||||
);
|
||||
}
|
||||
}
|
||||
Role::Eyedropper => {
|
||||
if is_set(p) {
|
||||
eyedroppers.push(name_of(p));
|
||||
}
|
||||
}
|
||||
Role::Lut { lut } => note_lut(p, row.suffix, data(), &mut luts[usize::from(!lut)]),
|
||||
// The Look's colour space only applies to a Look, which is reported.
|
||||
Role::LookSpace => {}
|
||||
Role::Data(_) if p.stored().is_some() && data().is_none() => {
|
||||
// The value record is there but its aRbs/aRbp payload is not: damaged, not the
|
||||
// default (a parameter without a record is the default).
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: the data of {label} is missing, not imported (the default used)"));
|
||||
}
|
||||
Role::Data(Data::HslKey) => import_hsl_key(data(), &here, &mut *group, &mut *col),
|
||||
Role::Data(d) => {
|
||||
if p.is_animated() || p.stored().is_some_and(|s| s.expression().is_some()) {
|
||||
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported"));
|
||||
}
|
||||
if !data_default(d, data()) {
|
||||
let why = match d {
|
||||
Data::RgbCurves => {
|
||||
import_rgb_curves(data(), (&here, &label), &mut *group, &mut *col);
|
||||
continue;
|
||||
}
|
||||
Data::HueSatCurve(Some(target)) => {
|
||||
import_hue_sat_curve(data(), target, (&here, &label), &mut *group, &mut *col);
|
||||
continue;
|
||||
}
|
||||
Data::Wheels => {
|
||||
import_wheels(data(), (&here, &label), &mut *group, &mut *col);
|
||||
continue;
|
||||
}
|
||||
Data::HueSatCurve(None) => "the curve's points are moved; no sample tells their scale",
|
||||
Data::CorrectionWheels | Data::SplitToning => "the data is not decoded (not sampled)",
|
||||
Data::HslKey | Data::Other => "no counterpart",
|
||||
};
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} is not imported ({why})"));
|
||||
}
|
||||
}
|
||||
Role::Derived => {}
|
||||
}
|
||||
}
|
||||
for (sec, list) in off {
|
||||
let why = if sec == Section::HslSecondary && switch_on(68) {
|
||||
"has no key colour picked (After Effects applies it to nothing)"
|
||||
} else {
|
||||
"is switched off (EffectCraft's Lumetri has no section switch)"
|
||||
};
|
||||
col.lose(LossCategory::Effects, format!("{here}: section {} {why}, its values are not imported: {}", sec.name(), list.join(", ")));
|
||||
}
|
||||
if !eyedroppers.is_empty() {
|
||||
col.lose(LossCategory::Effects, format!("{here}: the eyedropper colours {} are not imported (they only set other controls)", eyedroppers.join(", ")));
|
||||
}
|
||||
for (st, what) in luts.iter().zip(["Input LUT", "Look"]) {
|
||||
let name = st.names.first().cloned().or_else(|| st.item.clone());
|
||||
if name.is_some() || st.asset {
|
||||
let name = name.map(|n| format!(" '{n}'")).unwrap_or_default();
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: the {what}{name} is not imported (the LUT file is not in the project; EffectCraft's {what} stays None)"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// HSL Secondary's key as EffectCraft's hue centre / range / softness (degrees) and saturation and
|
||||
/// lightness bands (percent): range is taken as the half width, tolerance as the softness. A key
|
||||
/// that was never picked keeps EffectCraft's default (the whole image).
|
||||
fn import_hsl_key(d: Option<&[u8]>, here: &str, group: &mut effectcraft_project::PropGroup, col: &mut crate::import::report::Collector) {
|
||||
let Some(d) = d else { return };
|
||||
let Some(key) = HslKey::parse(d) else {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: the HSL Secondary key data is unreadable, the default key used"));
|
||||
return;
|
||||
};
|
||||
if !key.picked {
|
||||
if !key.is_default() {
|
||||
col.lose(LossCategory::Effects, format!("{here}: the HSL Secondary key holds values without a picked colour, not imported"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut set = |id: &str, v: Value| {
|
||||
if let Some(prop) = group.prop_mut(&format!("hslSecondary/key/{id}")) {
|
||||
prop.value = v;
|
||||
}
|
||||
};
|
||||
let [h, s, l] = key.channels.map(|(c, r, t, on)| (f64::from(c), f64::from(r), f64::from(t), on));
|
||||
set("hueEnabled", Value::Bool(h.3));
|
||||
set("hueCenter", Value::Scalar((h.0 * 360.0).rem_euclid(360.0)));
|
||||
set("hueRange", Value::Scalar((h.1 * 360.0).clamp(0.0, 180.0)));
|
||||
set("hueSoftness", Value::Scalar((h.2 * 360.0).clamp(0.0, 180.0)));
|
||||
for ((c, r, t, on), id) in [(s.0, s.1, s.2, s.3), (l.0, l.1, l.2, l.3)].into_iter().zip(["saturation", "lightness"]) {
|
||||
set(&format!("{id}Enabled"), Value::Bool(on));
|
||||
set(&format!("{id}Low"), Value::Scalar(((c - r) * 100.0).clamp(0.0, 100.0)));
|
||||
set(&format!("{id}High"), Value::Scalar(((c + r) * 100.0).clamp(0.0, 100.0)));
|
||||
set(&format!("{id}Softness"), Value::Scalar((t * 100.0).clamp(0.0, 100.0)));
|
||||
}
|
||||
}
|
||||
|
||||
/// A parameter of `group` set to `v` (ids the spec does not have are skipped).
|
||||
fn set_prop(group: &mut effectcraft_project::PropGroup, id: &str, v: Value) {
|
||||
if let Some(prop) = group.prop_mut(id) {
|
||||
prop.value = v;
|
||||
}
|
||||
}
|
||||
|
||||
/// Curve points as EffectCraft's `x,y x,y ...` text, x and y clamped to 0..1; `None` when a value
|
||||
/// is not finite.
|
||||
fn points_text(pts: impl IntoIterator<Item = (f64, f64)>) -> Option<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for (x, y) in pts {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
out.push(format!("{},{}", x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)));
|
||||
}
|
||||
Some(out.join(" "))
|
||||
}
|
||||
|
||||
/// The RGB curve (`-0039`, four curves of 520 bytes). The first is the master curve (1200
|
||||
/// `lumetri-60-preset-curves-rgb`: its midpoint raised to 0.787 lifts R, G and B alike) and
|
||||
/// becomes `curves/rgbCurves/master`. The other three are the channel curves, but no sample moves
|
||||
/// one, so which is red, green or blue is not known: a moved one is reported.
|
||||
fn import_rgb_curves(d: Option<&[u8]>, (here, label): (&str, &str), group: &mut effectcraft_project::PropGroup, col: &mut crate::import::report::Collector) {
|
||||
let Some(d) = d else { return };
|
||||
let curves: Option<Vec<Vec<(f64, f64)>>> = if d.len() == 4 * 520 { d.as_chunks::<520>().0.iter().map(|c| curve_points(c)).collect() } else { None };
|
||||
let Some(curves) = curves else {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: the data of {label} is unreadable, the curves are not imported"));
|
||||
return;
|
||||
};
|
||||
let identity = |pts: &[(f64, f64)]| pts.iter().all(|(x, y)| (x - y).abs() < 1e-9);
|
||||
if let Some(master) = curves.first().filter(|c| !identity(c)) {
|
||||
match points_text(master.iter().copied()) {
|
||||
Some(text) => set_prop(group, "curves/rgbCurves/master", Value::Str(text)),
|
||||
None => col.lose(LossCategory::DamagedData, format!("{here}: the master curve of {label} has unreadable points, not imported")),
|
||||
}
|
||||
}
|
||||
let moved = curves.iter().skip(1).filter(|c| !identity(c)).count();
|
||||
if moved > 0 {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: {moved} channel curve(s) of {label} are not imported (no sample tells which curve is red, green or blue)"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hue vs Sat (`-0042`): After Effects' y is an offset from neutral where 1 doubles the
|
||||
/// saturation (1200 `lumetri-61-preset-curves-huesat`: a point at hue 0.0155, y 0.97 scales pure
|
||||
/// red's saturation by about 1.96 in linear light; pins at -0.03 and -0.02 scale green, blue and
|
||||
/// cyan by 0.97). EffectCraft's y = 1 doubles it and 0.5 is neutral, so y becomes `0.5 + y / 2`.
|
||||
/// x is the hue in both (0 red, 1/3 green).
|
||||
fn import_hue_sat_curve(
|
||||
d: Option<&[u8]>,
|
||||
target: &str,
|
||||
(here, label): (&str, &str),
|
||||
group: &mut effectcraft_project::PropGroup,
|
||||
col: &mut crate::import::report::Collector,
|
||||
) {
|
||||
let Some(d) = d else { return };
|
||||
match curve_points(d).and_then(|pts| points_text(pts.into_iter().map(|(x, y)| (x, 0.5 + y / 2.0)))) {
|
||||
Some(text) => set_prop(group, target, Value::Str(text)),
|
||||
None => col.lose(LossCategory::DamagedData, format!("{here}: the data of {label} is unreadable, the curve is not imported")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour EffectCraft's wheel takes for After Effects' hue (degrees, 0 red, 120 green) and
|
||||
/// distance from the centre (0..1): the HSL colour of that hue with saturation = distance and
|
||||
/// lightness 0.5 (grey 0.5 at distance 0). EffectCraft's wheel adds that colour's offset from its
|
||||
/// grey, so the direction is After Effects' and the strength grows with the distance.
|
||||
fn wheel_colour(hue: f64, distance: f64) -> [f64; 4] {
|
||||
let c = distance.clamp(0.0, 1.0);
|
||||
let h = hue.rem_euclid(360.0) / 60.0;
|
||||
let x = c * (1.0 - (h.rem_euclid(2.0) - 1.0).abs());
|
||||
let (r, g, b) = match h {
|
||||
h if h < 1.0 => (c, x, 0.0),
|
||||
h if h < 2.0 => (x, c, 0.0),
|
||||
h if h < 3.0 => (0.0, c, x),
|
||||
h if h < 4.0 => (0.0, x, c),
|
||||
h if h < 5.0 => (x, 0.0, c),
|
||||
_ => (c, 0.0, x),
|
||||
};
|
||||
let m = 0.5 - c / 2.0;
|
||||
[r + m, g + m, b + m, 1.0]
|
||||
}
|
||||
|
||||
/// Color Wheels (`-0047`, 96 bytes): four wheels of three little-endian `f64`, the hue in degrees,
|
||||
/// the brightness slider (0..1, 0.5 neutral) and the distance from the centre (0..1); `0, 0.5, 0`
|
||||
/// each by default. The first three are Shadows, Midtones and Highlights (1200
|
||||
/// `lumetri-62-preset-wheels`: Shadows 229 degrees (blue), slider 0.37, distance 0.55; Midtones
|
||||
/// 0.1 degrees (red), 0.5, 0.39; Highlights 93 degrees (yellow-green), 0.73, 0.32); the fourth is
|
||||
/// not known. Hue and distance become EffectCraft's wheel colour ([`wheel_colour`]); the brightness
|
||||
/// sliders and a set fourth wheel have no counterpart and are reported.
|
||||
fn import_wheels(d: Option<&[u8]>, (here, label): (&str, &str), group: &mut effectcraft_project::PropGroup, col: &mut crate::import::report::Collector) {
|
||||
let Some(d) = d else { return };
|
||||
let wheels: Option<Vec<[f64; 3]>> = if d.len() == 4 * 24 {
|
||||
(0..4).map(|w| Some([le_f64(d, w * 24)?, le_f64(d, w * 24 + 8)?, le_f64(d, w * 24 + 16)?]).filter(|v| v.iter().all(|x| x.is_finite()))).collect()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(wheels) = wheels else {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: the data of {label} is unreadable, the colour wheels are not imported"));
|
||||
return;
|
||||
};
|
||||
let mut lost: Vec<String> = Vec::new();
|
||||
for (w, (id, name)) in wheels.iter().zip([("shadowsWheel", "Shadows"), ("midtonesWheel", "Midtones"), ("highlightsWheel", "Highlights")]) {
|
||||
let [hue, brightness, distance] = *w;
|
||||
if distance != 0.0 {
|
||||
set_prop(group, &format!("colorWheels/{id}"), Value::Color(wheel_colour(hue, distance)));
|
||||
}
|
||||
if (brightness - 0.5).abs() > 1e-9 {
|
||||
lost.push(format!("{name} brightness {brightness:.3} (0.5 is neutral)"));
|
||||
}
|
||||
}
|
||||
if wheels.get(3).is_some_and(|w| *w != [0.0, 0.5, 0.0]) {
|
||||
lost.push("the fourth wheel (its role is not known)".to_string());
|
||||
}
|
||||
if !lost.is_empty() {
|
||||
col.lose(LossCategory::Effects, format!("{here}: {label}: {} not imported (no counterpart)", lost.join(", ")));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,8 @@
|
||||
//! EffectCraft's `timeRemap` property (seconds, keys in layer time) at the top of the layer's
|
||||
//! properties, where the engine's Enable Time Remapping puts it.
|
||||
|
||||
use crate::{Chunk, CueType, Layer as AepLayer, Marker as AepMarker, PropNode, Property as AepProp};
|
||||
use crate::{CueType, Layer as AepLayer, Marker as AepMarker, PropNode, Property as AepProp};
|
||||
use craft_aep::Node as AepNode;
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::Ids;
|
||||
@@ -23,12 +24,12 @@ use crate::import::report::{Collector, LossCategory};
|
||||
use crate::import::time::TimeMap;
|
||||
|
||||
/// The time scale of the marker list below `holder` (the layer, or the composition's `SecL`).
|
||||
fn marker_scale(holder: &Chunk<'_>) -> Option<u32> {
|
||||
holder.find_list(b"mrst")?.child_list(b"tdbs").and_then(AepProp::from_chunk)?.time_scale().filter(|s| *s != 0)
|
||||
fn marker_scale(holder: AepNode<'_, '_>) -> Option<u32> {
|
||||
holder.marker_list()?.child_list(b"tdbs").and_then(AepProp::from_chunk)?.time_scale().filter(|s| *s != 0)
|
||||
}
|
||||
|
||||
/// The markers of a layer (`holder` = the layer chunk) or a composition (`holder` = its `SecL`).
|
||||
pub(crate) fn import_markers(list: Vec<AepMarker>, holder: &Chunk<'_>, what: &str, tm: &TimeMap, col: &mut Collector) -> Vec<Marker> {
|
||||
pub(crate) fn import_markers(list: Vec<AepMarker>, holder: AepNode<'_, '_>, what: &str, tm: &TimeMap, col: &mut Collector) -> Vec<Marker> {
|
||||
let scale = marker_scale(holder).unwrap_or(tm.timescale);
|
||||
let mut out: Vec<Marker> = Vec::with_capacity(list.len());
|
||||
for m in list {
|
||||
|
||||
@@ -50,13 +50,16 @@ fn source_rectangle(size: (u32, u32)) -> ShapePath {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`to_path`]'s error for a stored path without vertices.
|
||||
pub(crate) const NO_VERTICES: &str = "its path has no vertices";
|
||||
|
||||
pub(crate) fn to_path(s: &AepPath, size: (u32, u32)) -> Result<ShapePath, &'static str> {
|
||||
if !s.points.len().is_multiple_of(3) {
|
||||
return Err("its point count is not a multiple of three");
|
||||
}
|
||||
let n = s.vertex_count();
|
||||
if n == 0 {
|
||||
return Err("its path has no vertices");
|
||||
return Err(NO_VERTICES);
|
||||
}
|
||||
if n > MAX_VERTICES {
|
||||
return Err("its path has too many vertices");
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Placeholders: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect
|
||||
//! of expression controls) arrives as an effect group that renders nothing, as a missing plug-in
|
||||
//! does. Its effect id is the After Effects match name, so Find Missing Effects lists it. It holds
|
||||
//! the effect's parameters, flat and named as in After Effects, each with its value, keys and
|
||||
//! expression, so expressions that read them (`effect("Settings")("Speed")`) keep working. It is
|
||||
//! still reported, once per match name.
|
||||
//!
|
||||
//! The values keep After Effects' units, the ones its expressions read: sliders and angles as
|
||||
//! stored, points in layer pixels, colours RGBA 0..1, checkboxes on / off, popups as EffectCraft's
|
||||
//! 0-based items over the file's items in order (expressions read them 1-based, as After Effects
|
||||
//! does). Layer parameters name their layer (their keys and expression are reported). Paths and
|
||||
//! arbitrary data are not kept (reported when they hold something).
|
||||
//!
|
||||
//! The parameters placeholders walk, kept or not, and their popup items (by name length) are
|
||||
//! bounded per import ([`MAX_COST`]): definitions can be shared by many instances, so a small file
|
||||
//! could otherwise ask for very many properties. Once
|
||||
//! the budget is spent, later effects without a counterpart are reported without a placeholder.
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{GroupKind, Node, ParamUi, PropGroup, Property};
|
||||
|
||||
use crate::import::effects::{LayerCtx, ParamOut, PendingLayerRef, carries_nothing, convert, import_layer_ref, param_label};
|
||||
use crate::import::props::{Kind, import_expression, import_keys};
|
||||
use crate::import::report::{Collector, LossCategory};
|
||||
use crate::{Effect as AepEffect, EffectParam, ParamKind, ParamValue};
|
||||
|
||||
/// Most placeholder parameters (kept or not) and popup items one import walks.
|
||||
pub(crate) const MAX_COST: usize = 200_000;
|
||||
|
||||
/// Most items read from one placeholder popup.
|
||||
const MAX_POPUP_ITEMS: usize = 1024;
|
||||
|
||||
/// A popup item costs one more for each of these bytes in its name, so the names kept stay
|
||||
/// bounded too.
|
||||
const NAME_BYTES: usize = 16;
|
||||
|
||||
/// The placeholder of `fx`, with `params` (its parameter definitions) as properties.
|
||||
pub(crate) fn placeholder(
|
||||
fx: &AepEffect<'_, '_>,
|
||||
params: &[EffectParam<'_, '_>],
|
||||
cx: &LayerCtx<'_>,
|
||||
shown: &str,
|
||||
ids: &mut Ids<'_>,
|
||||
refs: &mut Vec<PendingLayerRef>,
|
||||
col: &mut Collector,
|
||||
) -> PropGroup {
|
||||
// The effect id is the match name; the group's match id is one segment of a property path
|
||||
// (a pseudo effect's `Pseudo/0.25` would be cut apart), so match paths find its parameters.
|
||||
let mut group = ids.group(&segment(fx.match_name()), shown);
|
||||
group.kind = GroupKind::Effect { effect: fx.match_name().to_string() };
|
||||
let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
|
||||
for p in params {
|
||||
// Every parameter walked counts, kept or not: a definition shared by many instances is
|
||||
// otherwise walked again for each one.
|
||||
if carries_nothing(p) {
|
||||
col.placeholder_cost = col.placeholder_cost.saturating_add(1).min(MAX_COST);
|
||||
continue;
|
||||
}
|
||||
if col.placeholder_cost >= MAX_COST {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameters past the import's {MAX_COST} placeholder parameters not kept"));
|
||||
break;
|
||||
}
|
||||
let label = param_label(p);
|
||||
let Some((kind, ui, default)) = shape(p, cx.size) else {
|
||||
col.placeholder_cost = col.placeholder_cost.saturating_add(1);
|
||||
if p.stored().is_some() {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (type {:?})", p.kind));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let (items, names) = match &ui {
|
||||
ParamUi::Popup { options } => (options.len(), options.iter().map(|o| 1 + o.len() / NAME_BYTES).fold(0, usize::saturating_add)),
|
||||
_ => (0, 0),
|
||||
};
|
||||
if p.kind == ParamKind::Popup && popup_len(p).is_some_and(|n| n > items) {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the items past the first {MAX_POPUP_ITEMS} not kept"));
|
||||
}
|
||||
let cost = col.placeholder_cost.saturating_add(names).saturating_add(1);
|
||||
if cost > MAX_COST {
|
||||
// The budget is spent: nothing more is built, here or in later effects (definitions
|
||||
// shared by many instances would otherwise still be walked item by item).
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: parameter {label} and the ones after it not kept (past the import's {MAX_COST} placeholder parameters)"),
|
||||
);
|
||||
col.placeholder_cost = MAX_COST;
|
||||
break;
|
||||
}
|
||||
col.placeholder_cost = cost;
|
||||
let mut prop = Property::new(ids.alloc(), ¶m_id(p), p.name.trim(), default).with_ui(ui);
|
||||
prop.spatial = p.kind == ParamKind::Point;
|
||||
prop.hold_only = matches!(p.kind, ParamKind::Checkbox | ParamKind::Popup | ParamKind::Layer);
|
||||
match kind {
|
||||
Some(kind) => {
|
||||
fill(p, &mut prop, kind, cx, (&here, &label), col);
|
||||
group.children.push(Node::Prop(prop));
|
||||
}
|
||||
// A layer parameter: the layer it names (set once every layer exists, by its uid).
|
||||
None => {
|
||||
let id = format!("@{}", prop.uid);
|
||||
group.children.push(Node::Prop(prop));
|
||||
import_layer_ref(p, &id, true, cx, (&here, &label), ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
|
||||
}
|
||||
}
|
||||
}
|
||||
group
|
||||
}
|
||||
|
||||
/// How parameter `p` is held on a layer `size` big: its unit conversion (`None` for a layer
|
||||
/// parameter), its control and its value until one is read. `None` for a type that is not kept.
|
||||
fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option<Kind>, ParamUi, Value)> {
|
||||
let (kind, ui, default) = match p.kind {
|
||||
ParamKind::IntSlider | ParamKind::FixedSlider | ParamKind::FloatSlider => (Kind::EffectNumber(1.0), slider_ui(p), Value::Scalar(0.0)),
|
||||
ParamKind::Angle => (Kind::EffectNumber(1.0), ParamUi::Angle, Value::Scalar(0.0)),
|
||||
ParamKind::Checkbox => (Kind::EffectBool, ParamUi::Checkbox, Value::Bool(false)),
|
||||
ParamKind::Color => (Kind::EffectColor, ParamUi::Color, Value::Color([0.0, 0.0, 0.0, 1.0])),
|
||||
ParamKind::Point => (Kind::EffectPoint(f64::from(size.0), f64::from(size.1)), ParamUi::Point, Value::Vec2([0.0, 0.0])),
|
||||
ParamKind::Layer => return Some((None, ParamUi::Layer, Value::Layer(None))),
|
||||
ParamKind::Popup => {
|
||||
// The file's items, separators (`(-`) included: After Effects counts them.
|
||||
let options: Vec<String> = match &p.items {
|
||||
Some(items) => items.iter().take(MAX_POPUP_ITEMS).cloned().collect(),
|
||||
None => (1..=popup_len(p)?.min(MAX_POPUP_ITEMS)).map(|i| format!("Item {i}")).collect(),
|
||||
};
|
||||
let n = u32::try_from(options.len()).ok().filter(|n| *n > 0)?;
|
||||
(Kind::EffectPopup(n), ParamUi::Popup { options }, Value::Enum(0))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some((Some(kind), ui, default))
|
||||
}
|
||||
|
||||
/// A slider's control: a float slider's valid range and drag range when they are ranges (only a
|
||||
/// float slider's are decoded), else a plain number.
|
||||
fn slider_ui(p: &EffectParam<'_, '_>) -> ParamUi {
|
||||
match (p.valid_min(), p.valid_max(), p.slider_range()) {
|
||||
(Some(min), Some(max), Some((smin, smax))) if [min, max, smin, smax].iter().all(|v| v.is_finite()) && min <= max && smin <= smax => {
|
||||
ParamUi::Slider { min, max, slider_min: smin.clamp(min, max), slider_max: smax.clamp(min, max), decimals: 2 }
|
||||
}
|
||||
_ => ParamUi::Number,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many items a popup has: the file's names, else the count in its definition.
|
||||
fn popup_len(p: &EffectParam<'_, '_>) -> Option<usize> {
|
||||
p.items.as_ref().map(Vec::len).or_else(|| p.popup_item_count().map(usize::from))
|
||||
}
|
||||
|
||||
/// The property id of `p`: its match name when that is one segment of a property path (a
|
||||
/// third-party effect's `CC Cylinder-0003`), else `param<index>` (a pseudo effect's
|
||||
/// `Pseudo/0.25-0001`: `/` and `.` separate path segments). Expressions also find it by its name.
|
||||
fn param_id(p: &EffectParam<'_, '_>) -> String {
|
||||
if !p.match_name.is_empty() && p.match_name.chars().all(plain) { p.match_name.clone() } else { format!("param{}", p.index) }
|
||||
}
|
||||
|
||||
/// Whether `c` can stand in one segment of a property path (`/`, `.`, `#` and `@` mean more).
|
||||
fn plain(c: char) -> bool {
|
||||
c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')
|
||||
}
|
||||
|
||||
/// `name` as one segment of a property path: other characters become `_` (`Pseudo/0.25` is
|
||||
/// `Pseudo_0_25`).
|
||||
fn segment(name: &str) -> String {
|
||||
name.chars().map(|c| if plain(c) { c } else { '_' }).collect()
|
||||
}
|
||||
|
||||
/// Sets `prop` from `p`: its expression, then its keys or its value (the record, else the `pard`
|
||||
/// default). `names` is `(here, label)` for the report.
|
||||
fn fill(p: &EffectParam<'_, '_>, prop: &mut Property, kind: Kind, cx: &LayerCtx<'_>, names: (&str, &str), col: &mut Collector) {
|
||||
let (here, label) = names;
|
||||
if let Some(stored) = p.stored() {
|
||||
import_expression(&stored, prop, col);
|
||||
}
|
||||
if p.is_animated() {
|
||||
let Some(stored) = p.stored() else { return };
|
||||
if kind == Kind::EffectBool {
|
||||
// Keys on a checkbox are not sampled by the corpus.
|
||||
col.lose(LossCategory::Effects, format!("{here}: the keyframes of parameter {label} are not kept (not decoded)"));
|
||||
return;
|
||||
}
|
||||
let before = prop.keys.len();
|
||||
import_keys(&stored, kind, cx.layer, &p.match_name, cx.tm, prop, col);
|
||||
if prop.keys.len() == before {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} has no readable keyframe"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let value = match (p.stored(), p.recorded_value()) {
|
||||
(Some(_), Some(v)) => v,
|
||||
(Some(_), None) => {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value"));
|
||||
return;
|
||||
}
|
||||
// A borrowed popup's default slot holds another copy's selection (docs/aep-format.md 3.7).
|
||||
(None, _) if p.kind == ParamKind::Popup && p.borrowed_definition => {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not known (shared definition), the first item used"));
|
||||
return;
|
||||
}
|
||||
// A popup's default slot can hold 0, no item (After Effects' save of a project it opened).
|
||||
(None, _) => match p.pard_default() {
|
||||
Some(ParamValue::Index(0)) => {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not stored, the first item used"));
|
||||
return;
|
||||
}
|
||||
Some(v) => v,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
match (convert(value, kind), value) {
|
||||
(Some(v), _) => prop.value = v,
|
||||
// An item of the file that is past the ones kept (reported with the cut): the first item.
|
||||
(None, ParamValue::Index(i)) if usize::try_from(i).is_ok_and(|i| i > MAX_POPUP_ITEMS && popup_len(p).is_some_and(|n| i <= n)) => {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item {i} is past the items kept, the first item used"));
|
||||
}
|
||||
(None, _) => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?})")),
|
||||
}
|
||||
}
|
||||
@@ -136,8 +136,12 @@ const IGNORED: [&str; 4] = ["ADBE Position_0", "ADBE Position_1", "ADBE Position
|
||||
/// How the stored Anchor Point becomes pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AnchorUnit {
|
||||
/// A fraction of a source this big (pixels): AV layers.
|
||||
/// A fraction of a source this big (pixels): AV layers; the source's centre when absent.
|
||||
Source(u32, u32),
|
||||
/// A fraction of a null object's source this big (pixels); its top-left corner when absent:
|
||||
/// After Effects 2026 reads a null's absent Anchor Point as `[0, 0]` (#3099: two nulls made
|
||||
/// with `addNull`, one left at its default, read back `[0, 0, 0]` and `[10, 20, 0]`).
|
||||
Null(u32, u32),
|
||||
/// Pixels as stored, the origin when absent: text (385) and shape (462) layers, which have no
|
||||
/// source.
|
||||
Pixels,
|
||||
@@ -169,6 +173,14 @@ pub(crate) fn import_transform(
|
||||
let (sw, sh) = (f64::from(w), f64::from(h));
|
||||
(Kind::Anchor(sw, sh), tr.anchor_px(sw, sh))
|
||||
}
|
||||
AnchorUnit::Null(w, h) => {
|
||||
let (sw, sh) = (f64::from(w), f64::from(h));
|
||||
let px = match tr.anchor_fraction.source {
|
||||
ValueSource::Default | ValueSource::Unreadable => [0.0; 3],
|
||||
ValueSource::Stored | ValueSource::Keyframed => tr.anchor_px(sw, sh),
|
||||
};
|
||||
(Kind::Anchor(sw, sh), px)
|
||||
}
|
||||
AnchorUnit::Pixels | AnchorUnit::PointOfInterest => (Kind::Anchor(1.0, 1.0), tr.text_anchor_px()),
|
||||
};
|
||||
let poi = anchor == AnchorUnit::PointOfInterest;
|
||||
@@ -219,15 +231,21 @@ pub(crate) fn import_transform(
|
||||
}
|
||||
import_expression(&node, prop, col);
|
||||
}
|
||||
if let Some(PropNode::Other(_)) = group.get("ADBE Orientation") {
|
||||
if let Some(PropNode::Other(otst)) = group.get("ADBE Orientation") {
|
||||
match (layer.orientation(), target.get_mut("orientation")) {
|
||||
(Some(o), Some(prop)) if !o.animated && !o.has_expression && sane(&Value::Vec3(o.degrees)) => prop.value = Value::Vec3(o.degrees),
|
||||
(Some(o), Some(prop)) if o.animated || sane(&Value::Vec3(o.degrees)) => {
|
||||
if o.animated {
|
||||
import_orientation_keys(layer, layer_name, tm, prop, col);
|
||||
} else {
|
||||
prop.value = Value::Vec3(o.degrees);
|
||||
}
|
||||
// The expression is stored in the `otst`'s `tdbs` as on any property (#3087).
|
||||
if let Some(node) = otst.child_list(b"tdbs").and_then(AepProp::from_chunk) {
|
||||
import_expression(&node, prop, col);
|
||||
}
|
||||
}
|
||||
// A layer without an orientation (an ambient light) loses nothing with the default.
|
||||
(Some(o), None) if !o.animated && !o.has_expression && o.degrees == [0.0; 3] => {}
|
||||
(Some(o), Some(prop)) if o.animated && !o.has_expression => import_orientation_keys(layer, layer_name, tm, prop, col),
|
||||
(Some(o), Some(_)) if o.has_expression => {
|
||||
col.lose(LossCategory::TransformProperties, format!("{layer_name}: ADBE Orientation expression (not decoded)"));
|
||||
}
|
||||
_ => col.lose(LossCategory::TransformProperties, format!("{layer_name}: ADBE Orientation")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! After Effects' Puppet effect (`ADBE FreePin3`) arrives as EffectCraft's Puppet
|
||||
//! (`ec.distort.puppet`) in its place in the stack, with its name and fx switch, but **without
|
||||
//! its meshes and pins**: how After Effects stores a pin's rest place (a vertex index and offset
|
||||
//! into the hidden mesh data) and its Position (pixels or a fraction of the layer) is not decoded
|
||||
//! yet, and a guessed rest place would deform the layer wrongly without a word. What the instance
|
||||
//! holds is reported instead, mesh by mesh: Triangles, Expansion, and per pin container (Deform,
|
||||
//! Stiffness, Overlap) the number of pins, how many are keyed or carry an expression, and the
|
||||
//! match names of their atoms (Advanced and Bend pins show up there). Any entry this reader does
|
||||
//! not know is named verbatim.
|
||||
//!
|
||||
//! The tree read here (docs/aep-format.md 3.7, Puppet) comes from an external scripting listing
|
||||
//! of the effect's property tree, not from the corpus (no corpus file has a Puppet): **?** until a
|
||||
//! byte sample exists. It is read with the same verified group reader as masks, shapes and layer
|
||||
//! styles; a file whose tree differs is reported, never guessed at.
|
||||
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{Node, PropGroup};
|
||||
|
||||
use crate::import::effects::{LayerCtx, carries_nothing};
|
||||
use crate::import::report::{Collector, LossCategory};
|
||||
use crate::{Effect as AepEffect, EffectDefinitions, ParamValue, PropGroup as AepGroup, PropNode, Property as AepProperty};
|
||||
|
||||
/// After Effects' Puppet effect.
|
||||
pub(crate) const MATCH_NAME: &str = "ADBE FreePin3";
|
||||
/// The hidden group that holds the meshes (`arap`).
|
||||
const ARAP: &str = "ADBE FreePin3 ARAP Group";
|
||||
/// Auto-traced Shapes, beside the meshes.
|
||||
const OUTLINES: &str = "ADBE FreePin3 Outlines";
|
||||
/// The hidden group of the meshes.
|
||||
const MESH_GROUP: &str = "ADBE FreePin3 Mesh Group";
|
||||
/// One mesh (`Mesh 1`).
|
||||
const MESH_ATOM: &str = "ADBE FreePin3 Mesh Atom";
|
||||
/// A mesh's hidden triangulation.
|
||||
const MESH_DATA: &str = "ADBE FreePin3 Mesh";
|
||||
const TRIANGLES: &str = "ADBE FreePin3 Mesh Tri Count";
|
||||
const EXPANSION: &str = "ADBE FreePin3 Mesh Expansion";
|
||||
/// At most this many meshes, pin atom names or unrecognised names are listed in a report line;
|
||||
/// the rest are counted (`and 3 more`).
|
||||
const LIST_CAP: usize = 10;
|
||||
/// The pin containers of a mesh: match name and the name After Effects shows.
|
||||
const PIN_GROUPS: [(&str, &str); 3] = [("ADBE FreePin3 PosPins", "Deform"), ("ADBE FreePin3 HghtPins", "Overlap"), ("ADBE FreePin3 StarchPins", "Stiffness")];
|
||||
|
||||
/// Imports a Puppet instance (the caller checked the match name) into `target`.
|
||||
pub(crate) fn import_puppet<'f, 'a>(
|
||||
defs: &EffectDefinitions<'f, 'a>,
|
||||
fx: &AepEffect<'f, 'a>,
|
||||
cx: &LayerCtx<'_>,
|
||||
ids: &mut Ids<'_>,
|
||||
target: &mut PropGroup,
|
||||
col: &mut Collector,
|
||||
) {
|
||||
let shown = fx.display_name().unwrap_or_else(|| fx.match_name().to_string());
|
||||
let here = format!("{}: '{}' effect '{shown}' ({MATCH_NAME})", cx.comp, cx.layer);
|
||||
let Some(spec) = effectcraft_effects::find(effectcraft_effects::puppet::ID) else {
|
||||
col.lose(LossCategory::Effects, format!("{}: '{}' has the effect '{shown}' ({MATCH_NAME})", cx.comp, cx.layer));
|
||||
return;
|
||||
};
|
||||
let size = [f64::from(cx.size.0), f64::from(cx.size.1)];
|
||||
let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size);
|
||||
match fx.enabled() {
|
||||
Some(on) => group.enabled = on,
|
||||
None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)),
|
||||
}
|
||||
// The ordinary parameters (`parT`): none is mapped yet, so a stored one is reported.
|
||||
let params = defs.params(fx);
|
||||
for p in ¶ms {
|
||||
if carries_nothing(p) {
|
||||
continue;
|
||||
}
|
||||
if p.stored().is_some() && !matches!(p.stored_value(), Some(ParamValue::Layer(0))) {
|
||||
let label = if p.name.is_empty() { p.match_name.clone() } else { format!("{} ({})", p.name, p.match_name) };
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} not imported"));
|
||||
}
|
||||
}
|
||||
report_meshes(fx, ¶ms.iter().map(|p| p.match_name.as_str()).collect::<Vec<_>>(), &here, col);
|
||||
// The effect itself arrives (an EffectCraft Puppet the user can pin again), so it counts as
|
||||
// imported; what it held is in the losses above.
|
||||
col.imported.effects = col.imported.effects.saturating_add(1);
|
||||
target.children.push(Node::Group(group));
|
||||
}
|
||||
|
||||
/// Reports the meshes and pins of `fx` and every entry of its value group that is neither a
|
||||
/// `parT` parameter (`param_names`) nor the mesh tree.
|
||||
fn report_meshes(fx: &AepEffect<'_, '_>, param_names: &[&str], here: &str, col: &mut Collector) {
|
||||
let mut unknown: Vec<String> = Vec::new();
|
||||
let values = fx.chunk().child_list(b"tdgp").and_then(AepGroup::from_chunk);
|
||||
let mut arap = None;
|
||||
for e in values.map(|g| g.entries()).unwrap_or_default() {
|
||||
if e.match_name == ARAP {
|
||||
if let PropNode::Group(g) = e.node {
|
||||
if arap.is_none() {
|
||||
arap = Some(g);
|
||||
}
|
||||
} else {
|
||||
push_unique(&mut unknown, e.match_name);
|
||||
}
|
||||
} else if !param_names.contains(&e.match_name.as_str()) {
|
||||
match e.node {
|
||||
// A value outside `parT` (On Transparent, ...): reported with what it holds.
|
||||
PropNode::Property(p) => col.lose(LossCategory::Effects, format!("{here}: property {} ({}) not imported", e.match_name, describe(&p))),
|
||||
PropNode::Group(_) | PropNode::Other(_) => push_unique(&mut unknown, e.match_name),
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut meshes: Vec<String> = Vec::new();
|
||||
let mut found = false;
|
||||
if let Some(arap) = arap {
|
||||
for e in arap.entries() {
|
||||
match (e.match_name.as_str(), e.node) {
|
||||
(MESH_GROUP, PropNode::Group(g)) if !found => {
|
||||
found = true;
|
||||
for m in g.entries() {
|
||||
match (m.match_name.as_str(), m.node) {
|
||||
(MESH_ATOM, PropNode::Group(mesh)) => {
|
||||
let n = meshes.len().saturating_add(1);
|
||||
meshes.push(mesh_summary(&mesh, n, &mut unknown));
|
||||
}
|
||||
_ => push_unique(&mut unknown, m.match_name.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
// Auto-traced Shapes are made from the layer again (EffectCraft traces the alpha).
|
||||
(OUTLINES, _) => {}
|
||||
_ => push_unique(&mut unknown, e.match_name.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
let extra = if unknown.is_empty() { String::new() } else { format!("; not recognised: {}", capped(&unknown, ", ")) };
|
||||
if !found {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: imported without meshes or pins: its mesh group ({ARAP} / {MESH_GROUP}) was not found or is not a group{extra}"),
|
||||
);
|
||||
} else if !meshes.is_empty() {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!(
|
||||
"{here}: imported without its meshes and pins (After Effects' pin rest places and positions are not decoded yet): {}{extra}",
|
||||
capped(&meshes, "; ")
|
||||
),
|
||||
);
|
||||
} else if !unknown.is_empty() {
|
||||
col.lose(LossCategory::Effects, format!("{here}: no mesh{extra}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// `Mesh n (Triangles t, Expansion e): Deform 3 pins (1 keyed) [atom names], Overlap no pins, ...`
|
||||
fn mesh_summary(mesh: &AepGroup<'_, '_>, n: usize, unknown: &mut Vec<String>) -> String {
|
||||
let name = mesh.user_name().unwrap_or_else(|| format!("Mesh {n}"));
|
||||
let mut settings: Vec<String> = Vec::new();
|
||||
let mut containers: Vec<String> = Vec::new();
|
||||
for e in mesh.entries() {
|
||||
let label = match e.match_name.as_str() {
|
||||
TRIANGLES => Some("Triangles"),
|
||||
EXPANSION => Some("Expansion"),
|
||||
_ => None,
|
||||
};
|
||||
match (label, e.node) {
|
||||
(Some(label), PropNode::Property(p)) => settings.push(format!("{label} {}", describe(&p))),
|
||||
// The triangulation After Effects keeps; EffectCraft builds its own.
|
||||
_ if e.match_name == MESH_DATA => {}
|
||||
_ => match (PIN_GROUPS.iter().find(|(m, _)| *m == e.match_name), e.node) {
|
||||
(Some((_, shown)), PropNode::Group(g)) => containers.push(format!("{shown} {}", pins_summary(&g, unknown))),
|
||||
_ => push_unique(unknown, e.match_name),
|
||||
},
|
||||
}
|
||||
}
|
||||
let settings = if settings.is_empty() { String::new() } else { format!(" ({})", settings.join(", ")) };
|
||||
let containers = if containers.is_empty() { "no pin groups".to_string() } else { containers.join(", ") };
|
||||
format!("{name}{settings}: {containers}")
|
||||
}
|
||||
|
||||
/// `3 pins (1 keyed, 1 with an expression) [ADBE FreePin3 PosPin Atom]`, or `no pins`. An entry
|
||||
/// of the container that is not a group (a pin is one) goes to `unknown`.
|
||||
fn pins_summary(container: &AepGroup<'_, '_>, unknown: &mut Vec<String>) -> String {
|
||||
let mut count = 0usize;
|
||||
let mut keyed = 0usize;
|
||||
let mut expressions = 0usize;
|
||||
let mut atoms: Vec<String> = Vec::new();
|
||||
for e in container.entries() {
|
||||
let PropNode::Group(pin) = e.node else {
|
||||
push_unique(unknown, e.match_name);
|
||||
continue;
|
||||
};
|
||||
count = count.saturating_add(1);
|
||||
push_unique(&mut atoms, e.match_name);
|
||||
let props: Vec<AepProperty<'_, '_>> =
|
||||
pin.entries().into_iter().filter_map(|p| if let PropNode::Property(p) = p.node { Some(p) } else { None }).collect();
|
||||
if props.iter().any(AepProperty::is_animated) {
|
||||
keyed = keyed.saturating_add(1);
|
||||
}
|
||||
if props.iter().any(|p| p.expression().is_some()) {
|
||||
expressions = expressions.saturating_add(1);
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return "no pins".to_string();
|
||||
}
|
||||
let mut what = vec![format!("{keyed} keyed")];
|
||||
if expressions > 0 {
|
||||
what.push(format!("{expressions} with an expression"));
|
||||
}
|
||||
format!("{count} pin{} ({}) [{}]", if count == 1 { "" } else { "s" }, what.join(", "), capped(&atoms, ", "))
|
||||
}
|
||||
|
||||
/// A stored property's value for the report: `keyed`, the static value, or `unreadable`.
|
||||
fn describe(p: &AepProperty<'_, '_>) -> String {
|
||||
if p.is_animated() {
|
||||
return "keyed".to_string();
|
||||
}
|
||||
match p.static_value() {
|
||||
Some(v) if v.len() == 1 => v.first().map(|x| format!("{x}")).unwrap_or_default(),
|
||||
Some(v) => format!("[{}]", v.iter().map(|x| format!("{x}")).collect::<Vec<_>>().join(", ")),
|
||||
None => "unreadable".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `name` to `names` unless it is there already.
|
||||
fn push_unique(names: &mut Vec<String>, name: String) {
|
||||
if !names.contains(&name) {
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The first [`LIST_CAP`] of `items` joined by `sep`, and how many more there are.
|
||||
fn capped(items: &[String], sep: &str) -> String {
|
||||
let shown: Vec<&str> = items.iter().take(LIST_CAP).map(String::as_str).collect();
|
||||
let mut out = shown.join(sep);
|
||||
let more = items.len().saturating_sub(LIST_CAP);
|
||||
if more > 0 {
|
||||
out.push_str(&format!("{sep}and {more} more"));
|
||||
}
|
||||
out
|
||||
}
|
||||
+280
-14
@@ -7,6 +7,9 @@ use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::container::AepFile;
|
||||
use crate::container::index::Root;
|
||||
|
||||
/// Most example lines kept per loss category (the count is always exact).
|
||||
pub const MAX_DETAILS: usize = 20;
|
||||
|
||||
@@ -54,7 +57,8 @@ pub enum LossCategory {
|
||||
/// Layers that could not be imported for another reason (unknown layer type, missing or
|
||||
/// unsupported source, precomposition loop).
|
||||
UnsupportedLayers,
|
||||
/// Project items of a kind that is not imported.
|
||||
/// Project items of a kind that is not imported, and items made from a Photoshop layer
|
||||
/// without pixels (they show the merged image).
|
||||
UnsupportedItems,
|
||||
/// Data that could not be read (damaged headers, unreadable keyframes).
|
||||
DamagedData,
|
||||
@@ -90,14 +94,47 @@ impl LossCategory {
|
||||
}
|
||||
}
|
||||
|
||||
/// One category of things that were not imported.
|
||||
/// One category of things that were not imported. The export report uses the same type with its
|
||||
/// own categories (`export::Loss`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Loss {
|
||||
pub category: LossCategory,
|
||||
pub struct Loss<C = LossCategory> {
|
||||
pub category: C,
|
||||
/// How many occurrences (exact).
|
||||
pub count: usize,
|
||||
/// Up to [`MAX_DETAILS`] example lines.
|
||||
/// Example lines: up to [`MAX_DETAILS`], and for effects with no counterpart one more line per
|
||||
/// effect (with its number of instances).
|
||||
pub details: Vec<String>,
|
||||
/// How many of the `count` occurrences no line of `details` describes.
|
||||
#[serde(default)]
|
||||
pub unlisted: usize,
|
||||
}
|
||||
|
||||
/// The loss bookkeeping the import and the export report share.
|
||||
impl<C: Copy + Ord> Loss<C> {
|
||||
/// Counts one loss of `category`; `detail` is only called while the category holds fewer than
|
||||
/// [`MAX_DETAILS`] lines.
|
||||
pub(crate) fn record(losses: &mut BTreeMap<C, Self>, category: C, detail: impl FnOnce() -> String) {
|
||||
let loss = losses.entry(category).or_insert_with(|| Loss { category, count: 0, details: Vec::new(), unlisted: 0 });
|
||||
loss.count = loss.count.saturating_add(1);
|
||||
if loss.details.len() < MAX_DETAILS {
|
||||
loss.details.push(detail());
|
||||
}
|
||||
}
|
||||
|
||||
/// The sum of all loss counts.
|
||||
pub(crate) fn total(losses: &[Self]) -> usize {
|
||||
losses.iter().map(|l| l.count).sum()
|
||||
}
|
||||
|
||||
/// The loss count of a category.
|
||||
pub(crate) fn count_of(losses: &[Self], category: C) -> usize {
|
||||
losses.iter().find(|l| l.category == category).map_or(0, |l| l.count)
|
||||
}
|
||||
|
||||
/// `effects: 3, masks: 1` (empty without losses).
|
||||
pub(crate) fn summary(losses: &[Self], label: impl Fn(C) -> &'static str) -> String {
|
||||
losses.iter().map(|l| format!("{}: {}", label(l.category), l.count)).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
}
|
||||
|
||||
/// What arrived in the project.
|
||||
@@ -154,6 +191,10 @@ pub struct Imported {
|
||||
/// in [`LossCategory::Effects`]).
|
||||
#[serde(default)]
|
||||
pub effects: usize,
|
||||
/// Effects with no counterpart, kept as placeholders that render nothing (their parameters,
|
||||
/// for expressions; each is also in [`LossCategory::Effects`]).
|
||||
#[serde(default)]
|
||||
pub placeholder_effects: usize,
|
||||
/// Layer styles (Drop Shadow, Stroke, ...), one per style on a layer.
|
||||
#[serde(default)]
|
||||
pub layer_styles: usize,
|
||||
@@ -177,12 +218,76 @@ pub struct ImportReport {
|
||||
pub missing_fonts: Vec<String>,
|
||||
/// What the file reader cannot see at all, so it can be neither imported nor counted.
|
||||
pub limitations: Vec<String>,
|
||||
/// The After Effects version the file is written for and the one that wrote it.
|
||||
#[serde(default)]
|
||||
pub ae_version: AeVersionInfo,
|
||||
}
|
||||
|
||||
/// The After Effects versions the importer is tested with (the major of the version a file is
|
||||
/// written for): files written for 24.x, 25.x and 26.x.
|
||||
pub const TESTED_MAJORS: std::ops::RangeInclusive<u8> = 24..=26;
|
||||
|
||||
/// The After Effects versions of a file, decoded from the container (never from the XMP packet,
|
||||
/// which names the application of the first save).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AeVersionInfo {
|
||||
/// The version the file is written for (`head`): `26.2.1x2` for a file saved by After Effects
|
||||
/// 26.2.1, `25.6.0x97` for a copy that After Effects 2026 saved as 25.x. `unknown` when the file
|
||||
/// does not say.
|
||||
pub file_version: String,
|
||||
/// The version of the After Effects that wrote the file (`svap`): `26.2.1x2` for that copy too.
|
||||
/// `unknown` when the file does not say.
|
||||
pub saved_by: String,
|
||||
/// Whether the importer is tested with files written for this version ([`TESTED_MAJORS`]).
|
||||
/// When not, what is read is still imported, and a line in
|
||||
/// [`ImportReport::limitations`] says the version is not tested.
|
||||
pub tested: bool,
|
||||
}
|
||||
|
||||
impl Default for AeVersionInfo {
|
||||
fn default() -> Self {
|
||||
Self { file_version: UNKNOWN.to_string(), saved_by: UNKNOWN.to_string(), tested: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a version the file does not state.
|
||||
pub const UNKNOWN: &str = "unknown";
|
||||
|
||||
impl AeVersionInfo {
|
||||
/// Reads the versions of a parsed file.
|
||||
pub fn of(file: &AepFile<'_>) -> Self {
|
||||
Self::of_root(Root::from(file))
|
||||
}
|
||||
|
||||
/// Reads the versions from the top-level chunks of either tree.
|
||||
pub(crate) fn of_root(file: Root<'_, '_>) -> Self {
|
||||
let file_version = file.file_version();
|
||||
Self {
|
||||
file_version: file_version.map_or_else(|| UNKNOWN.to_string(), |v| v.text()),
|
||||
saved_by: file.saved_by_version().map_or_else(|| UNKNOWN.to_string(), |v| v.text()),
|
||||
tested: file_version.is_some_and(|v| TESTED_MAJORS.contains(&v.major)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The limitation line for a version that is not tested; `None` for a tested one.
|
||||
pub fn limitation(&self) -> Option<String> {
|
||||
(!self.tested).then(|| {
|
||||
format!(
|
||||
"The file is written for After Effects {} (saved by {}); the importer is tested with files written for After Effects {} to {} only. What it reads is imported, but this version is not tested.",
|
||||
self.file_version,
|
||||
self.saved_by,
|
||||
TESTED_MAJORS.start(),
|
||||
TESTED_MAJORS.end()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ImportReport {
|
||||
/// The sum of all loss counts.
|
||||
pub fn total_losses(&self) -> usize {
|
||||
self.losses.iter().map(|l| l.count).sum()
|
||||
Loss::total(&self.losses)
|
||||
}
|
||||
|
||||
/// True when nothing was lost.
|
||||
@@ -192,12 +297,12 @@ impl ImportReport {
|
||||
|
||||
/// The loss count of a category.
|
||||
pub fn count(&self, category: LossCategory) -> usize {
|
||||
self.losses.iter().find(|l| l.category == category).map_or(0, |l| l.count)
|
||||
Loss::count_of(&self.losses, category)
|
||||
}
|
||||
|
||||
/// `effects: 3, masks: 1` (empty when lossless).
|
||||
pub fn summary(&self) -> String {
|
||||
self.losses.iter().map(|l| format!("{}: {}", l.category.label(), l.count)).collect::<Vec<_>>().join(", ")
|
||||
Loss::summary(&self.losses, LossCategory::label)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,25 +313,70 @@ pub(crate) struct Collector {
|
||||
losses: BTreeMap<LossCategory, Loss>,
|
||||
pub missing_footage: Vec<String>,
|
||||
pub missing_fonts: Vec<String>,
|
||||
/// The effects with no counterpart, by match name: the first instance's report line and how
|
||||
/// many instances there were. They get a line each in [`Collector::finish`], so one that
|
||||
/// comes after the example lines are used up is still named (#3365).
|
||||
unmapped_effects: BTreeMap<String, (String, usize)>,
|
||||
/// The properties and popup items the placeholders of this import hold so far (at most
|
||||
/// `placeholder::MAX_COST`).
|
||||
pub placeholder_cost: usize,
|
||||
}
|
||||
|
||||
/// How many different unmapped effects get a line of their own (a file names at most this many).
|
||||
const MAX_UNMAPPED_EFFECTS: usize = 100;
|
||||
|
||||
impl Collector {
|
||||
/// Records one loss.
|
||||
pub fn lose(&mut self, category: LossCategory, detail: impl Into<String>) {
|
||||
let loss = self.losses.entry(category).or_insert_with(|| Loss { category, count: 0, details: Vec::new() });
|
||||
loss.count = loss.count.saturating_add(1);
|
||||
if loss.details.len() < MAX_DETAILS {
|
||||
loss.details.push(detail.into());
|
||||
}
|
||||
self.lose_with(category, move || detail.into());
|
||||
}
|
||||
|
||||
pub fn finish(self) -> ImportReport {
|
||||
/// Records one loss whose detail line is built only while the category holds fewer than
|
||||
/// [`MAX_DETAILS`] lines (for a detail that needs `format!`).
|
||||
pub fn lose_with(&mut self, category: LossCategory, detail: impl FnOnce() -> String) {
|
||||
Loss::record(&mut self.losses, category, detail);
|
||||
}
|
||||
|
||||
/// Records one instance of an effect with no counterpart. The loss is counted now; its line is
|
||||
/// made in [`Collector::finish`], one per effect with the number of instances, so that many
|
||||
/// other losses cannot hide which effects were dropped.
|
||||
pub fn lose_unmapped_effect(&mut self, match_name: &str, detail: String) {
|
||||
let loss =
|
||||
self.losses.entry(LossCategory::Effects).or_insert_with(|| Loss { category: LossCategory::Effects, count: 0, details: Vec::new(), unlisted: 0 });
|
||||
loss.count = loss.count.saturating_add(1);
|
||||
if let Some(seen) = self.unmapped_effects.get_mut(match_name) {
|
||||
seen.1 = seen.1.saturating_add(1);
|
||||
} else if self.unmapped_effects.len() < MAX_UNMAPPED_EFFECTS {
|
||||
self.unmapped_effects.insert(match_name.to_string(), (detail, 1));
|
||||
}
|
||||
// (Past the limit an effect is only counted: its name is not worth a line of its own.)
|
||||
}
|
||||
|
||||
pub fn finish(mut self) -> ImportReport {
|
||||
// Every line describes one occurrence, except an unmapped effect's, which describes all
|
||||
// its instances.
|
||||
for loss in self.losses.values_mut() {
|
||||
loss.unlisted = loss.count.saturating_sub(loss.details.len());
|
||||
}
|
||||
if let Some(loss) = self.losses.get_mut(&LossCategory::Effects) {
|
||||
// The most used effects first.
|
||||
let mut named: Vec<(String, usize)> = std::mem::take(&mut self.unmapped_effects).into_values().collect();
|
||||
named.sort_by_key(|n| std::cmp::Reverse(n.1));
|
||||
let described = named.iter().fold(0usize, |sum, (_, n)| sum.saturating_add(*n));
|
||||
loss.unlisted = loss.unlisted.saturating_sub(described);
|
||||
let lines = named.into_iter().map(|(first, n)| match n {
|
||||
1 => first,
|
||||
_ => format!("{first}, and {} more like it", n - 1),
|
||||
});
|
||||
loss.details.splice(0..0, lines);
|
||||
}
|
||||
ImportReport {
|
||||
imported: self.imported,
|
||||
losses: self.losses.into_values().collect(),
|
||||
missing_footage: self.missing_footage,
|
||||
missing_fonts: self.missing_fonts,
|
||||
limitations: LIMITATIONS.iter().map(|s| (*s).to_string()).collect(),
|
||||
ae_version: AeVersionInfo::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,3 +389,119 @@ pub const LIMITATIONS: &[&str] = &[
|
||||
"Text: per-character 3D, text on a path and several style slots of unknown meaning are not decoded (stored values that differ from the default are reported as text layer features).",
|
||||
"Footage that is not a solid is linked by its stored path with its stored frame rate and duration; the importer never opens the files (use Reload Footage after the files are found).",
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A report with losses in two categories and a missing file, as the collector finishes it.
|
||||
fn collected() -> ImportReport {
|
||||
let mut col = Collector::default();
|
||||
col.imported.layers = 2;
|
||||
col.missing_footage.push("a.png".into());
|
||||
col.lose(LossCategory::Masks, "mask 1");
|
||||
col.lose(LossCategory::Effects, String::from("fx 1"));
|
||||
col.lose_with(LossCategory::Effects, || "fx 2".to_string());
|
||||
let mut report = col.finish();
|
||||
report.limitations.truncate(1);
|
||||
report
|
||||
}
|
||||
|
||||
/// The JSON shape agents read: field names, category spelling, order and the loss entries.
|
||||
#[test]
|
||||
fn the_json_shape_is_pinned() {
|
||||
let json = serde_json::to_string(&collected()).unwrap();
|
||||
assert_eq!(
|
||||
json,
|
||||
r#"{"imported":{"folders":0,"compositions":0,"solids":0,"footage":0,"layers":2,"solidLayers":0,"nullLayers":0,"adjustmentLayers":0,"footageLayers":0,"precompLayers":0,"textLayers":0,"keyframes":0,"expressions":0,"masks":0,"trackMattes":0,"markers":0,"timeRemaps":0,"shapeLayers":0,"shapeItems":0,"cameras":0,"lights":0,"textAnimators":0,"effects":0,"placeholderEffects":0,"layerStyles":0},"losses":[{"category":"effects","count":2,"details":["fx 1","fx 2"],"unlisted":0},{"category":"masks","count":1,"details":["mask 1"],"unlisted":0}],"missingFootage":["a.png"],"missingFonts":[],"limitations":["Frame blending, 3D material options, audio levels, guides are not decoded and not imported."],"aeVersion":{"fileVersion":"unknown","savedBy":"unknown","tested":false}}"#
|
||||
);
|
||||
let back: ImportReport = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, collected());
|
||||
}
|
||||
|
||||
/// The queries read the losses.
|
||||
#[test]
|
||||
fn the_queries_read_the_losses() {
|
||||
let report = collected();
|
||||
assert_eq!((report.total_losses(), report.is_lossless()), (3, false));
|
||||
assert_eq!((report.count(LossCategory::Effects), report.count(LossCategory::Lights)), (2, 0));
|
||||
assert_eq!(report.summary(), "effects: 2, masks: 1");
|
||||
let empty = Collector::default().finish();
|
||||
assert_eq!((empty.total_losses(), empty.is_lossless(), empty.summary()), (0, true, String::new()));
|
||||
}
|
||||
|
||||
/// The count stays exact past the detail cap, and a detail past the cap is never built.
|
||||
#[test]
|
||||
fn details_stop_at_the_cap_and_later_ones_are_not_built() {
|
||||
let mut col = Collector::default();
|
||||
let mut built = 0;
|
||||
for i in 0..MAX_DETAILS + 5 {
|
||||
col.lose_with(LossCategory::Masks, || {
|
||||
built += 1;
|
||||
format!("mask {i}")
|
||||
});
|
||||
}
|
||||
let report = col.finish();
|
||||
assert_eq!(report.count(LossCategory::Masks), MAX_DETAILS + 5);
|
||||
assert_eq!(report.losses[0].details.len(), MAX_DETAILS);
|
||||
assert_eq!(report.losses[0].details.last().map(String::as_str), Some("mask 19"));
|
||||
assert_eq!(built, MAX_DETAILS);
|
||||
}
|
||||
|
||||
/// #3365: with other losses filling the 20 example lines, an effect with no counterpart still
|
||||
/// gets its own line, with how many instances were lost. The category's count is unchanged.
|
||||
#[test]
|
||||
fn every_unmapped_effect_is_named_however_many_other_losses_there_are() {
|
||||
let mut col = Collector::default();
|
||||
for i in 0..30 {
|
||||
col.lose(LossCategory::Effects, format!("C: 'L{i}': parameter P not imported"));
|
||||
}
|
||||
for i in 0..25 {
|
||||
col.lose_unmapped_effect("CC Cylinder", format!("C: 'Cyl{i}' has the effect 'CC Cylinder' (CC Cylinder)"));
|
||||
}
|
||||
col.lose_unmapped_effect("Pseudo/", "C: 'D' has the effect 'Dropdown' (Pseudo/)".to_string());
|
||||
let report = col.finish();
|
||||
let effects = report.losses.iter().find(|l| l.category == LossCategory::Effects).unwrap();
|
||||
assert_eq!(effects.count, 56, "30 parameters, 25 cylinders and 1 dropdown");
|
||||
let named = |what: &str| effects.details.iter().filter(|d| d.contains(what)).collect::<Vec<_>>();
|
||||
assert_eq!(named("(CC Cylinder)").len(), 1, "{:?}", effects.details);
|
||||
assert!(named("(CC Cylinder)")[0].contains("24 more"), "{:?}", named("(CC Cylinder)"));
|
||||
// One instance stays the single line it was.
|
||||
assert_eq!(named("(Pseudo/)"), ["C: 'D' has the effect 'Dropdown' (Pseudo/)"]);
|
||||
assert!(effects.details.len() <= MAX_DETAILS + 2, "the examples stay bounded");
|
||||
// 20 parameter lines, the cylinders' line and the dropdown's describe 46; 10 parameters
|
||||
// have no line.
|
||||
assert_eq!(effects.unlisted, 10);
|
||||
// The most used effect comes first.
|
||||
assert!(effects.details[0].contains("(CC Cylinder)"), "{:?}", effects.details);
|
||||
}
|
||||
|
||||
/// #3365: each category says how many of its occurrences have no example line.
|
||||
#[test]
|
||||
fn a_loss_counts_the_occurrences_without_a_line() {
|
||||
let mut col = Collector::default();
|
||||
for i in 0..27 {
|
||||
col.lose(LossCategory::Masks, format!("mask {i}"));
|
||||
}
|
||||
col.lose(LossCategory::ShapeLayers, "one");
|
||||
let report = col.finish();
|
||||
let unlisted = |c| report.losses.iter().find(|l| l.category == c).map(|l| (l.details.len(), l.unlisted));
|
||||
assert_eq!(unlisted(LossCategory::Masks), Some((MAX_DETAILS, 7)));
|
||||
assert_eq!(unlisted(LossCategory::ShapeLayers), Some((1, 0)));
|
||||
}
|
||||
|
||||
/// A file with more than [`MAX_UNMAPPED_EFFECTS`] different unmapped effects names that many
|
||||
/// and counts the rest, whatever room the example lines have.
|
||||
#[test]
|
||||
fn at_most_the_limit_of_unmapped_effects_are_named() {
|
||||
let mut col = Collector::default();
|
||||
for i in 0..=MAX_UNMAPPED_EFFECTS {
|
||||
col.lose_unmapped_effect(&format!("Effect {i}"), format!("C: 'L' has the effect 'Effect {i}' (Effect {i})"));
|
||||
}
|
||||
let report = col.finish();
|
||||
let effects = report.losses.iter().find(|l| l.category == LossCategory::Effects).unwrap();
|
||||
assert_eq!(effects.count, MAX_UNMAPPED_EFFECTS + 1, "every instance is counted");
|
||||
assert_eq!(effects.details.len(), MAX_UNMAPPED_EFFECTS, "{} lines", effects.details.len());
|
||||
assert_eq!(effects.unlisted, 1, "the effect past the limit has no line");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Project settings (colour depth, working space, working gamma, linear-light switches, time
|
||||
//! display, frame count start) from [`crate::ProjectSettings`] (cases 620-634).
|
||||
|
||||
use crate::{AepFile, TimeDisplay, WorkingSpace};
|
||||
use crate::container::index::{Node, Root};
|
||||
use crate::{TimeDisplay, WorkingSpace};
|
||||
use effectcraft_color::ColorSpace;
|
||||
use effectcraft_project::{BitDepth, ProjectSettings, TimeDisplayStyle};
|
||||
|
||||
@@ -11,7 +12,9 @@ use crate::import::report::{Collector, LossCategory};
|
||||
pub(crate) fn color_space(name: &str) -> Option<ColorSpace> {
|
||||
match name {
|
||||
"sRGB IEC61966-2.1" => Some(ColorSpace::Srgb),
|
||||
"Rec.709 Gamma 2.4" => Some(ColorSpace::Rec709),
|
||||
// The second name is the one After Effects shows for the profile EffectCraft's exporter
|
||||
// writes (its description tag) once it re-saves such a project.
|
||||
"Rec.709 Gamma 2.4" | "Rec.709 Gamma 2.4 (EffectCraft)" => Some(ColorSpace::Rec709),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -20,9 +23,9 @@ pub(crate) fn color_space(name: &str) -> Option<ColorSpace> {
|
||||
/// holds in an unknown form) keeps the current value. The two linear-light switches are always
|
||||
/// held: After Effects writes their chunk only when on (626, 627), so a file without it has them off. A working space EffectCraft does not have is
|
||||
/// reported.
|
||||
pub(crate) fn map(file: &AepFile<'_>, current: &ProjectSettings, col: &mut Collector) -> ProjectSettings {
|
||||
let s = crate::ProjectSettings::read(file);
|
||||
let nhed = file.chunk(b"nhed").and_then(|c| c.bytes());
|
||||
pub(crate) fn map(file: Root<'_, '_>, current: &ProjectSettings, col: &mut Collector) -> ProjectSettings {
|
||||
let s = crate::ProjectSettings::of(file);
|
||||
let nhed = file.chunk(b"nhed").and_then(Node::bytes);
|
||||
let mut out = current.clone();
|
||||
match s.bits_per_channel {
|
||||
Some(8) => out.bit_depth = BitDepth::Bpc8,
|
||||
@@ -89,8 +92,9 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rec709_by_name() {
|
||||
fn rec709_under_both_names() {
|
||||
assert_eq!(color_space("Rec.709 Gamma 2.4"), Some(ColorSpace::Rec709));
|
||||
assert_eq!(color_space("Rec.709 Gamma 2.4 (EffectCraft)"), Some(ColorSpace::Rec709));
|
||||
assert_eq!(color_space("Rec.709 Gamma 2.4 (other)"), None);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 798 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user