diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 6a9202fd2..3c1706cc3 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -64,7 +64,7 @@ and licence texts are in [`NOTICE`](NOTICE). | `crates/model/tests/fixtures/cube.obj` | EffectCraft contributors | Original work: Wavefront OBJ test fixture (unit cube, two materials) | MIT OR Apache-2.0 | | `crates/model/tests/fixtures/cube.mtl` | EffectCraft contributors | Original work: MTL test fixture (materials of cube.obj) | MIT OR Apache-2.0 | -Two small After Effects test projects of `crates/aep` are in this repository: `crates/aep/tests/fixtures/synthetic.aep` (original work, made with After Effects 2026 from own data, working space None, the embedded colour profile removed; MIT OR Apache-2.0, with its `.attribution` sidecar) and `crates/aep/tests/fixtures/ai-mask-3099.aep` (original work, made with After Effects 2026 from four hand-written one-page PDFs named `.ai`, footage paths and host name neutralised, the embedded colour profiles replaced by stubs made with the `stubicc` example of `craft-aep` (storytold/craft-libs; formerly `crates/aep/examples/stubicc.rs`); MIT OR Apache-2.0, with its `.attribution` sidecar). The other After Effects test projects of `crates/aep` are not in this repository. They are original work of an EffectCraft contributor, generated with After Effects 2026 as own test data (MIT OR Apache-2.0, each file with its `.attribution` sidecar); they are in [storytold/effectcraft-corpus](https://github.com/storytold/effectcraft-corpus) with their sidecars, fetched by `cargo xtask aep-corpus` (commit-pinned, SHA-256-verified), and the tests read them only from the folder named by `EFFECTCRAFT_AEP_FIXTURES` (opt-in). Their embedded colour profiles are replaced by stubs made with the `stubicc` example of `craft-aep` (storytold/craft-libs; formerly `crates/aep/examples/stubicc.rs`) (a header and a description, no colour data), so no vendor profile data is in them. +Three small After Effects test projects of `crates/aep` are in this repository: `crates/aep/tests/fixtures/synthetic.aep` (original work, made with After Effects 2026 from own data, working space None, the embedded colour profile removed; MIT OR Apache-2.0, with its `.attribution` sidecar), `crates/aep/tests/fixtures/ai-mask-3099.aep` (original work, made with After Effects 2026 from four hand-written one-page PDFs named `.ai`, footage paths and host name neutralised, the embedded colour profiles replaced by stubs made with `crates/aep/examples/stubicc.rs`; MIT OR Apache-2.0, with its `.attribution` sidecar) and `crates/aep/tests/fixtures/text-synthetic.aep` (original work, made with After Effects 2026 by script from own data, working space None, no colour profile embedded, nothing changed after the save; MIT OR Apache-2.0, with its `.attribution` sidecar). The other After Effects test projects of `crates/aep` are not in this repository. They are original work of an EffectCraft contributor, generated with After Effects 2026 as own test data (MIT OR Apache-2.0, each file with its `.attribution` sidecar); they are in [storytold/effectcraft-corpus](https://github.com/storytold/effectcraft-corpus) with their sidecars, fetched by `cargo xtask aep-corpus` (commit-pinned, SHA-256-verified), and the tests read them only from the folder named by `EFFECTCRAFT_AEP_FIXTURES` (opt-in). Their embedded colour profiles are replaced by stubs made with `crates/aep/examples/stubicc.rs` (a header and a description, no colour data), so no vendor profile data is in them. ## Screenshots @@ -133,7 +133,9 @@ configuration from these Apache-2.0 projects: | Asset | Author | Source | Licence | |---|---|---|---| +| `crates/engine/src/tests/fixtures/analysed-0.24.ecproj` | arnav-hiwarkar | Original work, synthetic project keyed by EffectCraft 0.24.1 | MIT OR Apache-2.0 | | `crates/engine/src/tests/fixtures/object-matte-0.22.ecproj` | lisn0 | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | +| `crates/engine/src/tests/fixtures/tracked-0.22.ecproj` | arnav-hiwarkar | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | ## First-party brand marks diff --git a/Cargo.lock b/Cargo.lock index ee7db8b6e..2c64ce2f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1092,26 +1092,26 @@ dependencies = [ [[package]] name = "craft-aep" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58)", "thiserror 2.0.21", ] [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" [[package]] name = "craft-dpx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "thiserror 2.0.21", ] @@ -1119,7 +1119,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "serde", "serde_json", @@ -1129,12 +1129,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" [[package]] name = "craft-exr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "serde_json", ] @@ -1142,17 +1142,17 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1175,7 +1175,7 @@ dependencies = [ [[package]] name = "craft-lottie" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "serde_json", "thiserror 2.0.21", @@ -1184,7 +1184,7 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "thiserror 2.0.21", ] @@ -1200,7 +1200,7 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "miniz_oxide 0.9.1", "serde_json", @@ -1209,7 +1209,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "hayro-syntax", "thiserror 2.0.21", @@ -1218,7 +1218,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "encoding_rs", "flate2", @@ -1229,7 +1229,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "dispatch2", "egui", @@ -1240,7 +1240,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "craft-xml", "flate2", @@ -1252,7 +1252,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1273,7 +1273,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "chrono", "dunce", @@ -1300,9 +1300,9 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58)", "rayon", "thiserror 2.0.21", ] @@ -1310,7 +1310,7 @@ dependencies = [ [[package]] name = "craft-webp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "thiserror 2.0.21", ] @@ -1318,7 +1318,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "quick-xml 0.41.0", "thiserror 2.0.21", @@ -1558,6 +1558,7 @@ dependencies = [ "serde", "serde_json", "sysinfo", + "tempfile", "winit", "winresource", "zbus", @@ -1681,7 +1682,7 @@ name = "effectcraft-export" version = "0.24.1" dependencies = [ "craft-audio", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58)", "craft-video", "effectcraft-color", "effectcraft-effects", @@ -1850,7 +1851,7 @@ dependencies = [ "craft-dpx", "craft-exr", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58)", "craft-webp", "effectcraft-color", "effectcraft-effects", @@ -3420,7 +3421,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "hayro-ccitt", ] @@ -3434,7 +3435,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" +source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58" dependencies = [ "hayro-jbig2", "hayro-jpeg2000", @@ -4753,7 +4754,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.45.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 3ac4eccbb..664a2315a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,22 +11,22 @@ rust-version = "1.95" repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", version = "=0.1.0", default-features = false, features = ["read"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } -craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", default-features = false, features = ["stl", "obj", "gltf", "fbx"] } -craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", version = "=0.1.0", default-features = false, features = ["read"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } +craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", default-features = false, features = ["stl", "obj", "gltf", "fbx"] } +craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", features = ["egui"] } # internal effectcraft-time = { path = "crates/time" } effectcraft-geom = { path = "crates/geom" } @@ -90,9 +90,9 @@ same-file = "1.0" tempfile = "3.27" # codecs + containers shared by the Craft apps (crates/media, crates/export); keep all three on one rev. -craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", default-features = false, features = ["isobmff", "matroska"] } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] } -craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", default-features = false, features = ["isobmff", "matroska"] } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] } +craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } # footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001). # Only `crates/media`, `crates/export` and `crates/interchange` may depend on these. @@ -122,7 +122,7 @@ half = "2.7" # ui # Shared frontend components; keep this dependency above the engine boundary. # Shared UI and the complete egui family select reviewed immutable commits below. -craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", features = ["serde"] } +craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", features = ["serde"] } # `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()` # and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate. egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] } @@ -231,8 +231,8 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", version = "=0.3.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", version = "=0.3.0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/effectcraft/Cargo.toml b/apps/effectcraft/Cargo.toml index 21bd46755..2c8224f65 100644 --- a/apps/effectcraft/Cargo.toml +++ b/apps/effectcraft/Cargo.toml @@ -41,6 +41,9 @@ zbus = "5.19" # Icon + VERSIONINFO for effectcraft.exe; build.rs only uses it when targeting Windows. winresource = "0.1" +[dev-dependencies] +tempfile = { workspace = true } + [target.'cfg(target_os = "macos")'.dependencies] # Keep the control channel responsive when the window is covered (App Nap / occlusion throttling). objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSProcessInfo", "NSString", "NSObject"] } diff --git a/apps/effectcraft/src/crash_report.rs b/apps/effectcraft/src/crash_report.rs index 6ca42aab7..3080c12bb 100644 --- a/apps/effectcraft/src/crash_report.rs +++ b/apps/effectcraft/src/crash_report.rs @@ -426,6 +426,7 @@ mod tests { } fn helper_mode(dir: &Path, id: &str, interactive: bool) -> Reporter { + let _spawn_lock = crate::test_child_spawn_lock(); let mut child = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("reporter_process"), "--ignored", "--nocapture"]) .env(ROLE, "reporter") @@ -550,6 +551,7 @@ mod tests { #[test] fn accepted_native_close_finishes_before_process_termination() { let dir = folder(); + let _spawn_lock = crate::test_child_spawn_lock(); let status = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) .env(ROLE, "native-close") @@ -595,6 +597,7 @@ mod tests { #[test] fn an_aborting_parent_leaves_one_diagnostic_report() { let dir = folder(); + let _spawn_lock = crate::test_child_spawn_lock(); let status = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) .env(ROLE, "abort") @@ -616,6 +619,7 @@ mod tests { fn an_unrelated_child_does_not_keep_the_control_pipe_open() { let dir = folder(); let r = helper(&dir, "5-1"); + let _spawn_lock = crate::test_child_spawn_lock(); let mut unrelated = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("lingering_child"), "--ignored", "--nocapture"]) .env(ROLE, "linger") @@ -632,6 +636,7 @@ mod tests { #[test] fn an_unresponsive_helper_cannot_hang_clean_shutdown() { + let _spawn_lock = crate::test_child_spawn_lock(); let mut child = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("lingering_child"), "--ignored", "--nocapture"]) .env(ROLE, "linger") @@ -704,6 +709,7 @@ mod tests { #[cfg(windows)] fn windows_report_preserves_real_unsigned_exit_bits() { let dir = folder(); + let _spawn_lock = crate::test_child_spawn_lock(); let status = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) .env(ROLE, "windows-status") diff --git a/apps/effectcraft/src/launch_guard.rs b/apps/effectcraft/src/launch_guard.rs index 2656179ac..85d1fdd57 100644 --- a/apps/effectcraft/src/launch_guard.rs +++ b/apps/effectcraft/src/launch_guard.rs @@ -214,8 +214,8 @@ mod tests { /// A launch that never drew switches the next one to OpenGL, which then stays (#243). #[test] fn a_launch_that_never_drew_switches_the_next_to_opengl() { - let dir = std::env::temp_dir().join(format!("ec-launch-guard-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let _spawn_lock = crate::test_child_spawn_lock(); + let dir = fresh_dir("never-drew"); // A first launch that draws: nothing changes. Its first frames don't settle it (a driver // may still crash as the window is shown); frames for `SETTLE` do. let mut l = Launch::begin(Some(&dir), false); @@ -259,8 +259,8 @@ mod tests { /// normal quit in that time doesn't. #[test] fn a_launch_that_stops_after_its_first_frame_switches_the_next_to_opengl() { - let dir = std::env::temp_dir().join(format!("ec-launch-guard-3-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let _spawn_lock = crate::test_child_spawn_lock(); + let dir = fresh_dir("first-frame"); let mut l = Launch::begin(Some(&dir), false); assert!(l.frame_drawn().is_some()); drop(l); @@ -286,8 +286,8 @@ mod tests { /// open a window either goes back to Automatic instead of failing every launch. #[test] fn a_second_copy_or_failed_opengl_doesnt_strand_window_graphics() { - let dir = std::env::temp_dir().join(format!("ec-launch-guard-2-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let _spawn_lock = crate::test_child_spawn_lock(); + let dir = fresh_dir("second-copy"); let _first = Launch::begin(Some(&dir), false); assert_eq!(Launch::begin(Some(&dir), false).backends, None); assert_eq!(window_graphics(&dir), "auto"); @@ -303,10 +303,7 @@ mod tests { /// A fresh settings folder for one test. fn fresh_dir(case: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("ec-launch-guard-{case}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir + tempfile::Builder::new().prefix(&format!("ec-launch-guard-{case}-")).tempdir().unwrap().keep() } /// Window Graphics saved as OpenGL. @@ -318,6 +315,7 @@ mod tests { #[test] fn a_second_copy_reports_the_saved_backend_without_owning_the_guard() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("second-source"); save_opengl(&dir); let mut first = Launch::begin(Some(&dir), false); @@ -333,6 +331,7 @@ mod tests { /// one's marker (#477). #[test] fn a_second_copy_quitting_leaves_the_running_launchs_marker() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("second-quits"); let mut first = Launch::begin(Some(&dir), false); let mut second = Launch::begin(Some(&dir), false); @@ -346,6 +345,7 @@ mod tests { /// A second copy whose OpenGL window fails doesn't remove a running launch's marker. #[test] fn failed_opengl_in_a_second_copy_leaves_the_running_launchs_marker() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("second-gl-fails"); let mut first = Launch::begin(Some(&dir), false); let second = Launch::begin(Some(&dir), false); @@ -360,6 +360,7 @@ mod tests { /// With `WGPU_BACKEND` set, a stale marker and a saved OpenGL choice are left as they are. #[test] fn wgpu_backend_leaves_a_stale_marker_and_saved_opengl_alone() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("env-override"); save_opengl(&dir); std::fs::write(dir.join(MARKER), b"stale-marker").unwrap(); @@ -376,6 +377,7 @@ mod tests { /// After OpenGL fails to open a window, the next launch is back on Automatic, without a notice. #[test] fn failed_opengl_puts_the_next_launch_back_on_automatic() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("gl-recovers"); save_opengl(&dir); let l = Launch::begin(Some(&dir), false); @@ -396,6 +398,7 @@ mod tests { #[cfg(unix)] #[test] fn the_guard_file_stays_the_same_file_across_launches() { + let _spawn_lock = crate::test_child_spawn_lock(); use std::os::unix::fs::MetadataExt; let dir = fresh_dir("guard-identity"); let mut a = Launch::begin(Some(&dir), false); @@ -417,6 +420,7 @@ mod tests { /// A second copy's frames and quit neither settle nor unlock the running launch. #[test] fn a_second_copys_frames_dont_settle_the_running_launch() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("second-frames"); let mut a = Launch::begin(Some(&dir), false); std::fs::write(dir.join(MARKER), b"owner-marker").unwrap(); @@ -438,6 +442,7 @@ mod tests { /// once it has stopped without settling the next launch still switches to OpenGL. #[test] fn a_running_older_version_holding_the_marker_is_left_alone() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("older-version"); std::fs::write(dir.join(MARKER), b"old-owner").unwrap(); std::fs::write(dir.join(PREFS_FILE), Prefs::default().to_json()).unwrap(); @@ -468,6 +473,7 @@ mod tests { #[cfg(windows)] #[test] fn an_unopenable_marker_leaves_settings_and_marker_alone() { + let _spawn_lock = crate::test_child_spawn_lock(); use std::os::windows::fs::OpenOptionsExt; let dir = fresh_dir("marker-unopenable"); @@ -491,6 +497,7 @@ mod tests { /// A guard file that can't be opened leaves Window Graphics and the marker as they are. #[test] fn an_unusable_guard_file_leaves_settings_and_marker_alone() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("guard-unusable"); std::fs::create_dir(dir.join(LOCK)).unwrap(); std::fs::write(dir.join(MARKER), b"stale-marker").unwrap(); @@ -512,6 +519,7 @@ mod tests { /// Window Graphics to Automatic and removes the marker. #[test] fn failed_opengl_cleanup_waits_for_the_running_launch() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("gl-cleanup-waits"); save_opengl(&dir); let launch = Launch::begin(Some(&dir), false); diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs index 5a602adcb..b07e3ce43 100644 --- a/apps/effectcraft/src/main.rs +++ b/apps/effectcraft/src/main.rs @@ -35,6 +35,17 @@ mod window; use effectcraft_ui_egui::EffectcraftApp; use serde_json::json; +// On Unix, a subprocess briefly inherits every non-CLOFORK descriptor between fork and exec. +// The app's guard-lock tests hold an advisory lock while crash-reporter tests spawn child +// processes; coordinate just those intervals so an unrelated test child cannot extend a lock. +#[cfg(test)] +static TEST_CHILD_SPAWN_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[cfg(test)] +fn test_child_spawn_lock() -> std::sync::MutexGuard<'static, ()> { + TEST_CHILD_SPAWN_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The app icon for the window, taskbar and Dock (assets/app-icon, regenerated by /// `packaging/icons.sh`). macOS gets the padded variant so it sits on Apple's icon grid in the Dock. /// The 256 px app icon (Windows, Linux; the AppImage's desktop integration installs it too). diff --git a/crates/aep/README.md b/crates/aep/README.md index fc1cbabe8..fa82deaa2 100644 --- a/crates/aep/README.md +++ b/crates/aep/README.md @@ -77,6 +77,10 @@ solid, a folder, a Levels and a Glow effect with expressions). Every After Effec the working space's ICC profile (HP sRGB IEC61966-2.1 for the default) in a JSON settings chunk; the one `Utf8` chunk of this file that held a profile was replaced by `{}`, and nothing else was changed. The tests in `tests/it/import/synthetic.rs` damage copies of it and need no other file. +`tests/fixtures/text-synthetic.aep` is the other: made in After Effects 2026 the same way (working +space None, nothing changed after the save), one composition with two text layers that hold a +text animator's Stroke Opacity (static and keyed) and Source Text expressions (enabled and +disabled); `tests/it/import/text_synthetic.rs` reads it (#3170). `tests/fixtures/ai-mask-3099.aep` (131 KB, #3099) is the second: four hand-written one-page PDFs named `.ai` with distinct page boxes, placed in a composition, one of them with two masks under a diff --git a/crates/aep/src/container/effect_map.rs b/crates/aep/src/container/effect_map.rs index 15ecf549b..b08e92afe 100644 --- a/crates/aep/src/container/effect_map.rs +++ b/crates/aep/src/container/effect_map.rs @@ -38,6 +38,19 @@ pub enum Conv { Skip, } +impl Conv { + /// For a number (`Percent`, `Plain`, `Factor`): what a stored value is multiplied by to give + /// the value here. `None` for every other conversion. + pub fn number_scale(self) -> Option { + match self { + Conv::Percent { valid_max } => Some(100.0 / valid_max), + Conv::Plain { .. } => Some(1.0), + Conv::Factor { factor, .. } => Some(factor), + _ => None, + } + } +} + // After Effects' popup items as the corpus stores them (`pdnm`). /// 368. pub const RAMP_SHAPE: &[&str] = &["Linear Ramp", "Radial Ramp"]; diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index e8464bada..338e00fc5 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -707,3 +707,99 @@ pub(crate) static FX_DEFS: &[FxDef] = &[ p(BUILT_IN, 9, &[], None, None, None, 0x00000000), ]), ]; + +#[cfg(test)] +mod tests { + use super::*; + use crate::container::effect_map::by_match_name; + use effectcraft_project::ParamUi; + + /// Effect parameters whose hard range (`ParamUi::Slider` min..max, which `prop.set` and the + /// value editors clamp to) is still narrower than After Effects' recorded valid range, each + /// with the open issue that tracks it: (effect, parameter, issue). Remove a row when its + /// issue is fixed; the test fails on a row that is no longer needed. + #[rustfmt::skip] + const KNOWN_NARROWER: &[(&str, &str, u32)] = &[ + ("ec.blur.gaussian", "blurriness", 3460), + ("ec.blur.fastbox", "radius", 3461), + ("ec.blur.channel", "redBlurriness", 3462), + ("ec.blur.channel", "greenBlurriness", 3462), + ("ec.blur.channel", "blueBlurriness", 3462), + ("ec.blur.channel", "alphaBlurriness", 3462), + ("ec.obsolete.gaussianlegacy", "blurriness", 3463), + ("ec.perspective.dropshadow", "softness", 3464), + ("ec.blur.compound", "maximumBlur", 3465), + ("ec.blur.sharpen", "amount", 3466), + ("ec.blur.radial", "amount", 3467), + ("ec.blur.ccradial", "amount", 3468), + ("ec.distort.turbulentdisplace", "amount", 3469), + ("ec.time.pixelmotionblur", "shutterAngle", 3481), + ("ec.time.pixelmotionblur", "shutterSamples", 3482), + ("ec.noise.fractal", "subSettings/subInfluence", 3485), + ("ec.noise.fractal", "subSettings/subScaling", 3486), + ("ec.distort.ccpowerpin", "expandTop", 3492), + ("ec.distort.ccpowerpin", "expandLeft", 3492), + ("ec.distort.ccpowerpin", "expandRight", 3492), + ("ec.distort.ccpowerpin", "expandBottom", 3492), + ]; + + /// `a` is at most `b`, allowing for the `f32` the recorded bounds were read from. + fn at_most(a: f64, b: f64) -> bool { + a <= b + 1e-6 * a.abs().max(b.abs()).max(1.0) + } + + /// Every effect parameter the .aep table maps to a recorded After Effects definition accepts + /// at least After Effects' valid range, converted to EffectCraft's units the way the importer + /// converts values (`Conv::number_scale`). Only `ParamUi::Slider` limits values (`prop.set`, + /// the Effect Controls and Timeline editors); other controls take any number. A mapping with + /// a declared narrower range (`ParamMap::limit`) must match the effect's range instead. + #[test] + fn effect_hard_ranges_cover_recorded_after_effects_ranges() { + let mut problems = Vec::new(); + let mut narrower = Vec::new(); + for fx in FX_DEFS { + let Some(map) = by_match_name(fx.match_name) else { continue }; + let Some(spec) = effectcraft_effects::find(map.effect) else { + problems.push(format!("{}: no effect {}", fx.match_name, map.effect)); + continue; + }; + for pm in map.params { + let Some(scale) = pm.conv.number_scale() else { continue }; + let at = format!("{} {}", map.effect, pm.target); + let Some(ps) = spec.params.iter().find(|p| p.id == pm.target) else { + problems.push(format!("{at}: not a parameter of the effect")); + continue; + }; + // Other controls take any number. + let ParamUi::Slider { min, max, .. } = &ps.ui else { continue }; + let Some(def) = fx.params.get(pm.index) else { + problems.push(format!("{at}: no recorded definition at parT {}", pm.index)); + continue; + }; + let (Some(lo), Some(hi)) = (def.valid_min, def.valid_max) else { + problems.push(format!("{at}: no recorded valid range")); + continue; + }; + let (lo, hi) = (lo * scale, hi * scale); + if let Some(limit) = pm.limit { + if limit != (*min, *max) { + problems.push(format!("{at}: declared limit {limit:?} is not the effect's range {min}..{max}")); + } + } else if !(at_most(*min, lo) && at_most(hi, *max)) { + narrower.push((map.effect, pm.target, format!("{at}: {min}..{max} excludes After Effects' {lo}..{hi}"))); + } + } + } + for (effect, param, why) in &narrower { + if !KNOWN_NARROWER.iter().any(|(e, p, _)| e == effect && p == param) { + problems.push(why.clone()); + } + } + for (effect, param, issue) in KNOWN_NARROWER { + if !narrower.iter().any(|(e, p, _)| e == effect && p == param) { + problems.push(format!("{effect} {param}: covers After Effects' range now (or is not mapped); remove it from KNOWN_NARROWER (#{issue})")); + } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); + } +} diff --git a/crates/aep/src/export/text.rs b/crates/aep/src/export/text.rs index 815a89c83..8307f50a7 100644 --- a/crates/aep/src/export/text.rs +++ b/crates/aep/src/export/text.rs @@ -89,6 +89,8 @@ pub(crate) struct TextPlan { pub frame: Option<[f64; 4]>, /// The text animators (planned with the layer's time base, `textanim.rs`). pub animators: Vec, + /// The Source Text expression and its enable switch. + pub expr: Option<(String, bool)>, } /// Where a text value is written, for the loss report. @@ -133,16 +135,19 @@ pub(crate) fn plan_text(layer: &Layer, comp_name: &str, col: &mut Collector) -> if !st.keys.is_empty() { col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not written (the first key's text is)")); } - if st.has_expression() { - col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not written")); - } let value = st.keys.first().map(|k| &k.value).unwrap_or(&st.value); let Value::Text(doc) = value else { col.lose(LossCategory::TextLayers, format!("{what}: Source Text holds no text document")); return None; }; report_extras(text, &what, col); - Some(plan_doc(doc, &what, col)) + let mut plan = plan_doc(doc, &what, col); + // Written enabled or disabled, as on any other property. + plan.expr = st.expr.as_ref().filter(|e| !e.text.is_empty()).map(|e| (e.text.clone(), e.enabled)); + if plan.expr.is_some() { + col.exported.expressions = col.exported.expressions.saturating_add(1); + } + Some(plan) } /// Path / More Options that hold anything other than a new text layer's defaults are not @@ -190,6 +195,8 @@ fn differs(g: &PropGroup, def: Option<&PropGroup>, depth: usize) -> bool { }) } +/// The text document `doc` in the file's terms (text, style runs, paragraphs, box); what the file +/// cannot hold is reported for `what`. fn plan_doc(doc: &TextDoc, what: &str, col: &mut Collector) -> TextPlan { let base = doc.base_style(); let runs = doc.runs(); @@ -288,7 +295,7 @@ fn plan_doc(doc: &TextDoc, what: &str, col: &mut Collector) -> TextPlan { at.fit(h, (1.0, 1e6), 1.0, "box height"), ] }); - TextPlan { text, runs: out_runs, paras, frame, animators: Vec::new() } + TextPlan { text, runs: out_runs, paras, frame, animators: Vec::new(), expr: None } } fn style_out(s: &effectcraft_keyframe::text_doc::CharStyle, what: &str, col: &mut Collector) -> StyleOut { @@ -518,11 +525,47 @@ pub(crate) fn build_doc(proto: &TNode, tp: &TextPlan) -> Option { Some(doc) } -/// Rewrites the text document of a text layer block's `Layr` for `tp` and gives the document a -/// fresh `btgu/pgui`. +/// The Source Text expression into the `tdbs` of `btds` (`docs/aep-format.md` 3.10, read back from +/// `tests/fixtures/text-synthetic.aep`): `tdb4` byte 120 = 1, byte 119 = 1 when disabled, and the +/// text as a `Utf8` after the record's `cdat`. +fn put_source_text_expression(layr: &mut crate::Chunk<'static>, text: &str, enabled: bool) -> crate::export::tree::R<()> { + use crate::Body; + use crate::export::tree::tpl; + /// The `tdbs` of the first `btds` below `c`, at most 32 levels down. + fn find<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> { + if depth > 32 { + return None; + } + if c.is_list(b"btds") { + return match &mut c.body { + Body::List { children, .. } => children.iter_mut().find(|k| k.is_list(b"tdbs")), + _ => None, + }; + } + match &mut c.body { + Body::List { children, .. } | Body::Chunks(children) => children.iter_mut().find_map(|k| find(k, depth + 1)), + _ => None, + } + } + let tdbs = find(layr, 0).ok_or_else(|| tpl("text prototype without a Source Text record"))?; + let Body::List { children, .. } = &mut tdbs.body else { return Err(tpl("text prototype without a Source Text record")) }; + let tdb4 = children.iter_mut().find(|k| k.is(b"tdb4")).ok_or_else(|| tpl("Source Text record without tdb4"))?; + let Body::Data(d) = &mut tdb4.body else { return Err(tpl("Source Text record without tdb4")) }; + let d = d.to_mut(); + *d.get_mut(120).ok_or_else(|| tpl("short Source Text tdb4"))? = 1; + *d.get_mut(119).ok_or_else(|| tpl("short Source Text tdb4"))? = u8::from(!enabled); + children.retain(|k| !k.is(b"Utf8")); + let at = children.iter().position(|k| k.is(b"tdum")).unwrap_or(children.len()); + children.insert(at, crate::Chunk::data(*b"Utf8", text.as_bytes().to_vec())); + Ok(()) +} + +/// Rewrites the text document of a text layer block's `Layr` for `tp`, writes its Source Text +/// expression and gives the document a fresh `btgu/pgui`. pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8; 16]) -> crate::export::tree::R<()> { use crate::Body; use crate::export::tree::tpl; + /// The first `LIST btdk` below `c`, at most 32 levels down. fn find<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> { if depth > 32 { return None; @@ -535,6 +578,7 @@ pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8 _ => None, } } + /// The first `pgui` of the first `btgu` below `c`, at most 32 levels down. fn find_pgui<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> { if depth > 32 { return None; @@ -555,6 +599,9 @@ pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8 let proto = crate::export::textdoc::parse(data.as_ref()).ok_or_else(|| tpl("the text prototype's document does not parse"))?; let doc = build_doc(&proto, tp).ok_or_else(|| tpl("the text prototype's document has another shape"))?; *data = std::borrow::Cow::Owned(crate::export::textdoc::write(&doc)); + if let Some((text, enabled)) = &tp.expr { + put_source_text_expression(layr, text, *enabled)?; + } if let Some(p) = find_pgui(layr, 0) { *p = crate::Chunk::data(*b"pgui", guid.to_vec()); } diff --git a/crates/aep/src/export/textanim.rs b/crates/aep/src/export/textanim.rs index 760217cb8..ff5c81c09 100644 --- a/crates/aep/src/export/textanim.rs +++ b/crates/aep/src/export/textanim.rs @@ -88,6 +88,7 @@ const PROPS: &[(&str, &str, Conv, Layout)] = &[ ("opacity", "ADBE Text Opacity", c_scalar, Layout::One), ("fillColor", "ADBE Text Fill Color", c_color, Layout::Color), ("strokeColor", "ADBE Text Stroke Color", c_color, Layout::Color), + ("strokeOpacity", "ADBE Text Stroke Opacity", c_scalar, Layout::One), ("strokeWidth", "ADBE Text Stroke Width", c_scalar, Layout::One), ("tracking", "ADBE Text Tracking Amount", c_scalar, Layout::One), ("lineSpacing", "ADBE Text Line Spacing", c_vec2, Layout::Size), diff --git a/crates/aep/src/export/tree_defs.rs b/crates/aep/src/export/tree_defs.rs index 66371ea7a..23df87a23 100644 --- a/crates/aep/src/export/tree_defs.rs +++ b/crates/aep/src/export/tree_defs.rs @@ -264,6 +264,8 @@ pub(crate) static TEXT_ANIMATOR_RECORDS: &[Node] = &[ R("ADBE Text Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[37.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }), R("ADBE Text Fill Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }), R("ADBE Text Stroke Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }), + // text-synthetic.aep (#3170): the record After Effects wrote for Stroke Opacity 40 %. + R("ADBE Text Stroke Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[40.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }), R("ADBE Text Stroke Width", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[3.0], key_size: 0, limits: Some((-1000.0, 1000.0)), tdpi: None }), R("ADBE Text Tracking Amount", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[20.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }), R("ADBE Text Line Spacing", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[10.0, 20.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }), diff --git a/crates/aep/src/import.rs b/crates/aep/src/import.rs index fae3b3256..20a4b7b1e 100644 --- a/crates/aep/src/import.rs +++ b/crates/aep/src/import.rs @@ -14,7 +14,8 @@ //! missing-footage placeholders). `docs/aep-import.md` has the full list. //! //! What does not arrive is **reported**, never dropped silently: [`ImportReport`] counts other -//! effects (by match name) and unimported effect parameters, unusable masks, layer style +//! effects (by match name; they arrive as placeholders that render nothing, with their parameters +//! for expressions) and unimported effect parameters, unusable masks, layer style //! features, text layer features, shape items, unsupported blend modes and transform //! properties, simplified keyframes and unreadable data per [`LossCategory`]. By default the import //! is refused when anything would be lost ([`ImportOptions::allow_losses`] lifts that); a refusal @@ -30,6 +31,7 @@ mod effects; mod lumetri; mod markers; mod masks; +mod placeholder; mod props; mod puppet; mod report; diff --git a/crates/aep/src/import/build.rs b/crates/aep/src/import/build.rs index 7d5b902f1..189eaefb5 100644 --- a/crates/aep/src/import/build.rs +++ b/crates/aep/src/import/build.rs @@ -12,7 +12,8 @@ use effectcraft_color::{BlendMode, Label}; use effectcraft_keyframe::Value; use effectcraft_project::build::{self, Ids}; use effectcraft_project::{ - AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, TrackMatte, + AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, SourceLayer, + TrackMatte, }; use effectcraft_time::Tick; @@ -25,7 +26,7 @@ use crate::import::props::{AnchorUnit, import_transform}; use crate::import::report::{Collector, ImportReport, LossCategory}; use crate::import::shapes::import_shapes; use crate::import::styles::import_layer_styles; -use crate::import::text::{report_text_extras, text_doc}; +use crate::import::text::{import_source_text_expression, report_text_extras, text_doc}; use crate::import::text_anim::import_animators; use crate::import::time::{TimeMap, frame_rate}; @@ -216,7 +217,17 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_ let aep_id = item.id(); // An item without a stored name shows its file's name, a sequence `shot_[0101-0103].exr` // (126, 603-607). - let name = if name.is_empty() { default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string()) } else { name }; + // One layer of a Photoshop file is `/`, as EffectCraft's own Photoshop import + // names it (#3087). + let name = if name.is_empty() { + let file = default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string()); + match &f.psd_layer { + Some(l) if !l.name.is_empty() => format!("{}/{file}", l.name), + _ => file, + } + } else { + name + }; if f.is_solid { // A null object's placeholder solid is not an item here. if aep_id.is_some_and(|i| null_only.contains(&i)) { @@ -299,6 +310,7 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_ missing: !present, placed_page, sequence, + layer: source_layer(&f, &name, &mut cx.col), ..Footage::default() }; // The native frame rate and the stored duration of sequences and clips (352, 603, 606). @@ -338,6 +350,34 @@ fn is_placed_page_path(path: &str) -> bool { matches!(ext.as_deref(), Some("pdf" | "ai")) } +/// The Photoshop layer a footage item shows (#3087): at its own bounds when the item is as big +/// as they are (Retain Layer Sizes), else on the document. A layer without pixels (an adjustment +/// layer) keeps the merged image and is reported. So is a layer as big as the document but not at +/// its corner (the item's size fits both framings; its bounds are used), and an item as big as +/// neither (the document is used). +fn source_layer(f: &crate::Footage, name: &str, col: &mut Collector) -> Option { + let l = f.psd_layer.as_ref()?; + let Some(size) = l.size() else { + col.lose(LossCategory::UnsupportedItems, format!("footage '{name}': a Photoshop layer without pixels (an adjustment layer), the merged image used")); + return None; + }; + let layer_size = size == (f.width, f.height); + if !layer_size && l.document.iter().all(|side| *side > 0) && !l.document_is((f.width, f.height)) { + col.lose( + LossCategory::UnsupportedItems, + format!("footage '{name}': {} x {} is neither the Photoshop layer's size nor the document's, shown on the document", f.width, f.height), + ); + } + let [top, left, ..] = l.bounds; + if layer_size && (top, left) != (0, 0) && l.document_is(size) { + col.lose( + LossCategory::UnsupportedItems, + format!("footage '{name}': a Photoshop layer as big as the document but at ({left}, {top}), shown at its own bounds (Retain Layer Sizes assumed)"), + ); + } + Some(SourceLayer { index: l.index, name: l.name.clone(), layer_size, ..SourceLayer::default() }) +} + /// The name After Effects shows for a footage item that stores none: the file's name, or for a /// sequence the name with the frame range (`shot_[0101-0103].exr`). fn default_footage_name(item: &AepItem<'_, '_>, f: &crate::Footage) -> Option { @@ -667,8 +707,8 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition } } -/// The Source Text of a text layer from its text document, and the reports of what is not -/// imported. +/// The Source Text of a text layer from its text document and its expression, and the reports +/// of what is not imported. fn import_source_text(l: &mut Layer, layer: &AepLayer<'_, '_>, what: &str, cx: &mut Ctx<'_>) { match layer.text_document() { Some(doc) => { @@ -680,6 +720,7 @@ fn import_source_text(l: &mut Layer, layer: &AepLayer<'_, '_>, what: &str, cx: & } None => cx.col.lose(LossCategory::DamagedData, format!("{what}: the text document is unreadable, the layer is imported with empty text")), } + import_source_text_expression(layer, l.props.prop_mut("text/sourceText"), what, &mut cx.col); report_text_extras(layer, what, &mut cx.col); } diff --git a/crates/aep/src/import/effects.rs b/crates/aep/src/import/effects.rs index ea13bcb4b..3b447c13a 100644 --- a/crates/aep/src/import/effects.rs +++ b/crates/aep/src/import/effects.rs @@ -1,7 +1,8 @@ //! Effects: a table maps an After Effects effect (its match name) and its parameters (by their -//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Effects and -//! parameters outside the table are reported in [`LossCategory::Effects`] by match name, never -//! dropped silently. +//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Parameters +//! outside the table are reported in [`LossCategory::Effects`] by match name, never dropped +//! silently. An effect outside it arrives as a placeholder holding its parameters (`placeholder.rs`) +//! and is reported too. //! //! Every conversion is backed by the corpus (`docs/aep-format.md` 3.7, cases 356-450, 511-516): //! @@ -82,44 +83,37 @@ pub(crate) fn import_effects<'f, 'a>( continue; } let shown = fx.display_name().unwrap_or_else(|| fx.match_name().to_string()); - let Some(map) = EFFECTS.iter().find(|m| m.match_name == fx.match_name()) else { - col.lose_unmapped_effect(fx.match_name(), format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name())); - continue; - }; - let Some(spec) = effectcraft_effects::find(map.effect) else { - col.lose_unmapped_effect(fx.match_name(), format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name())); - continue; - }; + let found = EFFECTS.iter().find(|m| m.match_name == fx.match_name()).and_then(|m| Some((m, effectcraft_effects::find(m.effect)?))); + let lost = format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()); if defs.source(&fx) == DefinitionSource::Missing { - col.lose( - LossCategory::Effects, - format!("{}: '{}' has the effect '{shown}' ({}) without readable parameter definitions, not imported", cx.comp, cx.layer, fx.match_name()), - ); + match found { + Some(_) => col.lose(LossCategory::Effects, format!("{lost} without readable parameter definitions, not imported")), + None => col.lose_unmapped_effect(fx.match_name(), lost), + } continue; } - let size = [f64::from(cx.size.0), f64::from(cx.size.1)]; - let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size); - match fx.enabled() { - Some(on) => group.enabled = on, - None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)), + if found.is_none() && col.placeholder_cost >= crate::import::placeholder::MAX_COST { + // The import's placeholder budget is spent: the definitions (shared by many instances) + // are not read again. Named like any effect without a counterpart, in a group of its + // own (with the kept instances it would read as kept). + let key = format!("{} (not kept)", fx.match_name()); + col.lose_unmapped_effect(&key, format!("{lost}, not kept (past the import's placeholder parameters)")); + continue; } let params = defs.params(&fx); - // Borrowed definitions (another instance's or the project copy) may not name every value - // record this instance has: such a record has nothing to import into, so it is reported. - if params.first().is_some_and(|p| p.borrowed_definition) { - let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect(); - for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) { - col.lose( - LossCategory::Effects, - format!( - "{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported", - cx.comp, - cx.layer, - fx.match_name() - ), - ); - } - } + report_records_without_definition(&fx, ¶ms, cx, &shown, col); + let Some((map, spec)) = found else { + // No counterpart: kept as a placeholder that renders nothing, for expressions (#3087). + let mut group = crate::import::placeholder::placeholder(&fx, ¶ms, cx, &shown, ids, refs, col); + set_enabled(&fx, &mut group, cx, &shown, col); + col.lose_unmapped_effect(fx.match_name(), format!("{lost}, kept without rendering")); + col.imported.placeholder_effects = col.imported.placeholder_effects.saturating_add(1); + target.children.push(Node::Group(group)); + continue; + }; + let size = [f64::from(cx.size.0), f64::from(cx.size.1)]; + let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size); + set_enabled(&fx, &mut group, cx, &shown, col); if map.extra == Extra::Lumetri { crate::import::lumetri::import_lumetri(&fx, ¶ms, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col }); } else if map.extra == Extra::Cryptomatte { @@ -134,6 +128,29 @@ pub(crate) fn import_effects<'f, 'a>( } } +/// The effect's fx switch. +fn set_enabled(fx: &AepEffect<'_, '_>, group: &mut PropGroup, cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) { + match fx.enabled() { + Some(on) => group.enabled = on, + None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)), + } +} + +/// Borrowed definitions (another instance's or the project copy) may not name every value record +/// this instance has: such a record has nothing to import into, so it is reported. +fn report_records_without_definition(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) { + if !params.first().is_some_and(|p| p.borrowed_definition) { + return; + } + let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect(); + for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) { + col.lose( + LossCategory::Effects, + format!("{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported", cx.comp, cx.layer, fx.match_name()), + ); + } +} + /// Parameters that never carry a value to import. pub(crate) fn carries_nothing(p: &EffectParam<'_, '_>) -> bool { matches!(p.kind, ParamKind::Button | ParamKind::NoData | ParamKind::GroupStart | ParamKind::GroupEnd) || (p.index == 0 && p.kind == ParamKind::Layer) @@ -242,23 +259,12 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx Conv::Checkbox => Kind::EffectBool, // Handled above. Conv::LayerRef { .. } | Conv::Skip => return, - Conv::Percent { valid_max } => { + Conv::Percent { valid_max } | Conv::Plain { valid_max } | Conv::Factor { valid_max, .. } => { if !checked(valid_max, col) { return; } - Kind::EffectNumber(100.0 / valid_max) - } - Conv::Plain { valid_max } => { - if !checked(valid_max, col) { - return; - } - Kind::EffectNumber(1.0) - } - Conv::Factor { valid_max, factor } => { - if !checked(valid_max, col) { - return; - } - Kind::EffectNumber(factor) + let Some(scale) = m.conv.number_scale() else { return }; + Kind::EffectNumber(scale) } }; // Grouped parameters are addressed by path (`master/exposure`). @@ -364,7 +370,7 @@ fn report_beyond_limit<'v>(limit: Option<(f64, f64)>, values: impl Iterator, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) { +pub(crate) fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) { let (here, label) = names; let ParamOut { group, refs, col } = out; // After Effects hands the named layer's source to the effect, without its masks and effects @@ -804,7 +810,7 @@ fn px(v: f64) -> String { /// A decoded value in EffectCraft's units, `None` when it does not fit the kind or is not a valid /// number. -fn convert(value: ParamValue, kind: Kind) -> Option { +pub(crate) fn convert(value: ParamValue, kind: Kind) -> Option { let raw = match (value, kind) { // The reader gives colours as ARGB fractions; `Kind` takes the stored 0..255. (ParamValue::Argb(c), Kind::EffectColor) => c.map(|x| x * 255.0).to_vec(), diff --git a/crates/aep/src/import/placeholder.rs b/crates/aep/src/import/placeholder.rs new file mode 100644 index 000000000..2fc40b71b --- /dev/null +++ b/crates/aep/src/import/placeholder.rs @@ -0,0 +1,218 @@ +//! Placeholders: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect +//! of expression controls) arrives as an effect group that renders nothing, as a missing plug-in +//! does. Its effect id is the After Effects match name, so Find Missing Effects lists it. It holds +//! the effect's parameters, flat and named as in After Effects, each with its value, keys and +//! expression, so expressions that read them (`effect("Settings")("Speed")`) keep working. It is +//! still reported, once per match name. +//! +//! The values keep After Effects' units, the ones its expressions read: sliders and angles as +//! stored, points in layer pixels, colours RGBA 0..1, checkboxes on / off, popups as EffectCraft's +//! 0-based items over the file's items in order (expressions read them 1-based, as After Effects +//! does). Layer parameters name their layer (their keys and expression are reported). Paths and +//! arbitrary data are not kept (reported when they hold something). +//! +//! The parameters placeholders walk, kept or not, and their popup items (by name length) are +//! bounded per import ([`MAX_COST`]): definitions can be shared by many instances, so a small file +//! could otherwise ask for very many properties. Once +//! the budget is spent, later effects without a counterpart are reported without a placeholder. + +use effectcraft_keyframe::Value; +use effectcraft_project::build::Ids; +use effectcraft_project::{GroupKind, Node, ParamUi, PropGroup, Property}; + +use crate::import::effects::{LayerCtx, ParamOut, PendingLayerRef, carries_nothing, convert, import_layer_ref, param_label}; +use crate::import::props::{Kind, import_expression, import_keys}; +use crate::import::report::{Collector, LossCategory}; +use crate::{Effect as AepEffect, EffectParam, ParamKind, ParamValue}; + +/// Most placeholder parameters (kept or not) and popup items one import walks. +pub(crate) const MAX_COST: usize = 200_000; + +/// Most items read from one placeholder popup. +const MAX_POPUP_ITEMS: usize = 1024; + +/// A popup item costs one more for each of these bytes in its name, so the names kept stay +/// bounded too. +const NAME_BYTES: usize = 16; + +/// The placeholder of `fx`, with `params` (its parameter definitions) as properties. +pub(crate) fn placeholder( + fx: &AepEffect<'_, '_>, + params: &[EffectParam<'_, '_>], + cx: &LayerCtx<'_>, + shown: &str, + ids: &mut Ids<'_>, + refs: &mut Vec, + col: &mut Collector, +) -> PropGroup { + // The effect id is the match name; the group's match id is one segment of a property path + // (a pseudo effect's `Pseudo/0.25` would be cut apart), so match paths find its parameters. + let mut group = ids.group(&segment(fx.match_name()), shown); + group.kind = GroupKind::Effect { effect: fx.match_name().to_string() }; + let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()); + for p in params { + // Every parameter walked counts, kept or not: a definition shared by many instances is + // otherwise walked again for each one. + if carries_nothing(p) { + col.placeholder_cost = col.placeholder_cost.saturating_add(1).min(MAX_COST); + continue; + } + if col.placeholder_cost >= MAX_COST { + col.lose(LossCategory::Effects, format!("{here}: parameters past the import's {MAX_COST} placeholder parameters not kept")); + break; + } + let label = param_label(p); + let Some((kind, ui, default)) = shape(p, cx.size) else { + col.placeholder_cost = col.placeholder_cost.saturating_add(1); + if p.stored().is_some() { + col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (type {:?})", p.kind)); + } + continue; + }; + let (items, names) = match &ui { + ParamUi::Popup { options } => (options.len(), options.iter().map(|o| 1 + o.len() / NAME_BYTES).fold(0, usize::saturating_add)), + _ => (0, 0), + }; + if p.kind == ParamKind::Popup && popup_len(p).is_some_and(|n| n > items) { + col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the items past the first {MAX_POPUP_ITEMS} not kept")); + } + let cost = col.placeholder_cost.saturating_add(names).saturating_add(1); + if cost > MAX_COST { + // The budget is spent: nothing more is built, here or in later effects (definitions + // shared by many instances would otherwise still be walked item by item). + col.lose( + LossCategory::Effects, + format!("{here}: parameter {label} and the ones after it not kept (past the import's {MAX_COST} placeholder parameters)"), + ); + col.placeholder_cost = MAX_COST; + break; + } + col.placeholder_cost = cost; + let mut prop = Property::new(ids.alloc(), ¶m_id(p), p.name.trim(), default).with_ui(ui); + prop.spatial = p.kind == ParamKind::Point; + prop.hold_only = matches!(p.kind, ParamKind::Checkbox | ParamKind::Popup | ParamKind::Layer); + match kind { + Some(kind) => { + fill(p, &mut prop, kind, cx, (&here, &label), col); + group.children.push(Node::Prop(prop)); + } + // A layer parameter: the layer it names (set once every layer exists, by its uid). + None => { + let id = format!("@{}", prop.uid); + group.children.push(Node::Prop(prop)); + import_layer_ref(p, &id, true, cx, (&here, &label), ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col }); + } + } + } + group +} + +/// How parameter `p` is held on a layer `size` big: its unit conversion (`None` for a layer +/// parameter), its control and its value until one is read. `None` for a type that is not kept. +fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option, ParamUi, Value)> { + let (kind, ui, default) = match p.kind { + ParamKind::IntSlider | ParamKind::FixedSlider | ParamKind::FloatSlider => (Kind::EffectNumber(1.0), slider_ui(p), Value::Scalar(0.0)), + ParamKind::Angle => (Kind::EffectNumber(1.0), ParamUi::Angle, Value::Scalar(0.0)), + ParamKind::Checkbox => (Kind::EffectBool, ParamUi::Checkbox, Value::Bool(false)), + ParamKind::Color => (Kind::EffectColor, ParamUi::Color, Value::Color([0.0, 0.0, 0.0, 1.0])), + ParamKind::Point => (Kind::EffectPoint(f64::from(size.0), f64::from(size.1)), ParamUi::Point, Value::Vec2([0.0, 0.0])), + ParamKind::Layer => return Some((None, ParamUi::Layer, Value::Layer(None))), + ParamKind::Popup => { + // The file's items, separators (`(-`) included: After Effects counts them. + let options: Vec = match &p.items { + Some(items) => items.iter().take(MAX_POPUP_ITEMS).cloned().collect(), + None => (1..=popup_len(p)?.min(MAX_POPUP_ITEMS)).map(|i| format!("Item {i}")).collect(), + }; + let n = u32::try_from(options.len()).ok().filter(|n| *n > 0)?; + (Kind::EffectPopup(n), ParamUi::Popup { options }, Value::Enum(0)) + } + _ => return None, + }; + Some((Some(kind), ui, default)) +} + +/// A slider's control: a float slider's valid range and drag range when they are ranges (only a +/// float slider's are decoded), else a plain number. +fn slider_ui(p: &EffectParam<'_, '_>) -> ParamUi { + match (p.valid_min(), p.valid_max(), p.slider_range()) { + (Some(min), Some(max), Some((smin, smax))) if [min, max, smin, smax].iter().all(|v| v.is_finite()) && min <= max && smin <= smax => { + ParamUi::Slider { min, max, slider_min: smin.clamp(min, max), slider_max: smax.clamp(min, max), decimals: 2 } + } + _ => ParamUi::Number, + } +} + +/// How many items a popup has: the file's names, else the count in its definition. +fn popup_len(p: &EffectParam<'_, '_>) -> Option { + p.items.as_ref().map(Vec::len).or_else(|| p.popup_item_count().map(usize::from)) +} + +/// The property id of `p`: its match name when that is one segment of a property path (a +/// third-party effect's `CC Cylinder-0003`), else `param` (a pseudo effect's +/// `Pseudo/0.25-0001`: `/` and `.` separate path segments). Expressions also find it by its name. +fn param_id(p: &EffectParam<'_, '_>) -> String { + if !p.match_name.is_empty() && p.match_name.chars().all(plain) { p.match_name.clone() } else { format!("param{}", p.index) } +} + +/// Whether `c` can stand in one segment of a property path (`/`, `.`, `#` and `@` mean more). +fn plain(c: char) -> bool { + c.is_alphanumeric() || matches!(c, ' ' | '-' | '_') +} + +/// `name` as one segment of a property path: other characters become `_` (`Pseudo/0.25` is +/// `Pseudo_0_25`). +fn segment(name: &str) -> String { + name.chars().map(|c| if plain(c) { c } else { '_' }).collect() +} + +/// Sets `prop` from `p`: its expression, then its keys or its value (the record, else the `pard` +/// default). `names` is `(here, label)` for the report. +fn fill(p: &EffectParam<'_, '_>, prop: &mut Property, kind: Kind, cx: &LayerCtx<'_>, names: (&str, &str), col: &mut Collector) { + let (here, label) = names; + if let Some(stored) = p.stored() { + import_expression(&stored, prop, col); + } + if p.is_animated() { + let Some(stored) = p.stored() else { return }; + if kind == Kind::EffectBool { + // Keys on a checkbox are not sampled by the corpus. + col.lose(LossCategory::Effects, format!("{here}: the keyframes of parameter {label} are not kept (not decoded)")); + return; + } + let before = prop.keys.len(); + import_keys(&stored, kind, cx.layer, &p.match_name, cx.tm, prop, col); + if prop.keys.len() == before { + col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} has no readable keyframe")); + } + return; + } + let value = match (p.stored(), p.recorded_value()) { + (Some(_), Some(v)) => v, + (Some(_), None) => { + col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value")); + return; + } + // A borrowed popup's default slot holds another copy's selection (docs/aep-format.md 3.7). + (None, _) if p.kind == ParamKind::Popup && p.borrowed_definition => { + col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not known (shared definition), the first item used")); + return; + } + // A popup's default slot can hold 0, no item (After Effects' save of a project it opened). + (None, _) => match p.pard_default() { + Some(ParamValue::Index(0)) => { + col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not stored, the first item used")); + return; + } + Some(v) => v, + None => return, + }, + }; + match (convert(value, kind), value) { + (Some(v), _) => prop.value = v, + // An item of the file that is past the ones kept (reported with the cut): the first item. + (None, ParamValue::Index(i)) if usize::try_from(i).is_ok_and(|i| i > MAX_POPUP_ITEMS && popup_len(p).is_some_and(|n| i <= n)) => { + col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item {i} is past the items kept, the first item used")); + } + (None, _) => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?})")), + } +} diff --git a/crates/aep/src/import/report.rs b/crates/aep/src/import/report.rs index 4732592d9..e52421dc0 100644 --- a/crates/aep/src/import/report.rs +++ b/crates/aep/src/import/report.rs @@ -56,7 +56,8 @@ pub enum LossCategory { /// Layers that could not be imported for another reason (unknown layer type, missing or /// unsupported source, precomposition loop). UnsupportedLayers, - /// Project items of a kind that is not imported. + /// Project items of a kind that is not imported, and items made from a Photoshop layer + /// without pixels (they show the merged image). UnsupportedItems, /// Data that could not be read (damaged headers, unreadable keyframes). DamagedData, @@ -160,6 +161,10 @@ pub struct Imported { /// in [`LossCategory::Effects`]). #[serde(default)] pub effects: usize, + /// Effects with no counterpart, kept as placeholders that render nothing (their parameters, + /// for expressions; each is also in [`LossCategory::Effects`]). + #[serde(default)] + pub placeholder_effects: usize, /// Layer styles (Drop Shadow, Stroke, ...), one per style on a layer. #[serde(default)] pub layer_styles: usize, @@ -277,6 +282,9 @@ pub(crate) struct Collector { /// many instances there were. They get a line each in [`Collector::finish`], so one that /// comes after the example lines are used up is still named (#3365). unmapped_effects: BTreeMap, + /// The properties and popup items the placeholders of this import hold so far (at most + /// `placeholder::MAX_COST`). + pub placeholder_cost: usize, } /// How many different unmapped effects get a line of their own (a file names at most this many). diff --git a/crates/aep/src/import/text.rs b/crates/aep/src/import/text.rs index 5333efcb0..dd0f469e2 100644 --- a/crates/aep/src/import/text.rs +++ b/crates/aep/src/import/text.rs @@ -14,7 +14,9 @@ use crate::{AutoKern, Caps, FontBaseline, Justification, Layer as AepLayer, ParagraphRun, PropGroup, PropNode, StyleRun as AepRun, TextDocument}; use effectcraft_keyframe::text_doc::{BaselineOption, CharStyle, Composer, Direction, Justify, Kerning, ParaStyle, StyleRun, TextDoc}; +use effectcraft_project::Property; +use crate::import::props::import_expression; use crate::import::report::{Collector, LossCategory}; /// How deep the walk over the text property groups goes. @@ -344,15 +346,27 @@ fn has_stored(g: &PropGroup<'_, '_>, depth: usize) -> bool { }) } +/// The Source Text expression into `target` (the layer's `text/sourceText`). The Source Text +/// record keeps it like any other property: the text in its `Utf8`, the flags in its `tdb4` +/// (`tests/fixtures/text-synthetic.aep`). An expression whose flags are unreadable, or a layer +/// without a Source Text property, is reported. +pub(crate) fn import_source_text_expression(layer: &AepLayer<'_, '_>, target: Option<&mut Property>, what: &str, col: &mut Collector) { + let Some(st) = layer.source_text_property() else { return }; + if st.expression().is_none() { + return; + } + match target { + Some(p) if st.expression_enabled().is_some() => import_expression(&st, p, col), + _ => col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not imported")), + } +} + /// The parts of a text layer besides its first text document that are not imported. pub(crate) fn report_text_extras(layer: &AepLayer<'_, '_>, what: &str, col: &mut Collector) { - if let Some(st) = layer.source_text_property() { - if st.is_animated() || layer.text_document_count() > 1 { - col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not imported (the first text document is)")); - } - if st.expression().is_some() { - col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not imported")); - } + if let Some(st) = layer.source_text_property() + && (st.is_animated() || layer.text_document_count() > 1) + { + col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not imported (the first text document is)")); } let Some(PropNode::Group(text)) = layer.properties().and_then(|p| p.get("ADBE Text Properties")) else { return }; for e in text.entries() { diff --git a/crates/aep/src/import/text_anim.rs b/crates/aep/src/import/text_anim.rs index d7a8c513c..11d90eca6 100644 --- a/crates/aep/src/import/text_anim.rs +++ b/crates/aep/src/import/text_anim.rs @@ -11,8 +11,8 @@ //! //! Not imported, and reported in [`LossCategory::TextLayers`]: wiggly and expression selectors, //! animator properties other than the ones mapped below (Character Value, Fill / Stroke -//! Hue, Saturation, Brightness and Opacity, 3D rotations, variable font axes, ...), and a Tracking -//! Type other than the default. +//! Hue, Saturation and Brightness, Fill Opacity, 3D rotations, variable font axes, ...), and a +//! Tracking Type other than the default. use crate::{PropGroup as AepGroup, PropNode, Property as AepProp}; use effectcraft_project::build::{self, Ids}; @@ -37,6 +37,7 @@ const PROPS: &[(&str, &str, &str, Kind)] = &[ ("ADBE Text Opacity", "opacity", "opacity", Kind::Number), ("ADBE Text Fill Color", "fillColor", "fillColor", Kind::EffectColor), ("ADBE Text Stroke Color", "strokeColor", "strokeColor", Kind::EffectColor), + ("ADBE Text Stroke Opacity", "strokeOpacity", "strokeOpacity", Kind::Number), ("ADBE Text Stroke Width", "strokeWidth", "strokeWidth", Kind::Number), ("ADBE Text Tracking Amount", "tracking", "tracking", Kind::Number), ("ADBE Text Line Spacing", "lineSpacing", "lineSpacing", Kind::Vec2), diff --git a/crates/aep/src/lib.rs b/crates/aep/src/lib.rs index 2a3d4a816..ef650911e 100644 --- a/crates/aep/src/lib.rs +++ b/crates/aep/src/lib.rs @@ -21,8 +21,8 @@ pub use container::{ GradientType, HueSaturationData, Interpolation, Item, ItemKind, Justification, KernRun, KeyEase, KeyLayout, KeyList, Keyframe, KeyframeKind, LIST, Layer, LayerHeader, LayerRef, LayerType, LevelsData, LightType, Limits, ListHeader, Marker, Mask, MaskAtom, MaskMode, MatteMode, MeshData, NESTED_IDS, Orientation, OrientationKey, ParagraphRun, ParamKind, ParamValue, PathVertex, PolystarType, Project, ProjectSettings, PropEntry, PropGroup, PropNode, - Property, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin, StyleRun, - TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk, WorkingSpace, - curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx, read_aepx_with_limits, style_map, - write, write_to, + Property, PsdLayer, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin, + StyleRun, TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk, + WorkingSpace, curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx, + read_aepx_with_limits, style_map, write, write_to, }; diff --git a/crates/aep/tests/fixtures/text-synthetic.aep b/crates/aep/tests/fixtures/text-synthetic.aep new file mode 100644 index 000000000..16cd79d06 Binary files /dev/null and b/crates/aep/tests/fixtures/text-synthetic.aep differ diff --git a/crates/aep/tests/fixtures/text-synthetic.aep.attribution b/crates/aep/tests/fixtures/text-synthetic.aep.attribution new file mode 100644 index 000000000..5bb5b9158 --- /dev/null +++ b/crates/aep/tests/fixtures/text-synthetic.aep.attribution @@ -0,0 +1,7 @@ +asset: text-synthetic.aep +title: Small After Effects test project for the .aep importer's text animator and Source Text expression tests +author: EffectCraft contributors +source: original work (made in After Effects 2026 by script from own data: a composition with two text layers, a text animator Stroke Opacity, static and keyed, and Source Text expressions, enabled and disabled) +license: MIT OR Apache-2.0 +added: 2026-11-08 by EffectCraft contributors +notes: The working space was set to None, so the file embeds no ICC profile; nothing After Effects wrote was changed. See crates/aep/README.md (Clean room). diff --git a/crates/aep/tests/it/import.rs b/crates/aep/tests/it/import.rs index 2535edcff..3c1e71bca 100644 --- a/crates/aep/tests/it/import.rs +++ b/crates/aep/tests/it/import.rs @@ -18,10 +18,12 @@ mod effects_round2; mod effects_round3; mod effects_thirdparty; mod fx_inject; +mod issue_3087; mod lumetri; mod markers; mod masks; mod mattes; +mod placeholders; mod puppet; mod resaved_defaults; mod robustness; @@ -31,5 +33,6 @@ mod styles; mod synthetic; mod text; mod text_anim; +mod text_synthetic; mod timing; mod versions; diff --git a/crates/aep/tests/it/import/fx_inject.rs b/crates/aep/tests/it/import/fx_inject.rs index ae61794d3..535e82483 100644 --- a/crates/aep/tests/it/import/fx_inject.rs +++ b/crates/aep/tests/it/import/fx_inject.rs @@ -10,7 +10,7 @@ use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import}; use effectcraft_aep::{Body, Chunk, ParamKind, ParamValue, Project as AepProject, parse, write}; use effectcraft_keyframe::Value; -use effectcraft_project::{Project, PropGroup}; +use effectcraft_project::{GroupKind, Project, PropGroup}; const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep"); @@ -274,10 +274,15 @@ pub fn import_bytes(bytes: &[u8], effect: &str) -> (Option, ImportRes 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 == effect).cloned())); + 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 == effect || matches!(&g.kind, GroupKind::Effect { effect: e } if e == effect)) + .cloned() + }) + }); (g, r) } diff --git a/crates/aep/tests/it/import/issue_3087.rs b/crates/aep/tests/it/import/issue_3087.rs new file mode 100644 index 000000000..bf8b575f4 --- /dev/null +++ b/crates/aep/tests/it/import/issue_3087.rs @@ -0,0 +1,90 @@ +//! #3087: an expression on Orientation, built into the committed `synthetic.aep` (no external +//! files; the values are made up, the layouts are docs/aep-format.md's). The Photoshop layers and +//! placeholders of the issue are tested in `synthetic.rs` and `placeholders.rs`. + +use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import}; +use effectcraft_aep::{Body, Chunk, parse, write}; +use effectcraft_keyframe::Value; +use effectcraft_project::Project; + +const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep"); + +fn visit(chunks: &mut [Chunk<'_>], f: &mut dyn FnMut(&mut Chunk<'_>)) { + for c in chunks { + f(c); + visit(c.children_mut(), f); + } +} + +fn import_all(bytes: &[u8]) -> (Project, ImportResult) { + let mut project = Project::default(); + let none = |_: &str| false; + let r = import(&mut project, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap(); + (project, r) +} + +/// `synthetic.aep` with every Orientation set to `[10, 20, 30]` and the expression `text`. +fn with_orientation_expression(text: &str) -> Vec { + let mut file = parse(SYNTHETIC).unwrap(); + let mut patched = 0; + visit(&mut file.chunks, &mut |c| { + if !c.is_list(b"otst") { + return; + } + for k in c.children_mut() { + if k.is_list(b"tdbs") { + let kids = k.children_mut(); + for r in kids.iter_mut() { + if let Body::Data(d) = &mut r.body { + let d = d.to_mut(); + match &r.id { + b"tdsb" => d.copy_from_slice(&1u32.to_be_bytes()), + b"tdb4" => { + d[119] = 0; + d[120] = 1; + } + _ => {} + } + } + } + let Body::List { children, .. } = &mut k.body else { continue }; + children.push(Chunk::data(*b"Utf8", text.as_bytes().to_vec())); + } else if k.is_list(b"otky") { + let mut otda = Vec::new(); + for v in [10.0f64, 20.0, 30.0] { + otda.extend(v.to_be_bytes()); + } + *k = Chunk::list(*b"otky", vec![Chunk::data(*b"otda", otda)]); + } + } + patched += 1; + }); + assert!(patched > 0, "the synthetic project has an Orientation"); + write(&file).unwrap() +} + +/// An expression on Orientation arrives with the value (both were dropped and reported "not +/// decoded"). +#[test] +fn an_expression_on_orientation_is_imported() { + let (p, r) = import_all(&with_orientation_expression("[1, 2, 3]")); + let mut seen = 0; + for (_, c) in p.comps() { + for l in &c.layers { + let Some(o) = l.props.prop("transform/orientation") else { continue }; + assert_eq!(o.value, Value::Vec3([10.0, 20.0, 30.0]), "{}", l.name); + assert_eq!(o.expr.as_ref().map(|e| (e.text.as_str(), e.enabled)), Some(("[1, 2, 3]", true)), "{}", l.name); + seen += 1; + } + } + assert!(seen > 0); + let orientation: Vec = r + .report + .losses + .iter() + .filter(|l| l.category == LossCategory::TransformProperties) + .flat_map(|l| l.details.clone()) + .filter(|d| d.contains("Orientation")) + .collect(); + assert!(orientation.is_empty(), "{orientation:?}"); +} diff --git a/crates/aep/tests/it/import/placeholders.rs b/crates/aep/tests/it/import/placeholders.rs new file mode 100644 index 000000000..1a8ec697e --- /dev/null +++ b/crates/aep/tests/it/import/placeholders.rs @@ -0,0 +1,315 @@ +//! #3087: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect of +//! expression controls) arrives as a placeholder holding its parameters, so expressions that read +//! them keep working; it renders nothing and is still reported. Each effect is built into +//! `synthetic.aep` (`fx_inject`) in place of its Glow, on the 8 x 8 sequence layer. + +use crate::import::fx_inject::{Default, Fx, bytes_with, import_bytes, losses, other, popup, run, slider, v}; +use effectcraft_aep::import::LossCategory; +use effectcraft_aep::{Body, Chunk, ParamKind as K, parse, write}; +use effectcraft_keyframe::Value; +use effectcraft_project::{GroupKind, ParamUi, PropGroup}; + +/// A third-party effect with one parameter of each kept kind, inside a twirl-down group. +fn third_party(values: Vec<(usize, f64)>, keys: Vec<(usize, Vec<(i32, f64)>)>) -> Fx { + Fx { + match_name: "CC Cylinder", + name: "CC Cylinder", + defs: vec![ + other(K::GroupStart, "Light", Default::None), + slider(K::FloatSlider, "Radius (%)", 30.0, (0.0, 30000.0)), + other(K::GroupEnd, "", Default::None), + other(K::Angle, "Rotation X", Default::Number(12.5)), + other(K::Checkbox, "Wire", Default::Number(1.0)), + other(K::Color, "Light Color", Default::Color([255, 51, 102, 204])), + other(K::Point, "Position", Default::Point(0.25, 0.5)), + popup("Render", 1, &["Full", "(-", "Outside", "Inside"]), + slider(K::IntSlider, "Count", 3.0, (0.0, 50.0)), + ], + values, + data: vec![], + keys, + } +} + +fn placeholder_of(fx: &Fx) -> (PropGroup, effectcraft_aep::import::ImportResult) { + let (g, r) = run(fx, fx.match_name); + (g.expect("the placeholder"), r) +} + +#[test] +fn an_effect_without_a_counterpart_is_kept_with_its_values() { + // Radius 37.5 and Render "Outside" (3: the separator counts) stored, the rest at defaults. + let (g, r) = placeholder_of(&third_party(vec![(2, 37.5), (8, 3.0)], vec![])); + assert_eq!(g.kind, GroupKind::Effect { effect: "CC Cylinder".into() }); + assert_eq!(g.name, "CC Cylinder"); + let names: Vec<(&str, &str)> = g.props().map(|p| (p.match_id.as_str(), p.name.as_str())).collect(); + assert_eq!( + names, + [ + ("CC Cylinder-0002", "Radius (%)"), + ("CC Cylinder-0004", "Rotation X"), + ("CC Cylinder-0005", "Wire"), + ("CC Cylinder-0006", "Light Color"), + ("CC Cylinder-0007", "Position"), + ("CC Cylinder-0008", "Render"), + ("CC Cylinder-0009", "Count"), + ], + "flat, in order, without the group markers" + ); + assert_eq!(v(&g, "CC Cylinder-0002"), Value::Scalar(37.5)); + assert_eq!(v(&g, "CC Cylinder-0004"), Value::Scalar(12.5)); + assert_eq!(v(&g, "CC Cylinder-0005"), Value::Bool(true)); + let Value::Color(c) = v(&g, "CC Cylinder-0006") else { panic!("a colour") }; + assert!(c.iter().zip([0.2, 0.4, 0.8, 1.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{c:?}"); + assert_eq!(v(&g, "CC Cylinder-0007"), Value::Vec2([2.0, 4.0]), "layer pixels"); + assert_eq!(v(&g, "CC Cylinder-0008"), Value::Enum(2), "item 3 of 4, 0-based"); + assert_eq!(v(&g, "CC Cylinder-0009"), Value::Scalar(3.0)); + let render = g.prop("CC Cylinder-0008").unwrap(); + assert_eq!(render.ui, ParamUi::Popup { options: ["Full", "(-", "Outside", "Inside"].map(String::from).to_vec() }); + // Still reported, once, and counted apart from the imported effects. + let found = losses(&r, LossCategory::Effects, "CC Cylinder"); + assert!(found.len() == 1 && found[0].ends_with("has the effect 'CC Cylinder' (CC Cylinder), kept without rendering"), "{found:?}"); + assert_eq!((r.report.imported.placeholder_effects, r.report.imported.effects), (1, 1), "the placeholder and the Levels"); +} + +#[test] +fn keys_and_expressions_of_a_placeholder_are_kept() { + let fx = third_party(vec![(4, 12.5)], vec![(2, vec![(0, 10.0), (25, 20.0)])]); + let bytes = with_expression(&bytes_with(&fx), "CC Cylinder-0004", "time * 90"); + let (g, _) = import_bytes(&bytes, "CC Cylinder"); + let g = g.unwrap(); + let radius = g.prop("CC Cylinder-0002").unwrap(); + assert_eq!(radius.keys.iter().map(|k| k.value.clone()).collect::>(), [Value::Scalar(10.0), Value::Scalar(20.0)]); + let angle = g.prop("CC Cylinder-0004").unwrap(); + assert_eq!(angle.expr.as_ref().map(|e| (e.text.as_str(), e.enabled)), Some(("time * 90", true))); +} + +/// A pseudo effect's parameter match names (`Pseudo/0.25-0001`) are no property path segment: +/// its parameters are `param`, found by their names. +#[test] +fn a_pseudo_effect_is_kept_with_its_parameter_names() { + let fx = Fx { + match_name: "Pseudo/0.25", + name: "Settings", + defs: vec![slider(K::FloatSlider, "Speed", 1.0, (0.0, 100.0)), popup("Mode", 2, &["A", "B"])], + values: vec![(1, 4.0)], + data: vec![], + keys: vec![], + }; + let (g, r) = placeholder_of(&fx); + assert_eq!(g.prop("param1").map(|p| (p.name.as_str(), p.value.clone())), Some(("Speed", Value::Scalar(4.0)))); + assert_eq!(g.prop("param2").map(|p| (p.name.as_str(), p.value.clone())), Some(("Mode", Value::Enum(1)))); + assert_eq!(losses(&r, LossCategory::Effects, "Pseudo/0.25").len(), 1); + // The effect id stays the match name (Find Missing Effects, expressions); the group's match id + // is one path segment, so a match path (keyframe paste, pick whip) finds its parameters again. + assert_eq!(g.kind, GroupKind::Effect { effect: "Pseudo/0.25".into() }); + let speed = g.prop("param1").map(|p| p.uid); + let layer = PropGroup::new(0, "layer", "Layer").with(PropGroup::new(0, "effects", "Effects").with(g)); + let path = speed.and_then(|u| layer.match_path_of(u)); + assert_eq!(path.as_deref().and_then(|p| layer.prop(p)).map(|p| p.name.as_str()), Some("Speed"), "{path:?}"); +} + +/// A float slider keeps its valid range and slider range, so Effect Controls drags and clamps it +/// as After Effects does; a range that is not a range stays a plain number. +#[test] +fn a_float_slider_keeps_its_range() { + let fx = Fx { + match_name: "Pseudo/r", + name: "Rig", + defs: vec![slider(K::FloatSlider, "Speed", 1.0, (-10.0, 100.0)), slider(K::FloatSlider, "Odd", 1.0, (5.0, 1.0))], + values: vec![], + data: vec![], + keys: vec![], + }; + let (g, _) = placeholder_of(&fx); + let ui = |id: &str| g.prop(id).map(|p| p.ui.clone()); + assert_eq!(ui("param1"), Some(ParamUi::Slider { min: -10.0, max: 100.0, slider_min: -10.0, slider_max: 100.0, decimals: 2 })); + assert_eq!(ui("param2"), Some(ParamUi::Number)); +} + +/// A popup whose definition is borrowed (the project copy) and has no value record: its default +/// slot holds another copy's selection, so the first item is used and that is reported. +#[test] +fn a_borrowed_popup_without_a_record_takes_the_first_item_and_is_reported() { + let bytes = without_instance_definitions(&bytes_with(&third_party(vec![], vec![]))); + let (g, r) = import_bytes(&bytes, "CC Cylinder"); + assert_eq!(v(&g.unwrap(), "CC Cylinder-0008"), Value::Enum(0)); + let found = losses(&r, LossCategory::Effects, "CC Cylinder"); + assert!(found.iter().any(|d| d.contains("Render") && d.contains("default item is not known")), "{found:?}"); +} + +/// A popup default slot of 0 (no item; After Effects' save of a project it opened) takes the first +/// item and is reported, not read as damaged data. +#[test] +fn a_popup_default_of_no_item_takes_the_first_item() { + let fx = Fx { match_name: "Some Fx", name: "Some", defs: vec![popup("Mode", 0, &["A", "B"])], values: vec![], data: vec![], keys: vec![] }; + let (g, r) = placeholder_of(&fx); + assert_eq!(v(&g, "Some Fx-0001"), Value::Enum(0)); + let found = losses(&r, LossCategory::Effects, "Some Fx"); + assert!(found.iter().any(|d| d.contains("default item is not stored")), "{found:?}"); + assert!(losses(&r, LossCategory::DamagedData, "Some Fx").is_empty()); +} + +/// A popup past the 1024 items kept: the cut is reported, and a selection among the cut items +/// takes the first item and is reported as such, not as damaged data. +#[test] +fn a_popup_past_the_items_kept_is_reported() { + let items: &'static [&'static str] = Box::leak((0..1100).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::>().into_boxed_slice()); + let fx = Fx { match_name: "Long Fx", name: "Long", defs: vec![popup("Pick", 1, items)], values: vec![(1, 1050.0)], data: vec![], keys: vec![] }; + let (g, r) = placeholder_of(&fx); + let pick = g.prop("Long Fx-0001").unwrap(); + assert_eq!(pick.value, Value::Enum(0)); + assert!(matches!(&pick.ui, ParamUi::Popup { options } if options.len() == 1024)); + let found = losses(&r, LossCategory::Effects, "Long Fx"); + assert!(found.iter().any(|d| d.contains("past the first 1024")), "{found:?}"); + assert!(found.iter().any(|d| d.contains("item 1050 is past the items kept")), "{found:?}"); + assert!(losses(&r, LossCategory::DamagedData, "Long Fx").is_empty()); +} + +/// Many large popups stay within the import's budget: what is beyond is reported, not kept. +#[test] +fn a_hostile_placeholder_stays_bounded() { + let items: &'static [&'static str] = Box::leak((0..1000).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::>().into_boxed_slice()); + let fx = Fx { match_name: "Big Fx", name: "Big", defs: (0..300).map(|_| popup("P", 1, items)).collect(), values: vec![], data: vec![], keys: vec![] }; + let (g, r) = placeholder_of(&fx); + let kept = g.props().count(); + assert!(kept > 0 && kept < 300, "{kept}"); + assert!(g.props().map(|p| if let ParamUi::Popup { options } = &p.ui { options.len() + 1 } else { 1 }).sum::() <= 200_000); + assert!(losses(&r, LossCategory::Effects, "Big Fx").iter().any(|d| d.contains("placeholder parameters"))); +} + +/// Two instances of an effect whose parameters fill the import's budget: the first keeps what fits +/// and stops at the first parameter past it; the second is reported without a placeholder (its +/// shared definitions are not read again). +#[test] +fn an_effect_past_the_spent_budget_gets_no_placeholder() { + let items: &'static [&'static str] = Box::leak((0..1000).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::>().into_boxed_slice()); + let fx = Fx { match_name: "Big Fx", name: "Big", defs: (0..300).map(|_| popup("P", 1, items)).collect(), values: vec![], data: vec![], keys: vec![] }; + let bytes = twice(&bytes_with(&fx), "Big Fx"); + let mut project = effectcraft_project::Project::default(); + let none = |_: &str| false; + let r = effectcraft_aep::import::import( + &mut project, + &bytes, + &effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) }, + ) + .unwrap(); + let placeholders: Vec = project + .comps() + .flat_map(|(_, c)| c.layers.iter()) + .filter_map(|l| l.props.sub("effects")) + .flat_map(|fx| fx.children.iter().filter_map(|n| n.as_group()).filter(|g| g.match_id == "Big Fx").map(|g| g.props().count()).collect::>()) + .collect(); + // 199 popups of 1000 items (1001 each) fit in 200 000; the 200th stops the first instance. + assert_eq!(placeholders, [199]); + let found = losses(&r, LossCategory::Effects, "Big Fx"); + assert_eq!(found.iter().filter(|d| d.contains("and the ones after it not kept")).count(), 1, "{found:?}"); + assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}"); + assert!(found.iter().any(|d| d.contains("kept without rendering") && !d.contains("more like it")), "the kept instance alone: {found:?}"); +} + +/// Parameters a placeholder does not keep (markers, arbitrary data) still spend the budget: a +/// definition of very many of them, shared by many instances, is not walked again for each one. +#[test] +fn parameters_not_kept_still_spend_the_budget() { + let defs = (0..200_000).map(|i| other(if i % 2 == 0 { K::NoData } else { K::ArbitraryData }, "X", Default::None)).collect(); + let fx = Fx { match_name: "Odd Fx", name: "Odd", defs, values: vec![], data: vec![], keys: vec![] }; + let (_, r) = import_bytes(&twice(&bytes_with(&fx), "Odd Fx"), "Odd Fx"); + let found = losses(&r, LossCategory::Effects, "Odd Fx"); + assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}"); +} + +/// Long popup item names spend the budget by their length, so the names kept stay bounded. +#[test] +fn long_popup_item_names_spend_the_budget() { + let long = "x".repeat(1600); + let items: &'static [&'static str] = + Box::leak((0..1024).map(|i| &*Box::leak(format!("{long}{i}").into_boxed_str())).collect::>().into_boxed_slice()); + let fx = Fx { match_name: "Long Fx", name: "Long", defs: vec![popup("A", 1, items), popup("B", 1, items)], values: vec![], data: vec![], keys: vec![] }; + let (g, r) = placeholder_of(&fx); + assert_eq!(g.props().count(), 1); + assert!(losses(&r, LossCategory::Effects, "Long Fx").iter().any(|d| d.contains("placeholder parameters"))); +} + +/// `bytes` with the layer's instance of `match_name` (its `tdmn` and `sspc`) repeated after it. +fn twice(bytes: &[u8], match_name: &str) -> Vec { + let mut file = parse(bytes).unwrap(); + let mut done = 0; + edit(&mut file.chunks, false, &mut |c, in_project_copy| { + let Body::List { children, .. } = &mut c.body else { return }; + if in_project_copy { + return; + } + let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(match_name.as_bytes()))) + else { + return; + }; + let pair: Vec> = children[at..at + 2].to_vec(); + children.splice(at + 2..at + 2, pair); + done += 1; + }); + assert_eq!(done, 1, "one instance"); + write(&file).unwrap() +} + +/// `bytes` with the expression `text` on the parameter record `param` (enabled: `tdb4` byte 120 +/// 1, docs/aep-format.md 3.6). +fn with_expression(bytes: &[u8], param: &str, text: &str) -> Vec { + let mut file = parse(bytes).unwrap(); + let mut done = 0; + edit(&mut file.chunks, false, &mut |c, _| { + let Body::List { children, .. } = &mut c.body else { return }; + let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(param.as_bytes()))) else { + return; + }; + let Some(Body::List { children: record, .. }) = children.get_mut(at + 1).map(|k| &mut k.body) else { return }; + for k in record.iter_mut().filter(|k| k.is(b"tdb4")) { + if let Body::Data(d) = &mut k.body + && let Some(b) = d.to_mut().get_mut(120) + { + *b = 1; + } + } + record.push(Chunk::data(*b"Utf8", text.as_bytes().to_vec())); + done += 1; + }); + assert!(done >= 1); + write(&file).unwrap() +} + +/// `bytes` with the layer's instance of `CC Cylinder` stripped of its own definitions (an empty +/// `parT`): it borrows the project copy's (`EfdG`). +fn without_instance_definitions(bytes: &[u8]) -> Vec { + let mut file = parse(bytes).unwrap(); + let mut done = 0; + edit(&mut file.chunks, false, &mut |c, in_project_copy| { + let Body::List { children, .. } = &mut c.body else { return }; + if in_project_copy { + return; + } + let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(&b"CC Cylinder"[..]))) + else { + return; + }; + let Some(sspc) = children.get_mut(at + 1).filter(|k| k.is_list(b"sspc")) else { return }; + for k in sspc.children_mut() { + if let Body::List { list_type, children } = &mut k.body + && list_type == b"parT" + { + children.clear(); + done += 1; + } + } + }); + assert_eq!(done, 1, "one instance"); + write(&file).unwrap() +} + +/// Calls `f` on every chunk with whether it is inside the project's effect definitions (`EfdG`). +fn edit(chunks: &mut [Chunk<'_>], in_efdg: bool, f: &mut dyn FnMut(&mut Chunk<'_>, bool)) { + for c in chunks { + let inside = in_efdg || c.is_list(b"EfdG"); + f(c, inside); + edit(c.children_mut(), inside, f); + } +} diff --git a/crates/aep/tests/it/import/synthetic.rs b/crates/aep/tests/it/import/synthetic.rs index a31a61679..d1c030401 100644 --- a/crates/aep/tests/it/import/synthetic.rs +++ b/crates/aep/tests/it/import/synthetic.rs @@ -843,6 +843,92 @@ fn a_default_state_colour_record_holds_the_value() { assert_ne!(colour(&default_state), colour(&unchanged), "the recorded colour, not the default"); } +/// The project with its png item made one layer of a Photoshop file `art.psd`: the `opti` of +/// docs/aep-format.md 3.3 (tag `8BPS`, the layer index at 14, a 1000 x 1000 document at 32 and 36, +/// its bounds at 78-94, its name at 344) and the item `size` big. +fn as_psd_layer(index: i32, bounds: [i32; 4], name: &str, size: (u32, u32)) -> Vec { + let mut opti = vec![0u8; 602]; + opti[..4].copy_from_slice(b"8BPS"); + opti[14..18].copy_from_slice(&index.to_be_bytes()); + opti[32..36].copy_from_slice(&1000u32.to_le_bytes()); + opti[36..40].copy_from_slice(&1000u32.to_le_bytes()); + for (i, v) in bounds.iter().enumerate() { + opti[78 + 4 * i..82 + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + opti[344..344 + name.len()].copy_from_slice(name.as_bytes()); + let alias = br#"{"fullpath":"C:\\x\\art.psd","platform":1,"target_is_folder":false}"#.to_vec(); + mutate(&mut |c| { + if !c.is_list(b"Pin ") { + return; + } + let Body::List { children, .. } = &mut c.body else { return }; + if !children.iter().any(|k| k.is(b"opti") && k.bytes().is_some_and(|d| d.get(..4) == Some(&b"png!"[..]))) { + return; + } + // No sequence naming between the alias and the `opti`. + children.retain(|k| k.is(b"sspc") || k.is(b"opti") || k.is_list(b"Als2")); + for k in children.iter_mut() { + if k.is(b"opti") { + k.body = Body::Data(opti.clone().into()); + } else if k.is(b"sspc") { + set_data(k, 30, &size.0.to_be_bytes()); + set_data(k, 34, &size.1.to_be_bytes()); + } + } + visit(children, &mut |k| { + if k.is(b"alas") { + k.body = Body::Data(alias.clone().into()); + } + }); + }) +} + +/// #3087: an item made from one layer of a Photoshop file shows that layer, named +/// `/`; it showed the whole document, named after the file. Item as big as the layer: +/// Retain Layer Sizes; as big as the document: the layer on the document. +#[test] +fn a_photoshop_layer_item_shows_its_layer() { + for (size, layer_size) in [((48, 15), true), ((1000, 1000), false)] { + let (p, r) = run(&as_psd_layer(7, [749, 800, 764, 848], "Tëst", size), true); + r.unwrap(); + let (name, f) = p.items.values().find_map(|i| if let ItemKind::Footage(f) = &i.kind { Some((i.name.clone(), f.clone())) } else { None }).unwrap(); + assert_eq!(name, "Tëst/art.psd"); + let l = f.layer.expect("the layer"); + assert_eq!((l.index, l.name.as_str(), l.layer_size, (f.width, f.height)), (7, "Tëst", layer_size, size)); + } +} + +/// A layer as big as the document but off its corner fits both framings: shown at its own bounds +/// and reported. One at the corner, or bigger than the document, reads one way and is not. An item +/// as big as neither is shown on the document and reported. +#[test] +fn a_photoshop_layer_as_big_as_the_document_off_its_corner_is_reported() { + let framing = |bounds, size| { + let (p, r) = run(&as_psd_layer(3, bounds, "Moved", size), true); + let found = losses(&r.unwrap(), LossCategory::UnsupportedItems); + let said = |what: &str| found.iter().any(|d| d.contains("'Moved/art.psd'") && d.contains(what)); + (the_footage(&p).layer.map(|l| l.layer_size), said("as big as the document"), said("neither the Photoshop layer's size")) + }; + assert_eq!(framing([5, 10, 1005, 1010], (1000, 1000)), (Some(true), true, false)); + assert_eq!(framing([0, 0, 1000, 1000], (1000, 1000)), (Some(true), false, false)); + assert_eq!(framing([9, -346, 1083, 1086], (1432, 1074)), (Some(true), false, false)); + assert_eq!(framing([749, 800, 764, 848], (1000, 1000)), (Some(false), false, false)); + // An item as big as neither the layer nor the document: shown on the document, reported. + assert_eq!(framing([5, 10, 1005, 1010], (800, 800)), (Some(false), false, true)); +} + +/// #3087: a Photoshop layer without pixels (an adjustment layer) keeps the merged image and is +/// reported; the merged image itself (index -1) is no layer. +#[test] +fn a_photoshop_layer_without_pixels_keeps_the_merged_image() { + let (p, r) = run(&as_psd_layer(4, [0; 4], "Levels 1", (1000, 1000)), true); + let found = losses(&r.unwrap(), LossCategory::UnsupportedItems); + assert!(found.iter().any(|d| d.contains("'Levels 1/art.psd'") && d.contains("without pixels")), "{found:?}"); + assert_eq!(the_footage(&p).layer, None); + let (p, _) = run(&as_psd_layer(-1, [0; 4], "", (1000, 1000)), true); + assert_eq!(the_footage(&p).layer, None); +} + /// #3087: an expression on Orientation arrives with the stored value, as on any property; it was /// dropped together with the value and reported as "not decoded". #[test] diff --git a/crates/aep/tests/it/import/text_synthetic.rs b/crates/aep/tests/it/import/text_synthetic.rs new file mode 100644 index 000000000..537ca86f7 --- /dev/null +++ b/crates/aep/tests/it/import/text_synthetic.rs @@ -0,0 +1,131 @@ +//! A small committed text project (`tests/fixtures/text-synthetic.aep`), so the text animator +//! Stroke Opacity and the Source Text expression are checked without the external corpus, on +//! import and through an export and a second import (#3170). +//! +//! The project was made in After Effects 2026 with the working space set to None: one composition +//! `C` (64x48, 25 fps, 2 s) with two text layers. `T` holds `Hi` (Arial, 20 px, a blue 2 px +//! stroke), the Source Text expression `text.sourceText + "!"` (enabled), an animator `Stroke` +//! with Stroke Opacity 40 % and an animator `Keyed` with Stroke Opacity keyed 0 % at 0 s and +//! 100 % at 1 s. `Off` holds `Off` and the Source Text expression `"X"`, disabled. Nothing After +//! Effects wrote was changed. + +use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import}; +use effectcraft_aep::{AepFile, Body, Chunk, parse, write}; +use effectcraft_keyframe::Value; +use effectcraft_project::{Expression, Layer, Project, PropGroup}; +use effectcraft_time::{TICKS_PER_SECOND, Tick}; + +use crate::import::helpers::comp; + +const TEXT_SYNTHETIC: &[u8] = include_bytes!("../../fixtures/text-synthetic.aep"); + +/// Imports `bytes` with losses allowed. +fn run(bytes: &[u8]) -> (Project, ImportResult) { + let mut project = Project::default(); + let none = |_: &str| false; + let r = import(&mut project, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("the project imports"); + (project, r) +} + +/// The loss details of `category`. +fn losses(r: &ImportResult, category: LossCategory) -> Vec { + r.report.losses.iter().filter(|l| l.category == category).flat_map(|l| l.details.clone()).collect() +} + +/// The layer `name` of composition `C`. +fn layer<'p>(p: &'p Project, r: &ImportResult, name: &str) -> &'p Layer { + let (_, c) = comp(p, r, "C"); + c.layers.iter().find(|l| l.name == name).unwrap_or_else(|| panic!("text layer {name}")) +} + +/// The text animator `name` of `l`. +fn animator<'l>(l: &'l Layer, name: &str) -> &'l PropGroup { + l.props.group("text/animators").expect("animators").groups().find(|a| a.name == name).unwrap_or_else(|| panic!("animator {name}")) +} + +/// The Source Text of `l`: its stored text and its expression. +fn source_text(l: &Layer) -> (String, Option) { + let p = l.props.prop("text/sourceText").expect("Source Text"); + let Value::Text(doc) = &p.value else { panic!("{:?}", p.value) }; + (doc.text.clone(), p.expr.clone()) +} + +/// Stroke Opacity 40 % and its keys 0 % / 100 % arrive in percent, without a loss. +#[test] +fn text_animator_stroke_opacity_is_imported_static_and_keyed() { + let (p, r) = run(TEXT_SYNTHETIC); + let text = losses(&r, LossCategory::TextLayers); + assert!(!text.iter().any(|d| d.contains("Stroke Opacity")), "{text:?}"); + let t = layer(&p, &r, "T"); + // Stored as After Effects shows it: percent. + let st = animator(t, "Stroke").prop("properties/strokeOpacity").expect("strokeOpacity"); + assert_eq!((st.value.clone(), st.keys.len()), (Value::Scalar(40.0), 0)); + let keyed = animator(t, "Keyed").prop("properties/strokeOpacity").expect("strokeOpacity"); + let keys: Vec<_> = keyed.keys.iter().map(|k| (k.time, k.value.clone())).collect(); + assert_eq!(keys, vec![(Tick::ZERO, Value::Scalar(0.0)), (Tick(TICKS_PER_SECOND), Value::Scalar(100.0))]); +} + +/// Both Source Text expressions arrive with their enable switch, next to the stored text. +#[test] +fn the_source_text_expression_is_imported_enabled_and_disabled() { + let (p, r) = run(TEXT_SYNTHETIC); + let text = losses(&r, LossCategory::TextLayers); + assert!(!text.iter().any(|d| d.contains("Source Text expression")), "{text:?}"); + // The stored text stays the Source Text value; the expression comes next to it. + assert_eq!(source_text(layer(&p, &r, "T")), ("Hi".to_string(), Some(Expression { text: "text.sourceText + \"!\"".into(), enabled: true }))); + assert_eq!(source_text(layer(&p, &r, "Off")), ("Off".to_string(), Some(Expression { text: "\"X\"".into(), enabled: false }))); + assert_eq!(r.report.imported.expressions, 2); +} + +/// Calls `f` on every chunk below `chunks`, depth-first. +fn visit(chunks: &mut [Chunk<'_>], f: &mut dyn FnMut(&mut Chunk<'_>)) { + for c in chunks { + f(c); + visit(c.children_mut(), f); + } +} + +/// Export and a second import keep the Source Text expressions and Stroke Opacity, unreported. +#[test] +fn stroke_opacity_and_source_text_expressions_survive_export() { + let (p, r0) = run(TEXT_SYNTHETIC); + let out = effectcraft_aep::export::export(&p, &effectcraft_aep::export::ExportOptions { allow_losses: true }).expect("export"); + let text: Vec = + out.report.losses.iter().filter(|l| l.category == effectcraft_aep::export::LossCategory::TextLayers).flat_map(|l| l.details.clone()).collect(); + assert!(!text.iter().any(|d| d.contains("Stroke Opacity") || d.contains("Source Text expression")), "{text:?}"); + assert_eq!(out.report.exported.expressions, 2); + let (q, r) = run(&out.bytes); + for name in ["T", "Off"] { + assert_eq!(source_text(layer(&q, &r, name)), source_text(layer(&p, &r0, name)), "{name}"); + } + let t = layer(&q, &r, "T"); + assert_eq!(animator(t, "Stroke").prop("properties/strokeOpacity").map(|p| p.value.clone()), Some(Value::Scalar(40.0))); + let keys: Vec<_> = animator(t, "Keyed").prop("properties/strokeOpacity").expect("strokeOpacity").keys.iter().map(|k| (k.time, k.value.clone())).collect(); + assert_eq!(keys, vec![(Tick::ZERO, Value::Scalar(0.0)), (Tick(TICKS_PER_SECOND), Value::Scalar(100.0))]); +} + +/// Guard: an expression whose `tdb4` flags give no state stays reported instead of imported. +#[test] +fn a_source_text_expression_with_unreadable_flags_stays_reported() { + // `tdb4` byte 120 is 1 on a property with an expression; with 0 the expression's state is + // unknown, so it is reported instead of imported. + let mut file: AepFile<'_> = parse(TEXT_SYNTHETIC).expect("parse"); + visit(&mut file.chunks, &mut |c| { + if !c.is_list(b"btds") { + return; + } + for tdbs in c.children_mut().iter_mut().filter(|c| c.is_list(b"tdbs")) { + for tdb4 in tdbs.children_mut().iter_mut().filter(|c| c.is(b"tdb4")) { + if let Body::Data(d) = &mut tdb4.body + && let Some(b) = d.to_mut().get_mut(120) + { + *b = 0; + } + } + } + }); + let (p, r) = run(&write(&file).expect("write")); + let text = losses(&r, LossCategory::TextLayers); + assert_eq!(text.iter().filter(|d| d.contains("the Source Text expression is not imported")).count(), 2, "{text:?}"); + assert_eq!(source_text(layer(&p, &r, "T")), ("Hi".to_string(), None)); +} diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index 0407ba756..dda0a406c 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -65,6 +65,8 @@ const REFUSED: &[&str] = &[ "file.revealInFinder", "layer.openSource", "help.revealLogFile", + // Hands the footage file to the platform's default application. + "edit.editOriginal", "file.autoSave", // The Plug-in Library downloads code, installs it to load at start-up and reads `file://` catalogs. "library.refresh", @@ -73,6 +75,10 @@ const REFUSED: &[&str] = &[ "library.uninstall", "library.loadInstalled", "library.preview", + // Watch Folder renders the projects it finds to the outputs they name and writes status + // files into the watched folder: neither is a path the agent gives, so neither is checked. + "file.watchFolder", + "file.watchFolder.poll", ]; /// Most numbered folders `check_render_folder` inspects for one output; more are refused. @@ -91,7 +97,6 @@ const READS: &[(&str, &[&str])] = &[ ("file.replaceFootage", &["path"]), ("file.relinkFootage", &["folder"]), ("file.setProxy", &["path"]), - ("file.watchFolder", &["folder"]), ("anim.applyPreset", &["path"]), ("anim.applyRecentPreset", &["path"]), ("keys.rpfCameraImport", &["path"]), @@ -105,7 +110,6 @@ const READS: &[(&str, &[&str])] = &[ // unchecked. ("essential.templateInfo", &["path"]), ("file.importProject", &["path"]), - ("file.watchFolder.poll", &["folder"]), ("footage.relink", &["path"]), ("layer.newModel", &["path"]), ("mediaBrowser.fileInfo", &["path"]), @@ -785,6 +789,16 @@ mod tests { assert!(read(&footage(&inside)).1.is_complete()); } + #[test] + fn watch_folder_and_edit_original_are_refused_while_confined() { + let dir = std::env::temp_dir(); + let c = Confinement::new(std::slice::from_ref(&dir), std::slice::from_ref(&dir)).unwrap(); + for id in ["file.watchFolder", "file.watchFolder.poll", "edit.editOriginal"] { + let e = c.check_command(id, &serde_json::json!({"folder": dir.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("not available while file access is confined"), "{id}: {e}"); + } + } + #[test] fn relative_and_outside_paths_of_newly_listed_commands_are_refused() { let base = std::env::temp_dir().join(format!("ec-confine-1243-{}", std::process::id())); diff --git a/crates/effects/src/color2.rs b/crates/effects/src/color2.rs index 6639e649e..9df44d76f 100644 --- a/crates/effects/src/color2.rs +++ b/crates/effects/src/color2.rs @@ -252,10 +252,18 @@ impl Lv { if clip_w { t = t.min(1.0); } - self.ob + (self.ow - self.ob) * crate::color_fx::levels_gamma(t, self.g.max(0.01)) + let curve = crate::color_fx::levels_gamma(t, self.g.max(0.01)).clamp(-LEVELS_IC_CURVE_LIMIT, LEVELS_IC_CURVE_LIMIT); + self.ob + (self.ow - self.ob) * curve } } +/// How far Levels (Individual Controls)' curve may reach: with gamma down to 0 (rendered as 0.01, +/// an exponent of 100) an HDR value a few times Input White overflows `f32`, and an infinite curve +/// times an empty output range is NaN. 1e30 times the widest output range (2e4) is still finite +/// (`f32::MAX` is 3.4e38), and every curve that was finite before stays as it was below it. The +/// GPU (`fxt_lv`) uses the same. +const LEVELS_IC_CURVE_LIMIT: f32 = 1e30; + fn levels_ic(ctx: &EffectCtx, mut b: Buf) -> Buf { let lv = LV_IDS.map(|ids| Lv { ib: ctx.params.f(ids[0]) as f32, @@ -978,11 +986,14 @@ fn cc_kernel(ctx: &EffectCtx, mut b: Buf) -> Buf { pub fn specs() -> Vec { let mut lv_params = Vec::new(); for (ids, names) in LV_IDS.iter().zip(LV_NAMES.iter()) { - lv_params.push(p(ids[0], names[0], num(0.0), slider(-1.0, 2.0, 0.0, 1.0, 3))); - lv_params.push(p(ids[1], names[1], num(1.0), slider(-1.0, 2.0, 0.0, 1.0, 3))); - lv_params.push(p(ids[2], names[2], num(1.0), slider(0.1, 10.0, 0.1, 3.0, 2))); - lv_params.push(p(ids[3], names[3], num(0.0), slider(-1.0, 2.0, 0.0, 1.0, 3))); - lv_params.push(p(ids[4], names[4], num(1.0), slider(-1.0, 2.0, 0.0, 1.0, 3))); + // After Effects' valid ranges (#3487-#3491): levels -10000..10000 and gamma from 0 (the + // renderer floors it at 0.01); gamma keeps its wider maximum. The sliders stay 0..1. + let level = || slider(-10000.0, 10000.0, 0.0, 1.0, 3); + lv_params.push(p(ids[0], names[0], num(0.0), level())); + lv_params.push(p(ids[1], names[1], num(1.0), level())); + lv_params.push(p(ids[2], names[2], num(1.0), slider(0.0, 10.0, 0.1, 3.0, 2))); + lv_params.push(p(ids[3], names[3], num(0.0), level())); + lv_params.push(p(ids[4], names[4], num(1.0), level())); } lv_params.push(p("clipToOutputBlack", "Clip To Output Black", Value::Enum(2), popup(&crate::color_fx::LEVELS_CLIP))); lv_params.push(p("clipToOutputWhite", "Clip To Output White", Value::Enum(2), popup(&crate::color_fx::LEVELS_CLIP))); diff --git a/crates/effects/src/color2/tests.rs b/crates/effects/src/color2/tests.rs index 5f57692a0..76338dd98 100644 --- a/crates/effects/src/color2/tests.rs +++ b/crates/effects/src/color2/tests.rs @@ -270,6 +270,39 @@ fn levels_ic_clip_popups() { assert!(run("ec.color.levelsic", &img, &off).data[0][0] > 1.5); } +/// #3487-#3491: over After Effects' valid ranges (levels ±10000, gamma from 0) the output stays +/// finite: gamma 0 renders as 0.01, whose curve on an HDR value overflows `f32` unbounded. +#[test] +fn levels_ic_stays_finite_over_the_whole_range() { + let img = Image::filled(2, 2, [3.0, 0.5, -2.0, 1.0]); + for (ib, iw, ob, ow) in [ + (0.0, 1.0, 0.0, 1.0), + (0.0, 1.0, 1.0, 1.0), + (-10000.0, 10000.0, -10000.0, 10000.0), + (10000.0, -10000.0, 10000.0, -10000.0), + (0.0, 1e-3, -10000.0, 10000.0), + ] { + let lv = [ + ("rgb/rgbInBlack", num(ib)), + ("rgb/rgbInWhite", num(iw)), + ("rgb/rgbGamma", num(0.0)), + ("rgb/rgbOutBlack", num(ob)), + ("rgb/rgbOutWhite", num(ow)), + ("clipToOutputBlack", Value::Enum(0)), + ("clipToOutputWhite", Value::Enum(0)), + ]; + let out = run("ec.color.levelsic", &img, &lv); + assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{ib} {iw} {ob} {ow}: {:?}", out.data[0]); + } + // The bound only stops the overflow: an HDR value that was finite before keeps its level + // (gamma 0.1 at 4 x Input White: 4^10). + let bright = run("ec.color.levelsic", &Image::filled(1, 1, [4.0, 4.0, 4.0, 1.0]), &[("rgb/rgbGamma", num(0.1)), ("clipToOutputWhite", Value::Enum(0))]); + assert_eq!(bright.data[0][0], 4.0f32.powf(10.0)); + // Gamma 0 is the limit of a small gamma: below Input White the curve goes to 0. + let dark = run("ec.color.levelsic", &Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]), &[("rgb/rgbGamma", num(0.0))]); + assert!(dark.data[0][0] < 1e-6, "{:?}", dark.data[0]); +} + /// A host whose other layers and other frames are a fixed image. struct ImgHost(Image); impl crate::EffectHost for ImgHost { diff --git a/crates/effects/src/color3.rs b/crates/effects/src/color3.rs index d0d398100..6548fdbdb 100644 --- a/crates/effects/src/color3.rs +++ b/crates/effects/src/color3.rs @@ -809,7 +809,7 @@ pub fn specs() -> Vec { "Change Color", vec![ p("view", "View", Value::Enum(0), popup(&["Corrected Layer", "Color Correction Mask"])), - p("hueTransform", "Hue Transform", num(0.0), slider(-360.0, 360.0, -180.0, 180.0, 1)), + p("hueTransform", "Hue Transform", num(0.0), slider(-1800.0, 1800.0, -180.0, 180.0, 1)), p("lightnessTransform", "Lightness Transform", num(0.0), bipolar()), p("saturationTransform", "Saturation Transform", num(0.0), bipolar()), p("colorToChange", "Color To Change", col(0.8, 0.2, 0.2), ParamUi::Color), diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 610f73f4c..59d4aad01 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -506,8 +506,8 @@ pub fn specs() -> Vec { p("anchor", "Anchor Point", pt(0.5, 0.5), ParamUi::Point), p("position", "Position", pt(0.5, 0.5), ParamUi::Point), p("uniform", "Uniform Scale", Value::Bool(true), ParamUi::Checkbox), - p("scaleHeight", "Scale Height", num(100.0), slider(-10000.0, 10000.0, 0.0, 600.0, 1)), - p("scaleWidth", "Scale Width", num(100.0), slider(-10000.0, 10000.0, 0.0, 600.0, 1)), + p("scaleHeight", "Scale Height", num(100.0), slider(-30000.0, 30000.0, 0.0, 600.0, 1)), + p("scaleWidth", "Scale Width", num(100.0), slider(-30000.0, 30000.0, 0.0, 600.0, 1)), p("skew", "Skew", num(0.0), slider(-70.0, 70.0, -70.0, 70.0, 1)), p("skewAxis", "Skew Axis", num(0.0), ParamUi::Angle), p("rotation", "Rotation", num(0.0), ParamUi::Angle), diff --git a/crates/effects/src/distort2.rs b/crates/effects/src/distort2.rs index bbd8738a8..611cb6dcf 100644 --- a/crates/effects/src/distort2.rs +++ b/crates/effects/src/distort2.rs @@ -743,7 +743,7 @@ pub fn specs() -> Vec { p("evolution", "Evolution", num(0.0), ParamUi::Angle), p("evolutionOptions/cycleEvolution", "Cycle Evolution", Value::Bool(false), ParamUi::Checkbox), p("evolutionOptions/cycle", "Cycle (in Revolutions)", num(1.0), slider(1.0, 1000.0, 1.0, 20.0, 0)), - p("evolutionOptions/randomSeed", "Random Seed", num(0.0), slider(0.0, 10000.0, 0.0, 1000.0, 0)), + p("evolutionOptions/randomSeed", "Random Seed", num(0.0), slider(0.0, 100000.0, 0.0, 1000.0, 0)), p("pinning", "Pinning", Value::Enum(1), popup(&TURBULENT_PINNING)), p("resizeLayer", "Resize Layer", Value::Bool(false), ParamUi::Checkbox), ], diff --git a/crates/effects/src/file_cache.rs b/crates/effects/src/file_cache.rs new file mode 100644 index 000000000..88fb75bbd --- /dev/null +++ b/crates/effects/src/file_cache.rs @@ -0,0 +1,436 @@ +//! Caches of what effects read from files named by a parameter (a LUT, an OCIO transform file, an +//! OCIO config), keyed by the parameter text and checked against the files each result was read +//! from (#3493, #3538). +//! +//! A cached result remembers every file its load read, with the file's size and modification time +//! (its stamp) taken before reading, including the files a nested cached load read (a config's +//! `FileTransform` LUTs) and files looked for but missing. Each lookup stamps those files again +//! (one `metadata` call each) and loads again once one moved, so a file edited, created, deleted or +//! repaired on disk is followed. Inline text reads no file and is its own content. An edit that keeps +//! both the size and the modification time can't be told apart. +//! +//! Every file read is also followed by [`check_lut_files`], and [`lut_generation`] moves when one is +//! found changed: the viewers and frame caches drop the frames made before. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::SystemTime; + +/// A file's size and modification time when it was read (`None`: missing, or a file that could +/// not be described). A file whose stamp moved is read again. +pub(crate) type FileStamp = Option<(u64, Option)>; + +/// The files a load read and their stamps. +type Files = Vec<(String, FileStamp)>; + +/// At most this many files are followed by [`check_lut_files`]; the least recently read go first. +const MAX_FOLLOWED_FILES: usize = 1024; + +/// One cached result and what it was read from. +struct Entry { + files: Files, + value: V, + used: u64, + /// The result's size estimate and the parameter text, counted against the cache's byte bound. + bytes: usize, +} + +/// Results by parameter text, at most `max_entries` and `max_bytes` of them, the least recently +/// used going first. +pub(crate) struct SourceCache { + map: HashMap>, + clock: u64, + bytes: usize, + max_entries: usize, + max_bytes: usize, +} + +impl SourceCache { + pub(crate) fn new(max_entries: usize, max_bytes: usize) -> Self { + SourceCache { map: HashMap::new(), clock: 0, bytes: 0, max_entries, max_bytes } + } + + fn remove(&mut self, src: &str) { + if let Some(e) = self.map.remove(src) { + self.bytes = self.bytes.saturating_sub(e.bytes); + } + } + + /// Forget the results read from `path`. + fn forget_file(&mut self, path: &str) { + let stale: Vec = self.map.iter().filter(|(_, e)| e.files.iter().any(|(p, _)| p == path)).map(|(k, _)| k.clone()).collect(); + for src in stale { + self.remove(&src); + } + } + + /// Keep within the bounds, always the result for `keep`. + fn evict(&mut self, keep: &str) { + while self.map.len() > self.max_entries || (self.bytes > self.max_bytes && self.map.len() > 1) { + let Some(oldest) = self.map.iter().filter(|(k, _)| k.as_str() != keep).min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) else { break }; + self.remove(&oldest); + } + } + + /// The files the result cached for `src` was read from. + pub(crate) fn files(&self, src: &str) -> Option> { + self.map.get(src).map(|e| e.files.iter().map(|(p, _)| p.clone()).collect()) + } + + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.map.len() + } + + #[cfg(test)] + pub(crate) fn contains(&self, src: &str) -> bool { + self.map.contains_key(src) + } + + #[cfg(test)] + pub(crate) fn bytes(&self) -> (usize, usize, usize) { + (self.bytes, self.map.values().map(|e| e.bytes).sum(), self.max_bytes) + } +} + +/// Lock a cache; a panic elsewhere while it was held leaves a usable map. +pub(crate) fn lock(cache: &Mutex>) -> MutexGuard<'_, SourceCache> { + cache.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A cache that registers with [`check_lut_files`] on first use. +pub(crate) struct Registered { + cache: OnceLock>>, + max_entries: usize, + max_bytes: usize, +} + +impl Registered { + pub(crate) const fn new(max_entries: usize, max_bytes: usize) -> Self { + Registered { cache: OnceLock::new(), max_entries, max_bytes } + } + + pub(crate) fn get(&'static self) -> &'static Mutex> { + self.cache.get_or_init(|| { + registry().push(self); + Mutex::new(SourceCache::new(self.max_entries, self.max_bytes)) + }) + } +} + +/// A cache [`check_lut_files`] tells to forget the results read from a changed file. +trait ForgetFile: Sync { + fn forget_file(&self, path: &str); + /// Add the files the cached results were read from to `out`. + fn held_files(&self, out: &mut HashSet); +} + +impl ForgetFile for Registered { + fn forget_file(&self, path: &str) { + if let Some(c) = self.cache.get() { + lock(c).forget_file(path); + } + } + + fn held_files(&self, out: &mut HashSet) { + if let Some(c) = self.cache.get() { + out.extend(lock(c).map.values().flat_map(|e| e.files.iter().map(|(p, _)| p.clone()))); + } + } +} + +fn registry() -> MutexGuard<'static, Vec<&'static dyn ForgetFile>> { + static REGISTRY: OnceLock>> = OnceLock::new(); + REGISTRY.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner) +} + +thread_local! { + /// The loads running on this thread, innermost last: the files each read, and the bytes of + /// the cached results it holds (a config holds the LUTs its `FileTransform`s loaded). + static READING: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Note that the running load read (or looked for) `path`, stamped `stamp`. +pub(crate) fn note_file(path: &str, stamp: FileStamp) { + READING.with(|r| { + if let Ok(mut r) = r.try_borrow_mut() + && let Some((top, _)) = r.last_mut() + && !top.iter().any(|(p, _)| p == path) + { + top.push((path.to_string(), stamp)); + } + }); +} + +/// Note that the running load holds a cached result of `bytes`. +fn note_bytes(bytes: usize) { + READING.with(|r| { + if let Ok(mut r) = r.try_borrow_mut() + && let Some((_, held)) = r.last_mut() + { + *held = held.saturating_add(bytes); + } + }); +} + +/// Pops the files of a load when it ends, even by a panic. +struct Reading { + popped: bool, +} + +impl Reading { + fn start() -> Reading { + READING.with(|r| { + if let Ok(mut r) = r.try_borrow_mut() { + r.push((Vec::new(), 0)); + } + }); + Reading { popped: false } + } + + fn pop() -> Option<(Files, usize)> { + READING.with(|r| r.try_borrow_mut().ok().and_then(|mut r| r.pop())) + } + + /// The files the load read, and the bytes of the cached results it holds. + fn finish(mut self) -> (Files, usize) { + self.popped = true; + Self::pop().unwrap_or_default() + } +} + +impl Drop for Reading { + fn drop(&mut self) { + if !self.popped { + let _ = Self::pop(); + } + } +} + +/// The stamp of the file at `path` now: one `metadata` call. +pub(crate) fn file_stamp(path: &str) -> FileStamp { + std::fs::metadata(path).ok().map(|md| (md.len(), md.modified().ok())) +} + +/// Read the text file at `path` for the running load, stamped before reading (a file written +/// after it was stamped has a newer stamp, and is read again next time). +pub(crate) fn read(path: &str) -> std::io::Result { + note_file(path, file_stamp(path)); + std::fs::read_to_string(path) +} + +/// Note that the running load looked for `path` and did not find it: it loads again once the file +/// appears. +pub(crate) fn note_missing(path: &str) { + note_file(path, None); +} + +/// The result cached for `src`, or `load`'s (and its size estimate in bytes), cached. `load` reads +/// files with [`read`] (and notes the ones it looked for with [`note_missing`]); no lock is held +/// while it runs or while the files are stamped. +pub(crate) fn cached(cache: &Mutex>, src: &str, load: impl FnOnce() -> (V, usize)) -> V { + let files = lock(cache).map.get(src).map(|e| e.files.clone()); + let stale = files.is_some(); + if let Some(files) = files + && files.iter().all(|(p, s)| file_stamp(p) == *s) + { + let mut c = lock(cache); + c.clock += 1; + let now = c.clock; + if let Some(e) = c.map.get_mut(src) + && e.files == files + { + e.used = now; + let (value, bytes) = (e.value.clone(), e.bytes); + drop(c); + // (an enclosing load depends on these files too, and holds this result) + for (p, s) in &files { + note_file(p, *s); + } + note_bytes(bytes); + return value; + } + } + let reading = Reading::start(); + let (value, size) = load(); + let (files, held) = reading.finish(); + follow(&files, stale); + for (p, s) in &files { + note_file(p, *s); + } + // (what it holds counts against this cache's bound too: another cache letting go of it + // frees nothing while this result keeps it) + let bytes = size.saturating_add(held).saturating_add(src.len()); + note_bytes(bytes); + let mut c = lock(cache); + c.clock += 1; + let used = c.clock; + c.remove(src); + c.map.insert(src.to_string(), Entry { files, value: value.clone(), used, bytes }); + c.bytes = c.bytes.saturating_add(bytes); + c.evict(src); + value +} + +/// How often a file a cached load read was found changed on disk ([`lut_generation`]). +static GENERATION: AtomicU64 = AtomicU64::new(0); + +/// The files followed by [`check_lut_files`]: the stamp each was last read with, and when. +#[derive(Default)] +struct Followed { + files: HashMap, + clock: u64, +} + +fn followed() -> MutexGuard<'static, Followed> { + static FOLLOWED: OnceLock> = OnceLock::new(); + FOLLOWED.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner) +} + +impl Followed { + /// Note that `files` were read with these stamps; true when one has a different stamp than + /// its last read's: a file changed on disk. + fn read(&mut self, files: &Files) -> bool { + let mut moved = false; + for (path, stamp) in files { + self.clock += 1; + let now = self.clock; + if self.files.insert(path.clone(), (*stamp, now)).is_some_and(|(old, _)| old != *stamp) { + moved = true; + } + } + moved + } + + /// Keep at most [`MAX_FOLLOWED_FILES`], letting go of the least recently read first but never + /// of a file in `held` (a cached result was read from it) or in `files` (just read). + fn trim(&mut self, held: &HashSet, files: &Files) { + while self.files.len() > MAX_FOLLOWED_FILES { + let Some(oldest) = self + .files + .iter() + .filter(|(p, _)| !held.contains(p.as_str()) && !files.iter().any(|(f, _)| f == *p)) + .min_by_key(|(_, (_, used))| *used) + .map(|(p, _)| p.clone()) + else { + break; + }; + self.files.remove(&oldest); + } + } +} + +/// The files the registered caches' results were read from. +fn held_files() -> HashSet { + let caches: Vec<&'static dyn ForgetFile> = registry().clone(); + let mut out = HashSet::new(); + for c in caches { + c.held_files(&mut out); + } + out +} + +/// Note that `files` were read with these stamps. A file read with a different stamp than last +/// time, or a load replacing a result whose files moved (`stale`), means a file changed on disk, +/// and frames made before may show the old contents. +fn follow(files: &Files, stale: bool) { + let (moved, over) = { + let mut f = followed(); + (f.read(files), f.files.len() > MAX_FOLLOWED_FILES) + }; + if over { + // (gathered without the followed files' lock: no two of these locks are ever nested) + let held = held_files(); + followed().trim(&held, files); + } + if moved || stale { + GENERATION.fetch_add(1, Ordering::AcqRel); + } +} + +/// Changes each time a file a cached load read is found changed on disk (by a load itself or +/// [`check_lut_files`]): frames made before then may show the old contents. +pub fn lut_generation() -> u64 { + GENERATION.load(Ordering::Acquire) +} + +/// Look at every file read (one `metadata` call each) and forget the results read from the ones +/// that changed on disk since, so the next load reads them again. Returns [`lut_generation`]. +pub fn check_lut_files() -> u64 { + let files: Vec<(String, FileStamp)> = followed().files.iter().map(|(p, (s, _))| (p.clone(), *s)).collect(); + // (stamped without the lock: a file on a slow share must not hold up renders) + let changed: Vec<(String, FileStamp, FileStamp)> = + files.into_iter().filter_map(|(path, old)| Some(file_stamp(&path)).filter(|now| *now != old).map(|now| (path, old, now))).collect(); + let caches: Vec<&'static dyn ForgetFile> = registry().clone(); + for (path, old, now) in changed { + { + let mut f = followed(); + // (a render that read the file meanwhile has noted its new stamp already) + match f.files.get_mut(&path) { + Some((s, _)) if *s == old => *s = now, + _ => continue, + } + } + for c in &caches { + c.forget_file(&path); + } + GENERATION.fetch_add(1, Ordering::AcqRel); + } + lut_generation() +} + +#[cfg(test)] +pub(crate) fn followed_stamp(path: &str) -> Option { + followed().files.get(path).map(|(s, _)| *s) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Past [`MAX_FOLLOWED_FILES`], the file just read is still followed (a list of its own: the + /// shared one's files belong to the other tests too). + #[test] + fn the_file_just_read_stays_followed_past_the_limit() { + let mut f = Followed::default(); + let held: HashSet = ["/followed/0.cube".to_string()].into(); + for i in 0..MAX_FOLLOWED_FILES + 8 { + let files = vec![(format!("/followed/{i}.cube"), Some((1, None)))]; + assert!(!f.read(&files)); + f.trim(&held, &files); + assert!(f.files.contains_key(&files[0].0), "{i}: the file just read"); + assert!(f.files.len() <= MAX_FOLLOWED_FILES); + } + assert!(f.files.contains_key("/followed/0.cube"), "a file a cached result was read from"); + assert!(!f.files.contains_key("/followed/1.cube"), "the least recently read other"); + assert!(f.read(&vec![("/followed/1030.cube".into(), Some((2, None)))]), "a moved stamp"); + } + + /// A nested cached load's files count for the enclosing load. + #[test] + fn an_enclosing_load_depends_on_a_nested_loads_files() { + static INNER: Registered = Registered::new(8, 1 << 20); + static OUTER: Registered = Registered::new(8, 1 << 20); + let v = cached(OUTER.get(), "outer", || { + note_missing("/nested/outer-own.cube"); + let inner = cached(INNER.get(), "inner", || { + note_missing("/nested/inner.cube"); + (7, 100) + }); + (inner, 0) + }); + assert_eq!(v, 7); + let files = lock(OUTER.get()).files("outer").unwrap(); + let held = |src: &str| lock(OUTER.get()).map.get(src).map(|e| e.bytes); + // ("inner" is 5 bytes, its result 100: "outer" holds it, on a load and on a hit alike) + assert_eq!(held("outer"), Some(100 + 5 + "outer".len()), "the result an enclosing load holds counts"); + assert_eq!(files, vec!["/nested/outer-own.cube".to_string(), "/nested/inner.cube".to_string()]); + // A hit on the inner result still reports its files to a new enclosing load. + let w = cached(OUTER.get(), "outer 2", || (cached(INNER.get(), "inner", || (0, 0)), 0)); + assert_eq!(w, 7); + assert_eq!(lock(OUTER.get()).files("outer 2").unwrap(), vec!["/nested/inner.cube".to_string()]); + assert_eq!(held("outer 2"), Some(100 + 5 + "outer 2".len())); + } +} diff --git a/crates/effects/src/generate.rs b/crates/effects/src/generate.rs index ae0d61861..d8d47a7c7 100644 --- a/crates/effects/src/generate.rs +++ b/crates/effects/src/generate.rs @@ -121,11 +121,17 @@ pub fn four_color_softening(blend: f64, scale: f64) -> f64 { (b * b).max(1e-6) } +/// 4-Color Gradient's Jitter (percent, up to After Effects' 500 %) as the dither's strength: 1 at +/// 100 %, a few code values of noise per unit. +pub fn four_color_jitter(jitter: f64) -> f32 { + (jitter / 100.0).clamp(0.0, 5.0) as f32 +} + fn four_color(ctx: &EffectCtx, mut b: Buf) -> Buf { let pts: Vec<((f64, f64), [f32; 4])> = (1..=4).map(|i| (b.to_px(ctx.params.v2(&format!("positionsColors/point{i}"))), ctx.params.color(&format!("positionsColors/color{i}")))).collect(); let k = four_color_softening(ctx.params.f("blend"), b.scale); - let jitter = (ctx.params.f("jitter") / 100.0).clamp(0.0, 1.0) as f32; + let jitter = four_color_jitter(ctx.params.f("jitter")); let op = ctx.params.f("opacity") as f32 / 100.0; let mode = ctx.params.e("blendingMode"); let seed = ctx.seed; @@ -349,8 +355,9 @@ pub fn specs() -> Vec { p("positionsColors/color3", "Color 3", col(1.0, 0.0, 1.0), ParamUi::Color), p("positionsColors/point4", "Point 4", pt(0.9, 0.9), ParamUi::Point), p("positionsColors/color4", "Color 4", col(0.0, 0.0, 1.0), ParamUi::Color), - p("blend", "Blend", num(100.0), slider(1.0, 1000.0, 1.0, 1000.0, 1)), - p("jitter", "Jitter", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)), + // After Effects' valid ranges (#3478, #3479); Blend keeps its lower minimum (1, not 5). + p("blend", "Blend", num(100.0), slider(1.0, 10000.0, 1.0, 1000.0, 1)), + p("jitter", "Jitter", num(0.0), slider(0.0, 500.0, 0.0, 100.0, 1)), p("opacity", "Opacity", num(100.0), slider(0.0, 100.0, 0.0, 100.0, 1)), p("blendingMode", "Blending Mode", Value::Enum(0), popup(&GEN_BLEND_MODES[..18])), ], @@ -384,7 +391,7 @@ pub fn specs() -> Vec { p("corner", "Corner", pt(0.1, 0.1), ParamUi::Point), p("width", "Width", num(64.0), slider(1.0, 4000.0, 1.0, 400.0, 1)), p("height", "Height", num(64.0), slider(1.0, 4000.0, 1.0, 400.0, 1)), - p("border", "Border", num(2.0), slider(0.0, 400.0, 0.0, 40.0, 1)), + p("border", "Border", num(2.0), slider(0.0, 2000.0, 0.0, 40.0, 1)), p("feather/featherWidth", "Width", num(0.0), slider(0.0, 1000.0, 0.0, 50.0, 1)), p("feather/featherHeight", "Height", num(0.0), slider(0.0, 1000.0, 0.0, 50.0, 1)), p("invertGrid", "Invert Grid", Value::Bool(false), ParamUi::Checkbox), @@ -465,6 +472,21 @@ mod generator_tests { } } + /// #3479: Jitter goes up to After Effects' 500 %, and more jitter dithers more (the dither + /// stopped growing at 100 %). + #[test] + fn four_color_jitter_grows_up_to_five_hundred_percent() { + let img = Image::filled(32, 32, [0.0, 0.0, 0.0, 1.0]); + let spread = |jitter: f64| { + let o = run_fx("ec.generate.fourcolor", &[("jitter", num(jitter))], img.clone(), 0.0, EffectEnv::default()).img; + let flat = run_fx("ec.generate.fourcolor", &[], img.clone(), 0.0, EffectEnv::default()).img; + o.data.iter().zip(&flat.data).map(|(a, b)| (a[0] - b[0]).abs()).fold(0.0f32, f32::max) + }; + let (at100, at500) = (spread(100.0), spread(500.0)); + assert!(at100 > 0.0 && at500 > 4.0 * at100, "{at100} {at500}"); + assert!(at500 < 0.2, "a few code values: {at500}"); + } + /// After Effects 2026, 4-Color Gradient defaults (yellow, green, magenta, blue at 10 % / 90 % /// of a 1920 × 1080 layer) at Blend 100 and 300, here on a tenth-size layer with Blend 10 /// and 30 (the weights scale with the layer): colours at AE pixels (10x + 5, 10y + 5). diff --git a/crates/effects/src/generate2.rs b/crates/effects/src/generate2.rs index ad80cb9cd..6bf5443fc 100644 --- a/crates/effects/src/generate2.rs +++ b/crates/effects/src/generate2.rs @@ -1111,8 +1111,8 @@ pub fn specs() -> Vec { p("endPoint", "Ending Point", pt(0.75, 0.5), ParamUi::Point), p("length", "Length", num(25.0), pct()), p("time", "Time", num(0.0), pct()), - p("startThickness", "Starting Thickness", num(8.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), - p("endThickness", "Ending Thickness", num(8.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), + p("startThickness", "Starting Thickness", num(8.0), slider(0.0, 4000.0, 0.0, 100.0, 1)), + p("endThickness", "Ending Thickness", num(8.0), slider(0.0, 4000.0, 0.0, 100.0, 1)), p("softness", "Softness", num(20.0), pct()), p("insideColor", "Inside Color", col(1.0, 1.0, 1.0), ParamUi::Color), p("outsideColor", "Outside Color", col(0.4, 0.4, 1.0), ParamUi::Color), diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 532bb28c9..f9d8f97e8 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -39,6 +39,7 @@ mod keying2; pub mod keylight; mod matte; +mod file_cache; pub mod migrate; mod misc; pub mod mocha_shape; @@ -99,7 +100,7 @@ pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state}; pub use stylize2::strobe_on; // CPU helpers the GPU kernels share (effectcraft-gpu). pub use blur2::{CAMERA_LENS_MAX_RADIUS, camera_lens_plain, camera_lens_radius, camera_lens_spans, radial_fast_pad}; -pub use generate::{four_color_softening, gen_mode}; +pub use generate::{four_color_jitter, four_color_softening, gen_mode}; pub use generate2::pattern_kind as cell_pattern_kind; pub use generate2::{BoltSeg, Contour, Ghost, RadioPlan, Wave, flare_ghosts, lightning_segments, radio_plan}; pub use generate3::{ @@ -123,13 +124,14 @@ pub use channel3d::{ crypto_layer_name, crypto_layer_named, extractor_aux_channel, extractor_own_channel, id_color, is_extractor_copy, matte_only_px, reads_aux, selection_hashes, }; +pub use file_cache::{check_lut_files, lut_generation}; 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::{ CausticsSetup, FoamDisc, FoamEnv, FoamPlan, Piece, PiecePlan, PieceTex, PixelPlan, WavePlan, Waves, caustics_setup, foam_full_plan, piece_plan, pixel_plan, wave_world_plan, }; -pub use utility::{Lut, load_lut}; +pub use utility::{Lut, load_lut, lut_file, lut_files, lut_params}; pub use vr::{equi_dir as vr_equi_dir, rotation as vr_rotation}; /// Effect categories in Effects & Presets order. diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 65951ad97..9c7131657 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -919,7 +919,7 @@ pub fn specs() -> Vec { p("startAngle", "Start Angle", num(0.0), ParamUi::Angle), p("center", "Wipe Center", Value::Vec2([0.5, 0.5]), ParamUi::Point), p("wipe", "Wipe", Value::Enum(0), popup(&["Clockwise", "Counterclockwise", "Both"])), - p("feather", "Feather", num(0.0), slider(0.0, 360.0, 0.0, 50.0, 1)), + p("feather", "Feather", num(0.0), slider(0.0, 32000.0, 0.0, 50.0, 1)), ], radial_wipe, ), @@ -930,8 +930,8 @@ pub fn specs() -> Vec { vec![ p("completion", "Transition Completion", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 0)), p("direction", "Direction", num(90.0), ParamUi::Angle), - p("width", "Width", num(30.0), slider(2.0, 1000.0, 2.0, 200.0, 0)), - p("feather", "Feather", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)), + p("width", "Width", num(30.0), slider(1.0, 32000.0, 2.0, 200.0, 0)), + p("feather", "Feather", num(0.0), slider(0.0, 32000.0, 0.0, 100.0, 1)), ], venetian, ), diff --git a/crates/effects/src/noise.rs b/crates/effects/src/noise.rs index 09217f831..fde24b537 100644 --- a/crates/effects/src/noise.rs +++ b/crates/effects/src/noise.rs @@ -766,10 +766,12 @@ pub fn specs() -> Vec { let hls_common = || { vec![ p("noise", "Noise", Value::Enum(0), popup(&["Uniform", "Squared", "Grain"])), - p("hue", "Hue", num(0.0), pct()), - p("lightness", "Lightness", num(0.0), pct()), - p("saturation", "Saturation", num(0.0), pct()), - p("grainSize", "Grain Size", num(1.0), slider(0.1, 100.0, 0.5, 10.0, 2)), + // After Effects' valid ranges (#3483, #3484): the amounts go to 1000 %, Grain Size + // down to 0 (the renderer floors it at 0.1 px) and keeps its wider maximum. + p("hue", "Hue", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), + p("lightness", "Lightness", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), + p("saturation", "Saturation", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), + p("grainSize", "Grain Size", num(1.0), slider(0.0, 100.0, 0.5, 10.0, 2)), ] }; let mut hls = hls_common(); @@ -967,6 +969,32 @@ mod tests { assert_eq!(still.img, img); } + /// #3483, #3484: amounts above 100 % keep adding noise, and Grain Size 0 renders (floored at + /// 0.1 px) with finite output, for both effects. + #[test] + fn noise_hls_takes_after_effects_ranges() { + let mut img = Image::new(16, 16); + for (i, p) in img.data.iter_mut().enumerate() { + *p = premul([0.6, 0.3, (i % 7) as f32 / 7.0], 1.0); + } + for id in ["ec.noise.noisehls", "ec.noise.noisehlsauto"] { + for (param, lo, hi) in [("hue", 0.0, 1000.0), ("lightness", 0.0, 1000.0), ("saturation", 0.0, 1000.0), ("grainSize", 0.0, 100.0)] { + let ui = &crate::find(id).unwrap().params.iter().find(|p| p.id == param).unwrap().ui; + assert!(matches!(ui, ParamUi::Slider { min, max, .. } if *min == lo && *max == hi), "{id} {param}: {ui:?}"); + } + let at = |amount: f64, grain: f64| { + let vals = + [("noise", Value::Enum(2)), ("hue", num(amount)), ("lightness", num(amount)), ("saturation", num(amount)), ("grainSize", num(grain))]; + run(id, &vals, img.clone(), 0.0).img + }; + let (low, high) = (at(100.0, 1.0), at(1000.0, 1.0)); + assert_ne!(low, high, "{id}"); + for out in [high, at(1000.0, 0.0)] { + assert!(out.data.iter().flatten().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{id}"); + } + } + } + #[test] fn add_grain_keeps_flat_mean() { let out = run("ec.noise.addgrain", &[("tweaking/intensity", num(2.0)), ("application/blendingMode", Value::Enum(2))], gray(64, 64, 0.5), 0.0); diff --git a/crates/effects/src/ocio.rs b/crates/effects/src/ocio.rs index 2daa9857d..febbc163c 100644 --- a/crates/effects/src/ocio.rs +++ b/crates/effects/src/ocio.rs @@ -24,8 +24,7 @@ //! * Configuration ▸ Custom reads a `.ocio` file instead ([`crate::ocio_config`]); what it can't //! apply is reported by [`warning`]. -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::Arc; use effectcraft_color::ColorSpace; use effectcraft_color::space::{invert, mul, mul_vec, rgb_to_xyz}; @@ -51,6 +50,7 @@ pub use effects::parse_looks; pub use effects::{color_stabilizer_maps, warning}; #[cfg(test)] use effects::{tonemap, tonemap_inv}; +pub(crate) use lut::cached_files; pub use lut::{FileXform, load_file}; #[cfg(test)] pub use lut::{parse_file, parse_spi1d, parse_spi3d, parse_spimtx}; diff --git a/crates/effects/src/ocio/lut.rs b/crates/effects/src/ocio/lut.rs index de931a411..daa584278 100644 --- a/crates/effects/src/ocio/lut.rs +++ b/crates/effects/src/ocio/lut.rs @@ -1,5 +1,6 @@ use super::cdl::{Cdl, parse_cdl_xml}; -use super::{Arc, HashMap, Lut, Mutex, OnceLock, parse_cube}; +use super::{Arc, Lut, parse_cube}; +use crate::file_cache::{self, Registered}; // ---------------------------------------------------------------- LUT files @@ -264,33 +265,38 @@ pub fn parse_file(text: &str, ext: &str) -> Option { parse_3dl(text).map(|lut| FileXform::Lut { lut, shaper: None }) } -type FileCache = Mutex>>>; +/// [`load_file`]'s cache, by parameter text (bounded like [`crate::load_lut`]'s). +static FILES: Registered>> = Registered::new(64, 512 << 20); -/// Load (and cache) a transform from a file path or inline content. +/// The files the transform cached for `src` was read from. +pub(crate) fn cached_files(src: &str) -> Option> { + file_cache::lock(FILES.get()).files(src) +} + +/// Load (and cache) a transform from a file path or inline content. A file is stamped (one +/// `metadata` call) on every load and read again once its size or modification time moved (see +/// [`crate::file_cache`]); inline content is its own content. pub fn load_file(src: &str) -> Option> { let src_t = src.trim(); if src_t.is_empty() { return None; } - static CACHE: OnceLock = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - if let Ok(m) = cache.lock() - && let Some(v) = m.get(src) - { - return v.clone(); - } - let inline = src.contains('\n'); - let parsed = if inline { - parse_file(src, "") - } else { - let ext = std::path::Path::new(src_t).extension().and_then(std::ffi::OsStr::to_str).unwrap_or(""); - std::fs::read_to_string(src_t).ok().and_then(|t| parse_file(&t, ext)) - } - .map(Arc::new); - if let Ok(mut m) = cache.lock() { - m.insert(src.to_string(), parsed.clone()); - } - parsed + file_cache::cached(FILES.get(), src, || { + let parsed = if src.contains('\n') { + parse_file(src, "") + } else { + let ext = std::path::Path::new(src_t).extension().and_then(std::ffi::OsStr::to_str).unwrap_or(""); + file_cache::read(src_t).ok().and_then(|t| parse_file(&t, ext)) + } + .map(Arc::new); + let bytes = match parsed.as_deref() { + Some(FileXform::Lut { lut, shaper }) => crate::utility::lut_bytes(lut) + .saturating_add(shaper.as_ref().map_or(0, |s| s.iter().map(Vec::len).sum::().saturating_mul(std::mem::size_of::<(f32, f32)>()))), + Some(FileXform::Cdl(c)) => c.len().saturating_mul(std::mem::size_of::<(String, Cdl)>()), + Some(FileXform::Matrix { .. }) | None => 0, + }; + (parsed, bytes) + }) } impl FileXform { diff --git a/crates/effects/src/ocio/tests.rs b/crates/effects/src/ocio/tests.rs index fe93dd25a..e17fd782a 100644 --- a/crates/effects/src/ocio/tests.rs +++ b/crates/effects/src/ocio/tests.rs @@ -396,3 +396,43 @@ fn color_stabilizer_samples_the_reference_at_the_points_reference_positions() { assert!((o(x) - (a + b * v(x))).abs() < 1e-3, "x {x}"); } } + +/// Writes `text` to `dir/name` with modification time `secs` (so an edit within the file system's +/// time resolution still moves the stamp), returning the path. +fn write_dated(dir: &std::path::Path, name: &str, text: &str, secs: u64) -> String { + let path = dir.join(name); + std::fs::write(&path, text).unwrap(); + let f = std::fs::File::options().write(true).open(&path).unwrap(); + f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap(); + path.to_string_lossy().into_owned() +} + +/// #3538: OCIO File Transform read a file once per process; an edited, created, repaired or +/// deleted file was never followed. +#[test] +fn an_ocio_transform_file_is_read_again_once_it_changes() { + const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; + const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; + let dir = std::env::temp_dir().join(format!("ec-fx-3538-file-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let at = |src: &str| load_file(src).map(|x| x.apply([0.5; 3], 1, false, "")); + let edited = write_dated(dir.as_path(), "edited.cube", BLACK, 1_000); + assert_eq!(at(&edited), Some([0.0; 3])); + write_dated(dir.as_path(), "edited.cube", WHITE, 2_000); + assert_eq!(at(&edited), Some([1.0; 3]), "an edited file, same size"); + let created = dir.as_path().join("created.cube").to_string_lossy().into_owned(); + assert_eq!(at(&created), None); + write_dated(dir.as_path(), "created.cube", WHITE, 1_000); + assert_eq!(at(&created), Some([1.0; 3]), "a file created after a failed load"); + let repaired = write_dated(dir.as_path(), "repaired.cube", "not a lut", 1_000); + assert_eq!(at(&repaired), None); + write_dated(dir.as_path(), "repaired.cube", WHITE, 2_000); + assert_eq!(at(&repaired), Some([1.0; 3]), "a repaired file"); + std::fs::remove_file(&repaired).unwrap(); + assert_eq!(at(&repaired), None, "a deleted file"); + // Inline text is its own content: the same text is the same transform. + let inline = load_file(BLACK).unwrap(); + assert!(Arc::ptr_eq(&inline, &load_file(BLACK).unwrap())); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/effects/src/ocio_config.rs b/crates/effects/src/ocio_config.rs index e31281ede..17e61d4b1 100644 --- a/crates/effects/src/ocio_config.rs +++ b/crates/effects/src/ocio_config.rs @@ -42,9 +42,10 @@ //! resolving named transforms [`MAX_NAMED_DEPTH`] levels down or past [`MAX_OPS`] steps //! (a config that refers to itself in a loop), so a hostile config can't exhaust the stack. -use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::Arc; + +use crate::file_cache::{self, Registered}; use super::ocio::{ACES_CG, ACES2065_1, Cdl, D65, FileXform, P3, REC709, REC2020, Space, Tf, load_file, matrix, sp}; @@ -882,13 +883,21 @@ fn resolve(src: &str, dir: &Path, search: &[String]) -> Option { if src.trim().is_empty() { return None; } + // (a candidate not there is noted: the config is read again once it appears) + let found = |c: PathBuf| { + let there = c.exists(); + if !there { + file_cache::note_missing(&c.to_string_lossy()); + } + there.then_some(c) + }; let p = Path::new(src); if p.is_absolute() { - return p.exists().then(|| p.to_path_buf()); + return found(p.to_path_buf()); } let mut dirs: Vec = search.iter().map(|s| dir.join(s)).collect(); dirs.push(dir.to_path_buf()); - dirs.into_iter().map(|d| d.join(src)).find(|c| c.exists()) + dirs.into_iter().map(|d| d.join(src)).find_map(found) } // ---------------------------------------------------------------- the config @@ -1338,33 +1347,34 @@ impl<'c> Build<'c> { } } -type ConfigCache = Mutex, String>>>; +/// [`load_config`]'s cache, by parameter text. +static CONFIGS: Registered, String>> = Registered::new(16, 64 << 20); + +/// The files the config cached for `src` was read from: the `.ocio` file, the files its +/// `FileTransform`s read and the places it looked for missing ones. +pub(crate) fn cached_files(src: &str) -> Option> { + file_cache::lock(CONFIGS.get()).files(src) +} /// Load (and cache) a config from a `.ocio` path or the config text itself; why not, when it -/// can't be read. +/// can't be read. The config file and the files its `FileTransform`s read are stamped (one +/// `metadata` call each) on every load, and the config is read again once one of them moved or a +/// missing one appeared (see [`crate::file_cache`]). pub fn load_config(src: &str) -> Result, String> { let t = src.trim(); if t.is_empty() { return Err("no config file chosen".into()); } - static CACHE: OnceLock = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - if let Ok(m) = cache.lock() - && let Some(v) = m.get(src) - { - return v.clone(); - } - let parsed = if src.contains('\n') { - Config::parse(src, Path::new(".")) - } else { + file_cache::cached(CONFIGS.get(), src, || { + if src.contains('\n') { + return (Config::parse(src, Path::new(".")).map(Arc::new), 0); + } let p = Path::new(t); - std::fs::read_to_string(p).map_err(|e| format!("{t}: {e}")).and_then(|text| Config::parse(&text, p.parent().unwrap_or(Path::new(".")))) - } - .map(Arc::new); - if let Ok(mut m) = cache.lock() { - m.insert(src.to_string(), parsed.clone()); - } - parsed + match file_cache::read(t) { + Ok(text) => (Config::parse(&text, p.parent().unwrap_or(Path::new("."))).map(Arc::new), text.len()), + Err(e) => (Err(format!("{t}: {e}")), 0), + } + }) } #[cfg(test)] diff --git a/crates/effects/src/ocio_config/tests.rs b/crates/effects/src/ocio_config/tests.rs index b616e6263..31cac56c2 100644 --- a/crates/effects/src/ocio_config/tests.rs +++ b/crates/effects/src/ocio_config/tests.rs @@ -410,3 +410,69 @@ fn builtin_styles() { fn rgb_white_xyz() -> [f64; 3] { [D65[0] / D65[1], 1.0, (1.0 - D65[0] - D65[1]) / D65[1]] } + +/// #3538: a custom `.ocio` config, and the LUTs it reads, were read once per process. +#[test] +fn an_ocio_config_and_its_luts_are_read_again_once_they_change() { + const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; + const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; + let dir = std::env::temp_dir().join(format!("ec-fx-3538-config-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(dir.as_path().join("luts")).unwrap(); + let write = |name: &str, text: &str, secs: u64| { + let path = dir.as_path().join(name); + std::fs::write(&path, text).unwrap(); + let f = std::fs::File::options().write(true).open(&path).unwrap(); + f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap(); + path.to_string_lossy().into_owned() + }; + let config = |space: &str| { + format!( + "ocio_profile_version: 2\nsearch_path: luts\nroles:\n scene_linear: lin\ncolorspaces:\n - !\n name: lin\n - !\n name: {space}\n to_reference: ! {{src: grade.cube, interpolation: linear}}\n - !\n name: later\n to_reference: ! {{src: later.cube, interpolation: linear}}\n" + ) + }; + let src = dir.as_path().join("config.ocio").to_string_lossy().into_owned(); + assert!(load_config(&src).is_err(), "no config yet"); + write("config.ocio", &config("graded"), 1_000); + write("luts/grade.cube", BLACK, 1_000); + let to_lin = |space: &str| { + let c = load_config(&src).unwrap(); + c.convert(c.space(space).unwrap(), c.space("lin").unwrap(), [0.5; 3]) + }; + assert_eq!(to_lin("graded"), [0.0; 3], "a config created after a failed load"); + write("luts/grade.cube", WHITE, 2_000); + assert_eq!(to_lin("graded"), [1.0; 3], "a LUT the config reads, edited"); + assert_eq!(to_lin("later"), [0.5; 3], "a LUT not there yet passes through"); + write("luts/later.cube", BLACK, 1_000); + assert_eq!(to_lin("later"), [0.0; 3], "a LUT the config reads, created"); + write("config.ocio", &config("regraded"), 2_000); + assert!(load_config(&src).unwrap().space("regraded").is_some(), "an edited config"); + std::fs::remove_file(&src).unwrap(); + assert!(load_config(&src).is_err(), "a deleted config"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A LUT a cached config read that changes is noticed without a render loading the config (the +/// interface's watcher), and the config's files name it (frame and layer cache keys hold them). +#[test] +fn check_lut_files_notices_a_configs_lut() { + let dir = std::env::temp_dir().join(format!("ec-fx-3538-check-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let lut = dir.join("watched.cube"); + std::fs::write(&lut, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap(); + let config = dir.join("config.ocio"); + std::fs::write(&config, "ocio_profile_version: 2\ncolorspaces:\n - !\n name: lin\n - !\n name: graded\n to_reference: ! {src: watched.cube}\n").unwrap(); + let src = config.to_string_lossy().into_owned(); + // A config not read yet is read: its files name its LUT from the first render on. + let files = crate::lut_files(&src); + assert!(files.contains(&lut.to_string_lossy().into_owned()), "{files:?}"); + assert!(load_config(&src).is_ok()); + let before = crate::check_lut_files(); + assert!(cached_files(&src).is_some(), "an unchanged config stays"); + std::fs::write(&lut, "LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n").unwrap(); + assert!(crate::check_lut_files() > before); + assert!(cached_files(&src).is_none(), "a config whose LUT changed is read again"); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/effects/src/stylize2.rs b/crates/effects/src/stylize2.rs index 247854352..a2de2c35e 100644 --- a/crates/effects/src/stylize2.rs +++ b/crates/effects/src/stylize2.rs @@ -612,7 +612,7 @@ pub fn specs() -> Vec { "ec.stylize.scatter", "Scatter", vec![ - p("amount", "Scatter Amount", num(0.0), slider(0.0, 127.0, 0.0, 127.0, 1)), + p("amount", "Scatter Amount", num(0.0), slider(0.0, 1000.0, 0.0, 127.0, 1)), p("grain", "Grain", Value::Enum(0), popup(&["Both", "Horizontal", "Vertical"])), p("randomizeEveryFrame", "Scatter Randomness", Value::Bool(false), ParamUi::Checkbox), ], diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index f0275eab1..afb430e1d 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -1,9 +1,9 @@ //! Utility effects: bounds growth, HDR inspection/compression, Cineon log conversion and colour //! lookup tables (.cube). -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::Arc; +use crate::file_cache::{self, Registered}; use effectcraft_color::luminance; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; @@ -330,28 +330,71 @@ impl Lut { } } -type LutCache = Mutex>>>; +/// At most this many parsed LUTs (files and inline texts) are kept, and at most +/// [`MAX_CACHED_BYTES`] of them; the least recently used go first. +const MAX_CACHED_LUTS: usize = 64; +const MAX_CACHED_BYTES: usize = 512 << 20; -/// Load (and cache) a LUT from inline `.cube` text or a file path. +/// [`load_lut`]'s cache, by parameter text. +static LUTS: Registered>> = Registered::new(MAX_CACHED_LUTS, MAX_CACHED_BYTES); + +/// The parameters (paths in the effect's group) of `effect` that name a file an effect reads +/// through a cache that follows it ([`load_lut`], the OCIO file transforms and configs). +pub fn lut_params(effect: &str) -> &'static [&'static str] { + match effect { + "ec.utility.applylut" => &["lut"], + "ec.color.lumetri" => &["basicCorrection/inputLutFile", "creative/lookFile"], + "ec.color.ociofile" => &["file"], + "ec.color.ociocolorspace" | "ec.color.ociodisplay" => &["configFile"], + _ => &[], + } +} + +/// The file a LUT parameter names; `None` for inline `.cube` text or an empty parameter. +pub fn lut_file(src: &str) -> Option<&str> { + // `.cube` text always spans lines (a size header, then data rows); a path never does, even one + // whose file name contains `LUT_` (#3454). Trimmed, so a trailing newline is still a path. + let path = src.trim(); + (!path.is_empty() && !path.contains('\n')).then_some(path) +} + +/// The files a [`lut_params`] parameter set to `src` reads: the ones its cached result was read +/// from (an OCIO config's also the LUTs it names, and the places it looked for missing ones; an +/// `.ocio` config not read yet is read), else the file it names. +pub fn lut_files(src: &str) -> Vec { + // A config not read yet is read now: the LUTs it names are its files from the first render. + if crate::ocio_config::cached_files(src).is_none() + && lut_file(src).is_some_and(|p| std::path::Path::new(p).extension().is_some_and(|e| e.eq_ignore_ascii_case("ocio"))) + { + let _ = crate::ocio_config::load_config(src); + } + crate::ocio_config::cached_files(src) + .or_else(|| crate::ocio::cached_files(src)) + .or_else(|| file_cache::lock(LUTS.get()).files(src)) + .unwrap_or_else(|| lut_file(src).map(str::to_string).into_iter().collect()) +} + +/// Load (and cache) a LUT from inline `.cube` text or a file path. A file is stamped (one +/// `metadata` call) on every load and read again once its size or modification time moved (see +/// [`crate::file_cache`]); inline text is its own content. pub fn load_lut(src: &str) -> Option> { if src.trim().is_empty() { return None; } - static CACHE: OnceLock = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - if let Ok(m) = cache.lock() - && let Some(v) = m.get(src) - { - return v.clone(); - } - // `.cube` text always spans lines (a size header, then data rows); a path never does, even one - // whose file name contains `LUT_` (#3454). Trimmed, as the path is, so a trailing newline is a path. - let inline = src.trim().contains('\n'); - let parsed = if inline { parse_cube(src) } else { std::fs::read_to_string(src.trim()).ok().and_then(|t| parse_cube(&t)) }.map(Arc::new); - if let Ok(mut m) = cache.lock() { - m.insert(src.to_string(), parsed.clone()); - } - parsed + file_cache::cached(LUTS.get(), src, || { + let lut = match lut_file(src) { + Some(path) => file_cache::read(path).ok().and_then(|t| parse_cube(&t)), + None => parse_cube(src), + } + .map(Arc::new); + let bytes = lut.as_ref().map_or(0, |l| lut_bytes(l)); + (lut, bytes) + }) +} + +/// The size of a LUT's tables. +pub(crate) fn lut_bytes(l: &Lut) -> usize { + l.d1.len().saturating_add(l.d3.len()).saturating_mul(std::mem::size_of::<[f32; 3]>()) } fn apply_lut(ctx: &EffectCtx, mut b: Buf) -> Buf { @@ -500,6 +543,100 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + /// #3493: a LUT file was read once per process; an edited or newly created file never loaded. + #[test] + fn a_lut_file_is_read_again_once_it_changes() { + const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; + const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; + let dir = std::env::temp_dir().join(format!("ec-fx-3493-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let write = |name: &str, text: &str, secs: u64| { + let path = dir.join(name); + std::fs::write(&path, text).unwrap(); + let f = std::fs::File::options().write(true).open(&path).unwrap(); + f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap(); + path.to_string_lossy().into_owned() + }; + let at = |src: &str| load_lut(src).map(|l| l.apply([0.5; 3])); + let edited = write("edited.cube", BLACK, 1_000); + assert_eq!(at(&edited), Some([0.0; 3])); + write("edited.cube", WHITE, 2_000); + assert_eq!(at(&edited), Some([1.0; 3]), "an edited file, same size"); + let created = dir.join("created.cube").to_string_lossy().into_owned(); + assert_eq!(at(&created), None); + write("created.cube", WHITE, 1_000); + assert_eq!(at(&created), Some([1.0; 3]), "a file created after a failed load"); + let repaired = write("repaired.cube", "not a lut", 1_000); + assert_eq!(at(&repaired), None); + write("repaired.cube", WHITE, 2_000); + assert_eq!(at(&repaired), Some([1.0; 3]), "a repaired file"); + std::fs::remove_file(&repaired).unwrap(); + assert_eq!(at(&repaired), None, "a deleted file"); + // Inline text is its own content: the same text is the same LUT. + let inline = load_lut(BLACK).unwrap(); + assert!(Arc::ptr_eq(&inline, &load_lut(BLACK).unwrap())); + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// A file that changed is noticed without a render loading it, and the generation that tells + /// frames made before it apart moves. + #[test] + fn check_lut_files_forgets_a_changed_file() { + let dir = std::env::temp_dir().join(format!("ec-fx-3493-check-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("grade.cube"); + std::fs::write(&path, identity_cube(2)).unwrap(); + let src = path.to_string_lossy().into_owned(); + assert!(load_lut(&src).is_some()); + let before = crate::check_lut_files(); + assert!(file_cache::lock(LUTS.get()).contains(&src), "an unchanged file stays"); + std::fs::write(&path, identity_cube(3)).unwrap(); + assert!(crate::check_lut_files() > before); + assert!(!file_cache::lock(LUTS.get()).contains(&src), "a changed file is read again"); + assert_eq!(load_lut(&src).map(|l| l.n3), Some(3)); + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// The cache keeps at most [`MAX_CACHED_LUTS`] LUTs, the least recently used going first. + #[test] + fn the_lut_cache_is_bounded() { + // (text no other test loads: a load elsewhere would make it recently used) + let oldest = format!("TITLE \"bounded first\"\n{}", identity_cube(2)); + let first = load_lut(&oldest).unwrap(); + for i in 0..MAX_CACHED_LUTS + 8 { + let text = format!("TITLE \"bounded {i}\"\n{}", identity_cube(2)); + assert!(load_lut(&text).is_some()); + assert!(file_cache::lock(LUTS.get()).len() <= MAX_CACHED_LUTS); + } + assert!(!Arc::ptr_eq(&first, &load_lut(&oldest).unwrap()), "the oldest was let go"); + let (bytes, sum, max) = file_cache::lock(LUTS.get()).bytes(); + assert_eq!(bytes, sum, "the bytes kept add up"); + assert!(bytes <= max); + } + + /// A LUT file whose LUT left the cache is still followed: its frames are dropped when it + /// changes, though no render loads it again first. + #[test] + fn a_file_whose_lut_left_the_cache_is_still_followed() { + let dir = std::env::temp_dir().join(format!("ec-fx-3493-evicted-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("old.cube"); + std::fs::write(&path, identity_cube(2)).unwrap(); + let src = path.to_string_lossy().into_owned(); + assert!(load_lut(&src).is_some()); + for i in 0..MAX_CACHED_LUTS + 8 { + assert!(load_lut(&format!("TITLE \"evict {i}\"\n{}", identity_cube(2))).is_some()); + } + assert!(!file_cache::lock(LUTS.get()).contains(&src), "its LUT left the cache"); + std::fs::write(&path, identity_cube(3)).unwrap(); + crate::check_lut_files(); + assert_eq!(file_cache::followed_stamp(&src), Some(file_cache::file_stamp(&src)), "the change was noticed"); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn one_d_lut_with_domain() { let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap(); diff --git a/crates/engine/src/analysis.rs b/crates/engine/src/analysis.rs index fa2b8b4ec..a1adb6dac 100644 --- a/crates/engine/src/analysis.rs +++ b/crates/engine/src/analysis.rs @@ -1,4 +1,5 @@ pub mod camera_track; +pub(crate) mod frames_key; pub mod mask_track; pub mod models; pub mod roto; diff --git a/crates/engine/src/analysis/camera_track.rs b/crates/engine/src/analysis/camera_track.rs index 29961f533..8209af543 100644 --- a/crates/engine/src/analysis/camera_track.rs +++ b/crates/engine/src/analysis/camera_track.rs @@ -26,9 +26,10 @@ use effectcraft_track::camtrack::linalg::{self, Similarity, V3}; use effectcraft_track::camtrack::{AnalyzeOpts, CameraSolve, CameraTracks, SolveSettings, Target, TrackAnalyzer}; use serde::Serialize; +use crate::analysis::frames_key; use crate::offload::JobKind; use crate::tracking::lock; -use crate::warp::{analysis_times, signature}; +use crate::warp::analysis_times; use crate::{Event, Session}; /// Live analysis progress (serde for agents / the control channel). @@ -81,7 +82,7 @@ pub struct CameraJob { pub comp: ItemId, pub layer: LayerId, pub effect: Uid, - /// The layer signature the tracks are made from, and the solve settings key. + /// What the tracks are made from (`tracks_key`), and the solve settings key. key: String, solve_key: String, } @@ -122,10 +123,21 @@ fn str_of(g: &PropGroup, m: &str) -> String { } } -/// What a tracker's tracks are made from: the layer's frames and Detailed Analysis. +/// What a tracker's tracks are made from: its input (the layer's frames under its masks and the +/// effects above it, `frames_key::analysis_key`) and Detailed Analysis. fn tracks_key(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> String { + tracks_key_of(frames_key::analysis_key(project, cid, l, g.uid), g) +} + +fn tracks_key_of(input: String, g: &PropGroup) -> String { let detailed = effectcraft_effects::warp_stab::param(&static_params(g), "advanced/detailedAnalysis").is_some_and(Value::as_bool); - format!("{}{}", signature(project, cid, l), if detailed { "+detailed" } else { "" }) + format!("{input}{}", if detailed { "+detailed" } else { "" }) +} + +/// Whether the tracker's saved tracks are made from its current input and settings, after an +/// edit from `before` to `project` ([`frames_key::analysis_key_matches`]). +fn tracks_match(before: &Project, project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> bool { + frames_key::analysis_key_matches(before, project, cid, l, g.uid, &str_of(g, TRACKS_KEY), |k| tracks_key_of(k, g)) } /// Parameters of an instance from static values (the tracker's settings are not animated). @@ -165,7 +177,7 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId, let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id)); for g in fx.groups().filter(|g| is_tracker(g)) { let tracked = !str_of(g, TRACKS).is_empty(); - if tracked && str_of(g, TRACKS_KEY) != tracks_key(after, *cid, l, g) { + if tracked && !tracks_match(before, after, *cid, l, g) { clears.push((*cid, l.id, g.uid, true)); todo.push((*cid, l.id, g.uid)); } else if tracked && str_of(g, SOLVE_KEY) != ct::solve_key(&ct::settings(&static_params(g))) { @@ -325,7 +337,7 @@ impl Session { let key = tracks_key(&self.project, comp, l, g); let settings = ct::settings(¶ms); let solve_key = ct::solve_key(&settings); - let tracks = ct::tracks(¶ms).filter(|_| str_of(g, TRACKS_KEY) == key); + let tracks = ct::tracks(¶ms).filter(|_| tracks_match(&self.project, &self.project, comp, l, g)); let n = times.len(); let work = CamWork { project: self.project.clone(), diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs new file mode 100644 index 000000000..abbafde67 --- /dev/null +++ b/crates/engine/src/analysis/frames_key.rs @@ -0,0 +1,777 @@ +//! What an analysis of a layer is made from. One writer keys the Warp Stabilizer and the 3D +//! Camera Tracker ([`analysis_key`]: frames, masks, effects above, a precomp's contents) and Roto +//! Brush / Object Matte ([`input_key`]: frames, masks, effects above). +//! +//! The key hashes a text this module writes field by field. The source item (footage and its +//! settings, solid), the Time Remap property, the masks and effect groups (their properties, +//! keyframes and values) and a precomp's comp and layers are destructured or matched in full, and +//! each variant is written as a fixed word (or, for an enum the project file names, its name +//! there): a new field or variant doesn't compile until it is decided here, written if it changes +//! the layer's frames, left out (with a reason) if it doesn't. Renaming a field or variant doesn't +//! change keys. Of the analysed layer itself, only the fields named in `layer_frames` and +//! [`analysis_key`] are read. The text leaves out observations (whether footage is available) and +//! data that never changes pixels (colour labels, UI hints, markers but a comp's timing markers; +//! only expressions read the others), so they never drop saved +//! analyses (#3534, #3536). +//! +//! Keys saved by 0.22–0.24 hashed derived `Debug` text instead. [`legacy`] still recognises +//! them, and a matching saved key is kept rather than rewritten: frozen Roto Brush mattes and +//! segmentations hash the saved key itself. + +use std::collections::HashSet; +use std::fmt::Write as _; + +use effectcraft_color::ColorSpace; +use effectcraft_keyframe::{Ease, FeatherPoint, Gradient, Interp, Keyframe, ShapePath, Value}; +use effectcraft_project::{ + AlphaMode, CineonSettings, CineonUnits, Comp, Expression, FeatherFalloff, FieldOrder, Footage, FootageKind, GroupKind, ItemId, ItemKind, Layer, + LayerSource, LightKind, Marker, MaskMode, MaskMotionBlur, Node, PrimitiveKind, Project, PropGroup, Property, Solid, SourceLayer, Switches, TrackMatte, Uid, + essential, styles::GlobalLight, +}; +use effectcraft_time::{FrameRate, Tick}; + +pub(crate) mod legacy; + +/// The version of the text, its first word: a later change to what it writes bumps it. +const VERSION: &str = "frames/1"; + +/// Property groups nest a few levels (effect ▸ group ▸ property); deeper trees are cut here. +const MAX_DEPTH: usize = 32; + +/// Precomps nest deeper than the renderer draws them (16) only in broken projects; deeper +/// contents are cut here. +const MAX_NESTING: usize = 32; + +fn fnv(s: &str) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in s.as_bytes() { + h ^= *b as u64; + h = h.wrapping_mul(0x0100_0000_01b3); + } + h +} + +fn hex(s: &str) -> String { + format!("{:016x}", fnv(s)) +} + +/// Which signature a key is made from: today's, or one an earlier release saved. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Era { + Current, + Legacy, +} + +/// The signature of `layer`'s frames: its source (and the source item), In/Out, start time, +/// stretch, Time Remap and the comp frame rate. Roto Brush Input Keys and [`analysis_key`] are +/// made from it. +pub(crate) fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String { + hex(&signature_text(p, comp, layer)) +} + +/// The text [`signature`] hashes. +pub(crate) fn signature_text(p: &Project, comp: ItemId, layer: &Layer) -> String { + let mut t = Text::new(); + t.word(VERSION); + t.layer_frames(p, comp, layer); + t.0 +} + +/// A Roto Brush's (or Object Matte's) Input Key: the layer's frames, its masks and the effects +/// above the instance `uid`. +pub(crate) fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String { + input_key_of(signature(p, comp, layer), layer, uid) +} + +/// An Input Key from a [`signature`]. +pub(crate) fn input_key_of(signature: String, layer: &Layer, uid: Uid) -> String { + let mut t = Text::new(); + t.word(VERSION); + t.word(&signature); + t.inputs_above(layer, uid, true); + hex(&t.0) +} + +/// The first word of an [`analysis_key`]'s text: a later change to what it writes bumps it. +const ANALYSIS_VERSION: &str = "analysis/1"; + +/// What a Warp Stabilizer or 3D Camera Tracker, the instance `uid` of `layer`, analyses: its +/// input, the layer's frames ([`signature`]) under its masks and the effects above it, and a +/// precomp's contents (#3535). The instance's own settings and the effects below it are not part +/// of it. +pub(crate) fn analysis_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String { + let mut t = Text::new(); + t.word(ANALYSIS_VERSION); + t.word(&signature(p, comp, layer)); + // The Effects switch turns the effects above on or off (it has none when it is the first). + if layer.effects().and_then(|fx| fx.groups().next()).is_some_and(|g| g.uid != uid) { + t.field("effectsSwitch", layer.switches.effects); + } + // While it is off the renderer skips the whole effect stack: the effects above draw nothing. + t.inputs_above(layer, uid, layer.switches.effects); + t.precomp(p, comp, layer); + hex(&t.0) +} + +/// Whether `saved`, the key saved with the analysis of instance `uid` of `layer` in `after`, is +/// for its current input ([`analysis_key`]). `key` makes the saved form from an input key or a +/// frames signature (the tracker adds its Detailed Analysis). +/// +/// Keys saved before #3535 hashed only the layer's frames ([`signature`], or a [`legacy`] one). +/// Such a key is taken to be for the input the layer had when it was opened, and stays valid +/// while each edit (from `before` to `after`) keeps the input: the first edit that changes it +/// clears the analysis. A layer or instance new in `after` (pasted, opened) keeps such a key +/// while its frames match. +pub(crate) fn analysis_key_matches( + before: &Project, + after: &Project, + comp: ItemId, + layer: &Layer, + uid: Uid, + saved: &str, + key: impl Fn(String) -> String, +) -> bool { + let now = analysis_key(after, comp, layer, uid); + if key(now.clone()) == saved { + return true; + } + let old = before.comp(comp).and_then(|c| c.layer(layer.id)).filter(|l| l.props.find_group(uid).is_some()); + match old { + Some(old) => key_matches(before, comp, old, saved, |s, _| key(s)) && analysis_key(before, comp, old, uid) == now, + None => key_matches(after, comp, layer, saved, |s, _| key(s)), + } +} + +/// Whether `saved`, a key saved with an analysis of `layer`, is for the layer's current frames. +/// `key` makes such a key from a signature of the given era. A key an earlier release saved for +/// the same frames matches too: keep it rather than rewrite it (analysing writes today's). +pub(crate) fn key_matches(p: &Project, comp: ItemId, layer: &Layer, saved: &str, key: impl Fn(String, Era) -> String) -> bool { + key(signature(p, comp, layer), Era::Current) == saved || legacy::signatures(p, comp, layer).into_iter().any(|s| key(s, Era::Legacy) == saved) +} + +/// The text a key is hashed from. Fields are `name=value;`; strings are quoted and escaped, so +/// no value can end its field early. +struct Text(String); + +impl Text { + fn new() -> Text { + Text(String::new()) + } + + fn word(&mut self, w: &str) { + self.0.push_str(w); + self.0.push(';'); + } + + fn field(&mut self, name: &str, value: impl std::fmt::Display) { + let _ = write!(self.0, "{name}={value};"); + } + + fn str(&mut self, name: &str, s: &str) { + let _ = write!(self.0, "{name}={s:?};"); + } + + fn num(&mut self, name: &str, v: f64) { + let _ = write!(self.0, "{name}={v:?};"); + } + + fn nums(&mut self, name: &str, v: &[f64]) { + let _ = write!(self.0, "{name}={v:?};"); + } + + fn floats(&mut self, name: &str, v: &[f32]) { + let _ = write!(self.0, "{name}={v:?};"); + } + + fn opt(&mut self, name: &str, v: Option<&T>, write: impl FnOnce(&mut Text, &T)) { + match v { + Some(v) => { + let _ = write!(self.0, "{name}{{"); + write(self, v); + self.0.push_str("};"); + } + None => self.word(&format!("{name}=none")), + } + } + + fn tick(&mut self, name: &str, t: Tick) { + self.field(name, t.0); + } + + fn rate(&mut self, name: &str, r: FrameRate) { + let FrameRate { num, den } = r; + let _ = write!(self.0, "{name}={num}/{den};"); + } + + /// What a layer's frames are made of, before its masks and effects. + fn layer_frames(&mut self, p: &Project, comp: ItemId, layer: &Layer) { + self.layer_source(&layer.source); + if let Some(item) = layer.source.item() { + match p.item(item).map(|i| &i.kind) { + Some(ItemKind::Footage(f)) => self.footage(f), + Some(ItemKind::Solid(s)) => self.solid(s), + // Its contents are in an [`analysis_key`], not here: Roto Brush keys are made from this. + Some(ItemKind::Comp(c)) => { + self.word("comp"); + self.field("w", c.width); + self.field("h", c.height); + self.rate("rate", c.frame_rate); + self.tick("duration", c.duration); + } + Some(ItemKind::Folder) | None => self.word("item=none"), + } + } + self.tick("in", layer.in_point); + self.tick("out", layer.out_point); + self.tick("start", layer.start_time); + self.num("stretch", layer.stretch); + self.opt("timeRemap", layer.props.get("timeRemap"), |t, pr| t.property(pr)); + self.opt("compRate", p.comp(comp).map(|c| &c.frame_rate), |t, r| t.rate("rate", *r)); + } + + fn layer_source(&mut self, s: &LayerSource) { + match s { + LayerSource::Footage { item } => self.field("footage", item.0), + LayerSource::Comp { item } => self.field("comp", item.0), + LayerSource::Solid { item } => self.field("solid", item.0), + LayerSource::Model { item } => self.field("model", item.0), + LayerSource::Text => self.word("text"), + LayerSource::Shape => self.word("shape"), + LayerSource::Null => self.word("null"), + LayerSource::Camera => self.word("camera"), + LayerSource::Light { kind } => self.field( + "light", + match kind { + LightKind::Parallel => "parallel", + LightKind::Spot => "spot", + LightKind::Point => "point", + LightKind::Ambient => "ambient", + LightKind::Environment => "environment", + }, + ), + LayerSource::Primitive { kind } => self.field( + "primitive", + match kind { + PrimitiveKind::Cube => "cube", + PrimitiveKind::Sphere => "sphere", + PrimitiveKind::Plane => "plane", + PrimitiveKind::Torus => "torus", + PrimitiveKind::Cone => "cone", + PrimitiveKind::Cylinder => "cylinder", + }, + ), + } + } + + fn solid(&mut self, s: &Solid) { + let Solid { color, width, height, pixel_aspect } = s; + self.word("solid"); + self.floats("color", color); + self.field("w", width); + self.field("h", height); + self.num("par", *pixel_aspect); + } + + fn footage(&mut self, f: &Footage) { + let Footage { + path, + kind, + width, + height, + pixel_aspect, + frame_rate, + native_rate, + duration, + has_video, + has_audio, + alpha, + premul_color, + loop_count, + codec, + // Whether the file is there is an observation (`footage.check`), not an edit: an + // offline file is the same footage, and its analyses stay valid (#3534). + missing: _, + sequence, + color_profile, + layer, + fields, + invert_alpha, + linear_light, + preserve_rgb, + cineon, + data, + page, + alphabetical, + start_timecode, + file_timecode, + // Markers annotate the footage; they never change its frames. + markers: _, + placed_page, + } = f; + self.word("footage"); + self.str("path", path); + self.field( + "kind", + match kind { + FootageKind::Video => "video", + FootageKind::Still => "still", + FootageKind::Sequence => "sequence", + FootageKind::Audio => "audio", + FootageKind::Model => "model", + FootageKind::Data => "data", + }, + ); + self.field("w", width); + self.field("h", height); + self.num("par", *pixel_aspect); + self.rate("rate", *frame_rate); + self.opt("nativeRate", native_rate.as_ref(), |t, r| t.rate("rate", *r)); + self.tick("duration", *duration); + self.field("video", has_video); + self.field("audio", has_audio); + self.field( + "alpha", + match alpha { + AlphaMode::Straight => "straight", + AlphaMode::Premultiplied => "premultiplied", + AlphaMode::Ignore => "ignore", + }, + ); + self.floats("matte", premul_color); + self.field("loop", loop_count); + self.str("codec", codec); + self.field("frames", sequence.len()); + for s in sequence { + self.str("file", s); + } + self.opt("profile", color_profile.as_ref(), |t, c| t.word(color_space(*c))); + self.opt("layer", layer.as_ref(), |t, l| t.source_layer(l)); + self.field( + "fields", + match fields { + FieldOrder::Off => "off", + FieldOrder::UpperFirst => "upper", + FieldOrder::LowerFirst => "lower", + }, + ); + self.field("invertAlpha", invert_alpha); + self.field("linearLight", linear_light); + self.field("preserveRgb", preserve_rgb); + self.cineon(cineon); + self.opt("data", data.as_ref(), |t, d| t.str("text", d)); + self.field("page", page); + self.field("alphabetical", alphabetical); + self.opt("startTimecode", start_timecode.as_ref(), |t, v| t.field("frame", v)); + self.opt("fileTimecode", file_timecode.as_ref(), |t, v| t.field("frame", v)); + self.field("placedPage", placed_page); + } + + fn source_layer(&mut self, l: &SourceLayer) { + let SourceLayer { index, name, layer_size, embedded, placed } = l; + self.field("index", index); + // The layer is found by its index; the name only labels it. + let _ = name; + self.field("layerSize", layer_size); + self.opt("embedded", embedded.as_ref(), |t, e| t.str("id", e)); + self.field("placed", placed); + } + + fn cineon(&mut self, c: &CineonSettings) { + let CineonSettings { log_conversion, converted_black, converted_white, black, white, gamma, rolloff, units } = c; + self.word("cineon"); + self.field("log", log_conversion); + self.floats("points", &[*converted_black, *converted_white, *black, *white, *gamma, *rolloff]); + self.field( + "units", + match units { + CineonUnits::TenBit => "10bit", + CineonUnits::EightBit => "8bit", + CineonUnits::Float => "float", + }, + ); + } + + /// The layer's masks and the effects above the instance `uid`: what the effect's input is + /// made of besides the layer's frames. + /// `effects`: whether to write the effects (a Roto Brush Input Key always does: frozen mattes + /// hash the saved key, so it keeps its text). + fn inputs_above(&mut self, layer: &Layer, uid: Uid, effects: bool) { + if let Some(m) = layer.masks() { + self.word("masks"); + self.group(m, 0); + } + if let Some(fx) = layer.effects() { + self.word("effects"); + for g in fx.groups().take_while(|g| effects && g.uid != uid) { + self.group(g, 0); + } + } + } + + /// A precomp layer's contents: its Essential Properties (they set values inside it) and what + /// its comp draws, nested precomps included. + fn precomp(&mut self, p: &Project, comp: ItemId, layer: &Layer) { + let LayerSource::Comp { item } = layer.source else { return }; + if let Some(e) = layer.props.group(essential::GROUP) { + self.word("essential"); + self.group(e, 0); + } + // A precomp never draws the comp it is in. + let mut seen = HashSet::from([comp]); + self.comp_contents(p, item, 0, &mut seen); + } + + /// What comp `id` draws. Each comp is written once per key, where it is first reached; a + /// later reference (a comp used twice, or a cycle) writes only its id, so the work is bounded + /// by the size of the project. + fn comp_contents(&mut self, p: &Project, id: ItemId, depth: usize, seen: &mut HashSet) { + self.field("contents", id.0); + // Before `seen`: a comp first reached too deep is written in full where it is shallower. + if depth >= MAX_NESTING { + self.word("tooDeep"); + return; + } + if !seen.insert(id) { + self.word("seen"); + return; + } + let Some(ItemKind::Comp(c)) = p.item(id).map(|i| &i.kind) else { + self.word("none"); + return; + }; + let Comp { + width, + height, + pixel_aspect, + frame_rate, + duration, + display_start, + background, + // The work area, Hide Shy, the viewer's Resolution and guides, and the poster frame + // only show the comp or say what to preview; they never change its frames. + work_area: _, + layers, + markers, + shutter_angle, + shutter_phase, + motion_blur_samples, + motion_blur_adaptive_limit, + renderer, + hide_shy: _, + enable_motion_blur, + enable_frame_blending, + draft_3d, + preserve_frame_rate, + preserve_resolution, + poster_time: _, + global_light, + guides: _, + essential, + resolution: _, + } = &**c; + self.field("w", width); + self.field("h", height); + self.num("par", *pixel_aspect); + self.rate("rate", *frame_rate); + self.tick("duration", *duration); + self.tick("displayStart", *display_start); + self.floats("background", background); + self.timing_markers(markers); + self.nums("shutter", &[*shutter_angle, *shutter_phase]); + self.field("samples", format_args!("{motion_blur_samples}/{motion_blur_adaptive_limit}")); + self.form("renderer", renderer); + self.field("motionBlur", enable_motion_blur); + self.field("frameBlending", enable_frame_blending); + self.field("draft3d", draft_3d); + self.field("preserveRate", preserve_frame_rate); + self.field("preserveResolution", preserve_resolution); + let GlobalLight { angle, altitude } = global_light; + self.property(angle); + self.property(altitude); + self.opt("essentialGraphics", essential.as_ref(), |t, e| t.form("definition", e)); + for l in layers.iter() { + self.nested_layer(p, l, depth, seen); + } + self.word("end"); + } + + /// A layer of a precomp. + fn nested_layer(&mut self, p: &Project, l: &Layer, depth: usize, seen: &mut HashSet) { + let Layer { + id, + name, + // Whether the name follows the Source Text changes nothing until the name changes. + name_follows_text: _, + source, + // Labels and comments only show the layer. + label: _, + comment: _, + start_time, + in_point, + out_point, + stretch, + switches, + blend_mode, + preserve_transparency, + track_matte, + parent, + // Layer markers annotate it (only expressions read them, as for the analysed layer); + // Lock Markers protects them. + markers: _, + markers_locked: _, + auto_orient, + environment, + environment_background, + props, + } = l; + self.field("layer", id.0); + // Expressions find layers by name (`thisComp.layer("Clip")`), as they find effects. + self.str("name", name); + self.layer_source(source); + if let Some(item) = source.item() { + match p.item(item).map(|i| &i.kind) { + Some(ItemKind::Footage(f)) => self.footage(f), + Some(ItemKind::Solid(s)) => self.solid(s), + Some(ItemKind::Comp(_)) => self.comp_contents(p, item, depth.saturating_add(1), seen), + Some(ItemKind::Folder) | None => self.word("item=none"), + } + } + self.tick("in", *in_point); + self.tick("out", *out_point); + self.tick("start", *start_time); + self.num("stretch", *stretch); + self.switches(switches); + self.form("blend", blend_mode); + self.field("preserveTransparency", preserve_transparency); + self.opt("matte", track_matte.as_ref(), |t, m| { + let TrackMatte { layer, kind } = m; + t.field("layer", layer.0); + t.form("kind", kind); + }); + self.opt("parent", parent.as_ref(), |t, id| t.field("id", id.0)); + self.form("autoOrient", auto_orient); + self.field("environment", format_args!("{environment}/{environment_background}")); + self.group(props, 0); + } + + fn switches(&mut self, s: &Switches) { + // Lock and Shy only protect and hide the layer in the Timeline. Audio is written (as are + // the Audio group and audio effects, in the property tree): a waveform effect can draw it. + let Switches { video, audio, solo, locked: _, shy: _, collapse, quality, sampling, effects, frame_blend, motion_blur, adjustment, three_d, guide } = s; + self.field("switches", format_args!("{video}/{audio}/{solo}/{collapse}/{effects}/{motion_blur}/{adjustment}/{three_d}/{guide}")); + self.form("quality", quality); + self.form("sampling", sampling); + self.form("frameBlend", frame_blend); + } + + /// A comp's protected markers with a duration: they set its timing (Responsive Design). + /// Other markers annotate it; only expressions read them. + fn timing_markers(&mut self, markers: &[Marker]) { + for m in markers.iter().filter(|m| m.protected && m.duration > Tick::ZERO) { + self.tick("timingMarker", m.time); + self.tick("for", m.duration); + } + } + + /// A value in its project-file form: enums the project file names, and the Essential Graphics + /// definition. + fn form(&mut self, name: &str, v: &T) { + self.str(name, &serde_json::to_string(v).unwrap_or_default()); + } + + fn group(&mut self, g: &PropGroup, depth: usize) { + // Expressions find effects and groups by name (`effect("Blur")`, `propertyGroup(1).name`). + // The uid and colour label never change pixels. + let PropGroup { uid: _, match_id, name, kind, enabled, label: _, children } = g; + if depth >= MAX_DEPTH { + self.word("tooDeep"); + return; + } + self.str("group", match_id); + self.str("name", name); + self.group_kind(kind); + self.field("enabled", enabled); + for c in children { + match c { + Node::Prop(p) => self.property(p), + Node::Group(g) => self.group(g, depth + 1), + } + } + self.word("end"); + } + + fn group_kind(&mut self, k: &GroupKind) { + match k { + GroupKind::Plain => self.word("plain"), + GroupKind::Indexed => self.word("indexed"), + // A mask's colour and lock only show it in the UI. + GroupKind::Mask { mode, inverted, color: _, locked: _, motion_blur, feather_falloff, roto_bezier } => { + self.field( + "mask", + match mode { + MaskMode::None => "none", + MaskMode::Add => "add", + MaskMode::Subtract => "subtract", + MaskMode::Intersect => "intersect", + MaskMode::Lighten => "lighten", + MaskMode::Darken => "darken", + MaskMode::Difference => "difference", + }, + ); + self.field("inverted", inverted); + self.field( + "motionBlur", + match motion_blur { + MaskMotionBlur::SameAsLayer => "layer", + MaskMotionBlur::On => "on", + MaskMotionBlur::Off => "off", + }, + ); + self.field( + "falloff", + match feather_falloff { + FeatherFalloff::Smooth => "smooth", + FeatherFalloff::Linear => "linear", + }, + ); + self.field("rotoBezier", roto_bezier); + } + GroupKind::Effect { effect } => self.str("effect", effect), + // A motion tracker's settings say how to track, not how to draw the layer. + GroupKind::Tracker { settings: _ } => self.word("tracker"), + GroupKind::Essential { overridden } => { + self.word("essential"); + for u in overridden { + self.field("overridden", u); + } + } + } + } + + fn property(&mut self, pr: &Property) { + // Expressions read the name (`thisProperty.name`) and seed `random`/`wiggle` with the + // uid: the uid is written for a property with an expression. UI hints and the 2D/3D-only + // and hold-only flags say where and how it can be edited, not what it evaluates to. + let Property { uid, match_id, name, value, keys, expr, ui: _, spatial, hold_only: _, three_d_only: _, two_d_only: _, shown_dims: _, static_only: _ } = + pr; + self.str("prop", match_id); + self.str("name", name); + if expr.is_some() { + self.field("uid", uid); + } + self.value(value); + self.field("spatial", spatial); + for k in keys { + self.keyframe(k); + } + self.opt("expr", expr.as_ref(), |t, e| { + let Expression { text, enabled } = e; + t.str("text", text); + t.field("enabled", enabled); + }); + } + + fn keyframe(&mut self, k: &Keyframe) { + // A key's colour label only shows it in the UI. + let Keyframe { + time, + value, + in_interp, + out_interp, + in_ease, + out_ease, + continuous, + auto_bezier, + spatial_in, + spatial_out, + spatial_auto, + spatial_continuous, + roving, + label: _, + muted, + } = k; + self.tick("key", *time); + self.value(value); + self.field("interp", format_args!("{}/{}", interp(*in_interp), interp(*out_interp))); + for (side, eases) in [("inEase", in_ease), ("outEase", out_ease)] { + for e in eases { + let Ease { speed, influence } = e; + self.nums(side, &[*speed, *influence]); + } + } + self.field("continuous", continuous); + self.field("autoBezier", auto_bezier); + self.nums("spatialIn", spatial_in); + self.nums("spatialOut", spatial_out); + self.field("spatialAuto", spatial_auto); + self.field("spatialContinuous", spatial_continuous); + self.field("roving", roving); + self.field("muted", muted); + } + + fn value(&mut self, v: &Value) { + match v { + Value::Scalar(x) => self.num("scalar", *x), + Value::Vec2(x) => self.nums("vec2", x), + Value::Vec3(x) => self.nums("vec3", x), + Value::Color(x) => self.nums("color", x), + Value::Bool(b) => self.field("bool", b), + Value::Enum(i) => self.field("enum", i), + Value::Path(p) => self.shape_path(p), + // A text document has dozens of fields and no place in what a key covers today (a + // text layer's Source Text is not under its masks or effects): its project-file form. + Value::Text(d) => self.str("text", &serde_json::to_string(d).unwrap_or_default()), + Value::Layer(l) => self.opt("layer", l.as_ref(), |t, id| t.field("id", id)), + Value::Gradient(g) => { + let Gradient { colors, opacities } = g; + self.word("gradient"); + for (at, c) in colors { + self.num("stop", *at); + self.floats("rgba", c); + } + for (at, o) in opacities { + self.num("stop", *at); + self.floats("opacity", &[*o]); + } + } + Value::Str(s) => self.str("str", s), + } + } + + fn shape_path(&mut self, p: &ShapePath) { + let ShapePath { vertices, in_tangents, out_tangents, closed, feather } = p; + self.word("path"); + for (name, points) in [("v", vertices), ("in", in_tangents), ("out", out_tangents)] { + for pt in points { + self.nums(name, pt); + } + } + self.field("closed", closed); + for f in feather { + let FeatherPoint { segment, t, radius, tension } = f; + self.field("featherSegment", segment); + self.nums("feather", &[*t, *radius, *tension]); + } + } +} + +fn interp(i: Interp) -> &'static str { + match i { + Interp::Linear => "linear", + Interp::Bezier => "bezier", + Interp::Hold => "hold", + } +} + +fn color_space(c: ColorSpace) -> &'static str { + match c { + ColorSpace::Srgb => "srgb", + ColorSpace::Rec709 => "rec709", + ColorSpace::Rec2020 => "rec2020", + ColorSpace::DisplayP3 => "p3", + ColorSpace::AcesCg => "acescg", + ColorSpace::Aces2065 => "aces2065", + ColorSpace::Rec2100Pq => "rec2100pq", + ColorSpace::Rec2100Hlg => "rec2100hlg", + } +} diff --git a/crates/engine/src/analysis/frames_key/legacy.rs b/crates/engine/src/analysis/frames_key/legacy.rs new file mode 100644 index 000000000..882c82d80 --- /dev/null +++ b/crates/engine/src/analysis/frames_key/legacy.rs @@ -0,0 +1,147 @@ +//! Signatures as 0.22–0.24 wrote them, to recognise the keys those releases saved. Nothing new is +//! keyed with them. They hash derived `Debug` text, so `tests::analysis_signature` pins keys +//! those releases saved: if a type change alters this text, write that part out here. + +use effectcraft_project::{Footage, ItemId, ItemKind, Layer, LayerSource, Project, Uid}; + +use super::fnv; + +/// The signatures a saved key of `layer` may have been made from. The footage's availability is +/// tried both ways: those releases hashed it, though it isn't part of the footage (#3534). Before +/// `Footage::placed_page` was added in 0.23, the footage text ended without that field. +pub(crate) fn signatures(p: &Project, comp: ItemId, layer: &Layer) -> Vec { + let src = match &layer.source { + LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) { + Some(ItemKind::Footage(f)) => { + let mut out = Vec::with_capacity(4); + for missing in [false, true] { + out.push(signature_with_source(p, comp, layer, &footage_text(f, missing, true))); + if matches!(layer.source, LayerSource::Footage { .. }) && !f.placed_page { + out.push(signature_with_source(p, comp, layer, &footage_text(f, missing, false))); + } + } + return out; + } + Some(ItemKind::Solid(s)) => format!("{s:?}"), + Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration), + _ => String::new(), + }, + _ => String::new(), + }; + vec![signature_with_source(p, comp, layer, &src)] +} + +/// A Roto Brush Input Key as 0.22–0.24 made it from a [`signatures`] entry. +pub(crate) fn input_key_of(mut s: String, layer: &Layer, uid: Uid) -> String { + if let Some(m) = layer.masks() { + s.push_str(&format!("{m:?}")); + } + if let Some(fx) = layer.effects() { + for g in fx.groups() { + if g.uid == uid { + break; + } + s.push_str(&format!("{g:?}")); + } + } + format!("{:016x}", fnv(&s)) +} + +/// A footage item as 0.23–0.24 wrote it into a signature (without `placed_page` before 0.23), +/// with `missing` in place of the item's. +pub(crate) fn footage_text(f: &Footage, missing: bool, placed_page: bool) -> String { + format!("{:?}", FootageText { f, missing, placed_page }) +} + +struct FootageText<'a> { + f: &'a Footage, + missing: bool, + placed_page: bool, +} + +impl std::fmt::Debug for FootageText<'_> { + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Every field is named so that a new one doesn't compile until it is decided here: a new + // field was never in these keys, so it stays out. + let Footage { + path, + kind, + width, + height, + pixel_aspect, + frame_rate, + native_rate, + duration, + has_video, + has_audio, + alpha, + premul_color, + loop_count, + codec, + missing: _, + sequence, + color_profile, + layer, + fields, + invert_alpha, + linear_light, + preserve_rgb, + cineon, + data, + page, + alphabetical, + start_timecode, + file_timecode, + markers, + placed_page, + } = self.f; + let mut d = out.debug_struct("Footage"); + d.field("path", path) + .field("kind", kind) + .field("width", width) + .field("height", height) + .field("pixel_aspect", pixel_aspect) + .field("frame_rate", frame_rate) + .field("native_rate", native_rate) + .field("duration", duration) + .field("has_video", has_video) + .field("has_audio", has_audio) + .field("alpha", alpha) + .field("premul_color", premul_color) + .field("loop_count", loop_count) + .field("codec", codec) + .field("missing", &self.missing) + .field("sequence", sequence) + .field("color_profile", color_profile) + .field("layer", layer) + .field("fields", fields) + .field("invert_alpha", invert_alpha) + .field("linear_light", linear_light) + .field("preserve_rgb", preserve_rgb) + .field("cineon", cineon) + .field("data", data) + .field("page", page) + .field("alphabetical", alphabetical) + .field("start_timecode", start_timecode) + .field("file_timecode", file_timecode) + .field("markers", markers); + if self.placed_page { + d.field("placed_page", placed_page); + } + d.finish() + } +} + +fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String { + let rate = p.comp(comp).map(|c| format!("{:?}", c.frame_rate)).unwrap_or_default(); + let s = format!( + "{:?}|{src}|{:?}|{:?}|{:?}|{}|{:?}|{rate}", + layer.source, + layer.in_point, + layer.out_point, + layer.start_time, + layer.stretch, + layer.props.get("timeRemap") + ); + format!("{:016x}", fnv(&s)) +} diff --git a/crates/engine/src/analysis/roto.rs b/crates/engine/src/analysis/roto.rs index 246c8899c..cb67005f8 100644 --- a/crates/engine/src/analysis/roto.rs +++ b/crates/engine/src/analysis/roto.rs @@ -8,8 +8,8 @@ //! (`Renderer::layer_input`, source → masks → the effects above it). `roto.freeze` runs the same //! pass and stores the final mattes in the effect (one undo step). `sync`, run after every //! edit, keeps each instance's hidden Input Key equal to a signature of what its frames are made -//! of (the layer's source and timing, its masks and the effects above it) and drops frozen -//! mattes made from other frames. +//! of (the layer's source and timing, its masks and the effects above it: `analysis::frames_key`), +//! and drops frozen mattes made from other frames. Footage going offline keeps them. //! //! Object Matte instances run through the same jobs (`objectMatte.propagate` / `.freeze`): the //! frames are [`om::job_frames`] around the reference frame, each segmented through @@ -31,6 +31,7 @@ use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpt use effectcraft_time::Tick; use serde::{Deserialize, Serialize}; +use crate::analysis::frames_key::{self, Era}; use crate::tracking::lock; use crate::{Event, Session}; @@ -207,40 +208,10 @@ fn set_str(g: &mut PropGroup, m: &str, v: String) { } } -fn fnv(s: &str) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in s.as_bytes() { - h ^= *b as u64; - h = h.wrapping_mul(0x0100_0000_01b3); - } - h -} - /// What the effect's input frames are made of: the layer's source and timing, its masks and the /// effects above the Roto Brush. pub fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String { - input_key_with_signature(crate::warp::signature(p, comp, layer), layer, uid) -} - -/// Recognize the input key serialized before 0.23 without re-keying its frozen matte. -fn input_key_before_placed_page(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> Option { - let signature = crate::warp::signature_before_placed_page(p, comp, layer)?; - Some(input_key_with_signature(signature, layer, uid)) -} - -fn input_key_with_signature(mut s: String, layer: &Layer, uid: Uid) -> String { - if let Some(m) = layer.masks() { - s.push_str(&format!("{m:?}")); - } - if let Some(fx) = layer.effects() { - for g in fx.groups() { - if g.uid == uid { - break; - } - s.push_str(&format!("{g:?}")); - } - } - format!("{:016x}", fnv(&s)) + frames_key::input_key(p, comp, layer, uid) } /// After an edit: refresh Input Keys (Roto Brush and Object Matte); frozen mattes made from @@ -258,7 +229,11 @@ pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerI let old = before.comp(*cid).and_then(|bc| bc.layer(l.id)).and_then(|ol| ol.props.find_group(g.uid)); let saved_key = str_of(g, INPUT_KEY); // Keep a matching old key: the frozen cache itself also hashes that key. - if saved_key != key && input_key_before_placed_page(after, *cid, l, g.uid).as_deref() != Some(saved_key.as_str()) { + let key_of = |s, era| match era { + Era::Current => frames_key::input_key_of(s, l, g.uid), + Era::Legacy => frames_key::legacy::input_key_of(s, l, g.uid), + }; + if !frames_key::key_matches(after, *cid, l, &saved_key, key_of) { set.push((*cid, l.id, g.uid, key)); todo.push((*cid, l.id, g.uid)); } else if old.is_none_or(|o| guard_of(o) != guard_of(g)) { diff --git a/crates/engine/src/analysis/warp.rs b/crates/engine/src/analysis/warp.rs index 0ab576d2c..45af7f172 100644 --- a/crates/engine/src/analysis/warp.rs +++ b/crates/engine/src/analysis/warp.rs @@ -6,10 +6,11 @@ //! analyzer (step 1 of 2, "Analyzing in background"); step 2 ("Stabilizing") derives the //! stabilization plan once to validate and cache the result. When the job finishes, the analysis is //! written into the effect's hidden Analysis parameter as one undo step, together with a key of -//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap). Edits that -//! change those clear the analysis (`invalidate`, run after every edit) and queue the effect -//! for re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses -//! automatically too). +//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap, its masks, the +//! effects above the Warp Stabilizer and a precomp's contents: `analysis::frames_key::analysis_key`, +//! shared with the 3D Camera Tracker). Edits that change those clear the analysis (`invalidate`, run after every edit) and queue the effect for +//! re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses +//! automatically too). Footage going offline is not such a change. use crate::offload::{JobKind, rate}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -17,13 +18,14 @@ use std::sync::{Arc, Mutex}; use effectcraft_effects::warp_stab::{self, ANALYSIS, ANALYSIS_KEY}; use effectcraft_keyframe::Value; -use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Project, PropGroup, Uid}; +use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, Project, PropGroup, Uid}; use effectcraft_raster::Image; use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer}; use effectcraft_time::Tick; use effectcraft_track::stabilize::{AnalyzeOpts, Analyzer, WarpAnalysis}; use serde::Serialize; +use crate::analysis::frames_key; use crate::tracking::lock; use crate::{Event, Session}; @@ -69,7 +71,7 @@ pub struct WarpJob { pub comp: ItemId, pub layer: LayerId, pub effect: Uid, - /// The layer signature the analysis is made from. + /// What the analysis is made from (`frames_key::analysis_key`). key: String, } @@ -98,54 +100,6 @@ pub(crate) struct WarpWork { pub times: Vec, } -fn fnv(s: &str) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in s.as_bytes() { - h ^= *b as u64; - h = h.wrapping_mul(0x0100_0000_01b3); - } - h -} - -/// What an analysis of `layer` depends on (its frames): source (and the footage item's -/// interpretation), In/Out, start time, stretch, Time Remap and the comp frame rate. -pub fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String { - let src = match &layer.source { - LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) { - Some(ItemKind::Footage(f)) => format!("{f:?}"), - Some(ItemKind::Solid(s)) => format!("{s:?}"), - Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration), - _ => String::new(), - }, - _ => String::new(), - }; - signature_with_source(p, comp, layer, &src) -} - -/// Before `Footage::placed_page` was added in 0.23, the persisted signature hashed the -/// same Debug representation without that last field. Only ordinary footage can match it. -pub(crate) fn signature_before_placed_page(p: &Project, comp: ItemId, layer: &Layer) -> Option { - let LayerSource::Footage { item } = &layer.source else { return None }; - let ItemKind::Footage(footage) = &p.item(*item)?.kind else { return None }; - let src = format!("{footage:?}"); - let old = src.strip_suffix(", placed_page: false }")?; - Some(signature_with_source(p, comp, layer, &format!("{old} }}"))) -} - -fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String { - let rate = p.comp(comp).map(|c| format!("{:?}", c.frame_rate)).unwrap_or_default(); - let s = format!( - "{:?}|{src}|{:?}|{:?}|{:?}|{}|{:?}|{rate}", - layer.source, - layer.in_point, - layer.out_point, - layer.start_time, - layer.stretch, - layer.props.get("timeRemap") - ); - format!("{:016x}", fnv(&s)) -} - fn is_warp(g: &PropGroup) -> bool { matches!(&g.kind, GroupKind::Effect { effect } if effect == warp_stab::ID) } @@ -169,11 +123,10 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId, if !fx.groups().any(is_warp) { continue; } - let sig = signature(after, *cid, l); let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id)); for g in fx.groups().filter(|g| is_warp(g)) { let analysed = !str_of(g, ANALYSIS).is_empty(); - if analysed && str_of(g, ANALYSIS_KEY) != sig { + if analysed && !frames_key::analysis_key_matches(before, after, *cid, l, g.uid, &str_of(g, ANALYSIS_KEY), |k| k) { clear.push((*cid, l.id, g.uid)); todo.push((*cid, l.id, g.uid)); } else if !analysed && old_layer.and_then(|ol| ol.props.find_group(g.uid)).is_none() { @@ -352,7 +305,7 @@ impl Session { detailed, times, }; - let key = signature(&self.project, comp, l); + let key = frames_key::analysis_key(&self.project, comp, l, effect); if !wait && self.offloads() { drop(work); self.offload_analysis(crate::offload::WorkerJob::Warp { comp, layer, effect })?; diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 09caa7cf4..fefe01950 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -49,7 +49,7 @@ mod nav_more; pub mod paint; pub mod panels_cmds; pub(crate) mod path_nulls; -mod paths; +pub(crate) mod paths; mod project_items; pub(crate) mod prop; mod prop_groups; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 890a9def1..d0158a286 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -319,15 +319,19 @@ impl Prober { return f.map(|footage| Probed { name, footage, ask_alpha: false, warning: None }).map_err(fail); } let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?; - let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?; - let mut warning = None; + // What the file's own import left out (a model's textures over the limits) is a warning too. + let (mut f, mut warning) = match src { + Source::File(_) => importer.probe_noting(path).map_err(fail)?, + _ => (crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?, None), + }; // Settings ▸ Import ▸ Report Missing Frames (numbered sequences). if f.kind == FootageKind::Sequence && !f.alphabetical && self.report_missing_frames && let Some(gaps) = crate::sequence::missing_report(&f.sequence) { - warning = Some(format!("{name}: {gaps} (the previous frame is held)")); + let gaps = format!("{name}: {gaps} (the previous frame is held)"); + warning = Some(warning.map_or(gaps.clone(), |w| format!("{w}; {gaps}"))); } // Settings ▸ Import ▸ Interpret Unlabeled Alpha As: images only (a 3D model renders its // own alpha, and audio and data have none). diff --git a/crates/engine/src/cmd/mask.rs b/crates/engine/src/cmd/mask.rs index 3e4a8a9e4..bfb4ea403 100644 --- a/crates/engine/src/cmd/mask.rs +++ b/crates/engine/src/cmd/mask.rs @@ -762,7 +762,7 @@ pub fn specs() -> Vec { cmd!("mask.new", "New Mask from Points", [], None, "{layer?, vertices: [[x,y]…], inTangents?, outTangents?, closed?, mode?}", has_layers, new_mask), 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.setClosed", "Closed", [], 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), diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs index 8364f67ec..2f1e1051b 100644 --- a/crates/engine/src/cmd/paths.rs +++ b/crates/engine/src/cmd/paths.rs @@ -12,6 +12,9 @@ use super::layer_menu::target_masks; use super::{CommandSpec, b_p, bad, f_p, has_comp, has_layers, layer_mut, layer_p, merge_p, str_p}; use crate::{EngineError, Result, Session, VertexRef, cmd}; +mod closed; +pub(crate) use closed::selected_paths_closed; + // ---------------------------------------------------------------- RotoBezier /// Automatic (RotoBezier) tangents: each vertex's tangents follow the line through its @@ -547,6 +550,7 @@ fn ungroup_shapes(s: &mut Session, p: &Value) -> Result { pub fn specs() -> Vec { vec![ + cmd!("path.toggleClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{}", closed::has_paths, closed::toggle_closed), cmd!("path.rotoBezier", "RotoBezier", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?, value?}", has_layers, roto_bezier), cmd!("path.convertToBezier", "Convert To Bezier Path", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?}", has_layers, convert_to_bezier), cmd!("path.groupShapes", "Group Shapes", ["Layer"], Some("Cmd+G"), "{layer?, items?: [uid]}", has_shape_items, group_shapes), diff --git a/crates/engine/src/cmd/paths/closed.rs b/crates/engine/src/cmd/paths/closed.rs new file mode 100644 index 000000000..90ff7e737 --- /dev/null +++ b/crates/engine/src/cmd/paths/closed.rs @@ -0,0 +1,130 @@ +//! The selection-aware Closed menu action. Explicit edits retain `mask.setClosed`'s API. + +use effectcraft_keyframe::Value as KV; +use effectcraft_project::{GroupKind, Layer, LayerId, Node, PropGroup, Uid}; +use effectcraft_time::Tick; +use serde_json::{Value, json}; + +use super::super::{bad, layer_mut}; +use crate::{EngineError, Result, Session, VertexRef}; + +const MAX_DEPTH: usize = 128; + +struct Target { + layer: LayerId, + route: Vec, + closed: bool, + editable: bool, +} + +struct Selection<'a> { + vertices: &'a [VertexRef], + props: &'a [(LayerId, Uid)], + time: Tick, +} + +/// A route uses checked child access and never recurses through an input-controlled tree. +fn group_at_mut<'a>(mut group: &'a mut PropGroup, route: &[usize]) -> Option<&'a mut PropGroup> { + for &index in route { + group = group.children.get_mut(index)?.as_group_mut()?; + } + Some(group) +} + +/// The selected paths on the selected layers, else every path of those layers (as the other +/// Mask and Shape Path commands do). Locked layers and masks count as matches, so selecting one +/// never falls back to its siblings, and are then left out. +fn targets(s: &Session) -> Result> { + let comp = s.active_comp().ok_or(EngineError::NoComp)?; + let selection = Selection { vertices: &s.state.selected_vertices, props: &s.state.selected_props, time: s.time() }; + let mut targets = Vec::new(); + for whole_layers in [false, true] { + // Only selected layers: navigation and insertion can retain point/property selections + // on other layers, and every match below is per layer. + for layer in comp.layers.iter().filter(|l| s.state.selected_layers.contains(&l.id)) { + collect(&selection, layer, &layer.props, &mut Vec::new(), whole_layers, layer.switches.locked, &mut targets)?; + } + if !targets.is_empty() { + break; + } + } + targets.retain(|target| target.editable); + if targets.is_empty() { + return Err(bad("path.toggleClosed", "select an unlocked mask or Bezier shape path")); + } + Ok(targets) +} + +fn collect( + selection: &Selection, + layer: &Layer, + group: &PropGroup, + route: &mut Vec, + inherited: bool, + locked: bool, + targets: &mut Vec, +) -> Result<()> { + if route.len() > MAX_DEPTH { + return Err(bad("path.toggleClosed", "path group nesting exceeds 128 levels")); + } + let locked = locked || matches!(group.kind, GroupKind::Mask { locked: true, .. }); + let selected = inherited || selection.props.contains(&(layer.id, group.uid)); + if super::super::mask::is_path_group(group) + && let Some(prop) = group.get("path") + && let KV::Path(path) = prop.value_at(layer.layer_time(selection.time)) + { + // Selecting any of a path group's properties (Mask Path, Feather, Opacity…) or its points + // selects the path. + let selected = selected + || group.children.iter().any(|c| matches!(c, Node::Prop(p) if selection.props.contains(&(layer.id, p.uid)))) + || selection.vertices.iter().any(|v| v.layer == layer.id && v.mask == group.uid && v.index < path.vertices.len()); + if selected { + targets.push(Target { layer: layer.id, route: route.clone(), closed: path.closed, editable: !locked }); + } + return Ok(()); + } + for (index, child) in group.children.iter().enumerate() { + let Some(child) = child.as_group() else { continue }; + route.push(index); + collect(selection, layer, child, route, selected, locked, targets)?; + route.pop(); + } + Ok(()) +} + +pub(crate) fn selected_paths_closed(s: &Session) -> Option { + targets(s).ok().map(|targets| targets.iter().all(|target| target.closed)) +} + +pub(super) fn has_paths(s: &Session) -> std::result::Result<(), String> { + targets(s).map(|_| ()).map_err(|error| error.to_string()) +} + +pub(super) fn toggle_closed(s: &mut Session, _: &Value) -> Result { + let targets = targets(s)?; + let closed = !targets.iter().all(|target| target.closed); + let cid = s.active_comp_id().ok_or(EngineError::NoComp)?; + let time = s.time(); + s.edit("Closed", None, |project, _| { + for target in &targets { + let layer = layer_mut(project, cid, target.layer)?; + let time = layer.layer_time(time); + let group = group_at_mut(&mut layer.props, &target.route).ok_or_else(|| bad("path.toggleClosed", "the selected path no longer exists"))?; + let roto = super::is_roto(group); + let prop = group.get_mut("path").ok_or_else(|| bad("path.toggleClosed", "the selected group has no path"))?; + let KV::Path(mut path) = prop.value_at(time) else { return Err(bad("path.toggleClosed", "the selected value is not a path")) }; + if path.closed == closed { + continue; + } + // As `mask.setClosed`: a path read from a file may have fewer tangents than vertices (#1250). + path.fit_tangents(); + path.closed = closed; + if roto { + super::roto_smooth(&mut path); + } + prop.set_value_at(time, KV::Path(path)); + } + Ok(()) + })?; + Ok(json!({"paths": targets.len(), "closed": closed})) +} diff --git a/crates/engine/src/cmd/prop.rs b/crates/engine/src/cmd/prop.rs index b23e73575..761a295b2 100644 --- a/crates/engine/src/cmd/prop.rs +++ b/crates/engine/src/cmd/prop.rs @@ -1370,6 +1370,13 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result { if sel.is_empty() { return Err(bad(CMD, "no `path` given and no selected property has an expression")); } + // Every layer is checked before the first is converted: a refusal leaves them all as they were. + let step = comp.frame_duration().0; + for (lid, _) in &sel { + if let Some(l) = comp.layer(*lid) { + check_convertible(step, l)?; + } + } let mut n = 0; for (lid, uid) in sel { n += convert_one_expr(s, cid, lid, uid)?.as_u64().unwrap_or(0); @@ -1380,14 +1387,36 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result { convert_one_expr(s, cid, lid, uid) } +/// Most keyframes Convert Expression to Keyframes makes: 2^20, 4.8 hours at 60 fps (After Effects +/// compositions run to 3 hours, 648,000 frames at 60 fps). +const MAX_CONVERTED_KEYS: u64 = 1 << 20; +const _: () = assert!(MAX_CONVERTED_KEYS >= 3 * 3600 * 60); + +/// One evaluation and one key per frame of the layer: its In and Out points and the composition's +/// frame duration are saved data, so the step must advance and the count (a partial last frame +/// rounded up, as the loop steps, in 128 bits) is checked before any key is made. +fn check_convertible(step: i64, layer: &Layer) -> Result<()> { + const CMD: &str = "prop.convertExpressionToKeyframes"; + if step <= 0 { + return Err(bad(CMD, "the composition's frame duration is not positive")); + } + let (step, span) = (i128::from(step), i128::from(layer.out_point.0) - i128::from(layer.in_point.0)); + let frames = if span > 0 { (span + step - 1) / step } else { 0 }; + if frames > i128::from(MAX_CONVERTED_KEYS) { + return Err(bad(CMD, format!("the layer spans {frames} frames; at most {MAX_CONVERTED_KEYS} are converted"))); + } + Ok(()) +} + /// Replaces the expression on one property with keyframes sampled from its evaluated values. /// Returns the number of properties converted. fn convert_one_expr(s: &mut Session, cid: ItemId, lid: LayerId, uid: Uid) -> Result { let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); let layer = comp.layer(lid).ok_or(EngineError::NoComp)?.clone(); let pr = layer.props.find(uid).ok_or_else(|| bad("prop.convertExpressionToKeyframes", "no property"))?.clone(); - let mut keys = vec![]; let fd = comp.frame_duration(); + check_convertible(fd.0, &layer)?; + let mut keys = vec![]; let mut t = layer.in_point; while t < layer.out_point { let ctx = effectcraft_render::EvalCtx { diff --git a/crates/engine/src/footage.rs b/crates/engine/src/footage.rs index b921dd128..d64afcaf7 100644 --- a/crates/engine/src/footage.rs +++ b/crates/engine/src/footage.rs @@ -1,6 +1,7 @@ pub mod doc_path; pub mod footage_check; pub mod footage_reload; +pub mod lut_reload; pub mod media_browser; pub mod media_cache; pub mod sequence; diff --git a/crates/engine/src/footage/lut_reload.rs b/crates/engine/src/footage/lut_reload.rs new file mode 100644 index 000000000..54211eac0 --- /dev/null +++ b/crates/engine/src/footage/lut_reload.rs @@ -0,0 +1,90 @@ +//! LUT files that change on disk (#3493). +//! +//! A render follows a LUT file by itself: [`effectcraft_effects::load_lut`] stamps the file and +//! reads it again once it changed, and a layer's cache key holds the stamp. What the desktop app +//! keeps of earlier renders, the frames of its viewer and RAM preview, is dropped when +//! [`effectcraft_effects::lut_generation`] moves. The [`Watcher`] looks at the LUT files in use +//! every two seconds, so an edit shows without anything rendering first, and wakes the interface +//! only when one changed. + +use std::sync::mpsc::{RecvTimeoutError, SyncSender}; +use std::time::Duration; + +/// Moves each time a LUT file in use was found changed on disk: frames rendered before may show +/// the old LUT ([`effectcraft_effects::lut_generation`]). +pub fn generation() -> u64 { + effectcraft_effects::lut_generation() +} + +/// Stamp the LUT files in use now ([`effectcraft_effects::check_lut_files`]): the ones that +/// changed are read again by the next render. Returns [`generation`]. +pub fn check() -> u64 { + effectcraft_effects::check_lut_files() +} + +/// How often the LUT files in use are stamped. +pub const INTERVAL: Duration = Duration::from_secs(2); + +/// A worker thread that stamps the LUT files in use ([`effectcraft_effects::check_lut_files`]) +/// and runs `wake` when one changed. Dropping the watcher ends the thread. +pub struct Watcher { + _stop: SyncSender<()>, +} + +impl Watcher { + /// Start the worker. `None` where there are no threads (the web app, whose LUTs don't come + /// from files) or one couldn't be started. + pub fn start(wake: impl Fn() + Send + 'static) -> Option { + Self::start_with(wake, INTERVAL) + } + + /// [`Watcher::start`] stamping every `every` (tests). + pub fn start_with(wake: impl Fn() + Send + 'static, every: Duration) -> Option { + if cfg!(target_arch = "wasm32") { + return None; + } + let (tx, rx) = std::sync::mpsc::sync_channel::<()>(1); + std::thread::Builder::new() + .name("lut-watch".into()) + .spawn(move || { + let mut seen = effectcraft_effects::lut_generation(); + // (ends once the watcher, the only sender, is dropped) + while let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(every) { + let now = check(); + if now != seen { + seen = now; + wake(); + } + } + }) + .ok()?; + Some(Watcher { _stop: tx }) + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + /// A LUT file edited on disk wakes the interface without a render loading it. + #[test] + fn an_edited_lut_file_wakes_the_interface() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("watched.cube"); + std::fs::write(&path, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap(); + let src = path.to_string_lossy().into_owned(); + assert!(effectcraft_effects::load_lut(&src).is_some()); + let before = effectcraft_effects::lut_generation(); + let (tx, rx) = std::sync::mpsc::channel(); + let _watcher = Watcher::start_with( + move || { + let _ = tx.send(()); + }, + Duration::from_millis(10), + ) + .unwrap(); + std::fs::write(&path, "LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n").unwrap(); + rx.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(effectcraft_effects::lut_generation() > before); + } +} diff --git a/crates/engine/src/interchange/keyframe_text_effects.rs b/crates/engine/src/interchange/keyframe_text_effects.rs index 83f5b6c20..7b0658f61 100644 --- a/crates/engine/src/interchange/keyframe_text_effects.rs +++ b/crates/engine/src/interchange/keyframe_text_effects.rs @@ -273,6 +273,7 @@ pub(crate) const UNITS: &[(&str, &str, &str)] = &[ ("ec.distort.wavewarp", "width", "percent"), ("ec.distort.wavewarp", "speed", "pixels"), ("ec.generate.fourcolor", "blend", "percent"), + ("ec.generate.fourcolor", "jitter", "percent"), ("ec.generate.advancedlightning", "coreSettings/coreRadius", ""), ("ec.generate.advancedlightning", "glowSettings/glowRadius", "percent"), ("ec.generate.advancedlightning", "alphaObstacle", "pixels"), @@ -317,6 +318,15 @@ pub(crate) const UNITS: &[(&str, &str, &str)] = &[ ("ec.matte.rotobrush", "refineEdgeMatte/shiftEdge", "percent"), ("ec.matte.rotobrush", "refineEdgeMatte/decontamination/increaseDecontaminationRadius", ""), ("ec.matte.simplechoker", "chokeMatte", "pixels"), + // Their ranges were 0..100 (#3483, #3484). + ("ec.noise.noisehls", "hue", "percent"), + ("ec.noise.noisehls", "lightness", "percent"), + ("ec.noise.noisehls", "saturation", "percent"), + ("ec.noise.noisehls", "grainSize", ""), + ("ec.noise.noisehlsauto", "hue", "percent"), + ("ec.noise.noisehlsauto", "lightness", "percent"), + ("ec.noise.noisehlsauto", "saturation", "percent"), + ("ec.noise.noisehlsauto", "grainSize", ""), ("ec.noise.fractal", "transform/scale", "percent"), ("ec.noise.fractal", "transform/scaleWidth", "percent"), ("ec.noise.fractal", "transform/scaleHeight", "percent"), diff --git a/crates/engine/src/interchange/vector.rs b/crates/engine/src/interchange/vector.rs index 569e8e5bc..64ef00253 100644 --- a/crates/engine/src/interchange/vector.rs +++ b/crates/engine/src/interchange/vector.rs @@ -8,6 +8,7 @@ use effectcraft_project::{Comp, ItemId, Layer, LayerSource, MaskMode, Project, P use effectcraft_svg::{Affine, Doc, Geom, GradientKind, Node, Paint}; use kurbo::{BezPath, Point}; +/// Convert a kurbo path into shape path property groups. fn shape_paths(ids: &mut Ids, path: &BezPath) -> Vec { effectcraft_path::from_kurbo(path) .into_iter() @@ -20,6 +21,7 @@ fn shape_paths(ids: &mut Ids, path: &BezPath) -> Vec { .collect() } +/// Uniform scale factor of a transform (square root of its determinant magnitude). fn det_scale(m: Affine) -> f64 { let c = m.as_coeffs(); (c[0] * c[3] - c[1] * c[2]).abs().sqrt() @@ -31,6 +33,7 @@ fn axis_aligned(m: Affine) -> Option<(f64, f64, f64, f64)> { (c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && c[0] > 0.0 && c[3] > 0.0).then_some((c[0], c[3], c[4], c[5])) } +/// Convert an SVG gradient into the engine's gradient value. fn gradient_value(g: &effectcraft_svg::Gradient) -> Gradient { Gradient { colors: g.stops.iter().map(|(o, c)| (*o, [c[0] as f32, c[1] as f32, c[2] as f32, 1.0])).collect(), @@ -52,6 +55,7 @@ fn gradient_points(g: &effectcraft_svg::Gradient, m: Affine, bbox: kurbo::Rect) } } +/// Convert one SVG shape under transform `m` into shape-layer items. fn shape_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine) -> Vec { use kurbo::Shape as _; let mut items = vec![]; @@ -72,48 +76,60 @@ fn shape_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine) -> Vec build::shape_stroke(ids, [c[0], c[1], c[2], 1.0], width), + let paint = match &st.paint { + Paint::Color(c) => Some(build::shape_stroke(ids, [c[0], c[1], c[2], 1.0], width)), Paint::Gradient(gr) => { let (radial, a, b) = gradient_points(gr, m, bbox); - build::shape_gradient_stroke(ids, radial, a, b, gradient_value(gr), width) + Some(build::shape_gradient_stroke(ids, radial, a, b, gradient_value(gr), width)) } + // Editable shape layers do not yet have a pattern paint operator. Keep the geometry + // and any retained fallback as solid paint; SVG footage retains the rasterised pattern. + Paint::Pattern(pattern) => pattern.fallback.map(|c| build::shape_stroke(ids, [c[0], c[1], c[2], c[3]], width)), }; - set(&mut g, "opacity", Value::Scalar(st.opacity * 100.0)); - set(&mut g, "cap", Value::Enum(st.cap as u32)); - set(&mut g, "join", Value::Enum(st.join as u32)); - set(&mut g, "miter", Value::Scalar(st.miter)); - if let Some((d, off)) = &st.dash - && let Some(dg) = g.sub_mut("dashes") - { - let k = det_scale(m); - set(dg, "dash", Value::Scalar(d.first().copied().unwrap_or(0.0) * k)); - set(dg, "gap", Value::Scalar(d.get(1).or(d.first()).copied().unwrap_or(0.0) * k)); - set(dg, "offset", Value::Scalar(off * k)); + if let Some(mut g) = paint { + set(&mut g, "opacity", Value::Scalar(st.opacity * 100.0)); + set(&mut g, "cap", Value::Enum(st.cap as u32)); + set(&mut g, "join", Value::Enum(st.join as u32)); + set(&mut g, "miter", Value::Scalar(st.miter)); + if let Some((d, off)) = &st.dash + && let Some(dg) = g.sub_mut("dashes") + { + let k = det_scale(m); + set(dg, "dash", Value::Scalar(d.first().copied().unwrap_or(0.0) * k)); + set(dg, "gap", Value::Scalar(d.get(1).or(d.first()).copied().unwrap_or(0.0) * k)); + set(dg, "offset", Value::Scalar(off * k)); + } + items.push(g); } - items.push(g); } if let Some(f) = &s.fill { - let mut g = match f { - Paint::Color(c) => build::shape_fill(ids, [c[0], c[1], c[2], 1.0]), + let paint = match f { + Paint::Color(c) => Some(build::shape_fill(ids, [c[0], c[1], c[2], 1.0])), Paint::Gradient(gr) => { let (radial, a, b) = gradient_points(gr, m, bbox); - build::shape_gradient_fill(ids, radial, a, b, gradient_value(gr)) + Some(build::shape_gradient_fill(ids, radial, a, b, gradient_value(gr))) } + // Pattern artwork is preserved in rasterised SVG footage; editable shapes keep only + // any retained fallback as solid paint. + Paint::Pattern(pattern) => pattern.fallback.map(|c| build::shape_fill(ids, [c[0], c[1], c[2], c[3]])), }; - set(&mut g, "opacity", Value::Scalar(s.fill_opacity * 100.0)); - set(&mut g, "rule", Value::Enum(u32::from(s.fill_rule == effectcraft_svg::FillRule::EvenOdd))); - items.push(g); + if let Some(mut g) = paint { + set(&mut g, "opacity", Value::Scalar(s.fill_opacity * 100.0)); + set(&mut g, "rule", Value::Enum(u32::from(s.fill_rule == effectcraft_svg::FillRule::EvenOdd))); + items.push(g); + } } items } +/// Set a child property's value if present. fn set(g: &mut PropGroup, k: &str, v: Value) { if let Some(p) = g.get_mut(k) { p.value = v; } } +/// Wrap items in a named shape group with the given opacity (0..1). fn group(ids: &mut Ids, name: &str, items: Vec, opacity: f64) -> PropGroup { let mut g = build::shape_group(ids, name, items); if let Some(p) = g.prop_mut("transform/opacity") { @@ -165,6 +181,7 @@ fn clipped_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine, clips: &[ /// [`shapes_from_vector`]). Images are skipped (Layer ▸ Create makes them footage layers, see /// [`split_at_images`]); soft masks are not converted. pub fn svg_contents(ids: &mut Ids, doc: &Doc) -> Vec { + /// Convert nodes to property groups, applying transform `m` and clip paths. fn walk(ids: &mut Ids, nodes: &[Node], m: Affine, clips: &[BezPath]) -> Vec { let mut out = vec![]; for n in nodes.iter().rev() { @@ -406,6 +423,7 @@ fn copy_transform(proj: &mut Project, src: &Layer, dst: &mut Layer) { } } +/// Copy timing and parenting from `src` to `dst`. fn like_source(dst: &mut Layer, src: &Layer) { dst.start_time = src.start_time; dst.in_point = src.in_point; @@ -418,13 +436,17 @@ fn like_source(dst: &mut Layer, src: &Layer) { /// A raster image of a vector document (Create Shapes from Vector Layer makes it a footage /// layer: shape layers have no images). pub struct VectorImage { + /// Image name. pub name: String, + /// Pixel width. pub width: u32, + /// Pixel height. pub height: u32, /// Straight RGBA8. pub rgba: std::sync::Arc>, /// Image pixels → document pixels. pub transform: Affine, + /// Opacity, 0..1. pub opacity: f64, /// Inside a clipping group or under a soft mask (not carried over). pub clipped: bool, @@ -432,6 +454,7 @@ pub struct VectorImage { /// The document's images, bottom first, and how many soft-masked groups it has. pub fn vector_images(doc: &Doc) -> (Vec, usize) { + /// Collect images from a group tree, counting soft-masked groups. fn walk(g: &effectcraft_svg::Group, m: Affine, opacity: f64, clipped: bool, out: &mut Vec, masks: &mut usize) { let m = m * g.transform; let opacity = opacity * g.opacity; @@ -467,6 +490,7 @@ pub fn vector_images(doc: &Doc) -> (Vec, usize) { /// layers and image footage layers can stack in the document's order. One more segment than /// images. pub fn split_at_images(doc: &Doc) -> Vec { + /// Count the images in a group tree. fn count(g: &effectcraft_svg::Group) -> usize { g.children .iter() diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f8edfbe08..0b7608756 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -61,6 +61,7 @@ pub use effectcraft_track as track; pub use footage::doc_path; pub use footage::footage_check; pub use footage::footage_reload; +pub use footage::lut_reload; pub use footage::media_browser; pub use footage::media_cache; pub use footage::sequence; diff --git a/crates/engine/src/menus.rs b/crates/engine/src/menus.rs index f0ef8bd57..1301940e6 100644 --- a/crates/engine/src/menus.rs +++ b/crates/engine/src/menus.rs @@ -320,6 +320,7 @@ pub fn checked(s: &Session, command: &str, params: &Value) -> Option { let layer = s.state.selected_layers.first().and_then(|l| comp.layer(*l)); let pstr = |k: &str| params.get(k).and_then(Value::as_str); match command { + "path.toggleClosed" => crate::cmd::paths::selected_paths_closed(s), "layer.setBlendMode" => { let want = effectcraft_color::BlendMode::from_name(pstr("mode")?)?; Some(layer?.blend_mode == want) @@ -829,7 +830,7 @@ Layer Hide Locked Masks | layer.mask.hideLocked Mask and Shape Path RotoBezier | path.rotoBezier - Closed | mask.setClosed + Closed | path.toggleClosed Convert To Bezier Path | path.convertToBezier Set First Vertex | path.setFirstVertex Free Transform Points | path.freeTransform diff --git a/crates/engine/src/menus/tests.rs b/crates/engine/src/menus/tests.rs index 8de3cc6dc..740610971 100644 --- a/crates/engine/src/menus/tests.rs +++ b/crates/engine/src/menus/tests.rs @@ -159,6 +159,44 @@ fn checked_reflects_layer_state() { assert_eq!(checked(&s, "file.save", &serde_json::json!({})), None); } +#[test] +fn closed_menu_opens_and_recloses_a_manual_shape() { + use serde_json::json; + let mut s = crate::Session::default(); + s.execute("comp.new", json!({"width": 320, "height": 180})).unwrap(); + let r = s + .execute( + "shape.newPath", + json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true, + "inTangents": [[0, -12], [-8, 0], [0, -6]], "outTangents": [[12, 0], [0, 8], [-6, 0]]}), + ) + .unwrap(); + let lid = effectcraft_project::LayerId(r["layer"].as_u64().unwrap()); + let uid = r["path"].as_u64().unwrap(); + let path = + |s: &crate::Session| s.active_comp().unwrap().layer(lid).unwrap().props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); + let original = path(&s); + for mac in [true, false] { + let (_, entry) = + platform_entries(mac).into_iter().find(|(p, e)| p.iter().map(String::as_str).eq(["Layer", "Mask and Shape Path"]) && e.label == "Closed").unwrap(); + assert!(s.is_enabled(&entry.command)); + assert_eq!(checked(&s, &entry.command, &entry.params), Some(true)); + s.execute(&entry.command, entry.params.clone()).unwrap(); + let mut opened = original.clone(); + opened.closed = false; + assert_eq!(path(&s), opened); + assert!(!effectcraft_path::to_kurbo(&path(&s)).elements().contains(&effectcraft_path::PathEl::ClosePath)); + assert_eq!(checked(&s, &entry.command, &entry.params), Some(false)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(path(&s), original); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(path(&s), opened); + s.execute(&entry.command, entry.params).unwrap(); + assert_eq!(path(&s), original); + assert!(effectcraft_path::to_kurbo(&path(&s)).elements().contains(&effectcraft_path::PathEl::ClosePath)); + } +} + /// `cargo test -p effectcraft-engine dump_specs -- --ignored --nocapture`: every command as TSV. #[test] #[ignore] diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 5658df107..fe95f5300 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -106,6 +106,11 @@ pub trait Importer: Send + Sync { /// Probe one file and return footage metadata. Image sequences are the engine's /// ([`sequence`]): it groups numbered stills and probes their first file here. fn probe(&self, path: &str) -> std::result::Result; + /// [`probe`](Self::probe), and what the import left out of the file (a 3D model's textures + /// over the limits), which the import shows the user. + fn probe_noting(&self, path: &str) -> std::result::Result<(effectcraft_project::Footage, Option), String> { + self.probe(path).map(|f| (f, None)) + } /// A footage file's bytes are now at `path` (extracted from a template): hosts whose media /// layer reads from memory (the browser) register them; file-based ones need nothing. fn register(&self, _path: &str, _data: &[u8]) {} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 19953053e..df0853398 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1,6 +1,8 @@ mod add_item_options; mod aep_export; mod aep_import; +mod analysis_inputs; +mod analysis_signature; mod anim_presets; mod anim_tools; mod aux_footage; @@ -12,6 +14,7 @@ mod crypto_pick; mod delete_keys; mod disk_cache; mod display_pass; +mod effect_ranges; mod effects; mod essential; mod essential_more; @@ -27,8 +30,10 @@ mod key_metadata_order; mod key_time; mod keyframe_text; mod keylight; +mod legacy_analysis_keys; mod limits; mod lottie; +mod lut_files; mod m137; mod m145; mod markers; diff --git a/crates/engine/src/tests/analysis_inputs.rs b/crates/engine/src/tests/analysis_inputs.rs new file mode 100644 index 000000000..b45b38eda --- /dev/null +++ b/crates/engine/src/tests/analysis_inputs.rs @@ -0,0 +1,211 @@ +//! Warp Stabilizer and 3D Camera Tracker analyses follow their input: the layer's frames, its +//! masks, the effects above them and a precomp's contents (#3535). Edits that leave the input +//! as it was (effects below, names, labels) keep them. + +use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY}; +use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY}; +use effectcraft_keyframe::Value; +use effectcraft_project::{ItemId, LayerId, Project}; +use serde_json::{Value as Json, json}; + +use crate::Session; + +const COMP: ItemId = ItemId(2); +const CLIP: LayerId = LayerId(3); +const WARP: u64 = 26; +const TRACKER: u64 = 54; + +/// `analysed-0.24.ecproj`: the clip of `tracked-0.22.ecproj` with a mask and, in order, a Warp Stabilizer, a 3D Camera +/// Tracker, a Gaussian Blur and a Roto Brush. +const ANALYSED: &str = include_str!("fixtures/analysed-0.24.ecproj"); + +fn open(json: &str) -> Session { + let mut s = Session::default(); + s.replace_project(Project::from_json(json).unwrap(), None); + s.open_comp(COMP); + s +} + +/// Which keys an analysis saves. +#[derive(Clone, Copy, Debug)] +enum Saved { + /// Today's: the input to the instance. + Input, + /// Before #3535: the layer's frames only (still recognised). + Frames, +} + +/// The key an analysis of instance `uid` (no Detailed Analysis) saves. +fn key(p: &Project, uid: u64, saved: Saved) -> String { + let layer = p.comp(COMP).unwrap().layer(CLIP).unwrap(); + match saved { + Saved::Input => crate::analysis::frames_key::analysis_key(p, COMP, layer, uid), + Saved::Frames => crate::analysis::frames_key::signature(p, COMP, layer), + } +} + +/// Give the Warp Stabilizer and the tracker an analysis of the clip as it is now, saved with +/// `saved` keys, and reopen the project. +fn analyse(s: &mut Session, saved: Saved) { + let mut p = (*s.project).clone(); + let set = |p: &mut Project, uid: u64, data: &str, id: &str, key: &str| { + let g = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(uid).unwrap(); + g.prop_mut(data).unwrap().value = Value::Str(format!("saved {data}")); + g.prop_mut(id).unwrap().value = Value::Str(key.into()); + }; + // The Warp Stabilizer is above the tracker: its analysis is part of the tracker's input. + let k = key(&p, WARP, saved); + set(&mut p, WARP, ANALYSIS, ANALYSIS_KEY, &k); + let k = key(&p, TRACKER, saved); + set(&mut p, TRACKER, TRACKS, TRACKS_KEY, &k); + *s = open(&p.to_json()); + run(s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})); + assert_eq!(analysed(s), [true, true], "{saved:?}"); +} + +/// Whether the Warp Stabilizer and the tracker still have their analysis. +fn analysed(s: &Session) -> [bool; 2] { + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let has = |uid: u64, id: &str| matches!(&layer.props.find_group(uid).unwrap().prop(id).unwrap().value, Value::Str(s) if !s.is_empty()); + [has(WARP, ANALYSIS), has(TRACKER, TRACKS)] +} + +fn run(s: &mut Session, cmd: &str, params: Json) -> Json { + s.execute_checked(cmd, params).unwrap() +} + +fn undo(s: &mut Session) { + run(s, "edit.undo", json!({})); +} + +/// An edit, its effect on the two analyses, and that undo brings them back. +fn check(s: &mut Session, cmd: &str, params: Json, kept: [bool; 2]) { + assert_eq!(analysed(s), [true, true], "before {cmd} {params}"); + run(s, cmd, params.clone()); + assert_eq!(analysed(s), kept, "{cmd} {params}"); + undo(s); + assert_eq!(analysed(s), [true, true], "undo of {cmd} {params}"); +} + +#[test] +fn masks_and_effects_above_are_part_of_the_input() { + for saved in [Saved::Input, Saved::Frames] { + masks_and_effects_above(saved); + } +} + +fn masks_and_effects_above(saved: Saved) { + let mut s = open(ANALYSED); + analyse(&mut s, saved); + // The layer's mask is under every effect. + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3}), [false, false]); + // The Warp Stabilizer is above the tracker: its settings change the tracker's input only. + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/stabilization/smoothness", "value": 20}), [true, false]); + // The Gaussian Blur and the Roto Brush are below both. + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#3/blurriness", "value": 4}), [true, true]); + run(&mut s, "layer.rename", json!({"layer": CLIP.0, "name": "Renamed"})); + assert_eq!(analysed(&s), [true, true]); + // The Effects switch turns the Warp Stabilizer (above the tracker) off. + check(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": false}), [true, false]); + // While it is off, the effects above draw nothing: editing them keeps the analyses. + run(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": false})); + analyse(&mut s, saved); + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/stabilization/smoothness", "value": 20}), [true, true]); + run(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": true})); + assert_eq!(analysed(&s), [true, false]); + analyse(&mut s, saved); + + // An effect moved above the Warp Stabilizer is part of both inputs, and its settings too. + s.edit("blur first", None, |p, _| { + let fx = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.sub_mut("effects").unwrap(); + let blur = fx.children.remove(2); + fx.children.insert(0, blur); + Ok(()) + }) + .unwrap(); + assert_eq!(analysed(&s), [false, false]); + analyse(&mut s, saved); + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/blurriness", "value": 4}), [false, false]); + + // Saved and reopened, they still match, and a mask edit still clears them. + let mut s = open(&s.project.to_json()); + run(&mut s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})); + assert_eq!(analysed(&s), [true, true]); + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3}), [false, false]); +} +#[test] +fn a_precomps_contents_are_part_of_the_input() { + for saved in [Saved::Input, Saved::Frames] { + precomp_contents(saved); + } +} + +fn precomp_contents(saved: Saved) { + let mut s = open(ANALYSED); + // Pre-compose the clip, leaving its masks and effects on the precomp layer. + let r = run(&mut s, "layer.precompose", json!({"layers": [CLIP.0], "mode": "leave"})); + let inner = ItemId(r["comp"].as_u64().unwrap()); + let inner_layer = |s: &Session, comp: ItemId| s.project.comp(comp).unwrap().layers[0].id.0; + let clip = inner_layer(&s, inner); + analyse(&mut s, saved); + // Edits inside the precomp change the frames. + check(&mut s, "prop.set", json!({"comp": inner.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]); + check(&mut s, "effect.apply", json!({"comp": inner.0, "layers": [clip], "effect": "ec.blur.gaussian"}), [false, false]); + check(&mut s, "layer.timing", json!({"comp": inner.0, "layers": [clip], "out": 0.25}), [false, false]); + // A label or comment inside it doesn't. A name does: expressions find layers by name. + s.edit("label", None, |p, _| { + let l = p.comp_mut(inner).unwrap().layer_mut(LayerId(clip)).unwrap(); + l.label = effectcraft_color::Label::Pink; + l.comment = "a note".into(); + Ok(()) + }) + .unwrap(); + assert_eq!(analysed(&s), [true, true]); + check(&mut s, "layer.rename", json!({"comp": inner.0, "layer": clip, "name": "Inner"}), [false, false]); + + // A precomp inside the precomp: its contents too. + let r = run(&mut s, "layer.precompose", json!({"comp": inner.0, "layers": [clip], "mode": "leave"})); + let deeper = ItemId(r["comp"].as_u64().unwrap()); + assert_eq!(analysed(&s), [false, false], "pre-composing inside the precomp changes its contents"); + analyse(&mut s, saved); + let clip = inner_layer(&s, deeper); + check(&mut s, "prop.set", json!({"comp": deeper.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]); + + // Saved and reopened, they still match, and an edit inside still clears them. + let mut s = open(&s.project.to_json()); + run(&mut s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})); + assert_eq!(analysed(&s), [true, true]); + check(&mut s, "prop.set", json!({"comp": deeper.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]); +} + +/// Precomps used many times, nested deeply or (in a broken project) in a cycle are keyed in +/// bounded time, and an edit deep inside still changes the key. +#[test] +fn shared_deep_and_cyclic_precomps_are_keyed_in_bounded_time() { + use effectcraft_color::Label; + use effectcraft_project::{ItemKind, LayerSource}; + let mut s = open(ANALYSED); + let r = run(&mut s, "layer.precompose", json!({"layers": [CLIP.0], "mode": "leave"})); + let inner = ItemId(r["comp"].as_u64().unwrap()); + let mut p = (*s.project).clone(); + let template = p.comp(inner).unwrap().clone(); + // 40 comps, each drawing the next one twice (2^40 paths if each were walked), the last + // drawing the first. + let ids: Vec = (0..40).map(|i| p.add_item(&format!("Nest {i}"), Label::default(), None, ItemKind::Comp(template.clone().into()))).collect(); + for (i, id) in ids.iter().enumerate() { + let next = ids[(i + 1) % ids.len()]; + let mut layer = template.layers[0].clone(); + layer.source = LayerSource::Comp { item: next }; + let c = p.comp_mut(*id).unwrap(); + c.layers.push(layer.clone()); + layer.id = LayerId(layer.id.0 + 1000); + c.layers.push(layer); + } + p.comp_mut(inner).unwrap().layers[0].source = LayerSource::Comp { item: ids[0] }; + let key = |p: &Project| crate::analysis::frames_key::analysis_key(p, COMP, p.comp(COMP).unwrap().layer(CLIP).unwrap(), WARP); + let start = std::time::Instant::now(); + let before = key(&p); + assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed()); + p.comp_mut(ids[10]).unwrap().background = [1.0, 0.0, 0.0]; + assert_ne!(key(&p), before); +} diff --git a/crates/engine/src/tests/analysis_signature.rs b/crates/engine/src/tests/analysis_signature.rs new file mode 100644 index 000000000..045e279de --- /dev/null +++ b/crates/engine/src/tests/analysis_signature.rs @@ -0,0 +1,315 @@ +//! Warp Stabilizer, 3D Camera Tracker and Roto Brush keys saved by 0.24 keep matching their +//! layer's frames after edits that don't change them, and a real change still clears them. + +use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY}; +use effectcraft_effects::roto::{FROZEN, INPUT_KEY}; +use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY}; +use effectcraft_keyframe::Value; +use effectcraft_project::{ItemId, LayerId, Project}; +use serde_json::json; + +use crate::Session; + +const COMP: ItemId = ItemId(2); +const CLIP: LayerId = LayerId(3); +const WARP: u64 = 26; +const TRACKER: u64 = 54; +const ROTO: u64 = 86; + +/// Saved by 0.24.1 (before #3534/#3536): the clip of `tracked-0.22.ecproj` with Time Remap, a +/// mask, a Gaussian Blur and a Roto Brush, its analyses replaced by short stand-ins. The keys +/// are the ones that version computed for it. +const ANALYSED_0_24: &str = include_str!("fixtures/analysed-0.24.ecproj"); +const SIGNATURE_0_24: &str = "03efb7c4b0f27b65"; +const ROTO_INPUT_0_24: &str = "7b319ce93027617c"; + +fn open(json: &str) -> Session { + let mut s = Session::default(); + s.replace_project(Project::from_json(json).unwrap(), None); + s.open_comp(COMP); + s +} + +/// The (data, key) of the Warp Stabilizer, the 3D Camera Tracker and the Roto Brush. +fn saved(s: &Session) -> [(String, String); 3] { + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let get = |uid: u64, data: &str, key: &str| { + let params = crate::camera_track::static_params(layer.props.find_group(uid).unwrap()); + let text = |id: &str| match params.get(id) { + Some(Value::Str(s)) => s.clone(), + other => panic!("{id}: {other:?}"), + }; + (text(data), text(key)) + }; + [get(WARP, ANALYSIS, ANALYSIS_KEY), get(TRACKER, TRACKS, TRACKS_KEY), get(ROTO, FROZEN, INPUT_KEY)] +} + +fn add_to_render_queue(s: &mut Session) { + s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap(); +} + +#[test] +fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() { + let mut s = open(ANALYSED_0_24); + let before = saved(&s); + assert_eq!(before[0], ("saved analysis".into(), SIGNATURE_0_24.into())); + assert_eq!(before[1], ("saved tracks".into(), SIGNATURE_0_24.into())); + assert_eq!(before[2], ("saved frozen".into(), ROTO_INPUT_0_24.into())); + + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + + // Saved and reopened, the keys still match. + let mut s = open(&s.project.to_json()); + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + + // Other frames: all three are cleared (the Roto Brush gets a new key), and undo brings them back. + s.execute_checked("layer.timing", json!({"layer": CLIP.0, "out": 0.25})).unwrap(); + let after = saved(&s); + assert_eq!(after[0], (String::new(), String::new())); + assert_eq!(after[1], (String::new(), String::new())); + assert_eq!(after[2].0, ""); + assert_ne!(after[2].1, ROTO_INPUT_0_24); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + + // Time Remap is part of the frames. + s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "timeRemap", "value": 0.3})).unwrap(); + assert!(saved(&s).iter().all(|(data, _)| data.is_empty())); + s.execute_checked("edit.undo", json!({})).unwrap(); + + // The Roto Brush's input also has the layer's masks and the effects above it. + s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "effects/#3/blurriness", "value": 4})).unwrap(); + let after = saved(&s); + assert_eq!(after[2].0, ""); + assert_ne!(after[2].1, ROTO_INPUT_0_24); + s.execute_checked("edit.undo", json!({})).unwrap(); + s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3})).unwrap(); + assert_eq!(saved(&s)[2].0, ""); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); +} + +/// The text keys are made from today, written field by field (#3536). It changes only when this +/// test is changed with it: a new field of a type it writes doesn't compile until it is decided +/// in `analysis::frames_key`, and renaming a field or variant doesn't change it. +#[test] +fn signature_text_is_pinned() { + let s = open(ANALYSED_0_24); + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let key = r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=video;w=160;h=120;par=1.0;rate=12/1;nativeRate=none;duration=254016000000;video=true;audio=false;alpha=ignore;matte=[0.0, 0.0, 0.0];loop=1;codec="H.264 (High)";frames=0;profile{rec709;};layer=none;fields=off;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=false;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=10bit;data=none;page=0;alphabetical=false;startTimecode=none;fileTimecode=none;placedPage=false;in=0;out=254016000000;start=0;stretch=100.0;timeRemap{prop="timeRemap";name="Time Remap";scalar=0.0;spatial=false;key=0;scalar=0.2;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;key=254016000000;scalar=1.0;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;expr=none;};compRate{rate=12/1;};"#; + assert_eq!(crate::analysis::frames_key::signature_text(&s.project, COMP, layer), key); +} + +/// Keys made today (after analysing again) match through edits, undo and save/reopen too, and +/// renaming or relabelling never drops them. +#[test] +fn todays_keys_survive_edits_that_keep_their_frames() { + let mut s = open(ANALYSED_0_24); + // Analysing again writes today's keys. + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let signature = crate::analysis::frames_key::signature(&s.project, COMP, layer); + let input = crate::roto::input_key(&s.project, COMP, layer, ROTO); + assert_ne!(signature, SIGNATURE_0_24); + s.edit("analyse", None, |p, _| { + let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap(); + for (uid, id, key) in [(WARP, ANALYSIS_KEY, &signature), (TRACKER, TRACKS_KEY, &signature), (ROTO, INPUT_KEY, &input)] { + l.props.find_group_mut(uid).unwrap().get_mut(id).unwrap().value = Value::Str(key.clone()); + } + Ok(()) + }) + .unwrap(); + // The Roto Brush's key covers the effects above it: the Warp Stabilizer's new key changed it. + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let input = crate::roto::input_key(&s.project, COMP, layer, ROTO); + s.edit("roto key", None, |p, _| { + let g = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(ROTO).unwrap(); + g.get_mut(INPUT_KEY).unwrap().value = Value::Str(input.clone()); + g.get_mut(FROZEN).unwrap().value = Value::Str("saved frozen".into()); + Ok(()) + }) + .unwrap(); + let before = saved(&s); + assert_eq!(before[0].1, signature); + assert_eq!(before[2], ("saved frozen".into(), input)); + + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + let mut s = open(&s.project.to_json()); + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + // Offline and back online (#3534). + for missing in [true, false] { + if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.missing = missing; + } + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + } + // Colour labels and footage markers only show things. + s.edit("label", None, |p, _| { + let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap(); + l.props.find_group_mut(82).unwrap().label = Some(effectcraft_color::Label::Yellow); + if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.markers.push(effectcraft_project::Marker::default()); + } + Ok(()) + }) + .unwrap(); + assert_eq!(saved(&s), before); + // Expressions find effects by name: renaming the effect above the Roto Brush is a change for it. + s.edit("rename", None, |p, _| { + p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(82).unwrap().name = "Soft".into(); + Ok(()) + }) + .unwrap(); + assert_eq!(saved(&s)[..2], before[..2]); + assert_eq!(saved(&s)[2].0, ""); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + + // A real change still clears them. + s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap(); + assert!(saved(&s).iter().all(|(data, _)| data.is_empty())); +} + +/// Footage going offline (or coming back) is an observation, not an edit: the next edit keeps +/// every analysis (#3534). +#[test] +fn offline_footage_keeps_analyses() { + let mut s = open(ANALYSED_0_24); + let before = saved(&s); + let missing = |s: &Session| matches!(&s.project.item(ItemId(1)).unwrap().kind, effectcraft_project::ItemKind::Footage(f) if f.missing); + // The fixture's footage path doesn't exist here: the check marks it missing. + let r = s.execute_checked("footage.check", json!({"wait": true})).unwrap(); + assert_eq!(r["missing"], 1, "{r}"); + assert!(missing(&s)); + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + + // Saved and reopened while offline, then back online. + let mut s = open(&s.project.to_json()); + assert!(missing(&s)); + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.missing = false; + } + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + + // A real change while offline still clears them. + s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap(); + assert!(saved(&s).iter().all(|(data, _)| data.is_empty())); +} + +/// A key 0.24.1 saved while the footage was offline (it hashed the availability) matches too, +/// online or offline. 0.24.1 gave the Roto Brush this Input Key when the fixture's footage went +/// offline and an edit cleared the other two analyses. +#[test] +fn keys_saved_by_0_24_while_offline_still_match() { + const ROTO_INPUT_0_24_OFFLINE: &str = "6183fdd46b514259"; + let mut s = open(ANALYSED_0_24); + s.edit("offline", None, |p, _| { + if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.missing = true; + } + let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap(); + // What 0.24.1's edit cleared then. + use effectcraft_effects::camera_tracker::{AVERAGE_ERROR, METHOD_USED, SOLVE, SOLVE_KEY}; + for (uid, id) in + [(WARP, ANALYSIS), (WARP, ANALYSIS_KEY), (TRACKER, SOLVE), (TRACKER, SOLVE_KEY), (TRACKER, METHOD_USED), (TRACKER, TRACKS), (TRACKER, TRACKS_KEY)] + { + l.props.find_group_mut(uid).unwrap().prop_mut(id).unwrap().value = Value::Str(String::new()); + } + l.props.find_group_mut(TRACKER).unwrap().prop_mut(AVERAGE_ERROR).unwrap().value = Value::Scalar(0.0); + let g = l.props.find_group_mut(ROTO).unwrap(); + g.get_mut(INPUT_KEY).unwrap().value = Value::Str(ROTO_INPUT_0_24_OFFLINE.into()); + Ok(()) + }) + .unwrap(); + let roto = |s: &Session| saved(s)[2].clone(); + assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into())); + for missing in [true, false] { + if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.missing = missing; + } + add_to_render_queue(&mut s); + assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into())); + } +} + +/// Expressions seed `random` and `wiggle` with the property's uid: a Time Remap with an expression +/// keys its uid (a duplicated layer gets new uids), one without doesn't. +#[test] +fn an_expression_keys_its_property_uid() { + let s = open(ANALYSED_0_24); + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap().clone(); + let text = |l: &effectcraft_project::Layer| crate::analysis::frames_key::signature_text(&s.project, COMP, l); + let renumbered = |l: &effectcraft_project::Layer| { + let mut l = l.clone(); + l.props.get_mut("timeRemap").unwrap().uid += 1000; + l + }; + assert_eq!(text(&renumbered(&layer)), text(&layer)); + let mut with_expr = layer.clone(); + with_expr.props.get_mut("timeRemap").unwrap().expr = + Some(effectcraft_project::Expression { text: "seedRandom(0, true); random(0, 1)".into(), enabled: true }); + assert_ne!(text(&renumbered(&with_expr)), text(&with_expr)); +} + +/// Non-default values of the types the key writes are written as their fixed words (#3536). +#[test] +fn nested_values_are_written_as_fixed_words() { + use effectcraft_project::{ + AlphaMode, CineonUnits, FieldOrder, FootageKind, GroupKind, ItemKind, LayerSource, MaskMode, MaskMotionBlur, Solid, SourceLayer, + }; + let mut s = open(ANALYSED_0_24); + let p = std::sync::Arc::make_mut(&mut s.project); + if let Some(ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.kind = FootageKind::Sequence; + f.sequence = vec!["a_0001.png".into(), "a_0002.png".into()]; + f.alpha = AlphaMode::Premultiplied; + f.premul_color = [0.5, 0.25, 1.0]; + f.fields = FieldOrder::UpperFirst; + f.cineon.units = CineonUnits::Float; + f.cineon.log_conversion = true; + f.color_profile = Some(effectcraft_color::ColorSpace::DisplayP3); + f.layer = Some(SourceLayer { index: 3, name: "Sky".into(), layer_size: true, embedded: Some("id-7".into()), placed: true }); + f.native_rate = Some(effectcraft_time::FrameRate { num: 30000, den: 1001 }); + f.start_timecode = Some(42); + f.data = Some("{\"k\":1}".into()); + } + let layer = p.comp(COMP).unwrap().layer(CLIP).unwrap().clone(); + let text = crate::analysis::frames_key::signature_text(p, COMP, &layer); + let footage = text.split(";in=").next().unwrap(); + assert_eq!( + footage, + r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=sequence;w=160;h=120;par=1.0;rate=12/1;nativeRate{rate=30000/1001;};duration=254016000000;video=true;audio=false;alpha=premultiplied;matte=[0.5, 0.25, 1.0];loop=1;codec="H.264 (High)";frames=2;file="a_0001.png";file="a_0002.png";profile{p3;};layer{index=3;layerSize=true;embedded{id="id-7";};placed=true;};fields=upper;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=true;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=float;data{text="{\"k\":1}";};page=0;alphabetical=false;startTimecode{frame=42;};fileTimecode=none;placedPage=false"# + ); + + let solid = p.add_item("Solid", Default::default(), None, ItemKind::Solid(Solid { color: [1.0, 0.5, 0.0], width: 64, height: 48, pixel_aspect: 2.0 })); + let mut on_solid = layer.clone(); + on_solid.source = LayerSource::Solid { item: solid }; + let text = crate::analysis::frames_key::signature_text(p, COMP, &on_solid); + assert_eq!(text.split(";in=").next().unwrap(), format!("frames/1;solid={};solid;color=[1.0, 0.5, 0.0];w=64;h=48;par=2.0", solid.0)); + + // Every mask mode and motion blur setting gives its own Input Key. + let mask = layer.masks().unwrap().groups().next().unwrap().uid; + let mut keys = std::collections::BTreeSet::new(); + for mode in MaskMode::ALL { + for blur in [MaskMotionBlur::SameAsLayer, MaskMotionBlur::On, MaskMotionBlur::Off] { + let mut l = layer.clone(); + if let GroupKind::Mask { mode: m, motion_blur, .. } = &mut l.props.find_group_mut(mask).unwrap().kind { + (*m, *motion_blur) = (mode, blur); + } + keys.insert(crate::analysis::frames_key::input_key(p, COMP, &l, ROTO)); + } + } + assert_eq!(keys.len(), MaskMode::ALL.len() * 3); +} diff --git a/crates/engine/src/tests/camera_track.rs b/crates/engine/src/tests/camera_track.rs index 3ca8578a9..77829e7f9 100644 --- a/crates/engine/src/tests/camera_track.rs +++ b/crates/engine/src/tests/camera_track.rs @@ -252,6 +252,15 @@ fn invalidation_resolve_cancel_and_undo() { assert_eq!(status(&mut s)["analyzed"], false); assert!(s.redo()); assert_eq!(status(&mut s)["solved"], true); + // A mask is part of the tracked input (#3535): drawing one clears the tracks, undo keeps them. + s.execute_checked("mask.new", json!({"layer": clip.0, "vertices": [[10, 10], [200, 10], [200, 150]]})).unwrap(); + assert_eq!(status(&mut s)["analyzed"], false); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(status(&mut s)["solved"], true); + // An effect below the tracker isn't. + s.execute_checked("effect.apply", json!({"layers": [clip.0], "effect": "ec.blur.gaussian"})).unwrap(); + assert_eq!(status(&mut s)["solved"], true); + s.execute_checked("edit.undo", json!({})).unwrap(); // Changing the Solve Method keeps the tracks and only re-solves. s.execute_checked("prop.set", json!({"layer": clip.0, "path": "effects/#1/advanced/solveMethod", "value": 1})).unwrap(); diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs new file mode 100644 index 000000000..7deaaa911 --- /dev/null +++ b/crates/engine/src/tests/effect_ranges.rs @@ -0,0 +1,170 @@ +//! Effect parameters take the whole valid range After Effects records for them (fx_defs in the +//! aep crate), end to end: `prop.set` keeps both ends, undo and redo restore them, and a saved +//! project reopens with them. The aep crate's +//! `effect_hard_ranges_cover_recorded_after_effects_ranges` checks the ranges themselves +//! against that table. + +use effectcraft_project::{LayerId, Node, ParamUi, PropGroup}; +use serde_json::{Value, json}; + +use crate::Session; + +/// (issue, effect, parameter path, lowest, highest): the ends of the range the effect now accepts, +/// in EffectCraft's units: After Effects' valid range, or wider where EffectCraft already was. +/// At least one end of each is outside the range accepted before the issue. +#[rustfmt::skip] +const ROWS: &[(u32, &str, &str, f64, f64)] = &[ + (3487, "ec.color.levelsic", "rgb/rgbInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "rgb/rgbInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "rgb/rgbOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "rgb/rgbOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "rgb/rgbGamma", 0.0, 10.0), + (3487, "ec.color.levelsic", "red/redInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "red/redInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "red/redOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "red/redOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "red/redGamma", 0.0, 10.0), + (3487, "ec.color.levelsic", "green/greenInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "green/greenInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "green/greenOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "green/greenOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "green/greenGamma", 0.0, 10.0), + (3487, "ec.color.levelsic", "blue/blueInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "blue/blueInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "blue/blueOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "blue/blueOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "blue/blueGamma", 0.0, 10.0), + (3487, "ec.color.levelsic", "alpha/alphaInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "alpha/alphaInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "alpha/alphaOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "alpha/alphaOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "alpha/alphaGamma", 0.0, 10.0), + (3478, "ec.generate.fourcolor", "blend", 1.0, 10000.0), + (3479, "ec.generate.fourcolor", "jitter", 0.0, 500.0), + (3483, "ec.noise.noisehls", "hue", 0.0, 1000.0), + (3483, "ec.noise.noisehls", "lightness", 0.0, 1000.0), + (3483, "ec.noise.noisehls", "saturation", 0.0, 1000.0), + (3484, "ec.noise.noisehls", "grainSize", 0.0, 100.0), + (3483, "ec.noise.noisehlsauto", "hue", 0.0, 1000.0), + (3483, "ec.noise.noisehlsauto", "lightness", 0.0, 1000.0), + (3483, "ec.noise.noisehlsauto", "saturation", 0.0, 1000.0), + (3484, "ec.noise.noisehlsauto", "grainSize", 0.0, 100.0), + (3480, "ec.color.changecolor", "hueTransform", -1800.0, 1800.0), + (3476, "ec.generate.grid", "border", 0.0, 2000.0), + (3472, "ec.transition.venetian", "width", 1.0, 32000.0), + (3473, "ec.transition.venetian", "feather", 0.0, 32000.0), + (3474, "ec.transition.radialwipe", "feather", 0.0, 32000.0), + (3477, "ec.stylize.scatter", "amount", 0.0, 1000.0), + (3475, "ec.generate.beam", "startThickness", 0.0, 4000.0), + (3475, "ec.generate.beam", "endThickness", 0.0, 4000.0), + (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), + (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), + (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), +]; + +fn path(effect: &str, param: &str) -> String { + format!("effects/{effect}/{param}") +} + +fn read(s: &mut Session, layer: u64, effect: &str, param: &str) -> f64 { + let got = s.execute("prop.get", json!({"layer": layer, "path": path(effect, param)})).unwrap(); + got["value"].as_f64().unwrap_or_else(|| panic!("{effect} {param}: {got}")) +} + +fn set(s: &mut Session, layer: u64, effect: &str, param: &str, v: f64) -> Value { + s.execute("prop.set", json!({"layer": layer, "path": path(effect, param), "value": v})).unwrap() +} + +/// A composition with two solids, each with one instance of every effect in [`ROWS`]. +fn session() -> (Session, u64, u64) { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 2})).unwrap(); + let mut layers = [0; 2]; + for l in &mut layers { + *l = s.execute("layer.newSolid", json!({"color": "#808080", "width": 64, "height": 36})).unwrap()["layer"].as_u64().unwrap(); + let mut effects: Vec<&str> = ROWS.iter().map(|r| r.1).collect(); + effects.dedup(); + for e in effects { + s.execute("effect.apply", json!({"layers": [*l], "effect": e})).unwrap(); + } + } + (s, layers[0], layers[1]) +} + +/// Both ends of every row survive `prop.set`, undo / redo, and a save and reopen. +#[test] +fn effect_parameters_keep_both_ends_of_the_after_effects_range() { + let (mut s, low, high) = session(); + for &(issue, e, p, lo, hi) in ROWS { + assert_eq!(set(&mut s, high, e, p, lo), json!(lo), "#{issue} {e} {p}: prop.set reply"); + assert_eq!(read(&mut s, high, e, p), lo, "#{issue} {e} {p}"); + set(&mut s, high, e, p, hi); + assert_eq!(read(&mut s, high, e, p), hi, "#{issue} {e} {p}"); + assert!(s.undo()); + assert_eq!(read(&mut s, high, e, p), lo, "#{issue} {e} {p}: undo"); + assert!(s.redo()); + assert_eq!(read(&mut s, high, e, p), hi, "#{issue} {e} {p}: redo"); + set(&mut s, low, e, p, lo); + } + let dir = std::env::temp_dir().join(format!("ec-effect-ranges-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("ranges.ecproj").to_string_lossy().to_string(); + s.execute("file.save", json!({"path": file})).unwrap(); + let mut s2 = Session::default(); + s2.execute("file.open", json!({"path": file})).unwrap(); + let _ = std::fs::remove_dir_all(dir); + for &(issue, e, p, lo, hi) in ROWS { + assert_eq!(read(&mut s2, low, e, p), lo, "#{issue} {e} {p}: reopened"); + assert_eq!(read(&mut s2, high, e, p), hi, "#{issue} {e} {p}: reopened"); + } +} + +/// A project saved while these ranges were narrower stored that range with each instance +/// (`ParamUi`) and values clamped to it: opening it takes the effect's current range and keeps +/// the stored values, so the new ends can be set. +#[test] +fn projects_saved_with_the_narrower_ranges_open_with_the_new_ones() { + let (mut s, low, _) = session(); + let cid = s.active_comp_id().unwrap(); + let mut old = (*s.project).clone(); + let stored: Vec = ROWS.iter().map(|&(_, e, p, ..)| read(&mut s, low, e, p)).collect(); + { + let effectcraft_project::ItemKind::Comp(comp) = &mut old.items.get_mut(&cid).unwrap().kind else { panic!("not a composition") }; + let l = std::sync::Arc::make_mut(comp).layers.find_mut(|l| l.id == LayerId(low)).unwrap(); + for (&(_, e, p, ..), v) in ROWS.iter().zip(&stored) { + let g = l.props.sub_mut("effects").unwrap().children.iter_mut().find_map(|n| match n { + Node::Group(g) if g.match_id == e => Some(g), + _ => None, + }); + let pr = prop_mut(g.unwrap(), p).unwrap_or_else(|| panic!("{e} {p}")); + // The narrowest stored range that still holds the stored value. + pr.ui = ParamUi::Slider { min: *v, max: *v, slider_min: *v, slider_max: *v, decimals: 1 }; + } + } + let dir = std::env::temp_dir().join(format!("ec-effect-ranges-old-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("old.ecproj").to_string_lossy().to_string(); + std::fs::write(&file, old.to_json()).unwrap(); + let mut s2 = Session::default(); + s2.execute("file.open", json!({"path": file})).unwrap(); + let _ = std::fs::remove_dir_all(dir); + for (&(issue, e, p, lo, hi), v) in ROWS.iter().zip(&stored) { + assert_eq!(read(&mut s2, low, e, p), *v, "#{issue} {e} {p}: the stored value is kept"); + let spec = effectcraft_effects::find(e).unwrap().params.iter().find(|q| q.id == p).unwrap(); + let uid = s2.execute("prop.get", json!({"layer": low, "path": path(e, p)})).unwrap()["uid"].as_u64().unwrap(); + let layer = s2.project.comp(cid).unwrap().layer(LayerId(low)).unwrap(); + assert_eq!(layer.props.find(uid).unwrap().ui, spec.ui, "#{issue} {e} {p}: the range is refreshed"); + set(&mut s2, low, e, p, lo); + assert_eq!(read(&mut s2, low, e, p), lo, "#{issue} {e} {p}"); + set(&mut s2, low, e, p, hi); + assert_eq!(read(&mut s2, low, e, p), hi, "#{issue} {e} {p}"); + } +} + +/// The property at `path` (`group/param`) in an effect instance. +fn prop_mut<'a>(g: &'a mut PropGroup, path: &str) -> Option<&'a mut effectcraft_project::Property> { + match path.split_once('/') { + None => g.get_mut(path), + Some((first, rest)) => prop_mut(g.sub_mut(first)?, rest), + } +} diff --git a/crates/engine/src/tests/fixtures/analysed-0.24.ecproj b/crates/engine/src/tests/fixtures/analysed-0.24.ecproj new file mode 100644 index 000000000..e99b4acc0 --- /dev/null +++ b/crates/engine/src/tests/fixtures/analysed-0.24.ecproj @@ -0,0 +1 @@ +{"schema":2,"settings":{"bit_depth":"Bpc8","linearize":false,"working_space":null,"blend_linear":false,"time_display":"Timecode","frame_start":0,"audio_sample_rate":48000,"gpu_acceleration":true,"color_engine":"Adobe","hdr":"Clip","output_space":null,"working_gamma":2.2},"items":{"1":{"id":1,"name":"effectcraft-3456-shake.mp4","label":"Aqua","comment":"","parent":null,"kind":{"type":"Footage","path":"/tmp/effectcraft-3456-shake.mp4","kind":"Video","width":160,"height":120,"pixel_aspect":1.0,"frame_rate":{"num":12,"den":1},"native_rate":null,"duration":254016000000,"has_video":true,"has_audio":false,"alpha":"Ignore","premul_color":[0.0,0.0,0.0],"loop_count":1,"codec":"H.264 (High)","missing":false,"color_profile":"Rec709"}},"2":{"id":2,"name":"effectcraft-3456-shake","label":"Sandstone","comment":"","parent":null,"kind":{"type":"Comp","width":160,"height":120,"pixel_aspect":1.0,"frame_rate":{"num":12,"den":1},"duration":254016000000,"display_start":0,"background":[0.0,0.0,0.0],"work_area":[0,254016000000],"layers":[{"id":3,"name":"effectcraft-3456-shake.mp4","source":{"type":"Footage","item":1},"label":"Aqua","comment":"","start_time":0,"in_point":0,"out_point":254016000000,"stretch":100.0,"switches":{"video":true,"audio":true,"solo":false,"locked":false,"shy":false,"collapse":false,"quality":"Best","sampling":"Bilinear","effects":true,"frame_blend":"Off","motion_blur":false,"adjustment":false,"three_d":false,"guide":false},"blend_mode":"Normal","preserve_transparency":false,"track_matte":null,"parent":null,"markers":[],"auto_orient":"Off","props":{"uid":4,"match":"layer","name":"effectcraft-3456-shake.mp4","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":76,"match":"timeRemap","name":"Time Remap","value":{"t":"Scalar","v":0.0},"keys":[{"time":0,"value":{"t":"Scalar","v":0.2},"in_interp":"Linear","out_interp":"Linear","in_ease":[],"out_ease":[],"continuous":false,"auto_bezier":false,"spatial_in":[0.0,0.0,0.0],"spatial_out":[0.0,0.0,0.0],"spatial_auto":true,"spatial_continuous":false,"roving":false},{"time":254016000000,"value":{"t":"Scalar","v":1.0},"in_interp":"Linear","out_interp":"Linear","in_ease":[],"out_ease":[],"continuous":false,"auto_bezier":false,"spatial_in":[0.0,0.0,0.0],"spatial_out":[0.0,0.0,0.0],"spatial_auto":true,"spatial_continuous":false,"roving":false}],"ui":{"kind":"Number"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":5,"match":"masks","name":"Masks","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Group","uid":77,"match":"mask","name":"Mask 1","kind":{"kind":"Mask","mode":"Add","inverted":false,"color":[177,180,79],"locked":false,"motion_blur":"SameAsLayer","feather_falloff":"Smooth","roto_bezier":false},"enabled":true,"children":[{"node":"Prop","uid":78,"match":"path","name":"Mask Path","value":{"t":"Path","v":{"vertices":[[10.0,10.0],[120.0,10.0],[120.0,100.0],[10.0,100.0]],"in_tangents":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]],"out_tangents":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]],"closed":false}},"ui":{"kind":"Path"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":79,"match":"feather","name":"Mask Feather","value":{"t":"Vec2","v":[0.0,0.0]},"ui":{"kind":"Pixels"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":80,"match":"opacity","name":"Mask Opacity","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":81,"match":"expansion","name":"Mask Expansion","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Pixels"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]},{"node":"Group","uid":6,"match":"effects","name":"Effects","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Group","uid":26,"match":"ec.distort.warpstabilizer","name":"Warp Stabilizer","kind":{"kind":"Effect","effect":"ec.distort.warpstabilizer"},"enabled":true,"children":[{"node":"Group","uid":28,"match":"stabilization","name":"Stabilization","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":27,"match":"result","name":"Result","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Smooth Motion","No Motion"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":29,"match":"smoothness","name":"Smoothness","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":30,"match":"method","name":"Method","value":{"t":"Enum","v":3},"ui":{"kind":"Popup","options":["Position","Position, Scale, Rotation","Perspective","Subspace Warp"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":31,"match":"preserveScale","name":"Preserve Scale","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":33,"match":"borders","name":"Borders","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":32,"match":"framing","name":"Framing","value":{"t":"Enum","v":2},"ui":{"kind":"Popup","options":["Stabilize Only","Stabilize, Crop","Stabilize, Crop, Auto-scale","Stabilize, Synthesize Edges"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":35,"match":"autoScale","name":"Auto-scale","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":34,"match":"maximumScale","name":"Maximum Scale","value":{"t":"Scalar","v":150.0},"ui":{"kind":"Slider","min":100.0,"max":1000.0,"slider_min":100.0,"slider_max":200.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":36,"match":"actionSafeMargin","name":"Action-safe Margin","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":45.0,"slider_min":0.0,"slider_max":20.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":37,"match":"additionalScale","name":"Additional Scale","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":1.0,"max":1000.0,"slider_min":50.0,"slider_max":150.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":39,"match":"advanced","name":"Advanced","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":38,"match":"detailedAnalysis","name":"Detailed Analysis","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":40,"match":"rollingShutterRipple","name":"Rolling Shutter Ripple","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Automatic Reduction","Enhanced Reduction"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":41,"match":"cropLessSmoothMore","name":"Crop Less <-> Smooth More","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":42,"match":"synthesizeInputRange","name":"Synthesis Input Range (seconds)","value":{"t":"Scalar","v":1.0},"ui":{"kind":"Slider","min":0.0,"max":10.0,"slider_min":0.0,"slider_max":5.0,"decimals":2},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":43,"match":"synthesizeEdgeFeather","name":"Synthesis Edge Feather","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":45,"match":"edgeCropping","name":"Synthesis Edge Cropping","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":44,"match":"left","name":"Left","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":50.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":46,"match":"top","name":"Top","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":50.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":47,"match":"right","name":"Right","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":50.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":48,"match":"bottom","name":"Bottom","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":50.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":49,"match":"hideWarningBanner","name":"Hide Warning Banner","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":50,"match":"showTrackPoints","name":"Show Track Points","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":51,"match":"trackPointSize","name":"Track Point Size","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":200.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":52,"match":"analysis","name":"Analysis","value":{"t":"Str","v":"saved analysis"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":53,"match":"analysisKey","name":"Analysis Key","value":{"t":"Str","v":"03efb7c4b0f27b65"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":54,"match":"ec.perspective.cameratracker","name":"3D Camera Tracker","kind":{"kind":"Effect","effect":"ec.perspective.cameratracker"},"enabled":true,"children":[{"node":"Prop","uid":55,"match":"shotType","name":"Shot Type","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Fixed Angle of View","Variable Zoom","Specify Angle of View"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":56,"match":"horizontalAngleOfView","name":"Horizontal Angle of View","value":{"t":"Scalar","v":40.0},"ui":{"kind":"Slider","min":1.0,"max":170.0,"slider_min":10.0,"slider_max":120.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":57,"match":"showTrackPoints","name":"Show Track Points","value":{"t":"Enum","v":1},"ui":{"kind":"Popup","options":["2D Source","3D Solved"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":58,"match":"renderTrackPoints","name":"Render Track Points","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":59,"match":"trackPointSize","name":"Track Point Size","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":300.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":60,"match":"targetSize","name":"Target Size","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":1.0,"max":1000.0,"slider_min":10.0,"slider_max":300.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":62,"match":"advanced","name":"Advanced","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":61,"match":"solveMethod","name":"Solve Method","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Auto Detect","Typical","Mostly Flat Scene","Tripod Pan"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":63,"match":"methodUsed","name":"Method Used","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":64,"match":"averageError","name":"Average Error","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":65,"match":"detailedAnalysis","name":"Detailed Analysis","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":66,"match":"lensDistortion","name":"Solve Lens Distortion","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":67,"match":"undistort","name":"Undistort Footage","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":68,"match":"autoDeletePoints","name":"Auto-delete Points Across Time","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":69,"match":"hideWarningBanner","name":"Hide Warning Banner","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":70,"match":"tracks","name":"Tracks","value":{"t":"Str","v":"saved tracks"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":71,"match":"tracksKey","name":"Tracks Key","value":{"t":"Str","v":"03efb7c4b0f27b65"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":72,"match":"solve","name":"Solve","value":{"t":"Str","v":"saved solve"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":73,"match":"solveKey","name":"Solve Key","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":74,"match":"deleted","name":"Deleted Points","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":75,"match":"camera","name":"Camera Layer","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":82,"match":"ec.blur.gaussian","name":"Gaussian Blur","kind":{"kind":"Effect","effect":"ec.blur.gaussian"},"enabled":true,"children":[{"node":"Prop","uid":83,"match":"blurriness","name":"Blurriness","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":3000.0,"slider_min":0.0,"slider_max":50.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":84,"match":"dimensions","name":"Blur Dimensions","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Horizontal and Vertical","Horizontal","Vertical"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":85,"match":"repeatEdge","name":"Repeat Edge Pixels","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":86,"match":"ec.matte.rotobrush","name":"Roto Brush & Refine Edge","kind":{"kind":"Effect","effect":"ec.matte.rotobrush"},"enabled":true,"children":[{"node":"Prop","uid":87,"match":"version","name":"Version","value":{"t":"Enum","v":2},"ui":{"kind":"Popup","options":["1.0","2.0","3.0"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":88,"match":"quality","name":"Quality","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Standard","Best"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":90,"match":"rotoBrushPropagation","name":"Roto Brush Propagation","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":89,"match":"searchRadius","name":"Search Radius","value":{"t":"Scalar","v":15.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":50.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":91,"match":"motionThreshold","name":"Motion Threshold","value":{"t":"Scalar","v":10.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":92,"match":"motionDamping","name":"Motion Damping","value":{"t":"Scalar","v":20.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":93,"match":"viewSearchRegion","name":"View Search Region","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":95,"match":"rotoBrushMatte","name":"Roto Brush Matte","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":94,"match":"feather","name":"Feather","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":20.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":96,"match":"contrast","name":"Contrast","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":97,"match":"shiftEdge","name":"Shift Edge","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":-100.0,"max":100.0,"slider_min":-100.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":98,"match":"reduceChatter","name":"Reduce Chatter","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":99,"match":"object","name":"Show Object","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":32.0,"slider_min":0.0,"slider_max":32.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":101,"match":"refineEdgeMatte","name":"Refine Edge Matte","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":100,"match":"smooth","name":"Smooth","value":{"t":"Scalar","v":1.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":10.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":102,"match":"feather","name":"Feather","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":20.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":103,"match":"contrast","name":"Contrast","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":104,"match":"shiftEdge","name":"Shift Edge","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":-100.0,"max":100.0,"slider_min":-100.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":105,"match":"reduceChatter","name":"Reduce Chatter","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":106,"match":"useMotionBlur","name":"Use Motion Blur","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":108,"match":"motionBlur","name":"Motion Blur","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":107,"match":"motionBlurSamples","name":"Samples","value":{"t":"Scalar","v":11.0},"ui":{"kind":"Slider","min":1.0,"max":64.0,"slider_min":1.0,"slider_max":32.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":109,"match":"shutterAngle","name":"Shutter Angle","value":{"t":"Scalar","v":180.0},"ui":{"kind":"Slider","min":0.0,"max":720.0,"slider_min":0.0,"slider_max":360.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":110,"match":"higherQuality","name":"Higher Quality","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":111,"match":"decontaminateEdgeColors","name":"Decontaminate Edge Colors","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":113,"match":"decontamination","name":"Decontamination","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":112,"match":"decontaminationAmount","name":"Decontamination Amount","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":114,"match":"extendWhereSmoothed","name":"Extend Where Smoothed","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":115,"match":"increaseDecontaminationRadius","name":"Increase Decontamination Radius","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":20.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":116,"match":"viewDecontaminationMap","name":"View Decontamination Map","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]},{"node":"Prop","uid":117,"match":"strokes","name":"Strokes","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":118,"match":"inputKey","name":"Input Key","value":{"t":"Str","v":"7b319ce93027617c"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":119,"match":"frozen","name":"Frozen","value":{"t":"Str","v":"saved frozen"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":120,"match":"tracked","name":"Tracked","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]},{"node":"Group","uid":15,"match":"transform","name":"Transform","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":7,"match":"anchor","name":"Anchor Point","value":{"t":"Vec3","v":[80.0,60.0,0.0]},"ui":{"kind":"Point"},"spatial":true,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":2,"static_only":false},{"node":"Prop","uid":8,"match":"position","name":"Position","value":{"t":"Vec3","v":[80.0,60.0,0.0]},"ui":{"kind":"Point"},"spatial":true,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":2,"static_only":false},{"node":"Prop","uid":9,"match":"scale","name":"Scale","value":{"t":"Vec3","v":[100.0,100.0,100.0]},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":2,"static_only":false},{"node":"Prop","uid":10,"match":"orientation","name":"Orientation","value":{"t":"Vec3","v":[0.0,0.0,0.0]},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":true,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":11,"match":"rotationX","name":"X Rotation","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":true,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":12,"match":"rotationY","name":"Y Rotation","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":true,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":13,"match":"rotation","name":"Rotation","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":14,"match":"opacity","name":"Opacity","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":16,"match":"materialOptions","name":"Material Options","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":17,"match":"castsShadows","name":"Casts Shadows","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Off","On","Only"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":18,"match":"lightTransmission","name":"Light Transmission","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":19,"match":"acceptsShadows","name":"Accepts Shadows","value":{"t":"Enum","v":1},"ui":{"kind":"Popup","options":["Off","On","Only"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":20,"match":"acceptsLights","name":"Accepts Lights","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":21,"match":"ambient","name":"Ambient","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":22,"match":"diffuse","name":"Diffuse","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":23,"match":"specularIntensity","name":"Specular Intensity","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":24,"match":"specularShininess","name":"Specular Shininess","value":{"t":"Scalar","v":5.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":25,"match":"metal","name":"Metal","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]}}],"markers":[],"shutter_angle":180.0,"shutter_phase":-90.0,"motion_blur_samples":16,"motion_blur_adaptive_limit":128,"renderer":"Classic3D","hide_shy":false,"enable_motion_blur":true,"enable_frame_blending":true,"draft_3d":false,"preserve_frame_rate":false,"preserve_resolution":false,"poster_time":0,"global_light":{"angle":{"uid":0,"match":"globalLightAngle","name":"Global Light Angle","value":{"t":"Scalar","v":120.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},"altitude":{"uid":0,"match":"globalLightAltitude","name":"Global Light Altitude","value":{"t":"Scalar","v":30.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}}}}},"next_id":121} \ No newline at end of file diff --git a/crates/engine/src/tests/fixtures/analysed-0.24.ecproj.attribution b/crates/engine/src/tests/fixtures/analysed-0.24.ecproj.attribution new file mode 100644 index 000000000..06e8915f4 --- /dev/null +++ b/crates/engine/src/tests/fixtures/analysed-0.24.ecproj.attribution @@ -0,0 +1,8 @@ +asset: analysed-0.24.ecproj +title: The tracked-0.22 clip with Time Remap, a mask, Gaussian Blur and Roto Brush, keyed by EffectCraft 0.24.1 +author: arnav-hiwarkar +source: original work +license: MIT OR Apache-2.0 +license-file: ../../../../../LICENSE-MIT +added: 2026-11-12 by arnav-hiwarkar +notes: Made from tracked-0.22.ecproj with 0.24.1 engine commands (enable Time Remap, a rectangle mask, Gaussian Blur and Roto Brush), its saved analyses replaced by short stand-in strings, and the Warp Stabilizer, 3D Camera Tracker and Roto Brush keys that 0.24.1 computed for it. Written as compact JSON. No media is needed: the tests only check that the keys are kept or cleared. diff --git a/crates/engine/src/tests/fixtures/tracked-0.22.ecproj b/crates/engine/src/tests/fixtures/tracked-0.22.ecproj new file mode 100644 index 000000000..8e1d21b40 --- /dev/null +++ b/crates/engine/src/tests/fixtures/tracked-0.22.ecproj @@ -0,0 +1,1593 @@ +{ + "savedBy": "0.22.0", + "activeComp": 2, + "openComps": [ + 2 + ], + "schema": 2, + "settings": { + "bit_depth": "Bpc8", + "linearize": false, + "working_space": null, + "blend_linear": false, + "time_display": "Timecode", + "frame_start": 0, + "audio_sample_rate": 48000, + "gpu_acceleration": true, + "color_engine": "Adobe", + "hdr": "Clip", + "output_space": null, + "working_gamma": 2.2 + }, + "items": { + "1": { + "id": 1, + "name": "effectcraft-3456-shake.mp4", + "label": "Aqua", + "comment": "", + "parent": null, + "kind": { + "type": "Footage", + "path": "/tmp/effectcraft-3456-shake.mp4", + "kind": "Video", + "width": 160, + "height": 120, + "pixel_aspect": 1.0, + "frame_rate": { + "num": 12, + "den": 1 + }, + "native_rate": null, + "duration": 254016000000, + "has_video": true, + "has_audio": false, + "alpha": "Ignore", + "premul_color": [ + 0.0, + 0.0, + 0.0 + ], + "loop_count": 1, + "codec": "H.264 (High)", + "missing": false, + "color_profile": "Rec709" + } + }, + "2": { + "id": 2, + "name": "effectcraft-3456-shake", + "label": "Sandstone", + "comment": "", + "parent": null, + "kind": { + "type": "Comp", + "width": 160, + "height": 120, + "pixel_aspect": 1.0, + "frame_rate": { + "num": 12, + "den": 1 + }, + "duration": 254016000000, + "display_start": 0, + "background": [ + 0.0, + 0.0, + 0.0 + ], + "work_area": [ + 0, + 254016000000 + ], + "layers": [ + { + "id": 3, + "name": "effectcraft-3456-shake.mp4", + "source": { + "type": "Footage", + "item": 1 + }, + "label": "Aqua", + "comment": "", + "start_time": 0, + "in_point": 0, + "out_point": 254016000000, + "stretch": 100.0, + "switches": { + "video": true, + "audio": true, + "solo": false, + "locked": false, + "shy": false, + "collapse": false, + "quality": "Best", + "sampling": "Bilinear", + "effects": true, + "frame_blend": "Off", + "motion_blur": false, + "adjustment": false, + "three_d": false, + "guide": false + }, + "blend_mode": "Normal", + "preserve_transparency": false, + "track_matte": null, + "parent": null, + "markers": [], + "auto_orient": "Off", + "props": { + "uid": 4, + "match": "layer", + "name": "effectcraft-3456-shake.mp4", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Group", + "uid": 5, + "match": "masks", + "name": "Masks", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [] + }, + { + "node": "Group", + "uid": 6, + "match": "effects", + "name": "Effects", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Group", + "uid": 26, + "match": "ec.distort.warpstabilizer", + "name": "Warp Stabilizer", + "kind": { + "kind": "Effect", + "effect": "ec.distort.warpstabilizer" + }, + "enabled": true, + "children": [ + { + "node": "Group", + "uid": 28, + "match": "stabilization", + "name": "Stabilization", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 27, + "match": "result", + "name": "Result", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Smooth Motion", + "No Motion" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 29, + "match": "smoothness", + "name": "Smoothness", + "value": { + "t": "Scalar", + "v": 50.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 100.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 30, + "match": "method", + "name": "Method", + "value": { + "t": "Enum", + "v": 3 + }, + "ui": { + "kind": "Popup", + "options": [ + "Position", + "Position, Scale, Rotation", + "Perspective", + "Subspace Warp" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 31, + "match": "preserveScale", + "name": "Preserve Scale", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Group", + "uid": 33, + "match": "borders", + "name": "Borders", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 32, + "match": "framing", + "name": "Framing", + "value": { + "t": "Enum", + "v": 2 + }, + "ui": { + "kind": "Popup", + "options": [ + "Stabilize Only", + "Stabilize, Crop", + "Stabilize, Crop, Auto-scale", + "Stabilize, Synthesize Edges" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Group", + "uid": 35, + "match": "autoScale", + "name": "Auto-scale", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 34, + "match": "maximumScale", + "name": "Maximum Scale", + "value": { + "t": "Scalar", + "v": 150.0 + }, + "ui": { + "kind": "Slider", + "min": 100.0, + "max": 1000.0, + "slider_min": 100.0, + "slider_max": 200.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 36, + "match": "actionSafeMargin", + "name": "Action-safe Margin", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 45.0, + "slider_min": 0.0, + "slider_max": 20.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Prop", + "uid": 37, + "match": "additionalScale", + "name": "Additional Scale", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 1.0, + "max": 1000.0, + "slider_min": 50.0, + "slider_max": 150.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Group", + "uid": 39, + "match": "advanced", + "name": "Advanced", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 38, + "match": "detailedAnalysis", + "name": "Detailed Analysis", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 40, + "match": "rollingShutterRipple", + "name": "Rolling Shutter Ripple", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Automatic Reduction", + "Enhanced Reduction" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 41, + "match": "cropLessSmoothMore", + "name": "Crop Less <-> Smooth More", + "value": { + "t": "Scalar", + "v": 50.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 100.0, + "slider_min": 0.0, + "slider_max": 100.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 42, + "match": "synthesizeInputRange", + "name": "Synthesis Input Range (seconds)", + "value": { + "t": "Scalar", + "v": 1.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 10.0, + "slider_min": 0.0, + "slider_max": 5.0, + "decimals": 2 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 43, + "match": "synthesizeEdgeFeather", + "name": "Synthesis Edge Feather", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 100.0, + "slider_min": 0.0, + "slider_max": 100.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Group", + "uid": 45, + "match": "edgeCropping", + "name": "Synthesis Edge Cropping", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 44, + "match": "left", + "name": "Left", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 50.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 46, + "match": "top", + "name": "Top", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 50.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 47, + "match": "right", + "name": "Right", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 50.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 48, + "match": "bottom", + "name": "Bottom", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 50.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Prop", + "uid": 49, + "match": "hideWarningBanner", + "name": "Hide Warning Banner", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 50, + "match": "showTrackPoints", + "name": "Show Track Points", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 51, + "match": "trackPointSize", + "name": "Track Point Size", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 200.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Prop", + "uid": 52, + "match": "analysis", + "name": "Analysis", + "value": { + "t": "Str", + "v": "{\"version\":2,\"start\":0.0,\"frameDuration\":0.08333333333333333,\"size\":[160.0,120.0],\"detailed\":false,\"frames\":[{\"t\":[0.0,0.0],\"s\":[1.0,0.0,0.0,0.0],\"h\":[1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0],\"inliers\":0,\"features\":0},{\"t\":[-22.388798410890686,30.01868418985143],\"s\":[0.9277781961008736,-0.04422418749279422,-15.523833932787909,35.6091856999425],\"h\":[0.9277781961008736,0.04422418749279422,-15.523833932787909,-0.04422418749279422,0.9277781961008736,35.6091856999425,0.0,0.0],\"inliers\":9,\"features\":15,\"points\":[[92.3,107.9],[95.2,95.7],[92.2,103.7],[74.2,53.6],[74.3,37.4],[99.3,90.7],[82.6,41.5],[82.5,55.5],[88.5,43.5]]},{\"t\":[23.98122532957055,-1.9084399677775892],\"s\":[0.9063620953625465,-0.04409531016401132,30.797313797392007,5.599646102270199],\"h\":[0.7965841302132126,0.29995334448297317,20.168498543438005,-0.0740592055495628,1.046481410433727,-0.473260319309297,-0.002014895402579317,0.0023197947752658875],\"inliers\":10,\"features\":24,\"points\":[[118.4,97.1],[124.8,102.9],[100.5,51.5],[127.3,63.9],[127.5,45.0],[106.1,39.6],[106.2,53.7],[113.7,56.7],[52.5,35.6],[116.8,43.6]]},{\"t\":[11.687620662467452,-7.932031814223215],\"s\":[0.9951636472613027,0.0038103578382923703,12.438092774450126,-8.118641076572445],\"h\":[1.643484923435082,-0.7137632860918511,-2.5905208024072124,0.3548180400361871,0.46037059943190983,-10.538467107984474,0.004219805542554225,-0.0059212698862967],\"inliers\":9,\"features\":18,\"points\":[[132.6,73.5],[131.5,85.1],[106.5,41.5],[138.4,70.5],[143.4,74.0],[112.0,43.6],[122.5,47.5],[130.2,49.8],[149.3,58.5]]},{\"t\":[-30.310403914516613,33.907848152443364],\"s\":[1.007168616747288,0.0037069147029014813,-31.056396618707396,33.11324659331262],\"h\":[0.6198845159470996,0.0005618559126509149,-3.178267007922358,-0.13009530252511717,0.7726770220834841,43.55009577470153,-0.001720398359559105,0.00004737533435711085],\"inliers\":6,\"features\":6,\"points\":[[83.4,78.4],[111.5,91.5],[111.5,72.5],[89.0,80.3],[94.7,83.3],[92.1,67.5]]},{\"t\":[-5.583259809628714,-21.883441966142215],\"s\":[1.0031742036915483,-0.0014807972400717364,-6.0689262496146625,-22.023221544860448],\"h\":[1.1420296883900174,-0.04739597390990014,-10.605302345116598,0.09741208494601904,0.9834838974219691,-26.601790074159226,0.0009113645792746124,-0.0004613682942006241],\"inliers\":12,\"features\":26,\"points\":[[44.4,0.4],[95.7,91.4],[102.5,90.5],[96.9,82.3],[102.8,85.5],[102.6,81.2],[97.1,78.5],[127.8,90.7],[128.5,80.1],[108.6,91.2],[108.5,79.5],[105.0,77.7]]},{\"t\":[27.686733462643232,8.049769635251877],\"s\":[0.929460928303922,0.035973851378530715,35.6798165298027,9.23027450987749],\"h\":[1.008918148822829,0.1261308536278953,23.55178846805191,-0.030309790827892834,1.108836841709476,6.4896286706810855,-0.0005830225271129425,0.0013957761568033347],\"inliers\":9,\"features\":24,\"points\":[[55.5,112.5],[100.6,55.5],[100.6,69.5],[106.2,57.5],[106.1,71.6],[113.5,74.5],[76.4,61.6],[76.6,45.5],[116.6,61.6]]},{\"t\":[-2.1632428252979565,18.033956762750776],\"s\":[0.9823494564274133,-0.03858067520697906,-3.292485287213367,25.146037618301847],\"h\":[0.9579598760613574,-0.13114734456280325,2.830816183351523,0.009276438160611545,0.8429238585075404,27.816268384517308,0.00010866570427004524,-0.0010986404477924933],\"inliers\":9,\"features\":25,\"points\":[[10.2,63.8],[4.5,45.5],[53.4,60.9],[106.6,83.4],[106.6,97.6],[58.5,80.5],[71.6,85.4],[76.7,86.4],[112.4,85.5]]},{\"t\":[-30.66640840418232,-21.989852679037867],\"s\":[1.0156367307051672,0.004551071962152525,-31.763785052482092,-23.691591888755113],\"h\":[1.0156367307051672,-0.004551071962152525,-31.763785052482092,0.004551071962152525,1.0156367307051672,-23.691591888755113,0.0,0.0],\"inliers\":6,\"features\":9,\"points\":[[65.6,55.5],[68.5,58.4],[76.3,61.6],[58.5,55.9],[78.5,77.7],[43.4,48.3]]},{\"t\":[5.708740901092206,24.075281194659254],\"s\":[1.0135826886534363,-0.10515588147251018,-1.1163514746928627,27.59825643107368],\"h\":[1.1505001196625904,-0.004492526279963958,-0.5319258967829654,-0.025738957694540945,0.966887539263372,28.15190307627249,0.0007845902586792284,-0.00031935492918067597],\"inliers\":9,\"features\":24,\"points\":[[104.6,97.7],[104.8,101.6],[108.5,88.8],[103.9,89.0],[116.1,92.7],[112.4,87.8],[113.2,96.3],[47.3,72.5],[46.4,87.5]]},{\"t\":[27.779201319161004,9.926771642811133],\"s\":[0.9890321818477387,0.0013711446087583204,28.575284295787874,10.772618168795788],\"h\":[1.061498205619746,0.009950102807178602,26.602191497678987,0.03562744518371215,1.0470570180393335,7.3128067380884545,0.00040746752749711983,0.00013875206582740715],\"inliers\":19,\"features\":31,\"points\":[[101.5,91.5],[100.5,107.5],[95.4,104.6],[93.2,89.4],[62.5,94.4],[108.2,95.5],[108.2,109.3],[114.0,97.5],[89.2,102.5],[61.5,75.5],[70.5,80.5],[89.3,88.3],[114.9,111.1],[69.5,95.5],[66.5,78.5],[82.3,100.6],[76.5,82.5],[82.5,84.4],[119.1,112.0]]},{\"t\":[-18.08353148330616,-15.925984647541327],\"s\":[0.9665330472023047,-0.007772653084006622,-14.505725243709165,-11.14686987633948],\"h\":[1.396312496581232,-0.10268053165320767,-33.15101241390654,0.021275151660258673,1.173514724589782,-24.185902320422414,0.001847437675107323,-0.0003034312788189646],\"inliers\":9,\"features\":23,\"points\":[[119.3,75.5],[116.5,84.0],[121.6,82.9],[128.5,87.4],[127.6,83.0],[124.8,80.6],[128.7,71.5],[71.6,86.5],[58.4,66.5]]}],\"tracks\":[{\"id\":0,\"start\":0,\"pts\":[[121.5,16.5],[101.4,48.2],[127.2,46.6],[141.2,40.2],[111.2,74.3],[105.1,58.7],[135.1,68.5]]},{\"id\":1,\"start\":0,\"pts\":[[107.5,26.5],[85.4,56.6],[108.9,54.9],[121.0,46.9],[90.3,80.7],[82.3,64.9],[109.6,73.1],[105.7,97.1]]}]}" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 53, + "match": "analysisKey", + "name": "Analysis Key", + "value": { + "t": "Str", + "v": "f87b8df2e353c28e" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Group", + "uid": 54, + "match": "ec.perspective.cameratracker", + "name": "3D Camera Tracker", + "kind": { + "kind": "Effect", + "effect": "ec.perspective.cameratracker" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 55, + "match": "shotType", + "name": "Shot Type", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Fixed Angle of View", + "Variable Zoom", + "Specify Angle of View" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 56, + "match": "horizontalAngleOfView", + "name": "Horizontal Angle of View", + "value": { + "t": "Scalar", + "v": 40.0 + }, + "ui": { + "kind": "Slider", + "min": 1.0, + "max": 170.0, + "slider_min": 10.0, + "slider_max": 120.0, + "decimals": 1 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 57, + "match": "showTrackPoints", + "name": "Show Track Points", + "value": { + "t": "Enum", + "v": 1 + }, + "ui": { + "kind": "Popup", + "options": [ + "2D Source", + "3D Solved" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 58, + "match": "renderTrackPoints", + "name": "Render Track Points", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 59, + "match": "trackPointSize", + "name": "Track Point Size", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 300.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 60, + "match": "targetSize", + "name": "Target Size", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 1.0, + "max": 1000.0, + "slider_min": 10.0, + "slider_max": 300.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Group", + "uid": 62, + "match": "advanced", + "name": "Advanced", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 61, + "match": "solveMethod", + "name": "Solve Method", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Auto Detect", + "Typical", + "Mostly Flat Scene", + "Tripod Pan" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 63, + "match": "methodUsed", + "name": "Method Used", + "value": { + "t": "Str", + "v": "Tripod Pan" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 64, + "match": "averageError", + "name": "Average Error", + "value": { + "t": "Scalar", + "v": 0.48427435472856495 + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 65, + "match": "detailedAnalysis", + "name": "Detailed Analysis", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 66, + "match": "lensDistortion", + "name": "Solve Lens Distortion", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 67, + "match": "undistort", + "name": "Undistort Footage", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 68, + "match": "autoDeletePoints", + "name": "Auto-delete Points Across Time", + "value": { + "t": "Bool", + "v": true + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 69, + "match": "hideWarningBanner", + "name": "Hide Warning Banner", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Prop", + "uid": 70, + "match": "tracks", + "name": "Tracks", + "value": { + "t": "Str", + "v": "{\"version\":1,\"size\":[160.0,120.0],\"start\":0.0,\"frameDuration\":0.08333333333333333,\"frames\":12,\"factor\":1.0,\"detailed\":false,\"tracks\":[{\"id\":0,\"start\":0,\"pts\":[[77.5,21.5],[63.0,42.02],[84.44,46.2],[94.51,43.46],[76.29,65.76],[77.07,73.7],[83.0,80.68],[85.69,85.86],[87.92,90.96],[89.4,99.49],[90.13,103.45],[90.97,109.78]]},{\"id\":1,\"start\":0,\"pts\":[[137.5,41.5],[125.34,65.53],[144.58,68.06],[155.96,64.9],[137.55,87.17]]},{\"id\":2,\"start\":0,\"pts\":[[103.5,9.5],[85.74,29.12],[104.73,32.21],[110.44,21.58],[92.15,43.67]]},{\"id\":3,\"start\":0,\"pts\":[[104.5,29.5],[85.9,50.12],[103.93,52.29],[109.88,48.47],[92.18,70.78]]},{\"id\":4,\"start\":0,\"pts\":[[135.5,18.5],[123.93,41.77],[143.14,45.58],[156.62,36.13],[137.86,58.99],[138.18,64.4],[142.35,72.76]]},{\"id\":5,\"start\":0,\"pts\":[[145.5,43.5],[136.49,68.62],[152.24,70.07]]},{\"id\":6,\"start\":0,\"pts\":[[68.5,16.5],[54.6,38.04],[75.81,40.97],[85.89,39.76],[67.52,62.45],[65.27,69.0]]},{\"id\":7,\"start\":0,\"pts\":[[126.5,18.5],[111.0,39.74],[128.76,42.63],[136.89,32.11],[117.68,54.39]]},{\"id\":8,\"start\":1,\"pts\":[[62.5,17.5],[85.58,22.87],[94.22,13.25],[75.42,35.02],[75.53,43.03],[82.19,51.59],[83.63,56.75],[86.42,64.01],[88.28,72.0],[89.17,76.16],[88.59,83.65]]},{\"id\":9,\"start\":1,\"pts\":[[114.5,106.5],[136.85,100.86],[147.03,92.4]]},{\"id\":10,\"start\":1,\"pts\":[[72.5,23.5],[97.31,29.7],[103.74,19.02],[85.16,40.96],[87.87,50.25],[90.99,56.84],[95.55,64.14],[94.95,69.09],[98.79,80.06],[99.53,84.17],[96.16,89.83]]},{\"id\":11,\"start\":1,\"pts\":[[105.5,56.5],[123.21,58.51],[130.67,54.61],[112.22,76.63],[107.86,82.64],[110.99,88.56],[110.29,92.35],[107.8,96.22],[105.42,105.58],[106.34,109.09],[103.49,114.69]]},{\"id\":12,\"start\":1,\"pts\":[[48.5,14.5],[74.56,20.81],[80.17,10.47],[60.5,31.52]]},{\"id\":13,\"start\":1,\"pts\":[[56.5,17.5],[79.51,23.22],[88.21,13.13],[69.38,34.7],[69.5,43.04],[76.12,50.88],[77.6,55.88],[80.34,63.05],[82.34,69.83],[83.23,74.02],[82.59,80.86]]},{\"id\":14,\"start\":1,\"pts\":[[111.5,56.5],[129.28,58.38],[136.92,54.94]]},{\"id\":15,\"start\":2,\"pts\":[[111.5,35.5],[116.71,24.74],[98.61,46.94],[95.39,52.62],[97.78,59.24]]},{\"id\":16,\"start\":2,\"pts\":[[111.5,54.5],[116.45,50.61],[98.85,72.82],[95.85,78.52],[98.15,84.77]]},{\"id\":17,\"start\":2,\"pts\":[[35.5,25.5],[51.37,25.98],[29.35,47.25],[34.79,58.33],[37.82,64.46],[35.7,68.67]]},{\"id\":18,\"start\":2,\"pts\":[[65.5,37.5],[73.16,34.37],[53.32,56.61]]},{\"id\":19,\"start\":3,\"pts\":[[139.5,91.5],[121.67,103.33],[122.29,98.68],[128.91,94.42],[130.04,88.08],[132.48,82.73],[132.69,85.66],[135.56,80.73],[133.86,80.34]]},{\"id\":20,\"start\":3,\"pts\":[[128.5,27.5],[109.77,49.81],[105.68,55.33]]},{\"id\":21,\"start\":4,\"pts\":[[132.5,108.5],[134.61,103.06],[139.18,98.97]]},{\"id\":22,\"start\":4,\"pts\":[[12.5,44.5],[15.77,54.38],[21.97,62.49],[23.19,67.31],[25.95,73.59],[32.15,76.64],[31.59,80.8],[37.46,83.52]]},{\"id\":23,\"start\":5,\"pts\":[[88.5,76.5],[91.53,82.49],[96.99,88.67],[96.31,92.35]]},{\"id\":24,\"start\":5,\"pts\":[[23.5,26.5],[34.16,36.76],[31.29,40.39]]},{\"id\":25,\"start\":5,\"pts\":[[29.5,29.5],[41.15,39.45],[37.02,43.33],[44.0,51.94]]},{\"id\":26,\"start\":5,\"pts\":[[16.5,25.5],[25.23,35.61],[24.0,39.41],[27.82,47.95],[34.62,50.88],[34.62,55.8],[39.37,61.06]]},{\"id\":27,\"start\":5,\"pts\":[[12.5,21.5],[20.78,30.91],[20.0,35.48],[23.13,42.77],[30.29,46.76],[30.38,51.79],[34.65,56.39]]},{\"id\":28,\"start\":5,\"pts\":[[115.5,82.5],[118.64,88.43],[118.09,93.19],[117.39,96.49],[114.83,106.78],[114.88,110.08]]},{\"id\":29,\"start\":5,\"pts\":[[122.5,61.5],[124.31,67.9],[123.88,72.08],[123.44,76.68],[120.82,86.9],[120.84,90.61],[117.85,97.98]]},{\"id\":30,\"start\":5,\"pts\":[[120.5,66.5],[122.86,72.98],[122.45,77.21],[121.98,81.49]]},{\"id\":31,\"start\":7,\"pts\":[[130.5,110.5],[132.07,103.93],[132.1,107.25],[134.31,101.57],[134.08,101.95]]},{\"id\":32,\"start\":7,\"pts\":[[144.5,87.5],[147.64,81.13],[147.29,84.43]]},{\"id\":33,\"start\":7,\"pts\":[[149.5,87.5],[151.62,81.15],[151.6,83.45]]},{\"id\":34,\"start\":7,\"pts\":[[141.5,109.5],[142.65,102.86],[144.73,106.45]]},{\"id\":35,\"start\":7,\"pts\":[[130.5,105.5],[132.21,97.98],[132.16,101.56]]},{\"id\":36,\"start\":7,\"pts\":[[46.5,46.5],[46.28,52.04],[53.71,58.71],[53.81,63.25]]},{\"id\":37,\"start\":7,\"pts\":[[63.5,78.5],[60.78,82.81],[61.38,87.33],[61.18,91.39],[60.13,92.98]]},{\"id\":38,\"start\":7,\"pts\":[[147.5,79.5],[148.79,73.74],[148.89,76.93],[152.13,71.83],[150.74,73.15]]},{\"id\":39,\"start\":8,\"pts\":[[110.5,73.5],[108.69,82.44],[109.4,86.46],[105.45,92.92]]},{\"id\":40,\"start\":8,\"pts\":[[37.5,75.5],[39.63,77.92],[39.24,82.09],[46.3,85.66]]},{\"id\":41,\"start\":9,\"pts\":[[72.5,92.5],[72.19,96.59],[71.1,99.0]]},{\"id\":42,\"start\":9,\"pts\":[[71.5,66.5],[71.58,70.65],[69.4,74.61]]},{\"id\":43,\"start\":9,\"pts\":[[42.5,52.5],[42.63,57.29],[48.81,63.22]]},{\"id\":44,\"start\":9,\"pts\":[[65.5,63.5],[65.9,67.71],[62.84,71.25]]},{\"id\":45,\"start\":9,\"pts\":[[54.5,84.5],[54.33,88.51],[54.49,89.47]]},{\"id\":46,\"start\":9,\"pts\":[[93.5,108.5],[94.19,112.24],[95.37,117.47]]}]}" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 71, + "match": "tracksKey", + "name": "Tracks Key", + "value": { + "t": "Str", + "v": "f87b8df2e353c28e" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 72, + "match": "solve", + "name": "Solve", + "value": { + "t": "Str", + "v": "{\"version\":1,\"size\":[160.0,120.0],\"start\":0.0,\"frameDuration\":0.08333333333333333,\"shot\":\"fixedAngle\",\"methodUsed\":\"tripodPan\",\"averageError\":0.48427435472856495,\"frames\":[{\"rot\":[0.0,0.0,0.0],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.020706432791589117,-0.008075142299053078,-0.06077723052316193],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.023015120128512003,0.005766803085062508,-0.05310541732098104],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.0170200841043793,0.014154804924310056,-0.050762146721755434],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.03356753265765158,-0.00032501028659040183,-0.05939089867356119],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.03943129932097289,0.0005848011077747351,-0.08866812978617226],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.04587385659719372,0.00556317017360105,-0.0922903070481816],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.04943028885690781,0.006586719185689197,-0.1030177435734751],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.05420648867299307,0.008981748111204299,-0.12219539780340982],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.06013167434751454,0.009061063842010806,-0.02749230328481726],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.06324873745045556,0.009255262692673143,-0.0355321639175462],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.06618656945718411,0.009319774678589094,-0.015189163276848288],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true}],\"points\":[{\"id\":0,\"pos\":[-0.001884543346613208,-0.029037452307042782,0.9806051370981879],\"error\":0.56470084,\"first\":0,\"last\":11},{\"id\":1,\"pos\":[0.04710854544038102,-0.015334858559503525,1.0773487523110807],\"error\":0.4844214,\"first\":0,\"last\":4},{\"id\":2,\"pos\":[0.015277830948334362,-0.04530698241035739,1.0393293228690133],\"error\":0.3392279,\"first\":0,\"last\":4},{\"id\":3,\"pos\":[0.013625157539074177,-0.028048508549162222,1.005205908477461],\"error\":0.27458376,\"first\":0,\"last\":4},{\"id\":4,\"pos\":[0.04631029390834158,-0.03435434088491794,1.0740657193502177],\"error\":0.58201736,\"first\":0,\"last\":6},{\"id\":5,\"pos\":[0.053943894461564695,-0.013610066623604573,1.082119350918587],\"error\":0.33030823,\"first\":0,\"last\":2},{\"id\":6,\"pos\":[-0.008886582549498147,-0.03423365291632946,1.0500072858529375],\"error\":0.5071384,\"first\":0,\"last\":5},{\"id\":7,\"pos\":[0.03502079415367347,-0.03650999899856251,1.0590501262399414],\"error\":0.3427207,\"first\":0,\"last\":4},{\"id\":8,\"pos\":[-0.0010752140340087664,-0.05237350807489353,0.9970760865042246],\"error\":0.35491616,\"first\":1,\"last\":11},{\"id\":9,\"pos\":[0.04045532180900739,0.011287908043101045,1.1118602867055563],\"error\":0.35821888,\"first\":1,\"last\":3},{\"id\":12,\"pos\":[-0.012247058383356772,-0.05711454082770741,1.026095977383411],\"error\":0.7576372,\"first\":1,\"last\":4},{\"id\":13,\"pos\":[-0.0057782770174717585,-0.05312155593792027,1.002454847850506],\"error\":0.543182,\"first\":1,\"last\":11},{\"id\":14,\"pos\":[0.03444063369446883,-0.02322488536327569,1.0525377480568132],\"error\":0.5363785,\"first\":1,\"last\":3},{\"id\":15,\"pos\":[0.016549051463405264,-0.04448675703801009,1.039611880351983],\"error\":0.31473064,\"first\":2,\"last\":6},{\"id\":16,\"pos\":[0.015561268129555224,-0.024177980474891878,1.0505609541603724],\"error\":0.448273,\"first\":2,\"last\":6},{\"id\":17,\"pos\":[-0.037387500298151244,-0.046978366490905726,1.0292596184739917],\"error\":0.5814284,\"first\":2,\"last\":7},{\"id\":18,\"pos\":[-0.018963958767977365,-0.03840654941654895,1.029868839109744],\"error\":0.62771547,\"first\":2,\"last\":4},{\"id\":20,\"pos\":[0.025824410036239483,-0.04221331533850395,1.051265936102142],\"error\":0.2203965,\"first\":3,\"last\":5},{\"id\":22,\"pos\":[-0.04851356310948073,-0.04922371159135405,1.0148030992016972],\"error\":0.60021263,\"first\":4,\"last\":11},{\"id\":23,\"pos\":[0.0036124978633337353,-0.027413664985930772,0.9671987963193897],\"error\":0.2763749,\"first\":5,\"last\":8},{\"id\":24,\"pos\":[-0.040597577069465214,-0.0703196502868751,1.0235859186232383],\"error\":0.20348576,\"first\":5,\"last\":7},{\"id\":26,\"pos\":[-0.04416469175733074,-0.0698384544617488,1.0211428377131564],\"error\":0.7978787,\"first\":5,\"last\":11},{\"id\":27,\"pos\":[-0.04818954744569584,-0.07416243876625056,1.013378662747375],\"error\":0.6526291,\"first\":5,\"last\":11},{\"id\":36,\"pos\":[-0.02865646311969018,-0.06261471940209673,1.0103266984710924],\"error\":0.47229937,\"first\":7,\"last\":10},{\"id\":37,\"pos\":[-0.022363582487320836,-0.038494993762751006,0.9688013952945587],\"error\":0.5830236,\"first\":7,\"last\":11},{\"id\":39,\"pos\":[0.012856414034624068,-0.040629816490058715,0.9569374661053799],\"error\":0.26666406,\"first\":8,\"last\":11},{\"id\":40,\"pos\":[-0.039487212277480116,-0.04718518517554586,0.9962321113853498],\"error\":0.48472655,\"first\":8,\"last\":11},{\"id\":41,\"pos\":[-0.014270376399443,-0.03389203058278074,0.9480752077612952],\"error\":0.79931283,\"first\":9,\"last\":11},{\"id\":42,\"pos\":[-0.014596706636024855,-0.05446828640367654,0.9808373411559306],\"error\":0.021755833,\"first\":9,\"last\":11},{\"id\":43,\"pos\":[-0.03666075088242092,-0.06654420263172509,0.9970944504474955],\"error\":0.20362298,\"first\":9,\"last\":11},{\"id\":44,\"pos\":[-0.01908451035407613,-0.057350036080083884,0.9896103813509345],\"error\":0.18076603,\"first\":9,\"last\":11},{\"id\":45,\"pos\":[-0.028179725825267236,-0.04186664641926184,0.9918891096090983],\"error\":0.24652581,\"first\":9,\"last\":11},{\"id\":46,\"pos\":[0.0010670642752641536,-0.018463010859931878,0.8064992130555431],\"error\":0.7289736,\"first\":9,\"last\":11}]}" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 73, + "match": "solveKey", + "name": "Solve Key", + "value": { + "t": "Str", + "v": "FixedAngle||Auto|[]" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 74, + "match": "deleted", + "name": "Deleted Points", + "value": { + "t": "Str", + "v": "" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 75, + "match": "camera", + "name": "Camera Layer", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + } + ] + }, + { + "node": "Group", + "uid": 15, + "match": "transform", + "name": "Transform", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 7, + "match": "anchor", + "name": "Anchor Point", + "value": { + "t": "Vec3", + "v": [ + 80.0, + 60.0, + 0.0 + ] + }, + "ui": { + "kind": "Point" + }, + "spatial": true, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 2, + "static_only": false + }, + { + "node": "Prop", + "uid": 8, + "match": "position", + "name": "Position", + "value": { + "t": "Vec3", + "v": [ + 80.0, + 60.0, + 0.0 + ] + }, + "ui": { + "kind": "Point" + }, + "spatial": true, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 2, + "static_only": false + }, + { + "node": "Prop", + "uid": 9, + "match": "scale", + "name": "Scale", + "value": { + "t": "Vec3", + "v": [ + 100.0, + 100.0, + 100.0 + ] + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 2, + "static_only": false + }, + { + "node": "Prop", + "uid": 10, + "match": "orientation", + "name": "Orientation", + "value": { + "t": "Vec3", + "v": [ + 0.0, + 0.0, + 0.0 + ] + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": true, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 11, + "match": "rotationX", + "name": "X Rotation", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": true, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 12, + "match": "rotationY", + "name": "Y Rotation", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": true, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 13, + "match": "rotation", + "name": "Rotation", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 14, + "match": "opacity", + "name": "Opacity", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 100.0, + "slider_min": 0.0, + "slider_max": 100.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Group", + "uid": 16, + "match": "materialOptions", + "name": "Material Options", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 17, + "match": "castsShadows", + "name": "Casts Shadows", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Off", + "On", + "Only" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 18, + "match": "lightTransmission", + "name": "Light Transmission", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 19, + "match": "acceptsShadows", + "name": "Accepts Shadows", + "value": { + "t": "Enum", + "v": 1 + }, + "ui": { + "kind": "Popup", + "options": [ + "Off", + "On", + "Only" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 20, + "match": "acceptsLights", + "name": "Accepts Lights", + "value": { + "t": "Bool", + "v": true + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 21, + "match": "ambient", + "name": "Ambient", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 22, + "match": "diffuse", + "name": "Diffuse", + "value": { + "t": "Scalar", + "v": 50.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 23, + "match": "specularIntensity", + "name": "Specular Intensity", + "value": { + "t": "Scalar", + "v": 50.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 24, + "match": "specularShininess", + "name": "Specular Shininess", + "value": { + "t": "Scalar", + "v": 5.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 25, + "match": "metal", + "name": "Metal", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + } + ] + } + } + ], + "markers": [], + "shutter_angle": 180.0, + "shutter_phase": -90.0, + "motion_blur_samples": 16, + "motion_blur_adaptive_limit": 128, + "renderer": "Classic3D", + "hide_shy": false, + "enable_motion_blur": true, + "enable_frame_blending": true, + "draft_3d": false, + "preserve_frame_rate": false, + "preserve_resolution": false, + "poster_time": 0, + "global_light": { + "angle": { + "uid": 0, + "match": "globalLightAngle", + "name": "Global Light Angle", + "value": { + "t": "Scalar", + "v": 120.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + "altitude": { + "uid": 0, + "match": "globalLightAltitude", + "name": "Global Light Altitude", + "value": { + "t": "Scalar", + "v": 30.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + } + } + } + }, + "next_id": 76 +} \ No newline at end of file diff --git a/crates/engine/src/tests/fixtures/tracked-0.22.ecproj.attribution b/crates/engine/src/tests/fixtures/tracked-0.22.ecproj.attribution new file mode 100644 index 000000000..611f620f9 --- /dev/null +++ b/crates/engine/src/tests/fixtures/tracked-0.22.ecproj.attribution @@ -0,0 +1,8 @@ +asset: tracked-0.22.ecproj +title: One clip with an analysed Warp Stabilizer and 3D Camera Tracker from EffectCraft 0.22.0 +author: arnav-hiwarkar +source: original work +license: MIT OR Apache-2.0 +license-file: ../../../../../LICENSE-MIT +added: 2026-11-12 by arnav-hiwarkar +notes: Saved by the released 0.22.0 CLI after importing a generated 160x120, 12-frame shaking crop of an ffmpeg testsrc2 pattern, applying both effects and analysing them. The source path is a generic test path; the video is not needed by the tests, which only check that the saved analyses are kept or cleared. diff --git a/crates/engine/src/tests/keyframe_text.rs b/crates/engine/src/tests/keyframe_text.rs index 30d3b436e..a299899eb 100644 --- a/crates/engine/src/tests/keyframe_text.rs +++ b/crates/engine/src/tests/keyframe_text.rs @@ -480,3 +480,29 @@ fn camera_light_and_material_options_are_written_as_after_effects_does() { assert!(text.contains(block), "{block}in\n{text}"); } } + +/// The unit column of `name`'s block in copied keyframe text. +fn unit_of<'a>(text: &'a str, name: &str) -> &'a str { + let mut lines = text.lines().skip_while(|l| !l.contains(&format!("\t{name} #"))); + lines.next().unwrap_or_else(|| panic!("no {name} in\n{text}")); + lines.next().and_then(|l| l.strip_prefix("\tFrame\t")).and_then(|l| l.strip_suffix('\t')).unwrap_or_else(|| panic!("{name} in\n{text}")) +} + +/// Widening a 0..100 slider to After Effects' range (#3479, #3483, #3484) keeps the unit the +/// keyframe text writes for it. +#[test] +fn widened_effect_ranges_keep_their_keyframe_text_units() { + let (mut s, l) = session(); + s.execute("effect.apply", json!({"layer": l.0, "effect": "ec.generate.fourcolor"})).unwrap(); + let text = copy_props(&mut s, l, &["effects/#1/blend", "effects/#1/jitter"]); + assert_eq!(unit_of(&text, "Blend"), "percent"); + assert_eq!(unit_of(&text, "Jitter"), "percent"); + for fx in ["ec.noise.noisehls", "ec.noise.noisehlsauto"] { + let (mut s, l) = session(); + s.execute("effect.apply", json!({"layer": l.0, "effect": fx})).unwrap(); + let text = copy_props(&mut s, l, &["effects/#1/hue", "effects/#1/lightness", "effects/#1/saturation", "effects/#1/grainSize"]); + for (name, unit) in [("Hue", "percent"), ("Lightness", "percent"), ("Saturation", "percent"), ("Grain Size", "")] { + assert_eq!(unit_of(&text, name), unit, "{fx} {name}"); + } + } +} diff --git a/crates/engine/src/tests/legacy_analysis_keys.rs b/crates/engine/src/tests/legacy_analysis_keys.rs new file mode 100644 index 000000000..6cdb125d3 --- /dev/null +++ b/crates/engine/src/tests/legacy_analysis_keys.rs @@ -0,0 +1,127 @@ +//! Warp Stabilizer and 3D Camera Tracker analyses saved by an earlier release keep matching +//! their footage after an edit that doesn't change it (#3456), and a real change still clears them. + +use effectcraft_effects::camera_tracker::{SOLVE, TRACKS, TRACKS_KEY}; +use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY}; +use effectcraft_keyframe::Value; +use effectcraft_project::{ItemId, LayerId, Project}; +use serde_json::json; + +use crate::Session; + +const FOOTAGE: ItemId = ItemId(1); +const COMP: ItemId = ItemId(2); +const CLIP: LayerId = LayerId(3); +const WARP: u64 = 26; +const TRACKER: u64 = 54; + +/// The analysis (as its length and a hash: it's long) and key of the Warp Stabilizer and the +/// 3D Camera Tracker. +fn saved(s: &Session) -> [(usize, u64, String); 2] { + use std::hash::{Hash, Hasher}; + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let get = |uid: u64, data: &str, key: &str| { + let params = crate::camera_track::static_params(layer.props.find_group(uid).unwrap()); + let text = |id: &str| match params.get(id) { + Some(Value::Str(s)) => s.clone(), + other => panic!("{id}: {other:?}"), + }; + let analysis = text(data); + let mut h = std::collections::hash_map::DefaultHasher::new(); + analysis.hash(&mut h); + (analysis.len(), h.finish(), text(key)) + }; + [get(WARP, ANALYSIS, ANALYSIS_KEY), get(TRACKER, TRACKS, TRACKS_KEY)] +} + +fn open(json: &str) -> Session { + let mut s = Session::default(); + s.replace_project(Project::from_json(json).unwrap(), None); + s.open_comp(COMP); + s +} + +#[test] +fn analyses_saved_by_0_22_survive_edits_that_keep_their_frames() { + // Saved by the released 0.22.0 CLI after analysing both effects; its footage is offline here. + let mut s = open(include_str!("fixtures/tracked-0.22.ecproj")); + let before = saved(&s); + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + for (len, _, key) in &before { + assert!(*len > 0); + // The key predates Footage::placed_page, so it isn't today's signature. + assert_ne!(key, &crate::analysis::frames_key::signature(&s.project, COMP, layer)); + } + + // Adding to the render queue edits the project, as `effectcraft-cli render` does. + s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap(); + assert_eq!(saved(&s), before); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + + // Saved and reopened (by this version), the old keys are kept and still match. + let mut s = open(&s.project.to_json()); + s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap(); + assert_eq!(saved(&s), before); + + // Other frames, from other timing or a reinterpreted footage item: both analyses are + // cleared, and undo brings them back. + let cleared = |s: &Session| saved(s).iter().all(|(len, _, key)| *len == 0 && key.is_empty()); + s.execute_checked("layer.timing", json!({"layer": CLIP.0, "out": 0.5})).unwrap(); + assert!(cleared(&s)); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + s.execute_checked("file.interpretFootage", json!({"items": [FOOTAGE.0], "invertAlpha": true})).unwrap(); + assert!(cleared(&s)); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + // Footage framed as a placed page has other frames too, though 0.22 had no such field. + s.edit("place page", None, |p, _| { + if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(FOOTAGE).map(|i| &mut i.kind) { + f.placed_page = true; + } + Ok(()) + }) + .unwrap(); + assert!(cleared(&s)); +} + +/// Solving again reuses the 0.22 tracks rather than tracking the (here offline) footage again. +#[test] +fn camera_tracker_solves_again_from_tracks_saved_by_0_22() { + let mut s = open(include_str!("fixtures/tracked-0.22.ecproj")); + let tracks = saved(&s)[1].clone(); + let solve = |s: &Session| { + let g = s.project.comp(COMP).unwrap().layer(CLIP).unwrap().props.find_group(TRACKER).unwrap(); + crate::camera_track::static_params(g).get(SOLVE).cloned().unwrap() + }; + // Another solve method, and back, clears the solve and keeps the tracks. + for method in [1, 0] { + s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "effects/#2/advanced/solveMethod", "value": method})).unwrap(); + } + assert_eq!(solve(&s), Value::Str(String::new())); + assert_eq!(saved(&s)[1], tracks); + s.execute_checked("camera.analyze", json!({"layer": CLIP.0, "effect": TRACKER, "wait": true})).unwrap(); + assert!(matches!(solve(&s), Value::Str(v) if !v.is_empty())); + assert_eq!(saved(&s)[1], tracks); +} + +/// The footage text analysis keys are hashed from, as 0.23 saved it. A new `Footage` field must +/// not change it (or every saved analysis is dropped again). +#[test] +fn footage_signature_text_is_pinned() { + use effectcraft_project::{Footage, FootageKind}; + let f = Footage { + path: "clip.mp4".into(), + kind: FootageKind::Video, + width: 160, + height: 120, + invert_alpha: true, + page: 2, + placed_page: true, + ..Footage::default() + }; + let fields = r#"path: "clip.mp4", kind: Video, width: 160, height: 120, pixel_aspect: 1.0, frame_rate: FrameRate { num: 30, den: 1 }, native_rate: None, duration: Tick(0), has_video: false, has_audio: false, alpha: Straight, premul_color: [0.0, 0.0, 0.0], loop_count: 1, codec: "", missing: false, sequence: [], color_profile: None, layer: None, fields: Off, invert_alpha: true, linear_light: false, preserve_rgb: false, cineon: CineonSettings { log_conversion: false, converted_black: 0.0, converted_white: 1023.0, black: 95.0, white: 685.0, gamma: 1.7, rolloff: 20.0, units: TenBit }, data: None, page: 2, alphabetical: false, start_timecode: None, file_timecode: None, markers: []"#; + assert_eq!(crate::analysis::frames_key::legacy::footage_text(&f, false, true), format!("Footage {{ {fields}, placed_page: true }}")); + assert_eq!(crate::analysis::frames_key::legacy::footage_text(&f, false, false), format!("Footage {{ {fields} }}")); +} diff --git a/crates/engine/src/tests/lut_files.rs b/crates/engine/src/tests/lut_files.rs new file mode 100644 index 000000000..98c95652a --- /dev/null +++ b/crates/engine/src/tests/lut_files.rs @@ -0,0 +1,227 @@ +//! A LUT file that changes on disk renders again (#3493): Apply Color LUT and Lumetri's Input +//! LUT name a `.cube` file; an edit to it, or a file created, deleted or repaired, shows on the +//! next render of the same frame, from warm layer caches in memory and on disk, through a precomp +//! and a layer reading that precomp, and a frame kept on disk made with the old file is refused. + +use std::path::Path; +use std::time::{Duration, UNIX_EPOCH}; + +use serde_json::{Value, json}; + +use crate::Session; +use crate::render::RenderOpts; +use effectcraft_project::ItemId; +use effectcraft_render::disk_cache::{DiskCache, comp_content_key, frame_key}; +use effectcraft_render::reads::ReadLog; +use effectcraft_time::Tick; + +/// Every input to black, or to white (1D, two entries: the same size, so only the modification +/// time tells the two apart). +const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; +const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; +const GREY: f32 = 128.0 / 255.0; + +/// Write `text` to `path` with its modification time `secs` after the epoch. +fn write(path: &Path, text: &str, secs: u64) { + std::fs::write(path, text).unwrap(); + let f = std::fs::File::options().write(true).open(path).unwrap(); + f.set_modified(UNIX_EPOCH + Duration::from_secs(secs)).unwrap(); +} + +/// A session, its layer buffers written to a disk cache in `disk` when given. +fn session(disk: Option<&Path>) -> Session { + let mut s = Session::default(); + if let Some(dir) = disk { + s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": dir.to_string_lossy(), "disk.diskCacheEnabled": true}})).unwrap(); + s.disk_cache.as_ref().unwrap().set_min_layer_ms(0); + } + s +} + +/// Comp "Grade": a grey solid graded by `effect` (`params` set on it). Comp "Shot" shows it as a +/// precomp layer, under a solid that copies the precomp's channels (Set Channels): that layer is +/// cached with what the precomp shows. Returns (Grade, Shot). +fn shot(s: &mut Session, effect: &str, params: &[(&str, Value)]) -> (ItemId, ItemId) { + s.execute_checked("comp.new", json!({"name": "Shot", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap(); + let shot = s.active_comp_id().unwrap(); + let plate = s.execute_checked("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 8, "height": 8})).unwrap()["layer"].clone(); + s.execute_checked("effect.apply", json!({"layer": plate, "effect": effect})).unwrap(); + for (path, value) in params { + s.execute_checked("prop.set", json!({"layer": plate, "path": format!("effects/#1/{path}"), "value": value})).unwrap(); + } + let pre = s.execute_checked("layer.precompose", json!({"layers": [plate], "name": "Grade"})).unwrap(); + let grade = ItemId(pre["comp"].as_u64().unwrap()); + let copy = s.execute_checked("layer.newSolid", json!({"name": "Copy", "color": "#00ff00", "width": 8, "height": 8})).unwrap()["layer"].clone(); + s.execute_checked("effect.apply", json!({"layer": copy, "effect": "Set Channels"})).unwrap(); + for i in 1..=3 { + s.execute_checked("prop.set", json!({"layer": copy, "path": format!("effects/#1/sourceLayer{i}"), "value": pre["layer"]})).unwrap(); + } + (grade, shot) +} + +/// The red and green of the centre of both comps' first frame. +fn colours(s: &Session, (grade, shot): (ItemId, ItemId)) -> [f32; 4] { + let at = |comp| { + let img = s.render(comp, Tick::ZERO, RenderOpts::default()); + img.get(i64::from(img.width / 2), i64::from(img.height / 2)) + }; + let (g, c) = (at(grade), at(shot)); + [g[0], g[1], c[0], c[1]] +} + +#[track_caller] +fn assert_all(got: [f32; 4], want: f32) { + assert!(got.iter().all(|v| (v - want).abs() < 0.01), "{got:?}, want {want}"); +} + +#[test] +fn an_edited_lut_file_renders_again_from_warm_caches() { + let dir = tempfile::tempdir().unwrap(); + let lut = dir.path().join("grade.cube"); + write(&lut, BLACK, 1_000); + let mut s = session(None); + let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]); + assert_all(colours(&s, comps), 0.0); + let misses = s.layer_cache.stats().misses; + assert_all(colours(&s, comps), 0.0); + assert_eq!(s.layer_cache.stats().misses, misses, "an unchanged file keeps the cached layers"); + // A frame on disk made with the file names it. + let frames = DiskCache::open(dir.path().join("frames"), 1 << 30).unwrap(); + let key = frame_key(comp_content_key(&s.project, comps.1), 0, 1000, 0); + let log = ReadLog::new(); + let mut r = s.renderer(RenderOpts::default()); + r.reads = Some(&log); + let _ = r.comp_frame(comps.1, Tick::ZERO); + let files = log.into_files(); + assert!(files.get(&lut.to_string_lossy()).is_some(), "the render notes the LUT file: {files:?}"); + frames.put_frame_now(key, 1, 1, &[0; 4], &files); + assert!(frames.get_frame(key, None).is_some()); + let generation = effectcraft_effects::lut_generation(); + write(&lut, WHITE, 2_000); + assert_all(colours(&s, comps), 1.0); + assert!(effectcraft_effects::lut_generation() > generation, "the viewer's frames made before are dropped"); + assert!(frames.get_frame(key, None).is_none(), "the frame on disk made with the old file"); +} + +#[test] +fn an_edited_lut_file_is_not_served_from_the_disk_cache() { + let dir = tempfile::tempdir().unwrap(); + let (lut, disk) = (dir.path().join("grade.cube"), dir.path().join("cache")); + write(&lut, BLACK, 1_000); + let mut s = session(Some(&disk)); + let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]); + assert_all(colours(&s, comps), 0.0); + let dc = s.disk_cache.clone().unwrap(); + dc.flush(); + assert!(dc.stats().entries > 0, "layer buffers written"); + let project = s.project.clone(); + drop((s, dc)); + // A restart on the same cache, after the file changed. + write(&lut, WHITE, 2_000); + let mut s = session(Some(&disk)); + s.project = project; + s.bump(); + assert_all(colours(&s, comps), 1.0); +} + +#[test] +fn a_lut_file_created_deleted_or_repaired_renders_again() { + let dir = tempfile::tempdir().unwrap(); + let lut = dir.path().join("later.cube"); + let mut s = session(None); + let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]); + assert_all(colours(&s, comps), GREY); + write(&lut, WHITE, 1_000); + assert_all(colours(&s, comps), 1.0); + std::fs::remove_file(&lut).unwrap(); + assert_all(colours(&s, comps), GREY); + write(&lut, "not a LUT", 2_000); + assert_all(colours(&s, comps), GREY); + write(&lut, BLACK, 3_000); + assert_all(colours(&s, comps), 0.0); +} + +#[test] +fn lumetri_follows_its_input_lut_file() { + let dir = tempfile::tempdir().unwrap(); + let lut = dir.path().join("input.cube"); + write(&lut, BLACK, 1_000); + let mut s = session(None); + let comps = shot(&mut s, "Lumetri Color", &[("basicCorrection/inputLut", json!(1)), ("basicCorrection/inputLutFile", json!(lut.to_string_lossy()))]); + assert_all(colours(&s, comps), 0.0); + write(&lut, WHITE, 2_000); + assert_all(colours(&s, comps), 1.0); +} + +/// A precomp instance whose Essential Property names another LUT file follows that file, also +/// for a layer that reads the instance through a layer parameter. +#[test] +fn an_overridden_lut_file_renders_again() { + let dir = tempfile::tempdir().unwrap(); + let (base, overridden) = (dir.path().join("base.cube"), dir.path().join("override.cube")); + write(&base, WHITE, 1_000); + write(&overridden, BLACK, 1_000); + let mut s = session(None); + s.execute_checked("comp.new", json!({"name": "Grade", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap(); + let grade = s.active_comp_id().unwrap(); + let plate = s.execute_checked("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 8, "height": 8})).unwrap()["layer"].clone(); + s.execute_checked("effect.apply", json!({"layer": plate, "effect": "Apply Color LUT"})).unwrap(); + s.execute_checked("prop.set", json!({"layer": plate, "path": "effects/#1/lut", "value": base.to_string_lossy()})).unwrap(); + let control = s.execute_checked("essential.addProperty", json!({"layer": plate, "path": "effects/#1/lut", "name": "LUT"})).unwrap()["controls"][0].clone(); + s.execute_checked("comp.new", json!({"name": "Shot", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap(); + let shot = s.active_comp_id().unwrap(); + let instance = s.execute_checked("layer.addItem", json!({"item": grade.0})).unwrap()["layer"].clone(); + s.execute_checked("essential.set", json!({"layer": instance, "control": control, "value": overridden.to_string_lossy()})).unwrap(); + let copy = s.execute_checked("layer.newSolid", json!({"name": "Copy", "color": "#00ff00", "width": 8, "height": 8})).unwrap()["layer"].clone(); + s.execute_checked("effect.apply", json!({"layer": copy, "effect": "Set Channels"})).unwrap(); + for i in 1..=3 { + s.execute_checked("prop.set", json!({"layer": copy, "path": format!("effects/#1/sourceLayer{i}"), "value": instance})).unwrap(); + } + let centre = |s: &Session| { + let img = s.render(shot, Tick::ZERO, RenderOpts::default()); + let p = img.get(i64::from(img.width / 2), i64::from(img.height / 2)); + [p[0], p[1], p[0], p[1]] + }; + assert_all(centre(&s), 0.0); + write(&overridden, WHITE, 2_000); + assert_all(centre(&s), 1.0); +} + +/// #3538: OCIO File Transform and a custom OCIO config (and the LUT it names) follow their files +/// through warm layer caches, and a render notes the config's LUT for the disk cache. +#[test] +fn ocio_files_render_again_from_warm_caches() { + let dir = tempfile::tempdir().unwrap(); + let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts/grade.cube")); + std::fs::create_dir_all(dir.path().join("luts")).unwrap(); + write(&lut, BLACK, 1_000); + write(&grade, BLACK, 1_000); + let text = "ocio_profile_version: 2\nsearch_path: luts\nroles:\n scene_linear: lin\ncolorspaces:\n - !\n name: lin\n - !\n name: graded\n to_reference: ! {src: grade.cube, interpolation: linear}\n"; + write(&config, text, 1_000); + let mut s = session(None); + let file = shot(&mut s, "OCIO File Transform", &[("file", json!(lut.to_string_lossy()))]); + let custom = shot( + &mut s, + "OCIO Color Space Transform", + &[("config", json!(1)), ("configFile", json!(config.to_string_lossy())), ("sourceName", json!("graded")), ("destinationName", json!("lin"))], + ); + // A render notes the LUT the config names (a frame on disk is made of it too). + let log = ReadLog::new(); + let mut r = s.renderer(RenderOpts::default()); + r.reads = Some(&log); + let _ = r.comp_frame(custom.1, Tick::ZERO); + let files = log.into_files(); + assert!(files.get(&grade.to_string_lossy()).is_some(), "the render notes the config's LUT: {files:?}"); + assert_all(colours(&s, file), 0.0); + assert_all(colours(&s, custom), 0.0); + let misses = s.layer_cache.stats().misses; + assert_all(colours(&s, file), 0.0); + assert_all(colours(&s, custom), 0.0); + assert_eq!(s.layer_cache.stats().misses, misses, "unchanged files keep the cached layers"); + let generation = effectcraft_effects::lut_generation(); + write(&lut, WHITE, 2_000); + assert_all(colours(&s, file), 1.0); + write(&grade, WHITE, 2_000); + assert_all(colours(&s, custom), 1.0); + assert!(effectcraft_effects::lut_generation() > generation, "the viewer's frames made before are dropped"); +} diff --git a/crates/engine/src/tests/mask_warp.rs b/crates/engine/src/tests/mask_warp.rs index 5387fe562..e884091a5 100644 --- a/crates/engine/src/tests/mask_warp.rs +++ b/crates/engine/src/tests/mask_warp.rs @@ -391,6 +391,15 @@ fn warp_analysis_invalidates_and_cancels() { let fx = r["effect"].as_u64().unwrap(); let cid = s.active_comp_id().unwrap(); assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true); + // A mask is part of the analysed input (#3535): drawing one clears the analysis, undo keeps it. + s.execute_checked("mask.new", json!({"layer": clip.0, "vertices": [[10, 10], [200, 10], [200, 150]]})).unwrap(); + assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], false); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true); + // An effect below it isn't. + s.execute_checked("effect.apply", json!({"layers": [clip.0], "effect": "ec.blur.gaussian"})).unwrap(); + assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true); + s.execute_checked("edit.undo", json!({})).unwrap(); // Trimming the layer clears the analysis and queues it again. s.execute("layer.timing", json!({"layers": [clip.0], "out": 0.8})).unwrap(); let st = s.execute("warp.status", json!({})).unwrap(); diff --git a/crates/engine/src/tests/session.rs b/crates/engine/src/tests/session.rs index b253640e7..020c2daf0 100644 --- a/crates/engine/src/tests/session.rs +++ b/crates/engine/src/tests/session.rs @@ -96,6 +96,25 @@ fn imported_files_go_into_the_comp_where_they_were_dropped() { assert!(s.execute("layer.addItem", json!({"item": "a.png", "position": [1.0]})).is_err(), "position needs x and y"); } +/// What an import left out of a file (a 3D model's textures over the limits) comes back in the +/// import's `warnings`. +#[test] +fn what_an_import_left_out_is_a_warning() { + use effectcraft_project::{Footage, FootageKind}; + struct Probe; + impl crate::Importer for Probe { + fn probe(&self, path: &str) -> Result { + Ok(Footage { path: path.into(), kind: FootageKind::Model, ..Default::default() }) + } + fn probe_noting(&self, path: &str) -> Result<(Footage, Option), String> { + Ok((self.probe(path)?, Some(format!("{path}: texture `a.png` left out")))) + } + } + let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths": ["/m/scene.obj"]})).unwrap(); + assert_eq!(r["warnings"], json!(["/m/scene.obj: texture `a.png` left out"])); +} + /// #270: files dropped or picked in the Import dialog (`file.import {background}`) are probed in /// a background job that says which file it is reading and how many are left; then they arrive /// in one undo step, all selected, with a count. The same file imported again arrives again. diff --git a/crates/engine/src/tests/timeline.rs b/crates/engine/src/tests/timeline.rs index b5a44239b..291ad884e 100644 --- a/crates/engine/src/tests/timeline.rs +++ b/crates/engine/src/tests/timeline.rs @@ -1581,3 +1581,28 @@ fn a_typed_component_moves_its_follow_components_by_each_layers_own_change() { let keys: Vec> = prop(&s, b, "audio/levels").keys.iter().map(|k| k.value.components()).collect(); assert_eq!(keys, vec![vec![-20.0, -30.0], vec![-4.0, -34.0]], "B's 1 s key rises 6 dB on both channels"); } + +#[test] +fn convert_expression_to_keyframes_refuses_a_layer_of_millions_of_frames() { + let (mut s, l) = setup(); + s.execute("prop.setExpression", json!({"layer": l, "path": "transform/rotation", "expression": "value"})).unwrap(); + // A saved Out point a million seconds after the In point. + let cid = s.active_comp_id().unwrap(); + std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(l)).unwrap().out_point = + effectcraft_time::Tick::from_seconds_f64(1e6); + let e = s.execute("prop.convertExpressionToKeyframes", json!({"layer": l, "path": "transform/rotation"})).unwrap_err().to_string(); + assert!(e.contains("at most"), "{e}"); + assert!(prop(&s, l, "transform/rotation").keys.is_empty()); +} + +#[test] +fn convert_expression_to_keyframes_refuses_a_zero_frame_duration() { + let (mut s, l) = setup(); + s.execute("prop.setExpression", json!({"layer": l, "path": "transform/rotation", "expression": "value"})).unwrap(); + // A saved frame rate of 0/1 s has a frame duration of 0: the sampling loop never advanced. + let cid = s.active_comp_id().unwrap(); + std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().frame_rate.den = 0; + let e = s.execute("prop.convertExpressionToKeyframes", json!({"layer": l, "path": "transform/rotation"})).unwrap_err().to_string(); + assert!(e.contains("frame duration"), "{e}"); + assert!(prop(&s, l, "transform/rotation").keys.is_empty()); +} diff --git a/crates/engine/src/tests/vector_import.rs b/crates/engine/src/tests/vector_import.rs index 2f41b16b2..6372ffb35 100644 --- a/crates/engine/src/tests/vector_import.rs +++ b/crates/engine/src/tests/vector_import.rs @@ -320,6 +320,41 @@ fn paste_svg_markup_as_a_shape_layer() { assert_eq!(s.active_comp().unwrap().layers.len(), 1); } +#[test] +fn pasted_svg_pattern_keeps_geometry_and_editable_fallback_paint() { + let (mut s, _) = text_session(); + let svg = r##" + + + + + + + + "##; + let result = s.execute_checked("edit.pasteSvg", json!({"svg": svg})).unwrap(); + let layer_id = effectcraft_project::LayerId(result["layer"].as_u64().unwrap()); + let layer = s.active_comp().unwrap().layer(layer_id).unwrap(); + let shape = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned").unwrap(); + let items: Vec<_> = shape.sub("contents").unwrap().groups().collect(); + assert!(items.iter().any(|item| item.match_id == "rect"), "the editable geometry remains"); + let fill = items.iter().find(|item| item.match_id == "fill").expect("fallback fill remains editable"); + assert_eq!(fill.get("color").unwrap().value, KV::Color([1.0, 0.0, 0.0, 0.5])); + let stroke = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-stroke").unwrap(); + let items: Vec<_> = stroke.sub("contents").unwrap().groups().collect(); + assert!(items.iter().any(|item| item.match_id == "path"), "the editable stroke path remains"); + let stroke = items.iter().find(|item| item.match_id == "stroke").expect("fallback stroke remains editable"); + assert_eq!(stroke.get("color").unwrap().value, KV::Color([0.0, 0.0, 1.0, 0.25])); + let no_fallback = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-no-fallback").unwrap(); + let items: Vec<_> = no_fallback.sub("contents").unwrap().groups().collect(); + assert!(items.iter().any(|item| item.match_id == "rect"), "the editable geometry remains without a fallback"); + assert!(!items.iter().any(|item| item.match_id == "fill"), "pattern paint without a fallback is omitted"); + let no_fallback_stroke = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-stroke-no-fallback").unwrap(); + let items: Vec<_> = no_fallback_stroke.sub("contents").unwrap().groups().collect(); + assert!(items.iter().any(|item| item.match_id == "path"), "the editable stroke geometry remains without a fallback"); + assert!(!items.iter().any(|item| item.match_id == "stroke"), "pattern stroke without a fallback is omitted"); +} + #[test] fn paste_svg_rejects_text_that_is_not_usable_svg() { let (mut s, _) = text_session(); diff --git a/crates/engine/src/tests/viewer.rs b/crates/engine/src/tests/viewer.rs index 31197b2a8..a356aa192 100644 --- a/crates/engine/src/tests/viewer.rs +++ b/crates/engine/src/tests/viewer.rs @@ -346,6 +346,263 @@ fn shape_path(s: &Session, lid: u64, uid: u64) -> effectcraft_keyframe::ShapePat l.props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone() } +#[test] +fn toggle_closed_respects_path_and_vertex_selection() { + let mut s = comp(); + let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let lid = a["layer"].as_u64().unwrap(); + let a = a["path"].as_u64().unwrap(); + let b = s.execute("shape.newPath", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap()["path"].as_u64().unwrap(); + let leaf = layer(&s, lid).props.find_group(a).unwrap().get("path").unwrap().uid; + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(lid), leaf)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, lid, a).closed); + assert!(shape_path(&s, lid, b).closed, "an unselected sibling stays closed"); + s.state.selected_props = vec![(LayerId(lid), b)]; + s.state.selected_vertices = vec![crate::VertexRef { layer: LayerId(lid), mask: a, index: 1 }]; + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(shape_path(&s, lid, a).closed, "selected points and properties both describe target paths"); + assert!(shape_path(&s, lid, b).closed); + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(lid), a), (LayerId(lid), leaf), (LayerId(lid), b)]; + let r = s.execute("path.toggleClosed", json!({})).unwrap(); + assert_eq!(r["paths"], json!(2)); + assert!(!shape_path(&s, lid, a).closed); + assert!(!shape_path(&s, lid, b).closed); + s.execute("edit.undo", json!({})).unwrap(); + assert!(shape_path(&s, lid, a).closed); + assert!(shape_path(&s, lid, b).closed, "all paths undo in one step"); + s.execute("mask.setClosed", json!({"layer": lid, "mask": a, "closed": false})).unwrap(); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(false), "a mixed selection is unchecked"); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(shape_path(&s, lid, a).closed); + assert!(shape_path(&s, lid, b).closed, "a mixed selection closes all paths"); + s.state.selected_props.clear(); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, lid, a).closed); + assert!(!shape_path(&s, lid, b).closed, "layer selection addresses all editable paths"); +} + +#[test] +fn toggle_closed_combines_property_and_shape_group_selections() { + let mut s = comp(); + let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let (lid, a_path) = (a["layer"].as_u64().unwrap(), a["path"].as_u64().unwrap()); + let b = s.execute("shape.newPath", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap(); + let (b_path, b_group) = (b["path"].as_u64().unwrap(), b["group"].as_u64().unwrap()); + let c_path = + s.execute("shape.newPath", json!({"layer": lid, "vertices": [[20, 20], [80, 20], [80, 80]], "closed": true})).unwrap()["path"].as_u64().unwrap(); + s.execute("prop.select", json!({"layer": lid, "prop": a_path})).unwrap(); + s.execute("prop.select", json!({"layer": lid, "prop": b_group, "add": true})).unwrap(); + assert!(s.state.selected_vertices.iter().all(|v| v.mask == a_path), "only the selected path group implies selected vertices"); + assert!(!s.state.selected_vertices.is_empty()); + assert!(s.state.selected_props.contains(&(LayerId(lid), b_group))); + let result = s.execute("path.toggleClosed", json!({})).unwrap(); + assert_eq!(result["paths"], json!(2)); + assert!(!shape_path(&s, lid, a_path).closed); + assert!(!shape_path(&s, lid, b_path).closed, "the added shape group is included alongside implied vertices"); + assert!(shape_path(&s, lid, c_path).closed, "unselected sibling stays unchanged"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(shape_path(&s, lid, a_path).closed); + assert!(shape_path(&s, lid, b_path).closed, "both selected paths undo together"); + assert!(shape_path(&s, lid, c_path).closed); +} + +#[test] +fn toggle_closed_ignores_selections_retained_on_other_layers() { + let mut s = comp(); + let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let (a_layer, a_path) = (a["layer"].as_u64().unwrap(), a["path"].as_u64().unwrap()); + let b_layer = s.execute("layer.newShape", json!({"kind": "none"})).unwrap()["layer"].as_u64().unwrap(); + assert!(s.state.selected_vertices.iter().any(|v| v.layer == LayerId(a_layer)), "insertion retains old vertices"); + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert!(shape_path(&s, a_layer, a_path).closed); + + let b_path = + s.execute("shape.newPath", json!({"layer": b_layer, "vertices": [[0, 0], [50, 0], [50, 50]], "closed": true})).unwrap()["path"].as_u64().unwrap(); + s.execute("prop.select", json!({"layer": b_layer, "prop": b_path})).unwrap(); + s.execute("layer.selectNext", json!({})).unwrap(); + assert_eq!(s.state.selected_layers, vec![LayerId(a_layer)]); + assert!(s.state.selected_vertices.iter().any(|v| v.layer == LayerId(b_layer)), "navigation retains old vertices"); + assert!(s.state.selected_props.contains(&(LayerId(b_layer), b_path))); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true)); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, a_layer, a_path).closed); + assert!(shape_path(&s, b_layer, b_path).closed, "the deselected layer stays unchanged"); + s.execute("layer.selectPrevious", json!({})).unwrap(); + assert_eq!(s.state.selected_layers, vec![LayerId(b_layer)]); + s.execute("prop.select", json!({"layer": b_layer, "path": "transform/position"})).unwrap(); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true), "a non-path property falls back to the layer's paths"); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, b_layer, b_path).closed); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("layer.selectNext", json!({})).unwrap(); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(shape_path(&s, a_layer, a_path).closed, "a property retained on another layer cannot block this layer"); + assert!(shape_path(&s, b_layer, b_path).closed); +} + +#[test] +fn toggle_closed_falls_back_from_stale_selection_and_rejects_locked_or_pathless_layers() { + let mut s = comp(); + let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let (lid, uid) = (r["layer"].as_u64().unwrap(), r["path"].as_u64().unwrap()); + let before = s.project.clone(); + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(lid), u64::MAX)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, lid, uid).closed, "a stale property selection falls back to the layer's paths"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.project.same_content(&before)); + s.state.selected_props.clear(); + s.state.selected_vertices = vec![crate::VertexRef { layer: LayerId(lid), mask: uid, index: usize::MAX }]; + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, lid, uid).closed, "a stale vertex selection falls back to the layer's paths"); + s.execute("edit.undo", json!({})).unwrap(); + s.state.selected_vertices.clear(); + let cid = s.active_comp_id().unwrap(); + std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap().switches.locked = true; + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert!(shape_path(&s, lid, uid).closed); + s.execute("layer.newShape", json!({"kind": "rect"})).unwrap(); + s.state.selected_props.clear(); + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); +} + +#[test] +fn toggle_closed_handles_masks_and_preserves_explicit_set_closed() { + let mut s = comp(); + let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap(); + let uid = s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); + let path = |s: &Session| layer(s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); + let original = path(&s); + let other = s.execute("mask.new", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); + let other_closed = |s: &Session| layer(s, lid).props.find_group(other).unwrap().get("path").unwrap().value.as_path().unwrap().closed; + let feather = layer(&s, lid).props.find_group(uid).unwrap().get("feather").unwrap().uid; + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(lid), feather)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!path(&s).closed, "selecting Mask Feather selects its mask"); + assert!(other_closed(&s), "an unselected mask stays closed"); + assert!(layer(&s, lid).props.find_group(uid).unwrap().get("path").unwrap().keys.is_empty(), "a static path gains no keyframe"); + s.state.selected_props = vec![(LayerId(lid), uid)]; + s.execute("mask.setClosed", json!({"layer": lid, "mask": uid})).unwrap(); + assert_eq!(path(&s), original, "explicit API still defaults to closed"); + s.execute("mask.setClosed", json!({"layer": lid, "mask": uid, "closed": false})).unwrap(); + assert!(!path(&s).closed); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert_eq!(path(&s), original); + let cid = s.active_comp_id().unwrap(); + let g = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap().props.find_group_mut(uid).unwrap(); + if let effectcraft_project::GroupKind::Mask { locked, .. } = &mut g.kind { + *locked = true; + } + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert_eq!(path(&s), original); + assert!(other_closed(&s), "a selected locked mask does not fall back to its unlocked siblings"); +} + +#[test] +fn toggle_closed_recomputes_roto_bezier_tangents() { + let mut s = comp(); + let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap(); + let uid = + s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); + s.execute("path.rotoBezier", json!({"layer": lid, "value": true})).unwrap(); + let path = |s: &Session| layer(s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); + let closed = path(&s); + assert_ne!(closed.out_tangents[0], [0.0; 2], "a closed RotoBezier path has tangents at every vertex"); + s.state.selected_props = vec![(LayerId(lid), uid)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + let open = path(&s); + assert!(!open.closed); + assert_eq!((open.in_tangents[0], open.out_tangents[3]), ([0.0; 2], [0.0; 2]), "open ends lose their automatic tangents"); + assert_ne!(open.out_tangents[1], [0.0; 2]); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert_eq!(path(&s), closed, "reclosing restores the closed RotoBezier tangents"); +} + +#[test] +fn toggle_closed_fits_short_tangent_lists() { + let mut s = comp(); + let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap(); + let uid = s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); + let cid = s.active_comp_id().unwrap(); + let layer_mut = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap(); + let prop = layer_mut.props.find_group_mut(uid).unwrap().get_mut("path").unwrap(); + let KV::Path(path) = &mut prop.value else { panic!("not a path") }; + // A file can store fewer tangents than vertices (#1250). + path.in_tangents.clear(); + path.out_tangents.truncate(1); + s.state.selected_props = vec![(LayerId(lid), uid)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + let path = layer(&s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); + assert!(!path.closed); + assert_eq!((path.in_tangents.len(), path.out_tangents.len()), (3, 3)); +} + +#[test] +fn toggle_closed_edits_layer_time_and_roundtrips() { + use effectcraft_keyframe::Keyframe; + let mut s = comp(); + let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let (lid, uid) = (r["layer"].as_u64().unwrap(), r["path"].as_u64().unwrap()); + let cid = s.active_comp_id().unwrap(); + let original = shape_path(&s, lid, uid); + let second = Tick::from_seconds_f64(1.0); + let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap(); + layer.start_time = second; + layer.stretch = 200.0; + let prop = layer.props.find_group_mut(uid).unwrap().get_mut("path").unwrap(); + prop.keys = vec![Keyframe::new(Tick::ZERO, KV::Path(original.clone())), Keyframe::new(second, KV::Path(original.clone()))]; + let keys = prop.keys.clone(); + s.execute("time.set", json!({"time": 3.0})).unwrap(); + s.execute("path.toggleClosed", json!({})).unwrap(); + let prop = s.project.comp(cid).unwrap().layer(LayerId(lid)).unwrap().props.find_group(uid).unwrap().get("path").unwrap(); + assert_eq!(prop.keys.len(), 2); + assert_eq!(prop.keys[0], keys[0], "the other keyframe is untouched"); + let mut opened = original; + opened.closed = false; + assert_eq!(prop.value_at(second), KV::Path(opened.clone())); + assert!(prop.value_at(Tick::from_seconds_f64(0.5)).as_path().unwrap().closed, "the earlier segment keeps its closedness"); + let bytes = serde_json::to_vec(&*s.project).unwrap(); + let restored: effectcraft_project::Project = serde_json::from_slice(&bytes).unwrap(); + let prop = restored.comp(cid).unwrap().layer(LayerId(lid)).unwrap().props.find_group(uid).unwrap().get("path").unwrap(); + assert_eq!(prop.value_at(second), KV::Path(opened)); + s.execute("time.set", json!({"time": 2.0})).unwrap(); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true)); + s.execute("time.set", json!({"time": 3.0})).unwrap(); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(false)); +} + +#[test] +fn toggle_closed_rejects_excessive_group_nesting_without_an_edit() { + use effectcraft_project::build::{self, Ids}; + let mut s = comp(); + let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let lid = LayerId(r["layer"].as_u64().unwrap()); + let cid = s.active_comp_id().unwrap(); + let project = std::sync::Arc::make_mut(&mut s.project); + let mut next = project.next_id; + let contents = project.comp_mut(cid).unwrap().layer_mut(lid).unwrap().props.sub_mut("contents").unwrap(); + let node = contents.children.first_mut().unwrap(); + let mut nested = node.as_group().unwrap().clone(); + for _ in 0..130 { + nested = build::shape_group(&mut Ids(&mut next), "Nested", vec![nested]); + } + *node = effectcraft_project::Node::Group(nested); + project.next_id = next; + let before = s.project.clone(); + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert!(s.project.same_content(&before)); +} + #[test] fn shape_pen_builds_shape_group_and_renders() { let mut s = comp(); diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 2687eadad..d9af7b2aa 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -321,7 +321,7 @@ async fn sequence(cx: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) let mut i = 0; while i < st.total { let end = (i + batch).min(st.total); - let ks: Vec = (i..end).filter(|k| !(cx.settings.skip_existing && out::exists(cx.sink, &sequence_path(cx.path, f0 + *k as i64)))).collect(); + let ks: Vec = (i..end).filter(|k| !(cx.settings.skip_existing && cx.frame_exists(&sequence_path(cx.path, f0 + *k as i64)))).collect(); let written: Vec> = cx .frames(comp, ks, |k, img| { let path = sequence_path(cx.path, f0 + k as i64); diff --git a/crates/export/src/pipeline.rs b/crates/export/src/pipeline.rs index d447e0980..a0e4980ec 100644 --- a/crates/export/src/pipeline.rs +++ b/crates/export/src/pipeline.rs @@ -894,6 +894,20 @@ impl<'a> Cx<'a> { } } + /// Whether Skip Existing finds `path` already written: at its own place or, with Use Storage + /// Overflow, in any overflow folder (checked before a frame is placed, so a skipped frame + /// reserves no quota). + pub fn frame_exists(&self, path: &str) -> bool { + if out::exists(self.sink, path) { + return true; + } + if !self.job.settings.storage_overflow { + return false; + } + let Some(name) = std::path::Path::new(path).file_name() else { return false }; + self.job.options.overflow.iter().any(|dir| out::exists(self.sink, &std::path::Path::new(dir).join(name).to_string_lossy())) + } + /// Where a file goes: `path`, or (Use Storage Overflow) the first overflow folder with room /// for `bytes` when the quota hook says the output volume is full. pub fn place(&self, path: &str, bytes: u64) -> String { diff --git a/crates/export/tests/it/render_settings.rs b/crates/export/tests/it/render_settings.rs index 99e3d9c19..ddad4336e 100644 --- a/crates/export/tests/it/render_settings.rs +++ b/crates/export/tests/it/render_settings.rs @@ -444,6 +444,54 @@ fn cancelled_export_removes_only_files_it_opened() { std::fs::remove_dir_all(dir).unwrap(); } +/// Skip Existing keeps a frame that is already in the overflow folder the frame is placed in +/// (it checked only the primary destination, then truncated the overflow file). +#[test] +fn skip_existing_keeps_a_frame_in_the_overflow_folder() { + use std::path::PathBuf; + // Room only in the second overflow folder; the frame already sits in the first (which is full). + struct Overflow(PathBuf); + impl StorageQuota for Overflow { + fn has_room(&self, path: &str, _: u64) -> bool { + std::path::Path::new(path).starts_with(&self.0) + } + } + let guard = tempfile::tempdir().unwrap(); + let (dir, full, over) = (guard.path().to_path_buf(), guard.path().join("full"), guard.path().join("over")); + std::fs::create_dir_all(&full).unwrap(); + std::fs::create_dir_all(&over).unwrap(); + std::fs::write(full.join("clip_00000.png"), b"keep").unwrap(); + let quota = Overflow(over.clone()); + let (p, cid) = project(FrameRate::new(25, 1), |_, _| {}); + let settings = RenderSettings { skip_existing: true, storage_overflow: true, ..Default::default() }; + let om = OutputModule::for_format(OutputFormat::PngSequence); + let path = dir.join("clip_[#####].png"); + let result = export( + &Job { + project: &p, + footage: &NoFootage, + expr: None, + accel: None, + comp: cid, + settings: &settings, + output: &om, + path: path.to_str().unwrap(), + sink: None, + nested_switches: true, + options: JobOptions { + storage: Some("a), + overflow: vec![full.to_string_lossy().into_owned(), over.to_string_lossy().into_owned()], + ..Default::default() + }, + }, + &mut |_| true, + ); + assert!(result.is_ok(), "{result:?}"); + assert_eq!(std::fs::read(full.join("clip_00000.png")).unwrap(), b"keep"); + assert!(!over.join("clip_00000.png").exists(), "no duplicate in another overflow folder"); + assert!(over.join("clip_00001.png").exists(), "the other frames are still written"); +} + /// A GPU compositor stand-in that renders every frame solid green (the CPU draws the bar and the /// block on black) and keeps Auto's timing history. #[derive(Default)] diff --git a/crates/expr/src/host.rs b/crates/expr/src/host.rs index 43400ea1d..c397299ae 100644 --- a/crates/expr/src/host.rs +++ b/crates/expr/src/host.rs @@ -9,7 +9,8 @@ use effectcraft_geom::{Mat3, Mat4}; use effectcraft_keyframe::Value; -use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property}; +use effectcraft_project::ae_order::{self, AeChild}; +use effectcraft_project::{Comp, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property}; use effectcraft_render::EvalCtx; use effectcraft_time::Tick; @@ -272,6 +273,19 @@ fn node_resp(path: String, n: &Node, index: usize) -> Resp { ]) } +/// A top-level slot the layer has no node for, as group data: `@marker` (the markers, built by the +/// prelude) or `@absent` (an empty group, as After Effects shows an unused slot). +fn slot_resp(path: &str, s: &ae_order::AeSlot, index: usize) -> Resp { + Resp::List(vec![ + Resp::Str(path.into()), + Resp::Bool(true), + Resp::Str(s.name.into()), + Resp::Str(s.match_name.into()), + Resp::Num(0.0), + Resp::Num(index as f64), + ]) +} + fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> { match key { Key::Index(i) => usize::try_from(*i).ok().filter(|i| *i >= 1).and_then(|i| g.children.get(i - 1)), @@ -283,6 +297,9 @@ fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> { .find(|n| n.match_id() == m) .or_else(|| g.children.iter().find(|n| n.name().eq_ignore_ascii_case(name))) .or_else(|| g.children.iter().find(|n| compact(n.name()) == c || compact(n.match_id()) == c)) + // An effect by its After Effects match name, an imported placeholder's effect id + // (`effect("Pseudo/0.25")`; its match id is one path segment, `Pseudo_0_25`). + .or_else(|| g.children.iter().find(|n| matches!(n.as_group().map(|g| &g.kind), Some(GroupKind::Effect { effect }) if effect == name))) } } } @@ -348,7 +365,36 @@ impl<'a> Resolver<'a> { let uid = segs.get(keep - 1)?.strip_prefix('@')?.parse::().ok()?; let index = parent.children.iter().position(|c| c.uid() == uid)?; let n = parent.children.get(index)?; - Some(node_resp(group_path, n, index + 1)) + // A top-level group's number is After Effects' (see `ae_order`). + let number = if keep == 1 { ae_order::ae_index(l, n.match_id()) } else { None }.unwrap_or(index + 1); + Some(node_resp(group_path, n, number)) + } + + /// A child of a layer (`group` empty) or of one of its groups, by name or 1-based number. + fn child(&self, comp: u64, layer: u64, group: &str, key: &Key) -> Option { + let l = self.layer(comp, layer)?; + // A layer's numbers are After Effects' (Marker is 1, unused groups keep their slot), and so + // are its match names (`thisLayer("ADBE Effect Parade")`, as scripts such as Karton write). + let slot = match key { + Key::Index(i) => usize::try_from(*i).ok(), + Key::Name(name) => ae_order::ae_index_of_match_name(l, name), + }; + if group.is_empty() + && ae_order::ae_slots(&l.source).is_some() + && let Some(i) = slot + { + return Some(match ae_order::ae_child(l, i)? { + AeChild::Node(n) => node_resp(format!("@{}", n.uid()), n, i), + AeChild::Marker => slot_resp("@marker", &ae_order::MARKER, 1), + AeChild::Absent(s) => slot_resp("@absent", s, i), + }); + } + let g = if group.is_empty() { &l.props } else { l.props.group(group)? }; + let n = find_child(g, key)?; + let index = if group.is_empty() { ae_order::ae_index(l, n.match_id()) } else { None } + .unwrap_or_else(|| g.children.iter().position(|c| c.uid() == n.uid()).unwrap_or(0) + 1); + let path = if group.is_empty() { format!("@{}", n.uid()) } else { format!("{group}/@{}", n.uid()) }; + Some(node_resp(path, n, index)) } fn try_resolve(&self, req: &Req) -> Option { @@ -403,14 +449,7 @@ impl<'a> Resolver<'a> { Resp::Bool(l.switches.video), ]) } - Req::Child { comp, layer, group, key } => { - let l = self.layer(*comp, *layer)?; - let g = if group.is_empty() { &l.props } else { l.props.group(group)? }; - let n = find_child(g, key)?; - let index = g.children.iter().position(|c| c.uid() == n.uid()).unwrap_or(0) + 1; - let path = if group.is_empty() { format!("@{}", n.uid()) } else { format!("{group}/@{}", n.uid()) }; - node_resp(path, n, index) - } + Req::Child { comp, layer, group, key } => return self.child(*comp, *layer, group, key), Req::Ancestor { comp, layer, path, up } => return self.ancestor(*comp, *layer, path, *up), Req::PropInfo { comp, layer, path } => { let (l, p) = self.prop(*comp, *layer, path)?; @@ -423,7 +462,10 @@ impl<'a> Resolver<'a> { Some(g) => l.props.group(g)?, None => &l.props, }; - g.children.iter().position(|n| format!("@{}", n.uid()) == last).map(|i| i + 1) + let i = g.children.iter().position(|n| format!("@{}", n.uid()) == last)?; + // A top-level property (an enabled Time Remap) has After Effects' number. + let top = if parent.is_none() { g.children.get(i).and_then(|n| ae_order::ae_index(l, n.match_id())) } else { None }; + Some(top.unwrap_or(i + 1)) }); Resp::List(vec![ Resp::Str(p.name.clone()), diff --git a/crates/expr/src/prelude.js b/crates/expr/src/prelude.js index 9307973d8..a57145568 100644 --- a/crates/expr/src/prelude.js +++ b/crates/expr/src/prelude.js @@ -495,6 +495,8 @@ function __mod(a, d) { return ((a % d) + d) % d; } function __child(c, l, group, key) { var info = __h(__CHILD, c, l, group, key); if (info === null) return undefined; + // `thisLayer(1)` is the layer's markers, as in After Effects (see `ae_order`). + if (group === '' && info[0] === '@marker') return new Markers(c, l); return info[1] ? __mkGroup(c, l, info) : __mkProp(c, l, info[0]); } diff --git a/crates/expr/src/tests.rs b/crates/expr/src/tests.rs index d16f1dd54..a80f47b82 100644 --- a/crates/expr/src/tests.rs +++ b/crates/expr/src/tests.rs @@ -1376,6 +1376,28 @@ fn checkbox_and_dropdown_results() { assert_close!(f.ev(f.b, ROT, "effect('Dropdown Menu Control')('Menu') * 10", 0.0).unwrap().as_f64(), 10.0); } +/// An effect EffectCraft does not have (an imported After Effects placeholder, #3087) is read by +/// name like any other: its parameters by their names, a popup 1-based. It is also found by its +/// After Effects match name, its effect id (the group's match id is one path segment). +#[test] +fn an_unknown_effects_parameters_are_read_by_name() { + let mut f = fx(); + let g = group_push(&mut f.p, |ids| { + let mut g = ids.group("Pseudo_0_25", "Settings"); + g.kind = effectcraft_project::GroupKind::Effect { effect: "Pseudo/0.25".into() }; + g.children.push(ids.prop("param1", "Speed", Value::Scalar(3.0)).into()); + g.children.push(ids.prop("param2", "Mode", Value::Enum(1)).into()); + g + }); + f.layer_mut(f.b).props.sub_mut("effects").unwrap().children.push(g.into()); + assert_close!(f.ev(f.b, ROT, "effect('Settings')('Speed') * 2", 0.0).unwrap().as_f64(), 6.0); + assert_close!(f.ev(f.b, ROT, "effect('Settings')('Mode') * 10", 0.0).unwrap().as_f64(), 20.0); + assert_close!(f.ev(f.b, ROT, "effect('Settings')(1)", 0.0).unwrap().as_f64(), 3.0); + assert_close!(f.ev(f.b, ROT, "effect('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0); + assert_close!(f.ev(f.b, ROT, "thisLayer('Effects')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0); + assert_close!(f.ev(f.b, ROT, "thisLayer('ADBE Effect Parade')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0); +} + #[test] fn syntax_error_reports_line() { let f = fx(); @@ -2025,6 +2047,7 @@ fn an_expression_cant_change_the_prelude_for_the_next() { } } +mod ae_layer_order; mod property_group; /// Timing harness for the prelude's cost on the evaluation path. Ignored: it is a measurement, not diff --git a/crates/expr/src/tests/ae_layer_order.rs b/crates/expr/src/tests/ae_layer_order.rs new file mode 100644 index 000000000..dc97a991c --- /dev/null +++ b/crates/expr/src/tests/ae_layer_order.rs @@ -0,0 +1,98 @@ +//! A layer's top-level numbers are After Effects' (`project::ae_order`): Marker is 1, and slots the +//! layer does not use (Time Remap, Motion Trackers, Layer Styles…) keep their place. Rigs that read +//! a palette by number, such as `comp("Palette").layer(1)(4)(n)(1)` on a shape layer, failed +//! silently before: `(4)` reached Transform, the expression's `try` fell back to the stored value and +//! every linked colour rendered near-black. + +use super::*; +use effectcraft_project::Property; + +/// The fixture with a Slider Control (value 7) on layer "Shape". +fn with_shape_slider() -> Fx { + let mut f = fx(); + let spec = effectcraft_effects::find("ec.control.slider").unwrap(); + let mut slider = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Swatch 1", [20.0, 20.0])); + slider.prop_mut("slider").unwrap().value = Value::Scalar(7.0); + f.layer_mut(f.shape).props.sub_mut("effects").unwrap().children.push(slider.into()); + f +} + +fn yes(f: &Fx, cond: &str) -> f64 { + f.num(&format!("({cond}) ? 1 : 0"), 0.0) +} + +#[test] +fn effects_by_number_on_a_shape_layer_is_four() { + let f = with_shape_slider(); + // The Ray Dynamic Color lookup: layer(1)(4)(swatch)(1). + assert_close!(f.num("thisComp.layer('Shape')(4)(1)(1)", 0.0), 7.0); + assert_close!(f.num("try { thisComp.layer('Shape')(4)(1)(1) } catch (e) { -1 }", 0.0), 7.0); +} + +#[test] +fn effects_by_number_on_a_solid_is_five() { + let f = fx(); + assert_close!(f.num("thisComp.layer('A')(5)(1)(1)", 0.0), 42.0); + assert_close!(f.num("thisComp.layer('A')(5)('Slider Control')('Slider')", 0.0), 42.0); +} + +#[test] +fn top_level_names_follow_after_effects() { + let f = fx(); + assert_close!(yes(&f, "thisComp.layer('A')(4).name == 'Masks'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('A')(5).name == 'Effects'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('A')(6).name == 'Transform'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('Shape')(2).name == 'Contents'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('Shape')(5).name == 'Transform'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('Title')(2).name == 'Text'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('Title')(4).name == 'Effects'"), 1.0); + assert_close!(f.num("thisComp.layer('A')(6)('Position')[0]", 0.0), 50.0); +} + +#[test] +fn one_is_the_markers() { + let f = fx(); + assert_close!(f.num("thisComp.layer('A')(1).numKeys", 0.0), 2.0); + assert_close!(f.num("thisComp.layer('A')(1).key(2).time", 0.0), 4.0); +} + +#[test] +fn an_unused_slot_is_an_empty_group() { + let f = fx(); + // Layer Styles (7) and Data (12) exist in After Effects before they are used. + assert_close!(yes(&f, "thisComp.layer('A')(7).name == 'Layer Styles'"), 1.0); + assert_close!(f.num("thisComp.layer('A')(12).numProperties", 0.0), 0.0); + assert_close!(f.num("try { thisComp.layer('A')(12)(1); 1 } catch (e) { -1 }", 0.0), -1.0); + // Past the last slot there is nothing. + assert_close!(f.num("try { thisComp.layer('A')(16); 1 } catch (e) { -1 }", 0.0), -1.0); +} + +#[test] +fn property_index_of_a_top_level_group_is_after_effects() { + let f = fx(); + assert_close!(f.num("thisComp.layer('A').effect('Slider Control').propertyGroup(1).propertyIndex", 0.0), 5.0); + assert_close!(f.num("thisComp.layer('A')('Transform').propertyIndex", 0.0), 6.0); + assert_close!(f.num("thisComp.layer('Shape')('Contents').propertyIndex", 0.0), 2.0); +} + +#[test] +fn top_level_groups_by_after_effects_match_name() { + // Karton's expressions: thisLayer("ADBE Effect Parade")("…"). + let f = with_shape_slider(); + assert_close!(f.num("thisComp.layer('A')('ADBE Effect Parade')('Slider Control')('Slider')", 0.0), 42.0); + assert_close!(f.num("thisComp.layer('Shape')('ADBE Effect Parade')(1)(1)", 0.0), 7.0); + assert_close!(f.num("thisComp.layer('A')('ADBE Transform Group')('Position')[0]", 0.0), 50.0); + assert_close!(f.num("thisComp.layer('A')('ADBE Marker').numKeys", 0.0), 2.0); + assert_close!(f.num("thisComp.layer('A')('ADBE Effect Parade').propertyIndex", 0.0), 5.0); +} + +#[test] +fn an_enabled_time_remap_is_number_two() { + // Enabled Time Remap is a property at the top of the tree; After Effects numbers it 2. + let mut f = fx(); + let uid = f.p.next_id; + f.p.next_id += 1; + f.layer_mut(f.a).props.children.insert(0, Property::new(uid, "timeRemap", "Time Remap", Value::Scalar(0.0)).into()); + assert_close!(f.num("thisComp.layer('A')('Time Remap').propertyIndex", 0.0), 2.0); + assert_close!(f.num("thisComp.layer('A')(2).propertyIndex", 0.0), 2.0); +} diff --git a/crates/gpu/src/fx_generate.rs b/crates/gpu/src/fx_generate.rs index 893208a15..2dda38f45 100644 --- a/crates/gpu/src/fx_generate.rs +++ b/crates/gpu/src/fx_generate.rs @@ -385,7 +385,7 @@ fn four_color(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option { p.f[4 + i] = ctx.params.color(&format!("positionsColors/color{}", i + 1)); } let k = effectcraft_effects::four_color_softening(ctx.params.f("blend"), b.scale); - let jitter = (ctx.params.f("jitter") / 100.0).clamp(0.0, 1.0) as f32; + let jitter = effectcraft_effects::four_color_jitter(ctx.params.f("jitter")); p.u[0] = [gen_mode(ctx.params.e("blendingMode")), ctx.seed, 0, 0]; p.f[8] = [k as f32, jitter, ctx.params.f("opacity") as f32 / 100.0, 0.0]; run(e, "gen_fourcolor", &p, b, None, None) diff --git a/crates/gpu/src/shaders/fx_tone.wgsl b/crates/gpu/src/shaders/fx_tone.wgsl index bb206adbd..9472d63f0 100644 --- a/crates/gpu/src/shaders/fx_tone.wgsl +++ b/crates/gpu/src/shaders/fx_tone.wgsl @@ -40,7 +40,16 @@ fn fxt_lv(i: u32, v: f32, clip_b: bool, clip_w: bool) -> f32 { if (clip_w) { t = min(t, 1.0); } - return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * fxt_gamma(t, max(data[o + 2u], 0.01)); + // color2::LEVELS_IC_CURVE_LIMIT keeps the curve finite. WGSL leaves an overflowing pow + // indeterminate, so a curve past the bound saturates before pow: |t|^(1/g) > 1e30 once + // log2|t| / g > 99.66; between 1e30 and 2^99.7 the clamp gives the same 1e30. + // A branch, not select: select evaluates both sides, so pow would still run. + let g = max(data[o + 2u], 0.01); + var curve = sign(t) * 1e30; + if (!(abs(t) > 1.0 && log2(abs(t)) / g > 99.7)) { + curve = clamp(fxt_gamma(t, g), -1e30, 1e30); + } + return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * curve; } // color_fx::level (data offset o: ib, iw, g, ob, ow, clip black, clip white). diff --git a/crates/gpu/src/tests/fx_distort.rs b/crates/gpu/src/tests/fx_distort.rs index 1b8621408..6fc18f3c9 100644 --- a/crates/gpu/src/tests/fx_distort.rs +++ b/crates/gpu/src/tests/fx_distort.rs @@ -38,6 +38,8 @@ fn twirl_bulge_ripple_wave_warp() { #[test] fn turbulent_displace_and_cc_lens() { effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(20.0))]); + // #3470: After Effects' maximum Random Seed. + effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(20.0)), ("evolutionOptions/randomSeed", n(100000.0))]); effect_case( "ec.distort.turbulentdisplace", &[("displacement", e(1)), ("complexity", n(3.5)), ("evolution", n(90.0)), ("size", n(25.0)), ("pinning", e(2)), ("resizeLayer", on())], diff --git a/crates/gpu/src/tests/fx_gen2.rs b/crates/gpu/src/tests/fx_gen2.rs index 620cced13..1c19725e1 100644 --- a/crates/gpu/src/tests/fx_gen2.rs +++ b/crates/gpu/src/tests/fx_gen2.rs @@ -40,6 +40,8 @@ fn closed_form() { env_case("ec.generate.beam", &[]); env_case("ec.generate.beam", &[("length", n(70.0)), ("time", n(40.0)), ("softness", n(0.0)), ("perspective3d", off()), ("compositeOnOriginal", off())]); env_case("ec.generate.beam", &[("startThickness", n(3.0)), ("endThickness", n(20.0)), ("insideColor", c(0.3, 0.9, 1.0))]); + // #3475: After Effects' maximum thickness. + env_case("ec.generate.beam", &[("startThickness", n(0.0)), ("endThickness", n(4000.0))]); env_case("ec.generate.lensflare", &[]); env_case("ec.generate.lensflare", &[("lensType", e(1)), ("flareCenter", pt(50.0, 30.0)), ("blendWithOriginal", n(30.0))]); env_case("ec.generate.lensflare", &[("lensType", e(2)), ("flareBrightness", n(160.0))]); diff --git a/crates/gpu/src/tests/fx_generate.rs b/crates/gpu/src/tests/fx_generate.rs index d12920797..f8482b5ab 100644 --- a/crates/gpu/src/tests/fx_generate.rs +++ b/crates/gpu/src/tests/fx_generate.rs @@ -83,6 +83,11 @@ fn wipes() { effect_case("ec.transition.radialwipe", &[("completion", n(45.0)), ("wipe", e(1)), ("center", pt(30.2, 19.6))]); effect_case("ec.transition.radialwipe", &[("completion", n(60.0)), ("wipe", e(2)), ("startAngle", n(-40.0)), ("feather", n(3.0))]); effect_case("ec.transition.radialwipe", &[("completion", n(0.0)), ("feather", n(20.0))]); + // #3472-#3474: the ends of After Effects' ranges (a Feather wider than 8 blinds is the CPU's + // even veil). + effect_case("ec.transition.venetian", &[("completion", n(40.0)), ("width", n(1.0)), ("feather", n(6.0))]); + effect_case("ec.transition.venetian", &[("completion", n(40.0)), ("width", n(32000.0)), ("feather", n(32000.0))]); + effect_case("ec.transition.radialwipe", &[("completion", n(40.0)), ("feather", n(32000.0))]); effect_case("ec.transition.gradientwipe", &[("completion", n(40.0))]); effect_case("ec.transition.gradientwipe", &[("completion", n(55.0)), ("softness", n(30.0)), ("invert", b(true))]); effect_case("ec.transition.gradientwipe", &[("completion", n(100.0))]); @@ -147,6 +152,8 @@ fn generators() { ); effect_case("ec.generate.checkerboard", &[("sizeFrom", e(0)), ("corner", pt(16.0, 11.0)), ("color", c(0.9, 0.3, 0.1)), ("blendingMode", e(1))]); effect_case("ec.generate.grid", &[("width", n(12.0)), ("border", n(3.0))]); + // #3476: a border wider than the cells (After Effects' maximum). + effect_case("ec.generate.grid", &[("width", n(12.0)), ("border", n(2000.0))]); effect_case( "ec.generate.grid", &[ @@ -167,6 +174,8 @@ fn generators() { effect_case("ec.generate.fourcolor", &[]); effect_case("ec.generate.fourcolor", &[("blend", n(40.0)), ("jitter", n(50.0)), ("opacity", n(80.0)), ("blendingMode", e(3))]); effect_case("ec.generate.fourcolor", &[("blend", n(600.0)), ("blendingMode", e(16)), ("positionsColors/point2", pt(30.0, 20.0))]); + // #3478, #3479: the top of After Effects' ranges. + effect_case("ec.generate.fourcolor", &[("blend", n(10000.0)), ("jitter", n(500.0))]); } #[test] diff --git a/crates/gpu/src/tests/fx_noise.rs b/crates/gpu/src/tests/fx_noise.rs index 7d13004ee..006128c73 100644 --- a/crates/gpu/src/tests/fx_noise.rs +++ b/crates/gpu/src/tests/fx_noise.rs @@ -164,6 +164,8 @@ fn noise_alpha_and_hls() { effect_case("ec.noise.noisehls", &[("hue", n(30.0)), ("lightness", n(20.0)), ("saturation", n(40.0))]); effect_case("ec.noise.noisehls", &[("noise", e(1)), ("lightness", n(50.0)), ("noisePhase", n(200.0))]); effect_case("ec.noise.noisehls", &[("noise", e(2)), ("hue", n(60.0)), ("saturation", n(25.0)), ("grainSize", n(3.0))]); + // #3483, #3484: the ends of After Effects' ranges. + effect_case("ec.noise.noisehls", &[("noise", e(2)), ("hue", n(1000.0)), ("lightness", n(1000.0)), ("saturation", n(1000.0)), ("grainSize", n(0.0))]); effect_case("ec.noise.noisehlsauto", &[("noise", e(0)), ("hue", n(20.0)), ("lightness", n(30.0)), ("noiseAnimationSpeed", n(7.0))]); } diff --git a/crates/gpu/src/tests/fx_stylize.rs b/crates/gpu/src/tests/fx_stylize.rs index 63d93f207..8c6c7be33 100644 --- a/crates/gpu/src/tests/fx_stylize.rs +++ b/crates/gpu/src/tests/fx_stylize.rs @@ -109,6 +109,8 @@ fn arbitrary_map_signed_fractional_and_near_zero_wraps() { #[test] fn scatter_brush_strokes() { effect_case("ec.stylize.scatter", &[("amount", n(5.0))]); + // #3477: After Effects' maximum, far beyond the layer. + effect_case("ec.stylize.scatter", &[("amount", n(1000.0))]); effect_case("ec.stylize.scatter", &[("amount", n(3.0)), ("grain", e(1))]); effect_case("ec.stylize.scatter", &[("amount", n(7.0)), ("grain", e(2)), ("randomizeEveryFrame", on())]); effect_case("ec.stylize.brushstrokes", &[]); diff --git a/crates/gpu/src/tests/fx_tone.rs b/crates/gpu/src/tests/fx_tone.rs index 40bc9483f..3083f5949 100644 --- a/crates/gpu/src/tests/fx_tone.rs +++ b/crates/gpu/src/tests/fx_tone.rs @@ -29,6 +29,17 @@ fn levels_and_gamma() { ); effect_case("ec.color.levelsic", &[("green/greenInBlack", n(0.2)), ("green/greenInWhite", n(0.6)), ("clipToOutputWhite", e(0))]); effect_case("ec.color.levelsic", &[("alpha/alphaOutBlack", n(0.3))]); + // #3487-#3491: the ends of the valid ranges, the curve bounded where gamma 0 would overflow. + effect_case( + "ec.color.levelsic", + &[ + ("rgb/rgbInWhite", n(0.2)), + ("rgb/rgbGamma", n(0.0)), + ("red/redOutBlack", n(-10000.0)), + ("blue/blueOutWhite", n(10000.0)), + ("clipToOutputWhite", e(0)), + ], + ); effect_case("ec.color.levels", &[("redInBlack", n(0.1)), ("greenGamma", n(1.5)), ("blueOutWhite", n(0.7)), ("inWhite", n(0.9))]); effect_case("ec.color.levels", &[("alphaInWhite", n(0.6)), ("redInWhite", n(0.5)), ("redClipToOutputWhite", e(0))]); effect_case("ec.color.gammapedestalgain", &[("redGamma", n(1.4)), ("greenPedestal", n(0.1)), ("blueGain", n(0.8))]); @@ -70,6 +81,8 @@ fn colour_replacement() { &[("amount", n(100.0)), ("color", c(0.8, 0.4, 0.3)), ("matchColors", e(1)), ("tolerance", n(5.0)), ("edgeSoftness", n(30.0))], ); effect_case("ec.color.changecolor", &[("hueTransform", n(90.0)), ("colorToChange", c(0.7, 0.5, 0.4)), ("matchingSoftness", n(20.0))]); + // #3480: near the top of After Effects' range (four and three quarter turns). + effect_case("ec.color.changecolor", &[("hueTransform", n(1710.0)), ("colorToChange", c(0.7, 0.5, 0.4)), ("matchingSoftness", n(20.0))]); effect_case( "ec.color.changecolor", &[ @@ -188,3 +201,33 @@ fn color_stabilizer() { fn gradient_ramp_matches_the_cpu() { effect_case("ec.generate.gradientramp", &[]); } + +/// #3487-#3491: at the ends of the valid ranges the GPU's Levels (Individual Controls) output is +/// finite (the CPU / GPU comparison counts infinity on both sides as equal). +#[test] +fn levels_ic_is_finite_at_the_ends_of_its_ranges() { + let Some(g) = crate::tests::gpu() else { return }; + let spec = effectcraft_effects::find("ec.color.levelsic").unwrap(); + let size = [16.0, 8.0]; + let mut params = + effectcraft_effects::Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, size))).collect() }; + for (k, v) in [ + ("rgb/rgbInWhite", n(0.2)), + ("rgb/rgbGamma", n(0.0)), + ("red/redOutBlack", n(-10000.0)), + ("blue/blueOutWhite", n(10000.0)), + ("green/greenOutWhite", n(0.0)), + ("clipToOutputWhite", e(0)), + ] { + params.values.insert(k.to_string(), v); + } + let mut img = crate::tests::pattern(7, 16, 8); + for p in &mut img.data { + *p = p.map(|v| v * 3.0); + } + let buf = effectcraft_effects::Buf { img, offset: [0.0, 0.0], scale: 1.0 }; + let ctx = effectcraft_effects::EffectCtx { params: ¶ms, time: 0.0, layer_size: size, seed: 1, adjustment: false, env: Default::default() }; + let out = effectcraft_render::Accelerator::effects(g, &[effectcraft_render::FxStep { spec, ctx }], &buf, None) + .expect("the GPU runs Levels (Individual Controls)"); + assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "{:?}", out.img.data.iter().find(|p| p.iter().any(|v| !v.is_finite()))); +} diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index 843a06123..7212fd730 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -20,6 +20,9 @@ impl Importer for MediaImporter { fn probe(&self, path: &str) -> Result { effectcraft_media::probe(path).map_err(|e| e.to_string()) } + fn probe_noting(&self, path: &str) -> Result<(Footage, Option), String> { + effectcraft_media::probe_noting(path).map_err(|e| e.to_string()) + } } /// Render Queue export via `effectcraft-export`: to the file system, or to `sink` (the web app diff --git a/crates/media/src/gif_anim.rs b/crates/media/src/gif_anim.rs index 7fefe73e9..8453b50ac 100644 --- a/crates/media/src/gif_anim.rs +++ b/crates/media/src/gif_anim.rs @@ -86,7 +86,18 @@ impl Anim { if crate::webp_anim::is_webp(bytes) { return crate::webp_anim::load(bytes); } - let dec = GifDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?; + let mut dec = GifDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?; + // A frame may be far larger than the canvas, and the decoder allocates its buffer before + // decoding it: no single buffer may pass what all the frames may hold. + let mut limits = image::Limits::no_limits(); + limits.max_alloc = Some(MAX_BYTES as u64); + image::ImageDecoder::set_limits(&mut dec, limits).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?; + // The decoder allocates the full logical canvas for the first frame, however small the + // frames themselves are: check it before decoding any. + let (w, h) = image::ImageDecoder::dimensions(&dec); + if u64::from(w) * u64::from(h) * 4 > MAX_BYTES as u64 { + return Err(MediaError::Unsupported(format!("GIF canvas of {w}×{h} is too large to hold in memory"))); + } let (mut frames, mut starts) = (Vec::new(), Vec::new()); let (mut at, mut size) = (0i64, 0usize); for frame in dec.into_frames() { @@ -172,6 +183,17 @@ mod tests { assert_eq!(colour_at(&pool, &f, 5.0), [0.0, 0.0, 1.0]); } + #[test] + fn a_frame_far_larger_than_the_canvas_is_refused_before_it_is_allocated() { + // A 1×1 canvas and a 20000×20000 frame (1.6 GB of RGBA); the data itself is not there. + let mut bytes = b"GIF89a".to_vec(); + // (a two-entry global colour table, so the frame gets as far as its buffer) + bytes.extend([1, 0, 1, 0, 0x80, 0, 0, 0, 0, 0, 255, 255, 255]); + bytes.extend([0x2c, 0, 0, 0, 0, 0x20, 0x4e, 0x20, 0x4e, 0, 2, 0]); + let e = crate::gif_anim::Anim::load(&bytes).err().expect("refused").to_string(); + assert!(e.to_lowercase().contains("memory"), "{e}"); + } + #[test] fn a_zero_delay_is_ten_hundredths_like_in_browsers() { let f = probe_bytes("a.gif", gif(&[(RED, 0), (GREEN, 1)]).into()).unwrap(); @@ -205,4 +227,18 @@ mod tests { assert!(pool.frame_at(&f, Tick::ZERO).is_err()); let _ = probe_bytes("a.gif", bytes.into()); } + + #[test] + fn a_huge_canvas_is_refused_before_decoding() { + // A 65535×65535 logical screen (16 GiB of RGBA) holding one 1×1 frame. + let mut out = Vec::new(); + { + let mut enc = gif::Encoder::new(&mut out, u16::MAX, u16::MAX, &[]).unwrap(); + for _ in 0..2 { + enc.write_frame(&gif::Frame::from_rgb(1, 1, &RED)).unwrap(); + } + } + let e = super::Anim::load(&out).err().unwrap(); + assert!(e.to_string().contains("too large"), "{e}"); + } } diff --git a/crates/media/src/layered.rs b/crates/media/src/layered.rs index 64ade9394..adc23cf31 100644 --- a/crates/media/src/layered.rs +++ b/crates/media/src/layered.rs @@ -119,7 +119,7 @@ pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) - if u64::from(w) * u64::from(h) > u64::from(MAX_VECTOR_SIDE) * u64::from(MAX_VECTOR_SIDE) { return Err(MediaError::Decode(format!("{path}: {w}×{h} pixels is larger than vector footage can be drawn ({MAX_VECTOR_SIDE}×{MAX_VECTOR_SIDE})"))); } - let img = effectcraft_svg::rasterize_with(&doc, w, h, to_image); + let img = effectcraft_svg::try_rasterize_with(&doc, w, h, to_image).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; // The rasteriser produces premultiplied pixels already. let _ = op; return Ok(Some(img)); @@ -132,10 +132,15 @@ const MAX_VECTOR_SIDE: u32 = 16384; /// The vector footage `footage` (of the file `path` with these `bytes`) rasterised at `scale` × /// its size as [`effectcraft_render::vector_fit`] draws it (Continuously Rasterize). -pub(crate) fn rasterize_vector(path: &str, bytes: &[u8], footage: &Footage, scale: f64) -> Option { +/// +/// `None` when the file cannot be read as a vector document. `Some(Err(_))` when a render budget +/// refused part of the drawing (for example a layer scaled past the surface limit), so the caller +/// can report it instead of showing a partial or empty image as if it were complete. +pub(crate) fn rasterize_vector(path: &str, bytes: &[u8], footage: &Footage, scale: f64) -> Option> { let doc = footage_doc(path, bytes, footage)?.ok()?; let ((sw, sh), to_image) = fit(&doc, footage, scale); - Some(effectcraft_svg::rasterize_with(&doc, sw.clamp(1, MAX_VECTOR_SIDE), sh.clamp(1, MAX_VECTOR_SIDE), to_image)) + let drawn = effectcraft_svg::try_rasterize_with(&doc, sw.clamp(1, MAX_VECTOR_SIDE), sh.clamp(1, MAX_VECTOR_SIDE), to_image); + Some(drawn.map_err(|e| MediaError::Decode(format!("{path}: {e}")))) } /// The page framing of vector footage: as After Effects places it for footage from an After @@ -173,6 +178,18 @@ mod tests { assert_eq!((img.width, img.height), (40, 20)); } + /// Continuously Rasterize reports a layer scaled past the render budget as an error instead of + /// returning a partial or empty image, and still draws the same layer at an ordinary scale. + #[test] + fn rasterizing_vector_footage_past_the_budget_is_reported() { + let svg = br#""#; + let footage = probe("scaled.svg", svg).unwrap().unwrap(); + let ok = rasterize_vector("scaled.svg", svg, &footage, 1.0).unwrap().unwrap(); + assert_eq!((ok.width, ok.height), (100, 100)); + let e = rasterize_vector("scaled.svg", svg, &footage, 1000.0).unwrap().err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("scaled.svg"), "{e}"); + } + /// A 200 × 100 pt page: red left half, blue right half. fn halves_pdf() -> Vec { effectcraft_pdf::write::pdf( @@ -214,7 +231,7 @@ mod tests { (footage.width, footage.height) = (100, 80); let unplaced = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); assert!(unplaced == own, "not placed: drawn as before"); - assert_eq!(rasterize_vector("art.ai", &pdf, &footage, 0.5).map(|i| (i.width, i.height)), Some((100, 50))); + assert_eq!(rasterize_vector("art.ai", &pdf, &footage, 0.5).and_then(|r| r.ok()).map(|i| (i.width, i.height)), Some((100, 50))); footage.placed_page = true; let img = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); @@ -226,7 +243,7 @@ mod tests { assert!(is_blue(img.get(x, y)), "blue at ({x}, {y}): {:?}", img.get(x, y)); } - let sharp = rasterize_vector("art.ai", &pdf, &footage, 2.0).unwrap(); + let sharp = rasterize_vector("art.ai", &pdf, &footage, 2.0).unwrap().unwrap(); assert_eq!((sharp.width, sharp.height), (200, 160)); assert!(is_red(sharp.get(50, 155)) && is_blue(sharp.get(150, 155))); // Placed at the page's own size: 1:1. diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 0b509c45f..454c3705f 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -33,7 +33,7 @@ mod webp_anim; /// Video decoder counters (time in decoders, samples decoded, seeks, cache hits), for benchmarks. pub use filmcraft_codecs::{GopStats, gop_stats}; pub use pool::{DEFAULT_BUDGET, MediaPool, PoolStats}; -pub use probe::{DEFAULT_SEQUENCE_RATE, probe, probe_bytes, probe_model}; +pub use probe::{DEFAULT_SEQUENCE_RATE, probe, probe_bytes, probe_model, probe_noting}; /// Errors from probing or decoding footage. #[derive(Debug, thiserror::Error)] diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index e35ff37fc..f5d109797 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -1011,6 +1011,8 @@ impl Inner { crate::exr_channels::count_decode(false); match crate::probe::load_oriented(&bytes, crate::still_format(path, &bytes)) { Ok(img) => Ok(dynamic_to_image(&img, op)), + // Over the size limit: the layered fallback would allocate its planes anyway. + Err(e @ image::ImageError::Limits(_)) => Err(MediaError::Decode(format!("{path}: {e}"))), // A multi-layer OpenEXR file without an unnamed RGB layer: its colour layer. Err(e) => crate::exr_channels::layered_picture(path, bytes, &file, op, shared) .map_err(|why| MediaError::Decode(format!("{path}: {}", why.unwrap_or_else(|| e.to_string())))), @@ -1108,7 +1110,7 @@ impl FootageSource for MediaPool { } fn problem(&self, footage: &Footage) -> Option { - if footage.missing || footage.kind != FootageKind::Video { + if footage.missing || (footage.kind != FootageKind::Video && !effectcraft_render::is_vector_footage(footage)) { return None; } lock(&self.inner.problems).get(footage.path.as_str()).cloned() @@ -1119,7 +1121,19 @@ impl FootageSource for MediaPool { return None; } let bytes = self.inner.read(&footage.path).ok()?; - crate::layered::rasterize_vector(&footage.path, &bytes, footage, scale).map(Arc::new) + let path: Arc = footage.path.as_str().into(); + match crate::layered::rasterize_vector(&footage.path, &bytes, footage, scale)? { + Ok(img) => { + lock(&self.inner.problems).remove(&path); + Some(Arc::new(img)) + } + // Refused by a render budget (a layer scaled too far): no frame, with the reason + // reported through `problem` rather than showing a partial image as complete. + Err(e) => { + self.inner.note_problem(&path, "", &e); + None + } + } } fn set_aux_footage(&self, paths: &[String]) { diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 2c7b2a402..194eebc47 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -9,6 +9,15 @@ use image::metadata::Orientation; use crate::{MediaError, Result, ext_of, rate_from_fc}; +/// Most pixels a still may decode to: 4 GiB as the renderer's float RGBA (2^28, 16384 × 16384; +/// 150-megapixel medium-format frames, stitched panoramas and large scans decode). A browser tab's +/// wasm32 heap can't hold one allocation that large (and the decoded input beside it): 512 MiB +/// there, and on 32-bit targets, where one allocation may not pass `isize::MAX` (2 GiB). +#[cfg(not(any(target_arch = "wasm32", target_pointer_width = "32")))] +pub(crate) const MAX_STILL_PIXELS: u64 = 1 << 28; +#[cfg(any(target_arch = "wasm32", target_pointer_width = "32"))] +pub(crate) const MAX_STILL_PIXELS: u64 = 1 << 25; + /// Frame rate given to image sequences on import (After Effects' default preference). pub const DEFAULT_SEQUENCE_RATE: FrameRate = FrameRate::FPS_30; @@ -43,11 +52,25 @@ fn side_file_reader(model: &Path) -> impl Fn(&str) -> Option> + use<> { } } +thread_local! { + /// What the last model probed on this thread left out (see [`probe_noting`]). + static MODEL_WARNING: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// [`probe`], and what the import left out of the file (a 3D model's textures over the limits), +/// for the user. +pub fn probe_noting(path: impl AsRef) -> Result<(Footage, Option)> { + MODEL_WARNING.with(|w| w.borrow_mut().take()); + let f = probe(path)?; + Ok((f, MODEL_WARNING.with(|w| w.borrow_mut().take()))) +} + /// Probe a 3D model (glTF 2.0 / OBJ / STL / FBX): a [`FootageKind::Model`] item whose duration is its /// longest animation. `resolve` reads sibling resources. pub fn probe_model(path: &str, bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result { let m = effectcraft_model::load(path, bytes, resolve).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; let s = m.summary(); + MODEL_WARNING.with(|w| *w.borrow_mut() = (!m.warnings.is_empty()).then(|| format!("{path}: {}", m.warnings.join("; ")))); let dur = s.animations.iter().map(|a| a.1).fold(0.0f64, f64::max); let codec = match effectcraft_model::format_of(path) { Some("obj") => "OBJ", @@ -291,6 +314,12 @@ pub(crate) fn load_oriented(bytes: &[u8], fmt: Option) -> im None => image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?, }; let mut dec = reader.into_decoder()?; + // `from_decoder` skips the reader's allocation limit, and some decoders (BMP) allocate + // whatever size their header claims: refuse a still the renderer could not hold as floats. + let (w, h) = dec.dimensions(); + if u64::from(w) * u64::from(h) > MAX_STILL_PIXELS { + return Err(image::ImageError::Limits(image::error::LimitError::from_kind(image::error::LimitErrorKind::DimensionError))); + } let orientation = dec.orientation().unwrap_or(Orientation::NoTransforms); let mut img = image::DynamicImage::from_decoder(dec)?; img.apply_orientation(orientation); @@ -364,6 +393,23 @@ fn averaged_rate(timescale: u32, durations: impl Iterator) -> Option mod tests { use super::*; + #[test] + fn a_still_larger_than_the_renderer_holds_is_refused_before_decoding() { + // A 24-bit BMP header claiming 20000×20000 pixels (within the BMP decoder's own limit) + // over no pixel data. + let mut bmp = b"BM".to_vec(); + bmp.extend(54u32.to_le_bytes()); + bmp.extend([0u8; 4]); + bmp.extend(54u32.to_le_bytes()); + bmp.extend(40u32.to_le_bytes()); + bmp.extend(20_000i32.to_le_bytes()); + bmp.extend(20_000i32.to_le_bytes()); + bmp.extend(1u16.to_le_bytes()); + bmp.extend(24u16.to_le_bytes()); + bmp.extend([0u8; 24]); + assert!(matches!(load_oriented(&bmp, Some(image::ImageFormat::Bmp)), Err(image::ImageError::Limits(_)))); + } + /// #2592: an encoder-delayed H.264 track's edit list shows 75 frames at 25 fps (3 s at a /// 1000 timescale), though its media runs a frame longer; empty edits and no edits leave it. #[test] @@ -455,4 +501,21 @@ mod tests { assert_eq!(averaged_rate(u32::MAX, [u32::MAX; 300].into_iter()), None); assert_eq!(video_rate(b"not a movie"), None); } + + /// A 150-megapixel still (a medium-format frame) is not refused for its size: only its (absent) + /// pixel data fails, not the dimension check. A still past the limit is. + #[cfg(not(any(target_arch = "wasm32", target_pointer_width = "32")))] + #[test] + fn stills_up_to_the_limit_pass_the_size_check() { + let bmp = |w: u32, h: u32| { + let mut b = vec![b'B', b'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 40, 0, 0, 0]; + b.extend_from_slice(&w.to_le_bytes()); + b.extend_from_slice(&h.to_le_bytes()); + b.extend_from_slice(&[1, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + b + }; + let limit = |e: image::ImageError| matches!(e, image::ImageError::Limits(_)); + assert!(!load_oriented(&bmp(14_000, 10_800), None).err().is_some_and(limit), "150 MP passes the check"); + assert!(load_oriented(&bmp(20_000, 20_000), None).err().is_some_and(limit), "400 MP is refused"); + } } diff --git a/crates/media/src/webp_anim.rs b/crates/media/src/webp_anim.rs index d29d5dad4..147fe8264 100644 --- a/crates/media/src/webp_anim.rs +++ b/crates/media/src/webp_anim.rs @@ -122,6 +122,11 @@ pub(crate) fn load(bytes: &[u8]) -> Result { return Err(MediaError::Unsupported(format!("animated WebP of {} frames of {}×{} is too large to hold in memory", h.delays.len(), h.width, h.height))); } let dec = WebPDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("WebP: {e}")))?; + // The budget above used the canvas this file's header scan found; the decoder must agree, or + // a second VP8X header could make it allocate a far larger canvas. + if image::ImageDecoder::dimensions(&dec) != (h.width, h.height) { + return Err(MediaError::Decode("WebP: conflicting canvas sizes".into())); + } let (mut frames, mut delays, mut size) = (Vec::new(), Vec::new(), 0usize); for frame in dec.into_frames() { let frame = match frame { @@ -291,4 +296,20 @@ mod tests { let e = super::load(&bytes).err().unwrap(); assert!(e.to_string().contains("too large"), "{e}"); } + + #[test] + fn conflicting_canvas_headers_are_refused() { + // The first VP8X claims 16384×16384; a second one, which the header scan keeps, 1×1. + let mut bytes = webp(1, 1, &[(RED, 50); 2]); + bytes[24..27].copy_from_slice(&u24(16383)); + bytes[27..30].copy_from_slice(&u24(16383)); + let mut small = vec![0x12, 0, 0, 0]; + small.extend_from_slice(&u24(0)); + small.extend_from_slice(&u24(0)); + let second = chunk(b"VP8X", &small); + bytes.splice(30..30, second.iter().copied()); + let riff = u32::try_from(bytes.len() - 8).unwrap(); + bytes[4..8].copy_from_slice(&riff.to_le_bytes()); + assert!(super::load(&bytes).is_err()); + } } diff --git a/crates/model/src/extrude.rs b/crates/model/src/extrude.rs index 114606b95..71d550367 100644 --- a/crates/model/src/extrude.rs +++ b/crates/model/src/extrude.rs @@ -96,10 +96,14 @@ fn point_in(p: P, c: &[P]) -> bool { inside } +/// Most contours grouped into outlines; containment is tested pairwise, so the smallest are dropped. +pub const MAX_CONTOURS: usize = 10_000; + /// Group closed contours into outlines by nesting depth (even depth = outer, odd = hole of the -/// innermost containing outer contour). Degenerate contours are dropped. +/// innermost containing outer contour). Degenerate contours are dropped, as are the smallest +/// past [`MAX_CONTOURS`] (a kept hole always keeps its larger container). pub fn group_contours(contours: Vec>) -> Vec { - let cs: Vec> = contours + let mut cs: Vec> = contours .into_iter() .map(|mut c| { c.dedup(); @@ -110,26 +114,60 @@ pub fn group_contours(contours: Vec>) -> Vec { }) .filter(|c| c.len() >= 3 && signed_area(c).abs() > 1e-9) .collect(); + if cs.len() > MAX_CONTOURS { + log::warn!("model: {} contours, grouping the {MAX_CONTOURS} largest", cs.len()); + // Keep the largest, in their original order. + let area: Vec = cs.iter().map(|c| signed_area(c).abs()).collect(); + let mut keep: Vec = (0..cs.len()).collect(); + keep.sort_by(|&a, &b| area[b].total_cmp(&area[a])); + keep.truncate(MAX_CONTOURS); + keep.sort_unstable(); + cs = keep.into_iter().map(|i| std::mem::take(&mut cs[i])).collect(); + } let n = cs.len(); let area: Vec = cs.iter().map(|c| signed_area(c).abs()).collect(); - // Containers of each contour (by a vertex inside; nested contours do not cross). - let parents: Vec> = (0..n) + let bounds: Vec<[P; 2]> = cs + .iter() + .map(|c| c.iter().fold([[f64::MAX; 2], [f64::MIN; 2]], |[lo, hi], p| [[lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])]])) + .collect(); + // The containers of each contour: the larger contours holding a vertex of it (nested contours + // do not cross); the bounding box must hold the vertex first. Depth is their count, so + // overlapping (non-nested) paths keep every container they sit inside. + let containers = |i: usize, only: &dyn Fn(usize) -> bool| -> Vec { + let p = cs[i][0]; + (0..n) + .filter(|&j| j != i && area[j] > area[i] && only(j)) + .filter(|&j| (bounds[j][0][0]..=bounds[j][1][0]).contains(&p[0]) && (bounds[j][0][1]..=bounds[j][1][1]).contains(&p[1])) + .filter(|&j| point_in(p, &cs[j])) + .collect() + }; + let depth: Vec = (0..n).map(|i| containers(i, &|_| true).len()).collect(); + // A hole belongs to the innermost containing contour that is itself an outline: with + // overlapping paths the smallest container can be a hole, which has no outline to take it. + let parent: Vec> = (0..n) .map(|i| { - let probe = cs[i][0]; - (0..n).filter(|&j| j != i && area[j] > area[i] && point_in(probe, &cs[j])).collect() + if depth[i].is_multiple_of(2) { + None + } else { + containers(i, &|j| depth[j].is_multiple_of(2)).into_iter().min_by(|&a, &b| area[a].total_cmp(&area[b])) + } }) .collect(); let mut outlines: Vec = vec![]; let mut slot = vec![usize::MAX; n]; let mut order: Vec = (0..n).collect(); - order.sort_by_key(|&i| parents[i].len()); - for i in order { - let depth = parents[i].len(); - if depth.is_multiple_of(2) { + order.sort_by_key(|&i| depth[i]); + // Every outline gets its slot before any hole is attached: with overlapping paths a hole's + // parent can be deeper than the hole itself. + for &i in &order { + if depth[i].is_multiple_of(2) { slot[i] = outlines.len(); outlines.push(Outline { outer: cs[i].clone(), holes: vec![] }); - } else if let Some(&p) = parents[i].iter().filter(|&&j| parents[j].len() == depth - 1).min_by(|&&a, &&b| area[a].total_cmp(&area[b])) - && slot[p] != usize::MAX + } + } + for &i in &order { + if !depth[i].is_multiple_of(2) + && let Some(p) = parent[i] { outlines[slot[p]].holes.push(cs[i].clone()); } diff --git a/crates/model/src/fbx/tests.rs b/crates/model/src/fbx/tests.rs index 100b86abf..399b16e2d 100644 --- a/crates/model/src/fbx/tests.rs +++ b/crates/model/src/fbx/tests.rs @@ -213,3 +213,93 @@ fn fbx_models_instancing_one_geometry_share_its_mesh() { assert_ne!(mesh_of("Shape"), mesh_of("Red only"), "different materials: its own mesh"); assert_eq!(m.meshes.len(), 2); } + +#[test] +fn texture_aliases_of_one_image_share_its_pixels() { + let png = { + let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([0, 255, 0, 255])); + let mut b = std::io::Cursor::new(vec![]); + img.write_to(&mut b, image::ImageFormat::Png).unwrap(); + b.into_inner() + }; + let objects = r#" + Texture: 600, "Texture::Base", "" { + RelativeFilename: "maps\base.png" + } + Texture: 700, "Texture::Base again", "" { + RelativeFilename: "maps\base.png" + } +} +Connections: {"#; + let doc = ASCII + .replace("}\nConnections: {", objects) + .replace("C: \"OO\",500,300\n", "C: \"OO\",500,300\n\tC: \"OP\",600,400, \"DiffuseColor\"\n\tC: \"OP\",700,500, \"DiffuseColor\"\n"); + let resolve = |uri: &str| (uri == "maps/base.png").then(|| png.clone()); + let m = parse(doc.as_bytes(), &resolve).unwrap(); + assert_eq!(m.textures.len(), 1); + assert!(m.materials.iter().all(|x| x.base_color_tex.map(|t| t.texture) == Some(0))); + assert!(m.warnings.is_empty()); +} + +/// A PNG that is only a header claiming `w`×`h` pixels (an empty data chunk follows). +fn png_header_only(w: u32, h: u32) -> Vec { + fn chunk(png: &mut Vec, ty: &[u8], data: &[u8]) { + let body = [ty, data].concat(); + let mut crc = 0xFFFF_FFFFu32; + for &b in &body { + crc ^= u32::from(b); + for _ in 0..8 { + crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + png.extend((data.len() as u32).to_be_bytes()); + png.extend(&body); + png.extend((!crc).to_be_bytes()); + } + let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; + chunk(&mut png, b"IHDR", &[w.to_be_bytes(), h.to_be_bytes(), [8, 6, 0, 0]].concat().iter().copied().chain([0]).collect::>()); + chunk(&mut png, b"IDAT", &[]); + png +} + +#[test] +fn a_texture_past_the_limits_is_left_out_with_a_warning_not_a_failed_import() { + let objects = r#" + Texture: 600, "Texture::Base", "" { + RelativeFilename: "maps\base.png" + } +} +Connections: {"#; + let doc = ASCII.replace("}\nConnections: {", objects).replace("C: \"OO\",500,300\n", "C: \"OO\",500,300\n\tC: \"OP\",600,400, \"DiffuseColor\"\n"); + // 30000×30000 pixels would take ~14 GiB; the header alone is refused, before anything is allocated. + let huge = png_header_only(30000, 30000); + let resolve = |_: &str| Some(huge.clone()); + let m = parse(doc.as_bytes(), &resolve).unwrap(); + assert!(m.textures.is_empty() && m.materials.iter().all(|x| x.base_color_tex.is_none())); + assert!(m.warnings.iter().any(|w| w.contains("30000")), "{:?}", m.warnings); +} + +#[test] +fn texture_files_resolving_to_one_image_share_it() { + let png = { + let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([0, 255, 0, 255])); + let mut b = std::io::Cursor::new(vec![]); + img.write_to(&mut b, image::ImageFormat::Png).unwrap(); + b.into_inner() + }; + let objects = r#" + Texture: 600, "Texture::Base", "" { + RelativeFilename: "maps\base.png" + } + Texture: 700, "Texture::Other spelling", "" { + RelativeFilename: "missing\base.png" + FileName: "maps\base.png" + } +} +Connections: {"#; + let doc = ASCII + .replace("}\nConnections: {", objects) + .replace("C: \"OO\",500,300\n", "C: \"OO\",500,300\n\tC: \"OP\",600,400, \"DiffuseColor\"\n\tC: \"OP\",700,500, \"DiffuseColor\"\n"); + let resolve = |uri: &str| (uri == "maps/base.png").then(|| png.clone()); + assert_eq!(parse(doc.as_bytes(), &resolve).unwrap().textures.len(), 1); +} diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index b016c52b0..0f25570eb 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -67,14 +67,40 @@ pub struct Texture { pub wrap: [Wrap; 2], } +/// Most pixels one texture may hold (8192 × 8192: 1 GiB as float RGBA). +pub const MAX_TEXTURE_PIXELS: u64 = 1 << 26; +/// Most pixels the textures of one import may hold together (8 GiB as float RGBA: thirty-two 4K +/// maps). A texture past it is left out and the import says so (`Model::warnings`). +pub const MAX_IMPORT_TEXTURE_PIXELS: u64 = 1 << 29; + impl Texture { pub fn solid(c: [f32; 4]) -> Texture { Texture { width: 1, height: 1, data: vec![c], wrap: [Wrap::Repeat; 2] } } + /// The pixel size an image claims, read from its header without decoding it. + pub fn dimensions(bytes: &[u8]) -> Result<(u32, u32)> { + let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| perr(format!("image: {e}")))?; + reader.into_dimensions().map_err(|e| perr(format!("image: {e}"))) + } /// Decode a PNG or JPEG. pub fn decode(bytes: &[u8]) -> Result { - let img = image::load_from_memory(bytes).map_err(|e| perr(format!("image: {e}")))?.to_rgba32f(); + Self::decode_within(bytes, &mut MAX_IMPORT_TEXTURE_PIXELS.clone()) + } + /// [`decode`](Self::decode), of at most [`MAX_TEXTURE_PIXELS`], taking the pixels from `pixels_left`, an import's remaining + /// texture budget, before the image is decoded. + pub fn decode_within(bytes: &[u8], pixels_left: &mut u64) -> Result { + let err = |e: image::ImageError| perr(format!("image: {e}")); + let (w, h) = Self::dimensions(bytes)?; + let pixels = w as u64 * h as u64; + if pixels > MAX_TEXTURE_PIXELS { + return Err(ModelError::Unsupported(format!("a {w}×{h} texture (at most {MAX_TEXTURE_PIXELS} pixels)"))); + } + if pixels > *pixels_left { + return Err(ModelError::Unsupported(format!("a {w}×{h} texture: the model's textures would hold more than {MAX_IMPORT_TEXTURE_PIXELS} pixels"))); + } + let img = image::load_from_memory(bytes).map_err(err)?.to_rgba32f(); let (w, h) = (img.width(), img.height()); + *pixels_left -= pixels; let data = img.pixels().map(|p| p.0).collect(); Ok(Texture { width: w, height: h, data, wrap: [Wrap::Repeat; 2] }) } @@ -518,6 +544,8 @@ pub struct Model { pub cameras: Vec, /// Punctual lights embedded in the file (glTF `KHR_lights_punctual`). pub lights: Vec, + /// Parts of the file the import left out (textures over the limits), for the user. + pub warnings: Vec, } /// A camera embedded in a model file. @@ -576,8 +604,9 @@ pub struct Instance<'m> { pub mesh: &'m Mesh, /// Node → model space. pub world: Mat4, - /// Skinned meshes: joint matrices (model space, `joint_world × inverse_bind`). - pub joints: Option>, + /// Skinned meshes: joint matrices (model space, `joint_world × inverse_bind`), shared by + /// the instances of one skin. + pub joints: Option>>, } impl Model { @@ -628,6 +657,8 @@ impl Model { let mut seen = vec![false; self.nodes.len()]; let mut stack: Vec = self.roots.clone(); let mut out = vec![]; + // The pose is one for the whole scene, so every instance of a skin shares its matrices. + let mut joints_of: std::collections::HashMap>> = std::collections::HashMap::new(); while let Some(i) = stack.pop() { if i >= self.nodes.len() || seen[i] { continue; @@ -635,12 +666,19 @@ impl Model { seen[i] = true; let n = &self.nodes[i]; if let Some(m) = n.mesh.and_then(|m| self.meshes.get(m)) { - let joints = n.skin.and_then(|s| self.skins.get(s)).map(|s| { - s.joints - .iter() - .enumerate() - .map(|(k, &j)| world.get(j).copied().unwrap_or(Mat4::IDENTITY) * s.inverse_bind.get(k).copied().unwrap_or(Mat4::IDENTITY)) - .collect() + let joints = n.skin.and_then(|si| self.skins.get(si).map(|s| (si, s))).map(|(si, s)| { + joints_of + .entry(si) + .or_insert_with(|| { + Arc::new( + s.joints + .iter() + .enumerate() + .map(|(k, &j)| world.get(j).copied().unwrap_or(Mat4::IDENTITY) * s.inverse_bind.get(k).copied().unwrap_or(Mat4::IDENTITY)) + .collect(), + ) + }) + .clone() }); // Skinned vertices are placed by their joints alone (glTF: the node transform of // a skinned mesh is ignored). diff --git a/crates/model/src/scene.rs b/crates/model/src/scene.rs index 14416ffb9..07fee0397 100644 --- a/crates/model/src/scene.rs +++ b/crates/model/src/scene.rs @@ -8,8 +8,8 @@ use std::sync::Arc; use craft_mesh as cm; use crate::{ - AlphaMode, Animation, CameraProjection, Channel, ChannelPath, Interp, Mat4, Material, Mesh, Model, ModelCamera, ModelError, ModelLight, ModelLightKind, - Node, Primitive, Result, Skin, TexRef, Texture, Wrap, + AlphaMode, Animation, CameraProjection, Channel, ChannelPath, Interp, MAX_IMPORT_TEXTURE_PIXELS, Mat4, Material, Mesh, Model, ModelCamera, ModelError, + ModelLight, ModelLightKind, Node, Primitive, Result, Skin, TexRef, Texture, Wrap, }; /// The bounds every reader keeps: `craft-mesh`'s defaults, with up to 2 GiB of buffers, @@ -59,39 +59,57 @@ fn wrap(w: cm::Wrap) -> Wrap { /// The scene as a model. `image` gives the bytes of an image the scene names but does not hold /// (OBJ, which only names its textures); an image that cannot be read or decoded leaves its /// material untextured, with a log line. -pub(crate) fn to_model(scene: cm::Scene, missing: MissingNormals, image: &dyn Fn(&cm::Image) -> Option>) -> Result { - for w in &scene.warnings { +pub(crate) fn to_model(mut scene: cm::Scene, missing: MissingNormals, image: &dyn Fn(&cm::Image) -> Option>) -> Result { + let mut warnings = std::mem::take(&mut scene.warnings); + for w in &warnings { log::warn!("model: {w}"); } // Images decode once; each (image, wrap) a material uses is one texture. + let mut pixels_left = MAX_IMPORT_TEXTURE_PIXELS; + let mut decoded_by_name: HashMap>> = HashMap::new(); let decoded: Vec>> = scene .images .iter() - .map(|im| { - let bytes = im.data.clone().or_else(|| image(im)); - match bytes.map(|b| Texture::decode(&b)) { + .enumerate() + .map(|(index, im)| { + let key = image_key(im, index); + if let Some(decoded) = decoded_by_name.get(&key) { + return decoded.clone(); + } + let external; + let bytes = if let Some(data) = im.data.as_deref() { + Some(data) + } else { + external = image(im); + external.as_deref() + }; + let decoded = match bytes.map(|b| Texture::decode_within(b, &mut pixels_left)) { Some(Ok(t)) => Some(Arc::new(t)), Some(Err(e)) => { - log::warn!("model: cannot decode texture `{}`: {e}", im.uri.as_deref().unwrap_or(&im.name)); + let warning = format!("texture `{}` was left out: {e}", im.uri.as_deref().unwrap_or(&im.name)); + log::warn!("model: {warning}"); + warnings.push(warning); None } None => { - log::warn!("model: texture `{}` was not found next to the model", im.uri.as_deref().unwrap_or(&im.name)); + let warning = format!("texture `{}` was not found next to the model", im.uri.as_deref().unwrap_or(&im.name)); + log::warn!("model: {warning}"); + warnings.push(warning); None } - } + }; + decoded_by_name.insert(key, decoded.clone()); + decoded }) .collect(); let mut textures: Vec> = vec![]; - let mut texture_of: HashMap<(usize, [Wrap; 2]), usize> = HashMap::new(); + let mut texture_of: HashMap<(String, [Wrap; 2]), usize> = HashMap::new(); + for texture in &scene.texture_variants { + ensure_texture(&scene, &decoded, *texture, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings); + } let mut tref = |t: Option| -> Option { let t = t?; - let img = decoded.get(t.image).cloned().flatten()?; - let w = t.wrap.map(wrap); - let texture = *texture_of.entry((t.image, w)).or_insert_with(|| { - textures.push(if img.wrap == w { img } else { Arc::new(Texture { wrap: w, ..(*img).clone() }) }); - textures.len() - 1 - }); + let texture = ensure_texture(&scene, &decoded, t, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings)?; Some(TexRef { texture, uv_set: t.uv_set }) }; let materials: Vec = scene @@ -210,7 +228,45 @@ pub(crate) fn to_model(scene: cm::Scene, missing: MissingNormals, image: &dyn Fn range: l.range, }) .collect(); - Ok(Model { meshes, nodes, roots: scene.roots, materials, textures, skins, animations, cameras, lights }) + Ok(Model { meshes, nodes, roots: scene.roots, materials, textures, skins, animations, cameras, lights, warnings }) +} + +fn image_key(image: &cm::Image, index: usize) -> String { + image.uri.as_deref().or_else(|| (!image.name.is_empty()).then_some(image.name.as_str())).map(str::to_string).unwrap_or_else(|| format!("image:{index}")) +} + +fn ensure_texture( + scene: &cm::Scene, + decoded: &[Option>], + reference: cm::TextureRef, + textures: &mut Vec>, + texture_of: &mut HashMap<(String, [Wrap; 2]), usize>, + pixels_left: &mut u64, + warnings: &mut Vec, +) -> Option { + let image = decoded.get(reference.image)?.as_ref()?; + let wrap_mode = reference.wrap.map(wrap); + let key = (image_key(scene.images.get(reference.image)?, reference.image), wrap_mode); + if let Some(&index) = texture_of.get(&key) { + return Some(index); + } + if image.wrap != wrap_mode { + let cost = (image.width as u64).checked_mul(image.height as u64); + let Some(cost) = cost.filter(|&cost| cost <= *pixels_left) else { + let source = scene.images.get(reference.image)?; + let warning = format!("texture `{}` wrap variant exceeds the model texture pixel limit", source.uri.as_deref().unwrap_or(&source.name)); + log::warn!("model: {warning}"); + warnings.push(warning); + return None; + }; + *pixels_left -= cost; + textures.push(Arc::new(Texture { wrap: wrap_mode, ..(**image).clone() })); + } else { + textures.push(image.clone()); + } + let index = textures.len() - 1; + texture_of.insert(key, index); + Some(index) } /// One primitive per part, each with one vertex per distinct corner of its triangles. Normals @@ -369,3 +425,35 @@ fn smooth_normals(m: &cm::Mesh, missing: MissingNormals) -> HashMap<(u32, Option }) .collect() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wrap_variants_share_and_charge_the_import_pixel_budget() { + let scene = cm::Scene { images: vec![cm::Image { name: "texture.png".into(), ..cm::Image::default() }], ..cm::Scene::default() }; + let texture = Arc::new(Texture { width: 2, height: 2, data: vec![[1.0; 4]; 4], wrap: [Wrap::Repeat; 2] }); + let decoded = vec![Some(texture)]; + let mut textures = vec![]; + let mut texture_of = HashMap::new(); + // The decoded image has already taken four pixels from this budget. + let mut pixels_left = 4; + let mut warnings = vec![]; + let clamped = cm::TextureRef { image: 0, uv_set: 0, wrap: [cm::Wrap::Clamp; 2] }; + + let first = ensure_texture(&scene, &decoded, clamped, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).unwrap(); + let shared = ensure_texture(&scene, &decoded, clamped, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).unwrap(); + assert_eq!(first, shared); + assert_eq!(pixels_left, 0); + + let repeated = cm::TextureRef { wrap: [cm::Wrap::Repeat; 2], ..clamped }; + assert!(ensure_texture(&scene, &decoded, repeated, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).is_some()); + assert_eq!(pixels_left, 0); + + let mirrored = cm::TextureRef { wrap: [cm::Wrap::Mirror; 2], ..clamped }; + assert!(ensure_texture(&scene, &decoded, mirrored, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).is_none()); + assert_eq!(textures.len(), 2); + assert_eq!(warnings.len(), 1); + } +} diff --git a/crates/model/src/tests.rs b/crates/model/src/tests.rs index 69ba5e69b..8c6a347fb 100644 --- a/crates/model/src/tests.rs +++ b/crates/model/src/tests.rs @@ -448,6 +448,58 @@ fn contours_group_into_outlines_by_nesting() { assert_eq!(g.iter().map(|o| o.holes.len()).sum::(), 2); } +#[test] +fn overlapping_contours_keep_every_container_in_their_depth() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; + // C's first vertex lies inside both A and B, which overlap without nesting: C is two deep, + // an outer contour, not a hole cut out of B. + let g = group_contours(vec![rect(0.0, 0.0, 10.0, 10.0), rect(5.0, -2.0, 13.0, 8.0), rect(9.0, 1.0, 12.0, 2.0)]); + assert_eq!(g.len(), 3); + assert_eq!(g.iter().map(|o| o.holes.len()).sum::(), 0); +} + +#[test] +fn a_contour_inside_a_hole_takes_the_innermost_outline_not_the_hole() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; + // A and B overlap; C lies in A only (a hole of A); D lies in A, B and C (three deep, a hole). + // The smallest container of D is the hole C, which has no outline of its own: D goes to B. + let g = group_contours(vec![rect(0.0, 0.0, 10.0, 10.0), rect(5.0, -2.0, 13.0, 8.0), rect(1.0, 1.0, 9.0, 9.0), rect(6.0, 2.0, 7.0, 3.0)]); + assert_eq!(g.len(), 2); + assert_eq!(g.iter().map(|o| o.holes.len()).collect::>(), [1, 1], "C is a hole of A, D a hole of B (not dropped)"); +} + +#[test] +fn a_hole_whose_outline_is_deeper_than_it_is_still_attached() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; + // D is three deep and its innermost outline A four deep: A's slot must exist before D is attached. + let a = rect(0.0, 0.0, 10.0, 10.0); + let g = group_contours(vec![ + a.clone(), + rect(-1.0, -1.0, 20.0, 20.0), + rect(-2.0, -2.0, 25.0, 25.0), + rect(5.0, 5.0, 6.0, 6.0), + rect(-100.0, -100.0, 3.0, 3.0), + rect(-0.5, -1000.0, 0.5, 1000.0), + ]); + let o = g.iter().find(|o| o.outer == a).expect("A is an outline"); + assert_eq!(o.holes.len(), 1, "D is a hole of A"); +} + +#[test] +fn gltf_images_naming_one_file_share_their_wrap_variants() { + let png = { + let img = image::RgbaImage::from_fn(2, 2, |x, y| if (x + y) % 2 == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + // Two image entries with one URI share a decode; two textures clamp it, so they share one copy. + let doc = br#"{"asset":{"version":"2.0"},"images":[{"uri":"t.png"},{"uri":"t.png"}], + "samplers":[{"wrapS":33071,"wrapT":33071}],"textures":[{"source":0,"sampler":0},{"source":1,"sampler":0}]}"#; + let m = gltf::parse(doc, &|u| (u == "t.png").then(|| png.clone())).unwrap(); + assert_eq!(m.textures.len(), 1, "one clamped copy for both textures"); +} + #[test] fn gltf_cameras_and_punctual_lights() { let doc = r#"{ @@ -695,3 +747,102 @@ fn gltf_reused_buffer_less_accessor_is_read_once() { let result = crate::gltf::parse(doc.as_bytes(), &|_| None); assert!(result.is_ok(), "{result:?}"); } + +#[test] +fn texture_decoding_is_charged_to_the_import_budget() { + let png = { + let img = image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])); + let mut b = std::io::Cursor::new(vec![]); + img.write_to(&mut b, image::ImageFormat::Png).unwrap(); + b.into_inner() + }; + let mut left = 4; + assert_eq!(Texture::decode_within(&png, &mut left).unwrap().data.len(), 4); + assert_eq!(left, 0); + assert!(matches!(Texture::decode_within(&png, &mut left), Err(ModelError::Unsupported(_)))); +} + +#[test] +fn obj_repeated_material_libraries_and_textures_load_once() { + let png = { + let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([0, 255, 0, 255])); + let mut b = std::io::Cursor::new(vec![]); + img.write_to(&mut b, image::ImageFormat::Png).unwrap(); + b.into_inner() + }; + let mtl = b"newmtl A\nmap_Kd t.png\nnewmtl B\nmap_Kd t.png\n".to_vec(); + let src = b"mtllib m.mtl\nmtllib m.mtl\nv 0 0 0\nv 1 0 0\nv 0 1 0\nusemtl A\nf 1 2 3\nusemtl B\nf 1 2 3\nusemtl A\nf 1 2 3\n"; + let m = obj::parse(src, &|name| match name { + "m.mtl" => Some(mtl.clone()), + "t.png" => Some(png.clone()), + _ => None, + }) + .unwrap(); + assert_eq!(m.materials.iter().map(|m| m.name.as_str()).collect::>(), ["A", "B"]); + assert_eq!(m.textures.len(), 1); + assert_eq!(m.meshes[0].primitives.iter().map(|p| (p.material, p.triangle_count())).collect::>(), [(Some(0), 2), (Some(1), 1)]); +} + +#[test] +fn gltf_textures_naming_one_image_share_it() { + let doc = String::from_utf8(fixture("quad.gltf")).unwrap(); + // Three textures of one image: the fixture's sampler, the same sampler again, no sampler. + let doc = doc.replace( + "\"textures\": [\n {\n \"source\": 0,\n \"sampler\": 0\n }\n ]", + "\"textures\": [{\"source\": 0, \"sampler\": 0}, {\"source\": 0, \"sampler\": 0}, {\"source\": 0}]", + ); + let m = gltf::parse(doc.as_bytes(), &|_| None).unwrap(); + assert_eq!(m.textures.len(), 2); + assert_eq!(m.textures[0].wrap, [Wrap::Clamp, Wrap::Repeat]); + assert_eq!(m.textures[1].wrap, [Wrap::Repeat, Wrap::Repeat]); +} + +#[test] +fn instances_of_one_skin_share_its_joint_matrices() { + let p = mesh(PrimitiveKind::Plane, &PrimParams { size: [2.0, 2.0, 0.0], ..Default::default() }); + let mut m = Model::single(Mesh { name: "s".into(), primitives: vec![p] }, vec![Material::default()]); + m.nodes[0].skin = Some(0); + m.nodes.push(Node { mesh: Some(0), skin: Some(0), ..Node::default() }); + m.roots = vec![0, 1]; + m.skins.push(Skin { joints: vec![0], inverse_bind: vec![Mat4::IDENTITY] }); + let inst = m.instances(None, 0.0); + assert_eq!(inst.len(), 2); + assert!(Arc::ptr_eq(inst[0].joints.as_ref().unwrap(), inst[1].joints.as_ref().unwrap())); +} + +#[test] +fn contour_grouping_is_bounded() { + let sq = |x: f64, y: f64, s: f64| vec![[x, y], [x + s, y], [x + s, y + s], [x, y + s]]; + let n = extrude::MAX_CONTOURS + 1; + let cs: Vec> = (0..n).map(|i| sq(i as f64 * 2.0, 0.0, 1.0)).collect(); + let g = group_contours(cs); + assert_eq!(g.len(), extrude::MAX_CONTOURS); + assert!(g.iter().all(|o| o.holes.is_empty())); +} + +/// A texture the import leaves out (too large, or not an image) is named in `Model::warnings`, +/// which the import shows the user; the model still loads. +#[test] +fn left_out_textures_are_reported_as_import_warnings() { + // A 24-bit BMP header claiming 9000×9000 (81 MP, over one texture's limit) over no pixel data. + let mut big = b"BM".to_vec(); + big.extend_from_slice(&[0; 8]); + big.extend_from_slice(&54u32.to_le_bytes()); + big.extend_from_slice(&40u32.to_le_bytes()); + big.extend_from_slice(&9000u32.to_le_bytes()); + big.extend_from_slice(&9000u32.to_le_bytes()); + big.extend_from_slice(&[1, 0, 24, 0]); + big.extend_from_slice(&[0; 24]); + let mtl = b"newmtl A\nmap_Kd big.bmp\nnewmtl B\nmap_Kd junk.png\nnewmtl C\nmap_Kd gone.png\n".to_vec(); + let src = b"mtllib m.mtl\nv 0 0 0\nv 1 0 0\nv 0 1 0\nusemtl A\nf 1 2 3\n"; + let m = obj::parse(src, &|name| match name { + "m.mtl" => Some(mtl.clone()), + "big.bmp" => Some(big.clone()), + "junk.png" => Some(b"not an image".to_vec()), + _ => None, + }) + .unwrap(); + assert!(m.textures.is_empty()); + let all = m.warnings.join("|"); + assert!(all.contains("big.bmp") && all.contains("junk.png") && all.contains("gone.png"), "{all}"); +} diff --git a/crates/project/src/ae_order.rs b/crates/project/src/ae_order.rs new file mode 100644 index 000000000..b6dce1d44 --- /dev/null +++ b/crates/project/src/ae_order.rs @@ -0,0 +1,139 @@ +//! After Effects' numeric order of a layer's top-level property groups. +//! +//! In After Effects `thisLayer(4)` and `layer.property(4)` reach the same group on every layer of a +//! kind, whatever the layer holds: Marker is always 1, and the groups a layer has not used yet +//! (Time Remap, Motion Trackers, Layer Styles…) still take their slot. EffectCraft's tree holds only +//! the groups a layer has, without Marker, so its own positions differ and move as groups are +//! added. Rigs that address groups by number (`comp("Palette").layer(1)(4)(n)(1)`) read the wrong +//! group, or none, unless numbers go through this table. +//! +//! The order was observed in After Effects 26.3 by reading `layer.property(i).matchName` from a +//! script and `thisComp.layer(..)(i).name` from an expression on new layers of each kind; both +//! agree. 3D model and primitive layers have no table: their numbers stay EffectCraft's own. + +use crate::{Layer, LayerSource, Node}; + +/// One top-level slot in After Effects' order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AeSlot { + /// The group's match id in EffectCraft's tree, or `""` when EffectCraft has no such group. + pub match_id: &'static str, + /// The display name After Effects gives the slot. + pub name: &'static str, + /// After Effects' match name for the slot. + pub match_name: &'static str, +} + +const fn slot(match_id: &'static str, name: &'static str, match_name: &'static str) -> AeSlot { + AeSlot { match_id, name, match_name } +} + +/// The marker slot: number 1 on every layer. Markers are a field of [`Layer`], not a tree node. +pub const MARKER: AeSlot = slot("marker", "Marker", "ADBE Marker"); + +/// Footage, solid, adjustment, precomp and null layers. +const AV: &[AeSlot] = &[ + MARKER, + slot("timeRemap", "Time Remap", "ADBE Time Remapping"), + slot("motionTrackers", "Motion Trackers", "ADBE MTrackers"), + slot("masks", "Masks", "ADBE Mask Parade"), + slot("effects", "Effects", "ADBE Effect Parade"), + slot("transform", "Transform", "ADBE Transform Group"), + slot("layerStyles", "Layer Styles", "ADBE Layer Styles"), + slot("", "Geometry Options", "ADBE Plane Options Group"), + slot("geometryOptions", "Geometry Options", "ADBE Extrsn Options Group"), + slot("materialOptions", "Material Options", "ADBE Material Options Group"), + slot("audio", "Audio", "ADBE Audio Group"), + slot("", "Data", "ADBE Data Group"), + slot("", "Essential Properties", "ADBE Layer Overrides"), + slot("", "Sets", "ADBE Layer Sets"), + slot("", "Source Options", "ADBE Source Options Group"), +]; + +const TEXT: &[AeSlot] = &[ + MARKER, + slot("text", "Text", "ADBE Text Properties"), + slot("masks", "Masks", "ADBE Mask Parade"), + slot("effects", "Effects", "ADBE Effect Parade"), + slot("transform", "Transform", "ADBE Transform Group"), + slot("layerStyles", "Layer Styles", "ADBE Layer Styles"), + slot("geometryOptions", "Geometry Options", "ADBE Extrsn Options Group"), + slot("materialOptions", "Material Options", "ADBE Material Options Group"), + slot("audio", "Audio", "ADBE Audio Group"), + slot("", "Sets", "ADBE Layer Sets"), +]; + +const SHAPE: &[AeSlot] = &[ + MARKER, + slot("contents", "Contents", "ADBE Root Vectors Group"), + slot("masks", "Masks", "ADBE Mask Parade"), + slot("effects", "Effects", "ADBE Effect Parade"), + slot("transform", "Transform", "ADBE Transform Group"), + slot("layerStyles", "Layer Styles", "ADBE Layer Styles"), + slot("geometryOptions", "Geometry Options", "ADBE Extrsn Options Group"), + slot("materialOptions", "Material Options", "ADBE Material Options Group"), + slot("audio", "Audio", "ADBE Audio Group"), + slot("", "Sets", "ADBE Layer Sets"), +]; + +const CAMERA: &[AeSlot] = + &[MARKER, slot("transform", "Transform", "ADBE Transform Group"), slot("cameraOptions", "Camera Options", "ADBE Camera Options Group")]; + +const LIGHT: &[AeSlot] = &[MARKER, slot("transform", "Transform", "ADBE Transform Group"), slot("lightOptions", "Light Options", "ADBE Light Options Group")]; + +/// After Effects' top-level slots for a layer of this kind, or `None` for 3D model and primitive +/// layers, which keep EffectCraft's own numbers. +pub fn ae_slots(source: &LayerSource) -> Option<&'static [AeSlot]> { + match source { + LayerSource::Footage { .. } | LayerSource::Comp { .. } | LayerSource::Solid { .. } | LayerSource::Null => Some(AV), + LayerSource::Text => Some(TEXT), + LayerSource::Shape => Some(SHAPE), + LayerSource::Camera => Some(CAMERA), + LayerSource::Light { .. } => Some(LIGHT), + LayerSource::Model { .. } | LayerSource::Primitive { .. } => None, + } +} + +/// What After Effects' top-level number `index` (1-based) reaches on `layer`. +#[derive(Clone, Copy, Debug)] +pub enum AeChild<'a> { + /// The layer's markers (number 1). + Marker, + /// A group or property the layer has. + Node(&'a Node), + /// A slot After Effects always has and this layer does not (an empty group there). + Absent(&'static AeSlot), +} + +/// The top-level node After Effects' number `index` (1-based) reaches, or `None` when the number is +/// past the last slot or the layer kind has no table ([`ae_slots`]). +pub fn ae_child(layer: &Layer, index: usize) -> Option> { + let s = ae_slots(&layer.source)?.get(index.checked_sub(1)?)?; + if *s == MARKER { + return Some(AeChild::Marker); + } + if s.match_id.is_empty() { + return Some(AeChild::Absent(s)); + } + Some(layer.props.children.iter().find(|n| n.match_id() == s.match_id).map_or(AeChild::Absent(s), AeChild::Node)) +} + +/// After Effects' 1-based number for the top-level node with this match id, when it has one. +pub fn ae_index(layer: &Layer, match_id: &str) -> Option { + if match_id.is_empty() { + return None; + } + ae_slots(&layer.source)?.iter().position(|s| s.match_id == match_id).map(|i| i + 1) +} + +/// How many top-level properties After Effects counts on `layer` (`numProperties`), or `None` for +/// layer kinds without a table. +pub fn ae_count(layer: &Layer) -> Option { + ae_slots(&layer.source).map(<[AeSlot]>::len) +} + +/// After Effects' 1-based number for the top-level slot with this After Effects match name +/// (`ADBE Effect Parade`), when the layer kind has one. +pub fn ae_index_of_match_name(layer: &Layer, match_name: &str) -> Option { + ae_slots(&layer.source)?.iter().position(|s| s.match_name == match_name).map(|i| i + 1) +} diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index 6d0a72976..9f5f399e0 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -6,6 +6,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod ae_order; pub mod build; pub mod essential; mod file_check; diff --git a/crates/raster/src/flow.rs b/crates/raster/src/flow.rs index 4fdf0e060..3a4a9d6f8 100644 --- a/crates/raster/src/flow.rs +++ b/crates/raster/src/flow.rs @@ -113,16 +113,63 @@ pub fn block_flow(a: &Image, b: &Image, block: u32, radius: i32) -> Flow { block_flow_window(a, b, block, block, radius) } +/// Largest coarse search radius honoured (the effects use at most 64). +const MAX_RADIUS: i32 = 1024; +/// Upper bound on the pixel comparisons of one motion search (about 4·10¹²: minutes of work on +/// many cores). A finer vector grid than this allows is made coarser, by doubling the tile. +const MAX_SEARCH_WORK: f64 = 4.4e12; + +/// The pixel comparisons [`block_flow_window`] makes for tiles of `bs`: every tile, at every +/// pyramid level, tries its candidate vectors with a `window`-sized block, then refines. +/// The pyramid depth follows the requested tile `fine`, not the coarsened one, so a coarser vector +/// grid keeps the full search range. +fn search_work(w: usize, h: usize, bs: usize, fine: usize, win: i64, radius: i64) -> f64 { + let tiles = (w.div_ceil(bs).max(1) as f64) * (h.div_ceil(bs).max(1) as f64); + let reach = (fine as i64).max(win) as usize * 2; + let (mut lw, mut lh, mut top) = (w, h, 0u32); + while top < 3 && lw / 2 >= reach && lh / 2 >= reach { + (lw, lh, top) = (lw / 2, lh / 2, top + 1); + } + let mut per_tile = 5.0 * (win * win) as f64; + for level in 0..=top { + let lbs = (win >> level).max(4) as f64; + let (seeds, r) = if level == top { (1.0, radius as f64) } else { (6.0, 1.0) }; + per_tile += seeds * (2.0 * r + 1.0).powi(2) * lbs * lbs; + } + tiles * per_tile +} + +/// The tile size and radius to search with: `tile`, doubled (while it still fits the frame) and +/// then, if that is not enough, the radius halved, until the search is within [`MAX_SEARCH_WORK`]. +fn planned(w: usize, h: usize, tile: usize, win: i64, radius: i64) -> (usize, i64) { + let (mut bs, mut r) = (tile, radius); + while bs * 2 <= w.min(h) && search_work(w, h, bs, tile, win, r) > MAX_SEARCH_WORK { + bs *= 2; + } + while r > 1 && search_work(w, h, bs, tile, win, r) > MAX_SEARCH_WORK { + r /= 2; + } + (bs, r) +} + /// [`block_flow`] with separate vector spacing and matching window: one vector per /// `tile × tile` tile, each matched with the `window × window` block centred on its tile /// (Timewarp's Vector Detail and Block Size). pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i32) -> Flow { - let bs = tile.max(2) as usize; // The matching cost per vector grows with the window's area; 512 is far above any block size the effects offer. let win = i64::from(window.clamp(4, 512)); + let radius = radius.min(MAX_RADIUS); + let fine = tile.max(2) as usize; + let (bs, radius) = planned(a.width as usize, a.height as usize, fine, win, i64::from(radius)); + let coarse = bs != fine; // Window origin relative to the tile origin. let wo = bs as i64 / 2 - win / 2; let (w, h) = (a.width as usize, a.height as usize); + // A coarsened grid's last (partial) tiles keep their window inside the frame. + let origin = |c: i64, dim: usize| { + let o = c * bs as i64 + wo; + if coarse { o.clamp(0, (dim as i64 - win).max(0)) } else { o } + }; let cols = w.div_ceil(bs).max(1); let rows = h.div_ceil(bs).max(1); let mut flow = Flow { width: a.width, height: a.height, block: bs as u32, cols, rows, v: vec![[0.0; 2]; cols * rows] }; @@ -132,7 +179,7 @@ pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i // Pyramids (level 0 = full resolution); stop while blocks still fit. let mut pa = vec![Plane::luma(a)]; let mut pb = vec![Plane::luma(b)]; - while pa.len() < 4 && pa.last().is_some_and(|p| p.w / 2 >= (bs as i64).max(win) as usize * 2 && p.h / 2 >= (bs as i64).max(win) as usize * 2) { + while pa.len() < 4 && pa.last().is_some_and(|p| p.w / 2 >= (fine as i64).max(win) as usize * 2 && p.h / 2 >= (fine as i64).max(win) as usize * 2) { let (na, nb) = (pa.last().map(Plane::half), pb.last().map(Plane::half)); pa.extend(na); pb.extend(nb); @@ -145,14 +192,14 @@ pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i let k = 1i64 << level; // The block covers the tile's footprint at this level (at least 4 pixels). let lbs = (win / k).max(4); - let r = if level == top { radius as i64 } else { 1 }; + let r = if level == top { radius } else { 1 }; let prev = cur.clone(); cur = (0..cols * rows) .into_par_iter() .map(|i| { let (c, rr) = ((i % cols) as i64, (i / cols) as i64); - let bx = (c * bs as i64 + wo) / k; - let by = (rr * bs as i64 + wo) / k; + let bx = origin(c, w) / k; + let by = origin(rr, h) / k; // Candidates: this tile's and its neighbours' vectors from the coarser level. let mut seeds: Vec<[i64; 2]> = vec![[0, 0]]; if level != top { @@ -185,12 +232,11 @@ pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i } // Sub-pixel refinement (parabola through the SAD of the neighbours) at full resolution. let (la, lb) = (&pa[0], &pb[0]); - let bsi = bs as i64; let wsi = win; let fine: Vec<[f32; 2]> = (0..cols * rows) .into_par_iter() .map(|i| { - let (bx, by) = ((i % cols) as i64 * bsi + wo, (i / cols) as i64 * bsi + wo); + let (bx, by) = (origin((i % cols) as i64, w), origin((i / cols) as i64, h)); let d = cur[i]; let e0 = sad(la, lb, bx, by, wsi, d[0], d[1]); let fit = |em: f32, ep: f32| { @@ -296,6 +342,19 @@ mod tests { s / n as f32 } + #[test] + fn a_fine_vector_grid_with_a_huge_window_is_made_coarser() { + // 8K frame, a vector per 2 px, a 512-px window and a 1024-px search: far past the budget. + let (t, r) = super::planned(7680, 4320, 2, 512, 1024); + assert!(t > 2 && t <= 4320 && super::search_work(7680, 4320, t, 2, 512, r) <= super::MAX_SEARCH_WORK, "{t} {r}"); + // The tile stays inside the frame, and the pyramid (search range) follows the requested tile. + let (t, _) = super::planned(7680, 4320, 2, 512, 710); + assert!(t <= 4320); + // Pixel Motion Blur's finest grid with its largest search keeps its grid on a 1080p frame. + assert_eq!(super::planned(1920, 1080, 2, 16, 64), (2, 64)); + assert_eq!(super::planned(1920, 1080, 8, 64, 4), (8, 4)); + } + #[test] fn a_huge_matching_window_is_held_to_the_cap() { let (a, b) = (texture(520, 520, 0.0), texture(520, 520, 2.0)); diff --git a/crates/render/src/audio.rs b/crates/render/src/audio.rs index 00342847d..2c1538133 100644 --- a/crates/render/src/audio.rs +++ b/crates/render/src/audio.rs @@ -24,6 +24,15 @@ use crate::{EvalCtx, ExprHost, FootageSource}; const MAX_DEPTH: usize = 16; +/// The fastest a layer's audio plays (a Stretch of 1%). +const MAX_SPEED: f64 = 100.0; + +/// The most effect preroll (history before a block) mixed, in seconds, across a layer's effects. +const MAX_PREROLL_SECONDS: f64 = 30.0; + +/// The longest footage a waveform summarises (a day). +const MAX_PEAK_SECONDS: i64 = 24 * 3600; + /// `frames` stereo sample frames of `comp`'s mix from comp time `start` at `rate` Hz, /// interleaved (L R L R …). pub fn mix_comp(project: &Project, footage: &dyn FootageSource, expr: Option<&dyn ExprHost>, comp: ItemId, start: Tick, frames: usize, rate: u32) -> Vec { @@ -35,22 +44,29 @@ pub fn mix_comp(project: &Project, footage: &dyn FootageSource, expr: Option<&dy /// Whether the comp has anything audible (footage with audio, a sound generator, or a precomp /// that has). pub fn comp_has_audio(project: &Project, comp: ItemId) -> bool { - fn walk(project: &Project, comp: ItemId, depth: usize) -> bool { - let Some(c) = project.comp(comp) else { return false }; - depth < MAX_DEPTH - && c.layers.iter().any(|l| { - l.switches.audio - && (generates(l) - || match &l.source { - LayerSource::Footage { item } => { - matches!(project.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_audio && !f.missing) - } - LayerSource::Comp { item } => walk(project, *item, depth + 1), - _ => false, - }) - }) + // Breadth first, so each comp is looked at once and at its shallowest level: a comp reached + // first through a long chain (past MAX_DEPTH) is still found by a shorter route, and a cycle + // cannot hide a result (nothing is cached as "silent" while it is being explored). + let mut seen = std::collections::HashSet::from([comp]); + let mut level = vec![comp]; + for _ in 0..MAX_DEPTH { + let mut next = vec![]; + for id in level { + let Some(c) = project.comp(id) else { continue }; + for l in c.layers.iter().filter(|l| l.switches.audio) { + match &l.source { + _ if generates(l) => return true, + LayerSource::Footage { item } if matches!(project.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_audio && !f.missing) => { + return true; + } + LayerSource::Comp { item } if seen.insert(*item) => next.push(*item), + _ => {} + } + } + } + level = next; } - walk(project, comp, 0) + false } /// Enabled audio effects of a layer (in stack order) with their effect ids. @@ -157,7 +173,7 @@ impl MixEnv<'_> { let m = b - a; // Within ±1 % to ±9900 % (#3247): a stretch of 1e-300 % set in memory read about // usize::MAX source samples for one block. - let speed = 100.0 / l.effective_stretch(); + let speed = (100.0 / l.effective_stretch()).min(MAX_SPEED); let src_n = ((m as f64 * speed).ceil() as usize).max(1); let lt = l.layer_time(sample_tick(i0 + a as i64, rate)); let buf = match &l.source { @@ -213,7 +229,7 @@ impl MixEnv<'_> { return self.layer_raw(l, i0, n, false); } let reversed = fx.iter().any(|(id, _, _)| audio_fx::reverses(id)); - let pre_s: f64 = fx.iter().map(|(id, _, p)| audio_fx::preroll(id, p)).sum(); + let pre_s: f64 = fx.iter().map(|(id, _, p)| audio_fx::preroll(id, p)).sum::().clamp(0.0, MAX_PREROLL_SECONDS); let pre = (pre_s * self.rate as f64).ceil() as usize; let b0 = i0 - pre as i64; let mut buf = self.layer_raw(l, b0, n + pre, reversed); @@ -342,12 +358,14 @@ pub fn footage_peaks(footage: &dyn FootageSource, item: ItemId, f: &effectcraft_ let bin = (64usize).max(4000 / bins_per_sec as usize); let rate = bin as u32 * bins_per_sec; let chunk = bin * bins_per_sec as usize; - let total = units_ceil(duration, rate).max(0) as usize; + // The stated duration comes from the project: at most a day is summarised, and the summary + // ends where the audio does. + let total = units_ceil(duration, rate).clamp(0, MAX_PEAK_SECONDS.saturating_mul(rate as i64)) as usize; let mut out = Vec::with_capacity(total / bin + 1); let mut i = 0usize; while i < total { let n = chunk.min(total - i); - let buf = footage.audio(item, f, sample_tick(i as i64, rate), n, rate).unwrap_or_else(|| vec![0.0; n * 2]); + let Some(buf) = footage.audio(item, f, sample_tick(i as i64, rate), n, rate) else { break }; out.extend(peak_summary(&buf, bin)); i += n; } @@ -375,6 +393,55 @@ mod tests { } } + #[test] + fn audio_detection_answers_each_comp_once() { + // Twenty levels, each comp holding two layers of the one below: 2^20 walks without a + // memo, and all silent. A cycle is answered too. + let mut p = Project::default(); + let mk = |p: &mut Project, layers: Vec| { + let mut c = Comp::new(8, 8, FrameRate::new(25, 1), Tick::from_seconds_f64(1.0)); + c.layers = layers.into(); + p.add_item("C", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(c.into())) + }; + let base = Comp::new(8, 8, FrameRate::new(25, 1), Tick::from_seconds_f64(1.0)); + let mut below = mk(&mut p, vec![]); + for _ in 0..20 { + let a = build::layer(&mut p, &base, "a", LayerSource::Comp { item: below }, (0, 0), None); + let b = build::layer(&mut p, &base, "b", LayerSource::Comp { item: below }, (0, 0), None); + below = mk(&mut p, vec![a, b]); + } + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(comp_has_audio(&p, below)).ok()); + assert!(!rx.recv_timeout(std::time::Duration::from_secs(20)).expect("detection finishes")); + } + + #[test] + fn audio_found_by_a_short_route_is_not_hidden_by_a_deep_one() { + let mut p = Project::default(); + let base = Comp::new(8, 8, FrameRate::new(25, 1), Tick::from_seconds_f64(1.0)); + let mk = |p: &mut Project, layers: Vec| { + let mut c = base.clone(); + c.layers = layers.into(); + p.add_item("C", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(c.into())) + }; + let f = Footage { kind: FootageKind::Audio, has_audio: true, ..Default::default() }; + let fid = p.add_item("x.wav", effectcraft_color::Label::SeaFoam, None, ItemKind::Footage(f)); + let sound = build::layer(&mut p, &base, "s", LayerSource::Footage { item: fid }, (0, 0), None); + let audible = mk(&mut p, vec![sound]); + // A chain of MAX_DEPTH comps ends in `audible` one level past what is searched; the root + // reaches `audible` directly as well, after the chain. + let mut chain = audible; + for _ in 0..MAX_DEPTH { + let l = build::layer(&mut p, &base, "c", LayerSource::Comp { item: chain }, (0, 0), None); + chain = mk(&mut p, vec![l]); + } + assert!(!comp_has_audio(&p, chain), "too deep to be found"); + let via_chain = build::layer(&mut p, &base, "chain", LayerSource::Comp { item: chain }, (0, 0), None); + let direct = build::layer(&mut p, &base, "direct", LayerSource::Comp { item: audible }, (0, 0), None); + let root = mk(&mut p, vec![via_chain, direct]); + assert!(comp_has_audio(&p, root)); + } + #[test] fn mixes_layers_with_levels_and_in_out() { let mut p = Project::default(); diff --git a/crates/render/src/cache/dependencies.rs b/crates/render/src/cache/dependencies.rs index dc4216098..6f14ddcde 100644 --- a/crates/render/src/cache/dependencies.rs +++ b/crates/render/src/cache/dependencies.rs @@ -33,6 +33,8 @@ impl Dependencies<'_> { { for g in fx.groups().take(limit.unwrap_or(usize::MAX)).filter(|g| g.enabled) { self.group(ctx, layer, g, 0)?; + // A LUT file edited on disk changes the pixels without an edit (#3493). + crate::reads::lut_files(ctx, layer, g).hash(self.h); } } self.other_times = previous; @@ -169,6 +171,14 @@ impl Dependencies<'_> { ItemKind::Comp(comp) => { let time = ctx.source_time(layer); time.0.hash(self.h); + // The nested layers are walked without this instance's Essential + // Properties overrides, which the render applies: a LUT file one of + // them names is read too (#3493). + for o in crate::fx_host::essential_overrides(ctx, layer) { + if let effectcraft_keyframe::Value::Str(src) = &o.value { + crate::reads::source_files(src).hash(self.h); + } + } let nested = EvalCtx::new(ctx.project, item, comp, time); for child in &comp.layers { self.layer(&nested, child)?; diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 5c34348fe..3674b2667 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -483,12 +483,54 @@ pub fn default_folder() -> PathBuf { if let Some(x) = std::env::var_os("XDG_CACHE_HOME") { return PathBuf::from(x).join("effectcraft/disk-cache"); } - home.map(|h| h.join(".cache/effectcraft/disk-cache")).unwrap_or_else(|| std::env::temp_dir().join("effectcraft-disk-cache")) + // Without a home folder: a per-user folder in the shared temp folder, made private by `open`. + let user = std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_default(); + home.map(|h| h.join(".cache/effectcraft/disk-cache")).unwrap_or_else(|| std::env::temp_dir().join(format!("effectcraft-disk-cache-{user}"))) +} + +/// A cache folder in the shared temp folder must be ours alone: not a link someone placed there, +/// and private (setting the mode fails unless we own it), so another user cannot redirect the +/// cache's writes and clean-up or read its files. +#[cfg(unix)] +fn make_private(folder: &Path) -> std::io::Result<()> { + use std::os::unix::fs::PermissionsExt; + // Judge the folder as written and as it resolves (a relative path, a link or an alias such as + // /tmp -> /private/tmp can all land in the shared temp folder). + // The shared roots: the process's temp folder (`TMPDIR`) and the system's own, which a cache + // configured by path lands in whatever `TMPDIR` says. + let roots: Vec = [std::env::temp_dir(), PathBuf::from("/tmp"), PathBuf::from("/var/tmp")] + .into_iter() + .flat_map(|t| { + let real = t.canonicalize().unwrap_or_else(|_| t.clone()); + [t, real] + }) + .collect(); + let given = std::path::absolute(folder).unwrap_or_else(|_| folder.to_path_buf()); + let real = folder.canonicalize().unwrap_or_else(|_| given.clone()); + // The shared folder itself is not ours to change or to keep a cache in: refused. + if [&given, &real].iter().any(|p| roots.contains(p)) { + return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "the disk cache folder is the shared temp folder")); + } + // Only folders inside it are made private. + if ![&given, &real].iter().any(|p| roots.iter().any(|t| p.starts_with(t) && **p != *t)) { + return Ok(()); + } + if std::fs::symlink_metadata(folder)?.file_type().is_symlink() { + return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "the disk cache folder is a link")); + } + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o700)) +} + +#[cfg(not(unix))] +fn make_private(_: &Path) -> std::io::Result<()> { + Ok(()) } impl DiskCache { /// Open (or create) the cache in `folder`, holding at most `max_bytes`. pub fn open(folder: impl AsRef, max_bytes: u64) -> std::io::Result> { + std::fs::create_dir_all(folder.as_ref())?; + make_private(folder.as_ref())?; let dir = folder.as_ref().join(VERSION); std::fs::create_dir_all(&dir)?; let dc = Arc::new(DiskCache { @@ -1145,8 +1187,9 @@ impl DiskCache { /// started at. /// The buffer is shared, and encoded on the writer thread. pub fn put_layer(&self, key: u128, buf: &Arc, files: &EntryFiles, since: u64) { - // (no room on the disk: refused before the buffer is queued and compressed) - if self.contains(Kind::Layer, key) || !self.accepts_writes() { + // (no room on the disk, or a buffer no entry could hold: refused before it is queued and + // compressed) + if !layer_fits(buf.img.data.len()) || self.contains(Kind::Layer, key) || !self.accepts_writes() { return; } self.count_encode(); @@ -1155,6 +1198,9 @@ impl DiskCache { /// Write a layer buffer synchronously (tests); a list that can't be stored is not. pub fn put_layer_now(&self, key: u128, buf: &Buf, files: &ReadFiles) { + if !layer_fits(buf.img.data.len()) { + return; + } if let Some(files) = EntryFiles::of(files, None) { self.write_format(Kind::Layer, key, FORMAT_LAYER_FILES, &with_files(&files, encode_layer(buf))); } @@ -1163,8 +1209,12 @@ impl DiskCache { /// A segmentation (chain key, scale) written by [`DiskCache::put_seg`]. pub fn get_seg(&self, key: u64, scale: f64) -> Option { let p = self.read(Kind::Matte, seg_key(key, scale))?; - let raw = lz4_flex::decompress_size_prepended(&p).ok()?; - effectcraft_effects::roto::FrameSeg::from_bytes(&raw) + let seg = decompress_checked(&p, None).and_then(|raw| effectcraft_effects::roto::FrameSeg::from_bytes(&raw)); + if seg.is_none() { + // A rejected entry would otherwise stay indexed and keep `put_seg` from replacing it. + self.discard(Kind::Matte, seg_key(key, scale)); + } + seg } /// Queue a segmentation for writing. @@ -1403,16 +1453,38 @@ fn encode_frame(w: u32, h: u32, rgba: &[u8]) -> Vec { out } +/// The most bytes one cache entry decompresses to (a 16384² frame of 8-bit RGBA): the size an +/// entry states is checked against it, and against what the entry's dimensions need, before +/// anything is allocated. +const MAX_ENTRY_BYTES: usize = 1 << 30; + +/// An LZ4 payload with its stated size prepended, decompressed only when that size is +/// `expected` (any size up to [`MAX_ENTRY_BYTES`] when `None`). +fn decompress_checked(p: &[u8], expected: Option) -> Option> { + let size = u32::from_le_bytes(p.get(..4)?.try_into().ok()?) as usize; + if size > MAX_ENTRY_BYTES || expected.is_some_and(|e| e != size) { + return None; + } + // A block that ends short of the size it states is damaged: callers index by that size. + lz4_flex::decompress(p.get(4..)?, size).ok().filter(|raw| raw.len() == size) +} + fn decode_frame(p: &[u8]) -> Option { if p.len() < 8 { return None; } let w = u32::from_le_bytes(p[0..4].try_into().ok()?); let h = u32::from_le_bytes(p[4..8].try_into().ok()?); - let rgba = lz4_flex::decompress_size_prepended(&p[8..]).ok()?; + let rgba = decompress_checked(&p[8..], Some((w as usize).checked_mul(h as usize)?.checked_mul(4)?))?; (rgba.len() == w as usize * h as usize * 4).then_some(Frame8 { width: w, height: h, rgba }) } +/// Whether a layer of `pixels` pixels (16 bytes each, decompressed) is within what a cache entry +/// may hold: a larger one could never be read back, so it is not compressed or written. +fn layer_fits(pixels: usize) -> bool { + pixels.checked_mul(16).is_some_and(|b| b <= MAX_ENTRY_BYTES) +} + /// Half floats with their low and high bytes in planes (per channel), then LZ4: the high bytes /// (sign, exponent) repeat a lot, mixed with the low ones LZ4 finds little. fn encode_frame_f16(w: u32, h: u32, rgba: &[u16]) -> Vec { @@ -1440,10 +1512,7 @@ fn decode_frame_f16(p: &[u8]) -> Option { let w = u32::from_le_bytes(p[0..4].try_into().ok()?); let h = u32::from_le_bytes(p[4..8].try_into().ok()?); let n = (w as usize).checked_mul(h as usize)?; - let planes = lz4_flex::decompress_size_prepended(&p[8..]).ok()?; - if planes.len() != n.checked_mul(8)? { - return None; - } + let planes = decompress_checked(&p[8..], Some(n.checked_mul(8)?))?; let mut rgba = vec![0u16; n * 4]; for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { for (c, v) in px.iter_mut().enumerate() { @@ -1486,9 +1555,9 @@ fn decode_layer(p: &[u8]) -> Option { let f = |i: usize| -> Option { Some(f64::from_le_bytes(p[i..i + 8].try_into().ok()?)) }; let offset = [f(8)?, f(16)?]; let scale = f(24)?; - let planes = lz4_flex::decompress_size_prepended(&p[32..]).ok()?; let n = (w as usize).checked_mul(h as usize)?; - if planes.len() != n.checked_mul(16)? { + let planes = decompress_checked(&p[32..], Some(n.checked_mul(16)?))?; + if planes.len() != n * 16 { return None; } let mut img = Image::new(w, h); @@ -1507,7 +1576,7 @@ fn decode_layer(p: &[u8]) -> Option { // ---------------------------------------------------------------- content keys /// Bump when rendering changes in a way that makes old disk entries wrong. -const RENDER_VERSION: &str = "effectcraft-render-6"; +const RENDER_VERSION: &str = "effectcraft-render-7"; /// Feeds the `Debug` form of `v` into the hash, followed by a separator byte. fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { @@ -1619,6 +1688,82 @@ pub fn frame_key(content: u128, frame: i64, scale_milli: u32, view: u64) -> u128 mod tests { use super::*; + #[cfg(unix)] + #[test] + fn a_cache_folder_in_the_temp_folder_is_made_private_and_never_a_link() { + use std::os::unix::fs::PermissionsExt; + let d = tmpdir("private"); + let dc = DiskCache::open(&d, 1 << 20).unwrap(); + assert_eq!(std::fs::metadata(&d).unwrap().permissions().mode() & 0o777, 0o700); + drop(dc); + let link = tmpdir("link-private-temp"); + std::os::unix::fs::symlink(&d, &link).unwrap(); + assert!(DiskCache::open(&link, 1 << 20).is_err()); + let _ = std::fs::remove_file(&link); + let _ = std::fs::remove_dir_all(&d); + } + + #[cfg(unix)] + #[test] + fn the_shared_temp_folder_itself_is_refused_as_a_cache_folder() { + let tmp = std::env::temp_dir(); + assert!(DiskCache::open(&tmp, 1 << 20).is_err()); + } + + #[cfg(unix)] + #[test] + fn a_folder_that_resolves_into_the_temp_folder_is_made_private() { + use std::os::unix::fs::PermissionsExt; + // `/link` names a folder in the temp folder only through the link. + let real = tmpdir("alias-real"); + std::fs::create_dir_all(&real).unwrap(); + let link = std::env::current_dir().unwrap().join(format!("effectcraft-alias-link-{}", std::process::id())); + let _ = std::fs::remove_file(&link); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let dc = DiskCache::open(link.join("cache"), 1 << 20).unwrap(); + let mode = std::fs::metadata(real.join("cache")).map(|m| m.permissions().mode() & 0o777); + drop(dc); + let _ = std::fs::remove_file(&link); + let _ = std::fs::remove_dir_all(&real); + assert_eq!(mode.unwrap(), 0o700); + } + + #[test] + fn layers_too_big_to_read_back_are_not_written() { + assert!(layer_fits(MAX_ENTRY_BYTES / 16)); + assert!(!layer_fits(MAX_ENTRY_BYTES / 16 + 1)); + assert!(!layer_fits(10_000 * 10_000)); + assert!(!layer_fits(usize::MAX)); + } + + #[test] + fn an_entry_stating_a_size_its_dimensions_do_not_need_is_not_decompressed() { + // A 2×2 frame whose payload states 3 GiB: refused before any allocation. + let mut p = 2u32.to_le_bytes().to_vec(); + p.extend_from_slice(&2u32.to_le_bytes()); + p.extend_from_slice(&(3u32 << 30).to_le_bytes()); + p.extend_from_slice(&[0; 16]); + assert!(decode_frame(&p).is_none()); + assert!(decompress_checked(&p[8..], None).is_none()); + // A well-formed entry still decodes. + let ok = encode_frame(2, 2, &[7; 16]); + assert_eq!(decode_frame(&ok).map(|f| f.rgba), Some(vec![7; 16])); + } + + #[test] + fn a_block_shorter_than_the_size_it_states_is_rejected() { + // The payload states 100 bytes but holds a valid block of 10: `lz4_flex` returns the 10. + let mut p = 100u32.to_le_bytes().to_vec(); + p.extend_from_slice(&lz4_flex::block::compress(&[5u8; 10])); + assert!(decompress_checked(&p, None).is_none()); + // A half-float frame whose planes come up short is refused, not indexed past. + let mut f16 = 2u32.to_le_bytes().to_vec(); + f16.extend_from_slice(&2u32.to_le_bytes()); + f16.extend_from_slice(&32u32.to_le_bytes()); + f16.extend_from_slice(&lz4_flex::block::compress(&[1u8; 8])); + assert!(decode_frame_f16(&f16).is_none()); + } + fn tmpdir(name: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("effectcraft-disk-cache-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); diff --git a/crates/render/src/eval.rs b/crates/render/src/eval.rs index 41e6132d3..a9abefb16 100644 --- a/crates/render/src/eval.rs +++ b/crates/render/src/eval.rs @@ -283,7 +283,7 @@ impl<'a> EvalCtx<'a> { } impl crate::PropertyOverride { - fn value(&self, layer: &Layer, prop: &Property, time: Tick) -> Value { + pub(crate) fn value(&self, layer: &Layer, prop: &Property, time: Tick) -> Value { if self.font { // A Font control merges only the font into the target text, as // `essential::with_overrides` does. diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index b1ec0ca02..c0f4c8dd9 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -56,6 +56,29 @@ pub struct MediaOverride { pub(crate) item: ItemId, } +/// The most pixels a solid layer's buffer holds (as the other layer buffers are held to). +const MAX_SOLID_PIXELS: f64 = 16.0e6; + +/// The scale and whole-pixel size of a `width`×`height` solid rendered at `scale`, lowered until +/// the rounded size (each side at least one pixel) is within [`MAX_SOLID_PIXELS`]. +pub(crate) fn solid_size(width: u32, height: u32, mut scale: f64) -> (f64, u32, u32) { + let size = |s: f64| (((width as f64 * s).ceil() as u32).max(1), ((height as f64 * s).ceil() as u32).max(1)); + // Rounding up leaves an elongated solid over the cap after one step; each step shrinks the + // overshoot geometrically, so a few are enough. + for i in 0..64 { + let (w, h) = size(scale); + let area = w as f64 * h as f64; + if area <= MAX_SOLID_PIXELS { + break; + } + // The first step is the exact area ratio; later ones undershoot a little so rounding up + // cannot leave the size stuck just over the cap. + scale *= (MAX_SOLID_PIXELS / area).sqrt() * if i == 0 { 1.0 } else { 0.99 }; + } + let (w, h) = size(scale); + (scale, w, h) +} + impl MediaOverride { /// A Media Replacement of `layer`'s footage by `item`. pub fn new(layer: LayerId, item: ItemId) -> Self { @@ -757,6 +780,15 @@ impl<'a> Renderer<'a> { return; } let Some(fx) = layer.effects() else { return }; + // The LUT files the stack reads go to this render's files: a frame on disk made with one + // that changed since is not used (#3493). + if let Some(log) = self.reads { + for g in fx.groups().take(limit).filter(|g| g.enabled) { + for f in super::reads::lut_files(ctx, layer, g) { + log.note(f); + } + } + } let lt = layer.layer_time(ctx.time); let layer_size = ctx.effect_bounds(layer).0; // #659 / #1205: an authored layer's buffer spans only its painted content. Effects that @@ -890,8 +922,9 @@ impl<'a> Renderer<'a> { match &layer.source { LayerSource::Solid { item } => { let ItemKind::Solid(sol) = &self.project.item(*item)?.kind else { return None }; - let w = ((sol.width as f64 * s).ceil() as u32).max(1); - let h = ((sol.height as f64 * s).ceil() as u32).max(1); + // One colour: a solid larger than MAX_SOLID_PIXELS is made at a lower scale (the + // buffer carries it) instead of allocating gigabytes for a uniform plane. + let (s, w, h) = solid_size(sol.width, sol.height, s); if layer.switches.adjustment { return Some(Buf { img: Image::filled(w, h, [1.0; 4]), offset: [0.0; 2], scale: s }); } diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index ed97e50fd..af0535e5a 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -35,9 +35,10 @@ impl FileStamp { } /// The identity of the file at `path` now: one `metadata` call. `None` when the file system - /// can't describe it (missing, or a path served from memory). + /// can't describe it (missing, not a regular file, or a path served from memory). pub fn native(path: &str) -> Option { - std::fs::metadata(path).ok().map(|md| FileStamp::of_metadata(&md)) + let md = std::fs::metadata(path).ok()?; + md.is_file().then(|| FileStamp::of_metadata(&md)) } } @@ -65,6 +66,34 @@ impl ReadFile { } } +/// The files effect `g` of `layer` reads at the context time (Apply Color LUT, Lumetri's Input +/// LUT and Look, OCIO File Transform, a custom OCIO config and its LUTs: see +/// [`effectcraft_effects::lut_params`]), each with its identity now. A layer's cache key holds them and a render +/// notes them, so what was made with a file that changed since is not used (#3493). +pub(crate) fn lut_files(ctx: &crate::EvalCtx, layer: &effectcraft_project::Layer, g: &effectcraft_project::PropGroup) -> Vec { + let effectcraft_project::GroupKind::Effect { effect } = &g.kind else { return Vec::new() }; + effectcraft_effects::lut_params(effect) + .iter() + .filter_map(|param| match ctx.value(layer, g.prop(param)?) { + effectcraft_keyframe::Value::Str(src) => Some(source_files(&src)), + _ => None, + }) + .flatten() + .collect() +} + +/// The files a file parameter set to `src` reads (an OCIO config's also the LUTs it names, #3538), +/// each with its identity now. +pub(crate) fn source_files(src: &str) -> Vec { + effectcraft_effects::lut_files(src) + .into_iter() + .map(|path| { + let stamp = FileStamp::native(&path).unwrap_or(FileStamp::Missing); + ReadFile::new(path, stamp) + }) + .collect() +} + /// At most this many files are listed per render or cached buffer; more mark the list /// incomplete (a comp reading more files than this for one frame is not checked file by file). pub const MAX_READ_FILES: usize = 4096; @@ -327,6 +356,15 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_directory_is_not_a_native_file_stamp() { + let dir = std::env::temp_dir().join(format!("effectcraft-stamp-directory-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + assert_eq!(FileStamp::native(&dir.to_string_lossy()), None); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn the_list_is_bounded() { let files: ReadFiles = (0..MAX_READ_FILES + 3).map(|i| file(&format!("/f{i:06}"), 1)).collect(); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 4cfa35d0b..2d0f90ac5 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -2002,3 +2002,17 @@ fn a_copy_of_an_overridden_clip_is_not_served_the_keyed_clips_pixels() { assert_same(&render(&keyed, Some(&cache)), &render(&keyed, None), "the keyed clip's copy"); assert_same(&render(&overridden, Some(&cache)), &render(&overridden, None), "the overridden clip's copy"); } + +#[test] +fn elongated_solids_stay_within_the_pixel_cap_after_rounding() { + use crate::pipeline::solid_size; + // 1 × 100 million at full scale: rounding up used to leave 40 million pixels. + for (w, h) in [(1u32, 100_000_000u32), (100_000_000, 1), (u32::MAX, u32::MAX), (1, u32::MAX)] { + let (s, pw, ph) = solid_size(w, h, 1.0); + assert!(s > 0.0 && f64::from(pw) * f64::from(ph) <= 16.0e6, "{w}x{h} -> {pw}x{ph} at {s}"); + } + // A solid within the cap keeps its scale; an over-cap square is lowered by the exact ratio. + assert_eq!(solid_size(4000, 4000, 1.0), (1.0, 4000, 4000)); + let (s, pw, ph) = solid_size(5000, 5000, 1.0); + assert!((s - 0.8).abs() < 0.01 && pw * ph <= 16_000_000); +} diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 1e95bbc11..eef5b4067 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -198,6 +198,35 @@ pub fn in_index_units(layer: &Layer, uid: effectcraft_project::Uid) -> bool { /// Selection of every glyph by an animator's selectors, per dimension. pub fn animator_selection(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: &TextLayout) -> Vec<[f64; 3]> { + animator_selection_within(ctx, layer, anim, lay, &SelectorBudget::new()) +} + +/// The Expression Selector evaluations one layer's animators may run in all: counted, not timed, +/// so the same frame renders the same on every machine. +pub struct SelectorBudget(std::cell::Cell); + +impl SelectorBudget { + pub fn new() -> SelectorBudget { + SelectorBudget(std::cell::Cell::new(MAX_SELECTOR_EVALS)) + } + + /// Take one evaluation; `false` when none are left. + fn take(&self) -> bool { + let left = self.0.get(); + self.0.set(left.saturating_sub(1)); + left > 0 + } +} + +impl Default for SelectorBudget { + fn default() -> Self { + Self::new() + } +} + +/// [`animator_selection`] drawing its Expression Selector evaluations from `budget`, which the +/// caller shares across the layer's animators. +pub fn animator_selection_within(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: &TextLayout, budget: &SelectorBudget) -> Vec<[f64; 3]> { let sels: Vec<&PropGroup> = anim.sub("selectors").map(|s| s.groups().filter(|g| g.enabled).collect()).unwrap_or_default(); if sels.is_empty() { // No selectors: every character is fully affected. @@ -250,13 +279,31 @@ pub fn animator_selection(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: & { log.mark_unkeyed(); } - let stat = ctx.v3(layer, sel, "amount", [100.0; 3]); + // The keyframed amount, read without running its expression (the fallback when the + // expression cannot run); an Essential Property override still applies. + let stat = if prop.has_expression() { + // The expression is not run here, but an Essential Property override still wins over the base value. + match ctx.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == prop.uid) { + Some(o) => o.value(layer, prop, ctx.time), + None => prop.value_at(layer.layer_time(ctx.time)), + } + } else { + ctx.value(layer, prop) + } + .as_vec3(); + // One allowance for the whole layer (`budget`, shared by its animators): the + // expression runs per character, so a slow expression on a long text is stopped + // once it has failed or the layer's evaluations pass MAX_SELECTOR_EVALS. + let stopped = std::cell::Cell::new(false); Box::new(move |i, n, prev| { let pv = prev.map(|x| x * 100.0); // Without an expression engine: the static amount scales the selection. let fallback = [0, 1, 2].map(|d| stat[d] * prev[d]); - let r = match ctx.expr.filter(|_| prop.has_expression()) { - Some(h) => h.eval_text_selector(ctx, layer, prop, i, n, pv).unwrap_or(fallback), + let r = match ctx.expr.filter(|_| prop.has_expression() && !stopped.get() && budget.take()) { + Some(h) => h.eval_text_selector(ctx, layer, prop, i, n, pv).unwrap_or_else(|_| { + stopped.set(true); + fallback + }), None => fallback, }; r.map(|x| (x / 100.0).clamp(-1.0, 1.0)) @@ -282,13 +329,17 @@ pub fn animator_selection(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: & acc } +/// The most Expression Selector evaluations one layer's animators run across all its characters +/// (a text of 32,768 characters under one expression selector, or fewer under several). +const MAX_SELECTOR_EVALS: usize = 32_768; /// Evaluate animators for every glyph. pub fn char_transforms(ctx: &EvalCtx, layer: &Layer, text: &PropGroup, lay: &TextLayout) -> Vec { let mut out = vec![CharXf::default(); lay.glyphs.len()]; let Some(anims) = text.sub("animators") else { return out }; + let budget = SelectorBudget::new(); for anim in anims.groups().filter(|g| g.enabled) { let Some(props) = anim.sub("properties") else { continue }; - let sel = animator_selection(ctx, layer, anim, lay); + let sel = animator_selection_within(ctx, layer, anim, lay, &budget); let get = |m: &str| props.get(m).map(|p| ctx.value(layer, p).components()); let get1 = |m: &str| props.get(m).map(|p| ctx.value(layer, p).as_f64()); let c3 = |v: Vec, d: f64| [v.first().copied().unwrap_or(d), v.get(1).copied().unwrap_or(d), v.get(2).copied().unwrap_or(d)]; diff --git a/crates/render/src/text/tests.rs b/crates/render/src/text/tests.rs index 9b52d3098..bbc1cd28e 100644 --- a/crates/render/src/text/tests.rs +++ b/crates/render/src/text/tests.rs @@ -802,3 +802,12 @@ fn text_notes_the_font_files_it_draws_with() { assert!(files.is_complete(), "{files:?}"); assert_eq!(files.get(&font.to_string_lossy()), Some(stamp), "{files:?}"); } + +#[test] +fn selector_evaluations_are_counted_across_the_layer_not_timed() { + let b = SelectorBudget(std::cell::Cell::new(3)); + // Taken by any animator's selectors in turn; the fourth finds none, and stays none. + assert!([b.take(), b.take(), b.take()].iter().all(|t| *t)); + assert!(!b.take() && !b.take()); + assert_eq!(SelectorBudget::new().0.get(), MAX_SELECTOR_EVALS); +} diff --git a/crates/render/src/three_d/adv/raster.rs b/crates/render/src/three_d/adv/raster.rs index 1c37a6267..f0d6028f9 100644 --- a/crates/render/src/three_d/adv/raster.rs +++ b/crates/render/src/three_d/adv/raster.rs @@ -126,11 +126,14 @@ fn setup(s: &Scene, clip: &[[f32; 4]], range: std::ops::Range) -> Vec= bbox[2] || bbox[1] >= bbox[3] { continue; diff --git a/crates/render/src/three_d/camera.rs b/crates/render/src/three_d/camera.rs index 6aee50a78..18f6dfe8a 100644 --- a/crates/render/src/three_d/camera.rs +++ b/crates/render/src/three_d/camera.rs @@ -302,6 +302,13 @@ pub fn auto_orient_2d(ctx: &EvalCtx, layer: &Layer) -> f64 { path_tangent(ctx, layer).map(|t| t.y.atan2(t.x).to_degrees()).unwrap_or(0.0) } +/// The most camera-facing layers whose parents are evaluated inside one another. +const MAX_ORIENT_NESTING: usize = 8; + +thread_local! { + static ORIENT_NESTING: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Whether `id` is `layer` or one of its parents. fn in_parent_chain(ctx: &EvalCtx, layer: &Layer, id: effectcraft_project::LayerId) -> bool { let mut cur = Some(layer); @@ -336,8 +343,27 @@ pub fn auto_orient_3d(ctx: &EvalCtx, layer: &Layer, pos: Vec3) -> Option { if ctx.comp.active_camera(ctx.time).is_some_and(|c| in_parent_chain(ctx, c, layer.id)) { return None; } + // The parent's world matrix evaluates the parent's own orientation: a parent cycle + // of camera-facing layers would recurse without end, and a chain of them is walked + // again from every link. Past MAX_ORIENT_NESTING the layer keeps its Orientation. + let nesting = ORIENT_NESTING.with(|n| n.get()); + if nesting >= MAX_ORIENT_NESTING { + return None; + } + // Restored when this scope ends, a panic unwinding through it included (the CPU retry + // after one must not start with a raised count). + struct Restore(usize); + impl Drop for Restore { + fn drop(&mut self) { + ORIENT_NESTING.with(|n| n.set(self.0)); + } + } + ORIENT_NESTING.with(|n| n.set(nesting + 1)); + let restore = Restore(nesting); + let parent = parent_world(ctx, layer); + drop(restore); let eye = active_camera(ctx).eye; - let e = parent_world(ctx, layer).inverse().unwrap_or(Mat4::IDENTITY).apply(eye); + let e = parent.inverse().unwrap_or(Mat4::IDENTITY).apply(eye); let d = pos - e; (d.length() > 1e-9).then(|| basis_rotation(d, vec3(0.0, 1.0, 0.0))) } diff --git a/crates/script/src/model.rs b/crates/script/src/model.rs index e662c1cdc..62f3a8557 100644 --- a/crates/script/src/model.rs +++ b/crates/script/src/model.rs @@ -5,6 +5,7 @@ use effectcraft_engine::Session; use effectcraft_engine::color::Label; use effectcraft_keyframe::{Interp, TextDoc, Value as KV}; +use effectcraft_project::ae_order::{self, AeChild}; use effectcraft_project::{Comp, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, ParamUi, PropGroup}; use effectcraft_render::EvalCtx; use effectcraft_time::Tick; @@ -318,7 +319,8 @@ fn indexed_parade(g: &PropGroup) -> bool { fn node_json(c: &Comp, l: &Layer, uid: u64) -> R { if uid == 0 || uid == l.props.uid { - let n = l.props.children.len(); + // After Effects' count (every slot, used or not); 3D model layers count their own groups. + let n = ae_order::ae_count(l).unwrap_or(l.props.children.len()); return Ok(json!({ "uid": l.props.uid, "kind": "group", "name": l.name, "matchName": matchnames::layer(&l.source), "matchId": "layer", "index": c.index_of(l.id).unwrap_or(0), "depth": 0, "parent": null, "isLayer": true, "numProperties": n, @@ -329,7 +331,8 @@ fn node_json(c: &Comp, l: &Layer, uid: u64) -> R { let ch = chain(l, uid).ok_or("the property no longer exists (it was deleted)")?; let node = *ch.last().ok_or("bad property")?; let parent_group: &PropGroup = if ch.len() >= 2 { ch[ch.len() - 2].as_group().ok_or("bad tree")? } else { &l.props }; - let index = parent_group.children.iter().position(|x| x.uid() == uid).map(|i| i + 1).unwrap_or(0); + let top = if ch.len() == 1 { ae_order::ae_index(l, node.match_id()) } else { None }; + let index = top.unwrap_or_else(|| parent_group.children.iter().position(|x| x.uid() == uid).map(|i| i + 1).unwrap_or(0)); let parent_uid = if ch.len() >= 2 { ch[ch.len() - 2].uid() } else { l.props.uid }; let match_name = matchnames::node(&ch); let instance_parent = indexed_parade(parent_group) && ch.len() >= 2 || (ch.len() == 2 && ch[0].match_id() == "contents"); @@ -475,6 +478,25 @@ fn child(s: &Session, a: &J) -> R { let uid = u(a, "uid").unwrap_or(0); let g: &PropGroup = if uid == 0 || uid == l.props.uid { &l.props } else { l.props.find_group(uid).ok_or("not a property group")? }; let key = a.get("key").cloned().unwrap_or(J::Null); + // A layer's numbers and match names are After Effects' (Marker is 1, unused groups keep their + // slot and resolve to the same empty group by number or by match name). + let slot = match &key { + J::Number(n) => Some(n.as_u64().and_then(|i| usize::try_from(i).ok())), + J::String(name) => ae_order::ae_index_of_match_name(l, name).map(Some), + _ => None, + }; + if std::ptr::eq(g, &l.props) + && ae_order::ae_slots(&l.source).is_some() + && let Some(slot) = slot + { + let Some(i) = slot else { return Ok(J::Null) }; + return match ae_order::ae_child(l, i) { + Some(AeChild::Node(n)) => node_json(c, l, n.uid()), + Some(AeChild::Marker) => Ok(json!({"marker": true})), + Some(AeChild::Absent(s)) => Ok(json!({"absent": true, "name": s.name, "matchName": s.match_name, "index": i})), + None => Ok(J::Null), + }; + } let found = match &key { J::Number(n) => n.as_u64().and_then(|i| g.children.get((i as usize).checked_sub(1)?)), J::String(k) => find_child(l, g, k, NESTED_CHILD_DEPTH), diff --git a/crates/script/src/prelude.js b/crates/script/src/prelude.js index 5adab6eec..4b65a5298 100644 --- a/crates/script/src/prelude.js +++ b/crates/script/src/prelude.js @@ -653,10 +653,46 @@ TextDocument.prototype = { function __propOf(layer, info) { if (!info) return null; if (info.isLayer) return layer; + if (info.marker) return layer.marker; + if (info.absent) return __absentGroup(layer, info); if (info.kind === "group") return info.isMask ? new MaskPropertyGroup(layer, info.uid) : new PropertyGroup(layer, info.uid); return new Property(layer, info.uid); } +// A top-level slot After Effects always has and this layer does not use yet (Layer Styles before +// any style, Data, Sets…): an empty group, so loops over `numProperties` meet no null. +function __absentGroup(layer, info) { + var g = { + __kind: "PropertyGroup", + get name() { return info.name; }, + get matchName() { return info.matchName; }, + get propertyIndex() { return info.index; }, + get propertyDepth() { return 1; }, + get propertyType() { return PropertyType.NAMED_GROUP; }, + get parentProperty() { return layer; }, + get numProperties() { return 0; }, + get enabled() { return true; }, + get active() { return layer.enabled; }, + get canSetEnabled() { return false; }, + get isModified() { return false; }, + get isEffect() { return false; }, + get isMask() { return false; }, + get elided() { return false; }, + get selected() { return false; }, + property: function () { return null; }, + propertyGroup: function (n) { return n === undefined || n === 1 ? layer : null; }, + canAddProperty: function () { return false; }, + addProperty: function (n) { throw __err("Can not add \"" + n + "\" to \"" + info.name + "\""); }, + toString: function () { return "[object PropertyGroup]"; }, + }; + // Callable like any group: `layer.property(7)(1)` is `.property(1)`, null. + var f = function (k) { return g.property(k); }; + delete f.name; + delete f.length; + for (const k of Object.getOwnPropertyNames(g)) Object.defineProperty(f, k, Object.getOwnPropertyDescriptor(g, k)); + return f; +} + function PropertyBase() {} PropertyBase.prototype = { __info: function () { return __get("node", { comp: this.__layer.__comp, layer: this.__layer.__id, uid: this.__uid }); }, diff --git a/crates/script/src/tests.rs b/crates/script/src/tests.rs index 800ccdde7..8995b8202 100644 --- a/crates/script/src/tests.rs +++ b/crates/script/src/tests.rs @@ -10,6 +10,7 @@ use serde_json::{Value, json}; use crate::{Outcome, run_code}; +mod ae_layer_order; mod callable; mod ease_presets; mod evalfile; diff --git a/crates/script/src/tests/ae_layer_order.rs b/crates/script/src/tests/ae_layer_order.rs new file mode 100644 index 000000000..869ce348a --- /dev/null +++ b/crates/script/src/tests/ae_layer_order.rs @@ -0,0 +1,121 @@ +//! `layer.property(n)` and the layer's `numProperties` use After Effects' top-level numbers +//! (`project::ae_order`): Marker is 1 and unused slots keep their place as empty groups, so a loop +//! over `numProperties` meets every slot and never a null. + +use std::sync::Arc; + +use effectcraft_engine::Session; +use serde_json::json; + +use crate::{Outcome, run_code}; + +fn session() -> Session { + let mut s = Session { expr: Some(Arc::new(effectcraft_expr::Expressions)), expr_check: Some(effectcraft_expr::check_syntax), ..Default::default() }; + crate::install(&mut s); + s +} + +fn ok(s: &mut Session, code: &str) -> Outcome { + let o = run_code(s, code, "test.jsx"); + assert!(o.error.is_none(), "script failed: {:?}\noutput: {:?}", o.error, o.output); + o +} + +#[test] +fn layer_numbers_follow_after_effects() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var c = app.project.items.addComp("M", 200, 200, 1, 2, 30); + var solid = c.layers.addSolid([1, 1, 1], "S", 200, 200, 1); + solid.Effects.addProperty("ADBE Slider Control"); + var shape = c.layers.addShape(); + var text = c.layers.addText("t"); + var cam = c.layers.addCamera("Cam", [100, 100]); + function names(l) { var o = []; for (var i = 1; i <= l.numProperties; i++) o.push(l.property(i).matchName); return o; } + [names(solid), names(shape), names(text), names(cam), + solid.property(5)(1)(1).value, solid.property(5).propertyIndex, solid.property("Effects").propertyIndex, + solid.property(1) === solid.marker || solid.property(1).matchName, solid.property(16)] + "#, + ); + let av = [ + "ADBE Marker", + "ADBE Time Remapping", + "ADBE MTrackers", + "ADBE Mask Parade", + "ADBE Effect Parade", + "ADBE Transform Group", + "ADBE Layer Styles", + "ADBE Plane Options Group", + "ADBE Extrsn Options Group", + "ADBE Material Options Group", + "ADBE Audio Group", + "ADBE Data Group", + "ADBE Layer Overrides", + "ADBE Layer Sets", + "ADBE Source Options Group", + ]; + let vector = |first: &str| { + json!([ + "ADBE Marker", + first, + "ADBE Mask Parade", + "ADBE Effect Parade", + "ADBE Transform Group", + "ADBE Layer Styles", + "ADBE Extrsn Options Group", + "ADBE Material Options Group", + "ADBE Audio Group", + "ADBE Layer Sets" + ]) + }; + let r = o.result.as_array().unwrap(); + assert_eq!(r[0], json!(av), "solid"); + assert_eq!(r[1], vector("ADBE Root Vectors Group"), "shape"); + assert_eq!(r[2], vector("ADBE Text Properties"), "text"); + assert_eq!(r[3], json!(["ADBE Marker", "ADBE Transform Group", "ADBE Camera Options Group"]), "camera"); + assert_eq!(r[4], json!(0), "the slider's value through property(5)"); + assert_eq!(r[5], json!(5)); + assert_eq!(r[6], json!(5), "propertyIndex by name is After Effects' too"); + assert_eq!(r[7], json!("ADBE Marker")); + assert_eq!(r[8], json!(null), "past the last slot"); +} + +#[test] +fn walking_every_property_meets_no_null() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var c = app.project.items.addComp("M", 200, 200, 1, 2, 30); + var l = c.layers.addShape(); + var n = 0; + function walk(g) { + for (var i = 1; i <= g.numProperties; i++) { + var p = g.property(i); + if (p === null) throw new Error("null at " + i + " of " + g.name); + if (p.propertyType === PropertyType.PROPERTY) n++; else walk(p); + } + } + walk(l); + n > 0 + "#, + ); + assert_eq!(o.result, json!(true)); +} + +#[test] +fn an_unused_slot_is_the_same_by_number_and_match_name_and_callable() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var c = app.project.items.addComp("M", 200, 200, 1, 2, 30); + var l = c.layers.addSolid([1, 1, 1], "S", 200, 200, 1); + var byName = l.property("ADBE Layer Styles"), byNumber = l.property(7); + [byName !== null && byName.matchName, byName !== null && byName.numProperties, byNumber.propertyIndex, l.property(7)(1), l(12).name] + "#, + ); + assert_eq!(o.result, json!(["ADBE Layer Styles", 0, 7, null, "Data"])); +} diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 2b6b7a280..6a1e4d741 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "effectcraft-svg" -description = "SVG import: parses SVG 1.1 / SVG 2 static vector content (paths, basic shapes, groups, transforms, use, CSS styles, solid and gradient fills/strokes, opacity) and rasterises it at any scale" +description = "SVG import: parses SVG 1.1 / SVG 2 static vector content (paths, basic shapes, groups, transforms, use, CSS styles, solid, gradient and pattern fills/strokes, opacity) and rasterises it at any scale" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/svg/README.md b/crates/svg/README.md index 862bd01d0..f39156f22 100644 --- a/crates/svg/README.md +++ b/crates/svg/README.md @@ -18,9 +18,31 @@ here, plus **CSS Color Module Level 3** for colour keywords and functions: `stroke-opacity`, `opacity`, `display`, `visibility`, `color`/`currentColor`; - `linearGradient` and `radialGradient` (with `fx`/`fy` focal point), `gradientUnits`, `gradientTransform`, `spreadMethod`, `href` inheritance of stops and attributes; +- static (non-animated) `` fill/stroke with `patternUnits`, `patternContentUnits`, `patternTransform`, + tile `x`/`y`/`width`/`height`, local `href`/`xlink:href` inheritance and solid paints on + supported shape/group children; - styling through presentation attributes, the `style` attribute and `