Merge upstream/main into aep-import-thirdparty

#3119 (the base of this branch) is merged. Conflicts with the Cryptomatte
import (#3109) and the version report: Extra keeps Extractor, Identifier
and Cryptomatte, arbitrary.rs keeps ExtractorChannels /
identifier_channel_type next to CryptomatteData, the effect table counts
66, the docs keep both sides. The exporter from #2594 gets the Extractor
and Identifier arms: like Lumetri they have no prototype, so CC Color
Neutralizer, EXtractoR and IDentifier are reported, not written (new
test imported_plug_in_effects_are_reported_not_written).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76andClaude Opus 5.5 committed 2026-11-06 23:11:22 +01:00
commit 4e9fcee1c5
231 files changed
+29273 -954

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
+66 -3
View File
@@ -1,3 +1,56 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# EffectCraft — rules for agents and contributors
These rules apply to every human and AI contributor. `CLAUDE.md` holds the working instructions; this
@@ -102,10 +155,20 @@ reproduce an image (for example, point lists traced from someone else's icon).
## 3. Engineering rules
See `CLAUDE.md`: pure Rust, dependency layering (`cargo xtask layers`), exact `Tick` time, everything is
a command, everything is agent-drivable, and the quality gates (`cargo xtask ci`) before every commit.
- **Layering** (`cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd/cpal; L0–L4 build for wasm32.
- **Exact time:** `effectcraft_time::Tick` (254 016 000 000/s). Keyframe times are layer time.
- **Property tree:** everything animatable is a `Property` in the layer's `PropGroup` tree, addressed by paths (`transform/position`, `effects/#1/blurriness`, `@uid`).
- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP dispatch by id.
- **Everything is agent-drivable:** every interactive widget registers an automation id; UI state is serde.
- **Community links** (Help menu, About, header Discord button): https://discord.gg/artcraft, https://getartcraft.com, https://getartcraft.com/apps/effectcraft, https://github.com/storytold/effectcraft.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm).
- New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
- **Commits:** one task id per commit (`M6.3: trim paths`). Only green states.
- `cargo run -p effectcraft -- --control 9877` opens the desktop app with the JSON-lines control server (`docs/control-protocol.md`). For UI work, look at the result, including the headless `snapshot` example.
- `plan/` is an optional gitignored notebook (`plan/aftereffects/` may hold reference notes and captures). Do not ask for it, do not stop when it is absent, and never commit those captures.
- Read [`docs/gaps.md`](docs/gaps.md) and [`docs/target-app-parity.md`](docs/target-app-parity.md) before choosing work. Fidelity, reliability and stability (G1–G3) come before new features.
- Some workflow files still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in
[`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus).
+1 -37
View File
@@ -1,37 +1 @@
# EffectCraft — instructions for agents
EffectCraft is a clean-room, open-source, pure-Rust motion graphics and visual effects compositor targeting Adobe After Effects parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom) and `../designcraft` (InDesign), with the same conventions.
## Start every session here
`plan/` is maintainer-local (gitignored). Public equivalents: [`ROADMAP.md`](ROADMAP.md), [`docs/`](docs/).
1. Read `plan/STATUS.md` (current milestone, next task, running agents, blockers).
2. Read the task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the crate README/docs you touch. Feature ids: `plan/aftereffects/feature-catalog.md`; effects: `plan/aftereffects/effects-list.md`; UI reference: `plan/aftereffects/README.md`.
3. Read [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked, and the prioritised workstreams; the numbers are in [`docs/target-app-parity.md`](docs/target-app-parity.md). Fidelity, reliability and stability (G1–G3) come before new features.
4. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask.
## Non-negotiables
**Read [`AGENTS.md`](AGENTS.md) first; its rules override everything here.** No Adobe assets, every asset licensed + attributed (`cargo xtask assets`).
- **Never crash** (AGENTS.md "Never crash"; outranks feature work: a crash loses people's work). Non-test code has no `unwrap()`/`expect()`/`panic!`/`unreachable!`/`todo!`/`unimplemented!` and no `unsafe`: return `Result` and use `?`, `ok_or`, `let … else`. Input-derived indices, slices and arithmetic use `get()` and checked/saturating math; recursion is depth-limited; locks handle poisoning. The app's last-resort guard turns an escaped panic into an error and keeps the document. Every crash fix gets a regression test.
- **Clean-room.** Behaviour and public docs only. No GPL/LGPL/AGPL code. ffmpeg only as an external test oracle.
- **Pure Rust.** Media codecs come from FilmCraft crates (git deps behind `crates/media`, see `plan/adr/0001`).
- **Layering** (`cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd/cpal; L0–L4 build for wasm32.
- **Exact time:** `effectcraft_time::Tick` (254 016 000 000/s). Keyframe times are **layer time**.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Property tree:** everything animatable is a `Property` in the layer's `PropGroup` tree, addressed by paths (`transform/position`, `effects/#1/blurriness`, `@uid`).
- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP dispatch by id.
- **Everything is agent-drivable:** every interactive widget registers an automation id; UI state is serde.
- **Community links** (Help menu, About, header Discord button): https://discord.gg/artcraft, https://getartcraft.com, https://getartcraft.com/apps/effectcraft, https://github.com/storytold/effectcraft.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm).
- **New workspace crates** must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare the required crate-level lint attributes before modules or other crate items; crate-level `//!` documentation may precede them.
- **Commits:** one task id per commit (`M6.3: trim paths`). Only green states.
## Running and looking at the app
- `cargo run -p effectcraft -- --control 9877` opens the desktop app with the JSON-lines control server (`docs/control-protocol.md`).
- For UI work, **look at the result**. Headless (no window, works while the user is busy on the machine): `cargo run -p effectcraft-ui-egui --example snapshot -- --out ui.png --step '{"method":"engine.execute","params":{"command":"layer.select","params":{"layers":["#2"]}}}'` (steps are control-channel requests; `--script steps.jsonl`; `{"method":"snap","params":{"path":…}}` for intermediate shots). Or drive the live app via the control channel and take `ui.screenshot` (needs the window visible on screen).
- After Effects reference: drive AE via ExtendScript (`osascript -e 'tell application "Adobe After Effects 2026" to DoScriptFile "x.jsx"'`) and capture only AE's window (`screencapture -l <windowid>`); keep captures in `plan/aftereffects/ref/` (gitignored), never commit them, never capture the Home screen.
- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-<name>`; keep every `Cargo.toml` valid (the `crates/*` glob).
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
@AGENTS.md
Generated
+3
View File
@@ -1970,6 +1970,7 @@ dependencies = [
name = "effectcraft-ui-egui"
version = "0.21.0"
dependencies = [
"bytemuck",
"chrono",
"craft-quit",
"craft-ui",
@@ -1992,6 +1993,7 @@ dependencies = [
"egui_extras",
"egui_kittest",
"exr",
"half",
"image",
"kurbo",
"log",
@@ -2000,6 +2002,7 @@ dependencies = [
"serde",
"serde_json",
"sys-locale",
"tempfile",
"toml",
"web-time",
]
+1
View File
@@ -112,6 +112,7 @@ filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4
wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] }
bytemuck = "1"
pollster = "1"
half = "2.7"
# ui
# Shared frontend components; keep this dependency above the engine boundary.
+11 -2
View File
@@ -17,6 +17,7 @@
//! [--jpeg-quality N] [--bitrate KBPS] [--prores proxy|lt|standard|hq|4444|4444xq] [--audio auto|on|off]
//! [--profile main|main10] [--level auto|4.1] [--rate-control bitrate|quality] [--video-quality 1-100]
//! [--keyint FRAMES] [--webm-codec vp9|av1] [--audio-bitrate KBPS] [--opus-app audio|voice]
//! [--exr-compression none|rle|zips|zip|piz|pxr24|b44|b44a|dwaa|dwab] [--exr-depth half|float]
//! (a relative --out is relative to the working directory; --queue outputs follow the project's own settings)
//! [--progress] report progress on stderr when it is not a terminal, up to four lines a second:
//! `progress <frames done> <frames total> <seconds elapsed> <seconds left, or - when unknown>`
@@ -114,9 +115,13 @@ const USAGE: &str = "usage: effectcraft-cli <info|commands|exec|run|props|get|se
[--resolution full|half|third|quarter|K] [--quality best|draft] [--channels rgb|rgba]
[--jpeg-quality N] [--bitrate KBPS] [--prores PROFILE] [--audio auto|on|off]
[--profile main|main10] [--level auto|4.1] [--rate-control bitrate|quality] [--video-quality N]
[--keyint FRAMES] [--webm-codec vp9|av1] [--audio-bitrate KBPS] [--opus-app audio|voice] | --queue
[--keyint FRAMES] [--webm-codec vp9|av1] [--audio-bitrate KBPS] [--opus-app audio|voice]
[--exr-compression C] [--exr-depth half|float] | --queue
(formats h264|hevc|av1|prores|webm|png|jpeg|tiff|exr|tga|gif|wav|aiff;
--profile..--keyint: HEVC / AV1, --audio-bitrate/--opus-app: WebM Opus)
--profile..--keyint: HEVC / AV1, --audio-bitrate/--opus-app: WebM Opus;
--exr-compression none|rle|zips|zip|piz|pxr24|b44|b44a|dwaa|dwab
(default zip; pxr24 on float, b44/b44a on half and dwaa/dwab are lossy),
--exr-depth (default float): OpenEXR)
a relative --out is relative to the working directory
--progress: progress lines on stderr when it is not a terminal
(progress <frames done> <total> <seconds elapsed> <seconds left|->)
@@ -190,6 +195,8 @@ const VALUED: &[&str] = &[
"--webm-codec",
"--audio-bitrate",
"--opus-app",
"--exr-compression",
"--exr-depth",
// mcp
"--automation-read-root",
"--automation-write-root",
@@ -881,6 +888,8 @@ fn render(args: &Args, json_out: bool) -> Result<(), Failure> {
("--rate-control", "rateControl"),
("--webm-codec", "webmCodec"),
("--opus-app", "opusApplication"),
("--exr-compression", "exrCompression"),
("--exr-depth", "exrBitDepth"),
] {
if let Some(v) = args.opt(flag) {
p[key] = json!(v);
+52
View File
@@ -1171,3 +1171,55 @@ fn render_without_progress_writes_no_progress_lines() {
let stderr = render_demo_stderr("no-progress.gif", &[]);
assert!(!stderr.lines().any(|l| l.starts_with("progress")), "{stderr}");
}
/// `render --exr-compression C --exr-depth half` writes OpenEXR frames with that compression and
/// half-float channels (#2911); an unknown value is an error naming the parameter.
#[test]
fn render_exr_compression_and_depth() {
let root = tmp("render-exr-options");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
let project = root.join("x.ecproj");
let p = project.to_str().unwrap();
ok_json(&[
"run",
"comp.new",
r#"{"name":"T","width":64,"height":36,"duration":1}"#,
"layer.newSolid",
r#"{"width":64,"height":36}"#,
"--empty",
"--save-as",
p,
]);
let out = root.join("f_[#####].exr");
let reply = ok_json(&[
"render",
"--project",
p,
"--start",
"0",
"--end",
"0.01",
"--exr-compression",
"piz",
"--exr-depth",
"half",
"--out",
out.to_str().unwrap(),
]);
assert_eq!(reply["rendered"].as_array().unwrap().len(), 1, "{reply}");
let bytes = std::fs::read(root.join("f_00000.exr")).unwrap();
// The `compression` attribute: name, type name, a 1-byte size, then PIZ (4).
let attr = b"compression\0compression\0\x01\0\0\0";
let at = bytes.windows(attr.len()).position(|w| w == attr).expect("compression attribute");
assert_eq!(bytes[at + attr.len()], 4, "PIZ");
// Each channel in `chlist`: its name, then the pixel type (1 = half).
for name in [&b"R\0"[..], b"G\0", b"B\0", b"A\0"] {
let half = [name, &[1, 0, 0, 0]].concat();
assert!(bytes.windows(half.len()).any(|w| w == half.as_slice()), "{:?} is half float", std::str::from_utf8(name));
}
let (code, reply) = run_json(&["render", "--project", p, "--exr-depth", "8", "--out", out.to_str().unwrap()]);
assert_eq!(code, 1, "{reply}");
assert!(reply["error"].as_str().unwrap().contains("exrBitDepth: half|float"), "{reply}");
let _ = std::fs::remove_dir_all(&root);
}
+26 -2
View File
@@ -8,7 +8,9 @@
//! `--demo` opens the demo project instead (also Help ▸ Open Demo Project).
//!
//! `--control <port>` (or `EFFECTCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server;
//! see `effectcraft_ui_egui::control` for the methods.
//! see `effectcraft_ui_egui::control` for the methods. An app started for an agent opens without
//! taking keyboard focus and skips crash recovery, the Home screen (unless `--home`) and the
//! startup update check.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
@@ -112,6 +114,13 @@ fn parse_args(args: impl IntoIterator<Item = String>, env_port: Result<String, s
Ok(Some(out))
}
/// Whether the app looks for a newer release when it starts. Not when started for an agent
/// (`--control`): the "update available" prompt is modal and would block the run until a person
/// dismisses it. Help ▸ Check for Updates still works.
fn startup_update_check(control_port: Option<u16>) -> bool {
control_port.is_none()
}
/// A control-channel port from 1 to 65535 (0 would listen on a port nobody is told); `name` is
/// the flag or variable it came from.
fn control_port(name: &str, value: Option<&str>) -> Result<u16, String> {
@@ -267,6 +276,9 @@ fn main() -> eframe::Result {
// written on background threads (M13.14).
session.check_footage_on_open = true;
session.autosave.background = true;
// The disk cache's footage stamps too: an imported or opened project with thousands of
// sequence frames on a network share took half a minute to stamp.
session.disk_salt_background = true;
// Settings, shortcut presets and the crash-recovery sentinel live in the platform
// config directory. Agent-driven runs (`--control`) skip crash recovery.
if let Some(dir) = effectcraft_host::config_dir() {
@@ -310,7 +322,7 @@ fn main() -> eframe::Result {
// reported in a toast and forgotten).
let _ = session.execute("window.restoreScriptPanels", json!({}));
let mut app = EffectcraftApp::new(session);
app.set_startup_update_check(true);
app.set_startup_update_check(startup_update_check(control_port));
app.set_gpu_failure_bridge(gpu_failures);
app.ui.start_screen = show_home;
if let Some(n) = notice {
@@ -666,6 +678,18 @@ mod tests {
assert_eq!(parse_env(&[], Ok("9000".into())).unwrap().map(|a| a.control_port), Some(Some(9000)));
}
/// An app started for an agent (`--control` or `EFFECTCRAFT_CONTROL_PORT`) doesn't check for
/// updates at start, so no modal update prompt blocks the run; a normal launch still does.
#[test]
fn agent_runs_skip_the_startup_update_check() {
let port = |args: &[&str], env| parse_env(args, env).unwrap().unwrap_or_default().control_port;
assert!(super::startup_update_check(port(&[], Err(VarError::NotPresent))));
assert!(super::startup_update_check(port(&[], Ok(String::new()))));
assert!(!super::startup_update_check(port(&["--control", "9877"], Err(VarError::NotPresent))));
assert!(!super::startup_update_check(port(&["--control=9877"], Err(VarError::NotPresent))));
assert!(!super::startup_update_check(port(&[], Ok("9877".into()))));
}
/// A missing, non-numeric or zero `--control` value stops the launch instead of starting
/// without a control server, and the argument after `--control` isn't reinterpreted (#997).
#[test]
+2 -1
View File
@@ -62,7 +62,8 @@ sync_github_name = false
[people.vangel76]
real_name = "Valentin Klein"
display_name = "Valentin Klein"
display_name = "vangel76"
sync_github_name = false
[people.Losminek]
sync_github_name = true
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "effectcraft-aep"
description = "After Effects projects: the .aep (RIFX 'Egg!') / .aepx container as a lossless chunk tree with a typed view, and its import into an EffectCraft project, which reports everything it does not carry over"
description = "After Effects projects: the .aep (RIFX 'Egg!') / .aepx container as a lossless chunk tree with a typed view, import into an EffectCraft project and export back to .aep with every chunk built in code; each reports everything it does not carry over"
version.workspace = true
edition.workspace = true
license.workspace = true
+8 -4
View File
@@ -5,9 +5,9 @@ After Effects projects (`.aep`, `.aepx`) in one crate, the way `effectcraft-lott
- `container`: reads and writes the container as a lossless chunk tree, with a typed, read-only
view (below; its API is re-exported at the crate root);
- `import`: maps the typed view into an EffectCraft project and reports everything it does not
import ([`docs/aep-import.md`](../../docs/aep-import.md)).
Writing an EffectCraft project as an `.aep` (export) is not part of this crate yet.
import ([`docs/aep-import.md`](../../docs/aep-import.md));
- `export`: writes an EffectCraft project as an `.aep` with every chunk built in code, and reports everything it does not export
([`docs/aep-export.md`](../../docs/aep-export.md)).
No file access: callers pass bytes, so the crate builds for wasm32.
@@ -46,7 +46,11 @@ Public specifications used for parts the format embeds:
- ICC.1:2010: the profile description of a working-space profile (a v2 `desc` or a v4 `mluc`
tag), from which the working space's name is read (`container/settings.rs`).
- RFC 4648 (base64): the profile data in the project's colour settings JSON.
- RFC 4648 (base64): the profile data in the project's colour settings JSON (read, and written
by the exporter).
- The exporter's own colour profiles (`export/icc.rs`): ICC.1:2010 version 4.3 display profiles
with ITU-R BT.709 primaries, D65 white, a D50 PCS and a Bradford adaptation, the IEC 61966-2-1
sRGB curve or a 2.4 power curve; the profile ID is the MD5 of RFC 1321.
## Clean room
+5 -1
View File
@@ -33,10 +33,13 @@ 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, CurvesData, ExtractorChannels, HueSaturationData, LevelsData, MeshData, curve_lut, identifier_channel_type};
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};
@@ -54,4 +57,5 @@ pub use textdoc::{
};
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};
+170
View File
@@ -381,3 +381,173 @@ pub fn identifier_channel_type(data: &[u8]) -> Option<&str> {
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}");
}
}
}
+22 -2
View File
@@ -1,7 +1,8 @@
//! The effect table of the importer (`crate::import`): an After Effects effect (its match name) and its parameters (by
//! The effect table shared by the importer (`crate::import`) and the exporter
//! (`crate::export`): an After Effects effect (its match name) and its parameters (by
//! their index in `parT`) map to an EffectCraft effect, a parameter id and a unit conversion.
//! Plain data; the evidence for each row is in `docs/aep-format.md` 3.7 and the case numbers in
//! the comments.
//! the comments. The importer reads a file through it, the exporter writes the inverse.
use crate::container::effects::ParamKind;
use ParamKind as K;
@@ -109,6 +110,8 @@ pub const HUE_SAT_CHANNEL: &[&str] = &["Master", "Reds", "Yellows", "Greens", "C
pub const LEVELS_CHANNEL: &[&str] = &["RGB", "Red", "Green", "Blue", "Alpha"];
/// 511.
pub const LEVELS_CLIP: &[&str] = &["On", "Off", "Off for 32 bpc Color"];
/// The Cryptomatte plug-in's Output (`Cryptomatte-0002`).
pub const CRYPTOMATTE_OUTPUT: &[&str] = &["Colors", "Matted Colors", "Matted RGBA", "Matte Only"];
/// One mapped parameter.
#[derive(Clone, Copy, Debug)]
@@ -142,6 +145,10 @@ pub enum Extra {
Extractor,
/// IDentifier's Channel Info (`identifier_channel_type`): the chosen channel by name.
Identifier,
/// The Cryptomatte plug-in: the layer and selection in its Settings data
/// (`CryptomatteData`), Output split over EffectCraft's Display and Matte Only; every
/// parameter is handled by the importer's Cryptomatte step, none by the table.
Cryptomatte,
}
/// One mapped effect.
@@ -531,6 +538,9 @@ pub const EFFECTS: &[EffectMap] = &[
],
extra: Extra::MeshWarp,
},
// The Cryptomatte plug-in (docs/aep-format.md 3.7): 1 Settings data, 2 Output, 3 Selection
// Mode, imported by the Cryptomatte step (`Extra::Cryptomatte`).
EffectMap { match_name: "Cryptomatte", effect: "ec.3d.cryptomatte", params: &[], extra: Extra::Cryptomatte },
// Expression controls (070-077, 217-221, 310).
// Directional Blur (711): Direction in degrees, Blur Length in pixels (valid max 1 000).
fx(
@@ -1131,6 +1141,16 @@ pub fn popup_key(item: &str) -> String {
s.strip_suffix(" channel").map(str::to_string).unwrap_or(s)
}
/// The table row of an After Effects match name.
pub fn by_match_name(match_name: &str) -> Option<&'static EffectMap> {
EFFECTS.iter().find(|m| m.match_name == match_name)
}
/// The table row of an EffectCraft effect id.
pub fn by_effect(effect: &str) -> Option<&'static EffectMap> {
EFFECTS.iter().find(|m| m.effect == effect)
}
/// The EffectCraft parameters Hue/Saturation's master values (`Extra::HueSaturation`) go to,
/// in the order of the data (hue, saturation, lightness: 444-446).
pub const HUE_SATURATION_MASTER: [&str; 3] = ["hue", "saturation", "lightness"];
+3
View File
@@ -256,6 +256,9 @@ impl<'f, 'a> Effect<'f, 'a> {
&& 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());
}
+11 -1
View File
@@ -1,4 +1,5 @@
//! The layer-style table of the importer (`crate::import`): the After Effects layer styles (`ADBE Layer Styles`, docs
//! The layer-style table shared by the importer (`crate::import`) and the exporter
//! (`crate::export`): the After Effects layer styles (`ADBE Layer Styles`, docs
//! `aep-format.md` 3.14) and their parameters, the EffectCraft style and parameter each maps to,
//! the unit conversion and After Effects' default as it would be stored.
//!
@@ -72,6 +73,10 @@ 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)
@@ -321,6 +326,11 @@ pub fn by_ae(prefix: &str) -> Option<&'static StyleMap> {
STYLES.iter().find(|s| s.ae == prefix)
}
/// The style with this EffectCraft id.
pub fn by_ec(id: &str) -> Option<&'static StyleMap> {
STYLES.iter().find(|s| s.ec == id)
}
#[cfg(test)]
mod tests {
use super::*;
+120
View File
@@ -0,0 +1,120 @@
//! 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));
}
}
+125
View File
@@ -0,0 +1,125 @@
//! After Effects project (`.aep`) export: an EffectCraft [`Project`] written as an `.aep` that
//! After Effects 2026 opens.
//!
//! Every chunk is built in code: the project skeleton, the item, layer and property records are
//! prototypes in the layout After Effects writes (`template.rs` gathers them), and the exporter
//! clones them and writes only the fields whose layout is verified (`docs/aep-format.md` section 3, `docs/aep-export.md`):
//! item and layer ids, project settings, the composition header, the layer header (switches
//! including 3D, time stretch, blend modes, track mattes), solid colour and size, the Transform
//! properties (static values, keyframes with interpolation and ease, expressions), layer masks,
//! markers, time remapping, precomposition, footage, text (with animators), shape, camera and
//! light layers, footage items and image sequences, layer styles, and the effects of the table
//! shared with the importer (`crate::effect_map`). `docs/aep-export.md` has the full
//! list and the rules After Effects needs.
//!
//! What cannot be written is **reported**, never dropped silently ([`ExportReport`]); by default an
//! export that would lose anything is refused ([`ExportOptions::allow_losses`]).
//!
//! The crate sits at L3 (above `effectcraft-project`, next to the importer) and builds for wasm32:
//! it does no file access, the caller gets the bytes.
mod base;
mod camlight;
mod effects;
mod emit;
mod footage;
mod fx_defs;
mod fxsynth;
pub(crate) mod icc;
mod markers;
mod masks;
mod plan;
mod report;
mod settings;
mod shapes;
mod skeleton;
mod style_defs;
mod styles;
mod synth;
mod template;
mod text;
mod textanim;
mod textdoc;
mod textproto;
mod timebase;
mod tree;
mod tree_defs;
mod tree_spec;
use effectcraft_project::Project;
pub use report::{ExportReport, Exported, LIMITATIONS, Loss, LossCategory, MAX_DETAILS};
/// Why an `.aep` was not written.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum AepExportError {
/// Parts of the project cannot be exported and losses were not allowed. Nothing was written;
/// the report says what would be lost.
#[error("exporting would lose {}; allow losses to export anyway", .0.summary())]
Refused(Box<ExportReport>),
/// A prototype built in code does not have the shape the exporter expects (a bug in the crate).
#[error("internal error: {0}")]
Internal(&'static str),
/// The container could not be written (a chunk or the file exceeds the format's 4 GB limit).
#[error("{0}")]
Container(#[from] crate::AepError),
}
/// Options of [`export`].
#[derive(Clone, Copy, Debug, Default)]
pub struct ExportOptions {
/// Export even when [`ExportReport::losses`] is not empty.
pub allow_losses: bool,
}
/// An exported project.
#[derive(Clone, Debug, PartialEq)]
pub struct ExportResult {
/// The `.aep` file.
pub bytes: Vec<u8>,
pub report: ExportReport,
}
/// A neutral XMP packet for the end of the file (After Effects writes one; it only holds metadata).
const XMP: &[u8] = b"<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <dc:format>application/vnd.adobe.aftereffects.project</dc:format>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>";
/// Exports `project` as an `.aep`.
///
/// # Errors
/// [`AepExportError::Refused`] when something would be lost and `allow_losses` is not set (nothing
/// is written), [`AepExportError::Container`] for a file beyond the container's size limits.
pub fn export(project: &Project, options: &ExportOptions) -> Result<ExportResult, AepExportError> {
export_with(project, options, &|_| None)
}
/// [`export`] with the modification times of the image-sequence folders: `folder_time` is asked
/// with a sequence's first file path as the project stores it and answers with the modification
/// time of the folder that holds it, in whole seconds since 1970 (UTC), or `None`. The caller
/// decides whether that path may be followed (the engine applies its document-path policy) before
/// it looks at the folder.
///
/// After Effects keeps a sequence's stored numbering only while the stored folder time
/// (`sspc@118`) equals the folder's; otherwise it scans the folder again when the project opens
/// and warns about every gap in the numbering in a modal dialog (860, `export-tests` x1-x3).
/// Without a time it is written as 0, and such a folder is scanned again.
///
/// # Errors
/// As [`export`].
pub fn export_with(project: &Project, options: &ExportOptions, folder_time: &dyn Fn(&str) -> Option<u64>) -> Result<ExportResult, AepExportError> {
let mut col = report::Collector::default();
let mut plan = plan::plan(project, &mut col);
let report = col.finish();
if !options.allow_losses && !report.is_lossless() {
return Err(AepExportError::Refused(Box::new(report)));
}
footage::stamp_sequences(&mut plan.root, folder_time);
let bytes = emit::emit(&plan, XMP)?;
Ok(ExportResult { bytes, report })
}
/// The report an export would produce, without writing anything (a dry run).
pub fn analyze(project: &Project) -> ExportReport {
let mut col = report::Collector::default();
let _ = plan::plan(project, &mut col);
col.finish()
}
+332
View File
@@ -0,0 +1,332 @@
//! The project skeleton built in code (aep-format.md 3.1-3.3, 3.12a): the top-level chunks, the
//! composition shell with its view layers, the `Solids` folder, a solid item and the records that
//! follow a composition. Fields the exporter sets per item are left zero here; the bytes that are
//! not decoded are named constants, each with the value it has in every generated test file of
//! that kind (cases 000, 022, 211, 259, 620-634) and kept because After Effects refuses the file without them
//! (read-backs t-no<id>, t-zcdta, u-zsspc, u-noclrs, u-noftgi, u-nofrec, u-nocdrp).
use crate::Chunk;
use crate::export::synth::{tdmn, tdsn};
/// A zero buffer of `len` bytes with `fields` (offset, bytes) written into it.
pub(crate) fn bytes(len: usize, fields: &[(usize, &[u8])]) -> Vec<u8> {
let mut b = vec![0u8; 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
}
pub(crate) fn utf8(text: &str) -> Chunk<'static> {
Chunk::data(*b"Utf8", text.as_bytes().to_vec())
}
/// The After Effects version the file claims (`svap`, `head` 4..7): 26.x, the version every
/// sample was saved with.
const VERSION: [u8; 4] = [0x0f, 0x11, 0x0e, 0x02];
/// `head` 0..3 and byte 8: the same in every sample (not decoded; a zero `head` is refused as
/// "created with an older version", read-back u-zhead).
const HEAD_FORMAT: [u8; 4] = [0x00, 0x61, 0x00, 0x05];
/// The code page of the project's strings (`nhed` 18, `nnhd` 26): 65001, UTF-8.
const UTF8_CODE_PAGE: [u8; 2] = 65001u16.to_be_bytes();
/// The size of the render-queue settings blocks (`AFsi`, `ARsi`); zero bodies of this size are
/// read (read-back e1-zafsi), a missing one is refused (e1-noafsi).
const RQ_SETTINGS_LEN: usize = 1872;
/// The record size of the render-queue item list (`LRdr/list/lhd3` word 4).
const RQ_ITEM_LEN: u32 = 2246;
/// The id of the `Solids` folder, which `sfnm/sfid` names.
pub(crate) const SOLIDS_FOLDER_ID: u32 = 0x19;
/// The default end time of a view layer (5 s in 25 600 units): view layers keep it whatever the
/// composition's duration (000, 031, 032).
const VIEW_OUT: u32 = 128_000;
/// The top-level chunks of a project: the headers (`settings::emit` writes the settings into
/// them, `emit` the next free id), the project lists (`effects::put_project_lists` fills `Pefl`),
/// an empty `Fold` with its `fdta`, the workspace name and the render queue.
pub(crate) fn project_chunks() -> Vec<Chunk<'static>> {
let head = bytes(20, &[(0, &HEAD_FORMAT), (4, &VERSION), (8, &[0x80])]);
// nhed / nnhd: bytes 7 and 9 the same in every sample, byte 12 / 15 the timecode base (30),
// 13 / 19 the frames per foot (16), 14 / 20 the frame count start (2: from 0), 15 / 24 the
// colour depth (2: 32 bits); the save noise after the code page is left zero.
let nhed = bytes(32, &[(7, &[5]), (9, &[1]), (12, &[0x1e, 16, 2, 2]), (18, &UTF8_CODE_PAGE)]);
let nnhd = bytes(40, &[(7, &[5]), (9, &[1]), (15, &[0x1e]), (19, &[16, 2]), (24, &[2]), (26, &UTF8_CODE_PAGE)]);
let 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 wsnm: Vec<u8> = "Default".encode_utf16().flat_map(u16::to_be_bytes).collect();
vec![
Chunk::data(*b"svap", VERSION.to_vec()),
Chunk::data(*b"head", head),
Chunk::data(*b"nhed", nhed),
Chunk::data(*b"nnhd", nnhd),
// The project's audio sample rate.
Chunk::data(*b"adfr", 48_000f64.to_be_bytes().to_vec()),
Chunk::list(*b"Pefl", Vec::new()),
Chunk::data(*b"qtlg", vec![0]),
Chunk::list(*b"sfnm", vec![utf8("Solids"), Chunk::data(*b"sfid", SOLIDS_FOLDER_ID.to_le_bytes().to_vec())]),
Chunk::data(*b"mrid", vec![0; 4]),
// Compensate for Scene-referred Profiles: on.
Chunk::data(*b"acer", vec![1]),
Chunk::list(*b"CPPl", Vec::new()),
Chunk::data(*b"cpid", vec![0xff; 16]),
Chunk::data(*b"dwga", vec![0; 4]),
Chunk::data(*b"pcms", vec![1]),
utf8("{\"ocioConfigurationFile\":\"ACES 1.2\"}"),
Chunk::data(*b"PwCs", vec![1]),
utf8("{}"),
Chunk::data(*b"pdvc", vec![1]),
utf8("{}"),
Chunk::list(*b"ExEn", vec![utf8("javascript-1.0")]),
Chunk::list(*b"Fold", vec![Chunk::data(*b"fdta", vec![0; 14])]),
Chunk::data(*b"wsns", vec![0, 0x0e]),
Chunk::data(*b"wsnm", wsnm),
utf8("Default"),
Chunk::data(*b"fcid", vec![0; 4]),
Chunk::data(*b"oacc", vec![0; 2]),
Chunk::list(*b"LSIf", vec![Chunk::data(*b"AFsi", vec![0; RQ_SETTINGS_LEN])]),
Chunk::list(
*b"LRdr",
vec![
Chunk::data(*b"Rhed", vec![0; 20]),
Chunk::data(*b"Rout", vec![0; 4]),
Chunk::list(*b"list", vec![Chunk::data(*b"lhd3", lhd3)]),
Chunk::list(*b"LItm", Vec::new()),
Chunk::list(*b"LSIf", vec![Chunk::data(*b"ARsi", vec![0; RQ_SETTINGS_LEN])]),
],
),
]
}
/// `idta` of an item: the kind at 0, byte 23 per kind (0x20 composition, 0x30 footage, 0 folder;
/// After Effects renders differently without it, read-backs t-zidta and u-zidta2); `emit` writes
/// the id and the label.
pub(crate) fn idta(kind: u16, byte23: u8) -> Chunk<'static> {
Chunk::data(*b"idta", bytes(84, &[(0, &kind.to_be_bytes()), (23, &[byte23])]))
}
/// The guides of a layer or item (`Gide`: `gdta` zero and an empty list header).
pub(crate) fn guides() -> Chunk<'static> {
let header = crate::export::synth::key_list(16, 0, Vec::new()).children().iter().filter(|c| c.is(b"lhd3")).cloned().collect();
Chunk::list(*b"Gide", vec![Chunk::data(*b"gdta", vec![0; 8]), Chunk::list(*b"list", header)])
}
/// `cdta` with the bytes `emit::build_comp` does not write: 0..3, the shutter angle and phase
/// limits (360 at 176 and 184), the motion blur samples per frame (16 at 200) and the adaptive
/// sample limit (128 at 196); the same in every sample, and a `cdta` without them crashes After
/// Effects (read-back t-zcdta).
fn cdta() -> Chunk<'static> {
Chunk::data(
*b"cdta",
bytes(
204,
&[(0, &[0, 1, 0, 1]), (176, &360u32.to_be_bytes()), (184, &360u32.to_be_bytes()), (196, &128u32.to_be_bytes()), (200, &16u32.to_be_bytes())],
),
)
}
/// The renderer (`PRin`): the Classic 3D match name and display name (aep-format.md 3.2).
fn renderer() -> Chunk<'static> {
let prin = bytes(104, &[(4, b"ADBE Escher"), (52, b"Classic 3D"), (103, &[1])]);
Chunk::list(*b"PRin", vec![Chunk::data(*b"prin", prin), Chunk::data(*b"prda", vec![0; 12])])
}
/// The built-in view layers of a composition: list type, name, `ldta` byte 61 (label) and byte
/// 128 (layer type: 2 camera, 4 for the markers layer).
const VIEWS: [(&[u8; 4], &str, u8, u8); 11] = [
(b"DLay", "Default", 4, 2),
(b"SLay", "Front", 4, 2),
(b"SLay", "Left", 4, 2),
(b"SLay", "Top", 4, 2),
(b"SLay", "Back", 4, 2),
(b"SLay", "Right", 4, 2),
(b"SLay", "Bottom", 4, 2),
(b"CLay", "Custom View 1", 4, 2),
(b"CLay", "Custom View 2", 4, 2),
(b"CLay", "Custom View 3", 4, 2),
(b"SecL", "Markers", 8, 4),
];
/// One view layer: `ldta` with the decoded fields only (read-back t-zldta), an empty property
/// tree (t-vempty), the guides, `Ewst` and the two f-record sets. `emit` writes the id.
fn view_layer(ty: &[u8; 4], name: &str, label: u8, kind: u8) -> Vec<Chunk<'static>> {
let markers = kind == 4;
let mut name_copy = name.as_bytes().to_vec();
name_copy.truncate(31);
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 layer = Chunk::list(*ty, vec![Chunk::data(*b"ldta", ldta), utf8(name), Chunk::list(*b"tdgp", root), guides()]);
let mut out = vec![layer, Chunk::list(*b"Ewst", Vec::new())];
out.extend(crate::export::skeleton::f_records());
out.extend(crate::export::skeleton::f_records());
out
}
/// The composition item without layers, and the index of its children where the layer blocks go.
pub(crate) fn comp_shell() -> (Chunk<'static>, usize) {
let mut kids = vec![
Chunk::data(*b"iide", vec![0; 4]),
Chunk::data(*b"idpc", vec![0; 8]),
idta(4, 0x20),
utf8(""),
Chunk::list(*b"dats", vec![Chunk::data(*b"numS", vec![0; 4])]),
cdta(),
Chunk::data(*b"cdrp", vec![0]),
Chunk::data(*b"comr", vec![0]),
renderer(),
];
let layer_at = kids.len();
for (ty, name, label, kind) in VIEWS {
kids.extend(view_layer(ty, name, label, kind));
}
kids.push(guides());
(Chunk::list(*b"Item", kids), layer_at)
}
/// The list that follows a composition item (`FEE `, `ppSn` zero: read-back u-zppsn).
pub(crate) fn fee() -> Chunk<'static> {
Chunk::list(*b"FEE ", vec![Chunk::data(*b"ppSn", vec![0; 8])])
}
/// An empty folder item (`sfdt` 1 in every sample).
pub(crate) fn folder_item() -> Chunk<'static> {
Chunk::list(
*b"Item",
vec![
Chunk::data(*b"iide", vec![0; 4]),
Chunk::data(*b"idpc", vec![0; 8]),
idta(1, 0),
utf8(""),
Chunk::data(*b"sfdt", 1u32.to_be_bytes().to_vec()),
Chunk::list(*b"Sfdr", Vec::new()),
],
)
}
/// `ftgi` of a footage item, the same in every sample (required, read-back u-noftgi).
pub(crate) fn ftgi() -> Chunk<'static> {
Chunk::data(*b"ftgi", bytes(16, &[(7, &[1]), (8, &[0xff; 4]), (12, &600u32.to_be_bytes())]))
}
/// The `sspc` bytes of a solid that are not decoded, the same in every solid (000, 022, 211, 259);
/// After Effects refuses a solid with only the decoded fields (read-back u-zsspc).
const SOLID_SSPC: [(usize, &[u8]); 11] = [
(50, &[0, 0, 0x02, 0x58]),
(73, &[3]),
(105, &[1]),
(109, &[1]),
(125, &[0x0c]),
(129, &[1]),
(134, &[1]),
(139, &[1]),
(143, &[1]),
(188, &[0xff; 8]),
(212, &[1]),
];
/// A solid's footage item: `sspc` (type `Soli`, duration 0 / 1), `opti` (`Soli`; `emit` writes
/// the colour and the name), `pgui`, the colour-management list (no profile, the defaults of
/// every sample; required, read-back u-noclrs), `ftgi` (required, u-noftgi) and the guides. The
/// solid of a null layer is the same item.
pub(crate) fn solid_item() -> Chunk<'static> {
let mut sspc_fields: Vec<(usize, &[u8])> = vec![(22, b"Soli"), (45, &[1])];
sspc_fields.extend(SOLID_SSPC);
let clrs = Chunk::list(
*b"CLRS",
vec![
Chunk::data(*b"epid", vec![0xff; 16]),
Chunk::data(*b"apid", vec![0xff; 16]),
Chunk::data(*b"linl", vec![2, 0, 0, 0]),
Chunk::data(*b"embp", vec![1]),
Chunk::data(*b"ipws", vec![1]),
Chunk::data(*b"dcui", vec![1]),
Chunk::data(*b"prgb", vec![1]),
Chunk::data(*b"Mcsp", vec![1]),
utf8(""),
Chunk::data(*b"ocsp", vec![1]),
utf8(""),
Chunk::data(*b"hdrm", vec![1]),
utf8("{}"),
],
);
let pin = Chunk::list(
*b"Pin ",
vec![
Chunk::data(*b"sspc", bytes(222, &sspc_fields)),
utf8(""),
Chunk::data(*b"opti", bytes(282, &[(0, b"Soli")])),
Chunk::data(*b"pgui", vec![0; 16]),
clrs,
utf8(""),
],
);
Chunk::list(*b"Item", vec![Chunk::data(*b"iide", vec![0; 4]), Chunk::data(*b"idpc", vec![0; 8]), idta(7, 0x30), utf8(""), pin, ftgi(), utf8(""), guides()])
}
#[cfg(test)]
mod tests {
use super::*;
/// The chunks After Effects refuses a file without, or crashes on (aep-export.md, "What After
/// Effects needs").
#[test]
fn the_skeleton_has_what_after_effects_needs() {
let top = project_chunks();
for id in [b"adfr", b"qtlg", b"mrid", b"acer", b"fcid", b"oacc", b"head", b"nhed"] {
assert!(top.iter().any(|c| c.is(id)), "{}", String::from_utf8_lossy(id));
}
assert!(top.iter().any(|c| c.is_list(b"CPPl")));
let head = top.iter().find(|c| c.is(b"head")).and_then(|c| c.bytes()).unwrap();
assert_eq!(&head[..8], &[0x00, 0x61, 0x00, 0x05, 0x0f, 0x11, 0x0e, 0x02]);
let rq = top.iter().find(|c| c.is_list(b"LRdr")).unwrap();
let arsi = rq.child_list(b"LSIf").and_then(|l| l.child(b"ARsi")).and_then(|c| c.bytes()).unwrap();
assert_eq!(arsi.len(), RQ_SETTINGS_LEN);
let afsi = top.iter().find(|c| c.is_list(b"LSIf")).and_then(|l| l.child(b"AFsi")).and_then(|c| c.bytes()).unwrap();
assert_eq!(afsi.len(), RQ_SETTINGS_LEN);
let (comp, at) = comp_shell();
let kids = comp.children();
assert!(comp.child_list(b"dats").is_some(), "no dats: After Effects crashes");
assert!(kids.iter().any(|c| c.is(b"cdrp")) && kids.iter().any(|c| c.is(b"comr")));
let cdta = comp.child(b"cdta").and_then(|c| c.bytes()).unwrap();
for at in [1usize, 3, 179, 187, 199, 203] {
assert_ne!(cdta[at], 0, "cdta byte {at}: a zero cdta crashes After Effects");
}
let views = kids.iter().filter(|c| [*b"DLay", *b"SLay", *b"CLay", *b"SecL"].iter().any(|t| c.is_list(t))).count();
assert_eq!(views, 11);
assert!(kids.get(at).is_some_and(|c| c.is_list(b"DLay")), "the layers go before the view layers");
let solid = solid_item();
let pin = solid.child_list(b"Pin ").unwrap();
assert!(pin.child_list(b"CLRS").is_some() && solid.child(b"ftgi").is_some());
let sspc = pin.child(b"sspc").and_then(|c| c.bytes()).unwrap();
assert!(SOLID_SSPC.iter().all(|(at, v)| &sspc[*at..*at + v.len()] == *v));
assert_eq!(solid.child(b"idta").and_then(|c| c.bytes()).unwrap()[23], 0x30);
}
}
+283
View File
@@ -0,0 +1,283 @@
//! Camera and light layers (`docs/aep-format.md` 3.12; cases 251-256, 342-346).
//!
//! Both are written from a layer block of our own cases: the default two-node camera 256 and the
//! spot (254, its Intensity record removed) and point (252) lights. The layer header keeps the
//! case's type (`ldta@128` 2 camera, 1 light), source id (0 / `0xffffffff`), 3D bit and light type
//! (`ldta@136` 1 spot, 2 point); the exporter sets the auto-orient bit (`ldta@38` 0x40: a two-node
//! camera and a spot light orient towards their point of interest, 251 vs 256). The point of
//! interest is the Anchor Point in pixels and the Position an explicit value (253: 76 / 77 = 0),
//! both through the Transform writer. Options records are cloned from the one-change cases.
use crate::Chunk;
use effectcraft_keyframe::Value;
use effectcraft_project::{Layer, LightKind};
use crate::export::report::{Collector, LossCategory};
use crate::export::tree::{R, child_data, kids_mut, list_mut, put_f64, tpl};
/// A camera's options in the file's units (pixels, percent, a switch).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CameraPlan {
pub two_node: bool,
pub zoom: f64,
pub dof: bool,
pub focus: f64,
pub aperture: f64,
pub blur: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LightPlan {
/// `ldta@136`: 1 spot, 2 point (252, 254).
pub kind: u32,
pub intensity: f64,
/// `[A, R, G, B]` 0..255 (343).
pub color: [f64; 4],
pub cone_angle: f64,
pub cone_feather: f64,
}
/// The finite scalar at `path`; a property there that is not one is reported (its default is
/// written), an absent one is not.
fn scalar(layer: &Layer, path: &str, what: &str, col: &mut Collector) -> Option<f64> {
match layer.props.prop(path).map(|p| &p.value) {
Some(Value::Scalar(v)) if v.is_finite() => Some(*v),
None => None,
Some(_) => {
col.lose(LossCategory::InvalidValues, format!("{what}: {path} is not a number, the default is written"));
None
}
}
}
fn has_keys_or_expr(layer: &Layer, path: &str) -> bool {
layer.props.prop(path).is_some_and(|p| !p.keys.is_empty() || p.expr.as_ref().is_some_and(|e| !e.text.is_empty()))
}
/// The camera's options; keys and expressions on them are reported (the static value is written).
pub(crate) fn plan_camera(layer: &Layer, comp_width: u32, what: &str, col: &mut Collector) -> CameraPlan {
let default_zoom = f64::from(comp_width) * 50.0 / 36.0;
if matches!(layer.auto_orient, effectcraft_project::AutoOrient::AlongPath | effectcraft_project::AutoOrient::TowardsCamera) {
col.lose(LossCategory::Cameras, format!("{what}: the camera's Auto-Orient {:?} is not written (written as a one-node camera)", layer.auto_orient));
}
for id in ["zoom", "dof", "focusDistance", "aperture", "blurLevel"] {
if has_keys_or_expr(layer, &format!("cameraOptions/{id}")) {
col.lose(LossCategory::Cameras, format!("{what}: keys or an expression on the camera's {id} (the static value is written)"));
}
}
let iris_default = [
("irisShape", 0.0),
("irisRotation", 0.0),
("irisRoundness", 0.0),
("irisAspectRatio", 1.0),
("irisDiffractionFringe", 0.0),
("highlightGain", 0.0),
("highlightThreshold", 255.0),
("highlightSaturation", 0.0),
];
for (id, d) in iris_default {
let v = match layer.props.prop(&format!("cameraOptions/{id}")).map(|p| &p.value) {
Some(Value::Scalar(v)) => Some(*v),
Some(Value::Enum(e)) => Some(f64::from(*e)),
_ => None,
};
if v.is_some_and(|v| (v - d).abs() > 1e-9) || has_keys_or_expr(layer, &format!("cameraOptions/{id}")) {
col.lose(LossCategory::Cameras, format!("{what}: the camera's {id} is not written (not sampled)"));
}
}
let dof = matches!(layer.props.prop("cameraOptions/dof").map(|p| &p.value), Some(Value::Bool(true)));
CameraPlan {
two_node: layer.auto_orient == effectcraft_project::AutoOrient::TowardsPointOfInterest,
zoom: scalar(layer, "cameraOptions/zoom", what, col).unwrap_or(default_zoom),
dof,
focus: scalar(layer, "cameraOptions/focusDistance", what, col).unwrap_or(default_zoom),
aperture: scalar(layer, "cameraOptions/aperture", what, col).unwrap_or(25.3 * f64::from(comp_width) / 1920.0),
blur: scalar(layer, "cameraOptions/blurLevel", what, col).unwrap_or(100.0),
}
}
/// The light's options, or `None` (reported) for a type without a sampled case.
pub(crate) fn plan_light(layer: &Layer, kind: LightKind, what: &str, col: &mut Collector) -> Option<LightPlan> {
let code = match kind {
LightKind::Spot => 1,
LightKind::Point => 2,
other => {
col.lose(LossCategory::Lights, format!("{what}: a {} light is not written (not sampled)", other.label()));
return None;
}
};
// A spot light is written oriented towards its point of interest (a point light has no
// orientation that shows).
if code == 1 && layer.auto_orient != effectcraft_project::AutoOrient::TowardsPointOfInterest {
col.lose(LossCategory::Lights, format!("{what}: the light's Auto-Orient {:?} is written as towards the point of interest", layer.auto_orient));
}
for id in ["intensity", "color", "coneAngle", "coneFeather"] {
if has_keys_or_expr(layer, &format!("lightOptions/{id}")) {
col.lose(LossCategory::Lights, format!("{what}: keys or an expression on the light's {id} (the static value is written)"));
}
}
let defaults = [("radius", 500.0), ("falloffDistance", 500.0), ("shadowDarkness", 100.0), ("shadowDiffusion", 0.0)];
for (id, d) in defaults {
if scalar(layer, &format!("lightOptions/{id}"), what, col).is_some_and(|v| (v - d).abs() > 1e-9)
|| has_keys_or_expr(layer, &format!("lightOptions/{id}"))
{
col.lose(LossCategory::Lights, format!("{what}: the light's {id} is not written (not sampled)"));
}
}
// Options that are not written at all: a value other than the default, or keys or an expression
// (which change the render even when the static value is the default).
if matches!(layer.props.prop("lightOptions/falloff").map(|p| &p.value), Some(Value::Enum(e)) if *e != 0) || has_keys_or_expr(layer, "lightOptions/falloff")
{
col.lose(LossCategory::Lights, format!("{what}: the light's falloff type is not written (not sampled)"));
}
if matches!(layer.props.prop("lightOptions/castsShadows").map(|p| &p.value), Some(Value::Bool(true)))
|| has_keys_or_expr(layer, "lightOptions/castsShadows")
{
col.lose(LossCategory::Lights, format!("{what}: Casts Shadows is not written (not sampled)"));
}
let color = match layer.props.prop("lightOptions/color").map(|p| &p.value) {
Some(Value::Color(c)) => {
let out = [255.0, c[0] * 255.0, c[1] * 255.0, c[2] * 255.0].map(|v| if v.is_finite() { v.clamp(0.0, 255.0) } else { 255.0 });
if c.iter().take(3).zip(&out[1..]).any(|(v, o)| (v * 255.0).to_bits() != o.to_bits()) {
col.lose(LossCategory::Lights, format!("{what}: a light colour channel outside 0 to 1 is written as the nearest limit"));
}
out
}
_ => [255.0; 4],
};
Some(LightPlan {
kind: code,
intensity: scalar(layer, "lightOptions/intensity", what, col).unwrap_or(100.0),
color,
cone_angle: scalar(layer, "lightOptions/coneAngle", what, col).unwrap_or(90.0),
cone_feather: scalar(layer, "lightOptions/coneFeather", what, col).unwrap_or(50.0),
})
}
/// The option records: per match name the `tdbs` After Effects wrote when it was changed alone.
pub(crate) struct OptionProtos {
pub records: Vec<(String, Chunk<'static>)>,
}
impl OptionProtos {
fn get(&self, name: &str) -> R<Chunk<'static>> {
self.records.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()).ok_or_else(|| tpl("camera / light option prototype missing"))
}
}
/// The order of the properties inside the Camera and Light Options groups (After Effects' own,
/// as in 342 and 254 / 343: a record only where the value is not the default).
const CAMERA_ORDER: &[&str] =
&["ADBE Camera Zoom", "ADBE Camera Depth of Field", "ADBE Camera Focus Distance", "ADBE Camera Aperture", "ADBE Camera Blur Level"];
const LIGHT_ORDER: &[&str] = &[
"ADBE Light Env Atom",
"ADBE Light Backgd Visible",
"ADBE Light Backgd Opacity",
"ADBE Light Backgd Blur",
"ADBE Light Intensity",
"ADBE Light Color",
"ADBE Light Cone Angle",
"ADBE Light Cone Feather 2",
"ADBE Light Falloff Start",
"ADBE Light Falloff Distance",
"ADBE Casts Shadows",
];
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 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]));
}
pairs.retain(|(n, _)| !remove.contains(&n.as_str()));
for (name, rec) in set {
let entry = vec![tdmn_chunk(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()) };
pairs.sort_by_key(|(n, _)| rank(n));
gk.extend(header);
gk.extend(pairs.into_iter().flat_map(|(_, v)| v));
Ok(())
}
/// A copy of `proto` with the plain value `v` (`cdat` @0).
fn with_value(mut proto: Chunk<'static>, v: f64) -> R<Chunk<'static>> {
put_f64(child_data(&mut proto, b"cdat")?, 0, v)?;
Ok(proto)
}
pub(crate) fn put_camera(layr: &mut Chunk<'static>, protos: &OptionProtos, p: &CameraPlan) -> R<()> {
// Every option is written explicitly (After Effects' defaults depend on the composition
// width); Zoom and Blur Level take the plain-double layout of Focus Distance (342).
let plain = protos.get("ADBE Camera Focus Distance")?;
let set = vec![
("ADBE Camera Zoom", with_value(plain.clone(), p.zoom)?),
("ADBE Camera Depth of Field", with_value(protos.get("ADBE Camera Depth of Field")?, if p.dof { 1.0 } else { 0.0 })?),
("ADBE Camera Focus Distance", with_value(plain.clone(), p.focus)?),
("ADBE Camera Aperture", with_value(protos.get("ADBE Camera Aperture")?, p.aperture)?),
("ADBE Camera Blur Level", with_value(plain, p.blur)?),
];
put_group(layr, "ADBE Camera Options Group", CAMERA_ORDER, set, &[])
}
pub(crate) fn put_light(layr: &mut Chunk<'static>, protos: &OptionProtos, p: &LightPlan) -> R<()> {
let mut set = Vec::new();
let mut remove = Vec::new();
if (p.intensity - 100.0).abs() > 1e-9 {
set.push(("ADBE Light Intensity", with_value(protos.get("ADBE Light Intensity")?, p.intensity)?));
} else {
remove.push("ADBE Light Intensity");
}
if p.color != [255.0; 4] {
let mut rec = protos.get("ADBE Light Color")?;
let d = child_data(&mut rec, b"cdat")?;
for (i, v) in p.color.iter().enumerate() {
put_f64(d, i * 8, *v)?;
}
set.push(("ADBE Light Color", rec));
}
// A spot light stores its cone only when it differs (343-345); a point light keeps the inert
// records of its block (252).
if p.kind == 1 {
if (p.cone_angle - 90.0).abs() > 1e-9 {
set.push(("ADBE Light Cone Angle", with_value(protos.get("ADBE Light Cone Angle")?, p.cone_angle)?));
}
if (p.cone_feather - 50.0).abs() > 1e-9 {
set.push(("ADBE Light Cone Feather 2", with_value(protos.get("ADBE Light Cone Feather 2")?, p.cone_feather)?));
}
}
put_group(layr, "ADBE Light Options Group", LIGHT_ORDER, set, &remove)
}
File diff suppressed because it is too large. Load diff
+820
View File
@@ -0,0 +1,820 @@
//! Builds the chunk tree from the plan by cloning prototypes of the template and editing only the
//! fields whose layout is verified (`docs/aep-format.md`, section 3, and `docs/aep-export.md`).
use std::collections::HashMap;
use crate::{AepFile, Chunk};
use effectcraft_project::{ItemId, LayerId};
use crate::export::plan::{CompPlan, Entry, ItemPlan, KeyPlan, LayerPlan, LayerSrc, ProjectPlan, PropKind, PropPlan, SolidPlan, natural_key};
use crate::export::template::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,
};
/// The first id given to anything the export creates. The template's `Solids` folder keeps the id
/// 0x19 that the project header (`sfnm`/`sfid`) names; everything else is allocated from here.
const FIRST_ID: u32 = 0x1c;
const SOLIDS_FOLDER_ID: u32 = 0x19;
/// A composition item uses its own id and one id per built-in view layer (3D views, custom views,
/// the markers layer).
const VIEW_LAYERS: u32 = 11;
/// The name field of a solid (`opti` 26 to 281) holds 255 bytes and a NUL (a 140 character name
/// saved by After Effects fills it as far as it goes).
pub(crate) const MAX_SOLID_NAME: usize = 255;
struct Ids {
next: u32,
}
impl Ids {
fn alloc(&mut self) -> R<u32> {
let id = self.next;
self.next = self.next.checked_add(1).ok_or_else(|| tpl("more than 2^32 ids"))?;
Ok(id)
}
}
struct Cx<'t> {
t: &'t Template,
ids: Ids,
/// Item ids of the project's solids (for the layer source ids).
solid_ids: HashMap<ItemId, u32>,
/// Item id and duration in seconds of every exported composition (precomposition layers).
comp_ids: HashMap<ItemId, (u32, f64)>,
/// Item id and duration in seconds of every exported footage item (footage layers).
footage_ids: HashMap<ItemId, (u32, f64)>,
/// Hidden solid items of null layers, written into the `Solids` folder.
extra_solids: Vec<(String, Chunk<'static>)>,
guid: u64,
/// A root folder named `Solids` in the project is After Effects' own `Solids` folder (id 0x19).
special: Option<ItemId>,
special_slot: Option<(Chunk<'static>, Vec<Sorted>)>,
/// Effect types written so far (the first instance of a type holds its definitions).
fx_use: crate::export::effects::FxUse,
}
/// A sortable group of chunks: name, tie-break key, chunks.
type Sorted = (String, u64, Vec<Chunk<'static>>);
pub(crate) fn emit(plan: &ProjectPlan, extra: &[u8]) -> R<Vec<u8>> {
let t = Template::load()?;
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,
ids: Ids { next: FIRST_ID },
solid_ids: HashMap::new(),
comp_ids: HashMap::new(),
footage_ids: HashMap::new(),
extra_solids: Vec::new(),
guid: 0x9e37_79b9_7f4a_7c15,
special,
special_slot: None,
fx_use: crate::export::effects::FxUse::default(),
};
let mut ids_by_entry: HashMap<ItemId, u32> = HashMap::new();
assign_ids(&plan.root, &mut cx, &mut ids_by_entry)?;
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()];
v.extend(cx.t.fset.iter().cloned());
solids_children.push((name.clone(), i as u64, v));
}
let mut folder = match cx.special_slot.take() {
Some((item, inner)) => {
solids_children.extend(inner);
item
}
None => {
let mut f = cx.t.folder_item.clone();
set_item_header(&mut f, SOLIDS_FOLDER_ID, 2, "Solids")?;
f
}
};
sort_named(&mut solids_children);
kids_mut(list_mut(&mut folder, b"Sfdr")?)?.extend(solids_children.into_iter().flat_map(|(_, _, c)| c));
root.push(("Solids".to_string(), 0, vec![folder]));
sort_named(&mut root);
let mut file: AepFile<'static> = AepFile { chunks: t.file.chunks.clone(), trailer: std::borrow::Cow::Owned(extra.to_vec()) };
{
let fold = file.chunks.iter_mut().find(|c| c.is_list(b"Fold")).ok_or_else(|| tpl("template without Fold"))?;
let kids = kids_mut(fold)?;
let fdta = kids.iter().find(|c| c.is(b"fdta")).cloned().ok_or_else(|| tpl("template without fdta"))?;
kids.clear();
kids.push(fdta);
kids.extend(root.into_iter().flat_map(|(_, _, c)| c));
}
crate::export::effects::put_project_lists(&t.effects, &mut file, &cx.fx_use)?;
crate::export::settings::emit(&mut file, &plan.settings)?;
{
let head = file.chunks.iter_mut().find(|c| c.is(b"head")).ok_or_else(|| tpl("template without head"))?;
put_u32(data_mut(head)?, 12, cx.ids.next)?;
}
crate::write(&file).map_err(crate::export::AepExportError::Container)
}
/// Marks a root entry that goes into the `Solids` folder.
const ROOT_SOLID: u64 = 1 << 63;
fn sort_named(v: &mut [Sorted]) {
v.sort_by(|a, b| natural_cmp(&a.0, &b.0).then(a.1.cmp(&b.1)));
}
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())
}
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();
while let Some(e) = stack.pop() {
let id = if Some(e.ec) == cx.special { SOLIDS_FOLDER_ID } else { cx.ids.alloc()? };
match &e.plan {
ItemPlan::Comp(cp) => {
let seconds = f64::from(cp.duration_units) / f64::from(cp.tb.timescale.max(1));
cx.comp_ids.insert(e.ec, (id, seconds));
for _ in 0..VIEW_LAYERS {
cx.ids.alloc()?;
}
}
ItemPlan::Solid(_) => {
cx.solid_ids.insert(e.ec, id);
}
ItemPlan::Footage(fp) => {
cx.footage_ids.insert(e.ec, (id, fp.seconds));
}
ItemPlan::Folder(kids) => stack.extend(kids.iter().rev()),
}
map.insert(e.ec, id);
}
Ok(())
}
type Out<'a> = &'a mut dyn FnMut(String, u64, Vec<Chunk<'static>>);
/// Builds the chunks of one folder level (items and their trailing records) and hands each entry
/// to `sink`. Root-level solids are flagged [`ROOT_SOLID`] in their sort key.
fn build_level(entries: &[Entry], cx: &mut Cx<'_>, ids: &HashMap<ItemId, u32>, sink: Out<'_>) -> R<()> {
build_level_depth(entries, cx, ids, sink, true, 0)
}
fn build_level_depth(entries: &[Entry], cx: &mut Cx<'_>, ids: &HashMap<ItemId, u32>, sink: Out<'_>, root: bool, depth: usize) -> R<()> {
if depth > 80 {
return Err(tpl("folders nested too deeply"));
}
for e in entries {
let id = *ids.get(&e.ec).ok_or_else(|| tpl("item without an id"))?;
match &e.plan {
ItemPlan::Folder(kids) => {
let mut item = cx.t.folder_item.clone();
set_item_header(&mut item, id, e.label, &e.name)?;
let mut inner: Vec<Sorted> = Vec::new();
build_level_depth(kids, cx, ids, &mut |n, k, c| inner.push((n, k, c)), false, depth + 1)?;
if root && Some(e.ec) == cx.special {
// Completed once the hidden solids of null layers are known.
cx.special_slot = Some((item, inner));
sink(e.name.clone(), e.ec.0, Vec::new());
continue;
}
sort_named(&mut inner);
kids_mut(list_mut(&mut item, b"Sfdr")?)?.extend(inner.into_iter().flat_map(|(_, _, c)| c));
sink(e.name.clone(), e.ec.0, vec![item]);
}
ItemPlan::Comp(cp) => {
let item = build_comp(cx, id, e, cp)?;
let mut v = vec![item, cx.t.fee.clone()];
v.extend(cx.t.fset.iter().cloned());
sink(e.name.clone(), e.ec.0, v);
}
ItemPlan::Footage(fp) => {
let guid = unique_guid(cx);
let chunks = crate::export::footage::build_footage(&cx.t.footage, id, e.label, &e.name, fp, guid)?;
sink(e.name.clone(), e.ec.0, chunks);
}
ItemPlan::Solid(sp) => {
let item = build_solid(cx, id, e.label, &e.name, sp)?;
let mut v = vec![item];
v.extend(cx.t.fset.iter().cloned());
sink(e.name.clone(), e.ec.0 | if root { ROOT_SOLID } else { 0 }, v);
}
}
}
Ok(())
}
/// iide (little endian), idta id at 16 and label at 58, and the name.
fn set_item_header(item: &mut Chunk<'static>, id: u32, label: u8, name: &str) -> R<()> {
put(child_data(item, b"iide")?, 0, &id.to_le_bytes())?;
{
let idta = child_data(item, b"idta")?;
put_u32(idta, 16, id)?;
put_u8(idta, 58, label)?;
}
set_utf8(item, name)
}
fn unique_guid(cx: &mut Cx<'_>) -> [u8; 16] {
// A splitmix64 stream: distinct, deterministic, and no machine data.
let mut out = [0u8; 16];
for half in 0..2 {
cx.guid = cx.guid.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = cx.guid;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^= z >> 31;
if let Some(dst) = out.get_mut(half * 8..half * 8 + 8) {
dst.copy_from_slice(&z.to_be_bytes());
}
}
out
}
fn solid_item(cx: &mut Cx<'_>, proto: &Chunk<'static>, id: u32, label: u8, name: &str, color: [f32; 3], (w, h): (u32, u32)) -> R<Chunk<'static>> {
let mut item = proto.clone();
put(child_data(&mut item, b"iide")?, 0, &id.to_le_bytes())?;
{
let idta = child_data(&mut item, b"idta")?;
put_u32(idta, 16, id)?;
put_u8(idta, 58, label)?;
}
let guid = unique_guid(cx);
let pin = list_mut(&mut item, b"Pin ")?;
{
let sspc = child_data(pin, b"sspc")?;
put_u32(sspc, 30, w)?;
put_u32(sspc, 34, h)?;
}
{
let opti = child_data(pin, b"opti")?;
let [r, g, b] = color;
put_f32(opti, 10, 1.0)?;
put_f32(opti, 14, r)?;
put_f32(opti, 18, g)?;
put_f32(opti, 22, b)?;
put_cstr(opti, 26, MAX_SOLID_NAME + 1, name)?;
}
put(child_data(pin, b"pgui")?, 0, &guid)?;
Ok(item)
}
fn build_solid(cx: &mut Cx<'_>, id: u32, label: u8, name: &str, sp: &SolidPlan) -> R<Chunk<'static>> {
let proto = cx.t.solid_item.clone();
solid_item(cx, &proto, id, label, name, sp.color, (sp.width, sp.height))
}
/// Rebuilds all `tdb4` time scales (byte 12) below `c` to the composition's.
fn set_time_scales(c: &mut Chunk<'static>, ts: u32, depth: usize) -> R<()> {
if depth > 64 {
return Err(tpl("property tree nested too deeply"));
}
if c.is_list(b"tdbs") {
let tdb4 = child_data(c, b"tdb4")?;
put_u32(tdb4, 12, ts)?;
}
if let Ok(kids) = kids_mut(c) {
for k in kids.iter_mut() {
if k.list_type().is_some() {
set_time_scales(k, ts, depth + 1)?;
}
}
}
Ok(())
}
fn build_comp(cx: &mut Cx<'_>, id: u32, e: &Entry, cp: &CompPlan) -> R<Chunk<'static>> {
let mut item = cx.t.comp_shell.clone();
set_item_header(&mut item, id, e.label, &e.name)?;
{
let cdta = child_data(&mut item, b"cdta")?;
put_u32(cdta, 4, cp.tb.frame_duration)?;
put_u32(cdta, 8, cp.tb.timescale)?;
put_u32(cdta, 16, 600)?;
put_u32(cdta, 24, 600)?;
put_u32(cdta, 28, cp.work_start)?;
// Start and end of the work area are fractions: the time scale is their denominator once
// a work area is set, 600 while it spans the whole composition.
let set = cp.work_end.is_some() || cp.work_start != 0;
put_u32(cdta, 32, if set { cp.tb.timescale } else { 600 })?;
put_u32(cdta, 36, cp.work_end.unwrap_or(u32::MAX))?;
put_u32(cdta, 40, if set { cp.tb.timescale } else { 600 })?;
put_u32(cdta, 44, cp.duration_units)?;
put_u32(cdta, 48, cp.tb.timescale)?;
put(cdta, 52, &cp.background)?;
put_bits(cdta, 139, 0x08, cp.motion_blur)?;
put_u16(cdta, 140, cp.width)?;
put_u16(cdta, 142, cp.height)?;
put_u32(cdta, 144, cp.pixel_aspect.0)?;
put_u32(cdta, 148, cp.pixel_aspect.1)?;
put_u32(cdta, 156, crate::export::timebase::fixed_rate(cp.rate))?;
put_u32(cdta, 164, cp.display_start)?;
put_u32(cdta, 168, if cp.display_start == 0 { 1 } else { cp.tb.timescale })?;
put_u32(cdta, 172, cp.shutter_angle)?;
put_i32(cdta, 180, cp.shutter_phase)?;
}
// View layers: ids right after the composition's.
{
let mut view = id.checked_add(1).ok_or_else(|| tpl("id overflow"))?;
for k in kids_mut(&mut item)?.iter_mut() {
if k.is_list(b"DLay") || k.is_list(b"SLay") || k.is_list(b"CLay") || k.is_list(b"SecL") {
put_u32(child_data(k, b"ldta")?, 0, view)?;
view = view.checked_add(1).ok_or_else(|| tpl("id overflow"))?;
}
}
}
// The layers.
let mut layer_ids: HashMap<LayerId, u32> = HashMap::new();
for lp in &cp.layers {
layer_ids.insert(lp.ec_id, cx.ids.alloc()?);
}
let mut blocks: Vec<Chunk<'static>> = Vec::new();
for lp in &cp.layers {
let lid = *layer_ids.get(&lp.ec_id).ok_or_else(|| tpl("layer without an id"))?;
let block = build_layer(cx, lid, lp, cp, &layer_ids)?;
blocks.extend(block);
}
// Composition markers live in the view layer named `Markers` (`SecL`, 122, 509).
if !cp.markers.is_empty() {
let group = crate::export::markers::build(&cx.t.marker_group, &cp.markers)?;
let secl = kids_mut(&mut item)?.iter_mut().find(|c| c.is_list(b"SecL")).ok_or_else(|| tpl("composition without its markers layer"))?;
crate::export::markers::insert(list_mut(secl, b"tdgp")?, group)?;
}
// Every property of the composition counts keyframe times in its time scale (the layers
// have theirs already: a stretched layer's is scaled, R36).
set_time_scales(&mut item, cp.tb.timescale, 0)?;
let at = cx.t.layer_at.min(kids_mut(&mut item)?.len());
kids_mut(&mut item)?.splice(at..at, blocks);
put_used_comps(cx, &mut item, cp)?;
Ok(item)
}
/// A composition that shows other compositions as layers records each of them once in an `idpi`
/// chunk (little-endian item id) after `idpc`, and `idpc` starts with their number as a
/// little-endian `u32` (124, 257, 258, 600, 602: one; 601: two; the After Effects re-save of
/// `export-tests\precomp\p1`, written with the count 1, rewrote it to 2). The order carries no
/// meaning: After Effects reverses the list on every re-save (p1 and p1b); the exporter writes
/// ascending ids, the order After Effects created in 601.
fn put_used_comps(cx: &Cx<'_>, item: &mut Chunk<'static>, cp: &CompPlan) -> R<()> {
let mut used: Vec<u32> = Vec::new();
for lp in &cp.layers {
if let LayerSrc::Comp(c) = &lp.src {
let (id, _) = *cx.comp_ids.get(c).ok_or_else(|| tpl("precomposition without an id"))?;
if !used.contains(&id) {
used.push(id);
}
}
}
if used.is_empty() {
return Ok(());
}
used.sort_unstable();
let count = u32::try_from(used.len()).map_err(|_| tpl("too many precompositions"))?;
let kids = kids_mut(item)?;
let at = kids.iter().position(|c| c.is(b"idpc")).ok_or_else(|| tpl("composition without idpc"))?;
if let Some(idpc) = kids.get_mut(at) {
put(data_mut(idpc)?, 0, &count.to_le_bytes())?;
}
let chunks: Vec<Chunk<'static>> = used.iter().map(|id| Chunk::data(*b"idpi", id.to_le_bytes().to_vec())).collect();
kids.splice(at + 1..at + 1, chunks);
Ok(())
}
/// Sets the maximum of the inert `ADBE Time Remapping` property (`tduM`, seconds): the duration
/// of the layer's source (5 for a 5 s precomposition: 124, 257, 258; 0 for a solid: 000).
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 tdbs = kids.get_mut(at + 1).ok_or_else(|| tpl("Time Remapping without a record"))?;
put_f64(child_data(tdbs, b"tduM")?, 0, seconds)
}
/// Enables the layer's `ADBE Time Remapping` (aep-format.md, Time Remapping; 319, 354 against
/// 124, 353): `tdsb` 3 -> 1; with keys `tdb4` byte 5 bit 0 cleared and byte 68 = 1, and the `cdat`
/// replaced by a key list of plain 48-byte records (value in seconds at 8), the list header as a
/// keyed Opacity's (the same record kind); the plan always has a key (a remap without keys reads
/// back switched off, r1). An expression
/// is written as on the Transform properties (R15). The maximum (`tduM`) stays the source's
/// duration, as After Effects keeps it (319: 5).
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 tdbs = kids.get_mut(at + 1).ok_or_else(|| tpl("Time Remapping without a record"))?;
put_u32(child_data(tdbs, b"tdsb")?, 0, 1)?;
{
let tdb4 = child_data(tdbs, b"tdb4")?;
if !remap.keys.is_empty() {
let b5 = tdb4.get(5).copied().ok_or_else(|| tpl("short tdb4"))?;
put_u8(tdb4, 5, b5 & !0x01)?;
put_u8(tdb4, 68, 1)?;
}
if let Some((_, enabled)) = &remap.expr {
put_u8(tdb4, 76, 1)?;
put_u8(tdb4, 77, 1)?;
put_u8(tdb4, 120, 1)?;
put_u8(tdb4, 119, u8::from(!*enabled))?;
}
}
let rk = kids_mut(tdbs)?;
let cdat_at = rk.iter().position(|c| c.is(b"cdat")).ok_or_else(|| tpl("Time Remapping without a value"))?;
if remap.keys.is_empty() {
if let Some(cdat) = rk.get_mut(cdat_at) {
put_f64(data_mut(cdat)?, 0, remap.value.first().copied().unwrap_or(0.0))?;
}
} else {
// The key list of a keyed one-component property (Opacity's prototype).
let idx = PropKind::ALL.iter().position(|k| *k == PropKind::Opacity).ok_or_else(|| tpl("unknown property kind"))?;
let proto = cx.t.keyd.get(idx * 2 + 1).ok_or_else(|| tpl("prototype missing"))?;
let mut list = proto
.children()
.iter()
.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)),
}
if let Some(slot) = rk.get_mut(cdat_at) {
*slot = list;
}
}
if let Some((text, _)) = &remap.expr {
let at = rk.iter().position(|c| c.is(b"tdum")).unwrap_or(rk.len());
rk.insert(at, Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
}
Ok(())
}
fn build_layer(cx: &mut Cx<'_>, id: u32, lp: &LayerPlan, cp: &CompPlan, layer_ids: &HashMap<LayerId, u32>) -> R<Vec<Chunk<'static>>> {
let is_null = lp.src == LayerSrc::Null;
let mut block = match &lp.src {
LayerSrc::Null => cx.t.null_block.clone(),
LayerSrc::Text(tp) if tp.frame.is_some() => cx.t.text_box.clone(),
LayerSrc::Text(_) => cx.t.text_point.clone(),
LayerSrc::Camera(_) => cx.t.camera_block.clone(),
LayerSrc::Light(l) if l.kind == 2 => cx.t.point_block.clone(),
LayerSrc::Light(_) => cx.t.spot_block.clone(),
LayerSrc::Shape(_) => cx.t.shapes.block.clone(),
_ => cx.t.layer_block.clone(),
};
let mut remap_max = None;
let source_id = match &lp.src {
LayerSrc::Solid(item) => *cx.solid_ids.get(item).ok_or_else(|| tpl("layer source without an id"))?,
LayerSrc::Comp(item) => {
let (id, seconds) = *cx.comp_ids.get(item).ok_or_else(|| tpl("precomposition without an id"))?;
remap_max = Some(seconds);
id
}
LayerSrc::Footage(item) => {
let (id, seconds) = *cx.footage_ids.get(item).ok_or_else(|| tpl("footage without an id"))?;
remap_max = Some(seconds);
id
}
// A text layer and a camera have no source (110, 256), a light `0xffffffff` (252).
LayerSrc::Text(_) | LayerSrc::Camera(_) | LayerSrc::Shape(_) => 0,
LayerSrc::Light(_) => u32::MAX,
LayerSrc::Null => {
// The hidden solid every null object has.
let item_id = cx.ids.alloc()?;
let proto = cx.t.null_item.clone();
let name = format!("Null {}", item_id);
let item = solid_item(cx, &proto, item_id, 0, &name, [1.0, 1.0, 1.0], (100, 100))?;
cx.extra_solids.push((name, item));
item_id
}
};
let layr = block.get_mut(0).ok_or_else(|| tpl("empty layer block"))?;
{
let ldta = child_data(layr, b"ldta")?;
put_u32(ldta, 0, id)?;
put_u8(ldta, 5, lp.quality)?;
put_i32(ldta, 8, lp.stretch.0)?;
put_u32(ldta, 108, lp.stretch.1)?;
let den = cp.tb.timescale;
put_i32(ldta, 12, lp.start)?;
put_u32(ldta, 16, den)?;
put_i32(ldta, 20, lp.in_rel)?;
put_u32(ldta, 24, den)?;
put_i32(ldta, 28, lp.out_rel)?;
put_u32(ldta, 32, den)?;
put_bits(ldta, 37, 0x01, !lp.name.is_empty())?;
put_bits(ldta, 37, 0x02, lp.guide)?;
put_bits(ldta, 38, 0x02, lp.adjustment)?;
put_bits(ldta, 38, 0x04, lp.three_d)?;
put_bits(ldta, 38, 0x08, lp.solo)?;
put_bits(ldta, 38, 0x80, is_null)?;
put_bits(ldta, 39, 0x01, lp.video)?;
put_bits(ldta, 39, 0x02, lp.audio)?;
put_bits(ldta, 39, 0x04, lp.effects)?;
put_bits(ldta, 39, 0x08, lp.motion_blur)?;
put_bits(ldta, 39, 0x20, lp.locked)?;
put_bits(ldta, 39, 0x40, lp.shy)?;
put_bits(ldta, 39, 0x80, lp.collapse)?;
put_u32(ldta, 40, source_id)?;
put_u8(ldta, 61, lp.label)?;
put_cstr(ldta, 64, 32, &lp.name)?;
put_u8(ldta, 99, lp.blend)?;
// Layer type: 3 text, 2 camera, 1 light, 0 AV (solid, footage, precomposition, null) (3.1);
// the light type at 136 (1 spot, 2 point); auto-orient towards the point of interest is
// byte 38 bit 0x40 (two-node camera 256 vs one-node 251; set on every light).
let ty = match &lp.src {
LayerSrc::Text(_) => 3,
LayerSrc::Camera(_) => 2,
LayerSrc::Light(_) => 1,
LayerSrc::Shape(_) => 4,
_ => 0,
};
put_u32(ldta, 128, ty)?;
match &lp.src {
LayerSrc::Camera(c) => put_bits(ldta, 38, 0x40, c.two_node)?,
LayerSrc::Light(l) => {
put_u32(ldta, 136, l.kind)?;
put_bits(ldta, 38, 0x40, true)?;
}
_ => {}
}
let parent = lp.parent.and_then(|p| layer_ids.get(&p).copied()).unwrap_or(0);
put_u32(ldta, 132, parent)?;
// Track matte: mode at 107, the matte layer's id at 160 (403-408).
let (matte_id, matte_mode) = lp.matte.and_then(|(m, mode)| layer_ids.get(&m).map(|id| (*id, mode))).unwrap_or((0, 0));
put_u8(ldta, 107, matte_mode)?;
put_u32(ldta, 160, matte_id)?;
}
set_utf8(layr, &lp.name)?;
if let LayerSrc::Text(tp) = &lp.src {
let guid = unique_guid(cx);
crate::export::text::put_doc(layr, tp, guid)?;
crate::export::textanim::put_animators(layr, &cx.t.anims, &tp.animators, &cx.t.shapes.key_list)?;
}
if let Some(seconds) = remap_max {
put_time_remap_max(layr, seconds)?;
}
if let Some(remap) = &lp.remap {
put_time_remap(cx, layr, remap)?;
}
put_properties(cx, layr, lp, cp)?;
put_masks(cx, layr, lp)?;
put_effects(cx, layr, lp, id, layer_ids)?;
if let Some(styles) = &lp.styles {
crate::export::styles::put_styles(&cx.t.styles, layr, styles)?;
}
match &lp.src {
LayerSrc::Camera(c) => crate::export::camlight::put_camera(layr, &cx.t.options, c)?,
LayerSrc::Light(l) => crate::export::camlight::put_light(layr, &cx.t.options, l)?,
LayerSrc::Shape(items) => crate::export::shapes::put_contents(layr, &cx.t.shapes, items)?,
_ => {}
}
if !lp.markers.is_empty() {
let group = crate::export::markers::build(&cx.t.marker_group, &lp.markers)?;
crate::export::markers::insert(list_mut(layr, b"tdgp")?, group)?;
}
set_time_scales(layr, lp.time_scale, 0)?;
Ok(block)
}
/// Inserts the layer's `ADBE Mask Parade` before its Transform group (after Time Remapping, as
/// After Effects stores it: 090).
fn put_masks(cx: &Cx<'_>, layr: &mut Chunk<'static>, lp: &LayerPlan) -> R<()> {
if lp.masks.is_empty() {
return Ok(());
}
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"))?;
kids.splice(at..at, parade);
Ok(())
}
/// Inserts the layer's `ADBE Effect Parade` right before its Transform group (after the masks:
/// 357, 398).
fn put_effects(cx: &mut Cx<'_>, layr: &mut Chunk<'static>, lp: &LayerPlan, layer_id: u32, layer_ids: &HashMap<LayerId, u32>) -> R<()> {
if lp.fx.is_empty() {
return Ok(());
}
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"))?;
kids.splice(at..at, parade);
Ok(())
}
/// The order of a Transform group's records; `ADBE Group End` closes the group whatever else it
/// holds.
const GROUP_ORDER: [&str; 13] = [
"ADBE Anchor Point",
"ADBE Position",
"ADBE Position_0",
"ADBE Position_1",
"ADBE Position_2",
"ADBE Scale",
"ADBE Orientation",
"ADBE Rotate X",
"ADBE Rotate Y",
"ADBE Rotate Z",
"ADBE Opacity",
"ADBE Envir Appear in Reflect",
"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() {
return Ok(());
}
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 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 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 node = it.next().ok_or_else(|| tpl("match name without a node"))?;
pairs.push((name, vec![m, node]));
}
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 entry = vec![tdmn, built];
if let Some(slot) = pairs.iter_mut().find(|(n, _)| n == name) {
slot.1 = entry;
} else {
pairs.push((name.to_string(), 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()) };
pairs.sort_by_key(|(n, _)| rank(n));
gk.extend(header);
gk.extend(pairs.into_iter().flat_map(|(_, v)| v));
Ok(())
}
fn build_prop(cx: &Cx<'_>, p: &PropPlan, lp: &LayerPlan, cp: &CompPlan) -> R<Chunk<'static>> {
let idx = PropKind::ALL.iter().position(|k| *k == p.kind).ok_or_else(|| tpl("unknown property kind"))?;
let pool = if p.keys.is_empty() { &cx.t.stat } else { &cx.t.keyd };
let tdbs = pool.get(idx * 2 + 1).ok_or_else(|| tpl("prototype missing"))?;
let mut tdbs = tdbs.clone();
{
let tdb4 = child_data(&mut tdbs, b"tdb4")?;
put_u32(tdb4, 12, cp.tb.timescale)?;
if p.kind == PropKind::Anchor {
// The width / height of the layer's source (kept next to the anchor's other
// normalisation constants).
put_f64(tdb4, 24, f64::from(lp.source_size.0) / f64::from(lp.source_size.1.max(1)))?;
}
if let Some((_, enabled)) = &p.expr {
put_u8(tdb4, 76, 1)?;
put_u8(tdb4, 77, 1)?;
put_u8(tdb4, 120, 1)?;
put_u8(tdb4, 119, u8::from(!*enabled))?;
}
}
if p.keys.is_empty() {
let cdat = child_data(&mut tdbs, b"cdat")?;
cdat.iter_mut().for_each(|b| *b = 0);
for (i, v) in p.value.iter().enumerate() {
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)),
}
}
if let Some((text, _)) = &p.expr {
let kids = kids_mut(&mut tdbs)?;
let at = kids.iter().position(|c| c.is(b"tdum")).unwrap_or(kids.len());
kids.insert(at, Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
}
Ok(tdbs)
}
/// One keyframe record (`docs/aep-format.md`, 3.5).
fn key_record(kind: PropKind, k: &KeyPlan, size: usize) -> R<Vec<u8>> {
let mut r = vec![0u8; size];
let n = kind.dims();
put_i32(&mut r, 0, k.time)?;
put_u8(&mut r, 4, k.in_interp)?;
put_u8(&mut r, 5, k.out_interp)?;
let base: u16 = if kind.spatial() { 0x0007 } else { 0 };
let flags = base | if k.roving { 0x0020 } else { 0 } | (u16::from(k.label) << 6);
put_u16(&mut r, 6, flags)?;
if kind.spatial() {
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))?;
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))?;
}
} else {
r = plain_record(n, k, size)?;
}
Ok(r)
}
/// A plain keyframe record with `n` components: value at 8, then the type-major ease blocks.
pub(crate) fn plain_record(n: usize, k: &KeyPlan, size: usize) -> R<Vec<u8>> {
let mut r = vec![0u8; size];
put_i32(&mut r, 0, k.time)?;
put_u8(&mut r, 4, k.in_interp)?;
put_u8(&mut r, 5, k.out_interp)?;
let flags = if k.roving { 0x0020 } else { 0 } | (u16::from(k.label) << 6);
put_u16(&mut r, 6, flags)?;
for j in 0..n {
put_f64(&mut r, 8 + 8 * j, k.value.get(j).copied().unwrap_or(0.0))?;
}
let base = 8 + 8 * n;
for j in 0..n {
let i = k.in_ease.get(j).or(k.in_ease.last()).copied().unwrap_or_default();
let o = k.out_ease.get(j).or(k.out_ease.last()).copied().unwrap_or_default();
put_f64(&mut r, base + 8 * j, i.speed)?;
put_f64(&mut r, base + 8 * n + 8 * j, i.influence)?;
put_f64(&mut r, base + 16 * n + 8 * j, o.speed)?;
put_f64(&mut r, base + 24 * n + 8 * j, o.influence)?;
}
Ok(r)
}
+653
View File
@@ -0,0 +1,653 @@
//! Footage items (files), built in code per kind ([`FtProtos::build`]) with the layout of the items
//! After Effects writes when it imports a file of that kind: png still 607, jpeg 605, OpenEXR 604,
//! TIFF 613, H.264 mp4 606, QuickTime mov 612, WAV 351, png sequence 353, OpenEXR sequence 603,
//! jpeg sequence 611, Targa, Photoshop, Illustrator and EPS 650-653. The colour management names
//! our own sRGB profile (`icc.rs`). The exporter then writes the decoded fields
//! (`docs/aep-format.md` 3.3, `docs/aep-export.md` R28):
//!
//! * the alias JSON (`Als2/alas`): the full path, for a sequence its folder with
//! `target_is_folder`;
//! * `sspc`: width, height, duration (`num / den`), native frame rate, for sequences the first and
//! last frame number and the digits, and the folder's modification time when the caller gives
//! it ([`crate::export::export_with`]); the two `Utf8` around the number;
//! * `opti` of png: width, height and the first file's name;
//! * the item header: id, label, name; a fresh `pgui`.
//!
//! After Effects reads the format options of the other kinds from the file (their `opti` beyond
//! the header can be zero: read-backs v-fN-zoptiA).
use effectcraft_project::{Footage, FootageKind};
use crate::export::report::{Collector, LossCategory};
/// The prototype a footage item is cloned from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FtKind {
Png,
Jpeg,
Exr,
Mp4,
Wav,
PngSeq,
ExrSeq,
JpegSeq,
Mov,
Tiff,
Tga,
Psd,
Ai,
Eps,
}
impl FtKind {
/// The key a kind's prototype is found under.
pub(crate) fn key(self) -> [u8; 4] {
match self {
FtKind::Png => *b"png ",
FtKind::Jpeg => *b"jpg ",
FtKind::Exr => *b"exr ",
FtKind::Mp4 => *b"mp4 ",
FtKind::Wav => *b"wav ",
FtKind::PngSeq => *b"pngS",
FtKind::ExrSeq => *b"exrS",
FtKind::JpegSeq => *b"jpgS",
FtKind::Mov => *b"mov ",
FtKind::Tiff => *b"tif ",
FtKind::Tga => *b"tga ",
FtKind::Psd => *b"psd ",
FtKind::Ai => *b"ai ",
FtKind::Eps => *b"eps ",
}
}
/// The denominator of a still's duration (`sspc@42`: png 1, jpeg 600, OpenEXR 100).
fn still_den(self) -> u32 {
match self {
FtKind::Jpeg | FtKind::Tiff | FtKind::Tga | FtKind::Psd | FtKind::Ai | FtKind::Eps => 600,
FtKind::Exr => 100,
_ => 1,
}
}
pub(crate) fn is_sequence(self) -> bool {
matches!(self, FtKind::PngSeq | FtKind::ExrSeq | FtKind::JpegSeq)
}
}
/// The numbering of a sequence.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Numbering {
pub prefix: String,
pub suffix: String,
pub start: u32,
pub end: u32,
pub digits: u32,
}
/// A footage item in the file's units.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct FootagePlan {
pub kind: FtKind,
/// The alias target: the file, or a sequence's folder.
pub alias: String,
/// The (first) file's path as the project stores it: what the caller of
/// [`crate::export::export_with`] checks before it reads the sequence folder's time.
pub source: String,
/// The (first) file's name.
pub file_name: String,
pub width: u32,
pub height: u32,
/// Duration as stored, `num / den` seconds.
pub duration: (u32, u32),
/// Native frame rate (sequences and clips), 0 otherwise.
pub fps: u32,
/// The rate a clip is conformed to (`sspc@146`, also the effective rate at @150; 645), 0 when
/// it plays at its native rate.
pub conform: u32,
pub numbering: Option<Numbering>,
/// The duration in seconds (the Time Remapping maximum of a layer showing it).
pub seconds: f64,
/// A sequence's folder modification time as stored (`sspc@118`, seconds since 1904, UTC; 860),
/// when the caller supplied it ([`crate::export::export_with`]).
pub folder_time: Option<u32>,
}
/// Seconds between 1904-01-01 (the stored time's epoch) and 1970-01-01.
const SECONDS_1904_TO_1970: u64 = 2_082_844_800;
/// Fills in the folder time of every image sequence in `root` (folders included) from
/// `folder_time`, asked with the sequence's first file as the project stores it (seconds since
/// 1970); a time that does not fit the stored field is left out.
pub(crate) fn stamp_sequences(root: &mut [crate::export::plan::Entry], folder_time: &dyn Fn(&str) -> Option<u64>) {
use crate::export::plan::ItemPlan;
// Folders were planned with a bounded depth; walk them with an explicit stack anyway.
let mut stack: Vec<&mut [crate::export::plan::Entry]> = vec![root];
while let Some(entries) = stack.pop() {
for e in entries.iter_mut() {
match &mut e.plan {
ItemPlan::Folder(kids) => stack.push(kids),
ItemPlan::Footage(fp) if fp.kind.is_sequence() => {
fp.folder_time = folder_time(&fp.source).and_then(|t| u32::try_from(t.checked_add(SECONDS_1904_TO_1970)?).ok());
}
_ => {}
}
}
}
}
fn ext(path: &str) -> String {
let name = path.rsplit(['\\', '/']).next().unwrap_or_default();
match name.rsplit_once('.') {
Some((_, e)) => e.to_ascii_lowercase(),
None => String::new(),
}
}
fn split_dir(path: &str) -> (&str, &str) {
match path.rfind(['\\', '/']) {
Some(i) => (path.get(..i).unwrap_or_default(), path.get(i + 1..).unwrap_or_default()),
None => ("", path),
}
}
/// `shot_0101.exr` -> (`shot_`, 101, 4, `.exr`): the last run of digits before the extension.
fn parse_numbered(name: &str) -> Option<(String, u32, u32, String)> {
let dot = name.rfind('.').unwrap_or(name.len());
let stem = name.get(..dot)?;
let digits = stem.chars().rev().take_while(char::is_ascii_digit).count();
if digits == 0 || digits > 9 {
return None;
}
let split = stem.len().checked_sub(digits)?;
let number: u32 = stem.get(split..)?.parse().ok()?;
Some((stem.get(..split)?.to_string(), number, u32::try_from(digits).ok()?, name.get(dot..)?.to_string()))
}
/// Whole frames at an integer rate, or `None` (a rate After Effects' footage header stores as an
/// integer: 30 in 353 and 603, 25 in 606).
fn integer_rate(f: &Footage) -> Option<u32> {
let r = f.frame_rate;
(r.den == 1 && r.num > 0).then(|| u32::try_from(r.num).ok()).flatten()
}
/// Plans one footage item, or reports why it cannot be written.
pub(crate) fn plan_footage(name: &str, f: &Footage, col: &mut Collector) -> Option<FootagePlan> {
let what = |why: &str| format!("footage '{name}': {why}");
if f.layer.is_some() {
col.lose(LossCategory::FootageItems, what("one layer of a layered file is not exported"));
return None;
}
// Interpret Footage settings other than the defaults are not written (After Effects
// interprets the file itself).
let d = Footage::default();
let unwritten = [
((f.pixel_aspect - d.pixel_aspect).abs() > 1e-9, "pixel aspect"),
(f.alpha != d.alpha || f.premul_color != d.premul_color, "alpha interpretation"),
(f.invert_alpha, "Invert Alpha"),
(f.loop_count != d.loop_count, "loop count"),
(f.color_profile.is_some(), "colour profile"),
(f.fields != d.fields, "field order"),
(f.linear_light != d.linear_light, "Interpret As Linear Light"),
(f.preserve_rgb != d.preserve_rgb, "Preserve RGB"),
(f.cineon != d.cineon, "Cineon settings"),
];
for (_, setting) in unwritten.iter().filter(|(on, _)| *on) {
col.lose(LossCategory::FootageItems, what(&format!("the Interpret Footage {setting} is not written (the default is)")));
}
let e = ext(&f.path);
let kind = match (f.kind, e.as_str()) {
(FootageKind::Still, "png") => FtKind::Png,
(FootageKind::Still, "jpg" | "jpeg") => FtKind::Jpeg,
(FootageKind::Still, "exr") => FtKind::Exr,
(FootageKind::Still, "tif" | "tiff") => FtKind::Tiff,
(FootageKind::Still, "tga") => FtKind::Tga,
(FootageKind::Still, "psd") => FtKind::Psd,
(FootageKind::Still, "ai") => FtKind::Ai,
(FootageKind::Still, "eps") => FtKind::Eps,
(FootageKind::Sequence, "jpg" | "jpeg") => FtKind::JpegSeq,
(FootageKind::Video, "mov") => FtKind::Mov,
(FootageKind::Sequence, "png") => FtKind::PngSeq,
(FootageKind::Sequence, "exr") => FtKind::ExrSeq,
(FootageKind::Video, "mp4" | "m4v") => FtKind::Mp4,
(FootageKind::Audio, "wav") => FtKind::Wav,
_ => {
col.lose(LossCategory::FootageItems, what(&format!("{:?} footage of type '.{e}' is not exported (no prototype)", f.kind)));
return None;
}
};
if f.path.is_empty() || f.path.chars().any(char::is_control) {
col.lose(LossCategory::FootageItems, what("no usable path"));
return None;
}
if f.width > crate::export::plan::MAX_SIDE || f.height > crate::export::plan::MAX_SIDE {
col.lose(
LossCategory::FootageItems,
what(&format!("size {} x {} is larger than {}, written smaller", f.width, f.height, crate::export::plan::MAX_SIDE)),
);
}
let width = f.width.min(crate::export::plan::MAX_SIDE);
let height = f.height.min(crate::export::plan::MAX_SIDE);
let (dir, file) = split_dir(&f.path);
let mut plan = FootagePlan {
kind,
alias: f.path.clone(),
source: f.path.clone(),
file_name: file.to_string(),
width,
height,
duration: (0, kind.still_den()),
fps: 0,
conform: 0,
numbering: None,
seconds: 0.0,
folder_time: None,
};
match kind {
FtKind::PngSeq | FtKind::ExrSeq | FtKind::JpegSeq => {
let Some(fps) = integer_rate(f) else {
col.lose(
LossCategory::FootageItems,
what(&format!("a sequence at {} fps is not exported (only whole rates are sampled)", f.frame_rate.label())),
);
return None;
};
let Some((prefix, start, digits, suffix)) = parse_numbered(file) else {
col.lose(LossCategory::FootageItems, what("a sequence whose first file has no frame number"));
return None;
};
// The files must be the run start, start + 1, ... with the same name around the number.
let files: Vec<&str> = if f.sequence.is_empty() { vec![file] } else { f.sequence.iter().map(|p| split_dir(p).1).collect() };
let mut expect = start;
for name in &files {
let ok = parse_numbered(name).is_some_and(|(p, n, _, s)| p == prefix && s == suffix && n == expect);
if !ok {
col.lose(LossCategory::FootageItems, what("a sequence with gaps or mixed names is not exported"));
return None;
}
expect = expect.saturating_add(1);
}
let count = u32::try_from(files.len()).unwrap_or(u32::MAX);
plan.alias = dir.to_string();
plan.fps = fps;
plan.duration = (count, fps);
plan.seconds = f64::from(count) / f64::from(fps.max(1));
plan.numbering = Some(Numbering { prefix, suffix, start, end: start.saturating_add(count.saturating_sub(1)), digits });
if dir.is_empty() {
col.lose(LossCategory::FootageItems, what("a sequence without a folder"));
return None;
}
}
FtKind::Mp4 | FtKind::Mov => {
let Some(fps) = integer_rate(f) else {
col.lose(LossCategory::FootageItems, what(&format!("a clip at {} fps is not exported (only whole rates are sampled)", f.frame_rate.label())));
return None;
};
// A conformed clip (645): the frames play at `fps`, the stored duration stays in the
// native rate's frames, and the conformed rate goes to @146 and @150.
let native = match f.native_rate {
Some(n) if n != f.frame_rate => {
if n.den == 1 && n.num > 0 && n.num <= i64::from(u32::MAX) {
u32::try_from(n.num).ok()
} else {
col.lose(
LossCategory::FootageItems,
what(&format!("a clip with the native rate {} fps is written at its conformed rate only", n.label())),
);
None
}
}
_ => None,
};
let frames = (f.duration.seconds() * f64::from(fps)).round();
let frames = if frames.is_finite() && frames >= 1.0 && frames < f64::from(u32::MAX) {
frames as u32
} else {
col.lose(LossCategory::FootageItems, what("a duration that cannot be stored, written as 1 frame"));
1
};
plan.seconds = f64::from(frames) / f64::from(fps.max(1));
match native {
Some(n) => {
plan.fps = n;
plan.conform = fps;
plan.duration = (frames, n);
}
None => {
plan.fps = fps;
plan.duration = (frames, fps);
}
}
}
FtKind::Wav => {
// The sample rate is the denominator (351: 48 000 / 48 000 for 1 s).
let secs = f.duration.seconds();
let samples = (secs * 48_000.0).round();
let samples = if samples.is_finite() && samples >= 1.0 && samples < f64::from(u32::MAX) {
samples as u32
} else {
col.lose(LossCategory::FootageItems, what("a duration that cannot be stored, written as 1 second"));
48_000
};
plan.duration = (samples, 48_000);
plan.seconds = f64::from(samples) / 48_000.0;
}
FtKind::Png | FtKind::Jpeg | FtKind::Exr | FtKind::Tiff | FtKind::Tga | FtKind::Psd | FtKind::Ai | FtKind::Eps => {}
}
col.exported.footage = col.exported.footage.saturating_add(1);
Some(plan)
}
/// The alias JSON After Effects reads (`Als2/alas`, 126, 351, 353, 603), with the path escaped.
pub(crate) fn alias_json(p: &FootagePlan) -> Vec<u8> {
let mut path = String::with_capacity(p.alias.len() + 8);
for c in p.alias.chars() {
match c {
'"' => path.push_str("\\\""),
'\\' => path.push_str("\\\\"),
c if (c as u32) < 0x20 => path.push_str(&format!("\\u{:04x}", c as u32)),
c => path.push(c),
}
}
let folder = p.kind.is_sequence();
format!(
"{{\"ascendcount_base\":1,\"ascendcount_target\":{},\"fullpath\":\"{path}\",\"platform\":1,\"server_name\":\"\",\"server_volume_name\":\"\",\"target_is_folder\":{folder}}}",
if folder { 2 } else { 1 }
)
.into_bytes()
}
// ---------------------------------------------------------------------------------------------
// Emit.
use crate::Chunk;
use crate::export::tree::{R, child_data, kids_mut, list_mut, put, put_cstr, put_u8, put_u16, put_u32, tpl};
/// The footage prototypes: per kind the item and the f-records that follow it.
pub(crate) struct FtProtos {
items: Vec<([u8; 4], Vec<Chunk<'static>>)>,
}
/// Every kind the exporter writes.
const KINDS: [FtKind; 14] = [
FtKind::Png,
FtKind::Jpeg,
FtKind::Exr,
FtKind::Mp4,
FtKind::Wav,
FtKind::PngSeq,
FtKind::ExrSeq,
FtKind::JpegSeq,
FtKind::Mov,
FtKind::Tiff,
FtKind::Tga,
FtKind::Psd,
FtKind::Ai,
FtKind::Eps,
];
/// The colour management a kind's item carries (`Pin /CLRS`, 351, 353, 603-607, 611-613, 650-653).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Clrs {
/// Stills, sequences and audio: interpreted in the sRGB profile (`apid` its id).
Assigned,
/// A file with an embedded profile (TIFF, Photoshop): `epid` its id, the profile twice.
Embedded,
/// Video and JPEG: Rec. 709 with the codec's colour description.
Video(&'static str),
}
/// The colour description After Effects gives a JPEG, a jpeg sequence and a ProRes clip.
const BT709_FULL: &str = r#"{"baseColorProfile":{"colorProfileName":"BT.709 RGB Full"},"baseProfileType":1}"#;
/// The colour description of an H.264 clip.
const BT709_DISPLAY: &str =
r#"{"baseColorProfile":{"colorProfileData":"AQAAAP////8=","colorProfileName":"BT.709,8-bit,Display-Referred"},"baseProfileType":1}"#;
/// What a kind's item stores beyond the decoded fields: the file type tag (`sspc` 22, `opti` 0),
/// `idta` byte 23, the bits per pixel of the sampled file (`sspc` 63), `sspc` byte 73 (3, 1 for
/// OpenEXR, 0 for Illustrator and EPS), the `opti` size and its header bytes 4, 5 and 10 (the rest of
/// `opti` can be zero: read-back v-fN-zoptiA), and the colour management.
struct KindSpec {
tag: [u8; 4],
idta23: u8,
bpp: u8,
b73: u8,
opti: (u16, u8, u8, u8),
clrs: Clrs,
}
fn spec(kind: FtKind) -> KindSpec {
let (tag, idta23, bpp, b73, opti, clrs) = match kind {
FtKind::Png => (*b"png!", 0x30, 24, 3, (322, 0, 1, 1), Clrs::Assigned),
FtKind::Jpeg => (*b"ZPEG", 0x30, 24, 3, (58, 0, 5, 0), Clrs::Video(BT709_FULL)),
FtKind::Exr => (*b"oEXR", 0x30, 128, 1, (9750, 0, 1, 1), Clrs::Assigned),
FtKind::Mp4 => (*b"XCEX", 0x20, 24, 3, (58, 0, 5, 0), Clrs::Video(BT709_DISPLAY)),
FtKind::Wav => (*b"WAVE", 0x04, 0, 3, (58, 0, 5, 0), Clrs::Assigned),
FtKind::PngSeq => (*b"png!", 0x20, 24, 3, (322, 0, 1, 1), Clrs::Assigned),
FtKind::ExrSeq => (*b"oEXR", 0x20, 128, 1, (9750, 0, 1, 1), Clrs::Assigned),
FtKind::JpegSeq => (*b"ZPEG", 0x20, 24, 3, (58, 0, 5, 0), Clrs::Video(BT709_FULL)),
FtKind::Mov => (*b"MOoV", 0x20, 48, 3, (58, 0, 5, 0), Clrs::Video(BT709_FULL)),
FtKind::Tiff => (*b"TIF ", 0x30, 24, 3, (602, 1, 9, 0), Clrs::Embedded),
FtKind::Tga => (*b"TPIC", 0x30, 24, 3, (30, 0, 46, 5), Clrs::Assigned),
FtKind::Psd => (*b"8BPS", 0x30, 24, 3, (602, 1, 9, 0), Clrs::Embedded),
FtKind::Ai | FtKind::Eps => (*b"TEXT", 0x30, 32, 0, (596, 0, 8, 0), Clrs::Assigned),
};
KindSpec { tag, idta23, bpp, b73, opti, clrs }
}
/// The colour-management list of a kind (the order After Effects writes).
fn clrs(kind: Clrs) -> Chunk<'static> {
use crate::export::base::utf8;
let icc = crate::export::icc::srgb();
let id = crate::export::icc::profile_id(&icc).to_vec();
let json = crate::export::icc::profile_json(&icc, crate::export::icc::SRGB_NAME);
let none = vec![0xffu8; 16];
let one = |id: &[u8; 4]| Chunk::data(*id, vec![1u8]);
let tail = |kids: &mut Vec<Chunk<'static>>| {
kids.push(one(b"hdrm"));
kids.push(utf8("{}"));
};
let mut kids = match kind {
Clrs::Assigned => vec![
Chunk::data(*b"epid", none),
Chunk::data(*b"apid", id),
Chunk::data(*b"linl", vec![2, 0, 0, 0]),
one(b"embp"),
Chunk::data(*b"ipws", vec![0]),
one(b"Mcsp"),
utf8(""),
one(b"ocsp"),
utf8(&json),
],
Clrs::Embedded => vec![
Chunk::data(*b"epid", id),
Chunk::data(*b"apid", none),
Chunk::data(*b"linl", vec![2, 0, 0, 0]),
one(b"embp"),
Chunk::data(*b"ipws", vec![0]),
one(b"mcsp"),
utf8(&json),
one(b"Mcsp"),
utf8(&json),
one(b"ocsp"),
utf8(""),
],
Clrs::Video(desc) => vec![
Chunk::data(*b"epid", none.clone()),
Chunk::data(*b"apid", none),
one(b"empd"),
utf8("Rec. 709"),
Chunk::data(*b"linl", vec![0; 4]),
one(b"embp"),
Chunk::data(*b"ipws", vec![0]),
one(b"mcsp"),
utf8(desc),
one(b"Mcsp"),
utf8(desc),
one(b"ocsp"),
utf8(""),
],
};
tail(&mut kids);
Chunk::list(*b"CLRS", kids)
}
/// The item of a kind with zero ids and an empty alias (`build_footage` fills them), and the
/// f-records after it. `sspc` holds the tag, the bits per pixel, the time base of a still (600:
/// a clip's is its rate, written per item) and the bytes that have the same value in every
/// generated test file of the kind (125, 129,
/// 139, 143, 188..195; a sequence also 168, 184, 186, 187; a WAV its sample rate at 160); the bytes
/// left zero were zero in read-backs v-fN-zsspc1..3. `mnfo` is left out (v-fN-nomnfo).
fn kind_item(kind: FtKind) -> Vec<Chunk<'static>> {
use crate::export::base::{bytes, utf8};
let s = spec(kind);
let mut fields: Vec<(usize, Vec<u8>)> = vec![
(22, s.tag.to_vec()),
(50, 600u32.to_be_bytes().to_vec()),
(63, vec![s.bpp]),
(73, vec![s.b73]),
(125, vec![0x0c]),
(129, vec![1]),
(139, vec![1]),
(143, vec![1]),
(188, vec![0xff; 8]),
];
if kind.is_sequence() {
fields.extend([(168, 2u32.to_be_bytes().to_vec()), (184, vec![1]), (186, vec![1, 1])]);
}
if kind == FtKind::Wav {
fields.push((160, 48_000f64.to_be_bytes().to_vec()));
}
let refs: Vec<(usize, &[u8])> = fields.iter().map(|(at, v)| (*at, v.as_slice())).collect();
let (len, b4, b5, b10) = s.opti;
let opti = bytes(usize::from(len), &[(0, &s.tag), (4, &[b4, b5]), (8, &len.to_be_bytes()), (10, &[b10])]);
let mut pin = vec![Chunk::data(*b"sspc", bytes(222, &refs)), utf8(""), Chunk::list(*b"Als2", vec![Chunk::data(*b"alas", b"{}".to_vec())])];
if kind.is_sequence() {
pin.extend([utf8(""), utf8("")]);
}
pin.extend([Chunk::data(*b"opti", opti), Chunk::data(*b"pgui", vec![0; 16]), clrs(s.clrs), utf8("")]);
let item = Chunk::list(
*b"Item",
vec![
Chunk::data(*b"iide", vec![0; 4]),
Chunk::data(*b"idpc", vec![0; 8]),
crate::export::base::idta(7, s.idta23),
utf8(""),
Chunk::list(*b"Pin ", pin),
crate::export::base::ftgi(),
utf8(""),
crate::export::base::guides(),
],
);
let mut out = vec![item];
out.extend(crate::export::skeleton::f_records());
out
}
impl FtProtos {
/// The items of every kind, built in code.
pub(crate) fn build() -> FtProtos {
FtProtos { items: KINDS.iter().map(|k| (k.key(), kind_item(*k))).collect() }
}
}
/// The item (and its f-records) for `p`, with the id, label and name, and a fresh `pgui`.
pub(crate) fn build_footage(protos: &FtProtos, id: u32, label: u8, name: &str, p: &FootagePlan, guid: [u8; 16]) -> R<Vec<Chunk<'static>>> {
let key = p.kind.key();
let mut chunks = protos.items.iter().find(|(k, _)| *k == key).map(|(_, v)| v.clone()).ok_or_else(|| tpl("footage prototype missing"))?;
let item = chunks.get_mut(0).ok_or_else(|| tpl("empty footage prototype"))?;
put(child_data(item, b"iide")?, 0, &id.to_le_bytes())?;
{
let idta = child_data(item, b"idta")?;
put_u32(idta, 16, id)?;
put_u8(idta, 58, label)?;
}
// After Effects names a footage item after its file and then stores no name of its own (126,
// 603-607); a name of the user's is the item's `Utf8`. The WAV prototype keeps the name (351).
let default = match &p.numbering {
Some(n) => format!("{}[{:0w$}-{:0w$}]{}", n.prefix, n.start, n.end, n.suffix, w = usize::try_from(n.digits.min(16)).unwrap_or(0)),
None => p.file_name.clone(),
};
let stored = if name == default && p.kind != FtKind::Wav { "" } else { name };
crate::export::tree::set_utf8(item, stored)?;
let pin = list_mut(item, b"Pin ")?;
{
let sspc = child_data(pin, b"sspc")?;
put_u32(sspc, 30, p.width)?;
put_u32(sspc, 34, p.height)?;
put_u32(sspc, 38, p.duration.0)?;
put_u32(sspc, 42, p.duration.1)?;
if p.fps > 0 {
// A clip counts its time in its native rate (606, 612: 25); stills, sequences and
// audio in 600ths.
if matches!(p.kind, FtKind::Mp4 | FtKind::Mov) {
put_u32(sspc, 50, p.fps)?;
}
put_u32(sspc, 56, p.fps)?;
put_u32(sspc, 150, if p.conform > 0 { p.conform } else { p.fps })?;
}
if p.conform > 0 {
put_u32(sspc, 146, p.conform)?;
}
if let Some(n) = &p.numbering {
put_u32(sspc, 172, n.start)?;
put_u32(sspc, 176, n.end)?;
put_u32(sspc, 180, n.digits)?;
}
if let (true, Some(t)) = (p.kind.is_sequence(), p.folder_time) {
put_u32(sspc, 118, t)?;
}
}
{
let als = list_mut(pin, b"Als2")?;
let alas = kids_mut(als)?.iter_mut().find(|c| c.is(b"alas")).ok_or_else(|| tpl("footage prototype without alias"))?;
*alas = Chunk::data(*b"alas", alias_json(p));
}
if let Some(n) = &p.numbering {
// The two Utf8 between the alias and opti: the name around the number (353, 603).
let kids = kids_mut(pin)?;
let at = kids.iter().position(|c| c.is_list(b"Als2")).ok_or_else(|| tpl("footage prototype without alias"))?;
let mut names = [n.prefix.as_str(), n.suffix.as_str()].into_iter();
for c in kids.iter_mut().skip(at + 1).take_while(|c| !c.is(b"opti")) {
if c.is(b"Utf8")
&& let Some(text) = names.next()
{
*c = Chunk::data(*b"Utf8", text.as_bytes().to_vec());
}
}
}
if matches!(p.kind, FtKind::Png | FtKind::PngSeq) {
// png options: width and height (u16 at 20 and 24) and the (first) file's name at 58
// (126, 353, 607).
let opti = child_data(pin, b"opti")?;
put_u16(opti, 20, u16::try_from(p.width).unwrap_or(u16::MAX))?;
put_u16(opti, 24, u16::try_from(p.height).unwrap_or(u16::MAX))?;
put_cstr(opti, 58, 256, &p.file_name)?;
}
put(child_data(pin, b"pgui")?, 0, &guid)?;
Ok(chunks)
}
#[cfg(test)]
mod tests {
use super::*;
/// Every kind's item has the chunks After Effects refuses it without (`CLRS`, `ftgi`: read-backs
/// u-noclrs, u-noftgi) and the f-records after it; `opti` has its header and its size.
#[test]
fn every_kind_has_what_after_effects_needs() {
let protos = FtProtos::build();
assert_eq!(protos.items.len(), KINDS.len());
for (key, chunks) in &protos.items {
let what = String::from_utf8_lossy(key).into_owned();
let item = &chunks[0];
let pin = item.child_list(b"Pin ").unwrap();
assert!(pin.child_list(b"CLRS").is_some() && item.child(b"ftgi").is_some(), "{what}");
assert_eq!(chunks.len(), 8, "{what}: the item and seven f-records");
let opti = pin.child(b"opti").and_then(|c| c.bytes()).unwrap();
assert_eq!(usize::from(u16::from_be_bytes([opti[8], opti[9]])), opti.len(), "{what}");
let sspc = pin.child(b"sspc").and_then(|c| c.bytes()).unwrap();
assert_eq!(&sspc[22..26], &opti[0..4], "{what}");
}
}
}
+709
View File
@@ -0,0 +1,709 @@
//! The effects the exporter writes and the parameters of each, in `parT` order: what After
//! Effects shows for an effect (its match name and name, each parameter's id, type, default, slider
//! range and valid maximum; aep-format.md 3.7). The exporter builds an effect's `parT` and value
//! group from this table (`synth`); After Effects takes the full parameter definitions from the
//! effect itself (read-back e1-zpardfull).
//!
//! The rows were listed from our effect cases (356-397 and the later effect batches) through the
//! reader; `effect_map` names the parameters the importer and exporter convert.
/// The id of the `ADBE Effect Built In Params` entry, the last of every effect.
pub(crate) const BUILT_IN: u16 = u16::MAX;
/// One parameter: its id (the `-NNNN` of its match name, not its position), its type (`pard`
/// code: 0 layer, 1 integer slider, 2 fixed slider, 3 angle, 4 checkbox, 5 colour, 6 point, 7
/// popup, 9 no data, 10 float slider, 11 arbitrary data, 12 path, 13 / 14 group start / end, 15
/// button), its default in stored units, its slider range and its valid maximum.
#[derive(Clone, Copy, Debug)]
pub(crate) struct PDef {
pub id: u16,
pub code: u8,
pub default: &'static [f64],
pub range: Option<(f64, f64)>,
pub valid_max: Option<f64>,
/// The valid minimum of a slider.
pub valid_min: Option<f64>,
/// The display word of a slider: the decimals and the percent switch (fixed and integer
/// `pard@144`, float `pard@124`: aep-format.md 3.7); of a popup, its item count.
pub display: u32,
}
/// One effect.
#[derive(Clone, Copy, Debug)]
pub(crate) struct FxDef {
pub match_name: &'static str,
/// The effect's name (`fnam`).
pub name: &'static str,
pub params: &'static [PDef],
}
impl FxDef {
/// The match name of parameter `p` (`ADBE Tint-0003`).
pub fn record(&self, p: &PDef) -> String {
if p.id == BUILT_IN { "ADBE Effect Built In Params".to_string() } else { format!("{}-{:04}", self.match_name, p.id) }
}
}
const fn p(id: u16, code: u8, default: &'static [f64], range: Option<(f64, f64)>, valid_max: Option<f64>, valid_min: Option<f64>, display: u32) -> PDef {
PDef { id, code, default, range, valid_max, valid_min, display }
}
const fn fx(match_name: &'static str, name: &'static str, params: &'static [PDef]) -> FxDef {
FxDef { match_name, name, params }
}
#[rustfmt::skip]
pub(crate) static FX_DEFS: &[FxDef] = &[
fx("ADBE Tint", "Tint", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 5, &[0.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
p(2, 5, &[0.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
p(3, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(4, 15, &[], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Ramp", "Gradient Ramp", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 6, &[0.5, 0.0], None, None, None, 0x00000000),
p(2, 5, &[255.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
p(3, 6, &[0.5, 1.0], None, None, None, 0x00000000),
p(4, 5, &[255.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
p(5, 7, &[1.0], None, None, None, 0x00000002),
p(6, 2, &[0.0], Some((0.0, 50.0)), Some(512.0), Some(0.0), 0x00010000),
p(7, 2, &[0.0], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
p(8, 15, &[], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Exposure2", "Exposure", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000002),
p(2, 13, &[], None, None, None, 0x00000000),
p(3, 10, &[0.0], Some((-4.0, 4.0)), Some(100.0), Some(-100.0), 0x00020000),
p(4, 10, &[0.0], Some((-0.5, 0.5)), Some(2.0), Some(-2.0), 0x00040000),
p(5, 10, &[1.0], Some((0.10000000149011612, 10.0)), Some(10.0), Some(0.10000000149011612), 0x00020000),
p(6, 14, &[], None, None, None, 0x00000000),
p(7, 13, &[], None, None, None, 0x00000000),
p(8, 10, &[0.0], Some((-4.0, 4.0)), Some(100.0), Some(-100.0), 0x00020000),
p(9, 10, &[0.0], Some((-0.5, 0.5)), Some(2.0), Some(-2.0), 0x00040000),
p(10, 10, &[1.0], Some((0.10000000149011612, 10.0)), Some(10.0), Some(0.10000000149011612), 0x00020000),
p(11, 14, &[], None, None, None, 0x00000000),
p(12, 13, &[], None, None, None, 0x00000000),
p(13, 10, &[0.0], Some((-4.0, 4.0)), Some(100.0), Some(-100.0), 0x00020000),
p(14, 10, &[0.0], Some((-0.5, 0.5)), Some(2.0), Some(-2.0), 0x00040000),
p(15, 10, &[1.0], Some((0.10000000149011612, 10.0)), Some(10.0), Some(0.10000000149011612), 0x00020000),
p(16, 14, &[], None, None, None, 0x00000000),
p(17, 13, &[], None, None, None, 0x00000000),
p(18, 10, &[0.0], Some((-4.0, 4.0)), Some(100.0), Some(-100.0), 0x00020000),
p(19, 10, &[0.0], Some((-0.5, 0.5)), Some(2.0), Some(-2.0), 0x00040000),
p(20, 10, &[1.0], Some((0.10000000149011612, 10.0)), Some(10.0), Some(0.10000000149011612), 0x00020000),
p(21, 14, &[], None, None, None, 0x00000000),
p(22, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Invert", "Invert", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000010),
p(2, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00000001),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Box Blur2", "Fast Box Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((0.0, 127.0)), Some(30000.0), Some(0.0), 0x00010000),
p(2, 1, &[3.0], Some((1.0, 5.0)), Some(50.0), Some(1.0), 0x00000000),
p(3, 7, &[1.0], None, None, None, 0x00000003),
p(4, 4, &[1.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Gaussian Blur 2", "Gaussian Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 10, &[25.0], Some((0.0, 50.0)), Some(30000.0), Some(0.0), 0x00010000),
p(2, 7, &[1.0], None, None, None, 0x00000003),
p(3, 4, &[1.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Drop Shadow", "Drop Shadow", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 5, &[255.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
p(2, 2, &[127.5], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000001),
p(3, 3, &[135.0], None, None, None, 0x00000000),
p(4, 2, &[5.0], Some((0.0, 120.0)), Some(4000.0), Some(0.0), 0x00010000),
p(5, 2, &[0.0], Some((0.0, 250.0)), Some(30000.0), Some(0.0), 0x00010000),
p(6, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Timewarp", "Timewarp", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[3.0], None, None, None, 0x00000003),
p(2, 7, &[1.0], None, None, None, 0x00000002),
p(3, 2, &[50.0], Some((-100.0, 100.0)), Some(5000.0), Some(-5000.0), 0x00020000),
p(4, 2, &[0.0], Some((0.0, 1000.0)), Some(5000.0), Some(-5000.0), 0x00020000),
p(5, 13, &[], None, None, None, 0x00000000),
p(6, 2, &[20.0], Some((5.0, 100.0)), Some(100.0), Some(5.0), 0x00020000),
p(7, 13, &[], None, None, None, 0x00000000),
p(8, 2, &[500.0], Some((-1000.0, 1000.0)), Some(5000.0), Some(-5000.0), 0x00020000),
p(9, 2, &[500.0], Some((-1000.0, 1000.0)), Some(5000.0), Some(-5000.0), 0x00020000),
p(10, 1, &[5.0], Some((1.0, 50.0)), Some(300.0), Some(1.0), 0x00000000),
p(11, 14, &[], None, None, None, 0x00000000),
p(12, 4, &[0.0], None, None, None, 0x00000000),
p(13, 4, &[0.0], None, None, None, 0x00000000),
p(14, 7, &[1.0], None, None, None, 0x00000002),
p(15, 2, &[1.0], Some((0.0, 10.0)), Some(100.0), Some(0.0), 0x00020000),
p(16, 1, &[6.0], Some((4.0, 40.0)), Some(1000.0), Some(4.0), 0x00000000),
p(17, 13, &[], None, None, None, 0x00000000),
p(18, 2, &[29.899993896484375], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
p(19, 2, &[58.69999694824219], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
p(20, 2, &[11.44000244140625], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
p(277, 14, &[], None, None, None, 0x00000000),
p(278, 14, &[], None, None, None, 0x00000000),
p(23, 13, &[], None, None, None, 0x00000000),
p(24, 4, &[0.0], None, None, None, 0x00000000),
p(25, 7, &[2.0], None, None, None, 0x00000002),
p(26, 2, &[180.0], Some((0.0, 360.0)), Some(5000.0), Some(0.0), 0x00020000),
p(27, 1, &[5.0], Some((1.0, 20.0)), Some(1000.0), Some(1.0), 0x00000000),
p(28, 14, &[], None, None, None, 0x00000000),
p(29, 0, &[], None, None, None, 0x00000000),
p(30, 7, &[3.0], None, None, None, 0x00000004),
p(31, 0, &[], None, None, None, 0x00000000),
p(32, 7, &[1.0], None, None, None, 0x00000004),
p(33, 13, &[], None, None, None, 0x00000000),
p(34, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
p(35, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
p(36, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
p(37, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00020000),
p(38, 14, &[], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Glo2", "Glow", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[2.0], None, None, None, 0x00000002),
p(2, 2, &[153.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00010001),
p(3, 2, &[10.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010000),
p(4, 2, &[1.0], Some((0.0, 4.0)), Some(255.0), Some(0.0), 0x00010000),
p(5, 7, &[2.0], None, None, None, 0x00000003),
p(6, 7, &[3.0], None, None, None, 0x00000019),
p(7, 7, &[1.0], None, None, None, 0x00000003),
p(8, 7, &[3.0], None, None, None, 0x00000004),
p(9, 2, &[1.0], Some((1.0, 10.0)), Some(127.0), Some(1.0), 0x00010000),
p(10, 3, &[0.0], None, None, None, 0x00000000),
p(11, 2, &[0.5], Some((0.0099945068359375, 0.9900054931640625)), Some(0.9900054931640625), Some(0.0099945068359375), 0x00000001),
p(12, 5, &[255.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
p(13, 5, &[255.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
p(14, 7, &[1.0], None, None, None, 0x00000003),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Fill", "Fill", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 12, &[], None, None, None, 0x00000000),
p(7, 4, &[0.0], None, None, None, 0x00000000),
p(2, 5, &[255.0, 255.0, 0.0, 0.0], None, None, None, 0x00000000),
p(6, 4, &[0.0], None, None, None, 0x00000000),
p(3, 2, &[0.0], Some((0.0, 50.0)), Some(999.0), Some(0.0), 0x00010000),
p(4, 2, &[0.0], Some((0.0, 50.0)), Some(999.0), Some(0.0), 0x00010000),
p(5, 2, &[1.0], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE HUE SATURATION", "Hue/Saturation", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(2, 7, &[1.0], None, None, None, 0x00000007),
p(3, 11, &[], None, None, None, 0x00000000),
p(4, 3, &[0.0], None, None, None, 0x00000000),
p(5, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00000000),
p(6, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00000000),
p(7, 4, &[0.0], None, None, None, 0x00000000),
p(8, 3, &[0.0], None, None, None, 0x00000000),
p(9, 2, &[25.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00000000),
p(10, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Easy Levels2", "Levels", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000005),
p(2, 11, &[], None, None, None, 0x00000000),
p(3, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(4, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(5, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
p(6, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(7, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(8, 7, &[3.0], None, None, None, 0x00000003),
p(9, 7, &[3.0], None, None, None, 0x00000003),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Motion Blur", "Directional Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 3, &[90.0], None, None, None, 0x00000000),
p(2, 2, &[10.0], Some((0.0, 20.0)), Some(1000.0), Some(0.0), 0x00010000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Radial Blur", "Radial Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(5, 9, &[], None, None, None, 0x00000000),
p(1, 2, &[10.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010000),
p(2, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(3, 7, &[1.0], None, None, None, 0x00000002),
p(4, 7, &[1.0], None, None, None, 0x00000002),
p(6, 1, &[0.0], Some((0.0, 1000.0)), Some(10000.0), Some(0.0), 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("CC Radial Blur", "CC Radial Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[6.0], None, None, None, 0x00000007),
p(2, 2, &[0.0], Some((-100.0, 100.0)), Some(250.0), Some(-250.0), 0x00010000),
p(3, 2, &[50.0], Some((25.0, 100.0)), Some(100.0), Some(10.0), 0x00010000),
p(4, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Venetian Blinds", "Venetian Blinds", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00000001),
p(2, 3, &[0.0], None, None, None, 0x00000000),
p(3, 2, &[20.0], Some((1.0, 127.0)), Some(32000.0), Some(1.0), 0x00000000),
p(4, 2, &[0.0], Some((0.0, 100.0)), Some(32000.0), Some(0.0), 0x00010000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Channel Blur", "Channel Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((0.0, 127.0)), Some(32767.0), Some(0.0), 0x00010000),
p(2, 2, &[0.0], Some((0.0, 127.0)), Some(32767.0), Some(0.0), 0x00010000),
p(3, 2, &[0.0], Some((0.0, 127.0)), Some(32767.0), Some(0.0), 0x00010000),
p(4, 2, &[0.0], Some((0.0, 127.0)), Some(32767.0), Some(0.0), 0x00010000),
p(5, 4, &[1.0], None, None, None, 0x00000000),
p(6, 7, &[1.0], None, None, None, 0x00000003),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Black&White", "Black & White", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 10, &[40.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
p(2, 10, &[60.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
p(3, 10, &[40.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
p(4, 10, &[60.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
p(5, 10, &[20.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
p(6, 10, &[80.0], Some((-200.0, 300.0)), Some(300.0), Some(-200.0), 0x00010000),
p(7, 4, &[0.0], None, None, None, 0x00000000),
p(8, 5, &[255.0, 225.0, 211.0, 179.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Tritone", "Tritone", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 5, &[0.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
p(2, 5, &[0.0, 127.0, 100.0, 70.0], None, None, None, 0x00000000),
p(3, 5, &[0.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
p(4, 10, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Luma Key", "Luma Key", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[2.0], None, None, None, 0x00000004),
p(2, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
p(3, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
p(4, 1, &[0.0], Some((-5.0, 5.0)), Some(5.0), Some(-5.0), 0x00000000),
p(5, 2, &[0.0], Some((0.0, 10.0)), Some(100.0), Some(0.0), 0x00010000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Simple Choker", "Simple Choker", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000002),
p(2, 2, &[0.0], Some((-10.0, 10.0)), Some(100.0), Some(-100.0), 0x00020000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Matte Choker", "Matte Choker", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[4.0], Some((0.0, 10.0)), Some(100.0), Some(0.0), 0x00010000),
p(2, 1, &[75.0], Some((-127.0, 127.0)), Some(127.0), Some(-127.0), 0x00000000),
p(3, 2, &[0.100006103515625], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00000001),
p(4, 2, &[0.0], Some((0.0, 10.0)), Some(100.0), Some(0.0), 0x00020000),
p(5, 1, &[0.0], Some((-127.0, 127.0)), Some(127.0), Some(-127.0), 0x00000000),
p(6, 2, &[1.0], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
p(7, 1, &[1.0], Some((1.0, 10.0)), Some(100.0), Some(1.0), 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Geometry2", "Transform", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(2, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(11, 4, &[1.0], None, None, None, 0x00000000),
p(3, 2, &[100.0], Some((-200.0, 200.0)), Some(30000.0), Some(-30000.0), 0x00010000),
p(4, 2, &[100.0], Some((-200.0, 200.0)), Some(30000.0), Some(-30000.0), 0x00010000),
p(5, 2, &[0.0], Some((-70.0, 70.0)), Some(70.0), Some(-70.0), 0x00010000),
p(6, 3, &[0.0], None, None, None, 0x00000000),
p(7, 3, &[0.0], None, None, None, 0x00000000),
p(8, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010000),
p(9, 4, &[1.0], None, None, None, 0x00000000),
p(10, 2, &[0.0], Some((0.0, 360.0)), Some(360.0), Some(0.0), 0x00020000),
p(12, 7, &[1.0], None, None, None, 0x00000002),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Brightness & Contrast 2", "Brightness & Contrast", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((-150.0, 150.0)), Some(150.0), Some(-150.0), 0x00000000),
p(2, 2, &[0.0], Some((-50.0, 100.0)), Some(100.0), Some(-100.0), 0x00000000),
p(3, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Turbulent Displace", "Turbulent Displace", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x0000000b),
p(2, 2, &[50.0], Some((0.0, 100.0)), Some(10000.0), Some(-10000.0), 0x00010000),
p(3, 2, &[100.0], Some((5.0, 400.0)), Some(1000.0), Some(2.0), 0x00010000),
p(4, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(5, 2, &[1.0], Some((1.0, 5.0)), Some(10.0), Some(1.0), 0x00010000),
p(6, 3, &[0.0], None, None, None, 0x00000000),
p(7, 13, &[], None, None, None, 0x00000000),
p(8, 4, &[0.0], None, None, None, 0x00000000),
p(9, 1, &[1.0], Some((1.0, 30.0)), Some(88.0), Some(1.0), 0x00000000),
p(10, 1, &[0.0], Some((0.0, 1000.0)), Some(100000.0), Some(0.0), 0x00000000),
p(11, 14, &[], None, None, None, 0x00000000),
p(12, 7, &[3.0], None, None, None, 0x00000011),
p(13, 4, &[0.0], None, None, None, 0x00000000),
p(14, 7, &[1.0], None, None, None, 0x00000002),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Fractal Noise", "Fractal Noise", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000014),
p(2, 7, &[3.0], None, None, None, 0x00000004),
p(3, 4, &[0.0], None, None, None, 0x00000000),
p(4, 2, &[100.0], Some((0.0, 400.0)), Some(10000.0), Some(0.0), 0x00010000),
p(5, 2, &[0.0], Some((-100.0, 100.0)), Some(10000.0), Some(-10000.0), 0x00010000),
p(6, 7, &[4.0], None, None, None, 0x00000004),
p(7, 13, &[], None, None, None, 0x00000000),
p(8, 3, &[0.0], None, None, None, 0x00000000),
p(9, 4, &[1.0], None, None, None, 0x00000000),
p(10, 2, &[100.0], Some((20.0, 600.0)), Some(10000.0), Some(1.0), 0x00010000),
p(11, 2, &[100.0], Some((20.0, 600.0)), Some(10000.0), Some(1.0), 0x00010000),
p(12, 2, &[100.0], Some((20.0, 600.0)), Some(10000.0), Some(1.0), 0x00010000),
p(13, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(31, 4, &[0.0], None, None, None, 0x00000000),
p(14, 14, &[], None, None, None, 0x00000000),
p(15, 2, &[6.0], Some((1.0, 10.0)), Some(20.0), Some(1.0), 0x00010000),
p(16, 13, &[], None, None, None, 0x00000000),
p(17, 2, &[70.0], Some((25.0, 100.0)), Some(10000.0), Some(1.52587890625e-05), 0x00010000),
p(18, 2, &[56.0], Some((25.0, 100.0)), Some(10000.0), Some(10.0), 0x00010000),
p(19, 3, &[0.0], None, None, None, 0x00000000),
p(20, 6, &[0.0, 0.0], None, None, None, 0x00000000),
p(21, 4, &[0.0], None, None, None, 0x00000000),
p(22, 14, &[], None, None, None, 0x00000000),
p(23, 3, &[0.0], None, None, None, 0x00000000),
p(24, 13, &[], None, None, None, 0x00000000),
p(25, 4, &[0.0], None, None, None, 0x00000000),
p(26, 1, &[1.0], Some((1.0, 30.0)), Some(88.0), Some(1.0), 0x00000000),
p(27, 1, &[0.0], Some((0.0, 1000.0)), Some(100000.0), Some(0.0), 0x00000000),
p(28, 14, &[], None, None, None, 0x00000000),
p(29, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(30, 7, &[2.0], None, None, None, 0x00000015),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Laser", "Beam", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 6, &[0.100006103515625, 0.5], None, None, None, 0x00000000),
p(2, 6, &[0.899993896484375, 0.5], None, None, None, 0x00000000),
p(3, 2, &[0.25], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
p(4, 2, &[0.5], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
p(5, 2, &[8.0], Some((0.0, 50.0)), Some(4000.0), Some(0.0), 0x00020000),
p(6, 2, &[8.0], Some((0.0, 50.0)), Some(4000.0), Some(0.0), 0x00020000),
p(7, 2, &[0.5], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
p(8, 5, &[185.0, 255.0, 190.0, 250.0], None, None, None, 0x00000000),
p(9, 5, &[150.0, 255.0, 25.0, 25.0], None, None, None, 0x00000000),
p(10, 4, &[1.0], None, None, None, 0x00000000),
p(11, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("CC Radial Fast Blur", "CC Radial Fast Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(2, 2, &[50.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010000),
p(3, 7, &[1.0], None, None, None, 0x00000003),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Noise2", "Noise", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(2, 4, &[1.0], None, None, None, 0x00000000),
p(3, 4, &[1.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Pro Levels2", "Levels (Individual Controls)", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000005),
p(2, 11, &[], None, None, None, 0x00000000),
p(3, 13, &[], None, None, None, 0x00000000),
p(4, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(5, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(6, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
p(7, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(8, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(9, 14, &[], None, None, None, 0x00000000),
p(10, 13, &[], None, None, None, 0x00000000),
p(11, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(12, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(13, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
p(14, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(15, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(16, 14, &[], None, None, None, 0x00000000),
p(17, 13, &[], None, None, None, 0x00000000),
p(18, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(19, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(20, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
p(21, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(22, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(23, 14, &[], None, None, None, 0x00000000),
p(24, 13, &[], None, None, None, 0x00000000),
p(25, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(26, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(27, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
p(28, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(29, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(30, 14, &[], None, None, None, 0x00000000),
p(31, 13, &[], None, None, None, 0x00000000),
p(32, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(33, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(34, 10, &[1.0], Some((0.0, 5.0)), Some(5.0), Some(0.0), 0x00020000),
p(35, 10, &[0.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(36, 10, &[1.0], Some((0.0, 1.0)), Some(10000.0), Some(-10000.0), 0x00010002),
p(37, 14, &[], None, None, None, 0x00000000),
p(38, 7, &[3.0], None, None, None, 0x00000003),
p(39, 7, &[3.0], None, None, None, 0x00000003),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Corner Pin", "Corner Pin", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 6, &[0.0, 0.0], None, None, None, 0x00000000),
p(2, 6, &[1.0, 0.0], None, None, None, 0x00000000),
p(3, 6, &[0.0, 1.0], None, None, None, 0x00000000),
p(4, 6, &[1.0, 1.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Grid", "Grid", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(2, 7, &[1.0], None, None, None, 0x00000003),
p(3, 6, &[0.600006103515625, 0.600006103515625], None, None, None, 0x00000000),
p(4, 2, &[32.0], Some((4.0, 200.0)), Some(4000.0), Some(1.0), 0x00010000),
p(5, 2, &[24.0], Some((4.0, 200.0)), Some(4000.0), Some(1.0), 0x00010000),
p(6, 2, &[5.0], Some((0.0, 100.0)), Some(2000.0), Some(0.0), 0x00010000),
p(7, 13, &[], None, None, None, 0x00000000),
p(8, 2, &[0.0], Some((0.0, 20.0)), Some(400.0), Some(0.0), 0x00010000),
p(9, 2, &[0.0], Some((0.0, 20.0)), Some(400.0), Some(0.0), 0x00010000),
p(10, 14, &[], None, None, None, 0x00000000),
p(11, 4, &[0.0], None, None, None, 0x00000000),
p(12, 5, &[255.0, 255.0, 255.0, 255.0], None, None, None, 0x00000000),
p(13, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(14, 7, &[1.0], None, None, None, 0x00000017),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Sharpen", "Sharpen", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 1, &[0.0], Some((0.0, 100.0)), Some(4000.0), Some(0.0), 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Linear Color Key2", "Linear Color Key", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 9, &[], None, None, None, 0x00000000),
p(2, 7, &[1.0], None, None, None, 0x00000003),
p(3, 5, &[255.0, 0.0, 0.0, 255.0], None, None, None, 0x00000000),
p(4, 7, &[1.0], None, None, None, 0x00000003),
p(5, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(6, 2, &[10.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(7, 7, &[1.0], None, None, None, 0x00000002),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Radial Wipe", "Radial Wipe", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00000001),
p(2, 3, &[0.0], None, None, None, 0x00000000),
p(3, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(4, 7, &[1.0], None, None, None, 0x00000003),
p(5, 2, &[0.0], Some((0.0, 100.0)), Some(32000.0), Some(0.0), 0x00010000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Remove Color Matting", "Remove Color Matting", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 5, &[0.0, 0.0, 0.0, 0.0], None, None, None, 0x00000000),
p(2, 4, &[1.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("CC Bend It", "CC Bend It", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((-100.0, 100.0)), Some(250.0), Some(-250.0), 0x00010000),
p(2, 6, &[0.5, 0.75], None, None, None, 0x00000000),
p(3, 6, &[0.5, 0.25], None, None, None, 0x00000000),
p(4, 7, &[3.0], None, None, None, 0x00000004),
p(5, 7, &[1.0], None, None, None, 0x00000002),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("CC Power Pin", "CC Power Pin", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(2, 6, &[0.0, 0.0], None, None, None, 0x00000000),
p(3, 6, &[1.0, 0.0], None, None, None, 0x00000000),
p(4, 6, &[0.0, 1.0], None, None, None, 0x00000000),
p(5, 6, &[1.0, 1.0], None, None, None, 0x00000000),
p(6, 2, &[1.0], Some((0.0, 1.0)), Some(1.0), Some(0.0), 0x00010001),
p(7, 4, &[0.0], None, None, None, 0x00000000),
p(8, 13, &[], None, None, None, 0x00000000),
p(9, 2, &[0.0], Some((0.0, 50.0)), Some(200.0), Some(-200.0), 0x00010000),
p(10, 2, &[0.0], Some((0.0, 50.0)), Some(200.0), Some(-200.0), 0x00010000),
p(11, 2, &[0.0], Some((0.0, 50.0)), Some(200.0), Some(-200.0), 0x00010000),
p(12, 2, &[0.0], Some((0.0, 50.0)), Some(200.0), Some(-200.0), 0x00010000),
p(13, 14, &[], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE 4ColorGradient", "4-Color Gradient", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(11, 13, &[], None, None, None, 0x00000000),
p(1, 6, &[0.100006103515625, 0.100006103515625], None, None, None, 0x00000000),
p(2, 5, &[255.0, 255.0, 255.0, 0.0], None, None, None, 0x00000000),
p(3, 6, &[0.899993896484375, 0.100006103515625], None, None, None, 0x00000000),
p(4, 5, &[255.0, 0.0, 255.0, 0.0], None, None, None, 0x00000000),
p(5, 6, &[0.100006103515625, 0.899993896484375], None, None, None, 0x00000000),
p(6, 5, &[255.0, 255.0, 0.0, 255.0], None, None, None, 0x00000000),
p(7, 6, &[0.899993896484375, 0.899993896484375], None, None, None, 0x00000000),
p(8, 5, &[255.0, 0.0, 0.0, 255.0], None, None, None, 0x00000000),
p(12, 14, &[], None, None, None, 0x00000000),
p(9, 2, &[100.0], Some((10.0, 500.0)), Some(10000.0), Some(5.0), 0x00010000),
p(10, 2, &[0.0], Some((0.0, 100.0)), Some(500.0), Some(0.0), 0x00010001),
p(13, 2, &[100.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(14, 7, &[1.0], None, None, None, 0x00000016),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Change Color", "Change Color", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000002),
p(2, 2, &[0.0], Some((-180.0, 180.0)), Some(1800.0), Some(-1800.0), 0x00010000),
p(3, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00010000),
p(4, 2, &[0.0], Some((-100.0, 100.0)), Some(100.0), Some(-100.0), 0x00010000),
p(5, 5, &[255.0, 0.0, 0.0, 255.0], None, None, None, 0x00000000),
p(6, 2, &[15.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(7, 2, &[0.0], Some((0.0, 100.0)), Some(100.0), Some(0.0), 0x00010001),
p(8, 7, &[1.0], None, None, None, 0x00000003),
p(9, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Extract", "Extract", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 9, &[], None, None, None, 0x00000000),
p(2, 7, &[1.0], None, None, None, 0x00000005),
p(3, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
p(4, 1, &[255.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
p(5, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
p(6, 1, &[0.0], Some((0.0, 255.0)), Some(255.0), Some(0.0), 0x00000000),
p(7, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Noise HLS2", "Noise HLS", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000003),
p(2, 10, &[0.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010001),
p(3, 10, &[0.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010001),
p(4, 10, &[0.0], Some((0.0, 100.0)), Some(1000.0), Some(0.0), 0x00010001),
p(5, 2, &[1.0], Some((0.0, 4.0)), Some(10.0), Some(0.0), 0x00020000),
p(6, 3, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Scatter", "Scatter", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((0.0, 127.0)), Some(1000.0), Some(0.0), 0x00010000),
p(2, 7, &[1.0], None, None, None, 0x00000003),
p(3, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("CC Light Sweep", "CC Light Sweep", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 6, &[0.5, 0.25], None, None, None, 0x00000000),
p(2, 3, &[-30.0], None, None, None, 0x00000000),
p(3, 7, &[3.0], None, None, None, 0x00000003),
p(4, 2, &[50.0], Some((0.0, 200.0)), Some(4000.0), Some(0.0), 0x00010000),
p(5, 2, &[25.0], Some((0.0, 100.0)), Some(500.0), Some(0.0), 0x00010000),
p(6, 2, &[50.0], Some((0.0, 100.0)), Some(500.0), Some(0.0), 0x00010000),
p(7, 2, &[4.0], Some((0.0, 10.0)), Some(20.0), Some(0.0), 0x00020000),
p(8, 5, &[255.0, 255.0, 250.0, 240.0], None, None, None, 0x00000000),
p(9, 7, &[1.0], None, None, None, 0x00000003),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Compound Blur", "Compound Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 0, &[], None, None, None, 0x00000000),
p(2, 2, &[20.0], Some((0.0, 100.0)), Some(4000.0), Some(0.0), 0x00010000),
p(3, 4, &[1.0], None, None, None, 0x00000000),
p(4, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Displacement Map", "Displacement Map", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 0, &[], None, None, None, 0x00000000),
p(2, 7, &[1.0], None, None, None, 0x0000000b),
p(3, 2, &[5.0], Some((-100.0, 100.0)), Some(32000.0), Some(-32000.0), 0x00010000),
p(4, 7, &[2.0], None, None, None, 0x0000000b),
p(5, 2, &[5.0], Some((-100.0, 100.0)), Some(32000.0), Some(-32000.0), 0x00010000),
p(6, 7, &[1.0], None, None, None, 0x00000003),
p(7, 4, &[0.0], None, None, None, 0x00000000),
p(8, 4, &[1.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Set Matte3", "Set Matte", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 0, &[], None, None, None, 0x00000000),
p(2, 7, &[4.0], None, None, None, 0x0000000a),
p(3, 4, &[0.0], None, None, None, 0x00000000),
p(4, 4, &[1.0], None, None, None, 0x00000000),
p(5, 4, &[1.0], None, None, None, 0x00000000),
p(6, 4, &[1.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Gaussian Blur", "Gaussian Blur (Legacy)", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 2, &[0.0], Some((0.0, 50.0)), Some(30000.0), Some(0.0), 0x00010000),
p(2, 7, &[1.0], None, None, None, 0x00000003),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE OFMotionBlur", "Pixel Motion Blur", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 7, &[1.0], None, None, None, 0x00000002),
p(2, 10, &[180.0], Some((0.0, 360.0)), Some(5000.0), Some(0.0), 0x00020000),
p(3, 1, &[5.0], Some((1.0, 20.0)), Some(256.0), Some(1.0), 0x00000000),
p(4, 10, &[20.0], Some((5.0, 100.0)), Some(100.0), Some(5.0), 0x00010000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Layer Control", "Layer Control", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 0, &[], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Slider Control", "Slider Control", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 10, &[0.0], Some((0.0, 100.0)), Some(1000000.0), Some(-1000000.0), 0x00020000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Angle Control", "Angle Control", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 3, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Checkbox Control", "Checkbox Control", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 4, &[0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Color Control", "Color Control", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 5, &[255.0, 255.0, 0.0, 0.0], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE Point Control", "Point Control", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 6, &[0.5, 0.5], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE CurvesCustom", "Curves", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(2, 7, &[1.0], None, None, None, 0x00000005),
p(1, 11, &[], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
fx("ADBE MESH WARP", "Mesh Warp", &[
p(0, 0, &[], None, None, None, 0x00000000),
p(1, 1, &[7.0], Some((1.0, 31.0)), Some(31.0), Some(1.0), 0x00000000),
p(2, 1, &[7.0], Some((1.0, 31.0)), Some(31.0), Some(1.0), 0x00000000),
p(5, 1, &[8.0], Some((1.0, 10.0)), Some(10.0), Some(1.0), 0x00000000),
p(4, 11, &[], None, None, None, 0x00000000),
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
]),
];
+270
View File
@@ -0,0 +1,270 @@
//! Effect instances built in code from the effect table (`fx_defs`): the default `sspc` of every
//! effect type the exporter writes, its project copy (`EfDf`) and the value records of each
//! parameter type (aep-format.md 3.7).
//!
//! What After Effects needs (read-backs in `docs/aep-export.md`, "Built in code"): a `parT` entry
//! per parameter (`tdmn` + a 148-byte `pard`) whose bytes may be zero, since After Effects takes
//! the definitions from the effect itself (e1-zpardfull); no `sdat` (e2-nosdat). The `pard` fields
//! the importer reads back (type, default, valid maximum, slider range, popup item count) are
//! written from the table so that an exported file imports again.
use crate::Chunk;
use crate::effect_map::{Conv, by_match_name};
use crate::export::fx_defs::{BUILT_IN, FxDef, PDef};
use crate::export::synth::{KeyTemplate, NO_NAME, RecSpec, class, tdmn, tdsn};
use crate::{CURVE_IDENTITY, CurvesData, MeshData};
/// The layer a prototype's layer parameters name when their default is the owning layer; the
/// exporter replaces it with the owning layer's id (`effects::instance`).
pub(crate) const PROTO_OWNER: u32 = 1;
/// Layer parameters whose default is None instead of the owning layer (Timewarp's Matte Layer and
/// Warp Layer, 529).
const LAYER_NONE: &[&str] = &["ADBE Timewarp-0029", "ADBE Timewarp-0031"];
/// The record of a parameter type (`pard` code): its components, key template and class word.
pub(crate) fn value_spec(code: u8, range: Option<(f64, f64)>) -> Option<RecSpec> {
let scalar = |class| RecSpec { dims: 1, template: KeyTemplate::Plain, class, limits: None, byte5: None };
Some(match code {
// Sliders carry their range as `tdum` / `tduM`.
1 | 2 | 10 => RecSpec { limits: Some(range.unwrap_or((0.0, 0.0))), ..scalar(class::EFFECT_NUMBER) },
3 => scalar(class::EFFECT_NUMBER),
4 | 7 => scalar(class::EFFECT_CHOICE),
5 => RecSpec { dims: 4, template: KeyTemplate::Spatial(1), class: class::COLOR, limits: None, byte5: None },
6 => RecSpec { dims: 2, template: KeyTemplate::Spatial(3), class: class::SPATIAL, limits: None, byte5: None },
0 | 13 | 14 | 15 => scalar(class::EFFECT_OTHER),
_ => return None,
})
}
fn 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()
}
/// The 148-byte `pard` of a parameter: the type at 12, the default at 56 and the copies After
/// Effects reads it from (s8-e1..s12-e2), a popup's item count at 60, the valid range, slider
/// range and display word of a slider (float: `f32` at 104 / 108 / 112 / 116, default 120,
/// display 124; fixed and integer: 124 / 128 / 132 / 136, default 140, display 144). Every other
/// byte is zero (the switches at 48 are not needed: s12-e2-nofl).
pub(crate) fn pard(p: &PDef, popup_items: Option<u16>) -> Vec<u8> {
let mut b = vec![0u8; 148];
put(&mut b, 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());
// 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());
}
2 => put(&mut b, 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)));
}
1 => put(&mut b, 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)]);
}
// 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());
}
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));
}
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);
}
_ => {}
}
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());
}
match p.code {
10 => {
if let Some(m) = p.valid_min {
put(&mut b, 104, &(m as f32).to_be_bytes());
}
if let Some(m) = p.valid_max {
put(&mut b, 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());
}
}
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));
}
if let Some(m) = p.valid_max {
put(&mut b, 128, &enc(m));
}
if let Some((lo, hi)) = p.range {
put(&mut b, 132, &enc(lo));
put(&mut b, 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
}
/// The default arbitrary data of an effect (its type-11 parameter), from the decoded layouts
/// (aep-format.md 3.7).
pub(crate) fn default_data(match_name: &str) -> Option<Vec<u8>> {
match match_name {
// Master hue, saturation, lightness (0), then six colour ranges of four hue bounds and
// their hue, saturation and lightness (0): Reds centred at 0 degrees, then every 60, each
// range 30 degrees wide with 30 degree fall-off (443-446).
"ADBE HUE SATURATION" => {
let mut out = vec![0u8; 12];
for c in 0..6i32 {
let centre = 60 * c;
for off in [-45, -15, 15, 45] {
out.extend((centre + off).rem_euclid(360).to_be_bytes());
}
out.extend([0u8; 12]);
}
Some(out)
}
// A header word `0x000f10a7` and the version 1, then five channels (RGB, red, green, blue,
// alpha) of input black, input white, gamma, output black, output white as `f32`
// (511-516).
"ADBE Easy Levels2" | "ADBE Pro Levels2" => {
let mut out = Vec::with_capacity(108);
out.extend(0x000f_10a7_u32.to_be_bytes());
out.extend(1u32.to_be_bytes());
for _ in 0..5 {
for v in [0.0f32, 1.0, 1.0, 0.0, 1.0] {
out.extend(v.to_be_bytes());
}
}
Some(out)
}
"ADBE CurvesCustom" => CurvesData { curves: std::array::from_fn(|_| CURVE_IDENTITY.to_vec()) }.to_bytes(),
// 7 x 7 cells, undistorted (Rows / Columns default 7, 985).
"ADBE MESH WARP" => {
let (columns, rows) = (7, 7);
let vertices = (0..=rows).flat_map(|j| (0..=columns).map(move |i| MeshData::default_vertex(columns, rows, i, j))).collect();
MeshData { columns, rows, tail: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x0d, 0x0d], vertices }.to_bytes()
}
_ => None,
}
}
/// The popup item count of parameter position `index` from the shared effect table.
fn popup_items(fx: &FxDef, index: usize) -> Option<u16> {
let map = by_match_name(fx.match_name)?;
let pm = map.params.iter().find(|p| p.index == index)?;
match pm.conv {
Conv::Popup { items, .. } => u16::try_from(items.len()).ok(),
_ => None,
}
}
/// A record without a value of its own (layer parameters, groups, buttons): `tdsb` `state`, no
/// user name, the header and a zero `cdat`.
fn plain_record(state: u32, extra: Vec<Chunk<'static>>) -> Chunk<'static> {
let spec = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_OTHER, limits: None, byte5: None };
let mut kids = vec![
Chunk::data(*b"tdsb", state.to_be_bytes().to_vec()),
tdsn(NO_NAME),
Chunk::data(*b"tdb4", crate::export::synth::tdb4(&spec, false, 25_600)),
Chunk::data(*b"cdat", vec![0u8; spec.cdat_len()]),
];
kids.extend(extra);
Chunk::list(*b"tdbs", kids)
}
/// The arbitrary-data record (4-byte `cdat`, class `0x00060007`, colour-like template 1) and the
/// `LIST aRbs` with the data after it (443, 961).
fn data_record(data: Vec<u8>) -> [Chunk<'static>; 2] {
let spec = RecSpec { dims: 1, template: KeyTemplate::Spatial(1), class: class::ARBITRARY, limits: None, byte5: None };
let rec = Chunk::list(
*b"tdbs",
vec![
Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()),
tdsn(NO_NAME),
Chunk::data(*b"tdb4", crate::export::synth::tdb4(&spec, false, 25_600)),
Chunk::data(*b"cdat", vec![0u8; 4]),
],
);
[rec, Chunk::list(*b"aRbs", vec![Chunk::data(*b"aRbp", data)])]
}
/// The default `sspc` of an effect: its name (`fnam`), the parameter list (`parT`: the count,
/// then `tdmn` + `pard` per parameter, the default arbitrary data after its `pard`), the value
/// group (records only for layer parameters, groups, buttons and arbitrary data, the built-in
/// group) and `pgui` (zero).
pub(crate) fn default_sspc(fx: &FxDef) -> Chunk<'static> {
let fnam = Chunk { id: *b"fnam", body: crate::Body::Chunks(vec![Chunk::data(*b"Utf8", fx.name.as_bytes().to_vec())]), pad: None };
let count = u32::try_from(fx.params.len()).unwrap_or(u32::MAX);
let mut part = vec![Chunk::data(*b"parn", count.to_be_bytes().to_vec())];
let mut values = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(NO_NAME)];
for (i, p) in fx.params.iter().enumerate() {
let record = fx.record(p);
part.push(tdmn(&record));
part.push(Chunk::data(*b"pard", pard(p, popup_items(fx, i))));
if matches!(p.code, 4 | 7 | 15) {
// Checkboxes, popups and buttons have a `pdnm` (their label or items); its text may
// be empty.
part.push(Chunk { id: *b"pdnm", body: crate::Body::Chunks(vec![Chunk::data(*b"Utf8", Vec::new())]), pad: None });
}
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")]));
continue;
}
match p.code {
0 => {
let id = if LAYER_NONE.contains(&record.as_str()) { 0 } else { PROTO_OWNER };
// The input layer (position 0) and every layer parameter name a layer (`tdpi`);
// `tdps` 0 (320, 529).
let state = if i == 0 { 3 } else { 1 };
values.push(tdmn(&record));
values.push(plain_record(state, vec![Chunk::data(*b"tdpi", id.to_be_bytes().to_vec()), Chunk::data(*b"tdps", 0u32.to_be_bytes().to_vec())]));
}
9 | 13..=15 => {
values.push(tdmn(&record));
values.push(plain_record(1, Vec::new()));
}
11 => {
if let Some(data) = default_data(fx.match_name) {
part.push(Chunk::data(*b"aRbp", data.clone()));
values.push(tdmn(&record));
values.extend(data_record(data));
}
}
_ => {}
}
}
values.push(tdmn("ADBE 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])])
}
+289
View File
@@ -0,0 +1,289 @@
//! Colour profiles for the working spaces the exporter writes, authored here from the standards
//! so that no profile of another party is copied: "Rec.709 Gamma 2.4" (ITU-R BT.709 primaries,
//! a pure 2.4 power curve) and "sRGB IEC61966-2.1" (the same primaries, the IEC 61966-2-1
//! curve), both D65, ICC.1:2010 v4 with a D50 PCS and a Bradford adaptation. After Effects keeps
//! a working space as the profile's data (base64) and its profile ID (`cpid`, 624: the MD5
//! profile ID of the v4 header), R49.
/// The profile's description and the name After Effects lists the working space under (624).
pub(crate) const REC709_NAME: &str = "Rec.709 Gamma 2.4";
/// The name After Effects lists the sRGB working space under (620).
pub(crate) const SRGB_NAME: &str = "sRGB IEC61966-2.1";
fn s15(v: f64) -> [u8; 4] {
let x = (v * 65536.0).round();
let x = if x.is_finite() { x.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) } else { 0.0 };
(x as i32).to_be_bytes()
}
type M3 = [[f64; 3]; 3];
fn mul(a: &M3, b: &M3) -> M3 {
let mut o = [[0.0; 3]; 3];
for (i, row) in o.iter_mut().enumerate() {
for (j, v) in row.iter_mut().enumerate() {
*v = (0..3).map(|k| a[i][k] * b[k][j]).sum();
}
}
o
}
fn mulv(a: &M3, v: [f64; 3]) -> [f64; 3] {
[0, 1, 2].map(|i| (0..3).map(|k| a[i][k] * v[k]).sum())
}
fn inv(m: &M3) -> M3 {
let [[a, b, c], [d, e, f], [g, h, i]] = *m;
let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
let det = if det.abs() < 1e-12 { 1.0 } else { det };
[
[(e * i - f * h) / det, (c * h - b * i) / det, (b * f - c * e) / det],
[(f * g - d * i) / det, (a * i - c * g) / det, (c * d - a * f) / det],
[(d * h - e * g) / det, (b * g - a * h) / det, (a * e - b * d) / det],
]
}
fn xyz(x: f64, y: f64) -> [f64; 3] {
[x / y, 1.0, (1.0 - x - y) / y]
}
fn mluc(text: &str) -> Vec<u8> {
let t: Vec<u8> = text.encode_utf16().flat_map(u16::to_be_bytes).collect();
let mut v = b"mluc\0\0\0\0".to_vec();
v.extend(1u32.to_be_bytes());
v.extend(12u32.to_be_bytes());
v.extend(b"enUS");
v.extend(u32::try_from(t.len()).unwrap_or(0).to_be_bytes());
v.extend(28u32.to_be_bytes());
v.extend(t);
v
}
fn xyz_tag(v: [f64; 3]) -> Vec<u8> {
let mut o = b"XYZ \0\0\0\0".to_vec();
for c in v {
o.extend(s15(c));
}
o
}
/// The Rec.709 Gamma 2.4 display profile (ICC v4.3) with its profile ID filled in.
pub(crate) fn rec709_gamma24() -> Vec<u8> {
// A pure power curve: `para` function type 0.
let mut trc = b"para\0\0\0\0".to_vec();
trc.extend([0, 0, 0, 0]);
trc.extend(s15(2.4));
profile("Rec.709 Gamma 2.4 (EffectCraft)", trc)
}
/// The sRGB display profile (ICC v4.3): IEC 61966-2-1's curve as `para` function type 3, `Y =
/// ((X + 0.055) / 1.055) ^ 2.4` from 0.04045 and `X / 12.92` below.
pub(crate) fn srgb() -> Vec<u8> {
let mut trc = b"para\0\0\0\0".to_vec();
trc.extend([0, 3, 0, 0]);
for v in [2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045] {
trc.extend(s15(v));
}
profile(SRGB_NAME, trc)
}
/// A display profile with BT.709 primaries and D65 white, tone curve `trc` and description
/// `desc`, its profile ID filled in.
fn profile(desc: &str, trc: Vec<u8>) -> Vec<u8> {
let prim = [(0.640, 0.330), (0.300, 0.600), (0.150, 0.060)];
let w65 = xyz(0.3127, 0.3290);
let w50 = [0.9642, 1.0, 0.8249];
let cols = prim.map(|(x, y)| xyz(x, y));
let p: M3 = [0, 1, 2].map(|r| [0, 1, 2].map(|c| cols[c][r]));
let s = mulv(&inv(&p), w65);
let m: M3 = [0, 1, 2].map(|r| [0, 1, 2].map(|c| p[r][c] * s[c]));
let brad: M3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]];
let (cs, cd) = (mulv(&brad, w65), mulv(&brad, w50));
let d: M3 = [[cd[0] / cs[0], 0.0, 0.0], [0.0, cd[1] / cs[1], 0.0], [0.0, 0.0, cd[2] / cs[2]]];
let chad = mul(&inv(&brad), &mul(&d, &brad));
let m50 = mul(&chad, &m);
let mut sf32 = b"sf32\0\0\0\0".to_vec();
for row in chad {
for v in row {
sf32.extend(s15(v));
}
}
let tags: [(&[u8; 4], Vec<u8>); 10] = [
(b"desc", mluc(desc)),
(b"cprt", mluc("No copyright, use freely (EffectCraft)")),
(b"wtpt", xyz_tag(w50)),
(b"chad", sf32),
(b"rXYZ", xyz_tag([m50[0][0], m50[1][0], m50[2][0]])),
(b"gXYZ", xyz_tag([m50[0][1], m50[1][1], m50[2][1]])),
(b"bXYZ", xyz_tag([m50[0][2], m50[1][2], m50[2][2]])),
(b"rTRC", trc.clone()),
(b"gTRC", trc.clone()),
(b"bTRC", trc),
];
let start = 128 + 4 + 12 * tags.len();
let mut table = Vec::new();
let mut body: Vec<u8> = Vec::new();
let mut placed: Vec<(Vec<u8>, usize)> = Vec::new();
for (sig, data) in &tags {
let off = match placed.iter().find(|(d, _)| d == data) {
Some((_, off)) => *off,
None => {
let off = start + body.len();
body.extend(data);
body.resize(body.len().div_ceil(4) * 4, 0);
placed.push((data.clone(), off));
off
}
};
table.extend(*sig);
table.extend(u32::try_from(off).unwrap_or(0).to_be_bytes());
table.extend(u32::try_from(data.len()).unwrap_or(0).to_be_bytes());
}
let size = start + body.len();
let mut icc = vec![0u8; 128];
icc[0..4].copy_from_slice(&u32::try_from(size).unwrap_or(0).to_be_bytes());
icc[8..12].copy_from_slice(&[4, 0x30, 0, 0]);
icc[12..16].copy_from_slice(b"mntr");
icc[16..20].copy_from_slice(b"RGB ");
icc[20..24].copy_from_slice(b"XYZ ");
for (i, v) in [2026u16, 10, 19, 0, 0, 0].iter().enumerate() {
icc[24 + 2 * i..26 + 2 * i].copy_from_slice(&v.to_be_bytes());
}
icc[36..40].copy_from_slice(b"acsp");
for (i, c) in w50.iter().enumerate() {
icc[68 + 4 * i..72 + 4 * i].copy_from_slice(&s15(*c));
}
icc.extend(u32::try_from(tags.len()).unwrap_or(0).to_be_bytes());
icc.extend(table);
icc.extend(body);
// Profile ID (ICC.1:2010 7.2.18): the MD5 with flags, rendering intent and the ID zeroed (all
// zero here already).
let id = md5(&icc);
icc[84..100].copy_from_slice(&id);
icc
}
/// The profile ID of a v4 profile (header bytes 84..100).
pub(crate) fn profile_id(icc: &[u8]) -> [u8; 16] {
let mut id = [0u8; 16];
if let Some(src) = icc.get(84..100) {
id.copy_from_slice(src);
}
id
}
/// MD5 (RFC 1321).
pub(crate) fn md5(data: &[u8]) -> [u8; 16] {
const S: [u32; 64] = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4,
11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
];
let k: [u32; 64] = std::array::from_fn(|i| ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32);
let mut msg = data.to_vec();
let bits = (data.len() as u64).wrapping_mul(8);
msg.push(0x80);
while msg.len() % 64 != 56 {
msg.push(0);
}
msg.extend(bits.to_le_bytes());
let (mut a0, mut b0, mut c0, mut d0) = (0x6745_2301u32, 0xefcd_ab89u32, 0x98ba_dcfeu32, 0x1032_5476u32);
let (blocks, _) = msg.as_chunks::<64>();
for chunk in blocks {
let m: [u32; 16] = std::array::from_fn(|i| u32::from_le_bytes([chunk[4 * i], chunk[4 * i + 1], chunk[4 * i + 2], chunk[4 * i + 3]]));
let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
for i in 0..64 {
let (f, g) = match i / 16 {
0 => ((b & c) | (!b & d), i),
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
2 => (b ^ c ^ d, (3 * i + 5) % 16),
_ => (c ^ (b | !d), (7 * i) % 16),
};
let f = f.wrapping_add(a).wrapping_add(k[i]).wrapping_add(m[g]);
a = d;
d = c;
c = b;
b = b.wrapping_add(f.rotate_left(S[i]));
}
a0 = a0.wrapping_add(a);
b0 = b0.wrapping_add(b);
c0 = c0.wrapping_add(c);
d0 = d0.wrapping_add(d);
}
let mut out = [0u8; 16];
for (i, w) in [a0, b0, c0, d0].iter().enumerate() {
out[4 * i..4 * i + 4].copy_from_slice(&w.to_le_bytes());
}
out
}
/// The colour profile JSON After Effects stores for a working space or a footage item (620, 624):
/// the profile's data and its name.
pub(crate) fn profile_json(icc: &[u8], name: &str) -> String {
format!("{{\"baseColorProfile\":{{\"colorProfileData\":\"{}\",\"colorProfileName\":\"{}\"}},\"baseProfileType\":2}}", base64(icc), name)
}
/// Standard base64 with padding.
pub(crate) fn base64(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for c in data.chunks(3) {
let n = (u32::from(c[0]) << 16) | (u32::from(c.get(1).copied().unwrap_or(0)) << 8) | u32::from(c.get(2).copied().unwrap_or(0));
for (i, shift) in [18u32, 12, 6, 0].iter().enumerate() {
if i <= c.len() {
out.push(char::from(T[((n >> shift) & 63) as usize]));
} else {
out.push('=');
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn md5_and_base64_match_their_specifications() {
// RFC 1321 test suite and RFC 4648.
assert_eq!(md5(b"").iter().map(|b| format!("{b:02x}")).collect::<String>(), "d41d8cd98f00b204e9800998ecf8427e");
assert_eq!(md5(b"abc").iter().map(|b| format!("{b:02x}")).collect::<String>(), "900150983cd24fb0d6963f7d28e17f72");
let long = b"12345678901234567890123456789012345678901234567890123456789012345678901234567890";
assert_eq!(md5(long).iter().map(|b| format!("{b:02x}")).collect::<String>(), "57edf4a22be3c955ac49da2e2107b67a");
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
assert_eq!(base64(b"fooba"), "Zm9vYmE=");
assert_eq!(base64(b"foob"), "Zm9vYg==");
}
#[test]
fn the_srgb_profile_carries_the_iec_curve() {
let icc = srgb();
assert_eq!(u32::from_be_bytes(icc[0..4].try_into().unwrap()) as usize, icc.len());
let mut z = icc.clone();
z[84..100].fill(0);
assert_eq!(profile_id(&icc), md5(&z));
let at = icc.windows(8).position(|w| w == b"para\0\0\0\0").unwrap();
assert_eq!(&icc[at + 8..at + 12], &[0, 3, 0, 0]);
// AE shows its own name for the space only when the description is exactly this.
let name: Vec<u8> = SRGB_NAME.encode_utf16().flat_map(u16::to_be_bytes).collect();
let at = icc.windows(name.len()).position(|w| w == name.as_slice()).unwrap();
assert_ne!(&icc[at + name.len()..at + name.len() + 2], b"\0 ", "no suffix after the name");
}
#[test]
fn the_rec709_profile_is_a_valid_v4_display_profile() {
let icc = rec709_gamma24();
assert_eq!(u32::from_be_bytes(icc[0..4].try_into().unwrap()) as usize, icc.len());
assert_eq!(&icc[36..40], b"acsp");
// The ID is the MD5 of the profile with the ID zeroed.
let mut z = icc.clone();
z[84..100].fill(0);
assert_eq!(profile_id(&icc), md5(&z));
// D50 red primary of BT.709 (0.4361, 0.2225, 0.0139).
let tags = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize;
let r = (0..tags).find(|t| &icc[132 + 12 * t..136 + 12 * t] == b"rXYZ").unwrap();
let off = u32::from_be_bytes(icc[136 + 12 * r..140 + 12 * r].try_into().unwrap()) as usize;
let x = f64::from(i32::from_be_bytes(icc[off + 8..off + 12].try_into().unwrap())) / 65536.0;
assert!((x - 0.4361).abs() < 2e-4, "{x}");
}
}
+126
View File
@@ -0,0 +1,126 @@
//! Layer and composition markers (`docs/aep-format.md` 3.11; cases 122, 123, 249, 347-349, 509,
//! 510). A marker group is `tdmn ADBE Marker` + `LIST mrst`: a `tdbs` whose key list holds one
//! 16-byte record per marker (the time in the owner's time units, bytes 4 and 5 = 3, the rest
//! written 0: After Effects leaves session bytes there) and a `LIST mrky` with one `LIST Nmrd` per
//! marker (`NmHd`: cue type, number of cue parameters, duration in 1/600 s, 600, label; then the
//! comment, chapter, URL, frame target and cue point name and the parameter pairs as `Utf8`).
use crate::Chunk;
use effectcraft_project::Marker;
use crate::export::report::{Collector, LossCategory};
use crate::export::timebase::TimeBase;
use crate::export::tree::{R, child_data, kids_mut, list_mut, put, put_u8, put_u32, tpl};
/// The units per second of a marker duration (`NmHd` @12, 249).
const DURATION_UNITS: f64 = 600.0;
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct MarkerPlan {
pub time: i32,
pub duration: u32,
pub label: u8,
/// 4 event cue (also without a cue point), 5 navigation cue (347, 348).
pub cue: u32,
/// Comment, chapter, URL, frame target, cue point name (249).
pub strings: [String; 5],
pub params: Vec<(String, String)>,
}
/// The markers in the file's units (`tb` is the owner's time base: the composition's, or the
/// layer's for layer markers); what cannot be written is reported.
pub(crate) fn plan(markers: &[Marker], tb: &TimeBase, what: &str, col: &mut Collector) -> Vec<MarkerPlan> {
let mut out: Vec<MarkerPlan> = Vec::with_capacity(markers.len());
for m in markers {
let (u, inexact) = tb.units(m.time);
let Ok(time) = i32::try_from(u) else {
col.lose(LossCategory::Markers, format!("{what}: a marker time out of range is not written"));
continue;
};
if inexact {
col.lose(LossCategory::RoundedTimes, format!("{what}: marker at {:.4} s moved to the time base", m.time.seconds()));
}
let d = m.duration.seconds() * DURATION_UNITS;
let duration = if d.is_finite() && d > 0.0 { d.round().min(f64::from(u32::MAX)) as u32 } else { 0 };
if d.is_finite() && d > 0.0 && (d - d.round()).abs() > 1e-6 {
col.lose(LossCategory::RoundedTimes, format!("{what}: a marker duration is rounded to 1/600 s"));
}
if m.protected {
col.lose(LossCategory::Markers, format!("{what}: the protected-region switch of a marker is not written"));
}
let (cue, cue_name, params) = match &m.cue_point {
Some(c) => (if c.navigation { 5 } else { 4 }, c.name.clone(), c.params.clone()),
None => (4, String::new(), Vec::new()),
};
out.push(MarkerPlan {
time,
duration,
label: crate::export::plan::label_index(m.label),
cue,
strings: [m.comment.clone(), m.chapter.clone(), m.url.clone(), m.frame_target.clone(), cue_name],
params,
});
}
out.sort_by_key(|m| m.time);
col.exported.markers = col.exported.markers.saturating_add(out.len());
out
}
/// The marker group (`tdmn` + `LIST mrst`) for `plans`, cloned from the prototype (249).
pub(crate) fn build(proto: &[Chunk<'static>], plans: &[MarkerPlan]) -> R<Vec<Chunk<'static>>> {
let mut group = proto.to_vec();
let mrst = group.get_mut(1).filter(|c| c.is_list(b"mrst")).ok_or_else(|| tpl("marker prototype"))?;
let n = u32::try_from(plans.len()).map_err(|_| tpl("too many markers"))?;
{
let tdbs = list_mut(mrst, b"tdbs")?;
let list = list_mut(tdbs, b"list")?;
let lhd3 = child_data(list, b"lhd3")?;
crate::export::synth::put_key_counts(lhd3, n, 16)?;
let ldat = child_data(list, b"ldat")?;
ldat.clear();
for p in plans {
let mut rec = [0u8; 16];
put(&mut rec, 0, &p.time.to_be_bytes())?;
rec[4] = 3;
rec[5] = 3;
ldat.extend_from_slice(&rec);
}
}
let mrky = list_mut(mrst, b"mrky")?;
let nmrd_proto = kids_mut(mrky)?.first().cloned().ok_or_else(|| tpl("marker prototype without Nmrd"))?;
let mut entries = Vec::with_capacity(plans.len());
for p in plans {
let mut nmrd = nmrd_proto.clone();
{
let h = child_data(&mut nmrd, b"NmHd")?;
put_u32(h, 0, p.cue)?;
put_u32(h, 4, u32::try_from(p.params.len()).unwrap_or(0))?;
put_u32(h, 8, p.duration)?;
put_u32(h, 12, 600)?;
put_u8(h, 16, p.label)?;
}
let kids = kids_mut(&mut nmrd)?;
kids.retain(|c| !c.is(b"Utf8"));
for s in &p.strings {
kids.push(Chunk::data(*b"Utf8", s.as_bytes().to_vec()));
}
for (k, v) in &p.params {
kids.push(Chunk::data(*b"Utf8", k.as_bytes().to_vec()));
kids.push(Chunk::data(*b"Utf8", v.as_bytes().to_vec()));
}
entries.push(nmrd);
}
*kids_mut(mrky)? = entries;
Ok(group)
}
/// Inserts the marker group as the first property of a top property group (`tdgp`): right after
/// its `tdsb` / `tdsn` header, before Time Remapping or the Transform group (123, 509).
pub(crate) fn insert(tdgp: &mut Chunk<'static>, group: Vec<Chunk<'static>>) -> R<()> {
let kids = kids_mut(tdgp)?;
let at = kids.iter().position(|c| c.is(b"tdmn")).unwrap_or(kids.len());
for (i, c) in group.into_iter().enumerate() {
kids.insert(at.saturating_add(i), c);
}
Ok(())
}
+671
View File
@@ -0,0 +1,671 @@
//! Layer masks: the plan (file units, losses reported) and the chunks, cloned from the mask
//! prototypes built in code ([`MaskProtos::build`], with the layout of our fixtures 091, 093 and
//! 208).
//!
//! What is written, each with its verified layout (`docs/aep-format.md` 3.4, 3.5 and 3.8):
//! - per mask a `mkif` (inverted at byte 0, mode `u32` at 4, the layer's running mask counter at
//! 8; the other bytes are zero, read-back t-zmkif) and an atom with the user name;
//! - the path as `LIST shap` (`shph`: open bit `0x08` of byte 3, the box of vertices and handles
//! normalised to the layer source size; `list`: three `f32` points per vertex, vertex `i`, out
//! handle `i`, in handle `i + 1`, normalised inside the box);
//! - path keys as 64-byte records (time, interpolation, label, the rest copied from the prototype)
//! with one `shap` per key;
//! - Feather (static or keyed, plain template with two components), Opacity (fraction) and
//! Expansion (pixels), each only when it is not at its default.
use crate::Chunk;
use effectcraft_keyframe::{Ease, Interp, ShapePath, Value};
use effectcraft_project::{FeatherFalloff, GroupKind, Layer, MaskMode, MaskMotionBlur, PropGroup};
use crate::export::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};
/// The most vertices one mask path may have (as the importer).
pub(crate) const MAX_VERTICES: usize = 65_536;
/// One path shape in the file's units.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ShapePlan {
/// Left, top, right, bottom as fractions of the layer source size.
pub bbox: [f32; 4],
pub open: bool,
/// Three points per vertex, normalised inside the box.
pub points: Vec<[f32; 2]>,
}
/// One path keyframe.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct PathKeyPlan {
pub time: i32,
/// 1 linear, 2 bezier, 3 hold.
pub in_interp: u8,
pub out_interp: u8,
/// The ease of a bezier side: speed (as stored) and influence (a fraction), at bytes 24..55
/// as in the spatial template (599, 700).
pub in_ease: (f64, f64),
pub out_ease: (f64, f64),
pub label: u8,
pub shape: ShapePlan,
}
/// A mask in the file's units.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct MaskPlan {
pub name: String,
/// `mkif` mode id: None 0, Add 1, Subtract 2, Intersect 3, Lighten 4, Darken 5, Difference 6.
pub mode: u32,
pub inverted: bool,
/// The static path (the first key's when the path is keyed).
pub shape: ShapePlan,
pub path_keys: Vec<PathKeyPlan>,
/// Pixels; `None` at the default `[0, 0]`.
pub feather: Option<[f64; 2]>,
pub feather_keys: Vec<KeyPlan>,
/// A fraction; `None` at the default 1.
pub opacity: Option<f64>,
/// Pixels; `None` at the default 0.
pub expansion: Option<f64>,
}
fn mode_id(m: MaskMode) -> u32 {
match m {
MaskMode::None => 0,
MaskMode::Add => 1,
MaskMode::Subtract => 2,
MaskMode::Intersect => 3,
MaskMode::Lighten => 4,
MaskMode::Darken => 5,
MaskMode::Difference => 6,
}
}
fn finite(v: f64) -> Option<f64> {
(v.is_finite() && v.abs() <= LIMIT).then_some(v)
}
/// A project path (layer pixels) in the file's units for a layer source of `size` pixels.
pub(crate) fn shape_plan(p: &ShapePath, size: (u32, u32)) -> Result<ShapePlan, &'static str> {
let n = p.vertices.len();
if n == 0 {
return Err("its path has no vertices");
}
if n > MAX_VERTICES {
return Err("its path has more than 65 536 vertices");
}
let (w, h) = (f64::from(size.0.max(1)), f64::from(size.1.max(1)));
let at = |i: usize| -> Option<([f64; 2], [f64; 2], [f64; 2])> {
let v = *p.vertices.get(i)?;
let t_in = p.in_tangents.get(i).copied().unwrap_or([0.0; 2]);
let t_out = p.out_tangents.get(i).copied().unwrap_or([0.0; 2]);
let add = |a: [f64; 2], b: [f64; 2]| [a[0] + b[0], a[1] + b[1]];
Some((v, add(v, t_in), add(v, t_out)))
};
// Absolute points in layer pixels: vertex i, out handle i, in handle i + 1.
let mut abs: Vec<[f64; 2]> = Vec::with_capacity(n.saturating_mul(3));
for i in 0..n {
let (v, _, out) = at(i).ok_or("its path is incomplete")?;
let (_, next_in, _) = at((i + 1) % n).ok_or("its path is incomplete")?;
abs.extend([v, out, next_in]);
}
if !abs.iter().flatten().all(|c| finite(*c).is_some()) {
return Err("its path holds a number that is not valid");
}
// Normalised to the layer size, then the box of all points.
let norm: Vec<[f64; 2]> = abs.iter().map(|[x, y]| [x / w, y / h]).collect();
let (mut left, mut top, mut right, mut bottom) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for [x, y] in &norm {
left = left.min(*x);
right = right.max(*x);
top = top.min(*y);
bottom = bottom.max(*y);
}
let bbox = [left as f32, top as f32, right as f32, bottom as f32];
let [l, t, r, b] = bbox.map(f64::from);
// A box without width or height (all points on one line) stores 0 for that coordinate.
let unit = |v: f64, lo: f64, hi: f64| if hi - lo > 0.0 { ((v - lo) / (hi - lo)) as f32 } else { 0.0 };
let points = norm.iter().map(|[x, y]| [unit(*x, l, r), unit(*y, t, b)]).collect();
Ok(ShapePlan { bbox, open: !p.closed, points })
}
/// Plans the masks of a layer whose source is `size` pixels.
pub(crate) fn plan_masks(layer: &Layer, size: (u32, u32), cp: &CompPlan, comp_name: &str, col: &mut Collector) -> Vec<MaskPlan> {
let Some(masks) = layer.masks() else { return Vec::new() };
let mut out = Vec::new();
for g in masks.groups() {
let what = format!("{comp_name}: '{}' {}", layer.name, g.name);
if let Some(m) = plan_mask(g, size, cp, &what, col) {
col.exported.masks = col.exported.masks.saturating_add(1);
out.push(m);
}
}
out
}
fn plan_mask(g: &PropGroup, size: (u32, u32), cp: &CompPlan, what: &str, col: &mut Collector) -> Option<MaskPlan> {
let GroupKind::Mask { mode, inverted, locked, motion_blur, feather_falloff, roto_bezier, .. } = g.kind else {
col.lose(LossCategory::Masks, format!("{what}: not a mask, not exported"));
return None;
};
if !g.enabled {
col.lose(LossCategory::Masks, format!("{what}: a disabled mask is not exported"));
return None;
}
let Some(path_prop) = g.get("path") else {
col.lose(LossCategory::Masks, format!("{what}: no path, not exported"));
return None;
};
let Value::Path(static_path) = &path_prop.value else {
col.lose(LossCategory::Masks, format!("{what}: the path is not a path, not exported"));
return None;
};
// Switches the file layout does not hold (not decoded).
if locked {
col.lose(LossCategory::Masks, format!("{what}: the lock is not written"));
}
if motion_blur != MaskMotionBlur::SameAsLayer {
col.lose(LossCategory::Masks, format!("{what}: mask motion blur is written as Same As Layer"));
}
if feather_falloff != FeatherFalloff::Smooth {
col.lose(LossCategory::Masks, format!("{what}: Linear feather falloff is written as Smooth"));
}
if roto_bezier {
col.lose(LossCategory::Masks, format!("{what}: RotoBezier is not written (the tangents are)"));
}
for id in ["path", "feather", "opacity", "expansion"] {
if g.get(id).is_some_and(|p| p.has_expression()) {
col.lose(LossCategory::Masks, format!("{what}: the expression on Mask {id} is not written"));
}
}
// The path and its keys.
let mut path_keys: Vec<PathKeyPlan> = Vec::new();
let 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 side = |i: Interp| -> u8 {
match i {
Interp::Linear => 1,
Interp::Hold => 3,
Interp::Bezier => 2,
}
};
let ease = |e: &[effectcraft_keyframe::Ease], on: bool| -> (f64, f64) {
if !on {
return (0.0, 0.0);
}
let e = e.first().copied().unwrap_or(effectcraft_keyframe::Ease { speed: 0.0, influence: 1.0 / 3.0 });
let speed = finite(e.speed).filter(|v| v.abs() <= 1e9).unwrap_or(0.0);
let influence = if e.influence.is_finite() { e.influence.clamp(0.001, 1.0) } else { 1.0 / 3.0 };
(speed, influence)
};
let mut feather_points = !static_path.feather.is_empty();
for (u, k) in &keys {
let Ok(time) = i32::try_from(*u) else {
col.lose(LossCategory::InvalidValues, format!("{what}: path key time out of range, key dropped"));
continue;
};
let Value::Path(p) = &k.value else {
col.lose(LossCategory::InvalidValues, format!("{what}: a path key without a path was dropped"));
continue;
};
feather_points |= !p.feather.is_empty();
let shape = match shape_plan(p, size) {
Ok(s) => s,
Err(why) => {
col.lose(LossCategory::InvalidValues, format!("{what}: a path key was dropped, {why}"));
continue;
}
};
if k.roving {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a roving path key is written as a normal key"));
}
let (in_interp, out_interp) = (side(k.in_interp), side(k.out_interp));
if (in_interp == 2 && k.in_ease.first().is_some_and(|e| e.speed != 0.0)) || (out_interp == 2 && k.out_ease.first().is_some_and(|e| e.speed != 0.0)) {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a path key ease speed other than 0 is written as stored (its unit is not sampled)"));
}
let (in_ease, out_ease) = (ease(&k.in_ease, in_interp == 2), ease(&k.out_ease, out_interp == 2));
path_keys.push(PathKeyPlan { time, in_interp, out_interp, in_ease, out_ease, label: k.label.min(16), shape });
col.exported.keyframes = col.exported.keyframes.saturating_add(1);
}
if feather_points {
col.lose(LossCategory::Masks, format!("{what}: variable-width feather points are not written"));
}
let shape = match path_keys.first() {
Some(k) => k.shape.clone(),
None => match shape_plan(static_path, size) {
Ok(s) => s,
Err(why) => {
col.lose(LossCategory::Masks, format!("{what}: not exported, {why}"));
return None;
}
},
};
// Feather, opacity, expansion.
let feather_prop = g.get("feather");
let feather_value = match feather_prop.map(|p| &p.value) {
Some(Value::Vec2(v)) => *v,
_ => [0.0, 0.0],
};
let feather = match (finite(feather_value[0]), finite(feather_value[1])) {
(Some(x), Some(y)) if (0.0..=MASK_LIMIT).contains(&x) && (0.0..=MASK_LIMIT).contains(&y) => ([x, y] != [0.0, 0.0]).then_some([x, y]),
_ => {
col.lose(LossCategory::InvalidValues, format!("{what}: feather {feather_value:?} is not valid, the default was written"));
None
}
};
let feather_keys = feather_prop.map_or_else(Vec::new, |p| plan_feather_keys(&p.keys, cp, what, col));
let scalar = |id: &str, default: f64, lo: f64, hi: f64, col: &mut Collector| -> Option<f64> {
let p = g.get(id)?;
if !p.keys.is_empty() {
col.lose(LossCategory::Masks, format!("{what}: keys on Mask {id} are not written (no keyed prototype), the static value is"));
}
let Value::Scalar(v) = p.value else { return None };
match finite(v) {
Some(v) if (lo..=hi).contains(&v) => ((v - default).abs() > 1e-12).then_some(v),
_ => {
col.lose(LossCategory::InvalidValues, format!("{what}: Mask {id} {v} is not valid, the default was written"));
None
}
}
};
let opacity = scalar("opacity", 100.0, 0.0, 100.0, col).map(|v| v / 100.0);
// The record holds -32 000 to 32 000, as for the feather (`tduM`, 091).
let expansion = scalar("expansion", 0.0, -MASK_LIMIT, MASK_LIMIT, col);
let name = cut_name(&g.name, 255, what, col);
Some(MaskPlan { name, mode: mode_id(mode), inverted, shape, path_keys, feather, feather_keys, opacity, expansion })
}
/// Feather keys (plain template, two components, speed in pixels per second).
fn plan_feather_keys(src: &[effectcraft_keyframe::Keyframe], cp: &CompPlan, what: &str, col: &mut Collector) -> Vec<KeyPlan> {
let 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 mut out = Vec::with_capacity(keys.len());
let beyond = std::cell::Cell::new(false);
for (u, k) in &keys {
let Ok(time) = i32::try_from(*u) else {
col.lose(LossCategory::InvalidValues, format!("{what}: feather key time out of range, key dropped"));
continue;
};
let value = match &k.value {
Value::Vec2([x, y]) => match (finite(*x), finite(*y)) {
(Some(x), Some(y)) if (0.0..=MASK_LIMIT).contains(&x) && (0.0..=MASK_LIMIT).contains(&y) => vec![x, y],
_ => {
col.lose(LossCategory::InvalidValues, format!("{what}: a feather key that is not valid was dropped"));
continue;
}
},
_ => {
col.lose(LossCategory::InvalidValues, format!("{what}: a feather key that is not a pair was dropped"));
continue;
}
};
let code = |i: Interp| match i {
Interp::Linear => 1u8,
Interp::Bezier => 2,
Interp::Hold => 3,
};
let (in_interp, out_interp) = (code(k.in_interp), code(k.out_interp));
let ease = |eases: &[Ease], i: usize, on: bool| -> EaseSlot {
if !on {
return EaseSlot::default();
}
let e = crate::export::plan::key_ease(eases, i);
let speed = finite(e.speed).filter(|v| v.abs() <= 1e9).unwrap_or_else(|| {
beyond.set(true);
0.0
});
EaseSlot { speed, influence: if e.influence.is_finite() { e.influence.clamp(0.001, 1.0) } else { 1.0 / 3.0 } }
};
out.push(KeyPlan {
time,
value,
in_interp,
out_interp,
in_ease: (0..2).map(|i| ease(&k.in_ease, i, in_interp == 2)).collect(),
out_ease: (0..2).map(|i| ease(&k.out_ease, i, out_interp == 2)).collect(),
spatial_in: [0.0; 3],
spatial_out: [0.0; 3],
spatial_auto: false,
roving: false,
label: k.label.min(16),
});
if k.roving {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a roving feather key is written as a normal key"));
}
col.exported.keyframes = col.exported.keyframes.saturating_add(1);
}
crate::export::plan::report_beyond(beyond.get(), what, col);
out
}
// ---------------------------------------------------------------- chunks
/// The mask prototypes.
pub(crate) struct MaskProtos {
/// `tdmn ADBE Mask Parade`.
pub parade_name: Chunk<'static>,
/// The parade group children before its first match name (`tdsb`, `tdsn`).
pub parade_header: Vec<Chunk<'static>>,
/// `tdmn ADBE Mask Atom`, `mkif`, the atom `tdgp` (with static Feather, Opacity, Offset).
pub atom_name: Chunk<'static>,
pub mkif: Chunk<'static>,
pub atom: Chunk<'static>,
/// `tdmn ADBE Group End`.
pub group_end: Chunk<'static>,
/// The keyed path property (`tdbs`, two 64-byte records).
pub keyed_path: Chunk<'static>,
/// The keyed Mask Feather property (`tdbs`, two 88-byte records).
pub keyed_feather: Chunk<'static>,
}
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;
/// A shape header (`shph`, 24 bytes, aep-format.md 3.8): bytes 0..2 `b3 de 02` (in every
/// sample; meaning not decoded, and zero there is "an internally damaged shape" for After Effects,
/// s13-m1), byte 3 `0x01` (`0x09` once the path is open), the box at 4..19 (written per shape),
/// byte 20 1.
pub(crate) fn shph() -> Vec<u8> {
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);
b
}
impl MaskProtos {
/// The prototypes built in code (aep-format.md 3.8): the parade and atom groups, `mkif` with
/// only its decoded fields (bytes 12..47 zero, read-back t-zmkif), the path, feather, opacity
/// and expansion records, and the keyed path and feather records.
pub(crate) fn build() -> MaskProtos {
use crate::export::synth::{KeyTemplate, NO_NAME, RecSpec, class, key_list, tdb4, tdbs, tdmn, tdsn};
let state = || Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec());
// The path property: one component of the path template (`tdb4` byte 7 = 1), a 4-byte
// `cdat`; the shapes follow in `omks`.
let path = RecSpec { dims: 1, template: KeyTemplate::Spatial(1), class: class::PATH, limits: None, byte5: None };
let path_rec = |keyed: bool| {
let mut kids = vec![state(), tdsn(NO_NAME), Chunk::data(*b"tdb4", tdb4(&path, keyed, 25_600))];
if keyed {
// 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()));
} else {
kids.push(Chunk::data(*b"cdat", vec![0u8; 4]));
}
Chunk::list(*b"tdbs", kids)
};
let shap = Chunk::list(*b"shap", vec![Chunk::data(*b"shph", shph()), key_list(8, 0, Vec::new()), Chunk::data(*b"omtn", Vec::new())]);
let feather = RecSpec { dims: 2, template: KeyTemplate::Plain, class: class::EFFECT_NUMBER, limits: Some((0.0, MASK_LIMIT)), byte5: None };
let opacity = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_NUMBER, limits: Some((0.0, 100.0)), byte5: None };
let offset = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_NUMBER, limits: Some((-MASK_LIMIT, MASK_LIMIT)), byte5: None };
let atom = Chunk::list(
*b"tdgp",
vec![
state(),
tdsn("Mask 1"),
tdmn("ADBE Mask Shape"),
Chunk::list(*b"om-s", vec![path_rec(false), Chunk::list(*b"omks", vec![shap])]),
tdmn("ADBE Mask Feather"),
tdbs(&feather, false, 25_600),
tdmn("ADBE Mask Opacity"),
tdbs(&opacity, false, 25_600),
tdmn("ADBE Mask Offset"),
tdbs(&offset, false, 25_600),
tdmn("ADBE Group End"),
],
);
MaskProtos {
parade_name: tdmn("ADBE Mask Parade"),
parade_header: vec![state(), tdsn(NO_NAME)],
atom_name: tdmn("ADBE Mask Atom"),
mkif: Chunk::data(*b"mkif", vec![0u8; 48]),
atom,
group_end: tdmn("ADBE Group End"),
keyed_path: path_rec(true),
keyed_feather: tdbs(&feather, true, 25_600),
}
}
}
/// `tdmn` + `ADBE Mask Parade` group for the masks of a layer (source `size` pixels).
pub(crate) fn build_parade(t: &MaskProtos, masks: &[MaskPlan], size: (u32, u32)) -> R<[Chunk<'static>; 2]> {
let mut kids = t.parade_header.clone();
for (i, m) in masks.iter().enumerate() {
let mut mkif = t.mkif.clone();
{
let d = crate::export::tree::data_mut(&mut mkif)?;
put_u8(d, 0, u8::from(m.inverted))?;
put_u32(d, 4, m.mode)?;
put_u32(d, 8, u32::try_from(i.saturating_add(1)).map_err(|_| tpl("too many masks"))?)?;
}
kids.push(t.atom_name.clone());
kids.push(mkif);
kids.push(build_atom(t, m, size)?);
}
kids.push(t.group_end.clone());
Ok([t.parade_name.clone(), Chunk::list(*b"tdgp", kids)])
}
fn build_atom(t: &MaskProtos, m: &MaskPlan, size: (u32, u32)) -> R<Chunk<'static>> {
let mut atom = t.atom.clone();
{
let tdsn = child_mut(&mut atom, b"tdsn")?;
crate::export::tree::set_utf8(tdsn, &m.name)?;
}
let 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 keep = match name.as_str() {
"ADBE Mask Shape" => {
build_shape(t, &mut node, m, size)?;
true
}
"ADBE Mask Feather" => {
if !m.feather_keys.is_empty() {
node = keyed_feather(t, &m.feather_keys)?;
true
} else if let Some([x, y]) = m.feather {
set_cdat(&mut node, &[x, y])?;
true
} else {
false
}
}
"ADBE Mask Opacity" => match m.opacity {
Some(v) => {
set_cdat(&mut node, &[v])?;
true
}
None => false,
},
"ADBE Mask Offset" => match m.expansion {
Some(v) => {
set_cdat(&mut node, &[v])?;
true
}
None => false,
},
_ => true,
};
if keep {
out.push(tdmn);
out.push(node);
}
}
out.push(end);
*kids_mut(&mut atom)? = out;
Ok(atom)
}
fn set_cdat(tdbs: &mut Chunk<'static>, values: &[f64]) -> R<()> {
let cdat = child_data(tdbs, b"cdat")?;
cdat.iter_mut().for_each(|b| *b = 0);
for (i, v) in values.iter().enumerate() {
put_f64(cdat, i * 8, *v)?;
}
Ok(())
}
/// 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.
let size = 88;
let mut ldat = Vec::with_capacity(size * keys.len());
for k in keys {
ldat.extend(crate::export::emit::plain_record(2, k, size)?);
}
set_key_list(&mut tdbs, ldat, keys.len(), size)?;
Ok(tdbs)
}
/// The `om-s` of the path: the property (static or keyed) and one `shap` per shape.
fn build_shape(t: &MaskProtos, oms: &mut Chunk<'static>, m: &MaskPlan, size: (u32, u32)) -> R<()> {
let aspect = f64::from(size.0.max(1)) / f64::from(size.1.max(1));
let shapes: Vec<&ShapePlan> = if m.path_keys.is_empty() { vec![&m.shape] } else { m.path_keys.iter().map(|k| &k.shape).collect() };
let kids = kids_mut(oms)?;
// The shape prototype (one static `shap`).
let omks = kids.iter_mut().find(|c| c.is_list(b"omks")).ok_or_else(|| tpl("mask path without omks"))?;
let proto = kids_mut(omks)?.iter().find(|c| c.is_list(b"shap")).cloned().ok_or_else(|| tpl("mask path without a shape"))?;
let mut list = Vec::with_capacity(shapes.len());
for s in &shapes {
list.push(build_shap(&proto, s)?);
}
*kids_mut(omks)? = list;
let tdbs = kids.iter_mut().find(|c| c.is_list(b"tdbs")).ok_or_else(|| tpl("mask path without its property"))?;
if !m.path_keys.is_empty() {
let mut keyed = t.keyed_path.clone();
// The two prototype records (093). Only the common fields are decoded; the rest of the 64
// bytes is copied: the first key from the first record, every later key from the second
// (093 differs there: an `f64` 1 at byte 16 of the first record, 0 in the second).
let protos: Vec<Vec<u8>> = {
let list = keyed.child_list(b"list").ok_or_else(|| tpl("keyed path without keys"))?;
let ldat = list.child(b"ldat").and_then(|c| c.bytes()).ok_or_else(|| tpl("keyed path without records"))?;
ldat.as_chunks::<64>().0.iter().map(|r| r.to_vec()).collect()
};
let (first_rec, later_rec) = match protos.as_slice() {
[a, b, ..] => (a.clone(), b.clone()),
_ => return Err(tpl("keyed path prototype without two records")),
};
let mut ldat = Vec::with_capacity(64 * m.path_keys.len());
for (i, k) in m.path_keys.iter().enumerate() {
let mut r = if i == 0 { first_rec.clone() } else { later_rec.clone() };
let flags = u16::from_be_bytes([r.get(6).copied().unwrap_or(0), r.get(7).copied().unwrap_or(1)]) & !0x03e0;
put_i32(&mut r, 0, k.time)?;
put_u8(&mut r, 4, k.in_interp)?;
put_u8(&mut r, 5, k.out_interp)?;
put_u16(&mut r, 6, flags | (u16::from(k.label) << 6))?;
// The ease of bezier sides at 24..55 (599, 700); linear and hold sides keep the
// prototype's zeros.
if k.in_interp == 2 {
put_f64(&mut r, 24, k.in_ease.0)?;
put_f64(&mut r, 32, k.in_ease.1)?;
}
if k.out_interp == 2 {
put_f64(&mut r, 40, k.out_ease.0)?;
put_f64(&mut r, 48, k.out_ease.1)?;
}
ldat.extend(r);
}
set_key_list(&mut keyed, ldat, m.path_keys.len(), 64)?;
*tdbs = keyed;
}
// The width / height of the layer source, as for the Anchor Point (090, 093: 16 / 9 on a
// 1920 x 1080 solid; 309: 1 on a 100 x 100 solid).
put_f64(child_data(tdbs, b"tdb4")?, 24, aspect)?;
Ok(())
}
pub(crate) fn build_shap(proto: &Chunk<'static>, s: &ShapePlan) -> R<Chunk<'static>> {
let mut shap = proto.clone();
{
let shph = child_data(&mut shap, b"shph")?;
crate::export::tree::put_bits(shph, 3, 0x08, s.open)?;
for (i, v) in s.bbox.iter().enumerate() {
put_f32(shph, 4 + 4 * i, *v)?;
}
}
let list = list_mut(&mut shap, b"list")?;
let records = s.points.len();
let vertices = u32::try_from(records / 3).map_err(|_| tpl("too many vertices"))?;
{
// Point lists: word 2 the record count, words 3 and 7 the vertex count and four times it
// (090: 12 records, 4 and 16; 233: 9 records, 3 and 12), word 4 the record size 8.
let lhd3 = child_data(list, b"lhd3")?;
crate::export::synth::put_counts(lhd3, u32::try_from(records).map_err(|_| tpl("too many points"))?, vertices, 8, vertices, vertices.saturating_mul(4))?;
}
let mut ldat = vec![0u8; records.saturating_mul(8)];
for (i, [u, v]) in s.points.iter().enumerate() {
put_f32(&mut ldat, i * 8, *u)?;
put_f32(&mut ldat, i * 8 + 4, *v)?;
}
let ld = kids_mut(list)?;
match ld.iter_mut().find(|c| c.is(b"ldat")) {
Some(c) => *c = Chunk::data(*b"ldat", ldat),
None => ld.push(Chunk::data(*b"ldat", ldat)),
}
Ok(shap)
}
File diff suppressed because it is too large. Load diff
+268
View File
@@ -0,0 +1,268 @@
//! The export report: what was written (counts) and everything that was not, per category.
//!
//! Plain data (`serde`), so it round-trips through JSON: the engine command returns it and agents
//! read it. Nothing the exporter leaves out is missing from it.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
/// Most example lines kept per loss category (the count is always exact).
pub const MAX_DETAILS: usize = 20;
/// Why a piece of the project did not arrive in the `.aep`, or arrived changed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LossCategory {
/// Effects on layers that are not written (not in the table, a parameter
/// without a counterpart, an expression on a parameter).
Effects,
/// Mask data that is not written: a disabled mask or one without a usable path, keys on Mask
/// Opacity or Expansion, expressions on mask properties, the lock, mask motion blur other than
/// Same As Layer, Linear feather falloff, RotoBezier and variable-width feather points.
Masks,
/// Layer and composition markers.
Markers,
/// Text layer features that are not written (animators, Source Text keys, strokes, ...), and
/// text layers without a text document.
TextLayers,
/// Shape layer contents that are not written.
ShapeLayers,
/// Camera settings that are not written, Auto-Orient Along Path or Towards Camera included.
Cameras,
/// Light settings that are not written, a spot light not oriented towards its point of
/// interest included.
Lights,
/// 3D model and primitive layers (skipped as a whole).
ModelLayers,
/// Footage items that are not written (a file type without a prototype, a layered file's
/// layer, a sequence with gaps or at a fractional rate), and items in a folder loop.
FootageItems,
/// Layers whose source is not exported (footage that is not written, a precomposition that is
/// missing or closes a loop, other).
UnsupportedLayers,
/// Blend modes After Effects has no code for (written as Normal).
BlendModes,
/// Track mattes.
TrackMattes,
/// 3D features that are not written (per-character 3D of a text layer, Material Options other
/// than the defaults; the layer's 3D switch itself is written).
ThreeD,
/// A time stretch that is not an exact small ratio (the layer is written unstretched).
TimeStretch,
/// Transform properties other than Anchor Point, Position, Scale, Rotation and Opacity.
TransformProperties,
/// Expression on a property that is not exported.
Expressions,
/// Keyframes written in a simpler form (see the detail lines).
ApproximatedKeyframes,
/// A value that is not a finite number or beyond the range of the format (default written).
InvalidValues,
/// Frame rate that the format cannot hold exactly, composition size or duration out of range.
CompositionSettings,
/// Parent links to a layer that was not exported.
ParentLinks,
/// Times rounded to the composition's time base.
RoundedTimes,
/// Composition options that are not exported (guides, essential graphics, advanced renderer),
/// and settings that change rendered frames but are written at After Effects' defaults:
/// Preserve Frame Rate or Preserve Resolution switched on, motion blur samples per frame and
/// adaptive sample limit other than 16 and 128.
CompositionOptions,
/// Names longer than the format's name field (the name is kept in full where verified), and
/// item comments (not written).
Names,
/// Layer timing After Effects does not keep: a layer of a clip, sequence or sound that runs
/// past the end of its source (After Effects ends it there).
LayerTiming,
/// Project settings that are not written: a working space other than None, sRGB and Rec.709
/// Gamma 2.4, the OCIO
/// colour engine, HDR handling and output space, a frame count start other than 0 and 1.
ProjectSettings,
/// Time remapping on a layer After Effects cannot remap (a solid, a text): not written.
TimeRemapping,
/// Layer-style data that is not written: a style or Layer Styles switched off, edited
/// gradients, keys on colours, points, popups and checkboxes, Knockout.
LayerStyles,
/// Layer switches and options that are not written: Wireframe quality, Bicubic sampling,
/// frame blending, Preserve Transparency, Auto-Orient on a layer other than a camera or light
/// (theirs is reported as [`Cameras`](Self::Cameras) / [`Lights`](Self::Lights)), an
/// environment layer, locked markers.
LayerSwitches,
/// Render queue items (the render queue is not written).
RenderQueue,
}
impl LossCategory {
/// A short readable name.
pub fn label(self) -> &'static str {
match self {
LossCategory::Effects => "effects",
LossCategory::Masks => "masks",
LossCategory::Markers => "markers",
LossCategory::TextLayers => "text layers",
LossCategory::ShapeLayers => "shape layers",
LossCategory::Cameras => "cameras",
LossCategory::Lights => "lights",
LossCategory::ModelLayers => "3D model layers",
LossCategory::FootageItems => "footage items",
LossCategory::UnsupportedLayers => "unsupported layers",
LossCategory::BlendModes => "blend modes",
LossCategory::TrackMattes => "track mattes",
LossCategory::ThreeD => "3D layers",
LossCategory::TimeStretch => "time stretch",
LossCategory::TransformProperties => "transform properties",
LossCategory::Expressions => "expressions",
LossCategory::ApproximatedKeyframes => "approximated keyframes",
LossCategory::InvalidValues => "invalid values",
LossCategory::CompositionSettings => "composition settings",
LossCategory::ParentLinks => "parent links",
LossCategory::RoundedTimes => "rounded times",
LossCategory::CompositionOptions => "composition options",
LossCategory::Names => "names",
LossCategory::LayerTiming => "layer timing",
LossCategory::ProjectSettings => "project settings",
LossCategory::TimeRemapping => "time remapping",
LossCategory::LayerStyles => "layer styles",
LossCategory::LayerSwitches => "layer switches",
LossCategory::RenderQueue => "render queue",
}
}
}
/// One category of things that were not exported.
#[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>,
}
/// What was written to the file.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Exported {
pub folders: usize,
pub compositions: usize,
pub solids: usize,
/// All layers.
pub layers: usize,
pub solid_layers: usize,
pub null_layers: usize,
pub adjustment_layers: usize,
/// Transform properties written with a value that differs from the default.
pub properties: usize,
/// Keyframes written.
pub keyframes: usize,
/// Expressions written (source text and enable switch).
pub expressions: usize,
/// Layer masks written.
#[serde(default)]
pub masks: usize,
/// Precomposition layers (a composition shown as a layer).
#[serde(default)]
pub precomp_layers: usize,
/// Effect instances written.
#[serde(default)]
pub effects: usize,
/// Footage items (files) written.
#[serde(default)]
pub footage: usize,
/// Footage layers written.
#[serde(default)]
pub footage_layers: usize,
/// Text layers written.
#[serde(default)]
pub text_layers: usize,
/// Layer and composition markers written.
#[serde(default)]
pub markers: usize,
/// Camera layers written.
#[serde(default)]
pub cameras: usize,
/// Light layers written.
#[serde(default)]
pub lights: usize,
/// Shape layers written.
#[serde(default)]
pub shape_layers: usize,
/// Layers written with an enabled Time Remap.
#[serde(default)]
pub time_remaps: usize,
/// Text animators written.
#[serde(default)]
pub text_animators: usize,
/// Layer styles written (one per style on a layer).
#[serde(default)]
pub layer_styles: usize,
}
/// Standing limitations of the exporter (what it cannot write at all), listed in every report.
pub const LIMITATIONS: &[&str] = &[
"The render queue (its items are reported), render templates and project settings other than colour depth, working space (None, sRGB or Rec.709 Gamma 2.4), working gamma, the two linear-light switches, time display and frame count start are not exported.",
"Composition options other than size, frame rate, duration, work area, background, pixel aspect, shutter, motion blur switch and display start are written at After Effects' defaults: other values of preserve frame rate, preserve resolution, motion blur samples and adaptive sample limit are reported; draft 3D, hide shy, the viewer resolution, the poster time and the composition's frame blending switch (layer frame blending is reported, and no layer blends without it) are not exported. The background is stored with 8 bits per channel.",
"Footage is linked, not embedded: png, jpeg, OpenEXR, TIFF, Targa, Photoshop, Illustrator and EPS stills, png, OpenEXR and jpeg sequences, mp4 and mov clips and WAV audio are written with their path, size, duration and frame rate (a conformed clip rate too); the rest of their interpretation (alpha, colour management, fields, loops) is the default.",
"Layer comments, a 3D layer's X / Y rotation, orientation and material options (each reported when it is not at its default), parallel and ambient lights, and shape items outside groups, rectangles, ellipses, polystars, paths, fills, strokes, gradients, trim paths, round corners, merge and offset paths and repeaters (wiggle, twist, zig-zag, pucker and bloat, ...) are not written.",
"Mask colours are not written: After Effects shows its own colour for every exported mask.",
];
/// The result of planning/writing an `.aep`: counts of what was written, the losses per category
/// and the standing limitations of the exporter.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportReport {
pub exported: Exported,
/// Only categories that occurred, in category order.
pub losses: Vec<Loss>,
pub limitations: Vec<String>,
}
impl ExportReport {
/// The sum of all loss counts.
pub fn total_losses(&self) -> usize {
self.losses.iter().map(|l| l.count).sum()
}
/// True when nothing was lost.
pub fn is_lossless(&self) -> bool {
self.losses.is_empty()
}
/// The loss count of a category.
pub fn count(&self, category: LossCategory) -> usize {
self.losses.iter().find(|l| l.category == category).map_or(0, |l| l.count)
}
/// `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(", ")
}
}
/// Collects losses while planning.
#[derive(Default)]
pub(crate) struct Collector {
pub exported: Exported,
losses: BTreeMap<LossCategory, Loss>,
}
impl Collector {
/// Records one loss.
pub fn lose(&mut self, category: LossCategory, detail: impl Into<String>) {
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());
}
}
pub fn finish(self) -> ExportReport {
ExportReport {
exported: self.exported,
losses: self.losses.into_values().collect(),
limitations: LIMITATIONS.iter().map(|s| (*s).to_string()).collect(),
}
}
}
+142
View File
@@ -0,0 +1,142 @@
//! Project settings (`docs/aep-format.md` 3.12a, cases 620-634): colour depth, working space
//! (None, sRGB or Rec.709 Gamma 2.4, with profiles authored here), working gamma, the two linear-light switches, time display and
//! frame count start, written into the template's top-level chunks.
use crate::{AepFile, Chunk};
use effectcraft_color::ColorSpace;
use effectcraft_project::{BitDepth, ColorEngine, HdrMode, ProjectSettings, TimeDisplayStyle};
use crate::export::report::{Collector, LossCategory};
use crate::export::tree::{R, data_mut, put_u8, tpl};
/// The settings in the file's terms.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SettingsPlan {
/// `nhed` byte 15: 0 / 1 / 2 for 8 / 16 / 32 bits per channel.
pub depth: u8,
/// No working space (623); otherwise sRGB unless `rec709`.
pub no_working_space: bool,
/// Rec.709 Gamma 2.4, written with a profile authored here (`icc.rs`, R49).
pub rec709: bool,
/// `dwga` byte 0: 1 for a working gamma of 2.4.
pub gamma_24: bool,
pub linearize: bool,
pub blend_linear: bool,
/// `nhed` bytes 8, 11, 13: frames, feet + frames, frames per foot.
pub frames: bool,
pub feet: Option<u8>,
/// `nhed` byte 14: 2 for a count from 0, 1 for a count from 1.
pub frame_start: u8,
}
pub(crate) fn plan(s: &ProjectSettings, col: &mut Collector) -> SettingsPlan {
let depth = match s.bit_depth {
BitDepth::Bpc8 => 0,
BitDepth::Bpc16 => 1,
BitDepth::Bpc32 => 2,
};
let (no_working_space, rec709) = match s.working_space {
None => (true, false),
Some(ColorSpace::Srgb) => (false, false),
Some(ColorSpace::Rec709) => (false, true),
Some(other) => {
col.lose(
LossCategory::ProjectSettings,
format!("the working space {other:?} is written as sRGB (only None, sRGB and Rec.709 Gamma 2.4 are written)"),
);
(false, false)
}
};
if s.color_engine != ColorEngine::Adobe {
col.lose(LossCategory::ProjectSettings, "the OCIO colour engine is not written".to_string());
}
if s.hdr != HdrMode::Clip {
col.lose(LossCategory::ProjectSettings, "the HDR handling is not written".to_string());
}
// After Effects renders in the working space (902): an output space equal to the working
// space is its normal case (the importer sets it so for Rec.709 Gamma 2.4); another one has
// no place in the file.
if s.output_space.is_some_and(|o| Some(o) != s.working_space) {
col.lose(LossCategory::ProjectSettings, "an output space other than the working space is not written".to_string());
}
let (frames, feet) = match s.time_display {
TimeDisplayStyle::Timecode => (false, None),
TimeDisplayStyle::Frames => (true, None),
TimeDisplayStyle::Feet35 => (true, Some(16)),
TimeDisplayStyle::Feet16 => (true, Some(40)),
};
let frame_start = match s.frame_start {
0 => 2,
1 => 1,
other => {
col.lose(LossCategory::ProjectSettings, format!("a frame count start of {other} is written as 0 (only 0 and 1 exist)"));
2
}
};
SettingsPlan {
depth,
no_working_space,
rec709,
gamma_24: s.working_gamma_24(),
linearize: s.linearize,
blend_linear: s.blend_linear,
frames,
feet,
frame_start,
}
}
/// Writes `p` into the template's top-level chunks.
pub(crate) fn emit(file: &mut AepFile<'static>, p: &SettingsPlan) -> R<()> {
let top = &mut file.chunks;
let header =
|top: &mut Vec<Chunk<'static>>, id: &[u8; 4]| -> R<usize> { top.iter().position(|c| c.is(id)).ok_or_else(|| tpl("template header chunk missing")) };
// nhed and its copy nnhd (byte offsets per field: 620-634).
for (id, at_depth, at_display, at_feet, at_fpf, at_start) in [(b"nhed", 15, 8, 11, 13, 14), (b"nnhd", 24, 8, 11, 19, 20)] {
let i = header(top, id)?;
let d = data_mut(top.get_mut(i).ok_or_else(|| tpl("header"))?)?;
put_u8(d, at_depth, p.depth)?;
put_u8(d, at_display, u8::from(p.frames))?;
put_u8(d, at_feet, u8::from(p.feet.is_some()))?;
put_u8(d, at_fpf, p.feet.unwrap_or(16))?;
put_u8(d, at_start, p.frame_start)?;
}
{
let i = header(top, b"dwga")?;
put_u8(data_mut(top.get_mut(i).ok_or_else(|| tpl("dwga"))?)?, 0, u8::from(p.gamma_24))?;
}
// Blend Colors Using 1.0 Gamma (lnrb) and Linearize Working Space (lnrp): one-byte chunks
// right after cpid, in that order (626, 627, 632).
top.retain(|c| !c.is(b"lnrb") && !c.is(b"lnrp"));
let cpid = header(top, b"cpid")?;
let mut at = cpid.saturating_add(1);
if p.blend_linear {
top.insert(at, Chunk::data(*b"lnrb", vec![1u8]));
at = at.saturating_add(1);
}
if p.linearize {
top.insert(at, Chunk::data(*b"lnrp", vec![1u8]));
}
if !p.no_working_space {
// 620, 624: `cpid` is the profile ID, the JSON after PwCs holds the profile's data and the
// working space's name; the profiles are our own (R49).
let (icc, name) = if p.rec709 {
(crate::export::icc::rec709_gamma24(), crate::export::icc::REC709_NAME)
} else {
(crate::export::icc::srgb(), crate::export::icc::SRGB_NAME)
};
*top.get_mut(cpid).ok_or_else(|| tpl("cpid"))? = Chunk::data(*b"cpid", crate::export::icc::profile_id(&icc).to_vec());
let pw = header(top, b"PwCs")?;
let json = top.get_mut(pw.saturating_add(1)).filter(|c| c.is(b"Utf8")).ok_or_else(|| tpl("template without the working-space JSON"))?;
let text = crate::export::icc::profile_json(&icc, name);
*json = Chunk::data(*b"Utf8", text.into_bytes());
}
if p.no_working_space {
// 623: cpid all 0xff, the working-space JSON after PwCs is `{}`.
*top.get_mut(cpid).ok_or_else(|| tpl("cpid"))? = Chunk::data(*b"cpid", vec![0xffu8; 16]);
let pw = header(top, b"PwCs")?;
let json = top.get_mut(pw.saturating_add(1)).filter(|c| c.is(b"Utf8")).ok_or_else(|| tpl("template without the working-space JSON"))?;
*json = Chunk::data(*b"Utf8", b"{}".to_vec());
}
Ok(())
}
+827
View File
@@ -0,0 +1,827 @@
//! Shape layers (`docs/aep-format.md` 3.9; cases 238-242, 451-471, 519, 707-710, 731, 851-857):
//! groups (nested), rectangle, ellipse, polystar and freeform paths, fills, strokes, gradient
//! fills and strokes, trim paths, round corners, merge paths, offset paths and repeaters, the
//! group transform, with keys and expressions on their properties.
//!
//! The layer block is the shape layer of 519 with its contents removed; every item is the item
//! of 519 or 731 (all at After Effects' defaults, no value records) or the path item of 240, and
//! every property that differs from After Effects' default (or carries keys or an expression)
//! gets a value record, in After Effects' order (a record only for a non-default value, P.5):
//! sizes and positions in pixels relative to the layer, colours `[A, R, G, B]` 0..255,
//! opacities, percentages and the group scale in percent, popups 1-based (fill rule 455, line
//! cap / join 239, trim type 469, polystar type 331, merge type 707, offset line join 710),
//! angles in degrees. A record is the record After Effects wrote for the property in a
//! one-change case, else the record of its property's type (R46): over the corpus every shape
//! value record of a type has the same bytes but for its match name, the time scale and, for
//! sliders, the slider range in `tdum` / `tduM` (0..100 for every slider but Skew -85..85 and
//! Highlight Length -100..100; sizes and scales -32 000..32 000). A keyed record clears `tdb4`
//! bit 0 of byte 5, sets byte 68 and holds the key list (851-855, 857, 209): one-component and
//! two-component sizes plain records (48 / 88 bytes), points spatial records (104 bytes),
//! colours the colour records of effects (152 bytes). An expression is stored as on the
//! Transform properties (856, R15).
use crate::Chunk;
use effectcraft_keyframe::{Gradient, Interp, Keyframe, Value};
use effectcraft_project::{Node, PropGroup, Property};
use crate::export::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};
/// The deepest group nesting written.
const MAX_DEPTH: usize = 16;
/// A property's value in the file's units: the static value, the keys (layer time) and the
/// expression with its enable switch.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RecVal {
pub value: Vec<f64>,
pub keys: Vec<KeyPlan>,
pub expr: Option<(String, bool)>,
}
type Records = Vec<(&'static str, RecVal)>;
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum ShItem {
Group {
name: String,
items: Vec<ShItem>,
transform: Records,
},
/// Any other item but a path: the item's match name, name, value records and the records of
/// its sub-groups (a repeater's transform).
Simple {
kind: &'static str,
name: String,
records: Records,
subs: Vec<(&'static str, Records)>,
},
Path {
name: String,
shape: ShapePlan,
},
/// An item switched off (its eye): written with bit 0 of its group's `tdsb` cleared.
Off(Box<ShItem>),
}
/// The prototypes, by match name.
pub(crate) struct ShapeProtos {
/// The shape layer's block (519) with an empty `ADBE Root Vectors Group`.
pub block: Vec<Chunk<'static>>,
/// Item nodes (`tdmn` + node) at their defaults.
pub items: Vec<(String, [Chunk<'static>; 2])>,
/// Value records (`tdmn` + `tdbs`) by match name.
pub records: Vec<(String, [Chunk<'static>; 2])>,
/// The key list (`LIST list`) of a keyed property, whose header is rewritten.
pub key_list: Chunk<'static>,
}
/// How a shape property is stored.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Layout {
/// One component (sliders, angles, popups): plain keys of 48 bytes.
One,
/// A size or scale of two or three components: plain keys of 88 / 128 bytes.
Size,
/// A point: spatial keys of 104 bytes (853; 128 bytes for a 3D point).
Point,
/// A colour: the 152-byte colour keys (854).
Color,
/// A popup (keys not sampled).
Popup,
}
/// The record whose layout a property takes, the slider range its record repeats in `tdum` /
/// `tduM` (R46), and the key layout.
#[derive(Clone, Copy)]
struct RecKind {
proto: &'static str,
range: Option<(f64, f64)>,
layout: Layout,
}
const SLIDER: RecKind = RecKind { proto: "ADBE Vector Fill Opacity", range: Some((0.0, 100.0)), layout: Layout::One };
const ANGLE: RecKind = RecKind { proto: "ADBE Vector Rotation", range: None, layout: Layout::One };
const POPUP: RecKind = RecKind { proto: "ADBE Vector Fill Rule", range: None, layout: Layout::Popup };
const POINT: RecKind = RecKind { proto: "ADBE Vector Ellipse Position", range: None, layout: Layout::Point };
const SIZE: RecKind = RecKind { proto: "ADBE Vector Scale", range: Some((-32_000.0, 32_000.0)), layout: Layout::Size };
const COLOR: RecKind = RecKind { proto: "ADBE Vector Fill Color", range: None, layout: Layout::Color };
/// Every property the exporter writes, in After Effects' order within an item (455, 464, 239,
/// 331, 332, 828, 709), with its record type (sampled: 451-471, 238-242, 331, 332, 468, 469,
/// 473-477, 707-710, 828; Offset Paths' Miter Limit, the Repeater's Offset, Composite, Anchor and
/// Start Opacity are not sampled and take the type of their kind, E).
const KINDS: &[(&str, RecKind)] = &[
("ADBE Vector Rect Size", SIZE),
("ADBE Vector Rect Position", POINT),
("ADBE Vector Rect Roundness", SLIDER),
("ADBE Vector Ellipse Size", SIZE),
("ADBE Vector Ellipse Position", POINT),
("ADBE Vector Star Type", POPUP),
("ADBE Vector Star Points", SLIDER),
("ADBE Vector Star Position", POINT),
("ADBE Vector Star Rotation", ANGLE),
("ADBE Vector Star Inner Radius", SLIDER),
("ADBE Vector Star Outer Radius", SLIDER),
("ADBE Vector Star Inner Roundess", SLIDER),
("ADBE Vector Star Outer Roundess", SLIDER),
("ADBE Vector Fill Rule", POPUP),
("ADBE Vector Grad Type", POPUP),
("ADBE Vector Grad Start Pt", POINT),
("ADBE Vector Grad End Pt", POINT),
("ADBE Vector Grad HiLite Length", RecKind { proto: "ADBE Vector Fill Opacity", range: Some((-100.0, 100.0)), layout: Layout::One }),
("ADBE Vector Grad HiLite Angle", ANGLE),
("ADBE Vector Fill Color", COLOR),
("ADBE Vector Fill Opacity", SLIDER),
("ADBE Vector Stroke Color", COLOR),
("ADBE Vector Stroke Opacity", SLIDER),
("ADBE Vector Stroke Width", SLIDER),
("ADBE Vector Stroke Line Cap", POPUP),
("ADBE Vector Stroke Line Join", POPUP),
("ADBE Vector Stroke Miter Limit", SLIDER),
("ADBE Vector Trim Start", SLIDER),
("ADBE Vector Trim End", SLIDER),
("ADBE Vector Trim Offset", ANGLE),
("ADBE Vector Trim Type", POPUP),
("ADBE Vector RoundCorner Radius", SLIDER),
("ADBE Vector Merge Type", POPUP),
("ADBE Vector Offset Amount", SLIDER),
("ADBE Vector Offset Line Join", POPUP),
("ADBE Vector Offset Miter Limit", SLIDER),
("ADBE Vector Offset Copies", SLIDER),
("ADBE Vector Offset Copy Offset", SLIDER),
("ADBE Vector Repeater Copies", SLIDER),
("ADBE Vector Repeater Offset", SLIDER),
("ADBE Vector Repeater Order", POPUP),
("ADBE Vector Repeater Anchor", POINT),
("ADBE Vector Repeater Position", POINT),
("ADBE Vector Repeater Scale", SIZE),
("ADBE Vector Repeater Rotation", ANGLE),
("ADBE Vector Repeater Opacity 1", SLIDER),
("ADBE Vector Repeater Opacity 2", SLIDER),
("ADBE Vector Anchor", POINT),
("ADBE Vector Position", POINT),
("ADBE Vector Scale", SIZE),
// Skew has its own record (460: a slider of the angle layout, -85..85).
("ADBE Vector Skew", RecKind { proto: "ADBE Vector Skew", range: Some((-85.0, 85.0)), layout: Layout::One }),
("ADBE Vector Skew Axis", ANGLE),
("ADBE Vector Rotation", ANGLE),
("ADBE Vector Group Opacity", SLIDER),
];
fn kind_of(name: &str) -> Option<RecKind> {
KINDS.iter().find(|(n, _)| *n == name).map(|(_, k)| *k)
}
impl ShapeProtos {
fn item(&self, name: &str) -> R<[Chunk<'static>; 2]> {
self.items.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()).ok_or_else(|| tpl("shape item prototype missing"))
}
/// The static value record of `name`: the one After Effects wrote for it in a one-change
/// case, else the record of its type (R46).
fn record(&self, name: &'static str) -> R<[Chunk<'static>; 2]> {
if let Some((_, c)) = self.records.iter().find(|(n, _)| n == name) {
return Ok(c.clone());
}
let kind = kind_of(name).ok_or_else(|| tpl("shape property without a record type"))?;
let [_, mut node] = self.records.iter().find(|(n, _)| n == kind.proto).map(|(_, c)| c.clone()).ok_or_else(|| tpl("shape record prototype missing"))?;
if let Some((lo, hi)) = kind.range {
put_f64(child_data(&mut node, b"tdum")?, 0, lo)?;
put_f64(child_data(&mut node, b"tduM")?, 0, hi)?;
}
Ok([crate::export::camlight::tdmn_chunk(name), node])
}
}
fn finite(v: &[f64]) -> bool {
v.iter().all(|x| x.is_finite() && x.abs() <= 1e9)
}
/// The stored components of a value.
pub(crate) type Conv = fn(&Value) -> Option<Vec<f64>>;
pub(crate) fn c_scalar(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Scalar(s) => Some(vec![*s]),
_ => None,
}
}
/// Offset Paths' Copy Offset: EffectCraft's value + 1 (826-828).
fn c_copy_offset(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Scalar(s) => Some(vec![*s + 1.0]),
_ => None,
}
}
pub(crate) fn c_point(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Vec2(p) => Some(p.to_vec()),
Value::Vec3(p) => Some(vec![p[0], p[1]]),
_ => None,
}
}
/// A colour as the file stores it (alpha 255, then red, green and blue from 0 to 255). A channel
/// outside 0 to 1 is written as the nearest limit, as for lights (`rec_value` reports it); a
/// value that is not finite stays so and is reported as invalid.
pub(crate) fn c_color(v: &Value) -> Option<Vec<f64>> {
let ch = |x: f64| if x.is_finite() { x.clamp(0.0, 1.0) * 255.0 } else { x };
match v {
Value::Color(c) => Some(vec![255.0, ch(c[0]), ch(c[1]), ch(c[2])]),
_ => None,
}
}
/// Whether a colour that is written has a channel outside 0 to 1: the keys of an animated
/// property (its static value is not written then), else the static value.
fn colour_beyond(p: &Property, keyed: bool) -> bool {
let beyond = |v: &Value| matches!(v, Value::Color(c) if c.iter().take(3).any(|x| x.is_finite() && !(0.0..=1.0).contains(x)));
if keyed { p.keys.iter().any(|k| beyond(&k.value)) } else { beyond(&p.value) }
}
/// Whether a colour that is written has an alpha other than 1 (a colour property of After Effects
/// has no alpha): the keys of an animated property, else the static value.
fn colour_alpha(p: &Property, keyed: bool) -> bool {
let alpha = |v: &Value| matches!(v, Value::Color(c) if c[3].is_finite() && (c[3] - 1.0).abs() > 1e-9);
if keyed { p.keys.iter().any(|k| alpha(&k.value)) } else { alpha(&p.value) }
}
/// A popup stored 1-based (EffectCraft's items in After Effects' order).
pub(crate) fn c_popup(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Enum(e) => Some(vec![f64::from(*e) + 1.0]),
_ => None,
}
}
/// What planning a shape layer needs: the layer's time base and the report.
pub(crate) struct ShCx<'a> {
pub cp: &'a CompPlan,
pub col: &'a mut Collector,
}
/// The keys of `p` in the file's units.
fn plan_keys(p: &Property, conv: Conv, layout: Layout, what: &str, cx: &mut ShCx<'_>) -> Vec<KeyPlan> {
let 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 all: Vec<Keyframe> = timed.iter().map(|(_, k)| (*k).clone()).collect();
let mut out = Vec::with_capacity(timed.len());
let beyond = std::cell::Cell::new(false);
for (i, (u, k)) in timed.iter().enumerate() {
let Ok(time) = i32::try_from(*u) else {
cx.col.lose(LossCategory::InvalidValues, format!("{what}: key time out of range, key dropped"));
continue;
};
let Some(value) = conv(&k.value).filter(|v| finite(v)) else {
cx.col.lose(LossCategory::InvalidValues, format!("{what}: a key value that cannot be stored, key dropped"));
continue;
};
let mut side = |interp: Interp| -> u8 {
match interp {
Interp::Linear => 1,
Interp::Hold => 3,
// The ease of colour keys is sampled only as speed 0 / influence 0 (598).
Interp::Bezier if layout == Layout::Color => {
cx.col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: bezier ease of a colour key is written as linear (not sampled)"));
1
}
Interp::Bezier => 2,
}
};
let (in_i, out_i) = (side(k.in_interp), side(k.out_interp));
let slots = if layout == Layout::Size { value.len().max(1) } else { 1 };
let ease = |eases: &[effectcraft_keyframe::Ease], on: bool| -> Vec<EaseSlot> {
(0..slots)
.map(|s| {
if !on {
return EaseSlot::default();
}
let e = crate::export::plan::key_ease(eases, s);
let speed = if e.speed.is_finite() && e.speed.abs() <= 1e9 {
e.speed
} else {
beyond.set(true);
0.0
};
let influence = if e.influence.is_finite() { e.influence.clamp(0.001, 1.0) } else { 1.0 / 3.0 };
EaseSlot { speed, influence }
})
.collect()
};
let (mut tin, mut tout) = if layout == Layout::Point { effectcraft_keyframe::spatial_tangents(&all, i) } else { ([0.0; 3], [0.0; 3]) };
for t in tin.iter_mut().chain(tout.iter_mut()) {
if !t.is_finite() || t.abs() > 1e9 {
beyond.set(true);
*t = 0.0;
}
}
if k.roving {
cx.col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a roving key is written as a normal key"));
}
out.push(KeyPlan {
time,
value,
in_interp: in_i,
out_interp: out_i,
in_ease: ease(&k.in_ease, in_i == 2),
out_ease: ease(&k.out_ease, out_i == 2),
spatial_in: tin,
spatial_out: tout,
spatial_auto: k.spatial_auto,
roving: false,
label: k.label.min(16),
});
}
cx.col.exported.keyframes = cx.col.exported.keyframes.saturating_add(out.len());
crate::export::plan::report_beyond(beyond.get(), what, cx.col);
out
}
/// A property's value, keys and expression in the file's units; `None` when it needs no record:
/// at `default` (when given) with no keys and no expression. Keys on a popup are not sampled:
/// the first key's value is written (reported in `category`).
pub(crate) fn rec_value(
p: &Property,
conv: Conv,
layout: Layout,
default: Option<&[f64]>,
w: &str,
category: LossCategory,
cx: &mut ShCx<'_>,
) -> Option<RecVal> {
let expr = p.expr.as_ref().filter(|e| !e.text.is_empty()).map(|e| (e.text.clone(), e.enabled));
if expr.is_some() {
cx.col.exported.expressions = cx.col.exported.expressions.saturating_add(1);
}
let Some(value) = conv(&p.value) else {
cx.col.lose(category, format!("{w} holds a value of another type, not written"));
return None;
};
if !finite(&value) {
cx.col.lose(LossCategory::InvalidValues, format!("{w} is not a valid number (the default is written)"));
return None;
}
let differs = |v: &[f64]| default.is_none_or(|d| v.iter().zip(d).any(|(a, b)| (a - b).abs() > 1e-9));
let mut keys = Vec::new();
if !p.keys.is_empty() {
if layout == Layout::Popup {
cx.col.lose(category, format!("{w}: keys on a popup are not written (not sampled), the first key's value is written"));
let first = p.keys.first().and_then(|k| conv(&k.value)).unwrap_or(value);
return (differs(&first) || expr.is_some()).then_some(RecVal { value: first, keys: Vec::new(), expr });
}
keys = plan_keys(p, conv, layout, w, cx);
}
// Shape and text animator colours alike (both are planned here).
if layout == Layout::Color && colour_beyond(p, !keys.is_empty()) {
cx.col.lose(category, format!("{w}: a colour channel outside 0 to 1 is written as the nearest limit"));
}
if layout == Layout::Color && colour_alpha(p, !keys.is_empty()) {
cx.col.lose(category, format!("{w}: the colour's alpha is not written (After Effects colours have none; written opaque)"));
}
if keys.is_empty() && expr.is_none() && !differs(&value) {
return None;
}
let value = keys.first().map(|k| k.value.clone()).unwrap_or(value);
Some(RecVal { value, keys, expr })
}
/// Plans property `id` of `g` as the record `name` (`names`: `(name, id)`) unless it is at After
/// Effects' default with no keys and no expression.
fn rec(out: &mut Records, g: &PropGroup, names: (&'static str, &str), conv: Conv, default: &[f64], what: &str, cx: &mut ShCx<'_>) {
let (name, id) = names;
let Some(p) = g.get(id) else { return };
let Some(kind) = kind_of(name) else { return };
let w = format!("{what}: {name}");
if let Some(v) = rec_value(p, conv, kind.layout, Some(default), &w, LossCategory::ShapeLayers, cx) {
out.push((name, v));
}
}
fn en(g: &PropGroup, id: &str) -> Option<u32> {
match g.get(id).map(|p| &p.value) {
Some(Value::Enum(e)) => Some(*e),
_ => None,
}
}
/// Opacity, width, cap, join and miter limit of a stroke or gradient stroke; dashes, taper and
/// wave are reported when they hold values.
fn stroke_common(r: &mut Records, g: &PropGroup, w: &str, cx: &mut ShCx<'_>) {
rec(r, g, ("ADBE Vector Stroke Opacity", "opacity"), c_scalar, &[100.0], w, cx);
rec(r, g, ("ADBE Vector Stroke Width", "width"), c_scalar, &[2.0], w, cx);
rec(r, g, ("ADBE Vector Stroke Line Cap", "cap"), c_popup, &[1.0], w, cx);
rec(r, g, ("ADBE Vector Stroke Line Join", "join"), c_popup, &[1.0], w, cx);
rec(r, g, ("ADBE Vector Stroke Miter Limit", "miter"), c_scalar, &[4.0], w, cx);
// Dashes, a taper or a wave change the stroke (After Effects' defaults: no dash, no taper
// length, no wave amount).
let nonzero = |sub: &str, ids: &[&str]| {
g.sub(sub).is_some_and(|s| s.props().any(|p| ids.iter().any(|i| p.match_id.starts_with(i)) && matches!(p.value, Value::Scalar(v) if v != 0.0)))
};
if nonzero("dashes", &["dash", "gap"]) || nonzero("taper", &["startLength", "endLength"]) || nonzero("wave", &["amount"]) {
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: dashes, taper and wave of a stroke are not written"));
}
}
/// The gradient part of a gradient fill or stroke: type, start, end, highlight; the colour
/// stops are not decoded (only the default white to black is written).
fn gradient(r: &mut Records, g: &PropGroup, w: &str, cx: &mut ShCx<'_>) {
rec(r, g, ("ADBE Vector Grad Type", "type"), c_popup, &[1.0], w, cx);
rec(r, g, ("ADBE Vector Grad Start Pt", "start"), c_point, &[0.0, 0.0], w, cx);
rec(r, g, ("ADBE Vector Grad End Pt", "end"), c_point, &[100.0, 0.0], w, cx);
rec(r, g, ("ADBE Vector Grad HiLite Length", "highlightLength"), c_scalar, &[0.0], w, cx);
rec(r, g, ("ADBE Vector Grad HiLite Angle", "highlightAngle"), c_scalar, &[0.0], w, cx);
if let Some(p) = g.get("colors")
&& (matches!(&p.value, Value::Gradient(gr) if *gr != Gradient::default()) || !p.keys.is_empty() || p.has_expression())
{
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: the colour stops of a gradient are not written (not decoded), white to black"));
}
}
/// The items of a `contents` group, top first, in the file's terms.
pub(crate) fn plan_contents(contents: &PropGroup, what: &str, depth: usize, cx: &mut ShCx<'_>) -> Vec<ShItem> {
let mut out = Vec::new();
if depth > MAX_DEPTH {
cx.col.lose(LossCategory::ShapeLayers, format!("{what}: shape groups nested deeper than {MAX_DEPTH} levels are not written"));
return out;
}
for node in &contents.children {
let Node::Group(g) = node else { continue };
let w = format!("{what} / {}", g.name);
// A switched-off item keeps its node with bit 0 of its group flags cleared (986, 987).
let wrap = |item: ShItem| if g.enabled { item } else { ShItem::Off(Box::new(item)) };
if en(g, "direction").is_some_and(|d| d != 0) {
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: the path direction is not written"));
}
// A repeater writes its `composite` as Repeater Order.
let composite_lost = g.match_id != "repeater" && en(g, "composite").is_some_and(|d| d != 0);
if en(g, "blend").is_some_and(|d| d != 0) || composite_lost {
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: blend mode and composite order are not written"));
}
let mut r = Vec::new();
let mut subs = Vec::new();
let kind = match g.match_id.as_str() {
"group" => {
let items = g.sub("contents").map(|c| plan_contents(c, &w, depth + 1, cx)).unwrap_or_default();
let mut transform = Vec::new();
if let Some(t) = g.sub("transform") {
rec(&mut transform, t, ("ADBE Vector Anchor", "anchor"), c_point, &[0.0, 0.0], &w, cx);
rec(&mut transform, t, ("ADBE Vector Position", "position"), c_point, &[0.0, 0.0], &w, cx);
rec(&mut transform, t, ("ADBE Vector Scale", "scale"), c_point, &[100.0, 100.0], &w, cx);
rec(&mut transform, t, ("ADBE Vector Skew", "skew"), c_scalar, &[0.0], &w, cx);
rec(&mut transform, t, ("ADBE Vector Skew Axis", "skewAxis"), c_scalar, &[0.0], &w, cx);
rec(&mut transform, t, ("ADBE Vector Rotation", "rotation"), c_scalar, &[0.0], &w, cx);
rec(&mut transform, t, ("ADBE Vector Group Opacity", "opacity"), c_scalar, &[100.0], &w, cx);
}
out.push(wrap(ShItem::Group { name: g.name.clone(), items, transform }));
continue;
}
"path" => {
let p = g.get("path");
if p.is_some_and(|p| !p.keys.is_empty() || p.has_expression()) {
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: keys or an expression on the path (the static path is written)"));
}
match p.map(|p| &p.value) {
Some(Value::Path(sp)) => match crate::export::masks::shape_plan(sp, (1, 1)) {
Ok(shape) => out.push(wrap(ShItem::Path { name: g.name.clone(), shape })),
Err(why) => cx.col.lose(LossCategory::ShapeLayers, format!("{w}: the path is not written: {why}")),
},
_ => cx.col.lose(LossCategory::ShapeLayers, format!("{w}: a path item without a path is not written")),
}
continue;
}
"rect" => {
rec(&mut r, g, ("ADBE Vector Rect Size", "size"), c_point, &[100.0, 100.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Rect Position", "position"), c_point, &[0.0, 0.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Rect Roundness", "roundness"), c_scalar, &[0.0], &w, cx);
if g.get("perCorner").is_some_and(|p| p.value == Value::Bool(true) || !p.keys.is_empty() || p.has_expression()) {
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: per-corner roundness is not written (the uniform Roundness is)"));
}
"ADBE Vector Shape - Rect"
}
"ellipse" => {
rec(&mut r, g, ("ADBE Vector Ellipse Size", "size"), c_point, &[100.0, 100.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Ellipse Position", "position"), c_point, &[0.0, 0.0], &w, cx);
"ADBE Vector Shape - Ellipse"
}
// Polystar (104, 331, 473-477): After Effects' defaults are a 5-point star with radii
// 100 / 50 (519).
"star" => {
rec(&mut r, g, ("ADBE Vector Star Type", "type"), c_popup, &[1.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Star Points", "points"), c_scalar, &[5.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Star Position", "position"), c_point, &[0.0, 0.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Star Rotation", "rotation"), c_scalar, &[0.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Star Inner Radius", "innerRadius"), c_scalar, &[50.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Star Outer Radius", "outerRadius"), c_scalar, &[100.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Star Inner Roundess", "innerRoundness"), c_scalar, &[0.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Star Outer Roundess", "outerRoundness"), c_scalar, &[0.0], &w, cx);
"ADBE Vector Shape - Star"
}
"fill" => {
rec(&mut r, g, ("ADBE Vector Fill Rule", "rule"), c_popup, &[1.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Fill Color", "color"), c_color, &[255.0, 255.0, 0.0, 0.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Fill Opacity", "opacity"), c_scalar, &[100.0], &w, cx);
"ADBE Vector Graphic - Fill"
}
"stroke" => {
rec(&mut r, g, ("ADBE Vector Stroke Color", "color"), c_color, &[255.0, 255.0, 255.0, 255.0], &w, cx);
stroke_common(&mut r, g, &w, cx);
"ADBE Vector Graphic - Stroke"
}
"gfill" => {
rec(&mut r, g, ("ADBE Vector Fill Rule", "rule"), c_popup, &[1.0], &w, cx);
gradient(&mut r, g, &w, cx);
rec(&mut r, g, ("ADBE Vector Fill Opacity", "opacity"), c_scalar, &[100.0], &w, cx);
"ADBE Vector Graphic - G-Fill"
}
"gstroke" => {
gradient(&mut r, g, &w, cx);
stroke_common(&mut r, g, &w, cx);
"ADBE Vector Graphic - G-Stroke"
}
// Trim Paths (101, 465-469, 851-856).
"trim" => {
rec(&mut r, g, ("ADBE Vector Trim Start", "start"), c_scalar, &[0.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Trim End", "end"), c_scalar, &[100.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Trim Offset", "offset"), c_scalar, &[0.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Trim Type", "mode"), c_popup, &[1.0], &w, cx);
"ADBE Vector Filter - Trim"
}
// Round Corners (238; default radius 10, 519).
"round" => {
rec(&mut r, g, ("ADBE Vector RoundCorner Radius", "radius"), c_scalar, &[10.0], &w, cx);
"ADBE Vector Filter - RC"
}
// Merge Paths (707, 708, 731).
"merge" => {
rec(&mut r, g, ("ADBE Vector Merge Type", "mode"), c_popup, &[1.0], &w, cx);
"ADBE Vector Filter - Merge"
}
// Offset Paths (710, 828; defaults 731: amount 10, miter 4, one copy, copy offset 1).
"offset" => {
rec(&mut r, g, ("ADBE Vector Offset Amount", "amount"), c_scalar, &[10.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Offset Line Join", "join"), c_popup, &[1.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Offset Miter Limit", "miter"), c_scalar, &[4.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Offset Copies", "copies"), c_scalar, &[1.0], &w, cx);
// EffectCraft offsets copy i by Amount x (i + 1 + copyOffset), After Effects by
// Amount x (i + Copy Offset) (826-828): Copy Offset = copyOffset + 1, the
// importer's inverse.
rec(&mut r, g, ("ADBE Vector Offset Copy Offset", "copyOffset"), c_copy_offset, &[1.0], &w, cx);
if g.get("copyOffset").is_some_and(|p| p.has_expression()) {
cx.col.lose(
LossCategory::ShapeLayers,
format!("{w}: the expression on Offset Paths' Copy Offset is written as it is (After Effects' value is 1 more than EffectCraft's)"),
);
}
"ADBE Vector Filter - Offset"
}
// Repeater (102, 709; defaults 731: one copy, offset 0, below, identity transform).
"repeater" => {
rec(&mut r, g, ("ADBE Vector Repeater Copies", "copies"), c_scalar, &[1.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Repeater Offset", "offset"), c_scalar, &[0.0], &w, cx);
rec(&mut r, g, ("ADBE Vector Repeater Order", "composite"), c_popup, &[1.0], &w, cx);
let mut t = Vec::new();
if let Some(tr) = g.sub("transform") {
rec(&mut t, tr, ("ADBE Vector Repeater Anchor", "anchor"), c_point, &[0.0, 0.0], &w, cx);
rec(&mut t, tr, ("ADBE Vector Repeater Position", "position"), c_point, &[0.0, 0.0], &w, cx);
rec(&mut t, tr, ("ADBE Vector Repeater Scale", "scale"), c_point, &[100.0, 100.0], &w, cx);
rec(&mut t, tr, ("ADBE Vector Repeater Rotation", "rotation"), c_scalar, &[0.0], &w, cx);
rec(&mut t, tr, ("ADBE Vector Repeater Opacity 1", "startOpacity"), c_scalar, &[100.0], &w, cx);
rec(&mut t, tr, ("ADBE Vector Repeater Opacity 2", "endOpacity"), c_scalar, &[100.0], &w, cx);
}
subs.push(("ADBE Vector Repeater Transform", t));
"ADBE Vector Filter - Repeater"
}
other => {
cx.col.lose(LossCategory::ShapeLayers, format!("{w}: the shape item '{other}' is not written"));
continue;
}
};
out.push(wrap(ShItem::Simple { kind, name: g.name.clone(), records: r, subs }));
}
out
}
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)?;
let layout = kind_of(name).map_or(Layout::One, |k| k.layout);
build_record(m, node, layout, v, &t.key_list)
}
/// A static value record (`node`, after its `tdmn` `m`) turned into the record of `v`: its value,
/// its keys (`key_list` the list prototype) and its expression.
pub(crate) fn build_record(m: Chunk<'static>, mut node: Chunk<'static>, layout: Layout, v: &RecVal, key_list: &Chunk<'static>) -> R<[Chunk<'static>; 2]> {
if v.keys.is_empty() {
let d = child_data(&mut node, b"cdat")?;
for (i, x) in v.value.iter().enumerate() {
put_f64(d, i * 8, *x)?;
}
} else {
let n = v.value.len().max(1);
let size = match layout {
Layout::Point | Layout::Color => 56 + 24 * n,
_ => 8 + 40 * n,
};
{
let tdb4 = child_data(&mut node, b"tdb4")?;
let b5 = tdb4.get(5).copied().ok_or_else(|| tpl("short tdb4"))?;
put_u8(tdb4, 5, b5 & !0x01)?;
put_u8(tdb4, 68, 1)?;
// A keyed point or colour clears byte 79 too (853, 854; as on effects, R25).
if matches!(layout, Layout::Point | Layout::Color) {
put_u8(tdb4, 79, 0)?;
}
}
let mut 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)?,
_ => 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;
}
}
if let Some((text, enabled)) = &v.expr {
// As on the Transform properties (R15; 856).
{
let tdb4 = child_data(&mut node, b"tdb4")?;
put_u8(tdb4, 76, 1)?;
put_u8(tdb4, 77, 1)?;
put_u8(tdb4, 120, 1)?;
put_u8(tdb4, 119, u8::from(!*enabled))?;
}
let kids = kids_mut(&mut node)?;
let at = kids.iter().position(|c| c.is(b"tdum")).unwrap_or(kids.len());
kids.insert(at, Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
}
Ok([m, node])
}
/// Inserts value records into an item's `tdgp` (between its header and its sub-groups / end),
/// in the order of [`KINDS`].
fn put_records(t: &ShapeProtos, tdgp: &mut Chunk<'static>, records: &[(&'static str, RecVal)]) -> R<()> {
let kids = kids_mut(tdgp)?;
let mut at = kids.iter().position(|c| c.is(b"tdmn")).unwrap_or(kids.len());
let mut sorted: Vec<&(&'static str, RecVal)> = records.iter().collect();
sorted.sort_by_key(|(n, _)| KINDS.iter().position(|(o, _)| o == n).unwrap_or(KINDS.len()));
for (name, v) in sorted {
let [m, node] = value_record(t, name, v)?;
kids.insert(at, m);
kids.insert(at.saturating_add(1), node);
at = at.saturating_add(2);
}
Ok(())
}
/// The item nodes (`tdmn` + `tdgp` pairs) for `items`, top first.
pub(crate) fn build_items(t: &ShapeProtos, items: &[ShItem], depth: usize) -> R<Vec<Chunk<'static>>> {
let mut out = Vec::new();
if depth > MAX_DEPTH {
return Ok(out);
}
let pos = |kids: &[Chunk<'static>], n: &str| kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(n));
for item in items {
match item {
ShItem::Off(inner) => {
let mut built = build_items(t, std::slice::from_ref(inner.as_ref()), depth)?;
if let Some(node) = built.get_mut(1) {
let tdsb = child_data(node, b"tdsb")?;
let flags = tdsb.get(3).copied().ok_or_else(|| tpl("short tdsb"))?;
put_u8(tdsb, 3, flags & !1)?;
}
out.extend(built);
}
ShItem::Group { name, items, transform } => {
let [m, mut node] = t.item("ADBE Vector Group")?;
set_name(&mut node, name)?;
let children = build_items(t, items, depth + 1)?;
let kids = kids_mut(&mut node)?;
let vg = pos(kids, "ADBE Vectors Group").ok_or_else(|| tpl("group prototype without contents"))?;
let contents = kids.get_mut(vg + 1).ok_or_else(|| tpl("group prototype without contents"))?;
let ck = kids_mut(contents)?;
let end = ck.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("ADBE Group End")).unwrap_or(ck.len());
ck.splice(end..end, children);
let tg = pos(kids, "ADBE Vector Transform Group").ok_or_else(|| tpl("group prototype without transform"))?;
let tnode = kids.get_mut(tg + 1).ok_or_else(|| tpl("group prototype without transform"))?;
put_records(t, tnode, transform)?;
out.extend([m, node]);
}
ShItem::Simple { kind, name, records, subs } => {
let [m, mut node] = t.item(kind)?;
set_name(&mut node, name)?;
for (sub, recs) in subs {
if recs.is_empty() {
continue;
}
let kids = kids_mut(&mut node)?;
let at = pos(kids, sub).ok_or_else(|| tpl("shape item prototype without its sub-group"))?;
let group = kids.get_mut(at + 1).ok_or_else(|| tpl("shape item prototype without its sub-group"))?;
put_records(t, group, recs)?;
}
put_records(t, &mut node, records)?;
out.extend([m, node]);
}
ShItem::Path { name, shape } => {
let [m, mut node] = t.item("ADBE Vector Shape - Group")?;
set_name(&mut node, name)?;
let kids = kids_mut(&mut node)?;
let oms = kids.iter_mut().find(|c| c.is_list(b"om-s")).ok_or_else(|| tpl("path prototype without its shape"))?;
let omks = list_mut(oms, b"omks")?;
let proto = kids_mut(omks)?.iter().find(|c| c.is_list(b"shap")).cloned().ok_or_else(|| tpl("path prototype without a shape"))?;
*kids_mut(omks)? = vec![crate::export::masks::build_shap(&proto, shape)?];
out.extend([m, node]);
}
}
}
Ok(out)
}
/// The item's user name (`tdsn/Utf8`).
fn set_name(node: &mut Chunk<'static>, name: &str) -> R<()> {
let kids = kids_mut(node)?;
let tdsn = kids.iter_mut().find(|c| c.is(b"tdsn")).ok_or_else(|| tpl("shape item without a name"))?;
set_utf8(tdsn, name)
}
/// Fills the layer's `ADBE Root Vectors Group` with `items`.
pub(crate) fn put_contents(layr: &mut Chunk<'static>, t: &ShapeProtos, items: &[ShItem]) -> R<()> {
let built = build_items(t, items, 0)?;
let root = list_mut(layr, b"tdgp")?;
let kids = kids_mut(root)?;
let at = kids
.iter()
.position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some("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());
rk.splice(end..end, built);
Ok(())
}
+159
View File
@@ -0,0 +1,159 @@
//! The layer, item and project skeletons the exporter fills, built in code (aep-format.md 3.1-3.4):
//! only the property groups the exporter writes into, the default records it edits, and the small
//! fixed records each layer carries. After Effects adds the groups that are left out (read-back
//! e1-sparse).
use crate::Chunk;
use crate::export::synth::{KeyTemplate, NO_NAME, RecSpec, class, tdbs, tdmn, 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"));
[tdmn(name), Chunk::list(*b"tdgp", body)]
}
/// The seven records that follow a layer or item block (`fvdv` 3, the others zero; the same in
/// every sample, meaning not decoded).
pub(crate) fn f_records() -> Vec<Chunk<'static>> {
vec![
Chunk::data(*b"fvdv", 3u32.to_be_bytes().to_vec()),
Chunk::data(*b"fiop", vec![0]),
Chunk::data(*b"ftts", vec![0; 4]),
Chunk::data(*b"foac", vec![0]),
Chunk::data(*b"fiac", vec![0]),
Chunk::data(*b"fipc", vec![0; 2]),
Chunk::data(*b"fifl", vec![0; 4]),
]
}
/// The layer styles in the order After Effects keeps their switch groups (950).
const STYLE_ORDER: [&str; 10] =
["dropShadow", "innerShadow", "outerGlow", "innerGlow", "bevelEmboss", "chromeFX", "solidFill", "gradientFill", "patternFill", "frameFX"];
/// The empty `ADBE Layer Styles` group (state 3), Blending Options with the advanced group, and
/// the switch group of every style (state 2: not applied), for `styles::put_styles` to fill.
pub(crate) fn layer_styles() -> [Chunk<'static>; 2] {
let mut kids: Vec<Chunk<'static>> = group("ADBE Blend Options Group", 3, group("ADBE Adv Blend Group", 1, Vec::new()).into()).into();
for s in STYLE_ORDER {
kids.extend(group(&format!("{s}/enabled"), 2, Vec::new()));
}
group("ADBE Layer Styles", 3, kids)
}
/// The inert Time Remapping record every layer has (`tdsb` 3, value 0, the maximum written per
/// layer: aep-format.md 3.4).
fn time_remap() -> Chunk<'static> {
let spec = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: Some((0.0, 0.0)), byte5: None };
let mut rec = tdbs(&spec, false, 25_600);
if let Some(state) = rec.children_mut().iter_mut().find(|c| c.is(b"tdsb")) {
*state = Chunk::data(*b"tdsb", 3u32.to_be_bytes().to_vec());
}
rec
}
/// The block of an AV layer (solid, footage, precomposition): `Layr` (a zero `ldta` the exporter
/// fills with the decoded fields, read-back t-zldta; the name; the property tree with Time
/// Remapping, an empty Transform group and the layer styles), `Ewst` and the f-records.
pub(crate) fn av_layer() -> Vec<Chunk<'static>> {
let mut root = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(""), tdmn("ADBE Time Remapping"), time_remap()];
root.extend(group("ADBE Transform Group", 1, crate::export::tree_spec::build(crate::export::tree_defs::AV_TRANSFORM)));
root.extend(layer_styles());
root.push(tdmn("ADBE Group End"));
let layr = Chunk::list(
*b"Layr",
vec![Chunk::data(*b"ldta", vec![0; 164]), Chunk::data(*b"Utf8", Vec::new()), Chunk::list(*b"tdgp", root), crate::export::base::guides()],
);
let mut out = vec![layr, Chunk::list(*b"Ewst", Vec::new())];
// Two sets of f-records follow every layer (000).
out.extend(f_records());
out.extend(f_records());
out
}
/// The block of a layer whose property tree is `nodes` (cameras, lights, shapes: `tree_defs`),
/// with a zero `ldta`, the guides, `Ewst` and the f-records.
pub(crate) fn layer_block(nodes: &[crate::export::tree_spec::Node]) -> Vec<Chunk<'static>> {
let mut root = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn("")];
root.extend(crate::export::tree_spec::build(nodes));
root.push(tdmn("ADBE Group End"));
let layr = Chunk::list(
*b"Layr",
vec![Chunk::data(*b"ldta", vec![0; 164]), Chunk::data(*b"Utf8", Vec::new()), Chunk::list(*b"tdgp", root), crate::export::base::guides()],
);
let mut out = vec![layr, Chunk::list(*b"Ewst", Vec::new())];
// Two sets of f-records follow every layer (000).
out.extend(f_records());
out.extend(f_records());
out
}
/// The Source Text record (`btds/tdbs`, 110): one component, class `0x00010004`, a 4-byte zero
/// `cdat`.
const SOURCE_TEXT: crate::export::tree_spec::Rec = crate::export::tree_spec::Rec {
state: 1,
label: NO_NAME,
dims: 1,
template: 0,
class: class::EFFECT_CHOICE,
byte5: 0x01,
header: &[],
cdat_len: 4,
cdat: &[],
key_size: 0,
limits: None,
tdpi: None,
};
/// The block of a text layer (110, 245): `ADBE Text Properties` with the text document (the
/// Source Text record, the document `doc` as `LIST btdk`, and `btgu` with the document's id and
/// a zero one), the empty Path and More Options groups; the inert Transform records and the layer
/// styles; a zero `ldta`, the guides, `Ewst` and the f-records.
pub(crate) fn text_layer(doc: &[u8]) -> Vec<Chunk<'static>> {
use crate::export::tree_spec::{Node, build};
let btdk = Chunk { id: *b"LIST", body: crate::Body::OpaqueList { list_type: *b"btdk", data: doc.to_vec().into() }, pad: None };
// The record without its match name (`build` gives the pair).
let mut btds_kids: Vec<Chunk<'static>> = build(&[Node::R("ADBE Text Document", SOURCE_TEXT)]).into_iter().filter(|c| c.is_list(b"tdbs")).collect();
btds_kids.push(btdk);
let btgu = Chunk::list(*b"btgu", vec![Chunk::data(*b"pgui", vec![0; 16]), Chunk::data(*b"pgui", vec![0; 16])]);
let mut props = vec![tdmn("ADBE Text Document"), Chunk::list(*b"btds", btds_kids), btgu];
props.extend(group("ADBE Text Path Options", 1, Vec::new()));
props.extend(group("ADBE Text More Options", 1, Vec::new()));
let mut root = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn("")];
root.extend(group("ADBE Text Properties", 1, props));
root.extend(group("ADBE Transform Group", 1, crate::export::tree_spec::build(crate::export::tree_defs::AV_TRANSFORM)));
root.extend(layer_styles());
root.push(tdmn("ADBE Group End"));
let layr = Chunk::list(
*b"Layr",
vec![Chunk::data(*b"ldta", vec![0; 164]), Chunk::data(*b"Utf8", Vec::new()), Chunk::list(*b"tdgp", root), crate::export::base::guides()],
);
let mut out = vec![layr, Chunk::list(*b"Ewst", Vec::new())];
out.extend(f_records());
out.extend(f_records());
out
}
/// `tdmn` + node pairs of `nodes`, by match name.
pub(crate) fn pairs(nodes: &[crate::export::tree_spec::Node]) -> Vec<(String, [Chunk<'static>; 2])> {
let mut out = Vec::new();
let mut it = crate::export::tree_spec::build(nodes).into_iter();
while let (Some(m), Some(n)) = (it.next(), it.next()) {
let name = String::from_utf8_lossy(m.bytes().unwrap_or_default().split(|b| *b == 0).next().unwrap_or_default()).into_owned();
out.push((name, [m, n]));
}
out
}
/// The marker group (`tdmn ADBE Marker` + `LIST mrst`, aep-format.md 3.11) for
/// `markers::build`: the marker property as a keyed one-component record (class `0x00010004`,
/// 16-byte keys, 249) and `mrky` with one `Nmrd` whose header (`NmHd`) and strings are written
/// per marker.
pub(crate) fn marker_group() -> Vec<Chunk<'static>> {
let spec = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_CHOICE, limits: None, byte5: None };
let record = tdbs(&spec, true, 25_600);
let nmrd = Chunk::list(*b"Nmrd", vec![Chunk::data(*b"NmHd", vec![0; 20])]);
vec![tdmn("ADBE Marker"), Chunk::list(*b"mrst", vec![record, Chunk::list(*b"mrky", vec![nmrd])])]
}
+104
View File
@@ -0,0 +1,104 @@
//! The layer-style records the exporter writes, one per parameter (aep-format.md 3.12b): the
//! match name, the components, the key template (`tdb4` byte 7), the class word (`tdb4` 8..11)
//! and the limits (`tdum` / `tduM`), as After Effects shows them for each style parameter. The
//! rows were listed from our style cases (950-980) through the reader.
/// One record: match name, components, key template, class word, limits.
pub(crate) type StyleRec = (&'static str, u8, u8, u32, Option<(f64, f64)>);
const fn s(name: &'static str, dims: u8, template: u8, class: u32, limits: Option<(f64, f64)>) -> StyleRec {
(name, dims, template, class, limits)
}
#[rustfmt::skip]
pub(crate) static STYLE_RECORDS: &[StyleRec] = &[
s("ADBE B Channel Blend", 1, 0, 0xffff0004, None),
s("ADBE Blend Interior", 1, 0, 0xffff0004, None),
s("ADBE Blend Ranges", 1, 0, 0xffff0004, None),
s("ADBE G Channel Blend", 1, 0, 0xffff0004, None),
s("ADBE Global Altitude2", 1, 0, 0x0002ffff, None),
s("ADBE Global Angle2", 1, 0, 0x0002ffff, None),
s("ADBE Layer Fill Opacity2", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("ADBE R Channel Blend", 1, 0, 0xffff0004, None),
s("bevelEmboss/bevelDirection", 1, 0, 0x00010004, None),
s("bevelEmboss/bevelStyle", 1, 0, 0x00010004, None),
s("bevelEmboss/bevelTechnique", 1, 0, 0x00010004, None),
s("bevelEmboss/blur", 1, 0, 0xffffffff, Some((0.0, 250.0))),
s("bevelEmboss/highlightColor", 4, 1, 0x0002ffff, None),
s("bevelEmboss/highlightMode", 1, 0, 0x00010004, None),
s("bevelEmboss/highlightOpacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("bevelEmboss/localLightingAltitude", 1, 0, 0xffffffff, None),
s("bevelEmboss/localLightingAngle", 1, 0, 0xffffffff, None),
s("bevelEmboss/shadowColor", 4, 1, 0x0002ffff, None),
s("bevelEmboss/shadowMode", 1, 0, 0x00010004, None),
s("bevelEmboss/shadowOpacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("bevelEmboss/softness", 1, 0, 0xffffffff, Some((0.0, 16.0))),
s("bevelEmboss/strengthRatio", 1, 0, 0xffffffff, Some((1.0, 1000.0))),
s("bevelEmboss/useGlobalAngle", 1, 0, 0x00010004, None),
s("chromeFX/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("chromeFX/color", 4, 1, 0x0002ffff, None),
s("chromeFX/distance", 1, 0, 0xffffffff, Some((1.0, 100.0))),
s("chromeFX/invert", 1, 0, 0x00010004, None),
s("chromeFX/localLightingAngle", 1, 0, 0xffffffff, None),
s("chromeFX/mode2", 1, 0, 0x00010004, None),
s("chromeFX/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("dropShadow/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("dropShadow/chokeMatte", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("dropShadow/color", 4, 1, 0x0002ffff, None),
s("dropShadow/distance", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("dropShadow/layerConceals", 1, 0, 0x00010004, None),
s("dropShadow/localLightingAngle", 1, 0, 0xffffffff, None),
s("dropShadow/mode2", 1, 0, 0x00010004, None),
s("dropShadow/noise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("dropShadow/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("dropShadow/useGlobalAngle", 1, 0, 0x00010004, None),
s("frameFX/color", 4, 1, 0x0002ffff, None),
s("frameFX/mode2", 1, 0, 0x00010004, None),
s("frameFX/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("frameFX/size", 1, 0, 0xffffffff, Some((1.0, 100.0))),
s("frameFX/style", 1, 0, 0x00010004, None),
s("gradientFill/align", 1, 0, 0x00010004, None),
s("gradientFill/angle", 1, 0, 0xffffffff, None),
s("gradientFill/gradientSmoothness", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("gradientFill/mode2", 1, 0, 0x00010004, None),
s("gradientFill/offset", 2, 3, 0xffffffff, None),
s("gradientFill/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("gradientFill/reverse", 1, 0, 0x00010004, None),
s("gradientFill/scale", 1, 0, 0xffffffff, Some((10.0, 150.0))),
s("gradientFill/type", 1, 0, 0x00010004, None),
s("innerGlow/AEColorChoice", 1, 0, 0x00010004, None),
s("innerGlow/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerGlow/chokeMatte", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerGlow/color", 4, 1, 0x0002ffff, None),
s("innerGlow/glowTechnique", 1, 0, 0x00010004, None),
s("innerGlow/gradientSmoothness", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerGlow/innerGlowSource", 1, 0, 0x00010004, None),
s("innerGlow/inputRange", 1, 0, 0xffffffff, Some((1.0, 100.0))),
s("innerGlow/mode2", 1, 0, 0x00010004, None),
s("innerGlow/noise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerGlow/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerGlow/shadingNoise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerShadow/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerShadow/chokeMatte", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerShadow/color", 4, 1, 0x0002ffff, None),
s("innerShadow/distance", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerShadow/localLightingAngle", 1, 0, 0xffffffff, None),
s("innerShadow/mode2", 1, 0, 0x00010004, None),
s("innerShadow/noise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerShadow/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("innerShadow/useGlobalAngle", 1, 0, 0x00010004, None),
s("outerGlow/AEColorChoice", 1, 0, 0x00010004, None),
s("outerGlow/blur", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("outerGlow/chokeMatte", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("outerGlow/color", 4, 1, 0x0002ffff, None),
s("outerGlow/glowTechnique", 1, 0, 0x00010004, None),
s("outerGlow/gradientSmoothness", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("outerGlow/inputRange", 1, 0, 0xffffffff, Some((1.0, 100.0))),
s("outerGlow/mode2", 1, 0, 0x00010004, None),
s("outerGlow/noise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("outerGlow/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("outerGlow/shadingNoise", 1, 0, 0xffffffff, Some((0.0, 100.0))),
s("solidFill/color", 4, 1, 0x0002ffff, None),
s("solidFill/mode2", 1, 0, 0x00010004, None),
s("solidFill/opacity", 1, 0, 0xffffffff, Some((0.0, 100.0))),
];
+403
View File
@@ -0,0 +1,403 @@
//! Layer styles: the inverse of the importer, through the shared table
//! [`crate::style_map`].
//!
//! Every layer block already holds the `ADBE Layer Styles` group with Blending Options
//! and the ten switch groups at rest (950). A style is applied by setting its switch group's
//! `tdsb` to 1 and Layer Styles and Blending Options to 1 (951-960); a parameter that differs
//! from After Effects' default gets a record, built from the table of the record
//! After Effects writes for that parameter (`style_defs`, from 977) with the value, in After Effects'
//! property order (970). Keys on a scalar take the keyed form of 976 (`tdb4` bytes 5, 68 and 79
//! from it, plain 48-byte key records); an expression is stored as on an effect parameter
//! (`tdb4@120` 1, `@119` the disabled switch, the text before `tdum`).
//!
//! A style switched off keeps its records with its switch group's `tdsb` 0 (988). Not written,
//! reported: the whole Layer Styles group switched off (not sampled), gradients that differ from the default (`GCst` is not decoded), keys on
//! colours, points, popups and checkboxes (not sampled), Knockout (After Effects has none).
use std::collections::HashMap;
use crate::Chunk;
use crate::style_map::{self as sm, StyleConv, StyleParam};
use effectcraft_keyframe::{Interp, Value};
use effectcraft_project::build::Ids;
use effectcraft_project::styles::{self as st, STYLE_BLEND_MODES};
use effectcraft_project::{Comp, Layer, PropGroup, Property};
use crate::export::plan::{CompPlan, EaseSlot, KeyPlan};
use crate::export::report::{Collector, LossCategory};
use crate::export::tree::{R, child_data, kids_mut, put_f64, put_u8, put_u32, tpl};
/// A record's value.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum RecValue {
Static(Vec<f64>),
Keys(Vec<KeyPlan>),
}
/// One parameter record to write.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Record {
/// The full match name (`dropShadow/opacity`, `ADBE Global Angle2`).
pub name: String,
pub value: RecValue,
/// Expression text and its enabled switch.
pub expr: Option<(String, bool)>,
}
/// The layer styles of one layer.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct StylesPlan {
/// Applied styles (switch-group prefix) with their records and their switch, in menu order.
pub styles: Vec<(&'static str, Vec<Record>, bool)>,
/// Global Light Angle / Altitude records (Blending Options).
pub global: Vec<Record>,
/// Advanced Blending records.
pub adv: Vec<Record>,
}
fn sane(v: f64) -> Option<f64> {
(v.is_finite() && v.abs() <= crate::export::plan::LIMIT).then_some(v)
}
/// An EffectCraft value in the file's units.
pub(crate) fn stored(conv: StyleConv, v: &Value) -> Option<Vec<f64>> {
let out = match (conv, v) {
(StyleConv::Number, Value::Scalar(x)) => vec![sane(*x)?],
(StyleConv::Color, Value::Color(c)) => vec![255.0, sane(c[0] * 255.0)?, sane(c[1] * 255.0)?, sane(c[2] * 255.0)?],
(StyleConv::Mode, Value::Enum(i)) => {
let name = STYLE_BLEND_MODES.get(usize::try_from(*i).ok()?)?.0;
vec![f64::from(sm::mode_code(name)?)]
}
(StyleConv::Popup(map), Value::Enum(i)) => vec![f64::from(sm::popup_code(map, *i)?)],
(StyleConv::Checkbox, Value::Bool(b)) => vec![if *b { 1.0 } else { 0.0 }],
(StyleConv::Vec2, Value::Vec2(p)) => vec![sane(p[0])?, sane(p[1])?],
_ => return None,
};
Some(out)
}
/// Whether an expression on a style popup would mean something else in After Effects. Both
/// programs count popup items from 1 in expressions, so only a popup whose stored item numbers are
/// not EffectCraft's items in the same order (Inner Glow Source is stored reversed) or a blend
/// mode whose After Effects item number differs from its place in EffectCraft's list is reported.
fn popup_expression_differs(conv: StyleConv) -> bool {
match conv {
StyleConv::Popup(map) => map.iter().enumerate().any(|(i, m)| usize::try_from(*m).ok() != Some(i)),
StyleConv::Mode => STYLE_BLEND_MODES.iter().enumerate().any(|(i, (name, _))| sm::mode_code(name).and_then(|c| usize::try_from(c).ok()) != Some(i + 1)),
_ => false,
}
}
fn same(a: &[f64], b: &[f64]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-9 * x.abs().max(1.0))
}
/// The record of one parameter, `None` when it stays at After Effects' default (no record).
fn plan_record(spec: &StyleParam, full: String, prop: &Property, cp: &CompPlan, what: &str, col: &mut Collector) -> Option<Record> {
let here = format!("{what}: {full}");
let expr = prop.expr.as_ref().filter(|e| !e.text.is_empty()).map(|e| (e.text.clone(), e.enabled));
if expr.is_some() {
col.exported.expressions = col.exported.expressions.saturating_add(1);
if popup_expression_differs(spec.conv) {
col.lose(
LossCategory::LayerStyles,
format!("{here}: an expression on a popup whose items are in another order in After Effects means something else there (written unchanged)"),
);
}
}
if !prop.keys.is_empty() {
if spec.conv == StyleConv::Number {
let keys = plan_number_keys(prop, cp, &here, col);
if !keys.is_empty() {
return Some(Record { name: full, value: RecValue::Keys(keys), expr });
}
} else {
col.lose(LossCategory::LayerStyles, format!("{here}: keys are not written (not sampled for this kind), the current value is"));
}
}
let Some(value) = stored(spec.conv, &prop.value) else {
col.lose(LossCategory::InvalidValues, format!("{here}: a value that cannot be stored, After Effects' default written"));
return None;
};
if same(&value, spec.default) && expr.is_none() {
return None;
}
Some(Record { name: full, value: RecValue::Static(value), expr })
}
/// The keys of a scalar in the layer's time base: linear, hold and bezier sides with the ease in
/// stored units per second (the plain template of 976).
fn plan_number_keys(prop: &Property, cp: &CompPlan, what: &str, col: &mut Collector) -> Vec<KeyPlan> {
let 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 mut out = Vec::with_capacity(timed.len());
let beyond = std::cell::Cell::new(false);
for (u, k) in timed {
let (Ok(time), Some(v)) = (
i32::try_from(u),
match &k.value {
Value::Scalar(x) => sane(*x),
_ => None,
},
) else {
col.lose(LossCategory::InvalidValues, format!("{what}: a key that cannot be stored, key dropped"));
continue;
};
let side = |i: Interp| -> u8 {
match i {
Interp::Linear => 1,
Interp::Bezier => 2,
Interp::Hold => 3,
}
};
let (in_i, out_i) = (side(k.in_interp), side(k.out_interp));
let ease = |eases: &[effectcraft_keyframe::Ease], on: bool| -> Vec<EaseSlot> {
if !on {
return vec![EaseSlot::default()];
}
let e = crate::export::plan::key_ease(eases, 0);
let influence = if e.influence.is_finite() { e.influence.clamp(0.001, 1.0) } else { 1.0 / 3.0 };
let speed = sane(e.speed).unwrap_or_else(|| {
beyond.set(true);
0.0
});
vec![EaseSlot { speed, influence }]
};
out.push(KeyPlan {
time,
value: vec![v],
in_interp: in_i,
out_interp: out_i,
in_ease: ease(&k.in_ease, in_i == 2),
out_ease: ease(&k.out_ease, out_i == 2),
spatial_in: [0.0; 3],
spatial_out: [0.0; 3],
spatial_auto: true,
roving: false,
label: k.label.min(16),
});
if k.roving {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: a roving key is written as a normal key"));
}
}
crate::export::plan::report_beyond(beyond.get(), what, col);
out
}
/// EffectCraft's default of a style parameter (to tell an edited gradient).
fn model_default(style: &str, id: &str) -> Option<Value> {
let mut next = 1;
let g = st::style(&mut Ids(&mut next), style)?;
g.get(id).map(|p| p.value.clone())
}
/// The layer styles of `layer`; `None` when it has none applied.
pub(crate) fn plan_styles(layer: &Layer, comp: &Comp, cp: &CompPlan, what: &str, col: &mut Collector) -> Option<StylesPlan> {
let ls = layer.layer_styles()?;
let mut plan = StylesPlan::default();
let groups: Vec<&PropGroup> = ls.groups().filter(|g| g.match_id != st::BLENDING).collect();
if groups.is_empty() {
return None;
}
if !layer.can_have_styles() {
col.lose(LossCategory::LayerStyles, format!("{what}: layer styles on a layer that takes none, not written"));
return None;
}
if !ls.enabled {
col.lose(LossCategory::LayerStyles, format!("{what}: Layer Styles switched off (the stored switch is not sampled), not written"));
return None;
}
for g in groups {
let Some(spec) = sm::by_ec(&g.match_id) else {
col.lose(LossCategory::LayerStyles, format!("{what}: style {} has no After Effects counterpart", g.name));
continue;
};
let mut recs = Vec::new();
for prm in spec.params {
let Some(prop) = g.get(prm.ec) else { continue };
let full = spec.param_name(prm);
if prm.conv == StyleConv::Gradient {
let edited = !prop.keys.is_empty() || prop.expr.is_some() || model_default(spec.ec, prm.ec).is_some_and(|d| d != prop.value);
if edited {
col.lose(LossCategory::LayerStyles, format!("{what}: {full} (gradient colours are not decoded; After Effects' default gradient)"));
}
continue;
}
if let Some(r) = plan_record(prm, full, prop, cp, what, col) {
recs.push(r);
}
}
plan.styles.push((spec.ae, recs, g.enabled));
}
if plan.styles.is_empty() {
return None;
}
// Global Light: the composition's, on every styled layer.
const ANGLE: &[f64] = &[st::DEFAULT_ANGLE];
const ALTITUDE: &[f64] = &[st::DEFAULT_ALTITUDE];
for (name, p, default) in [(sm::GLOBAL_ANGLE, &comp.global_light.angle, ANGLE), (sm::GLOBAL_ALTITUDE, &comp.global_light.altitude, ALTITUDE)] {
let spec = StyleParam { ae: name, ec: name, conv: StyleConv::Number, default };
if let Some(r) = plan_record(&spec, name.to_string(), p, cp, what, col) {
plan.global.push(r);
}
}
if let Some(adv) = ls.sub(st::BLENDING).and_then(|b| b.sub("advancedBlending")) {
for prm in sm::ADVANCED_BLENDING {
if let Some(p) = adv.get(prm.ec)
&& let Some(r) = plan_record(prm, prm.ae.to_string(), p, cp, what, col)
{
plan.adv.push(r);
}
}
if adv.get("knockout").is_some_and(|p| p.value != Value::Enum(0) || !p.keys.is_empty()) {
col.lose(LossCategory::LayerStyles, format!("{what}: Knockout (After Effects has none)"));
}
}
col.exported.layer_styles += plan.styles.len();
Some(plan)
}
// ---------------------------------------------------------------------------------------------
// Emit.
/// The style record prototypes, built in code: full match name -> (`tdmn`, `tdbs`), and
/// the keyed scalar record.
pub(crate) struct StyleProtos {
records: HashMap<String, (Chunk<'static>, Chunk<'static>)>,
keyed: Chunk<'static>,
}
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.
pub(crate) fn from_table() -> StyleProtos {
use crate::export::synth::{KeyTemplate, RecSpec, class, tdbs, tdmn};
let records = crate::export::style_defs::STYLE_RECORDS
.iter()
.map(|(name, dims, template, cls, limits)| {
let template = if *template == 0 { KeyTemplate::Plain } else { KeyTemplate::Spatial(*template) };
let spec = RecSpec { dims: *dims, template, class: *cls, limits: *limits, byte5: None };
(name.to_string(), (tdmn(name), tdbs(&spec, false, 25_600)))
})
.collect();
let scalar = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::EFFECT_NUMBER, limits: Some((0.0, 100.0)), byte5: None };
StyleProtos { records, keyed: tdbs(&scalar, true, 25_600) }
}
/// The `tdmn` + `tdbs` of one record.
fn build(&self, r: &Record) -> R<[Chunk<'static>; 2]> {
let (m, proto) = self.records.get(&r.name).ok_or_else(|| tpl("style record prototype missing"))?;
let mut rec = proto.clone();
match &r.value {
RecValue::Static(v) => {
let cdat = child_data(&mut rec, b"cdat")?;
cdat.iter_mut().for_each(|b| *b = 0);
for (i, x) in v.iter().enumerate() {
put_f64(cdat, i * 8, *x)?;
}
}
RecValue::Keys(keys) => {
let ktdb4 = self.keyed.child(b"tdb4").and_then(|c| c.bytes()).ok_or_else(|| tpl("keyed style prototype without tdb4"))?;
{
let tdb4 = child_data(&mut rec, b"tdb4")?;
for at in [5usize, 68, 79] {
put_u8(tdb4, at, *ktdb4.get(at).ok_or_else(|| tpl("short tdb4"))?)?;
}
}
let mut list = self.keyed.child_list(b"list").cloned().ok_or_else(|| tpl("keyed style prototype without keys"))?;
let 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;
}
}
}
if let Some((text, enabled)) = &r.expr {
{
let tdb4 = child_data(&mut rec, b"tdb4")?;
put_u8(tdb4, 120, 1)?;
put_u8(tdb4, 119, u8::from(!*enabled))?;
}
let kids = kids_mut(&mut rec)?;
let at = kids.iter().position(|c| c.is(b"tdum")).unwrap_or(kids.len());
kids.insert(at, Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
}
Ok([m.clone(), rec])
}
}
/// The node after the `tdmn` named `name` among `kids`.
fn named_mut<'a>(kids: &'a mut [Chunk<'static>], name: &str) -> R<&'a mut Chunk<'static>> {
let i = kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(name)).ok_or_else(|| tpl("layer styles group incomplete"))?;
kids.get_mut(i + 1).ok_or_else(|| tpl("layer styles group incomplete"))
}
fn set_flags(g: &mut Chunk<'static>, flags: u32) -> R<()> {
put_u32(child_data(g, b"tdsb")?, 0, flags)
}
/// Inserts `recs` before the `tdmn` named `before` (or before `ADBE Group End`).
fn insert_records(protos: &StyleProtos, g: &mut Chunk<'static>, recs: &[Record], before: &str) -> R<()> {
let mut built = Vec::with_capacity(recs.len() * 2);
for r in recs {
built.extend(protos.build(r)?);
}
let kids = kids_mut(g)?;
let at = kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(before)).ok_or_else(|| tpl("layer styles group incomplete"))?;
kids.splice(at..at, built);
Ok(())
}
/// Applies `plan` to the layer's `ADBE Layer Styles` group.
pub(crate) fn put_styles(protos: &StyleProtos, layr: &mut Chunk<'static>, plan: &StylesPlan) -> R<()> {
let root = crate::export::tree::list_mut(layr, b"tdgp")?;
let ls = named_mut(kids_mut(root)?, sm::GROUP)?;
set_flags(ls, sm::FLAGS_ON)?;
{
let bo = named_mut(kids_mut(ls)?, sm::BLEND_OPTIONS)?;
set_flags(bo, sm::FLAGS_ON)?;
insert_records(protos, bo, &plan.global, sm::ADV_BLEND)?;
let adv = named_mut(kids_mut(bo)?, sm::ADV_BLEND)?;
insert_records(protos, adv, &plan.adv, "ADBE 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")?;
}
Ok(())
}
+215
View File
@@ -0,0 +1,215 @@
//! Chunks the exporter builds in code instead of copying them from projects After Effects saved.
//!
//! Every byte written here is a decoded field (`docs/aep-format.md`), a named constant with its
//! evidence, or zero where After Effects was shown to accept zero (the read-backs listed in
//! `docs/aep-export.md`, "Built in code").
use crate::{Body, Chunk};
/// `tdmn`: a match name padded to 40 bytes.
pub(crate) fn tdmn(name: &str) -> Chunk<'static> {
let mut b = vec![0u8; 40];
for (slot, c) in b.iter_mut().zip(name.bytes().take(39)) {
*slot = c;
}
Chunk::data(*b"tdmn", b)
}
/// The 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 }
}
/// How a property's keys are stored (`tdb4` byte 7, aep-format.md 3.5).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum KeyTemplate {
/// Value and type-major ease doubles: Opacity, Rotation, Scale, sliders.
Plain,
/// Ease, value and tangents; byte 7 is 3 on positions and points, 1 on colours and paths.
Spatial(u8),
}
/// The u32 at `tdb4` bytes 8..11. Its two u16 halves follow the kind of property (aep-format.md
/// 3.4, "class word"); without it After Effects drops a property's keys (read-back e1-bz5).
pub(crate) mod class {
/// Transform Scale, Rotation and Opacity; the other one-dimensional layer properties.
pub const LAYER_SCALAR: u32 = 0x0001_ffff;
/// Positions and points (spatial, no limits); effect sliders and angles.
pub const SPATIAL: u32 = 0xffff_ffff;
/// Effect sliders (integer, fixed, float) and angles.
pub const EFFECT_NUMBER: u32 = 0xffff_ffff;
/// Effect checkboxes and popups.
pub const EFFECT_CHOICE: u32 = 0x0001_0004;
/// Colours.
pub const COLOR: u32 = 0x0002_ffff;
/// Effect layer parameters, groups and buttons.
pub const EFFECT_OTHER: u32 = 0x0001_0000;
/// Arbitrary data (Hue/Saturation, Levels, Curves, Mesh Warp).
pub const ARBITRARY: u32 = 0x0006_0007;
/// Mask and shape paths.
pub const PATH: u32 = 0x0002_0007;
}
/// Byte 5 bits 1..3 of a spatial property, next to the static bit 0: `0x0e` on positions and
/// points (`0x0f` static, `0x0e` keyed: Anchor Point, Position, Gradient Ramp's points), `0x06` on
/// colours (`0x07` / `0x06`: Tint's colours). Meaning not decoded.
fn spatial_byte5(template: u8) -> u8 {
if template == 3 { 0x0e } else { 0x06 }
}
/// What a property record needs to know about its property.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RecSpec {
/// Components of a value (`tdb4` byte 3).
pub dims: u8,
pub template: KeyTemplate,
/// `tdb4` bytes 8..11 (see [`class`]).
pub class: u32,
/// `tdum` / `tduM`, written when the property has them (Scale `0, 0`, Opacity `0, 100`).
pub limits: Option<(f64, f64)>,
/// `tdb4` byte 5 of the static record when it is not the one [`tdb4`] derives (bits 1..3 are
/// not decoded; the keyed record clears bit 0).
pub byte5: Option<u8>,
}
impl RecSpec {
/// Bytes of a static value (`cdat`): the key record without its 8-byte header, value first,
/// the rest zero (aep-format.md 3.4 / 3.5: `40 n` plain, `24 n` spatial).
pub fn cdat_len(&self) -> usize {
let n = usize::from(self.dims);
match self.template {
KeyTemplate::Plain => 40 * n,
KeyTemplate::Spatial(_) => 24 * n,
}
}
/// Bytes of one key record (aep-format.md 3.5).
pub fn key_len(&self) -> usize {
let n = usize::from(self.dims);
match self.template {
KeyTemplate::Plain => 8 + 40 * n,
KeyTemplate::Spatial(_) => 56 + 24 * n,
}
}
}
/// The 124-byte `tdb4` header of a property (aep-format.md 3.4). The decoded bytes, the class
/// word and the constant doubles at 16..56 are written; After Effects reads the other bytes as
/// zero (read-back e1-ztdb4d).
pub(crate) fn tdb4(spec: &RecSpec, keyed: bool, time_scale: u32) -> Vec<u8> {
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]);
let spatial = match spec.template {
KeyTemplate::Plain => 0,
KeyTemplate::Spatial(t) => t,
};
let byte5 = match spec.byte5 {
Some(b) => (b & !0x01) | u8::from(!keyed),
None => (if spatial == 0 { 0 } else { spatial_byte5(spatial) }) | u8::from(!keyed),
};
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());
// 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());
for at in [24, 32, 40, 48] {
set(&mut b, at, &1.0f64.to_be_bytes());
}
set(&mut b, 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
}
/// A key list (`LIST list`: `lhd3` + `ldat`) of `count` records of `size` bytes (aep-format.md
/// 3.5): word 0 `0x00d00bee`, word 2 the count, word 3 the blocks of four (at least one), word 4
/// the size, words 5 and 7 the capacity (the count rounded up to four, at least two), word 6 one.
pub(crate) fn key_list(size: u32, count: u32, records: Vec<u8>) -> Chunk<'static> {
let 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);
Chunk::list(*b"list", vec![Chunk::data(*b"lhd3", lhd3), Chunk::data(*b"ldat", records)])
}
/// 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<()> {
let capacity = count.div_ceil(4).saturating_mul(4).max(2);
put_counts(lhd3, count, count.div_ceil(4).max(1), size, capacity, capacity)
}
/// Sets the count words of a list header: word 2 the record count, word 3 `blocks`, word 4 the
/// record size, word 5 `w5`, word 7 the capacity. A key list has `w5` = the capacity; a path
/// list counts vertices: `blocks` = `w5` = the vertex count, the capacity four times it (090:
/// 12 points, 4, 4 and 16; aep-format.md 3.5).
pub(crate) fn put_counts(lhd3: &mut [u8], count: u32, blocks: u32, size: u32, w5: u32, capacity: u32) -> crate::export::tree::R<()> {
use crate::export::tree::put_u32;
put_u32(lhd3, 8, count)?;
put_u32(lhd3, 12, blocks)?;
put_u32(lhd3, 16, size)?;
put_u32(lhd3, 20, w5)?;
put_u32(lhd3, 28, capacity)
}
/// A property record (`LIST tdbs`) with a zero static value or an empty key list, for the
/// exporter to fill: `tdsb` 1 (written), no user name, the header, then `cdat` or the key list,
/// then the limits.
pub(crate) fn tdbs(spec: &RecSpec, keyed: bool, time_scale: u32) -> Chunk<'static> {
let mut kids = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), tdsn(NO_NAME), Chunk::data(*b"tdb4", tdb4(spec, keyed, time_scale))];
if keyed {
kids.push(key_list(u32::try_from(spec.key_len()).unwrap_or(u32::MAX), 0, Vec::new()));
} else {
kids.push(Chunk::data(*b"cdat", vec![0u8; spec.cdat_len()]));
}
if let Some((lo, hi)) = spec.limits {
kids.push(Chunk::data(*b"tdum", lo.to_be_bytes().to_vec()));
kids.push(Chunk::data(*b"tduM", hi.to_be_bytes().to_vec()));
}
Chunk::list(*b"tdbs", kids)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_record_has_the_decoded_layout() {
let pos = RecSpec { dims: 3, template: KeyTemplate::Spatial(3), class: class::SPATIAL, limits: None, byte5: None };
let h = tdb4(&pos, false, 25_600);
assert_eq!(&h[..8], &[0xdb, 0x99, 0, 3, 0, 0x0f, 0, 3]);
assert_eq!(&h[8..16], &[0xff, 0xff, 0xff, 0xff, 0, 0, 0x64, 0]);
assert_eq!((h[68], h[79]), (0, 1));
// A roving key needs these to keep its time (read-back s14-re-keyframes).
assert_eq!(&h[16..24], &1e-4f64.to_be_bytes());
assert!(h[24..56].chunks(8).all(|d| d == 1.0f64.to_be_bytes()));
assert_eq!(pos.cdat_len(), 72);
assert_eq!(pos.key_len(), 128);
let opacity = RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: Some((0.0, 100.0)), byte5: None };
let k = tdb4(&opacity, true, 25_600);
assert_eq!((k[5], k[7], k[68]), (0, 0, 1));
let rec = tdbs(&opacity, false, 25_600);
let ids: Vec<[u8; 4]> = rec.children().iter().map(|c| c.id).collect();
assert_eq!(ids, [*b"tdsb", *b"tdsn", *b"tdb4", *b"cdat", *b"tdum", *b"tduM"]);
assert_eq!(rec.child(b"cdat").and_then(|c| c.bytes()).map(<[u8]>::len), Some(40));
}
#[test]
fn a_key_list_header_counts_and_rounds() {
let l = key_list(48, 5, vec![0; 240]);
let h = l.child(b"lhd3").and_then(|c| c.bytes()).unwrap();
let w = |i: usize| u32::from_be_bytes(h[i * 4..i * 4 + 4].try_into().unwrap());
assert_eq!((w(0), w(2), w(3), w(4), w(5), w(6), w(7)), (0x00d0_0bee, 5, 2, 48, 8, 1, 8));
assert_eq!(h.len(), 52);
}
}
+162
View File
@@ -0,0 +1,162 @@
//! The prototypes the exporter clones and edits, all built in code: the project skeleton
//! (`base`), the layer blocks (`skeleton`, `tree_defs`), and the records of Transform, masks,
//! effects, layer styles, footage, text and text animators (see `docs/aep-export.md`). Nothing is
//! read from a file After Effects wrote; each layout was checked by After Effects reading the
//! export back.
use crate::{AepFile, Chunk};
use crate::export::tree::{R, tpl};
/// The chunks cloned by the exporter.
pub(crate) struct Template {
/// The whole base project; its `Fold` children are replaced by the export.
pub file: AepFile<'static>,
/// The base composition item without its layer blocks.
pub comp_shell: Chunk<'static>,
/// Index in the shell's children where the layer blocks go.
pub layer_at: usize,
/// `Layr`, `Ewst` and the f-records that follow the layer `L`.
pub layer_block: Vec<Chunk<'static>>,
/// The footage item of the solid `L` (inside `Solids`).
pub solid_item: Chunk<'static>,
/// The `Solids` folder item.
pub folder_item: Chunk<'static>,
/// The f-records that follow a footage item inside a folder.
pub fset: Vec<Chunk<'static>>,
/// The `FEE ` list that follows a composition item.
pub fee: Chunk<'static>,
/// `tdmn`, `tdbs` pairs of the five Transform properties with a static value.
pub stat: Vec<Chunk<'static>>,
/// The same with two keys.
pub keyd: Vec<Chunk<'static>>,
/// The layer block of a null layer.
pub null_block: Vec<Chunk<'static>>,
/// The hidden solid item of a null layer.
pub null_item: Chunk<'static>,
/// The mask prototypes (fixtures 091, 093, 208).
pub masks: crate::export::masks::MaskProtos,
/// The effect prototypes (cases 356-397).
pub effects: crate::export::effects::FxProtos,
/// The footage item prototypes (cases 351, 353, 603-607).
pub footage: crate::export::footage::FtProtos,
/// The layer blocks of a point (110) and a box (245) text layer.
pub text_point: Vec<Chunk<'static>>,
pub text_box: Vec<Chunk<'static>>,
/// The text animator prototypes (579, 580-592, 728).
pub anims: crate::export::textanim::AnimProtos,
/// The marker group (`tdmn ADBE Marker` + `LIST mrst`) of fixture 249.
pub marker_group: Vec<Chunk<'static>>,
/// The layer blocks of a two-node camera (256), a spot (254) and a point light (252).
pub camera_block: Vec<Chunk<'static>>,
pub spot_block: Vec<Chunk<'static>>,
pub point_block: Vec<Chunk<'static>>,
/// Camera and light option records (342-345, 254).
pub options: crate::export::camlight::OptionProtos,
/// Shape layer, item and record prototypes (519, 240, 451-471, 239, 242).
pub shapes: crate::export::shapes::ShapeProtos,
/// Layer-style record prototypes (977, 976).
pub styles: crate::export::styles::StyleProtos,
}
/// The `tdmn`, `tdbs` pairs of the five Transform properties, static or keyed, built in code
/// (aep-format.md 3.4): Anchor Point and Position spatial, Scale, Rotation and Opacity plain;
/// Scale and Opacity carry their limits.
fn transform_records(keyed: bool) -> Vec<Chunk<'static>> {
use crate::export::plan::PropKind;
use crate::export::synth::{KeyTemplate, RecSpec, class};
PropKind::ALL
.iter()
.flat_map(|k| {
let spec = match k {
PropKind::Anchor | PropKind::Position => {
RecSpec { dims: 3, template: KeyTemplate::Spatial(3), class: class::SPATIAL, limits: None, byte5: None }
}
PropKind::Scale => RecSpec { dims: 3, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: Some((0.0, 0.0)), byte5: None },
PropKind::Rotation => RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: None, byte5: None },
PropKind::Opacity => RecSpec { dims: 1, template: KeyTemplate::Plain, class: class::LAYER_SCALAR, limits: Some((0.0, 100.0)), byte5: None },
};
[crate::export::synth::tdmn(k.match_name()), crate::export::synth::tdbs(&spec, keyed, 25_600)]
})
.collect()
}
impl Template {
pub fn load() -> R<Template> {
let file = AepFile { chunks: crate::export::base::project_chunks(), trailer: std::borrow::Cow::Borrowed(&[]) };
let fee = crate::export::base::fee();
let fset = crate::export::skeleton::f_records();
let folder_item = crate::export::base::folder_item();
let solid_item = crate::export::base::solid_item();
let (comp_shell, first) = crate::export::base::comp_shell();
let layer_block = crate::export::skeleton::av_layer();
let stat = transform_records(false);
let keyd = transform_records(true);
// A null layer has the AV layer's block; `ldta` marks it (byte 38 bit 0x80).
let null_block = crate::export::skeleton::av_layer();
// The hidden solid of a null layer is an ordinary solid item (022).
let null_item = crate::export::base::solid_item();
let masks = crate::export::masks::MaskProtos::build();
let effects = crate::export::effects::FxProtos::build();
let styles = crate::export::styles::StyleProtos::from_table();
let footage = crate::export::footage::FtProtos::build();
// Point (110) and box (245) text layers with a document built in code.
use crate::export::{textdoc, textproto};
let text_point = crate::export::skeleton::text_layer(&textdoc::write(&textproto::document(false)));
let text_box = crate::export::skeleton::text_layer(&textdoc::write(&textproto::document(true)));
let anims = crate::export::textanim::AnimProtos {
group: crate::export::tree_spec::build(crate::export::tree_defs::TEXT_ANIMATORS),
animator: crate::export::tree_spec::build(crate::export::tree_defs::TEXT_ANIMATOR),
records: crate::export::skeleton::pairs(crate::export::tree_defs::TEXT_ANIMATOR_RECORDS),
};
let marker_group = crate::export::skeleton::marker_group();
use crate::export::{skeleton, tree_defs};
let camera_block = skeleton::layer_block(tree_defs::CAMERA_ROOT);
let spot_block = skeleton::layer_block(tree_defs::SPOT_ROOT);
let point_block = skeleton::layer_block(tree_defs::POINT_ROOT);
let records = skeleton::pairs(tree_defs::OPTIONS).into_iter().map(|(name, [_, node])| (name, node)).collect();
let options = crate::export::camlight::OptionProtos { records };
// The key list of the keyed Opacity prototype (one-component plain keys; its header is
// rewritten for every keyed shape property).
let key_list = keyd
.iter()
.rev()
.find(|c| c.is_list(b"tdbs"))
.and_then(|c| c.child_list(b"list"))
.cloned()
.ok_or_else(|| tpl("keyed prototype without a key list"))?;
let shapes = crate::export::shapes::ShapeProtos {
block: skeleton::layer_block(tree_defs::SHAPE_ROOT),
items: skeleton::pairs(tree_defs::SHAPE_ITEMS),
records: skeleton::pairs(tree_defs::SHAPE_RECORDS),
key_list,
};
Ok(Template {
file,
comp_shell,
layer_at: first,
layer_block,
solid_item,
folder_item,
fset,
fee,
stat,
keyd,
null_block,
null_item,
masks,
effects,
footage,
text_point,
text_box,
anims,
marker_group,
camera_block,
spot_block,
point_block,
options,
shapes,
styles,
})
}
}
+562
View File
@@ -0,0 +1,562 @@
//! Text layers: the layer block of a point (110) or box (245) text layer, built in code
//! (`skeleton::text_layer`, `textproto`), with its text document rewritten from the layer's Source
//! Text (`docs/aep-format.md` 3.10, `docs/aep-export.md` R32-R34):
//!
//! * the text (paragraphs end with `\r`, the last one too), the paragraph runs with their
//! justification, the style runs with font, size, faux bold / italic, automatic or explicit
//! leading, tracking, caps, fill and stroke colour;
//! * fonts other than the prototype's are appended to the font list (its own entries, which the
//! rest of the document refers to by index, keep their places);
//! * a box text's frame (16 points tracing the rectangle, 245);
//! * the composed layout (`/1/1[0]/1/2`) is left empty: After Effects lays the text out again
//! when it opens the project (t1-t3).
use effectcraft_keyframe::Value;
use effectcraft_keyframe::text_doc::{BaselineOption, Composer, Direction, Justify, Kerning, TextDoc};
use effectcraft_project::{Layer, Node, PropGroup};
use crate::export::report::{Collector, LossCategory};
use crate::export::textdoc::{TNode, boolean, int, number, string};
/// The prototype's own font (index 0 of its font list).
const PROTO_FONT: &str = "TimesNewRomanPSMT";
/// The longest text written (characters).
const MAX_CHARS: usize = 1 << 20;
/// One style run in the file's terms.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct StyleOut {
pub font: String,
pub size: f64,
pub fill: [f64; 3],
pub stroke: [f64; 3],
pub tracking: f64,
/// `None` = automatic leading.
pub leading: Option<f64>,
pub faux_bold: bool,
pub faux_italic: bool,
/// 0 normal, 1 small caps, 2 all caps.
pub caps: i64,
/// Style slot `/13`: 0 normal, 1 superscript, 2 subscript (526-528).
pub script: i64,
/// Slots `/6` and `/7`: horizontal and vertical scale as factors (539, 540).
pub h_scale: f64,
pub v_scale: f64,
/// Slot `/9`: baseline shift in pixels.
pub baseline_shift: f64,
/// Slot `/11`: automatic kerning, 0 none, 1 metrics, 2 optical (541-543).
pub auto_kern: i64,
/// Slot `/18`: standard ligatures (555).
pub ligatures: bool,
/// Slot `/36`: tsume as a fraction (553).
pub tsume: f64,
/// Slots `/56`, `/57`: whether fill and stroke are drawn (544-546).
pub apply_fill: bool,
pub apply_stroke: bool,
/// Slot `/63`: stroke width in pixels; `None` keeps the prototype's value.
pub stroke_width: Option<f64>,
/// Slot `/58`: stroke over fill (one switch for the whole text in EffectCraft; 550).
pub stroke_over_fill: bool,
}
/// One paragraph in the file's terms (paragraph dictionary `RUN/5/0[n]/0/0/5`).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ParaOut {
/// `/0`: 0 left, 1 right, 2 centre, 3-6 justified with the last line left / right / centre /
/// justified.
pub justify: i64,
/// `/1` first-line indent, `/2` start indent, `/3` end indent, `/4` space before, `/5` space
/// after, in pixels.
pub indents: [f64; 5],
/// `/21`: Roman hanging punctuation (558).
pub hanging: bool,
/// `/29`: the every-line composer (557, 559).
pub every_line: bool,
/// `/33`: 0 left to right, 1 right to left (569).
pub direction: i64,
}
/// A text document in the file's terms.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct TextPlan {
/// The stored text: paragraphs separated and ended by `\r`.
pub text: String,
/// (characters, style), covering the text including the final `\r`.
pub runs: Vec<(usize, StyleOut)>,
/// (characters including the `\r`, paragraph settings).
pub paras: Vec<(usize, ParaOut)>,
/// Box text: left, top, width, height in layer pixels.
pub frame: Option<[f64; 4]>,
/// The text animators (planned with the layer's time base, `textanim.rs`).
pub animators: Vec<crate::export::textanim::AnimPlan>,
}
/// Where a text value is written, for the loss report.
struct At<'a, 'c> {
what: &'a str,
col: &'c mut Collector,
}
impl At<'_, '_> {
/// `v` limited to `lo..=hi` (a value that is not a number becomes `default`); a change is reported.
fn fit(&mut self, v: f64, (lo, hi): (f64, f64), default: f64, field: &str) -> f64 {
let out = if v.is_finite() { v.clamp(lo, hi) } else { default };
if out.to_bits() != v.to_bits() {
self.col.lose(LossCategory::TextLayers, format!("{}: {field} {v} is outside {lo} to {hi}, written as {out}", self.what));
}
out
}
/// The colour channels limited to 0..1, without alpha (a text colour in After Effects has none);
/// a change is reported.
fn rgb(&mut self, c: [f32; 4], field: &str) -> [f64; 3] {
let [r, g, b, a] = c.map(f64::from);
if a.to_bits() != 1f64.to_bits() {
self.col.lose(LossCategory::TextLayers, format!("{}: the {field} opacity {a} is not written (text colours have no alpha)", self.what));
}
let name = format!("{field} channel");
[self.fit(r, (0.0, 1.0), 0.0, &name), self.fit(g, (0.0, 1.0), 0.0, &name), self.fit(b, (0.0, 1.0), 0.0, &name)]
}
}
/// Plans the text of a text layer and reports what the document cannot hold.
pub(crate) fn plan_text(layer: &Layer, comp_name: &str, col: &mut Collector) -> Option<TextPlan> {
let what = format!("{comp_name}: '{}'", layer.name);
let Some(text) = layer.props.sub("text") else {
col.lose(LossCategory::TextLayers, format!("{what}: a text layer without text properties"));
return None;
};
let Some(st) = text.prop("sourceText") else {
col.lose(LossCategory::TextLayers, format!("{what}: a text layer without Source Text"));
return None;
};
if !st.keys.is_empty() {
col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not written (the first key's text is)"));
}
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))
}
/// Path / More Options that hold anything other than a new text layer's defaults are not
/// written (animators are, `textanim.rs`).
fn report_extras(text: &PropGroup, what: &str, col: &mut Collector) {
let mut next = 1u64;
let reference = effectcraft_project::build::text(&mut effectcraft_project::build::Ids(&mut next), TextDoc::default());
for node in &text.children {
let Node::Group(g) = node else { continue };
match g.match_id.as_str() {
"pathOptions" | "moreOptions" => {
let def = reference.children.iter().find_map(|n| match n {
Node::Group(r) if r.match_id == g.match_id => Some(r),
_ => None,
});
if differs(g, def, 0) {
col.lose(LossCategory::TextLayers, format!("{what}: {} are not written", g.name));
}
}
_ => {}
}
}
}
/// Whether `g` holds keys, expressions or values other than those of `def` (the same group of a
/// new text layer).
fn differs(g: &PropGroup, def: Option<&PropGroup>, depth: usize) -> bool {
if depth > 32 {
return true;
}
g.children.iter().any(|n| match n {
Node::Group(s) => {
let d = def.and_then(|d| {
d.children.iter().find_map(|x| match x {
Node::Group(r) if r.match_id == s.match_id => Some(r),
_ => None,
})
});
differs(s, d, depth + 1)
}
Node::Prop(p) => {
let d = def.and_then(|d| d.prop(&p.match_id));
!p.keys.is_empty() || p.has_expression() || d.is_none_or(|d| d.value != p.value)
}
})
}
fn plan_doc(doc: &TextDoc, what: &str, col: &mut Collector) -> TextPlan {
let base = doc.base_style();
let runs = doc.runs();
// Characters in EffectCraft's text, each with its run, CRLF and LF made After Effects' CR.
let chars: Vec<char> = doc.text.chars().collect();
let mut style_of: Vec<usize> = Vec::with_capacity(chars.len());
for (ri, r) in runs.iter().enumerate() {
style_of.extend(std::iter::repeat_n(ri, r.len));
}
let mut text = String::with_capacity(doc.text.len() + 1);
let mut out_style: Vec<usize> = Vec::new();
let mut i = 0;
while i < chars.len() && out_style.len() < MAX_CHARS {
let c = chars.get(i).copied().unwrap_or(' ');
let ri = style_of.get(i).copied().unwrap_or(runs.len().saturating_sub(1));
if c == '\r' && chars.get(i + 1) == Some(&'\n') {
i += 1;
}
text.push(if c == '\n' { '\r' } else { c });
out_style.push(ri);
i += 1;
}
if i < chars.len() {
col.lose(LossCategory::TextLayers, format!("{what}: the text is longer than {MAX_CHARS} characters and was cut"));
}
// The final paragraph end belongs to the last run.
text.push('\r');
out_style.push(out_style.last().copied().unwrap_or(0));
let mut styles: Vec<StyleOut> = Vec::with_capacity(runs.len().max(1));
for r in &runs {
styles.push(style_out(&r.style, what, col));
}
if styles.is_empty() {
styles.push(style_out(&base, what, col));
}
for st in &mut styles {
st.stroke_over_fill = doc.stroke_over_fill;
}
let mut out_runs: Vec<(usize, StyleOut)> = Vec::new();
for ri in out_style {
let s = styles.get(ri).or(styles.last()).cloned();
let Some(s) = s else { continue };
match out_runs.last_mut() {
Some((n, last)) if *last == s => *n += 1,
_ => out_runs.push((1, s)),
}
}
let paras_in = doc.paras();
let mut paras = Vec::new();
for (pi, part) in text.split_inclusive('\r').enumerate() {
let len = part.chars().count();
// A paragraph without its own settings takes the document's (every-line composer by
// default, as a new text in After Effects' Paragraph panel).
let base = doc.base_para();
let p = paras_in.get(pi).or(paras_in.last()).unwrap_or(&base);
// The stored code is relative to the direction: right-to-left swaps left / right and
// the two justified variants with a left / right last line (t7, as the importer).
let rtl = p.direction == Direction::Rtl;
let j = match p.justify {
Justify::Left if rtl => 1,
Justify::Right if rtl => 0,
Justify::JustifyLastLeft if rtl => 4,
Justify::JustifyLastRight if rtl => 3,
Justify::Left => 0,
Justify::Right => 1,
Justify::Center => 2,
// The justified variants, as the importer reads them (paragraph `/0`, 3-6).
Justify::JustifyLastLeft => 3,
Justify::JustifyLastRight => 4,
Justify::JustifyLastCenter => 5,
Justify::JustifyAll => 6,
};
let mut at = At { what, col: &mut *col };
let mut px = |v: f64, field: &str| at.fit(v, (-100_000.0, 100_000.0), 0.0, field);
let indents = [
px(p.indent_first, "first-line indent"),
px(p.indent_left, "left indent"),
px(p.indent_right, "right indent"),
px(p.space_before, "space before"),
px(p.space_after, "space after"),
];
let po = ParaOut { justify: j, indents, hanging: p.hanging_punctuation, every_line: p.composer == Composer::EveryLine, direction: i64::from(rtl) };
paras.push((len, po));
}
if doc.vertical {
col.lose(LossCategory::TextLayers, format!("{what}: vertical text is written horizontally"));
}
let mut at = At { what, col };
let frame = doc.box_size.map(|[w, h]| {
[
at.fit(doc.box_pos[0], (-1e6, 1e6), 0.0, "box left"),
at.fit(doc.box_pos[1], (-1e6, 1e6), 0.0, "box top"),
at.fit(w, (1.0, 1e6), 1.0, "box width"),
at.fit(h, (1.0, 1e6), 1.0, "box height"),
]
});
TextPlan { text, runs: out_runs, paras, frame, animators: Vec::new() }
}
fn style_out(s: &effectcraft_keyframe::text_doc::CharStyle, what: &str, col: &mut Collector) -> StyleOut {
let auto_kern = match s.kerning {
Kerning::Metrics => 1,
Kerning::Optical => 2,
// No automatic kerning is a manual amount of 0 (542).
Kerning::Manual(k) => {
if k != 0.0 {
col.lose(LossCategory::TextLayers, format!("{what}: a manual kerning amount is not written (written without automatic kerning)"));
}
0
}
};
if !s.opentype.is_default() || !s.variations.is_empty() {
col.lose(LossCategory::TextLayers, format!("{what}: OpenType features and variable font axes are not written"));
}
if s.style != "Regular" && !s.style.is_empty() {
col.lose(LossCategory::TextLayers, format!("{what}: the font style '{}' is not written (the font is named by its PostScript name)", s.style));
}
if s.font.is_empty() {
col.lose(LossCategory::TextLayers, format!("{what}: a run without a font name is written in {PROTO_FONT}"));
}
let mut at = At { what, col };
StyleOut {
font: if s.font.is_empty() { PROTO_FONT.to_string() } else { s.font.clone() },
size: at.fit(s.size, (0.1, 10_000.0), 100.0, "font size"),
fill: at.rgb(s.fill, "fill colour"),
stroke: at.rgb(s.stroke, "stroke colour"),
tracking: at.fit(s.tracking, (-100_000.0, 100_000.0), 0.0, "tracking"),
leading: s.leading.map(|l| at.fit(l, (0.0, 100_000.0), 0.0, "leading")),
faux_bold: s.faux_bold,
faux_italic: s.faux_italic,
caps: if s.all_caps {
2
} else if s.small_caps {
1
} else {
0
},
script: match s.baseline {
BaselineOption::Normal => 0,
BaselineOption::Superscript => 1,
BaselineOption::Subscript => 2,
},
h_scale: at.fit(s.h_scale, (1.0, 10_000.0), 100.0, "horizontal scale") / 100.0,
v_scale: at.fit(s.v_scale, (1.0, 10_000.0), 100.0, "vertical scale") / 100.0,
baseline_shift: at.fit(s.baseline_shift, (-100_000.0, 100_000.0), 0.0, "baseline shift"),
auto_kern,
ligatures: s.ligatures,
tsume: at.fit(s.tsume, (0.0, 100.0), 0.0, "tsume") / 100.0,
apply_fill: s.apply_fill,
apply_stroke: s.apply_stroke,
stroke_width: (s.apply_stroke || s.stroke_width > 0.0).then(|| at.fit(s.stroke_width, (0.0, 10_000.0), 1.0, "stroke width")),
stroke_over_fill: true,
}
}
// ---------------------------------------------------------------------------------------------
// The document.
/// The number an atom holds (`1`, `1.0`, `.5`).
fn atom_f64(n: Option<&TNode>) -> Option<f64> {
match n? {
TNode::Atom(a) => std::str::from_utf8(a).ok()?.trim().parse::<f64>().ok(),
_ => None,
}
}
/// Sets a number slot unless it already holds `v` (`absent` when the slot is missing).
fn set_num_if(d: &mut TNode, key: &str, v: f64, absent: f64) {
let cur = match d.get(key) {
None => Some(absent),
n => atom_f64(n),
};
if cur.is_none_or(|c| (c - v).abs() > 1e-9) {
d.set(key, number(v));
}
}
/// Sets a boolean slot unless it already holds `v` (`absent` when the slot is missing).
fn set_bool_if(d: &mut TNode, key: &str, v: bool, absent: bool) {
let cur = match d.get(key) {
None => Some(absent),
Some(TNode::Atom(a)) if a.as_slice() == b"true" => Some(true),
Some(TNode::Atom(a)) if a.as_slice() == b"false" => Some(false),
Some(_) => None,
};
if cur != Some(v) {
d.set(key, boolean(v));
}
}
fn num_or_int(v: f64) -> TNode {
if v.fract() == 0.0 && v.abs() < 1e12 { int(v as i64) } else { number(v) }
}
fn paint(rgb: [f64; 3]) -> TNode {
TNode::Array(vec![number(1.0), number(rgb[0]), number(rgb[1]), number(rgb[2])])
}
/// The rectangle as After Effects traces it: each corner twice at the ends of the list and four
/// times in between (245: top-left, top-right, bottom-right, bottom-left).
fn frame_points(f: [f64; 4]) -> TNode {
let [x, y, w, h] = f;
let (l, t, r, b) = (x, y, x + w, y + h);
let corners = [(l, t), (l, t), (r, t), (r, t), (r, t), (r, t), (r, b), (r, b), (r, b), (r, b), (l, b), (l, b), (l, b), (l, b), (l, t), (l, t)];
TNode::Array(corners.iter().flat_map(|(px, py)| [number(*px), number(*py)]).collect())
}
/// The prototype's document (110 or 245) rewritten for `tp`; `None` when the prototype does not
/// have the expected shape.
pub(crate) fn build_doc(proto: &TNode, tp: &TextPlan) -> Option<TNode> {
let mut doc = proto.clone();
// Fonts: the prototype's own stay where the document refers to them; others are appended.
let mut font_index: Vec<(String, usize)> = Vec::new();
{
let list = doc.path_mut("0/1/0")?;
let TNode::Array(entries) = list else { return None };
let template = entries.first()?.clone();
// Font names compare as the stored atoms (UTF-16 bytes): a lossy text conversion would
// make two non-ASCII names equal.
let name_of = |e: &TNode| -> Option<Vec<u8>> {
match e.path("0/0/0")? {
TNode::Atom(a) => Some(a.clone()),
_ => None,
}
};
for (_, s) in &tp.runs {
if font_index.iter().any(|(f, _)| f == &s.font) {
continue;
}
let TNode::Atom(atom) = string(&s.font) else { continue };
let at = match entries.iter().position(|e| name_of(e).as_ref() == Some(&atom)) {
Some(i) => i,
None => {
let mut e = template.clone();
let inner = e.path_mut("0/0")?;
inner.set("0", string(&s.font));
inner.set("2", int(0));
inner.remove("5");
entries.push(e);
entries.len() - 1
}
};
font_index.push((s.font.clone(), at));
}
}
{
let run = doc.path_mut("1/1[0]/0")?;
run.set("0", string(&tp.text));
let p0 = run.path("5/0[0]")?.clone();
let paras: Vec<TNode> = tp
.paras
.iter()
.map(|(len, po)| {
let mut p = p0.clone();
p.set("1", int(i64::try_from(*len).unwrap_or(i64::MAX)));
if let Some(d) = p.path_mut("0/0/5") {
d.set("0", int(po.justify));
// The paragraph settings decoded by the importer (560-569), written only
// where they differ from the prototype.
for (k, v) in ["1", "2", "3", "4", "5"].iter().zip(po.indents) {
set_num_if(d, k, v, 0.0);
}
set_bool_if(d, "21", po.hanging, false);
set_bool_if(d, "29", po.every_line, false);
if atom_f64(d.get("33")).unwrap_or(0.0) != po.direction as f64 {
d.set("33", int(po.direction));
}
}
p
})
.collect();
*run.path_mut("5/0")? = TNode::Array(paras);
let s0 = run.path("6/0[0]")?.clone();
let mut styles = Vec::with_capacity(tp.runs.len());
for (len, s) in &tp.runs {
let mut r = s0.clone();
r.set("1", int(i64::try_from(*len).unwrap_or(i64::MAX)));
let d = r.path_mut("0/0/6")?;
let fi = font_index.iter().find(|(f, _)| f == &s.font).map_or(0, |(_, i)| *i);
d.set("0", int(i64::try_from(fi).unwrap_or(0)));
d.set("1", number(s.size));
d.set("2", boolean(s.faux_bold));
d.set("3", boolean(s.faux_italic));
// Automatic leading: /4 true and /5 0.01 (400); explicit: /4 false, /5 the leading.
d.set("4", boolean(s.leading.is_none()));
d.set("5", number(s.leading.unwrap_or(0.01)));
d.set("8", num_or_int(s.tracking));
d.set("12", int(s.caps));
// Normal text must store 0: the prototypes (and every text After Effects creates by
// script) hold 1, superscript, which After Effects draws at 58.3 % size (526-528).
d.set("13", int(s.script));
// The character settings decoded by the importer (539-555): written only where they
// differ from what the slot holds, so a document in the default state keeps the
// prototype's bytes.
set_num_if(d, "6", s.h_scale, 1.0);
set_num_if(d, "7", s.v_scale, 1.0);
set_num_if(d, "9", s.baseline_shift, 0.0);
if atom_f64(d.get("11")).unwrap_or(1.0) != s.auto_kern as f64 {
d.set("11", int(s.auto_kern));
}
set_bool_if(d, "18", s.ligatures, false);
set_num_if(d, "36", s.tsume, 0.0);
set_bool_if(d, "56", s.apply_fill, true);
set_bool_if(d, "57", s.apply_stroke, false);
set_bool_if(d, "58", s.stroke_over_fill, true);
if let Some(w) = s.stroke_width {
set_num_if(d, "63", w, 1.0);
}
if let Some(fill) = d.path_mut("53/0") {
fill.set("1", paint(s.fill));
}
if let Some(stroke) = d.path_mut("54/0") {
stroke.set("1", paint(s.stroke));
}
styles.push(r);
}
*run.path_mut("6/0")? = TNode::Array(styles);
}
if let Some(f) = tp.frame {
doc.path_mut("0/8/0[0]/0/1")?.set("0", frame_points(f));
}
// The composed layout is dropped: After Effects lays the text out again (t3).
doc.path_mut("1/1[0]/1")?.set("2", TNode::Array(Vec::new()));
Some(doc)
}
/// Rewrites the text document of a text layer block's `Layr` for `tp` 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;
fn find<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> {
if depth > 32 {
return None;
}
if matches!(&c.body, Body::OpaqueList { list_type, .. } if list_type == b"btdk") {
return Some(c);
}
match &mut c.body {
Body::List { children, .. } | Body::Chunks(children) => children.iter_mut().find_map(|k| find(k, depth + 1)),
_ => None,
}
}
fn find_pgui<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> {
if depth > 32 {
return None;
}
if c.is_list(b"btgu") {
return match &mut c.body {
Body::List { children, .. } => children.iter_mut().find(|k| k.is(b"pgui")),
_ => None,
};
}
match &mut c.body {
Body::List { children, .. } | Body::Chunks(children) => children.iter_mut().find_map(|k| find_pgui(k, depth + 1)),
_ => None,
}
}
let btdk = find(layr, 0).ok_or_else(|| tpl("text prototype without a document"))?;
let Body::OpaqueList { data, .. } = &mut btdk.body else { return Err(tpl("text prototype without a document")) };
let proto = crate::export::textdoc::parse(data.as_ref()).ok_or_else(|| tpl("the text prototype's document does not parse"))?;
let doc = build_doc(&proto, tp).ok_or_else(|| tpl("the text prototype's document has another shape"))?;
*data = std::borrow::Cow::Owned(crate::export::textdoc::write(&doc));
if let Some(p) = find_pgui(layr, 0) {
*p = crate::Chunk::data(*b"pgui", guid.to_vec());
}
Ok(())
}
+311
View File
@@ -0,0 +1,311 @@
//! Text animators (`docs/aep-format.md` 3.10; cases 114, 579-594, 728): the animators of a text
//! layer with their properties and range selectors, the inverse of the importer's
//! `text_anim.rs`.
//!
//! The layer's `ADBE Text Animators` group is the one of 579 emptied; every animator is its first
//! animator (one range selector) with the properties and selectors of the EffectCraft animator.
//! An animator property is written whenever the animator has it (its presence is what After
//! Effects shows: Animate > Position adds the entry), a range selector property only when it
//! differs from After Effects' default or carries keys or an expression. Every record has the layout
//! After Effects writes for that property in a one-change case (579-592, 728; `tree_defs`):
//! positions, anchor points, stroke widths and line spacing in pixels, scales, opacity, Start /
//! End / Offset, Amount, Smoothness and the eases in percent, angles in degrees, tracking in 1/1000
//! em, colours ARGB 0..255, popups 1-based (Units, Based On, Mode, Shape in EffectCraft's item
//! order). With Units = Index the selector's range is `Index Start / End / Offset` (583). Keys
//! and expressions are written as on shape properties (R46; 593, 594).
use crate::Chunk;
use effectcraft_keyframe::Value;
use effectcraft_project::{Layer, Node, PropGroup};
use crate::export::plan::CompPlan;
use crate::export::report::{Collector, LossCategory};
use crate::export::shapes::{Conv, Layout, RecVal, ShCx, build_record, c_color, c_popup, c_scalar, rec_value};
use crate::export::tree::{R, kids_mut, set_utf8, tpl};
/// More animators or selectors than this on one layer are not written (and reported).
const MAX_ITEMS: usize = 1024;
/// A range selector in the file's terms.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct SelPlan {
pub name: String,
pub records: Vec<(&'static str, RecVal)>,
pub advanced: Vec<(&'static str, RecVal)>,
}
/// An animator in the file's terms.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct AnimPlan {
pub name: String,
pub props: Vec<(&'static str, RecVal)>,
pub selectors: Vec<SelPlan>,
}
/// The prototypes, built in code (`tree_defs`).
pub(crate) struct AnimProtos {
/// `tdmn ADBE Text Animators` + the emptied group.
pub group: Vec<Chunk<'static>>,
/// `tdmn ADBE Text Animator` + the animator with one range selector and no properties.
pub animator: Vec<Chunk<'static>>,
/// Value records by match name.
pub records: Vec<(String, [Chunk<'static>; 2])>,
}
fn c_vec3(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Vec3(p) => Some(p.to_vec()),
Value::Vec2(p) => Some(vec![p[0], p[1], 0.0]),
_ => None,
}
}
fn c_vec2(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Vec2(p) => Some(p.to_vec()),
Value::Vec3(p) => Some(vec![p[0], p[1]]),
_ => None,
}
}
fn c_bool(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Bool(b) => Some(vec![if *b { 1.0 } else { 0.0 }]),
Value::Scalar(s) => Some(vec![if *s != 0.0 { 1.0 } else { 0.0 }]),
_ => None,
}
}
/// EffectCraft animator property -> stored match name, conversion, key layout (the importer's
/// `PROPS`, 579-592, 728).
const PROPS: &[(&str, &str, Conv, Layout)] = &[
("anchor", "ADBE Text Anchor Point 3D", c_vec3, Layout::Point),
("position", "ADBE Text Position 3D", c_vec3, Layout::Point),
("scale", "ADBE Text Scale 3D", c_vec3, Layout::Size),
("skew", "ADBE Text Skew", c_scalar, Layout::One),
("skewAxis", "ADBE Text Skew Axis", c_scalar, Layout::One),
("rotation", "ADBE Text Rotation", c_scalar, Layout::One),
("opacity", "ADBE Text Opacity", c_scalar, Layout::One),
("fillColor", "ADBE Text Fill Color", c_color, Layout::Color),
("strokeColor", "ADBE Text Stroke Color", c_color, Layout::Color),
("strokeWidth", "ADBE Text Stroke Width", c_scalar, Layout::One),
("tracking", "ADBE Text Tracking Amount", c_scalar, Layout::One),
("lineSpacing", "ADBE Text Line Spacing", c_vec2, Layout::Size),
("blur", "ADBE Text Blur", c_vec2, Layout::Size),
("characterOffset", "ADBE Text Character Offset", c_scalar, Layout::One),
];
/// Properties After Effects adds with another one and EffectCraft keeps at their default: written
/// by After Effects itself (Tracking Type with Tracking, Character Range and Alignment with
/// Character Offset, 728); a value other than the default is reported.
const DEPENDENT: &[(&str, Value)] = &[("trackingType", Value::Enum(0)), ("characterRange", Value::Enum(0)), ("characterAlignment", Value::Enum(1))];
/// Range selector properties: EffectCraft id, stored match names (percent units, index units),
/// conversion, default (stored).
const RANGE: &[(&str, &str, &str, f64)] = &[
("start", "ADBE Text Percent Start", "ADBE Text Index Start", 0.0),
("end", "ADBE Text Percent End", "ADBE Text Index End", 100.0),
("offset", "ADBE Text Percent Offset", "ADBE Text Index Offset", 0.0),
];
const ADVANCED: &[(&str, &str, Conv, Layout, f64)] = &[
("units", "ADBE Text Range Units", c_popup, Layout::Popup, 1.0),
("basedOn", "ADBE Text Range Type2", c_popup, Layout::Popup, 1.0),
("mode", "ADBE Text Selector Mode", c_popup, Layout::Popup, 1.0),
("amount", "ADBE Text Selector Max Amount", c_scalar, Layout::One, 100.0),
("shape", "ADBE Text Range Shape", c_popup, Layout::Popup, 1.0),
("smoothness", "ADBE Text Selector Smoothness", c_scalar, Layout::One, 100.0),
("easeHigh", "ADBE Text Levels Max Ease", c_scalar, Layout::One, 0.0),
("easeLow", "ADBE Text Levels Min Ease", c_scalar, Layout::One, 0.0),
("randomize", "ADBE Text Randomize Order", c_bool, Layout::Popup, 0.0),
("randomSeed", "ADBE Text Random Seed", c_scalar, Layout::One, 0.0),
];
fn layout_of(name: &str) -> Layout {
if let Some((_, _, _, l)) = PROPS.iter().find(|(_, n, ..)| *n == name) {
return *l;
}
if let Some((_, _, _, l, _)) = ADVANCED.iter().find(|(_, n, ..)| *n == name) {
return *l;
}
Layout::One
}
/// The animators of `layer` (its `text/animators` group) in the file's terms; what cannot be
/// written is reported.
pub(crate) fn plan(layer: &Layer, cp: &CompPlan, what: &str, col: &mut Collector) -> Vec<AnimPlan> {
let Some(group) = layer.props.sub("text").and_then(|t| t.sub("animators")) else { return Vec::new() };
let mut cx = ShCx { cp, col };
let mut out = Vec::new();
for (i, node) in group.children.iter().enumerate() {
if i >= MAX_ITEMS {
cx.col.lose(LossCategory::TextLayers, format!("{what}: more than {MAX_ITEMS} text animators, the rest are not written"));
break;
}
let Node::Group(a) = node else { continue };
let here = format!("{what}: animator '{}'", a.name);
if !a.enabled {
cx.col.lose(LossCategory::TextLayers, format!("{here}: a switched-off animator is written switched on (the switch is not decoded)"));
}
let mut props = Vec::new();
if let Some(pg) = a.sub("properties") {
for n in &pg.children {
let Node::Prop(p) = n else { continue };
if let Some((_, name, conv, layout)) = PROPS.iter().find(|(id, ..)| *id == p.match_id) {
let w = format!("{here}: {name}");
if let Some(v) = rec_value(p, *conv, *layout, None, &w, LossCategory::TextLayers, &mut cx) {
props.push((*name, v));
}
} else if let Some((_, def)) = DEPENDENT.iter().find(|(id, _)| *id == p.match_id) {
if p.value != *def || !p.keys.is_empty() || p.has_expression() {
cx.col.lose(LossCategory::TextLayers, format!("{here}: {} is not written (only its default is sampled)", p.name));
}
} else {
cx.col.lose(LossCategory::TextLayers, format!("{here}: the animator property {} is not written", p.name));
}
}
}
let mut selectors = Vec::new();
if let Some(sg) = a.sub("selectors") {
for (k, n) in sg.children.iter().enumerate() {
if k >= MAX_ITEMS {
cx.col.lose(LossCategory::TextLayers, format!("{here}: more than {MAX_ITEMS} selectors, the rest are not written"));
break;
}
let Node::Group(s) = n else { continue };
if s.match_id != "rangeSelector" {
cx.col.lose(LossCategory::TextLayers, format!("{here}: the selector '{}' ({}) is not written (only range selectors)", s.name, s.match_id));
continue;
}
if !s.enabled {
cx.col.lose(
LossCategory::TextLayers,
format!("{here}: the switched-off selector '{}' is written switched on (the switch is not decoded)", s.name),
);
}
selectors.push(plan_selector(s, &here, &mut cx));
}
}
cx.col.exported.text_animators = cx.col.exported.text_animators.saturating_add(1);
out.push(AnimPlan { name: crate::export::plan::cut_name(&a.name, 255, &here, cx.col), props, selectors });
}
out
}
fn plan_selector(s: &PropGroup, animator: &str, cx: &mut ShCx<'_>) -> SelPlan {
let here = format!("{animator} '{}'", s.name);
let adv = s.sub("advanced");
let index = adv.and_then(|a| a.get("units")).is_some_and(|u| u.value == Value::Enum(1));
let mut records = Vec::new();
for (id, percent, idx, default) in RANGE {
let Some(p) = s.get(id) else { continue };
let name = if index { *idx } else { *percent };
// With Units = Index After Effects stores the range in characters, records for all three
// (583).
let default = if index { None } else { Some(std::slice::from_ref(default)) };
if let Some(v) = rec_value(p, c_scalar, Layout::One, default, &format!("{here}: {name}"), LossCategory::TextLayers, cx) {
records.push((name, v));
}
}
let mut advanced = Vec::new();
if let Some(a) = adv {
for (id, name, conv, layout, default) in ADVANCED {
let Some(p) = a.get(id) else { continue };
if let Some(v) = rec_value(p, *conv, *layout, Some(std::slice::from_ref(default)), &format!("{here}: {name}"), LossCategory::TextLayers, cx) {
advanced.push((*name, v));
}
}
}
SelPlan { name: crate::export::plan::cut_name(&s.name, 255, &here, cx.col), records, advanced }
}
fn 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))
}
/// The item's user name (`tdsn/Utf8`).
fn set_name(node: &mut Chunk<'static>, name: &str) -> R<()> {
let kids = kids_mut(node)?;
let tdsn = kids.iter_mut().find(|c| c.is(b"tdsn")).ok_or_else(|| tpl("animator prototype without a name"))?;
set_utf8(tdsn, name)
}
/// Inserts records before the group's first sub-group or end.
fn put_records(t: &AnimProtos, group: &mut Chunk<'static>, records: &[(&'static str, RecVal)], key_list: &Chunk<'static>) -> R<()> {
let kids = kids_mut(group)?;
let mut at = kids.iter().position(|c| c.is(b"tdmn")).unwrap_or(kids.len());
for (name, v) in records {
let [m, node] = t.records.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()).ok_or_else(|| tpl("text animator record prototype missing"))?;
let [m, node] = build_record(m, node, layout_of(name), v, key_list)?;
kids.insert(at, m);
kids.insert(at.saturating_add(1), node);
at = at.saturating_add(2);
}
Ok(())
}
/// Adds the `ADBE Text Animators` group with `anims` to the text layer `layr` (after More
/// Options, as 579 stores it).
pub(crate) fn put_animators(layr: &mut Chunk<'static>, t: &AnimProtos, anims: &[AnimPlan], key_list: &Chunk<'static>) -> R<()> {
if anims.is_empty() {
return Ok(());
}
let [gm, mut group] = <[Chunk<'static>; 2]>::try_from(t.group.clone()).map_err(|_| tpl("animators prototype incomplete"))?;
let [am, anim_proto] = <[Chunk<'static>; 2]>::try_from(t.animator.clone()).map_err(|_| tpl("animator prototype incomplete"))?;
let mut built = Vec::with_capacity(anims.len() * 2);
for a in anims {
let mut node = anim_proto.clone();
set_name(&mut node, &a.name)?;
let kids = kids_mut(&mut node)?;
// Selectors: one copy of the prototype's selector each.
let si = pos(kids, "ADBE Text Selectors").ok_or_else(|| tpl("animator prototype without selectors"))?;
{
let sels = kids.get_mut(si + 1).ok_or_else(|| tpl("animator prototype without selectors"))?;
let sk = kids_mut(sels)?;
let at = pos(sk, "ADBE Text Selector").ok_or_else(|| tpl("animator prototype without a selector"))?;
let sm = sk.get(at).cloned().ok_or_else(|| tpl("animator prototype without a selector"))?;
let sproto = sk.get(at + 1).cloned().ok_or_else(|| tpl("animator prototype without a selector"))?;
sk.drain(at..at + 2);
let mut sel_nodes = Vec::with_capacity(a.selectors.len() * 2);
for s in &a.selectors {
let mut sn = sproto.clone();
set_name(&mut sn, &s.name)?;
if !s.advanced.is_empty() {
let snk = kids_mut(&mut sn)?;
let ai = pos(snk, "ADBE Text Range Advanced").ok_or_else(|| tpl("selector prototype without Advanced"))?;
let adv = snk.get_mut(ai + 1).ok_or_else(|| tpl("selector prototype without Advanced"))?;
put_records(t, adv, &s.advanced, key_list)?;
}
put_records(t, &mut sn, &s.records, key_list)?;
sel_nodes.push(sm.clone());
sel_nodes.push(sn);
}
sk.splice(at..at, sel_nodes);
}
let pi = pos(kids, "ADBE Text Animator Properties").ok_or_else(|| tpl("animator prototype without properties"))?;
let props = kids.get_mut(pi + 1).ok_or_else(|| tpl("animator prototype without properties"))?;
put_records(t, props, &a.props, key_list)?;
built.push(am.clone());
built.push(node);
}
{
let gk = kids_mut(&mut group)?;
let end = pos(gk, "ADBE Group End").unwrap_or(gk.len());
gk.splice(end..end, built);
}
// Into the layer's `ADBE Text Properties`, before its Group End.
let root = crate::export::tree::list_mut(layr, b"tdgp")?;
let rk = kids_mut(root)?;
let ti = pos(rk, "ADBE Text Properties").ok_or_else(|| tpl("text layer without text properties"))?;
let tp = rk.get_mut(ti + 1).ok_or_else(|| tpl("text layer without text properties"))?;
let tk = kids_mut(tp)?;
let end = pos(tk, "ADBE Group End").unwrap_or(tk.len());
tk.splice(end..end, [gm, group]);
Ok(())
}
+330
View File
@@ -0,0 +1,330 @@
//! The text document dictionary (`LIST btdk`, `docs/aep-format.md` 3.10) as an editable tree:
//! `/key value` pairs, `<< >>` dictionaries, `[ ]` arrays, and atoms (numbers, names, booleans,
//! strings) kept as their raw bytes. Writing it back uses After Effects' own spacing (one space
//! between tokens, ` /key value` at the top level), so an unedited tree writes the bytes it was
//! read from.
/// Deepest nesting read (After Effects' documents nest about 16 deep).
const MAX_DEPTH: usize = 64;
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum TNode {
Dict(Vec<(String, TNode)>),
Array(Vec<TNode>),
/// A number, name, boolean or string, as stored.
Atom(Vec<u8>),
}
impl TNode {
pub(crate) fn get(&self, key: &str) -> Option<&TNode> {
match self {
TNode::Dict(kv) => kv.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
}
}
pub(crate) fn get_mut(&mut self, key: &str) -> Option<&mut TNode> {
match self {
TNode::Dict(kv) => kv.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
}
}
pub(crate) fn at_mut(&mut self, i: usize) -> Option<&mut TNode> {
match self {
TNode::Array(v) => v.get_mut(i),
_ => None,
}
}
/// The node at a `/`-separated path of keys and `[n]` indices (`1/1[0]/0`).
pub(crate) fn path_mut(&mut self, path: &str) -> Option<&mut TNode> {
let mut at = self;
for step in path.split('/').filter(|s| !s.is_empty()) {
let (key, idx) = match step.split_once('[') {
Some((k, rest)) => (k, rest.strip_suffix(']').and_then(|n| n.parse::<usize>().ok())),
None => (step, None),
};
at = at.get_mut(key)?;
if let Some(i) = idx {
at = at.at_mut(i)?;
}
}
Some(at)
}
pub(crate) fn path(&self, path: &str) -> Option<&TNode> {
let mut at = self;
for step in path.split('/').filter(|s| !s.is_empty()) {
let (key, idx) = match step.split_once('[') {
Some((k, rest)) => (k, rest.strip_suffix(']').and_then(|n| n.parse::<usize>().ok())),
None => (step, None),
};
at = at.get(key)?;
if let Some(i) = idx {
at = match at {
TNode::Array(v) => v.get(i)?,
_ => return None,
};
}
}
Some(at)
}
/// Sets (or adds) `key` in a dictionary.
pub(crate) fn set(&mut self, key: &str, value: TNode) {
if let TNode::Dict(kv) = self {
match kv.iter_mut().find(|(k, _)| k == key) {
Some((_, v)) => *v = value,
None => kv.push((key.to_string(), value)),
}
}
}
pub(crate) fn remove(&mut self, key: &str) {
if let TNode::Dict(kv) = self {
kv.retain(|(k, _)| k != key);
}
}
}
fn is_ws(c: u8) -> bool {
matches!(c, b' ' | b'\t' | b'\r' | b'\n' | 0)
}
fn is_delim(c: u8) -> bool {
is_ws(c) || matches!(c, b'/' | b'[' | b']' | b'(' | b')' | b'<' | b'>')
}
struct P<'a> {
b: &'a [u8],
i: usize,
}
impl P<'_> {
fn ws(&mut self) {
while self.b.get(self.i).copied().is_some_and(is_ws) {
self.i += 1;
}
}
fn peek(&self) -> Option<u8> {
self.b.get(self.i).copied()
}
fn starts(&self, s: &[u8]) -> bool {
self.b.get(self.i..).is_some_and(|r| r.starts_with(s))
}
fn name(&mut self) -> Option<String> {
if self.peek() != Some(b'/') {
return None;
}
self.i += 1;
let start = self.i;
while self.peek().is_some_and(|c| !is_delim(c)) {
self.i += 1;
}
Some(String::from_utf8_lossy(self.b.get(start..self.i)?).to_string())
}
fn value(&mut self, depth: usize) -> Option<TNode> {
if depth > MAX_DEPTH {
return None;
}
self.ws();
if self.starts(b"<<") {
self.i += 2;
let mut kv = Vec::new();
loop {
self.ws();
if self.starts(b">>") {
self.i += 2;
return Some(TNode::Dict(kv));
}
let k = self.name()?;
let v = self.value(depth + 1)?;
kv.push((k, v));
}
}
match self.peek()? {
b'[' => {
self.i += 1;
let mut v = Vec::new();
loop {
self.ws();
if self.peek()? == b']' {
self.i += 1;
return Some(TNode::Array(v));
}
v.push(self.value(depth + 1)?);
}
}
b'(' => {
let start = self.i;
self.i += 1;
loop {
match self.peek()? {
b'\\' => self.i += 2,
b')' => {
self.i += 1;
break;
}
_ => self.i += 1,
}
}
Some(TNode::Atom(self.b.get(start..self.i)?.to_vec()))
}
b'/' => {
// A name used as a value (`/CoolTypeFont`, `/nil`).
let start = self.i;
self.name()?;
Some(TNode::Atom(self.b.get(start..self.i)?.to_vec()))
}
_ => {
let start = self.i;
while self.peek().is_some_and(|c| !is_delim(c)) {
self.i += 1;
}
if self.i == start {
return None;
}
Some(TNode::Atom(self.b.get(start..self.i)?.to_vec()))
}
}
}
}
/// Parses a whole document (a top-level sequence of `/key value` pairs); `None` when it is not
/// well formed.
pub(crate) fn parse(b: &[u8]) -> Option<TNode> {
let mut p = P { b, i: 0 };
let mut kv = Vec::new();
loop {
p.ws();
if p.i >= b.len() {
return Some(TNode::Dict(kv));
}
let k = p.name()?;
let v = p.value(0)?;
kv.push((k, v));
}
}
fn write_value(n: &TNode, out: &mut Vec<u8>, depth: usize) {
if depth > MAX_DEPTH {
out.extend_from_slice(b"<< >>");
return;
}
match n {
TNode::Atom(a) => out.extend_from_slice(a),
TNode::Array(v) => {
out.push(b'[');
for x in v {
out.push(b' ');
write_value(x, out, depth + 1);
}
out.extend_from_slice(b" ]");
}
TNode::Dict(kv) => {
out.extend_from_slice(b"<<");
for (k, v) in kv {
out.extend_from_slice(b" /");
out.extend_from_slice(k.as_bytes());
out.push(b' ');
write_value(v, out, depth + 1);
}
out.extend_from_slice(b" >>");
}
}
}
/// The document's bytes.
pub(crate) fn write(doc: &TNode) -> Vec<u8> {
let mut out = Vec::new();
if let TNode::Dict(kv) = doc {
for (k, v) in kv {
out.extend_from_slice(b" /");
out.extend_from_slice(k.as_bytes());
out.push(b' ');
write_value(v, &mut out, 0);
}
}
out
}
/// A string atom: `(` + `fe ff` + UTF-16BE + `)`, with `(`, `)` and `\` escaped.
pub(crate) fn string(s: &str) -> TNode {
let mut out = vec![b'('];
let mut push = |b: u8| {
if matches!(b, b'(' | b')' | b'\\') {
out.push(b'\\');
}
out.push(b);
};
push(0xfe);
push(0xff);
for u in s.encode_utf16() {
let [hi, lo] = u.to_be_bytes();
push(hi);
push(lo);
}
out.push(b')');
TNode::Atom(out)
}
/// A number as After Effects writes it: integers without a point, others with one (`60.0`,
/// `.5`, `-49.05029`).
pub(crate) fn number(v: f64) -> TNode {
let v = if v.is_finite() { v } else { 0.0 };
let mut s = if v.fract() == 0.0 && v.abs() < 1e15 { format!("{v:.1}") } else { format!("{}", (v * 1e5).round() / 1e5) };
// `.5` and `-.25`, but `0.0` (113: `[ 1.0 1.0 .5 0.0 ]`).
if v != 0.0 {
if let Some(rest) = s.strip_prefix("0.") {
s = format!(".{rest}");
} else if let Some(rest) = s.strip_prefix("-0.") {
s = format!("-.{rest}");
}
}
TNode::Atom(s.into_bytes())
}
pub(crate) fn int(v: i64) -> TNode {
TNode::Atom(v.to_string().into_bytes())
}
pub(crate) fn boolean(v: bool) -> TNode {
TNode::Atom(if v { b"true".to_vec() } else { b"false".to_vec() })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_and_writes_back() {
let src = b" /98 << /0 13 >> /0 << /1 [ 1.0 .5 (\xfe\xff\x00A\\)) /nil << >> [ ] ] >>";
let t = parse(src).expect("parse");
assert_eq!(write(&t), src.to_vec());
assert_eq!(t.path("0/1[1]"), Some(&TNode::Atom(b".5".to_vec())));
}
#[test]
fn numbers_and_strings_as_after_effects_writes_them() {
assert_eq!(number(60.0), TNode::Atom(b"60.0".to_vec()));
assert_eq!(number(0.5), TNode::Atom(b".5".to_vec()));
assert_eq!(number(0.0), TNode::Atom(b"0.0".to_vec()));
assert_eq!(number(-0.25), TNode::Atom(b"-.25".to_vec()));
assert_eq!(number(98.123456), TNode::Atom(b"98.12346".to_vec()));
assert_eq!(string("A)"), TNode::Atom(b"(\xfe\xff\x00A\x00\\))".to_vec()));
}
#[test]
fn damaged_documents_are_none_not_a_panic() {
for bad in [&b"/a << /b"[..], b"/a [ 1 2", b"/a (unterminated", b"<<", b"/", b"/a >>", b"/a ]"] {
let _ = parse(bad);
}
let deep: Vec<u8> = std::iter::once(b"/a ".to_vec()).chain(std::iter::repeat_n(b"[ ".to_vec(), 500)).flatten().collect();
assert_eq!(parse(&deep), None);
}
}
+179
View File
@@ -0,0 +1,179 @@
//! The text document a text layer starts from, built in code (`docs/aep-format.md` 3.10): the
//! smallest dictionary After Effects reads back unchanged (read-backs t2-*, t3-*). `text::build_doc`
//! then writes the text, the runs, the fonts and the box frame into it.
//!
//! What stays and why: the font list (`/0/1`, names only), the style and paragraph sheets with
//! their name only (`/0/5`, `/0/6`; without them the layer is skipped), one text frame (`/0/8`: a
//! point text's, or a box text's with its outline), the document settings (`/1/0`: the line-break
//! classes of seven characters, the superscript and subscript size and offset, the small caps
//! size; without them, or with `/1/0/0` cut down, After Effects refuses or crashes), the composer
//! (`/1/5`; without it After Effects rewrites the document on open) and one run with one
//! paragraph and one style (`/1/1`) and an empty layout.
use crate::export::textdoc::{TNode, boolean, int, number, string};
fn dict(kv: Vec<(&str, TNode)>) -> TNode {
TNode::Dict(kv.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
}
fn name(n: &str) -> TNode {
TNode::Atom(format!("/{n}").into_bytes())
}
fn numbers(v: &[f64]) -> TNode {
TNode::Array(v.iter().map(|x| number(*x)).collect())
}
/// The fonts of a new document (the first is the one the runs use until `build_doc` sets theirs).
const FONTS: [&str; 4] = ["TimesNewRomanPSMT", "Myriad-Roman", "MyriadPro-Regular", "AdobeInvisFont"];
/// The line-break class of the characters the text engine treats specially: space, carriage
/// return, tab, paragraph separator, end of text, ideographic space, soft hyphen.
const BREAK_CLASSES: [(char, &str); 7] = [(' ', "1"), ('\r', "6"), ('\t', "0"), ('\u{2029}', "5"), ('\u{3}', "5"), ('\u{3000}', "1"), ('\u{ad}', "3")];
/// A sheet list with one sheet named `Normal RGB`, used by every run (`/1 [ << /0 0 >> ]`).
fn sheets() -> TNode {
dict(vec![("0", TNode::Array(vec![dict(vec![("0", dict(vec![("0", string("Normal RGB"))]))])])), ("1", TNode::Array(vec![dict(vec![("0", int(0))])]))])
}
/// The text frame: a point text's (no outline, size -1), or a box text's with an outline that
/// `build_doc` replaces with the layer's box.
fn frame(boxed: bool) -> TNode {
let (kind, size) = if boxed { (Some(1), -2.0) } else { (None, -1.0) };
let mut settings = vec![("6", numbers(&[size, size])), ("11", dict(vec![("4", int(size as i64)), ("18", number(size)), ("22", number(0.025))]))];
if let Some(k) = kind {
settings.insert(0, ("0", int(k)));
}
let mut entry = Vec::new();
if boxed {
entry.push(("1", dict(vec![("0", numbers(&[0.0; 32]))])));
}
entry.push(("2", dict(settings)));
dict(vec![("0", TNode::Array(vec![dict(vec![("0", dict(entry))])]))])
}
fn paint() -> TNode {
dict(vec![("99", name("SimplePaint")), ("0", dict(vec![("0", int(1)), ("1", numbers(&[1.0, 1.0, 1.0, 1.0]))]))])
}
/// The run: an empty text with one paragraph and one style run (the keys `build_doc` writes, at
/// the values it treats as unset) and an empty layout.
fn run() -> TNode {
let para = dict(vec![
("0", int(0)),
("1", number(0.0)),
("2", number(0.0)),
("3", number(0.0)),
("4", number(0.0)),
("5", number(0.0)),
("21", boolean(false)),
("29", boolean(false)),
("33", int(0)),
]);
let style = dict(vec![
("0", int(0)),
("1", number(12.0)),
("2", boolean(false)),
("3", boolean(false)),
("4", boolean(true)),
("5", number(0.01)),
("6", number(1.0)),
("7", number(1.0)),
("8", int(0)),
("9", number(0.0)),
("11", int(1)),
("12", int(0)),
("13", int(0)),
("18", boolean(false)),
("36", number(0.0)),
("53", paint()),
("54", paint()),
("56", boolean(true)),
("57", boolean(false)),
("58", boolean(true)),
("63", number(1.0)),
]);
// Each run names its sheet (`/0`) and the other sheet's index (0), in key order.
let entry = |kv: Vec<(&str, TNode)>| {
let mut inner = vec![("0", string(""))];
inner.extend(kv);
TNode::Array(vec![dict(vec![("0", dict(vec![("0", dict(inner))])), ("1", int(0))])])
};
let text = dict(vec![
("0", string("")),
("5", dict(vec![("0", entry(vec![("5", para), ("6", int(0))]))])),
("6", dict(vec![("0", entry(vec![("5", int(0)), ("6", style)]))])),
]);
let layout = dict(vec![("0", TNode::Array(vec![dict(vec![("0", int(0))])])), ("2", TNode::Array(Vec::new()))]);
dict(vec![("0", text), ("1", layout)])
}
/// A new document, for a box text when `boxed`.
pub(crate) fn document(boxed: bool) -> TNode {
let fonts = FONTS.iter().map(|f| dict(vec![("0", dict(vec![("99", name("CoolTypeFont")), ("0", dict(vec![("0", string(f))]))]))])).collect();
let resources = dict(vec![("1", dict(vec![("0", TNode::Array(fonts))])), ("5", sheets()), ("6", sheets()), ("8", frame(boxed))]);
let classes = BREAK_CLASSES.iter().map(|(c, class)| dict(vec![("0", string(&c.to_string())), ("1", string(class))])).collect();
let settings = dict(vec![
("0", dict(vec![("0", int(3)), ("1", TNode::Array(classes))])),
("1", int(0)),
("2", int(0)),
// Superscript size and offset, subscript size and offset, small caps size.
("3", number(0.583)),
("4", number(0.333)),
("5", number(0.583)),
("6", number(0.333)),
("7", number(0.7)),
("8", boolean(true)),
("16", boolean(false)),
("17", int(0)),
]);
let composer = TNode::Array(vec![dict(vec![
("0", int(0)),
("1", dict(vec![("0", int(7)), ("1", int(10)), ("2", int(0)), ("3", string("DVA"))])),
("2", string_bits("10000001000001010001100000000011101000000000000110000000")),
("3", string_bits("00110")),
("4", TNode::Array(vec![dict(vec![("0", int(0)), ("1", string("Version 7.12"))])])),
])]);
let doc_body = dict(vec![("0", settings), ("5", composer), ("1", TNode::Array(vec![run()]))]);
dict(vec![("0", resources), ("1", doc_body)])
}
/// A string of bits as the composer stores its flags: plain ASCII between parentheses.
fn string_bits(bits: &str) -> TNode {
TNode::Atom(format!("({bits})").into_bytes())
}
#[cfg(test)]
mod tests {
#[test]
fn the_document_parses_back_and_has_the_paths_build_doc_writes() {
for boxed in [false, true] {
let doc = super::document(boxed);
let bytes = crate::export::textdoc::write(&doc);
assert_eq!(crate::export::textdoc::parse(&bytes), Some(doc.clone()));
for path in ["0/1/0", "1/1[0]/0/5/0[0]/0/0/5", "1/1[0]/0/6/0[0]/0/0/6/53/0", "1/1[0]/1"] {
assert!(doc.path(path).is_some(), "{path}");
}
assert_eq!(doc.path("0/8/0[0]/0/1").is_some(), boxed);
}
}
}
#[cfg(test)]
mod needed {
/// The parts After Effects skips the layer without, or crashes on (read-backs t2-*, t3-*).
#[test]
fn the_document_keeps_what_after_effects_needs() {
for boxed in [false, true] {
let doc = super::document(boxed);
for path in ["0/5", "0/6", "0/8", "1/0", "1/5", "1/0/0/0"] {
assert!(doc.path(path).is_some(), "{path}");
}
match doc.path("1/0/0/1") {
Some(crate::export::textdoc::TNode::Array(classes)) => assert_eq!(classes.len(), 7),
other => panic!("line-break classes: {other:?}"),
}
assert!(doc.path("1/1[0]/0/5/0[0]/0/0/6").is_some() && doc.path("1/1[0]/0/6/0[0]/0/0/5").is_some());
}
}
}
+134
View File
@@ -0,0 +1,134 @@
//! The composition time base: the pair (frame duration, time scale) After Effects stores for a
//! frame rate, and conversions between [`Tick`]s and time units.
//!
//! Evidence (generated compositions saved by After Effects, see `docs/aep-export.md`): the time
//! scale is 23 976 for the NTSC rates (frame duration 1000, 800, 400, 200 for 23.976, 29.97,
//! 59.94, 119.88); for every other rate the frame duration is the smallest power of two for which
//! `rate x frame duration >= 24 576` (25 fps: 1024 and 25 600; 12 fps: 2048 and 24 576; 1 fps:
//! 32 768 and 32 768; 240 fps: 128 and 30 720).
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
/// Frame duration and time scale in units; one frame lasts `frame_duration` units and a second
/// has `timescale` units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct TimeBase {
pub frame_duration: u32,
pub timescale: u32,
}
/// The 16.16 fixed-point rate After Effects stores next to the time base (a float32 rate).
pub(crate) fn fixed_rate(rate: FrameRate) -> u32 {
let fps = ntsc_typed(rate).unwrap_or(rate.as_f64() as f32);
let v = (f64::from(fps) * 65536.0).round();
if v.is_finite() && v >= 0.0 && v <= f64::from(u32::MAX) { v as u32 } else { 0 }
}
/// The typed value of an NTSC rate (23.976, 29.97, 59.94, 119.88), which After Effects stores as
/// a float32 of exactly these decimals.
pub(crate) fn ntsc_typed(rate: FrameRate) -> Option<f32> {
[(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)
}
/// The time base for `rate`, or `None` for a rate After Effects cannot hold (non-positive, or not
/// representable with a frame duration that is a power of two).
pub(crate) fn time_base(rate: FrameRate) -> Option<TimeBase> {
if rate.num <= 0 || rate.den <= 0 {
return None;
}
if let Some(v) = ntsc_typed(rate) {
let fd = if v < 24.0 {
1000
} else if v < 30.0 {
800
} else if v < 60.0 {
400
} else {
200
};
return Some(TimeBase { frame_duration: fd, timescale: 23976 });
}
let (num, den) = (i128::from(rate.num), i128::from(rate.den));
let mut fd: i128 = 1;
while fd <= 65536 {
let ts = num.checked_mul(fd)?;
if ts % den == 0 {
let ts = ts / den;
if ts >= 24576 {
return Some(TimeBase { frame_duration: u32::try_from(fd).ok()?, timescale: u32::try_from(ts).ok()? });
}
}
fd *= 2;
}
None
}
impl TimeBase {
/// `tick` in time units, rounded to the nearest unit; the second value tells whether it was
/// not exact.
pub fn units(&self, tick: Tick) -> (i64, bool) {
let n = i128::from(tick.0) * i128::from(self.timescale);
let d = i128::from(TICKS_PER_SECOND);
let q = n.div_euclid(d);
let r = n.rem_euclid(d);
let rounded = if r * 2 >= d { q + 1 } else { q };
(i64::try_from(rounded).unwrap_or(if rounded < 0 { i64::MIN } else { i64::MAX }), r != 0)
}
/// Whole frames of `tick` (nearest).
pub fn frames(&self, tick: Tick, rate: FrameRate) -> i64 {
let n = i128::from(tick.0) * i128::from(rate.num);
let d = i128::from(TICKS_PER_SECOND) * i128::from(rate.den.max(1));
let q = n.div_euclid(d);
let r = n.rem_euclid(d);
let f = if r * 2 >= d { q + 1 } else { q };
i64::try_from(f).unwrap_or(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rates_match_after_effects() {
let tb = |n, d| time_base(FrameRate::new(n, d)).map(|t| (t.frame_duration, t.timescale));
assert_eq!(tb(25, 1), Some((1024, 25600)));
assert_eq!(tb(30, 1), Some((1024, 30720)));
assert_eq!(tb(24, 1), Some((1024, 24576)));
assert_eq!(tb(12, 1), Some((2048, 24576)));
assert_eq!(tb(25, 2), Some((2048, 25600)));
assert_eq!(tb(15, 1), Some((2048, 30720)));
assert_eq!(tb(48, 1), Some((512, 24576)));
assert_eq!(tb(50, 1), Some((512, 25600)));
assert_eq!(tb(60, 1), Some((512, 30720)));
assert_eq!(tb(240, 1), Some((128, 30720)));
assert_eq!(tb(1, 1), Some((32768, 32768)));
assert_eq!(tb(30000, 1001), Some((800, 23976)));
assert_eq!(tb(24000, 1001), Some((1000, 23976)));
assert_eq!(tb(60000, 1001), Some((400, 23976)));
assert_eq!(tb(120000, 1001), Some((200, 23976)));
assert_eq!(tb(0, 1), None);
assert_eq!(tb(1, 0), None);
}
#[test]
fn fixed_point_rates() {
assert_eq!(fixed_rate(FrameRate::new(25, 1)), 0x19_0000);
assert_eq!(fixed_rate(FrameRate::FPS_29_97), 1_964_114);
assert_eq!(fixed_rate(FrameRate::FPS_23_976), 1_571_291);
assert_eq!(fixed_rate(FrameRate::new(12, 1)), 0xc0000);
}
#[test]
fn units_round_to_the_nearest() {
let tb = TimeBase { frame_duration: 1024, timescale: 25600 };
assert_eq!(tb.units(Tick(TICKS_PER_SECOND)), (25600, false));
assert_eq!(tb.units(Tick(TICKS_PER_SECOND / 3)).0, 8533);
assert!(tb.units(Tick(TICKS_PER_SECOND / 3)).1);
assert_eq!(tb.frames(Tick(TICKS_PER_SECOND * 2), FrameRate::new(25, 1)), 50);
}
}
+109
View File
@@ -0,0 +1,109 @@
//! Small helpers to edit a chunk tree without panicking: every accessor returns a `Result` with
//! [`crate::export::AepExportError::Internal`] when a prototype does not have the expected shape.
use crate::{Body, Chunk};
use crate::export::AepExportError;
pub(crate) type R<T> = Result<T, AepExportError>;
pub(crate) fn tpl(msg: &'static str) -> AepExportError {
AepExportError::Internal(msg)
}
/// The bytes of a data chunk, owned and mutable.
pub(crate) fn data_mut<'a>(c: &'a mut Chunk<'static>) -> R<&'a mut Vec<u8>> {
match &mut c.body {
Body::Data(d) => Ok(d.to_mut()),
_ => Err(tpl("expected a data chunk")),
}
}
/// The child vector of a list or nested chunk.
pub(crate) fn kids_mut<'a>(c: &'a mut Chunk<'static>) -> R<&'a mut Vec<Chunk<'static>>> {
match &mut c.body {
Body::List { children, .. } | Body::Chunks(children) => Ok(children),
_ => Err(tpl("expected a list chunk")),
}
}
pub(crate) fn child_mut<'a>(c: &'a mut Chunk<'static>, id: &[u8; 4]) -> R<&'a mut Chunk<'static>> {
kids_mut(c)?.iter_mut().find(|k| k.is(id)).ok_or_else(|| tpl("missing child chunk"))
}
pub(crate) fn list_mut<'a>(c: &'a mut Chunk<'static>, list_type: &[u8; 4]) -> R<&'a mut Chunk<'static>> {
kids_mut(c)?.iter_mut().find(|k| k.is_list(list_type)).ok_or_else(|| tpl("missing child list"))
}
/// Mutable bytes of the data child `id`.
pub(crate) fn child_data<'a>(c: &'a mut Chunk<'static>, id: &[u8; 4]) -> R<&'a mut Vec<u8>> {
data_mut(child_mut(c, id)?)
}
pub(crate) fn put(d: &mut [u8], at: usize, bytes: &[u8]) -> R<()> {
let end = at.checked_add(bytes.len()).ok_or_else(|| tpl("offset overflow"))?;
let dst = d.get_mut(at..end).ok_or_else(|| tpl("chunk shorter than its layout"))?;
dst.copy_from_slice(bytes);
Ok(())
}
pub(crate) fn put_u8(d: &mut [u8], at: usize, v: u8) -> R<()> {
put(d, at, &[v])
}
pub(crate) fn put_u16(d: &mut [u8], at: usize, v: u16) -> R<()> {
put(d, at, &v.to_be_bytes())
}
pub(crate) fn put_u32(d: &mut [u8], at: usize, v: u32) -> R<()> {
put(d, at, &v.to_be_bytes())
}
pub(crate) fn put_i32(d: &mut [u8], at: usize, v: i32) -> R<()> {
put(d, at, &v.to_be_bytes())
}
pub(crate) fn put_f32(d: &mut [u8], at: usize, v: f32) -> R<()> {
put(d, at, &v.to_be_bytes())
}
pub(crate) fn put_f64(d: &mut [u8], at: usize, v: f64) -> R<()> {
put(d, at, &v.to_be_bytes())
}
/// Sets or clears the bits `mask` of byte `at`.
pub(crate) fn put_bits(d: &mut [u8], at: usize, mask: u8, on: bool) -> R<()> {
let b = d.get_mut(at).ok_or_else(|| tpl("chunk shorter than its layout"))?;
if on {
*b |= mask;
} else {
*b &= !mask;
}
Ok(())
}
/// Writes `text` NUL padded into `d[at..at + len]` (cut at a character boundary so that at least
/// one NUL remains).
pub(crate) fn put_cstr(d: &mut [u8], at: usize, len: usize, text: &str) -> R<()> {
let end = at.checked_add(len).ok_or_else(|| tpl("offset overflow"))?;
let dst = d.get_mut(at..end).ok_or_else(|| tpl("chunk shorter than its layout"))?;
dst.fill(0);
let mut n = 0;
for ch in text.chars() {
let l = ch.len_utf8();
if n + l >= len {
break;
}
let mut buf = [0u8; 4];
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;
}
}
n += l;
}
Ok(())
}
/// 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(())
}
+299
View File
@@ -0,0 +1,299 @@
//! The camera, light, shape and text animator skeletons as tables of [`Node`]s: match names, states, default
//! names and the decoded fields of each record (`tree_spec`). The rows were listed from our own
//! cases (the case numbers in each doc comment) through the decoded fields only.
#![cfg_attr(rustfmt, rustfmt::skip)]
use crate::export::tree_spec::{Node, Node::{G, O, P, R}, Rec};
/// The property tree of a two-node camera layer (256): Transform with its records and the Camera Options group.
pub(crate) static CAMERA_ROOT: &[Node] = &[
G("ADBE Transform Group", 1, "-_0_/-", &[
R("ADBE Anchor Point", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[960.0, 540.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Position", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[(76, 1), (77, 1)], cdat_len: 72, cdat: &[0.0, 0.0, -2666.6666666], key_size: 0, limits: None, tdpi: None }),
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Position_2", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Scale", Rec { state: 3, label: "-_0_/-", dims: 3, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 120, cdat: &[1.0, 1.0, 1.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Rotate Z", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
]),
G("ADBE Camera Options Group", 1, "-_0_/-", &[
]),
];
/// The property tree of a spot light layer (254).
pub(crate) static SPOT_ROOT: &[Node] = &[
G("ADBE Transform Group", 1, "-_0_/-", &[
R("ADBE Anchor Point", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[960.0, 540.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Position", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[(76, 1), (77, 1)], cdat_len: 72, cdat: &[0.0, 0.0, -1333.3333333], key_size: 0, limits: None, tdpi: None }),
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Position_2", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Scale", Rec { state: 3, label: "-_0_/-", dims: 3, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 120, cdat: &[1.0, 1.0, 1.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Rotate Z", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
]),
G("ADBE Light Options Group", 1, "-_0_/-", &[
G("ADBE Light Env Atom", 3, "-_0_/-", &[
]),
R("ADBE Light Backgd Visible", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Light Backgd Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Light Backgd Blur", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Light Intensity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Light Falloff Start", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[500.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Light Falloff Distance", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[500.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Casts Shadows", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
]),
];
/// The property tree of a point light layer (252).
pub(crate) static POINT_ROOT: &[Node] = &[
G("ADBE Transform Group", 1, "-_0_/-", &[
R("ADBE Anchor Point", Rec { state: 3, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[960.0, 540.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Position", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[(76, 1), (77, 1)], cdat_len: 72, cdat: &[0.0, 0.0, -1333.3333333], key_size: 0, limits: None, tdpi: None }),
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Position_2", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Scale", Rec { state: 3, label: "-_0_/-", dims: 3, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 120, cdat: &[1.0, 1.0, 1.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
O("ADBE Orientation", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x00060007, byte5: 0x07, header: &[(79, 1)], cdat_len: 24, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Rotate X", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Rotate Y", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Rotate Z", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
]),
G("ADBE Light Options Group", 1, "-_0_/-", &[
G("ADBE Light Env Atom", 3, "-_0_/-", &[
]),
R("ADBE Light Backgd Visible", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Light Backgd Opacity", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Light Backgd Blur", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Light Cone Angle", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[90.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Light Cone Feather 2", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Light Falloff Start", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[500.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Light Falloff Distance", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[500.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Casts Shadows", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
]),
];
/// The property tree of a shape layer (519) apart from Time Remapping and the contents.
pub(crate) static SHAPE_ROOT: &[Node] = &[
G("ADBE Root Vectors Group", 1025, "-_0_/-", &[
]),
G("ADBE Transform Group", 1, "-_0_/-", &[
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
O("ADBE Orientation", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x00060007, byte5: 0x07, header: &[(79, 1)], cdat_len: 24, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Rotate X", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Rotate Y", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
]),
G("ADBE Layer Styles", 3, "-_0_/-", &[
G("ADBE Blend Options Group", 3, "-_0_/-", &[
G("ADBE Adv Blend Group", 1, "-_0_/-", &[
]),
]),
G("dropShadow/enabled", 2, "-_0_/-", &[
]),
G("innerShadow/enabled", 2, "-_0_/-", &[
]),
G("outerGlow/enabled", 2, "-_0_/-", &[
]),
G("innerGlow/enabled", 2, "-_0_/-", &[
]),
G("bevelEmboss/enabled", 2, "-_0_/-", &[
]),
G("chromeFX/enabled", 2, "-_0_/-", &[
]),
G("solidFill/enabled", 2, "-_0_/-", &[
]),
G("gradientFill/enabled", 2, "-_0_/-", &[
]),
G("patternFill/enabled", 2, "-_0_/-", &[
]),
G("frameFX/enabled", 2, "-_0_/-", &[
]),
]),
G("ADBE Extrsn Options Group", 3, "-_0_/-", &[
R("ADBE Bevel Direction", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
]),
G("ADBE Material Options Group", 3, "-_0_/-", &[
R("ADBE Casts Shadows", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Light Transmission", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Accepts Shadows", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Accepts Lights", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Shadow Color", Rec { state: 3, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Appears in Reflections", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Ambient Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Diffuse Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Specular Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Shininess Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[5.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Metal Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Reflection Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Glossiness Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[100.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Fresnel Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Transparency Coefficient", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Transp Rolloff", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Index of Refraction", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: Some((1.0, 2.0)), tdpi: None }),
]),
G("ADBE Audio Group", 3, "-_0_/-", &[
]),
G("ADBE Layer Sets", 3, "-_0_/-", &[
]),
];
/// The camera and light option records the exporter writes (342-345, 254).
pub(crate) static OPTIONS: &[Node] = &[
R("ADBE Camera Depth of Field", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Camera Focus Distance", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[800.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Camera Aperture", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Light Intensity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Light Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 255.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Light Cone Angle", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[60.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Light Cone Feather 2", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
];
/// The shape items the exporter writes, as empty groups with their default names (240, 451-471).
pub(crate) static SHAPE_ITEMS: &[Node] = &[
G("ADBE Vector Group", 1, "Group 1", &[
G("ADBE Vectors Group", 1025, "-_0_/-", &[
]),
G("ADBE Vector Transform Group", 1, "-_0_/-", &[
]),
G("ADBE Vector Materials Group", 1, "-_0_/-", &[
]),
]),
G("ADBE Vector Shape - Rect", 1, "Rectangle Path 1", &[
]),
G("ADBE Vector Shape - Ellipse", 1, "Ellipse Path 1", &[
]),
G("ADBE Vector Shape - Star", 1, "Polystar Path 1", &[
]),
G("ADBE Vector Graphic - Fill", 1, "Fill 1", &[
]),
G("ADBE Vector Graphic - Stroke", 1, "Stroke 1", &[
G("ADBE Vector Stroke Dashes", 1, "-_0_/-", &[
]),
G("ADBE Vector Stroke Taper", 1, "-_0_/-", &[
]),
G("ADBE Vector Stroke Wave", 1, "-_0_/-", &[
]),
]),
G("ADBE Vector Graphic - G-Fill", 1, "Gradient Fill 1", &[
]),
G("ADBE Vector Graphic - G-Stroke", 1, "Gradient Stroke 1", &[
G("ADBE Vector Stroke Dashes", 1, "-_0_/-", &[
]),
G("ADBE Vector Stroke Taper", 1, "-_0_/-", &[
]),
G("ADBE Vector Stroke Wave", 1, "-_0_/-", &[
]),
]),
G("ADBE Vector Filter - Trim", 1, "Trim Paths 1", &[
]),
G("ADBE Vector Filter - RC", 1, "Round Corners 1", &[
]),
G("ADBE Vector Filter - Merge", 1, "Merge Paths 1", &[
]),
G("ADBE Vector Filter - Offset", 1, "Offset Paths 1", &[
]),
G("ADBE Vector Filter - Repeater", 1, "Repeater 1", &[
G("ADBE Vector Repeater Transform", 1, "-_0_/-", &[
]),
]),
G("ADBE Vector Shape - Group", 1, "Path 1", &[
P("ADBE Vector Shape", Rec { state: 1, label: "-_0_/-", dims: 1, template: 1, class: 0x00020007, byte5: 0x07, header: &[], cdat_len: 4, cdat: &[], key_size: 0, limits: None, tdpi: None }),
]),
];
/// The shape value records (239, 242).
pub(crate) static SHAPE_RECORDS: &[Node] = &[
R("ADBE Vector Ellipse Size", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[400.0, 300.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
R("ADBE Vector Fill Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Ellipse Position", Rec { state: 1, label: "-_0_/-", dims: 2, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 48, cdat: &[100.0, 50.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Fill Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Vector Fill Rule", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Anchor", Rec { state: 1, label: "-_0_/-", dims: 2, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 48, cdat: &[10.0, 20.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Scale", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[50.0, 80.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
R("ADBE Vector Rotation", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Group Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[40.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Vector Skew", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[20.0], key_size: 0, limits: Some((-85.0, 85.0)), tdpi: None }),
R("ADBE Vector Skew Axis", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[45.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Stroke Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 255.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Stroke Width", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[6.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Vector Stroke Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Vector Rect Size", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[200.0, 100.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
R("ADBE Vector Rect Roundness", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Vector Stroke Line Cap", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Stroke Line Join", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Vector Stroke Miter Limit", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[4.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Vector Position", Rec { state: 1, label: "-_0_/-", dims: 2, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 48, cdat: &[50.0, 50.0], key_size: 0, limits: None, tdpi: None }),
];
/// The empty text animator group of a text layer (579).
pub(crate) static TEXT_ANIMATORS: &[Node] = &[
G("ADBE Text Animators", 1, "-_0_/-", &[
]),
];
/// One text animator with a range selector and an empty property group (579, 580).
pub(crate) static TEXT_ANIMATOR: &[Node] = &[
G("ADBE Text Animator", 1, "Animator 1", &[
G("ADBE Text Selectors", 1, "-_0_/-", &[
G("ADBE Text Selector", 1, "Range Selector 1", &[
G("ADBE Text Range Advanced", 1, "-_0_/-", &[
]),
]),
]),
G("ADBE Text Animator Properties", 1, "-_0_/-", &[
]),
]),
];
/// The text animator property records (580-592, 728).
pub(crate) static TEXT_ANIMATOR_RECORDS: &[Node] = &[
R("ADBE Text Position 3D", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[0.0, -50.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Anchor Point 3D", Rec { state: 1, label: "-_0_/-", dims: 3, template: 3, class: 0xffffffff, byte5: 0x0f, header: &[], cdat_len: 72, cdat: &[3.0, 4.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Scale 3D", Rec { state: 1, label: "-_0_/-", dims: 3, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 120, cdat: &[150.0, 120.0, 100.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
R("ADBE Text Skew", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[10.0], key_size: 0, limits: Some((-70.0, 70.0)), tdpi: None }),
R("ADBE Text Skew Axis", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[20.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Rotation", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[45.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[37.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Text Fill Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Stroke Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Stroke Width", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[3.0], key_size: 0, limits: Some((-1000.0, 1000.0)), tdpi: None }),
R("ADBE Text Tracking Amount", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[20.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
R("ADBE Text Line Spacing", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[10.0, 20.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
R("ADBE Text Blur", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[5.0, 6.0], key_size: 0, limits: Some((0.0, 10000.0)), tdpi: None }),
R("ADBE Text Percent Start", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[25.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Text Percent End", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[75.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Text Percent Offset", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[10.0], key_size: 0, limits: Some((-100.0, 100.0)), tdpi: None }),
R("ADBE Text Range Units", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Index Start", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 32000.0)), tdpi: None }),
R("ADBE Text Index End", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[4.0], key_size: 0, limits: Some((0.0, 32000.0)), tdpi: None }),
R("ADBE Text Index Offset", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
R("ADBE Text Range Type2", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[3.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Selector Mode", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Selector Max Amount", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((-100.0, 100.0)), tdpi: None }),
R("ADBE Text Range Shape", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0x00020000, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[2.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Selector Smoothness", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[50.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
R("ADBE Text Levels Max Ease", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[30.0], key_size: 0, limits: Some((-100.0, 100.0)), tdpi: None }),
R("ADBE Text Levels Min Ease", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[40.0], key_size: 0, limits: Some((-100.0, 100.0)), tdpi: None }),
R("ADBE Text Randomize Order", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
R("ADBE Text Random Seed", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[7.0], key_size: 0, limits: Some((0.0, 10000.0)), tdpi: None }),
R("ADBE Text Character Offset", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[3.0], key_size: 0, limits: Some((-65535.0, 65535.0)), tdpi: None }),
];
/// The inert Transform records of an AV layer (000): split Position, Orientation, X and Y
/// Rotation, Appears in Reflections, all at their defaults (state 3).
pub(crate) static AV_TRANSFORM: &[Node] = &[
R("ADBE Position_0", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
R("ADBE Position_1", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: Some((0.0, 0.0)), tdpi: None }),
O("ADBE Orientation", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x00060007, byte5: 0x07, header: &[(79, 1)], cdat_len: 24, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Rotate X", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Rotate Y", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0x0001ffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[], key_size: 0, limits: None, tdpi: None }),
R("ADBE Envir Appear in Reflect", Rec { state: 3, label: "-_0_/-", dims: 1, template: 0, class: 0xffff0004, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[1.0], key_size: 0, limits: None, tdpi: None }),
];
+104
View File
@@ -0,0 +1,104 @@
//! Property trees described as data: groups and records by match name with their decoded fields
//! (aep-format.md 3.4), built into chunks by [`build`]. The camera, light, shape and text
//! skeletons the exporter fills are tables of these (`tree_defs`).
use crate::Chunk;
use crate::export::synth::{KeyTemplate, RecSpec, key_list, tdb4, tdmn, tdsn};
/// A property record: its state (`tdsb`), user name, the `tdb4` header fields (components, key
/// template, class word, byte 5, decoded bytes that differ from what [`tdb4`] derives), the
/// static value (`cdat`: its length and the leading values, the rest zero) or the record size of
/// an empty key list, the limits, and a layer id (`tdpi` / `tdps`).
#[derive(Clone, Copy, Debug)]
pub(crate) struct Rec {
pub state: u32,
pub label: &'static str,
pub dims: u8,
pub template: u8,
pub class: u32,
pub byte5: u8,
pub header: &'static [(u8, u8)],
pub cdat_len: u16,
pub cdat: &'static [f64],
pub key_size: u16,
pub limits: Option<(f64, f64)>,
pub tdpi: Option<u32>,
}
/// A node of a property tree.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Node {
/// A group: match name, state, user name, children (the closing `ADBE Group End` is added).
G(&'static str, u32, &'static str, &'static [Node]),
/// A property record under its match name.
R(&'static str, Rec),
/// Orientation: its record in an `otst` with `otky` holding one zero `otda` (three degrees)
/// per key (aep-format.md 3.5, keyed Orientation).
O(&'static str, Rec),
/// A path property (`om-s`): its record and `omks` with one empty shape (aep-format.md 3.8).
P(&'static str, Rec),
}
fn record(r: &Rec) -> Chunk<'static> {
let template = if r.template == 0 { KeyTemplate::Plain } else { KeyTemplate::Spatial(r.template) };
let spec = RecSpec { dims: r.dims, template, class: r.class, limits: r.limits, byte5: Some(r.byte5) };
let keyed = r.key_size > 0;
let mut header = tdb4(&spec, keyed, 25_600);
for (at, v) in r.header {
if let Some(slot) = header.get_mut(usize::from(*at)) {
*slot = *v;
}
}
let mut kids = vec![Chunk::data(*b"tdsb", r.state.to_be_bytes().to_vec()), tdsn(r.label), Chunk::data(*b"tdb4", header)];
if keyed {
kids.push(key_list(u32::from(r.key_size), 0, Vec::new()));
} else {
let mut cdat = vec![0u8; usize::from(r.cdat_len)];
for (slot, v) in cdat.as_chunks_mut::<8>().0.iter_mut().zip(r.cdat) {
slot.copy_from_slice(&v.to_be_bytes());
}
kids.push(Chunk::data(*b"cdat", cdat));
}
if let Some((lo, hi)) = r.limits {
kids.push(Chunk::data(*b"tdum", lo.to_be_bytes().to_vec()));
kids.push(Chunk::data(*b"tduM", hi.to_be_bytes().to_vec()));
}
if let Some(id) = r.tdpi {
kids.push(Chunk::data(*b"tdpi", id.to_be_bytes().to_vec()));
kids.push(Chunk::data(*b"tdps", vec![0; 4]));
}
Chunk::list(*b"tdbs", kids)
}
/// The chunks of `nodes` (each a `tdmn` and its list).
pub(crate) fn build(nodes: &[Node]) -> Vec<Chunk<'static>> {
let mut out = Vec::with_capacity(nodes.len() * 2);
for n in nodes {
match n {
Node::G(name, state, label, kids) => {
let mut body = vec![Chunk::data(*b"tdsb", state.to_be_bytes().to_vec()), tdsn(label)];
body.extend(build(kids));
body.push(tdmn("ADBE Group End"));
out.push(tdmn(name));
out.push(Chunk::list(*b"tdgp", body));
}
Node::R(name, r) => {
out.push(tdmn(name));
out.push(record(r));
}
Node::P(name, r) => {
let shap = Chunk::list(
*b"shap",
vec![Chunk::data(*b"shph", crate::export::masks::shph()), key_list(8, 0, Vec::new()), Chunk::data(*b"omtn", Vec::new())],
);
out.push(tdmn(name));
out.push(Chunk::list(*b"om-s", vec![record(r), Chunk::list(*b"omks", vec![shap])]));
}
Node::O(name, r) => {
out.push(tdmn(name));
out.push(Chunk::list(*b"otst", vec![record(r), Chunk::list(*b"otky", vec![Chunk::data(*b"otda", vec![0; 24])])]));
}
}
}
out
}
+5 -1
View File
@@ -41,7 +41,7 @@ mod time;
use effectcraft_project::{ItemId, Project, ProjectSettings};
pub use effects::supported_effects;
pub use report::{ImportReport, Imported, LIMITATIONS, Loss, LossCategory, MAX_DETAILS};
pub use report::{AeVersionInfo, ImportReport, Imported, LIMITATIONS, Loss, LossCategory, MAX_DETAILS, TESTED_MAJORS, UNKNOWN};
/// Why an `.aep` was not imported.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
@@ -118,6 +118,10 @@ pub fn import(project: &mut Project, bytes: &[u8], options: &ImportOptions<'_>)
// 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);
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);
for loss in col.finish().losses.into_iter().filter(|_| options.settings) {
+3 -2
View File
@@ -704,8 +704,9 @@ fn apply_timing(l: &mut Layer, h: &LayerHeader, tm: &TimeMap, name: &str, col: &
}
/// After Effects ends a layer of timed footage (a clip, a sequence, a sound) at its source's end
/// when it opens a project, whatever out point the file stores (f1: layers stored 5 s long over a
/// 1 s clip, a 3-frame sequence and a 1 s WAV read back 1, 0.1 and 1 s long). A remapped or looped layer keeps its out point, and so does one that runs
/// when it opens a project, whatever out point the file stores (export test f1: layers written
/// 5 s long over a 1 s clip, a 3-frame sequence and a 1 s WAV read back 1, 0.1 and 1 s long; R31
/// of aep-export.md). A remapped or looped layer keeps its out point, and so does one that runs
/// less than a composition frame past (`frame`): a clip's duration need not be whole frames.
fn end_at_source(project: &Project, l: &mut Layer, frame: Tick) {
let LayerSource::Footage { item } = &l.source else { return };
+2 -2
View File
@@ -83,8 +83,8 @@ fn import_group(group: &AepGroup<'_, '_>, table: &[(&str, &str, Kind)], what: &s
if !is_stored(&node) {
continue;
}
// Blur Level at 100 (the default) is neutral: stored explicitly, After Effects reads it
// back as 100 % (read-back o1); other values are not sampled.
// Blur Level at 100 (the default) is neutral: the exporter writes it explicitly and After
// Effects reads it back as 100 % (export read-back o1); other values are not sampled.
if name == "ADBE Camera Blur Level"
&& !node.is_animated()
&& node.expression().is_none()
+149 -8
View File
@@ -34,10 +34,10 @@
//! import. Hue/Saturation's master values and Levels' values are arbitrary data, decoded by the
//! reader (444-446, 512-516).
use crate::effect_map::{Conv, EFFECTS, EffectMap, Extra, HUE_SATURATION_MASTER, LEVELS_RGB, popup_key};
use crate::effect_map::{CRYPTOMATTE_OUTPUT, Conv, EFFECTS, EffectMap, Extra, HUE_SATURATION_MASTER, LEVELS_RGB, popup_key};
use crate::{
CurvesData, DefinitionSource, Effect as AepEffect, EffectDefinitions, EffectParam, ExtractorChannels, HueSaturationData, Layer as AepLayer, LayerRef,
LevelsData, MeshData, ParamKind, ParamValue,
CryptomatteData, CurvesData, DefinitionSource, Effect as AepEffect, EffectDefinitions, EffectParam, ExtractorChannels, HueSaturationData,
Layer as AepLayer, LayerRef, LevelsData, MeshData, ParamKind, ParamValue,
};
use effectcraft_keyframe::Value;
use effectcraft_project::build::Ids;
@@ -99,8 +99,12 @@ pub(crate) fn import_effects<'f, 'a>(
None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)),
}
let params = defs.params(&fx);
for p in &params {
import_param(&fx, map, p, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
if map.extra == Extra::Cryptomatte {
import_cryptomatte(&fx, &params, cx, &shown, &mut group, col);
} else {
for p in &params {
import_param(&fx, map, p, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
}
}
col.imported.effects = col.imported.effects.saturating_add(1);
target.children.push(Node::Group(group));
@@ -522,7 +526,144 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
},
None => col.lose(LossCategory::Effects, format!("{here}: the Channel Info data is not in the sampled layout, the object ID channel used")),
},
Extra::None => {}
Extra::None | Extra::Cryptomatte => {}
}
}
/// The Cryptomatte plug-in (`Extra::Cryptomatte`, docs/aep-format.md 3.7): 1 Settings data
/// (the layer by name and the selection, both carried as text), 2 Output (EffectCraft's Display
/// and Matte Only), 3 Selection Mode (reported when on). Anything else stored is reported.
fn import_cryptomatte(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx: &LayerCtx<'_>, shown: &str, group: &mut PropGroup, col: &mut Collector) {
let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
let set = |group: &mut PropGroup, id: &str, v: Value| {
if let Some(prop) = group.prop_mut(id) {
prop.value = v;
}
};
// The plug-in's Output starts at Colors (EffectCraft's Display starts at Preview); an Output
// that cannot be imported keeps it.
let (display, matte_only) = CRYPTO_COLORS;
set(group, "display", Value::Enum(display));
set(group, "matteOnly", Value::Bool(matte_only));
for p in params {
if carries_nothing(p) {
continue;
}
let label = if p.name.is_empty() { p.match_name.clone() } else { format!("{} ({})", p.name, p.match_name) };
let moving = p.is_animated() || p.stored().is_some_and(|s| s.expression().is_some());
match (p.index, p.kind) {
(1, ParamKind::ArbitraryData) => {
if moving {
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported"));
}
// No record: the definition's default, no layer and no selection. A record
// without its data (every sampled record has it) is damaged.
let Some(data) = fx.arbitrary_data(&p.match_name) else {
if p.stored().is_some() {
col.lose(LossCategory::DamagedData, format!("{here}: the Cryptomatte settings (layer, selection) have no data, none used"));
}
continue;
};
match CryptomatteData::parse(data) {
Some(d) => {
set(group, "layerName", Value::Str(d.layer));
set(group, "selection", Value::Str(d.selection));
}
None => col.lose(LossCategory::DamagedData, format!("{here}: the Cryptomatte settings (layer, selection) are unreadable, none used")),
}
}
(2, ParamKind::Popup) => {
if moving {
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported, Colors used"));
continue;
}
let (display, matte_only) = crypto_output(p, &here, &label, col);
set(group, "display", Value::Enum(display));
set(group, "matteOnly", Value::Bool(matte_only));
}
(3, ParamKind::Checkbox) => {
if moving {
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported"));
} else {
match selection_mode_on(p) {
// A picking switch of the plug-in; EffectCraft picks with its own tool.
Some(true) => col.lose(LossCategory::Effects, format!("{here}: parameter {label} is on and has no counterpart")),
Some(false) => {}
None => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value, off used")),
}
}
}
_ => {
if p.stored().is_some() && !matches!(p.stored_value(), Some(ParamValue::Layer(0))) {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} ({:?}) not imported", p.kind));
}
}
}
}
}
/// EffectCraft's (Display, Matte Only) for the plug-in's Output Colors, its default.
const CRYPTO_COLORS: (u32, bool) = (0, false);
/// Is Selection Mode on? The plug-in writes it, when on, as a record in the default state
/// (`tdsb` 3) holding 1.0, which [`EffectParam::stored_value`] does not read; After Effects
/// reads it back as on and renders it (1400 `crypto-01-set-all`, `crypto-02-chk-toggled`). So
/// the record's value counts whatever its state; no record is off (the `pard` default). `None`
/// when a record is there but its value cannot be read (never the definition's default then).
fn selection_mode_on(p: &EffectParam<'_, '_>) -> Option<bool> {
match p.stored() {
Some(s) => s.static_value().and_then(|v| v.first().copied()).map(|v| v != 0.0),
None => Some(p.value() == Some(ParamValue::Bool(true))),
}
}
/// Cryptomatte's Output as EffectCraft's (Display, Matte Only): Colors is Colors, Matted RGBA
/// is Matte (the layer keyed by the selection), Matte Only is Matte Only. Matted Colors (the
/// ID colours keyed by the selection) becomes Matte, the same matte over the layer's own
/// colours, and is reported; a value that cannot be read is reported and Colors used.
fn crypto_output(p: &EffectParam<'_, '_>, here: &str, label: &str, col: &mut Collector) -> (u32, bool) {
let items: Vec<String> = match &p.items {
Some(items) => items.clone(),
None if p.popup_item_count().map(usize::from) == Some(CRYPTOMATTE_OUTPUT.len()) => CRYPTOMATTE_OUTPUT.iter().map(|s| s.to_string()).collect(),
None => {
col.lose(
LossCategory::Effects,
format!("{here}: parameter {label}: the file names no popup items and has {:?} of them, not imported, Colors used", p.popup_item_count()),
);
return CRYPTO_COLORS;
}
};
let index = match (p.stored(), p.stored_value()) {
(Some(_), Some(ParamValue::Index(i))) => i,
(Some(_), _) => {
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value, Colors used"));
return CRYPTO_COLORS;
}
// No record: the default. The plug-in's is Colors (1): the `pard` default of the
// instance's own and of the project's shared definition, and what scripting reads from a
// fresh effect (1400 `crypto-00-defaults`). An instance's own definition with another
// default keeps it; a borrowed one has no reliable popup default.
(None, _) => match p.pard_default() {
Some(ParamValue::Index(i)) if i != 0 && !p.borrowed_definition => i,
_ => return CRYPTO_COLORS,
},
};
let item = usize::try_from(index).ok().and_then(|i| i.checked_sub(1)).and_then(|i| items.get(i)).map(String::as_str).unwrap_or_default();
match popup_key(item).as_str() {
"colors" => CRYPTO_COLORS,
"matted rgba" => (1, false),
"matte only" => (1, true),
"matted colors" => {
col.lose(
LossCategory::Effects,
format!("{here}: parameter {label}: item '{item}' ({index}) has no counterpart, imported as Matte (the layer's colours keyed by the selection, not the ID colours)"),
);
(1, false)
}
_ => {
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item '{item}' ({index}) has no counterpart, Colors used"));
CRYPTO_COLORS
}
}
}
@@ -578,7 +719,7 @@ fn import_mesh(m: &MeshData, here: &str, size: (u32, u32), group: &mut PropGroup
return;
}
// EffectCraft's mesh reads the first two numbers of a vertex; moved handles follow as
// eight more (kept in the project, not drawn).
// eight more (kept for the export, not drawn).
let mut token = format!("{},{}", px(dx * w), px(dy * h));
if own.iter().any(|x| x.abs() > 0.01) {
handles_moved = true;
@@ -591,7 +732,7 @@ fn import_mesh(m: &MeshData, here: &str, size: (u32, u32), group: &mut PropGroup
if handles_moved {
col.lose(
LossCategory::Effects,
format!("{here}: Distortion Mesh Bezier handles moved on their own are not drawn (EffectCraft's mesh is bilinear; they are kept in the project)"),
format!("{here}: Distortion Mesh Bezier handles moved on their own are not drawn (EffectCraft's mesh is bilinear; they are kept for the export)"),
);
}
if let Some(p) = group.prop_mut("rows") {
+62
View File
@@ -7,6 +7,8 @@ use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::container::AepFile;
/// Most example lines kept per loss category (the count is always exact).
pub const MAX_DETAILS: usize = 20;
@@ -177,6 +179,65 @@ pub struct ImportReport {
pub missing_fonts: Vec<String>,
/// What the file reader cannot see at all, so it can be neither imported nor counted.
pub limitations: Vec<String>,
/// The After Effects version the file is written for and the one that wrote it.
#[serde(default)]
pub ae_version: AeVersionInfo,
}
/// The After Effects versions the importer is tested with (the major of the version a file is
/// written for): files written for 24.x, 25.x and 26.x.
pub const TESTED_MAJORS: std::ops::RangeInclusive<u8> = 24..=26;
/// The After Effects versions of a file, decoded from the container (never from the XMP packet,
/// which names the application of the first save).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AeVersionInfo {
/// The version the file is written for (`head`): `26.2.1x2` for a file saved by After Effects
/// 26.2.1, `25.6.0x97` for a copy that After Effects 2026 saved as 25.x. `unknown` when the file
/// does not say.
pub file_version: String,
/// The version of the After Effects that wrote the file (`svap`): `26.2.1x2` for that copy too.
/// `unknown` when the file does not say.
pub saved_by: String,
/// Whether the importer is tested with files written for this version ([`TESTED_MAJORS`]).
/// When not, what is read is still imported, and a line in
/// [`ImportReport::limitations`] says the version is not tested.
pub tested: bool,
}
impl Default for AeVersionInfo {
fn default() -> Self {
Self { file_version: UNKNOWN.to_string(), saved_by: UNKNOWN.to_string(), tested: false }
}
}
/// The text of a version the file does not state.
pub const UNKNOWN: &str = "unknown";
impl AeVersionInfo {
/// Reads the versions of a parsed file.
pub fn of(file: &AepFile<'_>) -> Self {
let file_version = file.file_version();
Self {
file_version: file_version.map_or_else(|| UNKNOWN.to_string(), |v| v.text()),
saved_by: file.saved_by_version().map_or_else(|| UNKNOWN.to_string(), |v| v.text()),
tested: file_version.is_some_and(|v| TESTED_MAJORS.contains(&v.major)),
}
}
/// The limitation line for a version that is not tested; `None` for a tested one.
pub fn limitation(&self) -> Option<String> {
(!self.tested).then(|| {
format!(
"The file is written for After Effects {} (saved by {}); the importer is tested with files written for After Effects {} to {} only. What it reads is imported, but this version is not tested.",
self.file_version,
self.saved_by,
TESTED_MAJORS.start(),
TESTED_MAJORS.end()
)
})
}
}
impl ImportReport {
@@ -227,6 +288,7 @@ impl Collector {
missing_footage: self.missing_footage,
missing_fonts: self.missing_fonts,
limitations: LIMITATIONS.iter().map(|s| (*s).to_string()).collect(),
ae_version: AeVersionInfo::default(),
}
}
}
+5 -2
View File
@@ -11,7 +11,9 @@ use crate::import::report::{Collector, LossCategory};
pub(crate) fn color_space(name: &str) -> Option<ColorSpace> {
match name {
"sRGB IEC61966-2.1" => Some(ColorSpace::Srgb),
"Rec.709 Gamma 2.4" => Some(ColorSpace::Rec709),
// The second name is the one After Effects shows for the profile EffectCraft's exporter
// writes (its description tag) once it re-saves such a project.
"Rec.709 Gamma 2.4" | "Rec.709 Gamma 2.4 (EffectCraft)" => Some(ColorSpace::Rec709),
_ => None,
}
}
@@ -89,8 +91,9 @@ mod tests {
use super::*;
#[test]
fn rec709_by_name() {
fn rec709_under_both_names() {
assert_eq!(color_space("Rec.709 Gamma 2.4"), Some(ColorSpace::Rec709));
assert_eq!(color_space("Rec.709 Gamma 2.4 (EffectCraft)"), Some(ColorSpace::Rec709));
assert_eq!(color_space("Rec.709 Gamma 2.4 (other)"), None);
}
}
+14 -11
View File
@@ -1,24 +1,27 @@
//! After Effects projects: the `.aep` / `.aepx` container and its import into an EffectCraft
//! project, in one crate (like `effectcraft-lottie`).
//! After Effects projects: the `.aep` / `.aepx` container, import into an EffectCraft project and
//! 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.
//! - [`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.
//!
//! See `docs/aep-format.md` and `docs/aep-import.md`.
//! See `docs/aep-format.md`, `docs/aep-import.md` and `docs/aep-export.md`.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod container;
pub mod export;
pub mod import;
pub use container::{
AepError, AepFile, AutoKern, BlendMode, Body, CURVE_IDENTITY, CameraPosition, Caps, Chunk, Comp, CompHeader, CueType, CurvesData, DEFAULT_CAMERA_ZOOM,
DefinitionSource, Effect, EffectDefinitions, EffectParam, ExpressionFlags, ExtractorChannels, FontBaseline, Footage, 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,
AeVersion, AepError, AepFile, AutoKern, BlendMode, Body, CURVE_IDENTITY, CameraPosition, Caps, Chunk, Comp, CompHeader, CryptomatteData, CueType,
CurvesData, DEFAULT_CAMERA_ZOOM, DefinitionSource, Effect, EffectDefinitions, EffectParam, ExpressionFlags, ExtractorChannels, FontBaseline, Footage,
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,
};
+21
View File
@@ -0,0 +1,21 @@
//! export tests of effectcraft-aep.
#[macro_use]
mod helpers;
mod built;
mod ease;
mod effects;
mod footage;
mod masks;
mod objects;
mod precomp;
mod remap;
mod repairs;
mod robustness;
mod roundtrip;
mod settings;
mod shape_switch;
mod stretch;
mod styles;
mod text;
+515
View File
@@ -0,0 +1,515 @@
//! The exported bytes are parsed back with `effectcraft-aep` and every exported field is compared
//! with the project it came from.
use crate::export::helpers::*;
use effectcraft_aep::export::{AepExportError, ExportOptions, LossCategory, analyze, export};
use effectcraft_aep::{BlendMode as AepBlend, Interpolation, ItemKind as AepKind, PropNode, Quality as AepQuality, parse, write};
use effectcraft_color::{BlendMode, Label};
use effectcraft_keyframe::{Ease, Interp, Value};
use effectcraft_project::{ItemKind, LayerSource, Project, Quality};
use effectcraft_time::FrameRate;
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
#[test]
fn simple_project_round_trips_through_the_container() {
let (p, _, _) = simple();
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
let file = parse(&r.bytes).expect("parse");
// The container is consistent: writing it back gives the same bytes.
assert_eq!(write(&file).expect("write"), r.bytes);
let view = effectcraft_aep::Project::new(&file).expect("project");
let items = view.all_items();
let kinds: Vec<_> = items.iter().filter_map(|i| i.kind()).collect();
assert_eq!(kinds.iter().filter(|k| **k == AepKind::Composition).count(), 1);
assert_eq!(kinds.iter().filter(|k| **k == AepKind::Folder).count(), 1);
assert_eq!(kinds.iter().filter(|k| **k == AepKind::Footage).count(), 1);
}
#[test]
fn composition_header_fields() {
let mut p = Project::default();
let c = add_comp(&mut p, "Flags", 800, 600, FrameRate::new(30, 1), 10.0, None);
with_comp(&mut p, c, |cc| {
cc.work_area = (secs(1.0), secs(3.0));
cc.background = [0.5, 0.25, 1.0];
cc.pixel_aspect = 0.9091;
cc.shutter_angle = 90.0;
cc.shutter_phase = -45.0;
cc.display_start = secs(4.0);
cc.enable_motion_blur = true;
});
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let item = view.all_items().into_iter().find(|i| i.display_name().as_deref() == Some("Flags")).expect("comp");
let h = item.comp().expect("comp").header().expect("header");
assert_eq!((h.width, h.height), (800, 600));
assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 30720));
assert_eq!(h.duration_units, 307_200);
assert_eq!(h.work_area_start_units, 30_720);
assert_eq!(h.work_area_end_units, Some(92_160));
assert_eq!(h.background, [128, 64, 255]);
assert_eq!((h.pixel_aspect.num, h.pixel_aspect.den), (10, 11));
assert_eq!(h.shutter_angle, 90);
assert_eq!(h.shutter_phase, Some(-45));
assert!(h.motion_blur);
assert_eq!(h.display_start.map(|d| (d.num, d.den)), Some((122_880, 30_720)));
assert_eq!(h.frame_rate_fixed, 30 << 16);
}
#[test]
fn ntsc_and_odd_frame_rates_use_the_time_bases_after_effects_writes() {
for (rate, fd, ts, fixed) in [
(FrameRate::FPS_29_97, 800u32, 23_976u32, 1_964_114u32),
(FrameRate::FPS_23_976, 1000, 23_976, 1_571_291),
(FrameRate::new(24, 1), 1024, 24_576, 24 << 16),
(FrameRate::new(12, 1), 2048, 24_576, 12 << 16),
(FrameRate::new(60, 1), 512, 30_720, 60 << 16),
] {
let mut p = Project::default();
add_comp(&mut p, "R", 640, 360, rate, 2.0, None);
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let item = view.all_items().into_iter().find(|i| i.display_name().as_deref() == Some("R")).expect("comp");
let h = item.comp().expect("c").header().expect("h");
assert_eq!((h.time_base.frame_duration, h.time_base.timescale, h.frame_rate_fixed), (fd, ts, fixed), "{}", rate.label());
let frames = (rate.as_f64() * 2.0).round() as u32;
assert_eq!(h.duration_units, frames * fd);
}
}
#[test]
fn layer_header_fields() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 800, 600, FrameRate::new(30, 1), 10.0, None);
let s = add_solid(&mut p, "Sol", 800, 600, [0.1, 0.2, 0.3], None);
for name in ["Bottom", "Mid", "Top"] {
add_layer(&mut p, c, name, LayerSource::Solid { item: s }, (800, 600));
}
add_layer(&mut p, c, "Nul", LayerSource::Null, (100, 100));
let bottom = p.comp(c).and_then(|cc| cc.layers.last().map(|l| l.id)).expect("bottom");
with_layer(&mut p, c, 1, |l| {
l.switches.adjustment = true;
l.blend_mode = BlendMode::Multiply;
l.label = Label::Lavender;
l.switches.quality = Quality::Draft;
l.parent = Some(bottom);
});
with_layer(&mut p, c, 2, |l| {
l.switches.locked = true;
l.switches.shy = true;
l.switches.solo = true;
l.blend_mode = BlendMode::Screen;
l.start_time = secs(1.5);
l.in_point = secs(2.0);
l.out_point = secs(6.0);
l.switches.video = false;
l.switches.audio = false;
l.switches.effects = false;
l.switches.motion_blur = true;
l.switches.guide = true;
});
let r = export_all(&p);
assert!(r.report.is_lossless());
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find(|i| i.comp().is_some()).expect("comp");
let layers: Vec<_> = comp.comp().expect("c").layers().collect();
assert_eq!(layers.len(), 4);
let names: Vec<_> = layers.iter().map(|l| l.name().unwrap_or_default()).collect();
assert_eq!(names, ["Nul", "Top", "Mid", "Bottom"]);
let h: Vec<_> = layers.iter().map(|l| l.header().expect("header")).collect();
// Null.
assert!(h[0].is_null_object());
assert!(h[0].source_id.is_some());
// Adjustment layer "Top".
assert!(h[1].is_adjustment());
assert_eq!(h[1].blend_mode, AepBlend::Multiply);
assert_eq!(h[1].label, 5);
assert_eq!(h[1].quality, AepQuality::Draft);
assert_eq!(h[1].parent_id, Some(h[3].id));
// "Mid".
assert!(h[2].is_locked() && h[2].is_shy() && h[2].is_solo());
assert!(!h[2].is_video_enabled() && !h[2].is_audio_enabled() && !h[2].is_effects_enabled());
assert!(h[2].is_motion_blur() && h[2].is_guide());
assert_eq!(h[2].blend_mode, AepBlend::Screen);
assert_eq!((h[2].start.num, h[2].start.den), (46_080, 30_720));
assert_eq!(h[2].in_point_seconds(), Some(2.0));
assert_eq!(h[2].out_point_seconds(), Some(6.0));
assert_eq!(h[2].name_copy, "Mid");
// Ids are unique.
let mut ids: Vec<u32> = h.iter().map(|x| x.id).collect();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), 4);
}
#[test]
fn solids_and_items() {
let mut p = Project::default();
let f = p.add_item("Folder A", Label::None, None, ItemKind::Folder);
add_comp(&mut p, "Comp 1", 100, 100, FrameRate::new(25, 1), 1.0, Some(f));
add_solid(&mut p, "Blue", 640, 360, [0.0, 0.0, 1.0], Some(f));
add_solid(&mut p, "Root solid", 31, 17, [1.0, 0.5, 0.25], None);
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let all = view.all_items();
let folder = all.iter().find(|i| i.display_name().as_deref() == Some("Folder A")).expect("folder");
let kids: Vec<_> = folder.children().collect();
assert_eq!(kids.len(), 2);
let blue = kids.iter().find(|i| i.kind() == Some(AepKind::Footage)).expect("blue");
let f = blue.footage().expect("footage");
assert!(f.is_solid);
assert_eq!((f.width, f.height), (640, 360));
assert_eq!(f.solid_rgb(), Some([0.0, 0.0, 1.0]));
let solids = all.iter().find(|i| i.display_name().as_deref() == Some("Solids")).expect("Solids folder");
let rs = solids.children().next().expect("root solid").footage().expect("f");
assert_eq!((rs.width, rs.height), (31, 17));
assert_eq!(rs.solid_rgb(), Some([1.0, 0.5, 0.25]));
}
fn transform_of(bytes: &[u8]) -> (effectcraft_aep::Transform, Vec<(String, Vec<(i32, Option<Interpolation>, Option<Interpolation>, Vec<f64>)>)>) {
let file = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find(|i| i.comp().is_some()).expect("comp");
let h = comp.comp().expect("c").header().expect("h");
let layer = comp.comp().expect("c").layers().next().expect("layer");
let tr = layer.transform(u32::from(h.width), u32::from(h.height)).expect("transform");
let mut keys = Vec::new();
if let Some(PropNode::Group(g)) = layer.properties().and_then(|p| p.get("ADBE Transform Group")) {
for name in ["ADBE Anchor Point", "ADBE Position", "ADBE Scale", "ADBE Rotate Z", "ADBE Opacity"] {
if let Some(PropNode::Property(pr)) = g.get(name)
&& let Some(list) = pr.keys()
{
let recs = list
.keyframes()
.map(|k| (k.time_units().unwrap_or(0), k.interpolation_in(), k.interpolation_out(), k.value().unwrap_or_default()))
.collect();
keys.push((name.to_string(), recs));
}
}
}
(tr, keys)
}
#[test]
fn static_transform_values_use_the_file_units() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
let s = add_solid(&mut p, "L", 400, 300, [1.0, 0.5, 0.0], None);
add_layer(&mut p, c, "L", LayerSource::Solid { item: s }, (400, 300));
with_layer(&mut p, c, 0, |l| {
let tr = l.transform_mut().expect("tr");
tr.get_mut("anchor").expect("a").value = Value::Vec3([100.0, 50.0, 0.0]);
tr.get_mut("position").expect("p").value = Value::Vec3([300.0, 200.0, 0.0]);
tr.get_mut("scale").expect("s").value = Value::Vec3([50.0, 60.0, 100.0]);
tr.get_mut("rotation").expect("r").value = Value::Scalar(45.0);
tr.get_mut("opacity").expect("o").value = Value::Scalar(25.0);
});
let r = export_all(&p);
let (tr, keys) = transform_of(&r.bytes);
assert!(keys.is_empty());
let a = tr.anchor_px(400.0, 300.0);
assert!(close(a[0], 100.0) && close(a[1], 50.0));
assert_eq!(tr.anchor_fraction.value, [0.25, 50.0 / 300.0, 0.0]);
assert_eq!(tr.position.value, [300.0, 200.0, 0.0]);
assert_eq!(tr.scale_percent.value, [50.0, 60.0, 100.0]);
assert!(close(tr.rotation_degrees.value, 45.0));
assert!(close(tr.opacity_percent.value, 25.0));
}
#[test]
fn defaults_are_not_written() {
let (p, _, _) = simple();
let r = export_all(&p);
let plain = export_all(&p);
assert_eq!(r.bytes, plain.bytes);
// A layer at the default values has no property record beyond the template's.
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find(|i| i.comp().is_some()).expect("comp");
let layer = comp.comp().expect("c").layers().next().expect("layer");
let Some(PropNode::Group(g)) = layer.properties().and_then(|p| p.get("ADBE Transform Group")) else { panic!("no group") };
for n in ["ADBE Anchor Point", "ADBE Position", "ADBE Scale", "ADBE Rotate Z", "ADBE Opacity"] {
assert!(g.get(n).is_none(), "{n} must be absent at its default");
}
}
#[test]
fn keyframes_with_interpolation_ease_and_expressions() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
let s = add_solid(&mut p, "S", 400, 300, [0.2, 0.4, 0.6], None);
add_layer(&mut p, c, "S", LayerSource::Solid { item: s }, (400, 300));
with_layer(&mut p, c, 0, |l| {
let tr = l.transform_mut().expect("tr");
let o = tr.get_mut("opacity").expect("o");
let mut k0 = key(0.0, Value::Scalar(0.0));
let mut k1 = key(1.0, Value::Scalar(100.0));
k0.out_interp = Interp::Bezier;
k0.out_ease = vec![Ease { speed: 0.0, influence: 0.5 }];
k1.in_interp = Interp::Bezier;
k1.in_ease = vec![Ease { speed: 0.0, influence: 0.25 }];
k1.out_interp = Interp::Hold;
o.keys = vec![k0, k1, key(2.0, Value::Scalar(50.0))];
let rot = tr.get_mut("rotation").expect("r");
rot.value = Value::Scalar(10.0);
rot.expr = Some(effectcraft_project::Expression { text: "time*20".into(), enabled: false });
});
let r = export_all(&p);
assert_eq!(r.report.exported.keyframes, 3);
assert_eq!(r.report.exported.expressions, 1);
let (tr, keys) = transform_of(&r.bytes);
let (_, opacity) = keys.iter().find(|(n, _)| n == "ADBE Opacity").expect("opacity keys");
assert_eq!(opacity.len(), 3);
assert_eq!(opacity[0].0, 0);
assert_eq!(opacity[1].0, 25_600);
assert_eq!(opacity[2].0, 51_200);
assert_eq!(opacity[0].2, Some(Interpolation::Bezier));
assert_eq!(opacity[1].1, Some(Interpolation::Bezier));
assert_eq!(opacity[1].2, Some(Interpolation::Hold));
assert_eq!(opacity[1].3, vec![1.0]);
assert!(close(tr.rotation_degrees.value, 10.0));
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find(|i| i.comp().is_some()).expect("comp");
let layer = comp.comp().expect("c").layers().next().expect("layer");
let Some(PropNode::Group(g)) = layer.properties().and_then(|p| p.get("ADBE Transform Group")) else { panic!("no group") };
let Some(PropNode::Property(rot)) = g.get("ADBE Rotate Z") else { panic!("no rotation") };
assert_eq!(rot.expression().as_deref(), Some("time*20"));
assert_eq!(rot.expression_enabled(), Some(false));
}
#[test]
fn losses_are_reported_and_refused_unless_allowed() {
let (mut p, c, _) = simple();
let t = add_comp(&mut p, "T", 100, 100, FrameRate::new(25, 1), 1.0, None);
add_layer(&mut p, t, "Par", LayerSource::Light { kind: effectcraft_project::LightKind::Parallel }, (100, 100));
add_layer(&mut p, t, "Amb", LayerSource::Light { kind: effectcraft_project::LightKind::Ambient }, (100, 100));
with_layer(&mut p, c, 0, |l| {
l.blend_mode = BlendMode::Dissolve;
l.switches.three_d = true;
// A stretch that is not an exact small ratio is written unstretched.
l.stretch = 100.0 * std::f64::consts::PI;
l.transform_mut().expect("tr").get_mut("rotation").expect("r").keys = vec![key(0.0, Value::Scalar(0.0)), key(1.0, Value::Scalar(90.0))];
});
let rep = analyze(&p);
assert_eq!(rep.count(LossCategory::Lights), 2);
assert_eq!(rep.count(LossCategory::BlendModes), 1);
// The 3D switch is written.
assert_eq!(rep.count(LossCategory::ThreeD), 0);
assert_eq!(rep.count(LossCategory::TimeStretch), 1);
assert!(!rep.limitations.is_empty());
match export(&p, &ExportOptions::default()) {
Err(AepExportError::Refused(r)) => assert_eq!(*r, rep),
other => panic!("expected a refusal, got {other:?}"),
}
let ok = export(&p, &ExportOptions { allow_losses: true }).expect("allowed");
assert_eq!(ok.report, rep);
// The report round-trips through JSON.
let json = serde_json::to_string(&rep).expect("json");
assert_eq!(serde_json::from_str::<effectcraft_aep::export::ExportReport>(&json).expect("back"), rep);
}
#[test]
fn the_exported_file_is_deterministic() {
let (p, _, _) = simple();
assert_eq!(export_all(&p).bytes, export_all(&p).bytes);
}
/// The user, host and domain names of the machine that runs the test, lower-cased. They are read from
/// the environment so that no name is written down in the repository; names shorter than three
/// characters are skipped because they would match by chance.
fn local_names() -> Vec<String> {
["USERNAME", "USER", "COMPUTERNAME", "HOSTNAME", "USERDOMAIN"]
.into_iter()
.filter_map(|key| std::env::var(key).ok())
.map(|v| v.trim().to_lowercase())
.filter(|v| v.len() >= 3)
.collect()
}
/// Absolute drive-letter paths (`X:\…`, `X:/…`) in a lower-cased text, except the neutral
/// `c:\fixtures\` paths the fixtures use.
fn drive_paths(hay: &str) -> Vec<String> {
let b = hay.as_bytes();
let mut found = Vec::new();
for i in 0..b.len().saturating_sub(3) {
let starts = i == 0 || !b[i - 1].is_ascii_alphanumeric();
if starts
&& b[i].is_ascii_alphabetic()
&& b[i + 1] == b':'
&& matches!(b[i + 2], b'\\' | b'/')
&& b[i + 3].is_ascii_alphanumeric()
&& !b[i..].starts_with(b"c:\\fixtures\\")
&& !b[i..].starts_with(b"c:/fixtures/")
{
found.push(String::from_utf8_lossy(&b[i..b.len().min(i + 16)]).into_owned());
}
}
found
}
/// E-mail-like strings (`local@domain.tld`) in a lower-cased text.
fn email_like(hay: &str) -> Vec<String> {
let b = hay.as_bytes();
let local = |c: u8| c.is_ascii_alphanumeric() || b"._%+-".contains(&c);
let domain = |c: u8| c.is_ascii_alphanumeric() || c == b'-' || c == b'.';
let mut found = Vec::new();
for at in (0..b.len()).filter(|&i| b[i] == b'@') {
let mut s = at;
while s > 0 && local(b[s - 1]) {
s -= 1;
}
let mut e = at + 1;
while e < b.len() && domain(b[e]) {
e += 1;
}
while e > at + 1 && b[e - 1] == b'.' {
e -= 1;
}
let host = &b[at + 1..e];
let tld = host.iter().rposition(|&c| c == b'.').map(|dot| &host[dot + 1..]);
let has_dot_inside = host.iter().position(|&c| c == b'.').is_some_and(|dot| dot > 0);
if s < at && has_dot_inside && tld.is_some_and(|t| t.len() >= 2 && t.iter().all(u8::is_ascii_alphabetic)) {
found.push(String::from_utf8_lossy(&b[s..e]).into_owned());
}
}
found
}
/// Everything the exporter writes is built in code: an export holds no local name, path or
/// address.
#[test]
fn the_export_holds_no_local_data() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 100, 100, FrameRate::new(25, 1), 1.0, None);
let s = add_solid(&mut p, "Red", 50, 50, [1.0, 0.0, 0.0], None);
add_layer(&mut p, c, "Red", LayerSource::Solid { item: s }, (50, 50));
add_layer(&mut p, c, "N", LayerSource::Null, (100, 100));
let export = export_all(&p).bytes;
let names = local_names();
let fixed = ["desktop-", "\\users\\", "/users/", "/home/"];
for (name, bytes) in [("export", &export[..])] {
// Strings are searched as bytes and, with the NUL bytes removed, as UTF-16 text.
let utf16: Vec<u8> = bytes.iter().copied().filter(|&c| c != 0).collect();
for hay in [String::from_utf8_lossy(bytes).to_lowercase(), String::from_utf8_lossy(&utf16).to_lowercase()] {
for needle in names.iter().map(String::as_str).chain(fixed) {
assert!(!hay.contains(needle), "{name} contains a local name or path");
}
assert_eq!(drive_paths(&hay), Vec::<String>::new(), "{name} holds an absolute local path");
assert_eq!(email_like(&hay), Vec::<String>::new(), "{name} holds an e-mail address");
}
}
}
#[test]
fn the_local_data_search_finds_what_it_looks_for() {
assert_eq!(drive_paths("x d:\\work\\a.aep y"), vec!["d:\\work\\a.aep y".to_string()]);
assert_eq!(drive_paths("q:/media/a.mov"), vec!["q:/media/a.mov".to_string()]);
assert!(drive_paths("c:\\fixtures\\a.png and c:/fixtures/b.png").is_empty());
assert!(drive_paths("http://example and 12:30 and ab:/x").is_empty());
assert_eq!(email_like("by jane.doe@example.org."), vec!["jane.doe@example.org".to_string()]);
assert!(email_like("@@ a@b x@.org y@host").is_empty());
}
#[test]
fn a_root_folder_named_solids_is_the_solids_folder() {
let mut p = Project::default();
let f = p.add_item("Solids", Label::None, None, ItemKind::Folder);
let c = add_comp(&mut p, "C", 100, 100, FrameRate::new(25, 1), 1.0, None);
let s = add_solid(&mut p, "Orange", 50, 50, [1.0, 0.5, 0.0], Some(f));
add_layer(&mut p, c, "Orange", LayerSource::Solid { item: s }, (50, 50));
add_layer(&mut p, c, "N", LayerSource::Null, (100, 100));
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let folders: Vec<_> = view.all_items().into_iter().filter(|i| i.kind() == Some(AepKind::Folder)).collect();
assert_eq!(folders.len(), 1, "one Solids folder, not two");
let kids: Vec<_> = folders[0].children().filter_map(|k| k.footage()).collect();
assert_eq!(kids.len(), 2, "the solid and the hidden null solid");
assert!(kids.iter().all(|k| k.is_solid));
}
#[test]
fn the_3d_switch_is_written() {
// 015: ldta@38 bit 0x04.
let (mut p, c, _) = simple();
with_layer(&mut p, c, 0, |l| {
l.switches.three_d = true;
l.transform_mut().expect("tr").get_mut("position").expect("p").value = Value::Vec3([960.0, 540.0, 300.0]);
});
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let layer = view.all_items().into_iter().find_map(|i| i.comp()).and_then(|c| c.layers().next()).expect("layer");
assert!(layer.header().expect("header").is_three_d());
let Some(PropNode::Group(g)) = layer.properties().and_then(|p| p.get("ADBE Transform Group")) else { panic!("transform") };
let Some(PropNode::Property(pos)) = g.get("ADBE Position") else { panic!("position") };
assert_eq!(pos.static_value().expect("value")[..3], [960.0, 540.0, 300.0]);
}
#[test]
fn time_stretch_is_the_exact_ratio_and_scales_the_time_scale() {
// 018 (200 %: 2/1, 51 200), 316 (50 %: 1/2, 25 600), 317 (150 %: 3/2, 38 400).
for (pct, num, den, ts) in [(200.0, 2i32, 1u32, 51_200u32), (50.0, 1, 2, 25_600), (150.0, 3, 2, 38_400)] {
let (mut p, c, _) = simple();
with_layer(&mut p, c, 0, |l| {
l.stretch = pct;
l.start_time = secs(1.0);
l.in_point = secs(1.0);
l.out_point = secs(1.0 + 2.0 * pct / 100.0);
l.transform_mut().expect("tr").get_mut("opacity").expect("o").value = Value::Scalar(50.0);
});
let r = export_all(&p);
assert!(r.report.is_lossless(), "{pct}: {:?}", r.report.losses);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let layer = view.all_items().into_iter().find_map(|i| i.comp()).and_then(|c| c.layers().next()).expect("layer");
let h = layer.header().expect("header");
assert_eq!((h.stretch, h.stretch_den), (num, den), "{pct}");
// Relative times in source time: the 2 s of source end 2 s after the start.
assert_eq!((h.in_relative.num, h.out_relative.num), (0, 51_200), "{pct}");
let Some(PropNode::Group(g)) = layer.properties().and_then(|p| p.get("ADBE Transform Group")) else { panic!("transform") };
let Some(PropNode::Property(o)) = g.get("ADBE Opacity") else { panic!("opacity") };
assert_eq!(o.time_scale(), Some(ts), "{pct}");
// And back.
let mut q = Project::default();
let none = |_: &str| false;
effectcraft_aep::import::import(
&mut q,
&r.bytes,
&effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) },
)
.expect("import");
let l = q.items.values().find_map(|i| if let ItemKind::Comp(c) = &i.kind { c.layers.first().cloned() } else { None }).expect("layer");
assert!((l.stretch - pct).abs() < 1e-9 && l.out_point == secs(1.0 + 2.0 * pct / 100.0), "{pct}: {} {:?}", l.stretch, l.out_point);
}
// A ratio that is not small and exact is reported.
let (mut p, c, _) = simple();
with_layer(&mut p, c, 0, |l| l.stretch = 31.4159265);
assert_eq!(export_all(&p).report.count(LossCategory::TimeStretch), 1);
}
#[test]
fn unwritten_layer_switches_and_off_frame_times_are_reported() {
// Each of these changes the result in After Effects, so none may pass as lossless.
let (mut p, c, _) = simple();
with_layer(&mut p, c, 0, |l| {
l.switches.quality = Quality::Wireframe;
l.preserve_transparency = true;
l.auto_orient = effectcraft_project::AutoOrient::AlongPath;
l.in_point = secs(0.013);
});
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::LayerSwitches), 3, "{:?}", r.report.losses);
assert_eq!(r.report.count(LossCategory::RoundedTimes), 1, "{:?}", r.report.losses);
assert!(matches!(export(&p, &ExportOptions { allow_losses: false }), Err(AepExportError::Refused(_))));
}
+65
View File
@@ -0,0 +1,65 @@
//! Bezier ease the importer decodes is written back: Anchor Point keys (597, 730: speed in pixels
//! per second over the source height), effect point keys (598) and mask path keys (599, 700:
//! the ease at bytes 24..55 of the 64-byte record). The key records of the export equal After
//! Effects' in time, interpolation and ease.
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{Body, Chunk, parse};
use effectcraft_project::Project;
/// The key records (`ldat`) of the first property named `name` below a layer, split into records.
fn key_records(bytes: &[u8], name: &str) -> Vec<Vec<u8>> {
fn walk(cs: &[Chunk<'_>], name: &str) -> Option<Vec<Vec<u8>>> {
for (i, c) in cs.iter().enumerate() {
if c.is(b"tdmn") && matches!(&c.body, Body::Data(d) if d.split(|x| *x == 0).next() == Some(name.as_bytes())) {
let node = cs.get(i + 1)?;
// A property record, or the mask shape inside its atom.
let tdbs = if node.is_list(b"tdbs") { Some(node) } else { node.children().iter().find(|k| k.is_list(b"tdbs")) };
if let Some(list) = tdbs.and_then(|t| t.child_list(b"list")) {
let size =
list.child(b"lhd3").and_then(|c| c.bytes()).and_then(|b| b.get(16..20)).map(|b| u32::from_be_bytes(b.try_into().unwrap()) as usize)?;
let ldat = list.child(b"ldat").and_then(|c| c.bytes())?;
return Some(ldat.chunks(size).map(<[u8]>::to_vec).collect());
}
}
if let Some(r) = walk(c.children(), name) {
return Some(r);
}
}
None
}
let f = parse(bytes).expect("parse");
walk(&f.chunks, name).unwrap_or_default()
}
#[test]
fn decoded_bezier_ease_is_written_as_after_effects_wrote_it() {
for (name, prop) in [
("597-key-anchor-ease-out50-40-in30-60.aep", "ADBE Anchor Point"),
("730-key-anchor-ease-on-400x800-solid.aep", "ADBE Anchor Point"),
("598-key-ramp-point-ease-color-bezier.aep", "ADBE Ramp-0001"),
("599-key-mask-path-ease-infl75.aep", "ADBE Mask Shape"),
("700-key-mask-path-ease-out20-in50.aep", "ADBE Mask Shape"),
] {
let bytes = fixture!(name);
let mut p = Project::default();
let none = |_: &str| false;
import(&mut p, &bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("import");
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::ApproximatedKeyframes), 0, "{name}: {:?}", r.report.losses);
let (a, b) = (key_records(&bytes, prop), key_records(&r.bytes, prop));
assert!(a.len() >= 2, "{name}: {}", a.len());
assert_eq!(a.len(), b.len(), "{name}");
let f = |r: &[u8], at: usize| f64::from_be_bytes(r[at..at + 8].try_into().unwrap());
for (i, (x, y)) in a.iter().zip(&b).enumerate() {
assert_eq!(x[..6], y[..6], "{name} key {i}: time and interpolation");
// The used sides: the out side of the first key, the in side of the last.
let sides: &[usize] = if i == 0 { &[40, 48] } else { &[24, 32] };
for at in sides {
assert!((f(x, *at) - f(y, *at)).abs() < 1e-9, "{name} key {i} @{at}: {} vs {}", f(x, *at), f(y, *at));
}
}
}
}
+734
View File
@@ -0,0 +1,734 @@
//! Effects (Tint, Gradient Ramp, Exposure): every effect fixture is imported and exported, and the
//! exported effects are parsed back with `effectcraft-aep` and compared with the ones After
//! Effects wrote, parameter by parameter (stored values, keys, definitions); projects edited in
//! code check the parameters no fixture changes, several instances, and what is reported.
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{AepFile, ParamValue, parse};
use effectcraft_keyframe::{Interp, Value};
use effectcraft_project::{ItemKind, Node, Project, PropGroup};
fn fixtures_with_effects() -> Option<Vec<String>> {
Some({
let mut v: Vec<String> = crate::common::names("aep")?
.into_iter()
// Every fixture with an effect of the table (the dropdown and layer controls are not in it).
.filter(|n| {
n.ends_with(".aep")
&& (n.contains("-fx-") || n.contains("key-fill") || n.contains("key-ramp") || n.contains("adj-ramp"))
&& !n.contains("dropdown")
&& !n.contains("layercontrol")
})
.collect();
v.sort();
v
})
}
fn import_bytes(bytes: &[u8]) -> Project {
let mut p = Project::default();
let none = |_: &str| false;
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&none) };
import(&mut p, bytes, &opts).expect("import");
p
}
/// One effect as the reader sees it: match name, instance name, and per parameter index the
/// stored value (None = default) and the keys `(time units, value)`.
#[derive(Debug, PartialEq)]
struct Seen {
match_name: String,
name: Option<String>,
params: Vec<(usize, Option<ParamValue>, Vec<(i32, Vec<f64>, (u8, u8))>)>,
}
/// The effects of every layer, by (composition name, layer index).
fn effects_of(file: &AepFile<'_>) -> Vec<((String, usize), Vec<Seen>)> {
let view = effectcraft_aep::Project::new(file).expect("project");
let mut out = Vec::new();
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
let cname = item.display_name().unwrap_or_default();
for (i, layer) in comp.layers().enumerate() {
let mut fx = Vec::new();
// Effects outside the table are reported by the importer, not written.
for e in layer.effects().into_iter().filter(|e| effectcraft_aep::effect_map::by_match_name(e.match_name()).is_some()) {
let mut params = Vec::new();
for p in view.effect_params(&e) {
let keys = p
.keys()
.map(|k| {
k.keyframes()
.map(|r| {
let interp = (
r.interpolation_in().map_or(0, |x| match x {
effectcraft_aep::Interpolation::Linear => 1,
effectcraft_aep::Interpolation::Bezier => 2,
effectcraft_aep::Interpolation::Hold => 3,
effectcraft_aep::Interpolation::Other(c) => c,
}),
r.interpolation_out().map_or(0, |x| match x {
effectcraft_aep::Interpolation::Linear => 1,
effectcraft_aep::Interpolation::Bezier => 2,
effectcraft_aep::Interpolation::Hold => 3,
effectcraft_aep::Interpolation::Other(c) => c,
}),
);
(r.time_units().unwrap_or(-1), r.value().unwrap_or_default(), interp)
})
.collect()
})
.unwrap_or_default();
let value = if p.is_animated() { None } else { p.stored_value() };
params.push((p.index, value, keys));
}
fx.push(Seen { match_name: e.match_name().to_string(), name: e.display_name(), params });
}
if !fx.is_empty() {
out.push(((cname.clone(), i), fx));
}
}
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
fn close_value(a: &Option<ParamValue>, b: &Option<ParamValue>) -> bool {
let comps = |v: &ParamValue| -> Vec<f64> {
match v {
ParamValue::Number(n) => vec![*n],
ParamValue::Point(p) => p.to_vec(),
ParamValue::Argb(c) => c.iter().skip(1).copied().collect(),
ParamValue::Index(i) => vec![f64::from(*i)],
ParamValue::Bool(b) => vec![if *b { 1.0 } else { 0.0 }],
other => panic!("unexpected {other:?}"),
}
};
match (a, b) {
(None, None) => true,
// The input layer names the owning layer by its id, which differs between the files.
(Some(ParamValue::Layer(_)), Some(ParamValue::Layer(_))) => true,
(Some(x), Some(y)) => comps(x).iter().zip(comps(y)).all(|(p, q)| (p - q).abs() < 1e-6),
_ => false,
}
}
#[test]
fn every_effect_fixture_is_written_as_after_effects_wrote_it() {
let names = skip!(fixtures_with_effects());
assert!(names.len() >= 20, "{names:?}");
let mut compared = 0;
for name in &names {
let bytes = fixture!(name);
let original = parse(&bytes).expect("parse");
let mut p = Project::default();
let none = |_: &str| false;
let imported = import(&mut p, &bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("import");
let lossy: Vec<String> = imported.report.losses.iter().flat_map(|l| l.details.clone()).collect();
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::Effects), 0, "{name}: {:?}", r.report.losses);
let exported = parse(&r.bytes).expect("parse export");
let (a, b) = (effects_of(&original), effects_of(&exported));
assert_eq!(a.len(), b.len(), "{name}: layers with effects");
for ((ka, fa), (kb, fb)) in a.iter().zip(&b) {
assert_eq!(ka, kb, "{name}");
assert_eq!(fa.len(), fb.len(), "{name}: effect count");
for (x, y) in fa.iter().zip(fb) {
assert_eq!((&x.match_name, &x.name), (&y.match_name, &y.name), "{name}");
// Written as the importer took it over (712: CC Radial Blur's Type Scratch has no
// EffectCraft item, reported on import).
if lossy.iter().any(|d| d.contains(&format!("({})", x.match_name))) {
continue;
}
assert_eq!(x.params.len(), y.params.len(), "{name}: parameters of {}", x.match_name);
for (px, py) in x.params.iter().zip(&y.params) {
assert_eq!(px.0, py.0, "{name}");
assert!(close_value(&px.1, &py.1), "{name} {} #{}: {:?} vs {:?}", x.match_name, px.0, px.1, py.1);
assert_eq!(px.2.len(), py.2.len(), "{name} #{} keys", px.0);
// A colour key switched to bezier stores speed 0 / influence 0, which After
// Effects interpolates linearly (598): it is imported and written linear.
let colour = matches!(px.2.first().map(|k| k.1.len()), Some(4));
let lin = |i: (u8, u8)| if colour { (i.0.min(1), i.1.min(1)) } else { i };
for (kx, ky) in px.2.iter().zip(&py.2) {
assert_eq!((kx.0, lin(kx.2)), (ky.0, lin(ky.2)), "{name} #{} key", px.0);
assert!(kx.1.iter().zip(&ky.1).all(|(p, q)| (p - q).abs() < 1e-6), "{name} #{} key value {:?} {:?}", px.0, kx.1, ky.1);
}
}
compared += 1;
}
}
// The input layer of every exported instance names the layer that owns it (320).
let view = effectcraft_aep::Project::new(&exported).expect("project");
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
for layer in comp.layers() {
let id = layer.header().map(|h| h.id).expect("header");
for e in layer.effects() {
let input = view.effect_params(&e).into_iter().find(|p| p.index == 0).and_then(|p| p.stored_value());
assert_eq!(input, Some(ParamValue::Layer(id)), "{name}: input layer of {}", e.match_name());
}
}
}
// The container is consistent and the result imports to the same effect values.
assert_eq!(effectcraft_aep::write(&exported).expect("write"), r.bytes, "{name}");
let q = import_bytes(&r.bytes);
assert_eq!(effect_values(&p), effect_values(&q), "{name}: values after a second import");
}
assert!(compared >= 20, "{compared}");
}
/// Every effect parameter of the project: (comp, layer, effect, param path, value, key count).
fn effect_values(p: &Project) -> Vec<(String, String, String, String, Vec<i64>, usize)> {
let mut out = Vec::new();
for item in p.items.values() {
let ItemKind::Comp(c) = &item.kind else { continue };
for l in &c.layers {
let Some(fx) = l.effects() else { continue };
for g in fx.groups() {
let mut stack: Vec<(&PropGroup, String)> = vec![(g, String::new())];
while let Some((grp, pre)) = stack.pop() {
for n in &grp.children {
match n {
Node::Group(s) => stack.push((s, format!("{pre}{}/", s.match_id))),
Node::Prop(pr) => out.push((
item.name.clone(),
l.name.clone(),
g.name.clone(),
format!("{pre}{}", pr.match_id),
pr.value.components().iter().map(|v| (v * 1e6).round() as i64).collect(),
pr.keys.len(),
)),
}
}
}
}
}
}
out.sort();
out
}
/// The Tint of 356 imported, edited by `f`.
fn tint(f: impl FnOnce(&mut PropGroup)) -> Option<Project> {
Some({
let mut p = import_bytes(&crate::common::try_fixture("356-fx-tint-default.aep")?);
let id = p.items.values().find(|i| i.name == "C").map(|i| i.id).expect("C");
with_layer(&mut p, id, 0, |l| {
let g =
l.props.sub_mut("effects").and_then(|e| e.children.iter_mut().find_map(|n| if let Node::Group(g) = n { Some(g) } else { None })).expect("tint");
f(g);
});
p
})
}
#[test]
fn edited_parameters_and_keys_no_fixture_has() {
let p = skip!(tint(|g| {
g.get_mut("black").expect("black").value = Value::Color([0.25, 0.5, 0.75, 1.0]);
g.get_mut("white").expect("white").keys = vec![key(0.0, Value::Color([1.0, 0.0, 0.0, 1.0])), key(1.0, Value::Color([0.0, 0.0, 1.0, 1.0]))];
// A keyed property shows its first key's value.
g.get_mut("white").expect("white").value = Value::Color([1.0, 0.0, 0.0, 1.0]);
g.get_mut("amount").expect("amount").value = Value::Scalar(10.0);
let mut k0 = key(0.0, Value::Scalar(10.0));
k0.out_interp = Interp::Hold;
g.get_mut("amount").expect("amount").keys = vec![k0, key(2.0, Value::Scalar(90.0))];
g.name = "My Tint".into();
}));
let r = export_all(&p);
assert_eq!(r.report.exported.effects, 1);
assert_eq!(r.report.count(LossCategory::Effects), 0, "{:?}", r.report.losses);
let file = parse(&r.bytes).expect("parse");
let seen = effects_of(&file);
let fx = &seen.first().expect("layer").1[0];
assert_eq!(fx.name.as_deref(), Some("My Tint"));
// As After Effects stores a renamed instance (610): fnam keeps the effect's name.
let view = effectcraft_aep::Project::new(&file).expect("project");
let e = view.all_items().into_iter().find_map(|i| i.comp()).and_then(|c| c.layers().next()).map(|l| l.effects()).expect("effects");
assert_eq!((e[0].name().as_deref(), e[0].user_name().as_deref()), (Some("Tint"), Some("My Tint")));
let param = |i: usize| fx.params.iter().find(|p| p.0 == i).expect("param");
match &param(1).1 {
Some(ParamValue::Argb(c)) => assert!((c[1] - 0.25).abs() < 1e-6 && (c[2] - 0.5).abs() < 1e-6 && (c[3] - 0.75).abs() < 1e-6, "{c:?}"),
other => panic!("{other:?}"),
}
let white = &param(2).2;
assert_eq!(white.len(), 2);
assert_eq!(white[1].0, 25_600);
assert_eq!(white[1].1, vec![255.0, 0.0, 0.0, 255.0]);
let amount = &param(3).2;
assert_eq!(amount.iter().map(|k| (k.0, k.1[0], k.2)).collect::<Vec<_>>(), vec![(0, 10.0, (1, 3)), (51_200, 90.0, (1, 1))]);
// And back.
let q = import_bytes(&r.bytes);
assert_eq!(effect_values(&p).into_iter().filter(|v| v.2 == "My Tint").count(), 3);
assert_eq!(
effect_values(&p)
.into_iter()
.map(|mut v| {
v.1.clear();
v
})
.collect::<Vec<_>>(),
effect_values(&q)
.into_iter()
.map(|mut v| {
v.1.clear();
v
})
.collect::<Vec<_>>()
);
}
#[test]
fn several_instances_share_one_definition_copy() {
// Two Tints and a Ramp on one layer, a Ramp on a second layer.
let mut p = import_bytes(&fixture!("383-fx-ramp-on-100x100-start-10-20.aep"));
let tint_src = import_bytes(&fixture!("356-fx-tint-default.aep"));
let tint_group = tint_src
.items
.values()
.find_map(|i| if let ItemKind::Comp(c) = &i.kind { c.layers.first().and_then(|l| l.effects()).and_then(|e| e.groups().next().cloned()) } else { None })
.expect("tint");
let c = p.items.values().find(|i| i.name == "C").map(|i| i.id).expect("C");
with_layer(&mut p, c, 0, |l| {
let fx = l.props.sub_mut("effects").expect("effects");
fx.children.push(Node::Group(tint_group.clone()));
fx.children.push(Node::Group(tint_group));
});
let r = export_all(&p);
assert_eq!(r.report.exported.effects, 4, "{:?}", r.report.losses);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let mut full = Vec::new();
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
for layer in comp.layers() {
for e in layer.effects() {
full.push((e.match_name().to_string(), e.has_own_definitions()));
}
}
}
// The first instance of each type in the file holds the definitions.
assert_eq!(full.iter().filter(|(_, own)| *own).count(), 2, "{full:?}");
assert_eq!(full.len(), 4);
let defs: Vec<String> = view.effect_definitions().into_iter().map(|(n, _)| n).collect();
assert_eq!(defs, vec!["ADBE Ramp".to_string(), "ADBE Tint".to_string()]);
let pefl: Vec<String> =
file.list(b"Pefl").expect("Pefl").children().iter().filter_map(|c| c.bytes()).map(|b| String::from_utf8_lossy(b).to_string()).collect();
assert_eq!(pefl, vec!["ADBE Ramp".to_string(), "ADBE Tint".to_string()]);
let efdc = file.list(b"EfdG").and_then(|g| g.child(b"EfDC")).and_then(|c| c.bytes()).expect("EfDC");
assert_eq!(efdc, &2u32.to_le_bytes());
// Every instance reads its parameters (borrowed definitions included) and imports again.
let q = import_bytes(&r.bytes);
assert_eq!(effect_values(&q).iter().map(|v| v.2.clone()).collect::<std::collections::BTreeSet<_>>().len(), 2);
let n: usize = q
.items
.values()
.filter_map(|i| {
if let ItemKind::Comp(c) = &i.kind { Some(c.layers.iter().filter_map(|l| l.effects()).map(|e| e.groups().count()).sum::<usize>()) } else { None }
})
.sum();
assert_eq!(n, 4);
}
#[test]
fn what_cannot_be_written_is_reported() {
let p = skip!(tint(|g| {
g.enabled = false;
g.get_mut("amount").expect("amount").expr = Some(effectcraft_project::Expression { text: "50".into(), enabled: true });
}));
let r = export_all(&p);
// The switch (fx-switch cases) and the expression (534) are written; a second import gets the
// effect switched off.
assert_eq!(r.report.count(LossCategory::Effects), 0, "{:?}", r.report.losses);
let back = import_bytes(&r.bytes);
let off = back
.comps()
.flat_map(|(_, c)| c.layers.iter())
.filter_map(|l| l.props.sub("effects"))
.flat_map(|e| e.children.iter())
.any(|n| matches!(n, Node::Group(g) if !g.enabled));
assert!(off, "the switched-off effect comes back switched off");
// An effect outside the table.
let mut q = import_bytes(&fixture!("356-fx-tint-default.aep"));
let c = q.items.values().find(|i| i.name == "C").map(|i| i.id).expect("C");
with_layer(&mut q, c, 0, |l| {
if let Some(Node::Group(g)) = l.props.sub_mut("effects").and_then(|e| e.children.first_mut()) {
g.kind = effectcraft_project::GroupKind::Effect { effect: "ec.distort.notmapped".into() };
}
});
let r = export_all(&q);
assert_eq!(r.report.count(LossCategory::Effects), 1);
assert_eq!(r.report.exported.effects, 0);
parse(&r.bytes).expect("still a valid file");
}
/// CC Color Neutralizer, EXtractoR and IDentifier are in the import table but have no prototype
/// to write from: each is reported, not written.
#[test]
fn imported_plug_in_effects_are_reported_not_written() {
for effect in ["ec.color.cccolorneutralizer", "ec.3d.extractor", "ec.3d.identifier"] {
let mut p = skip!(tint(|_| {}));
let c = p.items.values().find(|i| i.name == "C").map(|i| i.id).expect("C");
with_layer(&mut p, c, 0, |l| {
if let Some(Node::Group(g)) = l.props.sub_mut("effects").and_then(|e| e.children.first_mut()) {
g.kind = effectcraft_project::GroupKind::Effect { effect: effect.into() };
}
});
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::Effects), 1, "{effect}: {:?}", r.report.losses);
assert_eq!(r.report.exported.effects, 0, "{effect}");
parse(&r.bytes).expect("still a valid file");
}
}
#[test]
fn hostile_effect_values_never_panic() {
for v in [Value::Scalar(f64::NAN), Value::Scalar(1e300), Value::Color([f32::NAN as f64, 2.0, -1.0, 1.0]), Value::Bool(true), Value::Text(Box::default())] {
let p = skip!(tint(|g| {
g.get_mut("black").expect("black").value = v.clone();
g.get_mut("amount").expect("amount").value = v.clone();
g.get_mut("white").expect("white").keys = vec![key(0.0, v.clone()), key(0.0, v.clone()), key(1e12, v.clone())];
}));
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
let _ = import_bytes(&r.bytes);
}
}
/// The static value records (`tdbs` with a `cdat`) of the mapped parameters of every effect
/// instance, by (composition, layer index, effect index, record name).
fn static_records(file: &AepFile<'_>) -> std::collections::BTreeMap<(String, usize, usize, String), effectcraft_aep::Chunk<'static>> {
let view = effectcraft_aep::Project::new(file).expect("project");
let mut out = std::collections::BTreeMap::new();
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
let cname = item.display_name().unwrap_or_default();
for (li, layer) in comp.layers().enumerate() {
for (ei, e) in layer.effects().into_iter().enumerate() {
let Some(spec) = effectcraft_aep::effect_map::by_match_name(e.match_name()) else { continue };
let Some(values) = e.chunk().child_list(b"tdgp") else { continue };
let k = values.children();
for (i, c) in k.iter().enumerate() {
let Some(name) =
c.bytes().filter(|_| c.is(b"tdmn")).map(|b| String::from_utf8_lossy(b.split(|x| *x == 0).next().unwrap_or(b"")).to_string())
else {
continue;
};
let Some(index) = name.rsplit('-').next().and_then(|s| s.parse::<usize>().ok()) else { continue };
if !spec.params.iter().any(|p| p.index == index) {
continue;
}
if let Some(rec) = k.get(i + 1).filter(|r| r.is_list(b"tdbs") && r.child(b"cdat").is_some()) {
let mut rec = rec.clone().into_owned();
// A layer parameter's `tdpi` is a layer id, which differs between the
// files (`layer_parameters_name_the_same_layers` checks the layers).
if let effectcraft_aep::Body::List { children, .. } = &mut rec.body {
for c in children.iter_mut().filter(|c| c.is(b"tdpi")) {
*c = effectcraft_aep::Chunk::data(*b"tdpi", vec![0; 4]);
}
}
out.insert((cname.clone(), li, ei, name), rec);
}
}
}
}
}
out
}
#[test]
fn every_static_value_record_is_rebuilt_in_its_decoded_bytes() {
// The records are built in code from the parameter's type and slider range (R45): every
// static record After Effects wrote for a mapped parameter of an effect fixture comes back
// with the same decoded bytes (the rest of the header is zero, the user name the placeholder).
let mut compared = 0;
for name in skip!(fixtures_with_effects()) {
let bytes = fixture!(&name);
let original = parse(&bytes).expect("parse");
let mut p = Project::default();
let none = |_: &str| false;
let imported = import(&mut p, &bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("import");
// An effect the importer could not take over completely (712: CC Radial Blur's Type
// Scratch has no EffectCraft item) is written as EffectCraft has it.
let lossy: Vec<String> = imported.report.losses.iter().flat_map(|l| l.details.clone()).collect();
let r = export_all(&p);
let exported = parse(&r.bytes).expect("parse export");
let skip = |k: &(String, usize, usize, String)| lossy.iter().any(|d| d.contains(k.3.rsplit_once('-').map_or("", |x| x.0)));
let (mut a, mut b) = (static_records(&original), static_records(&exported));
a.retain(|k, _| !skip(k));
b.retain(|k, _| !skip(k));
for (key, rec) in &a {
let got = b.get(key).unwrap_or_else(|| panic!("{name}: {key:?} not written"));
assert_eq!(decoded(got), decoded(rec), "{name}: {key:?}");
compared += 1;
}
for key in b.keys() {
assert!(a.contains_key(key), "{name}: {key:?} written but After Effects has none");
}
}
assert!(compared >= 60, "{compared}");
}
#[test]
fn hue_saturation_and_levels_data_is_written_as_after_effects_wrote_it() {
// Master Hue / Lightness (444, 446) and Levels' RGB input black, gamma, output white (512,
// 514, 516) live in the effect's arbitrary data: the exported `aRbp` equals After Effects'.
for (name, param) in [
("444-fx-huesat-hue-90.aep", "ADBE HUE SATURATION-0003"),
("446-fx-huesat-light-m30.aep", "ADBE HUE SATURATION-0003"),
("512-fx-levels-inblack-0.1.aep", "ADBE Easy Levels2-0002"),
("514-fx-levels-gamma-2.aep", "ADBE Easy Levels2-0002"),
("516-fx-levels-outwhite-0.9.aep", "ADBE Easy Levels2-0002"),
] {
let bytes = fixture!(name);
let data = |b: &[u8]| -> Vec<u8> {
let f = parse(b).expect("parse");
let view = effectcraft_aep::Project::new(&f).expect("project");
let mut out = Vec::new();
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
for layer in comp.layers() {
for e in layer.effects() {
if let Some(d) = e.arbitrary_data(param) {
out = d.to_vec();
}
}
}
}
out
};
let r = export_all(&import_bytes(&bytes));
assert!(!data(&bytes).is_empty(), "{name}");
assert_eq!(data(&r.bytes), data(&bytes), "{name}");
}
}
/// The layer each layer parameter names, by layer index (comp, layer, effect,
/// parameter index, named layer or "None").
fn layer_params(file: &AepFile<'_>) -> Vec<(String, String, String, usize, String)> {
let view = effectcraft_aep::Project::new(file).expect("project");
let mut out = Vec::new();
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
let cname = item.display_name().unwrap_or_default();
let names: std::collections::HashMap<u32, String> = comp.layers().enumerate().filter_map(|(i, l)| Some((l.header()?.id, format!("#{i}")))).collect();
for (i, layer) in comp.layers().enumerate() {
let lname = format!("#{i}");
for e in layer.effects() {
for p in view.effect_params(&e).into_iter().filter(|p| p.index > 0 && p.kind == effectcraft_aep::ParamKind::Layer) {
let named = match p.stored_value() {
Some(ParamValue::Layer(0)) => "None".to_string(),
Some(ParamValue::Layer(id)) => names.get(&id).cloned().unwrap_or_else(|| format!("? {id}")),
other => format!("{other:?}"),
};
out.push((cname.clone(), lname.clone(), e.match_name().to_string(), p.index, named));
}
}
}
}
out.sort();
out
}
#[test]
fn layer_parameters_name_the_same_layers() {
// 905: Compound Blur, Displacement Map and Set Matte name the grey solid R (904 E22-E24);
// 220 / 320 / 321: Layer Control on another layer, on itself, None.
let mut checked = 0;
for name in
["905-fx-24-effects-set-one-comp.aep", "220-fx-layercontrol-to-layer1.aep", "320-fx-layercontrol-self-explicit.aep", "321-fx-layercontrol-none.aep"]
{
let bytes = fixture!(name);
let original = parse(&bytes).expect("parse");
let p = import_bytes(&bytes);
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::Effects), 0, "{name}: {:?}", r.report.losses);
let exported = parse(&r.bytes).expect("parse export");
let (a, b) = (layer_params(&original), layer_params(&exported));
assert!(!a.is_empty(), "{name}");
assert_eq!(a, b, "{name}");
checked += 1;
}
assert_eq!(checked, 4);
}
/// Sets every property with this match id (in every effect of every layer) to `v`.
fn set_all(p: &mut Project, id: &str, v: Value) -> usize {
fn walk(g: &mut PropGroup, id: &str, v: &Value, n: &mut usize) {
for c in &mut g.children {
match c {
Node::Prop(pr) if pr.match_id == id => {
pr.value = v.clone();
*n += 1;
}
Node::Group(sub) => walk(sub, id, v, n),
_ => {}
}
}
}
let mut n = 0;
let ids: Vec<_> = p.comps().map(|(i, _)| *i).collect();
for cid in ids {
let Some(mut c) = p.comp(cid).cloned() else { continue };
for l in &mut c.layers {
walk(&mut l.props, id, &v, &mut n);
}
if let Some(it) = p.item_mut(cid) {
it.kind = ItemKind::Comp(std::sync::Arc::new(c));
}
}
n
}
fn find_id<'a>(g: &'a PropGroup, id: &str) -> Option<&'a effectcraft_project::Property> {
g.children.iter().find_map(|c| match c {
Node::Prop(pr) if pr.match_id == id => Some(pr),
Node::Group(sub) => find_id(sub, id),
_ => None,
})
}
#[test]
fn an_explicit_none_is_written_as_none() {
// After Effects' None on Compound Blur / Displacement Map / Set Matte (`tdpi` 0) differs from
// the owning layer (fx27 `layer-none`); it is EffectCraft's `NO_LAYER` both ways.
let mut p = import_bytes(&fixture!("905-fx-24-effects-set-one-comp.aep"));
let none = Value::Layer(Some(effectcraft_project::NO_LAYER));
let n: usize = ["blurLayer", "displacementMapLayer", "takeMatteFromLayer"].iter().map(|id| set_all(&mut p, id, none.clone())).sum();
assert_eq!(n, 3);
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::Effects), 0, "{:?}", r.report.losses);
let named: Vec<_> = layer_params(&parse(&r.bytes).expect("parse")).into_iter().filter(|x| x.2 != "ADBE Layer Control").map(|x| x.4).collect();
assert_eq!(named, ["None", "None", "None"]);
let q = import_bytes(&r.bytes);
let mut back = 0;
for (_, c) in q.comps() {
for l in &c.layers {
for id in ["blurLayer", "displacementMapLayer", "takeMatteFromLayer"] {
if let Some(pr) = find_id(&l.props, id) {
assert_eq!(pr.value, none, "{id}");
back += 1;
}
}
}
}
assert_eq!(back, 3);
}
#[test]
fn layer_control_on_a_named_layer_needs_no_source_choice() {
// Layer Control has no source choice in After Effects: a companion other than Source (a
// Layer Control made here defaults to Effects & Masks) is no loss.
let mut p = import_bytes(&fixture!("220-fx-layercontrol-to-layer1.aep"));
assert_eq!(set_all(&mut p, "layerSource", Value::Enum(2)), 1);
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::Effects), 0, "{:?}", r.report.losses);
}
#[test]
fn unmapped_layer_parameters_keep_their_default() {
// Timewarp's Matte Layer and Warp Layer are not in the table; their default is None (`tdpi`
// 0), which the export keeps: the re-import reports nothing (529-533). Written as the owning
// layer, the re-import reported both as "not imported".
for name in ["529-fx-timewarp-default.aep", "531-fx-timewarp-speed-keyed-50-200.aep"] {
let p = import_bytes(&fixture!(name));
let r = export_all(&p);
let mut q = Project::default();
let none = |_: &str| false;
let back = import(&mut q, &r.bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("re-import");
assert_eq!(back.report.count(effectcraft_aep::import::LossCategory::Effects), 0, "{name}: {:?}", back.report.losses);
}
}
/// The arbitrary data of the first instance of `match_name` in a file.
fn arb(bytes: &[u8], match_name: &str, record: &str) -> Vec<u8> {
let file = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let fx = comp.layers().flat_map(|l| l.effects()).find(|e| e.match_name() == match_name).expect("effect");
fx.arbitrary_data(record).expect("data").to_vec()
}
#[test]
fn curves_and_mesh_warp_are_written_as_after_effects_stores_them() {
// Curves: the points and the tables rebuilt from them are After Effects' bytes (963, 964).
for name in ["963-curves-red-mid-down-on-S.aep", "964-curves-rgb-s-curve-on-S.aep"] {
let bytes = fixture!(name);
let r = export_all(&import_bytes(&bytes));
assert_eq!(r.report.count(LossCategory::Effects), 0, "{name}: {:?}", r.report.losses);
assert_eq!(arb(&r.bytes, "ADBE CurvesCustom", "ADBE CurvesCustom-0001"), arb(&bytes, "ADBE CurvesCustom", "ADBE CurvesCustom-0001"), "{name}");
}
// Mesh Warp (985): the same grid, every coordinate within 1e-5 of the layer.
let bytes = fixture!("985-meshwarp-3x3-vertex-moved-on-S.aep");
let r = export_all(&import_bytes(&bytes));
assert_eq!(r.report.count(LossCategory::Effects), 0, "{:?}", r.report.losses);
let (a, b) = (arb(&r.bytes, "ADBE MESH WARP", "ADBE MESH WARP-0004"), arb(&bytes, "ADBE MESH WARP", "ADBE MESH WARP-0004"));
let (ma, mb) = (effectcraft_aep::MeshData::parse(&a).expect("written"), effectcraft_aep::MeshData::parse(&b).expect("stored"));
assert_eq!((ma.columns, ma.rows, ma.tail), (mb.columns, mb.rows, mb.tail));
for (x, y) in ma.vertices.iter().zip(&mb.vertices) {
for (p, q) in x.iter().zip(y) {
assert!((p[0] - q[0]).abs() < 1e-5 && (p[1] - q[1]).abs() < 1e-5, "{p:?} vs {q:?}");
}
}
}
#[test]
fn mesh_handles_moved_on_their_own_survive_the_round_trip() {
// 985 imported, then the right handle of vertex (2, 2) moved by 30 px on its own: the importer
// keeps such moves as extra numbers of the vertex (EffectCraft draws a bilinear mesh).
let mut p = import_bytes(&fixture!("985-meshwarp-3x3-vertex-moved-on-S.aep"));
let id: Vec<_> = p.comps().map(|(i, _)| *i).collect();
let mut tokens = Vec::new();
for cid in id {
let Some(mut c) = p.comp(cid).cloned() else { continue };
for l in &mut c.layers {
fn walk(g: &mut PropGroup, tokens: &mut Vec<String>) {
for n in &mut g.children {
match n {
Node::Prop(pr) if pr.match_id == "mesh" => {
if let Value::Str(s) = &pr.value {
let mut t: Vec<String> = s.split(' ').map(str::to_string).collect();
t[10] = format!("{},0,0,30,0,0,0,0,0", t[10]);
*tokens = t.clone();
pr.value = Value::Str(t.join(" "));
}
}
Node::Group(sub) => walk(sub, tokens),
_ => {}
}
}
}
walk(&mut l.props, &mut tokens);
}
if let Some(it) = p.item_mut(cid) {
it.kind = ItemKind::Comp(std::sync::Arc::new(c));
}
}
assert_eq!(tokens.len(), 16);
let r = export_all(&p);
let data = arb(&r.bytes, "ADBE MESH WARP", "ADBE MESH WARP-0004");
let m = effectcraft_aep::MeshData::parse(&data).expect("mesh");
let d = effectcraft_aep::MeshData::default_vertex(3, 3, 2, 2);
let v = m.vertices[10];
// The right handle: default + the vertex's move + 30 px.
assert!((v[2][0] - (d[2][0] + (132.0 + 30.0) / 1920.0)).abs() < 1e-5, "{:?}", v[2]);
assert!((v[1][0] - (d[1][0] + 132.0 / 1920.0)).abs() < 1e-5, "{:?}", v[1]);
// Re-imported, the vertex keeps the handle move.
let q = import_bytes(&r.bytes);
let mut found = false;
for (_, c) in q.comps() {
for l in &c.layers {
if let Some(Value::Str(s)) = find_id(&l.props, "mesh").map(|p| p.value.clone()) {
let t: Vec<&str> = s.split(' ').collect();
let n: Vec<f64> = t[10].split(',').map(|x| x.parse().expect("number")).collect();
assert_eq!(n.len(), 10, "{}", t[10]);
assert!((n[4] - 30.0).abs() < 0.01 && (n[0] - 132.0).abs() < 0.01, "{n:?}");
found = true;
}
}
}
assert!(found);
}
+338
View File
@@ -0,0 +1,338 @@
//! Footage items and layers: projects with every footage kind the exporter writes are exported
//! and parsed back with `effectcraft-aep` (type tag, size, duration, rate, numbering, alias path,
//! the name), the footage fixtures go through import, export and import, and what cannot be
//! written is reported.
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{PropNode, parse};
use effectcraft_color::Label;
use effectcraft_project::{Footage, FootageKind, ItemId, ItemKind, LayerSource, Project};
use effectcraft_time::FrameRate;
fn still(path: &str, w: u32, h: u32) -> Footage {
Footage { path: path.to_string(), kind: FootageKind::Still, width: w, height: h, has_video: true, ..Footage::default() }
}
fn seq(dir: &str, prefix: &str, start: u32, n: u32, digits: usize, suffix: &str, rate: FrameRate) -> Footage {
let files: Vec<String> = (start..start + n).map(|k| format!("{dir}\\{prefix}{k:0digits$}{suffix}")).collect();
let mut f = Footage { kind: FootageKind::Sequence, frame_rate: rate, sequence: files.clone(), ..still(&files[0], 64, 48) };
f.sync_sequence_duration();
f
}
/// Adds the footage and a layer showing it, as long as the footage (stills: the composition).
fn add_footage(p: &mut Project, comp: ItemId, name: &str, f: Footage) -> ItemId {
let size = (f.width.max(1), f.height.max(1));
let timed = f.kind != FootageKind::Still && f.duration > effectcraft_time::Tick::ZERO;
let duration = f.duration;
let id = p.add_item(name, Label::Lavender, None, ItemKind::Footage(f));
add_layer(p, comp, name, LayerSource::Footage { item: id }, size);
if timed {
with_layer(p, comp, 0, |l| l.out_point = l.start_time + duration);
}
id
}
fn reimport(bytes: &[u8]) -> Project {
let mut p = Project::default();
let none = |_: &str| false;
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&none) };
import(&mut p, bytes, &opts).expect("import");
p
}
/// One of every kind in a composition.
fn all_kinds() -> Project {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
add_footage(&mut p, c, "still.png", still(r"C:\media\still.png", 64, 48));
add_footage(&mut p, c, "still.jpg", still(r"C:\media\still.jpg", 64, 48));
add_footage(&mut p, c, "Renamed EXR", still(r"C:\media\still.exr", 64, 48));
add_footage(&mut p, c, "shot_[0101-0103].exr", seq(r"C:\media\exrseq", "shot_", 101, 3, 4, ".exr", FrameRate::new(30, 1)));
add_footage(&mut p, c, "seq_[001-003].png", seq(r"C:\media\test-seq", "seq_", 1, 3, 3, ".png", FrameRate::new(24, 1)));
let clip = Footage { kind: FootageKind::Video, frame_rate: FrameRate::new(25, 1), duration: secs(2.0), ..still(r"C:\media\clip.mp4", 64, 48) };
add_footage(&mut p, c, "clip.mp4", clip);
let wav = Footage { kind: FootageKind::Audio, duration: secs(1.5), has_video: false, has_audio: true, ..still(r"C:\media\tone.wav", 0, 0) };
add_footage(&mut p, c, "tone.wav", wav);
add_footage(&mut p, c, "still.tif", still(r"C:\media\still.tif", 64, 48));
add_footage(&mut p, c, "j_[000-002].jpg", seq(r"C:\media\jpgseq", "j_", 0, 3, 3, ".jpg", FrameRate::new(25, 1)));
let mov = Footage { kind: FootageKind::Video, frame_rate: FrameRate::new(25, 1), duration: secs(1.0), ..still(r"C:\media\clip.mov", 64, 48) };
add_footage(&mut p, c, "clip.mov", mov);
for e in ["tga", "psd", "ai", "eps"] {
add_footage(&mut p, c, &format!("still.{e}"), still(&format!(r"C:\media\still.{e}"), 64, 48));
}
// 645: 25 native frames conformed to 30 fps.
let conformed = Footage {
kind: FootageKind::Video,
frame_rate: FrameRate::new(30, 1),
native_rate: Some(FrameRate::new(25, 1)),
duration: FrameRate::new(30, 1).tick_of(25),
..still(r"C:\media\conformed.mp4", 64, 48)
};
add_footage(&mut p, c, "conformed.mp4", conformed);
// Its 25/30 s does not fall on the composition's 25 fps frames: the layer ends on a frame, as
// in After Effects (an off-frame out point is a rounded-time loss).
with_layer(&mut p, c, 0, |l| l.out_point = l.start_time + secs(0.8));
p
}
#[test]
fn every_kind_is_written_with_its_fields() {
let p = all_kinds();
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
assert_eq!((r.report.exported.footage, r.report.exported.footage_layers), (15, 15));
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
let view = effectcraft_aep::Project::new(&file).expect("project");
let items = view.all_items();
let by_path = |end: &str| items.iter().find(|i| i.footage().and_then(|f| f.path).is_some_and(|p| p.ends_with(end))).copied().expect(end);
// (path end, tag, w, h, duration num / den, fps, sequence)
let want: [(&str, &str, u32, u32, i64, i64, u32, bool); 15] = [
(r"\still.png", "png!", 64, 48, 0, 1, 0, false),
(r"\still.jpg", "ZPEG", 64, 48, 0, 600, 0, false),
(r"\still.exr", "oEXR", 64, 48, 0, 100, 0, false),
(r"\exrseq", "oEXR", 64, 48, 3, 30, 30, true),
(r"\test-seq", "png!", 64, 48, 3, 24, 24, true),
(r"\clip.mp4", "XCEX", 64, 48, 50, 25, 25, false),
(r"\tone.wav", "WAVE", 0, 0, 72_000, 48_000, 0, false),
(r"\still.tif", "TIF ", 64, 48, 0, 600, 0, false),
(r"\jpgseq", "ZPEG", 64, 48, 3, 25, 25, true),
(r"\clip.mov", "MOoV", 64, 48, 25, 25, 25, false),
(r"\still.tga", "TPIC", 64, 48, 0, 600, 0, false),
(r"\still.psd", "8BPS", 64, 48, 0, 600, 0, false),
(r"\still.ai", "TEXT", 64, 48, 0, 600, 0, false),
(r"\still.eps", "TEXT", 64, 48, 0, 600, 0, false),
(r"\conformed.mp4", "XCEX", 64, 48, 25, 25, 25, false),
];
for (end, tag, w, h, num, den, fps, is_seq) in want {
let item = by_path(end);
let f = item.footage().expect("footage");
assert_eq!((f.file_type.as_str(), f.width, f.height, f.native_frame_rate, f.is_sequence), (tag, w, h, fps, is_seq), "{end}");
let d = f.duration.expect("duration");
assert_eq!((d.num, d.den), (num, den), "{end}");
}
// The conformed clip keeps its native rate and frames and stores the conformed rate (645).
assert_eq!(by_path(r"\conformed.mp4").conform_frame_rate(), Some(30));
assert_eq!(by_path(r"\clip.mp4").conform_frame_rate(), None);
let s = by_path(r"\exrseq").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));
let s = by_path(r"\test-seq").sequence_info().expect("numbering");
assert_eq!((s.prefix.as_str(), s.suffix.as_str(), s.start, s.end, s.digits), ("seq_", ".png", 1, 3, 3));
// A default name is not stored (After Effects names the item after its file), another one is.
assert_eq!(by_path(r"\still.png").name(), None);
assert_eq!(by_path(r"\still.png").display_name().as_deref(), Some("still.png"));
assert_eq!(by_path(r"\exrseq").name(), None);
assert_eq!(by_path(r"\still.exr").name().as_deref(), Some("Renamed EXR"));
// png options: size and the first file's name.
assert_eq!(by_path(r"\test-seq").footage().and_then(|f| f.name).as_deref(), Some("seq_001.png"));
// Layers: the source, its size, the Time Remapping maximum (the source's duration).
let comp = items.iter().find_map(|i| i.comp()).expect("comp");
for layer in comp.layers() {
let src = view.layer_source(&layer).expect("source");
let f = src.footage().expect("footage source");
let Some(PropNode::Property(tr)) = layer.properties().and_then(|g| g.get("ADBE Time Remapping")) else { panic!("time remap") };
let max = tr.chunk().child(b"tduM").and_then(|c| c.bytes()).map(|b| f64::from_be_bytes(b[..8].try_into().expect("8"))).expect("tduM");
let d = f.duration.expect("duration");
// A conformed clip lasts its native frames at the conformed rate (645: 25 / 30 s).
let den = src.conform_frame_rate().map_or(d.den, i64::from);
assert!((max - d.num as f64 / den as f64).abs() < 1e-9, "{:?}: {max}", f.path);
}
}
#[test]
fn the_alias_holds_the_path_escaped() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 1.0, None);
add_footage(&mut p, c, "odd", still("C:\\a \"quoted\" dir\\Ünïcödé\\x.png", 8, 8));
add_footage(&mut p, c, "mac", still("/Volumes/Media/a.jpg", 8, 8));
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let paths: Vec<String> = view.all_items().iter().filter_map(|i| i.footage()).filter_map(|f| f.path).collect();
assert!(paths.contains(&"C:\\a \"quoted\" dir\\Ünïcödé\\x.png".to_string()), "{paths:?}");
assert!(paths.contains(&"/Volumes/Media/a.jpg".to_string()), "{paths:?}");
}
#[test]
fn footage_survives_import_export_import() {
for name in [
"126-footage-png-layer.aep",
"603-footage-exrseq-0101-as-layer.aep",
"645-footage-mp4-conform-30.aep",
"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",
] {
let p1 = reimport(&fixture!(name));
let r = export_all(&p1);
assert_eq!(r.report.count(LossCategory::FootageItems) + r.report.count(LossCategory::UnsupportedLayers), 0, "{name}: {:?}", r.report.losses);
let p2 = reimport(&r.bytes);
let footage = |p: &Project| -> Vec<(String, Footage)> {
let mut v: Vec<(String, Footage)> =
p.items.values().filter_map(|i| if let ItemKind::Footage(f) = &i.kind { Some((i.name.clone(), f.clone())) } else { None }).collect();
v.sort_by(|a, b| a.0.cmp(&b.0));
v
};
let (a, b) = (footage(&p1), footage(&p2));
assert_eq!(a.len(), 1, "{name}");
assert_eq!(a.len(), b.len(), "{name}");
for ((na, fa), (nb, fb)) in a.iter().zip(&b) {
assert_eq!(na, nb, "{name}");
assert_eq!((&fa.path, fa.kind, fa.width, fa.height, &fa.sequence), (&fb.path, fb.kind, fb.width, fb.height, &fb.sequence), "{name}");
assert_eq!((fa.frame_rate, fa.native_rate, fa.duration), (fb.frame_rate, fb.native_rate, fb.duration), "{name}");
}
let layers = |p: &Project| -> usize {
p.items
.values()
.filter_map(|i| {
if let ItemKind::Comp(c) = &i.kind {
Some(c.layers.iter().filter(|l| matches!(l.source, LayerSource::Footage { .. })).count())
} else {
None
}
})
.sum()
};
assert_eq!(layers(&p1), 1, "{name}");
assert_eq!(layers(&p2), 1, "{name}");
}
}
/// The stored folder time (`sspc@118`) of the sequence item, big-endian.
fn sequence_folder_time(bytes: &[u8]) -> u32 {
let file = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let item = view.all_items().into_iter().find(|i| i.footage().is_some_and(|f| f.is_sequence)).expect("sequence");
let sspc = item.chunk().child_list(b"Pin ").and_then(|pin| pin.child(b"sspc")).and_then(|c| c.bytes()).expect("sspc");
u32::from_be_bytes(sspc[118..122].try_into().expect("4 bytes"))
}
/// 860: After Effects stores the sequence folder's modification time (seconds since 1904, UTC) at
/// `sspc@118` and rescans the folder on open when it differs from the folder's, warning about the
/// missing number of a sparse sequence in a modal dialog (export-tests x1-x3: the folder's time
/// opens without the dialog, the first or the last file's time does not). The export writes the
/// time the caller gives (the folder of 860 at 2026-10-19 03:51:22 UTC is stored as 0xe6fb443a),
/// only for sequences, and keeps the template's without one.
#[test]
fn a_sequence_stores_its_folder_time() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 64, 48, FrameRate::new(30, 1), 1.0, None);
add_footage(&mut p, c, "sp_[0001-0005].png", seq(r"C:\media\sparse", "sp_", 1, 5, 4, ".png", FrameRate::new(30, 1)));
add_footage(&mut p, c, "still.png", still(r"C:\media\still.png", 64, 48));
let asked = std::cell::RefCell::new(Vec::<String>::new());
let time = |dir: &str| {
asked.borrow_mut().push(dir.to_string());
Some(1_792_381_882)
};
let opts = effectcraft_aep::export::ExportOptions { allow_losses: true };
let r = effectcraft_aep::export::export_with(&p, &opts, &time).expect("export");
assert_eq!(sequence_folder_time(&r.bytes), 0xe6fb_443a);
// The caller is asked with the sequence's first file as stored (it checks that path before it
// looks at the folder), and only for the sequence.
assert_eq!(*asked.borrow(), [r"C:\media\sparse\sp_0001.png"], "only the sequence is asked for");
// Without a time (plain `export`, or an unknown folder) the template's value stays.
let plain = export_all(&p);
let unknown = effectcraft_aep::export::export_with(&p, &opts, &|_| None).expect("export");
assert_eq!(sequence_folder_time(&unknown.bytes), sequence_folder_time(&plain.bytes));
assert_ne!(sequence_folder_time(&plain.bytes), 0xe6fb_443a);
// A time beyond the field (after 2040) is not written either.
let late = effectcraft_aep::export::export_with(&p, &opts, &|_| Some(u64::MAX)).expect("export");
assert_eq!(sequence_folder_time(&late.bytes), sequence_folder_time(&plain.bytes));
// The stills stay byte for byte as without times.
let still_bytes = |bytes: &[u8]| {
let file = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let item = view.all_items().into_iter().find(|i| i.footage().is_some_and(|f| !f.is_sequence)).expect("still");
item.chunk().child_list(b"Pin ").and_then(|pin| pin.child(b"sspc")).and_then(|c| c.bytes()).expect("sspc").to_vec()
};
assert_eq!(still_bytes(&r.bytes), still_bytes(&plain.bytes));
}
/// A sparse sequence (860: After Effects imports sp_0001, 0002, 0004, 0005 as `sp_[0001-0005].png`
/// and stores only the folder and the numbering 1-5): the import lists every number in the range,
/// files on disk or not, and the export writes the same range, so After Effects finds the folder
/// and treats the missing number as it does in the original (it holds the frame before). Opened
/// without a dialog only with the folder's time (`a_sequence_stores_its_folder_time`).
#[test]
fn a_sparse_sequence_keeps_its_range() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 64, 48, FrameRate::new(30, 1), 1.0, None);
add_footage(&mut p, c, "sp_[0001-0005].png", seq(r"C:\media\sparse", "sp_", 1, 5, 4, ".png", FrameRate::new(30, 1)));
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let item = view.all_items().into_iter().find(|i| i.footage().is_some()).expect("footage");
assert_eq!(item.footage().and_then(|f| f.path).as_deref(), Some(r"C:\media\sparse"), "the alias is the folder");
let s = item.sequence_info().expect("numbering");
assert_eq!((s.start, s.end, s.digits), (1, 5, 4));
// Re-import with number 3 absent on disk: still five frames, 1 to 5.
let mut q = Project::default();
let exists = |path: &str| !path.ends_with("sp_0003.png");
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&exists) };
import(&mut q, &r.bytes, &opts).expect("import");
let f = q.items.values().find_map(|i| if let ItemKind::Footage(f) = &i.kind { Some(f.clone()) } else { None }).expect("footage");
let names: Vec<&str> = f.sequence.iter().map(|s| s.rsplit('\\').next().unwrap_or(s)).collect();
assert_eq!(names, ["sp_0001.png", "sp_0002.png", "sp_0003.png", "sp_0004.png", "sp_0005.png"]);
}
#[test]
fn what_cannot_be_written_is_reported() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 1.0, None);
add_footage(&mut p, c, "avi", Footage { kind: FootageKind::Video, frame_rate: FrameRate::new(25, 1), ..still(r"C:\m\a.avi", 8, 8) });
add_footage(&mut p, c, "bmp", still(r"C:\m\a.bmp", 8, 8));
add_footage(&mut p, c, "ntsc", Footage { kind: FootageKind::Video, frame_rate: FrameRate::FPS_29_97, ..still(r"C:\m\a.mp4", 8, 8) });
let mut gaps = seq(r"C:\m", "g_", 1, 3, 2, ".png", FrameRate::new(25, 1));
gaps.sequence.remove(1);
add_footage(&mut p, c, "gaps", gaps);
add_footage(&mut p, c, "nopath", still("", 8, 8));
add_footage(&mut p, c, "mp3", Footage { kind: FootageKind::Audio, ..still(r"C:\m\a.mp3", 0, 0) });
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::FootageItems), 6, "{:?}", r.report.losses);
assert_eq!(r.report.count(LossCategory::UnsupportedLayers), 6, "{:?}", r.report.losses);
assert_eq!(r.report.exported.footage, 0);
parse(&r.bytes).expect("still a valid file");
}
#[test]
fn a_layer_past_its_source_s_end_is_reported() {
// After Effects ends such a layer at the source's end (f1 read-back).
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 5.0, None);
add_footage(
&mut p,
c,
"clip.mp4",
Footage { kind: FootageKind::Video, frame_rate: FrameRate::new(25, 1), duration: secs(2.0), ..still(r"C:\m\clip.mp4", 8, 8) },
);
with_layer(&mut p, c, 0, |l| l.out_point = secs(4.0));
add_footage(&mut p, c, "still.png", still(r"C:\m\still.png", 8, 8));
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::LayerTiming), 1, "{:?}", r.report.losses);
assert_eq!(r.report.exported.footage_layers, 2);
}
#[test]
fn hostile_footage_never_panics() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 1.0, None);
let big = seq(r"C:\m", "f", 1, 100_000, 6, ".exr", FrameRate::new(25, 1));
add_footage(&mut p, c, "big", big);
add_footage(&mut p, c, "huge", still(r"C:\m\h.png", u32::MAX, u32::MAX));
add_footage(&mut p, c, "ctl", still("C:\\m\\a\u{1}b.png", 8, 8));
add_footage(&mut p, c, "nodigits", seq(r"C:\m", "x", 1, 1, 1, ".png", FrameRate::new(25, 1)));
let mut nod = still(r"C:\m\plain.png", 8, 8);
nod.kind = FootageKind::Sequence;
add_footage(&mut p, c, "plain-seq", nod);
add_footage(&mut p, c, "zero-rate", Footage { kind: FootageKind::Video, frame_rate: FrameRate::new(0, 1), ..still(r"C:\m\z.mp4", 8, 8) });
add_footage(&mut p, c, "long", Footage { kind: FootageKind::Audio, duration: effectcraft_time::Tick(i64::MAX), ..still(r"C:\m\l.wav", 0, 0) });
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
let _ = reimport(&r.bytes);
}
+100
View File
@@ -0,0 +1,100 @@
#![allow(dead_code)]
//! Builders shared by the exporter tests.
use std::sync::Arc;
use effectcraft_aep::export::{ExportOptions, ExportResult, export};
use effectcraft_color::Label;
use effectcraft_keyframe::{Keyframe, Value};
use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, Project, Solid, build};
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
pub fn secs(s: f64) -> Tick {
Tick((s * TICKS_PER_SECOND as f64).round() as i64)
}
pub fn add_comp(p: &mut Project, name: &str, w: u32, h: u32, fps: FrameRate, dur: f64, parent: Option<ItemId>) -> ItemId {
let comp = Comp::new(w, h, fps, secs(dur));
p.add_item(name, Label::None, parent, ItemKind::Comp(Arc::new(comp)))
}
pub fn add_solid(p: &mut Project, name: &str, w: u32, h: u32, color: [f32; 3], parent: Option<ItemId>) -> ItemId {
p.add_item(name, Label::Red, parent, ItemKind::Solid(Solid { color, width: w, height: h, pixel_aspect: 1.0 }))
}
/// Adds a layer on top of the composition.
pub fn add_layer(p: &mut Project, comp: ItemId, name: &str, source: LayerSource, size: (u32, u32)) {
let mut c = p.comp(comp).cloned().expect("comp");
let mut l = build::layer(p, &c, name, source, size, None);
l.name = name.to_string();
c.layers.insert(0, l);
if let Some(i) = p.item_mut(comp) {
i.kind = ItemKind::Comp(Arc::new(c));
}
}
pub fn with_layer(p: &mut Project, comp: ItemId, idx: usize, f: impl FnOnce(&mut Layer)) {
let mut c = p.comp(comp).cloned().expect("comp");
if let Some(l) = c.layers.get_mut(idx) {
f(l);
}
if let Some(i) = p.item_mut(comp) {
i.kind = ItemKind::Comp(Arc::new(c));
}
}
pub fn with_comp(p: &mut Project, comp: ItemId, f: impl FnOnce(&mut Comp)) {
let mut c = p.comp(comp).cloned().expect("comp");
f(&mut c);
if let Some(i) = p.item_mut(comp) {
i.kind = ItemKind::Comp(Arc::new(c));
}
}
pub fn key(t: f64, v: Value) -> Keyframe {
Keyframe::new(secs(t), v)
}
pub fn export_all(p: &Project) -> ExportResult {
export(p, &ExportOptions { allow_losses: true }).expect("export")
}
/// One comp `C` (1920x1080, 25 fps, 5 s) with one solid layer `L`.
pub fn simple() -> (Project, ItemId, ItemId) {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
let s = add_solid(&mut p, "L", 1920, 1080, [1.0, 0.0, 0.0], None);
add_layer(&mut p, c, "L", LayerSource::Solid { item: s }, (1920, 1080));
(p, c, s)
}
/// `c` as far as the exporter writes property records: in every `tdbs` the user name is left out
/// and the header bytes that are not decoded are zero (aep-format.md 3.4; After Effects reads
/// them as zero, read-back e1-ztdb4d).
pub fn decoded(c: &effectcraft_aep::Chunk<'static>) -> effectcraft_aep::Chunk<'static> {
use effectcraft_aep::{Body, Chunk};
const KEEP: &[(usize, usize)] = &[(0, 4), (5, 6), (7, 16), (68, 69), (76, 78), (79, 80), (119, 121)];
let record = c.is_list(b"tdbs");
let kids = |children: &[Chunk<'static>]| -> Vec<Chunk<'static>> {
children
.iter()
.filter(|k| !(record && k.is(b"tdsn")))
.map(|k| {
if record && k.is(b"tdb4") {
let d = k.bytes().unwrap_or_default();
Chunk::data(
*b"tdb4",
d.iter().enumerate().map(|(i, b)| if KEEP.iter().any(|(f, e)| (*f..*e).contains(&i)) { *b } else { 0 }).collect::<Vec<u8>>(),
)
} else {
decoded(k)
}
})
.collect()
};
match &c.body {
Body::List { list_type, children } => Chunk { id: c.id, body: Body::List { list_type: *list_type, children: kids(children) }, pad: c.pad },
Body::Chunks(children) => Chunk { id: c.id, body: Body::Chunks(kids(children)), pad: c.pad },
_ => c.clone(),
}
}
+381
View File
@@ -0,0 +1,381 @@
//! Masks: projects built in code are exported, parsed back with `effectcraft-aep` (every written
//! field compared) and imported again; the mask fixtures go through import -> export -> import.
use crate::export::helpers::{add_comp, add_layer, add_solid, export_all, key, with_layer};
use effectcraft_aep::export::{ExportOptions, LossCategory, export};
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{Interpolation, KeyframeKind, MaskMode as AepMode, PropNode, ValueSource, parse, write};
use effectcraft_keyframe::{Ease, Interp, ShapePath, Value};
use effectcraft_project::{Expression, FeatherFalloff, GroupKind, Layer, LayerSource, MaskMode, Project, PropGroup, build};
use effectcraft_time::FrameRate;
fn add_mask(l: &mut Layer, next: &mut u64, name: &str, path: ShapePath, mode: MaskMode, f: impl FnOnce(&mut PropGroup)) {
let i = l.masks().map_or(0, |m| m.children.len());
let mut g = build::mask(&mut build::Ids(next), name, path, mode, build::MASK_COLORS[i % 8]);
f(&mut g);
l.props.sub_mut("masks").expect("masks group").children.push(g.into());
}
fn set(g: &mut PropGroup, id: &str, v: Value) {
g.get_mut(id).expect(id).value = v;
}
fn invert(g: &mut PropGroup) {
if let GroupKind::Mask { inverted, .. } = &mut g.kind {
*inverted = true;
}
}
/// A five-vertex open path with tangents.
fn open_path() -> ShapePath {
ShapePath {
vertices: vec![[200.0, 200.0], [600.0, 150.0], [900.0, 500.0], [700.0, 900.0], [300.0, 800.0]],
in_tangents: vec![[0.0, 0.0], [-100.0, -20.0], [0.0, -150.0], [120.0, 0.0], [40.0, 60.0]],
out_tangents: vec![[50.0, -30.0], [100.0, 20.0], [0.0, 150.0], [-120.0, 0.0], [0.0, 0.0]],
closed: false,
feather: Vec::new(),
}
}
/// A six-vertex closed polygon with tangents.
fn hexagon() -> ShapePath {
let mut p = ShapePath::polygon(&[[960.0, 200.0], [1260.0, 370.0], [1260.0, 710.0], [960.0, 880.0], [660.0, 710.0], [660.0, 370.0]], true);
p.in_tangents[1] = [-40.0, -40.0];
p.out_tangents[1] = [40.0, 40.0];
p
}
/// Composition C (1920x1080, 25 fps, 5 s) with solid layer L and the masks `f` adds.
fn project(f: impl FnOnce(&mut Layer, &mut u64)) -> Project {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
let s = add_solid(&mut p, "L", 1920, 1080, [1.0, 0.0, 0.0], None);
add_layer(&mut p, c, "L", LayerSource::Solid { item: s }, (1920, 1080));
let mut next = p.next_id;
with_layer(&mut p, c, 0, |l| f(l, &mut next));
p.next_id = next;
p
}
fn all_modes() -> Project {
project(|l, n| {
add_mask(l, n, "Rect", ShapePath::rect([960.0, 540.0], 800.0, 400.0), MaskMode::Add, |_| {});
add_mask(l, n, "Ellipse", ShapePath::ellipse([960.0, 540.0], 600.0, 300.0), MaskMode::Subtract, |g| {
invert(g);
set(g, "feather", Value::Vec2([20.0, 10.0]));
set(g, "opacity", Value::Scalar(50.0));
set(g, "expansion", Value::Scalar(5.0));
});
add_mask(l, n, "Open", open_path(), MaskMode::Intersect, |_| {});
add_mask(l, n, "Hex", hexagon(), MaskMode::Difference, |g| set(g, "expansion", Value::Scalar(-12.5)));
add_mask(l, n, "Lighten", ShapePath::rect([300.0, 300.0], 200.0, 100.0), MaskMode::Lighten, |_| {});
add_mask(l, n, "Darken", ShapePath::rect([1600.0, 300.0], 200.0, 100.0), MaskMode::Darken, |_| {});
add_mask(l, n, "None", ShapePath::ellipse([300.0, 900.0], 100.0, 100.0), MaskMode::None, |_| {});
})
}
fn animated() -> Project {
project(|l, n| {
add_mask(l, n, "Keyed", ShapePath::rect([960.0, 540.0], 400.0, 200.0), MaskMode::Add, |g| {
let path = g.get_mut("path").expect("path");
let mut k1 = key(1.0, Value::Path(ShapePath::rect([960.0, 540.0], 800.0, 400.0)));
k1.out_interp = Interp::Hold;
k1.label = 3;
path.keys = vec![
key(0.0, Value::Path(ShapePath::rect([960.0, 540.0], 400.0, 200.0))),
k1,
key(2.0, Value::Path(ShapePath::rect([900.0, 500.0], 600.0, 300.0))),
];
let feather = g.get_mut("feather").expect("feather");
let mut a = key(0.0, Value::Vec2([0.0, 0.0]));
a.out_interp = Interp::Bezier;
a.out_ease = vec![Ease { speed: 15.0, influence: 0.66 }, Ease { speed: 5.0, influence: 0.5 }];
let mut b = key(2.0, Value::Vec2([50.0, 30.0]));
b.in_interp = Interp::Bezier;
b.in_ease = vec![Ease { speed: 8.0, influence: 0.66 }, Ease { speed: 8.0, influence: 0.66 }];
feather.keys = vec![a, b];
});
})
}
fn masks_of(p: &Project) -> Vec<PropGroup> {
let c = p.items.values().find_map(|i| match &i.kind {
effectcraft_project::ItemKind::Comp(c) if i.name == "C" => Some(c.clone()),
_ => None,
});
let c = c.expect("comp C");
c.layers.iter().find(|l| l.name == "L").and_then(|l| l.masks()).map(|m| m.groups().cloned().collect()).unwrap_or_default()
}
fn reimport(bytes: &[u8]) -> Project {
let mut p = Project::default();
let none = |_: &str| false;
import(&mut p, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("import");
p
}
fn path_of(v: &Value) -> &ShapePath {
match v {
Value::Path(p) => p,
other => panic!("{other:?}"),
}
}
fn same_path(a: &ShapePath, b: &ShapePath, what: &str) {
assert_eq!((a.len(), a.closed), (b.len(), b.closed), "{what}");
let near = |x: [f64; 2], y: [f64; 2]| (x[0] - y[0]).abs() < 0.01 && (x[1] - y[1]).abs() < 0.01;
for i in 0..a.len() {
assert!(near(a.vertices[i], b.vertices[i]), "{what} vertex {i}: {:?} {:?}", a.vertices[i], b.vertices[i]);
assert!(near(a.in_tangents[i], b.in_tangents[i]), "{what} in {i}: {:?} {:?}", a.in_tangents[i], b.in_tangents[i]);
assert!(near(a.out_tangents[i], b.out_tangents[i]), "{what} out {i}: {:?} {:?}", a.out_tangents[i], b.out_tangents[i]);
}
}
/// Two projects' masks are equal for every written field.
fn same_masks(a: &[PropGroup], b: &[PropGroup]) {
assert_eq!(a.len(), b.len());
for (x, y) in a.iter().zip(b) {
let w = x.name.as_str();
assert_eq!(x.name, y.name);
let k = |g: &PropGroup| match g.kind {
GroupKind::Mask { mode, inverted, .. } => (mode, inverted),
_ => panic!("not a mask"),
};
assert_eq!(k(x), k(y), "{w}");
for id in ["path", "feather", "opacity", "expansion"] {
let (px, py) = (x.get(id).unwrap(), y.get(id).unwrap());
assert_eq!(px.keys.len(), py.keys.len(), "{w} {id} keys");
let pairs = std::iter::once((&px.value, &py.value)).chain(px.keys.iter().map(|k| &k.value).zip(py.keys.iter().map(|k| &k.value)));
for (vx, vy) in pairs {
if id == "path" {
same_path(path_of(vx), path_of(vy), w);
} else {
assert!(vx.components().iter().zip(vy.components()).all(|(p, q)| (p - q).abs() < 1e-9), "{w} {id} {vx:?} {vy:?}");
}
}
for (kx, ky) in px.keys.iter().zip(&py.keys) {
assert_eq!((kx.time, kx.in_interp, kx.out_interp, kx.label), (ky.time, ky.in_interp, ky.out_interp, ky.label), "{w} {id}");
if id == "feather" {
let near = |e: &[Ease], f: &[Ease]| {
e.len() == f.len() && e.iter().zip(f).all(|(a, b)| (a.speed - b.speed).abs() < 1e-9 && (a.influence - b.influence).abs() < 1e-9)
};
// The first key's in ease and the last key's out ease are not carried.
if kx.in_interp == Interp::Bezier && !kx.in_ease.is_empty() && !ky.in_ease.is_empty() {
assert!(near(&kx.in_ease, &ky.in_ease), "{w} in ease {:?} {:?}", kx.in_ease, ky.in_ease);
}
if kx.out_interp == Interp::Bezier && !kx.out_ease.is_empty() && !ky.out_ease.is_empty() {
assert!(near(&kx.out_ease, &ky.out_ease), "{w} out ease {:?} {:?}", kx.out_ease, ky.out_ease);
}
}
}
}
}
}
#[test]
fn every_written_field_parses_back() {
let p = all_modes();
let res = export_all(&p);
assert!(res.report.is_lossless(), "{:?}", res.report.losses);
assert_eq!(res.report.exported.masks, 7);
// The container is consistent: it writes back byte for byte.
let file = parse(&res.bytes).expect("parse");
assert_eq!(write(&file).expect("write"), res.bytes);
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let layer = comp.layers().next().expect("layer");
let masks = layer.masks();
let names: Vec<_> = masks.iter().map(|m| m.name.clone().unwrap_or_default()).collect();
assert_eq!(names, ["Rect", "Ellipse", "Open", "Hex", "Lighten", "Darken", "None"]);
let modes: Vec<_> = masks.iter().map(|m| m.mode).collect();
assert_eq!(modes, [AepMode::Add, AepMode::Subtract, AepMode::Intersect, AepMode::Difference, AepMode::Lighten, AepMode::Darken, AepMode::None].map(Some));
assert_eq!(masks.iter().map(|m| m.inverted).collect::<Vec<_>>(), [false, true, false, false, false, false, false].map(Some));
// The running counter of the layer: 1 to n.
assert_eq!(masks.iter().map(|m| m.counter).collect::<Vec<_>>(), (1..=7).map(Some).collect::<Vec<_>>());
// Feather, opacity, expansion: stored only when not at the default.
let e = &masks[1];
assert_eq!((e.feather.value, e.feather.source), ([20.0, 10.0], ValueSource::Stored));
assert_eq!((e.opacity_percent.value, e.opacity_percent.source), (50.0, ValueSource::Stored));
assert_eq!((e.expansion.value, e.expansion.source), (5.0, ValueSource::Stored));
assert_eq!(masks[3].expansion.value, -12.5);
for m in [&masks[0], &masks[2], &masks[4]] {
assert_eq!((m.feather.source, m.opacity_percent.source, m.expansion.source), (ValueSource::Default, ValueSource::Default, ValueSource::Default));
}
// Paths: vertices in layer pixels, open bit.
let px = view.mask_vertices_px(&layer, &masks[2]).expect("vertices");
let open = open_path();
assert!(masks[2].shapes[0].open && !masks[0].shapes[0].open);
for (v, (want, (ti, to))) in px[0].iter().zip(open.vertices.iter().zip(open.in_tangents.iter().zip(&open.out_tangents))) {
let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 0.01 && (a[1] - b[1]).abs() < 0.01;
assert!(near(v.position, *want) && near(v.in_tangent(), *ti) && near(v.out_tangent(), *to), "{v:?}");
}
// The point list header: count, vertex capacity and four times it (as 090 and 233).
let atoms = layer.mask_atoms();
let hex = &atoms[3].mask.shapes[0];
assert_eq!((hex.vertex_count(), hex.points.len()), (6, 18));
// The whole mask set imports back as it was exported.
same_masks(&masks_of(&p), &masks_of(&reimport(&res.bytes)));
}
#[test]
fn path_and_feather_keys_parse_back() {
let p = animated();
let res = export_all(&p);
assert!(res.report.is_lossless(), "{:?}", res.report.losses);
let file = parse(&res.bytes).expect("parse");
assert_eq!(write(&file).expect("write"), res.bytes);
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let layer = comp.layers().next().expect("layer");
let atoms = layer.mask_atoms();
let m = &atoms[0];
assert!(m.mask.path_animated);
assert_eq!(m.mask.path_key_seconds, [0.0, 1.0, 2.0]);
assert_eq!(m.path_shapes.len(), 3);
let path = m.path.expect("path property");
let keys: Vec<_> = path.keys().expect("keys").keyframes().collect();
assert!(keys.iter().all(|k| k.kind() == KeyframeKind::MaskPath));
assert_eq!((keys[1].interpolation_in(), keys[1].interpolation_out(), keys[1].label()), (Some(Interpolation::Linear), Some(Interpolation::Hold), Some(3)));
let Some(PropNode::Property(feather)) = m.atom.get("ADBE Mask Feather") else { panic!("feather") };
let fk: Vec<_> = feather.keys().expect("feather keys").keyframes().collect();
assert_eq!(fk.len(), 2);
assert_eq!(fk[1].value(), Some(vec![50.0, 30.0]));
let e = fk[0].ease_components().expect("ease");
assert_eq!((e[0].out_speed, e[0].out_influence, e[1].out_speed, e[1].out_influence), (15.0, 0.66, 5.0, 0.5));
same_masks(&masks_of(&p), &masks_of(&reimport(&res.bytes)));
}
#[test]
fn a_mask_on_a_small_solid_is_normalised_to_the_layer_size() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1280, 720, FrameRate::new(25, 1), 2.0, None);
let s = add_solid(&mut p, "L", 400, 300, [0.0, 1.0, 0.0], None);
add_layer(&mut p, c, "L", LayerSource::Solid { item: s }, (400, 300));
let mut next = p.next_id;
with_layer(&mut p, c, 0, |l| add_mask(l, &mut next, "Mask 1", ShapePath::rect([200.0, 150.0], 200.0, 100.0), MaskMode::Add, |_| {}));
p.next_id = next;
let res = export_all(&p);
let file = parse(&res.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let layer = comp.layers().next().expect("layer");
let m = &layer.masks()[0];
// The box is a fraction of the 400x300 solid: 100..300 / 400, 100..200 / 300.
let b = m.shapes[0].bbox.map(f64::from);
for (got, want) in b.iter().zip([0.25, 1.0 / 3.0, 0.75, 2.0 / 3.0]) {
assert!((got - want).abs() < 1e-6, "{b:?}");
}
same_masks(&masks_of(&p), &masks_of(&reimport(&res.bytes)));
}
#[test]
fn what_cannot_be_written_is_reported() {
let p = project(|l, n| {
add_mask(l, n, "Off", ShapePath::rect([960.0, 540.0], 100.0, 100.0), MaskMode::Add, |g| g.enabled = false);
add_mask(l, n, "Empty", ShapePath::default(), MaskMode::Add, |_| {});
add_mask(l, n, "Keyed opacity", ShapePath::rect([960.0, 540.0], 100.0, 100.0), MaskMode::Add, |g| {
g.get_mut("opacity").unwrap().keys = vec![key(0.0, Value::Scalar(10.0)), key(1.0, Value::Scalar(90.0))];
g.get_mut("expansion").unwrap().expr = Some(Expression { text: "time".into(), enabled: true });
if let GroupKind::Mask { locked, feather_falloff, roto_bezier, .. } = &mut g.kind {
*locked = true;
*feather_falloff = FeatherFalloff::Linear;
*roto_bezier = true;
}
});
add_mask(l, n, "Bezier path", ShapePath::rect([960.0, 540.0], 100.0, 100.0), MaskMode::Add, |g| {
let mut a = key(0.0, Value::Path(ShapePath::rect([960.0, 540.0], 100.0, 100.0)));
a.out_interp = Interp::Bezier;
g.get_mut("path").unwrap().keys = vec![a, key(1.0, Value::Path(ShapePath::rect([960.0, 540.0], 200.0, 100.0)))];
});
add_mask(l, n, "NaN", ShapePath::polygon(&[[f64::NAN, 0.0], [10.0, 10.0]], true), MaskMode::Add, |g| {
set(g, "feather", Value::Vec2([f64::INFINITY, -1.0]));
set(g, "opacity", Value::Scalar(400.0));
});
});
let err = export(&p, &ExportOptions { allow_losses: false }).unwrap_err();
assert!(err.to_string().contains("masks"), "{err}");
let res = export_all(&p);
let r = &res.report;
// Off, Empty and NaN are not written; Keyed opacity (5 losses: keys, expression, lock,
// falloff, RotoBezier) and Bezier path (its ease is written, 599 / 700) are.
assert_eq!(r.exported.masks, 2, "{:?}", r.losses);
assert_eq!(r.count(LossCategory::Masks), 3 + 5, "{:?}", r.losses);
assert_eq!(r.count(LossCategory::ApproximatedKeyframes), 0, "{:?}", r.losses);
let back = reimport(&res.bytes);
let m = masks_of(&back);
assert_eq!(m.len(), 2);
assert_eq!(m[1].get("path").unwrap().keys[0].out_interp, Interp::Bezier);
}
#[test]
fn hostile_masks_never_panic() {
let huge = ShapePath::polygon(&vec![[1.0, 2.0]; 70_000], true);
let line = ShapePath::polygon(&[[5.0, 5.0], [5.0, 900.0], [5.0, 30.0]], false);
let point = ShapePath::polygon(&[[5.0, 5.0]], true);
let lopsided = ShapePath { vertices: vec![[0.0, 0.0], [10.0, 0.0]], in_tangents: vec![], out_tangents: vec![[1.0, 1.0]], closed: true, feather: vec![] };
let p = project(|l, n| {
for (i, path) in [huge, line, point, lopsided, ShapePath::polygon(&[[1e300, 0.0], [0.0, 0.0]], true)].into_iter().enumerate() {
add_mask(l, n, &format!("M{i}"), path, MaskMode::Add, |_| {});
}
add_mask(l, n, &"x".repeat(1000), ShapePath::rect([1.0, 1.0], 1.0, 1.0), MaskMode::Add, |_| {});
});
let res = export_all(&p);
let file = parse(&res.bytes).expect("parse");
assert_eq!(write(&file).expect("write"), res.bytes);
// The line (zero width box), the point (zero box), the lopsided path and the long name are
// written; the huge and the out-of-range paths are not.
assert_eq!(res.report.exported.masks, 4, "{:?}", res.report.losses);
let back = masks_of(&reimport(&res.bytes));
assert_eq!(back.len(), 4);
let line = path_of(&back[0].get("path").unwrap().value);
assert!(line.vertices.iter().all(|v| (v[0] - 5.0).abs() < 1e-3));
assert!((line.vertices[1][1] - 900.0).abs() < 1e-2);
assert!(back[3].name.len() <= 255);
}
#[test]
fn mask_fixtures_round_trip() {
for name in [
"090-mask-rect.aep",
"091-mask-rect-props.aep",
"093-mask-path-2keys.aep",
"208-key-mask-feather-2key-linear.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",
"306-key-maskfeather-bezier-ease.aep",
"309-solid-100x100-mask-rect.aep",
"328-mask-two-ellipse-rect.aep",
"329-mask-ellipse-mode-none.aep",
] {
let a = reimport(&fixture!(name));
let res = export_all(&a);
assert_eq!(res.report.count(LossCategory::Masks), 0, "{name}: {:?}", res.report.losses);
let b = reimport(&res.bytes);
// 309 has its masked layer on a 100x100 solid in a second composition layer list; compare
// every layer with masks.
let all = |p: &Project| -> Vec<Vec<PropGroup>> {
let mut v: Vec<(String, Vec<PropGroup>)> = Vec::new();
for item in p.items.values() {
if let effectcraft_project::ItemKind::Comp(c) = &item.kind {
for l in &c.layers {
if let Some(m) = l.masks().filter(|m| !m.children.is_empty()) {
v.push((format!("{}/{}", item.name, l.name), m.groups().cloned().collect()));
}
}
}
}
v.sort_by(|x, y| x.0.cmp(&y.0));
v.into_iter().map(|(_, m)| m).collect()
};
let (ma, mb) = (all(&a), all(&b));
assert_eq!(ma.len(), mb.len(), "{name}");
assert!(!ma.is_empty(), "{name}");
for (x, y) in ma.iter().zip(&mb) {
same_masks(x, y);
}
}
}
+892
View File
@@ -0,0 +1,892 @@
//! Track mattes, markers, cameras, lights and shape layers: written from projects built in code
//! and read back with `effectcraft-aep`.
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::parse;
use effectcraft_project::{LayerSource, MatteKind, Project, TrackMatte};
use effectcraft_time::FrameRate;
/// `ldta` of every layer of the first composition, top first.
fn ldtas(bytes: &[u8]) -> Vec<Vec<u8>> {
let file = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
comp.layers().map(|l| l.chunk().child(b"ldta").and_then(|c| c.bytes()).expect("ldta").to_vec()).collect()
}
fn u32_at(b: &[u8], at: usize) -> u32 {
u32::from_be_bytes(b[at..at + 4].try_into().expect("4"))
}
fn two_solids() -> (Project, effectcraft_project::ItemId) {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 2.0, None);
let s = add_solid(&mut p, "S", 640, 360, [1.0, 0.0, 0.0], None);
add_layer(&mut p, c, "Target", LayerSource::Solid { item: s }, (640, 360));
add_layer(&mut p, c, "Matte", LayerSource::Solid { item: s }, (640, 360));
(p, c)
}
#[test]
fn track_mattes_are_written_with_mode_and_layer() {
// 403-406: the mode at ldta@107 (1 alpha, 2 alpha inverted, 3 luma, 4 luma inverted) and
// the matte layer's id at ldta@160, on the target layer.
for (kind, mode) in [(MatteKind::Alpha, 1u8), (MatteKind::AlphaInverted, 2), (MatteKind::Luma, 3), (MatteKind::LumaInverted, 4)] {
let (mut p, c) = two_solids();
let matte_id = p.comp(c).expect("c").layers[0].id;
with_layer(&mut p, c, 1, |l| l.track_matte = Some(TrackMatte { layer: matte_id, kind }));
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
let l = ldtas(&r.bytes);
// Top: Matte, then Target.
assert_eq!((l[0][107], u32_at(&l[0], 160)), (0, 0));
assert_eq!(l[1][107], mode);
assert_eq!(u32_at(&l[1], 160), u32_at(&l[0], 0), "the matte layer's id");
}
// A matte below the target (407) is written as well; one that is not exported is reported.
let (mut p, c) = two_solids();
let target = p.comp(c).expect("c").layers[1].id;
with_layer(&mut p, c, 0, |l| l.track_matte = Some(TrackMatte { layer: target, kind: MatteKind::Alpha }));
let l = ldtas(&export_all(&p).bytes);
assert_eq!((l[0][107], u32_at(&l[0], 160)), (1, u32_at(&l[1], 0)));
let (mut p, c) = two_solids();
with_layer(&mut p, c, 1, |l| l.track_matte = Some(TrackMatte { layer: effectcraft_project::LayerId(987_654), kind: MatteKind::Luma }));
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::TrackMattes), 1);
assert_eq!(ldtas(&r.bytes)[1][107], 0);
}
fn marker(t: f64, comment: &str) -> effectcraft_project::Marker {
effectcraft_project::Marker { time: secs(t), comment: comment.into(), ..Default::default() }
}
#[test]
fn markers_are_written_like_after_effects_stores_them() {
let (mut p, c) = two_solids();
with_comp(&mut p, c, |cc| {
cc.markers = vec![
effectcraft_project::Marker { label: effectcraft_color::Label::Yellow, ..marker(1.0, "M1") },
effectcraft_project::Marker { duration: secs(0.5), ..marker(2.5, "M2") },
];
});
with_layer(&mut p, c, 0, |l| {
l.markers = vec![
effectcraft_project::Marker {
duration: secs(1.0),
chapter: "Chap".into(),
url: "http://a.example/u".into(),
frame_target: "_blank".into(),
cue_point: Some(effectcraft_project::CuePoint {
name: "CueX".into(),
navigation: false,
params: vec![("speaker".into(), "A".into()), ("n".into(), "2".into())],
}),
..marker(1.0, "LM")
},
effectcraft_project::Marker {
cue_point: Some(effectcraft_project::CuePoint { name: "CueN".into(), navigation: true, params: Vec::new() }),
..marker(0.52, "Nav")
},
];
});
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
assert_eq!(r.report.exported.markers, 4);
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let cm = comp.markers();
assert_eq!(
cm.iter().map(|m| (m.time_units, m.comment.as_str(), m.duration_seconds, m.label)).collect::<Vec<_>>(),
vec![
(25_600, "M1", Some(0.0), Some(effectcraft_color::Label::ALL.iter().position(|l| *l == effectcraft_color::Label::Yellow).expect("label") as u8)),
// EffectCraft's default marker label is Red, index 1 (After Effects' own default is 0, None).
(64_000, "M2", Some(0.5), Some(1)),
]
);
let layer = comp.layers().next().expect("layer");
let lm = layer.markers();
assert_eq!(lm.len(), 2);
// In time order: Nav at 0.52 s (13 312 units, 510), LM at 1 s.
assert_eq!(
(lm[0].time_units, lm[0].comment.as_str(), lm[0].cue_type, lm[0].cue_point_name.as_str()),
(13_312, "Nav", Some(effectcraft_aep::CueType::Navigation), "CueN")
);
let m = &lm[1];
assert_eq!(
(m.time_units, m.comment.as_str(), m.chapter.as_str(), m.url.as_str(), m.frame_target.as_str(), m.cue_point_name.as_str()),
(25_600, "LM", "Chap", "http://a.example/u", "_blank", "CueX")
);
assert_eq!((m.duration_seconds, m.cue_type), (Some(1.0), Some(effectcraft_aep::CueType::Event)));
assert_eq!(m.cue_params, vec![("speaker".to_string(), "A".to_string()), ("n".to_string(), "2".to_string())]);
// A protected marker is reported (the switch is not decoded).
with_layer(&mut p, c, 1, |l| l.markers = vec![effectcraft_project::Marker { protected: true, ..marker(0.2, "P") }]);
assert_eq!(export_all(&p).report.count(LossCategory::Markers), 1);
}
#[test]
fn marker_fixtures_are_written_as_after_effects_wrote_them() {
// 122 (composition), 123, 249, 347-349 (layer): the reader sees the same markers after an
// import of the fixture, its markers put back from the reader's view (the importer does not
// read markers yet), and an export.
for name in [
"122-marker-comp-1s.aep",
"123-marker-layer-1s.aep",
"249-marker-layer-full.aep",
"347-marker-layer-label3.aep",
"348-marker-layer-navigation-cue.aep",
"349-marker-layer-event-cue-params.aep",
] {
let bytes = fixture!(name);
let file = parse(&bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let to_ec = |m: &effectcraft_aep::Marker| effectcraft_project::Marker {
time: secs(m.seconds.unwrap_or(0.0)),
duration: secs(m.duration_seconds.unwrap_or(0.0)),
comment: m.comment.clone(),
label: effectcraft_color::Label::ALL.get(usize::from(m.label.unwrap_or(0))).copied().unwrap_or_default(),
chapter: m.chapter.clone(),
url: m.url.clone(),
frame_target: m.frame_target.clone(),
cue_point: (!m.cue_point_name.is_empty() || m.cue_type == Some(effectcraft_aep::CueType::Navigation) || !m.cue_params.is_empty()).then(|| {
effectcraft_project::CuePoint {
name: m.cue_point_name.clone(),
navigation: m.cue_type == Some(effectcraft_aep::CueType::Navigation),
params: m.cue_params.clone(),
}
}),
protected: false,
};
let comp_markers: Vec<_> = comp.markers().iter().map(to_ec).collect();
let layer_markers: Vec<_> = comp.layers().next().map(|l| l.markers().iter().map(to_ec).collect()).unwrap_or_default();
let mut p = Project::default();
let none = |_: &str| false;
effectcraft_aep::import::import(
&mut p,
&bytes,
&effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) },
)
.expect(name);
let cid = p.comps().next().map(|(id, _)| *id).expect("comp");
with_comp(&mut p, cid, |c| c.markers = comp_markers);
with_layer(&mut p, cid, 0, |l| l.markers = layer_markers);
let r = export_all(&p);
let out = parse(&r.bytes).expect("parse");
let oview = effectcraft_aep::Project::new(&out).expect("project");
let ocomp = oview.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
assert_eq!(ocomp.markers(), comp.markers(), "{name}");
assert_eq!(ocomp.layers().next().map(|l| l.markers()), comp.layers().next().map(|l| l.markers()), "{name}");
}
}
fn with_props(p: &mut Project, c: effectcraft_project::ItemId, idx: usize, set: &[(&str, effectcraft_keyframe::Value)]) {
with_layer(p, c, idx, |l| {
for (path, v) in set {
l.props.prop_mut(path).unwrap_or_else(|| panic!("{path}")).value = v.clone();
}
});
}
fn first_comp_layers(bytes: &[u8], mut f: impl FnMut(&effectcraft_aep::Layer<'_, '_>)) {
let file = parse(bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), bytes);
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
for l in comp.layers() {
f(&l);
}
}
#[test]
fn cameras_are_written_with_position_point_of_interest_and_options() {
use effectcraft_keyframe::Value;
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "Cam", LayerSource::Camera, (1920, 1080));
with_props(
&mut p,
c,
0,
&[
("transform/position", Value::Vec3([100.0, 200.0, -1000.0])),
("transform/poi", Value::Vec3([960.0, 540.0, 0.0])),
("cameraOptions/dof", Value::Bool(true)),
("cameraOptions/focusDistance", Value::Scalar(800.0)),
("cameraOptions/aperture", Value::Scalar(30.0)),
("cameraOptions/zoom", Value::Scalar(1500.0)),
("cameraOptions/blurLevel", Value::Scalar(80.0)),
],
);
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
assert_eq!(r.report.exported.cameras, 1);
first_comp_layers(&r.bytes, |l| {
let h = l.header().expect("header");
assert_eq!(h.layer_type, effectcraft_aep::LayerType::Camera);
assert!(h.is_three_d() && h.is_auto_oriented(), "two-node camera");
let pos = l.camera_position().expect("position");
assert_eq!((pos.stored, pos.auto_state), ([100.0, 200.0, -1000.0], false));
assert_eq!(l.camera_point_of_interest(), Some([960.0, 540.0, 0.0]));
assert_eq!(l.camera_depth_of_field().map(|t| t.value), Some(true));
assert_eq!(l.camera_focus_distance().map(|t| t.value), Some(800.0));
assert_eq!(l.camera_aperture().map(|t| t.value), Some(30.0));
assert_eq!(l.camera_zoom().map(|t| t.value), Some(1500.0));
});
// One-node (auto-orient off): bit 0x40 clear (251).
with_layer(&mut p, c, 0, |l| l.auto_orient = effectcraft_project::AutoOrient::Off);
first_comp_layers(&export_all(&p).bytes, |l| assert!(!l.header().expect("h").is_auto_oriented()));
}
#[test]
fn spot_and_point_lights_are_written_with_their_options() {
use effectcraft_keyframe::Value;
use effectcraft_project::LightKind;
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "Spot", LayerSource::Light { kind: LightKind::Spot }, (1920, 1080));
add_layer(&mut p, c, "Point", LayerSource::Light { kind: LightKind::Point }, (1920, 1080));
// Layer 0 is the point light (added last, on top), 1 the spot.
with_props(
&mut p,
c,
1,
&[
("lightOptions/intensity", Value::Scalar(50.0)),
("lightOptions/color", Value::Color([1.0, 0.0, 0.0, 1.0])),
("lightOptions/coneAngle", Value::Scalar(60.0)),
("lightOptions/coneFeather", Value::Scalar(30.0)),
("transform/position", Value::Vec3([100.0, 50.0, -500.0])),
],
);
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
assert_eq!(r.report.exported.lights, 2);
let mut seen = Vec::new();
first_comp_layers(&r.bytes, |l| {
let h = l.header().expect("header");
assert_eq!(h.layer_type, effectcraft_aep::LayerType::Light);
seen.push(h.light_type());
match h.light_type() {
Some(effectcraft_aep::LightType::Spot) => {
assert_eq!(l.light_intensity().map(|t| t.value), Some(50.0));
assert_eq!(l.light_color().map(|t| t.value), Some([1.0, 1.0, 0.0, 0.0]));
assert_eq!(l.light_cone_angle().map(|t| t.value), Some(60.0));
assert_eq!(l.light_cone_feather().map(|t| t.value), Some(30.0));
assert_eq!(l.camera_position().map(|p| p.stored), Some([100.0, 50.0, -500.0]));
assert_eq!(l.camera_point_of_interest(), Some([960.0, 540.0, 0.0]));
}
Some(effectcraft_aep::LightType::Point) => {
assert_eq!(l.light_intensity().map(|t| t.value), Some(100.0));
}
other => panic!("{other:?}"),
}
});
assert_eq!(seen.len(), 2);
// Parallel and ambient lights, and unsampled options, are reported.
let mut q = Project::default();
let c = add_comp(&mut q, "C", 640, 360, FrameRate::new(25, 1), 1.0, None);
add_layer(&mut q, c, "Par", LayerSource::Light { kind: LightKind::Parallel }, (640, 360));
add_layer(&mut q, c, "Spot", LayerSource::Light { kind: LightKind::Spot }, (640, 360));
with_props(&mut q, c, 0, &[("lightOptions/castsShadows", Value::Bool(true))]);
assert_eq!(export_all(&q).report.count(LossCategory::Lights), 2);
}
#[test]
fn shape_layers_are_written_with_their_items() {
use effectcraft_keyframe::{ShapePath, Value};
use effectcraft_project::build;
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "S", LayerSource::Shape, (1920, 1080));
let mut next = p.next_id;
{
let mut ids = build::Ids(&mut next);
let mut rect = build::shape_rect(&mut ids, [400.0, 300.0], [10.0, -20.0], 15.0);
rect.name = "Rectangle Path 1".into();
let mut fill = build::shape_fill(&mut ids, [0.0, 1.0, 0.0, 1.0]);
if let Some(r) = fill.get_mut("rule") {
r.value = Value::Enum(1);
}
if let Some(o) = fill.get_mut("opacity") {
o.value = Value::Scalar(50.0);
}
let mut stroke = build::shape_stroke(&mut ids, [1.0, 0.0, 0.0, 1.0], 6.0);
if let Some(cap) = stroke.get_mut("cap") {
cap.value = Value::Enum(1);
}
let mut g1 = build::shape_group(&mut ids, "Group 1", vec![rect, stroke, fill]);
if let Some(t) = g1.sub_mut("transform") {
t.get_mut("position").expect("pos").value = Value::Vec2([50.0, 50.0]);
t.get_mut("scale").expect("scale").value = Value::Vec2([50.0, 80.0]);
t.get_mut("rotation").expect("rot").value = Value::Scalar(30.0);
}
let ellipse = build::shape_ellipse(&mut ids, [500.0, 200.0], [100.0, 50.0]);
let path = build::shape_path(
&mut ids,
ShapePath {
vertices: vec![[0.0, -100.0], [100.0, 100.0], [-100.0, 100.0]],
in_tangents: vec![[-10.0, -20.0], [30.0, 20.0], [-60.0, 10.0]],
out_tangents: vec![[40.0, 0.0], [-20.0, 30.0], [0.0, -50.0]],
closed: true,
feather: Vec::new(),
},
);
let fill2 = build::shape_fill(&mut ids, [0.0, 0.0, 1.0, 1.0]);
let inner = build::shape_group(&mut ids, "Inner", vec![ellipse]);
let g2 = build::shape_group(&mut ids, "Group 2", vec![inner, path, fill2]);
let star = build::shape_star(&mut ids, true, 5.0, [0.0, 0.0], 100.0, 50.0);
with_layer(&mut p, c, 0, |l| {
let contents = l.props.sub_mut("contents").expect("contents");
contents.children = vec![g1.into(), g2.into(), star.into()];
});
}
p.next_id = next;
let r = export_all(&p);
// Everything is written, the polystar too.
assert_eq!(r.report.count(LossCategory::ShapeLayers), 0, "{:?}", r.report.losses);
assert_eq!(r.report.exported.shape_layers, 1);
first_comp_layers(&r.bytes, |l| {
assert_eq!(l.header().expect("h").layer_type, effectcraft_aep::LayerType::Shape);
let groups = l.shape_groups();
assert_eq!(groups.len(), 2, "{groups:?}");
let names: Vec<_> = groups.iter().map(|g| g.name.clone()).collect();
assert_eq!(names, vec![Some("Group 1".to_string()), Some("Group 2".to_string())]);
let s = format!("{groups:?}");
// The path box equals the one After Effects stored for the same path (240).
for want in [
"400.0, 300.0",
"[10.0, -20.0]",
"50.0, 50.0",
"width: Some(Tracked { value: 6.0",
"cap: Tracked { value: Round",
"bbox: [-160.0, -120.0, 130.0, 130.0]",
] {
assert!(s.contains(want), "{want} in {s}");
}
});
}
#[test]
fn hostile_objects_never_panic() {
use effectcraft_keyframe::Value;
use effectcraft_project::{LightKind, build};
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "S", LayerSource::Shape, (640, 360));
let mut next = p.next_id;
{
let mut ids = build::Ids(&mut next);
// 200 nested groups, a NaN rectangle, an empty path.
let bad = build::shape_rect(&mut ids, [f64::NAN, 1e300], [0.0, 0.0], f64::INFINITY);
let mut inner = build::shape_group(&mut ids, "deep", vec![bad]);
for i in 0..200 {
inner = build::shape_group(&mut ids, &format!("g{i}"), vec![inner]);
}
let empty = build::shape_path(&mut ids, effectcraft_keyframe::ShapePath::default());
with_layer(&mut p, c, 0, |l| l.props.sub_mut("contents").expect("contents").children = vec![inner.into(), empty.into()]);
}
p.next_id = next;
add_layer(&mut p, c, "Cam", LayerSource::Camera, (640, 360));
with_props(&mut p, c, 0, &[("cameraOptions/zoom", Value::Scalar(f64::NAN)), ("transform/position", Value::Vec3([f64::INFINITY, 0.0, 0.0]))]);
add_layer(&mut p, c, "L", LayerSource::Light { kind: LightKind::Spot }, (640, 360));
with_props(&mut p, c, 0, &[("lightOptions/color", Value::Color([f64::NAN, 2.0, -1.0, 1.0])), ("lightOptions/intensity", Value::Scalar(-1e9))]);
with_layer(&mut p, c, 0, |l| {
l.markers = (0..500).map(|i| marker(f64::from(i) * 1e7, "x")).collect();
l.track_matte = Some(TrackMatte { layer: l.id, kind: MatteKind::Alpha });
});
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
assert!(r.report.count(LossCategory::ShapeLayers) >= 2, "{:?}", r.report.losses);
assert!(r.report.count(LossCategory::TrackMattes) == 1);
}
#[test]
fn camera_fixtures_come_back_without_a_loss() {
// The exporter writes every camera option, Blur Level 100 too; importing the export must not
// report it (it was reported as "not imported" before the importer and exporter lines met).
use effectcraft_aep::import::{ImportOptions, import};
let none = |_: &str| false;
for name in ["251-camera-one-node.aep", "256-camera-two-node-default.aep", "342-camera-dof-800-30.aep", "537-camera-default-on-3d-rotx.aep"] {
let bytes = fixture!(name);
let mut p = Project::default();
let r1 = import(&mut p, &bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("import");
assert!(r1.report.losses.is_empty(), "{name}: {:?}", r1.report.losses);
let out = export_all(&p);
assert!(out.report.is_lossless(), "{name}: {:?}", out.report.losses);
let mut p2 = Project::default();
let r2 = import(&mut p2, &out.bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("reimport");
assert!(r2.report.losses.is_empty(), "{name}: {:?}", r2.report.losses);
assert_eq!(r2.report.imported.cameras, 1, "{name}");
}
}
/// The static value records below the shape contents of every layer, by (layer index, path of
/// item match names, record match name).
fn shape_records(bytes: &[u8]) -> std::collections::BTreeMap<(usize, String), effectcraft_aep::Chunk<'static>> {
fn walk(
cs: &[effectcraft_aep::Chunk<'_>],
path: &str,
li: usize,
inside: bool,
out: &mut std::collections::BTreeMap<(usize, String), effectcraft_aep::Chunk<'static>>,
) {
let mut seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
for (i, c) in cs.iter().enumerate() {
let name = if c.is(b"tdmn") { c.bytes().map(|b| String::from_utf8_lossy(b.split(|x| *x == 0).next().unwrap_or(b"")).to_string()) } else { None };
let Some(name) = name else { continue };
let Some(node) = cs.get(i + 1) else { continue };
let n = seen.entry(name.clone()).or_insert(0);
let key = format!("{path}/{name}#{n}");
*n += 1;
let here = inside || name == "ADBE Root Vectors Group";
if here && node.is_list(b"tdbs") && node.child(b"cdat").is_some() {
let has_expression = node.child(b"Utf8").is_some();
let mut node = node.clone().into_owned();
// Header bytes 76 and 77 next to an expression vary between saves (see
// `keyed_shape_records`).
if has_expression
&& let effectcraft_aep::Body::List { children, .. } = &mut node.body
&& let Some(effectcraft_aep::Body::Data(d)) = children.iter_mut().find(|x| x.is(b"tdb4")).map(|x| &mut x.body)
&& let Some(b) = d.to_mut().get_mut(76..78)
{
b.fill(0);
}
out.insert((li, key.clone()), node);
}
if node.is_list(b"tdgp") {
walk(node.children(), &key, li, here, out);
}
}
}
let f = parse(bytes).expect("parse");
let mut out = std::collections::BTreeMap::new();
let view = effectcraft_aep::Project::new(&f).expect("project");
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
for (li, layer) in comp.layers().enumerate() {
if let Some(g) = layer.chunk().child_list(b"tdgp") {
walk(g.children(), "", li, false, &mut out);
}
}
}
out
}
#[test]
fn every_shape_value_record_is_written_as_after_effects_wrote_it() {
// Every static record of a shape fixture comes back with After Effects' bytes, built from the
// record of its property's type (R46).
let mut names: Vec<String> = fixture_names!("aep").into_iter().filter(|n| n.ends_with(".aep") && n.contains("shape")).collect();
names.sort();
let mut compared = 0;
for name in &names {
let bytes = fixture!(name);
let mut p = Project::default();
let none = |_: &str| false;
let imported = effectcraft_aep::import::import(
&mut p,
&bytes,
&effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) },
)
.expect("import");
if imported.report.count(effectcraft_aep::import::LossCategory::ShapeLayers) > 0 {
continue;
}
let r = export_all(&p);
let (a, b) = (shape_records(&bytes), shape_records(&r.bytes));
for (k, rec) in &a {
// A record After Effects keeps for a value set to its default (239: Miter Limit 4)
// is not needed: absent = default.
let first = rec.child(b"cdat").and_then(|c| c.bytes()).and_then(|d| d.get(..8)).and_then(|b| b.try_into().ok()).map(f64::from_be_bytes);
let explicit_default =
[("ADBE Vector Stroke Miter Limit#0", 4.0), ("ADBE Vector Grad HiLite Angle#0", 0.0), ("ADBE Vector Grad HiLite Length#0", 0.0)]
.iter()
.any(|(n, v)| k.1.ends_with(n) && first == Some(*v));
// A polygon has no inner radius or roundness in EffectCraft (After Effects keeps their
// records, 331; a polygon ignores them).
let polygon_inner = name.contains("polygon") && k.1.contains("ADBE Vector Star Inner");
let Some(got) = b.get(k) else {
assert!(explicit_default || polygon_inner, "{name}: {k:?} not written");
continue;
};
assert_eq!(crate::export::helpers::decoded(got), crate::export::helpers::decoded(rec), "{name}: {k:?}");
compared += 1;
}
for k in b.keys() {
assert!(a.contains_key(k), "{name}: {k:?} written but After Effects has none");
}
}
assert!(compared >= 40, "{compared}");
}
/// The keyed (or expression) records below the shape contents of the first layer: `(path,
/// tdb4, lhd3, ldat with spatial arc lengths zeroed, expression)`.
fn keyed_shape_records(bytes: &[u8]) -> Vec<(String, Vec<u8>, Vec<u8>, Vec<u8>, Option<Vec<u8>>)> {
fn walk(cs: &[effectcraft_aep::Chunk<'_>], path: &str, inside: bool, out: &mut Vec<(String, Vec<u8>, Vec<u8>, Vec<u8>, Option<Vec<u8>>)>) {
for (i, c) in cs.iter().enumerate() {
let Some(name) = c.bytes().filter(|_| c.is(b"tdmn")).map(|b| String::from_utf8_lossy(b.split(|x| *x == 0).next().unwrap_or(b"")).to_string())
else {
continue;
};
let Some(node) = cs.get(i + 1) else { continue };
let key = format!("{path}/{name}");
let here = inside || name == "ADBE Root Vectors Group";
if here && node.is_list(b"tdbs") {
let list = node.child_list(b"list");
let expr = node.child(b"Utf8").and_then(|u| u.bytes()).map(<[u8]>::to_vec);
if list.is_some() || expr.is_some() {
// The header bytes the exporter writes (the others are zero: `decoded`).
let mut tdb4 =
crate::export::helpers::decoded(&node.clone().into_owned()).child(b"tdb4").and_then(|c| c.bytes()).unwrap_or_default().to_vec();
// Header bytes 76 and 77 of a property with an expression: After Effects
// wrote 1 in one save and 0 in another (060 and 856 of the combined files);
// byte 120 marks the expression.
if expr.is_some()
&& let Some(b) = tdb4.get_mut(76..78)
{
b.fill(0);
}
let lhd3 = list.and_then(|l| l.child(b"lhd3")).and_then(|c| c.bytes()).unwrap_or_default().to_vec();
let mut ldat = list.and_then(|l| l.child(b"ldat")).and_then(|c| c.bytes()).unwrap_or_default().to_vec();
let size = lhd3.get(16..20).map_or(0, |b| u32::from_be_bytes(b.try_into().unwrap()) as usize);
if size == 104 {
for r in ldat.chunks_mut(104) {
r[16..24].fill(0);
// Automatic spatial tangents: After Effects keeps 0 for two keys
// made by script (853), the exporter writes the tangents it computes
// (collinear: the same straight path, R14).
if r[8..12] == [0, 0, 0, 1] {
r[72..104].fill(0);
}
}
}
// The colour distance to the next key (f64 at 16) of a colour key: After
// Effects wrote 0 for 854's linear keys in one save and 255 sqrt(2) in
// another (the combined file); the exporter writes 0.
if size == 152 {
for r in ldat.chunks_mut(152) {
r[16..24].fill(0);
}
}
// The ease before the first key and after the last one is never used (the
// importer keeps none, the exporter writes 1/3 influence there).
if size == 48 && ldat.len() >= 96 {
ldat[16..32].fill(0);
let n = ldat.len();
ldat[n - 16..n].fill(0);
}
out.push((key.clone(), tdb4, lhd3, ldat, expr));
}
}
if node.is_list(b"tdgp") {
walk(node.children(), &key, here, out);
}
}
}
let f = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&f).expect("project");
let mut out = Vec::new();
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
for layer in comp.layers() {
if let Some(g) = layer.chunk().child_list(b"tdgp") {
walk(g.children(), "", false, &mut out);
}
}
}
out
}
#[test]
fn keyed_shape_properties_are_written_as_after_effects_wrote_them() {
// 851-857: Trim End linear and bezier keys, group Position (spatial), Fill Color, Trim
// Offset with a hold key, an expression on Trim End, group Scale (two components).
for name in [
"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",
] {
let bytes = fixture!(name);
let mut p = Project::default();
let none = |_: &str| false;
effectcraft_aep::import::import(
&mut p,
&bytes,
&effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) },
)
.expect("import");
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::ShapeLayers), 0, "{name}: {:?}", r.report.losses);
let (a, b) = (keyed_shape_records(&bytes), keyed_shape_records(&r.bytes));
assert_eq!(a.len(), 1, "{name}");
assert_eq!(a, b, "{name}");
}
}
#[test]
fn shape_operators_and_keys_built_in_code_come_back() {
// Polystar, gradient fill / stroke, trim paths with keys, round corners, merge / offset paths
// and a repeater with a transform: exported, imported again, the same values and keys.
use effectcraft_keyframe::{Gradient, Keyframe, Value};
use effectcraft_project::build;
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "S", LayerSource::Shape, (1920, 1080));
let mut next = p.next_id;
{
let mut ids = build::Ids(&mut next);
let rect = build::shape_rect(&mut ids, [400.0, 300.0], [0.0, 0.0], 0.0);
let mut star = build::shape_star(&mut ids, true, 7.0, [10.0, 20.0], 120.0, 40.0);
star.get_mut("rotation").unwrap().value = Value::Scalar(15.0);
let mut gfill = build::shape_gradient_fill(&mut ids, true, [-50.0, 0.0], [60.0, 10.0], Gradient::default());
gfill.get_mut("opacity").unwrap().value = Value::Scalar(70.0);
let gstroke = build::shape_gradient_stroke(&mut ids, false, [0.0, 0.0], [100.0, 50.0], Gradient::default(), 5.0);
let mut trim = build::shape_trim(&mut ids, 10.0, 90.0, 30.0);
trim.get_mut("end").unwrap().keys = vec![
key(0.0, Value::Scalar(0.0)),
Keyframe { out_interp: effectcraft_keyframe::Interp::Hold, ..key(1.0, Value::Scalar(60.0)) },
key(1.5, Value::Scalar(100.0)),
];
let mut round = build::shape_simple_op(&mut ids, "round").unwrap();
round.get_mut("radius").unwrap().value = Value::Scalar(25.0);
let mut merge = build::shape_simple_op(&mut ids, "merge").unwrap();
merge.get_mut("mode").unwrap().value = Value::Enum(2);
let mut offset = build::shape_simple_op(&mut ids, "offset").unwrap();
offset.get_mut("amount").unwrap().value = Value::Scalar(-5.0);
offset.get_mut("join").unwrap().value = Value::Enum(1);
let mut rep = build::shape_repeater(&mut ids, 4.0, [80.0, 0.0]);
if let Some(t) = rep.sub_mut("transform") {
t.get_mut("rotation").unwrap().value = Value::Scalar(12.0);
t.get_mut("endOpacity").unwrap().value = Value::Scalar(30.0);
t.get_mut("position").unwrap().keys = vec![key(0.0, Value::Vec2([0.0, 0.0])), key(1.0, Value::Vec2([80.0, 40.0]))];
}
let mut fill = build::shape_fill(&mut ids, [0.0, 1.0, 0.0, 1.0]);
fill.get_mut("color").unwrap().keys = vec![key(0.0, Value::Color([1.0, 0.0, 0.0, 1.0])), key(1.0, Value::Color([0.0, 0.0, 1.0, 1.0]))];
let g = build::shape_group(&mut ids, "Group 1", vec![rect, star, gfill, gstroke, trim, round, merge, offset, rep, fill]);
with_layer(&mut p, c, 0, |l| l.props.sub_mut("contents").expect("contents").children = vec![g.into()]);
}
p.next_id = next;
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::ShapeLayers), 0, "{:?}", r.report.losses);
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
let mut q = Project::default();
let none = |_: &str| false;
let back = effectcraft_aep::import::import(
&mut q,
&r.bytes,
&effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) },
)
.expect("import");
assert!(back.report.losses.is_empty(), "{:?}", back.report.losses);
// Every property of the contents: value and key count (ids differ).
let flat = |p: &Project| -> Vec<(String, String, usize)> {
let mut out = Vec::new();
for item in p.items.values() {
let effectcraft_project::ItemKind::Comp(c) = &item.kind else { continue };
for l in &c.layers {
let Some(contents) = l.props.sub("contents") else { continue };
let mut stack = vec![(contents, String::new())];
while let Some((g, pre)) = stack.pop() {
for n in &g.children {
match n {
effectcraft_project::Node::Group(s) => stack.push((s, format!("{pre}{}/", s.match_id))),
// A keyed property's static value is its first key's in the file.
effectcraft_project::Node::Prop(pr) => out.push((
format!("{pre}{}", pr.match_id),
if pr.keys.is_empty() {
format!("{:?}", pr.value)
} else {
format!("{:?}", pr.keys.iter().map(|k| (k.time, k.value.clone(), k.out_interp)).collect::<Vec<_>>())
},
pr.keys.len(),
)),
}
}
}
}
}
out.sort();
out
};
assert_eq!(flat(&p), flat(&q));
}
#[test]
fn hostile_shape_keys_never_panic() {
use effectcraft_keyframe::Value;
use effectcraft_project::build;
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "S", LayerSource::Shape, (640, 360));
let mut next = p.next_id;
{
let mut ids = build::Ids(&mut next);
let mut trim = build::shape_trim(&mut ids, 0.0, 100.0, 0.0);
trim.get_mut("end").unwrap().keys = (0..20_000).map(|i| key(f64::from(i) * 0.0001, Value::Scalar(f64::from(i)))).collect();
trim.get_mut("start").unwrap().keys = vec![key(0.0, Value::Scalar(f64::NAN)), key(-5.0, Value::Bool(true)), key(1e12, Value::Scalar(1.0))];
trim.get_mut("mode").unwrap().keys = vec![key(0.0, Value::Enum(1)), key(1.0, Value::Enum(900))];
let mut fill = build::shape_fill(&mut ids, [0.0, 1.0, 0.0, 1.0]);
fill.get_mut("color").unwrap().keys = vec![key(0.0, Value::Color([f64::INFINITY, 0.0, 0.0, 1.0])), key(0.0, Value::Scalar(3.0))];
let g = build::shape_group(&mut ids, "G", vec![trim, fill]);
with_layer(&mut p, c, 0, |l| l.props.sub_mut("contents").expect("contents").children = vec![g.into()]);
}
p.next_id = next;
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
assert!(r.report.count(LossCategory::InvalidValues) >= 1, "{:?}", r.report.losses);
}
/// A shape colour channel outside 0 to 1 (an over-bright or negative value) is written as the
/// nearest limit and reported, as for lights; it was written unclamped (review finding). A colour
/// inside the range stays lossless.
#[test]
fn a_shape_colour_outside_the_range_is_clamped_and_reported() {
use effectcraft_keyframe::Value;
use effectcraft_project::build;
let shape = |fill_color: [f64; 4], key_color: Option<[f64; 4]>| {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "S", LayerSource::Shape, (640, 360));
let mut next = p.next_id;
{
let mut ids = build::Ids(&mut next);
let rect = build::shape_rect(&mut ids, [100.0, 50.0], [0.0, 0.0], 0.0);
let mut fill = build::shape_fill(&mut ids, fill_color);
if let Some(k) = key_color {
fill.get_mut("color").unwrap().keys = vec![key(0.0, Value::Color([0.0, 0.0, 1.0, 1.0])), key(1.0, Value::Color(k))];
}
let g = build::shape_group(&mut ids, "G", vec![rect, fill]);
with_layer(&mut p, c, 0, |l| l.props.sub_mut("contents").expect("contents").children = vec![g.into()]);
}
p.next_id = next;
p
};
let strict = |p: &Project| effectcraft_aep::export::export(p, &effectcraft_aep::export::ExportOptions { allow_losses: false }).is_ok();
let inside = shape([0.25, 0.5, 1.0, 1.0], None);
assert_eq!(export_all(&inside).report.count(LossCategory::ShapeLayers), 0);
assert!(strict(&inside));
// Keyed in range: the static value (here over-bright) is not written, so nothing is lost.
let keyed = shape([2.0, 0.0, 0.0, 1.0], Some([0.5, 0.5, 0.5, 1.0]));
assert_eq!(export_all(&keyed).report.count(LossCategory::ShapeLayers), 0, "{:?}", export_all(&keyed).report.losses);
assert!(strict(&keyed));
for p in [shape([2.0, 0.5, -0.5, 1.0], None), shape([0.0, 1.0, 0.0, 1.0], Some([1.5, 0.0, 0.0, 1.0]))] {
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::ShapeLayers), 1, "{:?}", r.report.losses);
assert!(!strict(&p));
// Every stored colour channel is within 0 to 255.
let mut q = Project::default();
let none = |_: &str| false;
let opts = effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) };
effectcraft_aep::import::import(&mut q, &r.bytes, &opts).expect("import");
let mut colours = Vec::new();
for item in q.items.values() {
let effectcraft_project::ItemKind::Comp(c) = &item.kind else { continue };
for l in &c.layers {
let mut stack: Vec<&effectcraft_project::PropGroup> = l.props.sub("contents").into_iter().collect();
while let Some(g) = stack.pop() {
for n in &g.children {
match n {
effectcraft_project::Node::Group(s) => stack.push(s),
effectcraft_project::Node::Prop(pr) => {
for v in std::iter::once(&pr.value).chain(pr.keys.iter().map(|k| &k.value)) {
if let Value::Color(c) = v {
colours.push(*c);
}
}
}
}
}
}
}
}
assert!(!colours.is_empty());
assert!(colours.iter().all(|c| c.iter().take(3).all(|x| (0.0..=1.0).contains(x))), "{colours:?}");
}
}
/// The Transform group of a camera ends with its Group End: the camera's `ADBE Position_2` record
/// sorts before it (review finding: an unlisted record used to sort after the end marker).
#[test]
fn a_camera_transform_group_ends_with_its_group_end() {
use effectcraft_keyframe::Value;
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "Cam", LayerSource::Camera, (1920, 1080));
with_props(&mut p, c, 0, &[("transform/position", Value::Vec3([100.0, 200.0, -1000.0]))]);
let bytes = export_all(&p).bytes;
let file = parse(&bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let layer = comp.layers().next().expect("camera");
let root = layer.chunk().child_list(b"tdgp").expect("tree").children();
let name =
|c: &effectcraft_aep::Chunk<'_>| String::from_utf8_lossy(c.bytes().unwrap_or_default().split(|b| *b == 0).next().unwrap_or_default()).into_owned();
let at = root.iter().position(|c| c.is(b"tdmn") && name(c) == "ADBE Transform Group").expect("transform");
let names: Vec<String> = root[at + 1].children().iter().filter(|c| c.is(b"tdmn")).map(name).collect();
assert_eq!(names.last().map(String::as_str), Some("ADBE Group End"), "{names:?}");
assert!(names.iter().any(|n| n == "ADBE Position_2"));
}
/// Camera and light options that are not written (the iris, the highlight, the light's radius,
/// falloff and shadow settings) are reported when they are animated, also while their static value
/// is the default: keys and expressions change the render, and the export was identical to the
/// unanimated layer with no loss (review finding). The default layer stays lossless.
#[test]
fn animated_camera_and_light_options_that_are_not_written_are_reported() {
use effectcraft_project::{Expression, LightKind};
let camera_ids = [
"irisShape",
"irisRotation",
"irisRoundness",
"irisAspectRatio",
"irisDiffractionFringe",
"highlightGain",
"highlightThreshold",
"highlightSaturation",
];
let light_ids = ["radius", "falloffDistance", "shadowDarkness", "shadowDiffusion", "falloff", "castsShadows"];
let make = |source: LayerSource, path: Option<String>, keyed: bool| {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "L", source, (640, 360));
if let Some(path) = path {
with_layer(&mut p, c, 0, |l| {
let prop = l.props.prop_mut(&path).unwrap_or_else(|| panic!("no {path}"));
if keyed {
let v = prop.value.clone();
prop.keys = vec![key(0.0, v.clone()), key(1.0, v)];
} else {
prop.expr = Some(Expression { text: "value".into(), enabled: true });
}
});
}
p
};
let strict = |p: &Project| effectcraft_aep::export::export(p, &effectcraft_aep::export::ExportOptions { allow_losses: false }).is_ok();
let cam = make(LayerSource::Camera, None, true);
assert!(export_all(&cam).report.is_lossless() && strict(&cam));
let light = make(LayerSource::Light { kind: LightKind::Spot }, None, true);
assert!(export_all(&light).report.is_lossless() && strict(&light));
for keyed in [true, false] {
for id in camera_ids {
let p = make(LayerSource::Camera, Some(format!("cameraOptions/{id}")), keyed);
assert_eq!(export_all(&p).report.count(LossCategory::Cameras), 1, "camera {id} keyed {keyed}");
assert!(!strict(&p), "camera {id} keyed {keyed}");
}
for id in light_ids {
let p = make(LayerSource::Light { kind: LightKind::Spot }, Some(format!("lightOptions/{id}")), keyed);
assert_eq!(export_all(&p).report.count(LossCategory::Lights), 1, "light {id} keyed {keyed}");
assert!(!strict(&p), "light {id} keyed {keyed}");
}
}
}
+146
View File
@@ -0,0 +1,146 @@
//! Precomposition layers: a composition shown as a layer of another composition. The exported
//! bytes are parsed back with `effectcraft-aep` (source id, `idpc` / `idpi`, the Time Remapping
//! maximum, the anchor unit) and imported again.
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{PropNode, parse};
use effectcraft_keyframe::Value;
use effectcraft_project::{ItemId, ItemKind, LayerSource, Project};
use effectcraft_time::FrameRate;
fn reimport(bytes: &[u8]) -> Project {
let mut p = Project::default();
let none = |_: &str| false;
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&none) };
import(&mut p, bytes, &opts).expect("import");
p
}
/// `Pre` (640 x 360, 30 fps, 3 s, one solid) shown in `C` with an anchor and a position.
fn nested() -> (Project, ItemId, ItemId) {
let mut p = Project::default();
let pre = add_comp(&mut p, "Pre", 640, 360, FrameRate::new(30, 1), 3.0, None);
let s = add_solid(&mut p, "S", 640, 360, [0.0, 1.0, 0.0], None);
add_layer(&mut p, pre, "S", LayerSource::Solid { item: s }, (640, 360));
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
add_layer(&mut p, c, "Pre", LayerSource::Comp { item: pre }, (640, 360));
with_layer(&mut p, c, 0, |l| {
let tr = l.props.sub_mut("transform").expect("transform");
tr.get_mut("anchor").expect("anchor").value = Value::Vec3([160.0, 90.0, 0.0]);
tr.get_mut("position").expect("position").value = Value::Vec3([300.0, 200.0, 0.0]);
});
(p, c, pre)
}
#[test]
fn a_precomposition_layer_points_at_its_composition() {
let (p, _, _) = nested();
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
assert_eq!(r.report.exported.precomp_layers, 1);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let items = view.all_items();
let by_name = |n: &str| items.iter().find(|i| i.display_name().as_deref() == Some(n)).copied().expect(n);
let (c, pre) = (by_name("C"), by_name("Pre"));
let pre_id = pre.id().expect("id");
// C records the composition it uses (idpi, little-endian), idpc byte 0 is 1.
assert_eq!(c.used_item_ids(), vec![pre_id]);
let idpc = c.chunk().child(b"idpc").and_then(|x| x.bytes()).expect("idpc");
assert_eq!(idpc.first(), Some(&1));
assert_eq!(pre.used_item_ids(), Vec::<u32>::new());
assert_eq!(pre.chunk().child(b"idpc").and_then(|x| x.bytes()).and_then(|b| b.first().copied()), Some(0));
let layer = c.comp().expect("comp").layers().next().expect("layer");
let h = layer.header().expect("header");
assert_eq!(h.source_id, Some(pre_id));
assert_eq!(view.layer_source_size(&layer), Some((640, 360)));
assert_eq!(layer.name().as_deref(), Some("Pre"));
// The anchor is a fraction of the precomposition's size.
let tr = layer.properties().and_then(|g| g.get("ADBE Transform Group"));
let Some(PropNode::Group(tr)) = tr else { panic!("transform") };
let Some(PropNode::Property(a)) = tr.get("ADBE Anchor Point") else { panic!("anchor") };
let v = a.static_value().expect("value");
assert!((v[0] - 0.25).abs() < 1e-12 && (v[1] - 0.25).abs() < 1e-12, "{v:?}");
// The Time Remapping maximum is the precomposition's duration (3 s; 0 on a solid).
let tdum_max = |l: &effectcraft_aep::Layer<'_, '_>| -> f64 {
let Some(PropNode::Property(tr)) = l.properties().and_then(|g| g.get("ADBE Time Remapping")) else { panic!("time remap") };
let b = tr.chunk().child(b"tduM").and_then(|x| x.bytes()).expect("tduM");
f64::from_be_bytes(b.get(..8).and_then(|s| s.try_into().ok()).expect("8 bytes"))
};
assert_eq!(tdum_max(&layer), 3.0);
let inner = pre.comp().expect("comp").layers().next().expect("layer");
assert_eq!(tdum_max(&inner), 0.0);
}
#[test]
fn a_precomposition_survives_import() {
let (p, _, _) = nested();
let q = reimport(&export_all(&p).bytes);
let comp_named = |n: &str| q.items.values().find(|i| i.name == n && matches!(i.kind, ItemKind::Comp(_))).expect(n);
let (c, pre) = (comp_named("C"), comp_named("Pre"));
let ItemKind::Comp(cc) = &c.kind else { unreachable!() };
let ItemKind::Comp(pc) = &pre.kind else { unreachable!() };
assert_eq!((pc.width, pc.height, pc.frame_rate), (640, 360, FrameRate::new(30, 1)));
let l = cc.layers.first().expect("layer");
assert_eq!(l.source, LayerSource::Comp { item: pre.id });
let tr = l.transform().expect("transform");
assert_eq!(tr.get("anchor").expect("anchor").value.components()[..2], [160.0, 90.0]);
assert_eq!(tr.get("position").expect("position").value.components()[..2], [300.0, 200.0]);
}
#[test]
fn one_composition_used_twice_is_recorded_once_and_chains_nest() {
let mut p = Project::default();
let a = add_comp(&mut p, "A", 100, 100, FrameRate::new(25, 1), 1.0, None);
let b = add_comp(&mut p, "B", 200, 100, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, b, "A1", LayerSource::Comp { item: a }, (100, 100));
add_layer(&mut p, b, "A2", LayerSource::Comp { item: a }, (100, 100));
let c = add_comp(&mut p, "C", 400, 300, FrameRate::new(25, 1), 3.0, None);
add_layer(&mut p, c, "B", LayerSource::Comp { item: b }, (200, 100));
add_layer(&mut p, c, "A", LayerSource::Comp { item: a }, (100, 100));
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
assert_eq!(r.report.exported.precomp_layers, 4);
let file = parse(&r.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let items = view.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 used = |n: &str| items.iter().find(|i| i.display_name().as_deref() == Some(n)).expect(n).used_item_ids();
assert_eq!(used("B"), vec![id("A")]);
// Ascending ids (601; the order carries no meaning), and idpc counts them.
let mut ab = vec![id("A"), id("B")];
ab.sort_unstable();
assert_eq!(used("C"), ab);
let idpc = |n: &str| {
items.iter().find(|i| i.display_name().as_deref() == Some(n)).and_then(|i| i.chunk().child(b"idpc")).and_then(|c| c.bytes()).map(|b| b[..4].to_vec())
};
assert_eq!(idpc("C"), Some(vec![2, 0, 0, 0]));
assert_eq!(idpc("B"), Some(vec![1, 0, 0, 0]));
assert!(used("A").is_empty());
let q = reimport(&r.bytes);
let n = q.items.values().filter_map(|i| if let ItemKind::Comp(c) = &i.kind { Some(c.layers.len()) } else { None }).sum::<usize>();
assert_eq!(n, 4);
}
#[test]
fn a_loop_of_precompositions_is_reported_not_written() {
let mut p = Project::default();
let a = add_comp(&mut p, "A", 100, 100, FrameRate::new(25, 1), 1.0, None);
let b = add_comp(&mut p, "B", 100, 100, FrameRate::new(25, 1), 1.0, None);
add_layer(&mut p, a, "self", LayerSource::Comp { item: a }, (100, 100));
add_layer(&mut p, a, "B", LayerSource::Comp { item: b }, (100, 100));
add_layer(&mut p, b, "A", LayerSource::Comp { item: a }, (100, 100));
// A missing composition.
add_layer(&mut p, b, "gone", LayerSource::Comp { item: ItemId(999_999) }, (100, 100));
// C uses A without a loop through C.
let c = add_comp(&mut p, "C", 100, 100, FrameRate::new(25, 1), 1.0, None);
add_layer(&mut p, c, "A", LayerSource::Comp { item: a }, (100, 100));
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::UnsupportedLayers), 4, "{:?}", r.report.losses);
assert_eq!(r.report.exported.precomp_layers, 1);
// What was written still parses and imports.
let q = reimport(&r.bytes);
assert!(q.items.values().any(|i| i.name == "A"));
}
+186
View File
@@ -0,0 +1,186 @@
//! Time Remapping: the fixtures with an enabled remap (319 on a precomposition layer, 354 on an
//! image-sequence layer) go through import, export and parse, and the remap record equals the one
//! After Effects wrote; remaps built in code (hold, reverse, bezier, an expression, no keys) are
//! written and imported back; what cannot be remapped is reported; hostile remaps never panic.
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{Body, Chunk, parse};
use effectcraft_keyframe::{Ease, Interp, Keyframe, Value};
use effectcraft_project::{Expression, ItemKind, LayerSource, Project, Property};
use effectcraft_time::FrameRate;
fn reimport(bytes: &[u8]) -> Project {
let mut p = Project::default();
let none = |_: &str| false;
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&none) };
import(&mut p, bytes, &opts).expect("import");
p
}
/// The enabled (`tdsb` 1) `ADBE Time Remapping` records of a file.
fn enabled_remaps(bytes: &[u8]) -> Vec<Chunk<'static>> {
fn walk(cs: &[Chunk<'_>], out: &mut Vec<Chunk<'static>>) {
for (i, c) in cs.iter().enumerate() {
if c.is(b"tdmn")
&& matches!(&c.body, Body::Data(d) if d.starts_with(b"ADBE Time Remapping\0"))
&& let Some(rec) = cs.get(i + 1)
&& rec.children().iter().any(|k| k.is(b"tdsb") && matches!(&k.body, Body::Data(d) if d.as_ref() == [0, 0, 0, 1]))
{
out.push(rec.clone().into_owned());
}
walk(c.children(), out);
}
}
let f = parse(bytes).expect("parse");
let mut out = Vec::new();
walk(&f.chunks, &mut out);
out
}
fn remap_of(p: &Project) -> Vec<Property> {
let mut v = Vec::new();
for item in p.items.values() {
let ItemKind::Comp(c) = &item.kind else { continue };
for l in &c.layers {
if let Some(r) = l.props.prop("timeRemap") {
v.push(Property { uid: 0, ..r.clone() });
}
}
}
v
}
#[test]
fn the_remap_fixtures_are_written_as_after_effects_wrote_them() {
for name in ["319-precomp-timeremap.aep", "354-footage-pngseq-timeremap.aep"] {
let bytes = fixture!(name);
let p1 = reimport(&bytes);
assert_eq!(remap_of(&p1).len(), 1, "{name}");
let r = export_all(&p1);
assert_eq!(r.report.count(LossCategory::TimeRemapping), 0, "{name}: {:?}", r.report.losses);
assert_eq!(r.report.exported.time_remaps, 1, "{name}");
let (a, b) = (enabled_remaps(&bytes), enabled_remaps(&r.bytes));
assert_eq!(a.len(), 1, "{name}");
// In the bytes the exporter writes (`decoded`).
let d = |v: &[effectcraft_aep::Chunk<'static>]| v.iter().map(crate::export::helpers::decoded).collect::<Vec<_>>();
assert_eq!(d(&a), d(&b), "{name}: the remap record differs from After Effects'");
let p2 = reimport(&r.bytes);
assert_eq!(remap_of(&p1), remap_of(&p2), "{name}");
}
}
/// A 25 fps comp `C` showing a 3 s precomposition `P` (a red solid) as layer 0, with `remap`
/// as the layer's `timeRemap` property.
fn remapped(remap: Property) -> Project {
let mut p = Project::default();
let pre = add_comp(&mut p, "P", 640, 360, FrameRate::new(25, 1), 3.0, None);
let s = add_solid(&mut p, "S", 640, 360, [1.0, 0.0, 0.0], None);
add_layer(&mut p, pre, "S", LayerSource::Solid { item: s }, (640, 360));
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
add_layer(&mut p, c, "P", LayerSource::Comp { item: pre }, (640, 360));
with_layer(&mut p, c, 0, |l| l.props.children.insert(0, remap.into()));
p
}
fn remap_prop(keys: Vec<Keyframe>) -> Property {
let mut r = Property::new(9_000, "timeRemap", "Time Remap", Value::Scalar(0.0));
r.keys = keys;
r
}
#[test]
fn remaps_built_in_code_come_back() {
let k = |t: f64, v: f64| key(t, Value::Scalar(v));
let hold = Keyframe { out_interp: Interp::Hold, ..k(1.0, 2.0) };
let ease = Keyframe {
in_interp: Interp::Bezier,
out_interp: Interp::Bezier,
in_ease: vec![Ease { speed: 0.5, influence: 0.4 }],
out_ease: vec![Ease { speed: 1.5, influence: 0.25 }],
label: 3,
..k(2.0, 1.0)
};
let cases: Vec<(&str, Property)> = vec![
("reverse", remap_prop(vec![k(0.0, 3.0), k(3.0, 0.0)])),
("hold and ease", remap_prop(vec![k(0.0, 0.0), hold, ease, k(4.96, 2.96)])),
("expression", {
let mut r = remap_prop(vec![k(0.0, 0.0), k(3.0, 3.0)]);
r.expr = Some(Expression { text: "time * 0.5".into(), enabled: true });
r
}),
("static", Property { value: Value::Scalar(1.2), ..remap_prop(Vec::new()) }),
];
for (name, prop) in cases {
let p1 = remapped(prop.clone());
let r = export_all(&p1);
assert!(r.report.is_lossless(), "{name}: {:?}", r.report.losses);
assert_eq!(r.report.exported.time_remaps, 1, "{name}");
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes, "{name}");
let back = remap_of(&reimport(&r.bytes));
assert_eq!(back.len(), 1, "{name}");
let got = &back[0];
if prop.keys.is_empty() {
// Written as one key holding the value (a keyless remap reads back off in After
// Effects, r1).
assert_eq!(got.keys.len(), 1, "{name}");
assert_eq!(got.keys[0].value, prop.value, "{name}");
continue;
}
assert_eq!(got.keys.len(), prop.keys.len(), "{name}");
for (a, b) in got.keys.iter().zip(&prop.keys) {
assert_eq!((a.time, a.in_interp, a.out_interp, a.label), (b.time, b.in_interp, b.out_interp, b.label), "{name}");
assert_eq!(a.value, b.value, "{name}");
if b.in_interp == Interp::Bezier {
assert_eq!(a.in_ease, b.in_ease, "{name}");
assert_eq!(a.out_ease, b.out_ease, "{name}");
}
}
assert_eq!(got.expr.as_ref().map(|e| (&e.text, e.enabled)), prop.expr.as_ref().map(|e| (&e.text, e.enabled)), "{name}");
}
}
#[test]
fn a_remapped_layer_may_run_past_its_source() {
// A remap holding the last frame: the layer runs 5 s over a 3 s source without a timing loss.
let mut p = remapped(remap_prop(vec![key(0.0, Value::Scalar(0.0)), key(3.0, Value::Scalar(3.0))]));
let c = p.comps().find(|(_, c)| c.width == 1920).map(|(id, _)| *id).unwrap();
with_layer(&mut p, c, 0, |l| {
l.out_point = secs(5.0);
});
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::LayerTiming), 0, "{:?}", r.report.losses);
}
#[test]
fn a_remap_where_after_effects_has_none_is_reported() {
// A solid cannot be remapped in After Effects (319): reported, not written.
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
let s = add_solid(&mut p, "S", 100, 100, [1.0, 0.0, 0.0], None);
add_layer(&mut p, c, "S", LayerSource::Solid { item: s }, (100, 100));
with_layer(&mut p, c, 0, |l| l.props.children.insert(0, remap_prop(vec![key(0.0, Value::Scalar(0.0))]).into()));
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::TimeRemapping), 1, "{:?}", r.report.losses);
assert!(enabled_remaps(&r.bytes).is_empty());
}
#[test]
fn hostile_remaps_never_panic() {
let many: Vec<Keyframe> = (0..20_000).map(|i| key(f64::from(i) * 0.000_2, Value::Scalar(f64::from(i)))).collect();
let cases = vec![
remap_prop(vec![key(0.0, Value::Scalar(f64::NAN)), key(1.0, Value::Scalar(f64::INFINITY))]),
remap_prop(vec![key(-10.0, Value::Scalar(1e300)), key(1e9, Value::Scalar(-1e300))]),
remap_prop(vec![key(1.0, Value::Vec3([1.0, 2.0, 3.0])), key(1.0, Value::Bool(true))]),
remap_prop(many),
Property { value: Value::Scalar(f64::NAN), ..remap_prop(Vec::new()) },
];
for prop in cases {
let r = export_all(&remapped(prop));
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
let _ = reimport(&r.bytes);
}
}
+430
View File
@@ -0,0 +1,430 @@
//! Values the export cannot write as they are (clamped, rounded, replaced or left out) are
//! reported, and a strict export refuses before writing anything. Every project is built in code,
//! so these run without the corpus.
use crate::export::helpers::*;
use effectcraft_aep::export::{AepExportError, ExportOptions, LossCategory, analyze, export};
use effectcraft_color::Label;
use effectcraft_keyframe::text_doc::{CharStyle, StyleRun, TextDoc};
use effectcraft_keyframe::{Ease, Interp, Value};
use effectcraft_project::{AutoOrient, Footage, FootageKind, ItemKind, Layer, LayerSource, LightKind, Marker, Node, Project, PropGroup, Proxy, build};
use effectcraft_time::FrameRate;
/// `p` reports a loss in `category` whose detail contains `needle`, and a strict export refuses.
#[track_caller]
fn reported(p: &Project, category: LossCategory, needle: &str) {
let r = analyze(p);
let hit = r.losses.iter().any(|l| l.category == category && l.details.iter().any(|d| d.contains(needle)));
assert!(hit, "no {category:?} loss with '{needle}': {:?}", r.losses);
assert!(matches!(export(p, &ExportOptions { allow_losses: false }), Err(AepExportError::Refused(_))));
}
#[track_caller]
fn lossless(p: &Project) {
let r = analyze(p);
assert!(r.is_lossless(), "{:?}", r.losses);
}
fn first_layer(p: &mut Project, c: effectcraft_project::ItemId, f: impl FnOnce(&mut Layer)) {
with_layer(p, c, 0, f);
}
#[test]
fn composition_settings_the_format_cannot_hold_are_reported() {
let (p, c, _) = simple();
lossless(&p);
// A duration that is not a whole number of frames (the rate changed afterwards).
let mut q = p.clone();
with_comp(&mut q, c, |comp| comp.duration = secs(5.01));
reported(&q, LossCategory::RoundedTimes, "duration moved to whole frames");
// Shutter angle and phase are whole degrees.
let mut q = p.clone();
with_comp(&mut q, c, |comp| comp.shutter_angle = 180.5);
reported(&q, LossCategory::CompositionSettings, "shutter angle 180.5");
let mut q = p.clone();
with_comp(&mut q, c, |comp| comp.shutter_phase = -12.25);
reported(&q, LossCategory::CompositionSettings, "shutter phase -12.25");
// The background has 8 bits per channel: the nearest level is written, a channel outside
// 0 to 1 is reported.
let mut q = p.clone();
with_comp(&mut q, c, |comp| comp.background = [0.5, 0.0, 1.0]);
lossless(&q);
with_comp(&mut q, c, |comp| comp.background = [1.5, 0.0, 1.0]);
reported(&q, LossCategory::CompositionSettings, "background channel 1.5");
// The start timecode is a whole, non-negative number of frames.
let mut q = p.clone();
with_comp(&mut q, c, |comp| comp.display_start = secs(-2.0));
reported(&q, LossCategory::CompositionSettings, "start timecode");
let mut q = p.clone();
with_comp(&mut q, c, |comp| comp.display_start = secs(1.0 + 1.0 / 51_200.0));
reported(&q, LossCategory::CompositionSettings, "start timecode");
// A pixel aspect without a small exact fraction.
let mut q = p;
with_comp(&mut q, c, |comp| comp.pixel_aspect = 1.0926);
reported(&q, LossCategory::CompositionSettings, "pixel aspect 1.0926");
}
#[test]
fn solid_values_the_format_cannot_hold_are_reported() {
let (p, _, s) = simple();
let set = |f: &dyn Fn(&mut effectcraft_project::Solid)| {
let mut q = p.clone();
if let Some(ItemKind::Solid(solid)) = q.item_mut(s).map(|i| &mut i.kind) {
f(solid);
}
q
};
reported(&set(&|s| s.color = [1.5, 0.0, 0.0]), LossCategory::InvalidValues, "colour channel 1.5");
reported(&set(&|s| s.pixel_aspect = 2.0), LossCategory::FootageItems, "pixel aspect 2");
}
#[test]
fn items_lose_their_comment_proxy_and_footage_markers_with_a_report() {
let (p, c, s) = simple();
let mut q = p.clone();
if let Some(i) = q.item_mut(c) {
i.comment = "a note".into();
}
reported(&q, LossCategory::Names, "item comment");
let still = Footage { path: "C:/x/a.png".into(), kind: FootageKind::Still, width: 64, height: 64, has_video: true, ..Footage::default() };
let mut q = p.clone();
if let Some(i) = q.item_mut(s) {
i.proxy = Some(Box::new(Proxy { footage: still.clone(), enabled: true }));
}
reported(&q, LossCategory::FootageItems, "proxy");
let mut q = p;
let marked = Footage { markers: vec![Marker { time: secs(0.5), ..Marker::default() }], ..still };
q.add_item("a.png", Label::None, None, ItemKind::Footage(marked));
reported(&q, LossCategory::Markers, "footage marker");
}
#[test]
fn key_settings_the_export_does_not_keep_are_reported() {
let (mut p, c, _) = simple();
first_layer(&mut p, c, |l| {
let o = l.props.prop_mut("transform/opacity").expect("opacity");
o.keys = vec![key(0.0, Value::Scalar(0.0)), key(1.0, Value::Scalar(50.0)), key(2.0, Value::Scalar(100.0))];
});
lossless(&p);
let keyed = |f: &dyn Fn(&mut effectcraft_keyframe::Keyframe)| {
let mut q = p.clone();
first_layer(&mut q, c, |l| {
if let Some(k) = l.props.prop_mut("transform/opacity").and_then(|o| o.keys.get_mut(1)) {
f(k);
}
});
q
};
reported(&keyed(&|k| k.muted = true), LossCategory::ApproximatedKeyframes, "muted key");
reported(
&keyed(&|k| {
k.in_interp = Interp::Bezier;
k.out_interp = Interp::Bezier;
k.auto_bezier = true;
}),
LossCategory::ApproximatedKeyframes,
"auto-Bezier",
);
reported(
&keyed(&|k| {
k.out_interp = Interp::Bezier;
k.out_ease = vec![Ease { speed: 1e12, influence: 0.5 }];
}),
LossCategory::InvalidValues,
"key speed",
);
}
#[test]
fn a_time_stretch_that_moves_a_layer_end_is_reported() {
let (mut p, c, _) = simple();
first_layer(&mut p, c, |l| {
l.stretch = 150.0;
l.start_time = secs(0.4);
l.in_point = secs(0.0);
});
reported(&p, LossCategory::RoundedTimes, "after the time stretch");
}
fn text_doc(f: impl FnOnce(&mut CharStyle)) -> TextDoc {
let mut d = TextDoc::plain("Text");
let mut style = CharStyle { font: "ArialMT".into(), style: "Regular".into(), size: 50.0, leading: Some(60.0), ..CharStyle::default() };
f(&mut style);
d.set_runs(vec![StyleRun { len: 4, style }]);
d
}
fn text_project(doc: TextDoc) -> Project {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
add_layer(&mut p, c, "T", LayerSource::Text, (1920, 1080));
first_layer(&mut p, c, |l| {
if let Some(st) = l.props.prop_mut("text/sourceText") {
st.value = Value::Text(Box::new(doc));
}
});
p
}
#[test]
fn text_values_the_document_cannot_hold_are_reported() {
lossless(&text_project(text_doc(|_| {})));
reported(&text_project(text_doc(|s| s.fill = [2.0, 0.0, 0.0, 1.0])), LossCategory::TextLayers, "fill colour channel 2");
reported(&text_project(text_doc(|s| s.fill = [1.0, 0.0, 0.0, 0.5])), LossCategory::TextLayers, "fill colour opacity 0.5");
reported(&text_project(text_doc(|s| s.tracking = 200_000.0)), LossCategory::TextLayers, "tracking 200000");
reported(&text_project(text_doc(|s| s.baseline_shift = -2e5)), LossCategory::TextLayers, "baseline shift");
reported(&text_project(text_doc(|s| s.font = String::new())), LossCategory::TextLayers, "without a font name");
let mut boxed = text_doc(|_| {});
boxed.box_size = Some([2e6, 100.0]);
reported(&text_project(boxed), LossCategory::TextLayers, "box width");
}
#[test]
fn a_switched_off_range_selector_is_reported() {
let mut p = text_project(text_doc(|_| {}));
let c = p.comps().next().map(|(id, _)| *id).expect("comp");
let mut next = p.next_id;
let mut animator = build::text_animator(&mut build::Ids(&mut next), "Animator 1", Vec::new());
p.next_id = next;
first_layer(&mut p, c, |l| {
if let Some(Node::Group(sel)) = animator.sub_mut("selectors").and_then(|s| s.children.first_mut()) {
sel.enabled = false;
}
l.props.sub_mut("text").and_then(|t| t.sub_mut("animators")).expect("animators").children.push(animator.into());
});
reported(&p, LossCategory::TextLayers, "switched-off selector");
}
#[test]
fn camera_and_light_options_that_are_not_written_are_reported() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
add_layer(&mut p, c, "Cam", LayerSource::Camera, (1920, 1080));
let mut q = p.clone();
first_layer(&mut q, c, |l| l.auto_orient = AutoOrient::AlongPath);
reported(&q, LossCategory::Cameras, "Auto-Orient");
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
add_layer(&mut p, c, "Spot", LayerSource::Light { kind: LightKind::Spot }, (1920, 1080));
let mut q = p.clone();
first_layer(&mut q, c, |l| l.auto_orient = AutoOrient::Off);
reported(&q, LossCategory::Lights, "Auto-Orient");
let mut q = p;
first_layer(&mut q, c, |l| {
if let Some(col) = l.props.prop_mut("lightOptions/color") {
col.value = Value::Color([2.0, 0.5, 0.5, 1.0]);
}
});
reported(&q, LossCategory::Lights, "light colour channel");
}
/// `simple()` with a new instance of the effect `id` on its layer, changed by `f`.
fn with_effect(id: &str, f: impl FnOnce(&mut PropGroup)) -> Project {
let (mut p, c, _) = simple();
let spec = effectcraft_effects::find(id).expect(id);
let mut next = p.next_id;
let mut g = effectcraft_effects::instantiate(spec, &mut build::Ids(&mut next), spec.name, [1920.0, 1080.0]);
p.next_id = next;
f(&mut g);
first_layer(&mut p, c, |l| l.props.sub_mut("effects").expect("effects").children.push(Node::Group(g)));
p
}
fn set(g: &mut PropGroup, path: &str, v: Value) {
g.prop_mut(path).unwrap_or_else(|| panic!("{path}")).value = v;
}
#[test]
fn effect_values_the_format_cannot_hold_are_reported() {
lossless(&with_effect("ec.color.tint", |_| {}));
reported(&with_effect("ec.color.tint", |g| set(g, "white", Value::Color([1.5, 0.0, 0.0, 1.0]))), LossCategory::InvalidValues, "colour channel");
reported(&with_effect("ec.blur.fastbox", |g| set(g, "iterations", Value::Scalar(2.5))), LossCategory::Effects, "whole number");
reported(&with_effect("ec.color.tint", |g| g.label = Some(Label::Red)), LossCategory::Effects, "label colour");
// After Effects' colour parameters have no opacity; Drop Shadow uses EffectCraft's.
reported(&with_effect("ec.perspective.dropshadow", |g| set(g, "color", Value::Color([0.0, 0.0, 0.0, 0.5]))), LossCategory::Effects, "opacity");
// A parameter the table has no record for, at a value other than a new instance's.
lossless(&with_effect("ec.time.timewarp", |_| {}));
reported(&with_effect("ec.time.timewarp", |g| set(g, "tuning/vectorDetail", Value::Scalar(50.0))), LossCategory::Effects, "Vector Detail");
// Curves points outside 0..1.
reported(&with_effect("ec.color.curves", |g| set(g, "rgb", Value::Str("0,0;1.2,1".into()))), LossCategory::Effects, "outside 0 to 1");
}
#[test]
fn per_corner_roundness_is_reported() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "S", LayerSource::Shape, (1920, 1080));
let mut next = p.next_id;
let mut ids = build::Ids(&mut next);
let mut rect = build::shape_rect(&mut ids, [400.0, 300.0], [0.0, 0.0], 15.0);
set(&mut rect, "perCorner", Value::Bool(true));
let fill = build::shape_fill(&mut ids, [0.0, 1.0, 0.0, 1.0]);
let group = build::shape_group(&mut ids, "Group 1", vec![rect, fill]);
p.next_id = next;
first_layer(&mut p, c, |l| l.props.sub_mut("contents").expect("contents").children.push(group.into()));
reported(&p, LossCategory::ShapeLayers, "per-corner roundness");
}
#[test]
fn footage_interpretation_and_durations_that_are_not_written_are_reported() {
let still = Footage { path: "C:/x/a.png".into(), kind: FootageKind::Still, width: 64, height: 64, has_video: true, ..Footage::default() };
let with = |f: Footage| {
let (mut p, _, _) = simple();
p.add_item("a", Label::None, None, ItemKind::Footage(f));
p
};
lossless(&with(still.clone()));
reported(&with(Footage { alpha: effectcraft_project::AlphaMode::Premultiplied, ..still.clone() }), LossCategory::FootageItems, "alpha interpretation");
reported(&with(Footage { pixel_aspect: 2.0, ..still.clone() }), LossCategory::FootageItems, "pixel aspect");
reported(&with(Footage { loop_count: 3, ..still.clone() }), LossCategory::FootageItems, "loop count");
let clip = Footage { path: "C:/x/a.mp4".into(), kind: FootageKind::Video, frame_rate: FrameRate::new(25, 1), duration: secs(0.0), ..still };
reported(&with(clip), LossCategory::FootageItems, "written as 1 frame");
}
#[test]
fn mask_values_beyond_the_record_limits_are_reported() {
let (mut p, c, _) = simple();
let mut next = p.next_id;
let mut g = build::mask(
&mut build::Ids(&mut next),
"Mask 1",
effectcraft_keyframe::ShapePath::rect([960.0, 540.0], 400.0, 200.0),
effectcraft_project::MaskMode::Add,
build::MASK_COLORS[0],
);
p.next_id = next;
set(&mut g, "feather", Value::Vec2([40_000.0, 10.0]));
let mut q = p.clone();
let h = g.clone();
first_layer(&mut q, c, |l| l.props.sub_mut("masks").expect("masks").children.push(h.into()));
reported(&q, LossCategory::InvalidValues, "feather");
set(&mut g, "feather", Value::Vec2([10.0, 10.0]));
set(&mut g, "expansion", Value::Scalar(-50_000.0));
first_layer(&mut p, c, |l| l.props.sub_mut("masks").expect("masks").children.push(g.into()));
reported(&p, LossCategory::InvalidValues, "Mask expansion");
}
#[test]
fn camera_options_stretch_curves_and_expressions_that_change_are_reported() {
// A camera option that is not a number.
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
add_layer(&mut p, c, "Cam", LayerSource::Camera, (1920, 1080));
first_layer(&mut p, c, |l| {
if let Some(z) = l.props.prop_mut("cameraOptions/zoom") {
z.value = Value::Bool(true);
}
});
reported(&p, LossCategory::InvalidValues, "cameraOptions/zoom");
// A stretch that is not a number is reported, not taken as 100 %.
let (mut p, c, _) = simple();
first_layer(&mut p, c, |l| l.stretch = f64::NAN);
reported(&p, LossCategory::TimeStretch, "");
// A curve that is not text.
reported(&with_effect("ec.color.curves", |g| set(g, "rgb", Value::Scalar(1.0))), LossCategory::InvalidValues, "not text");
// An expression on a popup whose items are After Effects' in another order (Invert's
// channels: After Effects counts its separators, EffectCraft has none).
let p = with_effect("ec.channel.invert", |g| {
g.prop_mut("channel").expect("channel").expr = Some(effectcraft_project::Expression { text: "6".into(), enabled: true });
});
reported(&p, LossCategory::Expressions, "other units");
}
/// A 3D layer's Material Options are not written: a value other than a new layer's, a key or an
/// expression is reported (one loss each), and a strict export refuses (review finding: changed
/// options were dropped without a report). The defaults, and any value on a 2D layer (where they
/// do nothing), stay lossless.
#[test]
fn changed_material_options_of_a_3d_layer_are_reported() {
let three_d = |f: &dyn Fn(&mut PropGroup)| {
let (mut p, c, _) = simple();
first_layer(&mut p, c, |l| {
l.switches.three_d = true;
f(l.props.sub_mut("materialOptions").expect("material options"));
});
p
};
lossless(&three_d(&|_| {}));
for (name, change) in [
("Accepts Lights", &(|g: &mut PropGroup| set(g, "acceptsLights", Value::Bool(false))) as &dyn Fn(&mut PropGroup)),
("Casts Shadows", &|g: &mut PropGroup| set(g, "castsShadows", Value::Enum(1))),
("Diffuse", &|g: &mut PropGroup| g.prop_mut("diffuse").expect("diffuse").keys = vec![key(0.0, Value::Scalar(50.0)), key(1.0, Value::Scalar(80.0))]),
("Ambient", &|g: &mut PropGroup| {
g.prop_mut("ambient").expect("ambient").expr = Some(effectcraft_project::Expression { text: "100".into(), enabled: true })
}),
] {
let p = three_d(change);
reported(&p, LossCategory::ThreeD, &format!("material option {name}"));
assert_eq!(analyze(&p).count(LossCategory::ThreeD), 1, "{name}");
}
let (mut flat, c, _) = simple();
first_layer(&mut flat, c, |l| set(l.props.sub_mut("materialOptions").expect("material options"), "acceptsLights", Value::Bool(false)));
lossless(&flat);
}
/// A popup expression is written as it is: both programs count popup items from 1, so where the
/// items are the same in the same order (Fast Box Blur's Blur Dimensions) its result picks the
/// same item, and nothing is reported (review finding: every popup expression was reported).
#[test]
fn a_popup_expression_with_the_same_items_is_not_a_loss() {
let p = with_effect("ec.blur.fastbox", |g| {
g.prop_mut("dimensions").expect("dimensions").expr = Some(effectcraft_project::Expression { text: "1".into(), enabled: true });
});
let r = effectcraft_aep::export::export(&p, &effectcraft_aep::export::ExportOptions { allow_losses: true }).expect("export");
assert_eq!(r.report.count(LossCategory::Expressions), 0, "{:?}", r.report.losses);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
assert!(effectcraft_aep::export::export(&p, &effectcraft_aep::export::ExportOptions { allow_losses: false }).is_ok());
assert_eq!(r.report.exported.expressions, 1);
}
#[test]
fn a_repeaters_order_is_written_not_reported() {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 2.0, None);
add_layer(&mut p, c, "S", LayerSource::Shape, (1920, 1080));
let mut next = p.next_id;
let mut ids = build::Ids(&mut next);
let rect = build::shape_rect(&mut ids, [100.0, 100.0], [0.0, 0.0], 0.0);
let fill = build::shape_fill(&mut ids, [0.0, 1.0, 0.0, 1.0]);
let mut rep = build::shape_repeater(&mut ids, 3.0, [120.0, 0.0]);
set(&mut rep, "composite", Value::Enum(1));
let group = build::shape_group(&mut ids, "Group 1", vec![rect, fill, rep]);
p.next_id = next;
first_layer(&mut p, c, |l| l.props.sub_mut("contents").expect("contents").children.push(group.into()));
lossless(&p);
}
#[test]
fn composition_options_and_the_render_queue_that_are_not_written_are_reported() {
// The base writes these at After Effects' defaults (cdta 196 and 200 hold 128 and 16 in every
// sample, the switches are not decoded) and writes an empty render queue: each non-default
// value is reported, and a strict export refuses.
let (p, c, _) = simple();
lossless(&p);
let cases: [(&dyn Fn(&mut effectcraft_project::Comp), &str); 4] = [
(&|comp| comp.preserve_frame_rate = true, "Preserve Frame Rate"),
(&|comp| comp.preserve_resolution = true, "Preserve Resolution"),
(&|comp| comp.motion_blur_samples = 32, "motion blur samples per frame"),
(&|comp| comp.motion_blur_adaptive_limit = 256, "adaptive sample limit"),
];
for (set, needle) in cases {
let mut q = p.clone();
with_comp(&mut q, c, set);
reported(&q, LossCategory::CompositionOptions, needle);
assert_eq!(analyze(&q).count(LossCategory::CompositionOptions), 1, "{needle}");
}
// Viewer state is a listed limitation, not a loss (the Home templates set a poster time).
let mut q = p.clone();
with_comp(&mut q, c, |comp| {
comp.hide_shy = true;
comp.draft_3d = true;
comp.poster_time = secs(1.5);
comp.resolution = effectcraft_project::Resolution::Half;
});
lossless(&q);
// A render queue item is not written.
let mut q = p;
q.render_queue.push(effectcraft_project::render_queue::RenderQueueItem::new(1, c));
reported(&q, LossCategory::RenderQueue, "render queue item of 'C'");
}
+164
View File
@@ -0,0 +1,164 @@
//! Odd projects never panic and always produce a container that parses and writes back.
use crate::export::helpers::*;
use effectcraft_aep::export::{ExportOptions, LossCategory, export};
use effectcraft_aep::{parse, write};
use effectcraft_color::Label;
use effectcraft_keyframe::{Ease, Interp, Value};
use effectcraft_project::{ItemKind, LayerSource, Project};
use effectcraft_time::{FrameRate, Tick};
fn check(p: &Project) -> effectcraft_aep::export::ExportResult {
let r = export(p, &ExportOptions { allow_losses: true }).expect("export");
let f = parse(&r.bytes).expect("parse");
assert_eq!(write(&f).expect("write"), r.bytes);
r
}
#[test]
fn empty_project_and_empty_names() {
let p = Project::default();
let r = check(&p);
assert!(r.report.is_lossless());
let mut p = Project::default();
let c = add_comp(&mut p, "", 100, 100, FrameRate::new(25, 1), 1.0, None);
let s = add_solid(&mut p, "", 10, 10, [0.0; 3], None);
add_layer(&mut p, c, "", LayerSource::Solid { item: s }, (10, 10));
let f = p.add_item("", Label::None, None, ItemKind::Folder);
add_comp(&mut p, "x", 10, 10, FrameRate::new(25, 1), 1.0, Some(f));
check(&p);
}
#[test]
fn huge_zero_and_negative_sizes_and_durations() {
let mut p = Project::default();
for (w, h) in [(0, 0), (1, 1), (30_000, 30_000), (u32::MAX, u32::MAX), (65_536, 3)] {
let c = add_comp(&mut p, "c", w, h, FrameRate::new(25, 1), 1.0, None);
let s = add_solid(&mut p, "s", w, h, [2.0, -1.0, f32::NAN], None);
add_layer(&mut p, c, "l", LayerSource::Solid { item: s }, (w, h));
}
for dur in [0.0, -5.0, 1e9, 1e-9] {
add_comp(&mut p, "d", 100, 100, FrameRate::new(25, 1), dur, None);
}
let r = check(&p);
assert!(r.report.count(LossCategory::CompositionSettings) >= 1);
}
#[test]
fn strange_frame_rates() {
let mut p = Project::default();
for (n, d) in [(0, 1), (1, 0), (-25, 1), (7, 3), (i64::MAX, 1), (1, i64::MAX), (25, 1), (1000, 1), (24_000, 1001)] {
let rate = FrameRate { num: n, den: d };
let mut c = effectcraft_project::Comp::new(100, 100, FrameRate::new(25, 1), Tick(254_016_000_000));
c.frame_rate = rate;
p.add_item("r", Label::None, None, ItemKind::Comp(std::sync::Arc::new(c)));
}
check(&p);
}
#[test]
fn non_finite_and_huge_values_are_written_as_defaults() {
let (mut p, c, _) = simple();
with_layer(&mut p, c, 0, |l| {
let tr = l.transform_mut().expect("tr");
tr.get_mut("position").expect("p").value = Value::Vec3([f64::NAN, f64::INFINITY, 1e300]);
tr.get_mut("opacity").expect("o").value = Value::Scalar(f64::NAN);
let sc = tr.get_mut("scale").expect("s");
let mut k0 = key(0.0, Value::Vec3([f64::NAN, 1e30, 0.0]));
k0.out_interp = Interp::Bezier;
k0.out_ease = vec![Ease { speed: f64::NAN, influence: f64::INFINITY }];
let mut k1 = key(1.0, Value::Vec3([1.0, 2.0, 3.0]));
k1.in_interp = Interp::Bezier;
k1.in_ease = vec![Ease { speed: 1e300, influence: -5.0 }];
sc.keys = vec![k0, k1];
let rot = tr.get_mut("rotation").expect("r");
rot.keys = vec![key(0.0, Value::Scalar(1.0)), key(0.0, Value::Scalar(2.0)), key(1e12, Value::Scalar(3.0)), key(-1e12, Value::Scalar(4.0))];
});
let r = check(&p);
assert!(r.report.count(LossCategory::InvalidValues) >= 3);
}
#[test]
fn thousands_of_layers_and_keys() {
let mut p = Project::default();
let c = add_comp(&mut p, "Many", 640, 360, FrameRate::new(25, 1), 20.0, None);
let s = add_solid(&mut p, "S", 64, 64, [0.5; 3], None);
let mut comp = p.comp(c).cloned().expect("comp");
for i in 0..2000 {
let mut l = effectcraft_project::build::layer(&mut p, &comp, &format!("L{i}"), LayerSource::Solid { item: s }, (64, 64), None);
l.name = format!("L{i}");
let pos = l.transform_mut().expect("tr").get_mut("position").expect("p");
pos.keys = (0..10).map(|k| key(f64::from(k), Value::Vec3([f64::from(i), f64::from(k), 0.0]))).collect();
comp.layers.push(l);
}
if let Some(i) = p.item_mut(c) {
i.kind = ItemKind::Comp(std::sync::Arc::new(comp));
}
let r = check(&p);
assert_eq!(r.report.exported.layers, 2000);
assert_eq!(r.report.exported.keyframes, 20_000);
}
#[test]
fn parent_loops_missing_sources_and_folder_loops() {
let (mut p, c, _) = simple();
add_layer(&mut p, c, "B", LayerSource::Solid { item: effectcraft_project::ItemId(9999) }, (10, 10));
add_layer(&mut p, c, "A", LayerSource::Null, (10, 10));
let (a, b) = {
let cc = p.comp(c).expect("c");
(cc.layers[0].id, cc.layers[1].id)
};
// A layer that is its own parent, and the unsupported layer B as the parent of a third.
with_layer(&mut p, c, 0, |l| l.parent = Some(a));
with_layer(&mut p, c, 2, |l| l.parent = Some(b));
// A loop of two exported layers.
add_layer(&mut p, c, "P", LayerSource::Null, (10, 10));
add_layer(&mut p, c, "Q", LayerSource::Null, (10, 10));
let (pid, qid) = {
let cc = p.comp(c).expect("c");
(cc.layers[1].id, cc.layers[0].id)
};
with_layer(&mut p, c, 1, |l| l.parent = Some(qid));
with_layer(&mut p, c, 0, |l| l.parent = Some(pid));
// Two folders that are each other's parent, and an item that names a missing parent.
let f1 = p.add_item("F1", Label::None, None, ItemKind::Folder);
let f2 = p.add_item("F2", Label::None, Some(f1), ItemKind::Folder);
if let Some(i) = p.item_mut(f1) {
i.parent = Some(f2);
}
let s = add_solid(&mut p, "InLoop", 10, 10, [0.0; 3], Some(f1));
add_layer(&mut p, c, "UsesLoopSolid", LayerSource::Solid { item: s }, (10, 10));
let r = check(&p);
assert!(r.report.count(LossCategory::ParentLinks) >= 3, "{}", r.report.summary());
assert!(r.report.count(LossCategory::FootageItems) >= 3);
assert!(r.report.count(LossCategory::UnsupportedLayers) >= 2);
}
#[test]
fn very_long_and_odd_names() {
let mut p = Project::default();
let long = "x".repeat(10_000);
let weird = "a\0b\u{1f600}\u{202e}\"'<>&\n\r\t".to_string();
let c = add_comp(&mut p, &long, 100, 100, FrameRate::new(25, 1), 1.0, None);
let s = add_solid(&mut p, &long, 10, 10, [0.0; 3], None);
add_layer(&mut p, c, &long, LayerSource::Solid { item: s }, (10, 10));
add_layer(&mut p, c, &weird, LayerSource::Null, (10, 10));
let s2 = add_solid(&mut p, &weird, 10, 10, [0.0; 3], None);
add_layer(&mut p, c, "\u{3042}".repeat(100).as_str(), LayerSource::Solid { item: s2 }, (10, 10));
let r = check(&p);
assert!(r.report.count(LossCategory::Names) >= 1);
}
#[test]
fn a_wide_folder_tree() {
let mut p = Project::default();
let mut parent = None;
for i in 0..100 {
parent = Some(p.add_item(&format!("F{i}"), Label::None, parent, ItemKind::Folder));
}
for i in 0..300 {
add_solid(&mut p, &format!("s{i}"), 8, 8, [0.1; 3], parent);
}
let r = check(&p);
assert!(r.report.count(LossCategory::FootageItems) > 0, "folders deeper than the limit are reported");
}
+145
View File
@@ -0,0 +1,145 @@
//! fixture -> import -> export -> import: the two imported projects are equal for the exported
//! subset (masks included), and the exporter never fails on what the importer produces.
use crate::export::helpers::export_all;
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_project::{Comp, Item, ItemKind, Layer, LayerSource, Project};
fn import_bytes(bytes: &[u8]) -> Option<Project> {
let mut p = Project::default();
let none = |_: &str| false;
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&none) };
import(&mut p, bytes, &opts).ok()?;
Some(p)
}
/// Items in tree order: (depth, name) with the item.
fn tree<'a>(p: &'a Project, parent: Option<effectcraft_project::ItemId>, depth: usize, out: &mut Vec<(usize, &'a Item)>) {
let mut kids: Vec<&Item> = p.items.values().filter(|i| i.parent == parent).collect();
kids.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then(a.id.0.cmp(&b.id.0)));
for k in kids {
out.push((depth, k));
if k.is_folder() && depth < 50 {
tree(p, Some(k.id), depth + 1, out);
}
}
}
fn same_comp(a: &Comp, b: &Comp, name: &str, pa: &Project, pb: &Project) {
assert_eq!((a.width, a.height, a.frame_rate, a.duration), (b.width, b.height, b.frame_rate, b.duration), "{name}");
assert_eq!(a.work_area, b.work_area, "{name} work area");
assert!((0..3).all(|i| (a.background[i] - b.background[i]).abs() < 1e-6), "{name} background");
assert!((a.pixel_aspect - b.pixel_aspect).abs() < 1e-3, "{name} pixel aspect");
assert_eq!(
(a.shutter_angle, a.shutter_phase, a.enable_motion_blur, a.display_start),
(b.shutter_angle, b.shutter_phase, b.enable_motion_blur, b.display_start),
"{name}"
);
// Layers that the exporter keeps (solid, null) in order.
let keep = |c: &Comp| -> Vec<Layer> {
c.layers.iter().filter(|l| matches!(l.source, LayerSource::Solid { .. } | LayerSource::Null | LayerSource::Comp { .. })).cloned().collect()
};
let (la, lb) = (keep(a), keep(b));
assert_eq!(la.len(), lb.len(), "{name} layer count");
for (x, y) in la.iter().zip(&lb) {
same_layer(x, y, a, b, name, pa, pb);
}
}
fn same_layer(x: &Layer, y: &Layer, ca: &Comp, cb: &Comp, comp: &str, pa: &Project, pb: &Project) {
let w = format!("{comp}/{}", x.name);
assert_eq!(x.name, y.name, "{w}");
assert_eq!((x.start_time, x.in_point, x.out_point), (y.start_time, y.in_point, y.out_point), "{w} timing");
assert_eq!(x.blend_mode, y.blend_mode, "{w}");
assert_eq!(x.label, y.label, "{w}");
assert_eq!(x.switches, y.switches, "{w} switches");
let idx = |c: &Comp, p: Option<effectcraft_project::LayerId>| p.and_then(|id| c.index_of(id));
assert_eq!(idx(ca, x.parent), idx(cb, y.parent), "{w} parent");
let src = |p: &Project, l: &Layer| match &l.source {
LayerSource::Solid { item } => p.item(*item).map(|i| (i.name.clone(), Some(i.kind.clone()))),
// A precomposition layer shows the composition of the same name.
LayerSource::Comp { item } => p.item(*item).map(|i| (i.name.clone(), None)),
_ => None,
};
assert_eq!(src(pa, x), src(pb, y), "{w} source");
// Masks (names, mode, invert, values and key counts; the field-by-field check is in masks.rs).
let masks = |l: &Layer| -> Vec<effectcraft_project::PropGroup> { l.masks().map(|m| m.groups().cloned().collect()).unwrap_or_default() };
let (mx, my) = (masks(x), masks(y));
assert_eq!(mx.len(), my.len(), "{w} mask count");
for (a, b) in mx.iter().zip(&my) {
assert_eq!((&a.name, &a.kind), (&b.name, &b.kind), "{w} mask");
for id in ["feather", "opacity", "expansion"] {
let (pa, pb) = (a.get(id).expect("p"), b.get(id).expect("p"));
assert!(pa.value.components().iter().zip(pb.value.components()).all(|(p, q)| (p - q).abs() < 1e-9), "{w} mask {id}");
assert_eq!(pa.keys.len(), pb.keys.len(), "{w} mask {id} keys");
}
assert_eq!(a.get("path").expect("path").keys.len(), b.get("path").expect("path").keys.len(), "{w} mask path keys");
}
let (tx, ty) = (x.transform().expect("t"), y.transform().expect("t"));
for id in ["anchor", "position", "scale", "rotation", "opacity"] {
let (px, py) = (tx.get(id).expect("p"), ty.get(id).expect("p"));
let close =
|a: &effectcraft_keyframe::Value, b: &effectcraft_keyframe::Value| a.components().iter().zip(b.components()).all(|(p, q)| (p - q).abs() < 1e-6);
assert!(close(&px.value, &py.value), "{w} {id} value {:?} {:?}", px.value, py.value);
assert_eq!(px.expr, py.expr, "{w} {id} expression");
assert_eq!(px.keys.len(), py.keys.len(), "{w} {id} key count");
for (kx, ky) in px.keys.iter().zip(&py.keys) {
same_key(kx, ky, px.spatial, &format!("{w} {id}"));
}
}
}
fn same_key(kx: &effectcraft_keyframe::Keyframe, ky: &effectcraft_keyframe::Keyframe, spatial: bool, w: &str) {
let close = |a: &effectcraft_keyframe::Value, b: &effectcraft_keyframe::Value| a.components().iter().zip(b.components()).all(|(p, q)| (p - q).abs() < 1e-6);
assert_eq!(kx.time, ky.time, "{w} key time");
assert!(close(&kx.value, &ky.value), "{w} key value");
assert_eq!(kx.roving, ky.roving, "{w}");
assert_eq!(kx.label, ky.label, "{w}");
assert_eq!(kx.spatial_auto, ky.spatial_auto, "{w}");
if spatial && !kx.spatial_auto {
assert!(kx.spatial_in.iter().zip(ky.spatial_in).all(|(p, q)| (p - q).abs() < 1e-6), "{w} tangent");
}
// Every side keeps its kind (the Anchor Point's ease too: 597, 730).
for (sx, sy, ex, ey) in [(kx.in_interp, ky.in_interp, &kx.in_ease, &ky.in_ease), (kx.out_interp, ky.out_interp, &kx.out_ease, &ky.out_ease)] {
assert_eq!(sx, sy, "{w} interpolation");
if sx == effectcraft_keyframe::Interp::Bezier {
assert_eq!(ex.len().max(1), ey.len().max(1), "{w} ease dims");
for (a, b) in ex.iter().zip(ey) {
assert!((a.speed - b.speed).abs() < 1e-6 && (a.influence - b.influence).abs() < 1e-6, "{w} ease {a:?} {b:?}");
}
}
}
}
#[test]
fn every_fixture_survives_import_export_import() {
let mut compared = 0;
let mut precomps = 0;
for name in fixture_names!("aep") {
let bytes = fixture!(name);
let Some(p1) = import_bytes(&bytes) else { continue };
let r = export_all(&p1);
precomps += r.report.exported.precomp_layers;
let p2 = import_bytes(&r.bytes).unwrap_or_else(|| panic!("{name}: the exported file does not import"));
let (mut t1, mut t2) = (Vec::new(), Vec::new());
tree(&p1, None, 0, &mut t1);
tree(&p2, None, 0, &mut t2);
// The exporter drops footage items and puts root solids in the Solids folder; compare the
// compositions by name.
let comps = |t: &[(usize, &Item)]| -> Vec<(String, Comp)> {
let mut v: Vec<(String, Comp)> =
t.iter().filter_map(|(_, i)| if let ItemKind::Comp(c) = &i.kind { Some((i.name.clone(), (**c).clone())) } else { None }).collect();
v.sort_by(|a, b| a.0.cmp(&b.0));
v
};
let (c1, c2) = (comps(&t1), comps(&t2));
assert_eq!(c1.len(), c2.len(), "{name}: composition count");
for ((n1, a), (n2, b)) in c1.iter().zip(&c2) {
assert_eq!(n1, n2, "{name}");
same_comp(a, b, &format!("{name}/{n1}"), &p1, &p2);
compared += 1;
}
}
assert!(compared > 100, "only {compared} compositions compared");
assert!(precomps >= 2, "only {precomps} precomposition layers compared");
}
+186
View File
@@ -0,0 +1,186 @@
//! Project settings (cases 620-634): written into the template's header chunks, read back with
//! `effectcraft-aep`, and the settings fixtures through import, export and import.
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::{TimeDisplay, WorkingSpace, parse, write};
use effectcraft_color::ColorSpace;
use effectcraft_project::{BitDepth, ColorEngine, Project, ProjectSettings, TimeDisplayStyle};
fn read_back(p: &Project) -> effectcraft_aep::ProjectSettings {
let r = export_all(p);
let file = parse(&r.bytes).expect("parse");
assert_eq!(write(&file).expect("write"), r.bytes, "container consistent");
effectcraft_aep::ProjectSettings::read(&file)
}
fn with(f: impl FnOnce(&mut ProjectSettings)) -> Project {
let (mut p, _, _) = simple();
f(&mut p.settings);
p
}
#[test]
fn every_setting_is_written_as_after_effects_stores_it() {
// EffectCraft's defaults: 8 bpc, no working space, gamma 2.2, timecode, frames from 0.
let d = read_back(&with(|_| {}));
assert_eq!(d.bits_per_channel, Some(8));
assert_eq!(d.working_space, Some(WorkingSpace::None));
assert_eq!(d.working_gamma_24, Some(false));
assert!(!d.linearize && !d.blend_linear);
assert_eq!(d.time_display, Some(TimeDisplay::Timecode));
assert_eq!(d.frame_start, Some(0));
assert_eq!(d.scene_compensation, Some(true), "kept from the template");
for (depth, bpc) in [(BitDepth::Bpc8, 8), (BitDepth::Bpc16, 16), (BitDepth::Bpc32, 32)] {
assert_eq!(read_back(&with(|s| s.bit_depth = depth)).bits_per_channel, Some(bpc));
}
let srgb = read_back(&with(|s| s.working_space = Some(ColorSpace::Srgb)));
assert_eq!(srgb.working_space, Some(WorkingSpace::Profile("sRGB IEC61966-2.1".into())));
assert_eq!(read_back(&with(|s| s.working_gamma = 2.4)).working_gamma_24, Some(true));
for (lin, blend) in [(true, false), (false, true), (true, true)] {
let r = read_back(&with(|s| {
s.linearize = lin;
s.blend_linear = blend;
}));
assert_eq!((r.linearize, r.blend_linear), (lin, blend));
}
for (style, want) in [
(TimeDisplayStyle::Frames, TimeDisplay::Frames),
(TimeDisplayStyle::Feet35, TimeDisplay::FeetFrames { frames_per_foot: 16 }),
(TimeDisplayStyle::Feet16, TimeDisplay::FeetFrames { frames_per_foot: 40 }),
(TimeDisplayStyle::Timecode, TimeDisplay::Timecode),
] {
assert_eq!(read_back(&with(|s| s.time_display = style)).time_display, Some(want));
}
assert_eq!(read_back(&with(|s| s.frame_start = 1)).frame_start, Some(1));
}
fn unbase64(s: &str) -> Vec<u8> {
let val = |c: u8| match c {
b'A'..=b'Z' => u32::from(c - b'A'),
b'a'..=b'z' => u32::from(c - b'a') + 26,
b'0'..=b'9' => u32::from(c - b'0') + 52,
b'+' => 62,
b'/' => 63,
_ => panic!("not base64: {c}"),
};
let mut out = Vec::new();
for q in s.as_bytes().chunks(4) {
let n = q.iter().filter(|&&c| c != b'=').count();
let v = q.iter().filter(|&&c| c != b'=').enumerate().fold(0u32, |acc, (i, &c)| acc | (val(c) << (18 - 6 * i)));
out.extend_from_slice(&v.to_be_bytes()[1..n]);
}
out
}
#[test]
fn rec709_gamma_24_is_written_with_a_profile_of_our_own() {
let p = with(|s| s.working_space = Some(ColorSpace::Rec709));
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
let file = parse(&r.bytes).expect("parse");
let s = effectcraft_aep::ProjectSettings::read(&file);
assert_eq!(s.working_space, Some(WorkingSpace::Profile("Rec.709 Gamma 2.4".into())));
let cpid = file.chunks.iter().find(|c| c.is(b"cpid")).and_then(|c| c.bytes()).expect("cpid").to_vec();
let pw = file.chunks.iter().position(|c| c.is(b"PwCs")).expect("PwCs");
let json: serde_json::Value = serde_json::from_slice(file.chunks[pw + 1].bytes().expect("Utf8")).expect("json");
assert_eq!(json["baseProfileType"], 2);
let icc = unbase64(json["baseColorProfile"]["colorProfileData"].as_str().expect("data"));
// An ICC v4 display profile: size, 'acsp', and the ID in cpid equals the one in the header.
assert_eq!(u32::from_be_bytes([icc[0], icc[1], icc[2], icc[3]]) as usize, icc.len());
assert_eq!(&icc[36..40], b"acsp");
assert_eq!(icc[8], 4);
assert_eq!(&icc[84..100], &cpid[..]);
assert_ne!(cpid, vec![0xffu8; 16]);
// Import maps it back to Rec.709.
let mut q = Project::default();
let none = |_: &str| false;
let back = effectcraft_aep::import::import(&mut q, &r.bytes, &effectcraft_aep::import::ImportOptions::new(&none)).expect("import");
assert_eq!(back.settings.working_space, Some(ColorSpace::Rec709));
}
#[test]
fn our_rec709_profile_without_its_name_is_still_rec709() {
// After Effects 26.2.1 drops the name on a re-save (settings-c): the name is then our profile's
// description. The name is blanked to spaces, so the JSON keeps its length.
let mut bytes = export_all(&with(|s| s.working_space = Some(ColorSpace::Rec709))).bytes;
let key = b",\"colorProfileName\":\"Rec.709 Gamma 2.4\"";
let at = bytes.windows(key.len()).position(|w| w == key).expect("name");
bytes[at..at + key.len()].fill(b' ');
let s = effectcraft_aep::ProjectSettings::read(&parse(&bytes).expect("parse"));
assert_eq!(s.working_space, Some(WorkingSpace::Profile("Rec.709 Gamma 2.4 (EffectCraft)".into())));
let mut q = Project::default();
let none = |_: &str| false;
let back = effectcraft_aep::import::import(&mut q, &bytes, &effectcraft_aep::import::ImportOptions::new(&none)).expect("import");
assert_eq!(back.settings.working_space, Some(ColorSpace::Rec709));
}
#[test]
fn what_the_file_cannot_hold_is_reported() {
let lossy = [
with(|s| s.working_space = Some(ColorSpace::Rec2020)),
with(|s| s.color_engine = ColorEngine::Ocio),
with(|s| s.output_space = Some(ColorSpace::Rec2100Pq)),
with(|s| s.frame_start = 7),
];
for p in &lossy {
let r = export_all(p);
assert_eq!(r.report.count(LossCategory::ProjectSettings), 1, "{:?}", r.report.losses);
}
// Rec. 2020 is written as sRGB.
assert_eq!(read_back(&lossy[0]).working_space, Some(WorkingSpace::Profile("sRGB IEC61966-2.1".into())));
assert!(export_all(&with(|_| {})).report.is_lossless());
}
#[test]
fn settings_fixtures_round_trip() {
let names = [
"000-base.aep",
"621-settings-bpc-8.aep",
"622-settings-bpc-16.aep",
"623-settings-workingspace-none.aep",
"625-settings-gamma-2.4.aep",
"629-settings-time-display-frames.aep",
"630-settings-frame-start-1.aep",
"632-settings-linearize-and-blend-linear.aep",
"633-settings-feet-frames-35.aep",
"634-settings-feet-frames-16.aep",
];
for name in names {
let bytes = fixture!(name);
let orig = effectcraft_aep::ProjectSettings::read(&parse(&bytes).expect("parse"));
let mut p = Project::default();
let none = |_: &str| false;
let r = effectcraft_aep::import::import(&mut p, &bytes, &effectcraft_aep::import::ImportOptions::new(&none)).expect(name);
p.settings = r.settings;
let back = read_back(&p);
// 621-630 share a file with 628 (scene compensation off), which the round trip does not
// carry (628 is not in this list); every other setting comes back.
let back = effectcraft_aep::ProjectSettings { scene_compensation: orig.scene_compensation, ..back };
assert_eq!(back, orig, "{name}");
}
}
#[test]
fn an_output_space_equal_to_the_working_space_is_the_normal_case() {
// After Effects renders in the working space (902): the importer sets the output space of a
// Rec.709 Gamma 2.4 project to Rec.709, and the export of such a project loses nothing.
let bytes = fixture!("902-settings-rec709-16bpc-steps-png-grey-solid.aep");
let mut p = Project::default();
let none = |_: &str| false;
let opts = effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) };
let r = effectcraft_aep::import::import(&mut p, &bytes, &opts).expect("import");
assert_eq!((r.settings.working_space, r.settings.output_space), (Some(ColorSpace::Rec709), Some(ColorSpace::Rec709)));
p.settings = r.settings;
let e = export_all(&p);
assert_eq!(e.report.count(LossCategory::ProjectSettings), 0, "{:?}", e.report.losses);
let mut q = Project::default();
let back = effectcraft_aep::import::import(&mut q, &e.bytes, &opts).expect("re-import");
assert_eq!((back.settings.working_space, back.settings.output_space), (Some(ColorSpace::Rec709), Some(ColorSpace::Rec709)));
// Another output space is still reported.
let other = with(|s| {
s.working_space = Some(ColorSpace::Rec709);
s.output_space = Some(ColorSpace::Srgb);
});
assert_eq!(export_all(&other).report.count(LossCategory::ProjectSettings), 1);
}
+107
View File
@@ -0,0 +1,107 @@
//! A shape item's eye switch (986, 987): bit 0 of the item group's `tdsb`. After Effects does
//! not draw a Fill whose bit is clear (986), and draws it once set (987). The importer keeps it as
//! the item's `enabled`, the exporter writes it back.
use crate::export::helpers::export_all;
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{PropGroup as AepGroup, PropNode, parse};
use effectcraft_project::{Node, Project, PropGroup};
fn import_bytes(bytes: &[u8]) -> Project {
let mut p = Project::default();
let none = |_: &str| false;
let r = import(&mut p, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("import");
assert!(r.report.losses.is_empty(), "{:?}", r.report.losses);
p
}
/// (match id, enabled) of every shape item, depth first.
fn items(g: &PropGroup, out: &mut Vec<(String, bool)>) {
for c in &g.children {
if let Node::Group(sub) = c {
if sub.match_id != "transform" && sub.match_id != "contents" {
out.push((sub.match_id.clone(), sub.enabled));
}
items(sub, out);
}
}
}
fn switches(p: &Project) -> Vec<(String, bool)> {
let mut out = Vec::new();
for (_, c) in p.comps() {
for l in &c.layers {
if let Some(contents) = l.props.sub("contents") {
items(contents, &mut out);
}
}
}
out
}
/// The stored flags of every `ADBE Vector Graphic - Fill` group in a file.
fn fill_flags(bytes: &[u8]) -> Vec<u32> {
fn walk(g: &AepGroup<'_, '_>, out: &mut Vec<u32>, depth: usize) {
if depth > 16 {
return;
}
for e in g.entries() {
if let PropNode::Group(sub) = e.node {
if e.match_name == "ADBE Vector Graphic - Fill" {
out.push(sub.flags().unwrap_or(99));
}
walk(&sub, out, depth + 1);
}
}
}
let f = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&f).expect("project");
let mut out = Vec::new();
for item in view.all_items() {
let Some(c) = item.comp() else { continue };
for l in c.layers() {
if let Some(root) = l.properties() {
walk(&root, &mut out, 0);
}
}
}
out
}
#[test]
fn a_switched_off_fill_stays_off() {
let bytes = fixture!("986-shape-fill-switched-off-green.aep");
assert_eq!(fill_flags(&bytes), [0]);
let p = import_bytes(&bytes);
let s = switches(&p);
assert!(s.contains(&("fill".to_string(), false)), "{s:?}");
assert!(s.iter().filter(|(id, _)| id != "fill").all(|(_, on)| *on), "{s:?}");
let r = export_all(&p);
assert!(r.report.losses.is_empty(), "{:?}", r.report.losses);
assert_eq!(fill_flags(&r.bytes), [0]);
assert_eq!(switches(&import_bytes(&r.bytes)), s);
// Switched on again, it is written with the bit set (987).
let mut q = p.clone();
let ids: Vec<_> = q.comps().map(|(i, _)| *i).collect();
for id in ids {
if let Some(mut c) = q.comp(id).cloned() {
for l in &mut c.layers {
fn on(g: &mut PropGroup) {
g.enabled = true;
for c in &mut g.children {
if let Node::Group(s) = c {
on(s);
}
}
}
if let Some(contents) = l.props.sub_mut("contents") {
on(contents);
}
}
if let Some(it) = q.item_mut(id) {
it.kind = effectcraft_project::ItemKind::Comp(std::sync::Arc::new(c));
}
}
}
assert_eq!(fill_flags(&export_all(&q).bytes), [1]);
}
+127
View File
@@ -0,0 +1,127 @@
//! Keys on time-stretched layers (cases 641-643): the key times count source time in the layer's
//! time scale (the composition's x stretch at 100 % or more, the composition's below).
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::{PropNode, parse};
use effectcraft_keyframe::{Interp, Value};
use effectcraft_project::{LayerSource, Project};
use effectcraft_time::FrameRate;
/// (stretch numerator, denominator, start units, Position time scale, key times) of the first
/// layer of the first composition.
fn position_keys(bytes: &[u8]) -> (i32, u32, i32, u32, Vec<i32>) {
let file = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let layer = comp.layers().next().expect("layer");
let h = layer.header().expect("header");
let Some(PropNode::Property(pos)) = layer.properties().and_then(|g| g.find(&["ADBE Transform Group", "ADBE Position"])) else { panic!("position") };
let times = pos.keys().expect("keys").keyframes().filter_map(|k| k.time_units()).collect();
(h.stretch, h.stretch_den, h.start.num as i32, pos.time_scale().expect("time scale"), times)
}
fn reimport(bytes: &[u8]) -> Project {
let mut p = Project::default();
let none = |_: &str| false;
effectcraft_aep::import::import(
&mut p,
bytes,
&effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) },
)
.expect("import");
p
}
#[test]
fn keys_on_stretched_layers_are_written_as_after_effects_stores_them() {
for name in ["641-stretch-200-keys-position-1s-2s.aep", "642-stretch-50-keys-position-1s-2s.aep", "643-stretch-200-start-1-keys-position-2s-3s.aep"] {
let bytes = fixture!(name);
let p1 = reimport(&bytes);
let r = export_all(&p1);
assert!(r.report.is_lossless(), "{name}: {:?}", r.report.losses);
assert_eq!(position_keys(&r.bytes), position_keys(&bytes), "{name}");
// A second import gives the same layer and keys.
let p2 = reimport(&r.bytes);
let layer = |p: &Project| p.comps().next().map(|(_, c)| c.layers[0].clone()).expect("layer");
let (a, b) = (layer(&p1), layer(&p2));
assert_eq!((a.stretch, a.start_time, a.in_point, a.out_point), (b.stretch, b.start_time, b.in_point, b.out_point), "{name}");
let keys =
|l: &effectcraft_project::Layer| l.props.prop("transform/position").map(|p| p.keys.iter().map(|k| (k.time, k.value.clone())).collect::<Vec<_>>());
assert_eq!(keys(&a), keys(&b), "{name}");
}
// What the cases hold (MANIFEST): 200 % keys at comp 1 s / 2 s = units 25 600 / 51 200 at
// time scale 51 200; 50 % at time scale 25 600 = 51 200 / 102 400.
assert_eq!(position_keys(&fixture!("641-stretch-200-keys-position-1s-2s.aep")), (2, 1, 0, 51200, vec![25600, 51200]));
assert_eq!(position_keys(&fixture!("642-stretch-50-keys-position-1s-2s.aep")), (1, 2, 0, 25600, vec![51200, 102400]));
}
#[test]
fn a_comp_time_survives_any_stretch() {
// Keys built in code on a 150 % layer starting at 0.4 s: the key at layer time 2 s is at
// comp 0.4 + 3 s, in source units 2 x 38 400.
let mut p = Project::default();
let c = add_comp(&mut p, "C", 640, 360, FrameRate::new(25, 1), 10.0, None);
let s = add_solid(&mut p, "S", 100, 100, [1.0, 0.0, 0.0], None);
add_layer(&mut p, c, "S", LayerSource::Solid { item: s }, (100, 100));
with_layer(&mut p, c, 0, |l| {
l.stretch = 150.0;
l.start_time = secs(0.4);
let pos = l.props.prop_mut("transform/position").expect("pos");
pos.keys = vec![key(1.0, Value::Vec3([0.0, 0.0, 0.0])), key(2.0, Value::Vec3([100.0, 0.0, 0.0]))];
});
// The in point (comp 0 s) is 0.4 s before the start: -10 240 units, -6 826.67 in source time
// at 150 %, which the format cannot hold. It is rounded, and the rounding is reported.
let r = export_all(&p);
assert_eq!(r.report.count(LossCategory::RoundedTimes), 1, "{:?}", r.report.losses);
let in_point = |p: &Project| p.comps().next().map(|(_, c)| c.layers[0].in_point.seconds()).expect("layer");
let moved = (in_point(&reimport(&r.bytes)) - in_point(&p)).abs();
assert!(moved > 0.0 && moved < 1.5 / 25_600.0, "{moved}");
// With the in point at the start, nothing is rounded.
with_layer(&mut p, c, 0, |l| l.in_point = l.start_time);
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
let (n, d, _, ts, times) = position_keys(&r.bytes);
assert_eq!((n, d, ts, times), (3, 2, 38400, vec![38400, 76800]));
// Bezier ease on a stretched layer is written but reported (its speed unit is not sampled).
with_layer(&mut p, c, 0, |l| {
let pos = l.props.prop_mut("transform/position").expect("pos");
pos.keys[0].out_interp = Interp::Bezier;
});
assert_eq!(export_all(&p).report.count(LossCategory::ApproximatedKeyframes), 1);
assert_eq!(export_all(&p).report.count(LossCategory::TimeStretch), 0);
}
/// (stretch numerator, denominator, start, in, out as stored; Opacity time scale and key times).
fn reversed_header(bytes: &[u8]) -> (i32, u32, i64, i64, i64, u32, Vec<i32>) {
let file = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let comp = view.all_items().into_iter().find_map(|i| i.comp()).expect("comp");
let layer = comp.layers().next().expect("layer");
let h = layer.header().expect("header");
let (ts, times) = match layer.properties().and_then(|g| g.find(&["ADBE Transform Group", "ADBE Opacity"])) {
Some(PropNode::Property(p)) if p.is_animated() => {
(p.time_scale().unwrap_or(0), p.keys().expect("keys").keyframes().filter_map(|k| k.time_units()).collect())
}
_ => (0, Vec::new()),
};
(h.stretch, h.stretch_den, h.start.num, h.in_relative.num, h.out_relative.num, ts, times)
}
#[test]
fn a_reversed_layer_is_written_as_after_effects_stores_it() {
// 981-983: a negative stretch numerator, the start at the later end, in / out relative in
// source time, keys in the composition's time scale.
for name in ["981-layer-stretch-minus100-start5.aep", "982-layer-stretch-minus100-opacity-keys.aep", "983-layer-stretch-minus50-opacity-keys.aep"] {
let bytes = fixture!(name);
let p1 = reimport(&bytes);
let l = p1.comps().next().map(|(_, c)| c.layers[0].clone()).expect("layer");
assert!(l.stretch < 0.0 && l.in_point < l.out_point, "{name}: {} {:?} {:?}", l.stretch, l.in_point, l.out_point);
let r = export_all(&p1);
assert!(r.report.is_lossless(), "{name}: {:?}", r.report.losses);
assert_eq!(reversed_header(&r.bytes), reversed_header(&bytes), "{name}");
let p2 = reimport(&r.bytes);
let m = p2.comps().next().map(|(_, c)| c.layers[0].clone()).expect("layer");
assert_eq!((l.stretch, l.start_time, l.in_point, l.out_point), (m.stretch, m.start_time, m.in_point, m.out_point), "{name}");
}
}
+224
View File
@@ -0,0 +1,224 @@
//! Layer styles: fixture -> import -> export -> import keeps every style value, the written
//! `ADBE Layer Styles` group is After Effects' own (951-979), and styles made in EffectCraft are
//! written with After Effects' defaults in mind.
use crate::export::helpers::{add_comp, add_layer, add_solid, export_all, key, with_comp, with_layer};
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{PropNode, parse};
use effectcraft_keyframe::Value;
use effectcraft_project::build::Ids;
use effectcraft_project::styles::{self as st, GROUP};
use effectcraft_project::{Expression, Layer, LayerSource, Project, PropGroup};
use effectcraft_time::FrameRate;
fn import_bytes(bytes: &[u8]) -> (Project, Vec<String>) {
let mut p = Project::default();
let none = |_: &str| false;
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&none) };
let r = import(&mut p, bytes, &opts).expect("import");
let losses = r.report.losses.iter().flat_map(|l| l.details.clone()).collect();
(p, losses)
}
fn layer<'p>(p: &'p Project, name: &str) -> &'p Layer {
p.comps().flat_map(|(_, c)| c.layers.iter()).find(|l| l.name == name).expect("layer")
}
/// Every style parameter as (style, param, value, keys, expression).
fn values(g: &PropGroup) -> Vec<(String, String, Value, usize, Option<Expression>)> {
let mut out = Vec::new();
for s in g.groups() {
for sub in std::iter::once(s).chain(s.groups()) {
for n in &sub.children {
if let Some(p) = n.as_prop() {
// A keyed property's static value means nothing (the importer takes the first key's).
let v = p.keys.first().map_or_else(|| p.value.clone(), |k| k.value.clone());
out.push((s.match_id.clone(), p.match_id.clone(), v, p.keys.len(), p.expr.clone()));
}
}
}
}
out
}
/// The stored `ADBE Layer Styles` group of the first layer with a style applied.
fn stored_group(bytes: &[u8]) -> Vec<u8> {
let f = parse(bytes).expect("parse");
let project = effectcraft_aep::Project::new(&f).expect("project");
for item in project.all_items() {
let Some(c) = item.comp() else { continue };
for l in c.layers() {
if let Some(PropNode::Group(g)) = l.properties().and_then(|p| p.get("ADBE Layer Styles"))
&& g.flags() == Some(1)
{
// As far as the exporter writes records (`decoded`).
let mut f2 = effectcraft_aep::AepFile {
chunks: vec![crate::export::helpers::decoded(&g.chunk().clone().into_owned())],
trailer: std::borrow::Cow::Owned(vec![]),
};
f2.trailer = std::borrow::Cow::Owned(vec![]);
return effectcraft_aep::write(&f2).expect("write");
}
}
}
panic!("no layer with a style");
}
const CASES: &[&str] = &[
"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",
"988-style-drop-shadow-switched-off.aep",
];
#[test]
fn fixtures_round_trip_without_losses() {
for name in CASES {
let bytes = fixture!(name);
let (p, losses) = import_bytes(&bytes);
assert!(losses.is_empty(), "{name}: {losses:?}");
let r = export_all(&p);
assert!(r.report.losses.is_empty(), "{name}: {:?}", r.report.losses);
assert!(r.report.exported.layer_styles > 0, "{name}");
let (q, losses) = import_bytes(&r.bytes);
assert!(losses.is_empty(), "{name} re-import: {losses:?}");
let (a, b) = (layer(&p, "B"), layer(&q, "B"));
assert_eq!(values(a.props.sub(GROUP).expect("styles")), values(b.props.sub(GROUP).expect("styles")), "{name}");
// The written group is the one After Effects saved, in its decoded bytes.
assert_eq!(stored_group(&bytes), stored_group(&r.bytes), "{name}: stored group differs");
let (ca, cb) = (p.comps().next().expect("comp").1, q.comps().next().expect("comp").1);
assert_eq!(ca.global_light, cb.global_light, "{name}");
}
}
#[test]
fn a_style_made_here_is_written_with_after_effects_defaults_in_mind() {
let mut p = Project::default();
let comp = add_comp(&mut p, "C", 400, 300, FrameRate::FPS_25, 4.0, None);
let s = add_solid(&mut p, "S", 200, 100, [0.2, 0.4, 0.8], None);
add_layer(&mut p, comp, "S", LayerSource::Solid { item: s }, (200, 100));
let gl = p.comp(comp).expect("comp").global_light.clone();
let mut next = p.next_id;
with_layer(&mut p, comp, 0, |l| {
let mut ids = Ids(&mut next);
st::add_style(l, &mut ids, "dropShadow", &gl, true);
st::add_style(l, &mut ids, "stroke", &gl, true);
let g = l.props.sub_mut(GROUP).expect("styles");
let ds = g.sub_mut("dropShadow").expect("ds");
ds.get_mut("opacity").expect("opacity").keys = vec![key(0.0, Value::Scalar(100.0)), key(2.0, Value::Scalar(20.0))];
ds.get_mut("color").expect("color").expr = Some(Expression { text: "[1, 0, 0, 1]".into(), enabled: true });
let stroke = g.sub_mut("stroke").expect("stroke");
stroke.get_mut("position").expect("position").value = Value::Enum(2);
stroke.get_mut("blendMode").expect("mode").value = Value::Enum(23);
});
p.next_id = next;
with_comp(&mut p, comp, |c| st::set_global_light(c, Some(60.0), None, effectcraft_time::Tick::ZERO));
let r = export_all(&p);
assert!(r.report.losses.is_empty(), "{:?}", r.report.losses);
let (q, losses) = import_bytes(&r.bytes);
assert!(losses.is_empty(), "{losses:?}");
let (a, b) = (layer(&p, "S"), layer(&q, "S"));
assert_eq!(values(a.props.sub(GROUP).expect("styles")), values(b.props.sub(GROUP).expect("styles")));
// EffectCraft's Use Global Light default (on) differs from After Effects' (off): written.
assert_eq!(b.props.sub(GROUP).and_then(|g| g.sub("dropShadow")).and_then(|g| g.get("useGlobalLight")).map(|p| p.value.clone()), Some(Value::Bool(true)));
assert_eq!(q.comps().next().expect("comp").1.global_light.angle.value, Value::Scalar(60.0));
}
#[test]
fn what_is_not_written_is_reported() {
let mut p = Project::default();
let comp = add_comp(&mut p, "C", 400, 300, FrameRate::FPS_25, 4.0, None);
let s = add_solid(&mut p, "S", 200, 100, [0.2, 0.4, 0.8], None);
add_layer(&mut p, comp, "S", LayerSource::Solid { item: s }, (200, 100));
let gl = p.comp(comp).expect("comp").global_light.clone();
let mut next = p.next_id;
with_layer(&mut p, comp, 0, |l| {
let mut ids = Ids(&mut next);
st::add_style(l, &mut ids, "satin", &gl, false);
st::add_style(l, &mut ids, "gradientOverlay", &gl, true);
let g = l.props.sub_mut(GROUP).expect("styles");
let go = g.sub_mut("gradientOverlay").expect("go");
if let Some(Value::Gradient(gr)) = go.get_mut("colors").map(|p| &mut p.value) {
gr.colors[0].1 = [1.0, 0.0, 0.0, 1.0];
}
go.get_mut("style").expect("style").keys = vec![key(0.0, Value::Enum(1)), key(1.0, Value::Enum(2))];
let adv = g.sub_mut(st::BLENDING).and_then(|b| b.sub_mut("advancedBlending")).expect("adv");
adv.get_mut("knockout").expect("knockout").value = Value::Enum(1);
});
p.next_id = next;
let r = export_all(&p);
let lines: Vec<String> = r.report.losses.iter().flat_map(|l| l.details.clone()).collect();
let has = |s: &str| lines.iter().any(|l| l.contains(s));
assert!(has("gradientFill/gradient"), "{lines:?}");
assert!(has("gradientFill/type: keys"), "{lines:?}");
assert!(has("Knockout"), "{lines:?}");
let (q, _) = import_bytes(&r.bytes);
let g = layer(&q, "S").props.sub(GROUP).expect("styles");
// A switched-off style is written switched off (988).
assert!(g.sub("satin").is_some_and(|s| !s.enabled) && g.sub("gradientOverlay").is_some_and(|s| s.enabled));
}
#[test]
fn styles_on_every_layer_kind_that_takes_them() {
let mut p = Project::default();
let comp = add_comp(&mut p, "C", 400, 300, FrameRate::FPS_25, 4.0, None);
let s = add_solid(&mut p, "S", 200, 100, [0.2, 0.4, 0.8], None);
add_layer(&mut p, comp, "S", LayerSource::Solid { item: s }, (200, 100));
add_layer(&mut p, comp, "Shape", LayerSource::Shape, (400, 300));
add_layer(&mut p, comp, "Text", LayerSource::Text, (400, 300));
add_layer(&mut p, comp, "Null", LayerSource::Null, (100, 100));
let gl = p.comp(comp).expect("comp").global_light.clone();
let mut next = p.next_id;
for i in 0..4 {
with_layer(&mut p, comp, i, |l| {
st::add_style(l, &mut Ids(&mut next), "stroke", &gl, true);
});
}
p.next_id = next;
let r = export_all(&p);
let (q, _) = import_bytes(&r.bytes);
for name in ["S", "Shape", "Text"] {
assert!(layer(&q, name).props.sub(GROUP).and_then(|g| g.sub("stroke")).is_some(), "{name}");
}
}
/// An expression on a style popup that After Effects stores in another order (Inner Glow Source:
/// Edge is 1 there, Center 1 here) means something else there: reported, and a strict export
/// refuses. A popup in the same order stays lossless (review finding).
#[test]
fn a_style_popup_expression_is_reported_only_when_the_items_are_stored_in_another_order() {
let build = |param: &str| {
let mut p = Project::default();
let comp = add_comp(&mut p, "C", 400, 300, FrameRate::FPS_25, 4.0, None);
let s = add_solid(&mut p, "S", 200, 100, [0.2, 0.4, 0.8], None);
add_layer(&mut p, comp, "S", LayerSource::Solid { item: s }, (200, 100));
let gl = p.comp(comp).expect("comp").global_light.clone();
let mut next = p.next_id;
with_layer(&mut p, comp, 0, |l| {
let mut ids = Ids(&mut next);
st::add_style(l, &mut ids, "innerGlow", &gl, true);
let g = l.props.sub_mut(GROUP).expect("styles");
let glow = g.sub_mut("innerGlow").expect("glow");
if let Some(prop) = glow.get_mut(param) {
prop.expr = Some(Expression { text: "1".into(), enabled: true });
} else {
panic!("no {param}");
}
});
p.next_id = next;
p
};
let strict = |p: &Project| effectcraft_aep::export::export(p, &effectcraft_aep::export::ExportOptions { allow_losses: false }).is_ok();
let reversed = build("source");
let r = export_all(&reversed);
assert_eq!(r.report.count(effectcraft_aep::export::LossCategory::LayerStyles), 1, "{:?}", r.report.losses);
assert!(!strict(&reversed));
let same = build("technique");
assert_eq!(export_all(&same).report.count(effectcraft_aep::export::LossCategory::LayerStyles), 0);
assert!(strict(&same));
}
+623
View File
@@ -0,0 +1,623 @@
//! Text layers: every text fixture is imported, exported and parsed back with `effectcraft-aep`;
//! the text document (text, paragraphs, style runs, fonts, box) must equal the one After Effects
//! wrote for every decoded field, and a second import gives the same Source Text. Documents built
//! in code check line breaks, runs, fonts, and what is reported.
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_aep::import::{ImportOptions, import};
use effectcraft_aep::{Caps, Justification, TextDocument, parse};
use effectcraft_keyframe::Value;
use effectcraft_keyframe::text_doc::{BaselineOption, CharStyle, Justify, ParaStyle, StyleRun, TextDoc};
use effectcraft_project::{ItemId, ItemKind, LayerSource, Project};
use effectcraft_time::FrameRate;
fn text_fixtures() -> Option<Vec<String>> {
Some({
let mut v: Vec<String> = crate::common::names("aep")?.into_iter().filter(|n| n.ends_with(".aep") && n.contains("-text-")).collect();
v.sort();
v
})
}
fn reimport(bytes: &[u8]) -> Project {
let mut p = Project::default();
let none = |_: &str| false;
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&none) };
import(&mut p, bytes, &opts).expect("import");
p
}
/// The text documents of all text layers, by composition name and layer index.
fn documents(bytes: &[u8]) -> Vec<((String, usize), TextDocument)> {
let file = parse(bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let mut out = Vec::new();
for item in view.all_items() {
let Some(comp) = item.comp() else { continue };
for (i, layer) in comp.layers().enumerate() {
if let Some(d) = layer.text_document() {
out.push(((item.display_name().unwrap_or_default(), i), d));
}
}
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-4
}
/// The decoded fields of two documents are equal (`font_of` resolves the font indices).
fn same_doc(a: &TextDocument, b: &TextDocument, w: &str) {
// U+0003 is imported as a paragraph break and written as one (386: the same layout).
assert_eq!(a.raw_text.replace('\u{3}', "\r"), b.raw_text, "{w}");
let paras = |d: &TextDocument| -> Vec<(usize, Justification)> { d.paragraphs.iter().map(|p| (p.length, p.justification)).collect() };
assert_eq!(paras(a), paras(b), "{w}");
assert_eq!(a.style_runs.len(), b.style_runs.len(), "{w}: style runs");
for (x, y) in a.style_runs.iter().zip(&b.style_runs) {
assert_eq!(x.length, y.length, "{w}");
assert_eq!(a.font_of(x), b.font_of(y), "{w}");
assert!(close(x.font_size, y.font_size), "{w}: size {} {}", x.font_size, y.font_size);
assert!((1..4).all(|i| close(x.fill_argb[i], y.fill_argb[i])), "{w}: fill {:?} {:?}", x.fill_argb, y.fill_argb);
assert!(close(x.tracking, y.tracking), "{w}: tracking");
assert_eq!((x.faux_bold, x.faux_italic, x.caps, x.auto_leading), (y.faux_bold, y.faux_italic, y.caps, y.auto_leading), "{w}");
if !x.auto_leading {
assert_eq!(x.leading.map(|l| (l * 1e4).round()), y.leading.map(|l| (l * 1e4).round()), "{w}: leading");
}
}
let bx = |d: &TextDocument| d.text_box.map(|t| [t.x, t.y, t.width, t.height]);
match (bx(a), bx(b)) {
(None, None) => {}
(Some(p), Some(q)) => assert!(p.iter().zip(q).all(|(u, v)| close(*u, v)), "{w}: box {p:?} {q:?}"),
other => panic!("{w}: box {other:?}"),
}
}
fn source_text(p: &Project) -> Vec<TextDoc> {
let mut v = Vec::new();
for item in p.items.values() {
let ItemKind::Comp(c) = &item.kind else { continue };
for l in &c.layers {
if let Some(Value::Text(d)) = l.props.prop("text/sourceText").map(|s| &s.value) {
v.push((**d).clone());
}
}
}
v.sort_by(|a, b| a.text.cmp(&b.text));
v
}
#[test]
fn every_text_fixture_is_written_with_its_document() {
let names = skip!(text_fixtures());
assert!(names.len() >= 15, "{names:?}");
for name in &names {
let bytes = fixture!(name);
let p1 = reimport(&bytes);
let r = export_all(&p1);
// Text animators and vertical text are imported but not written: the only text losses
// allowed.
let animators = r
.report
.losses
.iter()
.filter(|l| l.category == LossCategory::TextLayers)
.flat_map(|l| &l.details)
.filter(|d| d.contains("text animator") || d.contains("vertical text"))
.count();
assert_eq!(r.report.count(LossCategory::TextLayers), animators, "{name}: {:?}", r.report.losses);
let (a, b) = (documents(&bytes), documents(&r.bytes));
assert_eq!(a.len(), b.len(), "{name}");
for ((ka, da), (kb, db)) in a.iter().zip(&b) {
assert_eq!(ka.0, kb.0, "{name}");
same_doc(da, db, name);
}
// The container is consistent and a second import gives the same Source Text.
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes, "{name}");
let p2 = reimport(&r.bytes);
// Vertical text comes back horizontal (reported above).
let horizontal = |v: Vec<TextDoc>| v.into_iter().map(|d| TextDoc { vertical: false, ..d }).collect::<Vec<_>>();
assert_eq!(horizontal(source_text(&p1)), horizontal(source_text(&p2)), "{name}");
}
}
fn style(font: &str, size: f64) -> CharStyle {
CharStyle { font: font.into(), style: "Regular".into(), size, leading: Some(size * 1.2), ..CharStyle::default() }
}
fn text_project(docs: Vec<TextDoc>) -> (Project, ItemId) {
let mut p = Project::default();
let c = add_comp(&mut p, "C", 1920, 1080, FrameRate::new(25, 1), 5.0, None);
for (i, d) in docs.into_iter().enumerate() {
add_layer(&mut p, c, &format!("T{i}"), LayerSource::Text, (1920, 1080));
with_layer(&mut p, c, 0, |l| {
if let Some(st) = l.props.prop_mut("text/sourceText") {
st.value = Value::Text(Box::new(d));
}
});
}
(p, c)
}
#[test]
fn documents_built_in_code_are_written_as_their_fields() {
let mut runs = TextDoc::plain("Red\r\nBlue\nX");
runs.set_runs(vec![
StyleRun { len: 5, style: CharStyle { fill: [1.0, 0.0, 0.0, 1.0], tracking: 25.0, ..style("ArialMT", 50.0) } },
StyleRun { len: 6, style: CharStyle { fill: [0.0, 0.0, 1.0, 1.0], faux_bold: true, small_caps: true, leading: None, ..style("Georgia", 70.0) } },
]);
runs.set_paras(vec![
ParaStyle { justify: Justify::Center, ..runs.base_para() },
ParaStyle { justify: Justify::Right, ..runs.base_para() },
ParaStyle { justify: Justify::Left, ..runs.base_para() },
]);
let mut boxed = TextDoc::plain("In a box");
boxed.set_runs(vec![StyleRun { len: 8, style: style("TimesNewRomanPSMT", 30.0) }]);
boxed.box_size = Some([300.0, 120.0]);
boxed.box_pos = [-150.0, -60.0];
let empty = TextDoc::plain("");
let (p, _) = text_project(vec![runs, boxed, empty]);
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
assert_eq!(r.report.exported.text_layers, 3);
let docs = documents(&r.bytes);
let by_text = |t: &str| docs.iter().map(|(_, d)| d).find(|d| d.raw_text == t).unwrap_or_else(|| panic!("{t}"));
// CRLF and LF are After Effects' CR; the final paragraph ends with one too.
let d = by_text("Red\rBlue\rX\r");
assert_eq!(
d.paragraphs.iter().map(|p| (p.length, p.justification)).collect::<Vec<_>>(),
vec![(4, Justification::Center), (5, Justification::Right), (2, Justification::Left)]
);
// Runs in After Effects' characters: "Red\r" + 'B' of the first style (the CRLF counted
// once), then "lue\rX\r".
let runs: Vec<_> = d.style_runs.iter().map(|s| (s.length, d.font_of(s).map(str::to_string), s.font_size, s.faux_bold, s.caps, s.auto_leading)).collect();
assert_eq!(runs, vec![(4, Some("ArialMT".into()), 50.0, false, Caps::Normal, false), (7, Some("Georgia".into()), 70.0, true, Caps::Small, true)]);
assert!(close(d.style_runs[0].tracking, 25.0) && close(d.style_runs[0].fill_argb[1], 1.0) && close(d.style_runs[1].fill_argb[3], 1.0));
// The prototype's own fonts keep their places; new ones are appended.
assert_eq!(d.fonts.first().map(String::as_str), Some("TimesNewRomanPSMT"));
let b = by_text("In a box\r");
let tb = b.text_box.expect("box");
assert_eq!([tb.x, tb.y, tb.width, tb.height], [-150.0, -60.0, 300.0, 120.0]);
let e = by_text("\r");
assert_eq!(e.style_runs.iter().map(|s| s.length).sum::<usize>(), 1);
// A text layer named after its text stores no name.
let (p2, _) = text_project(vec![TextDoc::plain("Named")]);
let mut p2 = p2;
let c = p2.items.values().find(|i| i.name == "C").map(|i| i.id).expect("C");
with_layer(&mut p2, c, 0, |l| l.name = "Named".into());
let r2 = export_all(&p2);
let file = parse(&r2.bytes).expect("parse");
let view = effectcraft_aep::Project::new(&file).expect("project");
let layer = view.all_items().into_iter().find_map(|i| i.comp()).and_then(|c| c.layers().next()).expect("layer");
assert_eq!(layer.name(), None);
assert_eq!(layer.header().map(|h| h.layer_type), Some(effectcraft_aep::LayerType::Text));
}
#[test]
fn what_a_text_document_cannot_hold_is_reported() {
let mut d = TextDoc::plain("x");
d.set_runs(vec![StyleRun { len: 1, style: CharStyle { apply_stroke: true, stroke_width: 3.0, h_scale: 80.0, ..style("ArialMT", 40.0) } }]);
d.set_paras(vec![ParaStyle { justify: Justify::JustifyAll, indent_left: 10.0, ..d.base_para() }]);
d.vertical = true;
let (mut p, c) = text_project(vec![d]);
with_layer(&mut p, c, 0, |l| {
if let Some(st) = l.props.prop_mut("text/sourceText") {
st.keys = vec![key(0.0, st.value.clone()), key(1.0, Value::Text(Box::new(TextDoc::plain("y"))))];
}
});
let r = export_all(&p);
// Vertical text and Source Text keys (stroke, scale, justification and indents are written).
assert_eq!(r.report.count(LossCategory::TextLayers), 2, "{:?}", r.report.losses);
// A 3D text layer is written; only per-character 3D is reported.
let (mut p3, c3) = text_project(vec![TextDoc::plain("3D")]);
with_layer(&mut p3, c3, 0, |l| l.switches.three_d = true);
assert_eq!(export_all(&p3).report.count(LossCategory::ThreeD), 0);
with_layer(&mut p3, c3, 0, |l| {
if let Some(pc) = l.props.prop_mut("text/perChar3d") {
pc.value = Value::Bool(true);
}
});
assert_eq!(export_all(&p3).report.count(LossCategory::ThreeD), 1);
assert_eq!(r.report.exported.text_layers, 1);
}
#[test]
fn hostile_text_never_panics() {
let long: String = "ab\r".repeat(50_000);
let mut nan = TextDoc::plain("nan");
nan.set_runs(vec![StyleRun {
len: 3,
style: CharStyle { size: f64::NAN, tracking: f64::INFINITY, leading: Some(f64::NAN), fill: [f32::NAN, 2.0, -1.0, 1.0], ..style("", 10.0) },
}]);
let mut odd = TextDoc::plain("()\\ \u{3} \u{1F600} ünï");
odd.box_size = Some([f64::NAN, 1e300]);
odd.box_pos = [f64::INFINITY, -1e300];
// Runs that do not cover the text, or cover more.
let mut short = TextDoc::plain("short text");
short.runs = vec![StyleRun { len: 2, style: style("ArialMT", 20.0) }];
let mut over = TextDoc::plain("ab");
over.runs = vec![StyleRun { len: 1000, style: style("ArialMT", 20.0) }, StyleRun { len: usize::MAX, style: style("ArialMT", 20.0) }];
let mut max = TextDoc::plain("max");
max.runs = vec![StyleRun { len: usize::MAX, style: style("ArialMT", 20.0) }];
max.paragraphs = vec![effectcraft_keyframe::text_doc::ParaStyle::default(); 3];
let (p, _) = text_project(vec![TextDoc::plain(&long), nan, odd, short, over, max]);
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
let _ = reimport(&r.bytes);
}
#[test]
fn the_baseline_option_is_written_into_style_slot_13() {
// 526-528: slot /13 is 1 superscript (After Effects' scripted default, also in the prototypes),
// 0 normal, 2 subscript; normal text written as 1 is drawn by After Effects at 58.3 % size.
let doc = |b: BaselineOption| {
let mut d = TextDoc::plain("HHHH");
d.set_runs(vec![StyleRun { len: 4, style: CharStyle { baseline: b, ..style("ArialMT", 100.0) } }]);
d
};
for (b, slot_differs) in [(BaselineOption::Normal, true), (BaselineOption::Superscript, false), (BaselineOption::Subscript, true)] {
let (p, _) = text_project(vec![doc(b)]);
let r = export_all(&p);
assert!(r.report.is_lossless(), "{b:?}: {:?}", r.report.losses);
let docs = documents(&r.bytes);
let d = &docs.first().expect("doc").1;
// The reader decodes /13 now; the scripted default (also in the prototypes) is 1.
assert!(d.undecoded_style_fields.iter().all(|f| f != "13"), "{b:?}: {:?}", d.undecoded_style_fields);
let _ = slot_differs;
// A second import gives the same baseline option back (normal stays normal).
let back = source_text(&reimport(&r.bytes));
let got = back.first().and_then(|t| t.runs().first().map(|r| r.style.baseline));
assert_eq!(got, Some(b), "{b:?}");
let text = String::from_utf8_lossy(&r.bytes).to_string();
let want = match b {
BaselineOption::Normal => "/13 0",
BaselineOption::Superscript => "/13 1",
BaselineOption::Subscript => "/13 2",
};
assert!(text.contains(want), "{b:?}");
}
}
#[test]
fn superscript_stays_superscript_and_normal_stays_normal() {
// 526 and 113 are superscript (the scripted default), 527 normal, 528 subscript: the merged
// importer reads /13 and the exporter writes it back, so a round trip keeps each one.
for (name, want) in [
("113-text-Hello-size60-fillorange.aep", BaselineOption::Superscript),
("526-text-point-HHHH-default.aep", BaselineOption::Superscript),
("527-text-point-HHHH-baseline-normal.aep", BaselineOption::Normal),
("528-text-point-HHHH-baseline-subscript.aep", BaselineOption::Subscript),
] {
let p1 = reimport(&fixture!(name));
let baselines = |p: &Project| source_text(p).iter().flat_map(|d| d.runs().into_iter().map(|r| r.style.baseline)).collect::<Vec<_>>();
let b1 = baselines(&p1);
assert!(!b1.is_empty() && b1.iter().all(|b| *b == want), "{name}: {b1:?}");
let r = export_all(&p1);
let p2 = reimport(&r.bytes);
assert_eq!(baselines(&p2), b1, "{name}");
let docs = documents(&r.bytes);
let stored = match want {
BaselineOption::Normal => effectcraft_aep::FontBaseline::Normal,
BaselineOption::Superscript => effectcraft_aep::FontBaseline::Superscript,
BaselineOption::Subscript => effectcraft_aep::FontBaseline::Subscript,
};
assert!(docs.iter().flat_map(|(_, d)| &d.style_runs).all(|s| s.baseline == stored), "{name}");
}
}
#[test]
fn a_text_made_in_effectcraft_is_written_with_the_every_line_composer() {
// A plain box text without paragraph entries uses the document's settings: EffectCraft's
// default composer is every-line, which After Effects reads back as such (t6).
let mut d = TextDoc::plain("One two three four five six seven eight\rTwo");
d.set_runs(vec![StyleRun { len: d.text.chars().count(), style: style("ArialMT", 30.0) }]);
d.box_size = Some([300.0, 200.0]);
assert!(d.paragraphs.is_empty());
let (p, _) = text_project(vec![d.clone()]);
let r = export_all(&p);
assert!(r.report.is_lossless(), "{:?}", r.report.losses);
let docs = documents(&r.bytes);
let paras = &docs[0].1.paragraphs;
assert_eq!(paras.len(), 2);
assert!(paras.iter().all(|p| p.every_line_composer && p.direction == 0 && p.justification == Justification::Left), "{paras:?}");
assert_eq!(source_text(&reimport(&r.bytes))[0].para(0).composer, effectcraft_keyframe::text_doc::Composer::EveryLine);
}
#[test]
fn right_to_left_justification_is_stored_relative_to_the_direction() {
// t7: in a right-to-left paragraph After Effects lays code 0 and 3 out flush right and 1 and
// 4 flush left; 2, 5, 6 are the same in both directions.
use effectcraft_keyframe::text_doc::Direction;
let cases = [
(Justify::Left, Justification::Right),
(Justify::Right, Justification::Left),
(Justify::Center, Justification::Center),
(Justify::JustifyLastLeft, Justification::FullRight),
(Justify::JustifyLastRight, Justification::FullLeft),
(Justify::JustifyLastCenter, Justification::FullCenter),
(Justify::JustifyAll, Justification::FullAll),
];
for (rtl, ltr_stored) in [(true, false), (false, true)] {
let docs: Vec<TextDoc> = cases
.iter()
.enumerate()
.map(|(i, (j, _))| {
let mut d = TextDoc::plain(&format!("T{i}"));
d.set_runs(vec![StyleRun { len: 2, style: style("ArialMT", 30.0) }]);
let dir = if rtl { Direction::Rtl } else { Direction::Ltr };
d.set_paras(vec![ParaStyle { justify: *j, direction: dir, ..d.base_para() }]);
d
})
.collect();
let (p, _) = text_project(docs);
let r = export_all(&p);
let written = documents(&r.bytes);
let back = source_text(&reimport(&r.bytes));
for (i, (j, swapped)) in cases.iter().enumerate() {
let stored = written.iter().find(|(_, d)| d.raw_text == format!("T{i}\r")).map(|(_, d)| d.paragraphs[0].justification).unwrap();
let want = if ltr_stored { effectcraft_aep_justification(*j) } else { *swapped };
assert_eq!(stored, want, "rtl {rtl}: {j:?}");
assert_eq!(back[i].para(0).justify, *j, "rtl {rtl}: round trip");
}
}
}
fn effectcraft_aep_justification(j: Justify) -> Justification {
match j {
Justify::Left => Justification::Left,
Justify::Right => Justification::Right,
Justify::Center => Justification::Center,
Justify::JustifyLastLeft => Justification::FullLeft,
Justify::JustifyLastRight => Justification::FullRight,
Justify::JustifyLastCenter => Justification::FullCenter,
Justify::JustifyAll => Justification::FullAll,
}
}
/// Every `(path of match names, record)` below `ADBE Text Animators`, keyed records with the
/// unused ease before the first / after the last key and spatial arc lengths zeroed, and the
/// sequence of match names (the structure).
fn animator_records(bytes: &[u8]) -> (Vec<String>, Vec<(String, Vec<u8>)>) {
fn walk(cs: &[effectcraft_aep::Chunk<'_>], path: &str, inside: bool, names: &mut Vec<String>, out: &mut Vec<(String, Vec<u8>)>) {
for (i, c) in cs.iter().enumerate() {
let Some(name) = c.bytes().filter(|_| c.is(b"tdmn")).map(|b| String::from_utf8_lossy(b.split(|x| *x == 0).next().unwrap_or(b"")).to_string())
else {
// Items, layers and other lists: look inside (a node after a `tdmn` is walked
// with it).
let after_tdmn = i > 0 && cs.get(i - 1).is_some_and(|p| p.is(b"tdmn"));
if !inside && !after_tdmn {
walk(c.children(), path, inside, names, out);
}
continue;
};
let here = inside || name == "ADBE Text Animators";
let key = format!("{path}/{name}");
if here {
names.push(key.clone());
}
let Some(node) = cs.get(i + 1) else { continue };
if here && node.is_list(b"tdbs") {
// In the bytes the exporter writes (`decoded`).
let mut f = effectcraft_aep::AepFile { chunks: vec![crate::export::helpers::decoded(&node.clone().into_owned())], trailer: Default::default() };
if let Some(list) = f.chunks[0].children_mut().iter_mut().find(|k| k.is_list(b"list")) {
let size = list
.child(b"lhd3")
.and_then(|c| c.bytes())
.and_then(|b| b.get(16..20))
.map_or(0, |b| u32::from_be_bytes(b.try_into().unwrap()) as usize);
if let Some(ldat) = list.children_mut().iter_mut().find(|k| k.is(b"ldat"))
&& let effectcraft_aep::Body::Data(d) = &mut ldat.body
{
let mut v = d.to_vec();
let n = v.len();
if size == 48 && n >= 96 {
v[16..32].fill(0);
v[n - 16..n].fill(0);
}
if size >= 104 && size % 8 == 0 && (size - 56) % 24 == 0 {
for r in v.chunks_mut(size) {
r[16..24].fill(0);
}
}
*d = v.into();
}
}
out.push((key.clone(), effectcraft_aep::write(&f).unwrap()));
}
if node.is_list(b"tdgp") {
walk(node.children(), &key, here, names, out);
}
}
}
let f = parse(bytes).expect("parse");
let (mut names, mut out) = (Vec::new(), Vec::new());
walk(&f.chunks, "", false, &mut names, &mut out);
(names, out)
}
#[test]
fn text_animators_are_written_as_after_effects_wrote_them() {
// 114, 579-594, 728: the animators, their properties and range selectors come back with
// After Effects' structure and records.
let mut names: Vec<String> =
fixture_names!("aep").into_iter().filter(|n| n.ends_with(".aep") && (n.contains("textanim") || n.contains("text-animator"))).collect();
names.sort();
assert!(names.len() >= 16, "{names:?}");
let mut compared = 0;
for name in &names {
let bytes = fixture!(name);
let r = export_all(&reimport(&bytes));
assert_eq!(r.report.count(LossCategory::TextLayers), 0, "{name}: {:?}", r.report.losses);
let (mut na, mut ra) = animator_records(&bytes);
let (nb, rb) = animator_records(&r.bytes);
// With Units = Index After Effects keeps the percent range it had before (583); the
// index range is what it uses, the export has only that.
if na.iter().any(|n| n.ends_with("ADBE Text Index Start")) {
na.retain(|n| !n.contains("ADBE Text Percent"));
ra.retain(|(n, _)| !n.contains("ADBE Text Percent"));
}
// A record After Effects writes for a value at its default when another one makes it
// matter (587: Smoothness 100 with Shape Ramp Up): absent = default.
let explicit = |n: &str| n.ends_with("ADBE Text Selector Smoothness") && !nb.iter().any(|m| m == n);
let default_100 = |rec: &[u8]| rec.windows(8).any(|w| w == 100.0f64.to_be_bytes());
let drop: Vec<String> = ra.iter().filter(|(n, rec)| explicit(n) && default_100(rec)).map(|(n, _)| n.clone()).collect();
na.retain(|n| !drop.contains(n));
ra.retain(|(n, _)| !drop.contains(n));
if na != nb {
let short = |v: &[String]| v.iter().map(|s| s.rsplit('/').next().unwrap_or_default().to_string()).collect::<Vec<_>>();
panic!(
"{name}: structure
AE {:?}
out {:?}",
short(&na),
short(&nb)
);
}
for ((ka, a), (kb, b)) in ra.iter().zip(&rb) {
assert_eq!(ka, kb, "{name}");
assert_eq!(a, b, "{name}: {ka}");
compared += 1;
}
assert_eq!(ra.len(), rb.len(), "{name}");
}
assert!(compared >= 30, "{compared}");
}
#[test]
fn hostile_text_animators_never_panic() {
use effectcraft_project::build;
let mut d = TextDoc::plain("Hostile");
d.set_runs(vec![StyleRun { len: 7, style: style("ArialMT", 40.0) }]);
let (mut p, c) = text_project(vec![d]);
let mut next = p.next_id;
{
let mut ids = build::Ids(&mut next);
let mut anims = Vec::new();
for i in 0..300 {
let props: Vec<_> =
["position", "scale", "fillColor", "tracking", "blur"].iter().flat_map(|k| build::text_anim_props(&mut ids, k, false)).collect();
let mut a = build::text_animator(&mut ids, &format!("A{i}"), props);
if let Some(pg) = a.sub_mut("properties") {
pg.get_mut("position").unwrap().value = Value::Vec3([f64::NAN, 1e300, 0.0]);
pg.get_mut("tracking").unwrap().keys = (0..2000).map(|k| key(f64::from(k) * 0.001, Value::Scalar(f64::from(k)))).collect();
pg.get_mut("fillColor").unwrap().keys = vec![key(0.0, Value::Scalar(1.0)), key(1.0, Value::Color([f64::INFINITY, 0.0, 0.0, 1.0]))];
}
if let Some(sels) = a.sub_mut("selectors") {
sels.children.push(build::wiggly_selector(&mut ids, "W").into());
}
anims.push(effectcraft_project::Node::Group(a));
}
with_layer(&mut p, c, 0, |l| l.props.sub_mut("text").unwrap().sub_mut("animators").unwrap().children = anims);
}
p.next_id = next;
let r = export_all(&p);
let file = parse(&r.bytes).expect("parse");
assert_eq!(effectcraft_aep::write(&file).expect("write"), r.bytes);
assert!(r.report.count(LossCategory::TextLayers) >= 300, "{:?}", r.report.losses);
let _ = reimport(&r.bytes);
}
/// A text animator's Fill Color outside 0 to 1 is clamped and reported under text layers, like a
/// shape colour (review finding: the animator path skipped the check); an in-range one is
/// lossless.
#[test]
fn a_text_animator_colour_outside_the_range_is_reported() {
use effectcraft_project::build;
let with_fill = |colour: [f64; 4]| {
let mut d = TextDoc::plain("Glow");
d.set_runs(vec![StyleRun { len: 4, style: style("ArialMT", 40.0) }]);
let (mut p, c) = text_project(vec![d]);
let mut next = p.next_id;
{
let mut ids = build::Ids(&mut next);
let props = build::text_anim_props(&mut ids, "fillColor", false);
let mut a = build::text_animator(&mut ids, "A", props);
if let Some(pg) = a.sub_mut("properties") {
pg.get_mut("fillColor").unwrap().value = Value::Color(colour);
}
with_layer(&mut p, c, 0, |l| l.props.sub_mut("text").unwrap().sub_mut("animators").unwrap().children = vec![effectcraft_project::Node::Group(a)]);
}
p.next_id = next;
p
};
let lost = |p: &Project| {
let r = export_all(p);
r.report
.losses
.iter()
.filter(|l| l.category == LossCategory::TextLayers)
.flat_map(|l| l.details.clone())
.filter(|d| d.contains("outside 0 to 1"))
.count()
};
assert_eq!(lost(&with_fill([0.2, 0.4, 0.6, 1.0])), 0);
assert_eq!(lost(&with_fill([3.0, 0.4, -1.0, 1.0])), 1);
}
/// A text animator's Fill or Stroke Color alpha is reported (After Effects colours have none; the
/// converter wrote them opaque without a word, review finding), for the static value and for keys;
/// the check follows the values that are written: an alpha on the static value of a keyed colour
/// is not reported, an opaque control is lossless.
#[test]
fn a_text_animator_colour_alpha_is_reported_for_the_values_that_are_written() {
use effectcraft_project::build;
for id in ["fillColor", "strokeColor"] {
let make = |value: [f64; 4], keys: Option<([f64; 4], [f64; 4])>| {
let mut d = TextDoc::plain("Glow");
d.set_runs(vec![StyleRun { len: 4, style: style("ArialMT", 40.0) }]);
let (mut p, c) = text_project(vec![d]);
let mut next = p.next_id;
{
let mut ids = build::Ids(&mut next);
let props = build::text_anim_props(&mut ids, id, false);
let mut a = build::text_animator(&mut ids, "A", props);
if let Some(pg) = a.sub_mut("properties") {
let prop = pg.get_mut(id).unwrap();
prop.value = Value::Color(value);
if let Some((k0, k1)) = keys {
prop.keys = vec![key(0.0, Value::Color(k0)), key(1.0, Value::Color(k1))];
}
}
with_layer(&mut p, c, 0, |l| {
l.props.sub_mut("text").unwrap().sub_mut("animators").unwrap().children = vec![effectcraft_project::Node::Group(a)]
});
}
p.next_id = next;
p
};
let alpha_lost = |p: &Project| {
let r = export_all(p);
r.report.losses.iter().filter(|l| l.category == LossCategory::TextLayers).flat_map(|l| l.details.clone()).filter(|d| d.contains("alpha")).count()
};
let strict = |p: &Project| effectcraft_aep::export::export(p, &effectcraft_aep::export::ExportOptions { allow_losses: false }).is_ok();
let opaque = [0.2, 0.4, 0.6, 1.0];
let clear = [0.2, 0.4, 0.6, 0.25];
let control = make(opaque, None);
assert_eq!(alpha_lost(&control), 0, "{id}");
let static_alpha = make(clear, None);
assert_eq!(alpha_lost(&static_alpha), 1, "{id}");
assert!(!strict(&static_alpha), "{id}");
let keyed_alpha = make(opaque, Some((opaque, clear)));
assert_eq!(alpha_lost(&keyed_alpha), 1, "{id}");
// The static value of a keyed colour is not written: its alpha is not reported.
let keyed_opaque = make(clear, Some((opaque, opaque)));
assert_eq!(alpha_lost(&keyed_opaque), 0, "{id}");
}
}
/// Two fonts whose names differ only in bytes a lossy UTF-8 conversion turns into the same text
/// (U+4E80 and U+4E81 both read as `N` + U+FFFD) get entries of their own (review finding).
#[test]
fn non_ascii_font_names_keep_their_own_font_entries() {
let mut d = TextDoc::plain("ab");
d.set_runs(vec![StyleRun { len: 1, style: style("\u{4e80}", 40.0) }, StyleRun { len: 1, style: style("\u{4e81}", 40.0) }]);
let (p, _) = text_project(vec![d]);
let r = export_all(&p);
let docs = documents(&r.bytes);
let (_, doc) = docs.first().expect("document");
assert!(doc.fonts.iter().any(|f| f == "\u{4e80}") && doc.fonts.iter().any(|f| f == "\u{4e81}"), "{:?}", doc.fonts);
}
+2
View File
@@ -8,6 +8,7 @@ mod blend_modes;
mod cameras;
mod cases;
mod combined;
mod cryptomatte;
mod ease_round2;
mod effects;
mod effects_batch5;
@@ -28,3 +29,4 @@ mod synthetic;
mod text;
mod text_anim;
mod timing;
mod versions;
+449
View File
@@ -0,0 +1,449 @@
//! The Cryptomatte plug-in (match name `Cryptomatte`) arrives as EffectCraft's Cryptomatte
//! (`ec.3d.cryptomatte`): the layer and selection from its Settings data, Output as Display and
//! Matte Only. The effect is built into the committed `synthetic.aep` in place of its Glow, in
//! the layout docs/aep-format.md 3.7 describes (made-up layer names and ID hashes).
use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import};
use effectcraft_aep::{Body, Chunk, ParamKind, Project as AepProject, parse, write};
use effectcraft_keyframe::Value;
use effectcraft_project::{Project, PropGroup};
const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep");
/// A match name chunk (`tdmn`, 40 bytes).
fn tdmn(name: &str) -> Chunk<'static> {
let mut b = name.as_bytes().to_vec();
b.resize(40, 0);
Chunk::data(*b"tdmn", b)
}
/// A parameter definition: the type at byte 15, the name at 16; a popup's default at 56 and
/// item count at 60.
fn pard(kind: u8, name: &str, popup: Option<(u32, u16)>) -> Chunk<'static> {
let mut b = vec![0u8; 148];
b[15] = kind;
b[16..16 + name.len()].copy_from_slice(name.as_bytes());
if let Some((default, count)) = popup {
b[56..60].copy_from_slice(&default.to_be_bytes());
b[60..62].copy_from_slice(&count.to_be_bytes());
}
Chunk::data(*b"pard", b)
}
fn utf8(s: &str) -> Chunk<'static> {
Chunk::data(*b"Utf8", s.as_bytes().to_vec())
}
/// A chunk whose body is chunks without being a `LIST`, as After Effects writes `pdnm` and `fnam`
/// (`NESTED_IDS`). A `LIST pdnm` is not read as popup items.
fn nested(id: [u8; 4], children: Vec<Chunk<'static>>) -> Chunk<'static> {
Chunk { id, body: Body::Chunks(children), pad: None }
}
/// The plug-in's Output items in the order After Effects 2026 stores them (1400).
const OUTPUT: &[&str] = &["Colors", "Matted Colors", "Matted RGBA", "Matte Only"];
/// A static value record holding `v` in state `tdsb` (1 written, 3 the default state), after the
/// one After Effects wrote for Glow's A & B Midpoint (its header; without the expression).
fn record(template: &Chunk<'_>, tdsb: u32, v: f64) -> Chunk<'static> {
let mut kids = Vec::new();
for c in template.children() {
match &c.body {
Body::Data(_) if c.id == *b"tdsb" => kids.push(Chunk::data(*b"tdsb", tdsb.to_be_bytes().to_vec())),
Body::Data(d) if c.id == *b"tdb4" => kids.push(Chunk::data(c.id, d.to_vec())),
Body::Data(_) if c.id == *b"cdat" => {
let mut d = vec![0u8; 40];
d[..8].copy_from_slice(&v.to_be_bytes());
kids.push(Chunk::data(*b"cdat", d));
}
_ => {}
}
}
Chunk::list(*b"tdbs", kids)
}
/// The plug-in's Settings data: `cry1`, 28 bytes not read, the layer name in 64 bytes, a `u32` 1,
/// a `u32` not read, the text's length with its NUL, a `u32` not read, a zero byte, the text.
fn settings(layer: &str, selection: &str) -> Vec<u8> {
let mut d = b"cry1".to_vec();
d.resize(32, 0x5a);
d.extend(layer.as_bytes());
d.resize(96, 0);
d.extend(1u32.to_le_bytes());
d.extend(0x1234_5678u32.to_le_bytes());
d.extend(u32::try_from(selection.len() + 1).unwrap().to_le_bytes());
d.extend(0x9abc_def0u32.to_le_bytes());
d.push(0);
d.extend(selection.as_bytes());
d.push(0);
d.extend(b" <1"); // left-overs of a longer earlier text
d
}
struct Crypto {
/// The Settings data, if stored.
settings: Option<Vec<u8>>,
/// Output (1-based), if stored.
output: Option<u32>,
/// Selection Mode, if stored: on, and the record's `tdsb`.
selection_mode: Option<(bool, u32)>,
/// The instance has no definitions of its own (an empty `parT`) and borrows the project's,
/// as every instance but the first of a project does (1400).
borrowed: bool,
/// Output's popup items as written in its `pdnm`; `None` writes no `pdnm` (a definition with
/// four items then falls back to the plug-in's own list).
items: Option<&'static [&'static str]>,
}
/// The Cryptomatte instance: its own definitions (input layer, Settings, Output, Selection Mode,
/// the built-in entry; none when `own` is false) and the stored values of `c`.
fn sspc(c: &Crypto, template: &Chunk<'_>, own: bool) -> Chunk<'static> {
let name = |i: u32| format!("Cryptomatte-{i:04}");
let mut part = vec![
Chunk::data(*b"parn", 5u32.to_be_bytes().to_vec()),
tdmn(&name(0)),
pard(0, "", None),
tdmn(&name(1)),
pard(11, "Settings", None),
Chunk::data(*b"aRbp", settings("", "")),
tdmn(&name(2)),
pard(7, "Output", Some((1, c.items.map_or(4, |i| u16::try_from(i.len()).unwrap())))),
tdmn(&name(3)),
pard(4, "Selection Mode", None),
tdmn("ADBE Effect Built In Params"),
pard(9, "", None),
];
if let Some(items) = c.items {
// After the Output definition, as After Effects writes it.
part.insert(8, nested(*b"pdnm", vec![utf8(&items.join("|"))]));
}
let part = if own { part } else { Vec::new() };
let mut values = vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec())];
if let Some(d) = &c.settings {
values.push(tdmn(&name(1)));
values.push(record(template, 1, 0.0));
values.push(Chunk::list(*b"aRbs", vec![Chunk::data(*b"aRbp", d.clone())]));
}
if let Some(o) = c.output {
values.push(tdmn(&name(2)));
values.push(record(template, 1, f64::from(o)));
}
if let Some((on, tdsb)) = c.selection_mode {
values.push(tdmn(&name(3)));
values.push(record(template, tdsb, if on { 1.0 } else { 0.0 }));
}
Chunk::list(*b"sspc", vec![nested(*b"fnam", vec![utf8("Cryptomatte")]), Chunk::list(*b"parT", part), Chunk::list(*b"tdgp", values)])
}
fn find_glow_template<'a>(chunks: &'a [Chunk<'a>]) -> Option<Chunk<'a>> {
for c in chunks {
let kids = c.children();
if let Some(at) = kids.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.starts_with(b"ADBE Glo2-0011\0")))
&& let Some(record) = kids.get(at + 1).filter(|k| k.is_list(b"tdbs"))
{
return Some(record.clone());
}
if let Some(t) = find_glow_template(kids) {
return Some(t);
}
}
None
}
/// Puts `c` in place of the Glow effect (the instance in the effect parade and the project's
/// shared definitions, `defs` below `EfDf`); the number of places.
fn replace_glow(chunks: &mut [Chunk<'_>], c: &Crypto, template: &Chunk<'_>, defs: bool) -> usize {
let mut n = 0;
for ch in chunks {
let defs = defs || ch.is_list(b"EfDf");
let kids = ch.children_mut();
if let Some(at) = kids.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.starts_with(b"ADBE Glo2\0")))
&& kids.get(at + 1).is_some_and(|k| k.is_list(b"sspc"))
{
kids[at] = tdmn("Cryptomatte");
kids[at + 1] = sspc(c, template, defs || !c.borrowed);
n += 1;
}
n += replace_glow(kids, c, template, defs);
}
n
}
/// `synthetic.aep` with `c` in place of the Glow effect.
fn bytes_with(c: &Crypto) -> Vec<u8> {
let file = parse(SYNTHETIC).unwrap();
let template = find_glow_template(&file.chunks).expect("Glow's A & B Midpoint record");
let mut file = parse(SYNTHETIC).unwrap();
assert_eq!(replace_glow(&mut file.chunks, c, &template, false), 2, "the Glow effect and its shared definitions");
write(&file).unwrap()
}
fn run(c: &Crypto) -> (Option<PropGroup>, ImportResult) {
let bytes = bytes_with(c);
let mut project = Project::default();
let none = |_: &str| false;
let r = import(&mut project, &bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap();
let g = project.comps().flat_map(|(_, c)| c.layers.iter()).find_map(|l| {
l.props.sub("effects").and_then(|fx| fx.children.iter().filter_map(|n| n.as_group()).find(|g| g.match_id == "ec.3d.cryptomatte").cloned())
});
(g, r)
}
fn losses(r: &ImportResult, category: LossCategory) -> Vec<String> {
r.report.losses.iter().filter(|l| l.category == category).flat_map(|l| l.details.clone()).filter(|d| d.contains("Cryptomatte")).collect()
}
fn v(g: &PropGroup, id: &str) -> Value {
g.prop(id).unwrap_or_else(|| panic!("no {id}")).value.clone()
}
fn str(s: &str) -> Value {
Value::Str(s.into())
}
#[test]
fn cryptomatte_arrives_with_its_layer_selection_and_output() {
let sel = "<0000002a>, <deadbeef>";
let (g, r) = run(&Crypto { settings: Some(settings("Layer_A", sel)), output: Some(3), selection_mode: None, borrowed: false, items: Some(OUTPUT) });
assert_eq!(losses(&r, LossCategory::Effects), Vec::<String>::new());
assert_eq!(losses(&r, LossCategory::DamagedData), Vec::<String>::new());
let g = g.expect("an EffectCraft Cryptomatte");
// Matted RGBA: the layer keyed by the selection.
assert_eq!((v(&g, "layerName"), v(&g, "selection"), v(&g, "display"), v(&g, "matteOnly")), (str("Layer_A"), str(sel), Value::Enum(1), Value::Bool(false)));
// The selection's `<hex>` tokens are EffectCraft's own grammar.
assert_eq!(effectcraft_effects::selection_hashes(sel, None), vec![0x2a, 0xdead_beef]);
}
#[test]
fn cryptomatte_output_maps_to_display_and_matte_only() {
for (output, display, matte_only) in [(1, 0, false), (3, 1, false), (4, 1, true)] {
let (g, r) = run(&Crypto {
settings: Some(settings("L", "<00000001>")),
output: Some(output),
selection_mode: Some((false, 1)),
borrowed: false,
items: Some(OUTPUT),
});
assert_eq!(losses(&r, LossCategory::Effects), Vec::<String>::new(), "output {output}");
let g = g.expect("effect");
assert_eq!((v(&g, "display"), v(&g, "matteOnly")), (Value::Enum(display), Value::Bool(matte_only)), "output {output}");
}
// No Output record: the default, Colors, from the instance's own definition or, borrowed,
// the plug-in's (1400 `crypto-00-defaults`; every other composition there borrows).
for borrowed in [false, true] {
let (g, r) = run(&Crypto { settings: None, output: None, selection_mode: None, borrowed, items: Some(OUTPUT) });
assert_eq!(losses(&r, LossCategory::Effects), Vec::<String>::new(), "borrowed {borrowed}");
let g = g.expect("effect");
assert_eq!(
(v(&g, "display"), v(&g, "matteOnly"), v(&g, "layerName"), v(&g, "selection")),
(Value::Enum(0), Value::Bool(false), str(""), str("")),
"the default settings: Colors, no layer, no selection (borrowed {borrowed})"
);
}
// A borrowed definition with a stored Output.
let (g, r) = run(&Crypto { settings: None, output: Some(4), selection_mode: None, borrowed: true, items: Some(OUTPUT) });
assert_eq!(losses(&r, LossCategory::Effects), Vec::<String>::new());
let g = g.expect("effect");
assert_eq!((v(&g, "display"), v(&g, "matteOnly")), (Value::Enum(1), Value::Bool(true)));
}
/// The harness writes Output's items as After Effects does: the reader finds them in the `pdnm`
/// (and the instance name in `fnam`), so the Output tests go through the item names.
#[test]
fn the_injected_definition_reads_back_with_its_popup_items() {
let bytes = bytes_with(&Crypto { settings: None, output: Some(4), selection_mode: None, borrowed: false, items: Some(OUTPUT) });
let file = parse(&bytes).unwrap();
let proj = AepProject::new(&file).unwrap();
let defs = proj.effect_definition_index();
let fx = proj
.all_items()
.into_iter()
.filter_map(|i| i.comp())
.flat_map(|c| c.layers().collect::<Vec<_>>())
.flat_map(|l| l.effects())
.find(|e| e.match_name() == "Cryptomatte")
.expect("the effect");
let output = defs.params(&fx).into_iter().find(|p| p.index == 2).expect("Output");
let want: Vec<String> = OUTPUT.iter().map(|s| s.to_string()).collect();
assert_eq!((output.kind, output.popup_item_count(), output.items), (ParamKind::Popup, Some(4), Some(want)));
assert_eq!(fx.name().as_deref(), Some("Cryptomatte"));
}
/// Output is mapped by the item the stored index names, not by its position in the plug-in's
/// list: with the items in another order, index 4 is Colors and index 1 Matte Only.
#[test]
fn cryptomatte_output_maps_by_item_name() {
const REORDERED: &[&str] = &["Matte Only", "Matted RGBA", "Matted Colors", "Colors"];
for (output, display, matte_only) in [(1, 1, true), (2, 1, false), (4, 0, false)] {
let (g, r) = run(&Crypto { settings: None, output: Some(output), selection_mode: None, borrowed: false, items: Some(REORDERED) });
assert_eq!(losses(&r, LossCategory::Effects), Vec::<String>::new(), "output {output}");
let g = g.expect("effect");
assert_eq!((v(&g, "display"), v(&g, "matteOnly")), (Value::Enum(display), Value::Bool(matte_only)), "output {output}");
}
// Item names are matched without regard to case and spacing.
let (g, _) = run(&Crypto {
settings: None,
output: Some(2),
selection_mode: None,
borrowed: false,
items: Some(&["colors", "MATTE ONLY", "Matted RGBA", "Matted Colors"]),
});
assert_eq!((v(&g.expect("effect"), "matteOnly")), Value::Bool(true));
// An item EffectCraft does not know: reported, Colors used.
let (g, r) = run(&Crypto {
settings: None,
output: Some(2),
selection_mode: None,
borrowed: false,
items: Some(&["Colors", "Something New", "Matted RGBA", "Matte Only"]),
});
let found = losses(&r, LossCategory::Effects);
assert!(found.iter().any(|d| d.contains("'Something New'") && d.contains("Colors used")), "{found:?}");
assert_eq!((v(&g.expect("effect"), "display")), Value::Enum(0));
}
/// A file without Output's `pdnm` and four items in the definition: the plug-in's own list.
#[test]
fn cryptomatte_output_without_items_falls_back_to_the_plugin_list() {
let (g, r) = run(&Crypto { settings: None, output: Some(4), selection_mode: None, borrowed: false, items: None });
assert_eq!(losses(&r, LossCategory::Effects), Vec::<String>::new());
assert_eq!((v(&g.expect("effect"), "matteOnly")), Value::Bool(true));
}
#[test]
fn cryptomatte_values_without_a_counterpart_are_reported() {
// Matted Colors has no counterpart: reported, imported as Matte (the same matte).
let (g, r) = run(&Crypto { settings: Some(settings("L", "")), output: Some(2), selection_mode: Some((true, 1)), borrowed: false, items: Some(OUTPUT) });
let found = losses(&r, LossCategory::Effects);
assert!(found.iter().any(|d| d.contains("'Matted Colors'") && d.contains("no counterpart") && d.contains("imported as Matte")), "{found:?}");
assert!(found.iter().any(|d| d.contains("Selection Mode") && d.contains("is on")), "{found:?}");
assert_eq!(found.len(), 2, "{found:?}");
let g = g.expect("still imported");
assert_eq!((v(&g, "display"), v(&g, "matteOnly"), v(&g, "layerName")), (Value::Enum(1), Value::Bool(false), str("L")));
// Selection Mode on as After Effects writes it: a default-state record (`tdsb` 3) holding 1
// (1400 `crypto-01-set-all`). Reported like a written one; off in that form is not.
for (on, n) in [(true, 1), (false, 0)] {
let (_, r) = run(&Crypto { settings: None, output: None, selection_mode: Some((on, 3)), borrowed: true, items: Some(OUTPUT) });
let found = losses(&r, LossCategory::Effects);
assert_eq!(found.iter().filter(|d| d.contains("Selection Mode") && d.contains("is on")).count(), n, "on {on}: {found:?}");
assert_eq!(found.len(), n, "on {on}: {found:?}");
}
// Unreadable Settings data: reported as damaged, no layer and no selection.
let mut bad = settings("L", "<00000001>");
bad[0] = b'x';
let (g, r) = run(&Crypto { settings: Some(bad), output: Some(3), selection_mode: None, borrowed: false, items: Some(OUTPUT) });
let found = losses(&r, LossCategory::DamagedData);
assert!(found.iter().any(|d| d.contains("settings (layer, selection) are unreadable")), "{found:?}");
assert_eq!((v(&g.expect("effect"), "layerName")), str(""));
}
/// `bytes` with `f` applied to the children of every value group (`tdgp`) that holds the
/// parameter `match_name`, given the position of its match name.
fn edit_values(bytes: &[u8], match_name: &str, f: &dyn Fn(&mut Vec<Chunk<'static>>, usize)) -> Vec<u8> {
fn walk(chunks: &mut [Chunk<'_>], match_name: &str, f: &dyn Fn(&mut Vec<Chunk<'static>>, usize)) {
for c in chunks {
if c.is_list(b"tdgp") {
let mut kids: Vec<Chunk<'static>> = c.children().iter().cloned().map(Chunk::into_owned).collect();
if let Some(at) = kids.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.starts_with(format!("{match_name}").as_bytes()))) {
f(&mut kids, at);
*c = Chunk::list(*b"tdgp", kids);
continue;
}
}
walk(c.children_mut(), match_name, f);
}
}
let mut file = parse(bytes).unwrap();
walk(&mut file.chunks, match_name, f);
write(&file).unwrap()
}
fn import_bytes(bytes: &[u8]) -> ImportResult {
let mut project = Project::default();
let none = |_: &str| false;
import(&mut project, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap()
}
/// A stored record that has lost its data is reported as damaged, not read as the default.
#[test]
fn cryptomatte_records_without_their_data_are_reported() {
let c = Crypto { settings: Some(settings("L", "<00000001>")), output: None, selection_mode: Some((true, 3)), borrowed: false, items: Some(OUTPUT) };
let bytes = bytes_with(&c);
// The Settings record without its `aRbs` list.
let no_data = edit_values(&bytes, "Cryptomatte-0001", &|kids, at| {
if kids.get(at + 2).is_some_and(|k| k.is_list(b"aRbs")) {
kids.remove(at + 2);
}
});
let found = losses(&import_bytes(&no_data), LossCategory::DamagedData);
assert!(found.len() == 1 && found[0].contains("settings (layer, selection) have no data"), "{found:?}");
// The Selection Mode record without a readable value: damaged, not the `pard` default.
let unreadable = edit_values(&bytes, "Cryptomatte-0003", &|kids, at| {
if let Some(rec) = kids.get_mut(at + 1) {
let inner: Vec<Chunk<'static>> = rec.children().iter().filter(|k| !k.is(b"cdat")).cloned().map(Chunk::into_owned).collect();
*rec = Chunk::list(*b"tdbs", inner);
}
});
let r = import_bytes(&unreadable);
let found = losses(&r, LossCategory::DamagedData);
assert!(found.len() == 1 && found[0].contains("Selection Mode") && found[0].contains("unreadable value, off used"), "{found:?}");
assert!(losses(&r, LossCategory::Effects).iter().all(|d| !d.contains("is on")));
// Both intact: nothing damaged.
assert_eq!(losses(&import_bytes(&bytes), LossCategory::DamagedData), Vec::<String>::new());
}
/// Our own After Effects 2026 sample of the plug-in (2.6.6), corpus `aep/cryptomatte.aep`: one
/// Cryptomatte on an EXR layer per composition. The first instance has its own definitions, the
/// others borrow the project's. The first six hold the fresh Settings data (no layer, no
/// selection); the last two come from presets that chose a layer and picked one object
/// (`box_red` on CryptoObject) or one material (`mat_paint` on CryptoMaterial) in the plug-in's
/// UI. The EXR's manifest names those hashes, and After Effects draws exactly those objects as
/// selected.
#[test]
#[ignore = "needs aep/cryptomatte.aep in the corpus (EFFECTCRAFT_AEP_FIXTURES); not pinned yet"]
fn the_after_effects_sample_arrives_as_after_effects_shows_it() {
let bytes = fixture!("cryptomatte.aep");
let mut project = Project::default();
let none = |_: &str| false;
let r = import(&mut project, &bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap();
assert_eq!(losses(&r, LossCategory::DamagedData), Vec::<String>::new());
let found = losses(&r, LossCategory::Effects);
// (composition, Display, Matte Only, layer, selection, the loss it reports): the readbacks
// are Output 1 (fresh), 1, 1, 2, 3, 4, 1, 1 and Selection Mode 0, 1, 1, 0, 0, 0, 0, 0.
let want = [
("crypto-00-defaults", 0, false, "", "", None),
("crypto-01-set-all", 0, false, "", "", Some("Selection Mode")),
("crypto-02-chk-toggled", 0, false, "", "", Some("Selection Mode")),
("crypto-03-pop2-2", 1, false, "", "", Some("'Matted Colors'")),
("crypto-04-pop2-3", 1, false, "", "", None),
("crypto-05-pop2-4", 1, true, "", "", None),
("crypto-06-preset-object-box", 0, false, "CryptoObject", "<11a97486>", None),
("crypto-07-preset-material-paint", 0, false, "CryptoMaterial", "<a5deeb9e>", None),
];
for (comp, display, matte_only, layer, selection, loss) in want {
let c = project.find_by_name(comp).and_then(|i| i.as_comp()).unwrap_or_else(|| panic!("no {comp}"));
let g = c.layers.iter().find_map(|l| {
l.props.sub("effects").and_then(|fx| fx.children.iter().filter_map(|n| n.as_group()).find(|g| g.match_id == "ec.3d.cryptomatte").cloned())
});
let g = g.unwrap_or_else(|| panic!("{comp}: no Cryptomatte"));
assert_eq!(
(v(&g, "display"), v(&g, "matteOnly"), v(&g, "layerName"), v(&g, "selection")),
(Value::Enum(display), Value::Bool(matte_only), str(layer), str(selection)),
"{comp}"
);
let mine: Vec<_> = found.iter().filter(|d| d.starts_with(&format!("{comp}:"))).collect();
match loss {
None => assert!(mine.is_empty(), "{comp}: {mine:?}"),
Some(what) => assert!(mine.len() == 1 && mine[0].contains(what), "{comp}: {mine:?}"),
}
}
assert_eq!(found.len(), 3, "{found:?}");
// The picked tokens are the manifest's hashes, which are the hashes of the names: EffectCraft
// reads `<11a97486>` and `box_red` as the same object.
for (name, token) in [("box_red", "<11a97486>"), ("mat_paint", "<a5deeb9e>")] {
assert_eq!(effectcraft_effects::selection_hashes(token, None), effectcraft_effects::selection_hashes(name, None), "{name}");
}
assert_eq!(effectcraft_effects::selection_hashes("<11a97486>", None), vec![0x11a9_7486]);
}
+1 -1
View File
@@ -72,7 +72,7 @@ fn the_table_names_tint_gradient_ramp_and_exposure() {
] {
assert!(t.contains(&want), "{want:?}");
}
assert_eq!(t.len(), 65);
assert_eq!(t.len(), 66);
for (_, id) in t {
assert!(effectcraft_effects::find(id).is_some(), "{id}");
}
+1 -1
View File
@@ -1,5 +1,5 @@
//! A layer of timed footage ends at its source's end, as After Effects ends it when it opens a
//! project (f1): the three-frame OpenEXR sequence layer of 603 and the
//! project (export test f1, aep-export R31): the three-frame OpenEXR sequence layer of 603 and the
//! 1 s WAV layer of 351 with their out points moved to 5 s import as long as their source; the
//! remapped layer of 354 keeps its out point.
+181
View File
@@ -0,0 +1,181 @@
//! The After Effects version of a file (`head`, `svap`) in the import report, and files that After
//! Effects 2026 saved as copies for 25.x and 24.x (issue #3115).
//!
//! The fixture-free tests edit the committed `synthetic.aep` (saved by 26.2.1x2). The fixture tests
//! read, per family of the corpus, the same-session 2026 save `<family>-26.aep` and its copies
//! `<family>-25x.aep` (File ▸ Save a Copy As 25.x) and `<family>-24x.aep` (24.x) from
//! `EFFECTCRAFT_AEP_FIXTURES`; they are ignored until the corpus holds those files.
use effectcraft_aep::import::{AeVersionInfo, ImportOptions, ImportReport, ImportResult, TESTED_MAJORS, UNKNOWN, analyze, import};
use effectcraft_aep::{AepFile, Body, Chunk, parse, write};
use effectcraft_project::Project;
const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep");
/// The project with `edit` applied to every top-level chunk.
fn mutate(edit: &mut dyn FnMut(&mut Chunk<'_>)) -> Vec<u8> {
let mut file: AepFile<'_> = parse(SYNTHETIC).unwrap();
for c in &mut file.chunks {
edit(c);
}
write(&file).unwrap()
}
/// `synthetic.aep` with `head` bytes 4 to 7 replaced by `word`.
fn with_head_word(word: u32) -> Vec<u8> {
mutate(&mut |c| {
if c.is(b"head")
&& let Body::Data(d) = &mut c.body
{
d.to_mut().get_mut(4..8).unwrap().copy_from_slice(&word.to_be_bytes());
}
})
}
/// The report of an analysis of `bytes` (no footage on disk).
fn report(bytes: &[u8]) -> ImportReport {
analyze(bytes, &|_| false).unwrap()
}
/// The limitation lines about an untested version.
fn version_limitations(r: &ImportReport) -> Vec<&String> {
r.limitations.iter().filter(|l| l.contains("is not tested")).collect()
}
#[test]
fn the_report_names_the_version_the_file_is_written_for_and_saved_by() {
let r = report(SYNTHETIC);
assert_eq!(r.ae_version, AeVersionInfo { file_version: "26.2.1x2".into(), saved_by: "26.2.1x2".into(), tested: true });
assert!(version_limitations(&r).is_empty());
let json = serde_json::to_value(&r).unwrap();
assert_eq!(json["aeVersion"]["fileVersion"], "26.2.1x2");
assert_eq!(json["aeVersion"]["savedBy"], "26.2.1x2");
assert_eq!(json["aeVersion"]["tested"], true);
}
/// A copy saved for 25.x or 24.x reports that version and the 2026 writer, and counts as tested.
#[test]
fn a_copy_saved_for_an_older_version_names_both() {
// The words of the copies After Effects 2026 saved as 25.x and 24.x; `svap` stays 2026's.
for (word, text) in [(0x0f0b_0661, "25.6.0x97"), (0x0f03_0641, "24.6.0x65")] {
let r = report(&with_head_word(word));
assert_eq!(r.ae_version.file_version, text);
assert_eq!(r.ae_version.saved_by, "26.2.1x2");
assert!(r.ae_version.tested);
assert!(version_limitations(&r).is_empty());
}
}
#[test]
fn an_untested_version_is_imported_and_said_to_be_untested() {
// 23.6.0x97: major 23 (bits 25-24 = 10, bits 21-19 = 111).
let bytes = with_head_word(0x0e3b_0661);
let mut project = Project::default();
let none = |_: &str| false;
// Not a loss: the losses are those of the unedited file.
let r: ImportResult = import(&mut project, &bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap();
assert_eq!(r.report.losses, report(SYNTHETIC).losses);
assert_eq!(r.report.ae_version.file_version, "23.6.0x97");
assert!(!r.report.ae_version.tested);
assert!(!TESTED_MAJORS.contains(&23));
let lines = version_limitations(&r.report);
assert_eq!(lines.len(), 1);
assert!(lines[0].contains("After Effects 23.6.0x97 (saved by 26.2.1x2)"), "{}", lines[0]);
assert!(!r.comps.is_empty());
}
/// A missing, short or empty version word reads as `unknown` and the file still imports.
#[test]
fn a_file_without_a_version_reads_as_unknown_and_imports() {
// A zero word (After Effects itself refuses it, "[0.0x0]") and all ones.
for word in [0, u32::MAX] {
let r = report(&with_head_word(word));
assert_eq!(r.ae_version.file_version, UNKNOWN);
assert!(!r.ae_version.tested);
assert_eq!(version_limitations(&r).len(), 1);
}
// No `svap` (After Effects opens such a file): the id is renamed, the size kept.
let bytes = mutate(&mut |c| {
if c.is(b"svap") {
c.id = *b"xsvp";
}
});
let r = report(&bytes);
assert_eq!(r.ae_version.saved_by, UNKNOWN);
assert_eq!(r.ae_version.file_version, "26.2.1x2");
// A `head` too short for the word, and none at all.
for keep in [Some(5usize), None] {
let bytes = mutate(&mut |c| {
if c.is(b"head") {
match keep {
Some(n) => {
if let Body::Data(d) = &mut c.body {
d.to_mut().truncate(n);
}
}
None => c.id = *b"xhed",
}
}
});
let r = report(&bytes);
assert_eq!(r.ae_version, AeVersionInfo { file_version: UNKNOWN.into(), saved_by: "26.2.1x2".into(), tested: false });
}
}
#[test]
fn a_report_without_the_field_still_reads() {
let mut json = serde_json::to_value(report(SYNTHETIC)).unwrap();
json.as_object_mut().unwrap().remove("aeVersion");
let r: ImportReport = serde_json::from_value(json).unwrap();
assert_eq!(r.ae_version, AeVersionInfo::default());
assert_eq!(r.ae_version.file_version, UNKNOWN);
}
/// The corpus families saved three ways.
const FAMILIES: &[&str] =
&["1200-lumetri", "3d", "effects", "footage-precomp", "keyframes", "layers-comps", "markers", "masks", "settings-a", "shapes", "styles", "text"];
/// The import of a file: the project as JSON, the report and the parsed versions.
fn import_file(name: &str) -> Option<(serde_json::Value, ImportReport, effectcraft_project::ProjectSettings)> {
let bytes = crate::common::try_file(name)?;
let mut project = Project::default();
let none = |_: &str| false;
let opts = ImportOptions { allow_losses: true, ..ImportOptions::new(&none) };
let r = import(&mut project, &bytes, &opts).unwrap_or_else(|e| panic!("{name}: {e}"));
Some((serde_json::to_value(&project).unwrap(), r.report, r.settings))
}
/// Per corpus family, the 25.x and 24.x copies import to the same project and report as the 2026 save.
#[test]
#[ignore = "needs the version fixtures of the corpus (<family>-26/-25x/-24x.aep)"]
fn copies_saved_as_25x_and_24x_import_like_the_2026_file() {
for family in FAMILIES {
let Some((project_26, report_26, settings_26)) = import_file(&format!("{family}-26.aep")) else { continue };
assert_eq!(report_26.ae_version, AeVersionInfo { file_version: "26.2.1x2".into(), saved_by: "26.2.1x2".into(), tested: true }, "{family}");
for (suffix, version) in [("25x", "25.6.0x97"), ("24x", "24.6.0x65")] {
let name = format!("{family}-{suffix}.aep");
let Some((project, report, settings)) = import_file(&name) else { continue };
assert_eq!(report.ae_version, AeVersionInfo { file_version: version.into(), saved_by: "26.2.1x2".into(), tested: true }, "{name}");
assert_eq!(project, project_26, "{name}: the imported project differs from the 2026 file's");
assert_eq!(settings, settings_26, "{name}: the imported settings differ from the 2026 file's");
let same_but_version = ImportReport { ae_version: report_26.ae_version.clone(), ..report };
assert_eq!(same_but_version, report_26, "{name}: the report differs from the 2026 file's");
}
}
}
/// Per corpus family, `head` holds the version each copy is written for and `svap` the writer.
#[test]
#[ignore = "needs the version fixtures of the corpus (<family>-26/-25x/-24x.aep)"]
fn the_container_of_a_copy_states_its_version_in_head_and_the_writer_in_svap() {
for family in FAMILIES {
for (suffix, version, revision) in [("26", "26.2.1x2", 97), ("25x", "25.6.0x97", 96), ("24x", "24.6.0x65", 95)] {
let name = format!("{family}-{suffix}.aep");
let Some(bytes) = crate::common::try_file(&name) else { continue };
let file = parse(&bytes).unwrap();
assert_eq!(file.file_version().map(|v| v.text()).as_deref(), Some(version), "{name}");
assert_eq!(file.saved_by_version().map(|v| v.text()).as_deref(), Some("26.2.1x2"), "{name}");
assert_eq!(file.head_revision(), Some(revision), "{name}");
}
}
}
+2 -1
View File
@@ -1,8 +1,9 @@
//! The integration tests of effectcraft-aep, one binary: the container (chunk tree and typed
//! view) and import tests, and the fixture access they share (`common`).
//! view), import and export tests, and the fixture access they share (`common`).
#[macro_use]
mod common;
mod container;
mod export;
mod import;
+1
View File
@@ -131,6 +131,7 @@ const WRITES: &[(&str, &[&str])] = &[
// This query checks a proposed write destination, so it follows write confinement.
("file.checkOutput", &["path"]),
("file.exportLottie", &["path"]),
("file.exportAep", &["path"]),
("comp.saveFrameAs", &["path"]),
("comp.saveFrameAsPsd", &["path"]),
("comp.saveFrameAsExr", &["path"]),
+8
View File
@@ -210,6 +210,14 @@ impl ColorSpace {
}
}
/// The primaries and white as the OpenEXR `chromaticities` attribute stores them: red, green,
/// blue, white (CIE xy). Every space has a defined mapping: the PQ and HLG spaces are BT.2020
/// primaries with D65, the ACES spaces carry the ACES white.
pub fn exr_chromaticities(self) -> [[f32; 2]; 4] {
let [r, g, b] = self.primaries();
[r, g, b, self.white()].map(|c| c.map(|v| v as f32))
}
/// The transfer curve.
pub fn curve(self) -> Curve {
match self {
+80 -7
View File
@@ -409,8 +409,68 @@ pub fn selection_hashes(sel: &str, manifest: Option<&[(String, u32)]>) -> Vec<u3
out
}
/// The Cryptomatte layers every renderer names, and the Layer popup's options when the footage
/// has no Cryptomatte metadata. The stored Layer value is an index: 0-2 are these (an exact
/// match or a suffix such as `ViewLayer.CryptoObject`), 3 and up are the file's other Cryptomatte
/// layers in name order, so a project saved before the popup followed the footage loads unchanged.
pub const CRYPTO_LAYERS: [&str; 3] = ["CryptoObject", "CryptoMaterial", "CryptoAsset"];
/// The Layer popup's entries for Cryptomatte `layers` (sorted, as [`AuxChannels::crypto_layers`]
/// returns them): the stored value and the layer's name, in value order. Of several layers
/// that fit one standard slot (`A.CryptoObject`, `B.CryptoObject`) the first one keeps the standard
/// slot, so existing projects load unchanged, and the others get the next custom slots.
fn crypto_layer_slots(layers: &[String]) -> Vec<(usize, &str)> {
let mut out: Vec<(usize, &str)> = vec![];
let mut custom = CRYPTO_LAYERS.len();
for l in layers {
match CRYPTO_LAYERS.iter().position(|w| l == w || l.ends_with(w)) {
Some(i) if !out.iter().any(|(j, _)| *j == i) => out.push((i, l)),
_ => {
out.push((custom, l));
custom += 1;
}
}
}
out.sort_by_key(|(i, _)| *i);
out
}
/// What the Layer popup lists for the footage `aux`: the Cryptomatte layers the file has, as
/// (stored value, name), or the three standard ones when there is none (no footage, not an
/// OpenEXR, no Cryptomatte channels).
pub fn crypto_layer_choices(aux: Option<&AuxChannels>) -> Vec<(usize, String)> {
crypto_layer_menu(aux, 0).0
}
/// The Layer popup for the stored value `index`: [`crypto_layer_choices`], and the name of the
/// entry the effect reads (the first when `index` names none, as the effect does).
pub fn crypto_layer_menu(aux: Option<&AuxChannels>, index: usize) -> (Vec<(usize, String)>, Option<String>) {
let layers = aux.map(AuxChannels::crypto_layers).unwrap_or_default();
if layers.is_empty() {
let all: Vec<(usize, String)> = CRYPTO_LAYERS.iter().enumerate().map(|(i, n)| (i, n.to_string())).collect();
let shown = all.iter().find(|c| c.0 == index).or(all.first()).map(|c| c.1.clone());
return (all, shown);
}
let slots = crypto_layer_slots(&layers);
let shown = slots.iter().find(|(i, _)| *i == index).map(|(_, n)| n.to_string()).or_else(|| layers.first().cloned());
(slots.into_iter().map(|(i, n)| (i, n.to_string())).collect(), shown)
}
/// The Cryptomatte layer the effect reads: the one called `name` when the footage has it (Layer
/// Name, the layer an imported After Effects project names), else [`crypto_layer_name`]'s.
pub fn crypto_layer_named(aux: &AuxChannels, name: &str, index: usize) -> Option<String> {
aux.resolve_crypto_layer_named(name, &crypto_layer_name(aux, index)?)
}
/// The Cryptomatte layer of `aux` that the stored Layer value `index` reads: its slot's layer, else
/// the first layer (what a file without that layer has always shown). `None` without any.
pub fn crypto_layer_name(aux: &AuxChannels, index: usize) -> Option<String> {
if aux.crypto_layers().is_empty() {
return None;
}
crypto_layer_menu(Some(aux), index).1
}
/// Rank planes as [`AuxChannels::crypto_rank_planes`] returns them.
type RankPlanes<'a> = [(&'a [f32], &'a [f32])];
@@ -510,24 +570,32 @@ pub fn crypto_aux_image_with(a: &AuxChannels, layer: &str, sel: &[u32], what: Cr
img
}
/// The hidden switch that keeps Matte Only as projects saved before #3127 render it: the matte in
/// RGB and alpha. Fresh instances have it off (the matte in RGB over alpha 1, as After Effects'
/// Cryptomatte plug-in shows Matte Only); `migrate::legacy_default` turns it on for older saves.
pub const MATTE_ONLY_IN_ALPHA: &str = "matteOnlyInAlpha";
/// A Matte Only pixel for matte `m`: grey `m` over alpha 1, or with `in_alpha` (older
/// projects) `m` in every channel. The GPU shader (`fx_depth.wgsl`, op 7) does the same.
#[inline]
pub fn matte_only_px(m: f32, in_alpha: bool) -> Px {
if in_alpha { [m; 4] } else { [m, m, m, 1.0] }
}
fn cryptomatte(ctx: &EffectCtx, mut b: Buf) -> Buf {
let Some(a) = aux(ctx) else { return b };
let layers = a.crypto_layers();
if layers.is_empty() {
return b;
}
let want = CRYPTO_LAYERS[(ctx.params.e("layer") as usize).min(2)];
let layer = layers.iter().find(|l| l.as_str() == want || l.ends_with(want)).unwrap_or(&layers[0]).clone();
let Some(layer) = crypto_layer_named(&a, ctx.params.s("layerName"), ctx.params.e("layer") as usize) else { return b };
let manifest = a.manifests.iter().find(|(l, _)| *l == layer).map(|(_, m)| m.as_slice());
let sel = selection_hashes(ctx.params.s("selection"), manifest);
let idx = index_map(&b, &a);
let display = ctx.params.e("display");
let matte_only = ctx.params.b("matteOnly");
let in_alpha = ctx.params.b(MATTE_ONLY_IN_ALPHA);
let planes = a.crypto_rank_planes(&layer);
b.img.data.par_iter_mut().zip(idx.par_iter()).for_each_init(IdColorMemo::default, |memo, (px, &k)| {
let m = k.map_or(0.0, |k| crypto_matte(&planes, &sel, k));
if matte_only {
*px = [m, m, m, m];
*px = matte_only_px(m, in_alpha);
return;
}
*px = match display {
@@ -643,6 +711,11 @@ pub fn specs() -> Vec<EffectSpec> {
text("selection", "Selection", ""),
p("display", "Display", Value::Enum(2), popup(&["Colors", "Matte", "Preview"])),
p("matteOnly", "Matte Only", Value::Bool(false), ParamUi::Checkbox),
p(MATTE_ONLY_IN_ALPHA, "Matte Only In Alpha", Value::Bool(false), ParamUi::Hidden),
// A layer named in full (`CryptoMaterial`); empty uses Layer. Last, so the
// earlier parameters keep their indexes and saved instances, which get it
// appended, have the same order as new ones.
text("layerName", "Layer Name", ""),
],
cryptomatte,
),
+212 -7
View File
@@ -258,15 +258,20 @@ fn cryptomatte_cpu_path_is_bit_exact_inside_and_outside_the_aux_area() {
let names = "sphere, <7fc00000>, <7fc01234>, <80000000>";
assert_eq!(selection_hashes(names, None), edge_selection());
let src = img().data[0];
for (display, matte_only) in [(0, false), (1, false), (2, false), (0, true)] {
for (display, matte_only, in_alpha) in [(0, false, false), (1, false, false), (2, false, false), (0, true, false), (0, true, true)] {
let out = run(
"ec.3d.cryptomatte",
&[("selection", Value::Str(names.into())), ("display", Value::Enum(display)), ("matteOnly", Value::Bool(matte_only))],
&[
("selection", Value::Str(names.into())),
("display", Value::Enum(display)),
("matteOnly", Value::Bool(matte_only)),
(MATTE_ONLY_IN_ALPHA, Value::Bool(in_alpha)),
],
&host,
);
let expect = |c: [f32; 3], m: f32| -> [f32; 4] {
if matte_only {
return [m; 4];
return if in_alpha { [m; 4] } else { [m, m, m, 1.0] };
}
match display {
0 => {
@@ -279,24 +284,62 @@ fn cryptomatte_cpu_path_is_bit_exact_inside_and_outside_the_aux_area() {
};
for (x, y) in [(0u32, 0u32), (1, 0), (5, 0), (0, 1), (3, 1), (5, 1)] {
let (c, m) = reduce_by_name(&a, "CryptoObject", &edge_selection(), (y * 6 + x) as usize);
assert_eq!(out.get(x as i64, y as i64).map(f32::to_bits), expect(c, m).map(f32::to_bits), "display {display} matteOnly {matte_only} at ({x}, {y})");
assert_eq!(
out.get(x as i64, y as i64).map(f32::to_bits),
expect(c, m).map(f32::to_bits),
"display {display} matteOnly {matte_only} inAlpha {in_alpha} at ({x}, {y})"
);
}
for (x, y) in [(6u32, 0u32), (19, 0), (0, 2), (12, 9)] {
assert_eq!(
out.get(x as i64, y as i64).map(f32::to_bits),
expect([0.0; 3], 0.0).map(f32::to_bits),
"display {display} matteOnly {matte_only} outside the aux at ({x}, {y})"
"display {display} matteOnly {matte_only} inAlpha {in_alpha} outside the aux at ({x}, {y})"
);
}
}
}
/// #3127: Matte Only shows the matte as After Effects' Cryptomatte plug-in does, in RGB over
/// alpha 1 (its Matte Only render of 2026-11-05 is opaque black where nothing is selected), not
/// in alpha. A partly covered pixel is grey, not translucent; the hidden Matte Only In Alpha
/// switch (on for projects saved before) keeps the old matte in every channel.
#[test]
fn cryptomatte_matte_only_is_the_matte_in_rgb_over_alpha_one() {
let a = edge_aux(true);
let host = AuxHost(Arc::new(a.clone()));
let names = "sphere, <7fc00000>, <7fc01234>, <80000000>";
let only = |in_alpha: bool| {
run(
"ec.3d.cryptomatte",
&[("selection", Value::Str(names.into())), ("matteOnly", Value::Bool(true)), (MATTE_ONLY_IN_ALPHA, Value::Bool(in_alpha))],
&host,
)
};
let (new, old) = (only(false), only(true));
let partial = (0..6u32 * 2).map(|i| (i % 6, i / 6)).find(|&(x, y)| {
let m = reduce_by_name(&a, "CryptoObject", &edge_selection(), (y * 6 + x) as usize).1;
m > 0.0 && m < 1.0
});
let (x, y) = partial.expect("the edge aux has a partly covered pixel");
let m = reduce_by_name(&a, "CryptoObject", &edge_selection(), (y * 6 + x) as usize).1;
assert_eq!(new.get(x as i64, y as i64), [m, m, m, 1.0]);
assert_eq!(old.get(x as i64, y as i64), [m; 4]);
// Outside the aux area (and unselected): opaque black, as After Effects renders it.
assert_eq!(new.get(12, 9), [0.0, 0.0, 0.0, 1.0]);
assert_eq!(old.get(12, 9), [0.0; 4]);
// A fresh instance has the switch off.
let spec = crate::find("ec.3d.cryptomatte").unwrap();
let ps = spec.params.iter().find(|p| p.id == MATTE_ONLY_IN_ALPHA).expect("the hidden switch");
assert_eq!((&ps.default, &ps.ui), (&Value::Bool(false), &ParamUi::Hidden));
}
#[test]
fn cryptomatte_selects_by_name_and_wildcard() {
let h = scene();
let m = run("ec.3d.cryptomatte", &[("selection", Value::Str("right".into())), ("matteOnly", Value::Bool(true))], &h);
assert_eq!(m.get(2, 5)[3], 0.0);
assert_eq!(m.get(12, 5)[3], 1.0);
assert_eq!(m.get(2, 5), [0.0, 0.0, 0.0, 1.0]);
assert_eq!(m.get(12, 5), [1.0; 4]);
let w = run("ec.3d.cryptomatte", &[("selection", Value::Str("l*".into())), ("display", Value::Enum(1))], &h);
assert_eq!(w.get(2, 5)[3], 1.0);
assert_eq!(w.get(12, 5)[3], 0.0);
@@ -305,6 +348,60 @@ fn cryptomatte_selects_by_name_and_wildcard() {
assert_eq!(selection_hashes(&hex, None), vec![crypto_hash("left")]);
}
/// Layer Name picks a Cryptomatte layer named in full (`Crypto_Material`, which the Layer popup's
/// CryptoMaterial does not match); empty or missing it falls back to the Layer popup.
#[test]
fn cryptomatte_layer_name_picks_the_named_layer() {
let base = scene();
let mut a = (*base.0).clone();
// A second layer with the IDs swapped: left is on the right half there.
let swap = |name: &str| a.channels.iter().find(|(n, _)| n == name).map(|(_, v)| v.clone()).unwrap();
let (r, g) = (swap("CryptoObject00.R"), swap("CryptoObject00.G"));
let w = 20;
let r2: Vec<f32> = (0..r.len()).map(|i| r[(i / w) * w + (w - 1 - i % w)]).collect();
a.channels.push(("Crypto_Material00.R".into(), r2));
a.channels.push(("Crypto_Material00.G".into(), g));
let h = AuxHost(Arc::new(a));
let sel = format!("<{:08x}>", crypto_hash("left"));
let matte = |vals: &[(&str, Value)]| {
let mut v = vec![("selection", Value::Str(sel.clone())), ("matteOnly", Value::Bool(true))];
v.extend(vals.iter().cloned());
let m = run("ec.3d.cryptomatte", &v, &h);
(m.get(2, 5)[0], m.get(17, 5)[0])
};
assert_eq!(matte(&[("layerName", Value::Str("Crypto_Material".into()))]), (0.0, 1.0), "the named layer");
assert_eq!(matte(&[]), (1.0, 0.0), "the Layer popup's CryptoObject");
assert_eq!(matte(&[("layerName", Value::Str("Crypto_Name".into()))]), (1.0, 0.0), "a missing name falls back to the popup");
}
/// Layers whose names differ only in case are different layers: `layerName` "crypto_a" mattes
/// from crypto_a's own IDs, not from the earlier `Crypto_A`.
#[test]
fn cryptomatte_layer_name_is_case_sensitive() {
let base = scene();
let mut a = (*base.0).clone();
let (r, g) = (
a.channels.iter().find(|(n, _)| n == "CryptoObject00.R").unwrap().1.clone(),
a.channels.iter().find(|(n, _)| n == "CryptoObject00.G").unwrap().1.clone(),
);
let w = 20;
let flipped: Vec<f32> = (0..r.len()).map(|i| r[(i / w) * w + (w - 1 - i % w)]).collect();
// `Crypto_A` first, with left/right as in the base scene; `crypto_a` has them swapped.
a.channels.push(("Crypto_A00.R".into(), r));
a.channels.push(("Crypto_A00.G".into(), g.clone()));
a.channels.push(("crypto_a00.r".into(), flipped));
a.channels.push(("crypto_a00.g".into(), g));
let h = AuxHost(Arc::new(a));
let sel = format!("<{:08x}>", crypto_hash("left"));
let matte = |name: &str| {
let v = [("selection", Value::Str(sel.clone())), ("matteOnly", Value::Bool(true)), ("layerName", Value::Str(name.into()))];
let m = run("ec.3d.cryptomatte", &v, &h);
(m.get(2, 5)[0], m.get(17, 5)[0])
};
assert_eq!(matte("Crypto_A"), (1.0, 0.0));
assert_eq!(matte("crypto_a"), (0.0, 1.0));
}
/// #473: a name with a comma in it (Blender allows `Green, Glossy`) is selected when it is
/// quoted or its comma escaped, instead of being cut into two names that match nothing.
#[test]
@@ -400,6 +497,114 @@ fn instance3d_replaces_the_pixels_with_the_referenced_layer() {
assert_eq!(out.img.data, solid().data);
}
/// A 20×10 layer of one Cryptomatte layer `name` that holds "left" on its left half and
/// "right" on its right half, as [`scene`] does for `CryptoObject`.
fn crypto_only(names: &[&str]) -> AuxHost {
let (w, h) = (20usize, 10usize);
let mut a = AuxChannels::new(w as u32, h as u32, 1.0);
let (hl, hr) = (crypto_hash("left"), crypto_hash("right"));
for name in names {
let ids: Vec<f32> = (0..w * h).map(|i| crypto_float(if i % w < 10 { hl } else { hr })).collect();
a.channels.push((format!("{name}00.R"), ids));
a.channels.push((format!("{name}00.G"), vec![1.0; w * h]));
a.manifests.push((name.to_string(), vec![("left".into(), hl), ("right".into(), hr)]));
}
AuxHost(Arc::new(a))
}
fn choices(names: &[&str]) -> Vec<(usize, String)> {
crypto_layer_choices(Some(&crypto_only(names).0))
}
/// #473: the Layer popup lists the Cryptomatte layers the footage has, and the three standard
/// ones when there is no footage, no OpenEXR or no Cryptomatte in it.
#[test]
fn crypto_layer_popup_lists_the_layers_of_the_footage() {
let standard: Vec<(usize, String)> = CRYPTO_LAYERS.iter().enumerate().map(|(i, n)| (i, n.to_string())).collect();
assert_eq!(crypto_layer_choices(None), standard);
assert_eq!(crypto_layer_choices(Some(&AuxChannels::new(1, 1, 1.0))), standard, "an EXR without Cryptomatte");
assert_eq!(crypto_layer_choices(Some(&scene().0)), vec![(0, "CryptoObject".to_string())]);
// Only CryptoMaterial: it, not CryptoObject, with its own stored value.
assert_eq!(choices(&["CryptoMaterial"]), vec![(1, "CryptoMaterial".to_string())]);
// Standard layers come in slot order whatever the names sort like; prefixed ones fill their slot.
assert_eq!(choices(&["CryptoAsset", "ViewLayer.CryptoObject"]), vec![(0, "ViewLayer.CryptoObject".to_string()), (2, "CryptoAsset".to_string())]);
// A layer under another name gets a value after the standard ones, in name order.
assert_eq!(choices(&["Zed", "CryptoMaterial", "Alpha"]), vec![(1, "CryptoMaterial".to_string()), (3, "Alpha".to_string()), (4, "Zed".to_string())]);
// A name that only ends in a standard one fills its slot, as the effect always matched it.
assert_eq!(
choices(&["MyCryptoObject", "ViewLayer.CryptoMaterial", "Other"]),
vec![(0, "MyCryptoObject".to_string()), (1, "ViewLayer.CryptoMaterial".to_string()), (3, "Other".to_string())]
);
// The entry shown: the value's own, else the first layer; with no layers, the standard one.
let shown = |names: &[&str], i| crypto_layer_menu(Some(&crypto_only(names).0), i).1;
assert_eq!(
[0, 1, 7].map(|i| shown(&["CryptoMaterial"], i)),
[Some("CryptoMaterial".to_string()), Some("CryptoMaterial".to_string()), Some("CryptoMaterial".to_string())]
);
assert_eq!(crypto_layer_menu(None, 2).1.as_deref(), Some("CryptoAsset"));
assert_eq!(crypto_layer_menu(None, 9).1.as_deref(), Some("CryptoObject"), "a custom value with no footage");
// Two layers for one slot: the first keeps it, the next gets a custom value.
assert_eq!(choices(&["A.CryptoObject", "B.CryptoObject"]), vec![(0, "A.CryptoObject".to_string()), (3, "B.CryptoObject".to_string())]);
assert_eq!(choices(&["A.CryptoObject", "B.CryptoObject", "C.CryptoObject", "Mine"]).iter().map(|c| c.0).collect::<Vec<_>>(), [0, 3, 4, 5]);
}
/// A project saved with Layer = CryptoObject / CryptoMaterial / CryptoAsset renders the same layer
/// as before: the stored value's own layer, else the file's first; and the custom layers are read
/// by their value.
#[test]
fn crypto_layer_values_keep_their_meaning() {
let all = crypto_only(&["CryptoAsset", "CryptoMaterial", "CryptoObject", "Mine"]).0;
let name = |i| crypto_layer_name(&all, i);
assert_eq!([0, 1, 2, 3].map(name), ["CryptoObject", "CryptoMaterial", "CryptoAsset", "Mine"].map(|n| Some(n.to_string())));
// A value the file has no layer for reads its first layer, as the effect always did.
assert_eq!(name(4).as_deref(), Some("CryptoAsset"));
let only = crypto_only(&["CryptoMaterial"]).0;
assert_eq!(
[0, 1, 2].map(|i| crypto_layer_name(&only, i)),
[Some("CryptoMaterial".to_string()), Some("CryptoMaterial".to_string()), Some("CryptoMaterial".to_string())]
);
assert_eq!(crypto_layer_name(&AuxChannels::new(1, 1, 1.0), 0), None);
}
/// The effect keys the layer the Layer value names: a Material-only file renders its matte
/// whether Layer says Object (a saved project) or Material (what the popup now stores), and a
/// custom layer by its own value.
#[test]
fn cryptomatte_renders_the_layer_the_value_names() {
let sel = ("selection", Value::Str("left".into()));
let matte = |layer: u32, host: &AuxHost| run("ec.3d.cryptomatte", &[("layer", Value::Enum(layer)), sel.clone(), ("display", Value::Enum(1))], host);
let only = crypto_only(&["CryptoMaterial"]);
let (old, new) = (matte(0, &only), matte(1, &only));
assert_eq!(old.data, new.data);
assert_eq!((new.get(2, 5)[3], new.get(12, 5)[3]), (1.0, 0.0));
// Two layers: "left" is in both, under hashes the manifests share, so tell them apart by
// which has it on the right half.
let (hl, hr) = (crypto_hash("left"), crypto_hash("right"));
let mut a = AuxChannels::new(20, 10, 1.0);
for (name, flip) in [("CryptoObject", false), ("Mine", true)] {
let ids: Vec<f32> = (0..200).map(|i| crypto_float(if (i % 20 < 10) != flip { hl } else { hr })).collect();
a.channels.push((format!("{name}00.R"), ids));
a.channels.push((format!("{name}00.G"), vec![1.0; 200]));
}
let two = AuxHost(Arc::new(a));
let (object, mine) = (matte(0, &two), matte(3, &two));
assert_eq!((object.get(2, 5)[3], object.get(12, 5)[3]), (1.0, 0.0));
assert_eq!((mine.get(2, 5)[3], mine.get(12, 5)[3]), (0.0, 1.0), "Layer 3 is the custom layer");
// A second view's layer of a standard kind is selectable too: B.CryptoObject is Layer 3.
let mut a = AuxChannels::new(20, 10, 1.0);
for (name, flip) in [("A.CryptoObject", false), ("B.CryptoObject", true)] {
let ids: Vec<f32> = (0..200).map(|i| crypto_float(if (i % 20 < 10) != flip { hl } else { hr })).collect();
a.channels.push((format!("{name}00.R"), ids));
a.channels.push((format!("{name}00.G"), vec![1.0; 200]));
}
let views = AuxHost(Arc::new(a));
assert_eq!(crypto_layer_name(&views.0, 0).as_deref(), Some("A.CryptoObject"));
assert_eq!(crypto_layer_name(&views.0, 3).as_deref(), Some("B.CryptoObject"));
let (first, second) = (matte(0, &views), matte(3, &views));
assert_eq!((first.get(2, 5)[3], first.get(12, 5)[3]), (1.0, 0.0));
assert_eq!((second.get(2, 5)[3], second.get(12, 5)[3]), (0.0, 1.0), "Layer 3 renders B");
}
/// #474: [`reads_aux`] names exactly the 3D Channel effects that ask the host for channels.
#[test]
fn reads_aux_names_the_effects_that_read_channels() {
+2 -2
View File
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<EffectSpec> {
check("allMasks", "All Masks", false),
check("strokeSequentially", "Stroke Sequentially", true),
p("color", "Color", col(1.0, 1.0, 1.0), ParamUi::Color),
p("brushSize", "Brush Size", num(2.0), slider(0.0, 50.0, 0.0, 50.0, 1)),
p("brushSize", "Brush Size", num(2.0), slider(0.0, 200.0, 0.0, 50.0, 1)),
p("brushHardness", "Brush Hardness", num(75.0), pct()),
p("opacity", "Opacity", num(100.0), pct()),
p("start", "Start", num(0.0), pct()),
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<EffectSpec> {
vec![
p("brushPosition", "Brush Position", pt(0.5, 0.5), ParamUi::Point),
p("color", "Color", col(1.0, 1.0, 1.0), ParamUi::Color),
p("brushSize", "Brush Size", num(6.0), slider(0.0, 50.0, 0.0, 50.0, 1)),
p("brushSize", "Brush Size", num(6.0), slider(0.0, 200.0, 0.0, 50.0, 1)),
p("brushHardness", "Brush Hardness", num(75.0), pct()),
p("brushOpacity", "Brush Opacity", num(100.0), pct()),
p("strokeLength", "Stroke Length (secs)", num(0.0), slider(0.0, 30.0, 0.0, 30.0, 1)),
+16
View File
@@ -197,6 +197,22 @@ fn write_on_and_glue_gun_draw_at_brush() {
assert_eq!(g.img.get(0, 0), src.get(0, 0));
}
/// #2980: Brush Size of Write-on and Stroke goes up to 200 px as in After Effects (read back from
/// After Effects 2026: setting 201 is refused with "out of range 0 to 200"), and a brush that
/// wide paints that wide.
#[test]
fn brush_size_goes_up_to_200() {
for id in ["ec.generate.writeon", "ec.generate.stroke"] {
let spec = crate::find(id).unwrap();
let size = spec.params.iter().find(|p| p.id == "brushSize").unwrap();
assert!(matches!(size.ui, ParamUi::Slider { min, max, .. } if min == 0.0 && max == 200.0), "{id}: {:?}", size.ui);
}
let set = [("brushSize", num(120.0)), ("brushHardness", num(100.0)), ("brushPosition", Value::Vec2([128.0, 128.0]))];
let wide = run("ec.generate.writeon", &set, Image::new(256, 256));
assert!(wide.img.get(128 + 55, 128)[3] > 0.9, "radius 60 reaches 55 px from the centre");
assert!(wide.img.get(128 + 70, 128)[3] == 0.0);
}
/// #536: an animated Brush Position draws a stroke that stays (Stroke Length 0), expires
/// after Stroke Length, and lays its dabs Brush Spacing seconds apart.
#[test]
+6 -3
View File
@@ -88,8 +88,8 @@ use effectcraft_project::build::Ids;
use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property};
pub use effectcraft_raster::{AuxChannels, Image};
pub use misc::{
GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, glow_ab_t, glow_operation, glow_sigma, radial_wipe_sigma, radial_wipe_wedge, venetian_cover,
venetian_origin,
GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma, radial_wipe_sigma,
radial_wipe_wedge, venetian_cover, venetian_origin,
};
pub use sim::particle_state;
pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state};
@@ -115,7 +115,10 @@ pub use time_fx::{PixelMotion, TimewarpPlan, TwStep, pmb_plan, posterized_time,
// effectcraft-gpu fx_tone.
pub use ocio::color_stabilizer_maps;
// GPU effects, part B (3D Channel, Immersive Video, colour management, simulation render passes).
pub use channel3d::{CRYPTO_LAYERS, CryptoAux, aux_point, crypto_aux_image, crypto_aux_image_with, id_color, reads_aux, selection_hashes};
pub use channel3d::{
CRYPTO_LAYERS, CryptoAux, MATTE_ONLY_IN_ALPHA, aux_point, crypto_aux_image, crypto_aux_image_with, crypto_layer_choices, crypto_layer_menu,
crypto_layer_name, crypto_layer_named, id_color, matte_only_px, reads_aux, selection_hashes,
};
pub use ocio::{ColorOp, Straight, Tf, color_program};
pub use sim::{Acc, Blob, Bubble, Post, Shape, Sprite, SpritePlan, Tint, bubble_list, bubble_sample_bounds, drizzle_drops, mercury_blobs, sprite_plan};
pub use sim2::{
+31
View File
@@ -161,6 +161,10 @@ pub fn legacy_default(effect: &str, param: &str) -> Option<Value> {
("ec.key.advancedspill", "ultraSettings/tolerance") => Value::Scalar(100.0),
// Transition: Block Dissolve's blocks had hard edges.
("ec.transition.blockdissolve", "softEdges") => Value::Bool(false),
// Linear Wipe's feather was a linear ramp with the travel extended by it (#3125).
("ec.transition.linearwipe", "legacyFeather") => Value::Bool(true),
// 3D Channel: Cryptomatte's Matte Only put the matte in alpha too (#3127).
("ec.3d.cryptomatte", crate::channel3d::MATTE_ONLY_IN_ALPHA) => Value::Bool(true),
_ => return None,
})
}
@@ -516,6 +520,21 @@ mod tests {
assert_eq!(pr.ui, popup.ui);
}
/// #3127: Cryptomatte's Matte Only moved the matte from RGBA to RGB over alpha 1; a project
/// saved before has no Matte Only In Alpha switch and gets it on, keeping its render. A fresh
/// instance has it off.
#[test]
fn cryptomatte_saved_before_matte_only_in_rgb_keeps_the_matte_in_alpha() {
let id = crate::channel3d::MATTE_ONLY_IN_ALPHA;
let mut next = 1;
let (spec, mut g) = instance("ec.3d.cryptomatte", &mut next);
assert_eq!(g.get(id).map(|p| p.value.clone()), Some(Value::Bool(false)));
g.children.retain(|c| c.match_id() != id);
assert!(upgrade_instance(spec, &mut g, &mut Ids(&mut next), SIZE));
let pr = g.get(id).expect("added on upgrade");
assert_eq!((&pr.value, &pr.ui), (&Value::Bool(true), &ParamUi::Hidden));
}
/// #1797: Shift Channels' menu put Half On before Full Off; a project saved then keeps the
/// option it chose, by label.
#[test]
@@ -591,6 +610,18 @@ mod tests {
assert_eq!(current_param_id(stab, "other/smoothness"), None);
}
/// #3125: a Linear Wipe saved before its feather followed After Effects keeps the old ramp;
/// a new one doesn't.
#[test]
fn old_linear_wipes_keep_the_legacy_feather() {
let mut next = 1;
let (spec, mut g) = instance("ec.transition.linearwipe", &mut next);
assert_eq!(g.get("legacyFeather").unwrap().value, Value::Bool(false));
take_prop(&mut g, "legacyFeather");
assert!(upgrade_instance(spec, &mut g, &mut Ids(&mut next), SIZE));
assert_eq!(g.get("legacyFeather").unwrap().value, Value::Bool(true));
}
#[test]
fn card_wipe_back_layer_popup_becomes_a_layer_parameter() {
let spec = find("ec.transition.cardwipe").unwrap();
+143 -8
View File
@@ -538,16 +538,83 @@ fn noise(ctx: &EffectCtx, mut b: Buf) -> Buf {
b
}
fn linear_wipe(ctx: &EffectCtx, mut b: Buf) -> Buf {
let done = ctx.params.f("completion") / 100.0;
let ang = ctx.params.f("angle").to_radians();
let feather = (ctx.params.f("feather") * b.scale).max(0.001);
let (w, h) = (b.img.width as f64, b.img.height as f64);
// Direction the wipe travels: angle 90° wipes left→right.
/// Linear Wipe's geometry: the direction the wipe travels (angle 90° wipes left → right) and the
/// range of `x·dx + y·dy` over a `w` × `h` buffer's corners.
pub fn linear_wipe_axis(angle_deg: f64, w: f64, h: f64) -> ([f64; 2], f64, f64) {
let ang = angle_deg.to_radians();
let (dx, dy) = (ang.sin(), -ang.cos());
let corners = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)];
let proj: Vec<f64> = corners.iter().map(|(x, y)| x * dx + y * dy).collect();
let (lo, hi) = (proj.iter().cloned().fold(f64::INFINITY, f64::min), proj.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
let proj = corners.map(|(x, y)| x * dx + y * dy);
let (lo, hi) = (proj.iter().copied().fold(f64::INFINITY, f64::min), proj.iter().copied().fold(f64::NEG_INFINITY, f64::max));
([dx, dy], lo, hi)
}
/// Linear Wipe's Feather (`feather` pixels at preview `scale`) as the Gaussian sigma that
/// softens the edge of a `w` × `h` buffer. After Effects' feathered edge is the hard wipe
/// blurred with the layer's edges repeated; our importer sample (Feather 16 at 77°, 2026-11-05)
/// matches three box passes of radius 6 per axis, sigma 6.35..6.6, so sigma = Feather / 2.5
/// (pinned at Feather 16 only, #3125). Capped at twice the buffer's longer side, past which
/// a blur with repeated edges no longer changes and the running sums only cost time.
pub fn linear_wipe_sigma(feather: f64, scale: f64, w: f64, h: f64) -> f64 {
let s = feather * scale / 2.5;
if s.is_finite() && s > 0.0 { s.min(2.0 * w.max(h).max(1.0)) } else { 0.0 }
}
fn linear_wipe(ctx: &EffectCtx, b: Buf) -> Buf {
if ctx.params.b("legacyFeather") {
return linear_wipe_legacy(ctx, b);
}
linear_wipe_blurred(ctx, b)
}
/// After Effects' Linear Wipe (#3125): the edge sits at `lo + completion·(hi − lo)` whatever the
/// feather (0 % keeps the layer, 100 % clears it), anti-aliased by pixel coverage, and Feather
/// blurs that hard matte with the layer's edges repeated (so the feather leans opaque where it
/// meets the layer's sides, as After Effects' does).
fn linear_wipe_blurred(ctx: &EffectCtx, mut b: Buf) -> Buf {
let done = ctx.params.f("completion") / 100.0;
if done.is_nan() || done <= 0.0 {
return b;
}
if done >= 1.0 {
b.img.data.iter_mut().for_each(|px| *px = [0.0; 4]);
return b;
}
let (w, h) = (b.img.width as f64, b.img.height as f64);
let ([dx, dy], lo, hi) = linear_wipe_axis(ctx.params.f("angle"), w, h);
let edge = lo + (hi - lo) * done;
if !(edge.is_finite() && dx.is_finite() && dy.is_finite()) {
return b;
}
let mut mask = Image::new(b.img.width, b.img.height);
mask.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let d = (x as f64 + 0.5) * dx + (y as f64 + 0.5) * dy;
*px = [((d - edge) + 0.5).clamp(0.0, 1.0) as f32; 4];
}
});
let sigma = linear_wipe_sigma(ctx.params.f("feather"), b.scale, w, h);
// Three box passes per axis (the measured shape; the GPU runs the same passes). Below
// Feather ~2 they leave the anti-aliased edge alone.
if sigma > 1e-3 {
mask = gaussian_blur(&mask, sigma, sigma, true);
}
for (px, m) in b.img.data.iter_mut().zip(mask.data.iter()) {
let k = m[3].clamp(0.0, 1.0);
for c in px.iter_mut() {
*c *= k;
}
}
b
}
/// Linear Wipe as EffectCraft drew it before #3125 (projects saved then keep it): a linear ramp
/// Feather pixels wide, the travel extended by the feather at both ends.
fn linear_wipe_legacy(ctx: &EffectCtx, mut b: Buf) -> Buf {
let done = ctx.params.f("completion") / 100.0;
let feather = (ctx.params.f("feather") * b.scale).max(0.001);
let (w, h) = (b.img.width as f64, b.img.height as f64);
let ([dx, dy], lo, hi) = linear_wipe_axis(ctx.params.f("angle"), w, h);
let edge = lo - feather + (hi - lo + 2.0 * feather) * done;
b.img.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
@@ -838,6 +905,8 @@ pub fn specs() -> Vec<EffectSpec> {
p("completion", "Transition Completion", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 0)),
p("angle", "Wipe Angle", num(90.0), ParamUi::Angle),
p("feather", "Feather", num(0.0), slider(0.0, 32000.0, 0.0, 500.0, 1)),
// Projects saved before #3125 keep the earlier linear feather ramp.
p("legacyFeather", "Legacy Feather", Value::Bool(false), ParamUi::Hidden),
],
linear_wipe,
),
@@ -890,6 +959,72 @@ mod tests {
(16..24).map(|x| out.img.get(x, 4)[0]).collect()
}
fn wipe(vals: &[(&str, Value)]) -> effectcraft_raster::Image {
let card = effectcraft_raster::Image::filled(320, 180, [1.0, 1.0, 1.0, 1.0]);
run_fx("ec.transition.linearwipe", vals, card, 0.0, EffectEnv::default()).img
}
/// #3125: After Effects 2026's Linear Wipe on our 320 × 180 importer sample (2026-11-05,
/// `linwipe-01-set-all`): Completion 10, Wipe Angle 77, Feather 16. Alpha (8-bit) of rows
/// 150 and 120 from x = 8, where the feathered edge crosses the layer away from its sides.
#[test]
fn linear_wipe_feather_matches_after_effects() {
const ROW150: [u8; 48] = [
0, 0, 0, 0, 0, 1, 2, 3, 6, 9, 12, 17, 23, 31, 39, 49, 61, 73, 86, 100, 115, 129, 144, 158, 172, 185, 198, 208, 218, 226, 233, 239, 244, 247, 250,
252, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];
const ROW120: [u8; 48] = [
3, 5, 8, 12, 17, 23, 30, 39, 49, 60, 72, 85, 99, 114, 128, 143, 157, 171, 184, 197, 208, 217, 226, 233, 239, 243, 247, 250, 252, 253, 254, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];
let vals = [("completion", num(10.0)), ("angle", num(77.0)), ("feather", num(16.0))];
let out = wipe(&vals);
for (y, row) in [(150, &ROW150), (120, &ROW120)] {
for (i, &ae) in row.iter().enumerate() {
let x = 8 + i as i64;
let a = out.get(x, y)[3] * 255.0;
assert!((a - ae as f32).abs() <= 2.5, "({x}, {y}): {a} vs After Effects {ae}");
}
}
// Where the edge meets the layer's left side the feather leans opaque, as in After
// Effects (179 at (0, 30); a profile across the edge alone gives about 110).
assert!(out.get(0, 30)[3] * 255.0 > 160.0, "{}", out.get(0, 30)[3] * 255.0);
// Projects saved before keep the old linear ramp, which put the edge 13 px further left.
let legacy = wipe(&[vals.as_slice(), &[("legacyFeather", Value::Bool(true))]].concat());
assert!((legacy.get(23, 150)[3] * 255.0 - 129.0).abs() > 100.0);
}
/// #3125: without feather After Effects' edge sits at Completion × the layer's extent along
/// the wipe (9.5 % of 320 px = 30.4, `linwipe-04-keys`; 22 % = 70.4, `linwipe-05-expr`); the
/// edge pixel is anti-aliased (After Effects 143 / 255, coverage gives 0.6). 0 % keeps the
/// layer and 100 % clears it whatever the feather (`linwipe-02-min`, `linwipe-03-max`).
#[test]
fn linear_wipe_edge_follows_completion() {
for (c, col) in [(9.5, 30), (22.0, 70)] {
let out = wipe(&[("completion", num(c)), ("angle", num(90.0))]);
for y in [0, 90, 179] {
assert_eq!(out.get(col - 1, y)[3], 0.0, "{c}");
assert_eq!(out.get(col + 1, y)[3], 1.0, "{c}");
assert!((out.get(col, y)[3] - 143.0 / 255.0).abs() < 0.05, "{c}: {}", out.get(col, y)[3]);
}
}
let max = wipe(&[("completion", num(100.0)), ("feather", num(32000.0))]);
assert!(max.data.iter().all(|p| p[3] == 0.0));
let min = wipe(&[("completion", num(0.0)), ("feather", num(32000.0))]);
assert!(min.data.iter().all(|p| p[3] == 1.0));
}
/// Hostile values: a huge feather is capped (no slow or oversized blur), NaN does not spread.
#[test]
fn linear_wipe_survives_hostile_values() {
let out = wipe(&[("completion", num(50.0)), ("feather", num(1e12))]);
assert!(out.data.iter().all(|p| p[3].is_finite()));
let out = wipe(&[("completion", num(50.0)), ("angle", num(f64::NAN)), ("feather", num(f64::NAN))]);
assert!(out.data.iter().all(|p| p[3].is_finite()));
let out = wipe(&[("completion", num(f64::NAN))]);
assert!(out.data.iter().all(|p| p[3] == 1.0));
}
#[test]
fn small_gaussian_blurriness_is_continuous() {
// #1939: 0.9 used to be identical to 0, and 1.2 / 1.6 / 2.0 identical to each other.
+29 -11
View File
@@ -398,15 +398,38 @@ fn curve3(xs: [f64; 3], ys: [f64; 3], v: f64) -> f64 {
a.1 + (c.1 - a.1) * (v - a.0) / (c.0 - a.0).max(1e-9)
}
/// The Black, Mid and White Point parameters.
const STABILIZER_POINTS: [&str; 3] = ["blackPoint", "midPoint", "whitePoint"];
/// Color Stabilizer's samples: the current frame's means at the points' current positions and
/// the reference frame's means at the positions the points had at the reference time (After
/// Effects samples the reference where the points were when it was set: with keyframed points a
/// static picture is corrected, #3125). The points fall back to their current positions when
/// the host can't evaluate them at the reference time. `None` without a host or reference frame.
fn stabilizer_samples(ctx: &EffectCtx, b: &Buf) -> Option<([[f64; 3]; 3], [[f64; 3]; 3])> {
let host = ctx.env.host?;
let t_ref = ctx.params.f("referenceFrame");
let reference = host.self_at(t_ref, ctx.env.effect_index)?;
let r = ctx.params.f("sampleSize").max(0.5);
let pts = STABILIZER_POINTS.map(|id| ctx.params.v2(id));
let ref_params = host.params_at(t_ref);
let ref_pts = match &ref_params {
Some(p) => STABILIZER_POINTS.map(|id| p.v2(id)),
None => pts,
};
let cur = pts.map(|pt| sample_mean(b, pt, r));
let mut refv = [[0.0; 3]; 3];
for (o, pt) in refv.iter_mut().zip(ref_pts) {
*o = sample_mean(&reference, pt, r);
}
Some((cur, refv))
}
/// Color Stabilizer's correction of buffer `b` as one piecewise-linear map per channel (points
/// with increasing x; the end segments extend), the same maps `color_stabilizer` applies.
/// `None` without a host or reference frame (the layer passes through). (The GPU effect.)
pub fn color_stabilizer_maps(ctx: &EffectCtx, b: &Buf) -> Option<[Vec<(f64, f64)>; 3]> {
let reference = ctx.env.host?.self_at(ctx.params.f("referenceFrame"), ctx.env.effect_index)?;
let r = ctx.params.f("sampleSize").max(0.5);
let pts = [ctx.params.v2("blackPoint"), ctx.params.v2("midPoint"), ctx.params.v2("whitePoint")];
let cur = pts.map(|pt| sample_mean(b, pt, r));
let refv = pts.map(|pt| sample_mean(&reference, pt, r));
let (cur, refv) = stabilizer_samples(ctx, b)?;
let mode = ctx.params.e("stabilize");
Some([0, 1, 2].map(|k| {
let offset = |c0: f64, r0: f64| vec![(0.0, r0 - c0), (1.0, 1.0 + r0 - c0)];
@@ -439,12 +462,7 @@ pub fn color_stabilizer_maps(ctx: &EffectCtx, b: &Buf) -> Option<[Vec<(f64, f64)
}
pub(super) fn color_stabilizer(ctx: &EffectCtx, mut b: Buf) -> Buf {
let Some(host) = ctx.env.host else { return b };
let Some(reference) = host.self_at(ctx.params.f("referenceFrame"), ctx.env.effect_index) else { return b };
let r = ctx.params.f("sampleSize").max(0.5);
let pts = [ctx.params.v2("blackPoint"), ctx.params.v2("midPoint"), ctx.params.v2("whitePoint")];
let cur = pts.map(|pt| sample_mean(&b, pt, r));
let refv = pts.map(|pt| sample_mean(&reference, pt, r));
let Some((cur, refv)) = stabilizer_samples(ctx, &b) else { return b };
let mode = ctx.params.e("stabilize");
map_px(&mut b, |c| {
[0, 1, 2].map(|k| {
+77
View File
@@ -319,3 +319,80 @@ fn color_stabilizer_matches_the_reference_frame() {
let b = run_fx("ec.color.colorstabilizer", &vals2, lifted, 0.0, env);
assert!((b.img.get(5, 20)[0] - reference.get(5, 20)[0]).abs() < 0.01);
}
/// After Effects 2026's 320 × 180 test card from our importer samples (2026-11-05): a black to
/// white ramp across, six 40 px colour squares at y 45 and a white 30 px square moving from
/// x 20 to 300 at y 130 over 2 s.
fn stabilizer_card(t: f64) -> Image {
let mut img = Image::new(320, 180);
let cols = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0]];
let mover = 20.0 + 140.0 * t;
for y in 0..180 {
for x in 0..320 {
let (cx, cy) = (x as f64 + 0.5, y as f64 + 0.5);
let mut c = [(cx / 320.0) as f32; 3];
for (i, col) in cols.iter().enumerate() {
if (cx - (30.0 + 52.0 * i as f64)).abs() < 20.0 && (cy - 45.0).abs() < 20.0 {
c = col.map(|v| v as f32);
}
}
if (cx - mover).abs() < 15.0 && (cy - 130.0).abs() < 15.0 {
c = [1.0; 3];
}
img.set(x, y, [c[0], c[1], c[2], 1.0]);
}
}
img
}
/// The sample's keyframed points: Black Point (64, 90) → (151, 99) and Mid Point (160, 90) →
/// (188, 122) over the first second, White Point at (256, 90), Stabilize Levels.
struct KeyedCard;
impl EffectHost for KeyedCard {
fn layer(&self, _: u64, _: bool) -> Option<LayerPixels> {
None
}
fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option<Vec<f32>> {
None
}
fn self_at(&self, t: f64, _: usize) -> Option<Buf> {
Some(Buf { img: stabilizer_card(t), offset: [0.0; 2], scale: 1.0 })
}
fn params_at(&self, t: f64) -> Option<crate::Params> {
let mut p = crate::Params { values: Default::default() };
let k = t.clamp(0.0, 1.0);
let lerp = |a: [f64; 2], b: [f64; 2]| Value::Vec2([a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k]);
p.values.insert("blackPoint".into(), lerp([64.0, 90.0], [151.0, 99.0]));
p.values.insert("midPoint".into(), lerp([160.0, 90.0], [188.0, 122.0]));
p.values.insert("whitePoint".into(), Value::Vec2([256.0, 90.0]));
Some(p)
}
}
/// #3125: with keyframed sample points After Effects samples the reference frame where the
/// points were at the reference time, so a static card is corrected. Its render at 0.5 s (Black
/// Point at (107.5, 94.5)) is a Levels map of the ramp: `out = a + b·v` with b 1.2935..1.2965
/// and a −0.2365..−0.2350 (fitted on our 26-level export). EffectCraft sampled both frames at
/// the current points and left the card unchanged.
#[test]
fn color_stabilizer_samples_the_reference_at_the_points_reference_positions() {
let host = KeyedCard;
let env = EffectEnv { host: Some(&host), ..Default::default() };
let p = host.params_at(0.5).unwrap();
let mut vals: Vec<(&str, Value)> = ["blackPoint", "midPoint", "whitePoint"].iter().map(|id| (*id, p.values[*id].clone())).collect();
vals.push(("stabilize", Value::Enum(1)));
vals.push(("sampleSize", num(3.0)));
vals.push(("referenceFrame", num(0.0)));
let out = run_fx("ec.color.colorstabilizer", &vals, stabilizer_card(0.5), 0.5, env);
// The ramp row between the squares: fit out = a + b·v from two far-apart pixels.
let v = |x: i64| (x as f64 + 0.5) / 320.0;
let o = |x: i64| out.img.get(x, 90)[0] as f64;
let b = (o(240) - o(80)) / (v(240) - v(80));
let a = o(80) - b * v(80);
assert!((b - 1.295).abs() < 0.005, "slope {b}");
assert!((a + 0.2357).abs() < 0.005, "offset {a}");
// Every ramp pixel of that row follows the line (no clamping in 32 bpc).
for x in (0..320).step_by(7) {
assert!((o(x) - (a + b * v(x))).abs() < 1e-3, "x {x}");
}
}
+59 -10
View File
@@ -1,4 +1,5 @@
//! File ▸ Import ▸ After Effects Project… (`effectcraft_aep::import`).
//! File ▸ Import ▸ After Effects Project… (`effectcraft_aep::import`) and File ▸ Export ▸ After Effects
//! Project… (`effectcraft_aep::export`).
//!
//! Adds the items of an `.aep` (or its XML form, `.aepx`) to the project in a folder named after
//! the file (`docs/aep-import.md` lists what arrives). What the importer cannot bring over (effects
@@ -7,6 +8,7 @@
//! in the report's `missingFonts` (not a loss: the text keeps the font name and is drawn with the
//! fallback font).
use effectcraft_aep::export::{AepExportError, ExportOptions};
use effectcraft_aep::import::{AepImportError, ImportOptions};
use effectcraft_project::{FootageKind, ItemKind};
use serde_json::{Value, json};
@@ -88,14 +90,61 @@ fn import_aep(s: &mut Session, p: &Value) -> Result<Value> {
}))
}
fn export_aep(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_p(p, "path").ok_or_else(|| bad("file.exportAep", "missing `path`"))?.to_string();
let allow_losses = b_p(p, "allowLosses").unwrap_or(false);
let dry_run = b_p(p, "dryRun").unwrap_or(false);
if dry_run {
return Ok(json!({"dryRun": true, "report": effectcraft_aep::export::analyze(&s.project)}));
}
// Image-sequence folders keep their stored numbering in After Effects only with their actual
// modification time (otherwise it rescans them and warns about every gap on open). The folder
// is looked at only when the sequence's file passes the document-path policy (a path that came
// from a document is followed as import followed it; a refused one leaves the time unset).
let services = s.services.clone();
let stored = s.stored_paths.clone();
let folder_time = move |file: &str| {
let file = stored.follow(file).ok()?;
let file = file.to_str()?;
// Either separator, as the exporter splits the alias (a Windows path on another system).
let dir = file.get(..file.rfind(['/', '\\'])?).filter(|d| !d.is_empty())?;
services.stamp(dir).and_then(|(_, ns)| u64::try_from(ns / 1_000_000_000).ok())
};
let res = effectcraft_aep::export::export_with(&s.project, &ExportOptions { allow_losses }, &folder_time).map_err(|e| match e {
AepExportError::Refused(_) => {
EngineError::Other(format!("{e} (nothing was written: pass `allowLosses` to export anyway, or `dryRun` for the full report)"))
}
other => EngineError::Other(format!("cannot export {path}: {other}")),
})?;
s.services.write_file(&path, &res.bytes).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
let losses = res.report.total_losses();
s.toast(if losses == 0 {
format!("Exported After Effects project to {path}")
} else {
format!("Exported After Effects project to {path} ({losses} unsupported item{} not exported)", if losses == 1 { "" } else { "s" })
});
Ok(json!({"path": path, "bytes": res.bytes.len(), "report": res.report}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"file.importAep",
"After Effects Project...",
["File", "Import"],
None,
"{path (.aep or .aepx), allowLosses?: bool (import although parts cannot be imported), dryRun?: bool (only return the report), applySettings?: bool (take over the file's project settings; default: when the project has no compositions)}",
always,
import_aep
)]
vec![
cmd!(
"file.importAep",
"After Effects Project...",
["File", "Import"],
None,
"{path (.aep or .aepx), allowLosses?: bool (import although parts cannot be imported), dryRun?: bool (only return the report), applySettings?: bool (take over the file's project settings; default: when the project has no compositions)}",
always,
import_aep
),
cmd!(
"file.exportAep",
"After Effects Project...",
["File", "Export"],
None,
"{path (.aep), allowLosses?: bool (export although parts cannot be exported), dryRun?: bool (only return the report)}",
always,
export_aep
),
]
}
+4 -3
View File
@@ -6,7 +6,7 @@ use effectcraft_project::{Comp, Expression, ItemId, ItemKind, Layer, LayerId, La
use effectcraft_time::Tick;
use serde_json::{Value, json};
use super::{CommandSpec, has_comp, has_layers, layers_or, layers_p, match_path_of, selected_leaf_props, str_p};
use super::{CommandSpec, has_comp, has_layers, layers_or, layers_p, match_path_of, merge_p, selected_leaf_props, str_p};
use crate::{EngineError, KeyRef, LinkClip, Result, Session, cmd};
fn can_undo(s: &Session) -> std::result::Result<(), String> {
@@ -145,7 +145,8 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
Some(layer) => layers_or(s, p, &[layer])?,
None => layers_p(s, p)?,
};
let new = s.edit("Duplicate", None, |proj, st| {
// `merge` folds the copy and the drag that follows it (Alt-drag in the viewer) into one undo step.
let new = s.edit("Duplicate", merge_p(p), |proj, st| {
let mut next = proj.next_id;
let comp = proj.comp_mut(cid).ok_or(crate::EngineError::NoComp)?;
let mut created = vec![];
@@ -1007,7 +1008,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Duplicate",
["Edit"],
Some("Cmd+D"),
"{layers?} (without layers: during a text edit the edited layer, else the selected effects, shape items or text animators, else the selected layers)",
"{layers?, merge?} (without layers: during a text edit the edited layer, else the selected effects, shape items or text animators, else the selected layers)",
layers_or_text_edit,
duplicate
),
+1 -2
View File
@@ -517,12 +517,11 @@ impl CryptoProbe {
media_overrides: &[],
};
let params = effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(layer, pr));
let want = effectcraft_effects::CRYPTO_LAYERS.get(params.e("layer") as usize).copied().unwrap_or("CryptoAsset");
let aux = r.layer_aux(&ctx, layer).ok_or(NO_CRYPTO)?;
if !live() {
return Ok(None);
}
let layer_name = aux.resolve_crypto_layer(want).ok_or(NO_CRYPTO)?;
let layer_name = effectcraft_effects::crypto_layer_named(&aux, params.s("layerName"), params.e("layer") as usize).ok_or(NO_CRYPTO)?;
// The grid of the effect's input buffer (footage keeps native pixels from 3/4 scale
// up, proxies have their own size, earlier effects can pad it), rendered and cached.
if !live() {
+7 -2
View File
@@ -160,7 +160,8 @@ pub fn layered_exr(s: &Session, cid: ItemId, t: Tick, scale: f64) -> Result<(Vec
// The composite and every layer without the HDR step, decoded with the output space's
// curve (linear light in the output space's primaries).
let (full, layers) = isolate(s, cid, t, scale, true)?;
let dec = effectcraft_render::color::Pipe::of(&s.project.settings).output_linear();
let pipe = effectcraft_render::color::Pipe::of(&s.project.settings);
let dec = pipe.output_linear();
let (w, h) = (full.width as usize, full.height as usize);
let planes = |img: &effectcraft_raster::Image| -> [Vec<f32>; 4] {
let mut out: [Vec<f32>; 4] = Default::default();
@@ -192,7 +193,11 @@ pub fn layered_exr(s: &Session, cid: ItemId, t: Tick, scale: f64) -> Result<(Vec
}
let layer = Layer::new((w, h), LayerAttributes::default(), Encoding::SMALL_LOSSLESS, AnyChannels::sort(channels.into()));
let mut buf = std::io::Cursor::new(Vec::new());
Image::from_layer(layer).write().to_buffered(&mut buf).map_err(|e| EngineError::Other(format!("EXR encoding failed: {e}")))?;
let mut image = Image::from_layer(layer);
// The primaries and white the values are in (the output space's), for Nuke, AE and Blender.
let [red, green, blue, white] = pipe.output_linear_space().exr_chromaticities().map(|[x, y]| Vec2(x, y));
image.attributes.chromaticities = Some(exr::meta::attribute::Chromaticities { red, green, blue, white });
image.write().to_buffered(&mut buf).map_err(|e| EngineError::Other(format!("EXR encoding failed: {e}")))?;
Ok((buf.into_inner(), names, full.width, full.height))
}
+2 -1
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
fe!("app.commandPalette", "Quick Apply...", ["Edit"], Some("Cmd+Shift+Space"), "{query?}", always),
fe!("app.keyboardShortcuts", "Keyboard Shortcuts", ["Edit"], Some("Cmd+Alt+'"), "{}", always),
fe!("app.templates", "Templates", [], None, "{kind: renderSettings|outputModule}", always),
fe!("app.find", "Find", ["File"], Some("Cmd+F"), "{query?}", always),
fe!("app.find", "Find", ["File"], Some("Cmd+F"), "{query?: string, status?: all|available|missing}", always),
fe!("effects.copyPresetsFolderPath", "Copy Presets Folder Path", [], None, "{}", always),
// Preview.
fe!(
@@ -106,6 +106,7 @@ pub fn specs() -> Vec<CommandSpec> {
fe!("layer.openLayer", "Open Layer", ["Layer"], None, "{layer?}", has_layers),
fe!("effect.manage", "Manage Effects...", ["Effect"], None, "{}", always),
fe!("anim.browsePresets", "Browse Presets...", ["Animation"], None, "{}", always),
fe!("timeline.revealMask", "Reveal Created Mask", [], None, "{comp, layer, mask, projectEpoch} — engine-supplied creation identity", has_comp),
// Project panel: delete the selected items without the prompt that Delete shows when
// compositions use them. The UI runs `project.delete` (agents can run it directly).
fe!(
+1 -1
View File
@@ -182,7 +182,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Mask",
["Layer", "Mask"],
Some("Cmd+Shift+N"),
"{layer?, shape?: rect|ellipse|rounded|polygon|star, rect? [x,y,w,h] (layer space; a polygon or star fits its width), mode?}",
"{layer?, shape?: rect|ellipse|rounded|polygon|star, rect? [x,y,w,h] (layer space; a polygon or star fits its width), roundness? (a rounded rectangle's corner radius in px; default 20), mode?}",
has_layers,
add_mask
),
+15 -1
View File
@@ -4,6 +4,7 @@ use super::{
layer_p, merge_p, str_p,
};
/// Add a tool-shaped mask in one document edit, then request its Timeline controls separately.
pub(super) fn add_mask(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, lid) = layer_p(s, p, "layer.addMask")?;
let layer = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?.clone();
@@ -16,8 +17,17 @@ pub(super) fn add_mask(s: &mut Session, p: &Value) -> Result<Value> {
None => (if w > 0.0 { w / 2.0 } else { 0.0 }, h / 2.0, w * 0.6, h * 0.6),
};
// The shape tools' masks: rectangle, ellipse, rounded rectangle, polygon or star.
let path = crate::cmd::shape_tool::mask_path(shape, [cx, cy], [rw, rh])
let radius = match p.get("roundness").filter(|v| !v.is_null()) {
None => None,
Some(v) => {
Some(v.as_f64().filter(|r| r.is_finite() && *r >= 0.0).ok_or_else(|| bad("layer.addMask", "`roundness` is a corner radius in pixels, 0 or more"))?)
}
};
let path = crate::cmd::shape_tool::mask_path_rounded(shape, [cx, cy], [rw, rh], radius)
.ok_or_else(|| bad("layer.addMask", format!("unknown shape `{shape}`; one of rect, ellipse, rounded, polygon, star")))?;
if radius.is_some() && !matches!(shape, "rounded" | "roundedRect") {
return Err(bad("layer.addMask", "`roundness` only applies to shapes `rounded` and `roundedRect`"));
}
let mode = str_p(p, "mode").and_then(MaskMode::from_name).unwrap_or(MaskMode::Add);
let cycle = s.prefs.appearance.cycle_mask_colors;
let uid = s.edit("New Mask", None, |proj, _| {
@@ -31,6 +41,10 @@ pub(super) fn add_mask(s: &mut Session, p: &Value) -> Result<Value> {
proj.next_id = next;
Ok(uid)
})?;
s.events.push(crate::Event::Frontend {
command: "timeline.revealMask".into(),
params: json!({"comp": cid.0, "layer": lid.0, "mask": uid, "projectEpoch": s.script_ui.project_epoch}),
});
Ok(json!({"mask": uid}))
}
+80 -4
View File
@@ -243,17 +243,80 @@ fn set_transform(s: &mut Session, p: &Value) -> Result<Value> {
fn center_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, ids) = layers_p(s, p)?;
let ids = super::unlocked(s, cid, ids, "layer.centerAnchor")?;
move_anchor(s, cid, &ids, "Center Anchor Point", false, |[x0, y0, x1, y1]| [(x0 + x1) / 2.0, (y0 + y1) / 2.0])
}
/// The nine points Quick Set Anchor offers, as `(name, column, row)`: column 0 is the left edge
/// of the layer's content, 2 the right; row 0 the top, 2 the bottom.
const ANCHOR_POINTS: [(&str, u8, u8); 9] = [
("topLeft", 0, 0),
("top", 1, 0),
("topRight", 2, 0),
("left", 0, 1),
("center", 1, 1),
("right", 2, 1),
("bottomLeft", 0, 2),
("bottom", 1, 2),
("bottomRight", 2, 2),
];
/// `layer.quickSetAnchor {point, layers?}`: move the Anchor Point of the 2D layers to one of the
/// nine points of their content (corners, edge midpoints, centre) and shift Position, and every
/// Position key, so nothing moves on screen. 3D and locked layers, and layers with an animated
/// (or expression-driven) Anchor Point, Scale or Rotation, an expression on Position, or Auto-Orient
/// along the path, are skipped; an error when no layer is left or none has content bounds.
fn quick_set_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let c = "layer.quickSetAnchor";
let name = str_p(p, "point").ok_or_else(|| bad(c, "missing `point`"))?;
let (_, col, row) = ANCHOR_POINTS
.iter()
.copied()
.find(|(n, ..)| *n == name)
.ok_or_else(|| bad(c, format!("unknown point `{name}`; one of {}", ANCHOR_POINTS.map(|(n, ..)| n).join(", "))))?;
let (cid, ids) = layers_p(s, p)?;
let ids = super::unlocked(s, cid, ids, c)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
// The anchor is set at the current time and the Position shift is worked out from the current
// Anchor Point, Scale and Rotation, so a layer where any of them changes over time would move
// at other frames: it is skipped like a 3D one. So is a layer whose Position is expression-
// driven (the expression would override the shifted value and the layer would jump), and one
// that orients itself along its path (the renderer adds the path direction to Rotation).
let changes = |l: &effectcraft_project::Layer| {
let Some(tr) = l.transform() else { return false };
let moving = ["anchor", "scale", "rotation"].iter().any(|m| tr.get(m).is_some_and(|p| p.is_animated() || p.has_expression()));
let driven = ["position", "positionX", "positionY"].iter().any(|m| tr.get(m).is_some_and(|p| p.has_expression()));
moving || driven || l.auto_orient == effectcraft_project::AutoOrient::AlongPath
};
let flat: Vec<LayerId> = ids.into_iter().filter(|id| comp.layer(*id).is_some_and(|l| !l.is_3d() && !changes(l))).collect();
if flat.is_empty() {
return Err(bad(
c,
"Quick Set Anchor works on 2D layers whose Anchor Point, Scale and Rotation are not animated, whose Position has no expression and that do not auto-orient along a path",
));
}
let at = |lo: f64, hi: f64, i: u8| lo + (hi - lo) * f64::from(i) / 2.0;
move_anchor(s, cid, &flat, "Quick Set Anchor", true, |[x0, y0, x1, y1]| [at(x0, x1, col), at(y0, y1, row)])
}
/// Move each layer's Anchor Point to `target(content bounds)` (layer space) and offset Position
/// by the matching amount, so the layer stays put over its whole animation. Layers without content
/// bounds (an empty text or shape layer) are left alone; with `strict` it is an error when none of
/// the layers has any, so the command does not report success for a no-op.
fn move_anchor(s: &mut Session, cid: ItemId, ids: &[LayerId], label: &str, strict: bool, target: impl Fn([f64; 4]) -> [f64; 2]) -> Result<Value> {
let t = s.time();
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, t);
let mut centers = vec![];
for lid in &ids {
for lid in ids {
let Some(l) = comp.layer(*lid) else { continue };
if let Some([x0, y0, x1, y1]) = effectcraft_render::content_bounds(&ctx, l) {
centers.push((*lid, [(x0 + x1) / 2.0, (y0 + y1) / 2.0]));
if let Some(b) = effectcraft_render::content_bounds(&ctx, l) {
centers.push((*lid, target(b)));
}
}
s.edit("Center Anchor Point", None, |proj, _| {
if strict && centers.is_empty() {
return Err(bad("layer.quickSetAnchor", "none of the layers has content to anchor to (empty text or shape layers have no bounds)"));
}
s.edit(label, None, |proj, _| {
for (lid, c) in &centers {
let l = layer_mut(proj, cid, *lid)?;
let lt = l.layer_time(t);
@@ -718,6 +781,9 @@ fn opens_as_bundle(dir: &std::path::Path) -> bool {
/// plain folder after following links, is refused.
pub(crate) fn reveal_url(s: &Session, stored: &str) -> std::result::Result<String, String> {
let path = s.stored_path(stored).map_err(|why| crate::doc_path::refusal(stored, why))?;
if !s.services.exists(&path.to_string_lossy()) {
return Err(format!("Missing footage: {stored}. Use File ▸ Dependencies ▸ Relink Missing Footage or Replace Footage."));
}
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).ok_or_else(|| format!("{stored} is not in a folder"))?;
let real = std::fs::canonicalize(dir).map_err(|e| format!("cannot show the folder of {stored}: {e}"))?;
if !real.is_dir() || opens_as_bundle(dir) || opens_as_bundle(&real) {
@@ -902,6 +968,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_layers,
center_anchor
),
cmd!(
"layer.quickSetAnchor",
"Quick Set Anchor",
["Layer", "Transform", "Quick Set Anchor"],
None,
"{point: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight, layers?} → {layers}: moves the Anchor Point of 2D layers to that point of their content and compensates Position (and its keys); skips 3D and locked layers and those with an animated Anchor Point, Scale or Rotation",
has_layers,
quick_set_anchor
),
cmd!(
"layer.mask.shape",
"Mask Shape...",
@@ -966,6 +1041,7 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
for f in ["Clips", "Tool.app", "Shell.{20D04FE0-3AEA-1069-A2D8-08002B30309D}"] {
std::fs::create_dir_all(d.join(f)).unwrap();
std::fs::write(d.join(f).join("a.mov"), b"fixture").unwrap();
}
let s = crate::Session::default();
let reveal = |folder: &str| super::reveal_url(&s, &d.join(folder).join("a.mov").to_string_lossy());
+119
View File
@@ -174,6 +174,10 @@ fn new_mask(s: &mut Session, p: &Value) -> Result<Value> {
st.selected_vertices = vec![VertexRef { layer: lid, mask: uid, index: n - 1 }];
Ok(uid)
})?;
s.events.push(crate::Event::Frontend {
command: "timeline.revealMask".into(),
params: json!({"comp": cid.0, "layer": lid.0, "mask": uid, "projectEpoch": s.script_ui.project_epoch}),
});
Ok(json!({"mask": uid}))
}
@@ -225,6 +229,120 @@ fn set_closed(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!(c))
}
/// Rebuild a rectangular mask or shape path with corner radius `radius` (layer pixels; 0 gives
/// square corners). The rectangle is the path's bounding box. Only a plain rectangle (four
/// corner vertices, straight sides) or a rounded one (eight vertices, straight sides alternating
/// with circular corners) is reshaped; anything else (an ellipse, a star) is refused. The new path
/// keeps the old one's start vertex and direction, so the feather points and the other keys of an
/// animated path still line up; a change between square and rounded corners changes the vertex
/// count, which is refused when the path is keyed or has feather points.
fn set_roundness(s: &mut Session, p: &Value) -> Result<Value> {
let c = "mask.setRoundness";
let radius = p.get("roundness").and_then(Value::as_f64).filter(|r| r.is_finite() && *r >= 0.0);
let radius = radius.ok_or_else(|| bad(c, "need `roundness`: a corner radius in pixels, 0 or more"))?;
let (cid, lid) = layer_p(s, p, c)?;
let key = p.get("mask").cloned().ok_or_else(|| bad(c, "missing `mask` (uid, index or name)"))?;
let t = s.time();
s.edit(c, merge_p(p), |proj, _| {
let l = layer_mut(proj, cid, lid)?;
let lt = l.layer_time(t);
let g = path_group(&mut l.props, &key).ok_or_else(|| bad(c, "no such mask or shape path"))?;
let roto = super::paths::is_roto(g);
let pr = g.get_mut("path").ok_or_else(|| bad(c, "mask has no path"))?;
let KV::Path(mut sp) = pr.value_at(lt) else { return Err(bad(c, "not a path")) };
sp.fit_tangents();
let (lo, hi) = rect_box(&sp).ok_or_else(|| bad(c, "the path is not a closed rectangle or rounded rectangle"))?;
let size = [hi[0] - lo[0], hi[1] - lo[1]];
let bez = effectcraft_path::rect(size, [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0], radius);
let mut new = effectcraft_path::from_kurbo(&bez).into_iter().next().ok_or_else(|| bad(c, "could not rebuild the path"))?;
if new.vertices.len() != sp.vertices.len() {
if !pr.keys.is_empty() {
return Err(bad(c, "the path is keyed: changing between square and rounded corners would change its vertex count"));
}
if !sp.feather.is_empty() {
return Err(bad(c, "the path has feather points: changing between square and rounded corners would change its vertex count"));
}
}
align_like(&mut new, &sp);
new.feather = std::mem::take(&mut sp.feather);
if roto {
super::paths::roto_smooth(&mut new);
}
pr.set_value_at(lt, KV::Path(new));
Ok(())
})?;
Ok(Value::Null)
}
/// The bounding box of `sp` when it is a closed plain rectangle (four corner vertices, straight
/// sides) or rounded rectangle (eight vertices on the box's edges, straight sides along the edges
/// alternating with circular corners whose two ends are as far apart across as down).
fn rect_box(sp: &ShapePath) -> Option<([f64; 2], [f64; 2])> {
let first = *sp.vertices.first()?;
let (mut lo, mut hi) = (first, first);
for v in &sp.vertices {
lo = [lo[0].min(v[0]), lo[1].min(v[1])];
hi = [hi[0].max(v[0]), hi[1].max(v[1])];
}
let n = sp.vertices.len();
if !sp.closed || !(n == 4 || n == 8) || hi[0] <= lo[0] || hi[1] <= lo[1] {
return None;
}
let eps = 1e-9 * (hi[0] - lo[0]).max(hi[1] - lo[1]).max(1.0);
let x_edge = |v: [f64; 2]| v[0] == lo[0] || v[0] == hi[0];
let y_edge = |v: [f64; 2]| v[1] == lo[1] || v[1] == hi[1];
let zero = |t: Option<&[f64; 2]>| t.is_none_or(|t| *t == [0.0, 0.0]);
let seg = |i: usize| (sp.vertices[i], sp.vertices[(i + 1) % n]);
let straight = |i: usize| {
let (a, b) = seg(i);
zero(sp.out_tangents.get(i)) && zero(sp.in_tangents.get((i + 1) % n)) && ((a[0] == b[0] && x_edge(a)) || (a[1] == b[1] && y_edge(a)))
};
let corner = |i: usize| {
let (a, b) = seg(i);
let (dx, dy) = ((b[0] - a[0]).abs(), (b[1] - a[1]).abs());
dx > eps && (dx - dy).abs() <= eps.max(dx * 1e-9) && ((x_edge(a) && y_edge(b)) || (y_edge(a) && x_edge(b)))
};
let ok = if n == 4 {
sp.vertices.iter().all(|v| x_edge(*v) && y_edge(*v)) && (0..n).all(straight)
} else {
sp.vertices.iter().all(|v| x_edge(*v) || y_edge(*v)) && (0..2).any(|k| (0..n).all(|i| if i % 2 == k { straight(i) } else { corner(i) }))
};
ok.then_some((lo, hi))
}
/// Turn the rebuilt closed path `new` so it runs the same way round as `old` and starts at the
/// vertex nearest `old`'s first one, keeping vertex correspondence for keys and feather points.
fn align_like(new: &mut ShapePath, old: &ShapePath) {
let area = |sp: &ShapePath| {
let n = sp.vertices.len();
(0..n)
.map(|i| {
let (a, b) = (sp.vertices[i], sp.vertices[(i + 1) % n]);
a[0] * b[1] - b[0] * a[1]
})
.sum::<f64>()
};
if (area(new) > 0.0) != (area(old) > 0.0) {
// Reverse: vertex order flips and each vertex's in and out tangents swap; keep vertex 0.
new.vertices.reverse();
std::mem::swap(&mut new.in_tangents, &mut new.out_tangents);
new.in_tangents.reverse();
new.out_tangents.reverse();
let n = new.vertices.len();
if n > 0 {
new.vertices.rotate_right(1);
new.in_tangents.rotate_right(1);
new.out_tangents.rotate_right(1);
}
}
let Some(o) = old.vertices.first() else { return };
let d = |v: &[f64; 2]| (v[0] - o[0]).powi(2) + (v[1] - o[1]).powi(2);
let start = new.vertices.iter().enumerate().min_by(|a, b| d(a.1).total_cmp(&d(b.1))).map_or(0, |(i, _)| i);
new.vertices.rotate_left(start);
new.in_tangents.rotate_left(start);
new.out_tangents.rotate_left(start);
}
/// Selected (or given) vertices grouped per (layer, mask).
fn vertex_groups(s: &Session, p: &Value) -> Result<std::collections::BTreeMap<(u64, Uid), Vec<usize>>> {
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
@@ -645,6 +763,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("mask.addVertex", "Add Mask Vertex", [], None, "{layer?, mask, point: [x,y], in?, out?, index?}", has_layers, add_vertex),
cmd!("mask.setVertex", "Set Mask Vertex", [], None, "{layer?, mask, index, point?, in?, out?, merge?}", has_layers, set_vertex),
cmd!("mask.setClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{layer?, mask, closed?}", has_layers, set_closed),
cmd!("mask.setRoundness", "Set Mask Roundness", [], None, "{layer?, mask, roundness (corner radius in px; 0 = square)}", has_layers, set_roundness),
cmd!("mask.selectVertices", "Select Mask Vertices", [], None, "{vertices: [{layer, mask, index}], add?, toggle?}", has_comp, select_vertices),
cmd!("mask.moveVertices", "Move Mask Vertices", [], None, "{vertices?: [{layer, mask, index}], delta: [dx,dy], merge?}", has_vertices, move_vertices),
cmd!("mask.deleteVertices", "Delete Mask Vertices", [], None, "{vertices?}", has_vertices, delete_vertices),
+1
View File
@@ -53,6 +53,7 @@ fn probe(s: &Session, path: &str, cmd: &str) -> Result<Footage> {
/// Attach `footage` as the proxy of `items` (Use Proxy on). One undo step.
pub(crate) fn set_proxy_footage(s: &mut Session, items: &[ItemId], footage: Footage) -> Result<()> {
s.stored_paths.allow(&footage);
s.edit("Set Proxy", None, |proj, _| {
for i in items {
if let Some(it) = proj.item_mut(*i) {
+3 -3
View File
@@ -46,9 +46,9 @@ fn summary(s: &mut Session, _: &Value) -> Result<Value> {
o["layers"] = json!(c.layers.len());
o["frameRate"] = json!(c.frame_rate.as_f64());
}
// Footage (or the proxy in use) that shows no picture although its file is there (a
// codec or profile the decoders lack): why, so an agent can tell the user.
if let Some(why) = s.footage.item_problem(i) {
// Include offline originals and unused proxies in the inventory reported to agents.
o["missing"] = json!(i.has_missing_footage());
if let Some(why) = s.footage.item_problem(i).or_else(|| crate::render::missing_item_problem(i)) {
o["problem"] = json!(why);
}
o
+23 -6
View File
@@ -6,9 +6,9 @@
//! `index` (1-based, the # column).
use effectcraft_project::render_queue::{
AlphaMode, AudioFormat, AudioOutput, Channels, ColorDepth, CurrentOrOff, DEFAULT_SEQUENCE_TEMPLATE, DEFAULT_TEMPLATE, EffectsMode, FieldRender,
OutputFormat, OutputModule, PostRenderAction, ProResProfile, Pulldown, RESIZE_PRESETS, RenderLog, RenderQuality, RenderQueueItem, RenderSettings,
RenderStatus, ResizeQuality, SwitchOverride, TimeSpan, post_render_parse, without_project_extension,
AlphaMode, AudioFormat, AudioOutput, Channels, ColorDepth, CurrentOrOff, DEFAULT_SEQUENCE_TEMPLATE, DEFAULT_TEMPLATE, EffectsMode, ExrBitDepth,
ExrCompression, FieldRender, OutputFormat, OutputModule, PostRenderAction, ProResProfile, Pulldown, RESIZE_PRESETS, RenderLog, RenderQuality,
RenderQueueItem, RenderSettings, RenderStatus, ResizeQuality, SwitchOverride, TimeSpan, post_render_parse, without_project_extension,
};
use effectcraft_project::render_templates::{RenderTemplates, TemplateKind, TemplateSlot};
use effectcraft_time::{FrameRate, Tick};
@@ -202,6 +202,9 @@ fn apply_om_template(om: &mut OutputModule, t: &OutputModule) {
om.name = t.name.clone();
}
/// The `exrCompression` parameter's values.
const EXR_COMPRESSIONS: &str = "none|rle|zips|zip|piz|pxr24|b44|b44a|dwaa|dwab";
/// The `format` parameter's values.
const FORMATS: &str = "format: h264|hevc|av1|prores|uncompressed|webm|png|jpeg|tiff|exr|tga|gif|wav|aiff";
@@ -311,6 +314,17 @@ fn apply_resize(om: &mut OutputModule, p: &Value, cmd: &str) -> Result<()> {
Ok(())
}
/// OpenEXR `exrCompression` and `exrBitDepth`.
fn apply_exr(om: &mut OutputModule, p: &Value, cmd: &str) -> Result<()> {
if let Some(c) = enum_p(p, "exrCompression", cmd, ExrCompression::from_name, EXR_COMPRESSIONS)? {
om.exr_compression = c;
}
if let Some(d) = enum_p(p, "exrBitDepth", cmd, ExrBitDepth::from_name, "half|float")? {
om.exr_bit_depth = d;
}
Ok(())
}
/// Apply Output Module parameters (`template` first). `roi`: the viewer's region of interest
/// (captured by `crop.useRoi`).
fn apply_output(om: &mut OutputModule, templates: &RenderTemplates, roi: Option<[f64; 4]>, p: &Value, cmd: &str) -> Result<bool> {
@@ -344,6 +358,7 @@ fn apply_output(om: &mut OutputModule, templates: &RenderTemplates, roi: Option<
if let Some(pp) = str_p(p, "proresProfile") {
om.prores_profile = ProResProfile::from_name(pp).ok_or_else(|| bad(cmd, "proresProfile: proxy|lt|standard|hq|4444|4444xq"))?;
}
apply_exr(om, p, cmd)?;
apply_crop(om, roi, p, cmd)?;
apply_resize(om, p, cmd)?;
if let Some(a) = p.get("audio") {
@@ -745,6 +760,8 @@ fn formats(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({
"formats": v,
"proresProfiles": ProResProfile::ALL.iter().map(|p| p.label()).collect::<Vec<_>>(),
"exrCompressions": ExrCompression::ALL.iter().map(|c| json!({"id": c.name(), "label": c.label(), "lossyHalf": c.is_lossy(ExrBitDepth::Half), "lossyFloat": c.is_lossy(ExrBitDepth::Float)})).collect::<Vec<_>>(),
"exrBitDepths": ExrBitDepth::ALL.iter().map(|d| d.name()).collect::<Vec<_>>(),
"codecProfiles": CodecProfile::ALL.iter().map(|p| p.label()).collect::<Vec<_>>(),
"hevcLevels": VideoCodecOptions::HEVC_LEVELS.iter().map(level).collect::<Vec<_>>(),
"av1Levels": VideoCodecOptions::AV1_LEVELS.iter().map(level).collect::<Vec<_>>(),
@@ -1036,7 +1053,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add to Render Queue",
["Composition"],
["Cmd+M", "Cmd+Shift+/"],
"{comp?: id|name, template?: Render Settings template, format?: h264|hevc|av1|prores|uncompressed|webm|png|jpeg|tiff|exr|tga|gif|wav|aiff, output?: path|template, log?: errorsOnly|plusSettings|plusPerFrameInfo, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, proxyUse?, effects?, solo?, guideLayers?, colorDepth?, frameBlending?, fieldRender?, pulldown?, motionBlur?, timeSpan?: workArea|comp|custom, start?: s, end?: s, duration?: s, frameRate?: fps|null, skipExisting?: bool, storageOverflow?: bool, channels?: rgb|rgba|alpha, color?, bitrate?: kbps, webmBitrate?, keyframeInterval?, proresProfile?, profile?, level?, rateControl?, webmCodec?, audioBitrate?, opusApplication?, crop?, resize?, includeProjectLink?, audio?: auto|on|off, sampleRate?, audioChannels?, audioFormat?, loop?: bool (values as in setRenderSettings / setOutputModule)}",
"{comp?: id|name, template?: Render Settings template, format?: h264|hevc|av1|prores|uncompressed|webm|png|jpeg|tiff|exr|tga|gif|wav|aiff, output?: path|template, log?: errorsOnly|plusSettings|plusPerFrameInfo, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, proxyUse?, effects?, solo?, guideLayers?, colorDepth?, frameBlending?, fieldRender?, pulldown?, motionBlur?, timeSpan?: workArea|comp|custom, start?: s, end?: s, duration?: s, frameRate?: fps|null, skipExisting?: bool, storageOverflow?: bool, channels?: rgb|rgba|alpha, color?, bitrate?: kbps, webmBitrate?, keyframeInterval?, proresProfile?, exrCompression?, exrBitDepth?, profile?, level?, rateControl?, webmCodec?, audioBitrate?, opusApplication?, crop?, resize?, includeProjectLink?, audio?: auto|on|off, sampleRate?, audioChannels?, audioFormat?, loop?: bool (values as in setRenderSettings / setOutputModule)}",
can_add,
add
),
@@ -1056,7 +1073,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Output Module Settings...",
[],
None,
"{item?|index?, module?: n (1 = first), template?: name, format?: h264|hevc|av1|prores|uncompressed|webm|png|jpeg|tiff|exr|tga|gif|wav|aiff, channels?: rgb|rgba|alpha, color?: straight|premultiplied, quality?: 1-100, bitrate?: kbps, webmBitrate?: bool, keyframeInterval?: frames (0 = auto), proresProfile?: proxy|lt|standard|hq|4444|4444xq, profile?: main|main10 (HEVC/AV1), level?: auto|4.1, rateControl?: bitrate|quality, webmCodec?: vp9|av1, audioBitrate?: Opus kbps, opusApplication?: audio|voice, crop?: bool|{useRoi?, roi?, top?, left?, bottom?, right?}, cropTop?, cropLeft?, cropBottom?, cropRight?, resize?: bool|{preset?, width?, height?, lockAspect?, quality?: low|high}, resizeWidth?, resizeHeight?, postRenderAction?: none|import|importAndReplace|setProxy, includeProjectLink?: bool, audio?: auto|on|off, sampleRate?, audioChannels?: mono|stereo, audioFormat?: 16|24|32, loop?: bool, output?}",
"{item?|index?, module?: n (1 = first), template?: name, format?: h264|hevc|av1|prores|uncompressed|webm|png|jpeg|tiff|exr|tga|gif|wav|aiff, channels?: rgb|rgba|alpha, color?: straight|premultiplied, quality?: 1-100, bitrate?: kbps, webmBitrate?: bool, keyframeInterval?: frames (0 = auto), proresProfile?: proxy|lt|standard|hq|4444|4444xq, exrCompression?: none|rle|zips|zip|piz|pxr24|b44|b44a|dwaa|dwab (OpenEXR, scan lines; default zip; lossy: pxr24 on float, b44/b44a on half, dwaa/dwab), exrBitDepth?: half|float (OpenEXR; default float), profile?: main|main10 (HEVC/AV1), level?: auto|4.1, rateControl?: bitrate|quality, webmCodec?: vp9|av1, audioBitrate?: Opus kbps, opusApplication?: audio|voice, crop?: bool|{useRoi?, roi?, top?, left?, bottom?, right?}, cropTop?, cropLeft?, cropBottom?, cropRight?, resize?: bool|{preset?, width?, height?, lockAspect?, quality?: low|high}, resizeWidth?, resizeHeight?, postRenderAction?: none|import|importAndReplace|setProxy, includeProjectLink?: bool, audio?: auto|on|off, sampleRate?, audioChannels?: mono|stereo, audioFormat?: 16|24|32, loop?: bool, output?}",
has_items,
set_output_module
),
@@ -1074,7 +1091,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Output Module",
["Composition"],
None,
"{item?|index? (default: the last item), format?, output?, channels?, quality?, bitrate?, proresProfile?, audio?}",
"{item?|index? (default: the last item), format?, output?, channels?, quality?, bitrate?, proresProfile?, exrCompression?, exrBitDepth?, audio?}",
has_items,
add_output_module
),
+7 -1
View File
@@ -216,10 +216,16 @@ pub(crate) fn shape_group(ids: &mut Ids, kind: &str, size: [f64; 2], paint: &Sha
/// of every one of the five kinds, so a caller that only wants to draw it (the viewer's
/// drag ghost) cannot drift from what `shape.newShape` / `layer.addMask` commit.
pub fn mask_path(kind: &str, centre: [f64; 2], size: [f64; 2]) -> Option<ShapePath> {
mask_path_rounded(kind, centre, size, None)
}
/// [`mask_path`] with the rounded rectangle's corner radius (layer pixels) given; `None` keeps
/// the tool's default. Other kinds ignore it.
pub fn mask_path_rounded(kind: &str, centre: [f64; 2], size: [f64; 2], radius: Option<f64>) -> Option<ShapePath> {
let bez = match kind {
"rect" | "rectangle" => return Some(ShapePath::rect(centre, size[0], size[1])),
"ellipse" => return Some(ShapePath::ellipse(centre, size[0], size[1])),
"rounded" | "roundedRect" => effectcraft_path::rect(size, centre, roundness()),
"rounded" | "roundedRect" => effectcraft_path::rect(size, centre, radius.unwrap_or_else(roundness)),
k => {
let (star, points, outer, inner) = polystar_of(k, size)?;
effectcraft_path::polystar(effectcraft_path::Polystar {
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff. Show more