mirror of
https://github.com/storytold/effectcraft.git
synced 2026-12-04 21:13:15 -05:00
Merge upstream/main into reversed-layer-audio-3239
This commit is contained in:
commit
2aefe27278
610 files changed
+37851
-38475
No files matched your search
@@ -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'
|
||||
@@ -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:
|
||||
@@ -29,6 +33,7 @@ jobs:
|
||||
# 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 }}
|
||||
|
||||
+10
-2
@@ -64,7 +64,7 @@ and licence texts are in [`NOTICE`](NOTICE).
|
||||
| `crates/model/tests/fixtures/cube.obj` | EffectCraft contributors | Original work: Wavefront OBJ test fixture (unit cube, two materials) | MIT OR Apache-2.0 |
|
||||
| `crates/model/tests/fixtures/cube.mtl` | EffectCraft contributors | Original work: MTL test fixture (materials of cube.obj) | MIT OR Apache-2.0 |
|
||||
|
||||
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.
|
||||
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
|
||||
|
||||
@@ -99,7 +99,7 @@ Screenshots of EffectCraft itself, rendered headlessly, showing only procedurall
|
||||
(sidecars `.attribution`).
|
||||
- Bundled extension (ScriptUI panel) with its twelve built-in ease presets:
|
||||
`extensions/scriptui-panels/Ease Presets.jsx` (sidecar `.attribution`).
|
||||
- Example effect plug-in: `examples/plugins/posterize-bands` (plug-in API v1, WebAssembly).
|
||||
- Example effect plug-in: `examples/plugins/posterize-bands` (WebAssembly ABI 1).
|
||||
|
||||
## Trained models (optional downloads, not bundled)
|
||||
|
||||
@@ -129,6 +129,14 @@ configuration from these Apache-2.0 projects:
|
||||
- `crates/segment/src/mobilesam.rs` follows the MobileSAM, TinyViT and Segment Anything
|
||||
architectures and their Apache-2.0 reference code.
|
||||
|
||||
## Frozen matte regression fixture
|
||||
|
||||
| Asset | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `crates/engine/src/tests/fixtures/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
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ that variable set.
|
||||
```sh
|
||||
cargo run -p effectcraft -- --demo # the desktop app, with the demo project
|
||||
cargo test --workspace
|
||||
cargo xtask ci # what every commit must pass
|
||||
cargo xtask ci # what every commit must pass (dev-profile checks and tests)
|
||||
```
|
||||
|
||||
The default `dev` profile keeps debug info to line tables: builds are fast and panics/backtraces
|
||||
|
||||
Generated
+333
-138
File diff suppressed because it is too large.
Load diff
+34
-46
@@ -4,19 +4,29 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.21.0"
|
||||
version = "0.24.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/effectcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", default-features = false, features = ["read"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ca1b5e2edb8568335c6c14f390307bd5beae8238" }
|
||||
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 = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
|
||||
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" }
|
||||
@@ -41,7 +51,6 @@ 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" }
|
||||
@@ -49,8 +58,6 @@ 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" }
|
||||
|
||||
@@ -82,25 +89,23 @@ 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).
|
||||
# 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" }
|
||||
# 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" }
|
||||
# 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" }
|
||||
# decoder used as the round-trip oracle of effectcraft-opusenc (crates/export dev-dependency)
|
||||
filmcraft-opus = { 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" }
|
||||
# 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)
|
||||
@@ -117,7 +122,7 @@ half = "2.7"
|
||||
# ui
|
||||
# Shared frontend components; keep this dependency above the engine boundary.
|
||||
# Shared UI and the complete egui family select reviewed immutable commits below.
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "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"] }
|
||||
@@ -137,11 +142,6 @@ sys-locale = "0.3"
|
||||
# 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]
|
||||
@@ -200,50 +200,39 @@ opt-level = 3
|
||||
[profile.dev.package.effectcraft-export]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-vp9enc]
|
||||
# craft-libs codec hot loops.
|
||||
[profile.dev.package.craft-video]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-hevcenc]
|
||||
[profile.dev.package.craft-audio]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-av1enc]
|
||||
[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-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" }
|
||||
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" }
|
||||
@@ -254,8 +243,7 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
# Patch a crate only together with the dependency that needs it: an unused patch makes the Nix
|
||||
# build, which uses vendored sources, fail (`cargo xtask lock-patches`).
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
@@ -129,18 +129,14 @@ or into the Timeline, between layers and at the time you point to.
|
||||
|
||||
308 built-in effects across its categories, each with its parameter names, order and
|
||||
defaults: blur and sharpen, channel, color correction (Curves, Levels, Hue/Saturation, a full
|
||||
color-grading panel…), distort (Warp, Bulge, Turbulent Displace, CC Power Pin…), generate (Fractal Noise,
|
||||
color-grading panel…), distort (Warp, Bulge, Turbulent Displace, Perspective Pin…), generate (Fractal Noise,
|
||||
Gradient Ramp, Stroke, Write-on, Audio Spectrum…), keying, matte, noise and grain, perspective,
|
||||
**simulation** (CC Particle World, CC Rainfall, Shatter, Card Dance, Caustics, Wave World…),
|
||||
stylize (Glow, CC Glass…), **time** (Echo, Posterize Time, Timewarp, Time Displacement…),
|
||||
**simulation** (Particle Emitter 3D, Rainfall, Shatter, Card Dance, Caustics, Wave World…),
|
||||
stylize (Glow, Glass Relief…), **time** (Echo, Posterize Time, Timewarp, Time Displacement…),
|
||||
**audio** (Reverb, Parametric EQ, Delay, Stereo Mixer…), text, transitions, utility and expression
|
||||
controls. All nine **Layer Styles** (Drop Shadow, Inner/Outer Glow, Bevel and Emboss, Satin,
|
||||
overlays, Stroke) with Global Light. Preview plays audio in sync, with meters and waveforms.
|
||||
|
||||
<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,
|
||||
@@ -160,7 +156,7 @@ MP4, **WebM** (VP9 with inter frames and alpha, or AV1; Opus audio), PNG, JPEG,
|
||||
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
|
||||
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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -22,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;
|
||||
@@ -33,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).
|
||||
@@ -180,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<_>>()) {
|
||||
@@ -205,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 {
|
||||
@@ -245,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}");
|
||||
@@ -268,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);
|
||||
});
|
||||
}
|
||||
@@ -398,6 +465,7 @@ fn main() -> eframe::Result {
|
||||
window: window::Tracker::new(opened, saved_window, control_port.is_none()),
|
||||
launch,
|
||||
drawn: false,
|
||||
reporter: desktop_reporter,
|
||||
}))
|
||||
}),
|
||||
);
|
||||
@@ -491,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 {
|
||||
@@ -525,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) {
|
||||
|
||||
@@ -135,3 +135,6 @@ display_name = "Jonathan Cardoso"
|
||||
|
||||
[people.nazar-gavrylyk]
|
||||
sync_github_name = true
|
||||
|
||||
[people.andreaaazo]
|
||||
sync_github_name = 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
|
||||
+23
-14
@@ -3,7 +3,9 @@
|
||||
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));
|
||||
- `export`: writes an EffectCraft project as an `.aep` with every chunk built in code, and reports everything it does not export
|
||||
@@ -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
|
||||
@@ -69,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,61 +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 version;
|
||||
mod write;
|
||||
|
||||
pub use aepx::{is_aepx, parse_any, read_aepx, read_aepx_with_limits};
|
||||
pub use arbitrary::{
|
||||
CURVE_IDENTITY, CryptomatteData, CurvesData, ExtractorChannels, HueSaturationData, LevelsData, MeshData, curve_lut, identifier_channel_type,
|
||||
};
|
||||
pub use camera::{CameraPosition, DEFAULT_CAMERA_ZOOM};
|
||||
pub use chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk};
|
||||
pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue};
|
||||
pub use error::AepError;
|
||||
pub use footage::{Footage, SequenceInfo};
|
||||
pub use header::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Quality, Rational, Renderer};
|
||||
pub use keys::{ExpressionFlags, Interpolation, KeyEase, KeyframeKind, SpatialKey};
|
||||
pub use masks::{Mask, MaskAtom, MaskMode, PathVertex, ShapePath};
|
||||
pub use matte::{MatteMode, TrackMatte};
|
||||
pub use read::{Limits, parse, parse_with_limits};
|
||||
pub use settings::{ProjectSettings, TimeDisplay, WorkingSpace};
|
||||
pub use shapes::{GradientType, PolystarType, ShapeDetail, ShapeGroup, ShapeItem, Stroke, StrokeCap, StrokeJoin};
|
||||
pub use textdoc::{
|
||||
AutoKern, Caps, CueType, FontBaseline, Justification, KernRun, Marker, ParagraphRun, StyleRun, TextBox, TextDocument, TextValue, parse_text_dict,
|
||||
};
|
||||
pub use typed::{Comp, Item, ItemKind, KeyLayout, KeyList, Keyframe, Layer, ListHeader, Project, PropEntry, PropGroup, PropNode, Property, TimeBase};
|
||||
pub use values::{Orientation, OrientationKey, TimeRemap, TimeRemapKey, Tracked, Transform, ValueSource};
|
||||
pub use version::AeVersion;
|
||||
pub use write::{write, write_to};
|
||||
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,555 +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)
|
||||
}
|
||||
}
|
||||
|
||||
/// EXtractoR's Channel Info data (`EXtractoR-0013`, 688 bytes, the plug-in's own little-endian
|
||||
/// layout; read from the instances of the importer block of 2026-11-05: the defaults and a preset
|
||||
/// of our own that reads `Z` into Red, Green and Blue): a `u32` 1 and 28 bytes, then four records
|
||||
/// of 164 bytes (Red, Green, Blue, Alpha), each a kind in byte 0 (1 a channel of the footage by
|
||||
/// name, 2 the input's own channel: `(copy)`; bytes 1..4 are not always zero, `0x32` at 3 in one
|
||||
/// definition's default, so only byte 0 is read) and the channel name from byte 35,
|
||||
/// NUL-terminated. The other bytes are not read (they differ between instances with the same
|
||||
/// channels; the `u32` at 4 of a chosen channel looks like its position in the footage's sorted
|
||||
/// channel list, 13 of 14 for `Z`, where the defaults hold 0). Only the name is read.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ExtractorChannels {
|
||||
/// Per output channel (red, green, blue, alpha): the kind and the name.
|
||||
pub channels: [(u32, String); 4],
|
||||
}
|
||||
|
||||
impl ExtractorChannels {
|
||||
/// The data's length.
|
||||
pub const LEN: usize = 688;
|
||||
const RECORD: usize = 164;
|
||||
|
||||
/// `None` when the data does not have this layout.
|
||||
pub fn parse(data: &[u8]) -> Option<Self> {
|
||||
if data.len() != Self::LEN || data.get(..4)? != 1u32.to_le_bytes() {
|
||||
return None;
|
||||
}
|
||||
let mut channels: [(u32, String); 4] = Default::default();
|
||||
for (k, slot) in channels.iter_mut().enumerate() {
|
||||
let at = 32usize.checked_add(k.checked_mul(Self::RECORD)?)?;
|
||||
let rec = data.get(at..at.checked_add(Self::RECORD)?)?;
|
||||
let kind = u32::from(*rec.first()?);
|
||||
let name = rec.get(35..)?;
|
||||
let end = name.iter().position(|b| *b == 0)?;
|
||||
let name = std::str::from_utf8(name.get(..end)?).ok()?;
|
||||
*slot = (kind, name.to_string());
|
||||
}
|
||||
Some(Self { channels })
|
||||
}
|
||||
|
||||
/// The channels of a fresh EXtractoR: Red, Green and Blue from the channels of those names,
|
||||
/// Alpha copied from the input.
|
||||
pub fn is_default(&self) -> bool {
|
||||
let want = [(1, "R"), (1, "G"), (1, "B"), (2, "(copy)")];
|
||||
self.channels.iter().zip(want).all(|((k, n), (wk, wn))| *k == wk && n == wn)
|
||||
}
|
||||
|
||||
/// Per output channel (red, green, blue, alpha) the channel it reads, `Err` with the
|
||||
/// position of the first record of another kind or without a name: a named channel by its
|
||||
/// name, `(copy)` as EffectCraft's [`EXTRACTOR_COPY`](effectcraft_effects::EXTRACTOR_COPY),
|
||||
/// the effect input's own channel of the same position. It is not `R`, `G`, `B` or `A`:
|
||||
/// EffectCraft's EXtractoR reads those from an OpenEXR footage's channels of that name, the
|
||||
/// file's own, which loses what an earlier effect did to the channel.
|
||||
pub fn sources(&self) -> Result<[String; 4], usize> {
|
||||
let mut out: [String; 4] = Default::default();
|
||||
for (k, ((kind, name), slot)) in self.channels.iter().zip(out.iter_mut()).enumerate() {
|
||||
*slot = match (kind, name.trim()) {
|
||||
(1, n) if !n.is_empty() => n.to_string(),
|
||||
(2, _) => effectcraft_effects::EXTRACTOR_COPY.to_string(),
|
||||
_ => return Err(k),
|
||||
};
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// IDentifier's Channel Info data (`IDentifier-0005`, 148 bytes): the chosen channel's name,
|
||||
/// NUL-terminated from byte 19, or `Object ID` when none is chosen (importer blocks 1300 and 1310
|
||||
/// of 2026-11-05: `objectId` in a preset of our own that chose that UINT channel, `Object ID` in
|
||||
/// every other instance). The bytes around it differ between instances with the same settings
|
||||
/// and are not read (a chosen channel has 15 at byte 4, which looks like its position in the
|
||||
/// EXR's sorted channel list, as for EXtractoR).
|
||||
pub fn identifier_channel_type(data: &[u8]) -> Option<&str> {
|
||||
let s = data.get(19..)?;
|
||||
let end = s.iter().position(|b| *b == 0)?;
|
||||
std::str::from_utf8(s.get(..end)?).ok()
|
||||
}
|
||||
|
||||
/// The Cryptomatte plug-in's Settings data (`Cryptomatte-0001`, the plug-in's own layout,
|
||||
/// little-endian; read from 88 instances of one project and from our own sample 1400, fresh
|
||||
/// instances and two presets that pick a layer and an object, docs/aep-format.md 3.7): the magic
|
||||
/// `cry1`; bytes 4..32 are not read (they differ between instances holding the same settings);
|
||||
/// the Cryptomatte layer's name at 32, NUL-padded to 64 bytes (`CryptoObject`); at 96 a `u32` 1
|
||||
/// and a `u32` (neither read); at 104 the `u32` length of the selection text including its NUL,
|
||||
/// the `u32` MurmurHash3 (x86, 32-bit, seed 0) of that text with its NUL (not read) and a zero
|
||||
/// byte; the selection text from byte 113 (`<11a97486>, <deadbeef>`, the matte list as ID hashes,
|
||||
/// the hashes of the picked names). Bytes after it are left-overs of a longer earlier text. A
|
||||
/// fresh effect stores no layer and an empty text (length 1, its NUL); the `u32`s at 100 and 108
|
||||
/// are then both `0x514e28b7`, the hash of one NUL byte: the one at 100 looks like the hash of a
|
||||
/// first text that is empty in every sample, the zero byte at 112 like that text.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct CryptomatteData {
|
||||
/// The Cryptomatte layer's name (`CryptoMaterial`: the EXR layer's name, which is also its
|
||||
/// channel prefix in every sample); empty when none is chosen.
|
||||
pub layer: String,
|
||||
/// The selection (matte list) as the plug-in stores it.
|
||||
pub selection: String,
|
||||
}
|
||||
|
||||
impl CryptomatteData {
|
||||
/// Decodes the data; `None` when it is not this layout (no `cry1`, too short, a length past
|
||||
/// the end, no zero byte at 112, a text without its NUL, text that is not UTF-8).
|
||||
pub fn parse(data: &[u8]) -> Option<Self> {
|
||||
if data.get(..4)? != b"cry1" {
|
||||
return None;
|
||||
}
|
||||
let text = |b: &[u8]| -> Option<String> {
|
||||
let end = b.iter().position(|c| *c == 0).unwrap_or(b.len());
|
||||
String::from_utf8(b.get(..end)?.to_vec()).ok()
|
||||
};
|
||||
let layer = text(data.get(32..96)?)?;
|
||||
let len = usize::try_from(u32::from_le_bytes(data.get(104..108)?.try_into().ok()?)).ok()?;
|
||||
if *data.get(112)? != 0 {
|
||||
return None;
|
||||
}
|
||||
let selection = if len == 0 {
|
||||
String::new()
|
||||
} else {
|
||||
// The length counts the text's NUL as its last byte: a text without it, or with an early
|
||||
// NUL before more bytes (which `text` would silently cut short), is not this layout.
|
||||
let b = data.get(113..113usize.checked_add(len)?)?;
|
||||
let (last, text_bytes) = b.split_last()?;
|
||||
if *last != 0 || text_bytes.contains(&0) {
|
||||
return None;
|
||||
}
|
||||
text(b)?
|
||||
};
|
||||
Some(Self { layer, selection })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::CryptomatteData;
|
||||
|
||||
/// Settings data in the layout [`CryptomatteData::parse`] reads, with `noise` in the bytes it
|
||||
/// does not read.
|
||||
fn crypto(layer: &str, selection: &str, noise: u8) -> Vec<u8> {
|
||||
let mut d = b"cry1".to_vec();
|
||||
d.resize(32, noise);
|
||||
d.extend(layer.as_bytes());
|
||||
d.resize(96, 0);
|
||||
d.extend(1u32.to_le_bytes());
|
||||
d.extend([noise; 4]);
|
||||
let len = if selection.is_empty() { 0 } else { selection.len() + 1 };
|
||||
d.extend(u32::try_from(len).unwrap_or(0).to_le_bytes());
|
||||
d.extend([noise; 4]);
|
||||
d.push(0);
|
||||
d.extend(selection.as_bytes());
|
||||
d.push(0);
|
||||
// Left-overs of an earlier, longer text.
|
||||
d.extend(b" <de");
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cryptomatte_settings_are_read() {
|
||||
for noise in [0, 0x5a] {
|
||||
let d = CryptomatteData::parse(&crypto("Layer_A", "<0000002a>, <deadbeef>", noise));
|
||||
assert_eq!(d, Some(CryptomatteData { layer: "Layer_A".into(), selection: "<0000002a>, <deadbeef>".into() }), "noise {noise}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_whose_nul_is_not_its_last_byte_is_refused() {
|
||||
// An early NUL followed by more declared bytes would shorten the selection silently.
|
||||
let mut d = crypto("Layer_A", "<0000002a>, <deadbeef>", 0);
|
||||
d[113 + 4] = 0;
|
||||
assert_eq!(CryptomatteData::parse(&d), None);
|
||||
// No NUL at the end of the declared length.
|
||||
let mut d = crypto("Layer_A", "<0000002a>", 0);
|
||||
d[113 + 10] = b'x';
|
||||
assert_eq!(CryptomatteData::parse(&d), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_cryptomatte_settings_are_empty() {
|
||||
let mut d = b"cry1".to_vec();
|
||||
d.resize(116, 0);
|
||||
assert_eq!(CryptomatteData::parse(&d), Some(CryptomatteData::default()));
|
||||
// What After Effects 2026 wrote for a fresh effect (plug-in 2.6.6, sample 1400
|
||||
// `crypto-00-defaults`, the `pard` default and the instance's record alike): an empty text
|
||||
// of length 1 and its hash, twice.
|
||||
let mut fresh = b"cry1".to_vec();
|
||||
fresh.resize(96, 0);
|
||||
for _ in 0..2 {
|
||||
fresh.extend(1u32.to_le_bytes());
|
||||
fresh.extend(0x514e_28b7u32.to_le_bytes());
|
||||
}
|
||||
fresh.extend([0; 4]);
|
||||
assert_eq!(fresh.len(), 116);
|
||||
assert_eq!(CryptomatteData::parse(&fresh), Some(CryptomatteData::default()));
|
||||
}
|
||||
|
||||
/// The Settings data After Effects 2026 wrote for the two presets of sample 1400 (plug-in
|
||||
/// 2.6.6, `crypto-06-preset-object-box` and `crypto-07-preset-material-paint`: a layer chosen
|
||||
/// and one object or material picked in the plug-in's UI), byte for byte: 127 bytes, the `u32`
|
||||
/// at 108 the MurmurHash3 of the text with its NUL, three zero bytes after the text.
|
||||
#[test]
|
||||
fn the_presets_of_our_sample_are_read() {
|
||||
for (layer, selection, hash) in [("CryptoObject", "<11a97486>", 0x2788_0767u32), ("CryptoMaterial", "<a5deeb9e>", 0xf737_4a5b)] {
|
||||
let mut d = b"cry1".to_vec();
|
||||
d.resize(32, 0);
|
||||
d.extend(layer.as_bytes());
|
||||
d.resize(96, 0);
|
||||
for v in [1, 0x514e_28b7, 11, hash] {
|
||||
d.extend(u32::to_le_bytes(v));
|
||||
}
|
||||
d.push(0);
|
||||
d.extend(selection.as_bytes());
|
||||
d.extend([0; 4]);
|
||||
assert_eq!(d.len(), 127);
|
||||
assert_eq!(CryptomatteData::parse(&d), Some(CryptomatteData { layer: layer.into(), selection: selection.into() }), "{layer}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_cryptomatte_settings_are_not_read() {
|
||||
let good = crypto("L", "<00000001>", 0);
|
||||
let mut bad_magic = good.clone();
|
||||
bad_magic[0] = b'x';
|
||||
let mut past_end = good.clone();
|
||||
past_end[104..108].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
let mut no_zero = good.clone();
|
||||
no_zero[112] = b'<';
|
||||
let mut not_utf8 = good.clone();
|
||||
not_utf8[32] = 0xff;
|
||||
// The length covers the text without its NUL (`<00000001>` is 10 bytes, its NUL the 11th).
|
||||
let mut no_nul = good.clone();
|
||||
no_nul[104..108].copy_from_slice(&10u32.to_le_bytes());
|
||||
// No zero byte at 112 with an empty text.
|
||||
let mut empty_no_zero = crypto("L", "", 0);
|
||||
empty_no_zero[112] = b'<';
|
||||
for (what, d) in [
|
||||
("magic", bad_magic),
|
||||
("length", past_end),
|
||||
("zero byte", no_zero),
|
||||
("utf-8", not_utf8),
|
||||
("no NUL", no_nul),
|
||||
("empty text, zero byte", empty_no_zero),
|
||||
("short", good[..100].to_vec()),
|
||||
("empty", Vec::new()),
|
||||
] {
|
||||
assert_eq!(CryptomatteData::parse(&d), None, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
//! Plain data; the evidence for each row is in `docs/aep-format.md` 3.7 and the case numbers in
|
||||
//! 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)]
|
||||
@@ -38,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"];
|
||||
@@ -1142,11 +1155,37 @@ 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)
|
||||
@@ -1164,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,727 +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`.
|
||||
//!
|
||||
//! Some files have no `EfdG` at all (seen in 17 projects, all from inside After Effects-made
|
||||
//! Motion Graphics templates). In those, one instance per effect type kept its full `parT` (which
|
||||
//! one is not known) and it is the only place the definitions are written, so the other instances
|
||||
//! of that type borrow them from it (#3170).
|
||||
|
||||
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,
|
||||
/// The own `parT` of another instance of the same match name in the file: the instance's
|
||||
/// own `parT` is empty and the file has no project-level copy of the type (a project without
|
||||
/// `EfdG`, #3170).
|
||||
OtherInstance,
|
||||
/// None of these 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 borrowed: the project-level copy ([`DefinitionSource::Project`])
|
||||
/// or another instance's ([`DefinitionSource::OtherInstance`]).
|
||||
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 match names of the value records in the instance's own `tdgp` (properties only, not
|
||||
/// groups), in file order, each once.
|
||||
pub fn value_record_names(&self) -> Vec<String> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
self.chunk
|
||||
.child_list(b"tdgp")
|
||||
.and_then(PropGroup::from_chunk)
|
||||
.map(|g| g.entries())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|e| matches!(e.node, PropNode::Property(_)))
|
||||
.map(|e| e.match_name)
|
||||
.filter(|n| seen.insert(n.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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()
|
||||
// An empty `pdnm` names nothing (EffectCraft's exports write one: the effect
|
||||
// supplies its items).
|
||||
&& !b.is_empty()
|
||||
{
|
||||
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).
|
||||
/// For a type without a project-level copy it also keeps the own `parT` of the first instance
|
||||
/// in the file (items, layers and effects in file order) that has one.
|
||||
pub fn effect_definition_index(&self) -> EffectDefinitions<'f, 'a> {
|
||||
let by_name: HashMap<String, &'f Chunk<'a>> = self.effect_definitions().into_iter().collect();
|
||||
let mut instances: HashMap<String, &'f Chunk<'a>> = HashMap::new();
|
||||
for item in self.all_items() {
|
||||
let Some(comp) = item.comp() else { continue };
|
||||
for layer in comp.layers() {
|
||||
for fx in layer.effects() {
|
||||
if by_name.contains_key(&fx.match_name) || instances.contains_key(&fx.match_name) {
|
||||
continue;
|
||||
}
|
||||
if let Some(part) = fx.chunk.child_list(b"parT").filter(|p| has_pard(p)) {
|
||||
instances.insert(fx.match_name, part);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EffectDefinitions { by_name, instances }
|
||||
}
|
||||
|
||||
/// 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 borrowable effect definitions by match name ([`Project::effect_definition_index`]).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct EffectDefinitions<'f, 'a> {
|
||||
/// The project-level copies (`EfdG`).
|
||||
by_name: HashMap<String, &'f Chunk<'a>>,
|
||||
/// For a type without a project-level copy: the own `parT` of the first instance that has one.
|
||||
instances: 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 if self.instances.contains_key(effect.match_name()) {
|
||||
DefinitionSource::OtherInstance
|
||||
} 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, else from another instance of it that has
|
||||
/// its own ([`EffectParam::borrowed_definition`]). Values always come from the instance's own
|
||||
/// records (absent = the `pard` default); the values next to borrowed definitions 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()).or_else(|| self.instances.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,409 +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::chunk::Chunk;
|
||||
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), or its file list when it was imported with
|
||||
/// Force alphabetical order.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SequenceInfo {
|
||||
/// The file name before the frame number (`seq_`, `shot_`): the first `Utf8` after the alias.
|
||||
/// An empty prefix is not stored (`0001.png`): the one `Utf8` is then the suffix.
|
||||
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; both `0xFFFFFFFF` for a sequence with a file list).
|
||||
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,
|
||||
/// The file names in order for a sequence imported with Force alphabetical order (`LIST StVc`
|
||||
/// after the alias: `StVS` with the count as a little-endian `u32`, then one `Utf8` per file);
|
||||
/// empty for a numbered sequence. When set, it replaces the numbering.
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/// The number of files: the listed files, or the frame numbers from start to end (0 when the
|
||||
/// end lies before the start).
|
||||
pub fn frame_count(&self) -> u32 {
|
||||
if self.files.is_empty() {
|
||||
self.end.checked_sub(self.start).map_or(0, |d| d.saturating_add(1))
|
||||
} else {
|
||||
u32::try_from(self.files.len()).unwrap_or(u32::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the `i`-th file (from 0): from the file list, or numbered from `start`; `None`
|
||||
/// past the last file.
|
||||
pub fn nth_file_name(&self, i: u32) -> Option<String> {
|
||||
if self.files.is_empty() {
|
||||
let n = self.start.checked_add(i).filter(|n| *n <= self.end)?;
|
||||
Some(self.file_name(n))
|
||||
} else {
|
||||
self.files.get(usize::try_from(i).ok()?).cloned()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file names of a `LIST StVc` (Force alphabetical order): the `Utf8` children in order, at most
|
||||
/// as many as the count in `StVS` (little-endian `u32`) says. Empty names count toward that number
|
||||
/// and are then skipped. Without a readable count (no `StVS`, or one shorter than 4 bytes) the list
|
||||
/// is unreadable (empty). A name that is not a plain file name (holding `/`, `\`, `:` or a control
|
||||
/// character such as NUL, or being `.` or `..`) makes the whole list unreadable (empty): the names
|
||||
/// are joined to the folder.
|
||||
fn sequence_file_list(list: &Chunk<'_>) -> Vec<String> {
|
||||
// After Effects writes the count first (the one sample); a list without a readable count is
|
||||
// not read rather than guessed.
|
||||
let Some(count) = list.child(b"StVS").and_then(|c| c.bytes()).and_then(|b| le_u32(b, 0)).and_then(|n| usize::try_from(n).ok()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let names: Vec<String> =
|
||||
list.children().iter().filter(|c| c.is(b"Utf8")).filter_map(|c| c.bytes()).take(count).map(text).filter(|n| !n.is_empty()).collect();
|
||||
if names.iter().any(|n| n.contains(|c: char| matches!(c, '/' | '\\' | ':') || c.is_control()) || n == "." || n == "..") {
|
||||
return Vec::new();
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// The prefix and suffix of a sequence whose naming holds one `Utf8` (`part`): After Effects leaves
|
||||
/// out an empty prefix (`0001.png` stores only `.png`). The stored first file name (`opti`) decides:
|
||||
/// a name starting with `part` has it as the prefix, one ending with it as the suffix. Without that
|
||||
/// evidence, a `part` starting with `.` is the suffix (an extension); anything else is not read.
|
||||
fn single_name_part(part: &str, first_file: Option<&str>) -> Option<(String, String)> {
|
||||
if let Some(first) = first_file.filter(|_| !part.is_empty()) {
|
||||
match (first.starts_with(part), first.ends_with(part)) {
|
||||
(true, false) => return Some((part.to_string(), String::new())),
|
||||
(false, true) => return Some((String::new(), part.to_string())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
part.starts_with('.').then(|| (String::new(), part.to_string()))
|
||||
}
|
||||
|
||||
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 naming = || kids.iter().skip(after.saturating_add(1)).take_while(|c| !c.is(b"opti"));
|
||||
let (start, end, digits) = (be_u32(sspc, 172)?, be_u32(sspc, 176)?, be_u32(sspc, 180)?);
|
||||
// Force alphabetical order: the file list replaces the numbering.
|
||||
if let Some(list) = naming().find(|c| c.is_list(b"StVc")) {
|
||||
let files = sequence_file_list(list);
|
||||
if files.is_empty() {
|
||||
return None;
|
||||
}
|
||||
return Some(SequenceInfo { prefix: String::new(), suffix: String::new(), start, end, digits, files });
|
||||
}
|
||||
let names: Vec<String> = naming().filter(|c| c.is(b"Utf8")).filter_map(|c| c.bytes()).map(text).take(2).collect();
|
||||
let (prefix, suffix) = match names.as_slice() {
|
||||
[prefix, suffix] => (prefix.clone(), suffix.clone()),
|
||||
// An empty prefix is not stored (`0001.png` has only `.png`).
|
||||
[one] => single_name_part(one, f.name.as_deref())?,
|
||||
_ => return None,
|
||||
};
|
||||
Some(SequenceInfo { prefix, suffix, start, end, digits, files: Vec::new() })
|
||||
}
|
||||
|
||||
/// 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])
|
||||
}
|
||||
}
|
||||
@@ -73,10 +73,6 @@ pub struct StyleMap {
|
||||
}
|
||||
|
||||
impl StyleMap {
|
||||
/// The switch group's match name (`dropShadow/enabled`).
|
||||
pub fn switch_name(&self) -> String {
|
||||
format!("{}/enabled", self.ae)
|
||||
}
|
||||
/// A parameter's full match name (`dropShadow/opacity`).
|
||||
pub fn param_name(&self, p: &StyleParam) -> String {
|
||||
format!("{}/{}", self.ae, p.ae)
|
||||
|
||||
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,120 +0,0 @@
|
||||
//! The After Effects version a project is written for (`head` bytes 4 to 7) and the version of the
|
||||
//! After Effects that wrote it (`svap`).
|
||||
//!
|
||||
//! Both hold the same packed `u32` (see `docs/aep-format.md`, section 1, "Version"). A project saved
|
||||
//! normally has the same word in both; File ▸ Save a Copy As 25.x / 24.x of After Effects 2026 keeps
|
||||
//! `svap` (the 2026 version) and writes the older version into `head`. The XMP packet after the
|
||||
//! container names the application of the first save (`CreatorTool`) and is no guide to either.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::container::bytes::{be_u16, be_u32};
|
||||
use crate::container::chunk::AepFile;
|
||||
|
||||
/// An After Effects version as packed in `head` / `svap`: `26.2.1x2` is major 26, minor 2, bug-fix
|
||||
/// 1, build 2 (the form of the scripting API's `app.version`).
|
||||
///
|
||||
/// Bit layout of the big-endian word (bit 31 first), decoded from the samples (the 2026 word
|
||||
/// `0x0f11_0e02` is the version the saving After Effects reports, `26.2.1x2`; the down-saves give
|
||||
/// `0x0f0b_0661` and `0x0f03_0641`, read as `25.6.0x97` and `24.6.0x65`):
|
||||
///
|
||||
/// | bits | field |
|
||||
/// |---|---|
|
||||
/// | 31-26 | not decoded (`000011` in every sample) |
|
||||
/// | 25-24, 21-19 | major (high two bits, then low three bits) |
|
||||
/// | 23-22 | not decoded (`00` in every sample) |
|
||||
/// | 18-15 | minor |
|
||||
/// | 14-11 | bug-fix |
|
||||
/// | 10-8 | stage (6 in every sample) |
|
||||
/// | 7-0 | build |
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AeVersion {
|
||||
pub major: u8,
|
||||
pub minor: u8,
|
||||
pub bugfix: u8,
|
||||
/// The release stage (6 in every sample; not shown in [`AeVersion::text`]).
|
||||
pub stage: u8,
|
||||
pub build: u8,
|
||||
/// The word as stored.
|
||||
pub raw: u32,
|
||||
}
|
||||
|
||||
impl AeVersion {
|
||||
/// Decodes a stored word; `None` for a word that holds no version (zero, all ones, or major 0:
|
||||
/// After Effects itself refuses a file whose `head` version is zero, "[0.0x0]").
|
||||
pub fn from_word(raw: u32) -> Option<Self> {
|
||||
if raw == 0 || raw == u32::MAX {
|
||||
return None;
|
||||
}
|
||||
let [b0, b1, b2, b3] = raw.to_be_bytes();
|
||||
let major = ((b0 & 0x03) << 3) | ((b1 >> 3) & 0x07);
|
||||
if major == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(Self { major, minor: ((b1 & 0x07) << 1) | (b2 >> 7), bugfix: (b2 >> 3) & 0x0f, stage: b2 & 0x07, build: b3, raw })
|
||||
}
|
||||
|
||||
/// `26.2.1x2`.
|
||||
pub fn text(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for AeVersion {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}.{}.{}x{}", self.major, self.minor, self.bugfix, self.build)
|
||||
}
|
||||
}
|
||||
|
||||
impl AepFile<'_> {
|
||||
/// The version the file is written for: `head` bytes 4 to 7. After Effects 2026 writes its own
|
||||
/// version there, and the older version for File ▸ Save a Copy As 25.x / 24.x. `None` when the
|
||||
/// chunk is missing, short or holds no version.
|
||||
pub fn file_version(&self) -> Option<AeVersion> {
|
||||
AeVersion::from_word(be_u32(self.chunk(b"head")?.bytes()?, 4)?)
|
||||
}
|
||||
|
||||
/// The version of the After Effects that wrote the file: `svap` bytes 0 to 3 (the same word in a
|
||||
/// down-saved copy as in a normal save). `None` when the chunk is missing (After Effects opens such
|
||||
/// a file), short or holds no version.
|
||||
pub fn saved_by_version(&self) -> Option<AeVersion> {
|
||||
AeVersion::from_word(be_u32(self.chunk(b"svap")?.bytes()?, 0)?)
|
||||
}
|
||||
|
||||
/// The `u16` at `head` byte 0: 97 (`0x61`) in a 2026 file, 96 in a copy saved as 25.x, 95 as
|
||||
/// 24.x. It steps with the major version of [`AepFile::file_version`]; what it counts is not
|
||||
/// known, so nothing is derived from it.
|
||||
pub fn head_revision(&self) -> Option<u16> {
|
||||
be_u16(self.chunk(b"head")?.bytes()?, 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::AeVersion;
|
||||
|
||||
#[test]
|
||||
fn decodes_the_sampled_words() {
|
||||
let v = AeVersion::from_word(0x0f11_0e02).unwrap();
|
||||
assert_eq!((v.major, v.minor, v.bugfix, v.stage, v.build), (26, 2, 1, 6, 2));
|
||||
assert_eq!(v.text(), "26.2.1x2");
|
||||
assert_eq!(AeVersion::from_word(0x0f0b_0661).unwrap().text(), "25.6.0x97");
|
||||
assert_eq!(AeVersion::from_word(0x0f03_0641).unwrap().text(), "24.6.0x65");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_without_a_version_is_none() {
|
||||
assert_eq!(AeVersion::from_word(0), None);
|
||||
assert_eq!(AeVersion::from_word(u32::MAX), None);
|
||||
// Major 0 (only the undecoded high bits set).
|
||||
assert_eq!(AeVersion::from_word(0x0c00_0000), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_field_takes_its_extremes() {
|
||||
let v = AeVersion::from_word(0x03ff_ffff).unwrap();
|
||||
assert_eq!((v.major, v.minor, v.bugfix, v.stage, v.build), (31, 15, 15, 7, 255));
|
||||
let v = AeVersion::from_word(0x0000_0800 | 0x0008_0000).unwrap();
|
||||
assert_eq!((v.major, v.minor, v.bugfix, v.build), (1, 0, 1, 0));
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -26,6 +26,7 @@ mod footage;
|
||||
mod fx_defs;
|
||||
mod fxsynth;
|
||||
pub(crate) mod icc;
|
||||
mod keys;
|
||||
mod markers;
|
||||
mod masks;
|
||||
mod plan;
|
||||
|
||||
@@ -6,15 +6,20 @@
|
||||
//! (read-backs t-no<id>, t-zcdta, u-zsspc, u-noclrs, u-noftgi, u-nofrec, u-nocdrp).
|
||||
|
||||
use crate::Chunk;
|
||||
use crate::export::synth::{tdmn, tdsn};
|
||||
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.
|
||||
/// 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> {
|
||||
let mut b = vec![0u8; len];
|
||||
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 {
|
||||
if let Some(dst) = b.get_mut(*at..at.saturating_add(v.len())) {
|
||||
dst.copy_from_slice(v);
|
||||
}
|
||||
b.put(*at, v);
|
||||
}
|
||||
b
|
||||
}
|
||||
@@ -52,12 +57,8 @@ pub(crate) fn project_chunks() -> Vec<Chunk<'static>> {
|
||||
// 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 mut lhd3 = bytes(52, &[(0, &0x00d0_0bee_u32.to_be_bytes()), (12, &1u32.to_be_bytes()), (16, &RQ_ITEM_LEN.to_be_bytes())]);
|
||||
for at in [20, 24, 28] {
|
||||
if let Some(dst) = lhd3.get_mut(at..at + 4) {
|
||||
dst.copy_from_slice(&1u32.to_be_bytes());
|
||||
}
|
||||
}
|
||||
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()),
|
||||
@@ -157,30 +158,17 @@ fn view_layer(ty: &[u8; 4], name: &str, label: u8, kind: u8) -> Vec<Chunk<'stati
|
||||
let markers = kind == 4;
|
||||
let mut name_copy = name.as_bytes().to_vec();
|
||||
name_copy.truncate(31);
|
||||
let mut ldta = bytes(
|
||||
164,
|
||||
&[
|
||||
(8, &1u32.to_be_bytes()),
|
||||
(16, &600u32.to_be_bytes()),
|
||||
(24, &25_600u32.to_be_bytes()),
|
||||
(28, &VIEW_OUT.to_be_bytes()),
|
||||
(32, &25_600u32.to_be_bytes()),
|
||||
(61, &[label]),
|
||||
(64, &name_copy),
|
||||
(108, &1u32.to_be_bytes()),
|
||||
(128, &u32::from(kind).to_be_bytes()),
|
||||
],
|
||||
);
|
||||
// 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)] };
|
||||
for (at, v) in flags {
|
||||
if let Some(b) = ldta.get_mut(*at) {
|
||||
*b = *v;
|
||||
}
|
||||
}
|
||||
let root = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(""), tdmn("ADBE Group End")];
|
||||
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());
|
||||
@@ -293,6 +281,16 @@ pub(crate) fn solid_item() -> Chunk<'static> {
|
||||
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]
|
||||
|
||||
@@ -13,7 +13,8 @@ use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{Layer, LightKind};
|
||||
|
||||
use crate::export::report::{Collector, LossCategory};
|
||||
use crate::export::tree::{R, child_data, kids_mut, list_mut, put_f64, tpl};
|
||||
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)]
|
||||
@@ -183,50 +184,24 @@ const LIGHT_ORDER: &[&str] = &[
|
||||
"ADBE Casts Shadows",
|
||||
];
|
||||
|
||||
pub(crate) fn tdmn_chunk(name: &str) -> Chunk<'static> {
|
||||
let mut b = vec![0u8; 40];
|
||||
for (i, c) in name.bytes().take(39).enumerate() {
|
||||
b[i] = c;
|
||||
}
|
||||
Chunk::data(*b"tdmn", b)
|
||||
}
|
||||
|
||||
fn tdmn_name(c: &Chunk<'_>) -> Option<String> {
|
||||
let b = c.bytes()?;
|
||||
let end = b.iter().position(|x| *x == 0).unwrap_or(b.len());
|
||||
std::str::from_utf8(b.get(..end)?).ok().map(str::to_string)
|
||||
}
|
||||
|
||||
/// 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| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(group)).ok_or_else(|| tpl("options group missing"))?;
|
||||
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)?;
|
||||
let first = gk.iter().position(|c| c.is(b"tdmn")).unwrap_or(gk.len());
|
||||
let header: Vec<Chunk<'static>> = gk.drain(..first).collect();
|
||||
let mut pairs: Vec<(String, Vec<Chunk<'static>>)> = Vec::new();
|
||||
let mut it = std::mem::take(gk).into_iter();
|
||||
while let Some(m) = it.next() {
|
||||
let name = tdmn_name(&m).unwrap_or_default();
|
||||
if name == "ADBE Group End" {
|
||||
pairs.push((name, vec![m]));
|
||||
continue;
|
||||
}
|
||||
let Some(node) = it.next() else { break };
|
||||
// An atom group (Light Env Atom) carries its own Group End inside the list.
|
||||
pairs.push((name, vec![m, node]));
|
||||
}
|
||||
// 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_chunk(name), rec];
|
||||
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 == "ADBE Group End" { usize::MAX } else { order.iter().position(|g| *g == n).unwrap_or(order.len()) };
|
||||
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));
|
||||
|
||||
+359
-80
@@ -6,8 +6,10 @@ use std::collections::HashMap;
|
||||
use crate::{AepFile, Chunk};
|
||||
use effectcraft_project::{ItemId, LayerId};
|
||||
|
||||
use crate::export::keys::fill_key_list;
|
||||
use crate::export::plan::{CompPlan, Entry, ItemPlan, KeyPlan, LayerPlan, LayerSrc, ProjectPlan, PropKind, PropPlan, SolidPlan, natural_key};
|
||||
use crate::export::template::Template;
|
||||
use crate::export::synth::{is_tdmn, tdmn_name};
|
||||
use crate::export::template::{self, Template};
|
||||
use crate::export::tree::{
|
||||
R, child_data, data_mut, kids_mut, list_mut, put, put_bits, put_cstr, put_f32, put_f64, put_i32, put_u8, put_u16, put_u32, set_utf8, tpl,
|
||||
};
|
||||
@@ -58,10 +60,14 @@ struct Cx<'t> {
|
||||
type Sorted = (String, u64, Vec<Chunk<'static>>);
|
||||
|
||||
pub(crate) fn emit(plan: &ProjectPlan, extra: &[u8]) -> R<Vec<u8>> {
|
||||
let t = Template::load()?;
|
||||
emit_with(template::shared()?, plan, extra)
|
||||
}
|
||||
|
||||
/// [`emit`] with the prototypes of `t`.
|
||||
fn emit_with(t: &Template, plan: &ProjectPlan, extra: &[u8]) -> R<Vec<u8>> {
|
||||
let special = plan.root.iter().find(|e| e.name == "Solids" && matches!(e.plan, ItemPlan::Folder(_))).map(|e| e.ec);
|
||||
let mut cx = Cx {
|
||||
t: &t,
|
||||
t,
|
||||
ids: Ids { next: FIRST_ID },
|
||||
solid_ids: HashMap::new(),
|
||||
comp_ids: HashMap::new(),
|
||||
@@ -77,16 +83,14 @@ pub(crate) fn emit(plan: &ProjectPlan, extra: &[u8]) -> R<Vec<u8>> {
|
||||
|
||||
let mut root: Vec<Sorted> = Vec::new();
|
||||
build_level(&plan.root, &mut cx, &ids_by_entry, &mut |name, key, chunks| root.push((name, key, chunks)))?;
|
||||
// The Solids folder: root-level solids and the hidden solids of null layers.
|
||||
let mut solids_children: Vec<Sorted> = Vec::new();
|
||||
for (name, key, chunks) in root.iter().filter(|(_, k, _)| *k & ROOT_SOLID != 0) {
|
||||
solids_children.push((name.clone(), *key, chunks.clone()));
|
||||
}
|
||||
root.retain(|(_, k, c)| *k & ROOT_SOLID == 0 && !c.is_empty());
|
||||
for (i, (name, chunk)) in cx.extra_solids.iter().enumerate() {
|
||||
let mut v = vec![chunk.clone()];
|
||||
// The Solids folder: root-level solids and the hidden solids of null layers (moved, not
|
||||
// copied: the root keeps neither).
|
||||
let (mut solids_children, mut root): (Vec<Sorted>, Vec<Sorted>) = root.into_iter().partition(|(_, k, _)| *k & ROOT_SOLID != 0);
|
||||
root.retain(|(_, _, c)| !c.is_empty());
|
||||
for (i, (name, chunk)) in std::mem::take(&mut cx.extra_solids).into_iter().enumerate() {
|
||||
let mut v = vec![chunk];
|
||||
v.extend(cx.t.fset.iter().cloned());
|
||||
solids_children.push((name.clone(), i as u64, v));
|
||||
solids_children.push((name, i as u64, v));
|
||||
}
|
||||
let mut folder = match cx.special_slot.take() {
|
||||
Some((item, inner)) => {
|
||||
@@ -125,26 +129,57 @@ pub(crate) fn emit(plan: &ProjectPlan, extra: &[u8]) -> R<Vec<u8>> {
|
||||
/// Marks a root entry that goes into the `Solids` folder.
|
||||
const ROOT_SOLID: u64 = 1 << 63;
|
||||
|
||||
/// Sorts by name in natural order, then by the tie-break key. Each name's sort key is built once,
|
||||
/// not on every comparison; the sort is stable, as `sort_by` is.
|
||||
fn sort_named(v: &mut [Sorted]) {
|
||||
v.sort_by(|a, b| natural_cmp(&a.0, &b.0).then(a.1.cmp(&b.1)));
|
||||
v.sort_by_cached_key(|(name, key, _)| (natural_bytes(name), *key));
|
||||
}
|
||||
|
||||
fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
let (ka, kb) = (natural_key(a), natural_key(b));
|
||||
for (x, y) in ka.iter().zip(kb.iter()) {
|
||||
let c = match (x.0, y.0) {
|
||||
(true, true) => x.2.cmp(&y.2).then_with(|| x.1.cmp(&y.1)),
|
||||
(false, false) => x.1.cmp(&y.1),
|
||||
(true, false) => std::cmp::Ordering::Less,
|
||||
(false, true) => std::cmp::Ordering::Greater,
|
||||
};
|
||||
if c != std::cmp::Ordering::Equal {
|
||||
return c;
|
||||
/// The [`natural_key`] of `name` as one byte string whose plain byte order is the natural order:
|
||||
/// segment by segment, a number before text, numbers by value and then by their digit strings
|
||||
/// byte by byte (`01` before `1`), text by its lowercase string, and a key that is a prefix of
|
||||
/// the other first.
|
||||
///
|
||||
/// - A number: `0x01`, the count of significant bytes of its value, those bytes big-endian, its
|
||||
/// digits, `0x00` (digits are never `0x00`, so a digit string that is a prefix of another, as
|
||||
/// `0` of `00`, sorts first).
|
||||
/// - Text: `0x02`, its lowercase UTF-8 with each `0x00` written as `0x00 0x01`, then `0x00 0x00`.
|
||||
///
|
||||
/// At most 5 bytes per byte of `name` (`NATURAL_BYTES_PER_NAME_BYTE`), so the cached keys stay
|
||||
/// within a small multiple of the names they sort (one segment as a `(bool, String, u128)` takes
|
||||
/// 48 bytes plus its string, which is why the segments themselves are not cached).
|
||||
fn natural_bytes(name: &str) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(name.len().saturating_add(4));
|
||||
for (number, text, value) in natural_key(name) {
|
||||
if number {
|
||||
out.push(0x01);
|
||||
let be = value.to_be_bytes();
|
||||
let zeros = be.iter().take_while(|b| **b == 0).count();
|
||||
let significant = be.get(zeros..).unwrap_or_default();
|
||||
out.push(significant.len() as u8);
|
||||
out.extend_from_slice(significant);
|
||||
out.extend_from_slice(text.as_bytes());
|
||||
out.push(0x00);
|
||||
} else {
|
||||
out.push(0x02);
|
||||
for b in text.bytes() {
|
||||
out.push(b);
|
||||
if b == 0 {
|
||||
out.push(0x01);
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(&[0x00, 0x00]);
|
||||
}
|
||||
}
|
||||
ka.len().cmp(&kb.len())
|
||||
out
|
||||
}
|
||||
|
||||
/// The bound on [`natural_bytes`]: a run of `d` digits takes at most `3 + 2d` bytes (its value
|
||||
/// never needs more bytes than digits), a text run of `b` bytes at most `3 + 2b` (lowercasing and
|
||||
/// the NUL escape at most double a character), and every run is at least one byte long.
|
||||
#[cfg(test)]
|
||||
const NATURAL_BYTES_PER_NAME_BYTE: usize = 5;
|
||||
|
||||
fn assign_ids(entries: &[Entry], cx: &mut Cx<'_>, map: &mut HashMap<ItemId, u32>) -> R<()> {
|
||||
// Iterative to bound the stack by the folder depth the plan already limits.
|
||||
let mut stack: Vec<&Entry> = entries.iter().rev().collect();
|
||||
@@ -404,8 +439,7 @@ fn put_used_comps(cx: &Cx<'_>, item: &mut Chunk<'static>, cp: &CompPlan) -> R<()
|
||||
fn put_time_remap_max(layr: &mut Chunk<'static>, seconds: f64) -> R<()> {
|
||||
let root = list_mut(layr, b"tdgp")?;
|
||||
let kids = kids_mut(root)?;
|
||||
let at =
|
||||
kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Time Remapping")).ok_or_else(|| tpl("layer without Time Remapping"))?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, "ADBE Time Remapping")).ok_or_else(|| tpl("layer without Time Remapping"))?;
|
||||
let tdbs = kids.get_mut(at + 1).ok_or_else(|| tpl("Time Remapping without a record"))?;
|
||||
put_f64(child_data(tdbs, b"tduM")?, 0, seconds)
|
||||
}
|
||||
@@ -420,8 +454,7 @@ fn put_time_remap_max(layr: &mut Chunk<'static>, seconds: f64) -> R<()> {
|
||||
fn put_time_remap(cx: &Cx<'_>, layr: &mut Chunk<'static>, remap: &PropPlan) -> R<()> {
|
||||
let root = list_mut(layr, b"tdgp")?;
|
||||
let kids = kids_mut(root)?;
|
||||
let at =
|
||||
kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Time Remapping")).ok_or_else(|| tpl("layer without Time Remapping"))?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, "ADBE Time Remapping")).ok_or_else(|| tpl("layer without Time Remapping"))?;
|
||||
let tdbs = kids.get_mut(at + 1).ok_or_else(|| tpl("Time Remapping without a record"))?;
|
||||
put_u32(child_data(tdbs, b"tdsb")?, 0, 1)?;
|
||||
{
|
||||
@@ -454,21 +487,12 @@ fn put_time_remap(cx: &Cx<'_>, layr: &mut Chunk<'static>, remap: &PropPlan) -> R
|
||||
.find(|k| matches!(&k.body, crate::Body::List { list_type, .. } if list_type == b"list"))
|
||||
.cloned()
|
||||
.ok_or_else(|| tpl("keyed prototype without a list"))?;
|
||||
let n = u32::try_from(remap.keys.len()).map_err(|_| tpl("too many keys"))?;
|
||||
let size = 48usize;
|
||||
{
|
||||
let lhd3 = child_data(&mut list, b"lhd3")?;
|
||||
crate::export::synth::put_key_counts(lhd3, n, 48)?;
|
||||
}
|
||||
let mut ldat = Vec::with_capacity(size * remap.keys.len());
|
||||
for k in &remap.keys {
|
||||
ldat.extend(plain_record(1, k, size)?);
|
||||
}
|
||||
let ld = kids_mut(&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)),
|
||||
}
|
||||
fill_key_list(&mut list, ldat, remap.keys.len(), size)?;
|
||||
if let Some(slot) = rk.get_mut(cdat_at) {
|
||||
*slot = list;
|
||||
}
|
||||
@@ -616,10 +640,7 @@ fn put_masks(cx: &Cx<'_>, layr: &mut Chunk<'static>, lp: &LayerPlan) -> R<()> {
|
||||
let parade = crate::export::masks::build_parade(&cx.t.masks, &lp.masks, lp.source_size)?;
|
||||
let root = list_mut(layr, b"tdgp")?;
|
||||
let kids = kids_mut(root)?;
|
||||
let at = kids
|
||||
.iter()
|
||||
.position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Transform Group"))
|
||||
.ok_or_else(|| tpl("layer without a Transform group"))?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, "ADBE Transform Group")).ok_or_else(|| tpl("layer without a Transform group"))?;
|
||||
kids.splice(at..at, parade);
|
||||
Ok(())
|
||||
}
|
||||
@@ -633,10 +654,7 @@ fn put_effects(cx: &mut Cx<'_>, layr: &mut Chunk<'static>, lp: &LayerPlan, layer
|
||||
let parade = crate::export::effects::build_parade(&cx.t.effects, &lp.fx, layer_id, layer_ids, lp.source_size, &mut cx.fx_use)?;
|
||||
let root = list_mut(layr, b"tdgp")?;
|
||||
let kids = kids_mut(root)?;
|
||||
let at = kids
|
||||
.iter()
|
||||
.position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Transform Group"))
|
||||
.ok_or_else(|| tpl("layer without a Transform group"))?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, "ADBE Transform Group")).ok_or_else(|| tpl("layer without a Transform group"))?;
|
||||
kids.splice(at..at, parade);
|
||||
Ok(())
|
||||
}
|
||||
@@ -659,11 +677,6 @@ const GROUP_ORDER: [&str; 13] = [
|
||||
"ADBE Group End",
|
||||
];
|
||||
|
||||
fn tdmn_name(c: &Chunk<'_>) -> Option<String> {
|
||||
let d = c.bytes()?;
|
||||
Some(d.iter().take_while(|b| **b != 0).map(|b| char::from(*b)).collect())
|
||||
}
|
||||
|
||||
/// Inserts the properties of `lp` into the layer's Transform group, in the order the file uses.
|
||||
fn put_properties(cx: &Cx<'_>, layr: &mut Chunk<'static>, lp: &LayerPlan, cp: &CompPlan) -> R<()> {
|
||||
if lp.props.is_empty() {
|
||||
@@ -671,20 +684,19 @@ fn put_properties(cx: &Cx<'_>, layr: &mut Chunk<'static>, lp: &LayerPlan, cp: &C
|
||||
}
|
||||
let root = list_mut(layr, b"tdgp")?;
|
||||
let kids = kids_mut(root)?;
|
||||
let at = kids
|
||||
.iter()
|
||||
.position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Transform Group"))
|
||||
.ok_or_else(|| tpl("layer without a Transform group"))?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, "ADBE Transform Group")).ok_or_else(|| tpl("layer without a Transform group"))?;
|
||||
let group = kids.get_mut(at + 1).ok_or_else(|| tpl("Transform group without a list"))?;
|
||||
let gk = kids_mut(group)?;
|
||||
// Split the group into its header (up to the first match name) and (tdmn, node) pairs.
|
||||
let first = gk.iter().position(|c| c.is(b"tdmn")).ok_or_else(|| tpl("empty Transform group"))?;
|
||||
let header: Vec<Chunk<'static>> = gk.drain(..first).collect();
|
||||
let mut pairs: Vec<(String, Vec<Chunk<'static>>)> = Vec::new();
|
||||
let mut pairs: Vec<(Vec<u8>, Vec<Chunk<'static>>)> = Vec::new();
|
||||
let mut it = std::mem::take(gk).into_iter();
|
||||
while let Some(m) = it.next() {
|
||||
let name = tdmn_name(&m).unwrap_or_default();
|
||||
if name == "ADBE Group End" {
|
||||
// The match name as the shared decoder reads it (lossy UTF-8 up to the first NUL). Every
|
||||
// name looked up below is ASCII, so a name matches exactly when its bytes do.
|
||||
let name = tdmn_name(&m).unwrap_or_default().into_bytes();
|
||||
if name == b"ADBE Group End" {
|
||||
pairs.push((name, vec![m]));
|
||||
continue;
|
||||
}
|
||||
@@ -694,22 +706,19 @@ fn put_properties(cx: &Cx<'_>, layr: &mut Chunk<'static>, lp: &LayerPlan, cp: &C
|
||||
for p in &lp.props {
|
||||
let name = p.kind.match_name();
|
||||
let built = build_prop(cx, p, lp, cp)?;
|
||||
let tdmn = pairs.iter().find(|(n, _)| n == name).and_then(|(_, v)| v.first().cloned()).unwrap_or_else(|| {
|
||||
cx.t.stat
|
||||
.iter()
|
||||
.chain(cx.t.keyd.iter())
|
||||
.find(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(name))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Chunk::data(*b"tdmn", Vec::new()))
|
||||
let tdmn = pairs.iter().find(|(n, _)| n == name.as_bytes()).and_then(|(_, v)| v.first().cloned()).unwrap_or_else(|| {
|
||||
cx.t.stat.iter().chain(cx.t.keyd.iter()).find(|c| is_tdmn(c, name)).cloned().unwrap_or_else(|| Chunk::data(*b"tdmn", Vec::new()))
|
||||
});
|
||||
let entry = vec![tdmn, built];
|
||||
if let Some(slot) = pairs.iter_mut().find(|(n, _)| n == name) {
|
||||
if let Some(slot) = pairs.iter_mut().find(|(n, _)| n == name.as_bytes()) {
|
||||
slot.1 = entry;
|
||||
} else {
|
||||
pairs.push((name.to_string(), entry));
|
||||
pairs.push((name.as_bytes().to_vec(), entry));
|
||||
}
|
||||
}
|
||||
let rank = |n: &str| if n == "ADBE Group End" { usize::MAX } else { GROUP_ORDER.iter().position(|g| *g == n).unwrap_or(GROUP_ORDER.len()) };
|
||||
let rank = |n: &[u8]| {
|
||||
if n == b"ADBE Group End" { usize::MAX } else { GROUP_ORDER.iter().position(|g| g.as_bytes() == n).unwrap_or(GROUP_ORDER.len()) }
|
||||
};
|
||||
pairs.sort_by_key(|(n, _)| rank(n));
|
||||
gk.extend(header);
|
||||
gk.extend(pairs.into_iter().flat_map(|(_, v)| v));
|
||||
@@ -743,22 +752,12 @@ fn build_prop(cx: &Cx<'_>, p: &PropPlan, lp: &LayerPlan, cp: &CompPlan) -> R<Chu
|
||||
put_f64(cdat, i * 8, *v)?;
|
||||
}
|
||||
} else {
|
||||
let list = list_mut(&mut tdbs, b"list")?;
|
||||
let n = u32::try_from(p.keys.len()).map_err(|_| tpl("too many keys"))?;
|
||||
let size = if p.kind.spatial() { 56 + 24 * p.kind.dims() } else { 8 + 40 * p.kind.dims() };
|
||||
{
|
||||
let lhd3 = child_data(list, b"lhd3")?;
|
||||
crate::export::synth::put_key_counts(lhd3, n, u32::try_from(size).map_err(|_| tpl("record size"))?)?;
|
||||
}
|
||||
let mut ldat = Vec::with_capacity(size * p.keys.len());
|
||||
for k in &p.keys {
|
||||
ldat.extend(key_record(p.kind, k, size)?);
|
||||
}
|
||||
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)),
|
||||
}
|
||||
fill_key_list(list_mut(&mut tdbs, b"list")?, ldat, p.keys.len(), size)?;
|
||||
}
|
||||
if let Some((text, _)) = &p.expr {
|
||||
let kids = kids_mut(&mut tdbs)?;
|
||||
@@ -818,3 +817,283 @@ pub(crate) fn plain_record(n: usize, k: &KeyPlan, size: usize) -> R<Vec<u8>> {
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_keyframe::{Keyframe, Value};
|
||||
use effectcraft_project::{Comp, Expression, ItemKind, LayerSource, Project, Property, Solid, build};
|
||||
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
|
||||
|
||||
/// Seconds as ticks.
|
||||
fn secs(s: f64) -> Tick {
|
||||
Tick((s * TICKS_PER_SECOND as f64).round() as i64)
|
||||
}
|
||||
|
||||
/// Adds a layer to `comp`, changed by `edit` first.
|
||||
fn add_layer(p: &mut Project, comp: ItemId, name: &str, source: LayerSource, edit: impl FnOnce(&mut effectcraft_project::Layer)) {
|
||||
let mut c = p.comp(comp).cloned().expect("comp");
|
||||
let mut l = build::layer(p, &c, name, source, (640, 360), None);
|
||||
l.name = name.to_string();
|
||||
edit(&mut l);
|
||||
c.layers.insert(0, l);
|
||||
if let Some(i) = p.item_mut(comp) {
|
||||
i.kind = ItemKind::Comp(Arc::new(c));
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the property two keys (0 s and 1.5 s) holding its value.
|
||||
fn two_keys(prop: Option<&mut Property>) {
|
||||
let prop = prop.expect("property");
|
||||
let v = prop.value.clone();
|
||||
prop.keys = vec![Keyframe::new(secs(0.0), v.clone()), Keyframe::new(secs(1.5), v)];
|
||||
}
|
||||
|
||||
/// A project that reaches every part of `emit`: folders (one named `Solids`), root and nested
|
||||
/// solids with names that sort naturally, a precomposition, null layers (hidden solids), keyed
|
||||
/// Transform properties, an expression and a keyed time remap.
|
||||
fn varied(tag: &str) -> Project {
|
||||
let mut p = Project::default();
|
||||
let solid = |w| ItemKind::Solid(Solid { color: [0.2, 0.4, 0.6], width: w, height: 360, pixel_aspect: 1.0 });
|
||||
let solids = p.add_item("Solids", Label::None, None, ItemKind::Folder);
|
||||
let nested = p.add_item("Folder 10", Label::None, None, ItemKind::Folder);
|
||||
p.add_item("folder 9", Label::None, Some(nested), ItemKind::Folder);
|
||||
let mut ids = Vec::new();
|
||||
for name in ["Solid 10", "Solid 2", "solid 2", "Solid 02", "Solid", "Ölung 1", ""] {
|
||||
ids.push(p.add_item(&format!("{name}{tag}"), Label::Red, None, solid(640)));
|
||||
}
|
||||
p.add_item("In Solids 3", Label::None, Some(solids), solid(320));
|
||||
p.add_item("In folder", Label::None, Some(nested), solid(100));
|
||||
let pre = p.add_item("Pre 1", Label::None, Some(nested), ItemKind::Comp(Arc::new(Comp::new(640, 360, FrameRate::new(25, 1), secs(3.0)))));
|
||||
add_layer(&mut p, pre, "S", LayerSource::Solid { item: ids[0] }, |_| {});
|
||||
let main = p.add_item("Main", Label::None, None, ItemKind::Comp(Arc::new(Comp::new(1920, 1080, FrameRate::new(30, 1), secs(5.0)))));
|
||||
add_layer(&mut p, main, "Null A", LayerSource::Null, |_| {});
|
||||
add_layer(&mut p, main, "Null B", LayerSource::Null, |l| two_keys(l.props.prop_mut("transform/position")));
|
||||
add_layer(&mut p, main, "Solid layer", LayerSource::Solid { item: ids[1] }, |l| {
|
||||
two_keys(l.props.prop_mut("transform/opacity"));
|
||||
two_keys(l.props.prop_mut("transform/anchor"));
|
||||
if let Some(r) = l.props.prop_mut("transform/rotation") {
|
||||
r.expr = Some(Expression { text: "time * 10".into(), enabled: true });
|
||||
}
|
||||
});
|
||||
add_layer(&mut p, main, "Precomp", LayerSource::Comp { item: pre }, |l| {
|
||||
let mut r = Property::new(9_000, "timeRemap", "Time Remap", Value::Scalar(0.0));
|
||||
r.keys = vec![Keyframe::new(secs(0.0), Value::Scalar(3.0)), Keyframe::new(secs(3.0), Value::Scalar(0.0))];
|
||||
l.props.children.insert(0, r.into());
|
||||
});
|
||||
p
|
||||
}
|
||||
|
||||
/// The export plan of `p`.
|
||||
fn plan_of(p: &Project) -> ProjectPlan {
|
||||
let mut col = crate::export::report::Collector::default();
|
||||
crate::export::plan::plan(p, &mut col)
|
||||
}
|
||||
|
||||
/// The template is built once and every later export uses the same one.
|
||||
#[test]
|
||||
fn the_template_is_built_once() {
|
||||
let a = template::shared().expect("template");
|
||||
let b = template::shared().expect("template");
|
||||
assert!(std::ptr::eq(a, b));
|
||||
}
|
||||
|
||||
/// Exports with the shared template give the bytes a freshly built template gives, also after
|
||||
/// other exports have used it (nothing an export does reaches the template).
|
||||
#[test]
|
||||
fn the_shared_template_exports_what_a_fresh_one_does() {
|
||||
let (a, b) = (plan_of(&varied("")), plan_of(&varied(" x")));
|
||||
let fresh = |plan: &ProjectPlan| emit_with(&Template::load().expect("template"), plan, b"trailer").expect("emit");
|
||||
let (want_a, want_b) = (fresh(&a), fresh(&b));
|
||||
assert!(want_a != want_b);
|
||||
// The project exports without losses and the remap is written.
|
||||
let r = crate::export::export(&varied(""), &crate::export::ExportOptions { allow_losses: false }).expect("lossless");
|
||||
assert_eq!(r.report.exported.time_remaps, 1);
|
||||
// The null layers' hidden solids and the root solids went into the `Solids` folder.
|
||||
let file = crate::parse(&want_a).expect("parse");
|
||||
let folder = file.walk().map(|(_, c)| c).filter(|c| c.is_list(b"Sfdr")).map(|c| c.children().iter().filter(|k| k.is_list(b"Item")).count()).max();
|
||||
assert_eq!(folder, Some(10));
|
||||
for _ in 0..3 {
|
||||
assert!(emit(&a, b"trailer").expect("emit") == want_a);
|
||||
assert!(emit(&b, b"trailer").expect("emit") == want_b);
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports running at the same time on several threads all give the single-threaded bytes.
|
||||
/// This checks concurrent exports from a template that is already built: other tests in this
|
||||
/// binary usually fill the shared template first, so the race on the first build is not
|
||||
/// reliably exercised here (the `static OnceLock` makes that race safe by construction).
|
||||
#[test]
|
||||
fn concurrent_exports_give_the_same_bytes() {
|
||||
let plans: Vec<ProjectPlan> = ["", " x", " y", " z"].iter().map(|t| plan_of(&varied(t))).collect();
|
||||
let want: Vec<Vec<u8>> = plans.iter().map(|plan| emit_with(&Template::load().expect("template"), plan, &[]).expect("emit")).collect();
|
||||
let got: Vec<Vec<Vec<u8>>> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = (0..8)
|
||||
.map(|i| {
|
||||
let plans = &plans;
|
||||
s.spawn(move || (0..4).map(|k| emit(&plans[(i + k) % plans.len()], &[]).expect("emit")).collect::<Vec<_>>())
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().map(|h| h.join().expect("thread")).collect()
|
||||
});
|
||||
for (i, bytes) in got.iter().enumerate() {
|
||||
for (k, b) in bytes.iter().enumerate() {
|
||||
assert!(b == &want[(i + k) % want.len()], "thread {i}, export {k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The comparator `sort_named` used before its keys were cached: `natural_key` built on every
|
||||
/// comparison.
|
||||
fn old_sort_named(v: &mut [Sorted]) {
|
||||
/// The natural name order the cached sort keys replaced, as the reference.
|
||||
fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
let (ka, kb) = (natural_key(a), natural_key(b));
|
||||
for (x, y) in ka.iter().zip(kb.iter()) {
|
||||
let c = match (x.0, y.0) {
|
||||
(true, true) => x.2.cmp(&y.2).then_with(|| x.1.cmp(&y.1)),
|
||||
(false, false) => x.1.cmp(&y.1),
|
||||
(true, false) => std::cmp::Ordering::Less,
|
||||
(false, true) => std::cmp::Ordering::Greater,
|
||||
};
|
||||
if c != std::cmp::Ordering::Equal {
|
||||
return c;
|
||||
}
|
||||
}
|
||||
ka.len().cmp(&kb.len())
|
||||
}
|
||||
v.sort_by(|a, b| natural_cmp(&a.0, &b.0).then(a.1.cmp(&b.1)));
|
||||
}
|
||||
|
||||
/// The cached-key sort orders names exactly as the comparator it replaced, and keeps entries
|
||||
/// with the same name and key in their order (each carries its position as a marker chunk).
|
||||
#[test]
|
||||
fn sort_named_orders_as_the_old_comparator() {
|
||||
let parts = [
|
||||
"",
|
||||
"0",
|
||||
"00",
|
||||
"1",
|
||||
"01",
|
||||
"2",
|
||||
"10",
|
||||
"a",
|
||||
"A",
|
||||
"b",
|
||||
" ",
|
||||
"-",
|
||||
".",
|
||||
"é",
|
||||
"É",
|
||||
"ß",
|
||||
"İ",
|
||||
"\u{0}",
|
||||
"\u{1}",
|
||||
"a\u{0}",
|
||||
"Ⱥ",
|
||||
"K",
|
||||
"ẞ",
|
||||
"Solid ",
|
||||
"solid ",
|
||||
"x9",
|
||||
"9x",
|
||||
"340282366920938463463374607431768211455",
|
||||
"340282366920938463463374607431768211456",
|
||||
"999999999999999999999999999999999999999999",
|
||||
];
|
||||
// A small deterministic generator (splitmix64).
|
||||
let mut state = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let mut next = move || {
|
||||
state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
let mut z = state;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
(z ^ (z >> 31)) as usize
|
||||
};
|
||||
for round in 0..2000 {
|
||||
let n = 1 + next() % 40;
|
||||
let v: Vec<Sorted> = (0..n)
|
||||
.map(|i| {
|
||||
let name: String = (0..next() % 4).map(|_| parts[next() % parts.len()]).collect();
|
||||
let key = (next() % 3) as u64 | if next() % 2 == 0 { ROOT_SOLID } else { 0 };
|
||||
(name, key, vec![Chunk::data(*b"mark", (i as u32).to_le_bytes().to_vec())])
|
||||
})
|
||||
.collect();
|
||||
let (mut old, mut new) = (v.clone(), v);
|
||||
old_sort_named(&mut old);
|
||||
sort_named(&mut new);
|
||||
assert_eq!(old, new, "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The cached sort keys stay within [`NATURAL_BYTES_PER_NAME_BYTE`] bytes per name byte, also
|
||||
/// for the worst name (255 bytes of alternating one-character text and digit runs: 255
|
||||
/// segments, which as `(bool, String, u128)` segments took about 14 KB), and the per-character
|
||||
/// premise of the bound holds for every character.
|
||||
#[test]
|
||||
fn sort_keys_are_bounded_by_the_name() {
|
||||
for c in (0..=0x10_ffff_u32).filter_map(char::from_u32) {
|
||||
let lower: usize = c.to_lowercase().map(char::len_utf8).sum::<usize>() + usize::from(c == '\0');
|
||||
assert!(lower <= 2 * c.len_utf8(), "{c:?}");
|
||||
}
|
||||
let worst: String = (0..255).map(|i| if i % 2 == 0 { 'a' } else { '1' }).collect();
|
||||
let others = ["", "1", "a", "\u{0}", "İ", "Ⱥ1", "99999999999999999999999999999999999999999999", &"\u{0}".repeat(255), &"Ⱥ".repeat(127)];
|
||||
for name in std::iter::once(worst.as_str()).chain(others) {
|
||||
let k = natural_bytes(name);
|
||||
assert!(k.len() <= NATURAL_BYTES_PER_NAME_BYTE * name.len(), "{name:?}: {} bytes", k.len());
|
||||
}
|
||||
assert_eq!(natural_key(&worst).len(), 255);
|
||||
assert!(natural_bytes(&worst).len() <= 1_275);
|
||||
}
|
||||
|
||||
/// The shared `is_tdmn` / `tdmn_name` the emitter uses agree with the Latin-1 decoding it used
|
||||
/// before for every name it looks up, which holds because those names are ASCII.
|
||||
#[test]
|
||||
fn match_names_compare_as_the_latin1_decoding_did() {
|
||||
/// The Latin-1 decoding the emitter used before.
|
||||
fn old_tdmn_name(c: &Chunk<'_>) -> Option<String> {
|
||||
let d = c.bytes()?;
|
||||
Some(d.iter().take_while(|b| **b != 0).map(|b| char::from(*b)).collect())
|
||||
}
|
||||
let mut wanted: Vec<&str> = GROUP_ORDER.to_vec();
|
||||
wanted.extend(PropKind::ALL.iter().map(|k| k.match_name()));
|
||||
wanted.extend(["ADBE Time Remapping", "ADBE Transform Group", "ADBE Group End"]);
|
||||
assert!(wanted.iter().all(|n| n.is_ascii()));
|
||||
let mut chunks: Vec<Chunk<'static>> = wanted.iter().map(|n| Chunk::data(*b"tdmn", format!("{n}\0\0junk").into_bytes())).collect();
|
||||
chunks.extend([
|
||||
Chunk::data(*b"tdmn", Vec::new()),
|
||||
Chunk::data(*b"tdmn", b"ADBE Position".to_vec()),
|
||||
Chunk::data(*b"tdmn", b"ADBE Position_0\0".to_vec()),
|
||||
Chunk::data(*b"tdmn", b"ADBE Opacit\xe9\0".to_vec()),
|
||||
Chunk::data(*b"tdmn", b"\xc3\x84DBE Scale\0".to_vec()),
|
||||
Chunk::data(*b"tdmn", b"\0ADBE Scale".to_vec()),
|
||||
Chunk::list(*b"tdmn", Vec::new()),
|
||||
]);
|
||||
for c in &chunks {
|
||||
for n in &wanted {
|
||||
assert_eq!(is_tdmn(c, n), old_tdmn_name(c).as_deref() == Some(*n), "{c:?} {n}");
|
||||
let key = tdmn_name(c).unwrap_or_default().into_bytes();
|
||||
assert_eq!(key == n.as_bytes(), old_tdmn_name(c).as_deref() == Some(*n), "{c:?} {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `fill_key_list`, which the time remap and the Transform keys use, writes the counts and
|
||||
/// replaces the records, or adds them when the list has none.
|
||||
#[test]
|
||||
fn fill_key_list_writes_counts_and_records() {
|
||||
let lhd3 = || Chunk::data(*b"lhd3", vec![0; 52]);
|
||||
let mut want_lhd3 = vec![0; 52];
|
||||
crate::export::synth::put_key_counts(&mut want_lhd3, 3, 48).expect("counts");
|
||||
for start in [vec![lhd3(), Chunk::data(*b"ldat", vec![9; 4])], vec![lhd3()]] {
|
||||
let mut list = Chunk::list(*b"list", start);
|
||||
fill_key_list(&mut list, vec![7; 144], 3, 48).expect("set");
|
||||
assert_eq!(list.children(), &[Chunk::data(*b"lhd3", want_lhd3.clone()), Chunk::data(*b"ldat", vec![7; 144])]);
|
||||
}
|
||||
let mut no_header = Chunk::list(*b"list", Vec::new());
|
||||
assert!(fill_key_list(&mut no_header, Vec::new(), 0, 48).is_err());
|
||||
}
|
||||
}
|
||||
@@ -707,3 +707,99 @@ pub(crate) static FX_DEFS: &[FxDef] = &[
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,8 @@
|
||||
use crate::Chunk;
|
||||
use crate::effect_map::{Conv, by_match_name};
|
||||
use crate::export::fx_defs::{BUILT_IN, FxDef, PDef};
|
||||
use crate::export::synth::{KeyTemplate, NO_NAME, RecSpec, class, tdmn, tdsn};
|
||||
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
|
||||
@@ -37,12 +38,6 @@ pub(crate) fn value_spec(code: u8, range: Option<(f64, f64)>) -> Option<RecSpec>
|
||||
})
|
||||
}
|
||||
|
||||
fn put(b: &mut [u8], at: usize, bytes: &[u8]) {
|
||||
if let Some(dst) = b.get_mut(at..at + bytes.len()) {
|
||||
dst.copy_from_slice(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
fn fixed(v: f64) -> [u8; 4] {
|
||||
((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes()
|
||||
}
|
||||
@@ -53,83 +48,88 @@ fn fixed(v: f64) -> [u8; 4] {
|
||||
/// 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> {
|
||||
let mut b = vec![0u8; 148];
|
||||
put(&mut b, 12, &u32::from(p.code).to_be_bytes());
|
||||
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 => {
|
||||
put(&mut b, 56, &d(0).to_be_bytes());
|
||||
b.put(56, &d(0).to_be_bytes());
|
||||
// The default again as `f32` at 120, the display word (decimals) at 124.
|
||||
put(&mut b, 120, &(d(0) as f32).to_be_bytes());
|
||||
put(&mut b, 124, &p.display.to_be_bytes());
|
||||
b.put(120, &(d(0) as f32).to_be_bytes());
|
||||
b.put(124, &p.display.to_be_bytes());
|
||||
}
|
||||
2 => put(&mut b, 56, &fixed(d(0))),
|
||||
2 => b.put(56, &fixed(d(0))),
|
||||
// An angle: the default again at 60.
|
||||
3 => {
|
||||
put(&mut b, 56, &fixed(d(0)));
|
||||
put(&mut b, 60, &fixed(d(0)));
|
||||
b.put(56, &fixed(d(0)));
|
||||
b.put(60, &fixed(d(0)));
|
||||
}
|
||||
1 => put(&mut b, 56, &(d(0).round() as i32).to_be_bytes()),
|
||||
1 => b.put(56, &(d(0).round() as i32).to_be_bytes()),
|
||||
// A checkbox: the default again as a byte at 60.
|
||||
4 => {
|
||||
put(&mut b, 56, &(d(0).round().max(0.0) as u32).to_be_bytes());
|
||||
put(&mut b, 60, &[u8::from(d(0) != 0.0)]);
|
||||
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));
|
||||
put(&mut b, 56, &(sel as u32).to_be_bytes());
|
||||
put(&mut b, 62, &(sel as u16).to_be_bytes());
|
||||
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.
|
||||
put(&mut b, 56, &fixed(d(0)));
|
||||
put(&mut b, 60, &fixed(d(1)));
|
||||
put(&mut b, 68, &fixed(d(0) * 100.0));
|
||||
put(&mut b, 72, &fixed(d(1) * 100.0));
|
||||
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();
|
||||
put(&mut b, 56, &c);
|
||||
put(&mut b, 60, &c);
|
||||
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));
|
||||
put(&mut b, 60, &n.to_be_bytes());
|
||||
b.put(60, &n.to_be_bytes());
|
||||
}
|
||||
match p.code {
|
||||
10 => {
|
||||
if let Some(m) = p.valid_min {
|
||||
put(&mut b, 104, &(m as f32).to_be_bytes());
|
||||
b.put(104, &(m as f32).to_be_bytes());
|
||||
}
|
||||
if let Some(m) = p.valid_max {
|
||||
put(&mut b, 108, &(m as f32).to_be_bytes());
|
||||
b.put(108, &(m as f32).to_be_bytes());
|
||||
}
|
||||
if let Some((lo, hi)) = p.range {
|
||||
put(&mut b, 112, &(lo as f32).to_be_bytes());
|
||||
put(&mut b, 116, &(hi as f32).to_be_bytes());
|
||||
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 {
|
||||
put(&mut b, 124, &enc(m));
|
||||
b.put(124, &enc(m));
|
||||
}
|
||||
if let Some(m) = p.valid_max {
|
||||
put(&mut b, 128, &enc(m));
|
||||
b.put(128, &enc(m));
|
||||
}
|
||||
if let Some((lo, hi)) = p.range {
|
||||
put(&mut b, 132, &enc(lo));
|
||||
put(&mut b, 136, &enc(hi));
|
||||
b.put(132, &enc(lo));
|
||||
b.put(136, &enc(hi));
|
||||
}
|
||||
// The default again at 140, the display word (decimals, percent) at 144.
|
||||
put(&mut b, 140, &enc(d(0)));
|
||||
put(&mut b, 144, &p.display.to_be_bytes());
|
||||
b.put(140, &enc(d(0)));
|
||||
b.put(144, &p.display.to_be_bytes());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -224,7 +224,7 @@ fn data_record(data: Vec<u8>) -> [Chunk<'static>; 2] {
|
||||
/// 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 = Chunk { id: *b"fnam", body: crate::Body::Chunks(vec![Chunk::data(*b"Utf8", fx.name.as_bytes().to_vec())]), pad: None };
|
||||
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)];
|
||||
@@ -235,11 +235,11 @@ pub(crate) fn default_sspc(fx: &FxDef) -> Chunk<'static> {
|
||||
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(Chunk { id: *b"pdnm", body: crate::Body::Chunks(vec![Chunk::data(*b"Utf8", Vec::new())]), pad: None });
|
||||
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("ADBE Group End")]));
|
||||
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 {
|
||||
@@ -265,6 +265,24 @@ pub(crate) fn default_sspc(fx: &FxDef) -> Chunk<'static> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
values.push(tdmn("ADBE Group End"));
|
||||
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,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());
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,11 @@ 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::tree::{R, child_data, child_mut, kids_mut, list_mut, put_f32, put_f64, put_i32, put_u8, put_u16, put_u32, tpl};
|
||||
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;
|
||||
@@ -179,20 +181,7 @@ fn plan_mask(g: &PropGroup, size: (u32, u32), cp: &CompPlan, what: &str, col: &m
|
||||
}
|
||||
// The path and its keys.
|
||||
let mut path_keys: Vec<PathKeyPlan> = Vec::new();
|
||||
let mut keys: Vec<(i64, &effectcraft_keyframe::Keyframe)> = Vec::new();
|
||||
for k in &path_prop.keys {
|
||||
let (u, inexact) = cp.tb.units(k.time);
|
||||
if inexact {
|
||||
col.lose(LossCategory::RoundedTimes, format!("{what}: path key at {:.4} s moved to the time base", k.time.seconds()));
|
||||
}
|
||||
keys.push((u, k));
|
||||
}
|
||||
keys.sort_by_key(|(u, _)| *u);
|
||||
let before = keys.len();
|
||||
keys.dedup_by_key(|(u, _)| *u);
|
||||
if keys.len() != before {
|
||||
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: path keys at the same time were merged"));
|
||||
}
|
||||
let keys = timed_keys(&path_prop.keys, &cp.tb, what, "path key", col);
|
||||
let side = |i: Interp| -> u8 {
|
||||
match i {
|
||||
Interp::Linear => 1,
|
||||
@@ -288,20 +277,7 @@ fn plan_mask(g: &PropGroup, size: (u32, u32), cp: &CompPlan, what: &str, col: &m
|
||||
|
||||
/// 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 mut keys: Vec<(i64, &effectcraft_keyframe::Keyframe)> = Vec::with_capacity(src.len());
|
||||
for k in src {
|
||||
let (u, inexact) = cp.tb.units(k.time);
|
||||
if inexact {
|
||||
col.lose(LossCategory::RoundedTimes, format!("{what}: feather key at {:.4} s moved to the time base", k.time.seconds()));
|
||||
}
|
||||
keys.push((u, k));
|
||||
}
|
||||
keys.sort_by_key(|(u, _)| *u);
|
||||
let before = keys.len();
|
||||
keys.dedup_by_key(|(u, _)| *u);
|
||||
if keys.len() != before {
|
||||
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: feather keys at the same time were merged"));
|
||||
}
|
||||
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 {
|
||||
@@ -381,11 +357,6 @@ pub(crate) struct MaskProtos {
|
||||
pub keyed_feather: Chunk<'static>,
|
||||
}
|
||||
|
||||
pub(crate) fn tdmn_name(c: &Chunk<'_>) -> Option<String> {
|
||||
let d = c.bytes()?;
|
||||
Some(d.iter().take_while(|b| **b != 0).map(|b| char::from(*b)).collect())
|
||||
}
|
||||
|
||||
/// The limit of a mask's feather and expansion (`tduM` 32 000, 091).
|
||||
const MASK_LIMIT: f64 = 32_000.0;
|
||||
|
||||
@@ -394,9 +365,25 @@ const MASK_LIMIT: f64 = 32_000.0;
|
||||
/// 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> {
|
||||
let mut b = vec![0u8; 24];
|
||||
let _ = crate::export::tree::put(&mut b, 0, &[0xb3, 0xde, 0x02, 0x01]);
|
||||
let _ = put_u8(&mut b, 20, 1);
|
||||
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
|
||||
}
|
||||
|
||||
@@ -413,15 +400,7 @@ impl MaskProtos {
|
||||
let path_rec = |keyed: bool| {
|
||||
let mut kids = vec![state(), tdsn(NO_NAME), Chunk::data(*b"tdb4", tdb4(&path, keyed, 25_600))];
|
||||
if keyed {
|
||||
// Path keys are 64-byte records: flags `0x0001`, the `f64` at 16 1 on the first
|
||||
// key (093; the rest of the record is zero: its last bytes were uninitialised).
|
||||
let mut first = vec![0u8; 64];
|
||||
let mut later = vec![0u8; 64];
|
||||
for r in [&mut first, &mut later] {
|
||||
let _ = put_u16(r, 6, 0x0001);
|
||||
}
|
||||
let _ = put_f64(&mut first, 16, 1.0);
|
||||
kids.push(key_list(64, 2, [first, later].concat()));
|
||||
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]));
|
||||
}
|
||||
@@ -444,7 +423,7 @@ impl MaskProtos {
|
||||
tdbs(&opacity, false, 25_600),
|
||||
tdmn("ADBE Mask Offset"),
|
||||
tdbs(&offset, false, 25_600),
|
||||
tdmn("ADBE Group End"),
|
||||
tdmn(GROUP_END),
|
||||
],
|
||||
);
|
||||
MaskProtos {
|
||||
@@ -453,7 +432,7 @@ impl MaskProtos {
|
||||
atom_name: tdmn("ADBE Mask Atom"),
|
||||
mkif: Chunk::data(*b"mkif", vec![0u8; 48]),
|
||||
atom,
|
||||
group_end: tdmn("ADBE Group End"),
|
||||
group_end: tdmn(GROUP_END),
|
||||
keyed_path: path_rec(true),
|
||||
keyed_feather: tdbs(&feather, true, 25_600),
|
||||
}
|
||||
@@ -485,27 +464,21 @@ fn build_atom(t: &MaskProtos, m: &MaskPlan, size: (u32, u32)) -> R<Chunk<'static
|
||||
let tdsn = child_mut(&mut atom, b"tdsn")?;
|
||||
crate::export::tree::set_utf8(tdsn, &m.name)?;
|
||||
}
|
||||
let kids = kids_mut(&mut atom)?;
|
||||
let first = kids.iter().position(|c| c.is(b"tdmn")).ok_or_else(|| tpl("empty mask atom"))?;
|
||||
let header: Vec<Chunk<'static>> = kids.drain(..first).collect();
|
||||
let mut pairs: Vec<(String, [Chunk<'static>; 2])> = Vec::new();
|
||||
let mut end: Option<Chunk<'static>> = None;
|
||||
let mut it = std::mem::take(kids).into_iter();
|
||||
while let Some(c) = it.next() {
|
||||
let name = tdmn_name(&c).unwrap_or_default();
|
||||
if name == "ADBE Group End" {
|
||||
end = Some(c);
|
||||
continue;
|
||||
}
|
||||
let node = it.next().ok_or_else(|| tpl("mask match name without a node"))?;
|
||||
pairs.push((name, [c, node]));
|
||||
}
|
||||
let end = end.ok_or_else(|| tpl("mask atom without its end"))?;
|
||||
let mut out = header;
|
||||
for (name, [tdmn, mut node]) in pairs {
|
||||
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" => {
|
||||
@@ -540,7 +513,10 @@ fn build_atom(t: &MaskProtos, m: &MaskPlan, size: (u32, u32)) -> R<Chunk<'static
|
||||
out.push(node);
|
||||
}
|
||||
}
|
||||
out.push(end);
|
||||
// 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)
|
||||
}
|
||||
@@ -554,22 +530,6 @@ fn set_cdat(tdbs: &mut Chunk<'static>, values: &[f64]) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrites a key list (`lhd3` count words and `ldat`).
|
||||
fn set_key_list(tdbs: &mut Chunk<'static>, records: Vec<u8>, count: usize, size: usize) -> R<()> {
|
||||
let list = list_mut(tdbs, b"list")?;
|
||||
let n = u32::try_from(count).map_err(|_| tpl("too many keys"))?;
|
||||
{
|
||||
let lhd3 = child_data(list, b"lhd3")?;
|
||||
crate::export::synth::put_key_counts(lhd3, n, u32::try_from(size).map_err(|_| tpl("record size"))?)?;
|
||||
}
|
||||
let ld = kids_mut(list)?;
|
||||
match ld.iter_mut().find(|c| c.is(b"ldat")) {
|
||||
Some(c) => *c = Chunk::data(*b"ldat", records),
|
||||
None => ld.push(Chunk::data(*b"ldat", records)),
|
||||
}
|
||||
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.
|
||||
@@ -669,3 +629,37 @@ pub(crate) fn build_shap(proto: &Chunk<'static>, s: &ShapePlan) -> R<Chunk<'stat
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -817,7 +817,7 @@ fn plan_transform(layer: &Layer, src: &LayerSrc, comp: &Comp, source_size: (u32,
|
||||
let cam_light = matches!(src, LayerSrc::Camera(_) | LayerSrc::Light(_));
|
||||
let is_shape = matches!(src, LayerSrc::Shape(_));
|
||||
let mut props = Vec::new();
|
||||
let at = PropAt { comp, comp_name, layer: &layer.name, source: source_size, text: is_text || cam_light || is_shape };
|
||||
let at = PropAt { comp, comp_name, layer: &layer.name, source: source_size, text: is_text || cam_light || is_shape, null: matches!(src, LayerSrc::Null) };
|
||||
if let Some(tr) = layer.transform() {
|
||||
for kind in PropKind::ALL {
|
||||
// A camera's or light's point of interest is After Effects' Anchor Point.
|
||||
@@ -1172,16 +1172,21 @@ struct PropAt<'a> {
|
||||
source: (u32, u32),
|
||||
/// The anchor is stored in pixels (text, camera, light and shape layers).
|
||||
text: bool,
|
||||
/// A null layer: an Anchor Point that is not written is its top-left corner (#3099).
|
||||
null: bool,
|
||||
}
|
||||
|
||||
/// What is written for transform property `p` (`kind`) of a layer: its value or keys in the
|
||||
/// stored unit and its expression; `None` when it is at After Effects' default and has neither.
|
||||
fn plan_prop(kind: PropKind, label: Option<&str>, p: &Property, at: PropAt<'_>, cp: &CompPlan, col: &mut Collector) -> Option<PropPlan> {
|
||||
let PropAt { comp, comp_name, layer, source, text } = at;
|
||||
let PropAt { comp, comp_name, layer, source, text, null } = at;
|
||||
// A text layer's anchor is stored in pixels, with the origin as its default (385).
|
||||
let (sw, sh) = if text { (1.0, 1.0) } else { (f64::from(source.0.max(1)), f64::from(source.1.max(1))) };
|
||||
let what = format!("{comp_name}: '{layer}' {}", label.unwrap_or(kind.match_name()));
|
||||
let dims = kind.dims();
|
||||
let default: Vec<f64> = match kind {
|
||||
PropKind::Anchor if text => vec![0.0, 0.0, 0.0],
|
||||
// After Effects 2026 reads a null's absent Anchor Point as `[0, 0]` (#3099).
|
||||
PropKind::Anchor if text || null => vec![0.0, 0.0, 0.0],
|
||||
PropKind::Anchor => vec![0.5, 0.5, 0.0],
|
||||
PropKind::Position => vec![f64::from(comp.width) / 2.0, f64::from(comp.height) / 2.0, 0.0],
|
||||
PropKind::Scale => vec![1.0, 1.0, 1.0],
|
||||
@@ -1319,7 +1324,7 @@ fn plan_prop(kind: PropKind, label: Option<&str>, p: &Property, at: PropAt<'_>,
|
||||
/// back disabled).
|
||||
fn plan_remap(p: &Property, comp: &Comp, cp: &CompPlan, layer: &str, comp_name: &str, col: &mut Collector) -> PropPlan {
|
||||
// Rotation has the same layout (one component, stored as is, not spatial).
|
||||
let at = PropAt { comp, comp_name, layer, source: (1, 1), text: false };
|
||||
let at = PropAt { comp, comp_name, layer, source: (1, 1), text: false, null: false };
|
||||
let planned = plan_prop(PropKind::Rotation, Some("Time Remap"), p, at, cp, col);
|
||||
col.exported.time_remaps += 1;
|
||||
let mut plan = planned.unwrap_or_else(|| PropPlan { kind: PropKind::Rotation, value: vec![0.0], keys: Vec::new(), expr: None });
|
||||
|
||||
@@ -7,8 +7,9 @@ use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Most example lines kept per loss category (the count is always exact).
|
||||
pub const MAX_DETAILS: usize = 20;
|
||||
/// 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)]
|
||||
@@ -130,15 +131,9 @@ impl LossCategory {
|
||||
}
|
||||
}
|
||||
|
||||
/// One category of things that were not exported.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Loss {
|
||||
pub category: LossCategory,
|
||||
/// How many occurrences (exact).
|
||||
pub count: usize,
|
||||
/// Up to [`MAX_DETAILS`] example lines.
|
||||
pub details: Vec<String>,
|
||||
}
|
||||
/// 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)]
|
||||
@@ -222,7 +217,7 @@ pub struct ExportReport {
|
||||
impl ExportReport {
|
||||
/// 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.
|
||||
@@ -232,12 +227,12 @@ impl ExportReport {
|
||||
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,11 +246,7 @@ pub(crate) struct Collector {
|
||||
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());
|
||||
}
|
||||
Loss::record(&mut self.losses, category, move || detail.into());
|
||||
}
|
||||
|
||||
pub fn finish(self) -> ExportReport {
|
||||
@@ -266,3 +257,56 @@ impl Collector {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -24,10 +24,12 @@ 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::tree::{R, child_data, kids_mut, list_mut, put, put_f64, put_u8, put_u16, put_u32, set_utf8, tpl};
|
||||
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;
|
||||
@@ -192,7 +194,7 @@ impl ShapeProtos {
|
||||
put_f64(child_data(&mut node, b"tdum")?, 0, lo)?;
|
||||
put_f64(child_data(&mut node, b"tduM")?, 0, hi)?;
|
||||
}
|
||||
Ok([crate::export::camlight::tdmn_chunk(name), node])
|
||||
Ok([tdmn(name), node])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,20 +269,7 @@ pub(crate) struct ShCx<'a> {
|
||||
|
||||
/// 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 mut timed: Vec<(i64, &Keyframe)> = Vec::with_capacity(p.keys.len());
|
||||
for k in &p.keys {
|
||||
let (u, inexact) = cx.cp.tb.units(k.time);
|
||||
if inexact {
|
||||
cx.col.lose(LossCategory::RoundedTimes, format!("{what}: key 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 {
|
||||
cx.col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: keys at the same time were merged"));
|
||||
}
|
||||
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);
|
||||
@@ -618,38 +607,6 @@ pub(crate) fn plan_contents(contents: &PropGroup, what: &str, depth: usize, cx:
|
||||
out
|
||||
}
|
||||
|
||||
fn tdmn_name(c: &Chunk<'_>) -> Option<String> {
|
||||
let b = c.bytes()?;
|
||||
let end = b.iter().position(|x| *x == 0).unwrap_or(b.len());
|
||||
std::str::from_utf8(b.get(..end)?).ok().map(str::to_string)
|
||||
}
|
||||
|
||||
/// A key of a point (the spatial layout of a 2D Position, 853) or a colour (854).
|
||||
fn spatial_key(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)
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
@@ -681,32 +638,17 @@ pub(crate) fn build_record(m: Chunk<'static>, mut node: Chunk<'static>, layout:
|
||||
put_u8(tdb4, 79, 0)?;
|
||||
}
|
||||
}
|
||||
let mut list = key_list.clone();
|
||||
let count = u32::try_from(v.keys.len()).map_err(|_| tpl("too many keys"))?;
|
||||
{
|
||||
let lhd3 = child_data(&mut list, b"lhd3")?;
|
||||
crate::export::synth::put_key_counts(lhd3, count, u32::try_from(size).map_err(|_| tpl("record size"))?)?;
|
||||
}
|
||||
let mut ldat = Vec::with_capacity(size * v.keys.len());
|
||||
for k in &v.keys {
|
||||
ldat.extend(match layout {
|
||||
Layout::Point => spatial_key(k, n, true, size)?,
|
||||
Layout::Color => spatial_key(k, n, false, size)?,
|
||||
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 lk = kids_mut(&mut list)?;
|
||||
match lk.iter_mut().find(|c| c.is(b"ldat")) {
|
||||
Some(c) => *c = Chunk::data(*b"ldat", ldat),
|
||||
None => lk.push(Chunk::data(*b"ldat", ldat)),
|
||||
}
|
||||
}
|
||||
let kids = kids_mut(&mut node)?;
|
||||
let at = kids.iter().position(|c| c.is(b"cdat")).ok_or_else(|| tpl("shape record without cdat"))?;
|
||||
if let Some(slot) = kids.get_mut(at) {
|
||||
*slot = list;
|
||||
}
|
||||
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).
|
||||
@@ -746,7 +688,7 @@ pub(crate) fn build_items(t: &ShapeProtos, items: &[ShItem], depth: usize) -> R<
|
||||
if depth > MAX_DEPTH {
|
||||
return Ok(out);
|
||||
}
|
||||
let pos = |kids: &[Chunk<'static>], n: &str| kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(n));
|
||||
let pos = |kids: &[Chunk<'static>], n: &str| kids.iter().position(|c| is_tdmn(c, n));
|
||||
for item in items {
|
||||
match item {
|
||||
ShItem::Off(inner) => {
|
||||
@@ -766,7 +708,7 @@ pub(crate) fn build_items(t: &ShapeProtos, items: &[ShItem], depth: usize) -> R<
|
||||
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| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Group End")).unwrap_or(ck.len());
|
||||
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"))?;
|
||||
@@ -815,13 +757,10 @@ pub(crate) fn put_contents(layr: &mut Chunk<'static>, t: &ShapeProtos, items: &[
|
||||
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| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Root Vectors Group"))
|
||||
.ok_or_else(|| tpl("shape layer without contents"))?;
|
||||
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| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Group End")).unwrap_or(rk.len());
|
||||
let end = rk.iter().position(|c| is_tdmn(c, GROUP_END)).unwrap_or(rk.len());
|
||||
rk.splice(end..end, built);
|
||||
Ok(())
|
||||
}
|
||||
@@ -4,14 +4,14 @@
|
||||
//! e1-sparse).
|
||||
|
||||
use crate::Chunk;
|
||||
use crate::export::synth::{KeyTemplate, NO_NAME, RecSpec, class, tdbs, tdmn, tdsn};
|
||||
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("ADBE Group End"));
|
||||
body.push(tdmn(GROUP_END));
|
||||
[tdmn(name), Chunk::list(*b"tdgp", body)]
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ 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("ADBE Group End"));
|
||||
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()],
|
||||
@@ -78,7 +78,7 @@ pub(crate) fn av_layer() -> Vec<Chunk<'static>> {
|
||||
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("ADBE Group End"));
|
||||
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()],
|
||||
@@ -125,7 +125,7 @@ pub(crate) fn text_layer(doc: &[u8]) -> Vec<Chunk<'static>> {
|
||||
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("ADBE Group End"));
|
||||
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()],
|
||||
@@ -141,7 +141,7 @@ pub(crate) fn pairs(nodes: &[crate::export::tree_spec::Node]) -> Vec<(String, [C
|
||||
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 = String::from_utf8_lossy(m.bytes().unwrap_or_default().split(|b| *b == 0).next().unwrap_or_default()).into_owned();
|
||||
let name = tdmn_name(&m).unwrap_or_default();
|
||||
out.push((name, [m, n]));
|
||||
}
|
||||
out
|
||||
|
||||
@@ -23,8 +23,10 @@ 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.
|
||||
@@ -128,20 +130,7 @@ fn plan_record(spec: &StyleParam, full: String, prop: &Property, cp: &CompPlan,
|
||||
/// 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 mut timed: Vec<(i64, &effectcraft_keyframe::Keyframe)> = Vec::with_capacity(prop.keys.len());
|
||||
for k in &prop.keys {
|
||||
let (u, inexact) = cp.tb.units(k.time);
|
||||
if inexact {
|
||||
col.lose(LossCategory::RoundedTimes, format!("{what}: key 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}: keys at the same time were merged"));
|
||||
}
|
||||
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 {
|
||||
@@ -279,11 +268,6 @@ pub(crate) struct StyleProtos {
|
||||
keyed: Chunk<'static>,
|
||||
}
|
||||
|
||||
fn tdmn_name(c: &Chunk<'_>) -> Option<String> {
|
||||
let d = c.bytes()?;
|
||||
Some(d.iter().take_while(|b| **b != 0).map(|b| char::from(*b)).collect())
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -322,28 +306,13 @@ impl StyleProtos {
|
||||
}
|
||||
}
|
||||
let mut list = self.keyed.child_list(b"list").cloned().ok_or_else(|| tpl("keyed style prototype without keys"))?;
|
||||
let n = u32::try_from(keys.len()).map_err(|_| tpl("too many keys"))?;
|
||||
let size = 48usize;
|
||||
{
|
||||
let lhd3 = child_data(&mut list, b"lhd3")?;
|
||||
crate::export::synth::put_key_counts(lhd3, n, 48)?;
|
||||
}
|
||||
let mut ldat = Vec::with_capacity(size * keys.len());
|
||||
for k in keys {
|
||||
ldat.extend(crate::export::emit::plain_record(1, k, size)?);
|
||||
}
|
||||
{
|
||||
let lk = kids_mut(&mut list)?;
|
||||
match lk.iter_mut().find(|c| c.is(b"ldat")) {
|
||||
Some(c) => *c = Chunk::data(*b"ldat", ldat),
|
||||
None => lk.push(Chunk::data(*b"ldat", ldat)),
|
||||
}
|
||||
}
|
||||
let kids = kids_mut(&mut rec)?;
|
||||
let at = kids.iter().position(|c| c.is(b"cdat")).ok_or_else(|| tpl("style record without cdat"))?;
|
||||
if let Some(slot) = kids.get_mut(at) {
|
||||
*slot = list;
|
||||
}
|
||||
fill_key_list(&mut list, ldat, keys.len(), size)?;
|
||||
replace_cdat(&mut rec, list)?;
|
||||
}
|
||||
}
|
||||
if let Some((text, enabled)) = &r.expr {
|
||||
@@ -362,7 +331,7 @@ impl StyleProtos {
|
||||
|
||||
/// 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| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(name)).ok_or_else(|| tpl("layer styles group incomplete"))?;
|
||||
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"))
|
||||
}
|
||||
|
||||
@@ -377,7 +346,7 @@ fn insert_records(protos: &StyleProtos, g: &mut Chunk<'static>, recs: &[Record],
|
||||
built.extend(protos.build(r)?);
|
||||
}
|
||||
let kids = kids_mut(g)?;
|
||||
let at = kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(before)).ok_or_else(|| tpl("layer styles group incomplete"))?;
|
||||
let at = kids.iter().position(|c| is_tdmn(c, before)).ok_or_else(|| tpl("layer styles group incomplete"))?;
|
||||
kids.splice(at..at, built);
|
||||
Ok(())
|
||||
}
|
||||
@@ -392,12 +361,12 @@ pub(crate) fn put_styles(protos: &StyleProtos, layr: &mut Chunk<'static>, plan:
|
||||
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, "ADBE Group End")?;
|
||||
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, "ADBE Group End")?;
|
||||
insert_records(protos, g, recs, GROUP_END)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -4,9 +4,10 @@
|
||||
//! 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.
|
||||
/// `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)) {
|
||||
@@ -15,12 +16,34 @@ pub(crate) fn tdmn(name: &str) -> Chunk<'static> {
|
||||
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> {
|
||||
Chunk { id: *b"tdsn", body: Body::Chunks(vec![Chunk::data(*b"Utf8", name.as_bytes().to_vec())]), pad: None }
|
||||
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).
|
||||
@@ -100,13 +123,13 @@ impl RecSpec {
|
||||
/// 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> {
|
||||
let mut b = vec![0u8; 124];
|
||||
let set = |b: &mut Vec<u8>, at: usize, bytes: &[u8]| {
|
||||
if let Some(dst) = b.get_mut(at..at + bytes.len()) {
|
||||
dst.copy_from_slice(bytes);
|
||||
}
|
||||
};
|
||||
set(&mut b, 0, &[0xdb, 0x99, 0x00, spec.dims]);
|
||||
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,
|
||||
@@ -115,19 +138,19 @@ pub(crate) fn tdb4(spec: &RecSpec, keyed: bool, time_scale: u32) -> Vec<u8> {
|
||||
Some(b) => (b & !0x01) | u8::from(!keyed),
|
||||
None => (if spatial == 0 { 0 } else { spatial_byte5(spatial) }) | u8::from(!keyed),
|
||||
};
|
||||
set(&mut b, 5, &[byte5]);
|
||||
set(&mut b, 7, &[spatial]);
|
||||
set(&mut b, 8, &spec.class.to_be_bytes());
|
||||
set(&mut b, 12, &time_scale.to_be_bytes());
|
||||
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).
|
||||
set(&mut b, 16, &1e-4f64.to_be_bytes());
|
||||
b.put(16, &1e-4f64.to_be_bytes());
|
||||
for at in [24, 32, 40, 48] {
|
||||
set(&mut b, at, &1.0f64.to_be_bytes());
|
||||
b.put(at, &1.0f64.to_be_bytes());
|
||||
}
|
||||
set(&mut b, 68, &[u8::from(keyed)]);
|
||||
b.put(68, &[u8::from(keyed)]);
|
||||
// Set on a static spatial property, cleared once it is keyed (aep-format.md 3.4, byte 79).
|
||||
set(&mut b, 79, &[u8::from(spatial != 0 && !keyed)]);
|
||||
b.put(79, &[u8::from(spatial != 0 && !keyed)]);
|
||||
b
|
||||
}
|
||||
|
||||
@@ -135,16 +158,21 @@ pub(crate) fn tdb4(spec: &RecSpec, keyed: bool, time_scale: u32) -> Vec<u8> {
|
||||
/// 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 mut lhd3 = vec![0u8; 52];
|
||||
// Cannot fail: the header is 52 bytes.
|
||||
let _ = crate::export::tree::put_u32(&mut lhd3, 0, 0x00d0_0bee);
|
||||
let _ = crate::export::tree::put_u32(&mut lhd3, 24, 1);
|
||||
let _ = put_key_counts(&mut lhd3, count, size);
|
||||
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) -> crate::export::tree::R<()> {
|
||||
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)
|
||||
}
|
||||
@@ -153,8 +181,7 @@ pub(crate) fn put_key_counts(lhd3: &mut [u8], count: u32, size: u32) -> crate::e
|
||||
/// 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) -> crate::export::tree::R<()> {
|
||||
use crate::export::tree::put_u32;
|
||||
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)?;
|
||||
@@ -204,6 +231,38 @@ mod tests {
|
||||
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]);
|
||||
|
||||
@@ -81,6 +81,24 @@ fn transform_records(keyed: bool) -> Vec<Chunk<'static>> {
|
||||
.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(&[]) };
|
||||
|
||||
@@ -89,6 +89,8 @@ pub(crate) struct TextPlan {
|
||||
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.
|
||||
@@ -133,16 +135,19 @@ pub(crate) fn plan_text(layer: &Layer, comp_name: &str, col: &mut Collector) ->
|
||||
if !st.keys.is_empty() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not written (the first key's text is)"));
|
||||
}
|
||||
if st.has_expression() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not written"));
|
||||
}
|
||||
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);
|
||||
Some(plan_doc(doc, &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
|
||||
@@ -190,6 +195,8 @@ fn differs(g: &PropGroup, def: Option<&PropGroup>, depth: usize) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -288,7 +295,7 @@ fn plan_doc(doc: &TextDoc, what: &str, col: &mut Collector) -> TextPlan {
|
||||
at.fit(h, (1.0, 1e6), 1.0, "box height"),
|
||||
]
|
||||
});
|
||||
TextPlan { text, runs: out_runs, paras, frame, animators: Vec::new() }
|
||||
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 {
|
||||
@@ -518,11 +525,47 @@ pub(crate) fn build_doc(proto: &TNode, tp: &TextPlan) -> Option<TNode> {
|
||||
Some(doc)
|
||||
}
|
||||
|
||||
/// Rewrites the text document of a text layer block's `Layr` for `tp` and gives the document a
|
||||
/// fresh `btgu/pgui`.
|
||||
/// 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;
|
||||
@@ -535,6 +578,7 @@ pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8
|
||||
_ => 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;
|
||||
@@ -555,6 +599,9 @@ pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ 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).
|
||||
@@ -88,6 +89,7 @@ const PROPS: &[(&str, &str, Conv, Layout)] = &[
|
||||
("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),
|
||||
@@ -219,14 +221,8 @@ fn plan_selector(s: &PropGroup, animator: &str, cx: &mut ShCx<'_>) -> SelPlan {
|
||||
SelPlan { name: crate::export::plan::cut_name(&s.name, 255, &here, cx.col), records, advanced }
|
||||
}
|
||||
|
||||
fn tdmn_name(c: &Chunk<'_>) -> Option<String> {
|
||||
let b = c.bytes()?;
|
||||
let end = b.iter().position(|x| *x == 0).unwrap_or(b.len());
|
||||
std::str::from_utf8(b.get(..end)?).ok().map(str::to_string)
|
||||
}
|
||||
|
||||
fn pos(kids: &[Chunk<'static>], n: &str) -> Option<usize> {
|
||||
kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(n))
|
||||
kids.iter().position(|c| is_tdmn(c, n))
|
||||
}
|
||||
|
||||
/// The item's user name (`tdsn/Utf8`).
|
||||
@@ -296,7 +292,7 @@ pub(crate) fn put_animators(layr: &mut Chunk<'static>, t: &AnimProtos, anims: &[
|
||||
}
|
||||
{
|
||||
let gk = kids_mut(&mut group)?;
|
||||
let end = pos(gk, "ADBE Group End").unwrap_or(gk.len());
|
||||
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.
|
||||
@@ -305,7 +301,7 @@ pub(crate) fn put_animators(layr: &mut Chunk<'static>, t: &AnimProtos, anims: &[
|
||||
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, "ADBE Group End").unwrap_or(tk.len());
|
||||
let end = pos(tk, GROUP_END).unwrap_or(tk.len());
|
||||
tk.splice(end..end, [gm, group]);
|
||||
Ok(())
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
//! `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
|
||||
@@ -27,10 +28,7 @@ pub(crate) fn fixed_rate(rate: FrameRate) -> u32 {
|
||||
/// 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> {
|
||||
[(FrameRate::FPS_23_976, 23.976f32), (FrameRate::FPS_29_97, 29.97), (FrameRate::FPS_59_94, 59.94), (FrameRate::FPS_119_88, 119.88)]
|
||||
.into_iter()
|
||||
.find(|(r, _)| *r == rate)
|
||||
.map(|(_, v)| v)
|
||||
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
|
||||
|
||||
@@ -40,6 +40,7 @@ pub(crate) fn child_data<'a>(c: &'a mut Chunk<'static>, id: &[u8; 4]) -> R<&'a m
|
||||
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"))?;
|
||||
@@ -90,20 +91,161 @@ pub(crate) fn put_cstr(d: &mut [u8], at: usize, len: usize, text: &str) -> R<()>
|
||||
break;
|
||||
}
|
||||
let mut buf = [0u8; 4];
|
||||
let enc = ch.encode_utf8(&mut buf);
|
||||
for (i, b) in enc.as_bytes().iter().enumerate() {
|
||||
if let Some(slot) = dst.get_mut(n + i) {
|
||||
*slot = *b;
|
||||
}
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -264,6 +264,8 @@ pub(crate) static TEXT_ANIMATOR_RECORDS: &[Node] = &[
|
||||
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 }),
|
||||
|
||||
+152
-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
|
||||
@@ -30,6 +31,7 @@ mod effects;
|
||||
mod lumetri;
|
||||
mod markers;
|
||||
mod masks;
|
||||
mod placeholder;
|
||||
mod props;
|
||||
mod puppet;
|
||||
mod report;
|
||||
@@ -42,6 +44,9 @@ 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::{AeVersionInfo, ImportReport, Imported, LIMITATIONS, Loss, LossCategory, MAX_DETAILS, TESTED_MAJORS, UNKNOWN};
|
||||
|
||||
@@ -115,17 +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(&file);
|
||||
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);
|
||||
@@ -157,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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
@@ -216,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)) {
|
||||
@@ -285,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,
|
||||
@@ -295,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).
|
||||
@@ -327,6 +342,42 @@ 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> {
|
||||
@@ -453,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)
|
||||
}
|
||||
@@ -582,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);
|
||||
}
|
||||
@@ -654,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) => {
|
||||
@@ -667,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);
|
||||
}
|
||||
|
||||
@@ -906,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);
|
||||
|
||||
@@ -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,7 +35,7 @@
|
||||
//! import. Hue/Saturation's master values and Levels' values are arbitrary data, decoded by the
|
||||
//! reader (444-446, 512-516).
|
||||
|
||||
use crate::effect_map::{CRYPTOMATTE_OUTPUT, Conv, EFFECTS, EffectMap, Extra, HUE_SATURATION_MASTER, LEVELS_RGB, ParamMap, popup_key};
|
||||
use crate::effect_map::{CRYPTOMATTE_OUTPUT, Conv, EFFECTS, EffectMap, Extra, HUE_SATURATION_MASTER, LEVELS_RGB, ParamMap, popup_alias, popup_key};
|
||||
use crate::{
|
||||
CryptomatteData, CurvesData, DefinitionSource, Effect as AepEffect, EffectDefinitions, EffectParam, ExtractorChannels, HueSaturationData,
|
||||
Layer as AepLayer, LayerRef, LevelsData, MeshData, ParamKind, ParamValue,
|
||||
@@ -82,44 +83,37 @@ pub(crate) fn import_effects<'f, 'a>(
|
||||
continue;
|
||||
}
|
||||
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;
|
||||
};
|
||||
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 {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{}: '{}' has the effect '{shown}' ({}) without readable parameter definitions, not imported", cx.comp, cx.layer, fx.match_name()),
|
||||
);
|
||||
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;
|
||||
}
|
||||
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)),
|
||||
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);
|
||||
// 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.
|
||||
if params.first().is_some_and(|p| p.borrowed_definition) {
|
||||
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()
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
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 {
|
||||
@@ -134,6 +128,29 @@ pub(crate) fn import_effects<'f, 'a>(
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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)
|
||||
@@ -242,23 +259,12 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
|
||||
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`).
|
||||
@@ -364,7 +370,7 @@ fn report_beyond_limit<'v>(limit: Option<(f64, f64)>, values: impl Iterator<Item
|
||||
/// 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
|
||||
@@ -413,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;
|
||||
@@ -425,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(),
|
||||
)
|
||||
@@ -517,7 +528,7 @@ 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::Extractor => match ExtractorChannels::parse(data).map(|c| (c.sources(), c)) {
|
||||
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
|
||||
@@ -799,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(),
|
||||
|
||||
@@ -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")),
|
||||
}
|
||||
}
|
||||
|
||||
+218
-14
@@ -8,6 +8,7 @@ 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;
|
||||
@@ -56,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,
|
||||
@@ -92,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.
|
||||
@@ -156,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,
|
||||
@@ -218,6 +257,11 @@ 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()),
|
||||
@@ -243,7 +287,7 @@ impl AeVersionInfo {
|
||||
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.
|
||||
@@ -253,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,19 +313,63 @@ 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(),
|
||||
@@ -301,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};
|
||||
|
||||
@@ -22,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,
|
||||
|
||||
@@ -18,11 +18,11 @@
|
||||
//! options of extruded shapes.
|
||||
|
||||
use crate::{Layer as AepLayer, PropGroup as AepGroup, PropNode, Property as AepProp, ShapePath as AepPath};
|
||||
use effectcraft_keyframe::Gradient;
|
||||
use effectcraft_keyframe::{Gradient, ShapePath};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{Node, PropGroup};
|
||||
|
||||
use crate::import::masks::{import_path_keys, to_path};
|
||||
use crate::import::masks::{NO_VERTICES, import_path_keys, to_path};
|
||||
use crate::import::props::{Kind, import_expression, import_keys};
|
||||
use crate::import::report::{Collector, LossCategory};
|
||||
use crate::import::time::TimeMap;
|
||||
@@ -394,21 +394,26 @@ fn path(g: &AepGroup<'_, '_>, cx: &mut Cx<'_, '_>) -> Option<PropGroup> {
|
||||
return None;
|
||||
};
|
||||
let shapes: Vec<Option<AepPath>> =
|
||||
oms.child_list(b"omks").map(|k| k.children().iter().filter(|c| c.is_list(b"shap")).map(AepPath::from_chunk).collect()).unwrap_or_default();
|
||||
oms.child_list(b"omks").map(|k| k.children().filter(|c| c.is_list(b"shap")).map(AepPath::from_chunk).collect()).unwrap_or_default();
|
||||
let first = match shapes.first() {
|
||||
Some(Some(s)) => to_path(s, (1, 1)),
|
||||
Some(None) => Err("its path is unreadable"),
|
||||
None => Err("it has no path"),
|
||||
};
|
||||
let node = oms.child_list(b"tdbs").and_then(AepProp::from_chunk);
|
||||
// A static path an expression draws (a text-box rig writes its outline from the text's size):
|
||||
// After Effects stores it empty. The expression is the path, so it is kept, on an empty value.
|
||||
let drawn_by_expression = node.as_ref().is_some_and(|n| n.expression().is_some() && !n.is_animated());
|
||||
let first = match first {
|
||||
Ok(p) => p,
|
||||
Err(why) if why == NO_VERTICES && drawn_by_expression => ShapePath::default(),
|
||||
Err(why) => {
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{}: a shape path not imported, {why}", cx.what));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let mut p = build::shape_path(cx.ids, first);
|
||||
if let (Some(node), Some(prop)) = (oms.child_list(b"tdbs").and_then(AepProp::from_chunk), p.get_mut("path")) {
|
||||
if let (Some(node), Some(prop)) = (node, p.get_mut("path")) {
|
||||
if node.is_animated() {
|
||||
import_path_keys(&shapes, &node, cx.what, (1, 1), cx.tm, prop, cx.col);
|
||||
}
|
||||
@@ -457,18 +462,22 @@ fn shift_copy_offset(p: &mut effectcraft_project::Property, cx: &mut Cx<'_, '_>)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports a property whose only sampled value is the default 1.
|
||||
/// Reports a property whose only sampled value is the default 1. A record in the default state
|
||||
/// holds After Effects' default (docs/aep-format.md 3.4, state), so it holds nothing to lose.
|
||||
fn not_default(g: &AepGroup<'_, '_>, match_name: &str, what: &str, cx: &mut Cx<'_, '_>) {
|
||||
if let Some(PropNode::Property(p)) = g.get(match_name)
|
||||
&& stored(&p)
|
||||
&& (p.is_animated() || p.expression().is_some() || p.static_value().and_then(|v| v.first().copied()).is_some_and(|v| v != 1.0))
|
||||
{
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{}: {what} not imported", cx.what));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports a property whose only sampled value is 0.
|
||||
/// Reports a property whose only sampled value is 0 (a record in the default state, as above,
|
||||
/// holds nothing to lose).
|
||||
fn not_zero(g: &AepGroup<'_, '_>, match_name: &str, what: &str, cx: &mut Cx<'_, '_>) {
|
||||
if let Some(PropNode::Property(p)) = g.get(match_name)
|
||||
&& stored(&p)
|
||||
&& (p.is_animated() || p.expression().is_some() || p.static_value().and_then(|v| v.first().copied()).is_some_and(|v| v != 0.0))
|
||||
{
|
||||
cx.col.lose(LossCategory::ShapeLayers, format!("{}: {what} not imported", cx.what));
|
||||
@@ -490,3 +499,41 @@ fn unknown(g: &AepGroup<'_, '_>, known: &[&str], what: &str, cx: &mut Cx<'_, '_>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Chunk;
|
||||
|
||||
/// A group holding `match_name` as a one-component property in state `tdsb` with value `v`.
|
||||
fn group_with(match_name: &str, tdsb: u32, v: f64) -> Chunk<'static> {
|
||||
let mut name = match_name.as_bytes().to_vec();
|
||||
name.resize(40, 0);
|
||||
let mut tdb4 = vec![0u8; 124];
|
||||
tdb4[3] = 1;
|
||||
let tdbs = Chunk::list(
|
||||
*b"tdbs",
|
||||
vec![Chunk::data(*b"tdsb", tdsb.to_be_bytes().to_vec()), Chunk::data(*b"tdb4", tdb4), Chunk::data(*b"cdat", v.to_be_bytes().to_vec())],
|
||||
);
|
||||
Chunk::list(*b"tdgp", vec![Chunk::data(*b"tdmn", name), tdbs])
|
||||
}
|
||||
|
||||
fn reported(match_name: &str, tdsb: u32, v: f64, check: fn(&AepGroup<'_, '_>, &str, &str, &mut Cx<'_, '_>)) -> usize {
|
||||
let chunk = group_with(match_name, tdsb, v);
|
||||
let g = AepGroup::from_chunk(&chunk).unwrap();
|
||||
let tm = TimeMap { timescale: 30, frame_duration: 1, rate: crate::import::time::frame_rate(30, 1).unwrap() };
|
||||
let (mut next, mut col) = (1, Collector::default());
|
||||
check(&g, match_name, "it", &mut Cx { what: "L", tm: &tm, ids: &mut Ids(&mut next), col: &mut col });
|
||||
col.finish().losses.iter().map(|l| l.count).sum()
|
||||
}
|
||||
|
||||
/// #3087: a guide rectangle's Shape Direction recorded in the default state (`tdsb` 3, holding
|
||||
/// 2) is After Effects' default and is no loss; written (`tdsb` 1) with 2, it is one.
|
||||
#[test]
|
||||
fn a_default_state_record_is_no_loss() {
|
||||
assert_eq!(reported("ADBE Vector Shape Direction", 3, 2.0, not_default), 0);
|
||||
assert_eq!(reported("ADBE Vector Shape Direction", 1, 2.0, not_default), 1);
|
||||
assert_eq!(reported("ADBE Vector Grad HiLite Length", 3, 5.0, not_zero), 0);
|
||||
assert_eq!(reported("ADBE Vector Grad HiLite Length", 1, 5.0, not_zero), 1);
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,9 @@
|
||||
|
||||
use crate::{AutoKern, Caps, FontBaseline, Justification, Layer as AepLayer, ParagraphRun, PropGroup, PropNode, StyleRun as AepRun, TextDocument};
|
||||
use effectcraft_keyframe::text_doc::{BaselineOption, CharStyle, Composer, Direction, Justify, Kerning, ParaStyle, StyleRun, TextDoc};
|
||||
use effectcraft_project::Property;
|
||||
|
||||
use crate::import::props::import_expression;
|
||||
use crate::import::report::{Collector, LossCategory};
|
||||
|
||||
/// How deep the walk over the text property groups goes.
|
||||
@@ -344,15 +346,27 @@ fn has_stored(g: &PropGroup<'_, '_>, depth: usize) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// The Source Text expression into `target` (the layer's `text/sourceText`). The Source Text
|
||||
/// record keeps it like any other property: the text in its `Utf8`, the flags in its `tdb4`
|
||||
/// (`tests/fixtures/text-synthetic.aep`). An expression whose flags are unreadable, or a layer
|
||||
/// without a Source Text property, is reported.
|
||||
pub(crate) fn import_source_text_expression(layer: &AepLayer<'_, '_>, target: Option<&mut Property>, what: &str, col: &mut Collector) {
|
||||
let Some(st) = layer.source_text_property() else { return };
|
||||
if st.expression().is_none() {
|
||||
return;
|
||||
}
|
||||
match target {
|
||||
Some(p) if st.expression_enabled().is_some() => import_expression(&st, p, col),
|
||||
_ => col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not imported")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of a text layer besides its first text document that are not imported.
|
||||
pub(crate) fn report_text_extras(layer: &AepLayer<'_, '_>, what: &str, col: &mut Collector) {
|
||||
if let Some(st) = layer.source_text_property() {
|
||||
if st.is_animated() || layer.text_document_count() > 1 {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not imported (the first text document is)"));
|
||||
}
|
||||
if st.expression().is_some() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not imported"));
|
||||
}
|
||||
if let Some(st) = layer.source_text_property()
|
||||
&& (st.is_animated() || layer.text_document_count() > 1)
|
||||
{
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not imported (the first text document is)"));
|
||||
}
|
||||
let Some(PropNode::Group(text)) = layer.properties().and_then(|p| p.get("ADBE Text Properties")) else { return };
|
||||
for e in text.entries() {
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
//!
|
||||
//! Not imported, and reported in [`LossCategory::TextLayers`]: wiggly and expression selectors,
|
||||
//! animator properties other than the ones mapped below (Character Value, Fill / Stroke
|
||||
//! Hue, Saturation, Brightness and Opacity, 3D rotations, variable font axes, ...), and a Tracking
|
||||
//! Type other than the default.
|
||||
//! Hue, Saturation and Brightness, Fill Opacity, 3D rotations, variable font axes, ...), and a
|
||||
//! Tracking Type other than the default.
|
||||
|
||||
use crate::{PropGroup as AepGroup, PropNode, Property as AepProp};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
@@ -37,6 +37,7 @@ const PROPS: &[(&str, &str, &str, Kind)] = &[
|
||||
("ADBE Text Opacity", "opacity", "opacity", Kind::Number),
|
||||
("ADBE Text Fill Color", "fillColor", "fillColor", Kind::EffectColor),
|
||||
("ADBE Text Stroke Color", "strokeColor", "strokeColor", Kind::EffectColor),
|
||||
("ADBE Text Stroke Opacity", "strokeOpacity", "strokeOpacity", Kind::Number),
|
||||
("ADBE Text Stroke Width", "strokeWidth", "strokeWidth", Kind::Number),
|
||||
("ADBE Text Tracking Amount", "tracking", "tracking", Kind::Number),
|
||||
("ADBE Text Line Spacing", "lineSpacing", "lineSpacing", Kind::Vec2),
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! stay frames at every rate (29.97 fps is `23976 / 800` in the file and `30000 / 1001` in the
|
||||
//! project). Any other time is rounded to the nearest tick.
|
||||
|
||||
use crate::container::TimeBase as ContainerTimeBase;
|
||||
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
|
||||
|
||||
/// The composition's frame structure: the stored time base and the rate the project gets.
|
||||
@@ -27,7 +28,8 @@ pub(crate) fn frame_rate(timescale: u32, frame_duration: u32) -> Option<FrameRat
|
||||
}
|
||||
let exact = FrameRate::new(i64::from(timescale), i64::from(frame_duration));
|
||||
let fps = exact.as_f64();
|
||||
for ntsc in [FrameRate::FPS_23_976, FrameRate::FPS_29_97, FrameRate::FPS_59_94, FrameRate::FPS_119_88] {
|
||||
for ((num, den), _) in ContainerTimeBase::NTSC {
|
||||
let ntsc = FrameRate::new(i64::from(num), i64::from(den));
|
||||
if (ntsc.as_f64() - fps).abs() < 0.0005 {
|
||||
return Some(ntsc);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! export back to `.aep`, in one crate (like `effectcraft-lottie`).
|
||||
//!
|
||||
//! - [`container`]: the RIFX `Egg!` chunk tree (lossless, byte-identical round trip) and its typed,
|
||||
//! read-only view. Its API is re-exported at the crate root.
|
||||
//! read-only view, from `craft-aep`, re-exported at the crate root, plus the effect and
|
||||
//! layer-style tables that map them onto EffectCraft's.
|
||||
//! - [`import`]: maps the typed view into an EffectCraft project and reports what it drops.
|
||||
//! - [`export`]: writes an EffectCraft project as an `.aep`, every chunk built in code.
|
||||
//!
|
||||
@@ -20,8 +21,8 @@ pub use container::{
|
||||
GradientType, HueSaturationData, Interpolation, Item, ItemKind, Justification, KernRun, KeyEase, KeyLayout, KeyList, Keyframe, KeyframeKind, LIST, Layer,
|
||||
LayerHeader, LayerRef, LayerType, LevelsData, LightType, Limits, ListHeader, Marker, Mask, MaskAtom, MaskMode, MatteMode, MeshData, NESTED_IDS,
|
||||
Orientation, OrientationKey, ParagraphRun, ParamKind, ParamValue, PathVertex, PolystarType, Project, ProjectSettings, PropEntry, PropGroup, PropNode,
|
||||
Property, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin, StyleRun,
|
||||
TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk, WorkingSpace,
|
||||
curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx, read_aepx_with_limits, style_map,
|
||||
write, write_to,
|
||||
Property, PsdLayer, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin,
|
||||
StyleRun, TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk,
|
||||
WorkingSpace, curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx,
|
||||
read_aepx_with_limits, style_map, write, write_to,
|
||||
};
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
asset: ai-mask-3099.aep
|
||||
title: Small After Effects test project: placed .ai files with masks under two parented Nulls (#3099)
|
||||
author: EffectCraft contributors
|
||||
source: original work (made in After Effects 2026 from own data: four hand-written one-page PDFs named .ai, generated by tools/ai-mask-3099.py, imported and laid out by tools/ai-mask-3099.jsx)
|
||||
license: MIT OR Apache-2.0
|
||||
added: 2026-11-08 by EffectCraft contributors
|
||||
notes: Scrubbed with tools/scrub.py (footage paths C:\fixture\x\<name>.ai of the same length, host name HOST000, the XMP packet of an empty project of the contributor); its four embedded colour profiles replaced by stubs (description only, no colour data) with crates/aep/examples/stubicc.rs, then checked with the corpus repository's tools/aep/inspect-embedded.py (CLEAN). No Adobe asset is in it.
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
asset: text-synthetic.aep
|
||||
title: Small After Effects test project for the .aep importer's text animator and Source Text expression tests
|
||||
author: EffectCraft contributors
|
||||
source: original work (made in After Effects 2026 by script from own data: a composition with two text layers, a text animator Stroke Opacity, static and keyed, and Source Text expressions, enabled and disabled)
|
||||
license: MIT OR Apache-2.0
|
||||
added: 2026-11-08 by EffectCraft contributors
|
||||
notes: The working space was set to None, so the file embeds no ICC profile; nothing After Effects wrote was changed. See crates/aep/README.md (Clean room).
|
||||
+2
-1
@@ -29,6 +29,7 @@ single-case files some cases are merged from, and the contributor's own animatio
|
||||
| `scrub.py` | fixture hygiene of a saved `.aep`: footage alias paths replaced by neutral ones of the same length (`C:\fixtures\...`), host name `HOST000...`, neutral ascend counts, the XMP packet replaced by the base project's |
|
||||
| `layers-comps-scrub-aepx.py` | the same XMP swap for the `.aepx` of the pair |
|
||||
| `patch-text.py` | the byte edits of the text cases 732 and 733 (see below) |
|
||||
| `ai-mask-3099.py`, `ai-mask-3099.jsx` | the committed `../ai-mask-3099.aep` (#3099): the `.py` writes four one-page PDFs named `.ai` with distinct page boxes, the `.jsx` (ExtendScript, run once through an After Effects MCP server's script call in an empty untitled project) imports them, builds composition `ai-mask` and returns After Effects' read-back that `../../it/import/ai_mask.rs` compares against |
|
||||
|
||||
## Run order (per file)
|
||||
|
||||
@@ -53,7 +54,7 @@ single-case files some cases are merged from, and the contributor's own animatio
|
||||
5. Scrub: `python -I scrub.py <saved>.aep <fixture>.aep <base project>.aep` (and
|
||||
`layers-comps-scrub-aepx.py` for the `.aepx`). Set `SCRUB_FORBID` to the local folder and
|
||||
machine names that must not remain; the script fails if one does.
|
||||
6. Strip the colour profiles: `cargo run -p effectcraft-aep --example stubicc -- <fixture>.aep <fixture>.aep.new`
|
||||
6. Strip the colour profiles: `cargo run -p craft-aep --example stubicc -- <fixture>.aep <fixture>.aep.new` (in craft-libs)
|
||||
(and the `.aepx`) replaces the working-space profile (and the profile of imported images) by a
|
||||
stub with the same description and no colour data. It stops without writing if a profile cannot
|
||||
be replaced. Then scan the final files independently (the corpus repository's
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Issue 3099: how After Effects sizes a placed .ai (PDF) and where masks / parented layers land.
|
||||
// Generates ai-mask-3099.aep: run `python -I ai-mask-3099.py <work>` first, set `dir` to that
|
||||
// folder, then run this script (ExtendScript) in an empty, untitled project. It returns After
|
||||
// Effects' read-back (footage sizes, transforms, mask vertices, toComp points; the tests compare
|
||||
// against it) and saves <work>/i3099-ai-mask.aep, which is then scrubbed (README: steps 5 and 6).
|
||||
(function () {
|
||||
var dir = "<work>/";
|
||||
var out = {};
|
||||
if (app.project.file !== null || app.project.numItems !== 0) {
|
||||
return "ABORT: project not empty/untitled (" + app.project.numItems + " items)";
|
||||
}
|
||||
var target = new File(dir + "i3099-ai-mask.aep");
|
||||
if (target.exists) { return "ABORT: target exists"; }
|
||||
var names = ["i3099-a-boxes.ai", "i3099-b-frac.ai", "i3099-c-rot.ai", "i3099-d-trim.ai"];
|
||||
var items = {};
|
||||
out.footage = {};
|
||||
for (var i = 0; i < names.length; i++) {
|
||||
var io = new ImportOptions(new File(dir + names[i]));
|
||||
io.importAs = ImportAsType.FOOTAGE;
|
||||
var it = app.project.importFile(io);
|
||||
items[names[i]] = it;
|
||||
out.footage[names[i]] = { w: it.width, h: it.height, par: it.pixelAspect };
|
||||
}
|
||||
var comp = app.project.items.addComp("ai-mask", 1920, 1080, 1, 5, 25);
|
||||
var art = comp.layers.add(items["i3099-a-boxes.ai"]);
|
||||
art.name = "art";
|
||||
var artD = comp.layers.add(items["i3099-d-trim.ai"]);
|
||||
artD.name = "artD";
|
||||
artD.collapseTransformation = true;
|
||||
var artC = comp.layers.add(items["i3099-c-rot.ai"]);
|
||||
artC.name = "artC";
|
||||
artC.property("ADBE Transform Group").property("ADBE Position").setValue([1500, 800]);
|
||||
var n1 = comp.layers.addNull(); n1.name = "N1";
|
||||
var n2 = comp.layers.addNull(); n2.name = "N2";
|
||||
n2.setParentWithJump(n1);
|
||||
art.setParentWithJump(n2);
|
||||
artD.setParentWithJump(n2);
|
||||
var t = function (l, p, v) { l.property("ADBE Transform Group").property(p).setValue(v); };
|
||||
t(n1, "ADBE Position", [700, 400]);
|
||||
t(n1, "ADBE Rotate Z", 15);
|
||||
t(n1, "ADBE Scale", [80, 120]);
|
||||
t(n2, "ADBE Anchor Point", [10, 20]);
|
||||
t(n2, "ADBE Position", [50, -30]);
|
||||
t(n2, "ADBE Scale", [150, 150]);
|
||||
t(art, "ADBE Position", [0, 0]);
|
||||
t(artD, "ADBE Position", [300, 250]);
|
||||
// Two rectangular masks on each art layer, in layer pixels.
|
||||
var rect = function (l, nm, x0, y0, x1, y1) {
|
||||
var m = l.property("ADBE Mask Parade").addProperty("ADBE Mask Atom");
|
||||
m.name = nm;
|
||||
var s = new Shape();
|
||||
s.vertices = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
|
||||
s.closed = true;
|
||||
m.property("ADBE Mask Shape").setValue(s);
|
||||
};
|
||||
rect(art, "M1", 40, 30, 200, 90);
|
||||
rect(art, "M2", 220, 100, 350, 160);
|
||||
rect(artD, "M1", 40, 30, 200, 90);
|
||||
rect(artD, "M2", 220, 100, 350, 160);
|
||||
// World positions of layer points through the parent chain (toComp), read via a Point Control.
|
||||
var probe = n1.property("ADBE Effect Parade").addProperty("ADBE Point Control");
|
||||
var pt = probe.property(1);
|
||||
var toComp = function (ln, p) {
|
||||
pt.expression = "thisComp.layer('" + ln + "').toComp([" + p[0] + "," + p[1] + "])";
|
||||
var v = pt.valueAtTime(0, false);
|
||||
return [v[0], v[1]];
|
||||
};
|
||||
var rd = function (l) {
|
||||
var tg = l.property("ADBE Transform Group");
|
||||
var r = {
|
||||
w: l.width, h: l.height,
|
||||
anchor: tg.property("ADBE Anchor Point").value,
|
||||
position: tg.property("ADBE Position").value,
|
||||
scale: tg.property("ADBE Scale").value,
|
||||
rot: tg.property("ADBE Rotate Z").value,
|
||||
masks: []
|
||||
};
|
||||
var mp = l.property("ADBE Mask Parade");
|
||||
for (var k = 1; k <= mp.numProperties; k++) {
|
||||
r.masks.push(mp.property(k).property("ADBE Mask Shape").value.vertices);
|
||||
}
|
||||
return r;
|
||||
};
|
||||
out.layers = { art: rd(art), artD: rd(artD), artC: rd(artC), N1: rd(n1), N2: rd(n2) };
|
||||
out.world = {};
|
||||
var pts = { tl: [0, 0], tr: [art.width, 0], bl: [0, art.height], m1: [40, 30], m2: [350, 160] };
|
||||
for (var key in pts) { out.world["art_" + key] = toComp("art", pts[key]); }
|
||||
var ptsD = { tl: [0, 0], tr: [artD.width, 0], bl: [0, artD.height], m1: [40, 30] };
|
||||
for (var key2 in ptsD) { out.world["artD_" + key2] = toComp("artD", ptsD[key2]); }
|
||||
probe.remove();
|
||||
app.project.save(target);
|
||||
out.saved = target.fsName;
|
||||
return out;
|
||||
})();
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
"""Writes hand-made one-page PDFs named .ai with distinct page boxes (issue 3099 repro)."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
out = sys.argv[1]
|
||||
os.makedirs(out, exist_ok=True)
|
||||
|
||||
|
||||
def pdf(page_extra, content):
|
||||
objs = [
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
b"<< /Type /Page /Parent 2 0 R " + page_extra.encode() + b" /Contents 4 0 R >>",
|
||||
b"<< /Length " + str(len(content)).encode() + b" >>\nstream\n" + content + b"\nendstream",
|
||||
]
|
||||
data = b"%PDF-1.4\n"
|
||||
offs = []
|
||||
for i, o in enumerate(objs, 1):
|
||||
offs.append(len(data))
|
||||
data += str(i).encode() + b" 0 obj\n" + o + b"\nendobj\n"
|
||||
x = len(data)
|
||||
data += b"xref\n0 " + str(len(objs) + 1).encode() + b"\n0000000000 65535 f \n"
|
||||
for o in offs:
|
||||
data += b"%010d 00000 n \n" % o
|
||||
data += b"trailer\n<< /Size " + str(len(objs) + 1).encode() + b" /Root 1 0 R >>\nstartxref\n" + str(x).encode() + b"\n%%EOF\n"
|
||||
return data
|
||||
|
||||
|
||||
def boxes_content(boxes):
|
||||
# One outline per box (different colours) plus a filled marker at the media box origin corner.
|
||||
cols = ["0 0 0", "1 0 0", "0 0.6 0", "0 0 1", "1 0.5 0"]
|
||||
s = b"0.85 0.85 0.85 rg "
|
||||
x0, y0, x1, y1 = boxes[0]
|
||||
s += b"%g %g %g %g re f\n" % (x0, y0, x1 - x0, y1 - y0)
|
||||
for c, (a, b, cc, d) in zip(cols, boxes):
|
||||
s += c.encode() + b" RG 1 w %g %g %g %g re S\n" % (a + 0.5, b + 0.5, cc - a - 1, d - b - 1)
|
||||
# A solid square in the lower-left of the last (innermost) box: shows y orientation.
|
||||
a, b, _, _ = boxes[-1]
|
||||
s += b"0.2 0.2 0.8 rg %g %g 20 10 re f" % (a + 4, b + 4)
|
||||
return s
|
||||
|
||||
|
||||
def arr(b):
|
||||
return "[%s]" % " ".join("%g" % v for v in b)
|
||||
|
||||
|
||||
# A: every box distinct, nested, non-square.
|
||||
media, crop, bleed, trim, art = [0, 0, 420, 220], [5, 5, 415, 215], [10, 10, 410, 210], [20, 20, 400, 200], [60, 50, 300.6, 170.4]
|
||||
a = pdf(
|
||||
f"/MediaBox {arr(media)} /CropBox {arr(crop)} /BleedBox {arr(bleed)} /TrimBox {arr(trim)} /ArtBox {arr(art)}",
|
||||
boxes_content([media, crop, bleed, trim, art]),
|
||||
)
|
||||
# B: only a fractional media box.
|
||||
mb = [0, 0, 300.6, 120.4]
|
||||
b = pdf(f"/MediaBox {arr(mb)}", boxes_content([mb]))
|
||||
# C: media box with an offset origin and /Rotate 90.
|
||||
mc = [100, 50, 400, 150]
|
||||
c = pdf(f"/MediaBox {arr(mc)} /Rotate 90", boxes_content([mc]))
|
||||
# D: media + trim + art, no crop box (bleed around the artboard).
|
||||
md, td, ad = [0, 0, 418, 218], [9, 9, 409, 209], [40, 30, 250, 150]
|
||||
d = pdf(f"/MediaBox {arr(md)} /TrimBox {arr(td)} /BleedBox {arr(md)} /ArtBox {arr(ad)}", boxes_content([md, td, ad]))
|
||||
|
||||
for name, data in [("i3099-a-boxes.ai", a), ("i3099-b-frac.ai", b), ("i3099-c-rot.ai", c), ("i3099-d-trim.ai", d)]:
|
||||
with open(os.path.join(out, name), "wb") as f:
|
||||
f.write(data)
|
||||
print(name, len(data))
|
||||
@@ -128,6 +128,13 @@ pub fn resolve(name: &str) -> Option<PathBuf> {
|
||||
locate(name).map(|s| s.path().clone())
|
||||
}
|
||||
|
||||
/// The ids of the compositions an item uses as precomposition layers, as the file stores them:
|
||||
/// the little-endian `u32` of each `idpi` chunk (the importer does not read them; the exporter
|
||||
/// writes them).
|
||||
pub fn used_item_ids(item: &effectcraft_aep::Item<'_, '_>) -> Vec<u32> {
|
||||
item.chunk().children().filter(|c| c.is(b"idpi")).filter_map(|c| Some(u32::from_le_bytes(c.bytes()?.get(..4)?.try_into().ok()?))).collect()
|
||||
}
|
||||
|
||||
/// The bytes of a case (see the module comment), or `None` when it is missing.
|
||||
pub fn try_fixture(name: &str) -> Option<Vec<u8>> {
|
||||
match locate(name)? {
|
||||
|
||||
@@ -1,29 +1,2 @@
|
||||
//! container tests of effectcraft-aep.
|
||||
|
||||
#[macro_use]
|
||||
mod helpers;
|
||||
|
||||
mod aepx;
|
||||
mod batch3_core;
|
||||
mod batch3_objects;
|
||||
mod batch5;
|
||||
mod cases_600;
|
||||
mod ease_round2;
|
||||
mod effects;
|
||||
mod effects_batch4;
|
||||
mod effects_batch5;
|
||||
mod effects_exposure;
|
||||
mod header;
|
||||
mod keyframes;
|
||||
mod layer_switches;
|
||||
mod masks;
|
||||
mod matte;
|
||||
mod odd_cases;
|
||||
mod robustness;
|
||||
mod roundtrip;
|
||||
mod shapes;
|
||||
mod text_fields;
|
||||
mod text_markers_footage;
|
||||
mod text_style_slots;
|
||||
mod typed;
|
||||
mod values;
|
||||
//! Integration checks for the shared AEP tree exposed through EffectCraft.
|
||||
mod tree_index;
|
||||
@@ -1,174 +0,0 @@
|
||||
//! `.aepx` (the XML form) read into the chunk tree, compared with the `.aep` of the same project.
|
||||
//!
|
||||
//! The pair `aepx-pair` (cases 000, 058, 060, 110 and 124, one composition each) was saved by
|
||||
//! After Effects from the same state, the `.aepx` right after the `.aep`.
|
||||
//! The trees are identical except for two documented differences: the save counter (`head`
|
||||
//! `u32` at byte 16) is one higher in the `.aepx`, and pad bytes are not written in XML (an odd
|
||||
//! body gets a zero pad byte). The XMP packet of the fixtures is the base packet in both forms.
|
||||
|
||||
use effectcraft_aep::{AepError, AepFile, Body, Chunk, Limits, Project, is_aepx, parse, parse_any, read_aepx, read_aepx_with_limits, write};
|
||||
|
||||
/// The `.aepx` fixtures; each has the `.aep` of the same name.
|
||||
const PAIRS: &[&str] = &["aepx-pair"];
|
||||
|
||||
/// The `.aep` tree with the differences an `.aepx` of the next save has removed: the `head` save
|
||||
/// counter is taken from `other`.
|
||||
fn with_head_of(mut file: AepFile<'static>, other: &AepFile<'_>) -> AepFile<'static> {
|
||||
if let (Some(h), Some(src)) = (file.chunks.iter_mut().find(|c| c.is(b"head")), other.chunk(b"head")) {
|
||||
*h = src.clone().into_owned();
|
||||
}
|
||||
file
|
||||
}
|
||||
|
||||
/// The first difference of two chunk sequences, as a path, ignoring pad bytes.
|
||||
fn first_difference(a: &[Chunk<'_>], b: &[Chunk<'_>], path: &str) -> Option<String> {
|
||||
if a.len() != b.len() {
|
||||
return Some(format!("{path}: {} chunks against {}", a.len(), b.len()));
|
||||
}
|
||||
for (i, (x, y)) in a.iter().zip(b).enumerate() {
|
||||
let name = String::from_utf8_lossy(&x.list_type().unwrap_or(x.id)).into_owned();
|
||||
let here = format!("{path}/{i}:{name}");
|
||||
if x.id != y.id || x.list_type() != y.list_type() {
|
||||
return Some(format!("{here}: id differs"));
|
||||
}
|
||||
match (&x.body, &y.body) {
|
||||
(Body::Data(p), Body::Data(q)) | (Body::OpaqueList { data: p, .. }, Body::OpaqueList { data: q, .. }) => {
|
||||
if p != q {
|
||||
return Some(format!("{here}: body differs"));
|
||||
}
|
||||
}
|
||||
(Body::Chunks(p), Body::Chunks(q)) | (Body::List { children: p, .. }, Body::List { children: q, .. }) => {
|
||||
if let Some(d) = first_difference(p, q, &here) {
|
||||
return Some(d);
|
||||
}
|
||||
}
|
||||
_ => return Some(format!("{here}: body kind differs")),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn head_counter(file: &AepFile<'_>) -> u32 {
|
||||
let h = file.chunk(b"head").and_then(Chunk::bytes).expect("head");
|
||||
u32::from_be_bytes([h[16], h[17], h[18], h[19]])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pair_gives_the_same_chunk_tree() {
|
||||
for name in PAIRS {
|
||||
let aep = skip!(crate::common::try_file(&format!("{name}.aep")));
|
||||
let aepx = skip!(crate::common::try_file(&format!("{name}.aepx")));
|
||||
assert!(is_aepx(&aepx) && !is_aepx(&aep), "{name}");
|
||||
let bin = parse(&aep).unwrap();
|
||||
let xml = read_aepx(&aepx).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
// The save counter is the only difference in the container.
|
||||
assert_eq!(head_counter(&xml), head_counter(&bin) + 1, "{name}");
|
||||
let same = with_head_of(bin.clone().into_owned(), &xml);
|
||||
assert_eq!(first_difference(&same.chunks, &xml.chunks, ""), None, "{name}");
|
||||
assert_eq!(xml.trailer, bin.trailer, "{name}: XMP packet");
|
||||
// Even the bytes agree: written as an `.aep`, the tree is the `.aep` with the next save counter.
|
||||
assert!(write(&xml).unwrap() == write(&same).unwrap(), "{name}: written bytes differ");
|
||||
// And the content sniffer picks the right reader for both.
|
||||
assert_eq!(parse_any(&aepx).unwrap(), xml, "{name}");
|
||||
assert_eq!(parse_any(&aep).unwrap(), bin, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_typed_view_reads_the_same_values() {
|
||||
for name in PAIRS {
|
||||
let aep = skip!(crate::common::try_file(&format!("{name}.aep")));
|
||||
let aepx = skip!(crate::common::try_file(&format!("{name}.aepx")));
|
||||
let bin = parse(&aep).unwrap();
|
||||
let xml = read_aepx(&aepx).unwrap();
|
||||
let (pb, px) = (Project::new(&bin).unwrap(), Project::new(&xml).unwrap());
|
||||
let items = |p: &Project<'_, '_>| p.all_items().iter().map(|i| (i.kind(), i.display_name(), i.id())).collect::<Vec<_>>();
|
||||
assert_eq!(items(&pb), items(&px), "{name}");
|
||||
for (cb, cx) in pb.all_items().iter().filter_map(|i| i.comp()).zip(px.all_items().iter().filter_map(|i| i.comp())) {
|
||||
assert_eq!(cb.header(), cx.header(), "{name}");
|
||||
let layers = |c: &effectcraft_aep::Comp<'_, '_>| c.layers().map(|l| (l.name(), l.header(), l.transform(1920, 1080))).collect::<Vec<_>>();
|
||||
assert_eq!(layers(&cb), layers(&cx), "{name}");
|
||||
}
|
||||
}
|
||||
// Spot checks against the values the cases were made with (060's expression, 110's text).
|
||||
let aepx = skip!(crate::common::try_file("aepx-pair.aepx"));
|
||||
let xml = read_aepx(&aepx).unwrap();
|
||||
assert!(xml.walk().any(|(_, c)| c.is(b"Utf8") && c.bytes() == Some(&b"wiggle(1,10)"[..])));
|
||||
assert!(xml.walk().any(|(_, c)| c.is_list(b"btdk") && matches!(c.body, Body::OpaqueList { .. })));
|
||||
let names: Vec<_> = Project::new(&xml).unwrap().all_items().iter().filter(|i| i.comp().is_some()).filter_map(|i| i.name()).collect();
|
||||
assert_eq!(names, ["000-base", "058-key-opacity-2key", "060-expr-opacity-wiggle", "110-text-A", "124-precomp-Pre", "Pre"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_aepx_is_an_error_or_a_tree_never_a_panic() {
|
||||
let aepx = skip!(crate::common::try_file("aepx-pair.aepx"));
|
||||
// Truncation at about 160 points.
|
||||
for cut in (0..aepx.len()).step_by(aepx.len() / 160) {
|
||||
let _ = read_aepx(&aepx[..cut]);
|
||||
}
|
||||
assert!(read_aepx(&aepx[..aepx.len() / 2]).is_err());
|
||||
// Byte flips: each result is an error or a tree that writes and reads back.
|
||||
let mut state = 0x2545_f491_u32;
|
||||
for _ in 0..400 {
|
||||
let mut damaged = aepx.clone();
|
||||
for _ in 0..4 {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
let at = state as usize % damaged.len();
|
||||
damaged[at] ^= 1 << (state % 8);
|
||||
}
|
||||
if let Ok(file) = read_aepx(&damaged) {
|
||||
let bytes = write(&file).unwrap();
|
||||
let _ = Project::new(&parse(&bytes).unwrap()).map(|p| p.all_items().len());
|
||||
}
|
||||
}
|
||||
// Invalid hex and a damaged entity are errors.
|
||||
let text = String::from_utf8(aepx.clone()).unwrap();
|
||||
let odd = text.replacen("bdata=\"00", "bdata=\"0", 1);
|
||||
assert!(matches!(read_aepx(odd.as_bytes()), Err(AepError::Xml { .. })));
|
||||
let nonhex = text.replacen("bdata=\"00", "bdata=\"0g", 1);
|
||||
assert!(matches!(read_aepx(nonhex.as_bytes()), Err(AepError::Xml { .. })));
|
||||
// Deep nesting is refused at the limit; many elements are bounded.
|
||||
let deep = format!("<AfterEffectsProject>{}</AfterEffectsProject>", "<Fold>".repeat(1_000_000));
|
||||
assert_eq!(read_aepx(deep.as_bytes()), Err(AepError::TooDeep));
|
||||
assert_eq!(read_aepx_with_limits(&aepx, Limits { max_depth: 64, max_chunks: 100 }), Err(AepError::TooManyChunks));
|
||||
assert_eq!(read_aepx_with_limits(&aepx, Limits { max_depth: 3, max_chunks: 10_000_000 }), Err(AepError::TooDeep));
|
||||
// A huge hex body is bounded by the input: nothing is allocated from a declared size.
|
||||
let huge = format!("<AfterEffectsProject><cdat bdata=\"{}\"/></AfterEffectsProject>", "ab".repeat(1 << 20));
|
||||
assert_eq!(read_aepx(huge.as_bytes()).unwrap().chunks[0].bytes().map(<[u8]>::len), Some(1 << 20));
|
||||
}
|
||||
|
||||
/// Every pair of the local corpus (not in the repository): `AEP_CORPUS=<folder> cargo test
|
||||
/// --release -p effectcraft-aep --test it container::aepx:: -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "needs the local corpus (AEP_CORPUS)"]
|
||||
fn every_corpus_pair_gives_the_same_chunk_tree() {
|
||||
let Ok(dir) = std::env::var("AEP_CORPUS") else { return };
|
||||
let mut names: Vec<_> =
|
||||
std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aepx")).collect();
|
||||
names.sort();
|
||||
let (mut same, mut differ) = (0, Vec::new());
|
||||
for x in &names {
|
||||
let aepx = std::fs::read(x).unwrap();
|
||||
let aep = std::fs::read(x.with_extension("aep")).unwrap();
|
||||
let bin = parse(&aep).unwrap();
|
||||
let xml = match read_aepx(&aepx) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
differ.push(format!("{}: {e}", x.display()));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let fixed = with_head_of(bin.clone().into_owned(), &xml);
|
||||
match first_difference(&fixed.chunks, &xml.chunks, "") {
|
||||
None if write(&xml).unwrap() == write(&AepFile { trailer: xml.trailer.clone(), ..fixed }).unwrap() => same += 1,
|
||||
None => differ.push(format!("{}: bytes differ", x.display())),
|
||||
Some(d) => differ.push(format!("{}: {d}", x.display())),
|
||||
}
|
||||
}
|
||||
println!("{same} of {} pairs give the same chunk tree", names.len());
|
||||
for d in &differ {
|
||||
println!("{d}");
|
||||
}
|
||||
}
|
||||
@@ -1,383 +0,0 @@
|
||||
//! Batch 3 (core): explicit defaults, multi-component bezier ease, colour key distance, exact time
|
||||
//! stretch and in / out points, Time Remapping, composition aspect / shutter phase / display start.
|
||||
//! Every expected value is the value the corpus case was made with (its MANIFEST).
|
||||
|
||||
use crate::container::helpers::{assert_near, base_layer, first_comp, layer_shown_as, layer_with_id, near, open, without_layer_id};
|
||||
use effectcraft_aep::{Interpolation, KeyEase, KeyframeKind, LayerHeader, ParamValue, Project, PropNode, Property, Rational, ValueSource};
|
||||
|
||||
const L: u32 = 0x1b;
|
||||
|
||||
fn with_layer<R>(name: &str, id: u32, f: impl FnOnce(&Project<'_, '_>, &effectcraft_aep::Layer<'_, '_>) -> R) -> Option<R> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
// `L` names the base solid, whatever its id in the case.
|
||||
let layer = if id == L { base_layer(&comp) } else { layer_with_id(&comp, id) };
|
||||
f(&project, &layer)
|
||||
})
|
||||
}
|
||||
|
||||
fn header(name: &str) -> Option<LayerHeader> {
|
||||
with_layer(name, L, |_, l| l.header().unwrap())
|
||||
}
|
||||
|
||||
fn rat(num: i64, den: i64) -> Rational {
|
||||
Rational { num, den }
|
||||
}
|
||||
|
||||
fn ease(in_speed: f64, in_influence: f64, out_speed: f64, out_influence: f64) -> KeyEase {
|
||||
KeyEase { in_speed, in_influence, out_speed, out_influence }
|
||||
}
|
||||
|
||||
fn same_ease(a: &KeyEase, b: &KeyEase) -> bool {
|
||||
near(a.in_speed, b.in_speed, 1e-9)
|
||||
&& near(a.in_influence, b.in_influence, 1e-9)
|
||||
&& near(a.out_speed, b.out_speed, 1e-9)
|
||||
&& near(a.out_influence, b.out_influence, 1e-9)
|
||||
}
|
||||
|
||||
/// The property at a path of match names below a layer.
|
||||
fn with_property<R>(name: &str, id: u32, path: &[&str], f: impl FnOnce(&Property<'_, '_>) -> R) -> Option<R> {
|
||||
Some({
|
||||
with_layer(name, id, |_, layer| {
|
||||
let Some(PropNode::Property(p)) = layer.properties().unwrap().find(path) else { panic!("{name}: no property {path:?}") };
|
||||
f(&p)
|
||||
})?
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ explicit defaults (300-304, 311)
|
||||
|
||||
fn blur_param(name: &str) -> Option<(Option<ParamValue>, Option<ParamValue>, Option<bool>, ParamValue, bool)> {
|
||||
Some({
|
||||
with_layer(name, L, |project, layer| {
|
||||
let effects = layer.effects();
|
||||
assert_eq!(effects.len(), 1, "{name}");
|
||||
let p = project.effect_params(&effects[0]).into_iter().find(|p| p.name == "Blurriness").unwrap();
|
||||
(p.stored_value(), p.pard_default(), p.is_default(), p.value().unwrap(), p.stored().is_some())
|
||||
})?
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_zero_blurriness_is_a_value_record_and_25_is_the_default() {
|
||||
// 300: a fresh Gaussian Blur reads back Blurriness 25 (the MANIFEST row 214 "0" was wrong);
|
||||
// Blurriness set explicitly to 0 writes a record, the default in pard stays 25.
|
||||
let (stored, default, is_default, value, has_record) = skip!(blur_param("300-fx-gaussianblur-0-explicit.aep"));
|
||||
assert_eq!((stored, default, value, has_record), (Some(ParamValue::Number(0.0)), Some(ParamValue::Number(25.0)), ParamValue::Number(0.0), true));
|
||||
assert_eq!(is_default, Some(false));
|
||||
// 301: 25 -> 40 -> 25: the record is removed again, the effective value is the default 25.
|
||||
let (stored, default, is_default, value, has_record) = skip!(blur_param("301-fx-gaussianblur-40-then-25.aep"));
|
||||
assert_eq!((stored, default, value, has_record), (None, Some(ParamValue::Number(25.0)), ParamValue::Number(25.0), false));
|
||||
assert_eq!(is_default, Some(true));
|
||||
// 216 (Blurriness 40): a record, default still 25.
|
||||
let (stored, default, is_default, value, _) = skip!(blur_param("216-fx-gaussianblur-40.aep"));
|
||||
assert_eq!((stored, default, value), (Some(ParamValue::Number(40.0)), Some(ParamValue::Number(25.0)), ParamValue::Number(40.0)));
|
||||
assert_eq!(is_default, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_a_parameter_back_to_its_default_leaves_no_record() {
|
||||
// 303: Fill Opacity 1 -> 0.5 -> 1 and 302: Opacity set to 1 explicitly: no record, value 1.0 (100 %).
|
||||
for name in ["302-fx-fill-opacity-100-explicit.aep", "303-fx-fill-opacity-50-then-100.aep"] {
|
||||
skip!(with_layer(name, L, |project, layer| {
|
||||
let p = project.effect_params(&layer.effects()[0]).into_iter().find(|p| p.name == "Opacity").unwrap();
|
||||
assert!(p.stored().is_none(), "{name}");
|
||||
assert_eq!((p.value(), p.is_default()), (Some(ParamValue::Number(1.0)), Some(true)), "{name}");
|
||||
}));
|
||||
}
|
||||
// 304: Slider set to 0 explicitly: no record, value 0.
|
||||
skip!(with_layer("304-fx-slider-0-explicit.aep", L, |project, layer| {
|
||||
let p = project.effect_params(&layer.effects()[0]).into_iter().find(|p| p.name == "Slider").unwrap();
|
||||
assert!(p.stored().is_none());
|
||||
assert_eq!((p.value(), p.is_default()), (Some(ParamValue::Number(0.0)), Some(true)));
|
||||
}));
|
||||
// The implicit input layer and the built-in entry are not "at default" questions.
|
||||
skip!(with_layer("304-fx-slider-0-explicit.aep", L, |project, layer| {
|
||||
let params = project.effect_params(&layer.effects()[0]);
|
||||
assert_eq!(params.len(), 3);
|
||||
assert_eq!(params[0].is_default(), None);
|
||||
}));
|
||||
// 071 (Slider 77) is a record that differs from the default.
|
||||
skip!(with_layer("071-fx-slider-value77.aep", L, |project, layer| {
|
||||
let p = project.effect_params(&layer.effects()[0]).into_iter().find(|p| p.name == "Slider").unwrap();
|
||||
assert_eq!((p.value(), p.is_default()), (Some(ParamValue::Number(77.0)), Some(false)));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transform_set_to_its_default_adds_no_record() {
|
||||
// 311: Position set to the value it already had ([960,540,0]): the layer tree is the tree of the
|
||||
// unedited 299 (which equals the base layer except for the session), no ADBE Position record.
|
||||
skip!(with_layer("311-position-default-explicit.aep", L, |_, layer| {
|
||||
let t = layer.transform(1920, 1080).unwrap();
|
||||
assert_eq!((t.position.value, t.position.source), ([960.0, 540.0, 0.0], ValueSource::Default));
|
||||
assert_eq!(t.opacity_percent.source, ValueSource::Default);
|
||||
assert!(layer.properties().unwrap().find(&["ADBE Transform Group", "ADBE Position"]).is_none());
|
||||
// The two cases are layers of one file: they differ in the layer id only.
|
||||
let a = without_layer_id(layer.chunk());
|
||||
skip!(with_layer("299-save-noise.aep", L, |_, other| assert_eq!(a, without_layer_id(other.chunk()))));
|
||||
}));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bezier ease layouts (305-307)
|
||||
|
||||
#[test]
|
||||
fn scale_keys_keep_their_ease_type_major() {
|
||||
// 305: Scale keys t=0 [100,100,100] and t=2 [200,150,100]; key1 in speed 0 / influence 33, out
|
||||
// speed 20 / influence 66; key2 in speed 10 / influence 66, out speed 0 / influence 33. The
|
||||
// stored speed is a fraction per second (percent / 100), the influence a fraction.
|
||||
skip!(with_property("305-key-scale-bezier-ease.aep", L, &["ADBE Transform Group", "ADBE Scale"], |p| {
|
||||
let keys: Vec<_> = p.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
let scale = p.time_scale().unwrap();
|
||||
assert_eq!(keys.iter().map(|k| k.seconds(scale).unwrap()).collect::<Vec<_>>(), [0.0, 2.0]);
|
||||
for k in &keys {
|
||||
assert_eq!(k.kind(), KeyframeKind::Plain { components: 3 });
|
||||
assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier)));
|
||||
}
|
||||
assert_near(&keys[0].value().unwrap(), &[1.0, 1.0, 1.0], 1e-9);
|
||||
assert_near(&keys[1].value().unwrap(), &[2.0, 1.5, 1.0], 1e-9);
|
||||
// The raw block: [in speed x3][in influence x3][out speed x3][out influence x3].
|
||||
assert_near(&keys[0].plain_ease_slots().unwrap(), &[0.0, 0.0, 0.0, 0.33, 0.33, 0.33, 0.2, 0.2, 0.2, 0.66, 0.66, 0.66], 1e-9);
|
||||
assert_near(&keys[1].plain_ease_slots().unwrap(), &[0.1, 0.1, 0.1, 0.66, 0.66, 0.66, 0.0, 0.0, 0.0, 0.33, 0.33, 0.33], 1e-9);
|
||||
for i in 0..3 {
|
||||
assert!(same_ease(&keys[0].ease_component(i).unwrap(), &ease(0.0, 0.33, 0.2, 0.66)), "key 1 component {i}");
|
||||
assert!(same_ease(&keys[1].ease_component(i).unwrap(), &ease(0.1, 0.66, 0.0, 0.33)), "key 2 component {i}");
|
||||
}
|
||||
assert!(keys[0].ease_component(3).is_none());
|
||||
assert_eq!(keys[0].ease_components().unwrap().len(), 3);
|
||||
assert!(keys[0].color_distance().is_none());
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_feather_keys_keep_their_ease_type_major() {
|
||||
// 306: Mask Feather keys t=0 [0,0], t=2 [50,30]; key1 in 0/33, out 15/66; key2 in 8/66, out 0/33
|
||||
// (speed in pixels per second).
|
||||
skip!(with_layer("306-key-maskfeather-bezier-ease.aep", L, |_, layer| {
|
||||
let masks = layer.masks();
|
||||
assert_eq!(masks.len(), 1);
|
||||
assert_eq!(masks[0].feather.source, ValueSource::Keyframed);
|
||||
assert_eq!(masks[0].feather.value, [0.0, 0.0]);
|
||||
}));
|
||||
skip!(with_property("306-key-maskfeather-bezier-ease.aep", L, &["ADBE Mask Parade", "ADBE Mask Atom", "ADBE Mask Feather"], |p| {
|
||||
let keys: Vec<_> = p.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
for k in &keys {
|
||||
assert_eq!(k.kind(), KeyframeKind::Plain { components: 2 });
|
||||
assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier)));
|
||||
}
|
||||
assert_near(&keys[0].value().unwrap(), &[0.0, 0.0], 1e-9);
|
||||
assert_near(&keys[1].value().unwrap(), &[50.0, 30.0], 1e-9);
|
||||
assert_near(&keys[0].plain_ease_slots().unwrap(), &[0.0, 0.0, 0.33, 0.33, 15.0, 15.0, 0.66, 0.66], 1e-9);
|
||||
for i in 0..2 {
|
||||
assert!(same_ease(&keys[0].ease_component(i).unwrap(), &ease(0.0, 0.33, 15.0, 0.66)), "key 1 component {i}");
|
||||
assert!(same_ease(&keys[1].ease_component(i).unwrap(), &ease(8.0, 0.66, 0.0, 0.33)), "key 2 component {i}");
|
||||
}
|
||||
assert!(keys[1].ease_component(2).is_none());
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_component_and_position_ease_through_the_component_accessor() {
|
||||
// 205 (Opacity, n = 1): in 0.05 / 0.2, out 0.2 / 0.8; 204 (Position): the single entry.
|
||||
skip!(with_property("205-key-opacity-ease-asymmetric.aep", L, &["ADBE Transform Group", "ADBE Opacity"], |p| {
|
||||
let k = p.keys().unwrap().keyframes().next().unwrap();
|
||||
assert_eq!(k.ease_component(0), k.ease());
|
||||
assert!(same_ease(&k.ease_component(0).unwrap(), &ease(0.05, 0.2, 0.2, 0.8)));
|
||||
assert!(k.ease_component(1).is_none());
|
||||
}));
|
||||
skip!(with_property("204-key-ease-asymmetric.aep", L, &["ADBE Transform Group", "ADBE Position"], |p| {
|
||||
let k = p.keys().unwrap().keyframes().next().unwrap();
|
||||
assert_eq!(k.ease_component(0), k.ease());
|
||||
assert!(k.ease_component(1).is_none());
|
||||
assert_eq!(k.ease_components().unwrap().len(), 1);
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bezier_colour_keys_carry_the_distance_to_the_next_key() {
|
||||
// 307: Fill Color keys t=0 [1,0,0,1] and t=2 [0,0,1,1], both bezier; ease 0/0; f64@16 = the
|
||||
// ARGB distance 255 sqrt(2) = 360.6245 on key 1 and 0 on the last key. The linear keys of 210 have 0.
|
||||
skip!(with_layer("307-key-fillcolor-bezier.aep", L, |project, layer| {
|
||||
let p = project.effect_params(&layer.effects()[0]).into_iter().find(|p| p.name == "Color").unwrap();
|
||||
let keys: Vec<_> = p.stored().unwrap().keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert_eq!(keys[0].kind(), KeyframeKind::Spatial { components: 4 });
|
||||
assert_near(&keys[0].value().unwrap(), &[255.0, 255.0, 0.0, 0.0], 1e-9);
|
||||
assert_near(&keys[1].value().unwrap(), &[255.0, 0.0, 0.0, 255.0], 1e-9);
|
||||
for k in &keys {
|
||||
assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier)));
|
||||
assert!(same_ease(&k.ease_component(0).unwrap(), &ease(0.0, 0.0, 0.0, 0.0)));
|
||||
}
|
||||
assert!(near(keys[0].color_distance().unwrap(), 255.0 * 2f64.sqrt(), 1e-3), "{:?}", keys[0].color_distance());
|
||||
assert!(near(keys[0].color_distance().unwrap(), 360.6245, 1e-3));
|
||||
assert_eq!(keys[1].color_distance(), Some(0.0));
|
||||
}));
|
||||
skip!(with_layer("210-key-fill-color-2key-linear.aep", L, |_, layer| {
|
||||
let p = layer.effects()[0].params().into_iter().find(|p| p.name == "Color").unwrap();
|
||||
let k = p.stored().unwrap().keys().unwrap().keyframes().next().unwrap();
|
||||
assert_eq!(k.color_distance(), Some(0.0));
|
||||
}));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ time stretch and in / out points (316-318, 351, 353)
|
||||
|
||||
fn stretch_facts(name: &str) -> Option<(LayerHeader, Option<Rational>, Option<Rational>, u32)> {
|
||||
Some({
|
||||
with_layer(name, L, |_, layer| {
|
||||
let h = layer.header().unwrap();
|
||||
let Some(PropNode::Property(p)) = layer.properties().unwrap().get("ADBE Time Remapping") else { panic!("no time remap property") };
|
||||
(h.clone(), h.in_point(), h.out_point(), p.time_scale().unwrap())
|
||||
})?
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_stretch_is_an_exact_ratio() {
|
||||
// 316: stretch 100 -> 50 %: 1/2; the stored out point stays 5 s, the layer ends at 2.5 s; the
|
||||
// property time scale stays 25600.
|
||||
let (h, in_p, out_p, scale) = skip!(stretch_facts("316-layer-stretch50.aep"));
|
||||
assert_eq!((h.stretch, h.stretch_den), (1, 2));
|
||||
assert_eq!(h.stretch_ratio(), Some(rat(1, 2)));
|
||||
assert_eq!(h.stretch_percent(), 50.0);
|
||||
assert_eq!(h.out_relative, rat(128000, 25600));
|
||||
assert_eq!((in_p, out_p, scale), (Some(rat(0, 1)), Some(rat(5, 2)), 25600));
|
||||
// 317: 150 %: 3/2, ends at 7.5 s, the property time scale is 25600 x 3/2.
|
||||
let (h, in_p, out_p, scale) = skip!(stretch_facts("317-layer-stretch150.aep"));
|
||||
assert_eq!((h.stretch, h.stretch_den), (3, 2));
|
||||
assert_eq!(h.stretch_ratio(), Some(rat(3, 2)));
|
||||
assert_eq!(h.stretch_percent(), 150.0);
|
||||
assert_eq!((in_p, out_p, scale), (Some(rat(0, 1)), Some(rat(15, 2)), 38400));
|
||||
// 018: 200 %: 2/1, ends at 10 s, time scale 51200. The base is 1/1.
|
||||
let (h, _, out_p, scale) = skip!(stretch_facts("018-layer-stretch200.aep"));
|
||||
assert_eq!((h.stretch, h.stretch_den, h.stretch_ratio()), (2, 1, Some(rat(2, 1))));
|
||||
assert_eq!((out_p, scale), (Some(rat(10, 1)), 51200));
|
||||
let (h, _, out_p, scale) = skip!(stretch_facts("000-base.aep"));
|
||||
assert_eq!((h.stretch, h.stretch_den, h.stretch_percent()), (1, 1, 100.0));
|
||||
assert_eq!((out_p, scale), (Some(rat(5, 1)), 25600));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fractional_times_are_exact_multiples_of_one_over_25600() {
|
||||
// 318: inPoint 0.3333 s became 8532/25600 = 0.33328125 s; the out point moved with it (duration
|
||||
// kept): 136532/25600 = 5.33328125 s; start stays 0.
|
||||
let h = skip!(header("318-layer-inpoint-0.3333.aep"));
|
||||
assert_eq!(h.in_relative, rat(8532, 25600));
|
||||
assert_eq!(h.out_relative, rat(136532, 25600));
|
||||
assert_eq!(h.start, rat(0, 25600));
|
||||
assert_eq!(h.in_point(), Some(rat(2133, 6400)));
|
||||
assert_eq!(h.in_point_seconds(), Some(0.33328125));
|
||||
assert_eq!(h.out_point_seconds(), Some(5.33328125));
|
||||
assert_eq!(h.stretch_ratio(), Some(rat(1, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footage_layers_use_the_footage_time_base_as_out_point_denominator() {
|
||||
// 351: the audio layer's out point is 48000/48000 (the sample rate as denominator), start and
|
||||
// in point keep 25600; the layer copies the item's label 7 and shows the item's name.
|
||||
let bytes = fixture!("351-footage-wav-as-layer.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = comp.layers().find(|l| project.layer_source(l).and_then(|s| s.footage()).is_some_and(|f| f.file_type == "WAVE")).unwrap();
|
||||
let h = layer.header().unwrap();
|
||||
assert_eq!(h.out_relative, rat(48000, 48000));
|
||||
assert_eq!((h.start.den, h.in_relative.den), (25600, 25600));
|
||||
assert_eq!(h.out_point(), Some(rat(1, 1)));
|
||||
// The source is the WAV item (item id 0x20 in the single-case file).
|
||||
assert_eq!(h.label, 7);
|
||||
assert!(layer.name().is_none());
|
||||
assert!(h.is_video_enabled(), "the video switch stays set on an audio-only layer (flag byte 39 = 07)");
|
||||
// 354: the image sequence layer: out point 3/30 = 0.1 s (the frame rate as denominator), label 3,
|
||||
// the layer has no name of its own and shows the first file name.
|
||||
let bytes = fixture!("354-footage-pngseq-timeremap.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = layer_shown_as(&project, &comp, "seq_001.png");
|
||||
let h = layer.header().unwrap();
|
||||
assert_eq!(h.out_relative, rat(3, 30));
|
||||
assert_eq!(h.out_point(), Some(rat(1, 10)));
|
||||
assert_eq!((h.label, h.start.den), (3, 25600));
|
||||
// The source is the sequence item (item id 0x22 in the single-case file).
|
||||
assert!(project.layer_source(&layer).and_then(|s| s.footage()).is_some_and(|f| f.is_sequence));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Time Remapping (319, 354)
|
||||
|
||||
#[test]
|
||||
fn time_remapping_is_an_inert_property_until_enabled() {
|
||||
// Every layer has an inert ADBE Time Remapping property (tdsb 3, static 0, no keys).
|
||||
skip!(with_layer("000-base.aep", L, |_, layer| {
|
||||
let t = layer.time_remap().unwrap();
|
||||
assert!(!t.enabled && t.keys.is_empty());
|
||||
let Some(PropNode::Property(p)) = layer.properties().unwrap().get("ADBE Time Remapping") else { panic!() };
|
||||
assert_eq!((p.flags(), p.is_animated(), p.static_value()), (Some(3), false, Some(vec![0.0])));
|
||||
}));
|
||||
// 319: the precomp layer `Pre` with the remap on: keyed (tdsb 1), two keys 0 s -> 0 and 5 s -> 5;
|
||||
// the layer inside Pre and the other layers stay inert.
|
||||
let bytes = fixture!("319-precomp-timeremap.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = layer_shown_as(&project, &comp, "Pre");
|
||||
let t = layer.time_remap().unwrap();
|
||||
assert!(t.enabled);
|
||||
assert_eq!(t.keys.len(), 2);
|
||||
assert_eq!((t.keys[0].time_seconds, t.keys[0].value_seconds), (Some(0.0), 0.0));
|
||||
assert_eq!((t.keys[1].time_seconds, t.keys[1].value_seconds), (Some(5.0), 5.0));
|
||||
assert_eq!(t.keys[1].time_units, 128000);
|
||||
let Some(PropNode::Property(p)) = layer.properties().unwrap().get("ADBE Time Remapping") else { panic!() };
|
||||
assert_eq!((p.flags(), p.is_animated(), p.static_value()), (Some(1), true, None));
|
||||
let pre = project.all_items().into_iter().find(|i| i.name().as_deref() == Some("Pre")).unwrap().comp().unwrap();
|
||||
assert!(pre.layers().all(|l| !l.time_remap().unwrap().enabled));
|
||||
// 354: on a footage layer: keys 0 s -> 0 and 0.1 s -> 0.1.
|
||||
let bytes = fixture!("354-footage-pngseq-timeremap.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = layer_shown_as(&project, &comp, "seq_001.png");
|
||||
let t = layer.time_remap().unwrap();
|
||||
assert!(t.enabled);
|
||||
assert_eq!(t.keys.len(), 2);
|
||||
assert_eq!((t.keys[0].time_units, t.keys[0].value_seconds), (0, 0.0));
|
||||
assert!(near(t.keys[1].time_seconds.unwrap(), 0.1, 1e-6) && near(t.keys[1].value_seconds, 0.1, 1e-6), "{t:?}");
|
||||
assert!(!base_layer(&comp).time_remap().unwrap().enabled);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ composition (325-327)
|
||||
|
||||
fn comp_header(name: &str) -> Option<effectcraft_aep::CompHeader> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
first_comp(&Project::new(&file).unwrap()).header().unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_aspect_shutter_phase_and_display_start() {
|
||||
// 325: pixelAspect 0.9091 reads back 0.90909090909091 = the exact ratio 10/11.
|
||||
let h = skip!(comp_header("325-comp-pixelaspect-0.9091.aep"));
|
||||
assert_eq!(h.pixel_aspect.reduced(), Some(rat(10, 11)));
|
||||
assert!(near(h.pixel_aspect_ratio().unwrap(), 0.90909090909091, 1e-12));
|
||||
// 326: shutterPhase -90, the shutter angle stays 180.
|
||||
let h = skip!(comp_header("326-comp-shutterphase-m90.aep"));
|
||||
assert_eq!((h.shutter_phase, h.shutter_angle), (Some(-90), 180));
|
||||
// 327: displayStartFrame 100 at 25 fps = 4 s = 102400/25600; the shutter phase is back to 0.
|
||||
let h = skip!(comp_header("327-comp-displaystartframe-100.aep"));
|
||||
assert_eq!(h.display_start, Some(rat(102400, 25600)));
|
||||
assert_eq!((h.display_start_seconds(), h.display_start_frame(), h.shutter_phase), (Some(4.0), Some(100), Some(0)));
|
||||
// The base: no phase, start 0.
|
||||
let h = skip!(comp_header("000-base.aep"));
|
||||
assert_eq!((h.shutter_phase, h.display_start_seconds(), h.display_start_frame()), (Some(0), Some(0.0), Some(0)));
|
||||
assert_eq!(h.pixel_aspect_ratio(), Some(1.0));
|
||||
// A short chunk still decodes the old fields.
|
||||
let bytes = [0u8; 176];
|
||||
let h = effectcraft_aep::CompHeader::parse(&bytes).unwrap();
|
||||
assert_eq!((h.shutter_phase, h.display_start.map(|r| r.den)), (None, Some(0)));
|
||||
}
|
||||
@@ -1,543 +0,0 @@
|
||||
//! Batch 3 (objects): Point / Layer / Dropdown controls, masks, shape items, text styles, camera,
|
||||
//! light, marker data and footage items. Every expected value is the value the corpus case was
|
||||
//! made with (its MANIFEST).
|
||||
|
||||
use crate::container::helpers::{assert_near, base_layer, first_comp, layer_named, layer_of_type, layer_shown_as, near, open};
|
||||
use effectcraft_aep::{
|
||||
Caps, CueType, GradientType, ItemKind, Justification, LayerRef, LayerType, MaskMode, ParamKind, ParamValue, PolystarType, Project, PropNode, Rational,
|
||||
ShapeDetail, ShapeItem, TextDocument, ValueSource,
|
||||
};
|
||||
|
||||
fn rat(num: i64, den: i64) -> Rational {
|
||||
Rational { num, den }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Point control (310, 218)
|
||||
|
||||
#[test]
|
||||
fn the_point_default_is_a_fraction_of_the_layer() {
|
||||
// 310: the default Point of a Point Control on a 100x100 solid reads back [50, 50]: the default is
|
||||
// two 16.16 fractions 0.5 in pard, relative to the layer, not pixels.
|
||||
let bytes = fixture!("310-solid-100x100-pointcontrol.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = layer_shown_as(&project, &comp, "S100");
|
||||
assert_eq!(project.layer_source_size(&layer), Some((100, 100)));
|
||||
let effects = layer.effects();
|
||||
assert_eq!(effects.len(), 1);
|
||||
let p = effects[0].params().into_iter().find(|p| p.kind == ParamKind::Point).unwrap();
|
||||
assert!(p.stored().is_none());
|
||||
assert_eq!(p.pard_default(), Some(ParamValue::Point([0.5, 0.5])));
|
||||
assert_eq!((p.value(), p.is_default()), (Some(ParamValue::Point([0.5, 0.5])), Some(true)));
|
||||
assert_eq!(p.point_px(100.0, 100.0), Some([50.0, 50.0]));
|
||||
assert_eq!(&p.pard()[56..64], &[0, 0, 0x80, 0, 0, 0, 0x80, 0], "two 16.16 fractions 0.5");
|
||||
// 218: an explicit [111, 222] on the 1920x1080 solid is [111/1920, 222/1080] of the layer.
|
||||
let bytes = fixture!("218-fx-point-111-222.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let p = layer.effects()[0].params().into_iter().find(|p| p.kind == ParamKind::Point).unwrap();
|
||||
assert_eq!(p.is_default(), Some(false));
|
||||
let px = p.point_px(1920.0, 1080.0).unwrap();
|
||||
assert_near(&px, &[111.0, 222.0], 1e-9);
|
||||
assert!(p.point_px(f64::NAN, 1.0).is_some());
|
||||
let other = layer.effects()[0].params().into_iter().find(|p| p.kind == ParamKind::Layer).unwrap();
|
||||
assert_eq!(other.point_px(1.0, 1.0), None);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Layer Control (320, 321, 220)
|
||||
|
||||
/// The Layer Control's reference, the input layer's stored value and reference, the id of `L`
|
||||
/// (the owner) and the id of the top layer.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn layer_ref(name: &str) -> Option<(Option<LayerRef>, Option<ParamValue>, Option<LayerRef>, u32, u32)> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = base_layer(&comp);
|
||||
let owner = layer.id().unwrap();
|
||||
let effects = layer.effects();
|
||||
assert_eq!(effects.len(), 1, "{name}");
|
||||
assert_eq!(effects[0].match_name(), "ADBE Layer Control");
|
||||
let params = project.effect_params(&effects[0]);
|
||||
let p = params.iter().find(|p| p.kind == ParamKind::Layer && p.index == 1).unwrap();
|
||||
// The implicit input layer is not a layer reference.
|
||||
(p.layer_ref(owner), params[0].stored_value(), params[0].layer_ref(owner), owner, comp.layers().next().unwrap().id().unwrap())
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_control_self_versus_none() {
|
||||
// 320: Layer set explicitly to 1 = the layer itself: tdpi = the owning layer's id.
|
||||
let (r, input, input_ref, owner, _) = skip!(layer_ref("320-fx-layercontrol-self-explicit.aep"));
|
||||
assert_eq!((r, input, input_ref), (Some(LayerRef::This), Some(ParamValue::Layer(owner)), None));
|
||||
// 321: None: tdpi = 0.
|
||||
let (r, input, input_ref, owner, _) = skip!(layer_ref("321-fx-layercontrol-none.aep"));
|
||||
assert_eq!((r, input, input_ref), (Some(LayerRef::Nothing), Some(ParamValue::Layer(owner)), None));
|
||||
// 220: Layer 1 of a new Null layer (the top layer).
|
||||
let (r, _, _, owner, top) = skip!(layer_ref("220-fx-layercontrol-to-layer1.aep"));
|
||||
assert_ne!(top, owner);
|
||||
assert_eq!(r, Some(LayerRef::Layer(top)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Dropdown (323, 324, 077)
|
||||
|
||||
#[test]
|
||||
fn dropdown_items_selection_and_count() {
|
||||
for (name, selected, text, is_default) in
|
||||
[("323-fx-dropdown-5items.aep", 1, "Alpha", Some(true)), ("324-fx-dropdown-5items-select3.aep", 3, "Gamma", Some(false))]
|
||||
{
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let effects = layer.effects();
|
||||
assert_eq!(effects.len(), 1);
|
||||
// set_dropdown_items re-creates the effect definition under a new match name.
|
||||
assert!(effects[0].match_name().starts_with("Pseudo/@@") && effects[0].match_name().len() == 31, "{name}");
|
||||
assert_eq!(effects[0].name().as_deref(), Some("Dropdown Menu Control"));
|
||||
let p = effects[0].params().into_iter().find(|p| p.kind == ParamKind::Popup).unwrap();
|
||||
assert_eq!(p.items.as_deref(), Some(&["Alpha", "Beta", "Gamma", "Delta", "Epsilon"].map(String::from)[..]), "{name}");
|
||||
assert_eq!(p.popup_item_count(), Some(5), "{name}");
|
||||
assert_eq!((p.popup_selected_index(), p.popup_selected_item()), (Some(selected), Some(text)), "{name}");
|
||||
assert_eq!(p.is_default(), is_default, "{name}");
|
||||
assert_eq!(p.stored().is_some(), selected != 1, "{name}");
|
||||
if selected == 3 {
|
||||
// The selection is a value record and also overwrites pard@56.
|
||||
assert_eq!(p.stored_value(), Some(ParamValue::Index(3)));
|
||||
assert_eq!(p.pard_default(), Some(ParamValue::Index(3)));
|
||||
} else {
|
||||
assert_eq!(p.stored_value(), None);
|
||||
assert_eq!(p.pard_default(), Some(ParamValue::Index(1)));
|
||||
}
|
||||
}
|
||||
// 077: the default dropdown with three items.
|
||||
let bytes = fixture!("077-fx-dropdown-default.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let p = layer.effects()[0].params().into_iter().find(|p| p.kind == ParamKind::Popup).unwrap();
|
||||
assert_eq!((p.popup_item_count(), p.popup_selected_item()), (Some(3), Some("Item 1")));
|
||||
let no_data = layer.effects()[0].params().into_iter().find(|p| p.kind == ParamKind::NoData).unwrap();
|
||||
assert_eq!((no_data.popup_item_count(), no_data.popup_selected_index(), no_data.popup_selected_item()), (None, None, None));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ masks (309, 328, 329)
|
||||
|
||||
fn ellipse_vertices() -> [[f64; 2]; 4] {
|
||||
[[960.0, 340.0], [1360.0, 540.0], [960.0, 740.0], [560.0, 540.0]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_box_is_normalised_to_the_layer_size() {
|
||||
// 309: a 60x40 rectangle at [50,50] on a 100x100 solid: box 0.2, 0.3, 0.8, 0.7 of the LAYER;
|
||||
// vertices [20,30] [80,30] [80,70] [20,70].
|
||||
let bytes = fixture!("309-solid-100x100-mask-rect.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = layer_shown_as(&project, &comp, "S100");
|
||||
let masks = layer.masks();
|
||||
assert_eq!(masks.len(), 1);
|
||||
let m = &masks[0];
|
||||
assert_eq!((m.mode, m.inverted, m.counter), (Some(MaskMode::Add), Some(false), Some(1)));
|
||||
let want_box = [0.2, 0.3, 0.8, 0.7];
|
||||
for (got, want) in m.shapes[0].bbox.iter().zip(want_box) {
|
||||
assert!(near(f64::from(*got), want, 1e-6), "{:?}", m.shapes[0].bbox);
|
||||
}
|
||||
let shapes = project.mask_vertices_px(&layer, m).unwrap();
|
||||
assert_eq!(shapes.len(), 1);
|
||||
let got: Vec<[f64; 2]> = shapes[0].iter().map(|v| v.position).collect();
|
||||
for (g, w) in got.iter().zip([[20.0, 30.0], [80.0, 30.0], [80.0, 70.0], [20.0, 70.0]]) {
|
||||
assert_near(g, &w, 1e-3);
|
||||
}
|
||||
assert_eq!(got.len(), 4);
|
||||
// A layer without a sized source has no pixel vertices.
|
||||
let bytes = fixture!("333-shape-group-two-rects.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let shape = layer_named(&first_comp(&project), "Shape");
|
||||
assert!(project.mask_vertices_px(&shape, m).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_mkif_per_mask_and_the_mode_none() {
|
||||
// 328: ellipse 800x400 at [960,540] (Mask 1) and rectangle 400x300 at [700,500] (Mask 2), both Add;
|
||||
// the per-layer counter gives 1 and 2.
|
||||
let bytes = fixture!("328-mask-two-ellipse-rect.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let masks = layer.masks();
|
||||
assert_eq!(masks.len(), 2);
|
||||
assert_eq!(masks.iter().map(|m| m.name.as_deref()).collect::<Vec<_>>(), [Some("Mask 1"), Some("Mask 2")]);
|
||||
for (m, counter) in masks.iter().zip([1, 2]) {
|
||||
assert_eq!((m.mode, m.inverted, m.counter), (Some(MaskMode::Add), Some(false), Some(counter)));
|
||||
assert_eq!(m.shapes.len(), 1);
|
||||
}
|
||||
let v1 = project.mask_vertices_px(&layer, &masks[0]).unwrap();
|
||||
for (v, w) in v1[0].iter().zip(ellipse_vertices()) {
|
||||
assert_near(&v.position, &w, 1e-2);
|
||||
}
|
||||
// Mask 2 has its own box (500..900 x 350..650) normalised to the layer.
|
||||
let v2 = project.mask_vertices_px(&layer, &masks[1]).unwrap();
|
||||
for (v, w) in v2[0].iter().zip([[500.0, 350.0], [900.0, 350.0], [900.0, 650.0], [500.0, 650.0]]) {
|
||||
assert_near(&v.position, &w, 1e-2);
|
||||
}
|
||||
assert_eq!(v2[0].len(), 4);
|
||||
// 329: the same ellipse as 232 with the mode None (0). The layer's mask counter is 1: the case is the first mask on its layer.
|
||||
let bytes = fixture!("329-mask-ellipse-mode-none.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let none = base_layer(&first_comp(&project)).masks();
|
||||
assert_eq!(none.len(), 1);
|
||||
assert_eq!((none[0].mode, none[0].counter), (Some(MaskMode::None), Some(1)));
|
||||
assert_eq!(MaskMode::from_id(0), MaskMode::None);
|
||||
let bytes = fixture!("232-mask-ellipse.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let add = base_layer(&first_comp(&project)).masks();
|
||||
assert_eq!(add[0].mode, Some(MaskMode::Add));
|
||||
assert_eq!(add[0].shapes, none[0].shapes, "329 is 232 with another mode");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ shapes (330-333)
|
||||
|
||||
fn shape_group(name: &str) -> Option<effectcraft_aep::ShapeGroup> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = layer_named(&first_comp(&project), "Shape");
|
||||
let h = layer.header().unwrap();
|
||||
assert_eq!((h.layer_type, h.label), (LayerType::Shape, 8), "{name}");
|
||||
let mut groups = layer.shape_groups();
|
||||
assert_eq!(groups.len(), 1, "{name}");
|
||||
groups.remove(0)
|
||||
})
|
||||
}
|
||||
|
||||
fn other_name(item: &ShapeItem) -> &str {
|
||||
match item {
|
||||
ShapeItem::Other { match_name, .. } => match_name,
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polystar_defaults_and_polygon() {
|
||||
// 330: star, 5 points, outer 100, inner 50 = the defaults: no property record at all.
|
||||
let g = skip!(shape_group("330-shape-polystar-star-5-50-100.aep"));
|
||||
assert_eq!(g.name.as_deref(), Some("Group 1"));
|
||||
assert_eq!(g.items.len(), 2);
|
||||
assert_eq!(other_name(&g.items[0]), "ADBE Vector Shape - Star");
|
||||
assert!(matches!(&g.items[1], ShapeItem::Fill { color: Some(c), .. } if c.value == [1.0, 0.0, 1.0, 0.0]));
|
||||
let [ShapeDetail::Polystar { item_index, star_type, outer_radius, inner_radius, inner_roundness }] = &g.details[..] else { panic!("{:?}", g.details) };
|
||||
assert_eq!(*item_index, 0);
|
||||
assert_eq!((star_type.value, star_type.source), (PolystarType::Star, ValueSource::Default));
|
||||
assert_eq!((outer_radius.value, outer_radius.source), (100.0, ValueSource::Default));
|
||||
assert_eq!((inner_radius.value, inner_radius.source), (50.0, ValueSource::Default));
|
||||
assert!(inner_roundness.is_none());
|
||||
// 331: polygon (type 2): the type record, plus Inner Radius 50 and Inner Roundess 0 in their default state.
|
||||
let g = skip!(shape_group("331-shape-polystar-polygon-5-100.aep"));
|
||||
let [ShapeDetail::Polystar { star_type, outer_radius, inner_radius, inner_roundness, .. }] = &g.details[..] else { panic!("{:?}", g.details) };
|
||||
assert_eq!((star_type.value, star_type.source), (PolystarType::Polygon, ValueSource::Stored));
|
||||
assert_eq!((outer_radius.value, outer_radius.source), (100.0, ValueSource::Default));
|
||||
assert_eq!((inner_radius.value, inner_radius.source), (50.0, ValueSource::Stored));
|
||||
let r = inner_roundness.unwrap();
|
||||
assert_eq!((r.value, r.source), (0.0, ValueSource::Stored));
|
||||
// The tdsb states: the type is a written record (1), the other two are default-state records (3).
|
||||
let bytes = fixture!("331-shape-polystar-polygon-5-100.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = layer_named(&first_comp(&project), "Shape");
|
||||
let base = ["ADBE Root Vectors Group", "ADBE Vector Group", "ADBE Vectors Group", "ADBE Vector Shape - Star"];
|
||||
for (prop, flags) in [("ADBE Vector Star Type", 1), ("ADBE Vector Star Inner Radius", 3), ("ADBE Vector Star Inner Roundess", 3)] {
|
||||
let path: Vec<&str> = base.iter().copied().chain([prop]).collect();
|
||||
let Some(PropNode::Property(p)) = layer.properties().unwrap().find(&path) else { panic!("{prop}") };
|
||||
assert_eq!(p.flags(), Some(flags), "{prop}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_gradient_extra_records() {
|
||||
// 332: Rectangle Path 400x300 + Gradient Fill, radial (type 2), Start [0,0] = default (absent),
|
||||
// End [200,0], Highlight Length / Angle 0 written as records.
|
||||
let g = skip!(shape_group("332-shape-gradient-fill-radial.aep"));
|
||||
assert_eq!(g.items.len(), 2);
|
||||
let ShapeItem::GradientFill { start, end, .. } = &g.items[1] else { panic!("{:?}", g.items[1]) };
|
||||
assert!(start.is_none());
|
||||
assert_eq!(end.map(|e| (e.value, e.source)), Some(([200.0, 0.0], ValueSource::Stored)));
|
||||
let gradient = g.details.iter().find_map(|d| match d {
|
||||
ShapeDetail::Gradient { item_index, gradient_type, highlight_length, highlight_angle } => {
|
||||
Some((*item_index, *gradient_type, *highlight_length, *highlight_angle))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let (index, kind, length, angle) = gradient.unwrap();
|
||||
assert_eq!(index, 1);
|
||||
assert_eq!((kind.value, kind.source), (GradientType::Radial, ValueSource::Stored));
|
||||
assert_eq!(length.map(|t| (t.value, t.source)), Some((0.0, ValueSource::Stored)));
|
||||
assert_eq!(angle.map(|t| (t.value, t.source)), Some((0.0, ValueSource::Stored)));
|
||||
// 241 (linear): the type is the default and the highlight records are absent.
|
||||
let bytes = fixture!("241-shape-gradient-fill-linear.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = layer_named(&first_comp(&project), "S");
|
||||
let g = layer.shape_groups().remove(0);
|
||||
let linear = g.details.iter().find_map(|d| match d {
|
||||
ShapeDetail::Gradient { gradient_type, highlight_length, highlight_angle, .. } => Some((*gradient_type, *highlight_length, *highlight_angle)),
|
||||
_ => None,
|
||||
});
|
||||
let (kind, length, angle) = linear.unwrap();
|
||||
assert_eq!((kind.value, kind.source), (GradientType::Linear, ValueSource::Default));
|
||||
assert!(length.is_none() && angle.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_rectangles_in_one_group_are_two_items() {
|
||||
// 333: Rectangle Path 1 [400,300], Rectangle Path 2 [100,100] (= default, no Size record) at
|
||||
// position [300,0], Fill 1 (order: rect, rect, fill).
|
||||
let g = skip!(shape_group("333-shape-group-two-rects.aep"));
|
||||
assert_eq!(g.items.len(), 3);
|
||||
let ShapeItem::Rect { name: n1, size: s1 } = &g.items[0] else { panic!() };
|
||||
let ShapeItem::Rect { name: n2, size: s2 } = &g.items[1] else { panic!() };
|
||||
assert_eq!((n1.as_deref(), n2.as_deref()), (Some("Rectangle Path 1"), Some("Rectangle Path 2")));
|
||||
assert_eq!(s1.map(|s| s.value), Some([400.0, 300.0]));
|
||||
assert!(s2.is_none(), "[100, 100] is the default size");
|
||||
assert!(matches!(&g.items[2], ShapeItem::Fill { color: Some(c), .. } if c.value == [1.0, 0.0, 1.0, 0.0]));
|
||||
let positions: Vec<_> = g
|
||||
.details
|
||||
.iter()
|
||||
.filter_map(|d| match d {
|
||||
ShapeDetail::RectPosition { item_index, position } => Some((*item_index, position.value, position.source)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(positions, [(0, [0.0, 0.0], ValueSource::Default), (1, [300.0, 0.0], ValueSource::Stored)]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ text (334-340)
|
||||
|
||||
fn text(name: &str, layer: &str) -> Option<TextDocument> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
layer_named(&first_comp(&project), layer).text_document().unwrap_or_else(|| panic!("{name}: no text document"))
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_justification_in_box_text() {
|
||||
// 334: box text "Hello" in a 400x200 box at [-200,-100], right aligned (stored 1; compare 245: 0, 246: 2).
|
||||
let t = skip!(text("334-text-box-right-align.aep", "T"));
|
||||
assert_eq!(t.text, "Hello");
|
||||
assert_eq!((t.paragraphs.len(), t.paragraphs[0].length, t.paragraphs[0].justification), (1, 6, Justification::Right));
|
||||
let b = t.text_box.unwrap();
|
||||
assert_eq!((b.x, b.y, b.width, b.height), (-200.0, -100.0, 400.0, 200.0));
|
||||
assert_eq!(skip!(text("245-text-box-400x200-Hello.aep", "T")).paragraphs[0].justification, Justification::Left);
|
||||
assert_eq!(skip!(text("246-text-box-center-align.aep", "T")).paragraphs[0].justification, Justification::Center);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faux_styles_caps_and_leading() {
|
||||
// The reference style: no faux styles, normal caps, auto leading (stored 98), the font list of four.
|
||||
let t = skip!(text("337-text-point-allcaps.aep", "T"));
|
||||
assert_eq!(t.style_runs.len(), 1);
|
||||
let plain = t.style_runs[0];
|
||||
assert_eq!((plain.faux_bold, plain.faux_italic, plain.leading, plain.font_index), (false, false, Some(98.0), 0));
|
||||
assert_eq!((plain.caps, t.fonts.len()), (Caps::All, 4));
|
||||
// 335 / 336: faux bold / italic; the font list gains a first entry (4 -> 5) and the style uses font 1.
|
||||
for (name, bold, italic) in [("335-text-point-fauxbold.aep", true, false), ("336-text-point-fauxitalic.aep", false, true)] {
|
||||
let t = skip!(text(name, "T"));
|
||||
let s = t.style_runs[0];
|
||||
assert_eq!((s.faux_bold, s.faux_italic, s.caps), (bold, italic, Caps::Normal), "{name}");
|
||||
assert_eq!((t.fonts.len(), s.font_index, t.font_index), (5, 1, 1), "{name}");
|
||||
assert_eq!((t.fonts[0].as_str(), t.fonts[1].as_str()), ("TimesNewRomanPSMT", "TimesNewRomanPSMT"), "{name}");
|
||||
assert_eq!(t.font.as_deref(), Some("TimesNewRomanPSMT"));
|
||||
}
|
||||
// 338: small caps; 337: all caps.
|
||||
assert_eq!(skip!(text("338-text-point-smallcaps.aep", "T")).style_runs[0].caps, Caps::Small);
|
||||
// 339: leading 60.
|
||||
let s = skip!(text("339-text-point-leading60.aep", "T")).style_runs[0];
|
||||
assert_eq!((s.leading, s.caps, s.faux_bold), (Some(60.0), Caps::Normal, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_style_run_absorbs_the_final_carriage_return() {
|
||||
// 340: "el" red, "lo" blue and size 60 on "Hello": runs of 1, 2 and 3 characters (the last one
|
||||
// includes the \r), fills white / red / blue, sizes 100 / 100 / 60.
|
||||
let t = skip!(text("340-text-range-two-styles.aep", "T"));
|
||||
assert_eq!(t.raw_text, "Hello\r");
|
||||
assert_eq!(t.style_runs.iter().map(|r| r.length).collect::<Vec<_>>(), [1, 2, 3]);
|
||||
assert_eq!(t.style_runs.iter().map(|r| r.length).sum::<usize>(), t.raw_text.chars().count());
|
||||
assert_eq!(t.style_runs.iter().map(|r| r.fill_argb).collect::<Vec<_>>(), [[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 1.0]]);
|
||||
assert_eq!(t.style_runs.iter().map(|r| r.font_size).collect::<Vec<_>>(), [100.0, 100.0, 60.0]);
|
||||
assert_eq!(t.paragraphs.iter().map(|p| p.length).collect::<Vec<_>>(), [6]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ camera and light (341-345)
|
||||
|
||||
#[test]
|
||||
fn camera_zoom_and_depth_of_field() {
|
||||
let camera = |name: &str| {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = layer_of_type(&first_comp(&project), LayerType::Camera);
|
||||
(
|
||||
layer.camera_zoom(),
|
||||
layer.camera_depth_of_field(),
|
||||
layer.camera_focus_distance(),
|
||||
layer.camera_aperture(),
|
||||
layer.camera_position().map(|p| (p.stored, p.auto_state)),
|
||||
)
|
||||
})
|
||||
};
|
||||
// 341: Zoom 2000 is stored; the auto Position keeps [0, 0, -2666.67].
|
||||
let (zoom, dof, focus, aperture, pos) = skip!(camera("341-camera-zoom-2000.aep"));
|
||||
assert_eq!(zoom.map(|z| (z.value, z.source)), Some((2000.0, ValueSource::Stored)));
|
||||
assert_eq!((dof.map(|d| (d.value, d.source)), focus, aperture), (Some((false, ValueSource::Default)), None, None));
|
||||
let (stored, auto) = pos.unwrap();
|
||||
assert!(auto && near(stored[2], -2666.67, 0.01) && stored[0] == 0.0, "{stored:?}");
|
||||
// 342: DOF on, Focus Distance 800, Aperture 30; Zoom stays the default.
|
||||
let (zoom, dof, focus, aperture, _) = skip!(camera("342-camera-dof-800-30.aep"));
|
||||
assert_eq!(zoom.map(|z| (z.source, near(z.value, 2666.67, 0.01))), Some((ValueSource::Default, true)));
|
||||
assert_eq!(dof.map(|d| (d.value, d.source)), Some((true, ValueSource::Stored)));
|
||||
assert_eq!(focus.map(|f| (f.value, f.source)), Some((800.0, ValueSource::Stored)));
|
||||
assert_eq!(aperture.map(|f| (f.value, f.source)), Some((30.0, ValueSource::Stored)));
|
||||
// The default camera (256) has nothing but the default zoom.
|
||||
let (zoom, dof, ..) = skip!(camera("256-camera-two-node-default.aep"));
|
||||
assert_eq!((zoom.unwrap().source, dof.unwrap().value), (ValueSource::Default, false));
|
||||
assert_eq!(zoom.unwrap().value, effectcraft_aep::DEFAULT_CAMERA_ZOOM);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light_colour_cone_angle_and_feather() {
|
||||
let light = |name: &str| {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = layer_of_type(&first_comp(&project), LayerType::Light);
|
||||
assert_eq!(layer.header().unwrap().light_type(), Some(effectcraft_aep::LightType::Spot), "{name}");
|
||||
let t = |x: Option<effectcraft_aep::Tracked<f64>>| x.map(|x| (x.value, x.source));
|
||||
(layer.light_color().map(|c| (c.value, c.source)), t(layer.light_cone_angle()), t(layer.light_cone_feather()))
|
||||
})
|
||||
};
|
||||
// The default spot light: white, 90, 50, all absent.
|
||||
let (colour, angle, feather) = skip!(light("254-light-spot-intensity-50.aep"));
|
||||
assert_eq!((colour, angle, feather), (Some(([1.0; 4], ValueSource::Default)), Some((90.0, ValueSource::Default)), Some((50.0, ValueSource::Default))));
|
||||
// 343: colour [1,0,0,1] = ARGB doubles [255,255,0,0].
|
||||
let (colour, angle, feather) = skip!(light("343-light-spot-color-red.aep"));
|
||||
assert_eq!(colour, Some(([1.0, 1.0, 0.0, 0.0], ValueSource::Stored)));
|
||||
assert_eq!((angle, feather), (Some((90.0, ValueSource::Default)), Some((50.0, ValueSource::Default))));
|
||||
// 344: Cone Angle 60. 345: Cone Feather 30.
|
||||
let (colour, angle, feather) = skip!(light("344-light-spot-coneangle-60.aep"));
|
||||
assert_eq!((colour.unwrap().1, angle, feather), (ValueSource::Default, Some((60.0, ValueSource::Stored)), Some((50.0, ValueSource::Default))));
|
||||
let (_, angle, feather) = skip!(light("345-light-spot-conefeather-30.aep"));
|
||||
assert_eq!((angle, feather), (Some((90.0, ValueSource::Default)), Some((30.0, ValueSource::Stored))));
|
||||
// A point light (252) stores Cone Angle 90 / Feather 50 in their default state.
|
||||
let bytes = fixture!("252-light-point.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = layer_of_type(&first_comp(&project), LayerType::Light);
|
||||
assert_eq!(layer.light_cone_angle().map(|a| (a.value, a.source)), Some((90.0, ValueSource::Stored)));
|
||||
// Layers without light options have no light accessors.
|
||||
let bytes = fixture!("000-base.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let solid = base_layer(&first_comp(&project));
|
||||
assert!(solid.light_color().is_none() && solid.camera_zoom().is_none() && solid.camera_depth_of_field().is_none());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ marker data (347-349, 249)
|
||||
|
||||
fn layer_markers(name: &str) -> Option<Vec<effectcraft_aep::Marker>> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
base_layer(&first_comp(&project)).markers()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marker_label_cue_type_and_parameters() {
|
||||
// 347: marker at 1 s, comment M, label 3 (event cue by default, no parameters).
|
||||
let m = skip!(layer_markers("347-marker-layer-label3.aep"));
|
||||
assert_eq!(m.len(), 1);
|
||||
assert_eq!((m[0].seconds, m[0].comment.as_str(), m[0].label, m[0].cue_type), (Some(1.0), "M", Some(3), Some(CueType::Event)));
|
||||
assert_eq!((m[0].duration_seconds, m[0].cue_point_name.as_str(), m[0].cue_params.len()), (Some(0.0), "", 0));
|
||||
// 348: cue point name CueN, navigation cue (5).
|
||||
let m = skip!(layer_markers("348-marker-layer-navigation-cue.aep"));
|
||||
assert_eq!((m[0].cue_type, m[0].cue_point_name.as_str(), m[0].label), (Some(CueType::Navigation), "CueN", Some(0)));
|
||||
// 349: CueE, event cue, parameters speaker = A and n = 2.
|
||||
let m = skip!(layer_markers("349-marker-layer-event-cue-params.aep"));
|
||||
assert_eq!((m[0].cue_type, m[0].cue_point_name.as_str(), m[0].comment.as_str()), (Some(CueType::Event), "CueE", "M"));
|
||||
assert_eq!(m[0].cue_params, [("speaker".to_string(), "A".to_string()), ("n".to_string(), "2".to_string())]);
|
||||
assert_eq!((m[0].chapter.as_str(), m[0].url.as_str(), m[0].frame_target.as_str()), ("", "", ""));
|
||||
// 249 (batch 2): duration 1 s, the five strings, event cue, no parameters, label 0.
|
||||
let m = skip!(layer_markers("249-marker-layer-full.aep"));
|
||||
assert_eq!((m[0].cue_type, m[0].label, m[0].duration_seconds, m[0].cue_params.len()), (Some(CueType::Event), Some(0), Some(1.0), 0));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ footage items (126, 350, 352, 354)
|
||||
|
||||
#[test]
|
||||
fn audio_footage_item() {
|
||||
let bytes = fixture!("350-footage-wav-imported.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
// The solid L and the WAV (item id 32 in the single-case file): the WAV is not used in a layer.
|
||||
let footage: Vec<_> = project.all_items().into_iter().filter(|i| i.kind() == Some(ItemKind::Footage)).collect();
|
||||
assert_eq!(footage.len(), 2);
|
||||
let item = footage.iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).unwrap();
|
||||
let f = item.footage().unwrap();
|
||||
assert_eq!(f.file_type, "WAVE");
|
||||
assert_eq!((f.width, f.height, f.is_solid), (0, 0, false));
|
||||
assert_eq!(f.duration, Some(rat(48000, 48000)));
|
||||
assert_eq!((f.audio_sample_rate, f.file_size, f.bits_per_pixel, f.native_frame_rate), (Some(48000.0), 96044, 0, 0));
|
||||
assert!(!f.is_sequence && f.sequence_frame_count().is_none());
|
||||
// The combined file stores no display name for the item (the single-case file had
|
||||
// "test-tone.wav"); the path names the file.
|
||||
assert_eq!(item.label(), Some(7));
|
||||
assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test-tone.wav")));
|
||||
// The solid has no sample rate.
|
||||
let solid = footage.iter().find(|i| i.footage().is_some_and(|f| f.is_solid)).unwrap().footage().unwrap();
|
||||
assert_eq!((solid.audio_sample_rate, solid.duration.map(|d| d.num), solid.file_size), (None, Some(0), 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_sequence_is_one_item() {
|
||||
for name in ["352-footage-pngseq-imported.aep", "354-footage-pngseq-timeremap.aep"] {
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let footage: Vec<_> = project.all_items().into_iter().filter(|i| i.kind() == Some(ItemKind::Footage)).collect();
|
||||
assert_eq!(footage.len(), 2, "{name}: the solid and ONE sequence item");
|
||||
let item = footage.iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).unwrap();
|
||||
let f = item.footage().unwrap();
|
||||
assert_eq!((f.width, f.height, f.is_solid), (64, 64, false), "{name}");
|
||||
assert_eq!(f.duration, Some(rat(3, 30)), "{name}");
|
||||
assert_eq!((f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate), (30, 24, 504, None), "{name}");
|
||||
assert!(f.is_sequence, "{name}");
|
||||
assert_eq!(f.sequence_frame_count(), Some(3), "{name}");
|
||||
// The first file name sits in opti; the alias points at the sequence folder.
|
||||
assert_eq!(f.name.as_deref(), Some("seq_001.png"), "{name}");
|
||||
assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test-seq")), "{name}");
|
||||
assert_eq!(item.label(), Some(3), "{name}");
|
||||
}
|
||||
// The single png still (126): 32 bits per pixel, 149 bytes, not a sequence, duration 0.
|
||||
let bytes = fixture!("126-footage-png-layer.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let f = project.all_items().into_iter().filter_map(|i| i.footage()).find(|f| !f.is_solid).unwrap();
|
||||
assert_eq!((f.bits_per_pixel, f.file_size, f.native_frame_rate, f.is_sequence), (32, 149, 0, false));
|
||||
assert_eq!(f.duration.map(|d| d.num), Some(0));
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
//! Batch 5 checks of fields decoded before (markers with several entries and fractional
|
||||
//! durations, 509 and 510).
|
||||
|
||||
use crate::container::helpers::{first_comp, open};
|
||||
use effectcraft_aep::Project;
|
||||
|
||||
#[test]
|
||||
fn two_composition_markers_in_time_order_with_label_and_duration() {
|
||||
let bytes = fixture!("509-marker-comp-two.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let m = first_comp(&project).markers();
|
||||
let got: Vec<_> = m.iter().map(|m| (m.time_units, m.comment.as_str(), m.duration_seconds, m.label)).collect();
|
||||
assert_eq!(got, vec![(25_600, "M1", Some(0.0), Some(2)), (64_000, "M2", Some(0.5), Some(0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fractional_marker_time_and_duration() {
|
||||
let bytes = fixture!("510-marker-layer-0.52-dur0.3.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let layer = comp.layers().next().expect("L");
|
||||
let m = layer.markers();
|
||||
assert_eq!(m.len(), 1);
|
||||
// 0.52 s = 13 312 / 25 600; 0.3 s = 180 / 600.
|
||||
assert_eq!((m[0].time_units, m[0].comment.as_str()), (13_312, "LM"));
|
||||
assert!((m[0].duration_seconds.expect("duration") - 0.3).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// The stored value of the property at `path` (match names) of the first layer.
|
||||
fn shape_value(name: &str, path: &[&str]) -> Option<Option<Vec<f64>>> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let layer = comp.layers().next().expect("S");
|
||||
match layer.properties()?.find(path)? {
|
||||
effectcraft_aep::PropNode::Property(p) => p.static_value(),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const G1: [&str; 2] = ["ADBE Root Vectors Group", "ADBE Vector Group"];
|
||||
|
||||
#[test]
|
||||
fn shape_values_are_stored_as_shown() {
|
||||
let at = |rest: &[&'static str]| -> Vec<&'static str> { G1.iter().chain(rest.iter()).copied().collect() };
|
||||
assert_eq!(
|
||||
skip!(shape_value("451-shape-ellipse-400x300-fill.aep", &at(&["ADBE Vectors Group", "ADBE Vector Shape - Ellipse", "ADBE Vector Ellipse Size"]))),
|
||||
Some(vec![400.0, 300.0])
|
||||
);
|
||||
assert_eq!(
|
||||
skip!(shape_value("451-shape-ellipse-400x300-fill.aep", &at(&["ADBE Vectors Group", "ADBE Vector Graphic - Fill", "ADBE Vector Fill Color"]))),
|
||||
Some(vec![255.0, 0.0, 255.0, 0.0])
|
||||
);
|
||||
// Group scale in percent, not a fraction.
|
||||
assert_eq!(skip!(shape_value("457-shape-group-scale-50-80.aep", &at(&["ADBE Vector Transform Group", "ADBE Vector Scale"]))), Some(vec![50.0, 80.0]));
|
||||
assert_eq!(
|
||||
skip!(shape_value("464-shape-stroke-opacity-50.aep", &at(&["ADBE Vectors Group", "ADBE Vector Graphic - Stroke", "ADBE Vector Stroke Opacity"]))),
|
||||
Some(vec![50.0])
|
||||
);
|
||||
assert_eq!(
|
||||
skip!(shape_value("467-shape-trim-end-70.aep", &at(&["ADBE Vectors Group", "ADBE Vector Filter - Trim", "ADBE Vector Trim End"]))),
|
||||
Some(vec![70.0])
|
||||
);
|
||||
assert_eq!(
|
||||
skip!(shape_value("469-shape-trim-type-2.aep", &at(&["ADBE Vectors Group", "ADBE Vector Filter - Trim", "ADBE Vector Trim Type"]))),
|
||||
Some(vec![2.0])
|
||||
);
|
||||
assert_eq!(
|
||||
skip!(shape_value("471-shape-rect-roundness-30.aep", &at(&["ADBE Vectors Group", "ADBE Vector Shape - Rect", "ADBE Vector Rect Roundness"]))),
|
||||
Some(vec![30.0])
|
||||
);
|
||||
assert_eq!(
|
||||
skip!(shape_value("473-shape-star-points-6.aep", &at(&["ADBE Vectors Group", "ADBE Vector Shape - Star", "ADBE Vector Star Points"]))),
|
||||
Some(vec![6.0])
|
||||
);
|
||||
// The shape layer's own anchor: pixels as stored.
|
||||
assert_eq!(skip!(shape_value("462-shape-layer-anchor-10-20.aep", &["ADBE Transform Group", "ADBE Anchor Point"])), Some(vec![10.0, 20.0, 0.0]));
|
||||
// A new Trim Paths and every default item of 519 have no record.
|
||||
for item in
|
||||
["ADBE Vector Shape - Rect", "ADBE Vector Shape - Ellipse", "ADBE Vector Shape - Star", "ADBE Vector Graphic - Fill", "ADBE Vector Filter - Trim"]
|
||||
{
|
||||
let bytes = fixture!("519-shape-all-items-default.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let layer = comp.layers().next().expect("S");
|
||||
let Some(effectcraft_aep::PropNode::Group(g)) = layer.properties().and_then(|p| p.find(&at(&["ADBE Vectors Group", item]))) else { panic!("{item}") };
|
||||
assert!(g.entries().iter().all(|e| !matches!(e.node, effectcraft_aep::PropNode::Property(p) if p.flags() == Some(1))), "{item} has a value record");
|
||||
}
|
||||
}
|
||||
|
||||
/// The baseline option of the first style run of the first text layer.
|
||||
fn script_of(name: &str) -> Option<effectcraft_aep::FontBaseline> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let layer = comp.layers().find(|l| l.text_document().is_some()).expect("a text layer");
|
||||
let doc = layer.text_document().expect("document");
|
||||
assert!(doc.undecoded_style_fields.is_empty(), "{name}: {:?}", doc.undecoded_style_fields);
|
||||
doc.style_runs.first().expect("a run").baseline
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn superscript_and_subscript_are_style_slot_13() {
|
||||
use effectcraft_aep::FontBaseline;
|
||||
// The character state the corpus was made in is superscript (526, and 243, 517).
|
||||
assert_eq!(skip!(script_of("526-text-point-HHHH-default.aep")), FontBaseline::Superscript);
|
||||
assert_eq!(skip!(script_of("243-text-multiline-A-CR-B.aep")), FontBaseline::Superscript);
|
||||
assert_eq!(skip!(script_of("527-text-point-HHHH-baseline-normal.aep")), FontBaseline::Normal);
|
||||
assert_eq!(skip!(script_of("528-text-point-HHHH-baseline-subscript.aep")), FontBaseline::Subscript);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapping_box_text() {
|
||||
let bytes = fixture!("517-text-box-600x400-wrap.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let doc = comp.layers().find_map(|l| l.text_document()).expect("text");
|
||||
let b = doc.text_box.expect("box text");
|
||||
assert_eq!((b.x, b.y, b.width, b.height), (-300.0, -200.0, 600.0, 400.0));
|
||||
assert_eq!(doc.raw_text, "The quick brown fox jumps over the lazy dog and keeps running far away\r");
|
||||
assert_eq!(doc.style_runs[0].font_size, 100.0);
|
||||
}
|
||||
|
||||
fn layer_l<T>(name: &str, f: impl Fn(&effectcraft_aep::Layer<'_, '_>) -> T) -> Option<T> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let layer = comp.layers().next().expect("the solid L, the only layer");
|
||||
f(&layer)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orientation_is_otst_otda() {
|
||||
let o = skip!(layer_l("488-layer-3d-orientation-10-20-30.aep", |l| l.orientation())).expect("orientation");
|
||||
assert_eq!((o.degrees, o.animated, o.has_expression), ([10.0, 20.0, 30.0], false, false));
|
||||
for name in ["485-layer-3d-on.aep", "486-layer-3d-rotx-30.aep", "487-layer-3d-roty-45.aep"] {
|
||||
assert_eq!(skip!(layer_l(name, |l| l.orientation())), None, "{name}: absent at the default");
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
//! Cases of the 600 series (sessions X1 / X2): a renamed effect instance, a composition that shows
|
||||
//! two precompositions, image sequences, project settings, a conformed clip and more still types.
|
||||
//! Every expected value is the one the case was made with (its MANIFEST row).
|
||||
|
||||
use crate::container::helpers::open;
|
||||
use effectcraft_aep::Project;
|
||||
|
||||
#[test]
|
||||
fn a_renamed_effect_keeps_its_name_in_the_value_group() {
|
||||
let bytes = fixture!("610-fx-tint-named-My-Tint.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = project.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
|
||||
let layer = comp.layers().next().expect("layer");
|
||||
let fx = layer.effects();
|
||||
assert_eq!(fx.len(), 1);
|
||||
assert_eq!(fx[0].match_name(), "ADBE Tint");
|
||||
// fnam keeps the effect's own name, the instance name is the value group's tdsn.
|
||||
assert_eq!(fx[0].name().as_deref(), Some("Tint"));
|
||||
assert_eq!(fx[0].user_name().as_deref(), Some("My Tint"));
|
||||
assert_eq!(fx[0].display_name().as_deref(), Some("My Tint"));
|
||||
// An unnamed instance (356) shows the effect's name.
|
||||
let bytes = fixture!("356-fx-tint-default.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = project.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
|
||||
let fx = comp.layers().next().expect("layer").effects();
|
||||
assert_eq!(fx[0].user_name(), None);
|
||||
assert_eq!(fx[0].display_name().as_deref(), Some("Tint"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composition_counts_the_compositions_it_shows() {
|
||||
let bytes = fixture!("601-precomp-two-comps-in-C.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let items = project.all_items();
|
||||
let id = |n: &str| items.iter().find(|i| i.display_name().as_deref() == Some(n)).and_then(|i| i.id()).expect(n);
|
||||
let c = items.iter().find(|i| i.display_name().as_deref() == Some("C")).expect("C");
|
||||
// The list holds each used composition once (in no particular order).
|
||||
let mut used = c.used_item_ids();
|
||||
used.sort();
|
||||
let mut want = vec![id("P30"), id("Q")];
|
||||
want.sort();
|
||||
assert_eq!(used, want);
|
||||
let idpc = c.chunk().child(b"idpc").and_then(|x| x.bytes()).expect("idpc");
|
||||
assert_eq!(&idpc[..4], &2u32.to_le_bytes());
|
||||
// The precomposition layers: P30 640x360 30 fps 3 s, Q 320x240 25 fps 2 s.
|
||||
let comp = c.comp().expect("comp");
|
||||
let sizes: Vec<_> = comp.layers().filter_map(|l| project.layer_source_size(&l)).collect();
|
||||
assert_eq!(sizes, vec![(320, 240), (640, 360), (1920, 1080)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_sequence_knows_its_numbering() {
|
||||
// 603: shot_0101.exr .. shot_0103.exr imported as a sequence (64x48, 3 frames at 30 fps).
|
||||
let bytes = fixture!("603-footage-exrseq-0101-as-layer.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let item = project.all_items().into_iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).expect("sequence");
|
||||
let f = item.footage().expect("footage");
|
||||
assert_eq!((f.file_type.as_str(), f.width, f.height, f.native_frame_rate, f.is_sequence), ("oEXR", 64, 48, 30, true));
|
||||
assert_eq!(f.sequence_frame_count(), Some(3));
|
||||
let s = item.sequence_info().expect("numbering");
|
||||
assert_eq!((s.prefix.as_str(), s.suffix.as_str(), s.start, s.end, s.digits), ("shot_", ".exr", 101, 103, 4));
|
||||
assert_eq!(s.file_name(101), "shot_0101.exr");
|
||||
// A still has no numbering (000: the solid; the base has no other footage).
|
||||
let bytes = fixture!("126-footage-png-layer.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
assert!(project.all_items().iter().all(|i| i.sequence_info().is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_settings_are_read_from_the_header_chunks() {
|
||||
use effectcraft_aep::{ProjectSettings, TimeDisplay, WorkingSpace};
|
||||
let read = |name: &str| {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
ProjectSettings::read(&file)
|
||||
})
|
||||
};
|
||||
// The base (620 = 000): 32 bpc, sRGB, gamma 2.2, both linear switches off, compensation on,
|
||||
// timecode, frames from 0.
|
||||
let base = skip!(read("000-base.aep"));
|
||||
assert_eq!(
|
||||
base,
|
||||
ProjectSettings {
|
||||
bits_per_channel: Some(32),
|
||||
working_space: Some(WorkingSpace::Profile("sRGB IEC61966-2.1".into())),
|
||||
working_gamma_24: Some(false),
|
||||
linearize: false,
|
||||
blend_linear: false,
|
||||
scene_compensation: Some(true),
|
||||
time_display: Some(TimeDisplay::Timecode),
|
||||
frame_start: Some(0),
|
||||
}
|
||||
);
|
||||
// A project has one value per setting, so the settings cases (MANIFEST 621-634) share three
|
||||
// files: each holds the base with the changes of all its cases (tests/fixtures/CASES.md).
|
||||
let a = ProjectSettings {
|
||||
bits_per_channel: Some(8),
|
||||
working_space: Some(WorkingSpace::None),
|
||||
working_gamma_24: Some(true),
|
||||
scene_compensation: Some(false),
|
||||
time_display: Some(TimeDisplay::Frames),
|
||||
frame_start: Some(1),
|
||||
..base.clone()
|
||||
};
|
||||
let b = ProjectSettings { linearize: true, blend_linear: true, time_display: Some(TimeDisplay::FeetFrames { frames_per_foot: 16 }), ..base.clone() };
|
||||
// The file of 622, 634 and 902 is Rec.709: After Effects 26.2.1 stored the profile without its
|
||||
// name, so the name is the profile's own description.
|
||||
let c = ProjectSettings {
|
||||
bits_per_channel: Some(16),
|
||||
working_space: Some(WorkingSpace::Profile("Rec.709 Gamma 2.4".into())),
|
||||
time_display: Some(TimeDisplay::FeetFrames { frames_per_foot: 40 }),
|
||||
..base.clone()
|
||||
};
|
||||
for (names, want) in [
|
||||
(
|
||||
&[
|
||||
"621-settings-bpc-8.aep",
|
||||
"623-settings-workingspace-none.aep",
|
||||
"625-settings-gamma-2.4.aep",
|
||||
"628-settings-scene-compensation-off.aep",
|
||||
"629-settings-time-display-frames.aep",
|
||||
"630-settings-frame-start-1.aep",
|
||||
][..],
|
||||
a,
|
||||
),
|
||||
(&["632-settings-linearize-and-blend-linear.aep", "633-settings-feet-frames-35.aep"][..], b),
|
||||
(&["622-settings-bpc-16.aep", "634-settings-feet-frames-16.aep", "902-settings-rec709-16bpc-steps-png-grey-solid.aep"][..], c),
|
||||
] {
|
||||
for name in names {
|
||||
assert_eq!(skip!(read(name)), want, "{name}");
|
||||
}
|
||||
} // nnhd repeats the depth at byte 24.
|
||||
for (name, v) in [("621-settings-bpc-8.aep", 0u8), ("622-settings-bpc-16.aep", 1), ("000-base.aep", 2)] {
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
assert_eq!(file.chunk(b"nnhd").and_then(|c| c.bytes()).and_then(|b| b.get(24).copied()), Some(v), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conformed_clip_keeps_its_native_rate_and_frames() {
|
||||
// 645: the 25 fps, 25-frame mp4 of 606 conformed to 30 fps; 644 the same file unconformed.
|
||||
let read = |name: &str| {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let item = project.all_items().into_iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).expect("clip");
|
||||
let f = item.footage().expect("footage");
|
||||
(f.native_frame_rate, item.conform_frame_rate(), f.duration.map(|d| (d.num, d.den)))
|
||||
})
|
||||
};
|
||||
assert_eq!(skip!(read("645-footage-mp4-conform-30.aep")), (25, Some(30), Some((25, 25))));
|
||||
// Not conformed (the exr sequence 603, the stills of 650-653).
|
||||
assert_eq!(skip!(read("603-footage-exrseq-0101-as-layer.aep")).1, None);
|
||||
for name in ["650-footage-tga-still-as-layer.aep", "651-footage-psd-flat-as-layer.aep", "652-footage-ai-as-layer.aep", "653-footage-eps-as-layer.aep"] {
|
||||
assert_eq!(skip!(read(name)).1, None, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn still_footage_of_four_more_types() {
|
||||
// 650-653: a 64 x 48 tga, a flat psd, an ai and an eps imported as footage (MANIFEST); ai and
|
||||
// eps share the type tag `TEXT`.
|
||||
for (name, tag) in [
|
||||
("650-footage-tga-still-as-layer.aep", "TPIC"),
|
||||
("651-footage-psd-flat-as-layer.aep", "8BPS"),
|
||||
("652-footage-ai-as-layer.aep", "TEXT"),
|
||||
("653-footage-eps-as-layer.aep", "TEXT"),
|
||||
] {
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let f = project.all_items().into_iter().find_map(|i| i.footage().filter(|f| !f.is_solid)).expect(name);
|
||||
assert_eq!((f.width, f.height, f.native_frame_rate, f.is_sequence), (64, 48, 0, false), "{name}");
|
||||
assert_eq!(f.file_type, tag, "{name}");
|
||||
let ext = name.get(12..).and_then(|r| r.split('-').next()).unwrap_or_default();
|
||||
assert!(f.path.as_deref().is_some_and(|p| p.ends_with(&format!("still.{ext}"))), "{name}: {:?}", f.path);
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
//! Ease of Anchor Point, effect point and colour, and mask path keys (597-599, 700, 730); light
|
||||
//! type codes (701, 702).
|
||||
|
||||
use crate::container::helpers::{first_comp, layer_shown_as, open};
|
||||
use effectcraft_aep::{KeyframeKind, Project};
|
||||
|
||||
#[test]
|
||||
fn mask_path_keys_keep_their_ease_at_byte_24() {
|
||||
for (name, first_out, last_in) in [("599-key-mask-path-ease-infl75.aep", 0.75, 0.75), ("700-key-mask-path-ease-out20-in50.aep", 0.2, 0.5)] {
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = layer_shown_as(&project, &comp, "L");
|
||||
let atoms = layer.mask_atoms();
|
||||
let list = atoms[0].path.as_ref().and_then(|p| p.keys()).expect("path keys");
|
||||
let keys: Vec<_> = list.keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert_eq!(keys[0].kind(), KeyframeKind::MaskPath);
|
||||
let (a, b) = (keys[0].ease().unwrap(), keys[1].ease().unwrap());
|
||||
assert_eq!((a.out_speed, a.out_influence), (0.0, first_out), "{name}");
|
||||
assert_eq!((b.in_speed, b.in_influence), (0.0, last_in), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spatial_speed_is_divided_by_the_layer_height() {
|
||||
// 597: 1920x1080 L, out speed 50 px/s stored as 50 / 1080; 730: 400x800 P, 50 / 800.
|
||||
for (name, layer, h) in [("597-key-anchor-ease-out50-40-in30-60.aep", "L", 1080.0), ("730-key-anchor-ease-on-400x800-solid.aep", "P", 800.0)] {
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let props = layer_shown_as(&project, &comp, layer).properties().unwrap();
|
||||
let Some(effectcraft_aep::PropNode::Group(t)) = props.get("ADBE Transform Group") else { panic!() };
|
||||
let Some(effectcraft_aep::PropNode::Property(a)) = t.get("ADBE Anchor Point") else { panic!() };
|
||||
let keys: Vec<_> = a.keys().unwrap().keyframes().collect();
|
||||
let (e0, e1) = (keys[0].ease().unwrap(), keys[1].ease().unwrap());
|
||||
assert!((e0.out_speed * h - 50.0).abs() < 1e-9 && (e1.in_speed * h - 30.0).abs() < 1e-9, "{name}: {e0:?} {e1:?}");
|
||||
assert_eq!((e0.out_influence, e1.in_influence), (0.4, 0.6));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_and_ambient_lights_have_codes_0_and_3() {
|
||||
use effectcraft_aep::{LayerType, LightType};
|
||||
for (name, want) in [("701-light-parallel-int80-color.aep", LightType::Parallel), ("702-light-ambient-int50-color.aep", LightType::Ambient)] {
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let light = comp.layers().find(|l| l.header().is_some_and(|h| h.layer_type == LayerType::Light)).expect("light");
|
||||
assert_eq!(light.header().unwrap().light_type(), Some(want), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyed_orientation_pairs_records_and_values() {
|
||||
use effectcraft_aep::Interpolation;
|
||||
let bytes = fixture!("703-key-orientation-0-to-10-20-30-linear.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = layer_shown_as(&project, &comp, "L");
|
||||
assert!(layer.orientation().unwrap().animated);
|
||||
let keys = layer.orientation_keys();
|
||||
assert_eq!(keys.iter().map(|k| (k.time_units, k.degrees)).collect::<Vec<_>>(), [(0, [0.0; 3]), (51200, [10.0, 20.0, 30.0])]);
|
||||
assert!(keys.iter().all(|k| k.interpolation_in == Interpolation::Linear && k.interpolation_out == Interpolation::Linear));
|
||||
}
|
||||
@@ -1,292 +0,0 @@
|
||||
//! Effect instances: match names, parameter lists from `parT`/`pard` and stored values, checked
|
||||
//! against the values the corpus was made with (its MANIFEST).
|
||||
|
||||
use crate::container::helpers::{base_layer, first_comp, open};
|
||||
use effectcraft_aep::{Effect, ParamKind, ParamValue, Project};
|
||||
|
||||
/// Runs `f` on the single effect of the solid `L` in a fixture.
|
||||
fn with_effect<R>(name: &str, f: impl FnOnce(&Effect<'_, '_>) -> R) -> Option<R> {
|
||||
with_effect_in(name, |_, _, e| f(e))
|
||||
}
|
||||
|
||||
/// Runs `f` on the project, the solid `L` and its single effect in a fixture.
|
||||
fn with_effect_in<R>(name: &str, f: impl FnOnce(&Project<'_, '_>, &effectcraft_aep::Layer<'_, '_>, &Effect<'_, '_>) -> R) -> Option<R> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let effects = layer.effects();
|
||||
assert_eq!(effects.len(), 1, "{name}");
|
||||
f(&project, &layer, &effects[0])
|
||||
})
|
||||
}
|
||||
|
||||
fn kinds(e: &Effect<'_, '_>) -> Vec<(ParamKind, String)> {
|
||||
e.params().into_iter().map(|p| (p.kind, p.name)).collect()
|
||||
}
|
||||
|
||||
fn approx(v: Option<ParamValue>, expected: f64) {
|
||||
match v {
|
||||
Some(ParamValue::Number(n)) => assert!((n - expected).abs() < 1e-9, "{n} != {expected}"),
|
||||
other => panic!("{other:?} is not the number {expected}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_effects_without_a_parade_entry() {
|
||||
let bytes = fixture!("000-base.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
assert!(base_layer(&first_comp(&project)).effects().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slider_control_with_a_stored_value() {
|
||||
// 071: Slider Control, Slider = 77.
|
||||
skip!(with_effect_in("071-fx-slider-value77.aep", |_, layer, e| {
|
||||
assert_eq!((e.match_name(), e.name().as_deref()), ("ADBE Slider Control", Some("Slider Control")));
|
||||
assert_eq!(e.declared_param_count(), Some(3));
|
||||
assert_eq!(kinds(e), [(ParamKind::Layer, String::new()), (ParamKind::FloatSlider, "Slider".to_string()), (ParamKind::NoData, String::new())]);
|
||||
let params = e.params();
|
||||
assert_eq!(params[1].match_name, "ADBE Slider Control-0001");
|
||||
assert_eq!(params[2].match_name, "ADBE Effect Built In Params");
|
||||
assert_eq!(params[1].stored_value(), Some(ParamValue::Number(77.0)));
|
||||
assert_eq!(params[1].value(), Some(ParamValue::Number(77.0)));
|
||||
// The pard default of the slider is 0 (070 has the untouched control).
|
||||
assert_eq!(params[1].pard_default(), Some(ParamValue::Number(0.0)));
|
||||
// The input layer parameter has a value record of its own: its `tdpi` holds the id of the layer that owns the effect.
|
||||
assert_eq!(params[0].stored_value(), Some(ParamValue::Layer(layer.id().unwrap())));
|
||||
assert_eq!(params[0].pard().len(), 148);
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_control_stores_argb_doubles() {
|
||||
// 073: Color -> [0.2, 0.6, 1], stored as [255, 51, 153, 255] (alpha first).
|
||||
skip!(with_effect("073-fx-color-0.2-0.6-1.aep", |e| {
|
||||
assert_eq!((e.match_name(), e.name().as_deref()), ("ADBE Color Control", Some("Color Control")));
|
||||
assert_eq!(kinds(e), [(ParamKind::Layer, String::new()), (ParamKind::Color, "Color".to_string()), (ParamKind::NoData, String::new())]);
|
||||
let color = e.params()[1].value();
|
||||
let Some(ParamValue::Argb([a, r, g, b])) = color else { panic!("{color:?}") };
|
||||
for (got, want) in [(a, 1.0), (r, 0.2), (g, 0.6), (b, 1.0)] {
|
||||
assert!((got - want).abs() < 1e-6, "{color:?}");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropdown_menu_items_and_default() {
|
||||
// 077: Dropdown Menu Control with the default items.
|
||||
skip!(with_effect("077-fx-dropdown-default.aep", |e| {
|
||||
// A dropdown's match name is a fresh `Pseudo/@@` + 22-character id for every instance.
|
||||
assert!(e.match_name().starts_with("Pseudo/@@") && e.match_name().len() == 31, "{}", e.match_name());
|
||||
assert_eq!(e.name().as_deref(), Some("Dropdown Menu Control"));
|
||||
assert_eq!(kinds(e), [(ParamKind::Layer, String::new()), (ParamKind::Popup, "Menu".to_string()), (ParamKind::NoData, String::new())]);
|
||||
let menu = &e.params()[1];
|
||||
assert_eq!(menu.items.as_deref(), Some(&["Item 1".to_string(), "Item 2".to_string(), "Item 3".to_string()][..]));
|
||||
assert_eq!(menu.pard_default(), Some(ParamValue::Index(1)));
|
||||
// The choice count is the u16 at byte 60 of pard.
|
||||
assert_eq!(u16::from_be_bytes([menu.pard()[60], menu.pard()[61]]), 3);
|
||||
// No other parameter has items.
|
||||
assert!(e.params().iter().filter(|p| p.index != 1).all(|p| p.items.is_none()));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_shadow_defaults_come_from_pard() {
|
||||
// 080: Drop Shadow at its defaults (opacity 50 % = 127.5 of 255, direction 135, distance 5, softness 0).
|
||||
skip!(with_effect("080-fx-dropshadow-default.aep", |e| {
|
||||
assert_eq!((e.match_name(), e.name().as_deref()), ("ADBE Drop Shadow", Some("Drop Shadow")));
|
||||
let k: Vec<_> = e.params().into_iter().map(|p| (p.kind, p.name)).collect();
|
||||
let expected = [
|
||||
(ParamKind::Layer, ""),
|
||||
(ParamKind::Color, "Shadow Color"),
|
||||
(ParamKind::FixedSlider, "Opacity"),
|
||||
(ParamKind::Angle, "Direction"),
|
||||
(ParamKind::FixedSlider, "Distance"),
|
||||
(ParamKind::FixedSlider, "Softness"),
|
||||
(ParamKind::Checkbox, "Shadow Only"),
|
||||
(ParamKind::NoData, ""),
|
||||
];
|
||||
assert_eq!(k, expected.map(|(kind, n)| (kind, n.to_string())));
|
||||
let p = e.params();
|
||||
approx(p[2].value(), 127.5);
|
||||
approx(p[3].value(), 135.0);
|
||||
approx(p[4].value(), 5.0);
|
||||
approx(p[5].value(), 0.0);
|
||||
// A checkbox without a record is off; the shadow colour default (ARGB bytes in pard) is black.
|
||||
assert_eq!(p[6].value(), Some(ParamValue::Bool(false)));
|
||||
assert_eq!(p[1].value(), Some(ParamValue::Argb([1.0, 0.0, 0.0, 0.0])));
|
||||
}));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- batch 2 (defaults and values)
|
||||
|
||||
fn param<'f, 'a>(e: &Effect<'f, 'a>, name: &str) -> effectcraft_aep::EffectParam<'f, 'a> {
|
||||
e.params().into_iter().find(|p| p.name == name).unwrap_or_else(|| panic!("no parameter {name}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_blur_default_is_the_pard_default_25() {
|
||||
// 214: Gaussian Blur, all parameters default. The file has no value record and a pard default of 25
|
||||
// (the manifest says 0; the files only ever contain 25, see docs/aep-format.md).
|
||||
skip!(with_effect("214-fx-gaussianblur-default.aep", |e| {
|
||||
assert_eq!(e.match_name(), "ADBE Gaussian Blur 2");
|
||||
let blur = param(e, "Blurriness");
|
||||
assert_eq!(blur.kind, ParamKind::FloatSlider);
|
||||
assert!(blur.stored().is_none());
|
||||
assert_eq!(blur.stored_value(), None);
|
||||
assert_eq!(blur.value(), Some(ParamValue::Number(25.0)));
|
||||
assert_eq!(f64::from_be_bytes(blur.pard()[56..64].try_into().unwrap()), 25.0);
|
||||
assert_eq!(f32::from_be_bytes(blur.pard()[120..124].try_into().unwrap()), 25.0);
|
||||
// Dimensions: Horizontal and Vertical (the first item of the popup); Repeat Edge Pixels: on
|
||||
// (its pard default is 1; After Effects reads a fresh Gaussian Blur back with Repeat Edge
|
||||
// Pixels 1, 417; the corpus manifest's "off" for 214 was wrong).
|
||||
let dims = param(e, "Blur Dimensions");
|
||||
assert_eq!(dims.kind, ParamKind::Popup);
|
||||
assert_eq!(dims.value(), Some(ParamValue::Index(1)));
|
||||
assert_eq!(dims.items.as_ref().and_then(|i| i.first()).map(String::as_str), Some("Horizontal and Vertical"));
|
||||
// The last parameter is the Repeat Edge Pixels checkbox (its label is not in pard).
|
||||
let edge = &e.params()[3];
|
||||
assert_eq!(edge.kind, ParamKind::Checkbox);
|
||||
assert!(edge.stored().is_none());
|
||||
assert_eq!(edge.value(), Some(ParamValue::Bool(true)));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_blur_40_adds_a_value_record_and_leaves_pard_at_the_default() {
|
||||
// 216: Blurriness 40.
|
||||
// The case takes its definitions from the project copy (an earlier Gaussian Blur of its file).
|
||||
skip!(with_effect_in("216-fx-gaussianblur-40.aep", |project, _, e| {
|
||||
let blur = project.effect_params(e).into_iter().find(|p| p.name == "Blurriness").unwrap();
|
||||
assert_eq!(blur.stored().unwrap().flags(), Some(1));
|
||||
assert_eq!(blur.stored_value(), Some(ParamValue::Number(40.0)));
|
||||
assert_eq!(blur.value(), Some(ParamValue::Number(40.0)));
|
||||
// pard holds the default, not the current value.
|
||||
assert_eq!(blur.pard_default(), Some(ParamValue::Number(25.0)));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_defaults_come_from_pard() {
|
||||
// 215: Fill with the default colour (red) and opacity (100 %); the file has no value records for them.
|
||||
skip!(with_effect("215-fx-fill-default.aep", |e| {
|
||||
assert_eq!(e.match_name(), "ADBE Fill");
|
||||
let color = param(e, "Color");
|
||||
assert_eq!(color.kind, ParamKind::Color);
|
||||
assert!(color.stored().is_none());
|
||||
assert_eq!(&color.pard()[56..60], [0xff, 0xff, 0x00, 0x00]);
|
||||
assert_eq!(color.value(), Some(ParamValue::Argb([1.0, 1.0, 0.0, 0.0])));
|
||||
let opacity = param(e, "Opacity");
|
||||
assert_eq!(opacity.kind, ParamKind::FixedSlider);
|
||||
assert!(opacity.stored().is_none());
|
||||
assert_eq!(opacity.value(), Some(ParamValue::Number(1.0)));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkbox_point_and_angle_values() {
|
||||
// 217: Checkbox 0 -> 1 (stored 1.0).
|
||||
skip!(with_effect("217-fx-checkbox-on.aep", |e| {
|
||||
let p = param(e, "Checkbox");
|
||||
assert_eq!(p.kind, ParamKind::Checkbox);
|
||||
assert_eq!(p.stored_value(), Some(ParamValue::Bool(true)));
|
||||
assert_eq!(p.value(), Some(ParamValue::Bool(true)));
|
||||
assert_eq!(p.stored().unwrap().static_value(), Some(vec![1.0]));
|
||||
}));
|
||||
// 218: Point -> [111, 222], stored as a fraction of the layer size (the layer is 1920x1080).
|
||||
skip!(with_effect("218-fx-point-111-222.aep", |e| {
|
||||
let p = param(e, "Point");
|
||||
assert_eq!(p.kind, ParamKind::Point);
|
||||
let Some(ParamValue::Point([x, y])) = p.value() else { panic!("{:?}", p.value()) };
|
||||
assert!((x - 111.0 / 1920.0).abs() < 1e-12 && (y - 222.0 / 1080.0).abs() < 1e-12, "{x} {y}");
|
||||
assert!((x * 1920.0 - 111.0).abs() < 1e-9 && (y * 1080.0 - 222.0).abs() < 1e-9);
|
||||
}));
|
||||
// 219: Angle -> 90, stored as plain degrees.
|
||||
skip!(with_effect("219-fx-angle-90.aep", |e| {
|
||||
let p = param(e, "Angle");
|
||||
assert_eq!(p.kind, ParamKind::Angle);
|
||||
assert_eq!(p.stored_value(), Some(ParamValue::Number(90.0)));
|
||||
assert_eq!(p.value(), Some(ParamValue::Number(90.0)));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_control_refers_to_a_layer_by_id() {
|
||||
// 220: a new Null on top (layer index 1); L (now index 2) gets a Layer Control with Layer = 1: the tdpi
|
||||
// next to the value record holds the id of the Null.
|
||||
let bytes = fixture!("220-fx-layercontrol-to-layer1.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let null = comp.layers().next().unwrap();
|
||||
let null_id = null.id().unwrap();
|
||||
assert_ne!(Some(null_id), base_layer(&comp).id());
|
||||
assert!(null.header().unwrap().is_null_object());
|
||||
let layer = base_layer(&comp);
|
||||
let e = &layer.effects()[0];
|
||||
assert_eq!(e.match_name(), "ADBE Layer Control");
|
||||
let p = param(e, "Layer");
|
||||
assert_eq!(p.kind, ParamKind::Layer);
|
||||
assert_eq!(p.stored_value(), Some(ParamValue::Layer(null_id)));
|
||||
// The implicit input layer parameter refers to the layer that owns the effect.
|
||||
assert_eq!(e.params()[0].stored_value(), Some(ParamValue::Layer(layer.id().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curves_and_mesh_warp_data() {
|
||||
// 963: Red (0,0) (128,44) (255,255); 964: RGB (0,0) (62,24) (194,230) (255,255). Every stored
|
||||
// table is the natural spline through its points.
|
||||
for (name, curve, points) in [
|
||||
("963-curves-red-mid-down-on-S.aep", 1usize, vec![(0u8, 0u8), (128, 44), (255, 255)]),
|
||||
("964-curves-rgb-s-curve-on-S.aep", 0, vec![(0, 0), (62, 24), (194, 230), (255, 255)]),
|
||||
] {
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
let project = effectcraft_aep::Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let fx = comp.layers().flat_map(|l| l.effects()).find(|e| e.match_name() == "ADBE CurvesCustom").expect("curves");
|
||||
let data = fx.arbitrary_data("ADBE CurvesCustom-0001").expect("data");
|
||||
let d = effectcraft_aep::CurvesData::parse(data).expect("parse");
|
||||
assert_eq!(d.curves[curve], points, "{name}");
|
||||
assert!(d.curves.iter().enumerate().all(|(i, c)| i == curve || c.as_slice() == effectcraft_aep::CURVE_IDENTITY), "{name}");
|
||||
// Rebuilt from the points, the data is the stored data byte for byte.
|
||||
assert_eq!(d.to_bytes().as_deref(), Some(data), "{name}");
|
||||
}
|
||||
// 985: a 3 x 3 mesh (4 x 4 vertices), vertex (2, 2) moved by (+132, -2) px on 1920 x 1080 with
|
||||
// its handles; the others at their default.
|
||||
let bytes = fixture!("985-meshwarp-3x3-vertex-moved-on-S.aep");
|
||||
let file = open(&bytes);
|
||||
let project = effectcraft_aep::Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let fx = comp.layers().flat_map(|l| l.effects()).find(|e| e.match_name() == "ADBE MESH WARP").expect("mesh");
|
||||
let data = fx.arbitrary_data("ADBE MESH WARP-0004").expect("data");
|
||||
let m = effectcraft_aep::MeshData::parse(data).expect("parse");
|
||||
assert_eq!((m.columns, m.rows, m.vertices.len()), (3, 3, 16));
|
||||
for (k, v) in m.vertices.iter().enumerate() {
|
||||
let (i, j) = (k as u32 % 4, k as u32 / 4);
|
||||
let d = effectcraft_aep::MeshData::default_vertex(3, 3, i, j);
|
||||
let (dx, dy) = if (i, j) == (2, 2) { (132.0 / 1920.0, -2.0 / 1080.0) } else { (0.0, 0.0) };
|
||||
for (a, b) in v.iter().zip(&d) {
|
||||
let moved = if *b == [0.0, 0.0] { [0.0, 0.0] } else { [b[0] + dx, b[1] + dy] };
|
||||
assert!((a[0] - moved[0]).abs() < 2e-6 && (a[1] - moved[1]).abs() < 2e-6, "vertex {i},{j}: {a:?} vs {moved:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(m.to_bytes().as_deref(), Some(data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fx_switch_is_the_value_group_flag() {
|
||||
// fx-switch.aep: two Gaussian Blurs on L, the first switched off in After Effects, the second
|
||||
// added after it and left on (one save).
|
||||
let bytes = skip!(crate::common::try_file("fx-switch.aep"));
|
||||
let file = open(&bytes);
|
||||
let p = Project::new(&file).expect("project");
|
||||
let comp = first_comp(&p);
|
||||
let layer = base_layer(&comp);
|
||||
let fx = layer.effects();
|
||||
assert_eq!(fx.iter().map(|e| e.match_name().to_string()).collect::<Vec<_>>(), ["ADBE Gaussian Blur 2", "ADBE Gaussian Blur 2"]);
|
||||
assert_eq!(fx.iter().map(Effect::enabled).collect::<Vec<_>>(), [Some(false), Some(true)]);
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
//! Batch 4 (cases 356-383): Tint and Gradient Ramp parameters, their defaults, values, keys and
|
||||
//! scales, the effect stack order, and the second instance of an effect type whose `parT` is
|
||||
//! empty. Every expected value is the one the case was made with (its MANIFEST row).
|
||||
|
||||
use crate::container::helpers::{assert_near, base_layer, first_comp, open};
|
||||
use effectcraft_aep::{DefinitionSource, EffectParam, Interpolation, KeyframeKind, ParamKind, ParamValue, Project};
|
||||
|
||||
/// Key time 2 s in the property timescale 25600.
|
||||
const T2: i32 = 51200;
|
||||
|
||||
/// Runs `f` on the project view and the parameters of the single effect of `L`.
|
||||
fn with_params<R>(name: &str, f: impl FnOnce(&Project<'_, '_>, &[EffectParam<'_, '_>]) -> R) -> Option<R> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let effects = layer.effects();
|
||||
assert_eq!(effects.len(), 1, "{name}");
|
||||
// The first instance of a type in the combined file (the case that adds it at its defaults)
|
||||
// keeps its own definitions; the later cases read the project copy.
|
||||
let first = ["356-fx-tint-default.aep", "368-fx-ramp-default.aep", "389-fx-exposure-default.aep"].contains(&name);
|
||||
let want = if first { DefinitionSource::Instance } else { DefinitionSource::Project };
|
||||
assert_eq!(project.definition_source(&effects[0]), want, "{name}");
|
||||
let params = project.effect_params(&effects[0]);
|
||||
f(&project, ¶ms)
|
||||
})
|
||||
}
|
||||
|
||||
fn argb(v: Option<ParamValue>) -> [f64; 4] {
|
||||
match v {
|
||||
Some(ParamValue::Argb(c)) => c,
|
||||
other => panic!("{other:?} is not a colour"),
|
||||
}
|
||||
}
|
||||
|
||||
fn point(v: Option<ParamValue>) -> [f64; 2] {
|
||||
match v {
|
||||
Some(ParamValue::Point(p)) => p,
|
||||
other => panic!("{other:?} is not a point"),
|
||||
}
|
||||
}
|
||||
|
||||
fn number(v: Option<ParamValue>) -> f64 {
|
||||
match v {
|
||||
Some(ParamValue::Number(n)) => n,
|
||||
other => panic!("{other:?} is not a number"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour as the case set it: float32 precision (0.2 becomes 0.20000000298).
|
||||
const F32: f64 = 1e-6;
|
||||
|
||||
// ---------------------------------------------------------------------------- Tint
|
||||
|
||||
#[test]
|
||||
fn tint_parameters_and_defaults() {
|
||||
// 356: Tint with every parameter at its default.
|
||||
let bytes = fixture!("356-fx-tint-default.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let fx = base_layer(&first_comp(&project)).effects();
|
||||
let e = &fx[0];
|
||||
assert_eq!((e.match_name(), e.name().as_deref()), ("ADBE Tint", Some("Tint")));
|
||||
assert_eq!(e.declared_param_count(), Some(6));
|
||||
let p = project.effect_params(e);
|
||||
let kinds: Vec<_> = p.iter().map(|p| (p.kind, p.name.as_str())).collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
(ParamKind::Layer, ""),
|
||||
(ParamKind::Color, "Map Black To"),
|
||||
(ParamKind::Color, "Map White To"),
|
||||
(ParamKind::FixedSlider, "Amount to Tint"),
|
||||
(ParamKind::Button, ""),
|
||||
(ParamKind::NoData, ""),
|
||||
]
|
||||
);
|
||||
assert_eq!(p[4].match_name, "ADBE Tint-0004");
|
||||
// The defaults have alpha 0 (what After Effects reads back: [0,0,0,0] / [1,1,1,0]).
|
||||
assert_eq!(p[1].value(), Some(ParamValue::Argb([0.0, 0.0, 0.0, 0.0])));
|
||||
assert_eq!(p[2].value(), Some(ParamValue::Argb([0.0, 1.0, 1.0, 1.0])));
|
||||
assert!(p[1].stored().is_none() && p[2].stored().is_none() && p[3].stored().is_none());
|
||||
// Amount to Tint: 100 percent, stored as a plain percent (valid max 100).
|
||||
assert_eq!(p[3].value(), Some(ParamValue::Number(100.0)));
|
||||
assert_eq!(p[3].valid_max(), Some(100.0));
|
||||
// Swap Colors: a button whose record always exists and holds no value; its label is in pdnm.
|
||||
assert!(p[4].stored().is_some());
|
||||
assert_eq!(p[4].value(), None);
|
||||
assert_eq!(p[4].is_default(), None);
|
||||
assert_eq!(p[4].items.as_deref(), Some(&["Swap Colors".to_string()][..]));
|
||||
assert!(p.iter().all(|p| !p.borrowed_definition && !p.is_animated()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tint_colour_and_amount_values() {
|
||||
// 357: Map Black To [0.2, 0.4, 0.6], stored with alpha 255.
|
||||
skip!(with_params("357-fx-tint-black-0.2-0.4-0.6.aep", |_, p| {
|
||||
assert_near(&argb(p[1].stored_value()), &[1.0, 0.2, 0.4, 0.6], F32);
|
||||
assert_eq!(p[1].is_default(), Some(false));
|
||||
assert_eq!(p[2].value(), Some(ParamValue::Argb([0.0, 1.0, 1.0, 1.0])));
|
||||
}));
|
||||
// 361: Amount to Tint 0 writes a record with 0.
|
||||
skip!(with_params("361-fx-tint-amount-0.aep", |_, p| {
|
||||
assert_eq!(p[3].stored_value(), Some(ParamValue::Number(0.0)));
|
||||
assert_eq!(p[3].is_default(), Some(false));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tint_keyframes() {
|
||||
// 363: Amount to Tint keyed 20 at 0 s, 80 at 2 s, linear: plain 48-byte records.
|
||||
skip!(with_params("363-fx-tint-amount-2key.aep", |_, p| {
|
||||
let amount = &p[3];
|
||||
assert!(amount.is_animated());
|
||||
assert_eq!(amount.stored_value(), None);
|
||||
let keys: Vec<_> = amount.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert_eq!(keys.iter().map(|k| k.time_units().unwrap()).collect::<Vec<_>>(), [0, T2]);
|
||||
assert_eq!(keys.iter().map(|k| k.scalar_value().unwrap()).collect::<Vec<_>>(), [20.0, 80.0]);
|
||||
assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Plain { components: 1 } && k.interpolation_out() == Some(Interpolation::Linear)));
|
||||
}));
|
||||
// 364: Map White To keyed [1,1,0] -> [0,0,1]: 152-byte colour records, ARGB 0..255.
|
||||
skip!(with_params("364-fx-tint-white-2key.aep", |_, p| {
|
||||
let white = &p[2];
|
||||
assert!(white.is_animated());
|
||||
let keys: Vec<_> = white.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Spatial { components: 4 } && k.raw().len() == 152));
|
||||
assert_eq!(keys.iter().map(|k| k.time_units().unwrap()).collect::<Vec<_>>(), [0, T2]);
|
||||
assert_near(&keys[0].value().unwrap(), &[255.0, 255.0, 255.0, 0.0], 1e-9);
|
||||
assert_near(&keys[1].value().unwrap(), &[255.0, 0.0, 0.0, 255.0], 1e-9);
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_stack_order_is_the_parade_order() {
|
||||
// 366: Gaussian Blur moved above the Tint.
|
||||
let bytes = fixture!("366-fx-blur-then-tint.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let fx = base_layer(&first_comp(&project)).effects();
|
||||
assert_eq!(fx.iter().map(|e| e.match_name()).collect::<Vec<_>>(), ["ADBE Gaussian Blur 2", "ADBE Tint"]);
|
||||
// Both types first appear in earlier cases of the combined file (214, 356), so both read the
|
||||
// project copy, which holds one copy per type.
|
||||
assert!(fx.iter().all(|e| project.definition_source(e) == DefinitionSource::Project));
|
||||
let defs: Vec<String> = project.effect_definitions().into_iter().map(|(m, _)| m).collect();
|
||||
for m in ["ADBE Gaussian Blur 2", "ADBE Tint"] {
|
||||
assert_eq!(defs.iter().filter(|d| *d == m).count(), 1, "{m}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- Gradient Ramp
|
||||
|
||||
#[test]
|
||||
fn ramp_parameters_and_defaults() {
|
||||
// 368: Gradient Ramp with every parameter at its default.
|
||||
skip!(with_params("368-fx-ramp-default.aep", |_, p| {
|
||||
let kinds: Vec<_> = p.iter().map(|p| (p.kind, p.name.as_str())).collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
(ParamKind::Layer, ""),
|
||||
(ParamKind::Point, "Start of Ramp"),
|
||||
(ParamKind::Color, "Start Color"),
|
||||
(ParamKind::Point, "End of Ramp"),
|
||||
(ParamKind::Color, "End Color"),
|
||||
(ParamKind::Popup, "Ramp Shape"),
|
||||
(ParamKind::FixedSlider, "Ramp Scatter"),
|
||||
(ParamKind::FixedSlider, "Blend With Original"),
|
||||
(ParamKind::Button, ""),
|
||||
(ParamKind::NoData, ""),
|
||||
]
|
||||
);
|
||||
// Start [960,0] and End [960,1080] on the 1920x1080 layer: fractions of the layer size.
|
||||
assert_eq!(p[1].value(), Some(ParamValue::Point([0.5, 0.0])));
|
||||
assert_eq!(p[3].value(), Some(ParamValue::Point([0.5, 1.0])));
|
||||
assert_eq!(p[1].point_px(1920.0, 1080.0), Some([960.0, 0.0]));
|
||||
assert_eq!(p[3].point_px(1920.0, 1080.0), Some([960.0, 1080.0]));
|
||||
// Black to white with alpha 255.
|
||||
assert_eq!(p[2].value(), Some(ParamValue::Argb([1.0, 0.0, 0.0, 0.0])));
|
||||
assert_eq!(p[4].value(), Some(ParamValue::Argb([1.0, 1.0, 1.0, 1.0])));
|
||||
// Linear Ramp is item 1 of 2.
|
||||
assert_eq!(p[5].value(), Some(ParamValue::Index(1)));
|
||||
assert_eq!(p[5].popup_item_count(), Some(2));
|
||||
assert_eq!(p[5].popup_selected_item(), Some("Linear Ramp"));
|
||||
// Scatter 0 (pixels, valid max 512); Blend 0 (a 0..1 fraction, valid max 1).
|
||||
assert_eq!((p[6].value(), p[6].valid_max()), (Some(ParamValue::Number(0.0)), Some(512.0)));
|
||||
assert_eq!((p[7].value(), p[7].valid_max()), (Some(ParamValue::Number(0.0)), Some(1.0)));
|
||||
assert!(p[8].stored().is_some() && p[8].value().is_none());
|
||||
assert!((1..=7).all(|i| p[i].stored().is_none()));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ramp_values() {
|
||||
// 369: Start of Ramp [100, 200] -> [100/1920, 200/1080].
|
||||
skip!(with_params("369-fx-ramp-start-100-200.aep", |_, p| {
|
||||
assert_near(&point(p[1].stored_value()), &[100.0 / 1920.0, 200.0 / 1080.0], 1e-12);
|
||||
assert_near(&p[1].point_px(1920.0, 1080.0).unwrap(), &[100.0, 200.0], 1e-9);
|
||||
}));
|
||||
// 371: Start Color red.
|
||||
skip!(with_params("371-fx-ramp-startcolor-red.aep", |_, p| {
|
||||
assert_eq!(p[2].stored_value(), Some(ParamValue::Argb([1.0, 1.0, 0.0, 0.0])));
|
||||
}));
|
||||
// 374: End of Ramp [2000, -100], outside the layer.
|
||||
skip!(with_params("374-fx-ramp-end-2000-m100.aep", |_, p| {
|
||||
assert_near(&p[3].point_px(1920.0, 1080.0).unwrap(), &[2000.0, -100.0], 1e-9);
|
||||
}));
|
||||
// 377: Ramp Shape 2 = Radial Ramp.
|
||||
skip!(with_params("377-fx-ramp-shape-radial.aep", |_, p| {
|
||||
assert_eq!(p[5].stored_value(), Some(ParamValue::Index(2)));
|
||||
assert_eq!(p[5].popup_selected_item(), Some("Radial Ramp"));
|
||||
}));
|
||||
// 378: Ramp Scatter 12 (plain pixels).
|
||||
skip!(with_params("378-fx-ramp-scatter-12.aep", |_, p| assert_eq!(number(p[6].stored_value()), 12.0)));
|
||||
// 380: Blend With Original 25 % is stored as the fraction 0.25.
|
||||
skip!(with_params("380-fx-ramp-blend-25pct.aep", |_, p| {
|
||||
assert_eq!(number(p[7].stored_value()), 0.25);
|
||||
assert_eq!(p[7].valid_max(), Some(1.0));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ramp_point_keyframes() {
|
||||
// 382: Start of Ramp keyed [100,100] at 0 s, [1800,900] at 2 s, linear: 104-byte spatial records.
|
||||
skip!(with_params("382-fx-ramp-start-2key.aep", |_, p| {
|
||||
let start = &p[1];
|
||||
assert!(start.is_animated());
|
||||
let keys: Vec<_> = start.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Spatial { components: 2 } && k.raw().len() == 104));
|
||||
assert_eq!(keys.iter().map(|k| k.time_units().unwrap()).collect::<Vec<_>>(), [0, T2]);
|
||||
assert_near(&keys[0].value().unwrap(), &[100.0 / 1920.0, 100.0 / 1080.0], 1e-12);
|
||||
assert_near(&keys[1].value().unwrap(), &[1800.0 / 1920.0, 900.0 / 1080.0], 1e-12);
|
||||
assert!(keys.iter().all(|k| k.interpolation_in() == Some(Interpolation::Linear)));
|
||||
let s = keys[0].spatial().unwrap();
|
||||
assert_eq!((s.auto_bezier_flag, s.in_tangent.clone(), s.out_tangent.clone()), (1, vec![0.0; 2], vec![0.0; 2]));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_instance_takes_its_definitions_from_the_project_and_its_values_from_itself() {
|
||||
// 383: L keeps its default Gradient Ramp; the new 100x100 solid S100 above it has a Ramp with
|
||||
// Start of Ramp [10, 20]. One of the two instances has an empty parT.
|
||||
let bytes = fixture!("383-fx-ramp-on-100x100-start-10-20.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layers: Vec<_> = comp.layers().collect();
|
||||
assert_eq!(layers.len(), 2);
|
||||
let l = base_layer(&comp);
|
||||
let small = layers.iter().find(|x| x.id() != l.id()).unwrap();
|
||||
|
||||
let small_fx = small.effects();
|
||||
let l_fx = l.effects();
|
||||
assert_eq!((small_fx.len(), l_fx.len()), (1, 1));
|
||||
// In the combined file an earlier case holds the type's full definitions, so here both
|
||||
// instances take them from the project copy.
|
||||
assert_eq!(project.definition_source(&small_fx[0]), DefinitionSource::Project);
|
||||
assert_eq!(project.definition_source(&l_fx[0]), DefinitionSource::Project);
|
||||
assert!(l_fx[0].params().is_empty());
|
||||
assert_eq!(l_fx[0].declared_param_count(), None);
|
||||
|
||||
// S100: [10,20] px on its own 100x100 size; End of Ramp default [50,100].
|
||||
let sp = project.effect_params(&small_fx[0]);
|
||||
assert_near(&point(sp[1].stored_value()), &[0.1, 0.2], 1e-12);
|
||||
assert_near(&sp[1].point_px(100.0, 100.0).unwrap(), &[10.0, 20.0], 1e-9);
|
||||
assert_eq!(sp[3].point_px(100.0, 100.0), Some([50.0, 100.0]));
|
||||
|
||||
// L: the 368 defaults, not the values of the project copy (which is S100's instance).
|
||||
let lp = project.effect_params(&l_fx[0]);
|
||||
assert_eq!(lp.len(), 10);
|
||||
assert!(lp.iter().all(|p| p.borrowed_definition));
|
||||
assert_eq!(lp[1].name, "Start of Ramp");
|
||||
assert!(lp[1].stored().is_none());
|
||||
assert_eq!(lp[1].value(), Some(ParamValue::Point([0.5, 0.0])));
|
||||
assert_eq!(lp[3].value(), Some(ParamValue::Point([0.5, 1.0])));
|
||||
assert_eq!(lp[2].value(), Some(ParamValue::Argb([1.0, 0.0, 0.0, 0.0])));
|
||||
assert_eq!(lp[4].value(), Some(ParamValue::Argb([1.0, 1.0, 1.0, 1.0])));
|
||||
assert_eq!((number(lp[6].value()), number(lp[7].value())), (0.0, 0.0));
|
||||
// A borrowed popup has no reliable pard default (a selection writes into that slot).
|
||||
assert_eq!(lp[5].pard_default(), None);
|
||||
assert_eq!(lp[5].items.as_deref().map(<[String]>::len), Some(2));
|
||||
// L's own records: the input layer (its own id) and the button.
|
||||
assert_eq!(lp[0].stored_value(), Some(ParamValue::Layer(l.id().unwrap())));
|
||||
assert!(lp[8].stored().is_some());
|
||||
|
||||
// One definition for the type, although there are two instances.
|
||||
let defs = project.effect_definitions();
|
||||
assert_eq!(defs.iter().filter(|(m, _)| m == "ADBE Ramp").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_without_effects_have_no_definitions() {
|
||||
// The definitions are per file: a file has some exactly when one of its layers has an effect.
|
||||
let mut without = 0;
|
||||
for name in crate::common::FILES.iter().filter(|n| n.ends_with(".aep")) {
|
||||
let bytes = skip!(crate::common::try_file(name));
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let has_effects = project.all_items().iter().filter_map(|i| i.comp()).any(|c| c.layers().any(|l| !l.effects().is_empty()));
|
||||
assert_eq!(project.effect_definitions().is_empty(), !has_effects, "{name}");
|
||||
without += usize::from(!has_effects);
|
||||
}
|
||||
assert!(without > 0);
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
//! Effects of batch 5 (cases 409-450, 511-516): integer sliders, checkbox defaults, the stored
|
||||
//! scale of each slider (its valid maximum), popup items, and the arbitrary data of Hue/Saturation
|
||||
//! and Levels.
|
||||
|
||||
use crate::container::helpers::{first_comp, open};
|
||||
use effectcraft_aep::{EffectParam, HueSaturationData, LevelsData, ParamKind, ParamValue, Project};
|
||||
|
||||
/// Runs `f` on the parameters of the first effect of layer L (the only layer).
|
||||
fn with_params<R>(name: &str, f: impl FnOnce(&[EffectParam<'_, '_>], &effectcraft_aep::Effect<'_, '_>) -> R) -> Option<R> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).expect("project");
|
||||
let comp = first_comp(&project);
|
||||
let layer = comp.layers().next().expect("L");
|
||||
let fx = layer.effects().into_iter().next().expect("an effect");
|
||||
let params = project.effect_params(&fx);
|
||||
f(¶ms, &fx)
|
||||
})
|
||||
}
|
||||
|
||||
fn by_name<'p, 'f, 'a>(params: &'p [EffectParam<'f, 'a>], name: &str) -> &'p EffectParam<'f, 'a> {
|
||||
params.iter().find(|p| p.name == name || p.items.as_ref().is_some_and(|i| i.first().is_some_and(|f| f == name))).unwrap_or_else(|| panic!("no {name}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invert_channel_items_and_blend() {
|
||||
skip!(with_params("410-fx-invert-channel-2.aep", |p, fx| {
|
||||
assert_eq!(fx.match_name(), "ADBE Invert");
|
||||
let ch = by_name(p, "Channel");
|
||||
assert_eq!(ch.kind, ParamKind::Popup);
|
||||
// The items include separators "(-" (one index each).
|
||||
assert_eq!(ch.items.as_ref().map(|i| (i.len(), i[1].as_str(), i[4].as_str(), i[15].as_str())), Some((16, "Red", "(-", "Alpha")));
|
||||
assert_eq!(ch.stored_value(), Some(ParamValue::Index(2)));
|
||||
assert_eq!(by_name(p, "Blend With Original").valid_max(), Some(100.0));
|
||||
}));
|
||||
skip!(with_params("411-fx-invert-blend-50.aep", |p, _| assert_eq!(by_name(p, "Blend With Original").stored_value(), Some(ParamValue::Number(50.0)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_box_blur_integer_slider_and_checkbox_default_on() {
|
||||
skip!(with_params("413-fx-fastbox-radius-20.aep", |p, _| {
|
||||
let r = by_name(p, "Blur Radius");
|
||||
assert_eq!((r.kind, r.valid_max(), r.stored_value()), (ParamKind::FixedSlider, Some(30000.0), Some(ParamValue::Number(20.0))));
|
||||
let it = by_name(p, "Iterations");
|
||||
assert_eq!((it.kind, it.pard_default(), it.valid_max(), it.stored_value()), (ParamKind::IntSlider, Some(ParamValue::Number(3.0)), Some(50.0), None));
|
||||
// Repeat Edge Pixels is on by default (AE read-back 1): the pard default, no record.
|
||||
let rep = by_name(p, "Repeat Edge Pixels");
|
||||
assert_eq!((rep.kind, rep.pard_default(), rep.value()), (ParamKind::Checkbox, Some(ParamValue::Bool(true)), Some(ParamValue::Bool(true))));
|
||||
}));
|
||||
skip!(with_params("414-fx-fastbox-iterations-1.aep", |p, _| assert_eq!(by_name(p, "Iterations").stored_value(), Some(ParamValue::Number(1.0)))));
|
||||
skip!(with_params("416-fx-fastbox-repeatedge-off.aep", |p, _| {
|
||||
let rep = by_name(p, "Repeat Edge Pixels");
|
||||
assert_eq!((rep.stored_value(), rep.value(), rep.is_default()), (Some(ParamValue::Bool(false)), Some(ParamValue::Bool(false)), Some(false)));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_blur_dimensions_and_repeat_edge() {
|
||||
skip!(with_params("418-fx-gaussian-dimensions-3.aep", |p, _| {
|
||||
assert_eq!(by_name(p, "Blur Dimensions").stored_value(), Some(ParamValue::Index(3)));
|
||||
assert_eq!(by_name(p, "Blurriness").pard_default(), Some(ParamValue::Number(25.0)));
|
||||
assert_eq!(by_name(p, "Repeat Edge Pixels").value(), Some(ParamValue::Bool(true)));
|
||||
}));
|
||||
skip!(with_params("419-fx-gaussian-repeatedge-off.aep", |p, _| assert_eq!(by_name(p, "Repeat Edge Pixels").value(), Some(ParamValue::Bool(false)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_shadow_opacity_is_stored_on_0_to_255() {
|
||||
skip!(with_params("422-fx-dropshadow-opacity-204.aep", |p, _| {
|
||||
let o = by_name(p, "Opacity");
|
||||
assert_eq!((o.valid_max(), o.pard_default(), o.stored_value()), (Some(255.0), Some(ParamValue::Number(127.5)), Some(ParamValue::Number(204.0))));
|
||||
assert_eq!(by_name(p, "Distance").valid_max(), Some(4000.0));
|
||||
assert_eq!(by_name(p, "Shadow Only").pard_default(), Some(ParamValue::Bool(false)));
|
||||
}));
|
||||
skip!(with_params("426-fx-dropshadow-shadowonly-on.aep", |p, _| assert_eq!(by_name(p, "Shadow Only").stored_value(), Some(ParamValue::Bool(true)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glow_defaults_items_and_scales() {
|
||||
skip!(with_params("427-fx-glow-default.aep", |p, _| {
|
||||
let popup = |n: &str| (by_name(p, n).pard_default(), by_name(p, n).items.as_ref().map(|i| i.len()));
|
||||
assert_eq!(popup("Glow Based On"), (Some(ParamValue::Index(2)), Some(2)));
|
||||
assert_eq!(popup("Composite Original"), (Some(ParamValue::Index(2)), Some(3)));
|
||||
assert_eq!(popup("Glow Operation"), (Some(ParamValue::Index(3)), Some(25)));
|
||||
assert_eq!(popup("Color Looping"), (Some(ParamValue::Index(3)), Some(4)));
|
||||
let t = by_name(p, "Glow Threshold");
|
||||
assert_eq!((t.valid_max(), t.pard_default()), (Some(255.0), Some(ParamValue::Number(153.0))));
|
||||
let m = by_name(p, "A & B Midpoint");
|
||||
assert_eq!(m.pard_default(), Some(ParamValue::Number(0.5)));
|
||||
assert!(m.valid_max().is_some_and(|v| (v - 0.99).abs() < 0.001));
|
||||
}));
|
||||
skip!(with_params("429-fx-glow-threshold-76.5.aep", |p, _| assert_eq!(by_name(p, "Glow Threshold").stored_value(), Some(ParamValue::Number(76.5)))));
|
||||
skip!(with_params("438-fx-glow-midpoint-0.25.aep", |p, _| assert_eq!(by_name(p, "A & B Midpoint").stored_value(), Some(ParamValue::Number(0.25)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_saturation_master_values_are_arbitrary_data() {
|
||||
for (name, master) in [("444-fx-huesat-hue-90.aep", [90, 0, 0]), ("446-fx-huesat-light-m30.aep", [0, 0, -30])] {
|
||||
skip!(with_params(name, |p, fx| {
|
||||
// The visible Master parameters keep no record.
|
||||
assert!(by_name(p, "Master Hue").stored().is_none(), "{name}");
|
||||
let range = by_name(p, "Channel Range");
|
||||
assert_eq!(range.kind, ParamKind::ArbitraryData);
|
||||
let data = fx.arbitrary_data(&range.match_name).expect("data");
|
||||
let d = HueSaturationData::parse(data).expect("180 bytes");
|
||||
assert_eq!(d.master, master, "{name}");
|
||||
assert!(d.ranges_are_default(), "{name}");
|
||||
}));
|
||||
}
|
||||
skip!(with_params("448-fx-huesat-colorizehue-120.aep", |p, fx| {
|
||||
assert_eq!(by_name(p, "Colorize Hue").stored_value(), Some(ParamValue::Number(120.0)));
|
||||
assert_eq!(by_name(p, "Colorize Saturation").pard_default(), Some(ParamValue::Number(25.0)));
|
||||
let d = HueSaturationData::parse(fx.arbitrary_data(&by_name(p, "Channel Range").match_name).expect("data")).expect("parses");
|
||||
assert_eq!(d.master, [0, 0, 0]);
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_values_are_arbitrary_data() {
|
||||
let f32r = |x: f64| f32::from_bits((x as f32).to_bits());
|
||||
for (name, rgb) in [
|
||||
("512-fx-levels-inblack-0.1.aep", [f32r(0.1), 1.0, 1.0, 0.0, 1.0]),
|
||||
("514-fx-levels-gamma-2.aep", [0.0, 1.0, 2.0, 0.0, 1.0]),
|
||||
("516-fx-levels-outwhite-0.9.aep", [0.0, 1.0, 1.0, 0.0, f32r(0.9)]),
|
||||
] {
|
||||
skip!(with_params(name, |p, fx| {
|
||||
assert!(by_name(p, "Input Black").stored().is_none(), "{name}: the visible parameter keeps no record");
|
||||
let h = by_name(p, "Histogram");
|
||||
assert_eq!(h.kind, ParamKind::ArbitraryData);
|
||||
let d = LevelsData::parse(fx.arbitrary_data(&h.match_name).expect("data")).expect("108 bytes");
|
||||
assert_eq!(d.header, [0x000f_10a7, 1], "{name}");
|
||||
assert_eq!(d.channels[0], rgb, "{name}");
|
||||
for c in &d.channels[1..] {
|
||||
assert_eq!(*c, LevelsData::DEFAULT_CHANNEL, "{name}");
|
||||
}
|
||||
let clip = by_name(p, "Clip To Output Black");
|
||||
assert_eq!(clip.items.as_ref().map(|i| i.join("|")), Some("On|Off|Off for 32 bpc Color".to_string()));
|
||||
// A borrowed popup (a later Levels of the combined file) has no reliable pard default.
|
||||
let want = if clip.borrowed_definition { None } else { Some(ParamValue::Index(3)) };
|
||||
assert_eq!(clip.pard_default(), want, "{name}");
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_arbitrary_data_is_none() {
|
||||
assert_eq!(HueSaturationData::parse(&[0; 179]), None);
|
||||
assert_eq!(LevelsData::parse(&[0; 200]), None);
|
||||
assert!(HueSaturationData::parse(&[0xff; 180]).is_some());
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
//! Batch 4, session S7 (cases 389-397): Exposure (`ADBE Exposure2`): the popup, the four
|
||||
//! twirl-down groups (start / end markers that hold no value), float sliders with their valid and
|
||||
//! slider ranges, the Bypass checkbox and a keyed slider. Every expected value is the one the case
|
||||
//! was made with (its MANIFEST row).
|
||||
|
||||
use crate::container::helpers::{assert_near, base_layer, first_comp, open};
|
||||
use effectcraft_aep::{DefinitionSource, EffectParam, Interpolation, KeyframeKind, ParamKind, ParamValue, Project};
|
||||
|
||||
/// Key time 2 s in the property timescale 25600.
|
||||
const T2: i32 = 51200;
|
||||
/// Float sliders hold the float32 value widened to f64 (0.1 is 0.10000000149).
|
||||
const F32: f64 = 1e-6;
|
||||
|
||||
/// Runs `f` on the parameters of the single effect of `L`.
|
||||
fn with_params<R>(name: &str, f: impl FnOnce(&[EffectParam<'_, '_>]) -> R) -> Option<R> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let effects = layer.effects();
|
||||
assert_eq!(effects.len(), 1, "{name}");
|
||||
assert_eq!(effects[0].match_name(), "ADBE Exposure2", "{name}");
|
||||
// The first instance of a type in the combined file (the case that adds it at its defaults)
|
||||
// keeps its own definitions; the later cases read the project copy.
|
||||
let first = ["356-fx-tint-default.aep", "368-fx-ramp-default.aep", "389-fx-exposure-default.aep"].contains(&name);
|
||||
let want = if first { DefinitionSource::Instance } else { DefinitionSource::Project };
|
||||
assert_eq!(project.definition_source(&effects[0]), want, "{name}");
|
||||
let params = project.effect_params(&effects[0]);
|
||||
assert_eq!(params.len(), 24, "{name}");
|
||||
f(¶ms)
|
||||
})
|
||||
}
|
||||
|
||||
fn number(v: Option<ParamValue>) -> f64 {
|
||||
match v {
|
||||
Some(ParamValue::Number(n)) => n,
|
||||
other => panic!("{other:?} is not a number"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `parT` indices of the Exposure / Offset / Gamma Correction sliders of Master, Red, Green
|
||||
/// and Blue.
|
||||
const GROUPS: [(usize, &str); 4] = [(2, "Master"), (7, "Red"), (12, "Green"), (17, "Blue")];
|
||||
|
||||
#[test]
|
||||
fn exposure_parameters_and_defaults() {
|
||||
// 389: Exposure with every parameter at its default.
|
||||
let bytes = fixture!("389-fx-exposure-default.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let fx = base_layer(&first_comp(&project)).effects();
|
||||
assert_eq!((fx[0].match_name(), fx[0].name().as_deref()), ("ADBE Exposure2", Some("Exposure")));
|
||||
assert_eq!(fx[0].declared_param_count(), Some(24));
|
||||
skip!(with_params("389-fx-exposure-default.aep", |p| {
|
||||
assert_eq!((p[0].kind, p[1].kind, p[22].kind, p[23].kind), (ParamKind::Layer, ParamKind::Popup, ParamKind::Checkbox, ParamKind::NoData));
|
||||
assert_eq!(p[1].name, "Channels:");
|
||||
assert_eq!(p[1].items.as_deref(), Some(&["Master".to_string(), "Individual Channels".to_string()][..]));
|
||||
assert_eq!((p[1].value(), p[1].popup_item_count(), p[1].popup_selected_item()), (Some(ParamValue::Index(1)), Some(2), Some("Master")));
|
||||
for (start, group) in GROUPS {
|
||||
let prefix = if group == "Master" { String::new() } else { format!("{group} ") };
|
||||
// The group markers: always a record, no value, the end repeats the group's name.
|
||||
for (i, kind) in [(start, ParamKind::GroupStart), (start + 4, ParamKind::GroupEnd)] {
|
||||
assert_eq!((p[i].kind, p[i].name.as_str()), (kind, group));
|
||||
assert!(p[i].stored().is_some(), "{group} {kind:?}");
|
||||
assert_eq!((p[i].stored_value(), p[i].pard_default(), p[i].value(), p[i].is_default()), (None, None, None, None));
|
||||
}
|
||||
let names = [format!("{prefix}Exposure"), format!("{prefix}Offset"), format!("{prefix}Gamma Correction")];
|
||||
// Valid range, slider range and default per slider (the same for all four groups).
|
||||
let want = [((-100.0, 100.0), (-4.0, 4.0), 0.0), ((-2.0, 2.0), (-0.5, 0.5), 0.0), ((0.1, 10.0), (0.1, 10.0), 1.0)];
|
||||
for (k, (valid, slider, default)) in want.into_iter().enumerate() {
|
||||
let s = &p[start + 1 + k];
|
||||
assert_eq!((s.kind, s.name.as_str()), (ParamKind::FloatSlider, names[k].as_str()));
|
||||
assert_eq!(s.match_name, format!("ADBE Exposure2-{:04}", start + 1 + k));
|
||||
assert!(s.stored().is_none(), "{}", s.name);
|
||||
assert_eq!(s.value(), Some(ParamValue::Number(default)), "{}", s.name);
|
||||
assert_eq!(s.is_default(), Some(true));
|
||||
assert_near(&[s.valid_min().unwrap(), s.valid_max().unwrap()], &[valid.0, valid.1], F32);
|
||||
let (lo, hi) = s.slider_range().unwrap();
|
||||
assert_near(&[lo, hi], &[slider.0, slider.1], F32);
|
||||
}
|
||||
}
|
||||
// Bypass Linear Light Conversion: an unnamed checkbox labelled in pdnm, off.
|
||||
assert_eq!(p[22].name, "");
|
||||
assert_eq!(p[22].items.as_deref(), Some(&["Bypass Linear Light Conversion".to_string()][..]));
|
||||
assert!(p[22].stored().is_none());
|
||||
assert_eq!(p[22].value(), Some(ParamValue::Bool(false)));
|
||||
// Ranges exist only on float sliders.
|
||||
assert_eq!((p[1].valid_min(), p[1].slider_range(), p[22].slider_range(), p[2].valid_max()), (None, None, None, None));
|
||||
assert!(p.iter().all(|p| !p.borrowed_definition && !p.is_animated()));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exposure_values() {
|
||||
// 390: Channels -> Individual Channels (2).
|
||||
skip!(with_params("390-fx-exposure-channels-individual.aep", |p| {
|
||||
assert_eq!(p[1].stored_value(), Some(ParamValue::Index(2)));
|
||||
assert_eq!(p[1].popup_selected_item(), Some("Individual Channels"));
|
||||
assert_eq!(p[1].is_default(), Some(false));
|
||||
}));
|
||||
// 391: Exposure 1.5.
|
||||
skip!(with_params("391-fx-exposure-master-1.5.aep", |p| {
|
||||
assert_eq!(p[3].stored_value(), Some(ParamValue::Number(1.5)));
|
||||
assert_eq!(p[3].is_default(), Some(false));
|
||||
assert_eq!(p[4].value(), Some(ParamValue::Number(0.0)));
|
||||
}));
|
||||
// 393: Offset 0.1 (float32: 0.10000000149).
|
||||
skip!(with_params("393-fx-exposure-offset-0.1.aep", |p| {
|
||||
assert_near(&[number(p[4].stored_value())], &[0.1], F32);
|
||||
assert_eq!(p[3].value(), Some(ParamValue::Number(0.0)));
|
||||
}));
|
||||
// 394: Gamma Correction 2.2 (float32: 2.2000000477).
|
||||
skip!(with_params("394-fx-exposure-gamma-2.2.aep", |p| {
|
||||
assert_near(&[number(p[5].stored_value())], &[2.2], F32);
|
||||
assert_eq!(p[5].is_default(), Some(false));
|
||||
}));
|
||||
// 395: Channels 2 and Red Exposure 1: two ordinary records.
|
||||
skip!(with_params("395-fx-exposure-individual-red-1.aep", |p| {
|
||||
assert_eq!(p[1].stored_value(), Some(ParamValue::Index(2)));
|
||||
assert_eq!(p[8].stored_value(), Some(ParamValue::Number(1.0)));
|
||||
assert_eq!(p[3].value(), Some(ParamValue::Number(0.0)));
|
||||
}));
|
||||
// 396: Bypass on: a record with 1.0.
|
||||
skip!(with_params("396-fx-exposure-bypass-on.aep", |p| {
|
||||
assert_eq!(p[22].stored_value(), Some(ParamValue::Bool(true)));
|
||||
assert_eq!(p[22].is_default(), Some(false));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exposure_keyframes() {
|
||||
// 397: Exposure keyed -1 at 0 s, 2 at 2 s, linear: plain 48-byte records.
|
||||
skip!(with_params("397-fx-exposure-master-2key.aep", |p| {
|
||||
let e = &p[3];
|
||||
assert!(e.is_animated());
|
||||
assert_eq!(e.stored_value(), None);
|
||||
let keys: Vec<_> = e.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert_eq!(keys.iter().map(|k| k.time_units().unwrap()).collect::<Vec<_>>(), [0, T2]);
|
||||
assert_eq!(keys.iter().map(|k| k.scalar_value().unwrap()).collect::<Vec<_>>(), [-1.0, 2.0]);
|
||||
assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Plain { components: 1 } && k.raw().len() == 48));
|
||||
assert!(keys.iter().all(|k| k.interpolation_in() == Some(Interpolation::Linear) && k.interpolation_out() == Some(Interpolation::Linear)));
|
||||
}));
|
||||
}
|
||||
@@ -1,364 +0,0 @@
|
||||
//! The layer header (`ldta`) and the composition header (`cdta`, `PRin`), checked against the values
|
||||
//! the synthetic corpus was made with (its MANIFEST): comp `C` 1920x1080, 25 fps, 5 s, background
|
||||
//! black, shutter angle 180, one solid layer `L` (red, 1920x1080, label 1, Normal, Best, start 0,
|
||||
//! in 0, out 5, stretch 100), then one change per file.
|
||||
|
||||
use crate::container::helpers::{base_layer, first_comp, open};
|
||||
use effectcraft_aep::{BlendMode, LayerHeader, LayerType, Project, Quality, Rational};
|
||||
|
||||
const L: u32 = 0x1b;
|
||||
|
||||
/// The header of the solid layer `L` in a fixture.
|
||||
fn l_header(name: &str) -> Option<LayerHeader> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
base_layer(&comp).header().unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// The switches that the MANIFEST lists, so that a case can say which one differs from the base.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct Switches {
|
||||
shy: bool,
|
||||
locked: bool,
|
||||
solo: bool,
|
||||
three_d: bool,
|
||||
motion_blur: bool,
|
||||
collapse: bool,
|
||||
adjustment: bool,
|
||||
guide: bool,
|
||||
}
|
||||
|
||||
fn switches(h: &LayerHeader) -> Switches {
|
||||
Switches {
|
||||
shy: h.is_shy(),
|
||||
locked: h.is_locked(),
|
||||
solo: h.is_solo(),
|
||||
three_d: h.is_three_d(),
|
||||
motion_blur: h.is_motion_blur(),
|
||||
collapse: h.collapses_transformations(),
|
||||
adjustment: h.is_adjustment(),
|
||||
guide: h.is_guide(),
|
||||
}
|
||||
}
|
||||
|
||||
const NONE: Switches =
|
||||
Switches { shy: false, locked: false, solo: false, three_d: false, motion_blur: false, collapse: false, adjustment: false, guide: false };
|
||||
|
||||
/// Everything the base layer and every one-switch case share.
|
||||
fn assert_plain(h: &LayerHeader) {
|
||||
// The id is the case's own (0x1b in the single-case files); the source is the solid `L`.
|
||||
assert_eq!(h.layer_type, LayerType::Av);
|
||||
assert_eq!(h.label, 1);
|
||||
// No name was set, so the copy of the name at byte 64 is empty (the layer shows its source name).
|
||||
assert_eq!(h.name_copy, "");
|
||||
assert!(!h.name_is_user_set());
|
||||
assert!(!h.is_null_object());
|
||||
assert_eq!(h.parent_id, None);
|
||||
assert_eq!(h.source_id, Some(0x1a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_layer_header() {
|
||||
let h = skip!(l_header("000-base.aep"));
|
||||
assert_plain(&h);
|
||||
assert_eq!(h.quality, Quality::Best);
|
||||
assert_eq!(h.blend_mode, BlendMode::Normal);
|
||||
assert_eq!(h.stretch, 1);
|
||||
assert_eq!(h.stretch_percent(), 100.0);
|
||||
assert_eq!(switches(&h), NONE);
|
||||
// start 0 s, in 0 s, out 5 s; denominator = the composition timescale.
|
||||
assert_eq!(h.start, Rational { num: 0, den: 25600 });
|
||||
assert_eq!(h.in_relative, Rational { num: 0, den: 25600 });
|
||||
assert_eq!(h.out_relative, Rational { num: 128_000, den: 25600 });
|
||||
assert_eq!(h.start_seconds(), Some(0.0));
|
||||
assert_eq!(h.in_point_seconds(), Some(0.0));
|
||||
assert_eq!(h.out_point_seconds(), Some(5.0));
|
||||
assert_eq!(h.out_point(), Rational::new(5, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_switch_per_case() {
|
||||
// (file, the switches that case turns on)
|
||||
let cases = [
|
||||
("012-layer-shy.aep", Switches { shy: true, ..NONE }),
|
||||
("013-layer-locked.aep", Switches { locked: true, ..NONE }),
|
||||
("014-layer-solo.aep", Switches { solo: true, ..NONE }),
|
||||
("015-layer-3d.aep", Switches { three_d: true, ..NONE }),
|
||||
("017-layer-motionblur.aep", Switches { motion_blur: true, ..NONE }),
|
||||
("024-layer-collapse.aep", Switches { collapse: true, ..NONE }),
|
||||
("025-layer-adjustment.aep", Switches { adjustment: true, ..NONE }),
|
||||
("026-layer-guide.aep", Switches { guide: true, ..NONE }),
|
||||
];
|
||||
for (name, expected) in cases {
|
||||
let h = skip!(l_header(name));
|
||||
assert_eq!(switches(&h), expected, "{name}");
|
||||
assert_plain(&h);
|
||||
assert_eq!((h.quality, h.blend_mode, h.stretch), (Quality::Best, BlendMode::Normal, 1), "{name}");
|
||||
assert_eq!(h.out_point_seconds(), Some(5.0), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn name_blend_mode_and_quality() {
|
||||
let h = skip!(l_header("010-layer-name.aep"));
|
||||
assert_eq!(h.name_copy, "Renamed");
|
||||
assert!(h.name_is_user_set());
|
||||
let bytes = fixture!("010-layer-name.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
// The layer name is the user's; the source footage keeps its own name.
|
||||
assert_eq!(layer.name().as_deref(), Some("Renamed"));
|
||||
assert_eq!(project.layer_source(&layer).and_then(|i| i.display_name()).as_deref(), Some("L"));
|
||||
assert_eq!(project.layer_display_name(&layer).as_deref(), Some("Renamed"));
|
||||
|
||||
assert_eq!(skip!(l_header("016-layer-blend-multiply.aep")).blend_mode, BlendMode::Multiply);
|
||||
assert_eq!(skip!(l_header("023-layer-quality-draft.aep")).quality, Quality::Draft);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_name_falls_back_to_the_source_name() {
|
||||
let bytes = fixture!("000-base.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
assert_eq!(layer.name(), None);
|
||||
assert_eq!(project.layer_display_name(&layer).as_deref(), Some("L"));
|
||||
assert_eq!(project.layer_source_size(&layer), Some((1920, 1080)));
|
||||
let source = project.layer_source(&layer).unwrap();
|
||||
assert_eq!(source.id(), Some(0x1a));
|
||||
assert!(source.footage().unwrap().is_solid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_stretch_and_the_in_out_start_convention() {
|
||||
// 018: stretch 100 -> 200: the stored out point stays 5 s, the layer ends at 10 s.
|
||||
let h = skip!(l_header("018-layer-stretch200.aep"));
|
||||
assert_eq!(h.stretch, 2);
|
||||
assert_eq!(h.stretch_percent(), 200.0);
|
||||
assert_eq!(h.out_relative, Rational { num: 128_000, den: 25600 });
|
||||
assert_eq!(h.out_point_seconds(), Some(10.0));
|
||||
assert_eq!(h.in_point_seconds(), Some(0.0));
|
||||
|
||||
// 019: inPoint 0 -> 1; AE moved the out point to 6 s and left the start at 0.
|
||||
let h = skip!(l_header("019-layer-inpoint1.aep"));
|
||||
assert_eq!(h.start_seconds(), Some(0.0));
|
||||
assert_eq!(h.in_relative, Rational { num: 25600, den: 25600 });
|
||||
assert_eq!(h.in_point(), Rational::new(1, 1));
|
||||
assert_eq!(h.out_point_seconds(), Some(6.0));
|
||||
|
||||
// 021: startTime 0 -> 0.5: in 0.5 s and out 5.5 s although the stored in point stays 0.
|
||||
let h = skip!(l_header("021-layer-starttime0.5.aep"));
|
||||
assert_eq!(h.start, Rational { num: 12800, den: 25600 });
|
||||
assert_eq!(h.start_seconds(), Some(0.5));
|
||||
assert_eq!(h.in_relative.num, 0);
|
||||
assert_eq!(h.in_point(), Rational::new(1, 2));
|
||||
assert_eq!(h.in_point_seconds(), Some(0.5));
|
||||
assert_eq!(h.out_point_seconds(), Some(5.5));
|
||||
assert_eq!(h.out_point(), Rational::new(11, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parent_link_and_null_object() {
|
||||
// 022: a new null layer "Null" (source "Null 1", 100x100) on top; L is its child.
|
||||
let bytes = fixture!("022-layer-parent-null.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layers: Vec<_> = comp.layers().collect();
|
||||
assert_eq!(layers.len(), 2);
|
||||
let null = &layers[0];
|
||||
let nh = null.header().unwrap();
|
||||
assert_eq!(null.name().as_deref(), Some("Null"));
|
||||
assert!(nh.is_null_object());
|
||||
assert!(nh.name_is_user_set());
|
||||
assert_eq!(nh.layer_type, LayerType::Av);
|
||||
assert_eq!(nh.parent_id, None);
|
||||
assert_eq!(project.layer_source(null).and_then(|i| i.display_name()).as_deref(), Some("Null 1"));
|
||||
assert_eq!(project.layer_source_size(null), Some((100, 100)));
|
||||
let lh = layers[1].header().unwrap();
|
||||
assert_ne!(lh.id, nh.id);
|
||||
assert_eq!(lh.parent_id, Some(nh.id));
|
||||
assert!(!lh.is_null_object());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_header_is_none_when_ldta_is_too_short() {
|
||||
assert!(LayerHeader::parse(&[0; 139]).is_none());
|
||||
assert!(LayerHeader::parse(&[]).is_none());
|
||||
assert!(LayerHeader::parse(&[0; 140]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rational_is_exact() {
|
||||
assert_eq!(Rational::new(12800, 25600), Some(Rational { num: 1, den: 2 }));
|
||||
assert_eq!(Rational::new(-3, -6), Some(Rational { num: 1, den: 2 }));
|
||||
assert_eq!(Rational::new(3, -6), Some(Rational { num: -1, den: 2 }));
|
||||
assert_eq!(Rational::new(0, 7), Some(Rational { num: 0, den: 1 }));
|
||||
assert_eq!(Rational::new(1, 0), None);
|
||||
assert_eq!(Rational { num: 1, den: 0 }.to_f64(), None);
|
||||
assert_eq!(Rational::new(i64::MIN, 1), None);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------- composition
|
||||
|
||||
use effectcraft_aep::CompHeader;
|
||||
|
||||
fn comp_header(name: &str) -> Option<(CompHeader, Option<String>, Option<(String, String)>)> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
(comp.header().unwrap(), comp.name(), comp.renderer().map(|r| (r.match_name, r.display_name)))
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_comp_header() {
|
||||
let (h, name, renderer) = skip!(comp_header("000-base.aep"));
|
||||
assert_eq!(name.as_deref(), Some("C"));
|
||||
assert_eq!((h.width, h.height), (1920, 1080));
|
||||
assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 25600));
|
||||
assert_eq!(h.frame_rate(), Some(25.0));
|
||||
assert_eq!(h.frame_rate_from_fixed(), 25.0);
|
||||
assert_eq!(h.duration_units, 128_000);
|
||||
assert_eq!(h.duration_seconds(), Some(5.0));
|
||||
assert_eq!(h.background, [0, 0, 0]);
|
||||
assert_eq!(h.background_rgb(), [0.0, 0.0, 0.0]);
|
||||
assert_eq!(h.shutter_angle, 180);
|
||||
assert_eq!(h.work_area_start_seconds(), Some(0.0));
|
||||
assert_eq!(h.work_area_end_units, None);
|
||||
assert_eq!(h.work_area_end_seconds(), Some(5.0));
|
||||
assert_eq!(h.pixel_aspect, Rational { num: 1, den: 1 });
|
||||
assert_eq!(h.pixel_aspect_ratio(), Some(1.0));
|
||||
assert!(!h.motion_blur);
|
||||
// The manifest calls the classic renderer `ADBE Advanced 3d`; the file stores `ADBE Escher`
|
||||
// and the display name `Classic 3D`.
|
||||
assert_eq!(renderer, Some(("ADBE Escher".to_string(), "Classic 3D".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_comp_change_per_case() {
|
||||
let (base, _, _) = skip!(comp_header("000-base.aep"));
|
||||
|
||||
let (h, _, _) = skip!(comp_header("030-comp-size-1280x720.aep"));
|
||||
assert_eq!((h.width, h.height), (1280, 720));
|
||||
assert_eq!(CompHeader { width: 1920, height: 1080, ..h }, base);
|
||||
|
||||
// 031: frameRate 25 -> 30: the frame duration stays 1024, the timescale becomes 30720; the
|
||||
// duration stays 5 s (153 600 units).
|
||||
let (h, _, _) = skip!(comp_header("031-comp-fps30.aep"));
|
||||
assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 30720));
|
||||
assert_eq!(h.frame_rate(), Some(30.0));
|
||||
assert_eq!(h.frame_rate_from_fixed(), 30.0);
|
||||
assert_eq!(h.duration_units, 153_600);
|
||||
assert_eq!(h.duration_seconds(), Some(5.0));
|
||||
|
||||
// 032: duration 5 -> 10 s; the work area stays the whole composition.
|
||||
let (h, _, _) = skip!(comp_header("032-comp-duration10.aep"));
|
||||
assert_eq!(h.duration_units, 256_000);
|
||||
assert_eq!(h.duration_seconds(), Some(10.0));
|
||||
assert_eq!(h.work_area_end_seconds(), Some(10.0));
|
||||
|
||||
// 033: bgColor [0,0,0] -> [0,1,0].
|
||||
let (h, _, _) = skip!(comp_header("033-comp-bg-green.aep"));
|
||||
assert_eq!(h.background, [0, 255, 0]);
|
||||
assert_eq!(h.background_rgb(), [0.0, 1.0, 0.0]);
|
||||
|
||||
// 034: shutterAngle 180 -> 90.
|
||||
let (h, _, _) = skip!(comp_header("034-comp-shutter90.aep"));
|
||||
assert_eq!(h.shutter_angle, 90);
|
||||
assert_eq!(CompHeader { shutter_angle: 180, ..h }, base);
|
||||
|
||||
// 035: workAreaStart 0 -> 1, workAreaDuration 5 -> 2: the end is start + duration = 3 s.
|
||||
let (h, _, _) = skip!(comp_header("035-comp-workarea-1-2.aep"));
|
||||
assert_eq!(h.work_area_start_units, 25600);
|
||||
assert_eq!(h.work_area_end_units, Some(76_800));
|
||||
assert_eq!(h.work_area_start_seconds(), Some(1.0));
|
||||
assert_eq!(h.work_area_end_seconds(), Some(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_comp_change_per_case_aspect_blur_renderer() {
|
||||
let (base, _, base_renderer) = skip!(comp_header("000-base.aep"));
|
||||
|
||||
// 037: pixelAspect 1 -> 2.
|
||||
let (h, _, _) = skip!(comp_header("037-comp-pixelaspect2.aep"));
|
||||
assert_eq!(h.pixel_aspect, Rational { num: 2, den: 1 });
|
||||
assert_eq!(h.pixel_aspect_ratio(), Some(2.0));
|
||||
|
||||
// 038: comp motion blur on.
|
||||
let (h, _, _) = skip!(comp_header("038-comp-motionblur.aep"));
|
||||
assert!(h.motion_blur);
|
||||
assert_eq!(CompHeader { motion_blur: false, ..h }, base);
|
||||
|
||||
// 039: renderer -> Advanced 3D.
|
||||
let (h, _, renderer) = skip!(comp_header("039-comp-renderer-advanced3d.aep"));
|
||||
assert_eq!(renderer, Some(("ADBE Calder".to_string(), "Advanced 3D".to_string())));
|
||||
assert_ne!(renderer, base_renderer);
|
||||
assert_eq!(h, base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comp_header_is_none_when_cdta_is_too_short() {
|
||||
assert!(CompHeader::parse(&[0; 175]).is_none());
|
||||
assert!(CompHeader::parse(&[0; 176]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precomp_item_ids_and_labels() {
|
||||
// 124: L precomposed into "Pre"; the layer in C is a comp-sourced layer labelled 15.
|
||||
let bytes = fixture!("124-precomp-Pre.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comps: Vec<_> = project.all_items().into_iter().filter_map(|i| i.comp().map(|c| (i, c))).collect();
|
||||
let names: Vec<_> = comps.iter().map(|(_, c)| c.name().unwrap()).collect();
|
||||
assert_eq!(names, ["C", "Pre"]);
|
||||
let (c_item, c) = &comps[0];
|
||||
let (pre_item, pre) = &comps[1];
|
||||
let layers: Vec<_> = c.layers().collect();
|
||||
assert_eq!(layers.len(), 1);
|
||||
let layer = &layers[0];
|
||||
let h = layer.header().unwrap();
|
||||
assert_eq!(h.source_id, pre_item.id());
|
||||
assert_eq!(project.layer_source(layer).unwrap().id(), pre_item.id());
|
||||
assert_eq!(h.label, 15);
|
||||
assert!(!h.name_is_user_set());
|
||||
assert_eq!(layer.name(), None);
|
||||
assert_eq!(project.layer_display_name(layer).as_deref(), Some("Pre"));
|
||||
assert_eq!(project.layer_source_size(layer), Some((1920, 1080)));
|
||||
// The precomp layer's start time has the denominator 1; the Pre comp is 1920x1080, 25 fps, 5 s.
|
||||
assert_eq!(h.start.den, 1);
|
||||
let ph = pre.header().unwrap();
|
||||
assert_eq!((ph.width, ph.height, ph.frame_rate(), ph.duration_seconds()), (1920, 1080, Some(25.0), Some(5.0)));
|
||||
// C records that it uses the comp Pre (chunk idpi, a little-endian u32).
|
||||
assert_eq!(c_item.used_item_ids(), [pre_item.id().unwrap()]);
|
||||
assert!(pre_item.used_item_ids().is_empty());
|
||||
assert_eq!(pre_item.label(), Some(15));
|
||||
// The layer inside Pre is a new layer made from the solid L (moving the layers into a precomp
|
||||
// creates new layers).
|
||||
let inner: Vec<_> = pre.layers().collect();
|
||||
assert_eq!(inner.len(), 1);
|
||||
let ih = inner[0].header().unwrap();
|
||||
assert_ne!(ih.id, L);
|
||||
assert_eq!(ih.source_id, Some(0x1a));
|
||||
assert_eq!(project.layer_display_name(&inner[0]).as_deref(), Some("L"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_stretch_is_a_reversed_layer() {
|
||||
// 981: Time Reverse (stretch -100 %, start 5 s): numerator -1 (`0xffffffff`), the stored in
|
||||
// point 0 and out point 5 s relative, so the layer runs from 5 s back to 0 s; 983: -50 % = -1/2.
|
||||
let h = skip!(l_header("981-layer-stretch-minus100-start5.aep"));
|
||||
assert_eq!((h.stretch, h.stretch_den), (-1, 1));
|
||||
assert_eq!(h.stretch_percent(), -100.0);
|
||||
assert_eq!((h.in_point_seconds(), h.out_point_seconds()), (Some(5.0), Some(0.0)));
|
||||
let h = skip!(l_header("983-layer-stretch-minus50-opacity-keys.aep"));
|
||||
assert_eq!((h.stretch, h.stretch_den), (-1, 2));
|
||||
assert_eq!((h.in_point_seconds(), h.out_point_seconds()), (Some(5.0), Some(2.5)));
|
||||
}
|
||||
@@ -1,413 +0,0 @@
|
||||
//! Helpers shared by the container tests.
|
||||
#![allow(dead_code)]
|
||||
|
||||
/// The generated fixtures (own test data, see ATTRIBUTION.md).
|
||||
pub const FIXTURES: &[&str] = &[
|
||||
"000-base.aep",
|
||||
"001-empty.aep",
|
||||
"010-layer-name.aep",
|
||||
"012-layer-shy.aep",
|
||||
"013-layer-locked.aep",
|
||||
"014-layer-solo.aep",
|
||||
"015-layer-3d.aep",
|
||||
"016-layer-blend-multiply.aep",
|
||||
"017-layer-motionblur.aep",
|
||||
"018-layer-stretch200.aep",
|
||||
"019-layer-inpoint1.aep",
|
||||
"021-layer-starttime0.5.aep",
|
||||
"022-layer-parent-null.aep",
|
||||
"023-layer-quality-draft.aep",
|
||||
"024-layer-collapse.aep",
|
||||
"025-layer-adjustment.aep",
|
||||
"026-layer-guide.aep",
|
||||
"030-comp-size-1280x720.aep",
|
||||
"031-comp-fps30.aep",
|
||||
"032-comp-duration10.aep",
|
||||
"033-comp-bg-green.aep",
|
||||
"034-comp-shutter90.aep",
|
||||
"035-comp-workarea-1-2.aep",
|
||||
"037-comp-pixelaspect2.aep",
|
||||
"038-comp-motionblur.aep",
|
||||
"039-comp-renderer-advanced3d.aep",
|
||||
"040-static-position-100-200.aep",
|
||||
"041-static-scale-50.aep",
|
||||
"042-static-rotation-45.aep",
|
||||
"043-static-opacity-25.aep",
|
||||
"044-static-anchor-10-20.aep",
|
||||
"052-key-position-2key-ease.aep",
|
||||
"053-key-position-2key-hold-key1.aep",
|
||||
"054-key-position-2key-spatial-bezier.aep",
|
||||
"055-key-position-3key-inserted-t2.5.aep",
|
||||
"056-key-position-3key-roving-key2.aep",
|
||||
"057-key-position-3key-label9-key2.aep",
|
||||
"058-key-opacity-2key.aep",
|
||||
"060-expr-opacity-wiggle.aep",
|
||||
"071-fx-slider-value77.aep",
|
||||
"073-fx-color-0.2-0.6-1.aep",
|
||||
"077-fx-dropdown-default.aep",
|
||||
"080-fx-dropshadow-default.aep",
|
||||
"090-mask-rect.aep",
|
||||
"091-mask-rect-props.aep",
|
||||
"093-mask-path-2keys.aep",
|
||||
"110-text-A.aep",
|
||||
"113-text-Hello-size60-fillorange.aep",
|
||||
"122-marker-comp-1s.aep",
|
||||
"123-marker-layer-1s.aep",
|
||||
"124-precomp-Pre.aep",
|
||||
"126-footage-png-layer.aep",
|
||||
"202-key-out-hold-in-linear.aep",
|
||||
"203-key-in-hold-out-linear.aep",
|
||||
"204-key-ease-asymmetric.aep",
|
||||
"205-key-opacity-ease-asymmetric.aep",
|
||||
"206-key-scale-2key-linear.aep",
|
||||
"208-key-mask-feather-2key-linear.aep",
|
||||
"210-key-fill-color-2key-linear.aep",
|
||||
"211-anchor-100x100-solid-10-20.aep",
|
||||
"212-anchor-400x300-solid-100-50.aep",
|
||||
"213-expr-opacity-wiggle-disabled.aep",
|
||||
"214-fx-gaussianblur-default.aep",
|
||||
"215-fx-fill-default.aep",
|
||||
"216-fx-gaussianblur-40.aep",
|
||||
"217-fx-checkbox-on.aep",
|
||||
"218-fx-point-111-222.aep",
|
||||
"219-fx-angle-90.aep",
|
||||
"220-fx-layercontrol-to-layer1.aep",
|
||||
"221-fx-slider-2key.aep",
|
||||
"222-layer-video-off.aep",
|
||||
"223-layer-audio-off.aep",
|
||||
"224-layer-effects-off.aep",
|
||||
"225-layer-blend-screen.aep",
|
||||
"226-layer-blend-add.aep",
|
||||
"227-layer-blend-overlay.aep",
|
||||
"228-layer-blend-difference.aep",
|
||||
"229-comp-fps-29.97.aep",
|
||||
"230-comp-fps-23.976.aep",
|
||||
"231-comp-bg-grey-0.5.aep",
|
||||
"232-mask-ellipse.aep",
|
||||
"233-mask-open-path.aep",
|
||||
"234-mask-mode-intersect.aep",
|
||||
"235-mask-mode-lighten.aep",
|
||||
"236-mask-mode-darken.aep",
|
||||
"237-mask-mode-difference.aep",
|
||||
"238-shape-rect-rounded-corners.aep",
|
||||
"239-shape-stroke-green-w8-round.aep",
|
||||
"240-shape-custom-path-tangents.aep",
|
||||
"241-shape-gradient-fill-linear.aep",
|
||||
"242-shape-group-position-50-50.aep",
|
||||
"243-text-multiline-A-CR-B.aep",
|
||||
"245-text-box-400x200-Hello.aep",
|
||||
"246-text-box-center-align.aep",
|
||||
"247-text-tracking-100.aep",
|
||||
"248-text-range-fill-red-1-3.aep",
|
||||
"249-marker-layer-full.aep",
|
||||
"251-camera-one-node.aep",
|
||||
"252-light-point.aep",
|
||||
"253-camera-position-100-200-m1000.aep",
|
||||
"254-light-spot-intensity-50.aep",
|
||||
"256-camera-two-node-default.aep",
|
||||
"259-solid-blue-0-0-1.aep",
|
||||
"299-save-noise.aep",
|
||||
"300-fx-gaussianblur-0-explicit.aep",
|
||||
"301-fx-gaussianblur-40-then-25.aep",
|
||||
"302-fx-fill-opacity-100-explicit.aep",
|
||||
"303-fx-fill-opacity-50-then-100.aep",
|
||||
"304-fx-slider-0-explicit.aep",
|
||||
"305-key-scale-bezier-ease.aep",
|
||||
"306-key-maskfeather-bezier-ease.aep",
|
||||
"307-key-fillcolor-bezier.aep",
|
||||
"309-solid-100x100-mask-rect.aep",
|
||||
"310-solid-100x100-pointcontrol.aep",
|
||||
"311-position-default-explicit.aep",
|
||||
"316-layer-stretch50.aep",
|
||||
"317-layer-stretch150.aep",
|
||||
"318-layer-inpoint-0.3333.aep",
|
||||
"319-precomp-timeremap.aep",
|
||||
"320-fx-layercontrol-self-explicit.aep",
|
||||
"321-fx-layercontrol-none.aep",
|
||||
"323-fx-dropdown-5items.aep",
|
||||
"324-fx-dropdown-5items-select3.aep",
|
||||
"325-comp-pixelaspect-0.9091.aep",
|
||||
"326-comp-shutterphase-m90.aep",
|
||||
"327-comp-displaystartframe-100.aep",
|
||||
"328-mask-two-ellipse-rect.aep",
|
||||
"329-mask-ellipse-mode-none.aep",
|
||||
"330-shape-polystar-star-5-50-100.aep",
|
||||
"331-shape-polystar-polygon-5-100.aep",
|
||||
"332-shape-gradient-fill-radial.aep",
|
||||
"333-shape-group-two-rects.aep",
|
||||
"334-text-box-right-align.aep",
|
||||
"335-text-point-fauxbold.aep",
|
||||
"336-text-point-fauxitalic.aep",
|
||||
"337-text-point-allcaps.aep",
|
||||
"338-text-point-smallcaps.aep",
|
||||
"339-text-point-leading60.aep",
|
||||
"340-text-range-two-styles.aep",
|
||||
"341-camera-zoom-2000.aep",
|
||||
"342-camera-dof-800-30.aep",
|
||||
"343-light-spot-color-red.aep",
|
||||
"344-light-spot-coneangle-60.aep",
|
||||
"345-light-spot-conefeather-30.aep",
|
||||
"347-marker-layer-label3.aep",
|
||||
"348-marker-layer-navigation-cue.aep",
|
||||
"349-marker-layer-event-cue-params.aep",
|
||||
"350-footage-wav-imported.aep",
|
||||
"351-footage-wav-as-layer.aep",
|
||||
"352-footage-pngseq-imported.aep",
|
||||
"354-footage-pngseq-timeremap.aep",
|
||||
"356-fx-tint-default.aep",
|
||||
"357-fx-tint-black-0.2-0.4-0.6.aep",
|
||||
"361-fx-tint-amount-0.aep",
|
||||
"363-fx-tint-amount-2key.aep",
|
||||
"364-fx-tint-white-2key.aep",
|
||||
"366-fx-blur-then-tint.aep",
|
||||
"368-fx-ramp-default.aep",
|
||||
"369-fx-ramp-start-100-200.aep",
|
||||
"371-fx-ramp-startcolor-red.aep",
|
||||
"374-fx-ramp-end-2000-m100.aep",
|
||||
"377-fx-ramp-shape-radial.aep",
|
||||
"378-fx-ramp-scatter-12.aep",
|
||||
"380-fx-ramp-blend-25pct.aep",
|
||||
"382-fx-ramp-start-2key.aep",
|
||||
"383-fx-ramp-on-100x100-start-10-20.aep",
|
||||
"389-fx-exposure-default.aep",
|
||||
"390-fx-exposure-channels-individual.aep",
|
||||
"391-fx-exposure-master-1.5.aep",
|
||||
"393-fx-exposure-offset-0.1.aep",
|
||||
"394-fx-exposure-gamma-2.2.aep",
|
||||
"395-fx-exposure-individual-red-1.aep",
|
||||
"396-fx-exposure-bypass-on.aep",
|
||||
"397-fx-exposure-master-2key.aep",
|
||||
"403-matte-L-alpha-M.aep",
|
||||
"404-matte-L-alphainv-M.aep",
|
||||
"405-matte-L-luma-M.aep",
|
||||
"406-matte-L-lumainv-M.aep",
|
||||
"407-matte-M-alpha-L-below.aep",
|
||||
"408-matte-L-alpha-M-visible.aep",
|
||||
"509-marker-comp-two.aep",
|
||||
"510-marker-layer-0.52-dur0.3.aep",
|
||||
"451-shape-ellipse-400x300-fill.aep",
|
||||
"457-shape-group-scale-50-80.aep",
|
||||
"462-shape-layer-anchor-10-20.aep",
|
||||
"464-shape-stroke-opacity-50.aep",
|
||||
"467-shape-trim-end-70.aep",
|
||||
"469-shape-trim-type-2.aep",
|
||||
"471-shape-rect-roundness-30.aep",
|
||||
"473-shape-star-points-6.aep",
|
||||
"482-shape-two-groups.aep",
|
||||
"483-shape-nested-group-rect.aep",
|
||||
"519-shape-all-items-default.aep",
|
||||
"410-fx-invert-channel-2.aep",
|
||||
"411-fx-invert-blend-50.aep",
|
||||
"413-fx-fastbox-radius-20.aep",
|
||||
"414-fx-fastbox-iterations-1.aep",
|
||||
"416-fx-fastbox-repeatedge-off.aep",
|
||||
"418-fx-gaussian-dimensions-3.aep",
|
||||
"419-fx-gaussian-repeatedge-off.aep",
|
||||
"422-fx-dropshadow-opacity-204.aep",
|
||||
"426-fx-dropshadow-shadowonly-on.aep",
|
||||
"427-fx-glow-default.aep",
|
||||
"429-fx-glow-threshold-76.5.aep",
|
||||
"438-fx-glow-midpoint-0.25.aep",
|
||||
"444-fx-huesat-hue-90.aep",
|
||||
"446-fx-huesat-light-m30.aep",
|
||||
"448-fx-huesat-colorizehue-120.aep",
|
||||
"512-fx-levels-inblack-0.1.aep",
|
||||
"514-fx-levels-gamma-2.aep",
|
||||
"516-fx-levels-outwhite-0.9.aep",
|
||||
"517-text-box-600x400-wrap.aep",
|
||||
"526-text-point-HHHH-default.aep",
|
||||
"527-text-point-HHHH-baseline-normal.aep",
|
||||
"528-text-point-HHHH-baseline-subscript.aep",
|
||||
"485-layer-3d-on.aep",
|
||||
"486-layer-3d-rotx-30.aep",
|
||||
"487-layer-3d-roty-45.aep",
|
||||
"488-layer-3d-orientation-10-20-30.aep",
|
||||
"529-fx-timewarp-default.aep",
|
||||
"530-fx-timewarp-speed-25.aep",
|
||||
"531-fx-timewarp-speed-keyed-50-200.aep",
|
||||
"532-fx-timewarp-method-1.aep",
|
||||
"533-fx-timewarp-sourceframe-12.aep",
|
||||
"534-fx-slider-expression-time10.aep",
|
||||
"535-camera-position-on-3d-rotx.aep",
|
||||
"536-camera-one-node-position-on-3d-rotx.aep",
|
||||
"537-camera-default-on-3d-rotx.aep",
|
||||
"538-text-point-HHHH-normal-ref.aep",
|
||||
"539-text-hscale-0.9.aep",
|
||||
"540-text-vscale-1.5.aep",
|
||||
"541-text-baselineshift-41.aep",
|
||||
"542-text-autokern-none.aep",
|
||||
"543-text-autokern-optical.aep",
|
||||
"544-text-applystroke-on.aep",
|
||||
"545-text-strokewidth-5.aep",
|
||||
"546-text-applyfill-off.aep",
|
||||
"548-text-linejoin-round.aep",
|
||||
"550-text-strokeoverfill-off.aep",
|
||||
"552-text-nobreak-on.aep",
|
||||
"553-text-tsume-0.5.aep",
|
||||
"554-text-kerning-50.aep",
|
||||
"555-text-ligature-on.aep",
|
||||
"556-text-autohyphenate-off.aep",
|
||||
"558-text-hangingroman-on.aep",
|
||||
"559-text-everyline-on.aep",
|
||||
"560-text-firstlineindent-20.aep",
|
||||
"561-text-startindent-30.aep",
|
||||
"562-text-endindent-40.aep",
|
||||
"563-text-spacebefore-10.aep",
|
||||
"564-text-spaceafter-12.aep",
|
||||
"565-text-justify-fullleft.aep",
|
||||
"566-text-justify-fullcenter.aep",
|
||||
"567-text-justify-fullright.aep",
|
||||
"568-text-justify-fullall.aep",
|
||||
"569-text-direction-rtl.aep",
|
||||
"571-text-digitset-arabic.aep",
|
||||
"572-text-leadingtype-japanese.aep",
|
||||
"573-text-baselinedir-rotated.aep",
|
||||
"575-text-vertical-rtl.aep",
|
||||
"576-text-baselinedir-crossstream.aep",
|
||||
"578-text-digitset-hindi.aep",
|
||||
"595-text-stroke-scale-shift-combined.aep",
|
||||
"596-text-combined-fill-over-stroke.aep",
|
||||
"579-textanim-position-0-m50.aep",
|
||||
"580-textanim-start-25.aep",
|
||||
"581-textanim-end-75.aep",
|
||||
"582-textanim-offset-10.aep",
|
||||
"583-textanim-units-index.aep",
|
||||
"584-textanim-basedon-3-words.aep",
|
||||
"585-textanim-mode-2-subtract.aep",
|
||||
"586-textanim-amount-50.aep",
|
||||
"587-textanim-shape-2-rampup.aep",
|
||||
"588-textanim-smoothness-50.aep",
|
||||
"589-textanim-easehigh-30.aep",
|
||||
"590-textanim-easelow-40.aep",
|
||||
"591-textanim-randomize-seed-7.aep",
|
||||
"592-textanim-many-props.aep",
|
||||
"593-textanim-start-keyed-ease-0-100.aep",
|
||||
"594-textanim-position-start-keyed-ease.aep",
|
||||
"725-text-point-HHHH-normal-ref-S18.aep",
|
||||
"727-text-reset-paragraph.aep",
|
||||
"728-textanim-character-offset-3.aep",
|
||||
"711-fx-directional-blur-30-40-on-M.aep",
|
||||
"712-fx-eleven-effects-defaults-on-M.aep",
|
||||
"713-fx-radial-blur-zoom-20-on-M.aep",
|
||||
"714-fx-ccradial-type2-30-60-on-M.aep",
|
||||
"715-fx-venetian-40-30-50-5-on-M.aep",
|
||||
"716-fx-channel-blur-5-10-15-20-edge-horiz-on-M.aep",
|
||||
"717-fx-blackwhite-set-tint-on-L.aep",
|
||||
"718-fx-tritone-set-blend25-on-L.aep",
|
||||
"719-fx-lumakey-darker-140-20-1-2.5-on-M.aep",
|
||||
"720-fx-simplechoker-3.5-on-M.aep",
|
||||
"721-fx-simplechoker-3.5-view-matte-on-M.aep",
|
||||
"722-fx-mattechoker-set-on-M.aep",
|
||||
"723-fx-transform-set-on-M.aep",
|
||||
"597-key-anchor-ease-out50-40-in30-60.aep",
|
||||
"598-key-ramp-point-ease-color-bezier.aep",
|
||||
"599-key-mask-path-ease-infl75.aep",
|
||||
"700-key-mask-path-ease-out20-in50.aep",
|
||||
"701-light-parallel-int80-color.aep",
|
||||
"702-light-ambient-int50-color.aep",
|
||||
"703-key-orientation-0-to-10-20-30-linear.aep",
|
||||
"704-light-environment-default.aep",
|
||||
"705-mask-on-text-rect-40-m70-160-10.aep",
|
||||
"706-mask-on-shape-rect-0-m150-100-150.aep",
|
||||
"707-shape-merge-subtract-rect-ellipse.aep",
|
||||
"708-shape-merge-intersect-rect-ellipse.aep",
|
||||
"709-shape-repeater-3-pos150-60-rot10-scale90-80-op40.aep",
|
||||
"710-shape-offset-paths-20-round.aep",
|
||||
"730-key-anchor-ease-on-400x800-solid.aep",
|
||||
"731-shape-merge-offset-repeater-defaults.aep",
|
||||
"732-text-box-byteedit-para24-0.aep",
|
||||
"733-text-box-byteedit-para35-0.aep",
|
||||
"734-text-box-byteedit-style68-1.aep",
|
||||
"828-shape-offset-paths-20-copies3-copyoffset1.5-stroke.aep",
|
||||
"851-shape-key-trim-end-0-100-linear.aep",
|
||||
"852-shape-key-trim-end-bezier-out0-60-in20-30.aep",
|
||||
"853-shape-key-group-position-0-200-100-linear.aep",
|
||||
"854-shape-key-fill-color-red-blue-linear.aep",
|
||||
"855-shape-key-trim-offset-0-90-hold.aep",
|
||||
"856-shape-trim-end-expression-time50.aep",
|
||||
"857-shape-key-group-scale-100-50-150-linear.aep",
|
||||
"900-mask-added-no-path.aep",
|
||||
"901-mask-no-path-expansion-m100.aep",
|
||||
"902-settings-rec709-16bpc-steps-png-grey-solid.aep",
|
||||
"905-fx-24-effects-set-one-comp.aep",
|
||||
"906-blendmodes-13-solids-on-steps.aep",
|
||||
"963-curves-red-mid-down-on-S.aep",
|
||||
"964-curves-rgb-s-curve-on-S.aep",
|
||||
"951-styles-all-nine-defaults-on-B.aep",
|
||||
"966-style-drop-shadow-opacity50-distance20.aep",
|
||||
"970-style-stroke-size10-color-green.aep",
|
||||
"974-style-gradient-overlay-angle45-scale150.aep",
|
||||
"975-style-fill-opacity0-with-drop-shadow.aep",
|
||||
"976-style-drop-shadow-opacity-keyed-100-20-linear.aep",
|
||||
"977-styles-all-params-changed.aep",
|
||||
"979-style-inner-glow-source-2.aep",
|
||||
"981-layer-stretch-minus100-start5.aep",
|
||||
"982-layer-stretch-minus100-opacity-keys.aep",
|
||||
"983-layer-stretch-minus50-opacity-keys.aep",
|
||||
"985-meshwarp-3x3-vertex-moved-on-S.aep",
|
||||
"986-shape-fill-switched-off-green.aep",
|
||||
"988-style-drop-shadow-switched-off.aep",
|
||||
];
|
||||
|
||||
use effectcraft_aep::{AepFile, Comp, Layer, LayerType, Project, parse};
|
||||
|
||||
/// Parses a fixture; the bytes must outlive the file, so the caller keeps them.
|
||||
pub fn open(bytes: &[u8]) -> AepFile<'_> {
|
||||
parse(bytes).expect("fixture parses")
|
||||
}
|
||||
|
||||
/// The first composition of a project (comp `C` in the corpus; in 124 the precomp `Pre` comes later).
|
||||
pub fn first_comp<'f, 'a>(project: &Project<'f, 'a>) -> Comp<'f, 'a> {
|
||||
project.all_items().into_iter().find_map(|i| i.comp()).expect("a composition")
|
||||
}
|
||||
|
||||
/// The solid `L` of the base composition: the bottom layer (the first one made; id 0x1b in the
|
||||
/// single-case files, another id in each case of a combined file).
|
||||
pub fn base_layer<'f, 'a>(comp: &Comp<'f, 'a>) -> Layer<'f, 'a> {
|
||||
comp.layers().last().expect("a layer")
|
||||
}
|
||||
|
||||
/// The layer with this id in a composition.
|
||||
pub fn layer_with_id<'f, 'a>(comp: &Comp<'f, 'a>, id: u32) -> Layer<'f, 'a> {
|
||||
comp.layers().find(|l| l.id() == Some(id)).unwrap_or_else(|| panic!("no layer with id {id:#x}"))
|
||||
}
|
||||
|
||||
/// The layer with this user-set name in a composition.
|
||||
pub fn layer_named<'f, 'a>(comp: &Comp<'f, 'a>, name: &str) -> Layer<'f, 'a> {
|
||||
comp.layers().find(|l| l.name().as_deref() == Some(name)).unwrap_or_else(|| panic!("no layer named {name}"))
|
||||
}
|
||||
|
||||
/// The layer that shows this name: its own name, or its source's while it has none.
|
||||
pub fn layer_shown_as<'f, 'a>(project: &Project<'f, 'a>, comp: &Comp<'f, 'a>, name: &str) -> Layer<'f, 'a> {
|
||||
comp.layers().find(|l| project.layer_display_name(l).as_deref() == Some(name)).unwrap_or_else(|| panic!("no layer shown as {name}"))
|
||||
}
|
||||
|
||||
/// The first layer of this type in a composition.
|
||||
pub fn layer_of_type<'f, 'a>(comp: &Comp<'f, 'a>, layer_type: LayerType) -> Layer<'f, 'a> {
|
||||
comp.layers().find(|l| l.header().is_some_and(|h| h.layer_type == layer_type)).unwrap_or_else(|| panic!("no {layer_type:?} layer"))
|
||||
}
|
||||
|
||||
/// A copy of a layer's `LIST Layr` with its id (`ldta` bytes 0-3) set to 0, for comparing the
|
||||
/// same layer in two cases of a combined file.
|
||||
pub fn without_layer_id(layer: &effectcraft_aep::Chunk<'_>) -> effectcraft_aep::Chunk<'static> {
|
||||
let mut c = layer.clone().into_owned();
|
||||
if let effectcraft_aep::Body::List { children, .. } = &mut c.body
|
||||
&& let Some(ldta) = children.iter_mut().find(|x| x.is(b"ldta"))
|
||||
&& let effectcraft_aep::Body::Data(d) = &mut ldta.body
|
||||
{
|
||||
d.to_mut()[..4].fill(0);
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// Compares floats with a tolerance.
|
||||
pub fn near(a: f64, b: f64, tol: f64) -> bool {
|
||||
(a - b).abs() <= tol
|
||||
}
|
||||
|
||||
pub fn assert_near(got: &[f64], want: &[f64], tol: f64) {
|
||||
assert_eq!(got.len(), want.len(), "{got:?} vs {want:?}");
|
||||
for (g, w) in got.iter().zip(want) {
|
||||
assert!(near(*g, *w, tol), "{got:?} != {want:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
//! Keyframe interpolation sides and ease, the record layouts per template, the anchor point
|
||||
//! normalisation and the disabled-expression flag, checked against the values the corpus was made
|
||||
//! with (its MANIFEST, batch 2). The solid `L` is 1920x1080 in a 1920x1080 composition.
|
||||
|
||||
use crate::container::helpers::{assert_near, base_layer, first_comp, layer_shown_as, open};
|
||||
use effectcraft_aep::{Interpolation, KeyEase, KeyframeKind, Project, PropNode, Property, ValueSource};
|
||||
|
||||
fn prop_of<R>(name: &str, path: &[&str], f: impl FnOnce(Property<'_, '_>) -> R) -> Option<R> {
|
||||
Some({
|
||||
let bytes = crate::common::try_fixture(name)?;
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let Some(PropNode::Property(p)) = layer.properties().unwrap().find(path) else { panic!("{name}: no {path:?}") };
|
||||
f(p)
|
||||
})
|
||||
}
|
||||
|
||||
const POSITION: &[&str] = &["ADBE Transform Group", "ADBE Position"];
|
||||
const OPACITY: &[&str] = &["ADBE Transform Group", "ADBE Opacity"];
|
||||
|
||||
fn ease(in_speed: f64, in_influence: f64, out_speed: f64, out_influence: f64) -> KeyEase {
|
||||
KeyEase { in_speed, in_influence, out_speed, out_influence }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_and_out_interpolation_are_separate_bytes() {
|
||||
// 202: Position keys at 0 s [0,0,0] and 1 s [100,0,0]; key 1 inType LINEAR, outType HOLD (record bytes 01 03).
|
||||
skip!(prop_of("202-key-out-hold-in-linear.aep", POSITION, |p| {
|
||||
let keys: Vec<_> = p.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert_eq!(&keys[0].raw()[4..6], [1, 3]);
|
||||
assert_eq!((keys[0].interpolation_in(), keys[0].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Hold)));
|
||||
assert_eq!((keys[1].interpolation_in(), keys[1].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear)));
|
||||
assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::<Vec<_>>(), [0.0, 1.0]);
|
||||
assert_eq!(keys[1].spatial_value(), Some([100.0, 0.0, 0.0]));
|
||||
}));
|
||||
// 203: key 1 inType HOLD, outType LINEAR (bytes 03 01): byte 4 is the incoming side.
|
||||
skip!(prop_of("203-key-in-hold-out-linear.aep", POSITION, |p| {
|
||||
let keys: Vec<_> = p.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(&keys[0].raw()[4..6], [3, 1]);
|
||||
assert_eq!((keys[0].interpolation_in(), keys[0].interpolation_out()), (Some(Interpolation::Hold), Some(Interpolation::Linear)));
|
||||
assert_eq!((keys[1].interpolation_in(), keys[1].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear)));
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_ease_slots_in_speed_influence_out_speed_influence() {
|
||||
// 204: key 1 inSpeed 5 / inInfluence 20, outSpeed 50 / outInfluence 80; key 2 in 7 / 60, out 9 / 40.
|
||||
// After Effects reads key 1's in speed and key 2's out speed back as 0; the file keeps 5 and 9.
|
||||
skip!(prop_of("204-key-ease-asymmetric.aep", POSITION, |p| {
|
||||
let keys: Vec<_> = p.keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys[0].ease(), Some(ease(5.0, 0.2, 50.0, 0.8)));
|
||||
assert_eq!(keys[1].ease(), Some(ease(7.0, 0.6, 9.0, 0.4)));
|
||||
for k in &keys {
|
||||
assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier)));
|
||||
assert_eq!(k.kind(), KeyframeKind::Spatial { components: 3 });
|
||||
}
|
||||
// The spatial record gives the same four slots.
|
||||
assert_eq!(keys[0].spatial().unwrap().ease, [5.0, 0.2, 50.0, 0.8]);
|
||||
// The arc length of the segment to the next key (100 px) is on key 1, none on the last key.
|
||||
assert_eq!(keys.iter().map(|k| k.spatial().unwrap().segment_length).collect::<Vec<_>>(), [100.0, 0.0]);
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_ease_speed_is_in_stored_units_per_second() {
|
||||
// 205: Opacity 0 at 0 s, 100 at 2 s; key 1 in 5 / 20 %, out 20 / 80 %; key 2 in 30 / 60 %, out 9 / 40 %.
|
||||
// The speed is in stored value units (fractions), 100 times smaller than the UI value; the influence is a fraction.
|
||||
skip!(prop_of("205-key-opacity-ease-asymmetric.aep", OPACITY, |p| {
|
||||
let keys: Vec<_> = p.keys().unwrap().keyframes().collect();
|
||||
assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Plain { components: 1 } && k.raw().len() == 48));
|
||||
assert_eq!(keys.iter().map(|k| k.scalar_value().unwrap()).collect::<Vec<_>>(), [0.0, 1.0]);
|
||||
assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::<Vec<_>>(), [0.0, 2.0]);
|
||||
let e0 = keys[0].ease().unwrap();
|
||||
assert_near(&[e0.in_speed, e0.in_influence, e0.out_speed, e0.out_influence], &[0.05, 0.2, 0.2, 0.8], 1e-12);
|
||||
let e1 = keys[1].ease().unwrap();
|
||||
assert_near(&[e1.in_speed, e1.in_influence, e1.out_speed, e1.out_influence], &[0.3, 0.6, 0.09, 0.4], 1e-12);
|
||||
assert_eq!(keys[0].plain_ease_slots().unwrap().len(), 4);
|
||||
for k in &keys {
|
||||
assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier)));
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_keys_use_the_plain_template_with_three_components() {
|
||||
// 206: Scale keys at 0 s [100,100,100] and 1 s [200,150,100], linear: 128-byte plain records.
|
||||
skip!(prop_of("206-key-scale-2key-linear.aep", &["ADBE Transform Group", "ADBE Scale"], |p| {
|
||||
assert_eq!(p.dims(), Some(3));
|
||||
let keys: Vec<_> = p.keys().unwrap().keyframes().collect();
|
||||
for k in &keys {
|
||||
assert_eq!(k.raw().len(), 128);
|
||||
// A 128-byte record is not always spatial: the header's template flag decides.
|
||||
assert_eq!(k.kind(), KeyframeKind::Plain { components: 3 });
|
||||
assert_eq!(k.spatial(), None);
|
||||
assert_eq!(k.plain_ease_slots(), Some(vec![0.0; 12]));
|
||||
assert_eq!(k.ease(), None);
|
||||
assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear)));
|
||||
}
|
||||
assert_eq!(keys.iter().map(|k| k.value().unwrap()).collect::<Vec<_>>(), [vec![1.0, 1.0, 1.0], vec![2.0, 1.5, 1.0]]);
|
||||
assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::<Vec<_>>(), [0.0, 1.0]);
|
||||
assert_eq!(p.first_key_value(), Some(vec![1.0, 1.0, 1.0]));
|
||||
}));
|
||||
// The transform reports the first key as percent (before the template flag was used it read the wrong bytes).
|
||||
let bytes = fixture!("206-key-scale-2key-linear.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let t = layer.transform(1920, 1080).unwrap();
|
||||
assert_eq!((t.scale_percent.source, t.scale_percent.value), (ValueSource::Keyframed, [100.0, 100.0, 100.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_dimensional_mask_feather_keys() {
|
||||
// 208: Mask Feather keys at 0 s [0,0] and 1 s [40,20], linear: 88-byte plain records with two components.
|
||||
let bytes = fixture!("208-key-mask-feather-2key-linear.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let Some(PropNode::Group(parade)) = layer.properties().unwrap().get("ADBE Mask Parade") else { panic!("no mask parade") };
|
||||
let Some(PropNode::Group(atom)) = parade.get("ADBE Mask Atom") else { panic!("no mask atom") };
|
||||
let Some(PropNode::Property(feather)) = atom.get("ADBE Mask Feather") else { panic!("no feather") };
|
||||
let keys: Vec<_> = feather.keys().unwrap().keyframes().collect();
|
||||
assert!(keys.iter().all(|k| k.raw().len() == 88 && k.kind() == KeyframeKind::Plain { components: 2 }));
|
||||
assert_eq!(keys.iter().map(|k| k.value().unwrap()).collect::<Vec<_>>(), [vec![0.0, 0.0], vec![40.0, 20.0]]);
|
||||
assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::<Vec<_>>(), [0.0, 1.0]);
|
||||
assert_eq!(keys[0].plain_ease_slots(), Some(vec![0.0; 8]));
|
||||
let mask = &layer.masks()[0];
|
||||
assert!(mask.feather.source == ValueSource::Keyframed && mask.feather.value == [0.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_keys_use_the_spatial_template_with_four_components() {
|
||||
// 210: Fill colour keys at 0 s [1,0,0] and 1 s [0,0.5,1], linear: 152-byte records, ARGB doubles 0..255 at byte 56.
|
||||
let bytes = fixture!("210-key-fill-color-2key-linear.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let effects = layer.effects();
|
||||
assert_eq!(effects.len(), 1);
|
||||
let params = effects[0].params();
|
||||
let color = params.iter().find(|p| p.name == "Color").unwrap();
|
||||
let keys: Vec<_> = color.stored().unwrap().keys().unwrap().keyframes().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
for k in &keys {
|
||||
assert_eq!(k.raw().len(), 152);
|
||||
assert_eq!(k.kind(), KeyframeKind::Spatial { components: 4 });
|
||||
assert_eq!(k.flags(), Some(0x0001));
|
||||
let s = k.spatial().unwrap();
|
||||
assert_eq!(s.in_tangent, [0.0; 4]);
|
||||
assert_eq!(s.out_tangent, [0.0; 4]);
|
||||
}
|
||||
assert_eq!(keys[0].value(), Some(vec![255.0, 255.0, 0.0, 0.0]));
|
||||
assert_eq!(keys[1].value(), Some(vec![255.0, 0.0, 127.5, 255.0]));
|
||||
assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::<Vec<_>>(), [0.0, 1.0]);
|
||||
// A keyframed parameter has no single stored value.
|
||||
assert_eq!(color.stored_value(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyed_slider_uses_48_byte_records() {
|
||||
// 221: Slider Control, Slider keyed 10 at 0 s and 90 at 2 s (linear).
|
||||
let bytes = fixture!("221-fx-slider-2key.aep");
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let layer = base_layer(&first_comp(&project));
|
||||
let params = project.effect_params(&layer.effects()[0]);
|
||||
let slider = params.iter().find(|p| p.name == "Slider").unwrap();
|
||||
let stored = slider.stored().unwrap();
|
||||
assert!(stored.is_animated());
|
||||
assert_eq!(stored.static_value(), None);
|
||||
let keys: Vec<_> = stored.keys().unwrap().keyframes().collect();
|
||||
assert!(keys.iter().all(|k| k.raw().len() == 48));
|
||||
assert_eq!(keys.iter().filter_map(|k| k.scalar_value()).collect::<Vec<_>>(), [10.0, 90.0]);
|
||||
assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::<Vec<_>>(), [0.0, 2.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchor_is_a_fraction_of_the_layer_source_size() {
|
||||
// 211: a new 100x100 solid in the 1920x1080 composition, Anchor Point [50,50,0] -> [10,20,0], stored [0.1, 0.2, 0].
|
||||
// 212: a 400x300 solid, Anchor Point [100,50,0], stored [0.25, 1/6, 0]. The composition size is not the divisor.
|
||||
for (name, solid, size, fraction, px) in [
|
||||
("211-anchor-100x100-solid-10-20.aep", "S100", (100, 100), [0.1, 0.2, 0.0], [10.0, 20.0, 0.0]),
|
||||
("212-anchor-400x300-solid-100-50.aep", "S400", (400, 300), [0.25, 1.0 / 6.0, 0.0], [100.0, 50.0, 0.0]),
|
||||
] {
|
||||
let bytes = fixture!(name);
|
||||
let file = open(&bytes);
|
||||
let project = Project::new(&file).unwrap();
|
||||
let comp = first_comp(&project);
|
||||
let layer = layer_shown_as(&project, &comp, solid);
|
||||
assert_eq!(project.layer_source_size(&layer), Some(size), "{name}");
|
||||
let t = layer.transform(1920, 1080).unwrap();
|
||||
assert_eq!(t.anchor_fraction.source, ValueSource::Stored);
|
||||
assert_near(&t.anchor_fraction.value, &fraction, 1e-12);
|
||||
let anchor = project.layer_anchor_px(&layer).unwrap();
|
||||
assert_eq!(anchor.source, ValueSource::Stored);
|
||||
assert_near(&anchor.value, &px, 1e-9);
|
||||
// Position stays at the default, the composition centre.
|
||||
assert_eq!((t.position.source, t.position.value), (ValueSource::Default, [960.0, 540.0, 0.0]));
|
||||
// L is unchanged: the anchor is its centre.
|
||||
let l = base_layer(&comp);
|
||||
let a = project.layer_anchor_px(&l).unwrap();
|
||||
assert_eq!((a.source, a.value), (ValueSource::Default, [960.0, 540.0, 0.0]));
|
||||
}
|
||||
}
|
||||
|
||||
fn expression_state(name: &str) -> Option<(Option<String>, Option<bool>, bool, bool)> {
|
||||
Some({
|
||||
prop_of(name, OPACITY, |p| {
|
||||
let f = p.expression_flags().unwrap();
|
||||
// Byte 120 marks the expression (bytes 76 and 77 are not always set with it).
|
||||
(p.expression(), p.expression_enabled(), f.byte_120 == 1, f.disabled())
|
||||
})?
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_expression_keeps_its_text() {
|
||||
// 060: Opacity wiggle(1,10), enabled; 213: the same expression after expression.disable_all.
|
||||
assert_eq!(skip!(expression_state("060-expr-opacity-wiggle.aep")), (Some("wiggle(1,10)".to_string()), Some(true), true, false));
|
||||
assert_eq!(skip!(expression_state("213-expr-opacity-wiggle-disabled.aep")), (Some("wiggle(1,10)".to_string()), Some(false), true, true));
|
||||
// Only byte 119 differs between the two property headers.
|
||||
let header = |name: &str| prop_of(name, OPACITY, |p| p.header().unwrap().to_vec());
|
||||
let (enabled, disabled) = (skip!(header("060-expr-opacity-wiggle.aep")), skip!(header("213-expr-opacity-wiggle-disabled.aep")));
|
||||
let differing: Vec<_> = (0..enabled.len()).filter(|i| enabled[*i] != disabled[*i]).collect();
|
||||
assert_eq!(differing, [119]);
|
||||
// A property without an expression has no enabled state.
|
||||
assert_eq!(skip!(prop_of("058-key-opacity-2key.aep", OPACITY, |p| p.expression_enabled())), None);
|
||||
}
|
||||
Loaded 100 of 610 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user