diff --git a/Cargo.lock b/Cargo.lock index feec44ceb..e6450c078 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1089,39 +1089,70 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-aep" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" + [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", "thiserror 2.0.21", ] [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" + +[[package]] +name = "craft-dpx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +dependencies = [ + "thiserror 2.0.21", +] [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "serde", "serde_json", "thiserror 2.0.21", ] +[[package]] +name = "craft-eps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" + +[[package]] +name = "craft-exr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" + +[[package]] +name = "craft-gif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1141,10 +1172,19 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-lottie" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +dependencies = [ + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "thiserror 2.0.21", ] @@ -1157,19 +1197,39 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-mesh" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +dependencies = [ + "miniz_oxide 0.9.1", + "serde_json", +] + [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "hayro-syntax", "thiserror 2.0.21", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "dispatch2", "egui", @@ -1177,10 +1237,22 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +dependencies = [ + "craft-xml", + "flate2", + "kurbo", + "roxmltree", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1201,7 +1273,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "chrono", "dunce", @@ -1228,13 +1300,30 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", "rayon", "thiserror 2.0.21", ] +[[package]] +name = "craft-webp" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1469,6 +1558,7 @@ dependencies = [ "serde", "serde_json", "sysinfo", + "tempfile", "winit", "winresource", "zbus", @@ -1478,6 +1568,7 @@ dependencies = [ name = "effectcraft-aep" version = "0.24.1" dependencies = [ + "craft-aep", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -1592,7 +1683,7 @@ name = "effectcraft-export" version = "0.24.1" dependencies = [ "craft-audio", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", "craft-video", "effectcraft-color", "effectcraft-effects", @@ -1738,6 +1829,7 @@ name = "effectcraft-lottie" version = "0.24.1" dependencies = [ "craft-docpath", + "craft-lottie", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -1757,7 +1849,11 @@ version = "0.24.1" dependencies = [ "craft-audio", "craft-docpath", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)", + "craft-dpx", + "craft-exr", + "craft-gif", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", + "craft-webp", "effectcraft-color", "effectcraft-effects", "effectcraft-model", @@ -1788,12 +1884,11 @@ dependencies = [ name = "effectcraft-model" version = "0.24.1" dependencies = [ + "craft-mesh", "effectcraft-geom", "image", "log", - "miniz_oxide 0.9.1", "serde", - "serde_json", "thiserror 2.0.21", ] @@ -1820,6 +1915,7 @@ dependencies = [ name = "effectcraft-pdf" version = "0.24.1" dependencies = [ + "craft-eps", "craft-pdf", "effectcraft-raster", "effectcraft-svg", @@ -1862,6 +1958,7 @@ dependencies = [ name = "effectcraft-psd" version = "0.24.1" dependencies = [ + "craft-psd", "miniz_oxide 0.9.1", ] @@ -1869,6 +1966,7 @@ dependencies = [ name = "effectcraft-raster" version = "0.24.1" dependencies = [ + "craft-exr", "effectcraft-color", "effectcraft-geom", "rayon", @@ -1944,6 +2042,7 @@ dependencies = [ name = "effectcraft-svg" version = "0.24.1" dependencies = [ + "craft-svg", "effectcraft-geom", "effectcraft-path", "effectcraft-raster", @@ -3323,7 +3422,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "hayro-ccitt", ] @@ -3337,7 +3436,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" dependencies = [ "hayro-jbig2", "hayro-jpeg2000", @@ -4656,7 +4755,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 c812a3294..1b80048f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,12 +11,22 @@ rust-version = "1.95" repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.1.0", default-features = false, features = ["read"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" } -craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" } -craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.1.0", default-features = false, features = ["read"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["stl", "obj", "gltf", "fbx"] } +craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["egui"] } # internal effectcraft-time = { path = "crates/time" } effectcraft-geom = { path = "crates/geom" } @@ -80,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 = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", default-features = false, features = ["isobmff", "matroska"] } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] } -craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["isobmff", "matroska"] } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] } +craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } # footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001). # Only `crates/media`, `crates/export` and `crates/interchange` may depend on these. @@ -112,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 = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["serde"] } +craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["serde"] } # `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()` # and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate. egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] } @@ -221,8 +231,8 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.3.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.3.0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } 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/Cargo.toml b/crates/aep/Cargo.toml index 3deb09de2..0523edb9b 100644 --- a/crates/aep/Cargo.toml +++ b/crates/aep/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-aep = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } effectcraft-keyframe = { workspace = true } @@ -21,8 +22,3 @@ thiserror = { workspace = true } [dev-dependencies] serde_json = { workspace = true } - -# The tool's own tests run with the crate's (examples are only built by default). -[[example]] -name = "stubicc" -test = true diff --git a/crates/aep/README.md b/crates/aep/README.md index 39c8dd448..0e65d86f8 100644 --- a/crates/aep/README.md +++ b/crates/aep/README.md @@ -3,7 +3,9 @@ After Effects projects (`.aep`, `.aepx`) in one crate, the way `effectcraft-lottie` handles Lottie: - `container`: reads and writes the container as a lossless chunk tree, with a typed, read-only - view (below; its API is re-exported at the crate root); + view (below). This is `craft-aep` from [storytold/craft-libs](https://github.com/storytold/craft-libs), + re-exported at the crate root; its container tests and the `aepdump`/`stubicc` tools are there. + Only `effect_map` and `style_map` (After Effects effects and layer styles to EffectCraft's) are here; - `import`: maps the typed view into an EffectCraft project and reports everything it does not import ([`docs/aep-import.md`](../../docs/aep-import.md)); - `export`: writes an EffectCraft project as an `.aep` with every chunk built in code, and reports everything it does not export @@ -92,14 +94,9 @@ the import against After Effects' read-back, and the host's `vector_import` test - `tests/fixtures/tools/`: the generator of the test projects (regenerates the corpus with After Effects; its README says how). -- `examples/aepdump.rs`: prints the chunk tree of a file (ids, sizes, short data, match names): - `cargo run -p effectcraft-aep --example aepdump -- file.aep`. -- `examples/stubicc.rs`: replaces every embedded ICC profile of a saved project by a stub that keeps - only the profile's description: the JSON `colorProfileData` of the working space (any white space - around the colon, `\/` escapes, quotes as `"`) in an `.aep` chunk or the `.aepx` text, and a raw - profile of an imported image (an `.aep` chunk, or the `bdata` hex of an `.aepx`): - `cargo run -p effectcraft-aep --example stubicc -- in.aep out.aep`. A profile it cannot replace - stops it before anything is written. The importer reads the working space's name from the - description only, so the project imports the same; no vendor colour data stays in the test - project. Check the result independently, not by the tool's count (the corpus repository has - `tools/aep/inspect-embedded.py`, which scans the raw bytes, base64 and hex). +- `aepdump` (prints the chunk tree of a file) and `stubicc` (replaces every embedded ICC profile of a + saved project by a stub) are examples of `craft-aep` in + [storytold/craft-libs](https://github.com/storytold/craft-libs): + `cargo run -p craft-aep --example stubicc -- in.aep out.aep` there. Check the result independently, + not by the tool's count (the corpus repository has `tools/aep/inspect-embedded.py`, which scans the + raw bytes, base64 and hex). diff --git a/crates/aep/examples/aepdump.rs b/crates/aep/examples/aepdump.rs deleted file mode 100644 index 2fe492696..000000000 --- a/crates/aep/examples/aepdump.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! Developer tool: prints the chunk tree of an .aep (ids, sizes, short data), match names inline. -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use effectcraft_aep::{Body, Chunk}; - -/// Ends this developer tool with a message instead of a panic. -trait OrExit { - fn or_exit(self, what: &str) -> T; -} - -impl OrExit for Option { - fn or_exit(self, what: &str) -> T { - match self { - Some(v) => v, - None => exit(what), - } - } -} - -impl OrExit for Result { - fn or_exit(self, what: &str) -> T { - match self { - Ok(v) => v, - Err(e) => exit(&format!("{what}: {e:?}")), - } - } -} - -fn exit(msg: &str) -> ! { - eprintln!("{msg}"); - std::process::exit(1) -} - -fn show(c: &Chunk<'_>, depth: usize, max: usize, hex: usize) { - let ind = " ".repeat(depth); - let id = String::from_utf8_lossy(&c.id).to_string(); - match &c.body { - Body::Data(d) if &c.id == b"tdmn" => { - let n: String = d.iter().take_while(|b| **b != 0).map(|b| *b as char).collect(); - println!("{ind}tdmn {n}"); - } - Body::Data(d) => { - let h: String = d.iter().take(hex).map(|b| format!("{b:02x}")).collect(); - let a: String = d.iter().take(hex).map(|b| if (32..127).contains(b) { *b as char } else { '.' }).collect(); - println!("{ind}{id} [{}] {h} |{a}|", d.len()); - } - Body::Chunks(k) => { - println!("{ind}{id} (nested)"); - if depth < max { - for x in k { - show(x, depth + 1, max, hex); - } - } - } - Body::List { list_type, children } => { - println!("{ind}LIST {} ({} children)", String::from_utf8_lossy(list_type), children.len()); - if depth < max { - for x in children { - show(x, depth + 1, max, hex); - } - } - } - Body::OpaqueList { list_type, data } => println!("{ind}LIST {} opaque [{}]", String::from_utf8_lossy(list_type), data.len()), - } -} -fn main() { - let a: Vec = std::env::args().collect(); - let bytes = std::fs::read(a.get(1).or_exit("usage: see the comment at the top of this file")).or_exit("read"); - let max: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(4); - let hex: usize = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(32); - let f = effectcraft_aep::parse(&bytes).or_exit("parse"); - for c in &f.chunks { - show(c, 0, max, hex); - } - println!("trailer {} bytes", f.trailer.len()); -} diff --git a/crates/aep/examples/stubicc.rs b/crates/aep/examples/stubicc.rs deleted file mode 100644 index 9438da06d..000000000 --- a/crates/aep/examples/stubicc.rs +++ /dev/null @@ -1,359 +0,0 @@ -//! Developer tool: replaces every embedded ICC profile of an .aep / .aepx by a stub that keeps only the -//! profile's description. Fixture hygiene: a saved project carries the vendor's working-space profile -//! (a few KB of colour data); the importer reads only the profile's name, the `desc` tag, so the stub -//! (a 128-byte header, one `desc` tag, no colour data, made here) imports identically. -//! -//! `cargo run -p effectcraft-aep --example stubicc -- in.aep out.aep` -//! -//! It handles: -//! - the JSON value `"colorProfileData": ""` in any chunk of an .aep and anywhere in the text -//! of an .aepx (white space around the colon, `\/` escapes and quotes written as `"` allowed); -//! - a raw ICC profile stored as a chunk of its own (the profile of an imported image), in an .aep -//! as the chunk's bytes and in an .aepx as its `bdata=""` attribute. -//! -//! A profile it cannot replace (no readable description, data that does not decode) stops the tool -//! before anything is written. Check the result independently (the corpus has -//! `tools/aep/inspect-embedded.py`), not by this tool's own count. -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use effectcraft_aep::{Body, Chunk}; - -const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -/// Ends this developer tool with a message instead of a panic. -trait OrExit { - fn or_exit(self, what: &str) -> T; -} - -impl OrExit for Option { - fn or_exit(self, what: &str) -> T { - match self { - Some(v) => v, - None => exit(what), - } - } -} - -impl OrExit for Result { - fn or_exit(self, what: &str) -> T { - match self { - Ok(v) => v, - Err(e) => exit(&format!("{what}: {e:?}")), - } - } -} - -fn exit(msg: &str) -> ! { - eprintln!("{msg}"); - std::process::exit(1) -} - -fn b64_decode(text: &[u8]) -> Option> { - let (mut out, mut acc, mut bits) = (Vec::new(), 0u32, 0u32); - for &c in text.iter().filter(|c| **c != b'=') { - let v = u32::try_from(B64.iter().position(|b| *b == c)?).ok()?; - acc = (acc << 6 | v) & 0x00ff_ffff; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push(((acc >> bits) & 0xff) as u8); - } - } - Some(out) -} - -fn b64_encode(data: &[u8]) -> Vec { - let mut out = Vec::new(); - for ch in data.chunks(3) { - let at = |i: usize| u32::from(ch.get(i).copied().unwrap_or(0)); - let n = (at(0) << 16) | (at(1) << 8) | at(2); - for i in 0..4usize { - if i <= ch.len() { - out.push(B64.get(((n >> (18 - 6 * i)) & 63) as usize).copied().unwrap_or(b'A')); - } else { - out.push(b'='); - } - } - } - out -} - -fn be32(d: &[u8], at: usize) -> Option { - let b: [u8; 4] = d.get(at..at.checked_add(4)?)?.try_into().ok()?; - usize::try_from(u32::from_be_bytes(b)).ok() -} - -/// The profile description (ICC.1 `desc`: v2 ASCII or v4 `mluc`, first record). -fn description(icc: &[u8]) -> Option { - let count = be32(icc, 128)?; - let tag = (0..count.min(1024)).find_map(|i| { - let at = 132usize.checked_add(i.checked_mul(12)?)?; - (icc.get(at..at.checked_add(4)?)? == b"desc").then_some(at) - })?; - let off = be32(icc, tag.checked_add(4)?)?; - let body = icc.get(off..off.checked_add(be32(icc, tag.checked_add(8)?)?)?)?; - let text = match body.get(..4)? { - b"desc" => { - let n = be32(body, 8)?; - String::from_utf8_lossy(body.get(12..12usize.checked_add(n)?)?.split(|b| *b == 0).next()?).into_owned() - } - b"mluc" => { - let (n, at) = (be32(body, 20)?, be32(body, 24)?); - let units: Vec = body.get(at..at.checked_add(n)?)?.chunks(2).filter_map(|p| Some(u16::from_be_bytes([*p.first()?, *p.get(1)?]))).collect(); - String::from_utf16_lossy(&units) - } - _ => return None, - }; - Some(text.trim_end_matches('\0').trim().to_owned()) -} - -/// A profile with a header, one `desc` tag and no colour data. -fn stub(desc: &str) -> Option> { - let mut body = b"desc\0\0\0\0".to_vec(); - body.extend_from_slice(&u32::try_from(desc.len().checked_add(1)?).ok()?.to_be_bytes()); - body.extend_from_slice(desc.as_bytes()); - body.push(0); - body.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); - let mut p = vec![0u8; 128]; - for (at, v) in [(8, &0x0240_0000u32.to_be_bytes()[..]), (12, b"mntr"), (16, b"RGB "), (20, b"XYZ "), (36, b"acsp")] { - p.get_mut(at..at + v.len())?.copy_from_slice(v); - } - p.extend_from_slice(&1u32.to_be_bytes()); - p.extend_from_slice(b"desc"); - p.extend_from_slice(&144u32.to_be_bytes()); - p.extend_from_slice(&u32::try_from(body.len()).ok()?.to_be_bytes()); - p.extend_from_slice(&body); - let size = u32::try_from(p.len()).ok()?.to_be_bytes(); - p.get_mut(..4)?.copy_from_slice(&size); - Some(p) -} - -/// The JSON key, without its quotes. -const KEY: &[u8] = b"colorProfileData"; -/// How a JSON quote is written: as is (a `Utf8` chunk, the `` text of an .aepx) and as an -/// XML entity (JSON inside an attribute of an .aepx). -const QUOTES: [&[u8]; 2] = [b"\"", b"""]; - -/// What the tool did, counted. -#[derive(Default)] -struct Tally { - stubbed: usize, - /// Values too short to be a profile (no ICC header), kept as they are. - kept_short: usize, - /// Profiles that could not be replaced (no readable description, undecodable data): the tool - /// fails, so no profile is ever left behind silently. - failed: Vec, -} - -fn is_profile(d: &[u8]) -> bool { - d.len() > 132 && d.get(36..40) == Some(b"acsp") -} - -/// The stub for the bytes `d` of a value, or `None` (counted) when it holds no profile or the -/// profile has no readable description. -fn stub_of(d: &[u8], at: usize, tally: &mut Tally) -> Option> { - if !is_profile(d) { - tally.kept_short += 1; - return None; - } - let s = description(d).and_then(|t| stub(&t)); - if s.is_none() { - tally.failed.push(format!("profile at byte {at}: no readable description")); - } - s -} - -/// At the start of `t`: the key in quotes, optional white space, a colon, optional white space and -/// the opening quote of the value. Returns the length up to and including that quote, and the quote. -fn value_start(t: &[u8]) -> Option<(usize, &'static [u8])> { - let ws = |mut i: usize| { - while t.get(i).is_some_and(u8::is_ascii_whitespace) { - i += 1; - } - i - }; - QUOTES.into_iter().find_map(|q| { - let key_end = q.len().checked_mul(2)?.checked_add(KEY.len())?; - let quoted = t.get(..key_end)?; - if !(quoted.starts_with(q) && quoted.get(q.len()..q.len() + KEY.len())? == KEY && quoted.ends_with(q)) { - return None; - } - let colon = ws(key_end); - if t.get(colon) != Some(&b':') { - return None; - } - let open = ws(colon + 1); - t.get(open..)?.starts_with(q).then_some((open + q.len(), q)) - }) -} - -fn hex_decode(h: &[u8]) -> Option> { - if !h.len().is_multiple_of(2) { - return None; - } - h.chunks(2).map(|p| u8::from_str_radix(std::str::from_utf8(p).ok()?, 16).ok()).collect() -} - -fn hex_encode(d: &[u8], upper: bool) -> Vec { - d.iter().flat_map(|b| if upper { format!("{b:02X}") } else { format!("{b:02x}") }.into_bytes()).collect() -} - -/// Replaces, in `text`, every `colorProfileData` JSON value (base64; `\/` escapes, white space -/// around the colon and quotes written as `"` allowed) and every .aepx `bdata=""` -/// attribute that holds a raw profile. -fn stub_text(text: &[u8], tally: &mut Tally) -> Vec { - const BDATA: &[u8] = b"bdata=\""; - let (mut out, mut i) = (Vec::with_capacity(text.len()), 0); - while let Some(&b) = text.get(i) { - let rest = text.get(i..).unwrap_or_default(); - if let Some((open, q)) = value_start(rest) - && let Some(len) = rest.get(open..).and_then(|v| v.windows(q.len()).position(|w| w == q)) - { - let raw = rest.get(open..open + len).unwrap_or_default(); - let unescaped: Vec = raw.iter().copied().filter(|c| *c != b'\\').collect(); - let replaced = match b64_decode(&unescaped) { - Some(d) => stub_of(&d, i, tally).map(|s| b64_encode(&s)), - None => { - tally.failed.push(format!("colorProfileData at byte {i}: not base64")); - None - } - }; - out.extend_from_slice(rest.get(..open).unwrap_or_default()); - match replaced { - Some(enc) => { - out.extend_from_slice(&enc); - tally.stubbed += 1; - } - None => out.extend_from_slice(raw), - } - i += open + len; - continue; - } - if rest.starts_with(BDATA) - && let Some(len) = rest.get(BDATA.len()..).and_then(|v| v.iter().position(|c| *c == b'"')) - { - let hex = rest.get(BDATA.len()..BDATA.len() + len).unwrap_or_default(); - let replaced = hex_decode(hex).filter(|d| is_profile(d)).and_then(|d| stub_of(&d, i, tally)); - out.extend_from_slice(BDATA); - match replaced { - Some(s) => { - out.extend_from_slice(&hex_encode(&s, hex.iter().any(u8::is_ascii_uppercase))); - tally.stubbed += 1; - } - None => out.extend_from_slice(hex), - } - i += BDATA.len() + len; - continue; - } - out.push(b); - i += 1; - } - out -} - -fn walk(chunks: &mut [Chunk<'_>], tally: &mut Tally) { - for c in chunks.iter_mut() { - // Only a data chunk is rewritten as one: an opaque `LIST` also has bytes, but replacing it by - // a data chunk would drop its list type. - let data = if let Body::Data(d) = &c.body { Some(d.to_vec()) } else { None }; - match data { - Some(d) if d.windows(KEY.len()).any(|w| w == KEY) => { - let new = stub_text(&d, tally); - *c = Chunk::data(c.id, new); - } - Some(d) if is_profile(&d) => { - if let Some(s) = stub_of(&d, 0, tally) { - *c = Chunk::data(c.id, s); - tally.stubbed += 1; - } - } - _ => { - if let Body::List { children, .. } | Body::Chunks(children) = &mut c.body { - walk(children, tally); - } - } - } - } -} - -fn main() { - let args: Vec = std::env::args().collect(); - let (Some(input), Some(output)) = (args.get(1), args.get(2)) else { exit("usage: stubicc ") }; - let bytes = std::fs::read(input).or_exit("read the input"); - let mut tally = Tally::default(); - let out = if input.ends_with(".aepx") { - stub_text(&bytes, &mut tally) - } else { - let mut file = effectcraft_aep::parse(&bytes).or_exit("parse the input"); - walk(&mut file.chunks, &mut tally); - effectcraft_aep::write(&file).or_exit("write the output") - }; - if !tally.failed.is_empty() { - exit(&format!("nothing written: {} profile(s) could not be replaced:\n{}", tally.failed.len(), tally.failed.join("\n"))); - } - std::fs::write(output, out).or_exit("write the output"); - println!("stubbed {} profile(s); kept {} short value(s) that hold no profile", tally.stubbed, tally.kept_short); -} - -#[cfg(test)] -#[allow(clippy::unwrap_used)] -mod tests { - use super::*; - - fn profile(desc: &str) -> Vec { - // A profile with colour data after the description (like a real one): the stub of `desc` - // plus 3000 bytes, its size field updated. - let mut p = stub(desc).unwrap(); - p.extend(std::iter::repeat_n(0x5a, 3000)); - let size = u32::try_from(p.len()).unwrap().to_be_bytes(); - p[..4].copy_from_slice(&size); - p - } - - fn stubbed(text: &[u8]) -> (Vec, Tally) { - let mut tally = Tally::default(); - (stub_text(text, &mut tally), tally) - } - - #[test] - fn json_values_in_every_spelling_are_replaced() { - let b64 = String::from_utf8(b64_encode(&profile("sRGB IEC61966-2.1"))).unwrap(); - let want = String::from_utf8(b64_encode(&stub("sRGB IEC61966-2.1").unwrap())).unwrap(); - for (before, after) in [ - (format!("{{\"colorProfileData\":\"{b64}\"}}"), format!("{{\"colorProfileData\":\"{want}\"}}")), - (format!("{{\"colorProfileData\" : \n\t\"{b64}\"}}"), format!("{{\"colorProfileData\" : \n\t\"{want}\"}}")), - (format!("{{\"colorProfileData\":\"{}\"}}", b64.replace('/', "\\/")), format!("{{\"colorProfileData\":\"{want}\"}}")), - (format!("{{"colorProfileData": "{b64}"}}"), format!("{{"colorProfileData": "{want}"}}")), - ] { - let (out, tally) = stubbed(before.as_bytes()); - assert_eq!(String::from_utf8(out).unwrap(), after); - assert_eq!((tally.stubbed, tally.failed.len()), (1, 0)); - } - } - - #[test] - fn a_raw_profile_in_aepx_hex_is_replaced_and_other_hex_kept() { - let hex = String::from_utf8(hex_encode(&profile("Rec.709 Gamma 2.4"), false)).unwrap(); - let want = String::from_utf8(hex_encode(&stub("Rec.709 Gamma 2.4").unwrap(), false)).unwrap(); - let text = format!("", "ab".repeat(200)); - let (out, tally) = stubbed(text.as_bytes()); - assert_eq!(String::from_utf8(out).unwrap(), format!("", "ab".repeat(200))); - assert_eq!((tally.stubbed, tally.failed.len()), (1, 0)); - // Upper-case hex stays upper case. - let (out, _) = stubbed(format!("bdata=\"{}\"", hex.to_uppercase()).as_bytes()); - assert_eq!(String::from_utf8(out).unwrap(), format!("bdata=\"{}\"", want.to_uppercase())); - } - - #[test] - fn a_profile_that_cannot_be_replaced_is_a_failure_not_a_silent_copy() { - // An ICC header whose tag table has no `desc`. - let mut p = profile("x"); - p[132..136].copy_from_slice(b"wtpt"); - let (_, tally) = stubbed(format!("\"colorProfileData\":\"{}\"", String::from_utf8(b64_encode(&p)).unwrap()).as_bytes()); - assert_eq!((tally.stubbed, tally.failed.len()), (0, 1)); - let (_, tally) = stubbed(b"\"colorProfileData\":\"not*base64\""); - assert_eq!(tally.failed.len(), 1); - // A short value holds no profile: kept and counted, not a failure. - let (out, tally) = stubbed(b"\"colorProfileData\":\"AAAA\""); - assert_eq!((out.as_slice(), tally.kept_short, tally.failed.len()), (&b"\"colorProfileData\":\"AAAA\""[..], 1, 0)); - } -} diff --git a/crates/aep/src/container.rs b/crates/aep/src/container.rs index fe99f10b1..d9dbcfb14 100644 --- a/crates/aep/src/container.rs +++ b/crates/aep/src/container.rs @@ -1,64 +1,7 @@ -//! After Effects project (`.aep`) container reader and writer. -//! -//! An `.aep` is a `RIFX` container (big-endian RIFF) with form type `Egg!`. This crate reads it -//! into a lossless chunk tree ([`AepFile`]) and writes it back byte for byte. The XML form of a -//! project (`.aepx`) is read into the same tree by [`read_aepx`]; [`parse_any`] picks the reader -//! by content. See -//! `docs/aep-format.md` for the observed format and how it was established (clean room: only -//! files we generated ourselves, one change per file). -//! -//! [`Project::new`] opens a typed, read-only view over the tree: items, compositions -//! ([`CompHeader`]), layers ([`LayerHeader`], [`Transform`], effects, masks, text documents, -//! markers), properties, keyframes and footage. Only fields whose layout was verified against the -//! values the test files were made with are decoded; every accessor returns `None` (or an empty -//! list) on damaged data instead of failing. +//! The `.aep` / `.aepx` container and its typed view come from `craft-aep`; only the tables that map +//! After Effects effects and layer styles onto EffectCraft's are kept here. -mod aepx; -mod arbitrary; -mod bytes; -mod camera; -mod chunk; pub mod effect_map; -mod effects; -mod error; -mod footage; -mod header; -pub mod index; -mod keys; -mod masks; -mod matte; -mod read; -mod settings; -mod shapes; pub mod style_map; -mod textdoc; -mod typed; -mod values; -mod version; -mod write; -pub(crate) use aepx::{AepxDrafts, index_aepx}; -pub use aepx::{is_aepx, parse_any, read_aepx, read_aepx_with_limits}; -pub use arbitrary::{ - CURVE_IDENTITY, CryptomatteData, CurvesData, ExtractorChannels, HueSaturationData, LevelsData, MeshData, curve_lut, identifier_channel_type, -}; -pub use camera::{CameraPosition, DEFAULT_CAMERA_ZOOM}; -pub use chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; -pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue}; -pub use error::AepError; -pub use footage::{Footage, PsdLayer, SequenceInfo}; -pub use header::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Quality, Rational, Renderer}; -pub use index::{Node, NodeWalk, Nodes, TreeIndex}; -pub use keys::{ExpressionFlags, Interpolation, KeyEase, KeyframeKind, SpatialKey}; -pub use masks::{Mask, MaskAtom, MaskMode, PathVertex, ShapePath}; -pub use matte::{MatteMode, TrackMatte}; -pub use read::{Limits, parse, parse_with_limits}; -pub use settings::{ProjectSettings, TimeDisplay, WorkingSpace}; -pub use shapes::{GradientType, PolystarType, ShapeDetail, ShapeGroup, ShapeItem, Stroke, StrokeCap, StrokeJoin}; -pub use textdoc::{ - AutoKern, Caps, CueType, FontBaseline, Justification, KernRun, Marker, ParagraphRun, StyleRun, TextBox, TextDocument, TextValue, parse_text_dict, -}; -pub use typed::{Comp, Item, ItemKind, KeyLayout, KeyList, Keyframe, Layer, ListHeader, Project, PropEntry, PropGroup, PropNode, Property, TimeBase}; -pub use values::{Orientation, OrientationKey, TimeRemap, TimeRemapKey, Tracked, Transform, ValueSource}; -pub use version::AeVersion; -pub use write::{write, write_to}; +pub use craft_aep::*; diff --git a/crates/aep/src/container/aepx.rs b/crates/aep/src/container/aepx.rs deleted file mode 100644 index c4d2865ff..000000000 --- a/crates/aep/src/container/aepx.rs +++ /dev/null @@ -1,1204 +0,0 @@ -//! Reading the XML form of a project (`.aepx`) into the same chunk tree as an `.aep`. -//! -//! An `.aepx` is the `RIFX` chunk tree written as XML: one element per chunk, named by the chunk -//! id (or the list type of a `LIST`), with the body as hex in a `bdata` attribute. A few chunks -//! are written as text instead (`Utf8` as ``, the numbers `numS` and `ppSn`, the footage -//! alias `alas` as ``), and the XMP packet that follows the container of an `.aep` -//! is the element ``. The mapping, with the cases it was found on, is in -//! `docs/aep-format.md` (section 1.1). -//! -//! The reader is a small XML tokenizer for exactly that subset: elements, attributes, text, the -//! five predefined entities and character references, CDATA, comments and processing -//! instructions. A document type declaration is refused (no entity expansion). It runs without -//! recursion; the nesting depth and the element count are bounded by [`Limits`], and everything -//! it allocates is bounded by the size of the input. -//! -//! There are two readers. [`read_aepx`] builds the owned tree element by element -//! (`aepx/tree.rs`). The importer, which only reads, uses `index_aepx`: it decodes every body -//! (hex, text, the alias JSON, the numbers) into one buffer and records the chunks as entries of -//! the flat index ([`Draft`]s, in depth-first order, bodies as ranges of the buffer), which -//! [`crate::container::TreeIndex::from_drafts`] turns into an index that borrows the buffer. -//! The tests hold both to the same tree and the same errors. - -use std::borrow::Cow; - -use crate::container::chunk::{AepFile, LIST, NESTED_IDS}; -use crate::container::error::AepError; -use crate::container::index::{Draft, Kind as EntryKind}; -use crate::container::read::{Limits, parse}; - -mod tree; - -/// The root element of an `.aepx`. -const ROOT: &[u8] = b"AfterEffectsProject"; -/// The element that holds the XMP packet (the trailer of an `.aep`). -const XMP: &[u8] = b"ProjectXMPMetadata"; -/// The element of a `Utf8` chunk. -const STRING: &[u8] = b"string"; -/// The element of an `alas` chunk (footage alias), written as attributes instead of JSON. -const FILE_REFERENCE: &[u8] = b"fileReference"; - -/// List types whose body is not a chunk sequence: the `.aepx` writes them like data chunks (with -/// `bdata`), the `.aep` as an opaque `LIST`. -const OPAQUE_LIST_TYPES: [[u8; 4]; 1] = [*b"btdk"]; - -/// True when `data` looks like an `.aepx`: optional UTF-8 byte order mark and white space, then -/// an XML declaration or the `AfterEffectsProject` root element. -pub fn is_aepx(data: &[u8]) -> bool { - let rest = data.strip_prefix(&[0xef, 0xbb, 0xbf][..]).unwrap_or(data); - let start = rest.iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(rest.len()); - let rest = rest.get(start..).unwrap_or(&[]); - rest.starts_with(b" Result, AepError> { - if is_aepx(data) { read_aepx(data) } else { parse(data) } -} - -/// Reads an `.aepx` with the default [`Limits`] into the chunk tree an `.aep` of the same project -/// gives. -/// -/// # Errors -/// [`AepError::Xml`] for input that is not well-formed XML of the `.aepx` subset (bad UTF-8, an -/// unknown entity, an unclosed or mismatched tag, invalid or odd-length hex, a number that does -/// not parse, a document type declaration, a root element other than `AfterEffectsProject`); -/// [`AepError::TooDeep`] / [`AepError::TooManyChunks`] beyond the limits. -pub fn read_aepx(data: &[u8]) -> Result, AepError> { - read_aepx_with_limits(data, Limits::default()) -} - -/// Like [`read_aepx`] with explicit [`Limits`]: `max_depth` bounds the element nesting (the root -/// element's children are depth 1), `max_chunks` the number of elements. -/// -/// # Errors -/// See [`read_aepx`]. -pub fn read_aepx_with_limits(data: &[u8], limits: Limits) -> Result, AepError> { - tree::read(data, limits) -} - -/// An `.aepx` read for the flat index: every body decoded into one buffer, and the chunks as -/// [`Draft`]s in depth-first order with their bodies as ranges of that buffer. -/// [`crate::container::TreeIndex::from_drafts`] makes the index, which borrows the buffer. -pub(crate) struct AepxDrafts { - /// The decoded bodies (hex, text, alias JSON, numbers) and the XMP packet. - pub(crate) buffer: Vec, - pub(crate) nodes: Vec, - /// The XMP packet: a range of `buffer` (empty without one). - pub(crate) trailer: (usize, usize), -} - -/// Reads an `.aepx` into [`AepxDrafts`]: the tree [`read_aepx_with_limits`] gives, with the same -/// errors, without one allocation per chunk. -/// -/// # Errors -/// See [`read_aepx_with_limits`]. When memory runs out, two errors come up in more cases than -/// there: [`AepError::TooLarge`] when the chunk list cannot grow (the owned-tree reader would -/// abort), and [`AepError::Xml`] "bdata is too large to hold in memory" also when the shared body -/// buffer cannot grow (the owned-tree reader reserves each value on its own). -pub(crate) fn index_aepx(data: &[u8], limits: Limits) -> Result { - let text = match std::str::from_utf8(data) { - Ok(t) => t.as_bytes(), - Err(e) => return Err(xml(e.valid_up_to(), "the file is not valid UTF-8")), - }; - // Every counted element takes at least 3 bytes (`` in a document cut short), so there are - // never more chunks than this. - let bound = (text.len() / 3).min(limits.max_chunks); - let mut nodes = Vec::new(); - let _ = nodes.try_reserve_exact(bound.min(INITIAL_SLOTS)); - // Hex is most of an `.aepx` and decodes to half its length: one buffer of that size usually - // holds everything. A failed reservation is not an error here; the buffer grows as it goes. - let mut buffer = Vec::new(); - let _ = buffer.try_reserve_exact(text.len() / 2); - let reader = Reader { data: text, pos: 0, limits, count: 0, stack: Vec::new(), root_closed: false, trailer: None, buffer, nodes, bound, attrs: Vec::new() }; - reader.run() -} - -/// The slots the chunk list starts with; it doubles from there (as the array of -/// [`crate::container::TreeIndex`] does). -const INITIAL_SLOTS: usize = 1024; - -fn xml(offset: usize, what: &'static str) -> AepError { - AepError::Xml { offset, what } -} - -/// The pad byte of a body of `len` bytes, as [`crate::container::Chunk::data`] sets it. -fn pad_of(len: usize) -> Option { - if len % 2 == 1 { Some(0) } else { None } -} - -/// What an open element becomes when it closes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Kind { - /// The root element: its children are the top-level chunks. - Root, - /// A chunk with this id (or a `LIST` with this list type). - Chunk([u8; 4]), - /// A `Utf8` chunk. - Utf8, - /// An `alas` chunk built from the attributes. - Alias, - /// The XMP packet (only directly below the root). - Xmp, - /// An element without a chunk counterpart (a name that is no chunk id); skipped with its content. - Skip, -} - -struct Frame { - kind: Kind, - /// Offset of the start tag (for errors). - at: usize, - /// The name as written, to match the end tag. - name: (usize, usize), - /// The chunk's entry in the list (for `Chunk`, `Utf8` and `Alias`). - entry: Option, - /// The buffer length when the element opened: its body starts here. - mark: usize, - /// The end of the decoded `bdata` attribute in the buffer. - bdata_end: Option, - /// The attributes of a `fileReference`, in document order. - attrs: Vec<(String, String)>, -} - -struct Reader<'d> { - data: &'d [u8], - pos: usize, - limits: Limits, - count: usize, - stack: Vec, - /// True once the root element has closed. - root_closed: bool, - trailer: Option<(usize, usize)>, - buffer: Vec, - nodes: Vec, - /// The most chunks the input can hold under the limits: `nodes` never reserves past it. - bound: usize, - /// The attributes of the current start tag; kept to reuse its allocation. - attrs: Vec<((usize, usize), Cow<'d, [u8]>)>, -} - -impl<'d> Reader<'d> { - fn run(mut self) -> Result { - if self.data.starts_with(&[0xef, 0xbb, 0xbf]) { - self.pos = 3; - } - while self.pos < self.data.len() { - if self.rest().starts_with(b"<") { - self.markup()?; - } else { - self.text()?; - } - } - if let Some(open) = self.stack.last() { - return Err(xml(open.at, "an element is not closed before the end of the file")); - } - if !self.root_closed { - return Err(xml(self.data.len(), "no AfterEffectsProject root element")); - } - Ok(AepxDrafts { buffer: self.buffer, nodes: self.nodes, trailer: self.trailer.unwrap_or((0, 0)) }) - } - - fn rest(&self) -> &'d [u8] { - self.data.get(self.pos..).unwrap_or(&[]) - } - - /// The offset of `needle` at or after `from`. - fn find(&self, from: usize, needle: &[u8]) -> Option { - let hay = self.data.get(from..)?; - if needle.is_empty() || hay.len() < needle.len() { - return None; - } - let first = *needle.first()?; - let mut i = 0; - while let Some(p) = hay.get(i..)?.iter().position(|b| *b == first) { - let at = i.checked_add(p)?; - if hay.get(at..)?.starts_with(needle) { - return from.checked_add(at); - } - i = at.checked_add(1)?; - } - None - } - - /// Skips to just after `close`, which must follow. - fn skip_past(&mut self, close: &[u8], what: &'static str) -> Result { - let at = self.find(self.pos, close).ok_or(xml(self.pos, what))?; - self.pos = at.saturating_add(close.len()); - Ok(at) - } - - fn markup(&mut self) -> Result<(), AepError> { - let rest = self.rest(); - if rest.starts_with(b"", "a processing instruction is not closed")?; - } else if rest.starts_with(b"", "a comment is not closed")?; - } else if rest.starts_with(b"", "a CDATA section is not closed")?; - let content = self.data.get(start..end).unwrap_or(&[]); - match self.stack.last() { - Some(frame) => { - if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) { - self.buffer.extend_from_slice(content); - } - } - None => return Err(xml(start, "CDATA outside the root element")), - } - } else if rest.starts_with(b" bool { - !(b.is_ascii_whitespace() || matches!(b, b'<' | b'>' | b'/' | b'=' | b'"' | b'\'' | b'&')) - } - - fn name(&mut self) -> Result<(usize, usize), AepError> { - let start = self.pos; - let len = self.rest().iter().position(|b| !Self::is_name_byte(*b)).unwrap_or(self.rest().len()); - if len == 0 { - return Err(xml(start, "a tag or attribute has no name")); - } - self.pos = start.saturating_add(len); - Ok((start, self.pos)) - } - - fn skip_ws(&mut self) { - let n = self.rest().iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(self.rest().len()); - self.pos = self.pos.saturating_add(n); - } - - fn slice(&self, (a, b): (usize, usize)) -> &'d [u8] { - self.data.get(a..b).unwrap_or(&[]) - } - - /// Reads the attributes of a start tag into `attrs`; true when the tag closes itself. - fn attributes(&mut self, at: usize, attrs: &mut Vec<((usize, usize), Cow<'d, [u8]>)>) -> Result { - loop { - self.skip_ws(); - let rest = self.rest(); - if rest.starts_with(b"/>") { - self.pos = self.pos.saturating_add(2); - return Ok(true); - } - if rest.starts_with(b">") { - self.pos = self.pos.saturating_add(1); - return Ok(false); - } - if rest.is_empty() { - return Err(xml(at, "a start tag is not closed")); - } - let key = self.name()?; - self.skip_ws(); - if !self.rest().starts_with(b"=") { - return Err(xml(self.pos, "an attribute has no value")); - } - self.pos = self.pos.saturating_add(1); - self.skip_ws(); - let quote = *self.rest().first().ok_or(xml(self.pos, "a start tag is not closed"))?; - if quote != b'"' && quote != b'\'' { - return Err(xml(self.pos, "an attribute value is not quoted")); - } - let vstart = self.pos.saturating_add(1); - let vend = self.find(vstart, &[quote]).ok_or(xml(vstart, "an attribute value is not closed"))?; - let raw = self.data.get(vstart..vend).unwrap_or(&[]); - if raw.contains(&b'<') { - return Err(xml(vstart, "`<` inside an attribute value")); - } - // A value without `&` is its own decoding (most of them, every `bdata` After Effects - // writes): borrow it instead of copying it. - let value = if raw.contains(&b'&') { - let mut value = Vec::new(); - decode_entities(raw, vstart, &mut value)?; - Cow::Owned(value) - } else { - Cow::Borrowed(raw) - }; - self.pos = vend.saturating_add(1); - attrs.push((key, value)); - } - } - - fn start_tag(&mut self) -> Result<(), AepError> { - let at = self.pos; - self.pos = self.pos.saturating_add(1); - let name = self.name()?; - let mut attrs = std::mem::take(&mut self.attrs); - attrs.clear(); - let self_closing = self.attributes(at, &mut attrs)?; - let kind = self.kind_of(name, at)?; - if kind != Kind::Root { - self.count = self.count.saturating_add(1); - if self.count > self.limits.max_chunks { - return Err(AepError::TooManyChunks); - } - // The root's children are depth 1, like the top-level chunks of an `.aep`. - if self.stack.len() > self.limits.max_depth { - return Err(AepError::TooDeep); - } - } - let mark = self.buffer.len(); - let mut frame = Frame { kind, at, name, entry: None, mark, bdata_end: None, attrs: Vec::new() }; - match kind { - Kind::Chunk(id) => { - if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { - decode_hex_into(value, key.1, MAX_BDATA, &mut self.buffer)?; - frame.bdata_end = Some(self.buffer.len()); - } - frame.entry = Some(self.open_entry(id)?); - } - Kind::Utf8 => frame.entry = Some(self.open_entry(*b"Utf8")?), - Kind::Alias => { - frame.attrs = - attrs.iter().map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())).collect(); - frame.entry = Some(self.open_entry(*b"alas")?); - } - Kind::Root | Kind::Xmp | Kind::Skip => {} - } - self.attrs = attrs; - self.stack.push(frame); - if self_closing { - self.close()?; - } - Ok(()) - } - - /// Appends the entry of a chunk whose element just opened; its body is filled in when it - /// closes. The list grows by its length (at least 16) but never past [`Self::bound`]; an - /// allocation the target cannot make is an error, not an abort. - fn open_entry(&mut self, id: [u8; 4]) -> Result { - let at = self.nodes.len(); - // This entry and the one after it must have `u32` indices. - u32::try_from(at.checked_add(1).ok_or(AepError::TooManyChunks)?).map_err(|_| AepError::TooManyChunks)?; - if at == self.nodes.capacity() { - // Past the bound (which only a wrong guess could reach) it keeps doubling. - let room = self.bound.saturating_sub(at); - let more = if room == 0 { at.max(16) } else { at.max(16).min(room) }; - self.nodes.try_reserve_exact(more).map_err(|_| AepError::TooLarge)?; - } - self.nodes.push(Draft::placeholder(id)); - Ok(at) - } - - /// Fills in the entry at `at` once its element has closed; its subtree is what follows it. - fn finish(&mut self, at: usize, id: [u8; 4], kind: EntryKind, list_type: [u8; 4], body: (usize, usize), pad: Option) -> Result<(), AepError> { - let end = u32::try_from(self.nodes.len()).map_err(|_| AepError::TooManyChunks)?; - if let Some(d) = self.nodes.get_mut(at) { - *d = Draft { start: body.0, len: body.1.saturating_sub(body.0), id, list_type, end, kind, pad }; - } - Ok(()) - } - - /// Classifies an element by its name and where it is. - fn kind_of(&self, name: (usize, usize), at: usize) -> Result { - let n = self.slice(name); - let parent = match self.stack.last() { - None => { - if self.root_closed { - return Err(xml(at, "a second root element")); - } - if n != ROOT { - return Err(xml(at, "the root element is not AfterEffectsProject")); - } - return Ok(Kind::Root); - } - Some(p) => p.kind, - }; - Ok(match parent { - Kind::Skip | Kind::Utf8 | Kind::Xmp | Kind::Alias => Kind::Skip, - Kind::Root | Kind::Chunk(_) => { - if n == STRING { - Kind::Utf8 - } else if n == FILE_REFERENCE { - Kind::Alias - } else if n == XMP && parent == Kind::Root { - Kind::Xmp - } else if let Some(id) = chunk_id(n) { - Kind::Chunk(id) - } else { - Kind::Skip - } - } - }) - } - - fn end_tag(&mut self) -> Result<(), AepError> { - let at = self.pos; - self.pos = self.pos.saturating_add(2); - let name = self.name()?; - self.skip_ws(); - if !self.rest().starts_with(b">") { - return Err(xml(at, "an end tag is not closed")); - } - self.pos = self.pos.saturating_add(1); - let open = self.stack.last().ok_or(xml(at, "an end tag without a start tag"))?; - if self.slice(open.name) != self.slice(name) { - return Err(xml(at, "an end tag does not match its start tag")); - } - self.close() - } - - /// Closes the innermost element and fills in its chunk's entry. - fn close(&mut self) -> Result<(), AepError> { - let frame = self.stack.pop().ok_or(xml(self.pos, "an end tag without a start tag"))?; - match frame.kind { - Kind::Root => self.root_closed = true, - Kind::Skip => {} - Kind::Xmp => { - // Only the first packet is kept; a later one is dropped from the buffer (its - // children are skipped, so nothing else was written after it opened). - if self.trailer.is_none() { - self.trailer = Some((frame.mark, self.buffer.len())); - } else { - self.buffer.truncate(frame.mark); - } - } - Kind::Utf8 => { - let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; - let end = self.buffer.len(); - self.finish(at, *b"Utf8", EntryKind::Data, [0; 4], (frame.mark, end), pad_of(end.saturating_sub(frame.mark)))?; - } - Kind::Alias => { - let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; - self.buffer.extend_from_slice(alias_json(&frame.attrs).as_bytes()); - let end = self.buffer.len(); - self.finish(at, *b"alas", EntryKind::Data, [0; 4], (frame.mark, end), pad_of(end.saturating_sub(frame.mark)))?; - } - Kind::Chunk(id) => self.close_chunk(id, &frame)?, - } - Ok(()) - } - - /// The chunk of a closed element named by a chunk id (what the owned reader's `chunk_of` - /// built): `bdata` wins over children, `numS` / `ppSn` hold their number, a nested id holds its - /// children (or nothing), any other name is a `LIST` of that type. - fn close_chunk(&mut self, id: [u8; 4], frame: &Frame) -> Result<(), AepError> { - let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; - let after = at.checked_add(1).ok_or(AepError::TooManyChunks)?; - if let Some(bdata_end) = frame.bdata_end { - // The children were read (and counted, and checked) but are not part of the chunk. - self.nodes.truncate(after); - self.buffer.truncate(bdata_end); - let body = (frame.mark, bdata_end); - let pad = pad_of(bdata_end.saturating_sub(frame.mark)); - if OPAQUE_LIST_TYPES.contains(&id) { - return self.finish(at, LIST, EntryKind::OpaqueList, id, body, pad); - } - return self.finish(at, id, EntryKind::Data, [0; 4], body, pad); - } - // Numbers written as text: `0` and `150.000000000`. - if &id == b"numS" || &id == b"ppSn" { - let missing = || xml(frame.at, "a numS or ppSn element without its number"); - // Exactly one child chunk, a `Utf8`: the entry after this one, whose subtree runs to the end. - let only = self.nodes.get(after).copied().filter(|c| usize::try_from(c.end).ok() == Some(self.nodes.len())).ok_or_else(missing)?; - if only.id != *b"Utf8" { - return Err(missing()); - } - let text = match only.kind { - EntryKind::Data | EntryKind::OpaqueList => only.start.checked_add(only.len).and_then(|end| self.buffer.get(only.start..end)).unwrap_or(&[]), - EntryKind::List | EntryKind::Nested => &[], - }; - let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); - let body: [u8; 8]; - let bytes: &[u8] = if &id == b"numS" { - // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. - let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); - let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; - body = u64::from(n as u32).to_be_bytes(); - body.get(4..).unwrap_or(&[]) - } else { - body = text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes(); - &body - }; - self.nodes.truncate(after); - self.buffer.truncate(frame.mark); - self.buffer.extend_from_slice(bytes); - let end = self.buffer.len(); - return self.finish(at, id, EntryKind::Data, [0; 4], (frame.mark, end), pad_of(bytes.len())); - } - let empty = (frame.mark, frame.mark); - if NESTED_IDS.contains(&id) { - if self.nodes.len() == after { - return self.finish(at, id, EntryKind::Data, [0; 4], empty, None); - } - return self.finish(at, id, EntryKind::Nested, [0; 4], empty, None); - } - self.finish(at, LIST, EntryKind::List, id, empty, None) - } - - fn text(&mut self) -> Result<(), AepError> { - let start = self.pos; - let len = self.rest().iter().position(|b| *b == b'<').unwrap_or(self.rest().len()); - let end = start.saturating_add(len); - self.pos = end; - let raw = self.data.get(start..end).unwrap_or(&[]); - match self.stack.last() { - Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut self.buffer), - Some(_) => Ok(()), - None if raw.iter().all(u8::is_ascii_whitespace) => Ok(()), - None => Err(xml(start, "text outside the root element")), - } - } -} - -/// The chunk id of an element name: 1 to 4 printable ASCII bytes, padded with spaces (`Pin` is -/// the list type `Pin `). -fn chunk_id(name: &[u8]) -> Option<[u8; 4]> { - if name.is_empty() || name.len() > 4 || !name.iter().all(|b| b.is_ascii_graphic()) { - return None; - } - let mut id = [b' '; 4]; - for (d, s) in id.iter_mut().zip(name) { - *d = *s; - } - Some(id) -} - -/// Appends `raw` with the predefined entities and character references decoded. -fn decode_entities(raw: &[u8], offset: usize, out: &mut Vec) -> Result<(), AepError> { - let mut i = 0; - while let Some(rest) = raw.get(i..) { - let Some(amp) = rest.iter().position(|b| *b == b'&') else { - out.extend_from_slice(rest); - break; - }; - out.extend_from_slice(rest.get(..amp).unwrap_or(&[])); - let at = offset.saturating_add(i).saturating_add(amp); - let after = rest.get(amp.saturating_add(1)..).unwrap_or(&[]); - let semi = after.iter().take(12).position(|b| *b == b';').ok_or(xml(at, "an entity is not terminated"))?; - let name = after.get(..semi).unwrap_or(&[]); - let ch = match name { - b"amp" => '&', - b"lt" => '<', - b"gt" => '>', - b"quot" => '"', - b"apos" => '\'', - _ => { - let code = if let Some(hex) = name.strip_prefix(b"#x").or_else(|| name.strip_prefix(b"#X")) { - std::str::from_utf8(hex).ok().and_then(|h| u32::from_str_radix(h, 16).ok()) - } else if let Some(dec) = name.strip_prefix(b"#") { - std::str::from_utf8(dec).ok().and_then(|d| d.parse::().ok()) - } else { - return Err(xml(at, "an unknown entity")); - }; - code.filter(|c| *c != 0).and_then(char::from_u32).ok_or(xml(at, "an invalid character reference"))? - } - }; - let mut buf = [0u8; 4]; - out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); - i = i.saturating_add(amp).saturating_add(semi).saturating_add(2); - } - Ok(()) -} - -/// Decodes a `bdata` value (hex digits, two per byte) into a new `Vec` of exactly its size. -fn decode_hex(text: &[u8], offset: usize) -> Result, AepError> { - decode_hex_at_most(text, offset, MAX_BDATA) -} - -/// The most bytes one `bdata` may decode to: what the 32-bit size field of a chunk can hold (a -/// larger body could not be written back as an `.aep` either). -const MAX_BDATA: usize = u32::MAX as usize; - -/// [`decode_hex`] with the decoded-size limit as a parameter (so tests can reach it). -fn decode_hex_at_most(text: &[u8], offset: usize, max: usize) -> Result, AepError> { - // Checked before anything is reserved, then sized once (collecting into `Option` has no - // size hint and regrows step by step), and without aborting when the memory is not there. - let pairs = check_hex(text, offset, max)?; - let mut out = Vec::new(); - out.try_reserve_exact(pairs).map_err(|_| xml(offset, "bdata is too large to hold in memory"))?; - decode_checked(text, offset, &mut out)?; - Ok(out) -} - -/// Appends the bytes of a `bdata` value (hex digits, two per byte, at most `max` bytes) to `out`. -/// On an error `out` is unchanged. -fn decode_hex_into(text: &[u8], offset: usize, max: usize, out: &mut Vec) -> Result<(), AepError> { - let pairs = check_hex(text, offset, max)?; - // Grown at most once per value (amortised over a shared buffer), and without aborting when the - // memory is not there. - out.try_reserve(pairs).map_err(|_| xml(offset, "bdata is too large to hold in memory"))?; - decode_checked(text, offset, out) -} - -/// Appends the bytes of a `bdata` value that [`check_hex`] accepted. On an error (a digit the -/// check let through, which it does not) `out` is unchanged. -fn decode_checked(text: &[u8], offset: usize, out: &mut Vec) -> Result<(), AepError> { - let digit = |b: u8| match b { - b'0'..=b'9' => Some(b - b'0'), - b'a'..=b'f' => Some(b - b'a' + 10), - b'A'..=b'F' => Some(b - b'A' + 10), - _ => None, - }; - let mark = out.len(); - for [hi, lo] in text.as_chunks::<2>().0 { - match (digit(*hi), digit(*lo)) { - (Some(h), Some(l)) => out.push((h << 4) | l), - _ => { - out.truncate(mark); - return Err(xml(offset, "bdata holds a character that is not a hex digit")); - } - } - } - Ok(()) -} - -/// Checks a `bdata` value before anything is reserved for it: an even number of hex digits, at -/// most `max` bytes. Returns the number of bytes it decodes to. -fn check_hex(text: &[u8], offset: usize, max: usize) -> Result { - if text.len() % 2 == 1 { - return Err(xml(offset, "bdata has an odd number of hex digits")); - } - let pairs = text.len() / 2; - if pairs > max { - return Err(AepError::TooLarge); - } - // One cheap pass checks every digit first. Blocks without an early exit inside, so the check - // vectorises; it stops at the first bad block. - if !text.chunks(4096).all(|block| block.iter().fold(true, |ok, b| ok & b.is_ascii_hexdigit())) { - return Err(xml(offset, "bdata holds a character that is not a hex digit")); - } - Ok(pairs) -} - -/// The JSON body of an `alas` chunk from the attributes of a `fileReference`, keys in document -/// order (alphabetical in every sample, as in the `.aep`): the two `ascendcount_*` values as -/// numbers, `platform` `Win` as `1`, `target_is_folder` `0` / `1` as `false` / `true`, everything -/// else as a string. -fn alias_json(attrs: &[(String, String)]) -> String { - let mut out = String::from("{"); - for (i, (key, value)) in attrs.iter().enumerate() { - if i > 0 { - out.push(','); - } - json_str(&mut out, key); - out.push(':'); - let number = value.parse::().ok(); - match (key.as_str(), value.as_str()) { - ("ascendcount_base" | "ascendcount_target", _) if number.is_some() => out.push_str(value), - ("platform", "Win") => out.push('1'), - ("platform", _) if number.is_some() => out.push_str(value), - ("target_is_folder", "0" | "false") => out.push_str("false"), - ("target_is_folder", "1" | "true") => out.push_str("true"), - _ => json_str(&mut out, value), - } - } - out.push('}'); - out -} - -fn json_str(out: &mut String, s: &str) { - out.push('"'); - for c in s.chars() { - match c { - '"' => out.push_str("\\\""), - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - c if u32::from(c) < 0x20 => out.push_str(&format!("\\u{:04x}", u32::from(c))), - c => out.push(c), - } - } - out.push('"'); -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::container::index::TreeIndex; - - fn doc(body: &str) -> String { - format!("\n{body}\n") - } - - #[test] - fn maps_elements_to_chunks() { - let x = doc(concat!( - "\n", - "A & BA-3", - "150.000000000x", - "]]>" - )); - let f = read_aepx(x.as_bytes()).unwrap(); - assert_eq!(f.trailer.as_ref(), b""); - let ids: Vec<_> = f.chunks.iter().map(|c| (c.id, c.list_type())).collect(); - assert_eq!( - ids, - vec![ - (*b"head", None), - (LIST, Some(*b"Pin ")), - (LIST, Some(*b"Pefl")), - (*b"tdsn", None), - (*b"numS", None), - (*b"ppSn", None), - (LIST, Some(*b"btdk")) - ] - ); - assert_eq!(f.chunks[1].children()[0].bytes(), Some(&[1u8][..])); - assert_eq!(f.chunks[1].children()[0].pad, Some(0)); - assert_eq!(f.chunks[3].children()[0].bytes(), Some(&b"A & BA"[..])); - assert_eq!(f.chunks[4].bytes(), Some(&(-3i32).to_be_bytes()[..])); - assert_eq!(f.chunks[5].bytes(), Some(&150f64.to_be_bytes()[..])); - assert_eq!(f.chunks[6].bytes(), Some(&b"ABC"[..])); - // The tree writes as a valid `.aep` that parses back to itself. - let bin = crate::container::write(&f).unwrap(); - assert_eq!(parse(&bin).unwrap(), f); - } - - #[test] - fn file_reference_becomes_alias_json() { - let x = doc(concat!( - "" - )); - let f = read_aepx(x.as_bytes()).unwrap(); - let alas = f.chunks[0].children()[0].bytes().unwrap(); - assert_eq!( - std::str::from_utf8(alas).unwrap(), - r#"{"ascendcount_base":1,"ascendcount_target":1,"fullpath":"C:\\a\\\"b.png","platform":1,"server_name":"N","server_volume_name":"V","target_is_folder":false}"# - ); - } - - #[test] - fn nums_takes_signed_and_unsigned_32_bit_values() { - for (text, bytes) in [("-2147483648", [0x80, 0, 0, 0]), ("4294967295", [0xff; 4]), (" 7 ", [0, 0, 0, 7])] { - let f = read_aepx(doc(&format!("{text}")).as_bytes()).unwrap(); - assert_eq!(f.chunks[0].bytes(), Some(&bytes[..]), "{text}"); - } - for text in ["-2147483649", "4294967296", "1.5"] { - assert!(read_aepx(doc(&format!("{text}")).as_bytes()).is_err(), "{text}"); - } - } - - #[test] - fn detection() { - assert!(is_aepx(b"\xef\xbb\xbf ")); - assert!(is_aepx(b"")); - assert!(!is_aepx(b"RIFX\0\0\0\x04Egg!")); - assert!(parse_any(b"RIFX\0\0\0\x04Egg!").is_ok()); - assert!(parse_any(doc("").as_bytes()).is_ok()); - } - - #[test] - fn bad_input_is_an_error() { - let bad = [ - doc(""), - doc(""), - doc(" "), - doc("�"), - doc("&"), - doc(""), - doc(""), - doc("x"), - doc(""), - doc(""), - doc(""), - "]>".into(), - "".into(), - "".into(), - "".into(), - "junk".into(), - "b", "", "été", "xgoney", "\r\n"]); - out.push_str(&format!("{text}")); - } - 9 => { - let id = rng.pick(&["numS", "ppSn"]); - let inner = rng.pick(&[ - "0", - " 7 ", - "-2147483648", - "150.000000000", - "x", - "", - "12", - "", - "", - "34", - ]); - let attr = if rng.below(6) == 0 { " bdata=\"00000002\"" } else { "" }; - out.push_str(&format!("<{id}{attr}>{inner}")); - } - 10 => { - let n = rng.pick(&["", "41", "414243", "4c495354000000000000"]); - out.push_str(&format!("")); - } - 11 => { - let platform = rng.pick(&["Win", "1", "Mac"]); - out.push_str(&format!( - "", - rng.below(3) - )); - } - 12 if depth < 10 => { - out.push_str("text"); - content(rng, depth + 1, budget, out); - out.push_str(""); - } - 13 => { - let packet = rng.pick(&["x]]>", "plain & text", ""]); - out.push_str(&format!("{packet}")); - } - 14 => out.push_str(rng.pick(&["", "", "\n ", "stray"])), - _ => { - let n = rng.below(5); - out.push_str(&format!("", hex(rng, n))); - } - } - } - } - - /// The default limits and six tight ones (depth 0, 1 and 3; 0, 7 and 40 chunks). - fn limit_sets() -> [Limits; 7] { - [ - Limits { max_depth: 0, max_chunks: 10_000_000 }, - Limits { max_depth: 64, max_chunks: 0 }, - Limits::default(), - Limits { max_depth: 1, max_chunks: 10_000_000 }, - Limits { max_depth: 3, max_chunks: 10_000_000 }, - Limits { max_depth: 64, max_chunks: 7 }, - Limits { max_depth: 64, max_chunks: 40 }, - ] - } - - /// The index reader and the owned-tree reader give the same `Result` (the tree, or the error), - /// and the index walks like the index of the owned tree. - fn same(bytes: &[u8], limits: Limits) { - let old = read_aepx_with_limits(bytes, limits); - let new = index_aepx(bytes, limits).map(|d| TreeIndex::from_drafts(&d.buffer, d.nodes, d.trailer).to_file().into_owned()); - assert_eq!(new, old, "{}", String::from_utf8_lossy(bytes)); - if let Ok(file) = &old { - let AepxDrafts { buffer, nodes, trailer } = index_aepx(bytes, limits).unwrap(); - let index = TreeIndex::from_drafts(&buffer, nodes, trailer); - let expected = TreeIndex::from_file(file).unwrap(); - assert_eq!(index.len(), expected.len()); - assert_eq!(index.trailer(), expected.trailer()); - let a: Vec = index.walk().map(|(d, n)| format!("{d} {n:?}")).collect(); - let b: Vec = expected.walk().map(|(d, n)| format!("{d} {n:?}")).collect(); - assert_eq!(a, b); - } - } - - /// The two readers give the same tree and errors on generated and damaged documents. - #[test] - fn the_two_readers_agree_on_generated_and_damaged_documents() { - let mut rng = Rng(0x9e37_79b9_7f4a_7c15); - let noise = b"<>/=\"'&;#x0aZ \n![]-?"; - for _ in 0..600 { - let mut budget = 80; - let mut body = String::new(); - content(&mut rng, 0, &mut budget, &mut body); - let x = doc(&body); - for l in limit_sets() { - same(x.as_bytes(), l); - } - for _ in 0..4 { - let mut bad = x.clone().into_bytes(); - for _ in 0..1 + rng.below(3) { - let at = rng.below(bad.len()); - bad[at] = noise[rng.below(noise.len())]; - } - for l in limit_sets() { - same(&bad, l); - } - } - let cut = rng.below(x.len()); - same(&x.as_bytes()[..cut], Limits::default()); - // Bytes that are not UTF-8, and a multi-byte character cut in half. - let mut bad = x.clone().into_bytes(); - let at = rng.below(bad.len()); - bad.insert(at, 0xff); - same(&bad, Limits::default()); - let open = format!("{}é", x.trim_end().trim_end_matches("")).into_bytes(); - same(&open[..open.len() - 1], Limits::default()); - } - } - - /// The flat chunk list never reserves more slots than the input or the chunk limit allows. - #[test] - fn the_chunk_list_is_bounded_by_the_input_and_the_limit() { - let many = format!("{}", "".repeat(10_000)); - let d = index_aepx(many.as_bytes(), Limits::default()).unwrap(); - assert_eq!(d.nodes.len(), 10_000); - assert!(d.nodes.capacity() <= 2 * 10_000, "{} slots for 10 000 chunks", d.nodes.capacity()); - // The buffer is reserved once, at half the input, and holds nothing here. - assert!(d.buffer.is_empty() && d.buffer.capacity() <= many.len() / 2); - // At the limit the list never holds more slots than the limit. - let d = index_aepx(many.as_bytes(), Limits { max_depth: 64, max_chunks: 10_000 }).unwrap(); - assert!(d.nodes.capacity() <= 10_000); - let few = format!("{}", "".repeat(100)); - let d = index_aepx(few.as_bytes(), Limits { max_depth: 64, max_chunks: 100 }).unwrap(); - assert!(d.nodes.capacity() <= 100, "{} slots for at most 100 chunks", d.nodes.capacity()); - assert_eq!(index_aepx(few.as_bytes(), Limits { max_depth: 64, max_chunks: 99 }).err(), Some(AepError::TooManyChunks)); - // A tiny input cannot hold more than a third of its bytes in elements. - let tiny = doc(""); - assert!(index_aepx(tiny.as_bytes(), Limits::default()).unwrap().nodes.capacity() <= tiny.len() / 3); - } - - /// What a closed element drops is gone from the buffer and the chunk list, but was counted. - #[test] - fn dropped_content_leaves_nothing_behind_but_still_counts() { - // `bdata` wins over the children: they are read, counted and dropped. - let x = doc("xyzq"); - let d = index_aepx(x.as_bytes(), Limits::default()).unwrap(); - assert_eq!((d.buffer.as_slice(), d.nodes.len()), (&[1u8][..], 1)); - assert_eq!(index_aepx(x.as_bytes(), Limits { max_depth: 64, max_chunks: 4 }).err(), Some(AepError::TooManyChunks)); - assert!(index_aepx(x.as_bytes(), Limits { max_depth: 64, max_chunks: 5 }).is_ok()); - // A child's error is raised although the child would be dropped. - assert!(matches!(index_aepx(doc("").as_bytes(), Limits::default()), Err(AepError::Xml { .. }))); - // Only the first XMP packet stays in the buffer. - let packets = doc(&"packet".repeat(1000)); - let d = index_aepx(packets.as_bytes(), Limits::default()).unwrap(); - assert_eq!((d.buffer.as_slice(), d.trailer), (&b"packet"[..], (0, 6))); - // A number keeps its 4 or 8 bytes, not its text. - let d = index_aepx(doc(" 7 1.5").as_bytes(), Limits::default()).unwrap(); - assert_eq!(d.buffer, [&[0, 0, 0, 7][..], &1.5f64.to_be_bytes()[..]].concat()); - assert_eq!(d.nodes.len(), 2); - } - - /// Bodies keep what the element says they are, even where reading the same bytes as an `.aep` - /// would decide otherwise: a nested id whose `bdata` is a chunk sequence stays data, an empty - /// `btdk` stays an opaque list, an empty list at the deepest level stays a list. - #[test] - fn bodies_keep_the_kind_the_element_gives_them() { - let x = doc(""); - let AepxDrafts { buffer, nodes, trailer } = index_aepx(x.as_bytes(), Limits::default()).unwrap(); - let index = TreeIndex::from_drafts(&buffer, nodes, trailer); - let top: Vec<_> = index.chunks().collect(); - assert_eq!(top.len(), 3); - assert_eq!(top[0].bytes().map(<[u8]>::len), Some(11)); - assert!(top[0].children().next().is_none()); - assert!(top[1].is_opaque_list() && top[1].bytes() == Some(&[][..])); - assert!(top[2].is_opaque_list() && top[2].bytes().map(<[u8]>::len) == Some(12)); - // 64 levels: the innermost (empty) list is a list, not opaque. - let deep = format!("{}{}", "".repeat(64), "".repeat(64)); - let AepxDrafts { buffer, nodes, trailer } = index_aepx(deep.as_bytes(), Limits::default()).unwrap(); - let index = TreeIndex::from_drafts(&buffer, nodes, trailer); - assert_eq!(index.walk().map(|(d, _)| d).max(), Some(64)); - assert!(index.walk().all(|(_, n)| n.is_list(b"Fold") && !n.is_opaque_list())); - same(x.as_bytes(), Limits::default()); - same(deep.as_bytes(), Limits::default()); - } - - /// Hostile input is refused by both readers with the same errors. - #[test] - fn hostile_input_is_refused_alike_by_both_readers() { - let hostile = [ - format!("{}{}", "".repeat(100_000), "".repeat(100_000)), - format!("{}", "".repeat(1000)), - doc(&format!("", "00".repeat(100_000))), - doc(&format!("", "00".repeat(100_000))), - doc("4294967296"), - doc("1e400x"), - doc("�"), - doc("�"), - doc(&format!("{}", "".repeat(1000))), - format!("{}", "".repeat(10)), - " = - entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aepx")).collect(); - paths.sort(); - for path in paths { - let bytes = std::fs::read(&path).unwrap(); - for l in limit_sets() { - let index = index_aepx(&bytes, l).map(|d| TreeIndex::from_drafts(&d.buffer, d.nodes, d.trailer).to_file().into_owned()); - assert_eq!(index, read_aepx_with_limits(&bytes, l), "{}", path.display()); - } - } - } -} diff --git a/crates/aep/src/container/aepx/tree.rs b/crates/aep/src/container/aepx/tree.rs deleted file mode 100644 index ba7e20ed5..000000000 --- a/crates/aep/src/container/aepx/tree.rs +++ /dev/null @@ -1,361 +0,0 @@ -//! The `.aepx` reader of the owned chunk tree ([`super::read_aepx`]): it builds the tree element by -//! element. The importer uses the index reader in `aepx.rs` instead; the tests compare the two on -//! generated, damaged and corpus input (the same tree and the same errors). - -use std::borrow::Cow; - -use super::{FILE_REFERENCE, OPAQUE_LIST_TYPES, ROOT, STRING, XMP, alias_json, chunk_id, decode_entities, decode_hex, xml}; -use crate::container::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; -use crate::container::error::AepError; -use crate::container::read::Limits; - -/// [`super::read_aepx_with_limits`]. -pub(super) fn read(data: &[u8], limits: Limits) -> Result, AepError> { - let text = match std::str::from_utf8(data) { - Ok(t) => t.as_bytes(), - Err(e) => return Err(xml(e.valid_up_to(), "the file is not valid UTF-8")), - }; - Reader { data: text, pos: 0, limits, count: 0, stack: Vec::new(), top: None, trailer: None }.run() -} - -/// What an open element becomes when it closes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Kind { - /// The root element: its children are the top-level chunks. - Root, - /// A chunk with this id (or a `LIST` with this list type). - Chunk([u8; 4]), - /// A `Utf8` chunk. - Utf8, - /// An `alas` chunk built from the attributes. - Alias, - /// The XMP packet (only directly below the root). - Xmp, - /// An element without a chunk counterpart (a name that is no chunk id); skipped with its content. - Skip, -} - -struct Frame { - kind: Kind, - /// Offset of the start tag (for errors). - at: usize, - /// The name as written, to match the end tag. - name: (usize, usize), - /// The decoded `bdata` attribute. - bdata: Option>, - /// The attributes of a `fileReference`, in document order. - attrs: Vec<(String, String)>, - /// Collected text (only for `string` and the XMP packet). - text: Vec, - children: Vec>, -} - -struct Reader<'d> { - data: &'d [u8], - pos: usize, - limits: Limits, - count: usize, - stack: Vec, - /// The top-level chunks once the root element has closed. - top: Option>>, - trailer: Option>, -} - -impl Reader<'_> { - fn run(mut self) -> Result, AepError> { - if self.data.starts_with(&[0xef, 0xbb, 0xbf]) { - self.pos = 3; - } - while self.pos < self.data.len() { - if self.rest().starts_with(b"<") { - self.markup()?; - } else { - self.text()?; - } - } - if let Some(open) = self.stack.last() { - return Err(xml(open.at, "an element is not closed before the end of the file")); - } - let chunks = self.top.ok_or_else(|| xml(self.data.len(), "no AfterEffectsProject root element"))?; - Ok(AepFile { chunks, trailer: Cow::Owned(self.trailer.unwrap_or_default()) }) - } - - fn rest(&self) -> &[u8] { - self.data.get(self.pos..).unwrap_or(&[]) - } - - /// The offset of `needle` at or after `from`. - fn find(&self, from: usize, needle: &[u8]) -> Option { - let hay = self.data.get(from..)?; - if needle.is_empty() || hay.len() < needle.len() { - return None; - } - let first = *needle.first()?; - let mut i = 0; - while let Some(p) = hay.get(i..)?.iter().position(|b| *b == first) { - let at = i.checked_add(p)?; - if hay.get(at..)?.starts_with(needle) { - return from.checked_add(at); - } - i = at.checked_add(1)?; - } - None - } - - /// Skips to just after `close`, which must follow. - fn skip_past(&mut self, close: &[u8], what: &'static str) -> Result { - let at = self.find(self.pos, close).ok_or(xml(self.pos, what))?; - self.pos = at.saturating_add(close.len()); - Ok(at) - } - - fn markup(&mut self) -> Result<(), AepError> { - let rest = self.rest(); - if rest.starts_with(b"", "a processing instruction is not closed")?; - } else if rest.starts_with(b"", "a comment is not closed")?; - } else if rest.starts_with(b"", "a CDATA section is not closed")?; - let content = self.data.get(start..end).unwrap_or(&[]); - let at = start; - match self.stack.last_mut() { - Some(frame) => { - if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) { - frame.text.extend_from_slice(content); - } - } - None => return Err(xml(at, "CDATA outside the root element")), - } - } else if rest.starts_with(b" bool { - !(b.is_ascii_whitespace() || matches!(b, b'<' | b'>' | b'/' | b'=' | b'"' | b'\'' | b'&')) - } - - fn name(&mut self) -> Result<(usize, usize), AepError> { - let start = self.pos; - let len = self.rest().iter().position(|b| !Self::is_name_byte(*b)).unwrap_or(self.rest().len()); - if len == 0 { - return Err(xml(start, "a tag or attribute has no name")); - } - self.pos = start.saturating_add(len); - Ok((start, self.pos)) - } - - fn skip_ws(&mut self) { - let n = self.rest().iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(self.rest().len()); - self.pos = self.pos.saturating_add(n); - } - - fn slice(&self, (a, b): (usize, usize)) -> &[u8] { - self.data.get(a..b).unwrap_or(&[]) - } - - fn start_tag(&mut self) -> Result<(), AepError> { - let at = self.pos; - self.pos = self.pos.saturating_add(1); - let name = self.name()?; - let mut attrs = Vec::new(); - let self_closing = loop { - self.skip_ws(); - let rest = self.rest(); - if rest.starts_with(b"/>") { - self.pos = self.pos.saturating_add(2); - break true; - } - if rest.starts_with(b">") { - self.pos = self.pos.saturating_add(1); - break false; - } - if rest.is_empty() { - return Err(xml(at, "a start tag is not closed")); - } - let key = self.name()?; - self.skip_ws(); - if !self.rest().starts_with(b"=") { - return Err(xml(self.pos, "an attribute has no value")); - } - self.pos = self.pos.saturating_add(1); - self.skip_ws(); - let quote = *self.rest().first().ok_or(xml(self.pos, "a start tag is not closed"))?; - if quote != b'"' && quote != b'\'' { - return Err(xml(self.pos, "an attribute value is not quoted")); - } - let vstart = self.pos.saturating_add(1); - let vend = self.find(vstart, &[quote]).ok_or(xml(vstart, "an attribute value is not closed"))?; - let raw = self.data.get(vstart..vend).unwrap_or(&[]); - if raw.contains(&b'<') { - return Err(xml(vstart, "`<` inside an attribute value")); - } - // A value without `&` is its own decoding (most of them, every `bdata` After Effects - // writes): borrow it instead of copying it. - let value = if raw.contains(&b'&') { - let mut value = Vec::new(); - decode_entities(raw, vstart, &mut value)?; - Cow::Owned(value) - } else { - Cow::Borrowed(raw) - }; - self.pos = vend.saturating_add(1); - attrs.push((key, value)); - }; - let kind = self.kind_of(name, at)?; - if kind != Kind::Root { - self.count = self.count.saturating_add(1); - if self.count > self.limits.max_chunks { - return Err(AepError::TooManyChunks); - } - // The root's children are depth 1, like the top-level chunks of an `.aep`. - if self.stack.len() > self.limits.max_depth { - return Err(AepError::TooDeep); - } - } - let mut frame = Frame { kind, at, name, bdata: None, attrs: Vec::new(), text: Vec::new(), children: Vec::new() }; - if matches!(kind, Kind::Chunk(_)) { - if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { - frame.bdata = Some(decode_hex(value, key.1)?); - } - } else if kind == Kind::Alias { - frame.attrs = attrs.iter().map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())).collect(); - } - self.stack.push(frame); - if self_closing { - self.close()?; - } - Ok(()) - } - - /// Classifies an element by its name and where it is. - fn kind_of(&self, name: (usize, usize), at: usize) -> Result { - let n = self.slice(name); - let parent = match self.stack.last() { - None => { - if self.top.is_some() { - return Err(xml(at, "a second root element")); - } - if n != ROOT { - return Err(xml(at, "the root element is not AfterEffectsProject")); - } - return Ok(Kind::Root); - } - Some(p) => p.kind, - }; - Ok(match parent { - Kind::Skip | Kind::Utf8 | Kind::Xmp | Kind::Alias => Kind::Skip, - Kind::Root | Kind::Chunk(_) => { - if n == STRING { - Kind::Utf8 - } else if n == FILE_REFERENCE { - Kind::Alias - } else if n == XMP && parent == Kind::Root { - Kind::Xmp - } else if let Some(id) = chunk_id(n) { - Kind::Chunk(id) - } else { - Kind::Skip - } - } - }) - } - - fn end_tag(&mut self) -> Result<(), AepError> { - let at = self.pos; - self.pos = self.pos.saturating_add(2); - let name = self.name()?; - self.skip_ws(); - if !self.rest().starts_with(b">") { - return Err(xml(at, "an end tag is not closed")); - } - self.pos = self.pos.saturating_add(1); - let open = self.stack.last().ok_or(xml(at, "an end tag without a start tag"))?; - if self.slice(open.name) != self.slice(name) { - return Err(xml(at, "an end tag does not match its start tag")); - } - self.close() - } - - /// Closes the innermost element and hands its chunk to the parent. - fn close(&mut self) -> Result<(), AepError> { - let frame = self.stack.pop().ok_or(xml(self.pos, "an end tag without a start tag"))?; - let chunk = match frame.kind { - Kind::Root => { - self.top = Some(frame.children); - return Ok(()); - } - Kind::Skip => return Ok(()), - Kind::Xmp => { - if self.trailer.is_none() { - self.trailer = Some(frame.text); - } - return Ok(()); - } - Kind::Utf8 => Chunk::data(*b"Utf8", frame.text), - Kind::Alias => Chunk::data(*b"alas", alias_json(&frame.attrs).into_bytes()), - Kind::Chunk(id) => chunk_of(id, frame)?, - }; - if let Some(parent) = self.stack.last_mut() { - parent.children.push(chunk); - } - Ok(()) - } - - fn text(&mut self) -> Result<(), AepError> { - let start = self.pos; - let len = self.rest().iter().position(|b| *b == b'<').unwrap_or(self.rest().len()); - let end = start.saturating_add(len); - self.pos = end; - let raw = self.data.get(start..end).unwrap_or(&[]); - match self.stack.last_mut() { - Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut frame.text), - Some(_) => Ok(()), - None if raw.iter().all(u8::is_ascii_whitespace) => Ok(()), - None => Err(xml(start, "text outside the root element")), - } - } -} - -/// The chunk of a closed element named by a chunk id. -fn chunk_of(id: [u8; 4], frame: Frame) -> Result, AepError> { - if let Some(bytes) = frame.bdata { - if OPAQUE_LIST_TYPES.contains(&id) { - let pad = if bytes.len() % 2 == 1 { Some(0) } else { None }; - return Ok(Chunk { id: LIST, body: Body::OpaqueList { list_type: id, data: Cow::Owned(bytes) }, pad }); - } - return Ok(Chunk::data(id, bytes)); - } - // Numbers written as text: `0` and `150.000000000`. - if &id == b"numS" || &id == b"ppSn" { - let text = match frame.children.as_slice() { - [only] if only.is(b"Utf8") => only.bytes().unwrap_or(&[]), - _ => return Err(xml(frame.at, "a numS or ppSn element without its number")), - }; - let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); - let body = if &id == b"numS" { - // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. - let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); - let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; - (n as u32).to_be_bytes().to_vec() - } else { - text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes().to_vec() - }; - return Ok(Chunk::data(id, body)); - } - if NESTED_IDS.contains(&id) { - if frame.children.is_empty() { - return Ok(Chunk::data(id, Vec::new())); - } - return Ok(Chunk { id, body: Body::Chunks(frame.children), pad: None }); - } - Ok(Chunk::list(id, frame.children)) -} diff --git a/crates/aep/src/container/arbitrary.rs b/crates/aep/src/container/arbitrary.rs deleted file mode 100644 index 1fb8e8d86..000000000 --- a/crates/aep/src/container/arbitrary.rs +++ /dev/null @@ -1,555 +0,0 @@ -//! Arbitrary-data effect parameters (type 11): the values of Hue/Saturation and Levels that are not -//! ordinary parameters. -//! -//! In the effect's value group (`sspc/tdgp`) the parameter's `tdbs` (`tdsb` 1, a 4-byte `cdat`) is -//! followed by a `LIST aRbs` holding one `aRbp`: the data. The `aRbp` in `parT` right after the -//! parameter's `pard` holds the default (443, 511). Setting Master Hue, Saturation or Lightness of -//! Hue/Saturation (444-446) or a Levels value (512-516) changes only bytes of this `aRbp` (and stale -//! UI bytes of `pard`); the visible parameters of the same names keep no record. - -use crate::container::bytes::{be_f32, be_i32, be_u16, be_u32}; -use crate::container::effects::Effect; -use crate::container::index::Node; - -impl<'f, 'a> Effect<'f, 'a> { - /// The arbitrary data stored for the parameter with this match name (`-NNNN`): the - /// `aRbp` of the `LIST aRbs` that follows the parameter's value record. `None` when there is - /// none. - pub fn arbitrary_data(&self, match_name: &str) -> Option<&'f [u8]> { - let values = self.chunk().child_list(b"tdgp")?; - let mut kids = values.children(); - // Up to the parameter's match name, then the value record, then the data list (no match - // name of its own). - kids.find(|c| c.is(b"tdmn") && c.bytes().is_some_and(|b| name_is(b, match_name)))?; - let mut it = kids.take(3); - let _record = it.next().filter(|c| c.is_list(b"tdbs"))?; - it.find(|c| c.is_list(b"aRbs")).and_then(|l| l.child(b"aRbp")).and_then(Node::bytes) - } -} - -fn name_is(body: &[u8], name: &str) -> bool { - let end = body.iter().position(|c| *c == 0).unwrap_or(body.len()); - body.get(..end) == Some(name.as_bytes()) -} - -/// Hue/Saturation's data (180 bytes, `ADBE HUE SATURATION-0003`): the master hue, saturation and -/// lightness as `i32` at bytes 0, 4 and 8 (444: hue 90 is `0x5a`; 445: saturation 50; 446: -/// lightness -30), then six colour ranges (Reds, Yellows, Greens, Cyans, Blues, Magentas) of 28 -/// bytes each: four `i32` range points in degrees (Reds 315, 345, 15, 45 by default) and the -/// range's hue, saturation and lightness. Only the master values are sampled; the ranges' layout is -/// read from the default data. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct HueSaturationData { - /// Master hue (degrees), saturation and lightness (-100..100). - pub master: [i32; 3], - /// Per colour range: the four range points (degrees) and its hue, saturation and lightness. - pub ranges: [([i32; 4], [i32; 3]); 6], -} - -impl HueSaturationData { - /// The default data (443): master 0, 0, 0 and every range at its default points. - pub const DEFAULT_RANGES: [[i32; 4]; 6] = - [[315, 345, 15, 45], [15, 45, 75, 105], [75, 105, 135, 165], [135, 165, 195, 225], [195, 225, 255, 285], [255, 285, 315, 345]]; - - /// Decodes the data; `None` when it is not 180 bytes. - pub fn parse(data: &[u8]) -> Option { - if data.len() != 180 { - return None; - } - let i = |at: usize| be_i32(data, at); - let master = [i(0)?, i(4)?, i(8)?]; - let mut ranges = [([0; 4], [0; 3]); 6]; - for (k, r) in ranges.iter_mut().enumerate() { - let base = 12usize.checked_add(k.checked_mul(28)?)?; - r.0 = [i(base)?, i(base + 4)?, i(base + 8)?, i(base + 12)?]; - r.1 = [i(base + 16)?, i(base + 20)?, i(base + 24)?]; - } - Some(Self { master, ranges }) - } - - /// Whether every colour range is at its default (points as in 443, no adjustment). - pub fn ranges_are_default(&self) -> bool { - self.ranges.iter().zip(Self::DEFAULT_RANGES).all(|((points, hsl), d)| *points == d && *hsl == [0, 0, 0]) - } -} - -/// Levels' data (108 bytes, `ADBE Easy Levels2-0002`): a `u32` 0x000f10a7 and a `u32` 1 (511, in -/// every sample), then five channels (RGB, Red, Green, Blue, Alpha) of five `f32`: input black, -/// input white, gamma, output black, output white. The RGB values are sampled (512 input black -/// 0.1, 513 input white 0.8, 514 gamma 2, 515 output black 0.2, 516 output white 0.9); the other -/// channels' layout is read from the default data (0, 1, 1, 0, 1). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct LevelsData { - pub header: [u32; 2], - /// RGB, Red, Green, Blue, Alpha: input black, input white, gamma, output black, output white. - pub channels: [[f32; 5]; 5], -} - -impl LevelsData { - /// The values of a channel at its default. - pub const DEFAULT_CHANNEL: [f32; 5] = [0.0, 1.0, 1.0, 0.0, 1.0]; - - /// Decodes the data; `None` when it is not 108 bytes. - pub fn parse(data: &[u8]) -> Option { - if data.len() != 108 { - return None; - } - let header = [be_u32(data, 0)?, be_u32(data, 4)?]; - let mut channels = [[0.0; 5]; 5]; - for (k, c) in channels.iter_mut().enumerate() { - let base = 8usize.checked_add(k.checked_mul(20)?)?; - for (j, v) in c.iter_mut().enumerate() { - *v = be_f32(data, base.checked_add(j.checked_mul(4)?)?)?; - } - } - Some(Self { header, channels }) - } -} - -/// Curves' data (1644 bytes, `ADBE CurvesCustom-0001`; FORMAT S.1, 961-964): `u16` 1, `u16` 1, -/// five 256-byte lookup tables (RGB, Red, Green, Blue, Alpha: output 0..255 per input 0..255), -/// then five 72-byte point records: 16 slots of (`u16` input, `u16` output), both 0..255, the -/// number of points as `u32` at 64 and an `i32` at 68 (-1 at the default; the point count - 2 in -/// every edited sample, H: the active point). Every stored table is the natural cubic spline -/// through its points ([`curve_lut`]). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurvesData { - /// RGB, Red, Green, Blue, Alpha: the points (input, output), as stored. - pub curves: [Vec<(u8, u8)>; 5], -} - -/// The points of an untouched curve. -pub const CURVE_IDENTITY: [(u8, u8); 2] = [(0, 0), (255, 255)]; - -impl CurvesData { - pub const SIZE: usize = 1644; - const POINTS: usize = 1284; - - /// Decodes the data; `None` when it is not 1644 bytes or a point count is beyond 16. - pub fn parse(data: &[u8]) -> Option { - if data.len() != Self::SIZE { - return None; - } - let mut curves: [Vec<(u8, u8)>; 5] = Default::default(); - for (c, pts) in curves.iter_mut().enumerate() { - let base = Self::POINTS.checked_add(c.checked_mul(72)?)?; - let n = usize::try_from(be_u32(data, base.checked_add(64)?)?).ok()?; - if n > 16 { - return None; - } - for k in 0..n { - let at = base.checked_add(k.checked_mul(4)?)?; - let x = u8::try_from(be_u16(data, at)?).ok()?; - let y = u8::try_from(be_u16(data, at.checked_add(2)?)?).ok()?; - pts.push((x, y)); - } - } - Some(Self { curves }) - } - - /// Whether every curve is the identity. - pub fn is_default(&self) -> bool { - self.curves.iter().all(|c| c.as_slice() == CURVE_IDENTITY) - } - - /// The data After Effects stores for these curves: the tables rebuilt from the points. - /// `None` when a curve has fewer than 2 or more than 16 points or inputs that do not rise. - pub fn to_bytes(&self) -> Option> { - let mut out = vec![0u8; Self::SIZE]; - out.get_mut(0..4)?.copy_from_slice(&[0, 1, 0, 1]); - for (c, pts) in self.curves.iter().enumerate() { - if pts.len() > 16 { - return None; - } - let lut = curve_lut(pts)?; - out.get_mut(4 + 256 * c..4 + 256 * (c + 1))?.copy_from_slice(&lut); - let base = Self::POINTS + 72 * c; - for (k, (x, y)) in pts.iter().enumerate() { - out.get_mut(base + 4 * k..base + 4 * k + 4)?.copy_from_slice(&[0, *x, 0, *y]); - } - let n = u32::try_from(pts.len()).ok()?; - out.get_mut(base + 64..base + 68)?.copy_from_slice(&n.to_be_bytes()); - let active: i32 = if pts.as_slice() == CURVE_IDENTITY { -1 } else { i32::try_from(pts.len()).ok()? - 2 }; - out.get_mut(base + 68..base + 72)?.copy_from_slice(&active.to_be_bytes()); - } - Some(out) - } -} - -fn rising(points: &[(u8, u8)]) -> bool { - points.windows(2).all(|w| matches!(w, [a, b] if a.0 < b.0)) -} - -/// The lookup table After Effects stores for a curve: the natural cubic spline (second derivative -/// 0 at both ends) through the points, at the integers 0..255, rounded to the nearest integer and -/// clamped to 0..255; flat outside the first and last point (961-964: 0 of 1280 entries differ). -/// `None` for fewer than 2 points or inputs that do not rise. -pub fn curve_lut(points: &[(u8, u8)]) -> Option<[u8; 256]> { - let n = points.len(); - if n < 2 || !rising(points) { - return None; - } - let xs: Vec = points.iter().map(|p| f64::from(p.0)).collect(); - let ys: Vec = points.iter().map(|p| f64::from(p.1)).collect(); - let x = |i: usize| xs.get(i).copied().unwrap_or(0.0); - let y = |i: usize| ys.get(i).copied().unwrap_or(0.0); - let h = |i: usize| (x(i + 1) - x(i)).max(1.0); - let slope = |i: usize| (y(i + 1) - y(i)) / h(i); - // Second derivatives: the tridiagonal system of the natural spline (Thomas algorithm). - let mut m = vec![0.0f64; n]; - let k = n - 2; - if k > 0 { - let mut diag: Vec = (0..k).map(|i| 2.0 * (h(i) + h(i + 1))).collect(); - let upper: Vec = (0..k).map(|i| h(i + 1)).collect(); - let mut rhs: Vec = (0..k).map(|i| 6.0 * (slope(i + 1) - slope(i))).collect(); - for i in 1..k { - let (Some(&dp), Some(&up), Some(&rp)) = (diag.get(i - 1), upper.get(i - 1), rhs.get(i - 1)) else { return None }; - let w = h(i) / dp; - if let (Some(d), Some(r)) = (diag.get_mut(i), rhs.get_mut(i)) { - *d -= w * up; - *r -= w * rp; - } - } - for i in (0..k).rev() { - let next = m.get(i + 2).copied().unwrap_or(0.0); - let (Some(&r), Some(&u), Some(&d)) = (rhs.get(i), upper.get(i), diag.get(i)) else { return None }; - if let Some(slot) = m.get_mut(i + 1) { - *slot = (r - u * next) / d; - } - } - } - let mut lut = [0u8; 256]; - for (xi, slot) in lut.iter_mut().enumerate() { - let xf = xi as f64; - let v = if xf <= x(0) { - y(0) - } else if xf >= x(n - 1) { - y(n - 1) - } else { - let i = (0..n - 1).find(|&i| xf >= x(i) && xf <= x(i + 1)).unwrap_or(0); - let hh = h(i); - let (a, b) = ((x(i + 1) - xf) / hh, (xf - x(i)) / hh); - let (mi, mj) = (m.get(i).copied().unwrap_or(0.0), m.get(i + 1).copied().unwrap_or(0.0)); - a * y(i) + b * y(i + 1) + ((a * a * a - a) * mi + (b * b * b - b) * mj) * hh * hh / 6.0 - }; - *slot = (v + 0.5).floor().clamp(0.0, 255.0) as u8; - } - Some(lut) -} - -/// Mesh Warp's data (`ADBE MESH WARP-0004`; FORMAT S.2, 965, 985): `u32` rows plus one, `u32` -/// columns plus one (a 1 x 2-cell read-back test renders as made only in this order, `export-tests\mesh`; -/// the vertices run row-major, columns plus one per row), 12 more bytes (zero, then -/// `0d 0d`), -/// then per vertex, row-major, ten `f32`: the position and the handles top, right, bottom and -/// left, all as fractions 0..1 of the layer; a handle pointing out of the mesh is stored (0, 0). -#[derive(Debug, Clone, PartialEq)] -pub struct MeshData { - pub columns: u32, - pub rows: u32, - /// Bytes 8..20 as stored. - pub tail: [u8; 12], - /// Per vertex: position, top, right, bottom, left. - pub vertices: Vec<[[f32; 2]; 5]>, -} - -impl MeshData { - /// Decodes the data; `None` when the size does not fit the grid or the grid is beyond 31 x 31 - /// cells. - pub fn parse(data: &[u8]) -> Option { - let (r1, c1) = (be_u32(data, 0)?, be_u32(data, 4)?); - if !(2..=32).contains(&c1) || !(2..=32).contains(&r1) { - return None; - } - let count = usize::try_from(c1.checked_mul(r1)?).ok()?; - if data.len() != 20usize.checked_add(count.checked_mul(40)?)? { - return None; - } - let mut tail = [0u8; 12]; - tail.copy_from_slice(data.get(8..20)?); - let mut vertices = Vec::with_capacity(count); - for v in 0..count { - let base = 20 + 40 * v; - let mut rec = [[0.0f32; 2]; 5]; - for (j, p) in rec.iter_mut().enumerate() { - *p = [be_f32(data, base + 8 * j)?, be_f32(data, base + 8 * j + 4)?]; - } - vertices.push(rec); - } - Some(Self { columns: c1 - 1, rows: r1 - 1, tail, vertices }) - } - - /// The vertex at column `i`, row `j` of an undistorted mesh with its default handles (one - /// third of a cell along the grid lines; those pointing out of the mesh are (0, 0)). - pub fn default_vertex(columns: u32, rows: u32, i: u32, j: u32) -> [[f32; 2]; 5] { - let (cw, rh) = (1.0 / f64::from(columns.max(1)), 1.0 / f64::from(rows.max(1))); - let (x, y) = (f64::from(i) * cw, f64::from(j) * rh); - let p = |dx: f64, dy: f64, out: bool| if out { [0.0, 0.0] } else { [(x + dx) as f32, (y + dy) as f32] }; - [[x as f32, y as f32], p(0.0, -rh / 3.0, j == 0), p(cw / 3.0, 0.0, i == columns), p(0.0, rh / 3.0, j == rows), p(-cw / 3.0, 0.0, i == 0)] - } - - /// The bytes After Effects stores for this mesh. - pub fn to_bytes(&self) -> Option> { - let count = usize::try_from(self.columns.checked_add(1)?.checked_mul(self.rows.checked_add(1)?)?).ok()?; - if self.vertices.len() != count { - return None; - } - let mut out = Vec::with_capacity(20 + 40 * count); - out.extend((self.rows + 1).to_be_bytes()); - out.extend((self.columns + 1).to_be_bytes()); - out.extend(self.tail); - for v in &self.vertices { - for p in v { - out.extend(p[0].to_be_bytes()); - out.extend(p[1].to_be_bytes()); - } - } - Some(out) - } -} - -/// EXtractoR's Channel Info data (`EXtractoR-0013`, 688 bytes, the plug-in's own little-endian -/// layout; read from the instances of the importer block of 2026-11-05: the defaults and a preset -/// of our own that reads `Z` into Red, Green and Blue): a `u32` 1 and 28 bytes, then four records -/// of 164 bytes (Red, Green, Blue, Alpha), each a kind in byte 0 (1 a channel of the footage by -/// name, 2 the input's own channel: `(copy)`; bytes 1..4 are not always zero, `0x32` at 3 in one -/// definition's default, so only byte 0 is read) and the channel name from byte 35, -/// NUL-terminated. The other bytes are not read (they differ between instances with the same -/// channels; the `u32` at 4 of a chosen channel looks like its position in the footage's sorted -/// channel list, 13 of 14 for `Z`, where the defaults hold 0). Only the name is read. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ExtractorChannels { - /// Per output channel (red, green, blue, alpha): the kind and the name. - pub channels: [(u32, String); 4], -} - -impl ExtractorChannels { - /// The data's length. - pub const LEN: usize = 688; - const RECORD: usize = 164; - - /// `None` when the data does not have this layout. - pub fn parse(data: &[u8]) -> Option { - if data.len() != Self::LEN || data.get(..4)? != 1u32.to_le_bytes() { - return None; - } - let mut channels: [(u32, String); 4] = Default::default(); - for (k, slot) in channels.iter_mut().enumerate() { - let at = 32usize.checked_add(k.checked_mul(Self::RECORD)?)?; - let rec = data.get(at..at.checked_add(Self::RECORD)?)?; - let kind = u32::from(*rec.first()?); - let name = rec.get(35..)?; - let end = name.iter().position(|b| *b == 0)?; - let name = std::str::from_utf8(name.get(..end)?).ok()?; - *slot = (kind, name.to_string()); - } - Some(Self { channels }) - } - - /// The channels of a fresh EXtractoR: Red, Green and Blue from the channels of those names, - /// Alpha copied from the input. - pub fn is_default(&self) -> bool { - let want = [(1, "R"), (1, "G"), (1, "B"), (2, "(copy)")]; - self.channels.iter().zip(want).all(|((k, n), (wk, wn))| *k == wk && n == wn) - } - - /// Per output channel (red, green, blue, alpha) the channel it reads, `Err` with the - /// position of the first record of another kind or without a name: a named channel by its - /// name, `(copy)` as EffectCraft's [`EXTRACTOR_COPY`](effectcraft_effects::EXTRACTOR_COPY), - /// the effect input's own channel of the same position. It is not `R`, `G`, `B` or `A`: - /// EffectCraft's EXtractoR reads those from an OpenEXR footage's channels of that name, the - /// file's own, which loses what an earlier effect did to the channel. - pub fn sources(&self) -> Result<[String; 4], usize> { - let mut out: [String; 4] = Default::default(); - for (k, ((kind, name), slot)) in self.channels.iter().zip(out.iter_mut()).enumerate() { - *slot = match (kind, name.trim()) { - (1, n) if !n.is_empty() => n.to_string(), - (2, _) => effectcraft_effects::EXTRACTOR_COPY.to_string(), - _ => return Err(k), - }; - } - Ok(out) - } -} - -/// IDentifier's Channel Info data (`IDentifier-0005`, 148 bytes): the chosen channel's name, -/// NUL-terminated from byte 19, or `Object ID` when none is chosen (importer blocks 1300 and 1310 -/// of 2026-11-05: `objectId` in a preset of our own that chose that UINT channel, `Object ID` in -/// every other instance). The bytes around it differ between instances with the same settings -/// and are not read (a chosen channel has 15 at byte 4, which looks like its position in the -/// EXR's sorted channel list, as for EXtractoR). -pub fn identifier_channel_type(data: &[u8]) -> Option<&str> { - let s = data.get(19..)?; - let end = s.iter().position(|b| *b == 0)?; - std::str::from_utf8(s.get(..end)?).ok() -} - -/// The Cryptomatte plug-in's Settings data (`Cryptomatte-0001`, the plug-in's own layout, -/// little-endian; read from 88 instances of one project and from our own sample 1400, fresh -/// instances and two presets that pick a layer and an object, docs/aep-format.md 3.7): the magic -/// `cry1`; bytes 4..32 are not read (they differ between instances holding the same settings); -/// the Cryptomatte layer's name at 32, NUL-padded to 64 bytes (`CryptoObject`); at 96 a `u32` 1 -/// and a `u32` (neither read); at 104 the `u32` length of the selection text including its NUL, -/// the `u32` MurmurHash3 (x86, 32-bit, seed 0) of that text with its NUL (not read) and a zero -/// byte; the selection text from byte 113 (`<11a97486>, `, the matte list as ID hashes, -/// the hashes of the picked names). Bytes after it are left-overs of a longer earlier text. A -/// fresh effect stores no layer and an empty text (length 1, its NUL); the `u32`s at 100 and 108 -/// are then both `0x514e28b7`, the hash of one NUL byte: the one at 100 looks like the hash of a -/// first text that is empty in every sample, the zero byte at 112 like that text. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct CryptomatteData { - /// The Cryptomatte layer's name (`CryptoMaterial`: the EXR layer's name, which is also its - /// channel prefix in every sample); empty when none is chosen. - pub layer: String, - /// The selection (matte list) as the plug-in stores it. - pub selection: String, -} - -impl CryptomatteData { - /// Decodes the data; `None` when it is not this layout (no `cry1`, too short, a length past - /// the end, no zero byte at 112, a text without its NUL, text that is not UTF-8). - pub fn parse(data: &[u8]) -> Option { - if data.get(..4)? != b"cry1" { - return None; - } - let text = |b: &[u8]| -> Option { - let end = b.iter().position(|c| *c == 0).unwrap_or(b.len()); - String::from_utf8(b.get(..end)?.to_vec()).ok() - }; - let layer = text(data.get(32..96)?)?; - let len = usize::try_from(u32::from_le_bytes(data.get(104..108)?.try_into().ok()?)).ok()?; - if *data.get(112)? != 0 { - return None; - } - let selection = if len == 0 { - String::new() - } else { - // The length counts the text's NUL as its last byte: a text without it, or with an early - // NUL before more bytes (which `text` would silently cut short), is not this layout. - let b = data.get(113..113usize.checked_add(len)?)?; - let (last, text_bytes) = b.split_last()?; - if *last != 0 || text_bytes.contains(&0) { - return None; - } - text(b)? - }; - Some(Self { layer, selection }) - } -} - -#[cfg(test)] -mod tests { - use super::CryptomatteData; - - /// Settings data in the layout [`CryptomatteData::parse`] reads, with `noise` in the bytes it - /// does not read. - fn crypto(layer: &str, selection: &str, noise: u8) -> Vec { - let mut d = b"cry1".to_vec(); - d.resize(32, noise); - d.extend(layer.as_bytes()); - d.resize(96, 0); - d.extend(1u32.to_le_bytes()); - d.extend([noise; 4]); - let len = if selection.is_empty() { 0 } else { selection.len() + 1 }; - d.extend(u32::try_from(len).unwrap_or(0).to_le_bytes()); - d.extend([noise; 4]); - d.push(0); - d.extend(selection.as_bytes()); - d.push(0); - // Left-overs of an earlier, longer text. - d.extend(b" , ", noise)); - assert_eq!(d, Some(CryptomatteData { layer: "Layer_A".into(), selection: "<0000002a>, ".into() }), "noise {noise}"); - } - } - - #[test] - fn a_selection_whose_nul_is_not_its_last_byte_is_refused() { - // An early NUL followed by more declared bytes would shorten the selection silently. - let mut d = crypto("Layer_A", "<0000002a>, ", 0); - d[113 + 4] = 0; - assert_eq!(CryptomatteData::parse(&d), None); - // No NUL at the end of the declared length. - let mut d = crypto("Layer_A", "<0000002a>", 0); - d[113 + 10] = b'x'; - assert_eq!(CryptomatteData::parse(&d), None); - } - - #[test] - fn the_default_cryptomatte_settings_are_empty() { - let mut d = b"cry1".to_vec(); - d.resize(116, 0); - assert_eq!(CryptomatteData::parse(&d), Some(CryptomatteData::default())); - // What After Effects 2026 wrote for a fresh effect (plug-in 2.6.6, sample 1400 - // `crypto-00-defaults`, the `pard` default and the instance's record alike): an empty text - // of length 1 and its hash, twice. - let mut fresh = b"cry1".to_vec(); - fresh.resize(96, 0); - for _ in 0..2 { - fresh.extend(1u32.to_le_bytes()); - fresh.extend(0x514e_28b7u32.to_le_bytes()); - } - fresh.extend([0; 4]); - assert_eq!(fresh.len(), 116); - assert_eq!(CryptomatteData::parse(&fresh), Some(CryptomatteData::default())); - } - - /// The Settings data After Effects 2026 wrote for the two presets of sample 1400 (plug-in - /// 2.6.6, `crypto-06-preset-object-box` and `crypto-07-preset-material-paint`: a layer chosen - /// and one object or material picked in the plug-in's UI), byte for byte: 127 bytes, the `u32` - /// at 108 the MurmurHash3 of the text with its NUL, three zero bytes after the text. - #[test] - fn the_presets_of_our_sample_are_read() { - for (layer, selection, hash) in [("CryptoObject", "<11a97486>", 0x2788_0767u32), ("CryptoMaterial", "", 0xf737_4a5b)] { - let mut d = b"cry1".to_vec(); - d.resize(32, 0); - d.extend(layer.as_bytes()); - d.resize(96, 0); - for v in [1, 0x514e_28b7, 11, hash] { - d.extend(u32::to_le_bytes(v)); - } - d.push(0); - d.extend(selection.as_bytes()); - d.extend([0; 4]); - assert_eq!(d.len(), 127); - assert_eq!(CryptomatteData::parse(&d), Some(CryptomatteData { layer: layer.into(), selection: selection.into() }), "{layer}"); - } - } - - #[test] - fn damaged_cryptomatte_settings_are_not_read() { - let good = crypto("L", "<00000001>", 0); - let mut bad_magic = good.clone(); - bad_magic[0] = b'x'; - let mut past_end = good.clone(); - past_end[104..108].copy_from_slice(&u32::MAX.to_le_bytes()); - let mut no_zero = good.clone(); - no_zero[112] = b'<'; - let mut not_utf8 = good.clone(); - not_utf8[32] = 0xff; - // The length covers the text without its NUL (`<00000001>` is 10 bytes, its NUL the 11th). - let mut no_nul = good.clone(); - no_nul[104..108].copy_from_slice(&10u32.to_le_bytes()); - // No zero byte at 112 with an empty text. - let mut empty_no_zero = crypto("L", "", 0); - empty_no_zero[112] = b'<'; - for (what, d) in [ - ("magic", bad_magic), - ("length", past_end), - ("zero byte", no_zero), - ("utf-8", not_utf8), - ("no NUL", no_nul), - ("empty text, zero byte", empty_no_zero), - ("short", good[..100].to_vec()), - ("empty", Vec::new()), - ] { - assert_eq!(CryptomatteData::parse(&d), None, "{what}"); - } - } -} diff --git a/crates/aep/src/container/bytes.rs b/crates/aep/src/container/bytes.rs deleted file mode 100644 index 77f5f2199..000000000 --- a/crates/aep/src/container/bytes.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! Bounds-checked big-endian readers shared by the typed views. Every read returns `None` when the -//! bytes are not there; nothing here indexes a slice directly. - -pub(crate) fn text(b: &[u8]) -> String { - String::from_utf8_lossy(b).into_owned() -} - -/// The bytes up to the first NUL (all of them when there is none). -pub(crate) fn until_nul(b: &[u8]) -> &[u8] { - let end = b.iter().position(|c| *c == 0).unwrap_or(b.len()); - b.get(..end).unwrap_or(&[]) -} - -/// A NUL-terminated ASCII (or Latin-1) string at `at`, at most `max` bytes long. -pub(crate) fn cstr(b: &[u8], at: usize, max: usize) -> Option { - let end = at.checked_add(max)?.min(b.len()); - let field = b.get(at..end)?; - Some(until_nul(field).iter().map(|c| char::from(*c)).collect()) -} - -pub(crate) fn array(b: &[u8], at: usize) -> Option<[u8; N]> { - let s = b.get(at..at.checked_add(N)?)?; - let mut a = [0u8; N]; - a.copy_from_slice(s); - Some(a) -} - -pub(crate) fn be_u16(b: &[u8], at: usize) -> Option { - array::<2>(b, at).map(u16::from_be_bytes) -} - -pub(crate) fn be_u32(b: &[u8], at: usize) -> Option { - array::<4>(b, at).map(u32::from_be_bytes) -} - -pub(crate) fn be_i32(b: &[u8], at: usize) -> Option { - array::<4>(b, at).map(i32::from_be_bytes) -} - -pub(crate) fn le_u32(b: &[u8], at: usize) -> Option { - array::<4>(b, at).map(u32::from_le_bytes) -} - -pub(crate) fn be_f32(b: &[u8], at: usize) -> Option { - array::<4>(b, at).map(f32::from_be_bytes) -} - -pub(crate) fn be_f64(b: &[u8], at: usize) -> Option { - array::<8>(b, at).map(f64::from_be_bytes) -} diff --git a/crates/aep/src/container/camera.rs b/crates/aep/src/container/camera.rs deleted file mode 100644 index 0b72537ef..000000000 --- a/crates/aep/src/container/camera.rs +++ /dev/null @@ -1,46 +0,0 @@ -//! Cameras and lights. -//! -//! Both are layers without a source (`ldta` byte 40 is 0 for a camera and `0xffff_ffff` for a light) -//! whose type is 2 (camera) or 1 (light). Their `ldta` carries the auto-orient bit (byte 38, `0x40`) -//! and, for a light, the light type (see [`LayerHeader::light_type`](crate::container::LayerHeader)). The -//! properties sit in the same Transform group as on other layers but follow other conventions: -//! -//! * **Position** is stored as given once the user has set it. While it is at its computed default -//! the record is an "auto state" (`tdb4` bytes 76 and 77 are 1 although there is no expression) -//! that holds `[0, 0, -zoom]`. After Effects reports and renders the stored value, also for a -//! two-node camera (256 read back `[0, 0, -2666.67]` in session S16; 537 renders from there). An -//! earlier batch-3 note had a two-node camera report the composition centre; that was not -//! reproduced. -//! * **Anchor Point** of a camera is its point of interest, in pixels (not a fraction). -//! * A light's **Intensity** (`ADBE Light Options Group/ADBE Light Intensity`, percent) is stored -//! only when it is not the default 100. - -use crate::container::typed::{Layer, PropNode}; - -/// The Position of a camera or light layer as stored. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct CameraPosition { - /// `[x, y, z]` in pixels as stored: the absolute position once set by the user, `[0, 0, -zoom]` - /// in the auto state (camera) or `[0, 0, -1333.33]` (default light). - pub stored: [f64; 3], - /// True while the position is derived (`tdb4` bytes 76 and 77 are 1 without an expression). - pub auto_state: bool, -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The Position record of a camera or light layer. - pub fn camera_position(&self) -> Option { - let Some(PropNode::Group(transform)) = self.properties()?.get("ADBE Transform Group") else { return None }; - let Some(PropNode::Property(position)) = transform.get("ADBE Position") else { return None }; - let v = position.static_value()?; - let stored = *v.as_slice().first_chunk::<3>()?; - let h = position.header()?; - let derived = h.get(76) == Some(&1) && h.get(77) == Some(&1) && position.expression().is_none(); - Some(CameraPosition { stored, auto_state: derived }) - } -} - -/// The camera zoom After Effects uses when `ADBE Camera Zoom` is absent: 2666.67 px for the 50 mm -/// default camera in the 1920 px wide corpus composition. Whether it follows other composition -/// widths was not sampled. -pub const DEFAULT_CAMERA_ZOOM: f64 = 2_666.666_666_666_666_5; diff --git a/crates/aep/src/container/chunk.rs b/crates/aep/src/container/chunk.rs deleted file mode 100644 index 5fcc9af50..000000000 --- a/crates/aep/src/container/chunk.rs +++ /dev/null @@ -1,213 +0,0 @@ -//! The lossless chunk tree. - -use std::borrow::Cow; - -/// The id of a list chunk. -pub const LIST: [u8; 4] = *b"LIST"; - -/// Non-`LIST` chunk ids whose body is itself a sequence of chunks (observed: each holds one `Utf8` -/// chunk). They are parsed as [`Body::Chunks`] when the body is a well-formed chunk sequence and -/// kept as [`Body::Data`] otherwise. -pub const NESTED_IDS: [[u8; 4]; 3] = [*b"tdsn", *b"pdnm", *b"fnam"]; - -/// One chunk: a 4-byte id, a body and an optional pad byte. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Chunk<'a> { - /// The 4-byte id, as stored (case matters; some ids end in a space, e.g. `seq `). - pub id: [u8; 4], - /// The body. - pub body: Body<'a>, - /// The pad byte that followed an odd-sized body (normally `0`). `None` when the body is even, - /// or when an odd body is the last thing of its parent and the file has no pad byte there. - /// On writing, an odd body that is not the last sibling always gets a pad byte (`0` if this is - /// `None`); the last sibling gets one only if this is `Some`. - pub pad: Option, -} - -/// The body of a [`Chunk`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Body<'a> { - /// Opaque bytes (the content of nearly all chunks). - Data(Cow<'a, [u8]>), - /// A body that is a sequence of chunks although the id is not `LIST` (see [`NESTED_IDS`]). - Chunks(Vec>), - /// A `LIST`: a 4-byte list type followed by chunks. - List { list_type: [u8; 4], children: Vec> }, - /// A `LIST` whose content is not a well-formed chunk sequence (or is nested deeper than the - /// limit), kept as bytes after the list type (observed: `LIST btdk` holds raw text). - OpaqueList { list_type: [u8; 4], data: Cow<'a, [u8]> }, -} - -impl<'a> Chunk<'a> { - /// A data chunk with the pad byte its length needs. - pub fn data(id: [u8; 4], data: impl Into>) -> Self { - let data = data.into(); - let pad = if data.len() % 2 == 1 { Some(0) } else { None }; - Self { id, body: Body::Data(data), pad } - } - - /// A `LIST` chunk. - pub fn list(list_type: [u8; 4], children: Vec>) -> Self { - Self { id: LIST, body: Body::List { list_type, children }, pad: None } - } - - /// The raw bytes of a [`Body::Data`] chunk, or the bytes after the list type of an opaque list. - pub fn bytes(&self) -> Option<&[u8]> { - match &self.body { - Body::Data(d) => Some(d), - Body::OpaqueList { data, .. } => Some(data), - Body::Chunks(_) | Body::List { .. } => None, - } - } - - /// The child chunks of a list or nested chunk; empty for data. - pub fn children(&self) -> &[Chunk<'a>] { - match &self.body { - Body::Chunks(c) | Body::List { children: c, .. } => c, - Body::Data(_) | Body::OpaqueList { .. } => &[], - } - } - - /// Mutable child chunks; empty for data. - pub fn children_mut(&mut self) -> &mut [Chunk<'a>] { - match &mut self.body { - Body::Chunks(c) | Body::List { children: c, .. } => c, - Body::Data(_) | Body::OpaqueList { .. } => &mut [], - } - } - - /// The list type when this is a `LIST` (parsed or opaque). - pub fn list_type(&self) -> Option<[u8; 4]> { - match &self.body { - Body::List { list_type, .. } | Body::OpaqueList { list_type, .. } => Some(*list_type), - Body::Data(_) | Body::Chunks(_) => None, - } - } - - /// True when this is a `LIST` of the given type. - pub fn is_list(&self, list_type: &[u8; 4]) -> bool { - self.id == LIST && self.list_type().is_some_and(|t| &t == list_type) - } - - /// True when this is a `LIST` whose content could not be read as chunks (see - /// [`Body::OpaqueList`]): damaged, or nested deeper than the limit. - pub fn is_opaque_list(&self) -> bool { - matches!(self.body, Body::OpaqueList { .. }) - } - - /// True when this is a chunk (not a `LIST`) with the given id. - pub fn is(&self, id: &[u8; 4]) -> bool { - &self.id == id - } - - /// The first child (non-list) chunk with this id. - pub fn child(&self, id: &[u8; 4]) -> Option<&Chunk<'a>> { - self.children().iter().find(|c| c.is(id)) - } - - /// The first child `LIST` of this type. - pub fn child_list(&self, list_type: &[u8; 4]) -> Option<&Chunk<'a>> { - self.children().iter().find(|c| c.is_list(list_type)) - } - - /// Visits every chunk below this one depth-first (children before later siblings), without - /// recursion; the depth counts from 1 for the children of this chunk. - pub fn descendants(&self) -> Walk<'_, 'a> { - Walk { stack: vec![(self.children().iter(), 1)] } - } - - /// The first descendant `LIST` of this type, searching depth-first. - pub fn find_list(&self, list_type: &[u8; 4]) -> Option<&Chunk<'a>> { - self.descendants().map(|(_, c)| c).find(|c| c.is_list(list_type)) - } - - /// Copies all borrowed bytes so the tree no longer borrows the input. - pub fn into_owned(self) -> Chunk<'static> { - let body = match self.body { - Body::Data(d) => Body::Data(Cow::Owned(d.into_owned())), - Body::Chunks(c) => Body::Chunks(c.into_iter().map(Chunk::into_owned).collect()), - Body::List { list_type, children } => Body::List { list_type, children: children.into_iter().map(Chunk::into_owned).collect() }, - Body::OpaqueList { list_type, data } => Body::OpaqueList { list_type, data: Cow::Owned(data.into_owned()) }, - }; - Chunk { id: self.id, body, pad: self.pad } - } -} - -/// A parsed `.aep`: the `RIFX` container's chunks and the bytes after its declared end. -/// -/// Writing it back with [`crate::container::write`] reproduces the input byte for byte (the container size -/// and every list size are recomputed from the tree and equal what the file declared). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AepFile<'a> { - /// The top-level chunks (after the `Egg!` form type). - pub chunks: Vec>, - /// The bytes after the container's declared end. After Effects puts an XMP packet there. - pub trailer: Cow<'a, [u8]>, -} - -impl<'a> AepFile<'a> { - /// The first top-level chunk with this id. - pub fn chunk(&self, id: &[u8; 4]) -> Option<&Chunk<'a>> { - self.chunks.iter().find(|c| c.is(id)) - } - - /// The first top-level `LIST` of this type. - pub fn list(&self, list_type: &[u8; 4]) -> Option<&Chunk<'a>> { - self.chunks.iter().find(|c| c.is_list(list_type)) - } - - /// The XMP packet in the trailer (from ``). - pub fn xmp(&self) -> Option<&[u8]> { - let start = find(&self.trailer, b"")?; - rest.get(..end_marker.checked_add(close)?.checked_add(2)?) - } - - /// Visits every chunk depth-first with its nesting depth (the top level is 1), without recursion. - pub fn walk(&self) -> Walk<'_, 'a> { - Walk { stack: vec![(self.chunks.iter(), 1)] } - } - - /// Copies all borrowed bytes so the file no longer borrows the input. - pub fn into_owned(self) -> AepFile<'static> { - AepFile { chunks: self.chunks.into_iter().map(Chunk::into_owned).collect(), trailer: Cow::Owned(self.trailer.into_owned()) } - } -} - -fn find(hay: &[u8], needle: &[u8]) -> Option { - if needle.is_empty() { - return Some(0); - } - hay.windows(needle.len()).position(|w| w == needle) -} - -/// Depth-first iterator over all chunks, see [`AepFile::walk`]. -pub struct Walk<'f, 'a> { - stack: Vec<(std::slice::Iter<'f, Chunk<'a>>, usize)>, -} - -impl<'f, 'a> Iterator for Walk<'f, 'a> { - type Item = (usize, &'f Chunk<'a>); - - fn next(&mut self) -> Option { - loop { - let (iter, depth) = self.stack.last_mut()?; - let depth = *depth; - match iter.next() { - Some(chunk) => { - let kids = chunk.children(); - if !kids.is_empty() { - self.stack.push((kids.iter(), depth.saturating_add(1))); - } - return Some((depth, chunk)); - } - None => { - self.stack.pop(); - } - } - } - } -} diff --git a/crates/aep/src/container/effect_map.rs b/crates/aep/src/container/effect_map.rs index 29274fc68..b08e92afe 100644 --- a/crates/aep/src/container/effect_map.rs +++ b/crates/aep/src/container/effect_map.rs @@ -4,8 +4,8 @@ //! Plain data; the evidence for each row is in `docs/aep-format.md` 3.7 and the case numbers in //! the comments. The importer reads a file through it, the exporter writes the inverse. -use crate::container::effects::ParamKind; use ParamKind as K; +use craft_aep::ParamKind; /// How a stored parameter value becomes an EffectCraft value. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/aep/src/container/effects.rs b/crates/aep/src/container/effects.rs deleted file mode 100644 index 6ccfa3af6..000000000 --- a/crates/aep/src/container/effects.rs +++ /dev/null @@ -1,729 +0,0 @@ -//! Effect instances: match name, instance name, the parameter list from `parT`/`pard` and the -//! values stored with the instance. -//! -//! An effect on a layer is a `LIST sspc` under `ADBE Effect Parade`. It holds `fnam` (the -//! instance name), `LIST parT` (the parameter definitions: `parn`, then a `tdmn` and a 148-byte -//! `pard` per parameter, a `pdnm` after a popup), `LIST tdgp` (the values) and `pgui`. Only -//! parameters that differ from their `pard` default have a value record in the `tdgp` (the Layer -//! Control and button records are the exceptions: they always exist). -//! -//! When several layers carry an effect of the same type, only one instance has a full `parT`; the -//! others have an empty `LIST parT` (case 383). Their parameter definitions are the ones in the -//! project-level `LIST EfdG` (one `EfDf` per effect type: a `tdmn` with the match name, then a copy -//! of one instance's `sspc`), see [`Project::effect_params`]. That copy also carries the values of -//! the instance it was copied from, so values are only ever read from the instance's own `tdgp`. -//! -//! Some files have no `EfdG` at all (seen in 17 projects, all from inside After Effects-made -//! Motion Graphics templates). In those, one instance per effect type kept its full `parT` (which -//! one is not known) and it is the only place the definitions are written, so the other instances -//! of that type borrow them from it (#3170). - -use std::collections::{HashMap, HashSet}; - -use crate::container::bytes::{array, be_f32, be_f64, be_i32, be_u16, be_u32, cstr, text, until_nul}; -use crate::container::index::Node; -use crate::container::typed::{KeyList, Layer, Project, PropGroup, PropNode, Property}; - -/// The parameter type, the `u32` at byte 12 of `pard`. The numbering matches the plug-in -/// parameter types of the After Effects effect interface. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ParamKind { - /// `0`: a layer reference (also the implicit first parameter, the input layer). - Layer, - /// `1`: an integer slider (Fast Box Blur's Iterations, 412-414): the default is an `i32` at - /// `pard` byte 56 (3), the valid maximum an `i32` at byte 128 (50), the value record a plain - /// `f64` (1.0). - IntSlider, - /// `2`: a fixed-point (16.16) slider. - FixedSlider, - /// `3`: an angle (16.16 degrees). - Angle, - /// `4` - Checkbox, - /// `5` - Color, - /// `6` - Point, - /// `7`: a popup menu (the items are in the `pdnm` chunk). - Popup, - /// `9`: no data (the group-end entry `ADBE Effect Built In Params`). - NoData, - /// `10`: a floating-point slider. - FloatSlider, - /// `11`: arbitrary data (Hue/Saturation's Channel Range, Levels' Histogram, 443, 511): the - /// value record is a 4-byte `cdat`, the data itself the `aRbp` of the `LIST aRbs` after it, - /// see [`Effect::arbitrary_data`]. - ArbitraryData, - /// `12`: a path / mask reference. - Path, - /// `13`: the start of a twirl-down group (Exposure's Master, Red, Green and Blue, 389). It - /// holds no value; its value record always exists with `cdat` 0. - GroupStart, - /// `14`: the end of a twirl-down group (its name repeats the group's name, 389). It holds no - /// value; its value record always exists with `cdat` 0. - GroupEnd, - /// `15`: a button (Tint's and Gradient Ramp's Swap Colors). It holds no value; its value - /// record always exists with `cdat` 0 (356, 368). - Button, - /// Any other value. - Other(u32), -} - -impl ParamKind { - fn from_u32(v: u32) -> Self { - match v { - 0 => Self::Layer, - 1 => Self::IntSlider, - 2 => Self::FixedSlider, - 3 => Self::Angle, - 4 => Self::Checkbox, - 5 => Self::Color, - 6 => Self::Point, - 7 => Self::Popup, - 9 => Self::NoData, - 10 => Self::FloatSlider, - 11 => Self::ArbitraryData, - 12 => Self::Path, - 13 => Self::GroupStart, - 14 => Self::GroupEnd, - 15 => Self::Button, - other => Self::Other(other), - } - } -} - -/// A decoded parameter value. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum ParamValue { - /// A slider or angle value as stored: float sliders, fixed sliders and angles keep a plain - /// `f64` in their value record (an angle in degrees; a fixed slider in its own scale, see - /// [`EffectParam::valid_max`]); defaults read from `pard` are 16.16 decoded for fixed sliders - /// and angles. - Number(f64), - /// A checkbox: stored as 1.0 when on; an absent record means off. - Bool(bool), - /// A point control as stored: a fraction of the layer size (`[111, 222]` px on a 1920x1080 - /// layer is `[111/1920, 222/1080]`). - Point([f64; 2]), - /// A layer control: the id of the chosen layer (the `tdpi` chunk next to the value record). - /// In the implicit first parameter it is the id of the layer that owns the effect. - Layer(u32), - /// A colour as ARGB fractions 0..1 (stored as doubles 0..255 in the order alpha, red, green, - /// blue: a colour `[0.2, 0.6, 1]` is `[255, 51, 153, 255]`, with float rounding). - Argb([f64; 4]), - /// A popup's item index, 1-based (Gradient Ramp's Radial Ramp is 2, 377): the default in - /// `pard`, or the stored selection. - Index(u32), -} - -/// What a Layer Control points at, given the id of the layer that owns the effect. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum LayerRef { - /// The layer itself (the default, "Layer 1" on the first layer): the stored `tdpi` equals the - /// owning layer's id. - This, - /// None: the stored `tdpi` is 0. - Nothing, - /// Another layer, by id. - Layer(u32), -} - -/// An effect instance on a layer. -#[derive(Debug, Clone)] -pub struct Effect<'f, 'a> { - match_name: String, - chunk: Node<'f, 'a>, -} - -/// Where the parameter definitions of an effect instance come from. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DefinitionSource { - /// The instance's own `parT`. - Instance, - /// The project-level `EfdG/EfDf` copy for the effect's match name (the instance's own `parT` - /// is empty, 383). - Project, - /// The own `parT` of another instance of the same match name in the file: the instance's - /// own `parT` is empty and the file has no project-level copy of the type (a project without - /// `EfdG`, #3170). - OtherInstance, - /// None of these has any: the effect has no readable parameter definitions. - Missing, -} - -/// One parameter of an effect. -#[derive(Debug, Clone)] -pub struct EffectParam<'f, 'a> { - /// The position in `parT` (0 is the implicit input layer). - pub index: usize, - /// The `tdmn` match name (`-NNNN`, the last one is - /// `ADBE Effect Built In Params`). - pub match_name: String, - pub kind: ParamKind, - /// The parameter name (`Blurriness`, `Slider`, ...; empty for the implicit parameters). - pub name: String, - /// The popup items (`pdnm`, split at `|`; for a button its label, e.g. `Swap Colors`). - pub items: Option>, - /// True when the definition is borrowed: the project-level copy ([`DefinitionSource::Project`]) - /// or another instance's ([`DefinitionSource::OtherInstance`]). - pub borrowed_definition: bool, - pard: &'f [u8], - stored: Option>, -} - -impl<'f, 'a> Effect<'f, 'a> { - /// The effect's match name (`ADBE Slider Control`, `ADBE Gaussian Blur 2`, ...). - pub fn match_name(&self) -> &str { - &self.match_name - } - - /// The underlying `LIST sspc` chunk. - pub fn chunk(&self) -> Node<'f, 'a> { - self.chunk - } - - /// The instance name shown in the effect controls (`fnam`). - pub fn name(&self) -> Option { - self.chunk.child(b"fnam")?.child(b"Utf8")?.bytes().map(text) - } - - /// The name the user gave the instance: the `tdsn` of the instance's value group when it is - /// not the placeholder `-_0_/-` (610: `My Tint`; `fnam` keeps the effect's own name `Tint`). - /// `None` while the instance shows the effect's name. - pub fn user_name(&self) -> Option { - let values = self.chunk.child_list(b"tdgp")?; - let name = values.child(b"tdsn")?.child(b"Utf8")?.bytes().map(text)?; - (name != "-_0_/-" && !name.is_empty()).then_some(name) - } - - /// The instance's fx switch: the `tdsb` of its value group is 1 when on and 0 when switched - /// off (`fx-switch` cases: one instance on, one off, both in one save). `None` for another - /// value or a missing group. - pub fn enabled(&self) -> Option { - match be_u32(self.chunk.child_list(b"tdgp")?.child(b"tdsb")?.bytes()?, 0)? { - 1 => Some(true), - 0 => Some(false), - _ => None, - } - } - - /// The name After Effects shows for the instance: [`Effect::user_name`], else [`Effect::name`]. - pub fn display_name(&self) -> Option { - self.user_name().or_else(|| self.name()) - } - - /// The number of parameters declared by `parn` (the implicit input layer and the built-in - /// entry included). - pub fn declared_param_count(&self) -> Option { - be_u32(self.chunk.child_list(b"parT")?.child(b"parn")?.bytes()?, 0) - } - - /// True when the instance's own `parT` holds parameter definitions (a `pard`). A second - /// instance of an effect type has an empty `parT` (383). - pub fn has_own_definitions(&self) -> bool { - self.chunk.child_list(b"parT").is_some_and(has_pard) - } - - /// The match names of the value records in the instance's own `tdgp` (properties only, not - /// groups), in file order, each once. - pub fn value_record_names(&self) -> Vec { - let mut seen: HashSet = HashSet::new(); - self.chunk - .child_list(b"tdgp") - .and_then(PropGroup::from_chunk) - .map(|g| g.entries()) - .unwrap_or_default() - .into_iter() - .filter(|e| matches!(e.node, PropNode::Property(_))) - .map(|e| e.match_name) - .filter(|n| seen.insert(n.clone())) - .collect() - } - - /// The parameters in the order of the instance's own `parT`. Empty for an instance whose - /// `parT` is empty; [`Project::effect_params`] falls back to the project's definitions. - pub fn params(&self) -> Vec> { - match self.chunk.child_list(b"parT") { - Some(part) => self.params_from(part, false), - None => Vec::new(), - } - } - - /// The parameters described by `part` (a `LIST parT`) with the values of this instance. - fn params_from(&self, part: Node<'f, 'a>, borrowed: bool) -> Vec> { - let mut out: Vec> = Vec::new(); - // The stored values by match name: the first entry of a name, as `PropGroup::get` finds it - // (a group of that name means no stored value). Indexed once: a lookup per parameter - // would scan the whole group for each of them. - let mut values: HashMap>> = HashMap::new(); - for e in self.chunk.child_list(b"tdgp").and_then(PropGroup::from_chunk).map(|g| g.entries()).unwrap_or_default() { - let stored = if let PropNode::Property(p) = e.node { Some(p) } else { None }; - values.entry(e.match_name).or_insert(stored); - } - let mut pending: Option = None; - for c in part.children() { - if c.is(b"tdmn") { - pending = c.bytes().map(|b| text(until_nul(b))); - } else if c.is(b"pard") { - let Some(pard) = c.bytes() else { continue }; - let match_name = pending.take().unwrap_or_default(); - let stored = values.get(&match_name).copied().flatten(); - out.push(EffectParam { - index: out.len(), - match_name, - kind: ParamKind::from_u32(be_u32(pard, 12).unwrap_or(u32::MAX)), - name: cstr(pard, 16, 32).unwrap_or_default(), - items: None, - borrowed_definition: borrowed, - pard, - stored, - }); - } else if c.is(b"pdnm") - && let Some(last) = out.last_mut() - && let Some(u) = c.child(b"Utf8") - && let Some(b) = u.bytes() - // An empty `pdnm` names nothing (EffectCraft's exports write one: the effect - // supplies its items). - && !b.is_empty() - { - last.items = Some(text(b).split('|').map(str::to_string).collect()); - } - } - out - } -} - -/// True when a `LIST parT` holds parameter definitions (a `pard`). -fn has_pard(part: Node<'_, '_>) -> bool { - part.children().any(|c| c.is(b"pard")) -} - -impl<'f, 'a> Project<'f, 'a> { - /// The project-level effect definitions (`LIST EfdG`): one entry per effect type, the match - /// name and the `LIST parT` of the copied instance, in file order (the stack order of the - /// types, 365/366). The `EfDC` count before them is little-endian and is not needed to read - /// them. A type whose copy has no definitions is left out. - pub fn effect_definitions(&self) -> Vec<(String, Node<'f, 'a>)> { - let mut out: Vec<(String, Node<'f, 'a>)> = Vec::new(); - let Some(defs) = self.effect_defs else { return out }; - let mut seen: HashSet = HashSet::new(); - for df in defs.children().filter(|c| c.is_list(b"EfDf")) { - let mut name: Option = None; - for c in df.children() { - if c.is(b"tdmn") { - name = c.bytes().map(|b| text(until_nul(b))); - } else if c.is_list(b"sspc") - && let Some(n) = name.take() - && let Some(part) = c.child_list(b"parT").filter(|p| has_pard(*p)) - && seen.insert(n.clone()) - { - out.push((n, part)); - } - } - } - out - } - - /// [`Self::effect_definitions`] indexed by match name, for looking up many effects: build it - /// once per file, not once per effect (a file can hold many definitions and many instances). - /// For a type without a project-level copy it also keeps the own `parT` of the first instance - /// in the file (items, layers and effects in file order) that has one. - pub fn effect_definition_index(&self) -> EffectDefinitions<'f, 'a> { - let by_name: HashMap> = self.effect_definitions().into_iter().collect(); - let mut instances: HashMap> = HashMap::new(); - for item in self.all_items() { - let Some(comp) = item.comp() else { continue }; - for layer in comp.layers() { - for fx in layer.effects() { - if by_name.contains_key(&fx.match_name) || instances.contains_key(&fx.match_name) { - continue; - } - if let Some(part) = fx.chunk.child_list(b"parT").filter(|p| has_pard(*p)) { - instances.insert(fx.match_name, part); - } - } - } - } - EffectDefinitions { by_name, instances } - } - - /// Where the parameter definitions of `effect` come from. Builds the index each call: use - /// [`Self::effect_definition_index`] for more than one effect. - pub fn definition_source(&self, effect: &Effect<'f, 'a>) -> DefinitionSource { - self.effect_definition_index().source(effect) - } - - /// The parameters of `effect` ([`EffectDefinitions::params`]). Builds the index each call: - /// use [`Self::effect_definition_index`] for more than one effect. - pub fn effect_params(&self, effect: &Effect<'f, 'a>) -> Vec> { - self.effect_definition_index().params(effect) - } -} - -/// The borrowable effect definitions by match name ([`Project::effect_definition_index`]). -#[derive(Debug, Clone, Default)] -pub struct EffectDefinitions<'f, 'a> { - /// The project-level copies (`EfdG`). - by_name: HashMap>, - /// For a type without a project-level copy: the own `parT` of the first instance that has one. - instances: HashMap>, -} - -impl<'f, 'a> EffectDefinitions<'f, 'a> { - /// Where the parameter definitions of `effect` come from. - pub fn source(&self, effect: &Effect<'f, 'a>) -> DefinitionSource { - if effect.has_own_definitions() { - DefinitionSource::Instance - } else if self.by_name.contains_key(effect.match_name()) { - DefinitionSource::Project - } else if self.instances.contains_key(effect.match_name()) { - DefinitionSource::OtherInstance - } else { - DefinitionSource::Missing - } - } - - /// The parameters of `effect`: from its own `parT`, or, when that is empty, from the - /// project-level definition of its match name, else from another instance of it that has - /// its own ([`EffectParam::borrowed_definition`]). Values always come from the instance's own - /// records (absent = the `pard` default); the values next to borrowed definitions belong to - /// another instance and are never read. - pub fn params(&self, effect: &Effect<'f, 'a>) -> Vec> { - if effect.has_own_definitions() { - return effect.params(); - } - match self.by_name.get(effect.match_name()).or_else(|| self.instances.get(effect.match_name())) { - Some(part) => effect.params_from(*part, true), - None => Vec::new(), - } - } -} - -impl<'f, 'a> EffectParam<'f, 'a> { - /// The raw 148-byte `pard` record (it contains stale memory after the name). - pub fn pard(&self) -> &'f [u8] { - self.pard - } - - /// The value record stored with the instance (`-NNNN` in the instance's `tdgp`), which - /// exists only for parameters that differ from the default. - pub fn stored(&self) -> Option> { - self.stored - } - - /// True when the parameter's value record has keyframes ([`EffectParam::keys`]); then - /// [`EffectParam::stored_value`] is `None` and [`EffectParam::value`] is not the value. - pub fn is_animated(&self) -> bool { - self.stored.is_some_and(|p| p.is_animated()) - } - - /// The keyframes of an animated parameter: plain 48-byte records for sliders (363), 152-byte - /// colour records (364) and 104-byte spatial records for points (382), with the values in the - /// stored units of [`EffectParam::stored_value`]. - pub fn keys(&self) -> Option> { - self.stored?.keys() - } - - /// The value in the value record: float and fixed sliders, angles, checkboxes, points, - /// colours, popups and layer controls. A record counts when its `tdsb` is 1 and it has no - /// keyframes; a layer control reads the `tdpi` chunk; a button has no value. - pub fn stored_value(&self) -> Option { - let p = self.stored?; - if self.kind != ParamKind::Layer && p.flags() != Some(1) { - return None; - } - self.recorded_value() - } - - /// The value in the value record when the record is written (`tdsb` 1) or in the default - /// state (`tdsb` 3): what [`EffectParam::stored_value`] reads, also from a default-state - /// record. Lumetri Color writes the values of its hidden parameters so (High Dynamic Range, - /// HDR Specular, Look: 1200 `lumetri-01-set-all`, `-02-sec-top`, `-06-sec-light`; After - /// Effects reads back the recorded values). `None` with keyframes, without a record or for a - /// record in any other state (no sample has one; the importer reports it as damaged). - pub fn recorded_value(&self) -> Option { - let p = self.stored?; - if self.kind == ParamKind::Layer { - return be_u32(p.chunk().child(b"tdpi")?.bytes()?, 0).map(ParamValue::Layer); - } - if !matches!(p.flags(), Some(1 | 3)) || p.is_animated() { - return None; - } - let v = p.static_value()?; - match self.kind { - ParamKind::FloatSlider | ParamKind::FixedSlider | ParamKind::Angle | ParamKind::IntSlider => v.first().copied().map(ParamValue::Number), - ParamKind::Checkbox => v.first().map(|x| ParamValue::Bool(*x != 0.0)), - ParamKind::Point => { - let [x, y] = *v.as_slice().first_chunk::<2>()?; - Some(ParamValue::Point([x, y])) - } - ParamKind::Popup => { - let index = v.first().copied()?; - (0.0..=f64::from(u32::MAX)).contains(&index).then(|| ParamValue::Index(index.round() as u32)) - } - ParamKind::Color => { - let [a, r, g, b] = *v.as_slice().first_chunk::<4>()?; - Some(ParamValue::Argb([a / 255.0, r / 255.0, g / 255.0, b / 255.0])) - } - _ => None, - } - } - - /// The default stored in `pard` at byte 56: a float slider's `f64`, a fixed slider's or angle's - /// 16.16 value, a colour's ARGB bytes, a popup's item index, a point's two 16.16 fractions of - /// the layer size (Point Control 0.5, 0.5: the layer centre, also on a 100x100 layer; - /// Gradient Ramp Start 0.5, 0 and End 0.5, 1), an integer slider's `i32` (Iterations 3, 412), - /// a checkbox's `u32` (1 = on: Repeat Edge Pixels of Fast Box Blur and Gaussian Blur, read back - /// on, 412, 417; 0 = off: Shadow Only 420, Bypass Linear Light Conversion 389); other types: - /// `None`. - /// - /// It is the default and not the current value: Gaussian Blur with Blurriness 40 still has 25 - /// here and a value record with 40 (After Effects itself reads a fresh Gaussian Blur back as 25). - /// Exception: selecting a popup item also writes the selection to this slot. So a popup whose - /// definition was borrowed from the project copy ([`EffectParam::borrowed_definition`]) has no - /// reliable default here (the slot holds the copied instance's selection): `None`. - pub fn pard_default(&self) -> Option { - match self.kind { - ParamKind::Popup if self.borrowed_definition => None, - ParamKind::FloatSlider => be_f64(self.pard, 56).map(ParamValue::Number), - ParamKind::FixedSlider | ParamKind::Angle => be_i32(self.pard, 56).map(|v| ParamValue::Number(f64::from(v) / 65536.0)), - ParamKind::IntSlider => be_i32(self.pard, 56).map(|v| ParamValue::Number(f64::from(v))), - ParamKind::Checkbox => be_u32(self.pard, 56).map(|v| ParamValue::Bool(v != 0)), - ParamKind::Popup => be_u32(self.pard, 56).map(ParamValue::Index), - ParamKind::Point => { - let p = [f64::from(be_i32(self.pard, 56)?) / 65536.0, f64::from(be_i32(self.pard, 60)?) / 65536.0]; - // A fresh instance stores fractions of the layer (0.5, 0.5); After Effects' save of - // a project it opened stores percent (50, 50: the re-saves of read-back tests e1 and - // e2, where Gradient Ramp's Start and End and every other point default came back - // as 50 / 0 and 50 / 100). Point - // defaults lie inside the layer, so a component beyond 1 tells percent. - let percent = p.iter().any(|c| c.abs() > 1.0 + 1e-9); - Some(ParamValue::Point(if percent { p.map(|c| c / 100.0) } else { p })) - } - ParamKind::Color => { - let [a, r, g, b] = array::<4>(self.pard, 56)?.map(|c| f64::from(c) / 255.0); - Some(ParamValue::Argb([a, r, g, b])) - } - _ => None, - } - } - - /// True when the parameter is at its default: it has no value record (a record exists exactly - /// when the value differs from the `pard` default; setting a value back to the default removes - /// the record again), or the record equals the default. A record in the default state (`tdsb` - /// 3) counts with its value ([`EffectParam::recorded_value`]). `None` when that cannot be - /// decided (unknown parameter type, keyframes). - pub fn is_default(&self) -> Option { - match (self.stored, self.kind) { - // A Layer Control always has its record, and a popup selection overwrites the default - // in `pard`. Buttons and group markers hold no value at all. - (_, ParamKind::Layer | ParamKind::Button | ParamKind::GroupStart | ParamKind::GroupEnd) => None, - (None, _) => Some(true), - (Some(_), ParamKind::Popup) => Some(false), - (Some(_), _) => { - let stored = self.recorded_value()?; - // A checkbox's default is in `pard` too (on for Repeat Edge Pixels, 412). - Some(self.pard_default().is_some_and(|d| d == stored)) - } - } - } - - /// A point control in pixels of a layer of this size (the stored point is a fraction of the - /// layer size; the default is the layer centre). `None` for other parameter types. - pub fn point_px(&self, layer_width: f64, layer_height: f64) -> Option<[f64; 2]> { - match self.value()? { - ParamValue::Point([x, y]) if self.kind == ParamKind::Point => Some([x * layer_width, y * layer_height]), - _ => None, - } - } - - /// For a Layer Control: what the stored layer id means for the layer that owns the effect. - /// `None` for other types and for the implicit first parameter of an effect. - pub fn layer_ref(&self, owner_layer_id: u32) -> Option { - if self.kind != ParamKind::Layer || self.index == 0 { - return None; - } - match self.stored_value()? { - ParamValue::Layer(0) => Some(LayerRef::Nothing), - ParamValue::Layer(id) if id == owner_layer_id => Some(LayerRef::This), - ParamValue::Layer(id) => Some(LayerRef::Layer(id)), - _ => None, - } - } - - /// The largest valid value of a slider, from `pard`: a fixed slider's 16.16 at byte 128 (Tint - /// Amount to Tint 100, Gradient Ramp Ramp Scatter 512 and Blend With Original 1.0, Drop Shadow - /// Opacity 255), a float slider's `f32` at byte 108 (Blurriness 30000, Exposure 100, Exposure's - /// Gamma Correction 10). The stored scale of a - /// slider differs per parameter (Amount 37.5 % is stored 37.5, Blend 25 % is stored 0.25), so - /// this is what tells a reader the scale. `None` for other types. - pub fn valid_max(&self) -> Option { - match self.kind { - ParamKind::FixedSlider => be_i32(self.pard, 128).map(|v| f64::from(v) / 65536.0), - ParamKind::FloatSlider => be_f32(self.pard, 108).map(f64::from), - ParamKind::IntSlider => be_i32(self.pard, 128).map(f64::from), - _ => None, - } - } - - /// The smallest valid value of a float slider, the `f32` at byte 104 of `pard` (Exposure - /// -100, Offset -2, Gamma Correction 0.1: 389). `None` for other types (a fixed slider's - /// minimum is not decoded). - pub fn valid_min(&self) -> Option { - match self.kind { - ParamKind::FloatSlider => be_f32(self.pard, 104).map(f64::from), - _ => None, - } - } - - /// The range of a float slider's slider (what the control's drag covers, inside the valid - /// range): the `f32` pair at bytes 112 and 116 of `pard` (Exposure -4..4, Offset -0.5..0.5, - /// Gamma Correction 0.1..10: 389). Each value record repeats it as `tdum` / `tduM`. `None` - /// for other types. - pub fn slider_range(&self) -> Option<(f64, f64)> { - match self.kind { - ParamKind::FloatSlider => Some((f64::from(be_f32(self.pard, 112)?), f64::from(be_f32(self.pard, 116)?))), - _ => None, - } - } - - /// For a popup: the number of items (`u16` at byte 60 of `pard`). - pub fn popup_item_count(&self) -> Option { - if self.kind != ParamKind::Popup { - return None; - } - be_u16(self.pard, 60) - } - - /// For a popup: the selected item index (1-based): the stored selection, else the default. - pub fn popup_selected_index(&self) -> Option { - match self.value()? { - ParamValue::Index(i) if self.kind == ParamKind::Popup => Some(i), - _ => None, - } - } - - /// For a popup: the text of the selected item. - pub fn popup_selected_item(&self) -> Option<&str> { - let index = usize::try_from(self.popup_selected_index()?).ok()?.checked_sub(1)?; - self.items.as_ref()?.get(index).map(String::as_str) - } - - /// The effective value: the value in the record when there is one, also in a record in the - /// default state (`tdsb` 3, [`EffectParam::recorded_value`]), else the `pard` default (absent = - /// default); a checkbox without a record is off. - pub fn value(&self) -> Option { - self.recorded_value().or_else(|| self.pard_default()).or(match self.kind { - ParamKind::Checkbox if self.stored.is_none() => Some(ParamValue::Bool(false)), - _ => None, - }) - } -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The effects on the layer, in stack order (`ADBE Effect Parade`). - pub fn effects(&self) -> Vec> { - let Some(root) = self.properties() else { return Vec::new() }; - let Some(PropNode::Group(parade)) = root.get("ADBE Effect Parade") else { return Vec::new() }; - parade - .entries() - .into_iter() - .filter_map(|e| match e.node { - PropNode::Other(chunk) if chunk.is_list(b"sspc") => Some(Effect { match_name: e.match_name, chunk }), - _ => None, - }) - .collect() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::container::Chunk; - - fn tdmn(name: &str) -> Chunk<'static> { - let mut b = name.as_bytes().to_vec(); - b.resize(40, 0); - Chunk::data(*b"tdmn", b) - } - - fn pard() -> Chunk<'static> { - Chunk::data(*b"pard", vec![0u8; 48]) - } - - fn tdbs() -> Chunk<'static> { - Chunk::list(*b"tdbs", Vec::new()) - } - - /// An effect instance whose `parT` names `defs` and whose `tdgp` stores `stored` (in order). - fn instance(defs: &[String], stored: &[(String, Chunk<'static>)]) -> Chunk<'static> { - let part = defs.iter().flat_map(|n| [tdmn(n), pard()]).collect(); - let values = stored.iter().flat_map(|(n, c)| [tdmn(n), c.clone()]).collect(); - Chunk::list(*b"sspc", vec![Chunk::list(*b"parT", part), Chunk::list(*b"tdgp", values)]) - } - - #[test] - fn a_parameter_takes_the_first_stored_entry_of_its_name() { - let names: Vec = ["A", "B", "C"].map(String::from).to_vec(); - // `A` is stored twice (the first wins), `B` names a group (no stored value), `C` is absent. - let stored = vec![ - ("A".to_string(), tdbs()), - ("B".to_string(), Chunk::list(*b"tdgp", Vec::new())), - ("A".to_string(), Chunk::list(*b"tdbs", vec![Chunk::data(*b"cdat", vec![0u8; 8])])), - ]; - let chunk = instance(&names, &stored); - let fx = Effect { match_name: "X".into(), chunk: Node::from(&chunk) }; - let params = fx.params(); - assert_eq!(params.iter().map(|p| p.match_name.as_str()).collect::>(), ["A", "B", "C"]); - let first = params.first().and_then(|p| p.stored).expect("A stored"); - assert!(first.chunk.children().next().is_none(), "the first A (the second has a cdat)"); - assert!(params.get(1).is_some_and(|p| p.stored.is_none()), "a group of that name is no stored value"); - assert!(params.get(2).is_some_and(|p| p.stored.is_none())); - } - - #[test] - fn many_parameters_are_read_in_linear_time() { - // 100 000 parameters with 100 000 stored values: a lookup per parameter that scans the - // group (as before) is 1e10 entry builds; one index is instant. - let n = 100_000; - let names: Vec = (0..n).map(|i| format!("P{i}")).collect(); - let stored: Vec<(String, Chunk<'static>)> = names.iter().map(|m| (m.clone(), tdbs())).collect(); - let chunk = instance(&names, &stored); - let fx = Effect { match_name: "X".into(), chunk: Node::from(&chunk) }; - let params = fx.params(); - assert_eq!(params.len(), n); - assert!(params.iter().all(|p| p.stored.is_some())); - } - - #[test] - fn many_project_definitions_are_indexed_once() { - // 50 000 definitions, each twice (the first copy wins), then 1000 instances without - // their own definitions looked up through one index. - let n = 50_000; - let mut defs = Vec::new(); - for round in 0..2 { - for i in 0..n { - let part = Chunk::list(*b"parT", vec![tdmn(&format!("R{round}")), pard()]); - defs.push(Chunk::list(*b"EfDf", vec![tdmn(&format!("FX{i}")), Chunk::list(*b"sspc", vec![part])])); - } - } - let efdg = Chunk::list(*b"EfdG", defs); - let fold = Chunk::list(*b"Fold", Vec::new()); - let project = Project { fold: Node::from(&fold), effect_defs: Some(Node::from(&efdg)) }; - let all = project.effect_definitions(); - assert_eq!(all.len(), n); - let index = project.effect_definition_index(); - let bare = Chunk::list(*b"sspc", vec![Chunk::list(*b"parT", Vec::new())]); - for i in (0..n).step_by(50) { - let fx = Effect { match_name: format!("FX{i}"), chunk: Node::from(&bare) }; - assert_eq!(index.source(&fx), DefinitionSource::Project); - let params = index.params(&fx); - assert_eq!(params.iter().map(|p| p.match_name.as_str()).collect::>(), ["R0"], "the first copy's definitions"); - assert!(params.iter().all(|p| p.borrowed_definition)); - } - let unknown = Effect { match_name: "nope".into(), chunk: Node::from(&bare) }; - assert_eq!(index.source(&unknown), DefinitionSource::Missing); - assert!(index.params(&unknown).is_empty()); - assert_eq!(project.definition_source(&unknown), DefinitionSource::Missing); - } -} diff --git a/crates/aep/src/container/error.rs b/crates/aep/src/container/error.rs deleted file mode 100644 index fefc05b24..000000000 --- a/crates/aep/src/container/error.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! Errors of the container reader and writer. - -use std::fmt; - -/// Why a file could not be read or written. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum AepError { - /// The input is shorter than the 12-byte `RIFX` header, or does not start with `RIFX`. - NotRifx, - /// The form type after the declared size is not `Egg!`. - BadFormType([u8; 4]), - /// The declared container size runs past the end of the input. - Truncated { declared: u64, available: u64 }, - /// A chunk declares more body bytes than remain in its parent (`offset` is the chunk header). - ChunkTooLarge { offset: usize, size: u64, available: u64 }, - /// The chunk structure is not well formed at `offset` (what is wrong is in `what`). - Malformed { offset: usize, what: &'static str }, - /// Nesting is deeper than the allowed maximum. - TooDeep, - /// More chunks than the allowed maximum. - TooManyChunks, - /// A chunk or the whole file would not fit the 32-bit size fields when writing. - TooLarge, - /// An `.aepx` is not well-formed XML of the subset After Effects writes, at byte `offset` - /// (what is wrong is in `what`). - Xml { offset: usize, what: &'static str }, -} - -impl AepError { - /// Structural problems of the input that a lenient caller may repair by keeping a body opaque; - /// limits (`TooDeep`, `TooManyChunks`) are never repaired. - pub(crate) fn is_structural(&self) -> bool { - matches!(self, Self::ChunkTooLarge { .. } | Self::Malformed { .. } | Self::Truncated { .. }) - } -} - -impl fmt::Display for AepError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NotRifx => write!(f, "not an After Effects project: no RIFX header"), - Self::BadFormType(t) => write!(f, "RIFX form type {:?} is not \"Egg!\"", String::from_utf8_lossy(t)), - Self::Truncated { declared, available } => { - write!(f, "truncated file: the container declares {declared} bytes, {available} are available") - } - Self::ChunkTooLarge { offset, size, available } => { - write!(f, "chunk at offset {offset} declares {size} bytes, only {available} remain") - } - Self::Malformed { offset, what } => write!(f, "malformed chunk structure at offset {offset}: {what}"), - Self::TooDeep => write!(f, "chunks are nested too deeply"), - Self::TooManyChunks => write!(f, "too many chunks"), - Self::TooLarge => write!(f, "chunk too large for the 32-bit size field"), - Self::Xml { offset, what } => write!(f, "not a readable After Effects XML project (.aepx): {what} at byte {offset}"), - } - } -} - -impl std::error::Error for AepError {} diff --git a/crates/aep/src/container/footage.rs b/crates/aep/src/container/footage.rs deleted file mode 100644 index 14aeb1116..000000000 --- a/crates/aep/src/container/footage.rs +++ /dev/null @@ -1,474 +0,0 @@ -//! Item ids and labels, footage items (solids and files), precomp linkage, and the name and size -//! of a layer's source. - -use crate::container::bytes::{be_f32, be_f64, be_i32, be_u32, cstr, le_u32, text, until_nul}; -use crate::container::header::Rational; -use crate::container::index::Node; -use crate::container::typed::{Item, ItemKind, Layer, Project}; - -/// The footage data of an item (`LIST Pin ` with `sspc`, `opti` and, for files, `Als2/alas`). -#[derive(Debug, Clone, PartialEq)] -pub struct Footage { - /// The 4-character file type tag at byte 22 of `sspc` (`Soli` for a solid, `png!` for a png). - pub file_type: String, - /// The width in pixels (`u32` at byte 30 of `sspc`). - pub width: u32, - /// The height in pixels (`u32` at byte 34 of `sspc`). - pub height: u32, - /// The display name stored in `opti` (the item's own `Utf8` name is empty for footage): at byte - /// 26 for a solid and at byte 58 for a file. - pub name: Option, - /// True for a solid (tag `Soli` at the start of `opti`). - pub is_solid: bool, - /// The colour of a solid as ARGB floats 0..1 (`opti` bytes 10, 14, 18, 22); a red solid is - /// `[1, 1, 0, 0]`. - pub solid_argb: Option<[f32; 4]>, - /// The file path from the alias JSON (`Als2/alas`, key `fullpath`); none for solids. For an - /// image sequence it is the sequence **folder**. - pub path: Option, - /// The duration in seconds as stored (`sspc` `u32` at byte 38 over `u32` at byte 42; unreduced): - /// 0/1 for stills, 48000/48000 for the 1 s WAV (the sample rate is the denominator), 3/30 for - /// the three-frame image sequence (the frame rate is the denominator). - pub duration: Option, - /// The native frame rate (`sspc` `u32` at byte 56): 30 for the image sequence, 0 for stills, - /// audio and solids (also 0 when the byte is missing). - pub native_frame_rate: u32, - /// The bits per pixel (`sspc` `u32` at byte 60): 32 for an RGBA still, 24 for an RGB sequence, - /// 0 for solids and audio. - pub bits_per_pixel: u32, - /// The size in bytes of the source file(s) (`sspc` `u32` at byte 208): 149 for the png, 96044 - /// for the WAV (44 + 48000 x 2), 504 for three 168-byte png files. - pub file_size: u32, - /// The audio sample rate (`sspc` `f64` at byte 160, 48000.0 for the WAV and for an mp4 with - /// 48 kHz sound); `None` for footage without audio. - pub audio_sample_rate: Option, - /// True when the alias points at a folder (`"target_is_folder":true`): an image sequence is ONE - /// item whose alias is its folder and whose `opti` holds the first file name. - pub is_sequence: bool, - /// The one layer of a Photoshop file the item shows; `None` for the merged image and for - /// any other footage. - pub psd_layer: Option, -} - -/// One layer of a Photoshop file shown by a footage item, from its `opti` (tag `8BPS`, -/// docs/aep-format.md 3.3): the layer record's index as a big-endian `i32` at byte 14 (-1 for the -/// merged image), the document's sides as little-endian `u32` at 32 and 36, its bounds top, left, -/// bottom, right as little-endian `i32` at 78, 82, 86 and 90, and its name (UTF-8, NUL -/// terminated) from byte 344. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PsdLayer { - /// The layer record's position in the file (bottom of the stack = 0). - pub index: u32, - pub name: String, - /// Top, left, bottom, right in document pixels; all 0 for a layer without pixels (an - /// adjustment layer). - pub bounds: [i32; 4], - /// The document's two sides (bytes 32 and 36; which one is the width is not sampled: the one - /// file read has a square document). 0 when not stored. - pub document: [u32; 2], -} - -/// Most bytes of a Photoshop layer name read. -const MAX_NAME: usize = 1024; - -impl PsdLayer { - /// The bounds' width and height; `None` when they are empty. - pub fn size(&self) -> Option<(u32, u32)> { - let [top, left, bottom, right] = self.bounds; - let w = u32::try_from(i64::from(right) - i64::from(left)).ok().filter(|w| *w > 0)?; - let h = u32::try_from(i64::from(bottom) - i64::from(top)).ok().filter(|h| *h > 0)?; - Some((w, h)) - } - - /// Whether the document is `size` big, its sides in either order. - pub fn document_is(&self, size: (u32, u32)) -> bool { - let [a, b] = self.document; - a > 0 && b > 0 && ((a, b) == size || (b, a) == size) - } - - /// The layer an `opti` names; `None` for another tag, the merged image or a cut record. - fn read(opti: &[u8]) -> Option { - if opti.get(..4) != Some(&b"8BPS"[..]) { - return None; - } - let index = u32::try_from(be_i32(opti, 14)?).ok()?; - let le_i32 = |at| le_u32(opti, at).map(|v| i32::from_le_bytes(v.to_le_bytes())); - // (After Effects writes 602 bytes; a longer hostile name is cut.) - let name = opti.get(344..).map(|b| text(until_nul(b.get(..MAX_NAME).unwrap_or(b)))).unwrap_or_default(); - let document = [le_u32(opti, 32).unwrap_or(0), le_u32(opti, 36).unwrap_or(0)]; - Some(Self { index, name, bounds: [le_i32(78)?, le_i32(82)?, le_i32(86)?, le_i32(90)?], document }) - } -} - -impl Footage { - /// The solid's colour as fractions R, G, B. - pub fn solid_rgb(&self) -> Option<[f32; 3]> { - let [_, r, g, b] = self.solid_argb?; - Some([r, g, b]) - } -} - -/// The boolean value of `"key"` in a flat JSON object (`true` / `false`); `None` when missing. -pub(crate) fn json_bool(json: &[u8], key: &str) -> Option { - let needle = format!("\"{key}\":"); - let needle = needle.as_bytes(); - let at = json.windows(needle.len()).position(|w| w == needle)?; - let rest = json.get(at.checked_add(needle.len())?..)?; - if rest.starts_with(b"true") { - Some(true) - } else if rest.starts_with(b"false") { - Some(false) - } else { - None - } -} - -/// The string value of `"key"` in a flat JSON object, with the standard escapes decoded. -/// Returns `None` when the key is missing or the value is not a string. The key is the first -/// occurrence of `"key"` that is followed by `:` (the same text as a value is skipped). -pub(crate) fn json_string(json: &[u8], key: &str) -> Option { - let needle = format!("\"{key}\""); - let needle = needle.as_bytes(); - let mut from = 0usize; - loop { - let at = from.checked_add(json.get(from..)?.windows(needle.len()).position(|w| w == needle)?)?; - let after = at.checked_add(needle.len())?; - if let Some(v) = json_string_at(json, after) { - return Some(v); - } - from = at.checked_add(1)?; - } -} - -/// The string value right after a key ending at `i` (`: "…"`), or `None` when none follows. -fn json_string_at(json: &[u8], mut i: usize) -> Option { - let skip_ws = |i: &mut usize| { - while json.get(*i).is_some_and(|c| c.is_ascii_whitespace()) { - *i = i.saturating_add(1); - } - }; - skip_ws(&mut i); - if json.get(i) != Some(&b':') { - return None; - } - i = i.saturating_add(1); - skip_ws(&mut i); - if json.get(i) != Some(&b'"') { - return None; - } - i = i.saturating_add(1); - let mut out: Vec = Vec::new(); - loop { - let c = *json.get(i)?; - i = i.saturating_add(1); - match c { - b'"' => return Some(text(&out)), - b'\\' => { - let e = *json.get(i)?; - i = i.saturating_add(1); - match e { - b'n' => out.push(b'\n'), - b't' => out.push(b'\t'), - b'r' => out.push(b'\r'), - b'b' => out.push(8), - b'f' => out.push(12), - b'u' => { - let hex4 = |at: usize| { - json.get(at..at.checked_add(4)?).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u32::from_str_radix(h, 16).ok()) - }; - let mut code = hex4(i)?; - i = i.saturating_add(4); - // A character outside the BMP is a high surrogate and a `\u` low surrogate. - if (0xd800..0xdc00).contains(&code) - && json.get(i..i.saturating_add(2)) == Some(b"\\u") - && let Some(lo) = hex4(i.saturating_add(2)).filter(|lo| (0xdc00..0xe000).contains(lo)) - { - code = 0x10000 + ((code - 0xd800) << 10) + (lo - 0xdc00); - i = i.saturating_add(6); - } - let ch = char::from_u32(code).unwrap_or('\u{fffd}'); - let mut buf = [0u8; 4]; - out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); - } - other => out.push(other), - } - } - other => out.push(other), - } - } -} - -/// The numbering of an image sequence item (353, 603), or its file list when it was imported with -/// Force alphabetical order. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SequenceInfo { - /// The file name before the frame number (`seq_`, `shot_`): the first `Utf8` after the alias. - /// An empty prefix is not stored (`0001.png`): the one `Utf8` is then the suffix. - pub prefix: String, - /// The file name after the frame number (`.png`, `.exr`): the second `Utf8` after the alias. - pub suffix: String, - /// The first and last frame number (`sspc` `u32` at 172 and 176: 1 and 3 in 353, 101 and 103 - /// in 603; both `0xFFFFFFFF` for a sequence with a file list). - pub start: u32, - pub end: u32, - /// The digits of the frame number (`sspc` `u32` at 180: 3 for `seq_001`, 4 for `shot_0101`). - pub digits: u32, - /// The file names in order for a sequence imported with Force alphabetical order (`LIST StVc` - /// after the alias: `StVS` with the count as a little-endian `u32`, then one `Utf8` per file); - /// empty for a numbered sequence. When set, it replaces the numbering. - pub files: Vec, -} - -impl SequenceInfo { - /// The file name of frame `n` (`shot_0101.exr`). - pub fn file_name(&self, n: u32) -> String { - let width = usize::try_from(self.digits.min(16)).unwrap_or(0); - format!("{}{n:0width$}{}", self.prefix, self.suffix) - } - - /// The number of files: the listed files, or the frame numbers from start to end (0 when the - /// end lies before the start). - pub fn frame_count(&self) -> u32 { - if self.files.is_empty() { - self.end.checked_sub(self.start).map_or(0, |d| d.saturating_add(1)) - } else { - u32::try_from(self.files.len()).unwrap_or(u32::MAX) - } - } - - /// The name of the `i`-th file (from 0): from the file list, or numbered from `start`; `None` - /// past the last file. - pub fn nth_file_name(&self, i: u32) -> Option { - if self.files.is_empty() { - let n = self.start.checked_add(i).filter(|n| *n <= self.end)?; - Some(self.file_name(n)) - } else { - self.files.get(usize::try_from(i).ok()?).cloned() - } - } -} - -/// The file names of a `LIST StVc` (Force alphabetical order): the `Utf8` children in order, at most -/// as many as the count in `StVS` (little-endian `u32`) says. Empty names count toward that number -/// and are then skipped. Without a readable count (no `StVS`, or one shorter than 4 bytes) the list -/// is unreadable (empty). A name that is not a plain file name (holding `/`, `\`, `:` or a control -/// character such as NUL, or being `.` or `..`) makes the whole list unreadable (empty): the names -/// are joined to the folder. -fn sequence_file_list(list: Node<'_, '_>) -> Vec { - // After Effects writes the count first (the one sample); a list without a readable count is - // not read rather than guessed. - let Some(count) = list.child(b"StVS").and_then(|c| c.bytes()).and_then(|b| le_u32(b, 0)).and_then(|n| usize::try_from(n).ok()) else { - return Vec::new(); - }; - let names: Vec = list.children().filter(|c| c.is(b"Utf8")).filter_map(Node::bytes).take(count).map(text).filter(|n| !n.is_empty()).collect(); - if names.iter().any(|n| n.contains(|c: char| matches!(c, '/' | '\\' | ':') || c.is_control()) || n == "." || n == "..") { - return Vec::new(); - } - names -} - -/// The prefix and suffix of a sequence whose naming holds one `Utf8` (`part`): After Effects leaves -/// out an empty prefix (`0001.png` stores only `.png`). The stored first file name (`opti`) decides: -/// a name starting with `part` has it as the prefix, one ending with it as the suffix. Without that -/// evidence, a `part` starting with `.` is the suffix (an extension); anything else is not read. -fn single_name_part(part: &str, first_file: Option<&str>) -> Option<(String, String)> { - if let Some(first) = first_file.filter(|_| !part.is_empty()) { - match (first.starts_with(part), first.ends_with(part)) { - (true, false) => return Some((part.to_string(), String::new())), - (false, true) => return Some((String::new(), part.to_string())), - _ => {} - } - } - part.starts_with('.').then(|| (String::new(), part.to_string())) -} - -impl<'f, 'a> Item<'f, 'a> { - /// The numbering of an image sequence (an item whose alias is a folder); `None` for anything - /// else. - pub fn sequence_info(&self) -> Option { - let f = self.footage()?; - if !f.is_sequence { - return None; - } - let pin = self.chunk.child_list(b"Pin ")?; - let sspc = pin.child(b"sspc")?.bytes()?; - let after = pin.children().position(|c| c.is_list(b"Als2"))?; - let naming = || pin.children().skip(after.saturating_add(1)).take_while(|c| !c.is(b"opti")); - let (start, end, digits) = (be_u32(sspc, 172)?, be_u32(sspc, 176)?, be_u32(sspc, 180)?); - // Force alphabetical order: the file list replaces the numbering. - if let Some(list) = naming().find(|c| c.is_list(b"StVc")) { - let files = sequence_file_list(list); - if files.is_empty() { - return None; - } - return Some(SequenceInfo { prefix: String::new(), suffix: String::new(), start, end, digits, files }); - } - let names: Vec = naming().filter(|c| c.is(b"Utf8")).filter_map(Node::bytes).map(text).take(2).collect(); - let (prefix, suffix) = match names.as_slice() { - [prefix, suffix] => (prefix.clone(), suffix.clone()), - // An empty prefix is not stored (`0001.png` has only `.png`). - [one] => single_name_part(one, f.name.as_deref())?, - _ => return None, - }; - Some(SequenceInfo { prefix, suffix, start, end, digits, files: Vec::new() }) - } - - /// The rate a clip is conformed to (Interpret Footage ▸ Conform to frame rate; `sspc` `u32` at - /// byte 146): 30 for the 25 fps mp4 conformed to 30 (645), `None` when not conformed (0 in 644, - /// 606) or for an item without footage data. The effective rate is then also at byte 150 while - /// the stored duration (bytes 38 / 42) and byte 56 stay native. A conformed image sequence - /// stores the new rate in bytes 42, 56 and 150 instead and keeps 0 here (615). - pub fn conform_frame_rate(&self) -> Option { - let sspc = self.chunk.child_list(b"Pin ")?.child(b"sspc")?.bytes()?; - be_u32(sspc, 146).filter(|r| *r > 0) - } - - /// The item id: the big-endian `u32` at byte 16 of `idta` (what a layer's source id refers to). - pub fn id(&self) -> Option { - be_u32(self.chunk.child(b"idta")?.bytes()?, 16) - } - - /// The label colour index, byte 58 of `idta` (15 for a composition made by precomposing). - pub fn label(&self) -> Option { - self.chunk.child(b"idta")?.bytes()?.get(58).copied() - } - - /// The footage data of a footage item. - pub fn footage(&self) -> Option { - if self.kind()? != ItemKind::Footage { - return None; - } - let pin = self.chunk.child_list(b"Pin ")?; - let sspc = pin.child(b"sspc")?.bytes()?; - let opti = pin.child(b"opti")?.bytes()?; - let is_solid = opti.get(..4) == Some(&b"Soli"[..]); - let alias = pin.child_list(b"Als2").and_then(|als| als.child(b"alas")).and_then(|alas| alas.bytes()); - let path = alias.and_then(|json| json_string(json, "fullpath")); - let is_sequence = alias.and_then(|json| json_bool(json, "target_is_folder")).unwrap_or(false); - let solid_argb = if is_solid { Some([be_f32(opti, 10)?, be_f32(opti, 14)?, be_f32(opti, 18)?, be_f32(opti, 22)?]) } else { None }; - Some(Footage { - file_type: cstr(sspc, 22, 4)?, - width: be_u32(sspc, 30)?, - height: be_u32(sspc, 34)?, - name: cstr(opti, if is_solid { 26 } else { 58 }, 256).filter(|n| !n.is_empty()), - is_solid, - solid_argb, - path, - duration: be_u32(sspc, 38).zip(be_u32(sspc, 42)).map(|(num, den)| Rational { num: i64::from(num), den: i64::from(den) }), - native_frame_rate: be_u32(sspc, 56).unwrap_or(0), - bits_per_pixel: be_u32(sspc, 60).unwrap_or(0), - file_size: be_u32(sspc, 208).unwrap_or(0), - audio_sample_rate: be_f64(sspc, 160).filter(|r| r.is_finite() && *r > 0.0), - is_sequence, - psd_layer: PsdLayer::read(opti), - }) - } - - /// The name this item shows in the project: the item name, or for footage the name stored in - /// `opti`. - pub fn display_name(&self) -> Option { - self.name().or_else(|| self.footage().and_then(|f| f.name)) - } -} - -impl<'f, 'a> Project<'f, 'a> { - /// The item with this id (`idta` byte 16), searching every item including those in folders. - pub fn item_by_id(&self, id: u32) -> Option> { - self.all_items().into_iter().find(|i| i.id() == Some(id)) - } - - /// The item a layer is made from (its source id), e.g. the solid, the footage or the precomp. - pub fn layer_source(&self, layer: &Layer<'f, 'a>) -> Option> { - self.item_by_id(layer.header()?.source_id?) - } - - /// The pixel size of a layer's source: a footage item's width and height, or a precomp's - /// composition size. - pub fn layer_source_size(&self, layer: &Layer<'f, 'a>) -> Option<(u32, u32)> { - let source = self.layer_source(layer)?; - match source.kind()? { - ItemKind::Footage => source.footage().map(|f| (f.width, f.height)), - ItemKind::Composition => source.comp()?.header().map(|h| (u32::from(h.width), u32::from(h.height))), - ItemKind::Folder | ItemKind::Other(_) => None, - } - } -} - -#[cfg(test)] -mod tests { - use super::{PsdLayer, json_string}; - - /// A 602-byte Photoshop `opti` naming layer `index` with `bounds` and `name`. - fn opti(index: i32, bounds: [i32; 4], name: &[u8]) -> Vec { - let mut b = vec![0u8; 602]; - b[..4].copy_from_slice(b"8BPS"); - b[14..18].copy_from_slice(&index.to_be_bytes()); - for (i, v) in bounds.iter().enumerate() { - b[78 + 4 * i..82 + 4 * i].copy_from_slice(&v.to_le_bytes()); - } - b[344..344 + name.len()].copy_from_slice(name); - b - } - - #[test] - fn a_photoshop_layer_reads_its_index_bounds_and_name() { - let l = PsdLayer::read(&opti(7, [749, 800, 764, 848], "tést".as_bytes())).unwrap(); - assert_eq!((l.index, l.name.as_str(), l.bounds, l.size()), (7, "tést", [749, 800, 764, 848], Some((48, 15)))); - // The merged image, another tag, a cut record: no layer. - assert_eq!(PsdLayer::read(&opti(-1, [0; 4], b"x")), None); - let mut other = opti(1, [0; 4], b"x"); - other[..4].copy_from_slice(b"Soli"); - assert_eq!(PsdLayer::read(&other), None); - assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..80]), None); - // A cut name, and no name at all. - assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..345]).unwrap().name, "x"); - assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..300]).unwrap().name, ""); - // A layer without pixels has no size; extreme bounds do not overflow. - assert_eq!(PsdLayer::read(&opti(2, [0; 4], b"")).unwrap().size(), None); - assert_eq!(PsdLayer::read(&opti(2, [i32::MIN, i32::MIN, i32::MAX, i32::MAX], b"")).unwrap().size(), Some((u32::MAX, u32::MAX))); - assert_eq!(PsdLayer::read(&opti(2, [i32::MAX, 0, i32::MIN, 1], b"")).unwrap().size(), None); - // The document's size, its sides in either order; none when not stored. - let mut doc = opti(0, [0, 0, 1000, 800], b""); - doc[32..36].copy_from_slice(&800u32.to_le_bytes()); - doc[36..40].copy_from_slice(&1000u32.to_le_bytes()); - let l = PsdLayer::read(&doc).unwrap(); - assert_eq!(l.document, [800, 1000]); - assert!(l.document_is((800, 1000)) && l.document_is((1000, 800)) && !l.document_is((800, 800))); - assert!(!PsdLayer::read(&opti(0, [0; 4], b"")).unwrap().document_is((0, 0))); - } - - #[test] - fn reads_a_string_with_escapes() { - let json = br#"{"a":1,"fullpath":"C:\\dir\\f\u00e9.png","b":"x"}"#; - assert_eq!(json_string(json, "fullpath").as_deref(), Some(r"C:\dir\fé.png")); - assert_eq!(json_string(json, "b").as_deref(), Some("x")); - assert_eq!(json_string(json, "missing"), None); - assert_eq!(json_string(br#"{"a" : "spaced"}"#, "a").as_deref(), Some("spaced")); - // The key's text as an earlier value is not the key. - assert_eq!(json_string(br#"{"a":"fullpath","fullpath":"x"}"#, "fullpath").as_deref(), Some("x")); - // A surrogate pair is one character; a lone half stays U+FFFD. - assert_eq!(json_string(br#"{"a":"x\ud83d\ude00y"}"#, "a").as_deref(), Some("x😀y")); - assert_eq!(json_string(br#"{"a":"\ud83dz"}"#, "a").as_deref(), Some("\u{fffd}z")); - assert_eq!(json_string(br#"{"a":"\ude00"}"#, "a").as_deref(), Some("\u{fffd}")); - } - - #[test] - fn damaged_json_never_panics() { - for json in [ - &br#"{"fullpath":"#[..], - br#"{"fullpath":"abc"#, - br#"{"fullpath":"ab\"#, - br#"{"fullpath":"\u12"}"#, - br#"{"fullpath":"\uzzzz"}"#, - br#"{"fullpath":5}"#, - br#"{"fullpath"}"#, - b"\"fullpath\"", - b"", - b"\"", - br#"{"fullpath":"\ud800"}"#, - ] { - let _ = json_string(json, "fullpath"); - } - assert_eq!(json_string(br#"{"fullpath":"\ud800"}"#, "fullpath").as_deref(), Some("\u{fffd}")); - } -} diff --git a/crates/aep/src/container/header.rs b/crates/aep/src/container/header.rs deleted file mode 100644 index 060d37840..000000000 --- a/crates/aep/src/container/header.rs +++ /dev/null @@ -1,468 +0,0 @@ -//! The layer header (`ldta`) and the composition header (`cdta`, `PRin`). -//! -//! Every field here has a verified layout: the decoded value equals the value the generated corpus -//! was made with (see `docs/aep-format.md`, sections 4 and 5, for the evidence per field). Fields that -//! the corpus does not decide are not decoded; the raw bytes stay reachable through the chunk. - -use crate::container::bytes::{array, be_i32, be_u16, be_u32, cstr, text, until_nul}; -use crate::container::typed::{Comp, Item, Layer, TimeBase, utf8_child}; - -/// An exact fraction. Used for times (`seconds = num / den`) and for the pixel aspect ratio. The -/// fields hold the stored values unreduced; [`Rational::reduced`] normalises. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Rational { - pub num: i64, - pub den: i64, -} - -impl Rational { - /// A fraction with a positive denominator, reduced; `None` for a zero denominator. - pub fn new(num: i64, den: i64) -> Option { - Self { num, den }.reduced() - } - - /// The value as `f64`, `None` for a zero denominator. - pub fn to_f64(&self) -> Option { - (self.den != 0).then(|| self.num as f64 / self.den as f64) - } - - /// The same value in lowest terms with a positive denominator, `None` for a zero denominator. - pub fn reduced(&self) -> Option { - if self.den == 0 { - return None; - } - let (mut a, mut b) = (i128::from(self.num).unsigned_abs(), i128::from(self.den).unsigned_abs()); - let (mut x, mut y) = (a, b); - while y != 0 { - (x, y) = (y, x % y); - } - if x == 0 { - x = 1; - } - a /= x; - b /= x; - let negative = (self.num < 0) != (self.den < 0); - let num = i64::try_from(a).ok()?; - let den = i64::try_from(b).ok()?; - Some(Self { num: if negative { num.checked_neg()? } else { num }, den }) - } - - /// `self + other * factor`, exact, `None` on a zero denominator or overflow. - fn plus_scaled(&self, other: &Rational, factor: &Rational) -> Option { - if self.den == 0 || other.den == 0 || factor.den == 0 { - return None; - } - // other * factor = (other.num * factor.num) / (other.den * factor.den) - let scaled_num = i128::from(other.num).checked_mul(i128::from(factor.num))?; - let scaled_den = i128::from(other.den).checked_mul(i128::from(factor.den))?; - let den = i128::from(self.den).checked_mul(scaled_den)?; - let num = i128::from(self.num).checked_mul(scaled_den)?.checked_add(scaled_num.checked_mul(i128::from(self.den))?)?; - Rational { num: i64::try_from(num).ok()?, den: i64::try_from(den).ok()? }.reduced() - } -} - -/// The layer quality switch, `ldta` byte 5. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Quality { - /// `1` - Draft, - /// `2` - Best, - /// Any other value (`0` on cameras and lights; wireframe was not sampled). - Other(u8), -} - -/// The blend mode, `ldta` byte 99. Six modes were sampled; any other mode is kept as its raw code. -/// The codes 2, 4, 5, 6 and 7 coincide with the numbers of the After Effects plug-in transfer -/// modes; Difference is 26. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum BlendMode { - /// `2` - Normal, - /// `4` - Add, - /// `5` - Multiply, - /// `6` - Screen, - /// `7` - Overlay, - /// `26` - Difference, - /// Any other value (not sampled; `0` on cameras and lights). - Other(u8), -} - -impl BlendMode { - /// The mode for a code. - pub fn from_code(code: u8) -> Self { - match code { - 2 => Self::Normal, - 4 => Self::Add, - 5 => Self::Multiply, - 6 => Self::Screen, - 7 => Self::Overlay, - 26 => Self::Difference, - other => Self::Other(other), - } - } - - /// The code as stored. - pub fn code(&self) -> u8 { - match self { - Self::Normal => 2, - Self::Add => 4, - Self::Multiply => 5, - Self::Screen => 6, - Self::Overlay => 7, - Self::Difference => 26, - Self::Other(code) => *code, - } - } -} - -/// The light type, `ldta` `u32` at byte 136 of a light layer (0 on every other layer). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum LightType { - /// `0` (701) - Parallel, - /// `1` - Spot, - /// `2` - Point, - /// `3` (702; a light created as an environment light by script without the Advanced 3D - /// renderer is stored as an ambient light too, 704) - Ambient, - /// Any other value (an environment light was not sampled). - Other(u32), -} - -/// The layer type, `ldta` `u32` at byte 128. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum LayerType { - /// `0`: solid, footage, precomp or null object (an AV layer). - Av, - /// `1` - Light, - /// `2` - Camera, - /// `3` - Text, - /// `4` - Shape, - /// Any other value. - Other(u32), -} - -/// The decoded fields of a layer's `ldta` chunk (164 bytes; the fields below need the first 140). -/// -/// Times are stored as a numerator and a denominator (the denominator is the composition's -/// timescale, 1 in a precomp layer). The in and out points are stored **relative to the start**: -/// the absolute in point is `start + in * stretch`, see [`LayerHeader::in_point`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct LayerHeader { - /// The layer id (unique in the project); parent links use it. - pub id: u32, - pub quality: Quality, - /// The numerator of the time stretch (signed `i32` at byte 8). The stretch is the exact ratio - /// `stretch / stretch_den`: `1/1` = 100 %, `2/1` = 200 %, `1/2` = 50 %, `3/2` = 150 %, `-1/1` = - /// -100 % (a time-reversed layer, 981), `-1/2` = -50 % (983), see - /// [`LayerHeader::stretch_ratio`]. - pub stretch: i32, - /// The denominator of the time stretch (`u32` at byte 108; 1 in every file before 50 % was - /// sampled). - pub stretch_den: u32, - /// The layer start time, as stored. - pub start: Rational, - /// The in point relative to the start, as stored. - pub in_relative: Rational, - /// The out point relative to the start, as stored. - pub out_relative: Rational, - /// Bytes 37, 38 and 39 of `ldta`: the switch bits (see the `is_*` methods). - pub flag_bytes: [u8; 3], - /// The id of the source item (`ldta` byte 40), `None` for the values `0` (shape, text, camera) - /// and `0xffff_ffff` (light). - pub source_id: Option, - /// The label colour index (`ldta` byte 61: 1 red, 5, 8 blue, ...). - pub label: u8, - /// The copy of the layer name at byte 64 (31 characters at most; the layer's `Utf8` child holds - /// the full name). - pub name_copy: String, - pub blend_mode: BlendMode, - pub layer_type: LayerType, - /// The id of the parent layer, `None` when there is none. - pub parent_id: Option, - /// The `u32` at byte 136 (the light type of a light layer, 0 elsewhere), see - /// [`LayerHeader::light_type`]. - pub light_type_code: u32, -} - -impl LayerHeader { - /// Decodes an `ldta` body; `None` when it is shorter than 140 bytes. - pub fn parse(ldta: &[u8]) -> Option { - let time = |at: usize| Some(Rational { num: i64::from(be_i32(ldta, at)?), den: i64::from(be_u32(ldta, at.checked_add(4)?)?) }); - let source = be_u32(ldta, 40)?; - let parent = be_u32(ldta, 132)?; - Some(Self { - id: be_u32(ldta, 0)?, - quality: match *ldta.get(5)? { - 1 => Quality::Draft, - 2 => Quality::Best, - other => Quality::Other(other), - }, - stretch: be_i32(ldta, 8)?, - stretch_den: be_u32(ldta, 108)?, - start: time(12)?, - in_relative: time(20)?, - out_relative: time(28)?, - flag_bytes: array::<3>(ldta, 37)?, - source_id: (source != 0 && source != u32::MAX).then_some(source), - label: *ldta.get(61)?, - name_copy: text(until_nul(ldta.get(64..96)?)), - blend_mode: BlendMode::from_code(*ldta.get(99)?), - layer_type: match be_u32(ldta, 128)? { - 0 => LayerType::Av, - 1 => LayerType::Light, - 2 => LayerType::Camera, - 3 => LayerType::Text, - 4 => LayerType::Shape, - other => LayerType::Other(other), - }, - parent_id: (parent != 0).then_some(parent), - light_type_code: be_u32(ldta, 136)?, - }) - } - - fn flag(&self, byte: usize, mask: u8) -> bool { - self.flag_bytes.get(byte).is_some_and(|b| b & mask != 0) - } - - /// Byte 37 bit `0x02`: guide layer. - pub fn is_guide(&self) -> bool { - self.flag(0, 0x02) - } - - /// Byte 38 bit `0x02`: adjustment layer. - pub fn is_adjustment(&self) -> bool { - self.flag(1, 0x02) - } - - /// Byte 38 bit `0x04`: the 3D layer switch. - pub fn is_three_d(&self) -> bool { - self.flag(1, 0x04) - } - - /// Byte 38 bit `0x40`: the layer orients itself towards its point of interest. Set on two-node - /// cameras (byte 38 is `0x44`) and on all lights, clear on a one-node camera (`0x04`). - pub fn is_auto_oriented(&self) -> bool { - self.flag(1, 0x40) - } - - /// Byte 38 bit `0x08`: solo. - pub fn is_solo(&self) -> bool { - self.flag(1, 0x08) - } - - /// Byte 38 bit `0x80`: the layer was created as a null object. - pub fn is_null_object(&self) -> bool { - self.flag(1, 0x80) - } - - /// Byte 39 bit `0x01`: the video switch (the layer's eye icon; `enabled` in the scripting API). - pub fn is_video_enabled(&self) -> bool { - self.flag(2, 0x01) - } - - /// The same as [`LayerHeader::is_video_enabled`]. - pub fn is_enabled(&self) -> bool { - self.is_video_enabled() - } - - /// Byte 39 bit `0x02`: the audio switch (`audioEnabled`). - pub fn is_audio_enabled(&self) -> bool { - self.flag(2, 0x02) - } - - /// Byte 39 bit `0x04`: the effects switch (`effectsActive`). - pub fn is_effects_enabled(&self) -> bool { - self.flag(2, 0x04) - } - - /// Byte 39 bit `0x08`: the motion blur switch. - pub fn is_motion_blur(&self) -> bool { - self.flag(2, 0x08) - } - - /// Byte 39 bit `0x20`: locked. - pub fn is_locked(&self) -> bool { - self.flag(2, 0x20) - } - - /// Byte 39 bit `0x40`: shy. - pub fn is_shy(&self) -> bool { - self.flag(2, 0x40) - } - - /// Byte 39 bit `0x80`: collapse transformations / continuously rasterize. Shape and text - /// layers have it set from creation. - pub fn collapses_transformations(&self) -> bool { - self.flag(2, 0x80) - } - - /// The light type of a light layer: parallel 0, spot 1, point 2, ambient 3 (`None` for any - /// other layer type). - pub fn light_type(&self) -> Option { - (self.layer_type == LayerType::Light).then_some(match self.light_type_code { - 0 => LightType::Parallel, - 1 => LightType::Spot, - 2 => LightType::Point, - 3 => LightType::Ambient, - other => LightType::Other(other), - }) - } - - /// The time stretch as an exact reduced ratio (`stretch / stretch_den`: 50 % is `1/2`, 150 % - /// is `3/2`); `None` for a zero denominator. - pub fn stretch_ratio(&self) -> Option { - Rational::new(i64::from(self.stretch), i64::from(self.stretch_den)) - } - - /// The absolute in point, `start + in * stretch`, exact and reduced. - pub fn in_point(&self) -> Option { - self.start.plus_scaled(&self.in_relative, &self.stretch_ratio()?) - } - - /// The absolute out point, `start + out * stretch`, exact and reduced. For a footage layer the - /// stored denominator is the footage time base (the sample rate of an audio layer, the frame - /// rate of an image sequence), not the composition timescale. - pub fn out_point(&self) -> Option { - self.start.plus_scaled(&self.out_relative, &self.stretch_ratio()?) - } -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The layer id (`ldta` byte 0). - pub fn id(&self) -> Option { - be_u32(self.chunk.child(b"ldta")?.bytes()?, 0) - } - - /// The decoded `ldta`, see [`LayerHeader`]. - pub fn header(&self) -> Option { - LayerHeader::parse(self.chunk.child(b"ldta")?.bytes()?) - } - - /// The video switch (byte 39 bit `0x01`), `enabled` in the scripting API. - pub fn is_enabled(&self) -> Option { - self.header().map(|h| h.is_video_enabled()) - } - - /// The audio switch (byte 39 bit `0x02`), `audioEnabled`. - pub fn is_audio_enabled(&self) -> Option { - self.header().map(|h| h.is_audio_enabled()) - } - - /// The effects switch (byte 39 bit `0x04`), `effectsActive`. - pub fn is_effects_enabled(&self) -> Option { - self.header().map(|h| h.is_effects_enabled()) - } -} - -/// The renderer of a composition (`LIST PRin` / `prin`). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Renderer { - /// The match name (`ADBE Escher` for the Classic 3D renderer in the base project, - /// `ADBE Calder` for Advanced 3D). - pub match_name: String, - /// The display name (`Classic 3D`, `Advanced 3D`). - pub display_name: String, -} - -/// The decoded fields of a composition's `cdta` chunk (204 bytes; the fields below need 176). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CompHeader { - /// Frame duration (`u32` at byte 4) and timescale (`u32` at byte 8). - pub time_base: TimeBase, - /// The frame rate as 16.16 fixed point (`u32` at byte 156). - pub frame_rate_fixed: u32, - /// The composition duration in time units. - pub duration_units: u32, - /// The work area start in time units. - pub work_area_start_units: u32, - /// The work area end (start + duration) in time units; `None` when it is the whole - /// composition (stored as `0xffff_ffff`). - pub work_area_end_units: Option, - /// The background colour as R, G, B (bytes 52 to 54), 8 bits per channel: 0.5 is stored as 128 - /// and reads back as 128/255. - pub background: [u8; 3], - /// The shutter angle in degrees. - pub shutter_angle: u32, - pub width: u16, - pub height: u16, - /// The pixel aspect ratio as stored: numerator and denominator. - pub pixel_aspect: Rational, - /// The composition's motion blur switch. - pub motion_blur: bool, - /// The shutter phase in degrees (`i32` at byte 180, 0 by default, -90 in the sample); `None` - /// when the chunk ends before byte 184. - pub shutter_phase: Option, - /// The display start time (the comp start timecode) as `num / den` seconds: `u32` at byte 164 - /// over `u32` at byte 168 (0/1 by default; display start frame 100 at 25 fps is 102400/25600). - /// `None` when the chunk ends before byte 172. - pub display_start: Option, -} - -impl CompHeader { - /// Decodes a `cdta` body; `None` when it is shorter than 176 bytes. - pub fn parse(cdta: &[u8]) -> Option { - let work_end = be_u32(cdta, 36)?; - Some(Self { - time_base: TimeBase { frame_duration: be_u32(cdta, 4)?, timescale: be_u32(cdta, 8)? }, - frame_rate_fixed: be_u32(cdta, 156)?, - duration_units: be_u32(cdta, 44)?, - work_area_start_units: be_u32(cdta, 28)?, - work_area_end_units: (work_end != u32::MAX).then_some(work_end), - background: array::<3>(cdta, 52)?, - shutter_angle: be_u32(cdta, 172)?, - width: be_u16(cdta, 140)?, - height: be_u16(cdta, 142)?, - pixel_aspect: Rational { num: i64::from(be_u32(cdta, 144)?), den: i64::from(be_u32(cdta, 148)?) }, - motion_blur: cdta.get(139)? & 0x08 != 0, - shutter_phase: be_i32(cdta, 180), - display_start: be_u32(cdta, 164).zip(be_u32(cdta, 168)).map(|(num, den)| Rational { num: i64::from(num), den: i64::from(den) }), - }) - } - - /// Frames per second from the time base (`timescale / frame_duration`). - pub fn frame_rate(&self) -> Option { - self.time_base.frame_rate() - } - - /// The duration in seconds. - pub fn duration_seconds(&self) -> Option { - self.time_base.seconds(i32::try_from(self.duration_units).ok()?) - } -} - -impl<'f, 'a> Comp<'f, 'a> { - /// The decoded `cdta`, see [`CompHeader`]. - pub fn header(&self) -> Option { - CompHeader::parse(self.item.child(b"cdta")?.bytes()?) - } - - /// The composition name (the item's `Utf8` child). - pub fn name(&self) -> Option { - utf8_child(self.item).filter(|n| !n.is_empty()) - } - - /// The item this composition data belongs to. - pub fn item(&self) -> Item<'f, 'a> { - Item { chunk: self.item } - } - - /// The renderer (`LIST PRin` / `prin`: match name at byte 4, display name at byte 52, 32 - /// bytes each). - pub fn renderer(&self) -> Option { - let prin = self.item.child_list(b"PRin")?.child(b"prin")?.bytes()?; - Some(Renderer { match_name: cstr(prin, 4, 32)?, display_name: cstr(prin, 52, 32)? }) - } -} diff --git a/crates/aep/src/container/index.rs b/crates/aep/src/container/index.rs deleted file mode 100644 index 695d1e9f3..000000000 --- a/crates/aep/src/container/index.rs +++ /dev/null @@ -1,1015 +0,0 @@ -//! A read-only, flat index of the chunk tree for readers that only look (the importer). -//! -//! [`TreeIndex`] holds every chunk of a file in one `Vec` in depth-first order (a chunk, then its -//! whole subtree, then its next sibling). Each entry keeps its id, list type, pad byte, the bytes of -//! its body (borrowed from the input) and the index one past its subtree, so: -//! - a chunk's subtree is the index range `at + 1 .. end`, -//! - its direct children are found by stepping from `at + 1` to each child's `end`, -//! - the whole tree is one array, grown a few times while it is built and freed at once; it never -//! holds more slots than the input has room for chunk headers or the chunk limit allows. -//! -//! [`crate::container::parse`] builds the owned [`Chunk`] tree instead (one `Vec` per list), which -//! the exporter and editors need. [`TreeIndex::to_file`] and [`Node::to_chunk`] convert the index -//! into that tree where an owned one is needed. -//! -//! [`TreeIndex::parse_with_limits`] walks the input exactly as the [`Chunk`] parser does: the same -//! chunks are counted against [`Limits::max_chunks`] in the same order, the same lists are kept -//! opaque at [`Limits::max_depth`] or when damaged, and the same errors come back. A test compares -//! the two on the corpus and on generated and damaged trees. Two errors are its own, and both are -//! stricter than the [`Chunk`] parser (which would abort or could not address the tree): -//! [`AepError::TooLarge`] when the array cannot grow (a failed `try_reserve`), and -//! [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks. -//! -//! An `.aepx` is indexed by its own reader (`container/aepx.rs`), which decodes every body into -//! one buffer and fills the entries as it reads; the index then borrows that buffer -//! (`TreeIndex::from_drafts`). It gives the tree [`crate::container::read_aepx`] gives. -//! -//! [`Node`] is the handle the typed view ([`crate::container::Project`] and the types below it) -//! reads through: a chunk of either tree. The view works the same on both. - -use std::borrow::Cow; -use std::fmt; - -use crate::container::bytes::be_u32; -use crate::container::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; -use crate::container::error::AepError; -use crate::container::read::{Limits, container_end, id4}; - -/// What an entry's body is (the [`Body`] variants). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Kind { - Data, - /// [`Body::Chunks`]. - Nested, - List, - OpaqueList, -} - -/// One chunk of a [`TreeIndex`]. -#[derive(Debug, Clone, Copy)] -struct Entry<'a> { - /// The body bytes of a data chunk, or the bytes after the list type of an opaque list; empty - /// for a list or nested chunk (their content is their children). - data: &'a [u8], - id: [u8; 4], - /// The list type of a `LIST` (parsed or opaque); zero otherwise. - list_type: [u8; 4], - /// One past the last entry of this chunk's subtree. - end: u32, - kind: Kind, - pad: Option, -} - -impl<'a> Entry<'a> { - /// An entry for a chunk whose body is not read yet. - fn placeholder(id: [u8; 4]) -> Self { - Self { data: &[], id, list_type: [0; 4], end: 0, kind: Kind::Data, pad: None } - } -} - -/// An entry of an index whose bytes are still being written (the `.aepx` reader decodes into a -/// buffer that grows, so it keeps positions, not slices): the body is `start..start + len` of -/// that buffer. The fields are those of [`Entry`]; [`TreeIndex::from_drafts`] turns the list -/// into an index once the buffer is final. -#[derive(Debug, Clone, Copy)] -pub(crate) struct Draft { - pub(crate) start: usize, - pub(crate) len: usize, - pub(crate) id: [u8; 4], - pub(crate) list_type: [u8; 4], - pub(crate) end: u32, - pub(crate) kind: Kind, - pub(crate) pad: Option, -} - -impl Draft { - /// A data chunk with no body yet. - pub(crate) fn placeholder(id: [u8; 4]) -> Self { - Self { start: 0, len: 0, id, list_type: [0; 4], end: 0, kind: Kind::Data, pad: None } - } -} - -/// The chunk tree of a file as one flat, read-only array (see the module documentation). -#[derive(Clone)] -pub struct TreeIndex<'a> { - nodes: Vec>, - trailer: &'a [u8], -} - -impl fmt::Debug for TreeIndex<'_> { - /// The sizes only: the chunk count and the trailer length. - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TreeIndex").field("chunks", &self.nodes.len()).field("trailer", &self.trailer.len()).finish() - } -} - -/// An index that does not fit a `u32` (more than 4 billion chunks) is refused as too many chunks. -fn index_u32(at: usize) -> Result { - u32::try_from(at).map_err(|_| AepError::TooManyChunks) -} - -impl<'a> TreeIndex<'a> { - /// Indexes an `.aep` with the default [`Limits`]. - /// - /// # Errors - /// The errors of [`crate::container::parse`], for the same inputs. - pub fn parse(data: &'a [u8]) -> Result { - Self::parse_with_limits(data, Limits::default()) - } - - /// Indexes an `.aep` with explicit [`Limits`]. - /// - /// # Errors - /// The errors of [`crate::container::parse_with_limits`], for the same inputs and limits; also - /// [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks and - /// [`AepError::TooLarge`] when the array cannot be allocated. - pub fn parse_with_limits(data: &'a [u8], limits: Limits) -> Result { - let end = container_end(data)?; - // Every chunk header takes 8 bytes of its own and is counted once, so the tree never has - // more chunks than this. - let bound = (end.saturating_sub(12) / 8).min(limits.max_chunks); - let mut builder = Builder { data, limits, count: 0, nodes: Vec::new(), bound }; - // A small start; [`Builder::push`] doubles it as chunks arrive, never past the bound, so - // the array stays proportional to the chunk count (a file of a few large chunks gets a few - // slots, not one per 32 bytes). `try_reserve_exact` so it fails nothing here. - let _ = builder.nodes.try_reserve_exact(bound.min(INITIAL_SLOTS)); - builder.sequence(12, end, 1)?; - let trailer = data.get(end..).unwrap_or(&[]); - Ok(Self { nodes: builder.nodes, trailer }) - } - - /// The index of the entries `drafts` (in depth-first order, see [`Draft`]) whose bodies and - /// trailer are ranges of `buffer`. A range outside `buffer` reads as empty. The list is turned - /// into entries; a [`Draft`] and an [`Entry`] have the same size and alignment, so the standard - /// library reuses the list's allocation for them. - pub(crate) fn from_drafts(buffer: &'a [u8], drafts: Vec, trailer: (usize, usize)) -> Self { - let slice = |start: usize, len: usize| start.checked_add(len).and_then(|end| buffer.get(start..end)).unwrap_or(&[]); - let nodes = - drafts.into_iter().map(|d| Entry { data: slice(d.start, d.len), id: d.id, list_type: d.list_type, end: d.end, kind: d.kind, pad: d.pad }).collect(); - let trailer = buffer.get(trailer.0..trailer.1).unwrap_or(&[]); - Self { nodes, trailer } - } - - /// Indexes an already parsed (or built) chunk tree. The index borrows the file's bytes. - /// - /// # Errors - /// [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks. - pub fn from_file(file: &'a AepFile<'_>) -> Result { - // Sized once, to the chunks the tree holds. - let mut nodes: Vec> = Vec::new(); - nodes.try_reserve_exact(file.walk().count()).map_err(|_| AepError::TooLarge)?; - // Each frame: the siblings still to visit and the entry whose subtree they fill. - let mut stack: Vec<(std::slice::Iter<'a, Chunk<'_>>, Option)> = vec![(file.chunks.iter(), None)]; - while let Some((iter, parent)) = stack.last_mut() { - let parent = *parent; - match iter.next() { - Some(chunk) => { - let at = nodes.len(); - // The entry after this one must still have a `u32` index. - let next = index_u32(at.checked_add(1).ok_or(AepError::TooManyChunks)?)?; - let (kind, data, list_type) = match &chunk.body { - Body::Data(d) => (Kind::Data, &d[..], [0; 4]), - Body::Chunks(_) => (Kind::Nested, &[][..], [0; 4]), - Body::List { list_type, .. } => (Kind::List, &[][..], *list_type), - Body::OpaqueList { list_type, data } => (Kind::OpaqueList, &data[..], *list_type), - }; - nodes.push(Entry { data, id: chunk.id, list_type, end: next, kind, pad: chunk.pad }); - let kids = chunk.children(); - if !kids.is_empty() { - stack.push((kids.iter(), Some(at))); - } - } - None => { - stack.pop(); - if let Some(p) = parent { - let end = index_u32(nodes.len())?; - if let Some(e) = nodes.get_mut(p) { - e.end = end; - } - } - } - } - } - Ok(Self { nodes, trailer: &file.trailer[..] }) - } - - /// The number of chunks in the tree (at every depth). - pub fn len(&self) -> usize { - self.nodes.len() - } - - /// True when the container holds no chunks. - pub fn is_empty(&self) -> bool { - self.nodes.is_empty() - } - - /// The bytes after the container's declared end (see [`AepFile::trailer`]). - pub fn trailer(&self) -> &'a [u8] { - self.trailer - } - - /// The top-level chunks. - pub fn chunks(&self) -> Nodes<'_, 'a> { - Nodes(NodesRepr::Index { tree: self, next: 0, end: u32::try_from(self.nodes.len()).unwrap_or(u32::MAX) }) - } - - /// The first top-level chunk with this id. - pub fn chunk(&self, id: &[u8; 4]) -> Option> { - self.chunks().find(|c| c.is(id)) - } - - /// The first top-level `LIST` of this type. - pub fn list(&self, list_type: &[u8; 4]) -> Option> { - self.chunks().find(|c| c.is_list(list_type)) - } - - /// Visits every chunk depth-first with its nesting depth (the top level is 1), as - /// [`AepFile::walk`] does. - pub fn walk(&self) -> NodeWalk<'_, 'a> { - NodeWalk(WalkRepr::Index { tree: self, next: 0, end: u32::try_from(self.nodes.len()).unwrap_or(u32::MAX), open: Vec::new() }) - } - - /// The owned chunk tree (the bodies stay borrowed from the input): what - /// [`crate::container::parse`] gives for the same file. - pub fn to_file(&self) -> AepFile<'a> { - AepFile { chunks: self.build(0, u32::try_from(self.nodes.len()).unwrap_or(u32::MAX)), trailer: Cow::Borrowed(self.trailer) } - } - - /// The entry at `at`, `None` past the end. - fn entry(&self, at: u32) -> Option<&Entry<'a>> { - self.nodes.get(usize::try_from(at).ok()?) - } - - /// The end of the subtree at `at`; never before `at + 1`, so walks always move on. - fn end_of(&self, at: u32) -> u32 { - self.entry(at).map_or(u32::MAX, |e| e.end).max(at.saturating_add(1)) - } - - /// The owned chunks for the siblings that start at `next` and fill `next..end`, without - /// recursion. - fn build(&self, next: u32, end: u32) -> Vec> { - struct Frame<'a> { - /// The list or nested chunk being filled; `None` for the outermost range. - at: Option, - kids: Vec>, - next: u32, - end: u32, - } - let mut stack = vec![Frame { at: None, kids: Vec::new(), next, end }]; - loop { - let Some(top) = stack.last_mut() else { return Vec::new() }; - if top.next < top.end { - let at = top.next; - top.next = self.end_of(at); - let Some(e) = self.entry(at).copied() else { - top.next = top.end; - continue; - }; - match e.kind { - Kind::List | Kind::Nested => { - let sub_end = self.end_of(at); - stack.push(Frame { at: Some(at), kids: Vec::new(), next: at.saturating_add(1), end: sub_end }); - } - Kind::Data => top.kids.push(Chunk { id: e.id, body: Body::Data(Cow::Borrowed(e.data)), pad: e.pad }), - Kind::OpaqueList => { - top.kids.push(Chunk { id: e.id, body: Body::OpaqueList { list_type: e.list_type, data: Cow::Borrowed(e.data) }, pad: e.pad }); - } - } - } else { - let Some(frame) = stack.pop() else { return Vec::new() }; - let Some(at) = frame.at else { return frame.kids }; - let Some(e) = self.entry(at).copied() else { continue }; - let body = match e.kind { - Kind::Nested => Body::Chunks(frame.kids), - Kind::List | Kind::Data | Kind::OpaqueList => Body::List { list_type: e.list_type, children: frame.kids }, - }; - let chunk = Chunk { id: e.id, body, pad: e.pad }; - match stack.last_mut() { - Some(parent) => parent.kids.push(chunk), - None => return vec![chunk], - } - } - } - } -} - -/// The slots a [`TreeIndex`] starts with (32 KiB); it doubles from there. -const INITIAL_SLOTS: usize = 1024; - -/// Builds a [`TreeIndex`]; mirrors `read::Parser` step for step (see the module documentation). -struct Builder<'a> { - data: &'a [u8], - limits: Limits, - count: usize, - nodes: Vec>, - /// The most chunks the input can hold under the limits: `nodes` never reserves past it. - bound: usize, -} - -impl<'a> Builder<'a> { - /// Appends an entry. A full array grows by its length (at least 16), but never past - /// [`Self::bound`]; an allocation the target cannot make is an error, not an abort. - fn push(&mut self, entry: Entry<'a>) -> Result<(), AepError> { - let len = self.nodes.len(); - if len == self.nodes.capacity() { - let more = len.max(16).min(self.bound.saturating_sub(len)).max(1); - self.nodes.try_reserve_exact(more).map_err(|_| AepError::TooLarge)?; - } - self.nodes.push(entry); - Ok(()) - } - - /// Appends the sibling chunks that exactly fill `start..end`, each followed by its subtree. - fn sequence(&mut self, start: usize, end: usize, depth: usize) -> Result<(), AepError> { - let mut pos = start; - while pos < end { - let short = AepError::Malformed { offset: pos, what: "bytes left over that are too short for a chunk header" }; - let body_start = pos.checked_add(8).filter(|b| *b <= end).ok_or(short)?; - let id = id4(self.data, pos).ok_or(AepError::Malformed { offset: pos, what: "short read" })?; - let size = be_u32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize; - let avail = end - body_start; - if size > avail { - return Err(AepError::ChunkTooLarge { offset: pos, size: size as u64, available: avail as u64 }); - } - self.count = self.count.saturating_add(1); - if self.count > self.limits.max_chunks { - return Err(AepError::TooManyChunks); - } - let at = self.nodes.len(); - // This entry and the one after it must have `u32` indices. - index_u32(at.checked_add(1).ok_or(AepError::TooManyChunks)?)?; - self.push(Entry::placeholder(id))?; - let body_end = body_start + size; - self.body(at, id, body_start, body_end, depth)?; - let mut next = body_end; - let mut pad = None; - if size % 2 == 1 && next < end { - pad = Some(self.data.get(next).copied().ok_or(AepError::Malformed { offset: next, what: "missing pad byte" })?); - next += 1; - } - let subtree_end = index_u32(self.nodes.len())?; - if let Some(e) = self.nodes.get_mut(at) { - e.pad = pad; - e.end = subtree_end; - } - pos = next; - } - Ok(()) - } - - /// Like [`Self::sequence`] but a structural problem yields `false` and removes what the - /// attempt appended (the caller keeps bytes). The chunk count keeps the attempt's chunks, as - /// the [`Chunk`] parser's does. - fn tentative(&mut self, start: usize, end: usize, depth: usize) -> Result { - let mark = self.nodes.len(); - match self.sequence(start, end, depth) { - Ok(()) => Ok(true), - Err(e) if e.is_structural() => { - self.nodes.truncate(mark); - Ok(false) - } - Err(e) => Err(e), - } - } - - /// The input bytes `start..end` (empty when out of range). - fn slice(&self, start: usize, end: usize) -> &'a [u8] { - self.data.get(start..end).unwrap_or(&[]) - } - - /// Fills in the body of the entry at `at` once the parser knows what it is. - fn set(&mut self, at: usize, kind: Kind, data: &'a [u8], list_type: [u8; 4]) { - if let Some(e) = self.nodes.get_mut(at) { - e.kind = kind; - e.data = data; - e.list_type = list_type; - } - } - - /// Fills in the entry at `at` for the body `start..end` and appends its subtree. - fn body(&mut self, at: usize, id: [u8; 4], start: usize, end: usize, depth: usize) -> Result<(), AepError> { - let len = end - start; - if id == LIST && len >= 4 { - let list_type = id4(self.data, start).ok_or(AepError::Malformed { offset: start, what: "short read" })?; - if depth < self.limits.max_depth && self.tentative(start + 4, end, depth + 1)? { - self.set(at, Kind::List, &[], list_type); - } else { - let data = self.slice(start + 4, end); - self.set(at, Kind::OpaqueList, data, list_type); - } - return Ok(()); - } - if NESTED_IDS.contains(&id) && len >= 8 && depth < self.limits.max_depth { - let mark = self.nodes.len(); - if self.tentative(start, end, depth + 1)? && self.nodes.len() > mark { - self.set(at, Kind::Nested, &[], [0; 4]); - return Ok(()); - } - } - let data = self.slice(start, end); - self.set(at, Kind::Data, data, [0; 4]); - Ok(()) - } -} - -/// A chunk of either tree: an owned [`Chunk`] or an entry of a [`TreeIndex`]. The typed view -/// reads through it, so it works the same on both. Cheap to copy. -#[derive(Clone, Copy)] -pub struct Node<'f, 'a>(NodeRepr<'f, 'a>); - -#[derive(Clone, Copy)] -enum NodeRepr<'f, 'a> { - Chunk(&'f Chunk<'a>), - Index(&'f TreeIndex<'a>, u32), -} - -impl<'f, 'a> From<&'f Chunk<'a>> for Node<'f, 'a> { - /// The handle for this value. - fn from(chunk: &'f Chunk<'a>) -> Self { - Node(NodeRepr::Chunk(chunk)) - } -} - -/// Prints the chunk as [`Chunk`]'s `Debug` does, whichever tree it is in, without copying the -/// subtree. -impl fmt::Debug for Node<'_, '_> { - /// The chunk as `Chunk`'s `Debug` prints it. - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self.0 { - NodeRepr::Chunk(c) => fmt::Debug::fmt(c, f), - NodeRepr::Index(..) => f.debug_struct("Chunk").field("id", &self.id()).field("body", &BodyDebug(*self)).field("pad", &self.pad()).finish(), - } - } -} - -/// The body of an index [`Node`], printed as [`Body`]'s `Debug` prints it. -struct BodyDebug<'f, 'a>(Node<'f, 'a>); - -/// The children of a [`Node`], printed as a list. -struct ChildrenDebug<'f, 'a>(Node<'f, 'a>); - -impl fmt::Debug for BodyDebug<'_, '_> { - /// The body as `Body`'s `Debug` prints it. - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let Some(e) = self.0.entry() else { return f.write_str("?") }; - match e.kind { - Kind::Data => f.debug_tuple("Data").field(&e.data).finish(), - Kind::Nested => f.debug_tuple("Chunks").field(&ChildrenDebug(self.0)).finish(), - Kind::List => f.debug_struct("List").field("list_type", &e.list_type).field("children", &ChildrenDebug(self.0)).finish(), - Kind::OpaqueList => f.debug_struct("OpaqueList").field("list_type", &e.list_type).field("data", &e.data).finish(), - } - } -} - -impl fmt::Debug for ChildrenDebug<'_, '_> { - /// The children as a list. - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_list().entries(self.0.children()).finish() - } -} - -impl<'f, 'a> Node<'f, 'a> { - /// The entry at `at`, `None` past the end. - fn entry(self) -> Option<&'f Entry<'a>> { - match self.0 { - NodeRepr::Index(tree, at) => tree.entry(at), - NodeRepr::Chunk(_) => None, - } - } - - /// The [`Chunk`] when this node is one of an owned tree; `None` for an index entry (see - /// [`Self::to_chunk`]). - pub fn as_chunk(self) -> Option<&'f Chunk<'a>> { - match self.0 { - NodeRepr::Chunk(c) => Some(c), - NodeRepr::Index(..) => None, - } - } - - /// The chunk and its subtree as an owned [`Chunk`] (bodies stay borrowed). - pub fn to_chunk(self) -> Chunk<'a> { - match self.0 { - NodeRepr::Chunk(c) => c.clone(), - NodeRepr::Index(tree, at) => tree.build(at, tree.end_of(at)).into_iter().next().unwrap_or_else(|| Chunk::data(self.id(), &[][..])), - } - } - - /// The 4-byte id (see [`Chunk::id`]). - pub fn id(self) -> [u8; 4] { - match self.0 { - NodeRepr::Chunk(c) => c.id, - NodeRepr::Index(..) => self.entry().map_or([0; 4], |e| e.id), - } - } - - /// The pad byte (see [`Chunk::pad`]). - pub fn pad(self) -> Option { - match self.0 { - NodeRepr::Chunk(c) => c.pad, - NodeRepr::Index(..) => self.entry().and_then(|e| e.pad), - } - } - - /// The raw bytes of a data chunk, or the bytes after the list type of an opaque list (see - /// [`Chunk::bytes`]). - pub fn bytes(self) -> Option<&'f [u8]> { - match self.0 { - NodeRepr::Chunk(c) => c.bytes(), - NodeRepr::Index(..) => self.entry().filter(|e| matches!(e.kind, Kind::Data | Kind::OpaqueList)).map(|e| e.data), - } - } - - /// The child chunks of a list or nested chunk; none for data. - pub fn children(self) -> Nodes<'f, 'a> { - match self.0 { - NodeRepr::Chunk(c) => Nodes(NodesRepr::Slice(c.children().iter())), - NodeRepr::Index(tree, at) => { - let end = match tree.entry(at) { - Some(e) if matches!(e.kind, Kind::List | Kind::Nested) => tree.end_of(at), - _ => at.saturating_add(1), - }; - Nodes(NodesRepr::Index { tree, next: at.saturating_add(1), end }) - } - } - } - - /// The list type when this is a `LIST` (parsed or opaque). - pub fn list_type(self) -> Option<[u8; 4]> { - match self.0 { - NodeRepr::Chunk(c) => c.list_type(), - NodeRepr::Index(..) => self.entry().filter(|e| matches!(e.kind, Kind::List | Kind::OpaqueList)).map(|e| e.list_type), - } - } - - /// True when this is a `LIST` of the given type. - pub fn is_list(self, list_type: &[u8; 4]) -> bool { - match self.0 { - NodeRepr::Chunk(c) => c.is_list(list_type), - NodeRepr::Index(..) => self.entry().is_some_and(|e| e.id == LIST && matches!(e.kind, Kind::List | Kind::OpaqueList) && &e.list_type == list_type), - } - } - - /// True when this is a `LIST` whose content could not be read as chunks. - pub fn is_opaque_list(self) -> bool { - match self.0 { - NodeRepr::Chunk(c) => c.is_opaque_list(), - NodeRepr::Index(..) => self.entry().is_some_and(|e| e.kind == Kind::OpaqueList), - } - } - - /// True when this chunk has the given id. - pub fn is(self, id: &[u8; 4]) -> bool { - self.id() == *id - } - - /// The first child chunk with this id. - pub fn child(self, id: &[u8; 4]) -> Option { - self.children().find(|c| c.is(id)) - } - - /// The first child `LIST` of this type. - pub fn child_list(self, list_type: &[u8; 4]) -> Option { - self.children().find(|c| c.is_list(list_type)) - } - - /// Every chunk below this one depth-first (children before later siblings), with the depth - /// counted from 1 for the children of this chunk. - pub fn descendants(self) -> NodeWalk<'f, 'a> { - match self.0 { - NodeRepr::Chunk(c) => NodeWalk(WalkRepr::Chunk(c.descendants())), - NodeRepr::Index(tree, at) => { - let end = match tree.entry(at) { - Some(e) if matches!(e.kind, Kind::List | Kind::Nested) => tree.end_of(at), - _ => at.saturating_add(1), - }; - NodeWalk(WalkRepr::Index { tree, next: at.saturating_add(1), end, open: Vec::new() }) - } - } - } - - /// The first descendant `LIST` of this type, searching depth-first. - pub fn find_list(self, list_type: &[u8; 4]) -> Option { - match self.0 { - NodeRepr::Chunk(c) => c.find_list(list_type).map(Node::from), - // The subtree is a contiguous range in depth-first order: a plain scan. - NodeRepr::Index(tree, at) => { - let first = usize::try_from(at).ok()?.checked_add(1)?; - let end = usize::try_from(tree.end_of(at)).ok()?.min(tree.nodes.len()); - let range = tree.nodes.get(first..end)?; - let i = range.iter().position(|e| e.id == LIST && matches!(e.kind, Kind::List | Kind::OpaqueList) && &e.list_type == list_type)?; - let found = u32::try_from(first.checked_add(i)?).ok()?; - Some(Node(NodeRepr::Index(tree, found))) - } - } - } -} - -/// The children of a [`Node`] (or the top-level chunks of a [`TreeIndex`]), in file order. -#[derive(Clone)] -pub struct Nodes<'f, 'a>(NodesRepr<'f, 'a>); - -#[derive(Clone)] -enum NodesRepr<'f, 'a> { - Slice(std::slice::Iter<'f, Chunk<'a>>), - Index { tree: &'f TreeIndex<'a>, next: u32, end: u32 }, -} - -impl<'f, 'a> Iterator for Nodes<'f, 'a> { - type Item = Node<'f, 'a>; - - /// The next item, `None` at the end of the range. - fn next(&mut self) -> Option { - match &mut self.0 { - NodesRepr::Slice(it) => it.next().map(Node::from), - NodesRepr::Index { tree, next, end } => { - if *next >= *end { - return None; - } - let (tree, at) = (*tree, *next); - tree.entry(at)?; - *next = tree.end_of(at); - Some(Node(NodeRepr::Index(tree, at))) - } - } - } -} - -/// A depth-first walk over [`Node`]s with their depth; see [`Node::descendants`] and -/// [`TreeIndex::walk`]. -pub struct NodeWalk<'f, 'a>(WalkRepr<'f, 'a>); - -enum WalkRepr<'f, 'a> { - Chunk(Walk<'f, 'a>), - /// `open` holds the subtree ends of the entries above the next one (its ancestors inside the - /// walked range); their count is the next entry's depth minus one. - Index { - tree: &'f TreeIndex<'a>, - next: u32, - end: u32, - open: Vec, - }, -} - -impl<'f, 'a> Iterator for NodeWalk<'f, 'a> { - type Item = (usize, Node<'f, 'a>); - - /// The next item, `None` at the end of the range. - fn next(&mut self) -> Option { - match &mut self.0 { - WalkRepr::Chunk(w) => w.next().map(|(d, c)| (d, Node::from(c))), - WalkRepr::Index { tree, next, end, open } => { - if *next >= *end { - return None; - } - let (tree, at) = (*tree, *next); - tree.entry(at)?; - while open.last().is_some_and(|e| *e <= at) { - open.pop(); - } - let depth = open.len().saturating_add(1); - let sub_end = tree.end_of(at); - if sub_end > at.saturating_add(1) { - open.push(sub_end); - } - *next = at.saturating_add(1); - Some((depth, Node(NodeRepr::Index(tree, at)))) - } - } - } -} - -/// The top level of either tree: what the project settings and the version are read from. -#[derive(Clone, Copy)] -pub(crate) enum Root<'f, 'a> { - File(&'f AepFile<'a>), - Index(&'f TreeIndex<'a>), -} - -impl<'f, 'a> From<&'f AepFile<'a>> for Root<'f, 'a> { - /// The handle for this value. - fn from(file: &'f AepFile<'a>) -> Self { - Root::File(file) - } -} - -impl<'f, 'a> From<&'f TreeIndex<'a>> for Root<'f, 'a> { - /// The handle for this value. - fn from(index: &'f TreeIndex<'a>) -> Self { - Root::Index(index) - } -} - -impl<'f, 'a> Root<'f, 'a> { - /// The top-level chunks. - pub(crate) fn chunks(self) -> Nodes<'f, 'a> { - match self { - Root::File(f) => Nodes(NodesRepr::Slice(f.chunks.iter())), - Root::Index(t) => t.chunks(), - } - } - - /// The first top-level chunk with this id. - pub(crate) fn chunk(self, id: &[u8; 4]) -> Option> { - self.chunks().find(|c| c.is(id)) - } - - /// The first top-level `LIST` of this type. - pub(crate) fn list(self, list_type: &[u8; 4]) -> Option> { - self.chunks().find(|c| c.is_list(list_type)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::container::{parse_with_limits, write}; - - /// A tiny deterministic generator (xorshift64*), so the tests need no extra crate. - struct Rng(u64); - - impl Rng { - /// The next pseudo-random number (xorshift64*). - fn next(&mut self) -> u64 { - let mut x = self.0; - x ^= x >> 12; - x ^= x << 25; - x ^= x >> 27; - self.0 = x; - x.wrapping_mul(0x2545_f491_4f6c_dd1d) - } - - /// A number below `n` (0 for `n == 0`). - fn below(&mut self, n: u64) -> u64 { - if n == 0 { 0 } else { self.next() % n } - } - } - - /// A random tree: lists, nested-id chunks holding a `Utf8`, data of odd and even sizes, opaque - /// lists, empty lists, deep chains. - fn tree(rng: &mut Rng, depth: usize, budget: &mut usize) -> Vec> { - let n = rng.below(6); - let mut out = Vec::new(); - for _ in 0..n { - if *budget == 0 { - break; - } - *budget -= 1; - let pick = rng.below(10); - let chunk = if depth < 12 && pick < 4 { - let types: [&[u8; 4]; 4] = [b"Fold", b"tdgp", b"tdbs", b"Layr"]; - let t = *types[usize::try_from(rng.below(4)).expect("small")]; - Chunk::list(t, tree(rng, depth + 1, budget)) - } else if pick == 4 { - let ids: [&[u8; 4]; 3] = [b"tdsn", b"pdnm", b"fnam"]; - let id = *ids[usize::try_from(rng.below(3)).expect("small")]; - let text = vec![b'a'; usize::try_from(rng.below(5)).expect("small")]; - Chunk { id, body: Body::Chunks(vec![Chunk::data(*b"Utf8", text)]), pad: None } - } else if pick == 5 { - let raw = vec![0x5a; usize::try_from(rng.below(9)).expect("small")]; - Chunk { id: LIST, body: Body::OpaqueList { list_type: *b"btdk", data: raw.into() }, pad: None } - } else { - let ids: [&[u8; 4]; 4] = [b"cdat", b"tdmn", b"Utf8", b"idta"]; - let id = *ids[usize::try_from(rng.below(4)).expect("small")]; - Chunk::data(id, vec![u8::try_from(rng.below(256)).expect("byte"); usize::try_from(rng.below(13)).expect("small")]) - }; - out.push(chunk); - } - out - } - - /// Both readers on the same bytes and limits: the same result, errors included; and the - /// index's walk visits the same chunks at the same depths as the tree's. - fn same(bytes: &[u8], limits: Limits) { - let old = parse_with_limits(bytes, limits); - let new = TreeIndex::parse_with_limits(bytes, limits); - match (&old, &new) { - (Ok(file), Ok(index)) => { - assert_eq!(&index.to_file(), file, "the index converts to the parsed tree"); - let a: Vec<(usize, Chunk<'_>)> = file.walk().map(|(d, c)| (d, c.clone())).collect(); - let b: Vec<(usize, Chunk<'_>)> = index.walk().map(|(d, n)| (d, n.to_chunk())).collect(); - assert_eq!(a, b, "the walks agree"); - assert_eq!(index.len(), a.len()); - // Indexing the parsed tree gives the same index. - let again = TreeIndex::from_file(file).expect("index"); - assert_eq!(again.to_file(), *file); - } - (Err(a), Err(b)) => assert_eq!(a, b, "the same error"), - _ => panic!("one reader failed: {:?} vs {:?}", old.as_ref().err(), new.as_ref().err()), - } - } - - /// The default limits and four tight ones (depth 1 and 3, 7 and 40 chunks). - fn limits() -> [Limits; 5] { - [ - Limits::default(), - Limits { max_depth: 1, max_chunks: 10_000_000 }, - Limits { max_depth: 3, max_chunks: 10_000_000 }, - Limits { max_depth: 64, max_chunks: 7 }, - Limits { max_depth: 64, max_chunks: 40 }, - ] - } - - /// The index matches the chunk parser on generated and damaged trees. - #[test] - fn the_index_matches_the_chunk_parser_on_generated_and_damaged_trees() { - let mut rng = Rng(0x9e37_79b9_7f4a_7c15); - for _ in 0..400 { - let mut budget = 120; - let chunks = tree(&mut rng, 0, &mut budget); - let file = AepFile { chunks, trailer: Cow::Borrowed(b"x") }; - let bytes = write(&file).expect("write"); - for l in limits() { - same(&bytes, l); - } - // Damage: overwrite a few bytes past the container header (sizes, ids, list types). - for _ in 0..4 { - let mut bad = bytes.clone(); - for _ in 0..1 + rng.below(3) { - let at = 12 + usize::try_from(rng.below(u64::try_from(bad.len().saturating_sub(12)).expect("len"))).expect("index"); - if let Some(b) = bad.get_mut(at) { - *b = u8::try_from(rng.below(256)).expect("byte"); - } - } - for l in limits() { - same(&bad, l); - } - } - // Truncated inputs (the container size then no longer fits). - let cut = bytes.len().saturating_sub(usize::try_from(rng.below(8)).expect("small") + 1); - same(&bytes[..cut], Limits::default()); - } - } - - /// Header errors are the same. - #[test] - fn header_errors_are_the_same() { - for bytes in [&b""[..], b"RIFX", b"RIFX\0\0\0\x04Egg", b"RIFX\0\0\0\x04Fnord", b"RIFX\0\0\0\x08Egg!", b"RIFX\0\0\0\x03Egg!", b"RIFF\0\0\0\x04Egg!"] { - same(bytes, Limits::default()); - } - } - - /// The typed accessors give the same answers through either tree. - #[test] - fn nodes_answer_alike_on_both_trees() { - let mut rng = Rng(42); - for _ in 0..100 { - let mut budget = 200; - let file = AepFile { chunks: tree(&mut rng, 0, &mut budget), trailer: Cow::Borrowed(&[]) }; - let bytes = write(&file).expect("write"); - let parsed = crate::container::parse(&bytes).expect("parse"); - let index = TreeIndex::parse(&bytes).expect("index"); - let a: Vec> = parsed.walk().map(|(_, c)| Node::from(c)).collect(); - let b: Vec> = index.walk().map(|(_, n)| n).collect(); - assert_eq!(a.len(), b.len()); - for (x, y) in a.iter().zip(&b) { - assert_eq!((x.id(), x.pad(), x.bytes(), x.list_type(), x.is_opaque_list()), (y.id(), y.pad(), y.bytes(), y.list_type(), y.is_opaque_list())); - assert_eq!(x.children().map(Node::to_chunk).collect::>(), y.children().map(Node::to_chunk).collect::>()); - for t in [b"Fold", b"tdgp", b"tdbs", b"Layr", b"btdk"] { - assert_eq!(x.find_list(t).map(Node::to_chunk), y.find_list(t).map(Node::to_chunk)); - assert_eq!(x.child_list(t).map(Node::to_chunk), y.child_list(t).map(Node::to_chunk)); - assert_eq!(x.is_list(t), y.is_list(t)); - } - for id in [b"cdat", b"Utf8", b"tdsn"] { - assert_eq!(x.child(id).map(Node::to_chunk), y.child(id).map(Node::to_chunk)); - } - let dx: Vec<(usize, Chunk<'_>)> = x.descendants().map(|(d, n)| (d, n.to_chunk())).collect(); - let dy: Vec<(usize, Chunk<'_>)> = y.descendants().map(|(d, n)| (d, n.to_chunk())).collect(); - assert_eq!(dx, dy); - assert_eq!(format!("{x:?}"), format!("{y:?}")); - } - } - } - - /// The index never reserves more than the input or the limit allows. - #[test] - fn the_index_never_reserves_more_than_the_input_or_the_limit_allows() { - // 1000 empty headers: the most chunks the bytes can hold. - let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); - data.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); - let declared = u32::try_from(data.len() - 8).expect("small"); - data[4..8].copy_from_slice(&declared.to_be_bytes()); - let index = TreeIndex::parse(&data).expect("index"); - assert_eq!(index.len(), 1000); - // The start (1024 slots) is cut to what the input can hold. - assert!(index.nodes.capacity() <= 1000, "{} slots for at most 1000 headers", index.nodes.capacity()); - // A short tail or a header that runs past the end does not raise the bound. - let mut big = data.clone(); - big[16..20].copy_from_slice(&u32::MAX.to_be_bytes()); - assert!(TreeIndex::parse(&big).is_err() && crate::container::parse(&big).is_err()); - // Under a tighter limit the parse fails as the chunk parser does, and the guess never - // exceeds the limit. - let tight = Limits { max_depth: 64, max_chunks: 10 }; - assert_eq!(TreeIndex::parse_with_limits(&data, tight).err(), Some(AepError::TooManyChunks)); - let small = Limits { max_depth: 64, max_chunks: 1000 }; - let index = TreeIndex::parse_with_limits(&data, small).expect("exactly at the limit"); - assert_eq!(index.len(), 1000); - // A limit below what the input holds bounds the reservation: 100 chunks, never more slots. - let mut wide = b"RIFX\0\0\0\0Egg!".to_vec(); - wide.extend_from_slice(b"LIST"); - wide.extend_from_slice(&u32::try_from(4 + 8 * 99).expect("small").to_be_bytes()); - wide.extend_from_slice(b"Fold"); - wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 99).flatten()); - let declared = u32::try_from(wide.len() - 8).expect("small"); - wide[4..8].copy_from_slice(&declared.to_be_bytes()); - let index = TreeIndex::parse_with_limits(&wide, Limits { max_depth: 64, max_chunks: 100 }).expect("100 chunks"); - assert_eq!(index.len(), 100); - assert!(index.nodes.capacity() <= 100); - // `from_file` is sized exactly. - let file = crate::container::parse(&wide).expect("parse"); - assert_eq!(TreeIndex::from_file(&file).expect("index").nodes.capacity(), 100); - } - - /// A file of `n` data chunks of `size` bytes each. - fn flat(n: usize, size: usize) -> Vec { - let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); - for _ in 0..n { - data.extend_from_slice(b"cdat"); - data.extend_from_slice(&u32::try_from(size).expect("small").to_be_bytes()); - data.extend(std::iter::repeat_n(0u8, size)); - } - let declared = u32::try_from(data.len() - 8).expect("small"); - data[4..8].copy_from_slice(&declared.to_be_bytes()); - data - } - - /// The index grows with the chunk count not the byte size. - #[test] - fn the_index_grows_with_the_chunk_count_not_the_byte_size() { - // 4 MB in 4 chunks: a few slots, not one per 32 bytes (that would be 131 072 slots, 4 MB). - let big = flat(4, 1 << 20); - let index = TreeIndex::parse(&big).expect("index"); - assert_eq!(index.len(), 4); - assert!(index.nodes.capacity() <= INITIAL_SLOTS, "{} slots for 4 chunks", index.nodes.capacity()); - // Many small chunks: at most twice the count (it doubles). - let many = flat(10_000, 2); - let index = TreeIndex::parse(&many).expect("index"); - assert_eq!(index.len(), 10_000); - assert!(index.nodes.capacity() <= 2 * 10_000, "{} slots for 10 000 chunks", index.nodes.capacity()); - same(&big, Limits::default()); - same(&many, Limits::default()); - } - - /// `LIST Fold` around `inner`, followed by 6 bytes too short for a header, so the list's - /// sequence fails and the list is kept opaque. - fn broken_level(inner: &[u8]) -> Vec { - let mut body = b"Fold".to_vec(); - body.extend_from_slice(inner); - body.extend_from_slice(&[0xee; 6]); - let mut out = b"LIST".to_vec(); - out.extend_from_slice(&u32::try_from(body.len()).expect("small").to_be_bytes()); - out.extend_from_slice(&body); - out - } - - /// Failed attempts count once and leave nothing behind. - #[test] - fn failed_attempts_count_once_and_leave_nothing_behind() { - let mut wide = b"Fold".to_vec(); - wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); - let mut level = b"LIST".to_vec(); - level.extend_from_slice(&u32::try_from(wide.len()).expect("small").to_be_bytes()); - level.extend_from_slice(&wide); - for _ in 0..50 { - level = broken_level(&level); - } - let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); - data.extend_from_slice(&level); - let declared = u32::try_from(data.len() - 8).expect("small"); - data[4..8].copy_from_slice(&declared.to_be_bytes()); - let headers = 1 + 50 + 1000; - let index = TreeIndex::parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers }).expect("parse"); - assert_eq!(TreeIndex::parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers - 1 }).err(), Some(AepError::TooManyChunks)); - // Only the outermost list is left, opaque: every failed attempt was rolled back. - assert_eq!(index.len(), 1); - let top = index.chunks().next().expect("one top-level chunk"); - assert!(top.is_opaque_list() && top.bytes().map(<[u8]>::len) == Some(level.len() - 12)); - assert_eq!(write(&index.to_file()).expect("write"), data); - same(&data, Limits::default()); - } - - /// Depth beyond the limit stays opaque without recursion past it. - #[test] - fn depth_beyond_the_limit_stays_opaque_without_recursion_past_it() { - // 5000 nested lists: far deeper than the limit; everything below depth 64 stays bytes. - let mut level = b"LIST\0\0\0\x04tdgp".to_vec(); - for _ in 0..5000 { - let mut out = b"LIST".to_vec(); - out.extend_from_slice(&u32::try_from(level.len() + 4).expect("small").to_be_bytes()); - out.extend_from_slice(b"tdgp"); - out.extend_from_slice(&level); - level = out; - } - let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); - data.extend_from_slice(&level); - let declared = u32::try_from(data.len() - 8).expect("small"); - data[4..8].copy_from_slice(&declared.to_be_bytes()); - let index = TreeIndex::parse(&data).expect("parse"); - assert_eq!(index.len(), 64); - assert_eq!(index.walk().map(|(d, _)| d).max(), Some(64)); - assert!(index.walk().last().is_some_and(|(_, n)| n.is_opaque_list())); - same(&data, Limits::default()); - // Converting and indexing a deep owned tree uses no recursion either. - let file = index.to_file(); - assert_eq!(TreeIndex::from_file(&file).expect("index").len(), 64); - } -} diff --git a/crates/aep/src/container/keys.rs b/crates/aep/src/container/keys.rs deleted file mode 100644 index 06fcaecc5..000000000 --- a/crates/aep/src/container/keys.rs +++ /dev/null @@ -1,322 +0,0 @@ -//! Keyframe records, property flags and expressions. -//! -//! Keyframe times are **layer time**, in units of the property's own time scale -//! ([`Property::time_scale`], equal to the composition's timescale in every sample). -//! -//! Every record starts with an 8-byte header: `i32` time, `u8` at byte 4 = the interpolation of the -//! **incoming** side, `u8` at byte 5 = the **outgoing** side (1 linear, 2 bezier, 3 hold), and a -//! `u16` of flags (label, roving). The rest depends on the property header (`tdb4`), which selects -//! one of two templates for `n` value components: -//! -//! * **plain** (`tdb4` byte 7 = 0; Opacity, Rotation, Scale, 2-D properties, sliders): the value -//! (`n` x `f64`) at byte 8, then four `f64` per component of ease, type-major (`[in speed x n] -//! [in influence x n][out speed x n][out influence x n]`). Size `8 + 40 n`. -//! * **spatial** (`tdb4` byte 7 != 0; Position with `n` = 3, colours with `n` = 4): a `u32` at 8, the -//! arc length (`f64`) at 16, the four ease slots at 24 to 55, the value (`n` x `f64`) at 56, then -//! the spatial in tangent and out tangent (`n` x `f64` each). Size `56 + 24 n`. - -use crate::container::bytes::{be_f64, be_u16, be_u32, text}; -use crate::container::typed::{Keyframe, Property}; - -/// A keyframe interpolation type (a byte of the record header). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Interpolation { - /// `1` - Linear, - /// `2` - Bezier, - /// `3` - Hold, - /// Any other value. - Other(u8), -} - -impl Interpolation { - fn from_byte(b: u8) -> Self { - match b { - 1 => Self::Linear, - 2 => Self::Bezier, - 3 => Self::Hold, - other => Self::Other(other), - } - } -} - -/// What a keyframe record is, judged by the property header (when the list belongs to a property) -/// and the record size. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum KeyframeKind { - /// The plain template: `8 + 40 n` bytes, 48 for one component (Opacity, Rotation, Slider), 88 for - /// two (Mask Feather, Rectangle Size), 128 for three (Scale). - Plain { components: usize }, - /// The spatial template: `56 + 24 n` bytes, 128 for Position (3 components), 152 for a colour (4). - Spatial { components: usize }, - /// 64 bytes: a mask path key; the path itself is in the matching `shap` chunk. The ease sits at - /// byte 24 as in the spatial template (599, 700: speed 0, influences 0.75 / 0.20 / 0.50); the - /// `f64` at byte 16 is 1 or 2 on a first key and 0 on a last one (093, 599, 700; meaning not - /// decoded). - MaskPath, - /// 16 bytes: a marker (time and two hold bytes). - Marker, - /// Any other size. - Other(usize), -} - -/// The ease of a key: speed and influence of the incoming and outgoing side. Speed is in stored -/// value units per second (for Opacity a fraction, so 100 times smaller than the percent shown in -/// the UI; for Position pixels per second); influence is a fraction (20 % is `0.2`). After Effects -/// reports the first key's incoming speed and the last key's outgoing speed as 0, but the file -/// keeps the requested values, so these two slots are not meaningful. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct KeyEase { - pub in_speed: f64, - pub in_influence: f64, - pub out_speed: f64, - pub out_influence: f64, -} - -/// The fields of a spatial keyframe record. -#[derive(Debug, Clone, PartialEq)] -pub struct SpatialKey { - /// The `u32` at byte 8: `1` normally, `0` after the spatial interpolation was changed to - /// non-auto-bezier / non-continuous (the two switches were changed together). - pub auto_bezier_flag: u32, - /// The `f64` at byte 16: the arc length of the segment to the next key, updated lazily by - /// After Effects (0 right after creation). Safe to ignore. - pub segment_length: f64, - /// The four `f64` at bytes 24, 32, 40 and 48 as stored: in speed, in influence, out speed, out - /// influence (see [`KeyEase`]). - pub ease: [f64; 4], - /// The value (x, y, z in pixels for Position; ARGB 0..255 for a colour), from byte 56. - pub value: Vec, - /// The spatial in tangent as an offset from the value. - pub in_tangent: Vec, - /// The spatial out tangent as an offset from the value. - pub out_tangent: Vec, -} - -fn doubles(b: &[u8], at: usize, n: usize) -> Option> { - (0..n).map(|i| be_f64(b, at.checked_add(i.checked_mul(8)?)?)).collect() -} - -fn ease_at(b: &[u8], at: usize) -> Option { - Some(KeyEase { - in_speed: be_f64(b, at)?, - in_influence: be_f64(b, at.checked_add(8)?)?, - out_speed: be_f64(b, at.checked_add(16)?)?, - out_influence: be_f64(b, at.checked_add(24)?)?, - }) -} - -impl<'f> Keyframe<'f> { - /// The record kind. For a list that belongs to a property, the header's component count and - /// template flag decide; without a property, 48 bytes is read as plain with one component and - /// 128 bytes as spatial with three. - pub fn kind(&self) -> KeyframeKind { - let len = self.record.len(); - if let Some(layout) = self.layout { - let n = usize::from(layout.components); - if n > 0 { - if layout.spatial && Some(len) == n.checked_mul(24).and_then(|v| v.checked_add(56)) { - return KeyframeKind::Spatial { components: n }; - } - if !layout.spatial && Some(len) == n.checked_mul(40).and_then(|v| v.checked_add(8)) { - return KeyframeKind::Plain { components: n }; - } - } - } - match (len, self.layout) { - (64, _) => KeyframeKind::MaskPath, - (16, _) => KeyframeKind::Marker, - (48, None) => KeyframeKind::Plain { components: 1 }, - (128, None) => KeyframeKind::Spatial { components: 3 }, - (other, _) => KeyframeKind::Other(other), - } - } - - /// The time in seconds given the property's time scale (units per second). - pub fn seconds(&self, time_scale: u32) -> Option { - if time_scale == 0 { - return None; - } - Some(f64::from(self.time_units()?) / f64::from(time_scale)) - } - - /// The interpolation of the incoming side: the byte at offset 4. - pub fn interpolation_in(&self) -> Option { - self.record.get(4).copied().map(Interpolation::from_byte) - } - - /// The interpolation of the outgoing side: the byte at offset 5. - pub fn interpolation_out(&self) -> Option { - self.record.get(5).copied().map(Interpolation::from_byte) - } - - /// The flags word at byte 6. - pub fn flags(&self) -> Option { - be_u16(self.record, 6) - } - - /// The keyframe label: bits 6 to 9 of the flags (label 9 gives `0x0247` on a spatial key). - pub fn label(&self) -> Option { - u8::try_from((self.flags()? >> 6) & 0x0f).ok() - } - - /// True when the key is roving: bit `0x20` of the flags. - pub fn is_roving(&self) -> Option { - Some(self.flags()? & 0x0020 != 0) - } - - /// The number of value components of a plain or spatial record. - pub fn components(&self) -> Option { - match self.kind() { - KeyframeKind::Plain { components } | KeyframeKind::Spatial { components } => Some(components), - KeyframeKind::MaskPath | KeyframeKind::Marker | KeyframeKind::Other(_) => None, - } - } - - /// The stored value of a plain (from byte 8) or spatial (from byte 56) record, in the units of - /// the property's static value (fractions for Opacity and Scale, ARGB 0..255 for colours). - pub fn value(&self) -> Option> { - match self.kind() { - KeyframeKind::Plain { components } => doubles(self.record, 8, components), - KeyframeKind::Spatial { components } => doubles(self.record, 56, components), - KeyframeKind::MaskPath | KeyframeKind::Marker | KeyframeKind::Other(_) => None, - } - } - - /// The value of a record with one component (Opacity, Rotation, a slider). - pub fn scalar_value(&self) -> Option { - match self.kind() { - KeyframeKind::Plain { components: 1 } => be_f64(self.record, 8), - _ => None, - } - } - - /// The ease of the key: the four slots at byte 16 of a one-component plain record or at byte 24 - /// of a spatial record or a mask path record. For linear and hold keys all four are 0 (a bezier key stores what - /// `setTemporalEase` was given). Plain records with several components keep four slots per - /// component, see [`Keyframe::ease_component`]. - pub fn ease(&self) -> Option { - match self.kind() { - KeyframeKind::Plain { components: 1 } => ease_at(self.record, 16), - KeyframeKind::Spatial { .. } | KeyframeKind::MaskPath => ease_at(self.record, 24), - _ => None, - } - } - - /// The ease of one value component. A plain record with `n` components stores the `4 n` ease - /// doubles **type-major**: `[in speed x n][in influence x n][out speed x n][out influence x n]` - /// starting at byte `8 + 8 n`, and component `i` uses slot `i` of each block (verified for the - /// block layout with Scale `n = 3` and Mask Feather `n = 2` keys whose ease was the same in - /// every dimension; that different values sit in the slots of their dimension is inferred). - /// A spatial record (Position, colours) has one ease entry for all components, so only - /// `component == 0` returns it. For one component this is [`Keyframe::ease`]. - pub fn ease_component(&self, component: usize) -> Option { - match self.kind() { - KeyframeKind::Plain { components } if component < components => { - let block = components.checked_mul(8)?; - let first = block.checked_add(8)?; - let at = |k: usize| first.checked_add(block.checked_mul(k)?)?.checked_add(component.checked_mul(8)?); - Some(KeyEase { - in_speed: be_f64(self.record, at(0)?)?, - in_influence: be_f64(self.record, at(1)?)?, - out_speed: be_f64(self.record, at(2)?)?, - out_influence: be_f64(self.record, at(3)?)?, - }) - } - KeyframeKind::Spatial { .. } if component == 0 => ease_at(self.record, 24), - _ => None, - } - } - - /// The ease of every value component of a plain record, see [`Keyframe::ease_component`] - /// (one entry for a spatial record). - pub fn ease_components(&self) -> Option> { - let n = match self.kind() { - KeyframeKind::Plain { components } => components, - KeyframeKind::Spatial { .. } => 1, - KeyframeKind::MaskPath | KeyframeKind::Marker | KeyframeKind::Other(_) => return None, - }; - (0..n).map(|i| self.ease_component(i)).collect() - } - - /// The decoded spatial record (Position: 128 bytes, colour: 152 bytes). - pub fn spatial(&self) -> Option { - let KeyframeKind::Spatial { components: n } = self.kind() else { return None }; - let r = self.record; - let span = n.checked_mul(8)?; - let ease = ease_at(r, 24)?; - Some(SpatialKey { - auto_bezier_flag: be_u32(r, 8)?, - segment_length: be_f64(r, 16)?, - ease: [ease.in_speed, ease.in_influence, ease.out_speed, ease.out_influence], - value: doubles(r, 56, n)?, - in_tangent: doubles(r, 56usize.checked_add(span)?, n)?, - out_tangent: doubles(r, 56usize.checked_add(span.checked_mul(2)?)?, n)?, - }) - } -} - -/// The bytes of a property header that mark an expression: bytes 76, 77 and 120 of `tdb4` are all 1 -/// when the property has an expression (76 and 77 are also 1 on a camera's auto-computed Position, -/// which has none). Byte 119 is 1 when the expression is disabled. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ExpressionFlags { - pub byte_76: u8, - pub byte_77: u8, - /// 1 when the expression is disabled (`expression.disable_all`); the text stays in the file. - pub byte_119: u8, - pub byte_120: u8, -} - -impl ExpressionFlags { - /// True when byte 119 is 1. - pub fn disabled(&self) -> bool { - self.byte_119 == 1 - } -} - -impl<'f, 'a> Property<'f, 'a> { - /// The time scale (units per second) of this property's keyframe times: the `u32` at byte 12 - /// of `tdb4` (25600 at 25 fps, 30720 at 30 fps, 23976 at 29.97 and 23.976 fps). - pub fn time_scale(&self) -> Option { - be_u32(self.header()?, 12) - } - - /// The property's `tdsb` flags: `1` for a property that was written (non-default), `3` for - /// the default state. - pub fn flags(&self) -> Option { - be_u32(self.chunk.child(b"tdsb")?.bytes()?, 0) - } - - /// The expression source: the raw UTF-8 text of the `Utf8` child that follows the value in the - /// property (no length prefix, no engine tag; the engine is project-wide). - pub fn expression(&self) -> Option { - self.chunk.child(b"Utf8").and_then(|c| c.bytes()).map(text) - } - - /// The expression flag bytes of `tdb4`. - pub fn expression_flags(&self) -> Option { - let h = self.header()?; - Some(ExpressionFlags { byte_76: *h.get(76)?, byte_77: *h.get(77)?, byte_119: *h.get(119)?, byte_120: *h.get(120)? }) - } - - /// Whether the expression is enabled: `None` when the property has no expression (byte 120 is - /// not 1 or there is no `Utf8` text), else `Some(false)` when byte 119 marks it disabled. Byte - /// 119 also changes by itself on built-in view layers after a save, so it only counts together - /// with an expression. - pub fn expression_enabled(&self) -> Option { - let flags = self.expression_flags()?; - if flags.byte_120 != 1 || self.expression().is_none() { - return None; - } - Some(!flags.disabled()) - } - - /// The value of the first keyframe (plain or spatial record), for reading an animated property - /// at its first key. - pub fn first_key_value(&self) -> Option> { - self.keys()?.keyframes().next()?.value() - } -} diff --git a/crates/aep/src/container/masks.rs b/crates/aep/src/container/masks.rs deleted file mode 100644 index 7f00c07eb..000000000 --- a/crates/aep/src/container/masks.rs +++ /dev/null @@ -1,250 +0,0 @@ -//! Masks and bezier paths. -//! -//! A layer's masks are in `tdgp[ADBE Mask Parade]`: one `mkif` chunk (mode and invert switch) next -//! to one `tdgp[ADBE Mask Atom]` per mask. The atom holds the optional properties feather, opacity -//! and expansion (stored only when not at their defaults) and `om-s[ADBE Mask Shape]`: the path -//! property (`tdbs`, with a key list when animated) and `omks` with one `LIST shap` per keyframe (a -//! single one when the path is static). - -use crate::container::bytes::{be_f32, be_u32, until_nul}; -use crate::container::index::Node; -use crate::container::typed::{KeyList, Layer, PropGroup, PropNode, Property}; -use crate::container::values::{Tracked, read}; - -/// The mask mode (`mkif` `u32` at byte 4). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum MaskMode { - /// `0` (329) - None, - /// `1` - Add, - /// `2` - Subtract, - /// `3` - Intersect, - /// `4` - Lighten, - /// `5` - Darken, - /// `6` - Difference, - /// Any other value (not sampled). - Other(u32), -} - -impl MaskMode { - /// The mode for a stored id. - pub fn from_id(id: u32) -> Self { - match id { - 0 => Self::None, - 1 => Self::Add, - 2 => Self::Subtract, - 3 => Self::Intersect, - 4 => Self::Lighten, - 5 => Self::Darken, - 6 => Self::Difference, - other => Self::Other(other), - } - } -} - -/// A vertex of a bezier path with its two control points as absolute positions. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct PathVertex { - pub position: [f64; 2], - /// The control point of the incoming segment. - pub in_handle: [f64; 2], - /// The control point of the outgoing segment. - pub out_handle: [f64; 2], -} - -impl PathVertex { - /// The in tangent: the in handle minus the vertex (what the scripting API calls `inTangents`). - pub fn in_tangent(&self) -> [f64; 2] { - [self.in_handle[0] - self.position[0], self.in_handle[1] - self.position[1]] - } - - /// The out tangent: the out handle minus the vertex (`outTangents`). - pub fn out_tangent(&self) -> [f64; 2] { - [self.out_handle[0] - self.position[0], self.out_handle[1] - self.position[1]] - } -} - -/// One path shape (`LIST shap`): a bounding box and the control points normalised inside it. -/// -/// The `shph` chunk holds a magic word whose last byte carries the flags (`0x01` closed, `0x09` open: -/// bit `0x08`), the box (left, top, right, bottom) as four `f32`, and the byte at offset 20 (`1` in -/// every sample). The box is the box of the vertices **and** their handles. The `list` holds three -/// points per vertex, each as two `f32` in [0, 1] of the box, in the order `[vertex i, out handle i, -/// in handle i + 1]`; the last record is the in handle of vertex 0. For masks the box is normalised -/// to the **layer** size (the size of the layer's source, not the composition's: on a 100x100 solid -/// a 60x40 mask rectangle at the centre has the box `0.2, 0.3, 0.8, 0.7`, 309); for the paths of shape layers it is in pixels. Handles equal their vertex when a -/// vertex has no tangents; a tangent is the handle minus the vertex, without a sign change. -#[derive(Debug, Clone, PartialEq)] -pub struct ShapePath { - /// Left, top, right, bottom. - pub bbox: [f32; 4], - /// The byte at offset 20 of `shph` (`1` in every sample, also for the open path). - pub closed_flag: u8, - /// True for an open path: bit `0x08` of the last byte of the first `shph` word. - pub open: bool, - /// The normalised points as stored, three per vertex. - pub points: Vec<[f32; 2]>, -} - -impl ShapePath { - /// Decodes a `LIST shap` (a [`Chunk`](crate::container::Chunk) or a [`Node`]); `None` when - /// `shph` or the point list is malformed. - pub fn from_chunk<'f, 'a: 'f>(shap: impl Into>) -> Option { - let shap = shap.into(); - let shph = shap.child(b"shph")?.bytes()?; - let bbox = [be_f32(shph, 4)?, be_f32(shph, 8)?, be_f32(shph, 12)?, be_f32(shph, 16)?]; - let closed_flag = *shph.get(20)?; - let open = shph.get(3)? & 0x08 != 0; - let list = KeyList::from_chunk(shap.child_list(b"list")?)?; - if list.header.record_size != 8 { - return None; - } - let points = list.records().map(|r| Some([be_f32(r, 0)?, be_f32(r, 4)?])).collect::>>()?; - Some(Self { bbox, closed_flag, open, points }) - } - - /// The number of vertices (`points / 3`). - pub fn vertex_count(&self) -> usize { - self.points.len() / 3 - } - - /// The vertices with absolute control points: `box.left + u * (box.right - box.left)` (and the - /// same for y), multiplied by `scale` (the layer size in pixels for a mask, `(1, 1)` for a - /// shape layer path). - pub fn vertices(&self, scale: (f64, f64)) -> Vec { - let [left, top, right, bottom] = self.bbox.map(f64::from); - let abs = |p: Option<&[f32; 2]>| -> [f64; 2] { - let [u, v] = p.copied().unwrap_or([0.0, 0.0]).map(f64::from); - [(left + u * (right - left)) * scale.0, (top + v * (bottom - top)) * scale.1] - }; - let n = self.vertex_count(); - let total = n.saturating_mul(3); - (0..n) - .map(|i| { - let base = i.saturating_mul(3); - PathVertex { - position: abs(self.points.get(base)), - out_handle: abs(self.points.get(base.saturating_add(1))), - // The in handle of vertex i is the record before vertex i (the last one for vertex 0). - in_handle: abs(self.points.get(base.saturating_add(total).saturating_sub(1) % total.max(1))), - } - }) - .collect() - } -} - -/// One mask of a layer. -#[derive(Debug, Clone, PartialEq)] -pub struct Mask { - /// The mask name (`Mask 1`). - pub name: Option, - /// The mode, from this mask's `mkif` (there is one `mkif` per mask, directly before its atom). - pub mode: Option, - /// The invert switch (`mkif` byte 0). - pub inverted: Option, - /// The running mask id counter of the layer (`mkif` `u32` at byte 8): 1 for the first mask - /// created on a layer, +1 per mask created later on the same layer (undo does not reset it). - /// A session counter, not a stable id. - pub counter: Option, - /// Feather in pixels `[x, y]`; absent = `[0, 0]`. - pub feather: Tracked<[f64; 2]>, - /// Opacity in percent (stored as a fraction); absent = 100. - pub opacity_percent: Tracked, - /// Expansion in pixels; absent = 0. - pub expansion: Tracked, - /// True when the path has keyframes. - pub path_animated: bool, - /// The path keyframe times in seconds (empty for a static path). - pub path_key_seconds: Vec, - /// The path shapes: one for a static path, one per keyframe otherwise. - pub shapes: Vec, -} - -fn mask_from_atom(atom: &PropGroup<'_, '_>, mkif: Option<&[u8]>) -> Mask { - let opacity = read(atom, "ADBE Mask Opacity", [100.0], 100.0); - let expansion = read(atom, "ADBE Mask Offset", [0.0], 1.0); - let mut mask = Mask { - name: atom.user_name(), - mode: mkif.and_then(|m| be_u32(m, 4)).map(MaskMode::from_id), - inverted: mkif.and_then(|m| m.first()).map(|b| *b != 0), - counter: mkif.and_then(|m| be_u32(m, 8)), - feather: read(atom, "ADBE Mask Feather", [0.0, 0.0], 1.0), - opacity_percent: Tracked { value: opacity.value[0], source: opacity.source }, - expansion: Tracked { value: expansion.value[0], source: expansion.source }, - path_animated: false, - path_key_seconds: Vec::new(), - shapes: Vec::new(), - }; - if let Some(PropNode::Other(oms)) = atom.get("ADBE Mask Shape") { - if let Some(prop) = oms.child_list(b"tdbs").and_then(Property::from_chunk) { - mask.path_animated = prop.is_animated(); - if let (Some(keys), Some(scale)) = (prop.keys(), prop.time_scale()) { - mask.path_key_seconds = keys.keyframes().filter_map(|k| k.seconds(scale)).collect(); - } - } - if let Some(omks) = oms.child_list(b"omks") { - mask.shapes = omks.children().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect(); - } - } - mask -} - -/// One mask with the views of its records, for readers that need more than [`Mask`]: the -/// keyframes and expressions of the mask properties (in [`MaskAtom::atom`]: `ADBE Mask Feather`, -/// `ADBE Mask Opacity`, `ADBE Mask Offset`) and the path keyframes paired with their shapes. -#[derive(Debug, Clone)] -pub struct MaskAtom<'f, 'a> { - /// The decoded mask (as [`Layer::masks`] returns it). - pub mask: Mask, - /// The atom group (`tdgp[ADBE Mask Atom]`). - pub atom: PropGroup<'f, 'a>, - /// The path property (`om-s[ADBE Mask Shape]/tdbs`): its key list holds one 64-byte record - /// per path keyframe (time, interpolation, label and roving flags; 093). - pub path: Option>, - /// Every `LIST shap` of `omks` in file order, `None` where one is malformed, so that index `i` - /// stays the shape of path keyframe `i` (one entry for a static path). - pub path_shapes: Vec>, -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The layer's masks, in stack order. - pub fn masks(&self) -> Vec { - self.mask_atoms().into_iter().map(|m| m.mask).collect() - } - - /// The layer's masks with the views of their records, in stack order. - pub fn mask_atoms(&self) -> Vec> { - let Some(root) = self.properties() else { return Vec::new() }; - let Some(PropNode::Group(parade)) = root.get("ADBE Mask Parade") else { return Vec::new() }; - // Per mask: `tdmn` (Mask Atom), `mkif`, then the atom's `tdgp`. - let mut masks = Vec::new(); - let (mut name, mut mkif): (Option<&[u8]>, Option<&[u8]>) = (None, None); - for c in parade.chunk().children() { - if c.is(b"tdmn") { - name = c.bytes(); - } else if c.is(b"mkif") { - mkif = c.bytes(); - } else if c.is_list(b"tdgp") { - let is_atom = name.take().is_some_and(|n| until_nul(n) == b"ADBE Mask Atom"); - if is_atom && let Some(atom) = PropGroup::from_chunk(c) { - let mask = mask_from_atom(&atom, mkif.take()); - let (mut path, mut path_shapes) = (None, Vec::new()); - if let Some(PropNode::Other(oms)) = atom.get("ADBE Mask Shape") { - path = oms.child_list(b"tdbs").and_then(Property::from_chunk); - if let Some(omks) = oms.child_list(b"omks") { - path_shapes = omks.children().filter(|c| c.is_list(b"shap")).map(ShapePath::from_chunk).collect(); - } - } - masks.push(MaskAtom { mask, atom, path, path_shapes }); - } - } - } - masks - } -} diff --git a/crates/aep/src/container/matte.rs b/crates/aep/src/container/matte.rs deleted file mode 100644 index 09cb76b69..000000000 --- a/crates/aep/src/container/matte.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Track mattes: the matte mode and the matte layer, two fields of the layer header `ldta`. -//! -//! Cases 402-408 (a 960x540 grey solid `M` above the red solid `L`): setting a track matte on a -//! layer changes exactly two fields of that layer's `ldta` (and the video switch of the matte -//! layer, which After Effects turns off by itself): -//! -//! * byte 107 (`u8`; bytes 104..106 are 0 in every file of the corpus): the matte mode, 1 alpha -//! (403), 2 alpha inverted (404), 3 luma (405), 4 luma inverted (406), 0 no matte (every other -//! case); -//! * the `u32` at byte 160: the id of the matte layer (`ldta` byte 0 of that layer), `0x1d` = `M` -//! in 403-406 and 408, `0x1b` = `L` in 407, where the matte layer is BELOW the layer it mattes. -//! 0 in every file without a matte. -//! -//! A matte mode with a matte layer id of 0 (or an `ldta` too short to hold the id) has no case in -//! the corpus: After Effects 2026 writes the id. Before After Effects 23.0 a track matte always -//! used the layer directly above (the documented behaviour of those versions), so such a matte is -//! returned with [`TrackMatte::layer`] `None` and the caller decides. - -use crate::container::Layer; -use crate::container::bytes::be_u32; - -/// The matte mode (`ldta` byte 107). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum MatteMode { - /// `1` (403) - Alpha, - /// `2` (404) - AlphaInverted, - /// `3` (405) - Luma, - /// `4` (406) - LumaInverted, - /// Any other non-zero value (not sampled). - Other(u8), -} - -impl MatteMode { - /// The mode for a stored code; `None` for 0 (no matte). - pub fn from_code(code: u8) -> Option { - Some(match code { - 0 => return None, - 1 => Self::Alpha, - 2 => Self::AlphaInverted, - 3 => Self::Luma, - 4 => Self::LumaInverted, - other => Self::Other(other), - }) - } -} - -/// The track matte of a layer. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct TrackMatte { - pub mode: MatteMode, - /// The id of the matte layer (`u32` at `ldta` byte 160); `None` when it is 0 or the header is - /// too short to hold it (the older "layer above" form, see the module documentation). - pub layer: Option, -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The track matte of the layer, `None` when it has none (or the header is unreadable). - pub fn track_matte(&self) -> Option { - let ldta = self.chunk().child(b"ldta")?.bytes()?; - let mode = MatteMode::from_code(*ldta.get(107)?)?; - let layer = be_u32(ldta, 160).filter(|id| *id != 0); - Some(TrackMatte { mode, layer }) - } -} diff --git a/crates/aep/src/container/read.rs b/crates/aep/src/container/read.rs deleted file mode 100644 index 200b3d84a..000000000 --- a/crates/aep/src/container/read.rs +++ /dev/null @@ -1,278 +0,0 @@ -//! Parsing the `RIFX` container into an [`AepFile`]. - -use std::borrow::Cow; - -use crate::container::bytes::{array, be_u32}; -use crate::container::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; -use crate::container::error::AepError; - -/// Bounds for hostile input. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Limits { - /// Deepest list nesting that is parsed (the top level is depth 1). A list or nested chunk - /// whose children would be deeper is kept opaque instead. - pub max_depth: usize, - /// Most chunks a file may contain (counted across all parse attempts) before parsing fails. - pub max_chunks: usize, -} - -impl Default for Limits { - fn default() -> Self { - Self { max_depth: 64, max_chunks: 10_000_000 } - } -} - -/// Parses an `.aep` with the default [`Limits`]. -/// -/// # Errors -/// Returns an error when the input is not a well-formed `RIFX`/`Egg!` container at the top level. -/// Odd bodies *inside* the container (a `LIST` whose content is not a chunk sequence) do not -/// fail the parse: they are kept opaque. -pub fn parse(data: &[u8]) -> Result, AepError> { - parse_with_limits(data, Limits::default()) -} - -/// Parses an `.aep` with explicit [`Limits`]. -/// -/// # Errors -/// See [`parse`]; also fails with [`AepError::TooManyChunks`]. -pub fn parse_with_limits(data: &[u8], limits: Limits) -> Result, AepError> { - let end = container_end(data)?; - let mut parser = Parser { data, limits, count: 0 }; - let chunks = parser.sequence(12, end, 1)?; - let trailer = data.get(end..).unwrap_or(&[]); - Ok(AepFile { chunks, trailer: Cow::Borrowed(trailer) }) -} - -/// Checks the `RIFX`/`Egg!` header and returns where the container ends (its chunks fill -/// `12..end`; the trailer follows). Shared with [`crate::container::index::TreeIndex::parse`]. -pub(super) fn container_end(data: &[u8]) -> Result { - if id4(data, 0) != Some(*b"RIFX") { - return Err(AepError::NotRifx); - } - let declared = u64::from(be_u32(data, 4).ok_or(AepError::NotRifx)?); - let form = id4(data, 8).ok_or(AepError::NotRifx)?; - if &form != b"Egg!" { - return Err(AepError::BadFormType(form)); - } - let available = (data.len() as u64).saturating_sub(8); - if declared < 4 || declared > available { - return Err(AepError::Truncated { declared, available }); - } - // `declared <= available < data.len()`, so the end is inside the input. - usize::try_from(declared).map_err(|_| AepError::TooLarge)?.checked_add(8).ok_or(AepError::TooLarge) -} - -/// The 4-byte id at `at`, `None` when the input is too short. -pub(super) fn id4(data: &[u8], at: usize) -> Option<[u8; 4]> { - array::<4>(data, at) -} - -struct Parser<'a> { - data: &'a [u8], - limits: Limits, - count: usize, -} - -impl<'a> Parser<'a> { - /// Parses the sibling chunks that exactly fill `start..end`. - fn sequence(&mut self, start: usize, end: usize, depth: usize) -> Result>, AepError> { - // Sized once: a well-formed sequence fills exactly this many slots. `try_reserve` so a - // limit raised past what the target can allocate fails nothing here (the Vec then grows). - let mut out = Vec::new(); - let _ = out.try_reserve_exact(self.capacity_for(start, end)); - let mut pos = start; - while pos < end { - let short = AepError::Malformed { offset: pos, what: "bytes left over that are too short for a chunk header" }; - let body_start = pos.checked_add(8).filter(|b| *b <= end).ok_or(short)?; - let id = id4(self.data, pos).ok_or(AepError::Malformed { offset: pos, what: "short read" })?; - let size = be_u32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize; - let avail = end - body_start; - if size > avail { - return Err(AepError::ChunkTooLarge { offset: pos, size: size as u64, available: avail as u64 }); - } - self.count = self.count.saturating_add(1); - if self.count > self.limits.max_chunks { - return Err(AepError::TooManyChunks); - } - let body_end = body_start + size; - let body = self.body(id, body_start, body_end, depth)?; - let mut next = body_end; - let mut pad = None; - if size % 2 == 1 && next < end { - pad = Some(self.data.get(next).copied().ok_or(AepError::Malformed { offset: next, what: "missing pad byte" })?); - next += 1; - } - out.push(Chunk { id, body, pad }); - pos = next; - } - Ok(out) - } - - /// The slots to reserve for the sequence `start..end`: its header count, bounded by the input - /// (one per 8 bytes at most) and by the chunks the limit still allows. - fn capacity_for(&self, start: usize, end: usize) -> usize { - self.count_siblings(start, end).min(self.limits.max_chunks.saturating_sub(self.count)) - } - - /// The number of chunk headers that tile `start..end` the way [`Self::sequence`] walks them, - /// stopping at the first that does not fit. Never more than `(end - start) / 8`. - fn count_siblings(&self, start: usize, end: usize) -> usize { - let mut n = 0usize; - let mut pos = start; - while let Some(body_start) = pos.checked_add(8).filter(|b| *b <= end) { - let Some(size) = be_u32(self.data, pos.saturating_add(4)) else { break }; - let Some(next) = usize::try_from(size).ok().and_then(|s| body_start.checked_add(s)).filter(|e| *e <= end) else { break }; - n = n.saturating_add(1); - pos = if size % 2 == 1 && next < end { next.saturating_add(1) } else { next }; - } - n - } - - /// Like [`Self::sequence`] but a structural problem yields `None` (the caller keeps bytes). - fn tentative(&mut self, start: usize, end: usize, depth: usize) -> Result>>, AepError> { - match self.sequence(start, end, depth) { - Ok(v) => Ok(Some(v)), - Err(e) if e.is_structural() => Ok(None), - Err(e) => Err(e), - } - } - - fn slice(&self, start: usize, end: usize) -> &'a [u8] { - self.data.get(start..end).unwrap_or(&[]) - } - - fn body(&mut self, id: [u8; 4], start: usize, end: usize, depth: usize) -> Result, AepError> { - let len = end - start; - if id == LIST && len >= 4 { - let list_type = id4(self.data, start).ok_or(AepError::Malformed { offset: start, what: "short read" })?; - let opaque = |p: &Self| Body::OpaqueList { list_type, data: Cow::Borrowed(p.slice(start + 4, end)) }; - if depth >= self.limits.max_depth { - return Ok(opaque(self)); - } - return Ok(match self.tentative(start + 4, end, depth + 1)? { - Some(children) => Body::List { list_type, children }, - None => opaque(self), - }); - } - if NESTED_IDS.contains(&id) - && len >= 8 - && depth < self.limits.max_depth - && let Some(children) = self.tentative(start, end, depth + 1)? - && !children.is_empty() - { - return Ok(Body::Chunks(children)); - } - Ok(Body::Data(Cow::Borrowed(self.slice(start, end)))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Every children `Vec` in the tree, depth first. - fn child_vecs<'f, 'a>(chunks: &'f [Chunk<'a>], out: &mut Vec<&'f Vec>>) { - for c in chunks { - match &c.body { - Body::List { children, .. } | Body::Chunks(children) => { - out.push(children); - child_vecs(children, out); - } - Body::Data(_) | Body::OpaqueList { .. } => {} - } - } - } - - /// Every sibling list is allocated once at its exact length. - #[test] - fn every_sibling_list_is_allocated_once_at_its_exact_length() { - let inner: Vec> = (0..37u8).map(|i| Chunk::data(*b"cdat", vec![i; usize::from(i % 5)])).collect(); - let middle: Vec> = (0..9).map(|_| Chunk::list(*b"tdbs", inner.clone())).collect(); - let file = AepFile { chunks: vec![Chunk::data(*b"head", vec![0; 3]), Chunk::list(*b"Fold", middle)], trailer: Cow::Borrowed(&[]) }; - let bytes = crate::container::write(&file).expect("write"); - let parsed = parse(&bytes).expect("parse"); - assert_eq!(crate::container::write(&parsed).expect("rewrite"), bytes); - let mut vecs = vec![&parsed.chunks]; - child_vecs(&parsed.chunks, &mut vecs); - assert_eq!(vecs.len(), 11); - // `try_reserve_exact` gives exactly the requested capacity with std's allocator today; a - // Vec grown push by push would have rounded up to a power of two (37 -> 64, 9 -> 16). - for v in vecs { - assert_eq!(v.capacity(), v.len(), "a sibling Vec grew past its length"); - } - } - - /// The preallocation is bounded by the input and the chunk limit. - #[test] - fn the_preallocation_is_bounded_by_the_input_and_the_chunk_limit() { - // 1000 empty headers: the most chunks the bytes can hold. - let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); - data.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); - let declared = u32::try_from(data.len() - 8).expect("small"); - data[4..8].copy_from_slice(&declared.to_be_bytes()); - let parser = Parser { data: &data, limits: Limits::default(), count: 0 }; - assert_eq!(parser.count_siblings(12, data.len()), 1000); - assert!(parser.count_siblings(12, data.len()) <= (data.len() - 12) / 8); - // A header whose size runs past the end stops the count; a stray tail is not counted. - assert_eq!(parser.count_siblings(12, data.len() - 3), 999); - let mut big = data.clone(); - big[16..20].copy_from_slice(&u32::MAX.to_be_bytes()); - let parser = Parser { data: &big, limits: Limits::default(), count: 0 }; - assert_eq!(parser.count_siblings(12, big.len()), 0); - let f = parse(&data).expect("parse"); - assert_eq!((f.chunks.len(), f.chunks.capacity()), (1000, 1000)); - // Under a tighter limit the parse fails as before, without sizing for more than allowed. - let tight = Limits { max_depth: 64, max_chunks: 10 }; - assert_eq!(parse_with_limits(&data, tight), Err(AepError::TooManyChunks)); - // The reservation never exceeds what the chunk limit still allows. - let mut parser = Parser { data: &data, limits: tight, count: 0 }; - assert_eq!(parser.capacity_for(12, data.len()), 10); - parser.count = 7; - assert_eq!(parser.capacity_for(12, data.len()), 3); - parser.count = 11; - assert_eq!(parser.capacity_for(12, data.len()), 0); - let parser = Parser { data: &data, limits: Limits::default(), count: 0 }; - assert_eq!(parser.capacity_for(12, data.len()), 1000); - } - - /// `LIST Fold` around `inner`, followed by 6 bytes too short for a header, so the list's - /// sequence fails and the list is kept opaque. - fn broken_level(inner: &[u8]) -> Vec { - let mut body = b"Fold".to_vec(); - body.extend_from_slice(inner); - body.extend_from_slice(&[0xee; 6]); - let mut out = b"LIST".to_vec(); - out.extend_from_slice(&u32::try_from(body.len()).expect("small").to_be_bytes()); - out.extend_from_slice(&body); - out - } - - /// Nested lists with broken tails parse each header once. - #[test] - fn nested_lists_with_broken_tails_parse_each_header_once() { - // A wide, well-formed list at the bottom, then 50 levels that each fail and fall back to - // opaque: every level re-parses its child before giving up. - let mut wide = b"Fold".to_vec(); - wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); - let mut level = b"LIST".to_vec(); - level.extend_from_slice(&u32::try_from(wide.len()).expect("small").to_be_bytes()); - level.extend_from_slice(&wide); - for _ in 0..50 { - level = broken_level(&level); - } - let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); - data.extend_from_slice(&level); - let declared = u32::try_from(data.len() - 8).expect("small"); - data[4..8].copy_from_slice(&declared.to_be_bytes()); - // 1 + 50 + 1000 headers in the file: the parse counts each exactly once (the count spans - // every attempt), so the work stays linear in the input. - let headers = 1 + 50 + 1000; - let f = parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers }).expect("parse"); - assert_eq!(parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers - 1 }), Err(AepError::TooManyChunks)); - // The outermost list keeps its bytes, and the file writes back unchanged. - let [top] = f.chunks.as_slice() else { panic!("one top-level chunk") }; - assert!(matches!(&top.body, Body::OpaqueList { list_type, data } if list_type == b"Fold" && data.len() + 12 == level.len())); - assert_eq!(crate::container::write(&f).expect("write"), data); - } -} diff --git a/crates/aep/src/container/settings.rs b/crates/aep/src/container/settings.rs deleted file mode 100644 index a443df874..000000000 --- a/crates/aep/src/container/settings.rs +++ /dev/null @@ -1,237 +0,0 @@ -//! Project settings (File ▸ Project Settings): colour depth, working space, working gamma, the two -//! linear-light switches, the time display and the frame count start. Cases 620-634: one change -//! each against the base project 620; every field below is the only byte (or chunk) that changes. - -use crate::container::bytes::be_u32; -use crate::container::chunk::AepFile; -use crate::container::footage::json_string; -use crate::container::index::{Node, Root, TreeIndex}; - -/// The time display style (`nhed` byte 8, feet + frames byte 11, film type byte 13). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TimeDisplay { - /// Timecode (the base, 620): byte 8 = 0. - Timecode, - /// Frames (629): byte 8 = 1. - Frames, - /// Feet + frames (633, 634): byte 8 = 1 and byte 11 = 1; byte 13 is the frames per foot, - /// 16 for 35 mm (633) and 40 for 16 mm (634). - FeetFrames { frames_per_foot: u8 }, -} - -/// The working colour space (`cpid` and the JSON `Utf8` after `PwCs`). -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum WorkingSpace { - /// No colour management (623): `cpid` is 16 bytes of `0xff` and the JSON is `{}`. - None, - /// A colour profile, named as After Effects lists it (`baseColorProfile/colorProfileName`): - /// `sRGB IEC61966-2.1` in the base (620), `Rec.709 Gamma 2.4` in 624. The profile data next to - /// the name is kept as stored. - Profile(String), -} - -/// The project settings that are decoded. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ProjectSettings { - /// Bits per channel: 8, 16 or 32 (`nhed` byte 15 = 0 / 1 / 2: 621, 622, 620; the same byte - /// is `nnhd` byte 24). `None` for another value. - pub bits_per_channel: Option, - /// The working space; `None` when the chunks are missing or unreadable. - pub working_space: Option, - /// Working gamma 2.4 (`dwga` `u32` @0 = 1, 625) or 2.2 (0, 620). - pub working_gamma_24: Option, - /// Linearize Working Space: a 1-byte `lnrp` chunk holding 1 exists (626, 632). - pub linearize: bool, - /// Blend Colors Using 1.0 Gamma: a 1-byte `lnrb` chunk holding 1 exists (627, 632). - pub blend_linear: bool, - /// Compensate for Scene-referred Profiles (`acer` = 1 in the base, 0 in 628). - pub scene_compensation: Option, - /// The time display style. - pub time_display: Option, - /// Frame count start: `nhed` byte 14 holds 2 for a count from 0 (620) and 1 for a count from - /// 1 (630); this maps 2 to 0 and 1 to 1, anything else to `None`. - pub frame_start: Option, -} - -impl ProjectSettings { - /// Reads the settings from the top-level chunks. - pub fn read(file: &AepFile<'_>) -> ProjectSettings { - Self::of(Root::from(file)) - } - - /// Reads the settings from the top-level chunks of an indexed file. - pub fn read_index(index: &TreeIndex<'_>) -> ProjectSettings { - Self::of(Root::from(index)) - } - - /// Reads the settings from the top-level chunks of either tree. - pub(crate) fn of(file: Root<'_, '_>) -> ProjectSettings { - let nhed = file.chunk(b"nhed").and_then(Node::bytes); - let byte = |i: usize| nhed.and_then(|b| b.get(i).copied()); - let bits_per_channel = byte(15).and_then(|v| match v { - 0 => Some(8), - 1 => Some(16), - 2 => Some(32), - _ => None, - }); - let time_display = match (byte(8), byte(11), byte(13)) { - (Some(0), _, _) => Some(TimeDisplay::Timecode), - (Some(1), Some(0), _) => Some(TimeDisplay::Frames), - (Some(1), Some(1), Some(fpf)) => Some(TimeDisplay::FeetFrames { frames_per_foot: fpf }), - _ => None, - }; - let frame_start = byte(14).and_then(|v| match v { - 2 => Some(0), - 1 => Some(1), - _ => None, - }); - let flag = |id: &[u8; 4]| file.chunk(id).and_then(Node::bytes).and_then(|b| b.first().copied()) == Some(1); - let working_gamma_24 = file.chunk(b"dwga").and_then(Node::bytes).and_then(|b| b.get(..4)).map(|b| b != [0, 0, 0, 0]); - let scene_compensation = file.chunk(b"acer").and_then(Node::bytes).and_then(|b| b.first().copied()).map(|v| v != 0); - ProjectSettings { - bits_per_channel, - working_space: working_space(file), - working_gamma_24, - linearize: flag(b"lnrp"), - blend_linear: flag(b"lnrb"), - scene_compensation, - time_display, - frame_start, - } - } -} - -/// The working space: the `Utf8` right after `PwCs`. -fn working_space(file: Root<'_, '_>) -> Option { - let mut chunks = file.chunks(); - chunks.find(|c| c.is(b"PwCs"))?; - let json = chunks.next().filter(|c| c.is(b"Utf8"))?.bytes()?; - let trimmed: Vec = json.iter().copied().filter(|b| !b.is_ascii_whitespace() && *b != 0).collect(); - if trimmed == b"{}" { - return Some(WorkingSpace::None); - } - // After Effects 26.2.1 saves the profile data without the name (settings-c, 902): the name is - // then the profile's own description (ICC.1 `desc`). - json_string(json, "colorProfileName") - .or_else(|| json_string(json, "colorProfileData").and_then(|b| base64_decode(&b)).and_then(|icc| icc_description(&icc))) - .map(WorkingSpace::Profile) -} - -/// Standard base64 (RFC 4648) with or without padding; `None` for any other character. -fn base64_decode(text: &str) -> Option> { - let mut out = Vec::with_capacity(text.len() / 4 * 3); - let (mut acc, mut bits) = (0u32, 0u32); - for c in text.bytes().filter(|c| *c != b'=') { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' => 62, - b'/' => 63, - _ => return None, - }; - acc = (acc << 6 | u32::from(v)) & 0x00ff_ffff; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push(((acc >> bits) & 0xff) as u8); - } - } - Some(out) -} - -/// The profile description (ICC.1 tag `desc`): a v2 `desc` (ASCII) or a v4 `mluc` (its first -/// record, UTF-16BE). `None` when the profile or the tag is cut short. -fn icc_description(icc: &[u8]) -> Option { - let be32 = |at: usize| be_u32(icc, at); - let count = be32(128)?; - let tag = (0..count.min(1024)).find_map(|i| { - let at = 132usize.checked_add(usize::try_from(i).ok()?.checked_mul(12)?)?; - (icc.get(at..at.checked_add(4)?)? == b"desc").then_some(at) - })?; - let off = usize::try_from(be32(tag.checked_add(4)?)?).ok()?; - let len = usize::try_from(be32(tag.checked_add(8)?)?).ok()?; - let body = icc.get(off..off.checked_add(len)?)?; - let text = match body.get(..4)? { - b"desc" => { - let n = usize::try_from(be_u32(body, 8)?).ok()?; - let ascii = body.get(12..12usize.checked_add(n)?)?; - String::from_utf8_lossy(ascii.split(|b| *b == 0).next().unwrap_or_default()).into_owned() - } - b"mluc" => { - let n = usize::try_from(be_u32(body, 20)?).ok()?; - let at = usize::try_from(be_u32(body, 24)?).ok()?; - let units: Vec = body.get(at..at.checked_add(n)?)?.as_chunks::<2>().0.iter().map(|p| u16::from_be_bytes(*p)).collect(); - String::from_utf16_lossy(&units) - } - _ => return None, - }; - let text = text.trim_end_matches('\0').trim().to_owned(); - (!text.is_empty()).then_some(text) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn base64_decodes_with_and_without_padding() { - assert_eq!(base64_decode("Zm9vYmFy").as_deref(), Some(&b"foobar"[..])); - assert_eq!(base64_decode("Zm9vYmE=").as_deref(), Some(&b"fooba"[..])); - assert_eq!(base64_decode("Zm9vYg").as_deref(), Some(&b"foob"[..])); - assert_eq!(base64_decode("Zm9v*"), None); - } - - /// A profile with one tag, `desc`, holding `body`. - fn profile(body: &[u8]) -> Vec { - let mut icc = vec![0u8; 128]; - icc.extend_from_slice(&1u32.to_be_bytes()); - icc.extend_from_slice(b"desc"); - icc.extend_from_slice(&144u32.to_be_bytes()); - icc.extend_from_slice(&u32::try_from(body.len()).unwrap().to_be_bytes()); - icc.extend_from_slice(body); - icc - } - - /// A version 2 `desc` body. - fn desc(text: &str) -> Vec { - let mut b = b"desc\0\0\0\0".to_vec(); - b.extend_from_slice(&u32::try_from(text.len() + 1).unwrap().to_be_bytes()); - b.extend_from_slice(text.as_bytes()); - b.push(0); - b - } - - /// A version 4 `mluc` body with one record. - fn mluc(text: &str) -> Vec { - let units: Vec = text.encode_utf16().flat_map(u16::to_be_bytes).collect(); - let mut b = b"mluc\0\0\0\0".to_vec(); - b.extend_from_slice(&1u32.to_be_bytes()); - b.extend_from_slice(&12u32.to_be_bytes()); - b.extend_from_slice(b"enUS"); - b.extend_from_slice(&u32::try_from(units.len()).unwrap().to_be_bytes()); - b.extend_from_slice(&28u32.to_be_bytes()); - b.extend_from_slice(&units); - b - } - - #[test] - fn the_description_of_a_profile_is_read() { - assert_eq!(icc_description(&profile(&desc("Rec.709 Gamma 2.4"))).as_deref(), Some("Rec.709 Gamma 2.4")); - assert_eq!(icc_description(&profile(&mluc("sRGB IEC61966-2.1"))).as_deref(), Some("sRGB IEC61966-2.1")); - assert_eq!(icc_description(&profile(&desc(""))), None); - } - - #[test] - fn a_cut_or_damaged_profile_gives_no_description() { - let icc = profile(&mluc("Rec.709 Gamma 2.4")); - for n in 0..icc.len() { - let mut cut = icc.get(..n).unwrap_or_default().to_vec(); - let _ = icc_description(&cut); - cut.iter_mut().for_each(|b| *b = 0xff); - let _ = icc_description(&cut); - } - assert_eq!(icc_description(&icc[..150]), None); - assert_eq!(icc_description(&[]), None); - } -} diff --git a/crates/aep/src/container/shapes.rs b/crates/aep/src/container/shapes.rs deleted file mode 100644 index dee01bb22..000000000 --- a/crates/aep/src/container/shapes.rs +++ /dev/null @@ -1,264 +0,0 @@ -//! Shape layers: the groups under `ADBE Root Vectors Group` and the items in them. -//! -//! A shape layer (layer type 4) holds `tdgp[ADBE Root Vectors Group]` with one `ADBE Vector Group` -//! per shape group; the group holds `ADBE Vectors Group` (the contents, in z-order) and -//! `ADBE Vector Transform Group` (the group transform, only the properties that differ from the -//! default). Only the items and properties whose layout was verified are decoded; anything else is -//! listed as [`ShapeItem::Other`] with its match name. -//! -//! Colours are stored as ARGB doubles 0..255 and returned as fractions. Sizes, positions and path -//! points are in pixels relative to the layer origin. - -use crate::container::masks::ShapePath; -use crate::container::typed::{Layer, PropGroup, PropNode}; -use crate::container::values::{Tracked, read, read_opt}; - -/// The stroke line cap (`ADBE Vector Stroke Line Cap`, stored as a double; butt is the default and -/// is not stored). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum StrokeCap { - /// `1` - Butt, - /// `2` - Round, - /// Any other value (projecting square was not sampled). - Other(i64), -} - -/// The stroke line join (`ADBE Vector Stroke Line Join`; miter is the default and is not stored). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum StrokeJoin { - /// `1` - Miter, - /// `2` - Round, - /// Any other value (bevel was not sampled). - Other(i64), -} - -/// A stroke item. -#[derive(Debug, Clone, PartialEq)] -pub struct Stroke { - /// The color as `[A, R, G, B]` fractions; `None` while the property is absent (its default is - /// not verified). - pub color: Option>, - /// The width in pixels; `None` while absent. - pub width: Option>, - pub cap: Tracked, - pub join: Tracked, - /// The miter limit; after the join was touched it is stored in its default state (4). - pub miter_limit: Option>, -} - -/// An item of a shape group's contents. -#[derive(Debug, Clone, PartialEq)] -pub enum ShapeItem { - /// `ADBE Vector Shape - Rect`: the rectangle path. - Rect { name: Option, size: Option> }, - /// `ADBE Vector Shape - Group`: a bezier path (one shape per keyframe), points in pixels. - Path { name: Option, paths: Vec }, - /// `ADBE Vector Graphic - Fill`: the color as `[A, R, G, B]` fractions. - Fill { name: Option, color: Option> }, - /// `ADBE Vector Graphic - Stroke` - Stroke { name: Option, stroke: Stroke }, - /// `ADBE Vector Graphic - G-Fill`: the start and end point of the gradient in pixels (the - /// gradient type and the colour stops are not stored while they are at After Effects' default - /// and their encoding is not known). - GradientFill { name: Option, start: Option>, end: Option> }, - /// `ADBE Vector Filter - RC`: rounded corners, the radius in pixels. - RoundCorners { name: Option, radius: Option> }, - /// Any other item (ellipse, polystar, trim, repeater, ...: not ported). - Other { match_name: String, name: Option }, -} - -/// The polystar type (`ADBE Vector Star Type`; star is the default and is not stored). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PolystarType { - /// `1` - Star, - /// `2` - Polygon, - /// Any other value. - Other(i64), -} - -/// The gradient type (`ADBE Vector Grad Type`; linear is the default and is not stored). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum GradientType { - /// `1` - Linear, - /// `2` - Radial, - /// Any other value. - Other(i64), -} - -/// Fields of shape items that [`ShapeItem`] does not carry, in the order of the group's items. -/// `item_index` is the index into [`ShapeGroup::items`]. -#[derive(Debug, Clone, PartialEq)] -pub enum ShapeDetail { - /// `ADBE Vector Shape - Star` (listed as [`ShapeItem::Other`]). The defaults After Effects - /// applies when a property is absent are star, outer radius 100, inner radius 50, so a default - /// star has no property at all (330); a polygon stores the type and writes the inner radius and - /// the inner roundness (`ADBE Vector Star Inner Roundess`, After Effects' own spelling) in their - /// default state (331). - Polystar { - item_index: usize, - star_type: Tracked, - outer_radius: Tracked, - inner_radius: Tracked, - /// `None` unless the roundness is stored. - inner_roundness: Option>, - }, - /// `ADBE Vector Graphic - G-Fill`: the gradient type and, for a radial gradient, the highlight - /// length and angle (written as stored records with value 0 when the type is radial, 332). - Gradient { item_index: usize, gradient_type: Tracked, highlight_length: Option>, highlight_angle: Option> }, - /// The `ADBE Vector Rect Position` of a rectangle path (absent = `[0, 0]`), in pixels (333). - RectPosition { item_index: usize, position: Tracked<[f64; 2]> }, -} - -/// A shape group (`ADBE Vector Group`). -#[derive(Debug, Clone, PartialEq)] -pub struct ShapeGroup { - /// The group's name (`Group 1`). - pub name: Option, - /// The group transform's Position in pixels; absent = `[0, 0]`. - pub position: Tracked<[f64; 2]>, - /// The contents in z-order (top first, as in the file). Two siblings with the same match name - /// (two rectangles) are two items. - pub items: Vec, - /// More fields of the items (polystar, gradient type, rectangle position), see [`ShapeDetail`]. - pub details: Vec, -} - -const COLOR_SCALE: f64 = 1.0 / 255.0; - -fn number(group: &PropGroup<'_, '_>, name: &str) -> Option> { - read_opt::<1>(group, name, 1.0).map(|t| Tracked { value: t.value[0], source: t.source }) -} - -fn paths_of(group: &PropGroup<'_, '_>) -> Vec { - let Some(PropNode::Other(oms)) = group.get("ADBE Vector Shape") else { return Vec::new() }; - let Some(omks) = oms.child_list(b"omks") else { return Vec::new() }; - omks.children().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect() -} - -fn item(match_name: String, group: &PropGroup<'_, '_>) -> ShapeItem { - let name = group.user_name(); - match match_name.as_str() { - "ADBE Vector Shape - Rect" => ShapeItem::Rect { name, size: read_opt::<2>(group, "ADBE Vector Rect Size", 1.0) }, - "ADBE Vector Shape - Group" => ShapeItem::Path { name, paths: paths_of(group) }, - "ADBE Vector Graphic - Fill" => ShapeItem::Fill { name, color: read_opt::<4>(group, "ADBE Vector Fill Color", COLOR_SCALE) }, - "ADBE Vector Graphic - Stroke" => { - let cap = read(group, "ADBE Vector Stroke Line Cap", [1.0], 1.0); - let join = read(group, "ADBE Vector Stroke Line Join", [1.0], 1.0); - let stroke = Stroke { - color: read_opt::<4>(group, "ADBE Vector Stroke Color", COLOR_SCALE), - width: number(group, "ADBE Vector Stroke Width"), - cap: Tracked { - value: match cap.value[0].round() as i64 { - 1 => StrokeCap::Butt, - 2 => StrokeCap::Round, - other => StrokeCap::Other(other), - }, - source: cap.source, - }, - join: Tracked { - value: match join.value[0].round() as i64 { - 1 => StrokeJoin::Miter, - 2 => StrokeJoin::Round, - other => StrokeJoin::Other(other), - }, - source: join.source, - }, - miter_limit: number(group, "ADBE Vector Stroke Miter Limit"), - }; - ShapeItem::Stroke { name, stroke } - } - "ADBE Vector Graphic - G-Fill" => ShapeItem::GradientFill { - name, - start: read_opt::<2>(group, "ADBE Vector Grad Start Pt", 1.0), - end: read_opt::<2>(group, "ADBE Vector Grad End Pt", 1.0), - }, - "ADBE Vector Filter - RC" => ShapeItem::RoundCorners { name, radius: number(group, "ADBE Vector RoundCorner Radius") }, - _ => ShapeItem::Other { match_name, name }, - } -} - -fn detail(match_name: &str, group: &PropGroup<'_, '_>, item_index: usize) -> Option { - let tracked = |name: &str, default: f64| { - let t = read(group, name, [default], 1.0); - Tracked { value: t.value[0], source: t.source } - }; - match match_name { - "ADBE Vector Shape - Star" => { - let star_type = tracked("ADBE Vector Star Type", 1.0); - Some(ShapeDetail::Polystar { - item_index, - star_type: Tracked { - value: match star_type.value.round() as i64 { - 1 => PolystarType::Star, - 2 => PolystarType::Polygon, - other => PolystarType::Other(other), - }, - source: star_type.source, - }, - outer_radius: tracked("ADBE Vector Star Outer Radius", 100.0), - inner_radius: tracked("ADBE Vector Star Inner Radius", 50.0), - inner_roundness: number(group, "ADBE Vector Star Inner Roundess"), - }) - } - "ADBE Vector Graphic - G-Fill" => { - let gradient_type = tracked("ADBE Vector Grad Type", 1.0); - Some(ShapeDetail::Gradient { - item_index, - gradient_type: Tracked { - value: match gradient_type.value.round() as i64 { - 1 => GradientType::Linear, - 2 => GradientType::Radial, - other => GradientType::Other(other), - }, - source: gradient_type.source, - }, - highlight_length: number(group, "ADBE Vector Grad HiLite Length"), - highlight_angle: number(group, "ADBE Vector Grad HiLite Angle"), - }) - } - "ADBE Vector Shape - Rect" => Some(ShapeDetail::RectPosition { item_index, position: read(group, "ADBE Vector Rect Position", [0.0, 0.0], 1.0) }), - _ => None, - } -} - -fn group_of(group: &PropGroup<'_, '_>) -> ShapeGroup { - let (mut items, mut details) = (Vec::new(), Vec::new()); - if let Some(PropNode::Group(contents)) = group.get("ADBE Vectors Group") { - for e in contents.entries() { - if let PropNode::Group(g) = e.node { - details.extend(detail(&e.match_name, &g, items.len())); - items.push(item(e.match_name, &g)); - } - } - } - let position = match group.get("ADBE Vector Transform Group") { - Some(PropNode::Group(t)) => read(&t, "ADBE Vector Position", [0.0, 0.0], 1.0), - _ => Tracked { value: [0.0, 0.0], source: crate::container::values::ValueSource::Default }, - }; - ShapeGroup { name: group.user_name(), position, items, details } -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The shape groups of a shape layer (`ADBE Root Vectors Group`), top group first. - pub fn shape_groups(&self) -> Vec { - let Some(root) = self.properties() else { return Vec::new() }; - let Some(PropNode::Group(vectors)) = root.get("ADBE Root Vectors Group") else { return Vec::new() }; - vectors - .entries() - .into_iter() - .filter(|e| e.match_name == "ADBE Vector Group") - .filter_map(|e| match e.node { - PropNode::Group(g) => Some(group_of(&g)), - PropNode::Property(_) | PropNode::Other(_) => None, - }) - .collect() - } -} diff --git a/crates/aep/src/container/textdoc.rs b/crates/aep/src/container/textdoc.rs deleted file mode 100644 index e673e63cf..000000000 --- a/crates/aep/src/container/textdoc.rs +++ /dev/null @@ -1,1815 +0,0 @@ -//! Text documents (`LIST btdk`) and layer / composition markers. -//! -//! The body of a `btdk` list is not a chunk sequence but a PostScript-like dictionary: `/key -//! value` pairs, `<< >>` dictionaries, `[ ]` arrays, numbers, `true` / `false`, `/names`, and strings -//! as `(` + BOM `fe ff` + UTF-16BE + `)` with `\` escapes. [`parse_text_dict`] reads it (depth -//! limited, never panics) and [`Layer::text_document`] pulls out the verified fields. - -use std::borrow::Cow; -use std::sync::LazyLock; - -use crate::container::bytes::{be_u32, text}; -use crate::container::index::Node; -use crate::container::typed::{Comp, Layer, Property}; - -/// How deep dictionaries and arrays may nest before the parser gives up. -const MAX_DEPTH: usize = 64; - -/// A value of the text dictionary. -#[derive(Debug, Clone, PartialEq)] -pub enum TextValue { - /// `<< ... >>`: keys in file order (a key is the name, string or number written before the value). - Dict(Vec<(String, TextValue)>), - /// `[ ... ]` - Array(Vec), - /// A string that starts with the UTF-16BE byte order mark, decoded. - Str(String), - /// A string without the byte order mark. - Bytes(Vec), - /// `/name` - Name(String), - Int(i64), - Float(f64), - Bool(bool), - /// Any other bare word. - Token(String), -} - -impl TextValue { - /// The value of a dictionary key (the last one when a key repeats). - pub fn get(&self, key: &str) -> Option<&TextValue> { - match self { - Self::Dict(pairs) => pairs.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v), - _ => None, - } - } - - /// An array element. - pub fn at(&self, index: usize) -> Option<&TextValue> { - match self { - Self::Array(items) => items.get(index), - _ => None, - } - } - - /// The text of a string value. - pub fn as_str(&self) -> Option<&str> { - match self { - Self::Str(s) => Some(s), - _ => None, - } - } - - /// An integer or float as `f64`. - pub fn as_f64(&self) -> Option { - match self { - Self::Int(i) => Some(*i as f64), - Self::Float(f) => Some(*f), - _ => None, - } - } - - /// An integer value. - pub fn as_i64(&self) -> Option { - match self { - Self::Int(i) => Some(*i), - _ => None, - } - } -} - -/// The text of a key the way the dictionary stores it: a `/name` as written, any other value in -/// its canonical form (`06` and `+6` are `6`, `1.0` is `1`, a string its decoded text). -fn owned_key(value: &V<'_>) -> String { - match value { - V::Name(s) | V::Token(s) => text(s), - V::Str(utf16) => decode_utf16be(utf16), - V::Int(i) => i.to_string(), - V::Float(f) => f.to_string(), - V::Bool(b) => b.to_string(), - V::Bytes(b) => text(b), - V::Dict(_) | V::Array(_) => String::new(), - } -} - -/// A value of the text dictionary as [`TextDocument::parse`] reads it: it borrows names, bare -/// words and strings from the body, so a document is read without a `String` per token. A key is -/// borrowed when it is a `/name` (every key After Effects writes); its text is the same as the -/// [`TextValue`] key's. [`V::into_owned`] gives the public [`TextValue`]. -#[derive(Debug, Clone)] -enum V<'b> { - Dict(Vec<(Cow<'b, str>, V<'b>)>), - Array(Vec>), - /// A string that started with the byte order mark: the UTF-16BE bytes after it, unescaped. - Str(Cow<'b, [u8]>), - Bytes(Cow<'b, [u8]>), - Name(&'b [u8]), - Int(i64), - Float(f64), - Bool(bool), - Token(&'b [u8]), -} - -impl<'b> V<'b> { - /// The value of a dictionary key (the last one when a key repeats). - fn get(&self, key: &str) -> Option<&V<'b>> { - match self { - Self::Dict(pairs) => pairs.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v), - _ => None, - } - } - - fn at(&self, index: usize) -> Option<&V<'b>> { - match self { - Self::Array(items) => items.get(index), - _ => None, - } - } - - /// The decoded text of a string value. - fn string(&self) -> Option { - match self { - Self::Str(utf16) => Some(decode_utf16be(utf16)), - _ => None, - } - } - - fn as_f64(&self) -> Option { - match self { - Self::Int(i) => Some(*i as f64), - Self::Float(f) => Some(*f), - _ => None, - } - } - - fn as_i64(&self) -> Option { - match self { - Self::Int(i) => Some(*i), - _ => None, - } - } - - /// The key a value makes when it is written in a key position. - fn into_key(self) -> Cow<'b, str> { - match self { - Self::Name(s) => String::from_utf8_lossy(s), - other => Cow::Owned(owned_key(&other)), - } - } - - /// The public form. Recursion is bounded: a parsed value nests at most [`MAX_DEPTH`] + 1 deep. - fn into_owned(self) -> TextValue { - match self { - Self::Dict(pairs) => TextValue::Dict(pairs.into_iter().map(|(k, v)| (k.into_owned(), v.into_owned())).collect()), - Self::Array(items) => TextValue::Array(items.into_iter().map(V::into_owned).collect()), - Self::Str(utf16) => TextValue::Str(decode_utf16be(&utf16)), - Self::Bytes(b) => TextValue::Bytes(b.into_owned()), - Self::Name(s) => TextValue::Name(text(s)), - Self::Int(i) => TextValue::Int(i), - Self::Float(f) => TextValue::Float(f), - Self::Bool(b) => TextValue::Bool(b), - Self::Token(s) => TextValue::Token(text(s)), - } - } -} - -struct Parser<'b> { - b: &'b [u8], - i: usize, - /// The pairs of the dictionaries being read, innermost last: a dictionary's pairs are moved - /// into a vector of their exact size when it closes (one allocation per dictionary instead of - /// one per doubling). - pairs: Vec<(Cow<'b, str>, V<'b>)>, - /// The same for the items of arrays. - items: Vec>, -} - -/// Whitespace between tokens. -fn is_ws(c: u8) -> bool { - matches!(c, b' ' | b'\t' | b'\r' | b'\n') -} - -/// A byte that ends a bare word. -fn is_delimiter(c: u8) -> bool { - is_ws(c) || matches!(c, b'/' | b'[' | b']' | b'<' | b'>' | b'(' | b')') -} - -impl<'b> Parser<'b> { - /// The next byte, `None` at the end. - fn peek(&self) -> Option { - self.b.get(self.i).copied() - } - - /// Moves past whitespace. - fn skip_ws(&mut self) { - while self.peek().is_some_and(is_ws) { - self.i = self.i.saturating_add(1); - } - } - - /// True when the unread bytes start with `s`. - fn starts_with(&self, s: &[u8]) -> bool { - self.b.get(self.i..).is_some_and(|rest| rest.starts_with(s)) - } - - /// The bare word at the position (up to the next delimiter), borrowed from the body. - fn word(&mut self) -> &'b [u8] { - let start = self.i; - while self.peek().is_some_and(|c| !is_delimiter(c)) { - self.i = self.i.saturating_add(1); - } - self.b.get(start..self.i).unwrap_or(&[]) - } - - /// The body of a `( ... )` string after the `(`, with `\` escapes resolved: borrowed when it - /// has none. `None` when the string or an escape is not closed. - fn string_body(&mut self) -> Option> { - let rest = self.b.get(self.i..)?; - let stop = rest.iter().position(|c| matches!(c, b')' | b'\\'))?; - let head = rest.get(..stop)?; - self.i = self.i.saturating_add(stop); - if self.peek()? == b')' { - self.i = self.i.saturating_add(1); - return Some(Cow::Borrowed(head)); - } - let mut out = head.to_vec(); - loop { - let c = self.peek()?; - if c == b'\\' { - out.push(*self.b.get(self.i.saturating_add(1))?); - self.i = self.i.saturating_add(2); - } else if c == b')' { - self.i = self.i.saturating_add(1); - return Some(Cow::Owned(out)); - } else { - out.push(c); - self.i = self.i.saturating_add(1); - } - } - } - - /// The value at the position, `None` when it is malformed or nested deeper than the limit. - fn parse(&mut self, depth: usize) -> Option> { - self.skip_ws(); - if depth > MAX_DEPTH { - return None; - } - if self.starts_with(b"<<") { - self.i = self.i.saturating_add(2); - // On an error the pairs read so far stay on the stack: the error ends the whole parse. - let mark = self.pairs.len(); - loop { - self.skip_ws(); - if self.starts_with(b">>") { - self.i = self.i.saturating_add(2); - return Some(V::Dict(self.pairs.drain(mark..).collect())); - } - let key = self.parse(depth.saturating_add(1))?; - let value = self.parse(depth.saturating_add(1))?; - self.pairs.push((key.into_key(), value)); - } - } - match self.peek()? { - b'[' => { - self.i = self.i.saturating_add(1); - let mark = self.items.len(); - loop { - self.skip_ws(); - if self.peek()? == b']' { - self.i = self.i.saturating_add(1); - return Some(V::Array(self.items.drain(mark..).collect())); - } - let item = self.parse(depth.saturating_add(1))?; - self.items.push(item); - } - } - b'(' => { - self.i = self.i.saturating_add(1); - let body = self.string_body()?; - Some(if body.starts_with(&[0xfe, 0xff]) { - V::Str(match body { - Cow::Borrowed(b) => Cow::Borrowed(b.get(2..).unwrap_or(&[])), - Cow::Owned(mut v) => { - let n = v.len().min(2); - v.drain(..n); - Cow::Owned(v) - } - }) - } else { - V::Bytes(body) - }) - } - b'/' => { - self.i = self.i.saturating_add(1); - Some(V::Name(self.word())) - } - _ => { - let word = self.word(); - if word.is_empty() { - return None; - } - // A word that is not UTF-8 reads as text with replacement characters, which is - // neither a boolean nor a number: a token. - let Ok(w) = std::str::from_utf8(word) else { return Some(V::Token(word)) }; - Some(match w { - "true" => V::Bool(true), - "false" => V::Bool(false), - _ => match w.parse::() { - Ok(i) => V::Int(i), - // `parse` also takes `nan`, `inf` and overflowing exponents; those are not - // numbers a text document holds, so they stay tokens and read as missing. - Err(_) => match w.parse::() { - Ok(f) if f.is_finite() => V::Float(f), - _ => V::Token(word), - }, - }, - }) - } - } - } -} - -/// A big-endian UTF-16 string as text (unpaired surrogates become U+FFFD). -fn decode_utf16be(bytes: &[u8]) -> String { - let (pairs, rest) = bytes.as_chunks::<2>(); - let units = pairs.iter().map(|p| u16::from_be_bytes(*p)); - let mut s: String = char::decode_utf16(units).map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)).collect(); - if !rest.is_empty() { - s.push(char::REPLACEMENT_CHARACTER); - } - s -} - -/// The top-level `key value` pairs of a `btdk` body, borrowed (see [`parse_text_dict`]). -fn parse_dict(body: &[u8]) -> V<'_> { - let mut parser = Parser { b: body, i: 0, pairs: Vec::new(), items: Vec::new() }; - let mut pairs = Vec::new(); - loop { - parser.skip_ws(); - if parser.i >= body.len() { - break; - } - let Some(key) = parser.parse(0) else { break }; - let Some(value) = parser.parse(0) else { break }; - pairs.push((key.into_key(), value)); - } - V::Dict(pairs) -} - -/// Parses the body of a `btdk` list into its top-level `key value` pairs (as a [`TextValue::Dict`]). -/// Parsing stops silently at the first syntax error or at nesting deeper than 64 levels; what was -/// read before is returned. -pub fn parse_text_dict(body: &[u8]) -> TextValue { - parse_dict(body).into_owned() -} - -/// The run style slots (`RUN/6/0[n]/0/0/6/`) that are decoded; every other slot is compared -/// with its default (`STYLE_DEFAULTS`) and listed in -/// [`TextDocument::undecoded_style_fields`] when it differs. -pub const DECODED_STYLE_SLOTS: &[&str] = - &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "11", "12", "13", "18", "35", "36", "52", "53", "54", "56", "57", "58", "62", "63", "70"]; - -/// The paragraph slots (`RUN/5/0[n]/0/0/5/`) that are decoded (see [`ParagraphRun`]). -pub const DECODED_PARAGRAPH_SLOTS: &[&str] = &["0", "1", "2", "3", "4", "5", "8", "9", "21", "29", "33"]; - -/// A number slot. -fn val(v: f64) -> V<'static> { - V::Float(v) -} - -/// A dictionary value with these keys, for the built-in defaults. -fn dict(pairs: Vec<(&'static str, V<'static>)>) -> V<'static> { - V::Dict(pairs.into_iter().map(|(k, v)| (Cow::Borrowed(k), v)).collect()) -} - -/// An array of numbers, for the built-in defaults. -fn numbers(v: &[f64]) -> V<'static> { - V::Array(v.iter().map(|x| val(*x)).collect()) -} - -/// The default of every run style slot that is not decoded and not neutral (zero, `false`, -/// empty, `/nil`): the value an untouched point text holds in every sample (110, 243-245). A slot -/// with a neutral default is left out; [`undecoded_fields`] treats a missing default as neutral. -/// Built once. -static STYLE_DEFAULTS: LazyLock> = LazyLock::new(|| { - let paint = |a: f64| dict(vec![("99", V::Name(b"SimplePaint")), ("0", dict(vec![("0", val(1.0)), ("1", numbers(&[1.0, 1.0, 1.0, a]))]))]); - let class = |name: &'static [u8]| dict(vec![("99", V::Name(name))]); - dict(vec![ - ("37", val(2.0)), - ("41", val(2.0)), - ("43", dict(vec![("0", val(0.5))])), - ("44", val(2.0)), - ("45", val(2.0)), - ("46", val(7.0)), - ("49", val(-1.0)), - ("50", val(-1.0)), - ("55", class(b"SimpleBlender")), - ("64", val(4.0)), - ("71", val(4.0)), - ("77", V::Bool(true)), - ("78", V::Bool(true)), - ("79", paint(0.0)), - ("82", val(3.0)), - ("83", val(3.0)), - ("86", class(b"SimpleCustomFeature")), - ("87", val(100.0)), - ("88", V::Bool(true)), - ("95", dict(vec![("0", val(0.0)), ("1", val(0.0))])), - ("96", V::Bool(true)), - ]) -}); - -/// The same for the paragraph slots (110, 243-245). Built once. -static PARAGRAPH_DEFAULTS: LazyLock> = LazyLock::new(|| { - dict(vec![ - ("6", val(1.0)), - ("7", val(1.2)), - ("10", val(6.0)), - ("11", val(2.0)), - ("12", val(2.0)), - ("14", val(36.0)), - ("15", V::Bool(true)), - ("16", val(0.5)), - ("17", numbers(&[0.8, 1.0, 1.33])), - ("18", numbers(&[0.0, 0.0, 0.0])), - ("19", numbers(&[1.0, 1.0, 1.0])), - ("20", val(6.0)), - ("22", val(1.0)), - ("23", V::Bool(true)), - ("24", val(1.0)), - ("26", V::Bool(true)), - ("31", val(36.0)), - ("35", val(1.0)), - ("40", val(2.0)), - ]) -}); - -/// Equal values; numbers compare by value (`0` equals `0.0`), names and words by their text, -/// strings by their decoded text. -fn same(a: &V<'_>, b: &V<'_>) -> bool { - match (a, b) { - (V::Dict(x), V::Dict(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.iter().any(|(k2, v2)| k == k2 && same(v, v2))), - (V::Array(x), V::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), - (V::Str(x), V::Str(y)) => x == y || decode_utf16be(x) == decode_utf16be(y), - (V::Bytes(x), V::Bytes(y)) => x == y, - (V::Name(x), V::Name(y)) | (V::Token(x), V::Token(y)) => x == y || text(x) == text(y), - (V::Bool(x), V::Bool(y)) => x == y, - _ => match (a.as_f64(), b.as_f64()) { - (Some(p), Some(q)) => p == q, - _ => false, - }, - } -} - -/// A zero, `false`, empty or `/nil` value: a slot that the sampled documents do not have is only -/// listed when it holds something else (a neutral value carries nothing that could be lost). -/// `/nil` is how an untouched document stores a slot without a value (244: paragraph `/27`, `/28`, -/// `/36`). -fn is_neutral(v: &V<'_>) -> bool { - match v { - V::Name(n) => *n == b"nil", - V::Bool(b) => !b, - V::Array(a) => a.is_empty(), - V::Dict(d) => d.is_empty(), - other => other.as_f64() == Some(0.0), - } -} - -/// Paragraph slots whose meaning is not known but whose listed values lay text out alike, so they -/// carry nothing to lose: `/34` is 0 in a scripted text and 7 after Reset Paragraph (727 changes -/// only this slot), and a justified 600 px box text composes the same lines, baselines and bounds -/// with both (S18). `/24` and `/35` are 1 in a scripted text; the wrapping box text 517 with `/24` -/// or `/35` edited to 0 (732, 733) opens without a dialog, keeps the value on a re-save and lays -/// out with the same four lines, baselines and bounds (S21). -pub const NEUTRAL_PARAGRAPH_VALUES: &[(&str, &[i64])] = &[("24", &[0, 1]), ("34", &[0, 7]), ("35", &[0, 1])]; - -/// Style slots of unknown meaning whose listed values lay text out alike: `/68` is 0 in a scripted -/// text; 517 with `/68` edited to 1 (734) keeps it on a re-save and lays out and renders the same -/// (S21). -pub const NEUTRAL_STYLE_VALUES: &[(&str, &[i64])] = &[("68", &[0, 1])]; - -/// The most undecoded slots recorded per text document (style and paragraph each). They are listed -/// in one report line; a crafted dictionary with many thousands of distinct keys must neither make -/// the duplicate check quadratic nor the line unbounded. -pub const MAX_UNDECODED_FIELDS: usize = 64; - -/// Adds to `out` the slots of `actual` that are not decoded and differ from `sampled`, each once -/// and at most [`MAX_UNDECODED_FIELDS`] in all. -fn undecoded_fields(actual: &V<'_>, sampled: Option<&V<'_>>, decoded: &[&str], neutral: &[(&str, &[i64])], out: &mut Vec) { - let V::Dict(pairs) = actual else { return }; - for (key, value) in pairs { - if out.len() >= MAX_UNDECODED_FIELDS { - return; - } - if decoded.contains(&key.as_ref()) || out.iter().any(|o| o == key) { - continue; - } - if neutral.iter().any(|(slot, values)| slot == key && value.as_i64().is_some_and(|v| values.contains(&v))) { - continue; - } - let differs = match sampled.and_then(|s| s.get(key)) { - Some(default) => !same(value, default), - None => !is_neutral(value), - }; - if differs { - out.push(key.to_string()); - } - } -} - -/// The verified fields of a layer's text document. -#[derive(Debug, Clone, PartialEq)] -pub struct TextDocument { - /// The text without the trailing paragraph terminators (`\r`). - pub text: String, - /// The text as stored (a trailing `\r` ends the paragraph). - pub raw_text: String, - /// The font size of the first style run (100 is the default). - pub font_size: f64, - /// The fill colour of the first style run as `[A, R, G, B]` floats 0..1. - pub fill_argb: [f64; 4], - /// The index of the first style run's font in the document's font list. - pub font_index: usize, - /// The font (PostScript name) of the first style run. - pub font: Option, - /// The document's font list, in stored order (an entry whose name is unreadable is empty, so - /// the indices of the style runs stay valid). It always holds entries no run uses - /// (`Myriad-Roman`, `MyriadPro-Regular`, `AdobeInvisFont` in every sample). - pub fonts: Vec, - /// The paragraph runs: one per paragraph, with its length in characters (including the - /// terminating `\r`) and its justification. - pub paragraphs: Vec, - /// The style runs: consecutive characters with one style (a range style splits `Hello` into - /// runs of 1, 2 and 3 characters). - pub style_runs: Vec, - /// The text box of paragraph (box) text; `None` for point text. - pub text_box: Option, - /// Style and paragraph runs that were damaged: a run without a readable length is left out, a - /// run with a missing size, fill or font index takes them from the run before it (the first - /// run from the sampled defaults). - pub incomplete_runs: usize, - /// Style slots that are not decoded and differ from the sampled default (`"68"`, ...), each - /// once and at most [`MAX_UNDECODED_FIELDS`]; empty for every synthetic sample. - pub undecoded_style_fields: Vec, - /// Paragraph slots that are not decoded and differ from the sampled default. - pub undecoded_paragraph_fields: Vec, - /// Manual kerning (`RUN/8/0`, 554): runs of characters with their kerning amount in 1/1000 em; - /// a run without an amount has none. Empty when no character is kerned by hand. - pub kerning: Vec, - /// The line orientation (`/0/8/0[0]/0/2/1`): absent for horizontal text (538), 2 for vertical - /// right to left (575). - pub line_orientation: Option, -} - -/// Characters with one manual kerning amount. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct KernRun { - /// The number of characters. - pub length: usize, - /// The amount in 1/1000 em, `None` when the run is not kerned. - pub amount: Option, -} - -/// The manual kerning list of a text run dictionary (`RUN/8/0`): entries `<< /0 << /0 amount >> /1 -/// length >>` (554 kerns each of `HHHH` by 50; the closing `\r` has an entry without an amount). -fn kern_runs(run: &V<'_>) -> Vec { - let Some(V::Array(items)) = run.get("8").and_then(|v| v.get("0")) else { return Vec::new() }; - let runs: Vec = items - .iter() - .filter_map(|e| { - let length = e.get("1").and_then(usize_of)?; - let amount = e.get("0").and_then(|v| v.get("0")).and_then(V::as_f64).filter(|v| v.is_finite()); - Some(KernRun { length, amount }) - }) - .collect(); - if runs.iter().any(|r| r.amount.is_some_and(|a| a != 0.0)) { runs } else { Vec::new() } -} - -/// The paragraph justification (`RUN/5/0[n]/0/0/5/0`). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Justification { - /// `0` - Left, - /// `1` (334; the scripting enum value 7414 is not what is stored) - Right, - /// `2` - Center, - /// `3`: justified, last line left (565) - FullLeft, - /// `4`: justified, last line right (567) - FullRight, - /// `5`: justified, last line centred (566) - FullCenter, - /// `6`: justified, every line (568) - FullAll, - /// Any other value. - Other(i64), -} - -/// A paragraph run. Besides the justification it carries the paragraph settings found with one -/// change each against 538 (`RUN/5/0[n]/0/0/5/`); a missing slot gives the value of 538. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct ParagraphRun { - /// The number of characters including the `\r` that ends the paragraph. - pub length: usize, - pub justification: Justification, - /// First-line indent in pixels (`/1`, 560: 20). - pub first_line_indent: f64, - /// Start (left) indent in pixels (`/2`, 561: 30). - pub start_indent: f64, - /// End (right) indent in pixels (`/3`, 562: 40). - pub end_indent: f64, - /// Space before in pixels (`/4`, 563: 10). - pub space_before: f64, - /// Space after in pixels (`/5`, 564: 12). - pub space_after: f64, - /// The leading model (`/8`): 0 Roman, 1 Japanese (572). - pub leading_type: i64, - /// Automatic hyphenation (`/9`, on by default; 556 switches it off). - pub auto_hyphenate: bool, - /// Roman hanging punctuation (`/21`, 558). - pub hanging_roman: bool, - /// Every-line composer (`/29`: off by default, the single-line composer; 559 switches it on). - pub every_line_composer: bool, - /// The paragraph direction (`/33`): 0 left to right, 1 right to left (569). - pub direction: i64, -} - -/// The capitalisation of a style run (`RUN/6/0[n]/0/0/6/12`). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Caps { - /// `0` - Normal, - /// `1` - Small, - /// `2` - All, - /// Any other value. - Other(i64), -} - -/// Superscript / subscript of a style run (`RUN/6/0[n]/0/0/6/13`; 526-528: 1 superscript, 0 -/// normal, 2 subscript). After Effects draws superscript and subscript at 58.3 % of the size, 33.3 % -/// of the size above or below the baseline (`text.measure` and the layer bounds of 526-528). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum FontBaseline { - /// `0` - Normal, - /// `1` - Superscript, - /// `2` - Subscript, - /// Any other value. - Other(i64), -} - -/// Automatic kerning of a style run (`RUN/6/0[n]/0/0/6/11`; 542, 543). Manual kerning also stores -/// `0` and keeps the amounts in [`TextDocument::kerning`] (554). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AutoKern { - /// `0` - None, - /// `1`, the default - Metrics, - /// `2` - Optical, - /// Any other value. - Other(i64), -} - -/// A style run. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct StyleRun { - /// The number of characters in the run. - pub length: usize, - pub font_size: f64, - /// The fill colour as `[A, R, G, B]` floats 0..1. - pub fill_argb: [f64; 4], - /// The stroke colour as `[A, R, G, B]` (slot `/6/54`, same layout as the fill; white in every - /// sample). Whether the stroke is drawn and its width are not decoded. - pub stroke_argb: Option<[f64; 4]>, - /// The tracking (`RUN/6/0[n]/0/0/6/8`, 0 by default; 100 in the sample). - pub tracking: f64, - /// Faux bold (slot `/6/2`). Setting it also prepends a font-list entry and moves the style's - /// font index to 1 (335). - pub faux_bold: bool, - /// Faux italic (slot `/6/3`, 336). - pub faux_italic: bool, - /// All caps / small caps (slot `/6/12`; 337, 338). - pub caps: Caps, - /// Automatic leading (slot `/6/4`, 400): when it is set, lines advance by 1.2 x the size and - /// the stored [`StyleRun::leading`] is not used (400 stores 0.01 there). - pub auto_leading: bool, - /// The leading as stored (slot `/6/5`): the baseline-to-baseline distance in pixels when - /// [`StyleRun::auto_leading`] is off (243: the second line sits 98 px below the first; 339: - /// 60). `None` when the slot is missing. - pub leading: Option, - /// The index of the run's font in the document's font list (slot `/6/0`). - pub font_index: usize, - /// Superscript / subscript (slot `/6/13`); normal when the slot is missing. - pub baseline: FontBaseline, - /// Horizontal scale as a factor (slot `/6/6`, 1.0 by default; 539: 0.9). - pub horizontal_scale: f64, - /// Vertical scale as a factor (slot `/6/7`; 540: 1.5). - pub vertical_scale: f64, - /// Baseline shift in pixels (slot `/6/9`; 541: 41). - pub baseline_shift: f64, - /// Automatic kerning (slot `/6/11`). - pub auto_kern: AutoKern, - /// Standard ligatures (slot `/6/18`, off by default; 555). - pub ligatures: bool, - /// The baseline direction of vertical text (slot `/6/35`): 1 with the stream (default), 2 - /// rotated (573), 3 across the stream, tate-chu-yoko (576). - pub baseline_direction: i64, - /// Tsume as a fraction (slot `/6/36`; 553: 0.5). - pub tsume: f64, - /// No break (slot `/6/52`; 552). - pub no_break: bool, - /// Whether the fill is drawn (slot `/6/56`, on by default; 546). - pub apply_fill: bool, - /// Whether the stroke is drawn (slot `/6/57`, off by default; 544). - pub apply_stroke: bool, - /// Stroke over fill (slot `/6/58`, on by default; 550 switches it off). - pub stroke_over_fill: bool, - /// The stroke line join (slot `/6/62`): 0 miter (default), 1 round (548). - pub line_join: i64, - /// The stroke width in pixels (slot `/6/63`, 1.0 by default; 545: 5). - pub stroke_width: f64, - /// The digit set (slot `/6/70`): 0 default, 1 Arabic (571), 2 Hindi (578). - pub digit_set: i64, -} - -impl StyleRun { - /// The style of the sampled untouched document (244), used for a damaged first run. - pub(crate) const SAMPLED: StyleRun = StyleRun { - length: 0, - font_size: 100.0, - fill_argb: [1.0; 4], - stroke_argb: None, - tracking: 0.0, - faux_bold: false, - faux_italic: false, - caps: Caps::Normal, - auto_leading: false, - leading: Some(98.0), - font_index: 0, - // 244 itself is superscript (the character state the corpus was made in, 526); a damaged - // run falls back to the normal baseline. - baseline: FontBaseline::Normal, - horizontal_scale: 1.0, - vertical_scale: 1.0, - baseline_shift: 0.0, - auto_kern: AutoKern::Metrics, - ligatures: false, - baseline_direction: 1, - tsume: 0.0, - no_break: false, - apply_fill: true, - apply_stroke: false, - stroke_over_fill: true, - line_join: 0, - stroke_width: 1.0, - digit_set: 0, - }; -} - -/// The frame of paragraph (box) text: the box in layer space, as traced by the 16 points of the -/// frame path. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct TextBox { - /// The top-left corner. - pub x: f64, - pub y: f64, - pub width: f64, - pub height: f64, -} - -/// The RGBA colour in a style slot (`slot/0/1`), `None` when it is not four numbers. -fn colour_of(style: &V<'_>, slot: &str) -> Option<[f64; 4]> { - let c = style.get(slot)?.get("0")?.get("1")?; - Some([c.at(0)?.as_f64()?, c.at(1)?.as_f64()?, c.at(2)?.as_f64()?, c.at(3)?.as_f64()?]) -} - -/// A non-negative integer value as `usize`. -fn usize_of(v: &V<'_>) -> Option { - usize::try_from(v.as_i64()?).ok() -} - -/// A finite number slot of a style, `default` when it is missing or not a finite number. -fn num(style: &V<'_>, slot: &str, default: f64) -> f64 { - style.get(slot).and_then(V::as_f64).filter(|v| v.is_finite()).unwrap_or(default) -} - -/// A boolean slot of a style, `default` when it is missing or not a boolean. -fn flag(style: &V<'_>, slot: &str, default: bool) -> bool { - match style.get(slot) { - Some(V::Bool(b)) => *b, - _ => default, - } -} - -/// What the run lists of one document collect besides the runs. -#[derive(Default)] -struct RunNotes { - incomplete: usize, - style_fields: Vec, - paragraph_fields: Vec, -} - -/// The paragraph runs of a text run dictionary (`RUN/5/0`). -fn paragraph_runs(run: &V<'_>, notes: &mut RunNotes) -> Vec { - let Some(V::Array(items)) = run.get("5").and_then(|v| v.get("0")) else { return Vec::new() }; - let sampled = Some(&*PARAGRAPH_DEFAULTS); - let mut out: Vec = Vec::with_capacity(items.len()); - for e in items { - let Some(length) = e.get("1").and_then(usize_of) else { - notes.incomplete = notes.incomplete.saturating_add(1); - continue; - }; - let para = e.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("5")); - let justification = match para.and_then(|p| p.get("0")).and_then(V::as_i64) { - Some(0) => Justification::Left, - Some(1) => Justification::Right, - Some(2) => Justification::Center, - Some(3) => Justification::FullLeft, - Some(4) => Justification::FullRight, - Some(5) => Justification::FullCenter, - Some(6) => Justification::FullAll, - Some(other) => Justification::Other(other), - None => { - notes.incomplete = notes.incomplete.saturating_add(1); - out.last().map_or(Justification::Left, |p| p.justification) - } - }; - if let Some(p) = para { - undecoded_fields(p, sampled, DECODED_PARAGRAPH_SLOTS, NEUTRAL_PARAGRAPH_VALUES, &mut notes.paragraph_fields); - } - let num = |slot: &str| para.and_then(|p| p.get(slot)).and_then(V::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0); - let int = |slot: &str, default: i64| para.and_then(|p| p.get(slot)).and_then(V::as_i64).unwrap_or(default); - let flag = |slot: &str, default: bool| match para.and_then(|p| p.get(slot)) { - Some(V::Bool(b)) => *b, - _ => default, - }; - out.push(ParagraphRun { - length, - justification, - first_line_indent: num("1"), - start_indent: num("2"), - end_indent: num("3"), - space_before: num("4"), - space_after: num("5"), - leading_type: int("8", 0), - auto_hyphenate: flag("9", true), - hanging_roman: flag("21", false), - every_line_composer: flag("29", false), - direction: int("33", 0), - }); - } - out -} - -/// The style runs of a text run dictionary (`RUN/6/0`). -fn style_runs(run: &V<'_>, notes: &mut RunNotes) -> Vec { - let Some(V::Array(items)) = run.get("6").and_then(|v| v.get("0")) else { return Vec::new() }; - let sampled = Some(&*STYLE_DEFAULTS); - let mut out: Vec = Vec::with_capacity(items.len()); - for e in items { - let Some(length) = e.get("1").and_then(usize_of) else { - notes.incomplete = notes.incomplete.saturating_add(1); - continue; - }; - let prev = out.last().copied().unwrap_or(StyleRun::SAMPLED); - let Some(style) = e.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("6")) else { - notes.incomplete = notes.incomplete.saturating_add(1); - out.push(StyleRun { length, ..prev }); - continue; - }; - let font_size = style.get("1").and_then(V::as_f64); - let fill_argb = colour_of(style, "53"); - let font_index = style.get("0").and_then(usize_of); - if font_size.is_none() || fill_argb.is_none() || font_index.is_none() { - notes.incomplete = notes.incomplete.saturating_add(1); - } - undecoded_fields(style, sampled, DECODED_STYLE_SLOTS, NEUTRAL_STYLE_VALUES, &mut notes.style_fields); - out.push(StyleRun { - length, - font_size: font_size.unwrap_or(prev.font_size), - fill_argb: fill_argb.unwrap_or(prev.fill_argb), - stroke_argb: colour_of(style, "54"), - tracking: style.get("8").and_then(V::as_f64).unwrap_or(0.0), - faux_bold: matches!(style.get("2"), Some(V::Bool(true))), - faux_italic: matches!(style.get("3"), Some(V::Bool(true))), - caps: match style.get("12").and_then(V::as_i64) { - None | Some(0) => Caps::Normal, - Some(1) => Caps::Small, - Some(2) => Caps::All, - Some(other) => Caps::Other(other), - }, - auto_leading: matches!(style.get("4"), Some(V::Bool(true))), - leading: style.get("5").and_then(V::as_f64), - font_index: font_index.unwrap_or(prev.font_index), - baseline: match style.get("13").and_then(V::as_i64) { - None | Some(0) => FontBaseline::Normal, - Some(1) => FontBaseline::Superscript, - Some(2) => FontBaseline::Subscript, - Some(other) => FontBaseline::Other(other), - }, - horizontal_scale: num(style, "6", 1.0), - vertical_scale: num(style, "7", 1.0), - baseline_shift: num(style, "9", 0.0), - auto_kern: match style.get("11").and_then(V::as_i64) { - Some(0) => AutoKern::None, - None | Some(1) => AutoKern::Metrics, - Some(2) => AutoKern::Optical, - Some(other) => AutoKern::Other(other), - }, - ligatures: flag(style, "18", false), - baseline_direction: style.get("35").and_then(V::as_i64).unwrap_or(1), - tsume: num(style, "36", 0.0), - no_break: flag(style, "52", false), - apply_fill: flag(style, "56", true), - apply_stroke: flag(style, "57", false), - stroke_over_fill: flag(style, "58", true), - line_join: style.get("62").and_then(V::as_i64).unwrap_or(0), - stroke_width: num(style, "63", 1.0), - digit_set: style.get("70").and_then(V::as_i64).unwrap_or(0), - }); - } - out -} - -/// The box of paragraph text from the frame dictionary `/0/8/0[0]/0`: key `/1/0` holds 16 x, y pairs -/// that trace the rectangle, and `/2/0` is 1; both keys are absent for point text. -fn text_box(top: &V<'_>) -> Option { - let frame = top.get("0")?.get("8")?.get("0")?.at(0)?.get("0")?; - if frame.get("2")?.get("0")?.as_i64()? != 1 { - return None; - } - let V::Array(coords) = frame.get("1")?.get("0")? else { return None }; - let numbers: Vec = coords.iter().map(V::as_f64).collect::>()?; - let (pairs, _) = numbers.as_chunks::<2>(); - if pairs.is_empty() { - return None; - } - let min = |f: fn(&[f64; 2]) -> f64| pairs.iter().map(f).fold(f64::INFINITY, f64::min); - let max = |f: fn(&[f64; 2]) -> f64| pairs.iter().map(f).fold(f64::NEG_INFINITY, f64::max); - let (x, y) = (min(|p| p[0]), min(|p| p[1])); - Some(TextBox { x, y, width: max(|p| p[0]) - x, height: max(|p| p[1]) - y }) -} - -impl TextDocument { - /// Decodes the body of a `btdk` list. - pub fn parse(body: &[u8]) -> Option { - let top = parse_dict(body); - let run = top.get("1")?.get("1")?.at(0)?.get("0")?; - let raw_text = run.get("0")?.string()?; - let style = run.get("6")?.get("0")?.at(0)?.get("0")?.get("0")?.get("6")?; - let fill_argb = colour_of(style, "53")?; - let font_index = usize::try_from(style.get("0")?.as_i64()?).ok()?; - let mut fonts = Vec::new(); - if let Some(V::Array(list)) = top.get("0").and_then(|v| v.get("1")).and_then(|v| v.get("0")) { - fonts = list.iter().map(|f| f.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("0")).and_then(V::string).unwrap_or_default()).collect(); - } - let mut notes = RunNotes::default(); - let paragraphs = paragraph_runs(run, &mut notes); - let style_runs = style_runs(run, &mut notes); - Some(Self { - text: raw_text.trim_end_matches('\r').to_string(), - raw_text, - font_size: style.get("1")?.as_f64()?, - fill_argb, - font_index, - font: fonts.get(font_index).filter(|f| !f.is_empty()).cloned(), - fonts, - paragraphs, - style_runs, - text_box: text_box(&top), - incomplete_runs: notes.incomplete, - undecoded_style_fields: notes.style_fields, - undecoded_paragraph_fields: notes.paragraph_fields, - kerning: kern_runs(run), - line_orientation: top - .get("0") - .and_then(|v| v.get("8")) - .and_then(|v| v.get("0")) - .and_then(|v| v.at(0)) - .and_then(|v| v.get("0")) - .and_then(|v| v.get("2")) - .and_then(|v| v.get("1")) - .and_then(V::as_i64), - }) - } - - /// The paragraphs: the stored text split at `\r`, each without its terminator. `A\rB` is stored - /// as `A\rB\r` and gives `["A", "B"]`. - pub fn paragraph_texts(&self) -> Vec<&str> { - self.raw_text.strip_suffix('\r').unwrap_or(&self.raw_text).split('\r').collect() - } - - /// The fill colour as `[R, G, B]`. - pub fn fill_rgb(&self) -> [f64; 3] { - let [_, r, g, b] = self.fill_argb; - [r, g, b] - } - - /// The font (PostScript name) of a style run; `None` when its index is outside the font list or - /// the entry's name is unreadable. - pub fn font_of(&self, run: &StyleRun) -> Option<&str> { - self.fonts.get(run.font_index).map(String::as_str).filter(|f| !f.is_empty()) - } -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The Source Text record `LIST btds` (`ADBE Text Document`). It is a direct child of the - /// `ADBE Text Properties` group, which is a direct child of the layer's root `tdgp` - /// (`Layr/tdgp/tdgp/btds` in every sample, and where the exporter writes it), so only that - /// level is searched rather than the whole layer. - fn source_text_record(&self) -> Option> { - let root = self.chunk.child_list(b"tdgp")?; - root.children().filter(|g| g.is_list(b"tdgp")).find_map(|g| g.child_list(b"btds")) - } - - /// The text document of a text layer: the first `LIST btdk` in the Source Text record `btds` - /// (the same documents [`Layer::text_document_count`] counts). - pub fn text_document(&self) -> Option { - TextDocument::parse(self.source_text_record()?.find_list(b"btdk")?.bytes()?) - } - - /// The Source Text property record: the `tdbs` in `btds[ADBE Text Document]` (a placeholder - /// in every sample: no keys, no expression). Source Text keyframes and expressions were not - /// sampled; a `list` (keys) or an expression in it marks them. - pub fn source_text_property(&self) -> Option> { - Property::from_chunk(self.source_text_record()?.child_list(b"tdbs")?) - } - - /// The number of text documents (`LIST btdk`) in the Source Text record: 1 in every sample; - /// more would be one per Source Text keyframe (not sampled). - pub fn text_document_count(&self) -> usize { - self.source_text_record().map_or(0, |btds| btds.descendants().filter(|(_, c)| c.is_list(b"btdk")).count()) - } -} - -/// A marker with its comment. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct Marker { - /// The time in the property's time units (layer time for layer markers). - pub time_units: i32, - /// The time in seconds. - pub seconds: Option, - /// The comment (the first of the marker's `Utf8` strings). - pub comment: String, - /// The duration in seconds (`NmHd`: the `u32` at byte 8 counts 1/600 s, the `u32` at byte 12 - /// is that 600); 0 for a marker without duration. - pub duration_seconds: Option, - /// The chapter (second string). - pub chapter: String, - /// The URL (third string). - pub url: String, - /// The frame target (fourth string). - pub frame_target: String, - /// The cue point name (fifth string). - pub cue_point_name: String, - /// The label colour index (`NmHd` byte 16; 3 in 347, 0 by default). It is not in the keyframe - /// flags. - pub label: Option, - /// The cue type (`NmHd` `u32` at byte 0). - pub cue_type: Option, - /// The cue point parameters: key and value strings that follow the five fixed strings (the - /// count is the `u32` at byte 4 of `NmHd`). - pub cue_params: Vec<(String, String)>, -} - -/// The cue point type of a marker (`NmHd` `u32` at byte 0). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CueType { - /// `4`: an event cue (also for markers without a cue point name). - Event, - /// `5`: a navigation cue. - Navigation, - /// Any other value. - Other(u32), -} - -impl<'f, 'a> Node<'f, 'a> { - /// The marker list `LIST mrst` of a marker holder: a layer (`LIST Layr`) or a composition's - /// `SecL` list. A layer's `mrst` is a direct child of its root `tdgp` (`ADBE Marker`, where - /// After Effects and the exporter write it), so only that place is looked at; most layers have - /// none, and searching their whole property tree for it was a large part of an import. Any - /// other holder is searched depth-first. - pub(crate) fn marker_list(self) -> Option> { - if self.is_list(b"Layr") { - return self.child_list(b"tdgp")?.child_list(b"mrst"); - } - self.find_list(b"mrst") - } -} - -/// Reads the markers below `holder` (a layer or the composition's `SecL` list): the `mrst` list has a -/// property whose 16-byte records give the times and one `Nmrd` list per marker with the strings. -fn markers_in(holder: Node<'_, '_>) -> Vec { - let Some(mrst) = holder.marker_list() else { return Vec::new() }; - let Some(prop) = mrst.child_list(b"tdbs").and_then(Property::from_chunk) else { return Vec::new() }; - let Some(keys) = prop.keys() else { return Vec::new() }; - let scale = prop.time_scale().unwrap_or(0); - let details = mrst.descendants().map(|(_, c)| c).filter(|c| c.is_list(b"Nmrd")); - keys.keyframes() - .zip(details) - .filter_map(|(k, nmrd)| { - let time_units = k.time_units()?; - // The five strings, in the order comment, chapter, URL, frame target, cue point name. - let mut strings = nmrd.children().filter(|c| c.is(b"Utf8")).map(|c| c.bytes().map(text).unwrap_or_default()); - let mut next = || strings.next().unwrap_or_default(); - let (comment, chapter, url, frame_target, cue_point_name) = (next(), next(), next(), next(), next()); - let extras: Vec = strings.collect(); - let header = nmrd.child(b"NmHd").and_then(Node::bytes); - let duration_seconds = header.and_then(|h| { - let (duration, per_second) = (be_u32(h, 8)?, be_u32(h, 12)?); - (per_second != 0).then(|| f64::from(duration) / f64::from(per_second)) - }); - let pairs = header.and_then(|h| be_u32(h, 4)).and_then(|n| usize::try_from(n).ok()).unwrap_or(0); - let cue_params = extras.as_chunks::<2>().0.iter().take(pairs).map(|[k, v]| (k.clone(), v.clone())).collect(); - let cue_type = header.and_then(|h| be_u32(h, 0)).map(|t| match t { - 4 => CueType::Event, - 5 => CueType::Navigation, - other => CueType::Other(other), - }); - Some(Marker { - time_units, - seconds: k.seconds(scale), - comment, - duration_seconds, - chapter, - url, - frame_target, - cue_point_name, - label: header.and_then(|h| h.get(16).copied()), - cue_type, - cue_params, - }) - }) - .collect() -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The layer's markers (`mrst`), in time order. - pub fn markers(&self) -> Vec { - markers_in(self.chunk) - } -} - -impl<'f, 'a> Comp<'f, 'a> { - /// The composition's markers: they live in the `SecL` list named "Markers". - pub fn markers(&self) -> Vec { - self.item.child_list(b"SecL").map(markers_in).unwrap_or_default() - } -} - -/// The dictionary parser and the defaults as they were before they borrowed from the body (#3276), -/// kept as the reference the differential tests compare with. -#[cfg(test)] -mod oracle { - use super::{MAX_DEPTH, MAX_UNDECODED_FIELDS, TextValue}; - use crate::container::bytes::text; - - pub(super) fn same(a: &TextValue, b: &TextValue) -> bool { - match (a, b) { - (TextValue::Dict(x), TextValue::Dict(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.iter().any(|(k2, v2)| k == k2 && same(v, v2))), - (TextValue::Array(x), TextValue::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), - _ => match (a.as_f64(), b.as_f64()) { - (Some(p), Some(q)) => p == q, - _ => a == b, - }, - } - } - - pub(super) fn is_neutral(v: &TextValue) -> bool { - match v { - TextValue::Name(n) => n == "nil", - TextValue::Bool(b) => !b, - TextValue::Array(a) => a.is_empty(), - TextValue::Dict(d) => d.is_empty(), - other => other.as_f64() == Some(0.0), - } - } - - pub(super) fn undecoded_fields(actual: &TextValue, sampled: Option<&TextValue>, decoded: &[&str], neutral: &[(&str, &[i64])], out: &mut Vec) { - let TextValue::Dict(pairs) = actual else { return }; - for (key, value) in pairs { - if out.len() >= MAX_UNDECODED_FIELDS { - return; - } - if decoded.contains(&key.as_str()) || out.contains(key) { - continue; - } - if neutral.iter().any(|(slot, values)| slot == key && value.as_i64().is_some_and(|v| values.contains(&v))) { - continue; - } - let differs = match sampled.and_then(|s| s.get(key)) { - Some(default) => !same(value, default), - None => !is_neutral(value), - }; - if differs { - out.push(key.clone()); - } - } - } - - impl TextValue { - /// The canonical text of a key, as the owning parser built it. - fn key_text(&self) -> String { - match self { - Self::Name(s) | Self::Str(s) | Self::Token(s) => s.clone(), - Self::Int(i) => i.to_string(), - Self::Float(f) => f.to_string(), - Self::Bool(b) => b.to_string(), - Self::Bytes(b) => text(b), - Self::Dict(_) | Self::Array(_) => String::new(), - } - } - } - - struct Parser<'b> { - b: &'b [u8], - i: usize, - } - - /// Whitespace between tokens. - fn is_ws(c: u8) -> bool { - matches!(c, b' ' | b'\t' | b'\r' | b'\n') - } - - /// A byte that ends a bare word. - fn is_delimiter(c: u8) -> bool { - is_ws(c) || matches!(c, b'/' | b'[' | b']' | b'<' | b'>' | b'(' | b')') - } - - impl Parser<'_> { - /// The next byte, `None` at the end. - fn peek(&self) -> Option { - self.b.get(self.i).copied() - } - - /// Moves past whitespace. - fn skip_ws(&mut self) { - while self.peek().is_some_and(is_ws) { - self.i = self.i.saturating_add(1); - } - } - - /// True when the unread bytes start with `s`. - fn starts_with(&self, s: &[u8]) -> bool { - self.b.get(self.i..).is_some_and(|rest| rest.starts_with(s)) - } - - /// The bare word at the position (up to the next delimiter), borrowed from the body. - fn word(&mut self) -> &[u8] { - let start = self.i; - while self.peek().is_some_and(|c| !is_delimiter(c)) { - self.i = self.i.saturating_add(1); - } - self.b.get(start..self.i).unwrap_or(&[]) - } - - /// The value at the position, `None` when it is malformed or nested deeper than the limit. - fn parse(&mut self, depth: usize) -> Option { - self.skip_ws(); - if depth > MAX_DEPTH { - return None; - } - if self.starts_with(b"<<") { - self.i = self.i.saturating_add(2); - let mut pairs = Vec::new(); - loop { - self.skip_ws(); - if self.starts_with(b">>") { - self.i = self.i.saturating_add(2); - return Some(TextValue::Dict(pairs)); - } - let key = self.parse(depth.saturating_add(1))?; - let value = self.parse(depth.saturating_add(1))?; - pairs.push((key.key_text(), value)); - } - } - match self.peek()? { - b'[' => { - self.i = self.i.saturating_add(1); - let mut items = Vec::new(); - loop { - self.skip_ws(); - if self.peek()? == b']' { - self.i = self.i.saturating_add(1); - return Some(TextValue::Array(items)); - } - items.push(self.parse(depth.saturating_add(1))?); - } - } - b'(' => { - self.i = self.i.saturating_add(1); - let mut out = Vec::new(); - loop { - let c = self.peek()?; - if c == b'\\' { - out.push(*self.b.get(self.i.saturating_add(1))?); - self.i = self.i.saturating_add(2); - } else if c == b')' { - self.i = self.i.saturating_add(1); - break; - } else { - out.push(c); - self.i = self.i.saturating_add(1); - } - } - Some(match out.strip_prefix(&[0xfe, 0xff]) { - Some(utf16) => TextValue::Str(decode_utf16be(utf16)), - None => TextValue::Bytes(out), - }) - } - b'/' => { - self.i = self.i.saturating_add(1); - Some(TextValue::Name(text(self.word()))) - } - _ => { - let word = self.word(); - if word.is_empty() { - return None; - } - let w = text(word); - Some(match w.as_str() { - "true" => TextValue::Bool(true), - "false" => TextValue::Bool(false), - _ => match w.parse::() { - Ok(i) => TextValue::Int(i), - // `parse` also takes `nan`, `inf` and overflowing exponents; those are not - // numbers a text document holds, so they stay tokens and read as missing. - Err(_) => match w.parse::() { - Ok(f) if f.is_finite() => TextValue::Float(f), - _ => TextValue::Token(w), - }, - }, - }) - } - } - } - } - - /// A big-endian UTF-16 string as text (unpaired surrogates become U+FFFD). - fn decode_utf16be(bytes: &[u8]) -> String { - let (pairs, rest) = bytes.as_chunks::<2>(); - let units = pairs.iter().map(|p| u16::from_be_bytes(*p)); - let mut s: String = char::decode_utf16(units).map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)).collect(); - if !rest.is_empty() { - s.push(char::REPLACEMENT_CHARACTER); - } - s - } - - /// Parses the body of a `btdk` list into its top-level `key value` pairs (as a [`TextValue::Dict`]). - /// Parsing stops silently at the first syntax error or at nesting deeper than 64 levels; what was - /// read before is returned. - pub(super) fn parse_text_dict(body: &[u8]) -> TextValue { - let mut parser = Parser { b: body, i: 0 }; - let mut pairs = Vec::new(); - loop { - parser.skip_ws(); - if parser.i >= body.len() { - break; - } - let Some(key) = parser.parse(0) else { break }; - let Some(value) = parser.parse(0) else { break }; - pairs.push((key.key_text(), value)); - } - TextValue::Dict(pairs) - } - - fn val(v: f64) -> TextValue { - TextValue::Float(v) - } - - /// A dictionary value with these keys, for the built-in defaults. - fn dict(pairs: Vec<(&str, TextValue)>) -> TextValue { - TextValue::Dict(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) - } - - /// An array of numbers, for the built-in defaults. - fn numbers(v: &[f64]) -> TextValue { - TextValue::Array(v.iter().map(|x| val(*x)).collect()) - } - - /// The default of every run style slot that is not decoded and not neutral (zero, `false`, - /// empty, `/nil`): the value an untouched point text holds in every sample (110, 243-245). A slot - /// with a neutral default is left out; [`undecoded_fields`] treats a missing default as neutral. - pub(super) fn style_defaults() -> TextValue { - let paint = |a: f64| dict(vec![("99", TextValue::Name("SimplePaint".into())), ("0", dict(vec![("0", val(1.0)), ("1", numbers(&[1.0, 1.0, 1.0, a]))]))]); - let class = |name: &str| dict(vec![("99", TextValue::Name(name.into()))]); - dict(vec![ - ("37", val(2.0)), - ("41", val(2.0)), - ("43", dict(vec![("0", val(0.5))])), - ("44", val(2.0)), - ("45", val(2.0)), - ("46", val(7.0)), - ("49", val(-1.0)), - ("50", val(-1.0)), - ("55", class("SimpleBlender")), - ("64", val(4.0)), - ("71", val(4.0)), - ("77", TextValue::Bool(true)), - ("78", TextValue::Bool(true)), - ("79", paint(0.0)), - ("82", val(3.0)), - ("83", val(3.0)), - ("86", class("SimpleCustomFeature")), - ("87", val(100.0)), - ("88", TextValue::Bool(true)), - ("95", dict(vec![("0", val(0.0)), ("1", val(0.0))])), - ("96", TextValue::Bool(true)), - ]) - } - - /// The same for the paragraph slots (110, 243-245). - pub(super) fn paragraph_defaults() -> TextValue { - dict(vec![ - ("6", val(1.0)), - ("7", val(1.2)), - ("10", val(6.0)), - ("11", val(2.0)), - ("12", val(2.0)), - ("14", val(36.0)), - ("15", TextValue::Bool(true)), - ("16", val(0.5)), - ("17", numbers(&[0.8, 1.0, 1.33])), - ("18", numbers(&[0.0, 0.0, 0.0])), - ("19", numbers(&[1.0, 1.0, 1.0])), - ("20", val(6.0)), - ("22", val(1.0)), - ("23", TextValue::Bool(true)), - ("24", val(1.0)), - ("26", TextValue::Bool(true)), - ("31", val(36.0)), - ("35", val(1.0)), - ("40", val(2.0)), - ]) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::container::Chunk; - - /// A `LIST` of this type holding `kids`. - fn list(t: &[u8; 4], kids: Vec>) -> Chunk<'static> { - Chunk::list(*t, kids) - } - - /// A document with every kind of value, close to what After Effects writes: names, numbers, - /// a UTF-16 string with escapes, a plain string, nested dictionaries and arrays, an undecoded - /// style slot, a font list and a box frame. - const DOC: &[u8] = b"/0 << /1 << /0 [ << /0 << /0 << /0 (\xfe\xff\0M\0y\0r) >> /1 1 >> >> << /0 << /0 << /0 (\xfe\xff\0A\0\\)\0b) >> >> >> ] >> \ - /8 << /0 [ << /0 << /1 << /0 [ 0 0 10 0 10 5 0 5 ] >> /2 << /0 1 /1 2 >> >> >> ] >> >> \ - /1 << /1 [ << /0 << /0 (\xfe\xff\0H\0i\0\r) /5 << /0 [ << /0 << /0 << /5 << /0 2 /9 false /24 0 /34 7 /17 [ .8 1.0 1.33 ] >> >> >> /1 3 >> ] >> \ - /6 << /0 [ << /0 << /0 << /6 << /0 1 /1 36.5 /53 << /0 << /0 1 /1 [ 1 0.5 0 1 ] >> >> /79 << /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 0 ] >> >> /68 1 /90 /x /91 (plain) /92 word >> >> >> /1 3 >> ] >> \ - /8 << /0 [ << /0 << /0 50 >> /1 2 >> << /1 1 >> ] >> >> >> ] >>"; - - /// A deterministic xorshift generator: the tests need varied input, not a dependency. - struct Rng(u64); - - impl Rng { - /// The next pseudo-random number (xorshift). - fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } - - /// A number below `n` (0 for `n == 0`). - fn below(&mut self, n: usize) -> usize { - usize::try_from(self.next() % (n as u64)).unwrap_or(0) - } - } - - /// The borrowing parser reads what the owning one read. - #[test] - fn the_borrowing_parser_reads_what_the_owning_one_read() { - // Every key form the owned keys canonicalise (`06`, `+6`, `-0`, `1.0`, `1e2`, strings, - // booleans, containers), names that are not UTF-8, escapes, unclosed strings and escapes, - // non-finite numbers, and bare words. - let parts: &[&[u8]] = &[ - b"<<", - b">>", - b"[", - b"]", - b"/0", - b"/1", - b"/nil", - b"/SimplePaint", - b"/\xff\xfe", - b"/\xc3\xa9", - b"/", - b"06", - b"+6", - b"-0", - b"1.0", - b"1.50", - b"1e2", - b"-2.5", - b".8", - b"inf", - b"nan", - b"1e999", - b"9223372036854775808", - b"true", - b"false", - b"(abc)", - b"(\xfe\xff\0A\0B)", - b"(\xfe\xff\0A\0)", - b"(a\\)b)", - b"(\\", - b"(\xfe\xff\\)\0)", - b"(\\\xfe\xff\0C)", - b"()", - b"(\xfe\xff)", - b"(unclosed", - b"word", - b"\xc3\x28", - b"\xff", - b" ", - b"\n", - b"\t\r", - b"<", - b">", - b")", - ]; - // A value: mostly well formed, with a random part in its place now and then. - /// Appends one generated value to `out`: mostly well formed, now and then a random part. - fn value(rng: &mut Rng, parts: &[&[u8]], depth: usize, out: &mut Vec) { - let pick = |rng: &mut Rng| parts.get(rng.below(parts.len())).copied().unwrap_or_default(); - match rng.below(if depth > 6 { 5 } else { 10 }) { - 0 => out.extend_from_slice(pick(rng)), - 1..=4 => out.extend_from_slice([&b"/0"[..], b"1", b"(\xfe\xff\0z)", b"0.5", b"/nil"].get(rng.below(5)).copied().unwrap_or_default()), - 5..=7 => { - out.extend_from_slice(b"<< "); - for _ in 0..rng.below(5) { - let key = if rng.below(4) == 0 { pick(rng) } else { [&b"/0"[..], b"/1", b"/6", b"/53"].get(rng.below(4)).copied().unwrap_or_default() }; - out.extend_from_slice(key); - out.push(b' '); - value(rng, parts, depth + 1, out); - out.push(b' '); - } - if rng.below(20) != 0 { - out.extend_from_slice(b">>"); - } - } - _ => { - out.extend_from_slice(b"[ "); - for _ in 0..rng.below(5) { - value(rng, parts, depth + 1, out); - out.push(b' '); - } - if rng.below(20) != 0 { - out.push(b']'); - } - } - } - } - let mut rng = Rng(0x9e37_79b9_7f4a_7c15); - let (mut read, mut nested) = (0, 0); - for case in 0..40_000 { - let mut body = Vec::new(); - if case % 2 == 0 { - for _ in 0..rng.below(60) { - body.extend_from_slice(parts.get(rng.below(parts.len())).copied().unwrap_or_default()); - if rng.below(3) != 0 { - body.push(b' '); - } - } - } else { - for _ in 0..1 + rng.below(4) { - body.extend_from_slice(b"/0 "); - value(&mut rng, parts, 0, &mut body); - body.push(b'\n'); - } - } - let parsed = parse_text_dict(&body); - assert_eq!(parsed, oracle::parse_text_dict(&body), "case {case}: {}", String::from_utf8_lossy(&body)); - let _ = TextDocument::parse(&body); - if let TextValue::Dict(pairs) = &parsed { - read += usize::from(!pairs.is_empty()); - nested += usize::from(pairs.iter().any(|(_, v)| matches!(v, TextValue::Dict(d) if !d.is_empty()))); - } - } - // The input is not all rejected at the first token. - assert!(read > 25_000 && nested > 3_000, "{read} cases read something, {nested} a dictionary"); - // Every cut of a realistic document, and nesting past the limit. - for end in 0..=DOC.len() { - let body = DOC.get(..end).unwrap_or_default(); - assert_eq!(parse_text_dict(body), oracle::parse_text_dict(body), "cut at {end}"); - let _ = TextDocument::parse(body); - } - for depth in [63, 64, 65, 66, 200] { - let body = [b"/k ".to_vec(), b"<< /a ".repeat(depth), b"1".to_vec(), b" >>".repeat(depth), b" /z 2".to_vec()].concat(); - assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "depth {depth}"); - let body = [b"/k ".to_vec(), b"[ ".repeat(depth), b"]".repeat(depth)].concat(); - assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "array depth {depth}"); - } - // Dictionaries and arrays mixed (`<< /a [ << /a [ ...`), closed, and left open exactly - // at the limit. - for depth in 60..=68 { - let open: Vec = (0..depth).flat_map(|i| if i % 2 == 0 { &b"<< /a "[..] } else { &b"[ "[..] }).copied().collect(); - let close: Vec = (0..depth).rev().flat_map(|i| if i % 2 == 0 { &b" >>"[..] } else { &b" ]"[..] }).copied().collect(); - for body in [[b"/k ".to_vec(), open.clone(), b"1".to_vec(), close, b" /z 2".to_vec()].concat(), [b"/k ".to_vec(), open, b"1".to_vec()].concat()] { - assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "mixed depth {depth}"); - let _ = TextDocument::parse(&body); - } - } - } - - /// A realistic document is read in full. - #[test] - fn a_realistic_document_is_read_in_full() { - let doc = TextDocument::parse(DOC).expect("a document"); - assert_eq!((doc.text.as_str(), doc.font_size, doc.fill_argb, doc.font.as_deref()), ("Hi", 36.5, [1.0, 0.5, 0.0, 1.0], Some("A)b"))); - assert_eq!(doc.fonts, ["Myr", "A)b"]); - assert_eq!(doc.paragraphs.first().map(|p| (p.length, p.justification, p.auto_hyphenate)), Some((3, Justification::Center, false))); - // `/68 1` and `/34 7` are neutral; `/90 /x`, `/91 (plain)` and `/92 word` differ from the - // (missing, neutral) default; `/79` equals its default. - assert_eq!(doc.undecoded_style_fields, ["90", "91", "92"]); - assert!(doc.undecoded_paragraph_fields.is_empty()); - assert_eq!(doc.kerning, [KernRun { length: 2, amount: Some(50.0) }, KernRun { length: 1, amount: None }]); - assert_eq!(doc.text_box, Some(TextBox { x: 0.0, y: 0.0, width: 10.0, height: 5.0 })); - assert_eq!(doc.line_orientation, Some(2)); - } - - /// The defaults are the sampled ones and built once. - #[test] - fn the_defaults_are_the_sampled_ones_and_built_once() { - assert_eq!(STYLE_DEFAULTS.clone().into_owned(), oracle::style_defaults()); - assert_eq!(PARAGRAPH_DEFAULTS.clone().into_owned(), oracle::paragraph_defaults()); - assert!(std::ptr::eq(&*STYLE_DEFAULTS, &*STYLE_DEFAULTS)); - } - - /// Names keys and strings are borrowed from the body. - #[test] - fn names_keys_and_strings_are_borrowed_from_the_body() { - let V::Dict(pairs) = parse_dict(b"/a /b /c (\xfe\xff\0x) /d (plain) /e word /f 1.5 /g (\\(esc) 07 1") else { panic!("a dict") }; - // Every `/name` key, name, string without escapes and bare word points into the body. - assert!(pairs.iter().take(6).all(|(k, _)| matches!(k, Cow::Borrowed(_)))); - assert!(matches!(pairs.first().map(|p| &p.1), Some(V::Name(b"b")))); - assert!(matches!(pairs.get(1).map(|p| &p.1), Some(V::Str(Cow::Borrowed(b"\0x"))))); - assert!(matches!(pairs.get(2).map(|p| &p.1), Some(V::Bytes(Cow::Borrowed(b"plain"))))); - assert!(matches!(pairs.get(3).map(|p| &p.1), Some(V::Token(b"word")))); - // An escaped string is copied; a number key is written in its canonical form. - assert!(matches!(pairs.get(5).map(|p| &p.1), Some(V::Bytes(Cow::Owned(b))) if b == b"(esc")); - assert_eq!(pairs.get(6).map(|p| p.0.as_ref()), Some("7")); - // Containers hold what was read. - let V::Dict(outer) = parse_dict(b"/0 << /a 1 /b 2 /c 3 /d 4 /e 5 >> /1 [ 1 2 3 4 5 6 7 8 9 ]") else { panic!("a dict") }; - assert!(matches!(outer.first().map(|p| &p.1), Some(V::Dict(d)) if d.len() == 5 && d.capacity() >= d.len())); - assert!(matches!(outer.get(1).map(|p| &p.1), Some(V::Array(a)) if a.len() == 9 && a.capacity() >= a.len())); - } - - /// Slot checks agree with the owned ones. - #[test] - fn slot_checks_agree_with_the_owned_ones() { - // Slots: defaults, decoded, neutral-listed and unknown ones. Values: each default as - // stored (also as `Int` where it is `2.0`), near misses, neutral values and every kind. - let slots = ["0", "6", "7", "17", "24", "34", "35", "37", "43", "55", "68", "77", "79", "86", "95", "96", "200", "x"]; - let values: &[&[u8]] = &[ - b"2", - b"2.0", - b"7", - b"1", - b"0", - b"-1", - b"0.5", - b"1.2", - b"36", - b"true", - b"false", - b"/nil", - b"/x", - b"/SimpleBlender", - b"[ ]", - b"<< >>", - b"[ .8 1 1.33 ]", - b"[ 0.8 1.0 ]", - b"[ 1 1 1 ]", - b"<< /0 .5 >>", - b"<< /0 0 /1 0 >>", - b"<< /1 0 /0 0 >>", - b"<< /99 /SimpleBlender >>", - b"<< /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 0 ] >> >>", - b"<< /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 1 ] >> >>", - b"(plain)", - b"(\xfe\xff\0a)", - b"word", - b"/\xff", - ]; - let mut rng = Rng(0x2545_f491_4f6c_dd1d); - let mut listed = 0; - for case in 0..20_000 { - let mut body = b"/s << ".to_vec(); - for _ in 0..rng.below(12) { - body.push(b'/'); - body.extend_from_slice(slots.get(rng.below(slots.len())).copied().unwrap_or_default().as_bytes()); - body.push(b' '); - body.extend_from_slice(values.get(rng.below(values.len())).copied().unwrap_or_default()); - body.push(b' '); - } - body.extend_from_slice(b">>"); - let (new, old) = (parse_dict(&body), oracle::parse_text_dict(&body)); - let (Some(new), Some(old)) = (new.get("s"), old.get("s")) else { panic!("case {case}: a dict") }; - for (sampled, old_sampled, decoded, neutral) in [ - (&*STYLE_DEFAULTS, oracle::style_defaults(), DECODED_STYLE_SLOTS, NEUTRAL_STYLE_VALUES), - (&*PARAGRAPH_DEFAULTS, oracle::paragraph_defaults(), DECODED_PARAGRAPH_SLOTS, NEUTRAL_PARAGRAPH_VALUES), - ] { - let (mut a, mut b) = (Vec::new(), Vec::new()); - undecoded_fields(new, Some(sampled), decoded, neutral, &mut a); - oracle::undecoded_fields(old, Some(&old_sampled), decoded, neutral, &mut b); - assert_eq!(a, b, "case {case}: {}", String::from_utf8_lossy(&body)); - listed += a.len(); - } - // Every pair of values compares and reads as neutral alike. - if let (V::Dict(x), TextValue::Dict(y)) = (new, old) { - for ((_, p), (_, q)) in x.iter().zip(y) { - assert_eq!(is_neutral(p), oracle::is_neutral(q), "case {case}"); - for ((_, r), (_, t)) in x.iter().zip(y) { - assert_eq!(same(p, r), oracle::same(q, t), "case {case}"); - } - } - } - } - assert!(listed > 10_000, "{listed} slots listed"); - } - - /// Values compare by their text. - #[test] - fn values_compare_by_their_text() { - // Two names that are not UTF-8 read as the same text with replacement characters, as the - // owned values did. - assert!(same(&V::Name(b"\xff"), &V::Name(b"\xfe"))); - assert!(!same(&V::Name(b"a"), &V::Name(b"b"))); - assert!(same(&V::Str(Cow::Borrowed(b"\xd8\x00")), &V::Str(Cow::Owned(b"\xd8\x01".to_vec())))); - assert!(same(&V::Int(0), &V::Float(0.0)) && !same(&V::Int(0), &V::Bool(false)) && !same(&V::Name(b"x"), &V::Token(b"x"))); - assert!(is_neutral(&V::Name(b"nil")) && !is_neutral(&V::Token(b"nil")) && is_neutral(&V::Float(0.0)) && !is_neutral(&V::Str(Cow::Borrowed(b"")))); - } - - /// A layers marker list is the one in its root group. - #[test] - fn a_layers_marker_list_is_the_one_in_its_root_group() { - let marked = |tag: u8| list(b"mrst", vec![Chunk::data(*b"test", vec![tag])]); - // The stored place: `Layr/tdgp/mrst`. - let layer = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![]), marked(1)])]); - assert_eq!(Node::from(&layer).marker_list().and_then(|m| m.child(b"test")).and_then(Node::bytes), Some(&[1u8][..])); - // A list deeper in the layer is not the layer's marker list (the old depth-first search - // found it); a layer without a marker list in its root group has no markers. - let deep = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![marked(2)])])]); - assert!(Node::from(&deep).marker_list().is_none()); - assert!(Layer { chunk: Node::from(&deep) }.markers().is_empty()); - // Any other holder (a composition's `SecL`) is still searched depth-first. - let secl = list(b"SecL", vec![list(b"tdgp", vec![list(b"tdgp", vec![marked(3)])])]); - assert_eq!(Node::from(&secl).marker_list().and_then(|m| m.child(b"test")).and_then(Node::bytes), Some(&[3u8][..])); - } - - /// The source text record is found in the text group. - #[test] - fn the_source_text_record_is_found_in_the_text_group() { - let doc = b"/1 << /1 [ << /0 << /0 (\xfe\xff\0H\0\r) /6 << /0 [ << /0 << /0 << /6 << /0 0 /1 50 /53 << /0 << /1 [ 1 1 0 0 ] >> >> >> >> >> /1 2 >> ] >> >> >> ] >>"; - // `btdk` is an opaque list (its body is not a chunk sequence), as the reader makes it. - let btdk = || Chunk { id: *b"LIST", body: crate::container::Body::OpaqueList { list_type: *b"btdk", data: doc.to_vec().into() }, pad: None }; - let btds_real = |n: usize| list(b"btds", std::iter::once(list(b"tdbs", vec![])).chain((0..n).map(|_| btdk())).collect()); - let layer = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![]), list(b"tdgp", vec![btds_real(2)])])]); - let view = Layer { chunk: Node::from(&layer) }; - assert_eq!(view.text_document().map(|d| d.text), Some("H".to_string())); - assert!(view.source_text_property().is_some()); - assert_eq!(view.text_document_count(), 2); - // A record anywhere else in the layer is not its Source Text. - let elsewhere = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![list(b"tdgp", vec![btds_real(1)])])])]); - let view = Layer { chunk: Node::from(&elsewhere) }; - assert!(view.text_document().is_none() && view.source_text_property().is_none()); - assert_eq!(view.text_document_count(), 0); - } - - #[test] - fn non_finite_numbers_are_not_numbers() { - let TextValue::Dict(pairs) = parse_text_dict(b"/1 inf /2 nan /3 1e999 /4 -inf /5 2.5 /6 7") else { panic!("a dict") }; - let numbers: Vec> = pairs.iter().map(|(_, v)| v.as_f64()).collect(); - assert_eq!(numbers, [None, None, None, None, Some(2.5), Some(7.0)]); - } - - #[test] - fn undecoded_fields_are_capped_and_linear() { - // 300 000 distinct undecoded slots that differ from a sampled default: before, each was - // checked against every slot recorded so far (4.5e10 compares) and all were listed. - let actual = V::Dict((0..300_000).map(|i| (Cow::Owned(format!("{}", 9000 + i)), V::Int(1))).collect()); - let mut out = Vec::new(); - undecoded_fields(&actual, None, &["0"], &[], &mut out); - assert_eq!(out.len(), MAX_UNDECODED_FIELDS); - assert_eq!(out.first().map(String::as_str), Some("9000")); - // A slot listed once is not listed again. - let again = V::Dict(vec![(Cow::Borrowed("9000"), V::Int(1))]); - let mut short = vec!["9000".to_string()]; - undecoded_fields(&again, None, &[], &[], &mut short); - assert_eq!(short, ["9000"]); - } -} diff --git a/crates/aep/src/container/typed.rs b/crates/aep/src/container/typed.rs deleted file mode 100644 index 7e7bfd0ec..000000000 --- a/crates/aep/src/container/typed.rs +++ /dev/null @@ -1,593 +0,0 @@ -//! A small typed view over the chunk tree: project items, compositions, layers, the property -//! tree and keyframe lists. The field decoders for headers, values, keyframes, effects, masks, text, -//! markers and footage are in the sibling modules and extend these types. -//! -//! Only facts that were established from our own one-change-per-file corpus and are checked by -//! tests against it are decoded (see `docs/aep-format.md` for the evidence). Everything else -//! stays reachable through the raw chunk tree ([`Node`]). Views borrow the file and never fail -//! loudly: a chunk that does not have the expected shape yields `None` or is skipped. -//! -//! A view reads either tree: the owned [`Chunk`](crate::container::Chunk) tree -//! ([`Project::new`]) or the flat [`TreeIndex`] the importer builds ([`Project::from_index`]); -//! both give the same answers. - -use crate::container::bytes::{be_f64, be_u16, be_u32, text, until_nul}; -use crate::container::chunk::AepFile; -use crate::container::index::{Node, Root, TreeIndex}; - -/// The name a user gave a property or group: the `Utf8` inside its `tdsn` chunk. `None` for the -/// sentinel `-_0_/-` ("no custom name") and for empty names. -pub(crate) fn user_name(chunk: Node<'_, '_>) -> Option { - let name = chunk.child(b"tdsn")?.child(b"Utf8")?.bytes().map(text)?; - (!name.is_empty() && name != "-_0_/-").then_some(name) -} - -/// The content of a `Utf8` child as text (not trimmed). -pub(crate) fn utf8_child(chunk: Node<'_, '_>) -> Option { - chunk.child(b"Utf8").and_then(Node::bytes).map(text) -} - -/// The project: the top-level `LIST Fold`, which holds the project items. -#[derive(Debug, Clone, Copy)] -pub struct Project<'f, 'a> { - pub(crate) fold: Node<'f, 'a>, - /// The top-level `LIST EfdG` (project-level effect definitions), when there is one. - pub(crate) effect_defs: Option>, -} - -impl<'f, 'a> Project<'f, 'a> { - /// The project view of a file, or `None` when it has no `LIST Fold`. - pub fn new(file: &'f AepFile<'a>) -> Option { - Self::of(Root::from(file)) - } - - /// The project view of an indexed file ([`TreeIndex`]), or `None` when it has no `LIST Fold`. - pub fn from_index(index: &'f TreeIndex<'a>) -> Option { - Self::of(Root::from(index)) - } - - /// The project view of either tree: its `LIST Fold` and `LIST EfdG`. - pub(crate) fn of(root: Root<'f, 'a>) -> Option { - root.list(b"Fold").map(|fold| Self { fold, effect_defs: root.list(b"EfdG") }) - } - - /// The top-level items (the project panel's root; folders hold their children, see - /// [`Item::children`]). - pub fn items(&self) -> impl Iterator> + 'f { - self.fold.children().filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) - } - - /// True when the `LIST Fold` could not be read as chunks (damaged): its items cannot be seen. - pub fn items_unreadable(&self) -> bool { - self.fold.is_opaque_list() - } - - /// Every item including those inside folders, depth-first, without recursion. - pub fn all_items(&self) -> Vec> { - let mut out = Vec::new(); - let mut stack: Vec> = self.items().collect(); - stack.reverse(); - while let Some(item) = stack.pop() { - let mut kids: Vec> = item.children().collect(); - kids.reverse(); - out.push(item); - stack.extend(kids); - } - out - } -} - -/// What a project item is (the first 16-bit word of its `idta` chunk). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ItemKind { - /// `1` - Folder, - /// `4` - Composition, - /// `7` - Footage, - /// Any other value. - Other(u16), -} - -/// A project item (`LIST Item`). -#[derive(Debug, Clone, Copy)] -pub struct Item<'f, 'a> { - pub(crate) chunk: Node<'f, 'a>, -} - -impl<'f, 'a> Item<'f, 'a> { - /// The underlying chunk. - pub fn chunk(&self) -> Node<'f, 'a> { - self.chunk - } - - /// The item kind, from `idta`. - pub fn kind(&self) -> Option { - let idta = self.chunk.child(b"idta")?.bytes()?; - Some(match be_u16(idta, 0)? { - 1 => ItemKind::Folder, - 4 => ItemKind::Composition, - 7 => ItemKind::Footage, - other => ItemKind::Other(other), - }) - } - - /// The item name (the `Utf8` child). `None` when absent or empty: a solid's footage item - /// stores no name there. - pub fn name(&self) -> Option { - utf8_child(self.chunk).filter(|n| !n.is_empty()) - } - - /// The items inside a folder (`LIST Sfdr`). - pub fn children(&self) -> impl Iterator> + 'f { - self.chunk.child_list(b"Sfdr").into_iter().flat_map(Node::children).filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) - } - - /// Whether the item has the `LIST Sfdr` of a folder's contents (After Effects writes an empty - /// one for an empty folder). - pub fn has_folder_contents(&self) -> bool { - self.chunk.child_list(b"Sfdr").is_some() - } - - /// True when the folder's `LIST Sfdr` is there but could not be read as chunks (damaged). - pub fn folder_contents_unreadable(&self) -> bool { - self.chunk.child_list(b"Sfdr").is_some_and(Node::is_opaque_list) - } - - /// The composition view when this item has composition data (`cdta`). - pub fn comp(&self) -> Option> { - self.chunk.child(b"cdta").map(|_| Comp { item: self.chunk }) - } -} - -/// The time base of a composition: one frame lasts `frame_duration` units and a second has -/// `timescale` units. Keyframe times are counted in these units. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct TimeBase { - pub frame_duration: u32, - pub timescale: u32, -} - -impl TimeBase { - /// The NTSC rates and the value After Effects stores for each (a float32 of exactly these - /// decimals): the one table the importer and the exporter use. - pub(crate) const NTSC: [(effectcraft_time::FrameRate, f32); 4] = [ - (effectcraft_time::FrameRate::FPS_23_976, 23.976), - (effectcraft_time::FrameRate::FPS_29_97, 29.97), - (effectcraft_time::FrameRate::FPS_59_94, 59.94), - (effectcraft_time::FrameRate::FPS_119_88, 119.88), - ]; - - /// Frames per second (`timescale / frame_duration`), `None` for a zero duration. - pub fn frame_rate(&self) -> Option { - (self.frame_duration != 0).then(|| f64::from(self.timescale) / f64::from(self.frame_duration)) - } - - /// Converts time units to seconds, `None` for a zero timescale. - pub fn seconds(&self, units: i32) -> Option { - (self.timescale != 0).then(|| f64::from(units) / f64::from(self.timescale)) - } -} - -/// A composition item (an [`Item`] with `cdta`). -#[derive(Debug, Clone, Copy)] -pub struct Comp<'f, 'a> { - pub(crate) item: Node<'f, 'a>, -} - -impl<'f, 'a> Comp<'f, 'a> { - /// The time base from `cdta` (`u32` at byte 4 is the frame duration, `u32` at byte 8 the - /// timescale). - pub fn time_base(&self) -> Option { - let cdta = self.item.child(b"cdta")?.bytes()?; - Some(TimeBase { frame_duration: be_u32(cdta, 4)?, timescale: be_u32(cdta, 8)? }) - } - - /// The layers, top layer first (`LIST Layr`; the `DLay`/`SLay`/`CLay`/`SecL` lists next to - /// them are not layers). - pub fn layers(&self) -> impl Iterator> + 'f { - self.item.children().filter(|c| c.is_list(b"Layr")).map(|chunk| Layer { chunk }) - } -} - -/// A layer (`LIST Layr`). -#[derive(Debug, Clone, Copy)] -pub struct Layer<'f, 'a> { - pub(crate) chunk: Node<'f, 'a>, -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The underlying chunk. - pub fn chunk(&self) -> Node<'f, 'a> { - self.chunk - } - - /// The layer name when it was set (the `Utf8` child); `None` when empty, in which case the - /// layer shows its source's name. - pub fn name(&self) -> Option { - utf8_child(self.chunk).filter(|n| !n.is_empty()) - } - - /// The 3D layer switch: bit `0x04` of byte 38 of `ldta`. - pub fn is_three_d(&self) -> Option { - let ldta = self.chunk.child(b"ldta")?.bytes()?; - Some(ldta.get(38)? & 0x04 != 0) - } - - /// The root of the layer's property tree. - pub fn properties(&self) -> Option> { - self.chunk.child_list(b"tdgp").map(|chunk| PropGroup { chunk }) - } -} - -/// A node of the property tree. -#[derive(Debug, Clone, Copy)] -pub enum PropNode<'f, 'a> { - /// A property group (`LIST tdgp`). - Group(PropGroup<'f, 'a>), - /// A property (`LIST tdbs`). - Property(Property<'f, 'a>), - /// Any other list that follows a match name (observed: `otst`, the effect instance `sspc`). - Other(Node<'f, 'a>), -} - -impl<'f, 'a> PropNode<'f, 'a> { - /// The node a `LIST` after a match name is. - fn of(c: Node<'f, 'a>) -> Self { - if c.is_list(b"tdgp") { - PropNode::Group(PropGroup { chunk: c }) - } else if c.is_list(b"tdbs") { - PropNode::Property(Property { chunk: c }) - } else { - PropNode::Other(c) - } - } -} - -/// A match name with the node it names. -#[derive(Debug, Clone)] -pub struct PropEntry<'f, 'a> { - pub match_name: String, - pub node: PropNode<'f, 'a>, -} - -/// A property group (`LIST tdgp`): after its `tdsb` and `tdsn` chunks come pairs of a `tdmn` -/// (the 40-byte NUL-padded ASCII match name) and the list it names; a `tdmn` named -/// `ADBE Group End` closes the group and names nothing. -#[derive(Debug, Clone, Copy)] -pub struct PropGroup<'f, 'a> { - pub(crate) chunk: Node<'f, 'a>, -} - -impl<'f, 'a> PropGroup<'f, 'a> { - /// A group view of a `LIST tdgp` chunk (a [`Chunk`](crate::container::Chunk) or a [`Node`]). - pub fn from_chunk(chunk: impl Into>) -> Option { - let chunk = chunk.into(); - chunk.is_list(b"tdgp").then_some(Self { chunk }) - } - - /// The underlying chunk. - pub fn chunk(&self) -> Node<'f, 'a> { - self.chunk - } - - /// The name the user gave the group (e.g. `Mask 1`, `Group 1`); `None` when it has none. - pub fn user_name(&self) -> Option { - user_name(self.chunk) - } - - /// The group's flags (`tdsb`, a `u32`). - pub fn flags(&self) -> Option { - be_u32(self.chunk.child(b"tdsb")?.bytes()?, 0) - } - - /// The entries in file order. - pub fn entries(&self) -> Vec> { - let mut out = Vec::new(); - let mut pending: Option = None; - for c in self.chunk.children() { - if c.is(b"tdmn") { - pending = c.bytes().map(match_name); - } else if c.is(&crate::container::chunk::LIST) - && let Some(name) = pending.take() - { - out.push(PropEntry { match_name: name, node: PropNode::of(c) }); - } - } - out - } - - /// The match names of the entries, in file order. - pub fn names(&self) -> Vec { - self.entries().into_iter().map(|e| e.match_name).collect() - } - - /// The first entry with this match name. One pass that stops at it, without collecting the - /// group's entries (callers look names up in loops). - pub fn get(&self, name: &str) -> Option> { - let mut pending: Option<&[u8]> = None; - for c in self.chunk.children() { - if c.is(b"tdmn") { - pending = c.bytes(); - } else if c.is(&crate::container::chunk::LIST) - && let Some(body) = pending.take() - && match_name_is(body, name) - { - return Some(PropNode::of(c)); - } - } - None - } - - /// Follows a path of match names through nested groups. - pub fn find(&self, path: &[&str]) -> Option> { - let (first, rest) = path.split_first()?; - let node = self.get(first)?; - if rest.is_empty() { - return Some(node); - } - match node { - PropNode::Group(g) => g.find(rest), - PropNode::Property(_) | PropNode::Other(_) => None, - } - } -} - -/// The match name in a `tdmn` body: ASCII up to the first NUL. -fn match_name(body: &[u8]) -> String { - text(until_nul(body)) -} - -/// `match_name(body) == name` without building the `String`: equal bytes match; otherwise only -/// a body that is not valid UTF-8 can still match (through its U+FFFD replacements), and only a -/// name that holds U+FFFD. -fn match_name_is(body: &[u8], name: &str) -> bool { - let bytes = until_nul(body); - bytes == name.as_bytes() || (name.contains('\u{FFFD}') && String::from_utf8_lossy(bytes) == name) -} - -/// A property (`LIST tdbs`): `tdsb`, `tdsn`, the 124-byte header `tdb4`, then either the static -/// value `cdat` or a keyframe `LIST list`. -#[derive(Debug, Clone, Copy)] -pub struct Property<'f, 'a> { - pub(crate) chunk: Node<'f, 'a>, -} - -impl<'f, 'a> Property<'f, 'a> { - /// A property view of a `LIST tdbs` chunk (a [`Chunk`](crate::container::Chunk) or a [`Node`]). - pub fn from_chunk(chunk: impl Into>) -> Option { - let chunk = chunk.into(); - chunk.is_list(b"tdbs").then_some(Self { chunk }) - } - - /// The underlying chunk. - pub fn chunk(&self) -> Node<'f, 'a> { - self.chunk - } - - /// The name the user gave the property; `None` when it has none. - pub fn user_name(&self) -> Option { - user_name(self.chunk) - } - - /// The raw 124-byte `tdb4` header. - pub fn header(&self) -> Option<&'f [u8]> { - self.chunk.child(b"tdb4")?.bytes() - } - - /// The number of value components: byte 3 of `tdb4`. - pub fn dims(&self) -> Option { - self.header()?.get(3).copied() - } - - /// True when the property has keyframes, i.e. its value is a `LIST list` instead of `cdat`. - /// `tdb4` byte 68 is 1 in exactly these properties. - pub fn is_animated(&self) -> bool { - self.chunk.child_list(b"list").is_some() - } - - /// The static value: the first `dims` big-endian `f64` of `cdat`. `None` for animated - /// properties and for values that are not `f64` arrays. - pub fn static_value(&self) -> Option> { - let dims = usize::from(self.dims()?); - let cdat = self.chunk.child(b"cdat")?.bytes()?; - (0..dims).map(|i| be_f64(cdat, i.checked_mul(8)?)).collect() - } - - /// The keyframe list of an animated property, with the record layout the property header - /// selects (`tdb4` byte 3 = components, byte 7 non-zero = spatial template, unless the record - /// size tells). - pub fn keys(&self) -> Option> { - let list = KeyList::from_chunk(self.chunk.child_list(b"list")?)?; - let header = self.header(); - // The record size decides where the two templates differ in size: a shape colour's keys - // are spatial (152 bytes for 4 components) although its `tdb4` byte 7 is 0 (854). For 3 - // components both templates are 128 bytes; byte 7 decides. - let size = list.header.record_size; - let layout = header.and_then(|h| { - let components = *h.get(3)?; - let n = u32::from(components); - let (spatial_size, plain_size) = (56 + 24 * n, 8 + 40 * n); - let spatial = if size == spatial_size && size != plain_size { - true - } else if size == plain_size && size != spatial_size { - false - } else { - *h.get(7)? != 0 - }; - Some(KeyLayout { components, spatial }) - }); - Some(KeyList { layout, ..list }) - } -} - -/// The header `lhd3` of a `LIST list`: 13 big-endian `u32`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ListHeader { - /// Word 0, `0x00d00bee` in every list. - pub magic: u32, - /// Word 2: the number of records. - pub count: u32, - /// Word 4: the size of one record in bytes. - pub record_size: u32, - /// All 13 words. - pub words: [u32; 13], -} - -impl ListHeader { - /// Parses a 52-byte `lhd3` body. - pub fn parse(body: &[u8]) -> Option { - if body.len() != 52 { - return None; - } - let mut words = [0u32; 13]; - for (i, w) in words.iter_mut().enumerate() { - *w = be_u32(body, i * 4)?; - } - Some(Self { magic: words[0], count: words[2], record_size: words[4], words }) - } -} - -/// A `LIST list`: `lhd3` and `ldat`, where `len(ldat) == count * record_size`. -#[derive(Debug, Clone, Copy)] -pub struct KeyList<'f> { - pub header: ListHeader, - ldat: &'f [u8], - layout: Option, -} - -/// What the property header says about its keyframe records: how many value components each -/// record holds and which of the two record templates applies (see [`KeyframeKind`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct KeyLayout { - /// `tdb4` byte 3. - pub components: u8, - /// `tdb4` byte 7 is non-zero: the spatial template (Position, colours) instead of the plain one. - pub spatial: bool, -} - -impl<'f> KeyList<'f> { - /// A view of a `LIST list` chunk. `None` when `lhd3` is not 52 bytes or `ldat` is not exactly - /// `count * record_size` bytes (a list without `ldat` must have no records). - pub fn from_chunk<'a: 'f>(chunk: impl Into>) -> Option { - let chunk = chunk.into(); - if !chunk.is_list(b"list") { - return None; - } - let header = ListHeader::parse(chunk.child(b"lhd3")?.bytes()?)?; - let ldat: &[u8] = chunk.child(b"ldat").and_then(Node::bytes).unwrap_or(&[]); - let expected = usize::try_from(header.count).ok()?.checked_mul(usize::try_from(header.record_size).ok()?)?; - (ldat.len() == expected).then_some(Self { header, ldat, layout: None }) - } - - /// The number of records actually present (what [`Self::records`] yields). Not the declared - /// count: a list with record size 0 and no data passes [`Self::from_chunk`] whatever count it - /// declares, and a caller sizing an allocation by that count would abort. - pub fn len(&self) -> usize { - self.records().count() - } - - /// True when there are no records. - pub fn is_empty(&self) -> bool { - self.ldat.is_empty() - } - - /// The records as byte slices. - pub fn records(&self) -> impl Iterator { - let size = usize::try_from(self.header.record_size).unwrap_or(0); - self.ldat.chunks_exact(size.max(1)) - } - - /// The record layout from the property header, `None` for a list that does not belong to a - /// property (the point list of a path). - pub fn layout(&self) -> Option { - self.layout - } - - /// The records of a keyframe list as [`Keyframe`]s. - pub fn keyframes(&self) -> impl Iterator> { - let layout = self.layout; - self.records().map(move |record| Keyframe { record, layout }) - } -} - -/// One keyframe record: the time is the `i32` at byte 0, in the composition's time units -/// ([`TimeBase`]). -#[derive(Debug, Clone, Copy)] -pub struct Keyframe<'f> { - pub(crate) record: &'f [u8], - pub(crate) layout: Option, -} - -impl<'f> Keyframe<'f> { - /// The whole record. - pub fn raw(&self) -> &'f [u8] { - self.record - } - - /// The keyframe time in time units (layer time). - pub fn time_units(&self) -> Option { - be_u32(self.record, 0).map(|u| i32::from_be_bytes(u.to_be_bytes())) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::container::Chunk; - - fn key_list(count: u32, record_size: u32, ldat: &[u8]) -> Chunk<'static> { - let mut lhd3 = vec![0u8; 52]; - lhd3[8..12].copy_from_slice(&count.to_be_bytes()); - lhd3[16..20].copy_from_slice(&record_size.to_be_bytes()); - Chunk::list(*b"list", vec![Chunk::data(*b"lhd3", lhd3), Chunk::data(*b"ldat", ldat.to_vec())]) - } - - #[test] - fn a_key_list_counts_the_records_it_holds() { - let two = key_list(2, 4, &[0; 8]); - assert_eq!(KeyList::from_chunk(&two).map(|l| l.len()), Some(2)); - // Record size 0 with no data passes the size check whatever count is declared; the length - // is what is there, so no caller sizes an allocation by 4 billion records. - let hostile = key_list(u32::MAX, 0, &[]); - let list = KeyList::from_chunk(&hostile).expect("a well-formed empty list"); - assert_eq!((list.len(), list.is_empty(), list.records().count()), (0, true, 0)); - } - - #[test] - fn get_finds_the_first_entry_of_a_name() { - let tdmn = |n: &str| { - let mut b = n.as_bytes().to_vec(); - b.resize(40, 0); - Chunk::data(*b"tdmn", b) - }; - let group = Chunk::list( - *b"tdgp", - vec![tdmn("A"), Chunk::list(*b"tdgp", Vec::new()), tdmn("B"), Chunk::list(*b"tdbs", Vec::new()), tdmn("A"), Chunk::list(*b"tdbs", Vec::new())], - ); - let g = PropGroup::from_chunk(&group).expect("group"); - assert!(matches!(g.get("A"), Some(PropNode::Group(_))), "the first A is the group"); - assert!(matches!(g.get("B"), Some(PropNode::Property(_)))); - assert!(g.get("C").is_none()); - assert_eq!(g.names(), ["A", "B", "A"]); - } - - /// Match name is agrees with comparing the decoded name. - #[test] - fn match_name_is_agrees_with_comparing_the_decoded_name() { - let bodies: [&[u8]; 9] = - [b"ADBE Position\0\0\0", b"ADBE Position", b"ADBE Pos", b"", b"\0ADBE", b"ADBE \xff Bad\0", b"\xff", b"\xef\xbf\xbd", "Gr\u{fc}n\0".as_bytes()]; - let names = ["ADBE Position", "ADBE Pos", "", "ADBE \u{FFFD} Bad", "\u{FFFD}", "Gr\u{fc}n", "ADBE Position\0", "ADBE \u{FFFD}"]; - for body in bodies { - for name in names { - assert_eq!(match_name_is(body, name), match_name(body) == name, "{body:?} vs {name:?}"); - } - } - // Names read back from a group find their entries, a damaged one included. - let group = Chunk::list(*b"tdgp", vec![Chunk::data(*b"tdmn", b"X\xffY\0".to_vec()), Chunk::list(*b"tdbs", Vec::new())]); - let g = PropGroup::from_chunk(&group).expect("group"); - let names = g.names(); - assert!(g.get(&names[0]).is_some()); - } -} diff --git a/crates/aep/src/container/values.rs b/crates/aep/src/container/values.rs deleted file mode 100644 index ddd5caa75..000000000 --- a/crates/aep/src/container/values.rs +++ /dev/null @@ -1,261 +0,0 @@ -//! Static transform values with their units, and the "absent = default" rule. -//! -//! After Effects stores a property only when it differs from the default it computes for the layer -//! and composition (sparse storage), so a reader has to supply the defaults: Position defaults to -//! the composition centre `[width / 2, height / 2, 0]` (verified: after the composition is resized -//! without moving the layer, the old centre appears as a stored value), Anchor Point to the layer -//! centre (`0.5, 0.5` of the layer **source** size), Scale to 100 %, Rotation to 0 and Opacity to -//! 100 %. These defaults are verified for AV layers (solids); cameras and lights use other -//! conventions (see the `camera` module). - -use crate::container::bytes::be_f64; -use crate::container::typed::{Layer, Project, PropGroup, PropNode}; - -/// Where a [`Tracked`] value came from. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ValueSource { - /// The property is absent from the file: the value is the computed default. - Default, - /// The property stores a static value. - Stored, - /// The property has keyframes: the value is that of the first keyframe. - Keyframed, - /// The property is present but its value could not be read: the value is the default. - Unreadable, -} - -/// A value and where it came from. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Tracked { - pub value: T, - pub source: ValueSource, -} - -/// The five basic transform properties of an AV layer, in the units After Effects shows. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Transform { - /// Pixels `[x, y, z]`. - pub position: Tracked<[f64; 3]>, - /// Stored as a fraction of the layer's **source** size for x and y (`10, 20` px on a 100x100 - /// solid in a 1920x1080 composition is `0.1, 0.2`; on a 400x300 solid `100, 50` is `0.25, 1/6`) - /// and in pixels for z; see [`Transform::anchor_px`] and [`Project::layer_anchor_px`]. - pub anchor_fraction: Tracked<[f64; 3]>, - /// Percent `[x, y, z]` (stored as fractions: 50 % is `0.5`). - pub scale_percent: Tracked<[f64; 3]>, - /// Degrees (Rotation, the Z rotation). - pub rotation_degrees: Tracked, - /// Percent (stored as a fraction: 25 % is `0.25`). - pub opacity_percent: Tracked, -} - -impl Transform { - /// The anchor point in pixels for a layer whose source has this size. - pub fn anchor_px(&self, width: f64, height: f64) -> [f64; 3] { - let [x, y, z] = self.anchor_fraction.value; - [x * width, y * height, z] - } - - /// The anchor point of a **text** layer in layer pixels. A text layer has no source, so the - /// stored value is not a fraction: it is pixels as stored (385: Anchor Point `10, 20` is stored - /// `10, 20`), and an - /// absent anchor is the text origin `[0, 0, 0]` (After Effects' default for new text, absent in - /// every other text sample 110-114, 243-248, 334-340, 386). - pub fn text_anchor_px(&self) -> [f64; 3] { - match self.anchor_fraction.source { - ValueSource::Stored | ValueSource::Keyframed => self.anchor_fraction.value, - ValueSource::Default | ValueSource::Unreadable => [0.0; 3], - } - } -} - -/// Reads `N` components from the property `name` of `group` and multiplies them by `scale` (stored -/// fractions to percent); `default` is in the output units and used when the property is absent. -pub(crate) fn read(group: &PropGroup<'_, '_>, name: &str, default: [f64; N], scale: f64) -> Tracked<[f64; N]> { - let unreadable = Tracked { value: default, source: ValueSource::Unreadable }; - let property = match group.get(name) { - None => return Tracked { value: default, source: ValueSource::Default }, - Some(PropNode::Property(p)) => p, - Some(PropNode::Group(_) | PropNode::Other(_)) => return unreadable, - }; - let (values, source) = - if property.is_animated() { (property.first_key_value(), ValueSource::Keyframed) } else { (property.static_value(), ValueSource::Stored) }; - let Some(values) = values else { return unreadable }; - if values.len() < N { - return unreadable; - } - let mut out = default; - for (slot, v) in out.iter_mut().zip(&values) { - *slot = *v * scale; - } - Tracked { value: out, source } -} - -/// Like [`read`] but `None` when the property is absent or unreadable (for properties whose default -/// is not known), keeping the value's source. -pub(crate) fn read_opt(group: &PropGroup<'_, '_>, name: &str, scale: f64) -> Option> { - let tracked = read(group, name, [0.0; N], scale); - matches!(tracked.source, ValueSource::Stored | ValueSource::Keyframed).then_some(tracked) -} - -impl<'f, 'a> Project<'f, 'a> { - /// The anchor point of an AV layer in pixels: the stored fraction times the size of the layer's - /// source (a solid or footage item, or a precomp's composition), z unchanged. `None` when the - /// layer has no source (shape, text, camera, light) or no Transform group. - pub fn layer_anchor_px(&self, layer: &Layer<'f, 'a>) -> Option> { - let (width, height) = self.layer_source_size(layer)?; - let Some(PropNode::Group(group)) = layer.properties()?.get("ADBE Transform Group") else { return None }; - let fraction = read(&group, "ADBE Anchor Point", [0.5, 0.5, 0.0], 1.0); - let [x, y, z] = fraction.value; - Some(Tracked { value: [x * f64::from(width), y * f64::from(height), z], source: fraction.source }) - } -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The transform of an AV layer in a composition of this size (pixels), with absent - /// properties replaced by their defaults. `None` when the layer has no Transform group. - pub fn transform(&self, comp_width: u32, comp_height: u32) -> Option { - let Some(PropNode::Group(group)) = self.properties()?.get("ADBE Transform Group") else { return None }; - let centre = [f64::from(comp_width) / 2.0, f64::from(comp_height) / 2.0, 0.0]; - let rotation = read(&group, "ADBE Rotate Z", [0.0], 1.0); - let opacity = read(&group, "ADBE Opacity", [100.0], 100.0); - Some(Transform { - position: read(&group, "ADBE Position", centre, 1.0), - anchor_fraction: read(&group, "ADBE Anchor Point", [0.5, 0.5, 0.0], 1.0), - scale_percent: read(&group, "ADBE Scale", [100.0, 100.0, 100.0], 100.0), - rotation_degrees: Tracked { value: rotation.value[0], source: rotation.source }, - opacity_percent: Tracked { value: opacity.value[0], source: opacity.source }, - }) - } -} - -/// One key of a layer's Time Remapping property: the layer time of the key and the source time it -/// maps to, both in seconds. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct TimeRemapKey { - /// The key time in the property's time units. - pub time_units: i32, - /// The key time in seconds (layer time). - pub time_seconds: Option, - /// The value in seconds (the plain record's value at byte 8). - pub value_seconds: f64, -} - -/// The state of a layer's `ADBE Time Remapping` property. Every layer has the property; while the -/// remap is off it is an inert record (`tdsb` 3, static value 0, no keys). Enabling the remap turns -/// it into a keyed property (`tdsb` 1, `tdb4` byte 68 = 1, no `cdat`) with two keys: the layer's in -/// and out time mapped to the source time (319: 0 s and 5 s; 354: 0 s and 0.1 s). -#[derive(Debug, Clone, PartialEq)] -pub struct TimeRemap { - /// True when the property has keys. - pub enabled: bool, - pub keys: Vec, -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The Time Remapping state; `None` when the layer has no such property. - pub fn time_remap(&self) -> Option { - let Some(PropNode::Property(p)) = self.properties()?.get("ADBE Time Remapping") else { return None }; - let scale = p.time_scale().unwrap_or(0); - let keys = match p.keys() { - Some(list) => list - .keyframes() - .filter_map(|k| Some(TimeRemapKey { time_units: k.time_units()?, time_seconds: k.seconds(scale), value_seconds: k.scalar_value()? })) - .collect(), - None => Vec::new(), - }; - Some(TimeRemap { enabled: p.is_animated(), keys }) - } -} - -/// The Orientation of a 3D layer (`ADBE Orientation`, 488): a `LIST otst` holding a `tdbs` and a -/// `LIST otky` whose `otda` is three big-endian `f64` degrees `[x, y, z]`; absent at `[0, 0, 0]` -/// (485-487). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Orientation { - /// Degrees `[x, y, z]`: the static value (for a keyed Orientation the first `otda`, whose - /// meaning is not sampled). - pub degrees: [f64; 3], - /// The `tdbs` of the `otst` has keys (see [`Layer::orientation_keys`]). - pub animated: bool, - /// The `tdbs` of the `otst` has an expression. - pub has_expression: bool, -} - -impl<'f, 'a> Layer<'f, 'a> { - /// The Orientation; `None` when it is absent (the default `[0, 0, 0]`) or unreadable. - pub fn orientation(&self) -> Option { - let Some(PropNode::Group(group)) = self.properties()?.get("ADBE Transform Group") else { return None }; - let Some(PropNode::Other(otst)) = group.get("ADBE Orientation") else { return None }; - if !otst.is_list(b"otst") { - return None; - } - let property = otst.child_list(b"tdbs").and_then(crate::container::typed::Property::from_chunk); - let otda = otst.child_list(b"otky")?.child(b"otda")?.bytes()?; - let mut degrees = [0.0; 3]; - for (i, slot) in degrees.iter_mut().enumerate() { - *slot = be_f64(otda, i * 8)?; - } - Some(Orientation { - degrees, - animated: property.as_ref().is_some_and(|p| p.is_animated()), - has_expression: property.as_ref().is_some_and(|p| p.expression().is_some()), - }) - } - - /// The time scale of the Orientation's key times (`tdb4` bytes 12..15), which follows the - /// layer's stretch like every property of the layer. - pub fn orientation_time_scale(&self) -> Option { - let Some(PropNode::Group(group)) = self.properties().and_then(|p| p.get("ADBE Transform Group")) else { return None }; - let Some(PropNode::Other(otst)) = group.get("ADBE Orientation") else { return None }; - otst.child_list(b"tdbs").and_then(crate::container::typed::Property::from_chunk).and_then(|p| p.time_scale()) - } - - /// The keyframes of a keyed Orientation (703): the `tdbs` of the `otst` holds one 80-byte - /// record per key (time, interpolation sides, flags; the rest is not decoded) and `otky` one - /// `otda` (three `f64` degrees) per key, in the same order. Empty when the Orientation is not - /// keyed or the counts differ. After Effects interpolates between the keys by a quaternion slerp - /// of the rotations `Rx Ry Rz`, not per component (703's values at 0.5 / 1 / 1.5 s). - pub fn orientation_keys(&self) -> Vec { - let Some(PropNode::Group(group)) = self.properties().and_then(|p| p.get("ADBE Transform Group")) else { return Vec::new() }; - let Some(PropNode::Other(otst)) = group.get("ADBE Orientation") else { return Vec::new() }; - let Some(list) = otst.child_list(b"tdbs").and_then(crate::container::typed::Property::from_chunk).and_then(|p| p.keys()) else { return Vec::new() }; - let values: Vec> = otst - .child_list(b"otky") - .map(|k| { - k.children() - .filter(|c| c.is(b"otda")) - .map(|c| { - let b = c.bytes()?; - Some([be_f64(b, 0)?, be_f64(b, 8)?, be_f64(b, 16)?]) - }) - .collect() - }) - .unwrap_or_default(); - let keys: Vec<_> = list.keyframes().collect(); - if keys.len() != values.len() { - return Vec::new(); - } - keys.iter() - .zip(values) - .filter_map(|(k, v)| { - Some(OrientationKey { - time_units: k.time_units()?, - interpolation_in: k.interpolation_in()?, - interpolation_out: k.interpolation_out()?, - degrees: v?, - }) - }) - .collect() - } -} - -/// A keyframe of a keyed Orientation. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct OrientationKey { - /// The time in the property's time units (layer time). - pub time_units: i32, - pub interpolation_in: crate::container::Interpolation, - pub interpolation_out: crate::container::Interpolation, - /// Degrees `[x, y, z]`. - pub degrees: [f64; 3], -} diff --git a/crates/aep/src/container/version.rs b/crates/aep/src/container/version.rs deleted file mode 100644 index 407c7046c..000000000 --- a/crates/aep/src/container/version.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! The After Effects version a project is written for (`head` bytes 4 to 7) and the version of the -//! After Effects that wrote it (`svap`). -//! -//! Both hold the same packed `u32` (see `docs/aep-format.md`, section 1, "Version"). A project saved -//! normally has the same word in both; File ▸ Save a Copy As 25.x / 24.x of After Effects 2026 keeps -//! `svap` (the 2026 version) and writes the older version into `head`. The XMP packet after the -//! container names the application of the first save (`CreatorTool`) and is no guide to either. - -use std::fmt; - -use crate::container::bytes::be_u32; -use crate::container::chunk::AepFile; -use crate::container::index::{Root, TreeIndex}; - -/// An After Effects version as packed in `head` / `svap`: `26.2.1x2` is major 26, minor 2, bug-fix -/// 1, build 2 (the form of the scripting API's `app.version`). -/// -/// Bit layout of the big-endian word (bit 31 first), decoded from the samples (the 2026 word -/// `0x0f11_0e02` is the version the saving After Effects reports, `26.2.1x2`; the down-saves give -/// `0x0f0b_0661` and `0x0f03_0641`, read as `25.6.0x97` and `24.6.0x65`): -/// -/// | bits | field | -/// |---|---| -/// | 31-26 | not decoded (`000011` in every sample) | -/// | 25-24, 21-19 | major (high two bits, then low three bits) | -/// | 23-22 | not decoded (`00` in every sample) | -/// | 18-15 | minor | -/// | 14-11 | bug-fix | -/// | 10-8 | stage (6 in every sample) | -/// | 7-0 | build | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct AeVersion { - pub major: u8, - pub minor: u8, - pub bugfix: u8, - /// The release stage (6 in every sample; not shown in [`AeVersion::text`]). - pub stage: u8, - pub build: u8, - /// The word as stored. - pub raw: u32, -} - -impl AeVersion { - /// Decodes a stored word; `None` for a word that holds no version (zero, all ones, or major 0: - /// After Effects itself refuses a file whose `head` version is zero, "[0.0x0]"). - pub fn from_word(raw: u32) -> Option { - if raw == 0 || raw == u32::MAX { - return None; - } - let [b0, b1, b2, b3] = raw.to_be_bytes(); - let major = ((b0 & 0x03) << 3) | ((b1 >> 3) & 0x07); - if major == 0 { - return None; - } - Some(Self { major, minor: ((b1 & 0x07) << 1) | (b2 >> 7), bugfix: (b2 >> 3) & 0x0f, stage: b2 & 0x07, build: b3, raw }) - } - - /// `26.2.1x2`. - pub fn text(&self) -> String { - self.to_string() - } -} - -impl fmt::Display for AeVersion { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}.{}.{}x{}", self.major, self.minor, self.bugfix, self.build) - } -} - -impl AepFile<'_> { - /// The version the file is written for: `head` bytes 4 to 7. After Effects 2026 writes its own - /// version there, and the older version for File ▸ Save a Copy As 25.x / 24.x. `None` when the - /// chunk is missing, short or holds no version. - pub fn file_version(&self) -> Option { - Root::from(self).file_version() - } - - /// The version of the After Effects that wrote the file: `svap` bytes 0 to 3 (the same word in a - /// down-saved copy as in a normal save). `None` when the chunk is missing (After Effects opens such - /// a file), short or holds no version. - pub fn saved_by_version(&self) -> Option { - Root::from(self).saved_by_version() - } -} - -impl TreeIndex<'_> { - /// [`AepFile::file_version`] of the indexed file. - pub fn file_version(&self) -> Option { - Root::from(self).file_version() - } - - /// [`AepFile::saved_by_version`] of the indexed file. - pub fn saved_by_version(&self) -> Option { - Root::from(self).saved_by_version() - } -} - -impl Root<'_, '_> { - pub(crate) fn file_version(self) -> Option { - AeVersion::from_word(be_u32(self.chunk(b"head")?.bytes()?, 4)?) - } - - pub(crate) fn saved_by_version(self) -> Option { - AeVersion::from_word(be_u32(self.chunk(b"svap")?.bytes()?, 0)?) - } -} - -#[cfg(test)] -mod tests { - use super::AeVersion; - - #[test] - fn decodes_the_sampled_words() { - let v = AeVersion::from_word(0x0f11_0e02).unwrap(); - assert_eq!((v.major, v.minor, v.bugfix, v.stage, v.build), (26, 2, 1, 6, 2)); - assert_eq!(v.text(), "26.2.1x2"); - assert_eq!(AeVersion::from_word(0x0f0b_0661).unwrap().text(), "25.6.0x97"); - assert_eq!(AeVersion::from_word(0x0f03_0641).unwrap().text(), "24.6.0x65"); - } - - #[test] - fn a_word_without_a_version_is_none() { - assert_eq!(AeVersion::from_word(0), None); - assert_eq!(AeVersion::from_word(u32::MAX), None); - // Major 0 (only the undecoded high bits set). - assert_eq!(AeVersion::from_word(0x0c00_0000), None); - } - - #[test] - fn every_field_takes_its_extremes() { - let v = AeVersion::from_word(0x03ff_ffff).unwrap(); - assert_eq!((v.major, v.minor, v.bugfix, v.stage, v.build), (31, 15, 15, 7, 255)); - let v = AeVersion::from_word(0x0000_0800 | 0x0008_0000).unwrap(); - assert_eq!((v.major, v.minor, v.bugfix, v.build), (1, 0, 1, 0)); - } -} diff --git a/crates/aep/src/container/write.rs b/crates/aep/src/container/write.rs deleted file mode 100644 index 9f401b3d4..000000000 --- a/crates/aep/src/container/write.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Writing an [`AepFile`] back to bytes. - -use std::io::Write; - -use crate::container::chunk::{AepFile, Body, Chunk}; -use crate::container::error::AepError; - -/// Deepest tree [`write`] accepts (a hand-built tree may be deeper than any parsed one). -const MAX_WRITE_DEPTH: usize = 256; - -/// Serialises `file`: `RIFX`, the recomputed container size, `Egg!`, the chunks and the trailer. -/// Sizes of the container and of every chunk are recomputed from the tree; an unmodified parsed -/// file comes back byte for byte. -/// -/// # Errors -/// [`AepError::TooLarge`] when a chunk or the container exceeds the 32-bit size field, -/// [`AepError::TooDeep`] for an absurdly deep hand-built tree. -pub fn write(file: &AepFile<'_>) -> Result, AepError> { - let mut out = Vec::new(); - // Sized once to the exact output. A tree past the 32-bit container size fails at once (the - // same error the write below would give after serialising it). `try_reserve` so a hand-built - // tree that repeats one large borrowed body many times cannot abort on the allocation; the - // writer then grows as it goes, as before. - if let Some(len) = sequence_len(&file.chunks, 1) { - if u32::try_from(len.saturating_add(4)).is_err() { - return Err(AepError::TooLarge); - } - if let Some(total) = len.checked_add(12).and_then(|n| n.checked_add(file.trailer.len())) { - let _ = out.try_reserve_exact(total); - } - } - out.extend_from_slice(b"RIFX"); - out.extend_from_slice(&[0; 4]); - out.extend_from_slice(b"Egg!"); - write_sequence(&mut out, &file.chunks, 1)?; - let size = u32::try_from(out.len().saturating_sub(8)).map_err(|_| AepError::TooLarge)?; - patch_u32(&mut out, 4, size)?; - out.extend_from_slice(&file.trailer); - Ok(out) -} - -/// Like [`write`], into any writer. -/// -/// # Errors -/// A size or depth error of [`write`] becomes `ErrorKind::InvalidData`; otherwise I/O errors. -pub fn write_to(file: &AepFile<'_>, w: &mut impl Write) -> std::io::Result<()> { - let bytes = write(file).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; - w.write_all(&bytes) -} - -fn patch_u32(out: &mut [u8], at: usize, v: u32) -> Result<(), AepError> { - let end = at.checked_add(4).ok_or(AepError::TooLarge)?; - let dst = out.get_mut(at..end).ok_or(AepError::TooLarge)?; - for (d, s) in dst.iter_mut().zip(v.to_be_bytes()) { - *d = s; - } - Ok(()) -} - -fn write_sequence(out: &mut Vec, chunks: &[Chunk<'_>], depth: usize) -> Result<(), AepError> { - if depth > MAX_WRITE_DEPTH { - return Err(AepError::TooDeep); - } - let count = chunks.len(); - for (i, chunk) in chunks.iter().enumerate() { - write_chunk(out, chunk, i + 1 == count, depth)?; - } - Ok(()) -} - -/// The number of bytes [`write_sequence`] produces for `chunks`; `None` past the depth limit or -/// on overflow (both make the write fail). -fn sequence_len(chunks: &[Chunk<'_>], depth: usize) -> Option { - if depth > MAX_WRITE_DEPTH { - return None; - } - let count = chunks.len(); - let mut total = 0usize; - for (i, chunk) in chunks.iter().enumerate() { - let body = match &chunk.body { - Body::Data(d) => d.len(), - Body::Chunks(c) => sequence_len(c, depth + 1)?, - Body::List { children, .. } => sequence_len(children, depth + 1)?.checked_add(4)?, - Body::OpaqueList { data, .. } => data.len().checked_add(4)?, - }; - // The same pad rule as `write_chunk`. - let pad = usize::from(body % 2 == 1 && (chunk.pad.is_some() || i + 1 != count)); - total = total.checked_add(8)?.checked_add(body)?.checked_add(pad)?; - } - Some(total) -} - -fn write_chunk(out: &mut Vec, chunk: &Chunk<'_>, is_last: bool, depth: usize) -> Result<(), AepError> { - out.extend_from_slice(&chunk.id); - let size_at = out.len(); - out.extend_from_slice(&[0; 4]); - let body_start = out.len(); - match &chunk.body { - Body::Data(d) => out.extend_from_slice(d), - Body::Chunks(c) => write_sequence(out, c, depth + 1)?, - Body::List { list_type, children } => { - out.extend_from_slice(list_type); - write_sequence(out, children, depth + 1)?; - } - Body::OpaqueList { list_type, data } => { - out.extend_from_slice(list_type); - out.extend_from_slice(data); - } - } - let len = out.len().saturating_sub(body_start); - patch_u32(out, size_at, u32::try_from(len).map_err(|_| AepError::TooLarge)?)?; - if len % 2 == 1 { - match chunk.pad { - Some(b) => out.push(b), - None if !is_last => out.push(0), - None => {} - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use std::borrow::Cow; - - use super::*; - - /// The output is sized once to its exact length. - #[test] - fn the_output_is_sized_once_to_its_exact_length() { - let odd = |n: u8| Chunk::data(*b"cdat", vec![n; usize::from(n)]); - let mut padded = odd(3); - padded.pad = Some(0x7f); - let trees = [ - AepFile { chunks: Vec::new(), trailer: Cow::Borrowed(&[]) }, - AepFile { - chunks: vec![ - odd(1), - Chunk::list(*b"Fold", vec![odd(2), odd(3), Chunk::list(*b"tdgp", vec![odd(5)])]), - Chunk { id: *b"LIST", body: Body::OpaqueList { list_type: *b"btdk", data: Cow::Owned(vec![1, 2, 3]) }, pad: None }, - Chunk { id: *b"tdmn", body: Body::Chunks(vec![odd(7), padded]), pad: None }, - odd(9), - ], - trailer: Cow::Borrowed(b""), - }, - ]; - for file in &trees { - let out = write(file).expect("write"); - assert_eq!(sequence_len(&file.chunks, 1).map(|n| n + 12 + file.trailer.len()), Some(out.len())); - // Exact with std's allocator today; grown push by push it would be rounded up. - assert_eq!(out.capacity(), out.len(), "the output grew past its size"); - } - } - - /// A tree past the container size fails before serialising. - #[cfg(target_pointer_width = "64")] - #[test] - fn a_tree_past_the_container_size_fails_before_serialising() { - // 4097 chunks borrowing one 1 MiB body: over 4 GiB of output, none of it written. - let body = vec![0u8; 1 << 20]; - let chunks: Vec> = (0..4097).map(|_| Chunk::data(*b"cdat", &body[..])).collect(); - let file = AepFile { chunks, trailer: Cow::Borrowed(&[]) }; - assert_eq!(write(&file), Err(AepError::TooLarge)); - // Just under the limit still sizes, and fails nothing up front. - assert!(sequence_len(&file.chunks[..4000], 1).is_some_and(|n| u32::try_from(n + 4).is_ok())); - } - - /// A tree past the depth limit has no size. - #[test] - fn a_tree_past_the_depth_limit_has_no_size() { - let mut deep = Chunk::data(*b"cdat", vec![0]); - for _ in 0..=MAX_WRITE_DEPTH { - deep = Chunk::list(*b"tdgp", vec![deep]); - } - let file = AepFile { chunks: vec![deep], trailer: Cow::Borrowed(&[]) }; - assert_eq!(sequence_len(&file.chunks, 1), None); - assert_eq!(write(&file), Err(AepError::TooDeep)); - } -} diff --git a/crates/aep/src/export/timebase.rs b/crates/aep/src/export/timebase.rs index af9d22926..a4353902b 100644 --- a/crates/aep/src/export/timebase.rs +++ b/crates/aep/src/export/timebase.rs @@ -7,11 +7,16 @@ //! `rate x frame duration >= 24 576` (25 fps: 1024 and 25 600; 12 fps: 2048 and 24 576; 1 fps: //! 32 768 and 32 768; 240 fps: 128 and 30 720). +use crate::container::TimeBase as ContainerTimeBase; use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick}; -/// The container's time base (frame duration and time scale in units; one frame lasts -/// `frame_duration` units and a second has `timescale` units), which the importer reads. -pub(crate) use crate::container::TimeBase; +/// Frame duration and time scale in units; one frame lasts `frame_duration` units and a second +/// has `timescale` units. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct TimeBase { + pub frame_duration: u32, + pub timescale: u32, +} /// The 16.16 fixed-point rate After Effects stores next to the time base (a float32 rate). pub(crate) fn fixed_rate(rate: FrameRate) -> u32 { @@ -22,8 +27,8 @@ pub(crate) fn fixed_rate(rate: FrameRate) -> u32 { /// The typed value of an NTSC rate (23.976, 29.97, 59.94, 119.88), which After Effects stores as /// a float32 of exactly these decimals. -fn ntsc_typed(rate: FrameRate) -> Option { - TimeBase::NTSC.into_iter().find(|(r, _)| *r == rate).map(|(_, v)| v) +pub(crate) fn ntsc_typed(rate: FrameRate) -> Option { + ContainerTimeBase::NTSC.into_iter().find(|((num, den), _)| FrameRate::new(i64::from(*num), i64::from(*den)) == rate).map(|(_, v)| v) } /// The time base for `rate`, or `None` for a rate After Effects cannot hold (non-positive, or not @@ -60,27 +65,28 @@ pub(crate) fn time_base(rate: FrameRate) -> Option { } impl TimeBase { - /// `tick` in time units, rounded to the nearest unit (saturated to `i64`); the second value - /// tells whether it was not exact. - pub(crate) fn units(&self, tick: Tick) -> (i64, bool) { - nearest(i128::from(tick.0).saturating_mul(i128::from(self.timescale)), i128::from(TICKS_PER_SECOND)) + /// `tick` in time units, rounded to the nearest unit; the second value tells whether it was + /// not exact. + pub fn units(&self, tick: Tick) -> (i64, bool) { + let n = i128::from(tick.0) * i128::from(self.timescale); + let d = i128::from(TICKS_PER_SECOND); + let q = n.div_euclid(d); + let r = n.rem_euclid(d); + let rounded = if r * 2 >= d { q + 1 } else { q }; + (i64::try_from(rounded).unwrap_or(if rounded < 0 { i64::MIN } else { i64::MAX }), r != 0) } - /// Whole frames of `tick` (nearest, saturated to `i64` like [`TimeBase::units`]). - pub(crate) fn frames(&self, tick: Tick, rate: FrameRate) -> i64 { - let d = i128::from(TICKS_PER_SECOND).saturating_mul(i128::from(rate.den.max(1))); - nearest(i128::from(tick.0).saturating_mul(i128::from(rate.num)), d).0 + /// Whole frames of `tick` (nearest). + pub fn frames(&self, tick: Tick, rate: FrameRate) -> i64 { + let n = i128::from(tick.0) * i128::from(rate.num); + let d = i128::from(TICKS_PER_SECOND) * i128::from(rate.den.max(1)); + let q = n.div_euclid(d); + let r = n.rem_euclid(d); + let f = if r * 2 >= d { q + 1 } else { q }; + i64::try_from(f).unwrap_or(0) } } -/// `n / d` rounded to the nearest whole number (a half rounds up), saturated to `i64`, and whether -/// it was not exact. `d` is positive. -fn nearest(n: i128, d: i128) -> (i64, bool) { - let (q, r) = (n.div_euclid(d), n.rem_euclid(d)); - let rounded = if r.saturating_mul(2) >= d { q.saturating_add(1) } else { q }; - (i64::try_from(rounded).unwrap_or(if rounded < 0 { i64::MIN } else { i64::MAX }), r != 0) -} - #[cfg(test)] mod tests { use super::*; @@ -123,19 +129,4 @@ mod tests { assert!(tb.units(Tick(TICKS_PER_SECOND / 3)).1); assert_eq!(tb.frames(Tick(TICKS_PER_SECOND * 2), FrameRate::new(25, 1)), 50); } - - /// Frames saturate like units (they used to become 0 past `i64`). No storable rate gets - /// there: [`time_base`] only accepts rates far below one frame per tick. - #[test] - fn frames_and_units_saturate_alike() { - let tb = TimeBase { frame_duration: 1024, timescale: u32::MAX }; - let huge = FrameRate { num: i64::MAX, den: 1 }; - assert_eq!(tb.frames(Tick(i64::MAX), huge), i64::MAX); - assert_eq!(tb.frames(Tick(i64::MIN), huge), i64::MIN); - // A half rounds up on the signed value, in frames and in units. - assert_eq!(tb.frames(Tick(TICKS_PER_SECOND / 2), FrameRate::new(1, 1)), 1); - assert_eq!(tb.frames(Tick(-TICKS_PER_SECOND / 2), FrameRate::new(1, 1)), 0); - let tb1 = TimeBase { frame_duration: 1, timescale: 1 }; - assert_eq!((tb1.units(Tick(TICKS_PER_SECOND / 2)), tb1.units(Tick(-TICKS_PER_SECOND / 2))), ((1, true), (0, true))); - } } diff --git a/crates/aep/src/import/effects.rs b/crates/aep/src/import/effects.rs index 11d975cd8..3b447c13a 100644 --- a/crates/aep/src/import/effects.rs +++ b/crates/aep/src/import/effects.rs @@ -528,7 +528,7 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h Some(m) => import_mesh(&m, here, size, group, col), None => col.lose(LossCategory::DamagedData, format!("{here}: the Distortion Mesh is unreadable, defaults used")), }, - Extra::Extractor => match ExtractorChannels::parse(data).map(|c| (c.sources(), c)) { + Extra::Extractor => match ExtractorChannels::parse(data).map(|c| (c.sources(effectcraft_effects::EXTRACTOR_COPY), c)) { // Each output channel reads the footage's channel of the stored name, which // EffectCraft's EXtractoR finds by the same name (`Z`); After Effects' `(copy)` is the // input's own channel, EffectCraft's `(copy)` (not `A`, which EffectCraft reads from an diff --git a/crates/aep/src/import/markers.rs b/crates/aep/src/import/markers.rs index 7767bfca4..bac338c62 100644 --- a/crates/aep/src/import/markers.rs +++ b/crates/aep/src/import/markers.rs @@ -11,8 +11,8 @@ //! EffectCraft's `timeRemap` property (seconds, keys in layer time) at the top of the layer's //! properties, where the engine's Enable Time Remapping puts it. -use crate::container::index::Node as AepNode; use crate::{CueType, Layer as AepLayer, Marker as AepMarker, PropNode, Property as AepProp}; +use craft_aep::Node as AepNode; use effectcraft_color::Label; use effectcraft_keyframe::Value; use effectcraft_project::build::Ids; diff --git a/crates/aep/src/import/time.rs b/crates/aep/src/import/time.rs index 0f4f67097..d709a6b6d 100644 --- a/crates/aep/src/import/time.rs +++ b/crates/aep/src/import/time.rs @@ -5,10 +5,9 @@ //! stay frames at every rate (29.97 fps is `23976 / 800` in the file and `30000 / 1001` in the //! project). Any other time is rounded to the nearest tick. +use crate::container::TimeBase as ContainerTimeBase; use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick}; -use crate::container::TimeBase; - /// The composition's frame structure: the stored time base and the rate the project gets. #[derive(Clone, Copy, Debug)] pub(crate) struct TimeMap { @@ -29,8 +28,13 @@ pub(crate) fn frame_rate(timescale: u32, frame_duration: u32) -> Option.aep .aep .aep` (and `layers-comps-scrub-aepx.py` for the `.aepx`). Set `SCRUB_FORBID` to the local folder and machine names that must not remain; the script fails if one does. -6. Strip the colour profiles: `cargo run -p effectcraft-aep --example stubicc -- .aep .aep.new` +6. Strip the colour profiles: `cargo run -p craft-aep --example stubicc -- .aep .aep.new` (in craft-libs) (and the `.aepx`) replaces the working-space profile (and the profile of imported images) by a stub with the same description and no colour data. It stops without writing if a profile cannot be replaced. Then scan the final files independently (the corpus repository's diff --git a/crates/aep/tests/it/container.rs b/crates/aep/tests/it/container.rs index 4fc6d804e..a03f19db7 100644 --- a/crates/aep/tests/it/container.rs +++ b/crates/aep/tests/it/container.rs @@ -1,30 +1,2 @@ -//! container tests of effectcraft-aep. - -#[macro_use] -mod helpers; - -mod aepx; -mod batch3_core; -mod batch3_objects; -mod batch5; -mod cases_600; -mod ease_round2; -mod effects; -mod effects_batch4; -mod effects_batch5; -mod effects_exposure; -mod header; -mod keyframes; -mod layer_switches; -mod masks; -mod matte; -mod odd_cases; -mod robustness; -mod roundtrip; -mod shapes; -mod text_fields; -mod text_markers_footage; -mod text_style_slots; +//! Integration checks for the shared AEP tree exposed through EffectCraft. mod tree_index; -mod typed; -mod values; diff --git a/crates/aep/tests/it/container/aepx.rs b/crates/aep/tests/it/container/aepx.rs deleted file mode 100644 index 0baf1afd8..000000000 --- a/crates/aep/tests/it/container/aepx.rs +++ /dev/null @@ -1,174 +0,0 @@ -//! `.aepx` (the XML form) read into the chunk tree, compared with the `.aep` of the same project. -//! -//! The pair `aepx-pair` (cases 000, 058, 060, 110 and 124, one composition each) was saved by -//! After Effects from the same state, the `.aepx` right after the `.aep`. -//! The trees are identical except for two documented differences: the save counter (`head` -//! `u32` at byte 16) is one higher in the `.aepx`, and pad bytes are not written in XML (an odd -//! body gets a zero pad byte). The XMP packet of the fixtures is the base packet in both forms. - -use effectcraft_aep::{AepError, AepFile, Body, Chunk, Limits, Project, is_aepx, parse, parse_any, read_aepx, read_aepx_with_limits, write}; - -/// The `.aepx` fixtures; each has the `.aep` of the same name. -const PAIRS: &[&str] = &["aepx-pair"]; - -/// The `.aep` tree with the differences an `.aepx` of the next save has removed: the `head` save -/// counter is taken from `other`. -fn with_head_of(mut file: AepFile<'static>, other: &AepFile<'_>) -> AepFile<'static> { - if let (Some(h), Some(src)) = (file.chunks.iter_mut().find(|c| c.is(b"head")), other.chunk(b"head")) { - *h = src.clone().into_owned(); - } - file -} - -/// The first difference of two chunk sequences, as a path, ignoring pad bytes. -fn first_difference(a: &[Chunk<'_>], b: &[Chunk<'_>], path: &str) -> Option { - if a.len() != b.len() { - return Some(format!("{path}: {} chunks against {}", a.len(), b.len())); - } - for (i, (x, y)) in a.iter().zip(b).enumerate() { - let name = String::from_utf8_lossy(&x.list_type().unwrap_or(x.id)).into_owned(); - let here = format!("{path}/{i}:{name}"); - if x.id != y.id || x.list_type() != y.list_type() { - return Some(format!("{here}: id differs")); - } - match (&x.body, &y.body) { - (Body::Data(p), Body::Data(q)) | (Body::OpaqueList { data: p, .. }, Body::OpaqueList { data: q, .. }) => { - if p != q { - return Some(format!("{here}: body differs")); - } - } - (Body::Chunks(p), Body::Chunks(q)) | (Body::List { children: p, .. }, Body::List { children: q, .. }) => { - if let Some(d) = first_difference(p, q, &here) { - return Some(d); - } - } - _ => return Some(format!("{here}: body kind differs")), - } - } - None -} - -fn head_counter(file: &AepFile<'_>) -> u32 { - let h = file.chunk(b"head").and_then(Chunk::bytes).expect("head"); - u32::from_be_bytes([h[16], h[17], h[18], h[19]]) -} - -#[test] -fn every_pair_gives_the_same_chunk_tree() { - for name in PAIRS { - let aep = skip!(crate::common::try_file(&format!("{name}.aep"))); - let aepx = skip!(crate::common::try_file(&format!("{name}.aepx"))); - assert!(is_aepx(&aepx) && !is_aepx(&aep), "{name}"); - let bin = parse(&aep).unwrap(); - let xml = read_aepx(&aepx).unwrap_or_else(|e| panic!("{name}: {e}")); - // The save counter is the only difference in the container. - assert_eq!(head_counter(&xml), head_counter(&bin) + 1, "{name}"); - let same = with_head_of(bin.clone().into_owned(), &xml); - assert_eq!(first_difference(&same.chunks, &xml.chunks, ""), None, "{name}"); - assert_eq!(xml.trailer, bin.trailer, "{name}: XMP packet"); - // Even the bytes agree: written as an `.aep`, the tree is the `.aep` with the next save counter. - assert!(write(&xml).unwrap() == write(&same).unwrap(), "{name}: written bytes differ"); - // And the content sniffer picks the right reader for both. - assert_eq!(parse_any(&aepx).unwrap(), xml, "{name}"); - assert_eq!(parse_any(&aep).unwrap(), bin, "{name}"); - } -} - -#[test] -fn the_typed_view_reads_the_same_values() { - for name in PAIRS { - let aep = skip!(crate::common::try_file(&format!("{name}.aep"))); - let aepx = skip!(crate::common::try_file(&format!("{name}.aepx"))); - let bin = parse(&aep).unwrap(); - let xml = read_aepx(&aepx).unwrap(); - let (pb, px) = (Project::new(&bin).unwrap(), Project::new(&xml).unwrap()); - let items = |p: &Project<'_, '_>| p.all_items().iter().map(|i| (i.kind(), i.display_name(), i.id())).collect::>(); - assert_eq!(items(&pb), items(&px), "{name}"); - for (cb, cx) in pb.all_items().iter().filter_map(|i| i.comp()).zip(px.all_items().iter().filter_map(|i| i.comp())) { - assert_eq!(cb.header(), cx.header(), "{name}"); - let layers = |c: &effectcraft_aep::Comp<'_, '_>| c.layers().map(|l| (l.name(), l.header(), l.transform(1920, 1080))).collect::>(); - assert_eq!(layers(&cb), layers(&cx), "{name}"); - } - } - // Spot checks against the values the cases were made with (060's expression, 110's text). - let aepx = skip!(crate::common::try_file("aepx-pair.aepx")); - let xml = read_aepx(&aepx).unwrap(); - assert!(xml.walk().any(|(_, c)| c.is(b"Utf8") && c.bytes() == Some(&b"wiggle(1,10)"[..]))); - assert!(xml.walk().any(|(_, c)| c.is_list(b"btdk") && matches!(c.body, Body::OpaqueList { .. }))); - let names: Vec<_> = Project::new(&xml).unwrap().all_items().iter().filter(|i| i.comp().is_some()).filter_map(|i| i.name()).collect(); - assert_eq!(names, ["000-base", "058-key-opacity-2key", "060-expr-opacity-wiggle", "110-text-A", "124-precomp-Pre", "Pre"]); -} - -#[test] -fn damaged_aepx_is_an_error_or_a_tree_never_a_panic() { - let aepx = skip!(crate::common::try_file("aepx-pair.aepx")); - // Truncation at about 160 points. - for cut in (0..aepx.len()).step_by(aepx.len() / 160) { - let _ = read_aepx(&aepx[..cut]); - } - assert!(read_aepx(&aepx[..aepx.len() / 2]).is_err()); - // Byte flips: each result is an error or a tree that writes and reads back. - let mut state = 0x2545_f491_u32; - for _ in 0..400 { - let mut damaged = aepx.clone(); - for _ in 0..4 { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - let at = state as usize % damaged.len(); - damaged[at] ^= 1 << (state % 8); - } - if let Ok(file) = read_aepx(&damaged) { - let bytes = write(&file).unwrap(); - let _ = Project::new(&parse(&bytes).unwrap()).map(|p| p.all_items().len()); - } - } - // Invalid hex and a damaged entity are errors. - let text = String::from_utf8(aepx.clone()).unwrap(); - let odd = text.replacen("bdata=\"00", "bdata=\"0", 1); - assert!(matches!(read_aepx(odd.as_bytes()), Err(AepError::Xml { .. }))); - let nonhex = text.replacen("bdata=\"00", "bdata=\"0g", 1); - assert!(matches!(read_aepx(nonhex.as_bytes()), Err(AepError::Xml { .. }))); - // Deep nesting is refused at the limit; many elements are bounded. - let deep = format!("{}", "".repeat(1_000_000)); - assert_eq!(read_aepx(deep.as_bytes()), Err(AepError::TooDeep)); - assert_eq!(read_aepx_with_limits(&aepx, Limits { max_depth: 64, max_chunks: 100 }), Err(AepError::TooManyChunks)); - assert_eq!(read_aepx_with_limits(&aepx, Limits { max_depth: 3, max_chunks: 10_000_000 }), Err(AepError::TooDeep)); - // A huge hex body is bounded by the input: nothing is allocated from a declared size. - let huge = format!("", "ab".repeat(1 << 20)); - assert_eq!(read_aepx(huge.as_bytes()).unwrap().chunks[0].bytes().map(<[u8]>::len), Some(1 << 20)); -} - -/// Every pair of the local corpus (not in the repository): `AEP_CORPUS= cargo test -/// --release -p effectcraft-aep --test it container::aepx:: -- --ignored --nocapture`. -#[test] -#[ignore = "needs the local corpus (AEP_CORPUS)"] -fn every_corpus_pair_gives_the_same_chunk_tree() { - let Ok(dir) = std::env::var("AEP_CORPUS") else { return }; - let mut names: Vec<_> = - std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aepx")).collect(); - names.sort(); - let (mut same, mut differ) = (0, Vec::new()); - for x in &names { - let aepx = std::fs::read(x).unwrap(); - let aep = std::fs::read(x.with_extension("aep")).unwrap(); - let bin = parse(&aep).unwrap(); - let xml = match read_aepx(&aepx) { - Ok(f) => f, - Err(e) => { - differ.push(format!("{}: {e}", x.display())); - continue; - } - }; - let fixed = with_head_of(bin.clone().into_owned(), &xml); - match first_difference(&fixed.chunks, &xml.chunks, "") { - None if write(&xml).unwrap() == write(&AepFile { trailer: xml.trailer.clone(), ..fixed }).unwrap() => same += 1, - None => differ.push(format!("{}: bytes differ", x.display())), - Some(d) => differ.push(format!("{}: {d}", x.display())), - } - } - println!("{same} of {} pairs give the same chunk tree", names.len()); - for d in &differ { - println!("{d}"); - } -} diff --git a/crates/aep/tests/it/container/batch3_core.rs b/crates/aep/tests/it/container/batch3_core.rs deleted file mode 100644 index 7b9699e36..000000000 --- a/crates/aep/tests/it/container/batch3_core.rs +++ /dev/null @@ -1,377 +0,0 @@ -//! Batch 3 (core): explicit defaults, multi-component bezier ease, colour key distance, exact time -//! stretch and in / out points, Time Remapping, composition aspect / shutter phase / display start. -//! Every expected value is the value the corpus case was made with (its MANIFEST). - -use crate::container::helpers::{assert_near, base_layer, first_comp, layer_shown_as, layer_with_id, near, open, without_layer_id}; -use effectcraft_aep::{Interpolation, KeyEase, KeyframeKind, LayerHeader, ParamValue, Project, PropNode, Property, Rational, ValueSource}; - -const L: u32 = 0x1b; - -fn with_layer(name: &str, id: u32, f: impl FnOnce(&Project<'_, '_>, &effectcraft_aep::Layer<'_, '_>) -> R) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - // `L` names the base solid, whatever its id in the case. - let layer = if id == L { base_layer(&comp) } else { layer_with_id(&comp, id) }; - f(&project, &layer) - }) -} - -fn header(name: &str) -> Option { - with_layer(name, L, |_, l| l.header().unwrap()) -} - -fn rat(num: i64, den: i64) -> Rational { - Rational { num, den } -} - -fn ease(in_speed: f64, in_influence: f64, out_speed: f64, out_influence: f64) -> KeyEase { - KeyEase { in_speed, in_influence, out_speed, out_influence } -} - -fn same_ease(a: &KeyEase, b: &KeyEase) -> bool { - near(a.in_speed, b.in_speed, 1e-9) - && near(a.in_influence, b.in_influence, 1e-9) - && near(a.out_speed, b.out_speed, 1e-9) - && near(a.out_influence, b.out_influence, 1e-9) -} - -/// The property at a path of match names below a layer. -fn with_property(name: &str, id: u32, path: &[&str], f: impl FnOnce(&Property<'_, '_>) -> R) -> Option { - Some({ - with_layer(name, id, |_, layer| { - let Some(PropNode::Property(p)) = layer.properties().unwrap().find(path) else { panic!("{name}: no property {path:?}") }; - f(&p) - })? - }) -} - -// ------------------------------------------------------------------ explicit defaults (300-304, 311) - -fn blur_param(name: &str) -> Option<(Option, Option, Option, ParamValue, bool)> { - Some({ - with_layer(name, L, |project, layer| { - let effects = layer.effects(); - assert_eq!(effects.len(), 1, "{name}"); - let p = project.effect_params(&effects[0]).into_iter().find(|p| p.name == "Blurriness").unwrap(); - (p.stored_value(), p.pard_default(), p.is_default(), p.value().unwrap(), p.stored().is_some()) - })? - }) -} - -#[test] -fn an_explicit_zero_blurriness_is_a_value_record_and_25_is_the_default() { - // 300: a fresh Gaussian Blur reads back Blurriness 25 (the MANIFEST row 214 "0" was wrong); - // Blurriness set explicitly to 0 writes a record, the default in pard stays 25. - let (stored, default, is_default, value, has_record) = skip!(blur_param("300-fx-gaussianblur-0-explicit.aep")); - assert_eq!((stored, default, value, has_record), (Some(ParamValue::Number(0.0)), Some(ParamValue::Number(25.0)), ParamValue::Number(0.0), true)); - assert_eq!(is_default, Some(false)); - // 301: 25 -> 40 -> 25: the record is removed again, the effective value is the default 25. - let (stored, default, is_default, value, has_record) = skip!(blur_param("301-fx-gaussianblur-40-then-25.aep")); - assert_eq!((stored, default, value, has_record), (None, Some(ParamValue::Number(25.0)), ParamValue::Number(25.0), false)); - assert_eq!(is_default, Some(true)); - // 216 (Blurriness 40): a record, default still 25. - let (stored, default, is_default, value, _) = skip!(blur_param("216-fx-gaussianblur-40.aep")); - assert_eq!((stored, default, value), (Some(ParamValue::Number(40.0)), Some(ParamValue::Number(25.0)), ParamValue::Number(40.0))); - assert_eq!(is_default, Some(false)); -} - -#[test] -fn setting_a_parameter_back_to_its_default_leaves_no_record() { - // 303: Fill Opacity 1 -> 0.5 -> 1 and 302: Opacity set to 1 explicitly: no record, value 1.0 (100 %). - for name in ["302-fx-fill-opacity-100-explicit.aep", "303-fx-fill-opacity-50-then-100.aep"] { - skip!(with_layer(name, L, |project, layer| { - let p = project.effect_params(&layer.effects()[0]).into_iter().find(|p| p.name == "Opacity").unwrap(); - assert!(p.stored().is_none(), "{name}"); - assert_eq!((p.value(), p.is_default()), (Some(ParamValue::Number(1.0)), Some(true)), "{name}"); - })); - } - // 304: Slider set to 0 explicitly: no record, value 0. - skip!(with_layer("304-fx-slider-0-explicit.aep", L, |project, layer| { - let p = project.effect_params(&layer.effects()[0]).into_iter().find(|p| p.name == "Slider").unwrap(); - assert!(p.stored().is_none()); - assert_eq!((p.value(), p.is_default()), (Some(ParamValue::Number(0.0)), Some(true))); - })); - // The implicit input layer and the built-in entry are not "at default" questions. - skip!(with_layer("304-fx-slider-0-explicit.aep", L, |project, layer| { - let params = project.effect_params(&layer.effects()[0]); - assert_eq!(params.len(), 3); - assert_eq!(params[0].is_default(), None); - })); - // 071 (Slider 77) is a record that differs from the default. - skip!(with_layer("071-fx-slider-value77.aep", L, |project, layer| { - let p = project.effect_params(&layer.effects()[0]).into_iter().find(|p| p.name == "Slider").unwrap(); - assert_eq!((p.value(), p.is_default()), (Some(ParamValue::Number(77.0)), Some(false))); - })); -} - -#[test] -fn a_transform_set_to_its_default_adds_no_record() { - // 311: Position set to the value it already had ([960,540,0]): the layer tree is the tree of the - // unedited 299 (which equals the base layer except for the session), no ADBE Position record. - skip!(with_layer("311-position-default-explicit.aep", L, |_, layer| { - let t = layer.transform(1920, 1080).unwrap(); - assert_eq!((t.position.value, t.position.source), ([960.0, 540.0, 0.0], ValueSource::Default)); - assert_eq!(t.opacity_percent.source, ValueSource::Default); - assert!(layer.properties().unwrap().find(&["ADBE Transform Group", "ADBE Position"]).is_none()); - // The two cases are layers of one file: they differ in the layer id only. - let a = without_layer_id(&layer.chunk().to_chunk()); - skip!(with_layer("299-save-noise.aep", L, |_, other| assert_eq!(a, without_layer_id(&other.chunk().to_chunk())))); - })); -} - -// ------------------------------------------------------------------ bezier ease layouts (305-307) - -#[test] -fn scale_keys_keep_their_ease_type_major() { - // 305: Scale keys t=0 [100,100,100] and t=2 [200,150,100]; key1 in speed 0 / influence 33, out - // speed 20 / influence 66; key2 in speed 10 / influence 66, out speed 0 / influence 33. The - // stored speed is a fraction per second (percent / 100), the influence a fraction. - skip!(with_property("305-key-scale-bezier-ease.aep", L, &["ADBE Transform Group", "ADBE Scale"], |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - let scale = p.time_scale().unwrap(); - assert_eq!(keys.iter().map(|k| k.seconds(scale).unwrap()).collect::>(), [0.0, 2.0]); - for k in &keys { - assert_eq!(k.kind(), KeyframeKind::Plain { components: 3 }); - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); - } - assert_near(&keys[0].value().unwrap(), &[1.0, 1.0, 1.0], 1e-9); - assert_near(&keys[1].value().unwrap(), &[2.0, 1.5, 1.0], 1e-9); - // The raw block is [in speed x3][in influence x3][out speed x3][out influence x3]. - for i in 0..3 { - assert!(same_ease(&keys[0].ease_component(i).unwrap(), &ease(0.0, 0.33, 0.2, 0.66)), "key 1 component {i}"); - assert!(same_ease(&keys[1].ease_component(i).unwrap(), &ease(0.1, 0.66, 0.0, 0.33)), "key 2 component {i}"); - } - assert!(keys[0].ease_component(3).is_none()); - assert_eq!(keys[0].ease_components().unwrap().len(), 3); - })); -} - -#[test] -fn mask_feather_keys_keep_their_ease_type_major() { - // 306: Mask Feather keys t=0 [0,0], t=2 [50,30]; key1 in 0/33, out 15/66; key2 in 8/66, out 0/33 - // (speed in pixels per second). - skip!(with_layer("306-key-maskfeather-bezier-ease.aep", L, |_, layer| { - let masks = layer.masks(); - assert_eq!(masks.len(), 1); - assert_eq!(masks[0].feather.source, ValueSource::Keyframed); - assert_eq!(masks[0].feather.value, [0.0, 0.0]); - })); - skip!(with_property("306-key-maskfeather-bezier-ease.aep", L, &["ADBE Mask Parade", "ADBE Mask Atom", "ADBE Mask Feather"], |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - for k in &keys { - assert_eq!(k.kind(), KeyframeKind::Plain { components: 2 }); - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); - } - assert_near(&keys[0].value().unwrap(), &[0.0, 0.0], 1e-9); - assert_near(&keys[1].value().unwrap(), &[50.0, 30.0], 1e-9); - for i in 0..2 { - assert!(same_ease(&keys[0].ease_component(i).unwrap(), &ease(0.0, 0.33, 15.0, 0.66)), "key 1 component {i}"); - assert!(same_ease(&keys[1].ease_component(i).unwrap(), &ease(8.0, 0.66, 0.0, 0.33)), "key 2 component {i}"); - } - assert!(keys[1].ease_component(2).is_none()); - })); -} - -#[test] -fn one_component_and_position_ease_through_the_component_accessor() { - // 205 (Opacity, n = 1): in 0.05 / 0.2, out 0.2 / 0.8; 204 (Position): the single entry. - skip!(with_property("205-key-opacity-ease-asymmetric.aep", L, &["ADBE Transform Group", "ADBE Opacity"], |p| { - let k = p.keys().unwrap().keyframes().next().unwrap(); - assert_eq!(k.ease_component(0), k.ease()); - assert!(same_ease(&k.ease_component(0).unwrap(), &ease(0.05, 0.2, 0.2, 0.8))); - assert!(k.ease_component(1).is_none()); - })); - skip!(with_property("204-key-ease-asymmetric.aep", L, &["ADBE Transform Group", "ADBE Position"], |p| { - let k = p.keys().unwrap().keyframes().next().unwrap(); - assert_eq!(k.ease_component(0), k.ease()); - assert!(k.ease_component(1).is_none()); - assert_eq!(k.ease_components().unwrap().len(), 1); - })); -} - -#[test] -fn bezier_colour_keys_carry_the_distance_to_the_next_key() { - // 307: Fill Color keys t=0 [1,0,0,1] and t=2 [0,0,1,1], both bezier; ease 0/0; f64@16 = the - // ARGB distance 255 sqrt(2) = 360.6245 on key 1 and 0 on the last key. The linear keys of 210 have 0. - skip!(with_layer("307-key-fillcolor-bezier.aep", L, |project, layer| { - let p = project.effect_params(&layer.effects()[0]).into_iter().find(|p| p.name == "Color").unwrap(); - let keys: Vec<_> = p.stored().unwrap().keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - assert_eq!(keys[0].kind(), KeyframeKind::Spatial { components: 4 }); - assert_near(&keys[0].value().unwrap(), &[255.0, 255.0, 0.0, 0.0], 1e-9); - assert_near(&keys[1].value().unwrap(), &[255.0, 0.0, 0.0, 255.0], 1e-9); - for k in &keys { - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); - assert!(same_ease(&k.ease_component(0).unwrap(), &ease(0.0, 0.0, 0.0, 0.0))); - } - let distance = |k: &effectcraft_aep::Keyframe<'_>| k.spatial().unwrap().segment_length; - assert!(near(distance(&keys[0]), 255.0 * 2f64.sqrt(), 1e-3), "{}", distance(&keys[0])); - assert!(near(distance(&keys[0]), 360.6245, 1e-3)); - assert_eq!(distance(&keys[1]), 0.0); - })); - skip!(with_layer("210-key-fill-color-2key-linear.aep", L, |_, layer| { - let p = layer.effects()[0].params().into_iter().find(|p| p.name == "Color").unwrap(); - let k = p.stored().unwrap().keys().unwrap().keyframes().next().unwrap(); - assert_eq!(k.spatial().unwrap().segment_length, 0.0); - })); -} - -// ------------------------------------------------------------------ time stretch and in / out points (316-318, 351, 353) - -fn stretch_facts(name: &str) -> Option<(LayerHeader, Option, Option, u32)> { - Some({ - with_layer(name, L, |_, layer| { - let h = layer.header().unwrap(); - let Some(PropNode::Property(p)) = layer.properties().unwrap().get("ADBE Time Remapping") else { panic!("no time remap property") }; - (h.clone(), h.in_point(), h.out_point(), p.time_scale().unwrap()) - })? - }) -} - -#[test] -fn time_stretch_is_an_exact_ratio() { - // 316: stretch 100 -> 50 %: 1/2; the stored out point stays 5 s, the layer ends at 2.5 s; the - // property time scale stays 25600. - let (h, in_p, out_p, scale) = skip!(stretch_facts("316-layer-stretch50.aep")); - assert_eq!((h.stretch, h.stretch_den), (1, 2)); - assert_eq!(h.stretch_ratio(), Some(rat(1, 2))); - assert_eq!(h.out_relative, rat(128000, 25600)); - assert_eq!((in_p, out_p, scale), (Some(rat(0, 1)), Some(rat(5, 2)), 25600)); - // 317: 150 %: 3/2, ends at 7.5 s, the property time scale is 25600 x 3/2. - let (h, in_p, out_p, scale) = skip!(stretch_facts("317-layer-stretch150.aep")); - assert_eq!((h.stretch, h.stretch_den), (3, 2)); - assert_eq!(h.stretch_ratio(), Some(rat(3, 2))); - assert_eq!((in_p, out_p, scale), (Some(rat(0, 1)), Some(rat(15, 2)), 38400)); - // 018: 200 %: 2/1, ends at 10 s, time scale 51200. The base is 1/1. - let (h, _, out_p, scale) = skip!(stretch_facts("018-layer-stretch200.aep")); - assert_eq!((h.stretch, h.stretch_den, h.stretch_ratio()), (2, 1, Some(rat(2, 1)))); - assert_eq!((out_p, scale), (Some(rat(10, 1)), 51200)); - let (h, _, out_p, scale) = skip!(stretch_facts("000-base.aep")); - assert_eq!((h.stretch, h.stretch_den, h.stretch_ratio()), (1, 1, Some(rat(1, 1)))); - assert_eq!((out_p, scale), (Some(rat(5, 1)), 25600)); -} - -#[test] -fn fractional_times_are_exact_multiples_of_one_over_25600() { - // 318: inPoint 0.3333 s became 8532/25600 = 0.33328125 s; the out point moved with it (duration - // kept): 136532/25600 = 5.33328125 s; start stays 0. - let h = skip!(header("318-layer-inpoint-0.3333.aep")); - assert_eq!(h.in_relative, rat(8532, 25600)); - assert_eq!(h.out_relative, rat(136532, 25600)); - assert_eq!(h.start, rat(0, 25600)); - // 0.33328125 s and 5.33328125 s. - assert_eq!(h.in_point(), Some(rat(2133, 6400))); - assert_eq!(h.out_point(), Some(rat(34133, 6400))); - assert_eq!(h.stretch_ratio(), Some(rat(1, 1))); -} - -#[test] -fn footage_layers_use_the_footage_time_base_as_out_point_denominator() { - // 351: the audio layer's out point is 48000/48000 (the sample rate as denominator), start and - // in point keep 25600; the layer copies the item's label 7 and shows the item's name. - let bytes = fixture!("351-footage-wav-as-layer.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = comp.layers().find(|l| project.layer_source(l).and_then(|s| s.footage()).is_some_and(|f| f.file_type == "WAVE")).unwrap(); - let h = layer.header().unwrap(); - assert_eq!(h.out_relative, rat(48000, 48000)); - assert_eq!((h.start.den, h.in_relative.den), (25600, 25600)); - assert_eq!(h.out_point(), Some(rat(1, 1))); - // The source is the WAV item (item id 0x20 in the single-case file). - assert_eq!(h.label, 7); - assert!(layer.name().is_none()); - assert!(h.is_video_enabled(), "the video switch stays set on an audio-only layer (flag byte 39 = 07)"); - // 354: the image sequence layer: out point 3/30 = 0.1 s (the frame rate as denominator), label 3, - // the layer has no name of its own and shows the first file name. - let bytes = fixture!("354-footage-pngseq-timeremap.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_shown_as(&project, &comp, "seq_001.png"); - let h = layer.header().unwrap(); - assert_eq!(h.out_relative, rat(3, 30)); - assert_eq!(h.out_point(), Some(rat(1, 10))); - assert_eq!((h.label, h.start.den), (3, 25600)); - // The source is the sequence item (item id 0x22 in the single-case file). - assert!(project.layer_source(&layer).and_then(|s| s.footage()).is_some_and(|f| f.is_sequence)); -} - -// ------------------------------------------------------------------ Time Remapping (319, 354) - -#[test] -fn time_remapping_is_an_inert_property_until_enabled() { - // Every layer has an inert ADBE Time Remapping property (tdsb 3, static 0, no keys). - skip!(with_layer("000-base.aep", L, |_, layer| { - let t = layer.time_remap().unwrap(); - assert!(!t.enabled && t.keys.is_empty()); - let Some(PropNode::Property(p)) = layer.properties().unwrap().get("ADBE Time Remapping") else { panic!() }; - assert_eq!((p.flags(), p.is_animated(), p.static_value()), (Some(3), false, Some(vec![0.0]))); - })); - // 319: the precomp layer `Pre` with the remap on: keyed (tdsb 1), two keys 0 s -> 0 and 5 s -> 5; - // the layer inside Pre and the other layers stay inert. - let bytes = fixture!("319-precomp-timeremap.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_shown_as(&project, &comp, "Pre"); - let t = layer.time_remap().unwrap(); - assert!(t.enabled); - assert_eq!(t.keys.len(), 2); - assert_eq!((t.keys[0].time_seconds, t.keys[0].value_seconds), (Some(0.0), 0.0)); - assert_eq!((t.keys[1].time_seconds, t.keys[1].value_seconds), (Some(5.0), 5.0)); - assert_eq!(t.keys[1].time_units, 128000); - let Some(PropNode::Property(p)) = layer.properties().unwrap().get("ADBE Time Remapping") else { panic!() }; - assert_eq!((p.flags(), p.is_animated(), p.static_value()), (Some(1), true, None)); - let pre = project.all_items().into_iter().find(|i| i.name().as_deref() == Some("Pre")).unwrap().comp().unwrap(); - assert!(pre.layers().all(|l| !l.time_remap().unwrap().enabled)); - // 354: on a footage layer: keys 0 s -> 0 and 0.1 s -> 0.1. - let bytes = fixture!("354-footage-pngseq-timeremap.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_shown_as(&project, &comp, "seq_001.png"); - let t = layer.time_remap().unwrap(); - assert!(t.enabled); - assert_eq!(t.keys.len(), 2); - assert_eq!((t.keys[0].time_units, t.keys[0].value_seconds), (0, 0.0)); - assert!(near(t.keys[1].time_seconds.unwrap(), 0.1, 1e-6) && near(t.keys[1].value_seconds, 0.1, 1e-6), "{t:?}"); - assert!(!base_layer(&comp).time_remap().unwrap().enabled); -} - -// ------------------------------------------------------------------ composition (325-327) - -fn comp_header(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - first_comp(&Project::new(&file).unwrap()).header().unwrap() - }) -} - -#[test] -fn pixel_aspect_shutter_phase_and_display_start() { - // 325: pixelAspect 0.9091 reads back 0.90909090909091 = the exact ratio 10/11. - let h = skip!(comp_header("325-comp-pixelaspect-0.9091.aep")); - assert_eq!(h.pixel_aspect.reduced(), Some(rat(10, 11))); - // 326: shutterPhase -90, the shutter angle stays 180. - let h = skip!(comp_header("326-comp-shutterphase-m90.aep")); - assert_eq!((h.shutter_phase, h.shutter_angle), (Some(-90), 180)); - // 327: displayStartFrame 100 at 25 fps = 4 s = 102400/25600; the shutter phase is back to 0. - let h = skip!(comp_header("327-comp-displaystartframe-100.aep")); - assert_eq!(h.display_start, Some(rat(102400, 25600))); - assert_eq!(h.shutter_phase, Some(0)); - // The base: no phase, start 0. - let h = skip!(comp_header("000-base.aep")); - assert_eq!((h.shutter_phase, h.display_start.and_then(|r| r.reduced())), (Some(0), Some(rat(0, 1)))); - assert_eq!(h.pixel_aspect.reduced(), Some(rat(1, 1))); - // A short chunk still decodes the old fields. - let bytes = [0u8; 176]; - let h = effectcraft_aep::CompHeader::parse(&bytes).unwrap(); - assert_eq!((h.shutter_phase, h.display_start.map(|r| r.den)), (None, Some(0))); -} diff --git a/crates/aep/tests/it/container/batch3_objects.rs b/crates/aep/tests/it/container/batch3_objects.rs deleted file mode 100644 index 714938312..000000000 --- a/crates/aep/tests/it/container/batch3_objects.rs +++ /dev/null @@ -1,485 +0,0 @@ -//! Batch 3 (objects): Point / Layer / Dropdown controls, masks, shape items, text styles, camera, -//! light, marker data and footage items. Every expected value is the value the corpus case was -//! made with (its MANIFEST). - -use crate::container::helpers::{assert_near, base_layer, first_comp, layer_named, layer_of_type, layer_shown_as, near, open}; -use effectcraft_aep::{ - Caps, CueType, GradientType, ItemKind, Justification, LayerRef, LayerType, MaskMode, ParamKind, ParamValue, PolystarType, Project, PropNode, Rational, - ShapeDetail, ShapeItem, TextDocument, ValueSource, -}; - -fn rat(num: i64, den: i64) -> Rational { - Rational { num, den } -} - -// ------------------------------------------------------------------ Point control (310, 218) - -#[test] -fn the_point_default_is_a_fraction_of_the_layer() { - // 310: the default Point of a Point Control on a 100x100 solid reads back [50, 50]: the default is - // two 16.16 fractions 0.5 in pard, relative to the layer, not pixels. - let bytes = fixture!("310-solid-100x100-pointcontrol.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_shown_as(&project, &comp, "S100"); - assert_eq!(project.layer_source_size(&layer), Some((100, 100))); - let effects = layer.effects(); - assert_eq!(effects.len(), 1); - let p = effects[0].params().into_iter().find(|p| p.kind == ParamKind::Point).unwrap(); - assert!(p.stored().is_none()); - assert_eq!(p.pard_default(), Some(ParamValue::Point([0.5, 0.5]))); - assert_eq!((p.value(), p.is_default()), (Some(ParamValue::Point([0.5, 0.5])), Some(true))); - assert_eq!(p.point_px(100.0, 100.0), Some([50.0, 50.0])); - assert_eq!(&p.pard()[56..64], &[0, 0, 0x80, 0, 0, 0, 0x80, 0], "two 16.16 fractions 0.5"); - // 218: an explicit [111, 222] on the 1920x1080 solid is [111/1920, 222/1080] of the layer. - let bytes = fixture!("218-fx-point-111-222.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let p = layer.effects()[0].params().into_iter().find(|p| p.kind == ParamKind::Point).unwrap(); - assert_eq!(p.is_default(), Some(false)); - let px = p.point_px(1920.0, 1080.0).unwrap(); - assert_near(&px, &[111.0, 222.0], 1e-9); - assert!(p.point_px(f64::NAN, 1.0).is_some()); - let other = layer.effects()[0].params().into_iter().find(|p| p.kind == ParamKind::Layer).unwrap(); - assert_eq!(other.point_px(1.0, 1.0), None); -} - -// ------------------------------------------------------------------ Layer Control (320, 321, 220) - -/// The Layer Control's reference, the input layer's stored value and reference, the id of `L` -/// (the owner) and the id of the top layer. -#[allow(clippy::type_complexity)] -fn layer_ref(name: &str) -> Option<(Option, Option, Option, u32, u32)> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = base_layer(&comp); - let owner = layer.id().unwrap(); - let effects = layer.effects(); - assert_eq!(effects.len(), 1, "{name}"); - assert_eq!(effects[0].match_name(), "ADBE Layer Control"); - let params = project.effect_params(&effects[0]); - let p = params.iter().find(|p| p.kind == ParamKind::Layer && p.index == 1).unwrap(); - // The implicit input layer is not a layer reference. - (p.layer_ref(owner), params[0].stored_value(), params[0].layer_ref(owner), owner, comp.layers().next().unwrap().id().unwrap()) - }) -} - -#[test] -fn layer_control_self_versus_none() { - // 320: Layer set explicitly to 1 = the layer itself: tdpi = the owning layer's id. - let (r, input, input_ref, owner, _) = skip!(layer_ref("320-fx-layercontrol-self-explicit.aep")); - assert_eq!((r, input, input_ref), (Some(LayerRef::This), Some(ParamValue::Layer(owner)), None)); - // 321: None: tdpi = 0. - let (r, input, input_ref, owner, _) = skip!(layer_ref("321-fx-layercontrol-none.aep")); - assert_eq!((r, input, input_ref), (Some(LayerRef::Nothing), Some(ParamValue::Layer(owner)), None)); - // 220: Layer 1 of a new Null layer (the top layer). - let (r, _, _, owner, top) = skip!(layer_ref("220-fx-layercontrol-to-layer1.aep")); - assert_ne!(top, owner); - assert_eq!(r, Some(LayerRef::Layer(top))); -} - -// ------------------------------------------------------------------ Dropdown (323, 324, 077) - -#[test] -fn dropdown_items_selection_and_count() { - for (name, selected, text, is_default) in - [("323-fx-dropdown-5items.aep", 1, "Alpha", Some(true)), ("324-fx-dropdown-5items-select3.aep", 3, "Gamma", Some(false))] - { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let effects = layer.effects(); - assert_eq!(effects.len(), 1); - // set_dropdown_items re-creates the effect definition under a new match name. - assert!(effects[0].match_name().starts_with("Pseudo/@@") && effects[0].match_name().len() == 31, "{name}"); - assert_eq!(effects[0].name().as_deref(), Some("Dropdown Menu Control")); - let p = effects[0].params().into_iter().find(|p| p.kind == ParamKind::Popup).unwrap(); - assert_eq!(p.items.as_deref(), Some(&["Alpha", "Beta", "Gamma", "Delta", "Epsilon"].map(String::from)[..]), "{name}"); - assert_eq!(p.popup_item_count(), Some(5), "{name}"); - assert_eq!((p.popup_selected_index(), p.popup_selected_item()), (Some(selected), Some(text)), "{name}"); - assert_eq!(p.is_default(), is_default, "{name}"); - assert_eq!(p.stored().is_some(), selected != 1, "{name}"); - if selected == 3 { - // The selection is a value record and also overwrites pard@56. - assert_eq!(p.stored_value(), Some(ParamValue::Index(3))); - assert_eq!(p.pard_default(), Some(ParamValue::Index(3))); - } else { - assert_eq!(p.stored_value(), None); - assert_eq!(p.pard_default(), Some(ParamValue::Index(1))); - } - } - // 077: the default dropdown with three items. - let bytes = fixture!("077-fx-dropdown-default.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let p = layer.effects()[0].params().into_iter().find(|p| p.kind == ParamKind::Popup).unwrap(); - assert_eq!((p.popup_item_count(), p.popup_selected_item()), (Some(3), Some("Item 1"))); - let no_data = layer.effects()[0].params().into_iter().find(|p| p.kind == ParamKind::NoData).unwrap(); - assert_eq!((no_data.popup_item_count(), no_data.popup_selected_index(), no_data.popup_selected_item()), (None, None, None)); -} - -// ------------------------------------------------------------------ masks (309, 328, 329) - -fn ellipse_vertices() -> [[f64; 2]; 4] { - [[960.0, 340.0], [1360.0, 540.0], [960.0, 740.0], [560.0, 540.0]] -} - -#[test] -fn a_mask_box_is_normalised_to_the_layer_size() { - // 309: a 60x40 rectangle at [50,50] on a 100x100 solid: box 0.2, 0.3, 0.8, 0.7 of the LAYER; - // vertices [20,30] [80,30] [80,70] [20,70]. - let bytes = fixture!("309-solid-100x100-mask-rect.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_shown_as(&project, &comp, "S100"); - let masks = layer.masks(); - assert_eq!(masks.len(), 1); - let m = &masks[0]; - assert_eq!((m.mode, m.inverted, m.counter), (Some(MaskMode::Add), Some(false), Some(1))); - let want_box = [0.2, 0.3, 0.8, 0.7]; - for (got, want) in m.shapes[0].bbox.iter().zip(want_box) { - assert!(near(f64::from(*got), want, 1e-6), "{:?}", m.shapes[0].bbox); - } - // The box scales by the size of the layer's source (the importer takes that size from the - // source item it matched, the same item `layer_source_size` reads). - let (w, h) = project.layer_source_size(&layer).unwrap(); - assert_eq!(m.shapes.len(), 1); - let got: Vec<[f64; 2]> = m.shapes[0].vertices((f64::from(w), f64::from(h))).iter().map(|v| v.position).collect(); - for (g, w) in got.iter().zip([[20.0, 30.0], [80.0, 30.0], [80.0, 70.0], [20.0, 70.0]]) { - assert_near(g, &w, 1e-3); - } - assert_eq!(got.len(), 4); - // A layer without a sized source has no size to scale by. - let bytes = fixture!("333-shape-group-two-rects.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let shape = layer_named(&first_comp(&project), "Shape"); - assert!(project.layer_source_size(&shape).is_none()); -} - -#[test] -fn one_mkif_per_mask_and_the_mode_none() { - // 328: ellipse 800x400 at [960,540] (Mask 1) and rectangle 400x300 at [700,500] (Mask 2), both Add; - // the per-layer counter gives 1 and 2. - let bytes = fixture!("328-mask-two-ellipse-rect.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let masks = layer.masks(); - assert_eq!(masks.len(), 2); - assert_eq!(masks.iter().map(|m| m.name.as_deref()).collect::>(), [Some("Mask 1"), Some("Mask 2")]); - for (m, counter) in masks.iter().zip([1, 2]) { - assert_eq!((m.mode, m.inverted, m.counter), (Some(MaskMode::Add), Some(false), Some(counter))); - assert_eq!(m.shapes.len(), 1); - } - let (w, h) = project.layer_source_size(&layer).unwrap(); - let px = |m: &effectcraft_aep::Mask| m.shapes.iter().map(|s| s.vertices((f64::from(w), f64::from(h)))).collect::>(); - let v1 = px(&masks[0]); - for (v, w) in v1[0].iter().zip(ellipse_vertices()) { - assert_near(&v.position, &w, 1e-2); - } - // Mask 2 has its own box (500..900 x 350..650) normalised to the layer. - let v2 = px(&masks[1]); - for (v, w) in v2[0].iter().zip([[500.0, 350.0], [900.0, 350.0], [900.0, 650.0], [500.0, 650.0]]) { - assert_near(&v.position, &w, 1e-2); - } - assert_eq!(v2[0].len(), 4); - // 329: the same ellipse as 232 with the mode None (0). The layer's mask counter is 1: the case is the first mask on its layer. - let bytes = fixture!("329-mask-ellipse-mode-none.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let none = base_layer(&first_comp(&project)).masks(); - assert_eq!(none.len(), 1); - assert_eq!((none[0].mode, none[0].counter), (Some(MaskMode::None), Some(1))); - assert_eq!(MaskMode::from_id(0), MaskMode::None); - let bytes = fixture!("232-mask-ellipse.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let add = base_layer(&first_comp(&project)).masks(); - assert_eq!(add[0].mode, Some(MaskMode::Add)); - assert_eq!(add[0].shapes, none[0].shapes, "329 is 232 with another mode"); -} - -// ------------------------------------------------------------------ shapes (330-333) - -fn shape_group(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_named(&first_comp(&project), "Shape"); - let h = layer.header().unwrap(); - assert_eq!((h.layer_type, h.label), (LayerType::Shape, 8), "{name}"); - let mut groups = layer.shape_groups(); - assert_eq!(groups.len(), 1, "{name}"); - groups.remove(0) - }) -} - -fn other_name(item: &ShapeItem) -> &str { - match item { - ShapeItem::Other { match_name, .. } => match_name, - _ => "", - } -} - -#[test] -fn polystar_defaults_and_polygon() { - // 330: star, 5 points, outer 100, inner 50 = the defaults: no property record at all. - let g = skip!(shape_group("330-shape-polystar-star-5-50-100.aep")); - assert_eq!(g.name.as_deref(), Some("Group 1")); - assert_eq!(g.items.len(), 2); - assert_eq!(other_name(&g.items[0]), "ADBE Vector Shape - Star"); - assert!(matches!(&g.items[1], ShapeItem::Fill { color: Some(c), .. } if c.value == [1.0, 0.0, 1.0, 0.0])); - let [ShapeDetail::Polystar { item_index, star_type, outer_radius, inner_radius, inner_roundness }] = &g.details[..] else { panic!("{:?}", g.details) }; - assert_eq!(*item_index, 0); - assert_eq!((star_type.value, star_type.source), (PolystarType::Star, ValueSource::Default)); - assert_eq!((outer_radius.value, outer_radius.source), (100.0, ValueSource::Default)); - assert_eq!((inner_radius.value, inner_radius.source), (50.0, ValueSource::Default)); - assert!(inner_roundness.is_none()); - // 331: polygon (type 2): the type record, plus Inner Radius 50 and Inner Roundess 0 in their default state. - let g = skip!(shape_group("331-shape-polystar-polygon-5-100.aep")); - let [ShapeDetail::Polystar { star_type, outer_radius, inner_radius, inner_roundness, .. }] = &g.details[..] else { panic!("{:?}", g.details) }; - assert_eq!((star_type.value, star_type.source), (PolystarType::Polygon, ValueSource::Stored)); - assert_eq!((outer_radius.value, outer_radius.source), (100.0, ValueSource::Default)); - assert_eq!((inner_radius.value, inner_radius.source), (50.0, ValueSource::Stored)); - let r = inner_roundness.unwrap(); - assert_eq!((r.value, r.source), (0.0, ValueSource::Stored)); - // The tdsb states: the type is a written record (1), the other two are default-state records (3). - let bytes = fixture!("331-shape-polystar-polygon-5-100.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_named(&first_comp(&project), "Shape"); - let base = ["ADBE Root Vectors Group", "ADBE Vector Group", "ADBE Vectors Group", "ADBE Vector Shape - Star"]; - for (prop, flags) in [("ADBE Vector Star Type", 1), ("ADBE Vector Star Inner Radius", 3), ("ADBE Vector Star Inner Roundess", 3)] { - let path: Vec<&str> = base.iter().copied().chain([prop]).collect(); - let Some(PropNode::Property(p)) = layer.properties().unwrap().find(&path) else { panic!("{prop}") }; - assert_eq!(p.flags(), Some(flags), "{prop}"); - } -} - -#[test] -fn radial_gradient_extra_records() { - // 332: Rectangle Path 400x300 + Gradient Fill, radial (type 2), Start [0,0] = default (absent), - // End [200,0], Highlight Length / Angle 0 written as records. - let g = skip!(shape_group("332-shape-gradient-fill-radial.aep")); - assert_eq!(g.items.len(), 2); - let ShapeItem::GradientFill { start, end, .. } = &g.items[1] else { panic!("{:?}", g.items[1]) }; - assert!(start.is_none()); - assert_eq!(end.map(|e| (e.value, e.source)), Some(([200.0, 0.0], ValueSource::Stored))); - let gradient = g.details.iter().find_map(|d| match d { - ShapeDetail::Gradient { item_index, gradient_type, highlight_length, highlight_angle } => { - Some((*item_index, *gradient_type, *highlight_length, *highlight_angle)) - } - _ => None, - }); - let (index, kind, length, angle) = gradient.unwrap(); - assert_eq!(index, 1); - assert_eq!((kind.value, kind.source), (GradientType::Radial, ValueSource::Stored)); - assert_eq!(length.map(|t| (t.value, t.source)), Some((0.0, ValueSource::Stored))); - assert_eq!(angle.map(|t| (t.value, t.source)), Some((0.0, ValueSource::Stored))); - // 241 (linear): the type is the default and the highlight records are absent. - let bytes = fixture!("241-shape-gradient-fill-linear.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_named(&first_comp(&project), "S"); - let g = layer.shape_groups().remove(0); - let linear = g.details.iter().find_map(|d| match d { - ShapeDetail::Gradient { gradient_type, highlight_length, highlight_angle, .. } => Some((*gradient_type, *highlight_length, *highlight_angle)), - _ => None, - }); - let (kind, length, angle) = linear.unwrap(); - assert_eq!((kind.value, kind.source), (GradientType::Linear, ValueSource::Default)); - assert!(length.is_none() && angle.is_none()); -} - -#[test] -fn two_rectangles_in_one_group_are_two_items() { - // 333: Rectangle Path 1 [400,300], Rectangle Path 2 [100,100] (= default, no Size record) at - // position [300,0], Fill 1 (order: rect, rect, fill). - let g = skip!(shape_group("333-shape-group-two-rects.aep")); - assert_eq!(g.items.len(), 3); - let ShapeItem::Rect { name: n1, size: s1 } = &g.items[0] else { panic!() }; - let ShapeItem::Rect { name: n2, size: s2 } = &g.items[1] else { panic!() }; - assert_eq!((n1.as_deref(), n2.as_deref()), (Some("Rectangle Path 1"), Some("Rectangle Path 2"))); - assert_eq!(s1.map(|s| s.value), Some([400.0, 300.0])); - assert!(s2.is_none(), "[100, 100] is the default size"); - assert!(matches!(&g.items[2], ShapeItem::Fill { color: Some(c), .. } if c.value == [1.0, 0.0, 1.0, 0.0])); - let positions: Vec<_> = g - .details - .iter() - .filter_map(|d| match d { - ShapeDetail::RectPosition { item_index, position } => Some((*item_index, position.value, position.source)), - _ => None, - }) - .collect(); - assert_eq!(positions, [(0, [0.0, 0.0], ValueSource::Default), (1, [300.0, 0.0], ValueSource::Stored)]); -} - -// ------------------------------------------------------------------ text (334-340) - -fn text(name: &str, layer: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - layer_named(&first_comp(&project), layer).text_document().unwrap_or_else(|| panic!("{name}: no text document")) - }) -} - -#[test] -fn right_justification_in_box_text() { - // 334: box text "Hello" in a 400x200 box at [-200,-100], right aligned (stored 1; compare 245: 0, 246: 2). - let t = skip!(text("334-text-box-right-align.aep", "T")); - assert_eq!(t.text, "Hello"); - assert_eq!((t.paragraphs.len(), t.paragraphs[0].length, t.paragraphs[0].justification), (1, 6, Justification::Right)); - let b = t.text_box.unwrap(); - assert_eq!((b.x, b.y, b.width, b.height), (-200.0, -100.0, 400.0, 200.0)); - assert_eq!(skip!(text("245-text-box-400x200-Hello.aep", "T")).paragraphs[0].justification, Justification::Left); - assert_eq!(skip!(text("246-text-box-center-align.aep", "T")).paragraphs[0].justification, Justification::Center); -} - -#[test] -fn faux_styles_caps_and_leading() { - // The reference style: no faux styles, normal caps, auto leading (stored 98), the font list of four. - let t = skip!(text("337-text-point-allcaps.aep", "T")); - assert_eq!(t.style_runs.len(), 1); - let plain = t.style_runs[0]; - assert_eq!((plain.faux_bold, plain.faux_italic, plain.leading, plain.font_index), (false, false, Some(98.0), 0)); - assert_eq!((plain.caps, t.fonts.len()), (Caps::All, 4)); - // 335 / 336: faux bold / italic; the font list gains a first entry (4 -> 5) and the style uses font 1. - for (name, bold, italic) in [("335-text-point-fauxbold.aep", true, false), ("336-text-point-fauxitalic.aep", false, true)] { - let t = skip!(text(name, "T")); - let s = t.style_runs[0]; - assert_eq!((s.faux_bold, s.faux_italic, s.caps), (bold, italic, Caps::Normal), "{name}"); - assert_eq!((t.fonts.len(), s.font_index, t.font_index), (5, 1, 1), "{name}"); - assert_eq!((t.fonts[0].as_str(), t.fonts[1].as_str()), ("TimesNewRomanPSMT", "TimesNewRomanPSMT"), "{name}"); - assert_eq!(t.font.as_deref(), Some("TimesNewRomanPSMT")); - } - // 338: small caps; 337: all caps. - assert_eq!(skip!(text("338-text-point-smallcaps.aep", "T")).style_runs[0].caps, Caps::Small); - // 339: leading 60. - let s = skip!(text("339-text-point-leading60.aep", "T")).style_runs[0]; - assert_eq!((s.leading, s.caps, s.faux_bold), (Some(60.0), Caps::Normal, false)); -} - -#[test] -fn the_last_style_run_absorbs_the_final_carriage_return() { - // 340: "el" red, "lo" blue and size 60 on "Hello": runs of 1, 2 and 3 characters (the last one - // includes the \r), fills white / red / blue, sizes 100 / 100 / 60. - let t = skip!(text("340-text-range-two-styles.aep", "T")); - assert_eq!(t.raw_text, "Hello\r"); - assert_eq!(t.style_runs.iter().map(|r| r.length).collect::>(), [1, 2, 3]); - assert_eq!(t.style_runs.iter().map(|r| r.length).sum::(), t.raw_text.chars().count()); - assert_eq!(t.style_runs.iter().map(|r| r.fill_argb).collect::>(), [[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 1.0]]); - assert_eq!(t.style_runs.iter().map(|r| r.font_size).collect::>(), [100.0, 100.0, 60.0]); - assert_eq!(t.paragraphs.iter().map(|p| p.length).collect::>(), [6]); -} - -// ------------------------------------------------------------------ camera and light (341-345) - -/// Camera zoom keeps the auto position. -#[test] -fn camera_zoom_keeps_the_auto_position() { - // 341: Zoom 2000 is stored (checked on import); the auto Position keeps [0, 0, -2666.67]. - let bytes = fixture!("341-camera-zoom-2000.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_of_type(&first_comp(&project), LayerType::Camera); - let pos = layer.camera_position().unwrap(); - assert!(pos.auto_state && near(pos.stored[2], -2666.67, 0.01) && pos.stored[0] == 0.0, "{:?}", pos.stored); -} - -// ------------------------------------------------------------------ marker data (347-349, 249) - -fn layer_markers(name: &str) -> Option> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - base_layer(&first_comp(&project)).markers() - }) -} - -#[test] -fn marker_label_cue_type_and_parameters() { - // 347: marker at 1 s, comment M, label 3 (event cue by default, no parameters). - let m = skip!(layer_markers("347-marker-layer-label3.aep")); - assert_eq!(m.len(), 1); - assert_eq!((m[0].seconds, m[0].comment.as_str(), m[0].label, m[0].cue_type), (Some(1.0), "M", Some(3), Some(CueType::Event))); - assert_eq!((m[0].duration_seconds, m[0].cue_point_name.as_str(), m[0].cue_params.len()), (Some(0.0), "", 0)); - // 348: cue point name CueN, navigation cue (5). - let m = skip!(layer_markers("348-marker-layer-navigation-cue.aep")); - assert_eq!((m[0].cue_type, m[0].cue_point_name.as_str(), m[0].label), (Some(CueType::Navigation), "CueN", Some(0))); - // 349: CueE, event cue, parameters speaker = A and n = 2. - let m = skip!(layer_markers("349-marker-layer-event-cue-params.aep")); - assert_eq!((m[0].cue_type, m[0].cue_point_name.as_str(), m[0].comment.as_str()), (Some(CueType::Event), "CueE", "M")); - assert_eq!(m[0].cue_params, [("speaker".to_string(), "A".to_string()), ("n".to_string(), "2".to_string())]); - assert_eq!((m[0].chapter.as_str(), m[0].url.as_str(), m[0].frame_target.as_str()), ("", "", "")); - // 249 (batch 2): duration 1 s, the five strings, event cue, no parameters, label 0. - let m = skip!(layer_markers("249-marker-layer-full.aep")); - assert_eq!((m[0].cue_type, m[0].label, m[0].duration_seconds, m[0].cue_params.len()), (Some(CueType::Event), Some(0), Some(1.0), 0)); -} - -// ------------------------------------------------------------------ footage items (126, 350, 352, 354) - -#[test] -fn audio_footage_item() { - let bytes = fixture!("350-footage-wav-imported.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - // The solid L and the WAV (item id 32 in the single-case file): the WAV is not used in a layer. - let footage: Vec<_> = project.all_items().into_iter().filter(|i| i.kind() == Some(ItemKind::Footage)).collect(); - assert_eq!(footage.len(), 2); - let item = footage.iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).unwrap(); - let f = item.footage().unwrap(); - assert_eq!(f.file_type, "WAVE"); - assert_eq!((f.width, f.height, f.is_solid), (0, 0, false)); - assert_eq!(f.duration, Some(rat(48000, 48000))); - assert_eq!((f.audio_sample_rate, f.file_size, f.bits_per_pixel, f.native_frame_rate), (Some(48000.0), 96044, 0, 0)); - assert!(!f.is_sequence && item.sequence_info().is_none()); - // The combined file stores no display name for the item (the single-case file had - // "test-tone.wav"); the path names the file. - assert_eq!(item.label(), Some(7)); - assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test-tone.wav"))); - // The solid has no sample rate. - let solid = footage.iter().find(|i| i.footage().is_some_and(|f| f.is_solid)).unwrap().footage().unwrap(); - assert_eq!((solid.audio_sample_rate, solid.duration.map(|d| d.num), solid.file_size), (None, Some(0), 0)); -} - -#[test] -fn image_sequence_is_one_item() { - for name in ["352-footage-pngseq-imported.aep", "354-footage-pngseq-timeremap.aep"] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let footage: Vec<_> = project.all_items().into_iter().filter(|i| i.kind() == Some(ItemKind::Footage)).collect(); - assert_eq!(footage.len(), 2, "{name}: the solid and ONE sequence item"); - let item = footage.iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).unwrap(); - let f = item.footage().unwrap(); - assert_eq!((f.width, f.height, f.is_solid), (64, 64, false), "{name}"); - assert_eq!(f.duration, Some(rat(3, 30)), "{name}"); - assert_eq!((f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate), (30, 24, 504, None), "{name}"); - assert!(f.is_sequence, "{name}"); - assert_eq!(item.sequence_info().map(|s| s.frame_count()), Some(3), "{name}"); - // The first file name sits in opti; the alias points at the sequence folder. - assert_eq!(f.name.as_deref(), Some("seq_001.png"), "{name}"); - assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test-seq")), "{name}"); - assert_eq!(item.label(), Some(3), "{name}"); - } - // The single png still (126): 32 bits per pixel, 149 bytes, not a sequence, duration 0. - let bytes = fixture!("126-footage-png-layer.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let f = project.all_items().into_iter().filter_map(|i| i.footage()).find(|f| !f.is_solid).unwrap(); - assert_eq!((f.bits_per_pixel, f.file_size, f.native_frame_rate, f.is_sequence), (32, 149, 0, false)); - assert_eq!(f.duration.map(|d| d.num), Some(0)); -} diff --git a/crates/aep/tests/it/container/batch5.rs b/crates/aep/tests/it/container/batch5.rs deleted file mode 100644 index d716c79a7..000000000 --- a/crates/aep/tests/it/container/batch5.rs +++ /dev/null @@ -1,152 +0,0 @@ -//! Batch 5 checks of fields decoded before (markers with several entries and fractional -//! durations, 509 and 510). - -use crate::container::helpers::{first_comp, open}; -use effectcraft_aep::Project; - -#[test] -fn two_composition_markers_in_time_order_with_label_and_duration() { - let bytes = fixture!("509-marker-comp-two.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let m = first_comp(&project).markers(); - let got: Vec<_> = m.iter().map(|m| (m.time_units, m.comment.as_str(), m.duration_seconds, m.label)).collect(); - assert_eq!(got, vec![(25_600, "M1", Some(0.0), Some(2)), (64_000, "M2", Some(0.5), Some(0))]); -} - -#[test] -fn a_fractional_marker_time_and_duration() { - let bytes = fixture!("510-marker-layer-0.52-dur0.3.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = first_comp(&project); - let layer = comp.layers().next().expect("L"); - let m = layer.markers(); - assert_eq!(m.len(), 1); - // 0.52 s = 13 312 / 25 600; 0.3 s = 180 / 600. - assert_eq!((m[0].time_units, m[0].comment.as_str()), (13_312, "LM")); - assert!((m[0].duration_seconds.expect("duration") - 0.3).abs() < 1e-12); -} - -/// The stored value of the property at `path` (match names) of the first layer. -fn shape_value(name: &str, path: &[&str]) -> Option>> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = first_comp(&project); - let layer = comp.layers().next().expect("S"); - match layer.properties()?.find(path)? { - effectcraft_aep::PropNode::Property(p) => p.static_value(), - _ => None, - } - }) -} - -const G1: [&str; 2] = ["ADBE Root Vectors Group", "ADBE Vector Group"]; - -#[test] -fn shape_values_are_stored_as_shown() { - let at = |rest: &[&'static str]| -> Vec<&'static str> { G1.iter().chain(rest.iter()).copied().collect() }; - assert_eq!( - skip!(shape_value("451-shape-ellipse-400x300-fill.aep", &at(&["ADBE Vectors Group", "ADBE Vector Shape - Ellipse", "ADBE Vector Ellipse Size"]))), - Some(vec![400.0, 300.0]) - ); - assert_eq!( - skip!(shape_value("451-shape-ellipse-400x300-fill.aep", &at(&["ADBE Vectors Group", "ADBE Vector Graphic - Fill", "ADBE Vector Fill Color"]))), - Some(vec![255.0, 0.0, 255.0, 0.0]) - ); - // Group scale in percent, not a fraction. - assert_eq!(skip!(shape_value("457-shape-group-scale-50-80.aep", &at(&["ADBE Vector Transform Group", "ADBE Vector Scale"]))), Some(vec![50.0, 80.0])); - assert_eq!( - skip!(shape_value("464-shape-stroke-opacity-50.aep", &at(&["ADBE Vectors Group", "ADBE Vector Graphic - Stroke", "ADBE Vector Stroke Opacity"]))), - Some(vec![50.0]) - ); - assert_eq!( - skip!(shape_value("467-shape-trim-end-70.aep", &at(&["ADBE Vectors Group", "ADBE Vector Filter - Trim", "ADBE Vector Trim End"]))), - Some(vec![70.0]) - ); - assert_eq!( - skip!(shape_value("469-shape-trim-type-2.aep", &at(&["ADBE Vectors Group", "ADBE Vector Filter - Trim", "ADBE Vector Trim Type"]))), - Some(vec![2.0]) - ); - assert_eq!( - skip!(shape_value("471-shape-rect-roundness-30.aep", &at(&["ADBE Vectors Group", "ADBE Vector Shape - Rect", "ADBE Vector Rect Roundness"]))), - Some(vec![30.0]) - ); - assert_eq!( - skip!(shape_value("473-shape-star-points-6.aep", &at(&["ADBE Vectors Group", "ADBE Vector Shape - Star", "ADBE Vector Star Points"]))), - Some(vec![6.0]) - ); - // The shape layer's own anchor: pixels as stored. - assert_eq!(skip!(shape_value("462-shape-layer-anchor-10-20.aep", &["ADBE Transform Group", "ADBE Anchor Point"])), Some(vec![10.0, 20.0, 0.0])); - // A new Trim Paths and every default item of 519 have no record. - for item in - ["ADBE Vector Shape - Rect", "ADBE Vector Shape - Ellipse", "ADBE Vector Shape - Star", "ADBE Vector Graphic - Fill", "ADBE Vector Filter - Trim"] - { - let bytes = fixture!("519-shape-all-items-default.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = first_comp(&project); - let layer = comp.layers().next().expect("S"); - let Some(effectcraft_aep::PropNode::Group(g)) = layer.properties().and_then(|p| p.find(&at(&["ADBE Vectors Group", item]))) else { panic!("{item}") }; - assert!(g.entries().iter().all(|e| !matches!(e.node, effectcraft_aep::PropNode::Property(p) if p.flags() == Some(1))), "{item} has a value record"); - } -} - -/// The baseline option of the first style run of the first text layer. -fn script_of(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = first_comp(&project); - let layer = comp.layers().find(|l| l.text_document().is_some()).expect("a text layer"); - let doc = layer.text_document().expect("document"); - assert!(doc.undecoded_style_fields.is_empty(), "{name}: {:?}", doc.undecoded_style_fields); - doc.style_runs.first().expect("a run").baseline - }) -} - -#[test] -fn superscript_and_subscript_are_style_slot_13() { - use effectcraft_aep::FontBaseline; - // The character state the corpus was made in is superscript (526, and 243, 517). - assert_eq!(skip!(script_of("526-text-point-HHHH-default.aep")), FontBaseline::Superscript); - assert_eq!(skip!(script_of("243-text-multiline-A-CR-B.aep")), FontBaseline::Superscript); - assert_eq!(skip!(script_of("527-text-point-HHHH-baseline-normal.aep")), FontBaseline::Normal); - assert_eq!(skip!(script_of("528-text-point-HHHH-baseline-subscript.aep")), FontBaseline::Subscript); -} - -#[test] -fn a_wrapping_box_text() { - let bytes = fixture!("517-text-box-600x400-wrap.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = first_comp(&project); - let doc = comp.layers().find_map(|l| l.text_document()).expect("text"); - let b = doc.text_box.expect("box text"); - assert_eq!((b.x, b.y, b.width, b.height), (-300.0, -200.0, 600.0, 400.0)); - assert_eq!(doc.raw_text, "The quick brown fox jumps over the lazy dog and keeps running far away\r"); - assert_eq!(doc.style_runs[0].font_size, 100.0); -} - -fn layer_l(name: &str, f: impl Fn(&effectcraft_aep::Layer<'_, '_>) -> T) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = first_comp(&project); - let layer = comp.layers().next().expect("the solid L, the only layer"); - f(&layer) - }) -} - -#[test] -fn orientation_is_otst_otda() { - let o = skip!(layer_l("488-layer-3d-orientation-10-20-30.aep", |l| l.orientation())).expect("orientation"); - assert_eq!((o.degrees, o.animated, o.has_expression), ([10.0, 20.0, 30.0], false, false)); - for name in ["485-layer-3d-on.aep", "486-layer-3d-rotx-30.aep", "487-layer-3d-roty-45.aep"] { - assert_eq!(skip!(layer_l(name, |l| l.orientation())), None, "{name}: absent at the default"); - } -} diff --git a/crates/aep/tests/it/container/cases_600.rs b/crates/aep/tests/it/container/cases_600.rs deleted file mode 100644 index ad6248ecc..000000000 --- a/crates/aep/tests/it/container/cases_600.rs +++ /dev/null @@ -1,186 +0,0 @@ -//! Cases of the 600 series (sessions X1 / X2): a renamed effect instance, a composition that shows -//! two precompositions, image sequences, project settings, a conformed clip and more still types. -//! Every expected value is the one the case was made with (its MANIFEST row). - -use crate::container::helpers::open; -use effectcraft_aep::Project; - -#[test] -fn a_renamed_effect_keeps_its_name_in_the_value_group() { - let bytes = fixture!("610-fx-tint-named-My-Tint.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = project.all_items().into_iter().find_map(|i| i.comp()).expect("comp"); - let layer = comp.layers().next().expect("layer"); - let fx = layer.effects(); - assert_eq!(fx.len(), 1); - assert_eq!(fx[0].match_name(), "ADBE Tint"); - // fnam keeps the effect's own name, the instance name is the value group's tdsn. - assert_eq!(fx[0].name().as_deref(), Some("Tint")); - assert_eq!(fx[0].user_name().as_deref(), Some("My Tint")); - assert_eq!(fx[0].display_name().as_deref(), Some("My Tint")); - // An unnamed instance (356) shows the effect's name. - let bytes = fixture!("356-fx-tint-default.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = project.all_items().into_iter().find_map(|i| i.comp()).expect("comp"); - let fx = comp.layers().next().expect("layer").effects(); - assert_eq!(fx[0].user_name(), None); - assert_eq!(fx[0].display_name().as_deref(), Some("Tint")); -} - -#[test] -fn a_composition_counts_the_compositions_it_shows() { - let bytes = fixture!("601-precomp-two-comps-in-C.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let items = project.all_items(); - let id = |n: &str| items.iter().find(|i| i.display_name().as_deref() == Some(n)).and_then(|i| i.id()).expect(n); - let c = items.iter().find(|i| i.display_name().as_deref() == Some("C")).expect("C"); - // The list holds each used composition once (in no particular order). - let mut used = crate::common::used_item_ids(c); - used.sort(); - let mut want = vec![id("P30"), id("Q")]; - want.sort(); - assert_eq!(used, want); - let idpc = c.chunk().child(b"idpc").and_then(|x| x.bytes()).expect("idpc"); - assert_eq!(&idpc[..4], &2u32.to_le_bytes()); - // The precomposition layers: P30 640x360 30 fps 3 s, Q 320x240 25 fps 2 s. - let comp = c.comp().expect("comp"); - let sizes: Vec<_> = comp.layers().filter_map(|l| project.layer_source_size(&l)).collect(); - assert_eq!(sizes, vec![(320, 240), (640, 360), (1920, 1080)]); -} - -#[test] -fn an_image_sequence_knows_its_numbering() { - // 603: shot_0101.exr .. shot_0103.exr imported as a sequence (64x48, 3 frames at 30 fps). - let bytes = fixture!("603-footage-exrseq-0101-as-layer.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let item = project.all_items().into_iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).expect("sequence"); - let f = item.footage().expect("footage"); - assert_eq!((f.file_type.as_str(), f.width, f.height, f.native_frame_rate, f.is_sequence), ("oEXR", 64, 48, 30, true)); - let s = item.sequence_info().expect("numbering"); - assert_eq!(s.frame_count(), 3); - assert_eq!((s.prefix.as_str(), s.suffix.as_str(), s.start, s.end, s.digits), ("shot_", ".exr", 101, 103, 4)); - assert_eq!(s.file_name(101), "shot_0101.exr"); - // A still has no numbering (000: the solid; the base has no other footage). - let bytes = fixture!("126-footage-png-layer.aep"); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - assert!(project.all_items().iter().all(|i| i.sequence_info().is_none())); -} - -#[test] -fn project_settings_are_read_from_the_header_chunks() { - use effectcraft_aep::{ProjectSettings, TimeDisplay, WorkingSpace}; - let read = |name: &str| { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - ProjectSettings::read(&file) - }) - }; - // The base (620 = 000): 32 bpc, sRGB, gamma 2.2, both linear switches off, compensation on, - // timecode, frames from 0. - let base = skip!(read("000-base.aep")); - assert_eq!( - base, - ProjectSettings { - bits_per_channel: Some(32), - working_space: Some(WorkingSpace::Profile("sRGB IEC61966-2.1".into())), - working_gamma_24: Some(false), - linearize: false, - blend_linear: false, - scene_compensation: Some(true), - time_display: Some(TimeDisplay::Timecode), - frame_start: Some(0), - } - ); - // A project has one value per setting, so the settings cases (MANIFEST 621-634) share three - // files: each holds the base with the changes of all its cases (tests/fixtures/CASES.md). - let a = ProjectSettings { - bits_per_channel: Some(8), - working_space: Some(WorkingSpace::None), - working_gamma_24: Some(true), - scene_compensation: Some(false), - time_display: Some(TimeDisplay::Frames), - frame_start: Some(1), - ..base.clone() - }; - let b = ProjectSettings { linearize: true, blend_linear: true, time_display: Some(TimeDisplay::FeetFrames { frames_per_foot: 16 }), ..base.clone() }; - // The file of 622, 634 and 902 is Rec.709: After Effects 26.2.1 stored the profile without its - // name, so the name is the profile's own description. - let c = ProjectSettings { - bits_per_channel: Some(16), - working_space: Some(WorkingSpace::Profile("Rec.709 Gamma 2.4".into())), - time_display: Some(TimeDisplay::FeetFrames { frames_per_foot: 40 }), - ..base.clone() - }; - for (names, want) in [ - ( - &[ - "621-settings-bpc-8.aep", - "623-settings-workingspace-none.aep", - "625-settings-gamma-2.4.aep", - "628-settings-scene-compensation-off.aep", - "629-settings-time-display-frames.aep", - "630-settings-frame-start-1.aep", - ][..], - a, - ), - (&["632-settings-linearize-and-blend-linear.aep", "633-settings-feet-frames-35.aep"][..], b), - (&["622-settings-bpc-16.aep", "634-settings-feet-frames-16.aep", "902-settings-rec709-16bpc-steps-png-grey-solid.aep"][..], c), - ] { - for name in names { - assert_eq!(skip!(read(name)), want, "{name}"); - } - } // nnhd repeats the depth at byte 24. - for (name, v) in [("621-settings-bpc-8.aep", 0u8), ("622-settings-bpc-16.aep", 1), ("000-base.aep", 2)] { - let bytes = fixture!(name); - let file = open(&bytes); - assert_eq!(file.chunk(b"nnhd").and_then(|c| c.bytes()).and_then(|b| b.get(24).copied()), Some(v), "{name}"); - } -} - -#[test] -fn a_conformed_clip_keeps_its_native_rate_and_frames() { - // 645: the 25 fps, 25-frame mp4 of 606 conformed to 30 fps; 644 the same file unconformed. - let read = |name: &str| { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let item = project.all_items().into_iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).expect("clip"); - let f = item.footage().expect("footage"); - (f.native_frame_rate, item.conform_frame_rate(), f.duration.map(|d| (d.num, d.den))) - }) - }; - assert_eq!(skip!(read("645-footage-mp4-conform-30.aep")), (25, Some(30), Some((25, 25)))); - // Not conformed (the exr sequence 603, the stills of 650-653). - assert_eq!(skip!(read("603-footage-exrseq-0101-as-layer.aep")).1, None); - for name in ["650-footage-tga-still-as-layer.aep", "651-footage-psd-flat-as-layer.aep", "652-footage-ai-as-layer.aep", "653-footage-eps-as-layer.aep"] { - assert_eq!(skip!(read(name)).1, None, "{name}"); - } -} - -#[test] -fn still_footage_of_four_more_types() { - // 650-653: a 64 x 48 tga, a flat psd, an ai and an eps imported as footage (MANIFEST); ai and - // eps share the type tag `TEXT`. - for (name, tag) in [ - ("650-footage-tga-still-as-layer.aep", "TPIC"), - ("651-footage-psd-flat-as-layer.aep", "8BPS"), - ("652-footage-ai-as-layer.aep", "TEXT"), - ("653-footage-eps-as-layer.aep", "TEXT"), - ] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let f = project.all_items().into_iter().find_map(|i| i.footage().filter(|f| !f.is_solid)).expect(name); - assert_eq!((f.width, f.height, f.native_frame_rate, f.is_sequence), (64, 48, 0, false), "{name}"); - assert_eq!(f.file_type, tag, "{name}"); - let ext = name.get(12..).and_then(|r| r.split('-').next()).unwrap_or_default(); - assert!(f.path.as_deref().is_some_and(|p| p.ends_with(&format!("still.{ext}"))), "{name}: {:?}", f.path); - } -} diff --git a/crates/aep/tests/it/container/ease_round2.rs b/crates/aep/tests/it/container/ease_round2.rs deleted file mode 100644 index 89cf20a2c..000000000 --- a/crates/aep/tests/it/container/ease_round2.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Ease of Anchor Point, effect point and colour, and mask path keys (597-599, 700, 730); light -//! type codes (701, 702). - -use crate::container::helpers::{first_comp, layer_shown_as, open}; -use effectcraft_aep::{KeyframeKind, Project}; - -#[test] -fn mask_path_keys_keep_their_ease_at_byte_24() { - for (name, first_out, last_in) in [("599-key-mask-path-ease-infl75.aep", 0.75, 0.75), ("700-key-mask-path-ease-out20-in50.aep", 0.2, 0.5)] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_shown_as(&project, &comp, "L"); - let atoms = layer.mask_atoms(); - let list = atoms[0].path.as_ref().and_then(|p| p.keys()).expect("path keys"); - let keys: Vec<_> = list.keyframes().collect(); - assert_eq!(keys.len(), 2); - assert_eq!(keys[0].kind(), KeyframeKind::MaskPath); - let (a, b) = (keys[0].ease().unwrap(), keys[1].ease().unwrap()); - assert_eq!((a.out_speed, a.out_influence), (0.0, first_out), "{name}"); - assert_eq!((b.in_speed, b.in_influence), (0.0, last_in), "{name}"); - } -} - -#[test] -fn a_spatial_speed_is_divided_by_the_layer_height() { - // 597: 1920x1080 L, out speed 50 px/s stored as 50 / 1080; 730: 400x800 P, 50 / 800. - for (name, layer, h) in [("597-key-anchor-ease-out50-40-in30-60.aep", "L", 1080.0), ("730-key-anchor-ease-on-400x800-solid.aep", "P", 800.0)] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let props = layer_shown_as(&project, &comp, layer).properties().unwrap(); - let Some(effectcraft_aep::PropNode::Group(t)) = props.get("ADBE Transform Group") else { panic!() }; - let Some(effectcraft_aep::PropNode::Property(a)) = t.get("ADBE Anchor Point") else { panic!() }; - let keys: Vec<_> = a.keys().unwrap().keyframes().collect(); - let (e0, e1) = (keys[0].ease().unwrap(), keys[1].ease().unwrap()); - assert!((e0.out_speed * h - 50.0).abs() < 1e-9 && (e1.in_speed * h - 30.0).abs() < 1e-9, "{name}: {e0:?} {e1:?}"); - assert_eq!((e0.out_influence, e1.in_influence), (0.4, 0.6)); - } -} - -#[test] -fn parallel_and_ambient_lights_have_codes_0_and_3() { - use effectcraft_aep::{LayerType, LightType}; - for (name, want) in [("701-light-parallel-int80-color.aep", LightType::Parallel), ("702-light-ambient-int50-color.aep", LightType::Ambient)] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let light = comp.layers().find(|l| l.header().is_some_and(|h| h.layer_type == LayerType::Light)).expect("light"); - assert_eq!(light.header().unwrap().light_type(), Some(want), "{name}"); - } -} - -#[test] -fn keyed_orientation_pairs_records_and_values() { - use effectcraft_aep::Interpolation; - let bytes = fixture!("703-key-orientation-0-to-10-20-30-linear.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_shown_as(&project, &comp, "L"); - assert!(layer.orientation().unwrap().animated); - let keys = layer.orientation_keys(); - assert_eq!(keys.iter().map(|k| (k.time_units, k.degrees)).collect::>(), [(0, [0.0; 3]), (51200, [10.0, 20.0, 30.0])]); - assert!(keys.iter().all(|k| k.interpolation_in == Interpolation::Linear && k.interpolation_out == Interpolation::Linear)); -} diff --git a/crates/aep/tests/it/container/effects.rs b/crates/aep/tests/it/container/effects.rs deleted file mode 100644 index 93e4b0e55..000000000 --- a/crates/aep/tests/it/container/effects.rs +++ /dev/null @@ -1,292 +0,0 @@ -//! Effect instances: match names, parameter lists from `parT`/`pard` and stored values, checked -//! against the values the corpus was made with (its MANIFEST). - -use crate::container::helpers::{base_layer, first_comp, open}; -use effectcraft_aep::{Effect, ParamKind, ParamValue, Project}; - -/// Runs `f` on the single effect of the solid `L` in a fixture. -fn with_effect(name: &str, f: impl FnOnce(&Effect<'_, '_>) -> R) -> Option { - with_effect_in(name, |_, _, e| f(e)) -} - -/// Runs `f` on the project, the solid `L` and its single effect in a fixture. -fn with_effect_in(name: &str, f: impl FnOnce(&Project<'_, '_>, &effectcraft_aep::Layer<'_, '_>, &Effect<'_, '_>) -> R) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let effects = layer.effects(); - assert_eq!(effects.len(), 1, "{name}"); - f(&project, &layer, &effects[0]) - }) -} - -fn kinds(e: &Effect<'_, '_>) -> Vec<(ParamKind, String)> { - e.params().into_iter().map(|p| (p.kind, p.name)).collect() -} - -fn approx(v: Option, expected: f64) { - match v { - Some(ParamValue::Number(n)) => assert!((n - expected).abs() < 1e-9, "{n} != {expected}"), - other => panic!("{other:?} is not the number {expected}"), - } -} - -#[test] -fn no_effects_without_a_parade_entry() { - let bytes = fixture!("000-base.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - assert!(base_layer(&first_comp(&project)).effects().is_empty()); -} - -#[test] -fn slider_control_with_a_stored_value() { - // 071: Slider Control, Slider = 77. - skip!(with_effect_in("071-fx-slider-value77.aep", |_, layer, e| { - assert_eq!((e.match_name(), e.name().as_deref()), ("ADBE Slider Control", Some("Slider Control"))); - assert_eq!(e.declared_param_count(), Some(3)); - assert_eq!(kinds(e), [(ParamKind::Layer, String::new()), (ParamKind::FloatSlider, "Slider".to_string()), (ParamKind::NoData, String::new())]); - let params = e.params(); - assert_eq!(params[1].match_name, "ADBE Slider Control-0001"); - assert_eq!(params[2].match_name, "ADBE Effect Built In Params"); - assert_eq!(params[1].stored_value(), Some(ParamValue::Number(77.0))); - assert_eq!(params[1].value(), Some(ParamValue::Number(77.0))); - // The pard default of the slider is 0 (070 has the untouched control). - assert_eq!(params[1].pard_default(), Some(ParamValue::Number(0.0))); - // The input layer parameter has a value record of its own: its `tdpi` holds the id of the layer that owns the effect. - assert_eq!(params[0].stored_value(), Some(ParamValue::Layer(layer.id().unwrap()))); - assert_eq!(params[0].pard().len(), 148); - })); -} - -#[test] -fn color_control_stores_argb_doubles() { - // 073: Color -> [0.2, 0.6, 1], stored as [255, 51, 153, 255] (alpha first). - skip!(with_effect("073-fx-color-0.2-0.6-1.aep", |e| { - assert_eq!((e.match_name(), e.name().as_deref()), ("ADBE Color Control", Some("Color Control"))); - assert_eq!(kinds(e), [(ParamKind::Layer, String::new()), (ParamKind::Color, "Color".to_string()), (ParamKind::NoData, String::new())]); - let color = e.params()[1].value(); - let Some(ParamValue::Argb([a, r, g, b])) = color else { panic!("{color:?}") }; - for (got, want) in [(a, 1.0), (r, 0.2), (g, 0.6), (b, 1.0)] { - assert!((got - want).abs() < 1e-6, "{color:?}"); - } - })); -} - -#[test] -fn dropdown_menu_items_and_default() { - // 077: Dropdown Menu Control with the default items. - skip!(with_effect("077-fx-dropdown-default.aep", |e| { - // A dropdown's match name is a fresh `Pseudo/@@` + 22-character id for every instance. - assert!(e.match_name().starts_with("Pseudo/@@") && e.match_name().len() == 31, "{}", e.match_name()); - assert_eq!(e.name().as_deref(), Some("Dropdown Menu Control")); - assert_eq!(kinds(e), [(ParamKind::Layer, String::new()), (ParamKind::Popup, "Menu".to_string()), (ParamKind::NoData, String::new())]); - let menu = &e.params()[1]; - assert_eq!(menu.items.as_deref(), Some(&["Item 1".to_string(), "Item 2".to_string(), "Item 3".to_string()][..])); - assert_eq!(menu.pard_default(), Some(ParamValue::Index(1))); - // The choice count is the u16 at byte 60 of pard. - assert_eq!(u16::from_be_bytes([menu.pard()[60], menu.pard()[61]]), 3); - // No other parameter has items. - assert!(e.params().iter().filter(|p| p.index != 1).all(|p| p.items.is_none())); - })); -} - -#[test] -fn drop_shadow_defaults_come_from_pard() { - // 080: Drop Shadow at its defaults (opacity 50 % = 127.5 of 255, direction 135, distance 5, softness 0). - skip!(with_effect("080-fx-dropshadow-default.aep", |e| { - assert_eq!((e.match_name(), e.name().as_deref()), ("ADBE Drop Shadow", Some("Drop Shadow"))); - let k: Vec<_> = e.params().into_iter().map(|p| (p.kind, p.name)).collect(); - let expected = [ - (ParamKind::Layer, ""), - (ParamKind::Color, "Shadow Color"), - (ParamKind::FixedSlider, "Opacity"), - (ParamKind::Angle, "Direction"), - (ParamKind::FixedSlider, "Distance"), - (ParamKind::FixedSlider, "Softness"), - (ParamKind::Checkbox, "Shadow Only"), - (ParamKind::NoData, ""), - ]; - assert_eq!(k, expected.map(|(kind, n)| (kind, n.to_string()))); - let p = e.params(); - approx(p[2].value(), 127.5); - approx(p[3].value(), 135.0); - approx(p[4].value(), 5.0); - approx(p[5].value(), 0.0); - // A checkbox without a record is off; the shadow colour default (ARGB bytes in pard) is black. - assert_eq!(p[6].value(), Some(ParamValue::Bool(false))); - assert_eq!(p[1].value(), Some(ParamValue::Argb([1.0, 0.0, 0.0, 0.0]))); - })); -} - -// ---------------------------------------------------------------------------- batch 2 (defaults and values) - -fn param<'f, 'a>(e: &Effect<'f, 'a>, name: &str) -> effectcraft_aep::EffectParam<'f, 'a> { - e.params().into_iter().find(|p| p.name == name).unwrap_or_else(|| panic!("no parameter {name}")) -} - -#[test] -fn gaussian_blur_default_is_the_pard_default_25() { - // 214: Gaussian Blur, all parameters default. The file has no value record and a pard default of 25 - // (the manifest says 0; the files only ever contain 25, see docs/aep-format.md). - skip!(with_effect("214-fx-gaussianblur-default.aep", |e| { - assert_eq!(e.match_name(), "ADBE Gaussian Blur 2"); - let blur = param(e, "Blurriness"); - assert_eq!(blur.kind, ParamKind::FloatSlider); - assert!(blur.stored().is_none()); - assert_eq!(blur.stored_value(), None); - assert_eq!(blur.value(), Some(ParamValue::Number(25.0))); - assert_eq!(f64::from_be_bytes(blur.pard()[56..64].try_into().unwrap()), 25.0); - assert_eq!(f32::from_be_bytes(blur.pard()[120..124].try_into().unwrap()), 25.0); - // Dimensions: Horizontal and Vertical (the first item of the popup); Repeat Edge Pixels: on - // (its pard default is 1; After Effects reads a fresh Gaussian Blur back with Repeat Edge - // Pixels 1, 417; the corpus manifest's "off" for 214 was wrong). - let dims = param(e, "Blur Dimensions"); - assert_eq!(dims.kind, ParamKind::Popup); - assert_eq!(dims.value(), Some(ParamValue::Index(1))); - assert_eq!(dims.items.as_ref().and_then(|i| i.first()).map(String::as_str), Some("Horizontal and Vertical")); - // The last parameter is the Repeat Edge Pixels checkbox (its label is not in pard). - let edge = &e.params()[3]; - assert_eq!(edge.kind, ParamKind::Checkbox); - assert!(edge.stored().is_none()); - assert_eq!(edge.value(), Some(ParamValue::Bool(true))); - })); -} - -#[test] -fn gaussian_blur_40_adds_a_value_record_and_leaves_pard_at_the_default() { - // 216: Blurriness 40. - // The case takes its definitions from the project copy (an earlier Gaussian Blur of its file). - skip!(with_effect_in("216-fx-gaussianblur-40.aep", |project, _, e| { - let blur = project.effect_params(e).into_iter().find(|p| p.name == "Blurriness").unwrap(); - assert_eq!(blur.stored().unwrap().flags(), Some(1)); - assert_eq!(blur.stored_value(), Some(ParamValue::Number(40.0))); - assert_eq!(blur.value(), Some(ParamValue::Number(40.0))); - // pard holds the default, not the current value. - assert_eq!(blur.pard_default(), Some(ParamValue::Number(25.0))); - })); -} - -#[test] -fn fill_defaults_come_from_pard() { - // 215: Fill with the default colour (red) and opacity (100 %); the file has no value records for them. - skip!(with_effect("215-fx-fill-default.aep", |e| { - assert_eq!(e.match_name(), "ADBE Fill"); - let color = param(e, "Color"); - assert_eq!(color.kind, ParamKind::Color); - assert!(color.stored().is_none()); - assert_eq!(&color.pard()[56..60], [0xff, 0xff, 0x00, 0x00]); - assert_eq!(color.value(), Some(ParamValue::Argb([1.0, 1.0, 0.0, 0.0]))); - let opacity = param(e, "Opacity"); - assert_eq!(opacity.kind, ParamKind::FixedSlider); - assert!(opacity.stored().is_none()); - assert_eq!(opacity.value(), Some(ParamValue::Number(1.0))); - })); -} - -#[test] -fn checkbox_point_and_angle_values() { - // 217: Checkbox 0 -> 1 (stored 1.0). - skip!(with_effect("217-fx-checkbox-on.aep", |e| { - let p = param(e, "Checkbox"); - assert_eq!(p.kind, ParamKind::Checkbox); - assert_eq!(p.stored_value(), Some(ParamValue::Bool(true))); - assert_eq!(p.value(), Some(ParamValue::Bool(true))); - assert_eq!(p.stored().unwrap().static_value(), Some(vec![1.0])); - })); - // 218: Point -> [111, 222], stored as a fraction of the layer size (the layer is 1920x1080). - skip!(with_effect("218-fx-point-111-222.aep", |e| { - let p = param(e, "Point"); - assert_eq!(p.kind, ParamKind::Point); - let Some(ParamValue::Point([x, y])) = p.value() else { panic!("{:?}", p.value()) }; - assert!((x - 111.0 / 1920.0).abs() < 1e-12 && (y - 222.0 / 1080.0).abs() < 1e-12, "{x} {y}"); - assert!((x * 1920.0 - 111.0).abs() < 1e-9 && (y * 1080.0 - 222.0).abs() < 1e-9); - })); - // 219: Angle -> 90, stored as plain degrees. - skip!(with_effect("219-fx-angle-90.aep", |e| { - let p = param(e, "Angle"); - assert_eq!(p.kind, ParamKind::Angle); - assert_eq!(p.stored_value(), Some(ParamValue::Number(90.0))); - assert_eq!(p.value(), Some(ParamValue::Number(90.0))); - })); -} - -#[test] -fn layer_control_refers_to_a_layer_by_id() { - // 220: a new Null on top (layer index 1); L (now index 2) gets a Layer Control with Layer = 1: the tdpi - // next to the value record holds the id of the Null. - let bytes = fixture!("220-fx-layercontrol-to-layer1.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let null = comp.layers().next().unwrap(); - let null_id = null.id().unwrap(); - assert_ne!(Some(null_id), base_layer(&comp).id()); - assert!(null.header().unwrap().is_null_object()); - let layer = base_layer(&comp); - let e = &layer.effects()[0]; - assert_eq!(e.match_name(), "ADBE Layer Control"); - let p = param(e, "Layer"); - assert_eq!(p.kind, ParamKind::Layer); - assert_eq!(p.stored_value(), Some(ParamValue::Layer(null_id))); - // The implicit input layer parameter refers to the layer that owns the effect. - assert_eq!(e.params()[0].stored_value(), Some(ParamValue::Layer(layer.id().unwrap()))); -} - -#[test] -fn curves_and_mesh_warp_data() { - // 963: Red (0,0) (128,44) (255,255); 964: RGB (0,0) (62,24) (194,230) (255,255). Every stored - // table is the natural spline through its points. - for (name, curve, points) in [ - ("963-curves-red-mid-down-on-S.aep", 1usize, vec![(0u8, 0u8), (128, 44), (255, 255)]), - ("964-curves-rgb-s-curve-on-S.aep", 0, vec![(0, 0), (62, 24), (194, 230), (255, 255)]), - ] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = effectcraft_aep::Project::new(&file).expect("project"); - let comp = first_comp(&project); - let fx = comp.layers().flat_map(|l| l.effects()).find(|e| e.match_name() == "ADBE CurvesCustom").expect("curves"); - let data = fx.arbitrary_data("ADBE CurvesCustom-0001").expect("data"); - let d = effectcraft_aep::CurvesData::parse(data).expect("parse"); - assert_eq!(d.curves[curve], points, "{name}"); - assert!(d.curves.iter().enumerate().all(|(i, c)| i == curve || c.as_slice() == effectcraft_aep::CURVE_IDENTITY), "{name}"); - // Rebuilt from the points, the data is the stored data byte for byte. - assert_eq!(d.to_bytes().as_deref(), Some(data), "{name}"); - } - // 985: a 3 x 3 mesh (4 x 4 vertices), vertex (2, 2) moved by (+132, -2) px on 1920 x 1080 with - // its handles; the others at their default. - let bytes = fixture!("985-meshwarp-3x3-vertex-moved-on-S.aep"); - let file = open(&bytes); - let project = effectcraft_aep::Project::new(&file).expect("project"); - let comp = first_comp(&project); - let fx = comp.layers().flat_map(|l| l.effects()).find(|e| e.match_name() == "ADBE MESH WARP").expect("mesh"); - let data = fx.arbitrary_data("ADBE MESH WARP-0004").expect("data"); - let m = effectcraft_aep::MeshData::parse(data).expect("parse"); - assert_eq!((m.columns, m.rows, m.vertices.len()), (3, 3, 16)); - for (k, v) in m.vertices.iter().enumerate() { - let (i, j) = (k as u32 % 4, k as u32 / 4); - let d = effectcraft_aep::MeshData::default_vertex(3, 3, i, j); - let (dx, dy) = if (i, j) == (2, 2) { (132.0 / 1920.0, -2.0 / 1080.0) } else { (0.0, 0.0) }; - for (a, b) in v.iter().zip(&d) { - let moved = if *b == [0.0, 0.0] { [0.0, 0.0] } else { [b[0] + dx, b[1] + dy] }; - assert!((a[0] - moved[0]).abs() < 2e-6 && (a[1] - moved[1]).abs() < 2e-6, "vertex {i},{j}: {a:?} vs {moved:?}"); - } - } - assert_eq!(m.to_bytes().as_deref(), Some(data)); -} - -#[test] -fn the_fx_switch_is_the_value_group_flag() { - // fx-switch.aep: two Gaussian Blurs on L, the first switched off in After Effects, the second - // added after it and left on (one save). - let bytes = skip!(crate::common::try_file("fx-switch.aep")); - let file = open(&bytes); - let p = Project::new(&file).expect("project"); - let comp = first_comp(&p); - let layer = base_layer(&comp); - let fx = layer.effects(); - assert_eq!(fx.iter().map(|e| e.match_name().to_string()).collect::>(), ["ADBE Gaussian Blur 2", "ADBE Gaussian Blur 2"]); - assert_eq!(fx.iter().map(Effect::enabled).collect::>(), [Some(false), Some(true)]); -} diff --git a/crates/aep/tests/it/container/effects_batch4.rs b/crates/aep/tests/it/container/effects_batch4.rs deleted file mode 100644 index c53ce8ae8..000000000 --- a/crates/aep/tests/it/container/effects_batch4.rs +++ /dev/null @@ -1,307 +0,0 @@ -//! Batch 4 (cases 356-383): Tint and Gradient Ramp parameters, their defaults, values, keys and -//! scales, the effect stack order, and the second instance of an effect type whose `parT` is -//! empty. Every expected value is the one the case was made with (its MANIFEST row). - -use crate::container::helpers::{assert_near, base_layer, first_comp, open}; -use effectcraft_aep::{DefinitionSource, EffectParam, Interpolation, KeyframeKind, ParamKind, ParamValue, Project}; - -/// Key time 2 s in the property timescale 25600. -const T2: i32 = 51200; - -/// Runs `f` on the project view and the parameters of the single effect of `L`. -fn with_params(name: &str, f: impl FnOnce(&Project<'_, '_>, &[EffectParam<'_, '_>]) -> R) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let effects = layer.effects(); - assert_eq!(effects.len(), 1, "{name}"); - // The first instance of a type in the combined file (the case that adds it at its defaults) - // keeps its own definitions; the later cases read the project copy. - let first = ["356-fx-tint-default.aep", "368-fx-ramp-default.aep", "389-fx-exposure-default.aep"].contains(&name); - let want = if first { DefinitionSource::Instance } else { DefinitionSource::Project }; - assert_eq!(project.definition_source(&effects[0]), want, "{name}"); - let params = project.effect_params(&effects[0]); - f(&project, ¶ms) - }) -} - -fn argb(v: Option) -> [f64; 4] { - match v { - Some(ParamValue::Argb(c)) => c, - other => panic!("{other:?} is not a colour"), - } -} - -fn point(v: Option) -> [f64; 2] { - match v { - Some(ParamValue::Point(p)) => p, - other => panic!("{other:?} is not a point"), - } -} - -fn number(v: Option) -> f64 { - match v { - Some(ParamValue::Number(n)) => n, - other => panic!("{other:?} is not a number"), - } -} - -/// The colour as the case set it: float32 precision (0.2 becomes 0.20000000298). -const F32: f64 = 1e-6; - -// ---------------------------------------------------------------------------- Tint - -#[test] -fn tint_parameters_and_defaults() { - // 356: Tint with every parameter at its default. - let bytes = fixture!("356-fx-tint-default.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let fx = base_layer(&first_comp(&project)).effects(); - let e = &fx[0]; - assert_eq!((e.match_name(), e.name().as_deref()), ("ADBE Tint", Some("Tint"))); - assert_eq!(e.declared_param_count(), Some(6)); - let p = project.effect_params(e); - let kinds: Vec<_> = p.iter().map(|p| (p.kind, p.name.as_str())).collect(); - assert_eq!( - kinds, - [ - (ParamKind::Layer, ""), - (ParamKind::Color, "Map Black To"), - (ParamKind::Color, "Map White To"), - (ParamKind::FixedSlider, "Amount to Tint"), - (ParamKind::Button, ""), - (ParamKind::NoData, ""), - ] - ); - assert_eq!(p[4].match_name, "ADBE Tint-0004"); - // The defaults have alpha 0 (what After Effects reads back: [0,0,0,0] / [1,1,1,0]). - assert_eq!(p[1].value(), Some(ParamValue::Argb([0.0, 0.0, 0.0, 0.0]))); - assert_eq!(p[2].value(), Some(ParamValue::Argb([0.0, 1.0, 1.0, 1.0]))); - assert!(p[1].stored().is_none() && p[2].stored().is_none() && p[3].stored().is_none()); - // Amount to Tint: 100 percent, stored as a plain percent (valid max 100). - assert_eq!(p[3].value(), Some(ParamValue::Number(100.0))); - assert_eq!(p[3].valid_max(), Some(100.0)); - // Swap Colors: a button whose record always exists and holds no value; its label is in pdnm. - assert!(p[4].stored().is_some()); - assert_eq!(p[4].value(), None); - assert_eq!(p[4].is_default(), None); - assert_eq!(p[4].items.as_deref(), Some(&["Swap Colors".to_string()][..])); - assert!(p.iter().all(|p| !p.borrowed_definition && !p.is_animated())); -} - -#[test] -fn tint_colour_and_amount_values() { - // 357: Map Black To [0.2, 0.4, 0.6], stored with alpha 255. - skip!(with_params("357-fx-tint-black-0.2-0.4-0.6.aep", |_, p| { - assert_near(&argb(p[1].stored_value()), &[1.0, 0.2, 0.4, 0.6], F32); - assert_eq!(p[1].is_default(), Some(false)); - assert_eq!(p[2].value(), Some(ParamValue::Argb([0.0, 1.0, 1.0, 1.0]))); - })); - // 361: Amount to Tint 0 writes a record with 0. - skip!(with_params("361-fx-tint-amount-0.aep", |_, p| { - assert_eq!(p[3].stored_value(), Some(ParamValue::Number(0.0))); - assert_eq!(p[3].is_default(), Some(false)); - })); -} - -#[test] -fn tint_keyframes() { - // 363: Amount to Tint keyed 20 at 0 s, 80 at 2 s, linear: plain 48-byte records. - skip!(with_params("363-fx-tint-amount-2key.aep", |_, p| { - let amount = &p[3]; - assert!(amount.is_animated()); - assert_eq!(amount.stored_value(), None); - let keys: Vec<_> = amount.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - assert_eq!(keys.iter().map(|k| k.time_units().unwrap()).collect::>(), [0, T2]); - assert_eq!(keys.iter().map(|k| k.scalar_value().unwrap()).collect::>(), [20.0, 80.0]); - assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Plain { components: 1 } && k.interpolation_out() == Some(Interpolation::Linear))); - })); - // 364: Map White To keyed [1,1,0] -> [0,0,1]: 152-byte colour records, ARGB 0..255. - skip!(with_params("364-fx-tint-white-2key.aep", |_, p| { - let white = &p[2]; - assert!(white.is_animated()); - let keys: Vec<_> = white.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Spatial { components: 4 } && k.raw().len() == 152)); - assert_eq!(keys.iter().map(|k| k.time_units().unwrap()).collect::>(), [0, T2]); - assert_near(&keys[0].value().unwrap(), &[255.0, 255.0, 255.0, 0.0], 1e-9); - assert_near(&keys[1].value().unwrap(), &[255.0, 0.0, 0.0, 255.0], 1e-9); - })); -} - -#[test] -fn effect_stack_order_is_the_parade_order() { - // 366: Gaussian Blur moved above the Tint. - let bytes = fixture!("366-fx-blur-then-tint.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let fx = base_layer(&first_comp(&project)).effects(); - assert_eq!(fx.iter().map(|e| e.match_name()).collect::>(), ["ADBE Gaussian Blur 2", "ADBE Tint"]); - // Both types first appear in earlier cases of the combined file (214, 356), so both read the - // project copy, which holds one copy per type. - assert!(fx.iter().all(|e| project.definition_source(e) == DefinitionSource::Project)); - let defs: Vec = project.effect_definitions().into_iter().map(|(m, _)| m).collect(); - for m in ["ADBE Gaussian Blur 2", "ADBE Tint"] { - assert_eq!(defs.iter().filter(|d| *d == m).count(), 1, "{m}"); - } -} - -// ---------------------------------------------------------------------------- Gradient Ramp - -#[test] -fn ramp_parameters_and_defaults() { - // 368: Gradient Ramp with every parameter at its default. - skip!(with_params("368-fx-ramp-default.aep", |_, p| { - let kinds: Vec<_> = p.iter().map(|p| (p.kind, p.name.as_str())).collect(); - assert_eq!( - kinds, - [ - (ParamKind::Layer, ""), - (ParamKind::Point, "Start of Ramp"), - (ParamKind::Color, "Start Color"), - (ParamKind::Point, "End of Ramp"), - (ParamKind::Color, "End Color"), - (ParamKind::Popup, "Ramp Shape"), - (ParamKind::FixedSlider, "Ramp Scatter"), - (ParamKind::FixedSlider, "Blend With Original"), - (ParamKind::Button, ""), - (ParamKind::NoData, ""), - ] - ); - // Start [960,0] and End [960,1080] on the 1920x1080 layer: fractions of the layer size. - assert_eq!(p[1].value(), Some(ParamValue::Point([0.5, 0.0]))); - assert_eq!(p[3].value(), Some(ParamValue::Point([0.5, 1.0]))); - assert_eq!(p[1].point_px(1920.0, 1080.0), Some([960.0, 0.0])); - assert_eq!(p[3].point_px(1920.0, 1080.0), Some([960.0, 1080.0])); - // Black to white with alpha 255. - assert_eq!(p[2].value(), Some(ParamValue::Argb([1.0, 0.0, 0.0, 0.0]))); - assert_eq!(p[4].value(), Some(ParamValue::Argb([1.0, 1.0, 1.0, 1.0]))); - // Linear Ramp is item 1 of 2. - assert_eq!(p[5].value(), Some(ParamValue::Index(1))); - assert_eq!(p[5].popup_item_count(), Some(2)); - assert_eq!(p[5].popup_selected_item(), Some("Linear Ramp")); - // Scatter 0 (pixels, valid max 512); Blend 0 (a 0..1 fraction, valid max 1). - assert_eq!((p[6].value(), p[6].valid_max()), (Some(ParamValue::Number(0.0)), Some(512.0))); - assert_eq!((p[7].value(), p[7].valid_max()), (Some(ParamValue::Number(0.0)), Some(1.0))); - assert!(p[8].stored().is_some() && p[8].value().is_none()); - assert!((1..=7).all(|i| p[i].stored().is_none())); - })); -} - -#[test] -fn ramp_values() { - // 369: Start of Ramp [100, 200] -> [100/1920, 200/1080]. - skip!(with_params("369-fx-ramp-start-100-200.aep", |_, p| { - assert_near(&point(p[1].stored_value()), &[100.0 / 1920.0, 200.0 / 1080.0], 1e-12); - assert_near(&p[1].point_px(1920.0, 1080.0).unwrap(), &[100.0, 200.0], 1e-9); - })); - // 371: Start Color red. - skip!(with_params("371-fx-ramp-startcolor-red.aep", |_, p| { - assert_eq!(p[2].stored_value(), Some(ParamValue::Argb([1.0, 1.0, 0.0, 0.0]))); - })); - // 374: End of Ramp [2000, -100], outside the layer. - skip!(with_params("374-fx-ramp-end-2000-m100.aep", |_, p| { - assert_near(&p[3].point_px(1920.0, 1080.0).unwrap(), &[2000.0, -100.0], 1e-9); - })); - // 377: Ramp Shape 2 = Radial Ramp. - skip!(with_params("377-fx-ramp-shape-radial.aep", |_, p| { - assert_eq!(p[5].stored_value(), Some(ParamValue::Index(2))); - assert_eq!(p[5].popup_selected_item(), Some("Radial Ramp")); - })); - // 378: Ramp Scatter 12 (plain pixels). - skip!(with_params("378-fx-ramp-scatter-12.aep", |_, p| assert_eq!(number(p[6].stored_value()), 12.0))); - // 380: Blend With Original 25 % is stored as the fraction 0.25. - skip!(with_params("380-fx-ramp-blend-25pct.aep", |_, p| { - assert_eq!(number(p[7].stored_value()), 0.25); - assert_eq!(p[7].valid_max(), Some(1.0)); - })); -} - -#[test] -fn ramp_point_keyframes() { - // 382: Start of Ramp keyed [100,100] at 0 s, [1800,900] at 2 s, linear: 104-byte spatial records. - skip!(with_params("382-fx-ramp-start-2key.aep", |_, p| { - let start = &p[1]; - assert!(start.is_animated()); - let keys: Vec<_> = start.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Spatial { components: 2 } && k.raw().len() == 104)); - assert_eq!(keys.iter().map(|k| k.time_units().unwrap()).collect::>(), [0, T2]); - assert_near(&keys[0].value().unwrap(), &[100.0 / 1920.0, 100.0 / 1080.0], 1e-12); - assert_near(&keys[1].value().unwrap(), &[1800.0 / 1920.0, 900.0 / 1080.0], 1e-12); - assert!(keys.iter().all(|k| k.interpolation_in() == Some(Interpolation::Linear))); - let s = keys[0].spatial().unwrap(); - assert_eq!((s.auto_bezier_flag, s.in_tangent.clone(), s.out_tangent.clone()), (1, vec![0.0; 2], vec![0.0; 2])); - })); -} - -#[test] -fn second_instance_takes_its_definitions_from_the_project_and_its_values_from_itself() { - // 383: L keeps its default Gradient Ramp; the new 100x100 solid S100 above it has a Ramp with - // Start of Ramp [10, 20]. One of the two instances has an empty parT. - let bytes = fixture!("383-fx-ramp-on-100x100-start-10-20.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layers: Vec<_> = comp.layers().collect(); - assert_eq!(layers.len(), 2); - let l = base_layer(&comp); - let small = layers.iter().find(|x| x.id() != l.id()).unwrap(); - - let small_fx = small.effects(); - let l_fx = l.effects(); - assert_eq!((small_fx.len(), l_fx.len()), (1, 1)); - // In the combined file an earlier case holds the type's full definitions, so here both - // instances take them from the project copy. - assert_eq!(project.definition_source(&small_fx[0]), DefinitionSource::Project); - assert_eq!(project.definition_source(&l_fx[0]), DefinitionSource::Project); - assert!(l_fx[0].params().is_empty()); - assert_eq!(l_fx[0].declared_param_count(), None); - - // S100: [10,20] px on its own 100x100 size; End of Ramp default [50,100]. - let sp = project.effect_params(&small_fx[0]); - assert_near(&point(sp[1].stored_value()), &[0.1, 0.2], 1e-12); - assert_near(&sp[1].point_px(100.0, 100.0).unwrap(), &[10.0, 20.0], 1e-9); - assert_eq!(sp[3].point_px(100.0, 100.0), Some([50.0, 100.0])); - - // L: the 368 defaults, not the values of the project copy (which is S100's instance). - let lp = project.effect_params(&l_fx[0]); - assert_eq!(lp.len(), 10); - assert!(lp.iter().all(|p| p.borrowed_definition)); - assert_eq!(lp[1].name, "Start of Ramp"); - assert!(lp[1].stored().is_none()); - assert_eq!(lp[1].value(), Some(ParamValue::Point([0.5, 0.0]))); - assert_eq!(lp[3].value(), Some(ParamValue::Point([0.5, 1.0]))); - assert_eq!(lp[2].value(), Some(ParamValue::Argb([1.0, 0.0, 0.0, 0.0]))); - assert_eq!(lp[4].value(), Some(ParamValue::Argb([1.0, 1.0, 1.0, 1.0]))); - assert_eq!((number(lp[6].value()), number(lp[7].value())), (0.0, 0.0)); - // A borrowed popup has no reliable pard default (a selection writes into that slot). - assert_eq!(lp[5].pard_default(), None); - assert_eq!(lp[5].items.as_deref().map(<[String]>::len), Some(2)); - // L's own records: the input layer (its own id) and the button. - assert_eq!(lp[0].stored_value(), Some(ParamValue::Layer(l.id().unwrap()))); - assert!(lp[8].stored().is_some()); - - // One definition for the type, although there are two instances. - let defs = project.effect_definitions(); - assert_eq!(defs.iter().filter(|(m, _)| m == "ADBE Ramp").count(), 1); -} - -#[test] -fn files_without_effects_have_no_definitions() { - // The definitions are per file: a file has some exactly when one of its layers has an effect. - let mut without = 0; - for name in crate::common::FILES.iter().filter(|n| n.ends_with(".aep")) { - let bytes = skip!(crate::common::try_file(name)); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let has_effects = project.all_items().iter().filter_map(|i| i.comp()).any(|c| c.layers().any(|l| !l.effects().is_empty())); - assert_eq!(project.effect_definitions().is_empty(), !has_effects, "{name}"); - without += usize::from(!has_effects); - } - assert!(without > 0); -} diff --git a/crates/aep/tests/it/container/effects_batch5.rs b/crates/aep/tests/it/container/effects_batch5.rs deleted file mode 100644 index d776f650f..000000000 --- a/crates/aep/tests/it/container/effects_batch5.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! Effects of batch 5 (cases 409-450, 511-516): integer sliders, checkbox defaults, the stored -//! scale of each slider (its valid maximum), popup items, and the arbitrary data of Hue/Saturation -//! and Levels. - -use crate::container::helpers::{first_comp, open}; -use effectcraft_aep::{EffectParam, HueSaturationData, LevelsData, ParamKind, ParamValue, Project}; - -/// Runs `f` on the parameters of the first effect of layer L (the only layer). -fn with_params(name: &str, f: impl FnOnce(&[EffectParam<'_, '_>], &effectcraft_aep::Effect<'_, '_>) -> R) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = first_comp(&project); - let layer = comp.layers().next().expect("L"); - let fx = layer.effects().into_iter().next().expect("an effect"); - let params = project.effect_params(&fx); - f(¶ms, &fx) - }) -} - -fn by_name<'p, 'f, 'a>(params: &'p [EffectParam<'f, 'a>], name: &str) -> &'p EffectParam<'f, 'a> { - params.iter().find(|p| p.name == name || p.items.as_ref().is_some_and(|i| i.first().is_some_and(|f| f == name))).unwrap_or_else(|| panic!("no {name}")) -} - -#[test] -fn invert_channel_items_and_blend() { - skip!(with_params("410-fx-invert-channel-2.aep", |p, fx| { - assert_eq!(fx.match_name(), "ADBE Invert"); - let ch = by_name(p, "Channel"); - assert_eq!(ch.kind, ParamKind::Popup); - // The items include separators "(-" (one index each). - assert_eq!(ch.items.as_ref().map(|i| (i.len(), i[1].as_str(), i[4].as_str(), i[15].as_str())), Some((16, "Red", "(-", "Alpha"))); - assert_eq!(ch.stored_value(), Some(ParamValue::Index(2))); - assert_eq!(by_name(p, "Blend With Original").valid_max(), Some(100.0)); - })); - skip!(with_params("411-fx-invert-blend-50.aep", |p, _| assert_eq!(by_name(p, "Blend With Original").stored_value(), Some(ParamValue::Number(50.0))))); -} - -#[test] -fn fast_box_blur_integer_slider_and_checkbox_default_on() { - skip!(with_params("413-fx-fastbox-radius-20.aep", |p, _| { - let r = by_name(p, "Blur Radius"); - assert_eq!((r.kind, r.valid_max(), r.stored_value()), (ParamKind::FixedSlider, Some(30000.0), Some(ParamValue::Number(20.0)))); - let it = by_name(p, "Iterations"); - assert_eq!((it.kind, it.pard_default(), it.valid_max(), it.stored_value()), (ParamKind::IntSlider, Some(ParamValue::Number(3.0)), Some(50.0), None)); - // Repeat Edge Pixels is on by default (AE read-back 1): the pard default, no record. - let rep = by_name(p, "Repeat Edge Pixels"); - assert_eq!((rep.kind, rep.pard_default(), rep.value()), (ParamKind::Checkbox, Some(ParamValue::Bool(true)), Some(ParamValue::Bool(true)))); - })); - skip!(with_params("414-fx-fastbox-iterations-1.aep", |p, _| assert_eq!(by_name(p, "Iterations").stored_value(), Some(ParamValue::Number(1.0))))); - skip!(with_params("416-fx-fastbox-repeatedge-off.aep", |p, _| { - let rep = by_name(p, "Repeat Edge Pixels"); - assert_eq!((rep.stored_value(), rep.value(), rep.is_default()), (Some(ParamValue::Bool(false)), Some(ParamValue::Bool(false)), Some(false))); - })); -} - -#[test] -fn gaussian_blur_dimensions_and_repeat_edge() { - skip!(with_params("418-fx-gaussian-dimensions-3.aep", |p, _| { - assert_eq!(by_name(p, "Blur Dimensions").stored_value(), Some(ParamValue::Index(3))); - assert_eq!(by_name(p, "Blurriness").pard_default(), Some(ParamValue::Number(25.0))); - assert_eq!(by_name(p, "Repeat Edge Pixels").value(), Some(ParamValue::Bool(true))); - })); - skip!(with_params("419-fx-gaussian-repeatedge-off.aep", |p, _| assert_eq!(by_name(p, "Repeat Edge Pixels").value(), Some(ParamValue::Bool(false))))); -} - -#[test] -fn drop_shadow_opacity_is_stored_on_0_to_255() { - skip!(with_params("422-fx-dropshadow-opacity-204.aep", |p, _| { - let o = by_name(p, "Opacity"); - assert_eq!((o.valid_max(), o.pard_default(), o.stored_value()), (Some(255.0), Some(ParamValue::Number(127.5)), Some(ParamValue::Number(204.0)))); - assert_eq!(by_name(p, "Distance").valid_max(), Some(4000.0)); - assert_eq!(by_name(p, "Shadow Only").pard_default(), Some(ParamValue::Bool(false))); - })); - skip!(with_params("426-fx-dropshadow-shadowonly-on.aep", |p, _| assert_eq!(by_name(p, "Shadow Only").stored_value(), Some(ParamValue::Bool(true))))); -} - -#[test] -fn glow_defaults_items_and_scales() { - skip!(with_params("427-fx-glow-default.aep", |p, _| { - let popup = |n: &str| (by_name(p, n).pard_default(), by_name(p, n).items.as_ref().map(|i| i.len())); - assert_eq!(popup("Glow Based On"), (Some(ParamValue::Index(2)), Some(2))); - assert_eq!(popup("Composite Original"), (Some(ParamValue::Index(2)), Some(3))); - assert_eq!(popup("Glow Operation"), (Some(ParamValue::Index(3)), Some(25))); - assert_eq!(popup("Color Looping"), (Some(ParamValue::Index(3)), Some(4))); - let t = by_name(p, "Glow Threshold"); - assert_eq!((t.valid_max(), t.pard_default()), (Some(255.0), Some(ParamValue::Number(153.0)))); - let m = by_name(p, "A & B Midpoint"); - assert_eq!(m.pard_default(), Some(ParamValue::Number(0.5))); - assert!(m.valid_max().is_some_and(|v| (v - 0.99).abs() < 0.001)); - })); - skip!(with_params("429-fx-glow-threshold-76.5.aep", |p, _| assert_eq!(by_name(p, "Glow Threshold").stored_value(), Some(ParamValue::Number(76.5))))); - skip!(with_params("438-fx-glow-midpoint-0.25.aep", |p, _| assert_eq!(by_name(p, "A & B Midpoint").stored_value(), Some(ParamValue::Number(0.25))))); -} - -#[test] -fn hue_saturation_master_values_are_arbitrary_data() { - for (name, master) in [("444-fx-huesat-hue-90.aep", [90, 0, 0]), ("446-fx-huesat-light-m30.aep", [0, 0, -30])] { - skip!(with_params(name, |p, fx| { - // The visible Master parameters keep no record. - assert!(by_name(p, "Master Hue").stored().is_none(), "{name}"); - let range = by_name(p, "Channel Range"); - assert_eq!(range.kind, ParamKind::ArbitraryData); - let data = fx.arbitrary_data(&range.match_name).expect("data"); - let d = HueSaturationData::parse(data).expect("180 bytes"); - assert_eq!(d.master, master, "{name}"); - assert!(d.ranges_are_default(), "{name}"); - })); - } - skip!(with_params("448-fx-huesat-colorizehue-120.aep", |p, fx| { - assert_eq!(by_name(p, "Colorize Hue").stored_value(), Some(ParamValue::Number(120.0))); - assert_eq!(by_name(p, "Colorize Saturation").pard_default(), Some(ParamValue::Number(25.0))); - let d = HueSaturationData::parse(fx.arbitrary_data(&by_name(p, "Channel Range").match_name).expect("data")).expect("parses"); - assert_eq!(d.master, [0, 0, 0]); - })); -} - -#[test] -fn levels_values_are_arbitrary_data() { - let f32r = |x: f64| f32::from_bits((x as f32).to_bits()); - for (name, rgb) in [ - ("512-fx-levels-inblack-0.1.aep", [f32r(0.1), 1.0, 1.0, 0.0, 1.0]), - ("514-fx-levels-gamma-2.aep", [0.0, 1.0, 2.0, 0.0, 1.0]), - ("516-fx-levels-outwhite-0.9.aep", [0.0, 1.0, 1.0, 0.0, f32r(0.9)]), - ] { - skip!(with_params(name, |p, fx| { - assert!(by_name(p, "Input Black").stored().is_none(), "{name}: the visible parameter keeps no record"); - let h = by_name(p, "Histogram"); - assert_eq!(h.kind, ParamKind::ArbitraryData); - let d = LevelsData::parse(fx.arbitrary_data(&h.match_name).expect("data")).expect("108 bytes"); - assert_eq!(d.header, [0x000f_10a7, 1], "{name}"); - assert_eq!(d.channels[0], rgb, "{name}"); - for c in &d.channels[1..] { - assert_eq!(*c, LevelsData::DEFAULT_CHANNEL, "{name}"); - } - let clip = by_name(p, "Clip To Output Black"); - assert_eq!(clip.items.as_ref().map(|i| i.join("|")), Some("On|Off|Off for 32 bpc Color".to_string())); - // A borrowed popup (a later Levels of the combined file) has no reliable pard default. - let want = if clip.borrowed_definition { None } else { Some(ParamValue::Index(3)) }; - assert_eq!(clip.pard_default(), want, "{name}"); - })); - } -} - -#[test] -fn hostile_arbitrary_data_is_none() { - assert_eq!(HueSaturationData::parse(&[0; 179]), None); - assert_eq!(LevelsData::parse(&[0; 200]), None); - assert!(HueSaturationData::parse(&[0xff; 180]).is_some()); -} diff --git a/crates/aep/tests/it/container/effects_exposure.rs b/crates/aep/tests/it/container/effects_exposure.rs deleted file mode 100644 index f29c8b7fe..000000000 --- a/crates/aep/tests/it/container/effects_exposure.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Batch 4, session S7 (cases 389-397): Exposure (`ADBE Exposure2`): the popup, the four -//! twirl-down groups (start / end markers that hold no value), float sliders with their valid and -//! slider ranges, the Bypass checkbox and a keyed slider. Every expected value is the one the case -//! was made with (its MANIFEST row). - -use crate::container::helpers::{assert_near, base_layer, first_comp, open}; -use effectcraft_aep::{DefinitionSource, EffectParam, Interpolation, KeyframeKind, ParamKind, ParamValue, Project}; - -/// Key time 2 s in the property timescale 25600. -const T2: i32 = 51200; -/// Float sliders hold the float32 value widened to f64 (0.1 is 0.10000000149). -const F32: f64 = 1e-6; - -/// Runs `f` on the parameters of the single effect of `L`. -fn with_params(name: &str, f: impl FnOnce(&[EffectParam<'_, '_>]) -> R) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let effects = layer.effects(); - assert_eq!(effects.len(), 1, "{name}"); - assert_eq!(effects[0].match_name(), "ADBE Exposure2", "{name}"); - // The first instance of a type in the combined file (the case that adds it at its defaults) - // keeps its own definitions; the later cases read the project copy. - let first = ["356-fx-tint-default.aep", "368-fx-ramp-default.aep", "389-fx-exposure-default.aep"].contains(&name); - let want = if first { DefinitionSource::Instance } else { DefinitionSource::Project }; - assert_eq!(project.definition_source(&effects[0]), want, "{name}"); - let params = project.effect_params(&effects[0]); - assert_eq!(params.len(), 24, "{name}"); - f(¶ms) - }) -} - -fn number(v: Option) -> f64 { - match v { - Some(ParamValue::Number(n)) => n, - other => panic!("{other:?} is not a number"), - } -} - -/// The `parT` indices of the Exposure / Offset / Gamma Correction sliders of Master, Red, Green -/// and Blue. -const GROUPS: [(usize, &str); 4] = [(2, "Master"), (7, "Red"), (12, "Green"), (17, "Blue")]; - -#[test] -fn exposure_parameters_and_defaults() { - // 389: Exposure with every parameter at its default. - let bytes = fixture!("389-fx-exposure-default.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let fx = base_layer(&first_comp(&project)).effects(); - assert_eq!((fx[0].match_name(), fx[0].name().as_deref()), ("ADBE Exposure2", Some("Exposure"))); - assert_eq!(fx[0].declared_param_count(), Some(24)); - skip!(with_params("389-fx-exposure-default.aep", |p| { - assert_eq!((p[0].kind, p[1].kind, p[22].kind, p[23].kind), (ParamKind::Layer, ParamKind::Popup, ParamKind::Checkbox, ParamKind::NoData)); - assert_eq!(p[1].name, "Channels:"); - assert_eq!(p[1].items.as_deref(), Some(&["Master".to_string(), "Individual Channels".to_string()][..])); - assert_eq!((p[1].value(), p[1].popup_item_count(), p[1].popup_selected_item()), (Some(ParamValue::Index(1)), Some(2), Some("Master"))); - for (start, group) in GROUPS { - let prefix = if group == "Master" { String::new() } else { format!("{group} ") }; - // The group markers: always a record, no value, the end repeats the group's name. - for (i, kind) in [(start, ParamKind::GroupStart), (start + 4, ParamKind::GroupEnd)] { - assert_eq!((p[i].kind, p[i].name.as_str()), (kind, group)); - assert!(p[i].stored().is_some(), "{group} {kind:?}"); - assert_eq!((p[i].stored_value(), p[i].pard_default(), p[i].value(), p[i].is_default()), (None, None, None, None)); - } - let names = [format!("{prefix}Exposure"), format!("{prefix}Offset"), format!("{prefix}Gamma Correction")]; - // Valid range, slider range and default per slider (the same for all four groups). - let want = [((-100.0, 100.0), (-4.0, 4.0), 0.0), ((-2.0, 2.0), (-0.5, 0.5), 0.0), ((0.1, 10.0), (0.1, 10.0), 1.0)]; - for (k, (valid, slider, default)) in want.into_iter().enumerate() { - let s = &p[start + 1 + k]; - assert_eq!((s.kind, s.name.as_str()), (ParamKind::FloatSlider, names[k].as_str())); - assert_eq!(s.match_name, format!("ADBE Exposure2-{:04}", start + 1 + k)); - assert!(s.stored().is_none(), "{}", s.name); - assert_eq!(s.value(), Some(ParamValue::Number(default)), "{}", s.name); - assert_eq!(s.is_default(), Some(true)); - assert_near(&[s.valid_min().unwrap(), s.valid_max().unwrap()], &[valid.0, valid.1], F32); - let (lo, hi) = s.slider_range().unwrap(); - assert_near(&[lo, hi], &[slider.0, slider.1], F32); - } - } - // Bypass Linear Light Conversion: an unnamed checkbox labelled in pdnm, off. - assert_eq!(p[22].name, ""); - assert_eq!(p[22].items.as_deref(), Some(&["Bypass Linear Light Conversion".to_string()][..])); - assert!(p[22].stored().is_none()); - assert_eq!(p[22].value(), Some(ParamValue::Bool(false))); - // Ranges exist only on float sliders. - assert_eq!((p[1].valid_min(), p[1].slider_range(), p[22].slider_range(), p[2].valid_max()), (None, None, None, None)); - assert!(p.iter().all(|p| !p.borrowed_definition && !p.is_animated())); - })); -} - -#[test] -fn exposure_values() { - // 390: Channels -> Individual Channels (2). - skip!(with_params("390-fx-exposure-channels-individual.aep", |p| { - assert_eq!(p[1].stored_value(), Some(ParamValue::Index(2))); - assert_eq!(p[1].popup_selected_item(), Some("Individual Channels")); - assert_eq!(p[1].is_default(), Some(false)); - })); - // 391: Exposure 1.5. - skip!(with_params("391-fx-exposure-master-1.5.aep", |p| { - assert_eq!(p[3].stored_value(), Some(ParamValue::Number(1.5))); - assert_eq!(p[3].is_default(), Some(false)); - assert_eq!(p[4].value(), Some(ParamValue::Number(0.0))); - })); - // 393: Offset 0.1 (float32: 0.10000000149). - skip!(with_params("393-fx-exposure-offset-0.1.aep", |p| { - assert_near(&[number(p[4].stored_value())], &[0.1], F32); - assert_eq!(p[3].value(), Some(ParamValue::Number(0.0))); - })); - // 394: Gamma Correction 2.2 (float32: 2.2000000477). - skip!(with_params("394-fx-exposure-gamma-2.2.aep", |p| { - assert_near(&[number(p[5].stored_value())], &[2.2], F32); - assert_eq!(p[5].is_default(), Some(false)); - })); - // 395: Channels 2 and Red Exposure 1: two ordinary records. - skip!(with_params("395-fx-exposure-individual-red-1.aep", |p| { - assert_eq!(p[1].stored_value(), Some(ParamValue::Index(2))); - assert_eq!(p[8].stored_value(), Some(ParamValue::Number(1.0))); - assert_eq!(p[3].value(), Some(ParamValue::Number(0.0))); - })); - // 396: Bypass on: a record with 1.0. - skip!(with_params("396-fx-exposure-bypass-on.aep", |p| { - assert_eq!(p[22].stored_value(), Some(ParamValue::Bool(true))); - assert_eq!(p[22].is_default(), Some(false)); - })); -} - -#[test] -fn exposure_keyframes() { - // 397: Exposure keyed -1 at 0 s, 2 at 2 s, linear: plain 48-byte records. - skip!(with_params("397-fx-exposure-master-2key.aep", |p| { - let e = &p[3]; - assert!(e.is_animated()); - assert_eq!(e.stored_value(), None); - let keys: Vec<_> = e.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - assert_eq!(keys.iter().map(|k| k.time_units().unwrap()).collect::>(), [0, T2]); - assert_eq!(keys.iter().map(|k| k.scalar_value().unwrap()).collect::>(), [-1.0, 2.0]); - assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Plain { components: 1 } && k.raw().len() == 48)); - assert!(keys.iter().all(|k| k.interpolation_in() == Some(Interpolation::Linear) && k.interpolation_out() == Some(Interpolation::Linear))); - })); -} diff --git a/crates/aep/tests/it/container/header.rs b/crates/aep/tests/it/container/header.rs deleted file mode 100644 index 2ebdbd59d..000000000 --- a/crates/aep/tests/it/container/header.rs +++ /dev/null @@ -1,345 +0,0 @@ -//! The layer header (`ldta`) and the composition header (`cdta`, `PRin`), checked against the values -//! the synthetic corpus was made with (its MANIFEST): comp `C` 1920x1080, 25 fps, 5 s, background -//! black, shutter angle 180, one solid layer `L` (red, 1920x1080, label 1, Normal, Best, start 0, -//! in 0, out 5, stretch 100), then one change per file. - -use crate::container::helpers::{base_layer, first_comp, open}; -use effectcraft_aep::{BlendMode, LayerHeader, LayerType, Project, Quality, Rational}; - -const L: u32 = 0x1b; - -/// The header of the solid layer `L` in a fixture. -fn l_header(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - base_layer(&comp).header().unwrap() - }) -} - -/// The switches that the MANIFEST lists, so that a case can say which one differs from the base. -#[derive(Debug, Clone, PartialEq)] -struct Switches { - shy: bool, - locked: bool, - solo: bool, - three_d: bool, - motion_blur: bool, - collapse: bool, - adjustment: bool, - guide: bool, -} - -fn switches(h: &LayerHeader) -> Switches { - Switches { - shy: h.is_shy(), - locked: h.is_locked(), - solo: h.is_solo(), - three_d: h.is_three_d(), - motion_blur: h.is_motion_blur(), - collapse: h.collapses_transformations(), - adjustment: h.is_adjustment(), - guide: h.is_guide(), - } -} - -const NONE: Switches = - Switches { shy: false, locked: false, solo: false, three_d: false, motion_blur: false, collapse: false, adjustment: false, guide: false }; - -/// Everything the base layer and every one-switch case share. -fn assert_plain(h: &LayerHeader) { - // The id is the case's own (0x1b in the single-case files); the source is the solid `L`. - assert_eq!(h.layer_type, LayerType::Av); - assert_eq!(h.label, 1); - // No name was set, so the copy of the name at byte 64 is empty (the layer shows its source name). - assert_eq!(h.name_copy, ""); - assert!(!h.is_null_object()); - assert_eq!(h.parent_id, None); - assert_eq!(h.source_id, Some(0x1a)); -} - -#[test] -fn base_layer_header() { - let h = skip!(l_header("000-base.aep")); - assert_plain(&h); - assert_eq!(h.quality, Quality::Best); - assert_eq!(h.blend_mode, BlendMode::Normal); - assert_eq!((h.stretch, h.stretch_den), (1, 1)); - assert_eq!(switches(&h), NONE); - // start 0 s, in 0 s, out 5 s; denominator = the composition timescale. - assert_eq!(h.start, Rational { num: 0, den: 25600 }); - assert_eq!(h.in_relative, Rational { num: 0, den: 25600 }); - assert_eq!(h.out_relative, Rational { num: 128_000, den: 25600 }); - assert_eq!(h.in_point(), Rational::new(0, 1)); - assert_eq!(h.out_point(), Rational::new(5, 1)); -} - -#[test] -fn one_switch_per_case() { - // (file, the switches that case turns on) - let cases = [ - ("012-layer-shy.aep", Switches { shy: true, ..NONE }), - ("013-layer-locked.aep", Switches { locked: true, ..NONE }), - ("014-layer-solo.aep", Switches { solo: true, ..NONE }), - ("015-layer-3d.aep", Switches { three_d: true, ..NONE }), - ("017-layer-motionblur.aep", Switches { motion_blur: true, ..NONE }), - ("024-layer-collapse.aep", Switches { collapse: true, ..NONE }), - ("025-layer-adjustment.aep", Switches { adjustment: true, ..NONE }), - ("026-layer-guide.aep", Switches { guide: true, ..NONE }), - ]; - for (name, expected) in cases { - let h = skip!(l_header(name)); - assert_eq!(switches(&h), expected, "{name}"); - assert_plain(&h); - assert_eq!((h.quality, h.blend_mode, h.stretch), (Quality::Best, BlendMode::Normal, 1), "{name}"); - assert_eq!(h.out_point(), Rational::new(5, 1), "{name}"); - } -} - -#[test] -fn name_blend_mode_and_quality() { - let h = skip!(l_header("010-layer-name.aep")); - assert_eq!(h.name_copy, "Renamed"); - let bytes = fixture!("010-layer-name.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - // The layer name is the user's; the source footage keeps its own name. - assert_eq!(layer.name().as_deref(), Some("Renamed")); - assert_eq!(project.layer_source(&layer).and_then(|i| i.display_name()).as_deref(), Some("L")); - - assert_eq!(skip!(l_header("016-layer-blend-multiply.aep")).blend_mode, BlendMode::Multiply); - assert_eq!(skip!(l_header("023-layer-quality-draft.aep")).quality, Quality::Draft); -} - -#[test] -fn display_name_falls_back_to_the_source_name() { - let bytes = fixture!("000-base.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - assert_eq!(layer.name(), None); - assert_eq!(project.layer_source(&layer).and_then(|i| i.display_name()).as_deref(), Some("L")); - assert_eq!(project.layer_source_size(&layer), Some((1920, 1080))); - let source = project.layer_source(&layer).unwrap(); - assert_eq!(source.id(), Some(0x1a)); - assert!(source.footage().unwrap().is_solid); -} - -#[test] -fn time_stretch_and_the_in_out_start_convention() { - // 018: stretch 100 -> 200: the stored out point stays 5 s, the layer ends at 10 s. - let h = skip!(l_header("018-layer-stretch200.aep")); - assert_eq!(h.stretch, 2); - assert_eq!(h.stretch_ratio(), Rational::new(2, 1)); - assert_eq!(h.out_relative, Rational { num: 128_000, den: 25600 }); - assert_eq!(h.out_point(), Rational::new(10, 1)); - assert_eq!(h.in_point(), Rational::new(0, 1)); - - // 019: inPoint 0 -> 1; AE moved the out point to 6 s and left the start at 0. - let h = skip!(l_header("019-layer-inpoint1.aep")); - assert_eq!(h.start.num, 0); - assert_eq!(h.in_relative, Rational { num: 25600, den: 25600 }); - assert_eq!(h.in_point(), Rational::new(1, 1)); - assert_eq!(h.out_point(), Rational::new(6, 1)); - - // 021: startTime 0 -> 0.5: in 0.5 s and out 5.5 s although the stored in point stays 0. - let h = skip!(l_header("021-layer-starttime0.5.aep")); - assert_eq!(h.start, Rational { num: 12800, den: 25600 }); - assert_eq!(h.in_relative.num, 0); - assert_eq!(h.in_point(), Rational::new(1, 2)); - assert_eq!(h.out_point(), Rational::new(11, 2)); -} - -#[test] -fn parent_link_and_null_object() { - // 022: a new null layer "Null" (source "Null 1", 100x100) on top; L is its child. - let bytes = fixture!("022-layer-parent-null.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layers: Vec<_> = comp.layers().collect(); - assert_eq!(layers.len(), 2); - let null = &layers[0]; - let nh = null.header().unwrap(); - assert_eq!(null.name().as_deref(), Some("Null")); - assert!(nh.is_null_object()); - assert_eq!(nh.layer_type, LayerType::Av); - assert_eq!(nh.parent_id, None); - assert_eq!(project.layer_source(null).and_then(|i| i.display_name()).as_deref(), Some("Null 1")); - assert_eq!(project.layer_source_size(null), Some((100, 100))); - let lh = layers[1].header().unwrap(); - assert_ne!(lh.id, nh.id); - assert_eq!(lh.parent_id, Some(nh.id)); - assert!(!lh.is_null_object()); -} - -#[test] -fn layer_header_is_none_when_ldta_is_too_short() { - assert!(LayerHeader::parse(&[0; 139]).is_none()); - assert!(LayerHeader::parse(&[]).is_none()); - assert!(LayerHeader::parse(&[0; 140]).is_some()); -} - -#[test] -fn rational_is_exact() { - assert_eq!(Rational::new(12800, 25600), Some(Rational { num: 1, den: 2 })); - assert_eq!(Rational::new(-3, -6), Some(Rational { num: 1, den: 2 })); - assert_eq!(Rational::new(3, -6), Some(Rational { num: -1, den: 2 })); - assert_eq!(Rational::new(0, 7), Some(Rational { num: 0, den: 1 })); - assert_eq!(Rational::new(1, 0), None); - assert_eq!(Rational { num: 1, den: 0 }.to_f64(), None); - assert_eq!(Rational::new(i64::MIN, 1), None); -} - -// ----------------------------------------------------------------------------------- composition - -use effectcraft_aep::CompHeader; - -fn comp_header(name: &str) -> Option<(CompHeader, Option, Option<(String, String)>)> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - (comp.header().unwrap(), comp.name(), comp.renderer().map(|r| (r.match_name, r.display_name))) - }) -} - -#[test] -fn base_comp_header() { - let (h, name, renderer) = skip!(comp_header("000-base.aep")); - assert_eq!(name.as_deref(), Some("C")); - assert_eq!((h.width, h.height), (1920, 1080)); - assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 25600)); - assert_eq!(h.frame_rate(), Some(25.0)); - assert_eq!(h.frame_rate_fixed, 25 << 16); - assert_eq!(h.duration_units, 128_000); - assert_eq!(h.duration_seconds(), Some(5.0)); - assert_eq!(h.background, [0, 0, 0]); - assert_eq!(h.shutter_angle, 180); - assert_eq!(h.work_area_start_units, 0); - assert_eq!(h.work_area_end_units, None); - assert_eq!(h.pixel_aspect, Rational { num: 1, den: 1 }); - assert!(!h.motion_blur); - // The manifest calls the classic renderer `ADBE Advanced 3d`; the file stores `ADBE Escher` - // and the display name `Classic 3D`. - assert_eq!(renderer, Some(("ADBE Escher".to_string(), "Classic 3D".to_string()))); -} - -#[test] -fn one_comp_change_per_case() { - let (base, _, _) = skip!(comp_header("000-base.aep")); - - let (h, _, _) = skip!(comp_header("030-comp-size-1280x720.aep")); - assert_eq!((h.width, h.height), (1280, 720)); - assert_eq!(CompHeader { width: 1920, height: 1080, ..h }, base); - - // 031: frameRate 25 -> 30: the frame duration stays 1024, the timescale becomes 30720; the - // duration stays 5 s (153 600 units). - let (h, _, _) = skip!(comp_header("031-comp-fps30.aep")); - assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 30720)); - assert_eq!(h.frame_rate(), Some(30.0)); - assert_eq!(h.frame_rate_fixed, 30 << 16); - assert_eq!(h.duration_units, 153_600); - assert_eq!(h.duration_seconds(), Some(5.0)); - - // 032: duration 5 -> 10 s; the work area stays the whole composition. - let (h, _, _) = skip!(comp_header("032-comp-duration10.aep")); - assert_eq!(h.duration_units, 256_000); - assert_eq!(h.duration_seconds(), Some(10.0)); - assert_eq!(h.work_area_end_units, None); - - // 033: bgColor [0,0,0] -> [0,1,0]. - let (h, _, _) = skip!(comp_header("033-comp-bg-green.aep")); - assert_eq!(h.background, [0, 255, 0]); - - // 034: shutterAngle 180 -> 90. - let (h, _, _) = skip!(comp_header("034-comp-shutter90.aep")); - assert_eq!(h.shutter_angle, 90); - assert_eq!(CompHeader { shutter_angle: 180, ..h }, base); - - // 035: workAreaStart 0 -> 1, workAreaDuration 5 -> 2: the end is start + duration = 3 s. - let (h, _, _) = skip!(comp_header("035-comp-workarea-1-2.aep")); - assert_eq!(h.work_area_start_units, 25600); - assert_eq!(h.work_area_end_units, Some(76_800)); -} - -#[test] -fn one_comp_change_per_case_aspect_blur_renderer() { - let (base, _, base_renderer) = skip!(comp_header("000-base.aep")); - - // 037: pixelAspect 1 -> 2. - let (h, _, _) = skip!(comp_header("037-comp-pixelaspect2.aep")); - assert_eq!(h.pixel_aspect, Rational { num: 2, den: 1 }); - - // 038: comp motion blur on. - let (h, _, _) = skip!(comp_header("038-comp-motionblur.aep")); - assert!(h.motion_blur); - assert_eq!(CompHeader { motion_blur: false, ..h }, base); - - // 039: renderer -> Advanced 3D. - let (h, _, renderer) = skip!(comp_header("039-comp-renderer-advanced3d.aep")); - assert_eq!(renderer, Some(("ADBE Calder".to_string(), "Advanced 3D".to_string()))); - assert_ne!(renderer, base_renderer); - assert_eq!(h, base); -} - -#[test] -fn comp_header_is_none_when_cdta_is_too_short() { - assert!(CompHeader::parse(&[0; 175]).is_none()); - assert!(CompHeader::parse(&[0; 176]).is_some()); -} - -#[test] -fn precomp_item_ids_and_labels() { - // 124: L precomposed into "Pre"; the layer in C is a comp-sourced layer labelled 15. - let bytes = fixture!("124-precomp-Pre.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comps: Vec<_> = project.all_items().into_iter().filter_map(|i| i.comp().map(|c| (i, c))).collect(); - let names: Vec<_> = comps.iter().map(|(_, c)| c.name().unwrap()).collect(); - assert_eq!(names, ["C", "Pre"]); - let (c_item, c) = &comps[0]; - let (pre_item, pre) = &comps[1]; - let layers: Vec<_> = c.layers().collect(); - assert_eq!(layers.len(), 1); - let layer = &layers[0]; - let h = layer.header().unwrap(); - assert_eq!(h.source_id, pre_item.id()); - assert_eq!(project.layer_source(layer).unwrap().id(), pre_item.id()); - assert_eq!(h.label, 15); - assert_eq!(layer.name(), None); - assert_eq!(project.layer_source(layer).and_then(|i| i.display_name()).as_deref(), Some("Pre")); - assert_eq!(project.layer_source_size(layer), Some((1920, 1080))); - // The precomp layer's start time has the denominator 1; the Pre comp is 1920x1080, 25 fps, 5 s. - assert_eq!(h.start.den, 1); - let ph = pre.header().unwrap(); - assert_eq!((ph.width, ph.height, ph.frame_rate(), ph.duration_seconds()), (1920, 1080, Some(25.0), Some(5.0))); - // C records that it uses the comp Pre (chunk idpi, a little-endian u32). - assert_eq!(crate::common::used_item_ids(c_item), [pre_item.id().unwrap()]); - assert!(crate::common::used_item_ids(pre_item).is_empty()); - assert_eq!(pre_item.label(), Some(15)); - // The layer inside Pre is a new layer made from the solid L (moving the layers into a precomp - // creates new layers). - let inner: Vec<_> = pre.layers().collect(); - assert_eq!(inner.len(), 1); - let ih = inner[0].header().unwrap(); - assert_ne!(ih.id, L); - assert_eq!(ih.source_id, Some(0x1a)); - assert_eq!(project.layer_source(&inner[0]).and_then(|i| i.display_name()).as_deref(), Some("L")); -} - -#[test] -fn a_negative_stretch_is_a_reversed_layer() { - // 981: Time Reverse (stretch -100 %, start 5 s): numerator -1 (`0xffffffff`), the stored in - // point 0 and out point 5 s relative, so the layer runs from 5 s back to 0 s; 983: -50 % = -1/2. - let h = skip!(l_header("981-layer-stretch-minus100-start5.aep")); - assert_eq!((h.stretch, h.stretch_den), (-1, 1)); - assert_eq!((h.in_point(), h.out_point()), (Rational::new(5, 1), Rational::new(0, 1))); - let h = skip!(l_header("983-layer-stretch-minus50-opacity-keys.aep")); - assert_eq!((h.stretch, h.stretch_den), (-1, 2)); - assert_eq!((h.in_point(), h.out_point()), (Rational::new(5, 1), Rational::new(5, 2))); -} diff --git a/crates/aep/tests/it/container/helpers.rs b/crates/aep/tests/it/container/helpers.rs deleted file mode 100644 index 5c01ebb8f..000000000 --- a/crates/aep/tests/it/container/helpers.rs +++ /dev/null @@ -1,414 +0,0 @@ -//! Helpers shared by the container tests. -#![allow(dead_code)] - -/// The generated fixtures (own test data, see ATTRIBUTION.md). -pub const FIXTURES: &[&str] = &[ - "000-base.aep", - "001-empty.aep", - "010-layer-name.aep", - "012-layer-shy.aep", - "013-layer-locked.aep", - "014-layer-solo.aep", - "015-layer-3d.aep", - "016-layer-blend-multiply.aep", - "017-layer-motionblur.aep", - "018-layer-stretch200.aep", - "019-layer-inpoint1.aep", - "021-layer-starttime0.5.aep", - "022-layer-parent-null.aep", - "023-layer-quality-draft.aep", - "024-layer-collapse.aep", - "025-layer-adjustment.aep", - "026-layer-guide.aep", - "030-comp-size-1280x720.aep", - "031-comp-fps30.aep", - "032-comp-duration10.aep", - "033-comp-bg-green.aep", - "034-comp-shutter90.aep", - "035-comp-workarea-1-2.aep", - "037-comp-pixelaspect2.aep", - "038-comp-motionblur.aep", - "039-comp-renderer-advanced3d.aep", - "040-static-position-100-200.aep", - "041-static-scale-50.aep", - "042-static-rotation-45.aep", - "043-static-opacity-25.aep", - "044-static-anchor-10-20.aep", - "052-key-position-2key-ease.aep", - "053-key-position-2key-hold-key1.aep", - "054-key-position-2key-spatial-bezier.aep", - "055-key-position-3key-inserted-t2.5.aep", - "056-key-position-3key-roving-key2.aep", - "057-key-position-3key-label9-key2.aep", - "058-key-opacity-2key.aep", - "060-expr-opacity-wiggle.aep", - "071-fx-slider-value77.aep", - "073-fx-color-0.2-0.6-1.aep", - "077-fx-dropdown-default.aep", - "080-fx-dropshadow-default.aep", - "090-mask-rect.aep", - "091-mask-rect-props.aep", - "093-mask-path-2keys.aep", - "110-text-A.aep", - "113-text-Hello-size60-fillorange.aep", - "122-marker-comp-1s.aep", - "123-marker-layer-1s.aep", - "124-precomp-Pre.aep", - "126-footage-png-layer.aep", - "202-key-out-hold-in-linear.aep", - "203-key-in-hold-out-linear.aep", - "204-key-ease-asymmetric.aep", - "205-key-opacity-ease-asymmetric.aep", - "206-key-scale-2key-linear.aep", - "208-key-mask-feather-2key-linear.aep", - "210-key-fill-color-2key-linear.aep", - "211-anchor-100x100-solid-10-20.aep", - "212-anchor-400x300-solid-100-50.aep", - "213-expr-opacity-wiggle-disabled.aep", - "214-fx-gaussianblur-default.aep", - "215-fx-fill-default.aep", - "216-fx-gaussianblur-40.aep", - "217-fx-checkbox-on.aep", - "218-fx-point-111-222.aep", - "219-fx-angle-90.aep", - "220-fx-layercontrol-to-layer1.aep", - "221-fx-slider-2key.aep", - "222-layer-video-off.aep", - "223-layer-audio-off.aep", - "224-layer-effects-off.aep", - "225-layer-blend-screen.aep", - "226-layer-blend-add.aep", - "227-layer-blend-overlay.aep", - "228-layer-blend-difference.aep", - "229-comp-fps-29.97.aep", - "230-comp-fps-23.976.aep", - "231-comp-bg-grey-0.5.aep", - "232-mask-ellipse.aep", - "233-mask-open-path.aep", - "234-mask-mode-intersect.aep", - "235-mask-mode-lighten.aep", - "236-mask-mode-darken.aep", - "237-mask-mode-difference.aep", - "238-shape-rect-rounded-corners.aep", - "239-shape-stroke-green-w8-round.aep", - "240-shape-custom-path-tangents.aep", - "241-shape-gradient-fill-linear.aep", - "242-shape-group-position-50-50.aep", - "243-text-multiline-A-CR-B.aep", - "245-text-box-400x200-Hello.aep", - "246-text-box-center-align.aep", - "247-text-tracking-100.aep", - "248-text-range-fill-red-1-3.aep", - "249-marker-layer-full.aep", - "251-camera-one-node.aep", - "252-light-point.aep", - "253-camera-position-100-200-m1000.aep", - "254-light-spot-intensity-50.aep", - "256-camera-two-node-default.aep", - "259-solid-blue-0-0-1.aep", - "299-save-noise.aep", - "300-fx-gaussianblur-0-explicit.aep", - "301-fx-gaussianblur-40-then-25.aep", - "302-fx-fill-opacity-100-explicit.aep", - "303-fx-fill-opacity-50-then-100.aep", - "304-fx-slider-0-explicit.aep", - "305-key-scale-bezier-ease.aep", - "306-key-maskfeather-bezier-ease.aep", - "307-key-fillcolor-bezier.aep", - "309-solid-100x100-mask-rect.aep", - "310-solid-100x100-pointcontrol.aep", - "311-position-default-explicit.aep", - "316-layer-stretch50.aep", - "317-layer-stretch150.aep", - "318-layer-inpoint-0.3333.aep", - "319-precomp-timeremap.aep", - "320-fx-layercontrol-self-explicit.aep", - "321-fx-layercontrol-none.aep", - "323-fx-dropdown-5items.aep", - "324-fx-dropdown-5items-select3.aep", - "325-comp-pixelaspect-0.9091.aep", - "326-comp-shutterphase-m90.aep", - "327-comp-displaystartframe-100.aep", - "328-mask-two-ellipse-rect.aep", - "329-mask-ellipse-mode-none.aep", - "330-shape-polystar-star-5-50-100.aep", - "331-shape-polystar-polygon-5-100.aep", - "332-shape-gradient-fill-radial.aep", - "333-shape-group-two-rects.aep", - "334-text-box-right-align.aep", - "335-text-point-fauxbold.aep", - "336-text-point-fauxitalic.aep", - "337-text-point-allcaps.aep", - "338-text-point-smallcaps.aep", - "339-text-point-leading60.aep", - "340-text-range-two-styles.aep", - "341-camera-zoom-2000.aep", - "342-camera-dof-800-30.aep", - "343-light-spot-color-red.aep", - "344-light-spot-coneangle-60.aep", - "345-light-spot-conefeather-30.aep", - "347-marker-layer-label3.aep", - "348-marker-layer-navigation-cue.aep", - "349-marker-layer-event-cue-params.aep", - "350-footage-wav-imported.aep", - "351-footage-wav-as-layer.aep", - "352-footage-pngseq-imported.aep", - "354-footage-pngseq-timeremap.aep", - "356-fx-tint-default.aep", - "357-fx-tint-black-0.2-0.4-0.6.aep", - "361-fx-tint-amount-0.aep", - "363-fx-tint-amount-2key.aep", - "364-fx-tint-white-2key.aep", - "366-fx-blur-then-tint.aep", - "368-fx-ramp-default.aep", - "369-fx-ramp-start-100-200.aep", - "371-fx-ramp-startcolor-red.aep", - "374-fx-ramp-end-2000-m100.aep", - "377-fx-ramp-shape-radial.aep", - "378-fx-ramp-scatter-12.aep", - "380-fx-ramp-blend-25pct.aep", - "382-fx-ramp-start-2key.aep", - "383-fx-ramp-on-100x100-start-10-20.aep", - "389-fx-exposure-default.aep", - "390-fx-exposure-channels-individual.aep", - "391-fx-exposure-master-1.5.aep", - "393-fx-exposure-offset-0.1.aep", - "394-fx-exposure-gamma-2.2.aep", - "395-fx-exposure-individual-red-1.aep", - "396-fx-exposure-bypass-on.aep", - "397-fx-exposure-master-2key.aep", - "403-matte-L-alpha-M.aep", - "404-matte-L-alphainv-M.aep", - "405-matte-L-luma-M.aep", - "406-matte-L-lumainv-M.aep", - "407-matte-M-alpha-L-below.aep", - "408-matte-L-alpha-M-visible.aep", - "509-marker-comp-two.aep", - "510-marker-layer-0.52-dur0.3.aep", - "451-shape-ellipse-400x300-fill.aep", - "457-shape-group-scale-50-80.aep", - "462-shape-layer-anchor-10-20.aep", - "464-shape-stroke-opacity-50.aep", - "467-shape-trim-end-70.aep", - "469-shape-trim-type-2.aep", - "471-shape-rect-roundness-30.aep", - "473-shape-star-points-6.aep", - "482-shape-two-groups.aep", - "483-shape-nested-group-rect.aep", - "519-shape-all-items-default.aep", - "410-fx-invert-channel-2.aep", - "411-fx-invert-blend-50.aep", - "413-fx-fastbox-radius-20.aep", - "414-fx-fastbox-iterations-1.aep", - "416-fx-fastbox-repeatedge-off.aep", - "418-fx-gaussian-dimensions-3.aep", - "419-fx-gaussian-repeatedge-off.aep", - "422-fx-dropshadow-opacity-204.aep", - "426-fx-dropshadow-shadowonly-on.aep", - "427-fx-glow-default.aep", - "429-fx-glow-threshold-76.5.aep", - "438-fx-glow-midpoint-0.25.aep", - "444-fx-huesat-hue-90.aep", - "446-fx-huesat-light-m30.aep", - "448-fx-huesat-colorizehue-120.aep", - "512-fx-levels-inblack-0.1.aep", - "514-fx-levels-gamma-2.aep", - "516-fx-levels-outwhite-0.9.aep", - "517-text-box-600x400-wrap.aep", - "526-text-point-HHHH-default.aep", - "527-text-point-HHHH-baseline-normal.aep", - "528-text-point-HHHH-baseline-subscript.aep", - "485-layer-3d-on.aep", - "486-layer-3d-rotx-30.aep", - "487-layer-3d-roty-45.aep", - "488-layer-3d-orientation-10-20-30.aep", - "529-fx-timewarp-default.aep", - "530-fx-timewarp-speed-25.aep", - "531-fx-timewarp-speed-keyed-50-200.aep", - "532-fx-timewarp-method-1.aep", - "533-fx-timewarp-sourceframe-12.aep", - "534-fx-slider-expression-time10.aep", - "535-camera-position-on-3d-rotx.aep", - "536-camera-one-node-position-on-3d-rotx.aep", - "537-camera-default-on-3d-rotx.aep", - "538-text-point-HHHH-normal-ref.aep", - "539-text-hscale-0.9.aep", - "540-text-vscale-1.5.aep", - "541-text-baselineshift-41.aep", - "542-text-autokern-none.aep", - "543-text-autokern-optical.aep", - "544-text-applystroke-on.aep", - "545-text-strokewidth-5.aep", - "546-text-applyfill-off.aep", - "548-text-linejoin-round.aep", - "550-text-strokeoverfill-off.aep", - "552-text-nobreak-on.aep", - "553-text-tsume-0.5.aep", - "554-text-kerning-50.aep", - "555-text-ligature-on.aep", - "556-text-autohyphenate-off.aep", - "558-text-hangingroman-on.aep", - "559-text-everyline-on.aep", - "560-text-firstlineindent-20.aep", - "561-text-startindent-30.aep", - "562-text-endindent-40.aep", - "563-text-spacebefore-10.aep", - "564-text-spaceafter-12.aep", - "565-text-justify-fullleft.aep", - "566-text-justify-fullcenter.aep", - "567-text-justify-fullright.aep", - "568-text-justify-fullall.aep", - "569-text-direction-rtl.aep", - "571-text-digitset-arabic.aep", - "572-text-leadingtype-japanese.aep", - "573-text-baselinedir-rotated.aep", - "575-text-vertical-rtl.aep", - "576-text-baselinedir-crossstream.aep", - "578-text-digitset-hindi.aep", - "595-text-stroke-scale-shift-combined.aep", - "596-text-combined-fill-over-stroke.aep", - "579-textanim-position-0-m50.aep", - "580-textanim-start-25.aep", - "581-textanim-end-75.aep", - "582-textanim-offset-10.aep", - "583-textanim-units-index.aep", - "584-textanim-basedon-3-words.aep", - "585-textanim-mode-2-subtract.aep", - "586-textanim-amount-50.aep", - "587-textanim-shape-2-rampup.aep", - "588-textanim-smoothness-50.aep", - "589-textanim-easehigh-30.aep", - "590-textanim-easelow-40.aep", - "591-textanim-randomize-seed-7.aep", - "592-textanim-many-props.aep", - "593-textanim-start-keyed-ease-0-100.aep", - "594-textanim-position-start-keyed-ease.aep", - "725-text-point-HHHH-normal-ref-S18.aep", - "727-text-reset-paragraph.aep", - "728-textanim-character-offset-3.aep", - "711-fx-directional-blur-30-40-on-M.aep", - "712-fx-eleven-effects-defaults-on-M.aep", - "713-fx-radial-blur-zoom-20-on-M.aep", - "714-fx-ccradial-type2-30-60-on-M.aep", - "715-fx-venetian-40-30-50-5-on-M.aep", - "716-fx-channel-blur-5-10-15-20-edge-horiz-on-M.aep", - "717-fx-blackwhite-set-tint-on-L.aep", - "718-fx-tritone-set-blend25-on-L.aep", - "719-fx-lumakey-darker-140-20-1-2.5-on-M.aep", - "720-fx-simplechoker-3.5-on-M.aep", - "721-fx-simplechoker-3.5-view-matte-on-M.aep", - "722-fx-mattechoker-set-on-M.aep", - "723-fx-transform-set-on-M.aep", - "597-key-anchor-ease-out50-40-in30-60.aep", - "598-key-ramp-point-ease-color-bezier.aep", - "599-key-mask-path-ease-infl75.aep", - "700-key-mask-path-ease-out20-in50.aep", - "701-light-parallel-int80-color.aep", - "702-light-ambient-int50-color.aep", - "703-key-orientation-0-to-10-20-30-linear.aep", - "704-light-environment-default.aep", - "705-mask-on-text-rect-40-m70-160-10.aep", - "706-mask-on-shape-rect-0-m150-100-150.aep", - "707-shape-merge-subtract-rect-ellipse.aep", - "708-shape-merge-intersect-rect-ellipse.aep", - "709-shape-repeater-3-pos150-60-rot10-scale90-80-op40.aep", - "710-shape-offset-paths-20-round.aep", - "730-key-anchor-ease-on-400x800-solid.aep", - "731-shape-merge-offset-repeater-defaults.aep", - "732-text-box-byteedit-para24-0.aep", - "733-text-box-byteedit-para35-0.aep", - "734-text-box-byteedit-style68-1.aep", - "828-shape-offset-paths-20-copies3-copyoffset1.5-stroke.aep", - "851-shape-key-trim-end-0-100-linear.aep", - "852-shape-key-trim-end-bezier-out0-60-in20-30.aep", - "853-shape-key-group-position-0-200-100-linear.aep", - "854-shape-key-fill-color-red-blue-linear.aep", - "855-shape-key-trim-offset-0-90-hold.aep", - "856-shape-trim-end-expression-time50.aep", - "857-shape-key-group-scale-100-50-150-linear.aep", - "900-mask-added-no-path.aep", - "901-mask-no-path-expansion-m100.aep", - "902-settings-rec709-16bpc-steps-png-grey-solid.aep", - "905-fx-24-effects-set-one-comp.aep", - "906-blendmodes-13-solids-on-steps.aep", - "963-curves-red-mid-down-on-S.aep", - "964-curves-rgb-s-curve-on-S.aep", - "951-styles-all-nine-defaults-on-B.aep", - "966-style-drop-shadow-opacity50-distance20.aep", - "970-style-stroke-size10-color-green.aep", - "974-style-gradient-overlay-angle45-scale150.aep", - "975-style-fill-opacity0-with-drop-shadow.aep", - "976-style-drop-shadow-opacity-keyed-100-20-linear.aep", - "977-styles-all-params-changed.aep", - "979-style-inner-glow-source-2.aep", - "981-layer-stretch-minus100-start5.aep", - "982-layer-stretch-minus100-opacity-keys.aep", - "983-layer-stretch-minus50-opacity-keys.aep", - "985-meshwarp-3x3-vertex-moved-on-S.aep", - "986-shape-fill-switched-off-green.aep", - "988-style-drop-shadow-switched-off.aep", -]; - -use effectcraft_aep::{AepFile, Comp, Layer, LayerType, Project, parse}; - -/// Parses a fixture; the bytes must outlive the file, so the caller keeps them. -pub fn open(bytes: &[u8]) -> AepFile<'_> { - parse(bytes).expect("fixture parses") -} - -/// The first composition of a project (comp `C` in the corpus; in 124 the precomp `Pre` comes later). -pub fn first_comp<'f, 'a>(project: &Project<'f, 'a>) -> Comp<'f, 'a> { - project.all_items().into_iter().find_map(|i| i.comp()).expect("a composition") -} - -/// The solid `L` of the base composition: the bottom layer (the first one made; id 0x1b in the -/// single-case files, another id in each case of a combined file). -pub fn base_layer<'f, 'a>(comp: &Comp<'f, 'a>) -> Layer<'f, 'a> { - comp.layers().last().expect("a layer") -} - -/// The layer with this id in a composition. -pub fn layer_with_id<'f, 'a>(comp: &Comp<'f, 'a>, id: u32) -> Layer<'f, 'a> { - comp.layers().find(|l| l.id() == Some(id)).unwrap_or_else(|| panic!("no layer with id {id:#x}")) -} - -/// The layer with this user-set name in a composition. -pub fn layer_named<'f, 'a>(comp: &Comp<'f, 'a>, name: &str) -> Layer<'f, 'a> { - comp.layers().find(|l| l.name().as_deref() == Some(name)).unwrap_or_else(|| panic!("no layer named {name}")) -} - -/// The layer that shows this name: its own name, or its source's while it has none. -pub fn layer_shown_as<'f, 'a>(project: &Project<'f, 'a>, comp: &Comp<'f, 'a>, name: &str) -> Layer<'f, 'a> { - let shown = |l: &Layer<'f, 'a>| l.name().or_else(|| project.layer_source(l)?.display_name()); - comp.layers().find(|l| shown(l).as_deref() == Some(name)).unwrap_or_else(|| panic!("no layer shown as {name}")) -} - -/// The first layer of this type in a composition. -pub fn layer_of_type<'f, 'a>(comp: &Comp<'f, 'a>, layer_type: LayerType) -> Layer<'f, 'a> { - comp.layers().find(|l| l.header().is_some_and(|h| h.layer_type == layer_type)).unwrap_or_else(|| panic!("no {layer_type:?} layer")) -} - -/// A copy of a layer's `LIST Layr` with its id (`ldta` bytes 0-3) set to 0, for comparing the -/// same layer in two cases of a combined file. -pub fn without_layer_id(layer: &effectcraft_aep::Chunk<'_>) -> effectcraft_aep::Chunk<'static> { - let mut c = layer.clone().into_owned(); - if let effectcraft_aep::Body::List { children, .. } = &mut c.body - && let Some(ldta) = children.iter_mut().find(|x| x.is(b"ldta")) - && let effectcraft_aep::Body::Data(d) = &mut ldta.body - { - d.to_mut()[..4].fill(0); - } - c -} - -/// Compares floats with a tolerance. -pub fn near(a: f64, b: f64, tol: f64) -> bool { - (a - b).abs() <= tol -} - -pub fn assert_near(got: &[f64], want: &[f64], tol: f64) { - assert_eq!(got.len(), want.len(), "{got:?} vs {want:?}"); - for (g, w) in got.iter().zip(want) { - assert!(near(*g, *w, tol), "{got:?} != {want:?}"); - } -} diff --git a/crates/aep/tests/it/container/keyframes.rs b/crates/aep/tests/it/container/keyframes.rs deleted file mode 100644 index ac7b35ff7..000000000 --- a/crates/aep/tests/it/container/keyframes.rs +++ /dev/null @@ -1,233 +0,0 @@ -//! Keyframe interpolation sides and ease, the record layouts per template, the anchor point -//! normalisation and the disabled-expression flag, checked against the values the corpus was made -//! with (its MANIFEST, batch 2). The solid `L` is 1920x1080 in a 1920x1080 composition. - -use crate::container::helpers::{assert_near, base_layer, first_comp, layer_shown_as, open}; -use effectcraft_aep::{Interpolation, KeyEase, KeyframeKind, Project, PropNode, Property, ValueSource}; - -fn prop_of(name: &str, path: &[&str], f: impl FnOnce(Property<'_, '_>) -> R) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let Some(PropNode::Property(p)) = layer.properties().unwrap().find(path) else { panic!("{name}: no {path:?}") }; - f(p) - }) -} - -const POSITION: &[&str] = &["ADBE Transform Group", "ADBE Position"]; -const OPACITY: &[&str] = &["ADBE Transform Group", "ADBE Opacity"]; - -/// The ease of a linear key: all four slots 0. -const NO_EASE: KeyEase = KeyEase { in_speed: 0.0, in_influence: 0.0, out_speed: 0.0, out_influence: 0.0 }; - -fn ease(in_speed: f64, in_influence: f64, out_speed: f64, out_influence: f64) -> KeyEase { - KeyEase { in_speed, in_influence, out_speed, out_influence } -} - -#[test] -fn in_and_out_interpolation_are_separate_bytes() { - // 202: Position keys at 0 s [0,0,0] and 1 s [100,0,0]; key 1 inType LINEAR, outType HOLD (record bytes 01 03). - skip!(prop_of("202-key-out-hold-in-linear.aep", POSITION, |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - assert_eq!(&keys[0].raw()[4..6], [1, 3]); - assert_eq!((keys[0].interpolation_in(), keys[0].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Hold))); - assert_eq!((keys[1].interpolation_in(), keys[1].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); - assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 1.0]); - assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); - })); - // 203: key 1 inType HOLD, outType LINEAR (bytes 03 01): byte 4 is the incoming side. - skip!(prop_of("203-key-in-hold-out-linear.aep", POSITION, |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert_eq!(&keys[0].raw()[4..6], [3, 1]); - assert_eq!((keys[0].interpolation_in(), keys[0].interpolation_out()), (Some(Interpolation::Hold), Some(Interpolation::Linear))); - assert_eq!((keys[1].interpolation_in(), keys[1].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); - })); -} - -#[test] -fn position_ease_slots_in_speed_influence_out_speed_influence() { - // 204: key 1 inSpeed 5 / inInfluence 20, outSpeed 50 / outInfluence 80; key 2 in 7 / 60, out 9 / 40. - // After Effects reads key 1's in speed and key 2's out speed back as 0; the file keeps 5 and 9. - skip!(prop_of("204-key-ease-asymmetric.aep", POSITION, |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert_eq!(keys[0].ease(), Some(ease(5.0, 0.2, 50.0, 0.8))); - assert_eq!(keys[1].ease(), Some(ease(7.0, 0.6, 9.0, 0.4))); - for k in &keys { - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); - assert_eq!(k.kind(), KeyframeKind::Spatial { components: 3 }); - } - // The spatial record gives the same four slots. - assert_eq!(keys[0].spatial().unwrap().ease, [5.0, 0.2, 50.0, 0.8]); - // The arc length of the segment to the next key (100 px) is on key 1, none on the last key. - assert_eq!(keys.iter().map(|k| k.spatial().unwrap().segment_length).collect::>(), [100.0, 0.0]); - })); -} - -#[test] -fn opacity_ease_speed_is_in_stored_units_per_second() { - // 205: Opacity 0 at 0 s, 100 at 2 s; key 1 in 5 / 20 %, out 20 / 80 %; key 2 in 30 / 60 %, out 9 / 40 %. - // The speed is in stored value units (fractions), 100 times smaller than the UI value; the influence is a fraction. - skip!(prop_of("205-key-opacity-ease-asymmetric.aep", OPACITY, |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Plain { components: 1 } && k.raw().len() == 48)); - assert_eq!(keys.iter().map(|k| k.scalar_value().unwrap()).collect::>(), [0.0, 1.0]); - assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 2.0]); - let e0 = keys[0].ease().unwrap(); - assert_near(&[e0.in_speed, e0.in_influence, e0.out_speed, e0.out_influence], &[0.05, 0.2, 0.2, 0.8], 1e-12); - let e1 = keys[1].ease().unwrap(); - assert_near(&[e1.in_speed, e1.in_influence, e1.out_speed, e1.out_influence], &[0.3, 0.6, 0.09, 0.4], 1e-12); - assert_eq!(keys[0].ease_components(), Some(vec![e0])); - for k in &keys { - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); - } - })); -} - -#[test] -fn scale_keys_use_the_plain_template_with_three_components() { - // 206: Scale keys at 0 s [100,100,100] and 1 s [200,150,100], linear: 128-byte plain records. - skip!(prop_of("206-key-scale-2key-linear.aep", &["ADBE Transform Group", "ADBE Scale"], |p| { - assert_eq!(p.dims(), Some(3)); - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - for k in &keys { - assert_eq!(k.raw().len(), 128); - // A 128-byte record is not always spatial: the header's template flag decides. - assert_eq!(k.kind(), KeyframeKind::Plain { components: 3 }); - assert_eq!(k.spatial(), None); - assert_eq!(k.ease_components(), Some(vec![NO_EASE; 3])); - assert_eq!(k.ease(), None); - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); - } - assert_eq!(keys.iter().map(|k| k.value().unwrap()).collect::>(), [vec![1.0, 1.0, 1.0], vec![2.0, 1.5, 1.0]]); - assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 1.0]); - assert_eq!(p.first_key_value(), Some(vec![1.0, 1.0, 1.0])); - })); - // The transform reports the first key as percent (before the template flag was used it read the wrong bytes). - let bytes = fixture!("206-key-scale-2key-linear.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let t = layer.transform(1920, 1080).unwrap(); - assert_eq!((t.scale_percent.source, t.scale_percent.value), (ValueSource::Keyframed, [100.0, 100.0, 100.0])); -} - -#[test] -fn two_dimensional_mask_feather_keys() { - // 208: Mask Feather keys at 0 s [0,0] and 1 s [40,20], linear: 88-byte plain records with two components. - let bytes = fixture!("208-key-mask-feather-2key-linear.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let Some(PropNode::Group(parade)) = layer.properties().unwrap().get("ADBE Mask Parade") else { panic!("no mask parade") }; - let Some(PropNode::Group(atom)) = parade.get("ADBE Mask Atom") else { panic!("no mask atom") }; - let Some(PropNode::Property(feather)) = atom.get("ADBE Mask Feather") else { panic!("no feather") }; - let keys: Vec<_> = feather.keys().unwrap().keyframes().collect(); - assert!(keys.iter().all(|k| k.raw().len() == 88 && k.kind() == KeyframeKind::Plain { components: 2 })); - assert_eq!(keys.iter().map(|k| k.value().unwrap()).collect::>(), [vec![0.0, 0.0], vec![40.0, 20.0]]); - assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 1.0]); - assert_eq!(keys[0].ease_components(), Some(vec![NO_EASE; 2])); - let mask = &layer.masks()[0]; - assert!(mask.feather.source == ValueSource::Keyframed && mask.feather.value == [0.0, 0.0]); -} - -#[test] -fn colour_keys_use_the_spatial_template_with_four_components() { - // 210: Fill colour keys at 0 s [1,0,0] and 1 s [0,0.5,1], linear: 152-byte records, ARGB doubles 0..255 at byte 56. - let bytes = fixture!("210-key-fill-color-2key-linear.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let effects = layer.effects(); - assert_eq!(effects.len(), 1); - let params = effects[0].params(); - let color = params.iter().find(|p| p.name == "Color").unwrap(); - let keys: Vec<_> = color.stored().unwrap().keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - for k in &keys { - assert_eq!(k.raw().len(), 152); - assert_eq!(k.kind(), KeyframeKind::Spatial { components: 4 }); - assert_eq!(k.flags(), Some(0x0001)); - let s = k.spatial().unwrap(); - assert_eq!(s.in_tangent, [0.0; 4]); - assert_eq!(s.out_tangent, [0.0; 4]); - } - assert_eq!(keys[0].value(), Some(vec![255.0, 255.0, 0.0, 0.0])); - assert_eq!(keys[1].value(), Some(vec![255.0, 0.0, 127.5, 255.0])); - assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 1.0]); - // A keyframed parameter has no single stored value. - assert_eq!(color.stored_value(), None); -} - -#[test] -fn keyed_slider_uses_48_byte_records() { - // 221: Slider Control, Slider keyed 10 at 0 s and 90 at 2 s (linear). - let bytes = fixture!("221-fx-slider-2key.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let params = project.effect_params(&layer.effects()[0]); - let slider = params.iter().find(|p| p.name == "Slider").unwrap(); - let stored = slider.stored().unwrap(); - assert!(stored.is_animated()); - assert_eq!(stored.static_value(), None); - let keys: Vec<_> = stored.keys().unwrap().keyframes().collect(); - assert!(keys.iter().all(|k| k.raw().len() == 48)); - assert_eq!(keys.iter().filter_map(|k| k.scalar_value()).collect::>(), [10.0, 90.0]); - assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 2.0]); -} - -#[test] -fn anchor_is_a_fraction_of_the_layer_source_size() { - // 211: a new 100x100 solid in the 1920x1080 composition, Anchor Point [50,50,0] -> [10,20,0], stored [0.1, 0.2, 0]. - // 212: a 400x300 solid, Anchor Point [100,50,0], stored [0.25, 1/6, 0]. The composition size is not the divisor. - for (name, solid, size, fraction, px) in [ - ("211-anchor-100x100-solid-10-20.aep", "S100", (100, 100), [0.1, 0.2, 0.0], [10.0, 20.0, 0.0]), - ("212-anchor-400x300-solid-100-50.aep", "S400", (400, 300), [0.25, 1.0 / 6.0, 0.0], [100.0, 50.0, 0.0]), - ] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_shown_as(&project, &comp, solid); - assert_eq!(project.layer_source_size(&layer), Some(size), "{name}"); - let t = layer.transform(1920, 1080).unwrap(); - assert_eq!(t.anchor_fraction.source, ValueSource::Stored); - assert_near(&t.anchor_fraction.value, &fraction, 1e-12); - let anchor = project.layer_anchor_px(&layer).unwrap(); - assert_eq!(anchor.source, ValueSource::Stored); - assert_near(&anchor.value, &px, 1e-9); - // Position stays at the default, the composition centre. - assert_eq!((t.position.source, t.position.value), (ValueSource::Default, [960.0, 540.0, 0.0])); - // L is unchanged: the anchor is its centre. - let l = base_layer(&comp); - let a = project.layer_anchor_px(&l).unwrap(); - assert_eq!((a.source, a.value), (ValueSource::Default, [960.0, 540.0, 0.0])); - } -} - -fn expression_state(name: &str) -> Option<(Option, Option, bool, bool)> { - Some({ - prop_of(name, OPACITY, |p| { - let f = p.expression_flags().unwrap(); - // Byte 120 marks the expression (bytes 76 and 77 are not always set with it). - (p.expression(), p.expression_enabled(), f.byte_120 == 1, f.disabled()) - })? - }) -} - -#[test] -fn disabled_expression_keeps_its_text() { - // 060: Opacity wiggle(1,10), enabled; 213: the same expression after expression.disable_all. - assert_eq!(skip!(expression_state("060-expr-opacity-wiggle.aep")), (Some("wiggle(1,10)".to_string()), Some(true), true, false)); - assert_eq!(skip!(expression_state("213-expr-opacity-wiggle-disabled.aep")), (Some("wiggle(1,10)".to_string()), Some(false), true, true)); - // Only byte 119 differs between the two property headers. - let header = |name: &str| prop_of(name, OPACITY, |p| p.header().unwrap().to_vec()); - let (enabled, disabled) = (skip!(header("060-expr-opacity-wiggle.aep")), skip!(header("213-expr-opacity-wiggle-disabled.aep"))); - let differing: Vec<_> = (0..enabled.len()).filter(|i| enabled[*i] != disabled[*i]).collect(); - assert_eq!(differing, [119]); - // A property without an expression has no enabled state. - assert_eq!(skip!(prop_of("058-key-opacity-2key.aep", OPACITY, |p| p.expression_enabled())), None); -} diff --git a/crates/aep/tests/it/container/layer_switches.rs b/crates/aep/tests/it/container/layer_switches.rs deleted file mode 100644 index 3d1f764fb..000000000 --- a/crates/aep/tests/it/container/layer_switches.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! Layer switches, blend modes, composition frame rates and background, cameras, lights and solid -//! colours, checked against the values the corpus was made with (its MANIFEST, batch 2). - -use crate::container::helpers::{assert_near, base_layer, first_comp, layer_of_type, layer_shown_as, open}; -use effectcraft_aep::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Project}; - -fn l_header(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - base_layer(&first_comp(&project)).header().unwrap() - }) -} - -fn comp_header(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - first_comp(&project).header().unwrap() - }) -} - -#[test] -fn video_audio_and_effects_switches_are_bits_1_2_and_4_of_byte_39() { - // The base has all three on (byte 39 = 07); 222 turns the video switch off (06), 223 the audio switch - // (05), 224 the effects switch (03). Each case changes only that byte. - for (name, byte, video, audio, effects) in [ - ("000-base.aep", 0x07, true, true, true), - ("222-layer-video-off.aep", 0x06, false, true, true), - ("223-layer-audio-off.aep", 0x05, true, false, true), - ("224-layer-effects-off.aep", 0x03, true, true, false), - ] { - let h = skip!(l_header(name)); - assert_eq!(h.flag_bytes[2], byte, "{name}"); - assert_eq!((h.is_video_enabled(), h.is_audio_enabled(), h.is_effects_enabled()), (video, audio, effects), "{name}"); - assert_eq!(h.is_enabled(), video, "{name}"); - // The other switches stay as in the base. - assert!(!h.is_shy() && !h.is_locked() && !h.is_motion_blur() && !h.collapses_transformations(), "{name}"); - } - let bytes = fixture!("222-layer-video-off.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - assert_eq!((layer.is_enabled(), layer.is_audio_enabled(), layer.is_effects_enabled()), (Some(false), Some(true), Some(true))); - // Only byte 39 of ldta differs from the base layer (besides the layer id, bytes 0-3: the two - // are layers of one combined file). - let base_bytes = fixture!("000-base.aep"); - let base_file = open(&base_bytes); - let base_project = Project::new(&base_file).unwrap(); - let base_ldta = base_layer(&first_comp(&base_project)).chunk().child(b"ldta").unwrap().bytes().unwrap().to_vec(); - let ldta = layer.chunk().child(b"ldta").unwrap().bytes().unwrap(); - let differing: Vec<_> = (4..ldta.len()).filter(|i| ldta[*i] != base_ldta[*i]).collect(); - assert_eq!(differing, [39]); -} - -#[test] -fn blend_mode_codes() { - // Normal 2 (base), Multiply 5 (016), Screen 6 (225), Add 4 (226), Overlay 7 (227), Difference 26 (228). - for (name, mode, code) in [ - ("000-base.aep", BlendMode::Normal, 2), - ("016-layer-blend-multiply.aep", BlendMode::Multiply, 5), - ("225-layer-blend-screen.aep", BlendMode::Screen, 6), - ("226-layer-blend-add.aep", BlendMode::Add, 4), - ("227-layer-blend-overlay.aep", BlendMode::Overlay, 7), - ("228-layer-blend-difference.aep", BlendMode::Difference, 26), - ] { - let h = skip!(l_header(name)); - assert_eq!((h.blend_mode, h.blend_mode.code()), (mode, code), "{name}"); - assert_eq!(BlendMode::from_code(code), mode); - } - // A mode that was not sampled keeps its raw code. - assert_eq!(BlendMode::from_code(30), BlendMode::Other(30)); - assert_eq!(BlendMode::Other(30).code(), 30); -} - -#[test] -fn ntsc_frame_rates_are_exact_fractions() { - // 229: frameRate 29.97 -> read back 29.9700012207031; the duration snaps from 5 s to 150 frames (5.005005 s). - let h = skip!(comp_header("229-comp-fps-29.97.aep")); - assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (800, 23976)); - assert!((h.frame_rate().unwrap() - 29.97).abs() < 1e-12); - // The 16.16 rate holds the float32 29.97 (29.9700012207031). - assert_eq!(h.frame_rate_fixed, 1_964_114); - // 150 frames of 800 units. - assert_eq!(h.duration_units, 120_000); - assert!((h.duration_seconds().unwrap() - 5.005_005_005_005_01).abs() < 1e-9); - // 230: frameRate 23.976 -> read back 23.9759979248047; 120 frames. - let h = skip!(comp_header("230-comp-fps-23.976.aep")); - assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1000, 23976)); - assert!((h.frame_rate().unwrap() - 23.976).abs() < 1e-12); - // The 16.16 rate holds the float32 23.976 (23.9759979248047). - assert_eq!(h.frame_rate_fixed, 1_571_291); - // 120 frames of 1000 units. - assert_eq!(h.duration_units, 120_000); - assert!((h.duration_seconds().unwrap() - 5.005_005_005_005_01).abs() < 1e-9); - // 25 fps stays 25. - let h = skip!(comp_header("000-base.aep")); - assert_eq!((h.time_base.timescale, h.time_base.frame_duration, h.duration_units), (25600, 1024, 128_000)); -} - -#[test] -fn keyframe_times_follow_the_ntsc_timescale() { - // All keyframe time scales in the composition follow its timescale (tdb4 byte 12 = 23976 in every property). - for name in ["229-comp-fps-29.97.aep", "230-comp-fps-23.976.aep"] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let mut scales = std::collections::BTreeSet::new(); - let mut stack = vec![layer.properties().unwrap()]; - while let Some(group) = stack.pop() { - for e in group.entries() { - match e.node { - effectcraft_aep::PropNode::Group(g) => stack.push(g), - effectcraft_aep::PropNode::Property(p) => { - scales.extend(p.time_scale()); - } - effectcraft_aep::PropNode::Other(_) => {} - } - } - } - assert_eq!(scales.into_iter().collect::>(), [23976], "{name}"); - } -} - -#[test] -fn background_is_8_bits_per_channel() { - // 231: bgColor [0.5, 0.5, 0.5] is stored as 128 and reads back as 128/255 = 0.50196. - let h = skip!(comp_header("231-comp-bg-grey-0.5.aep")); - assert_eq!(h.background, [128, 128, 128]); - // The frame rate stays 25 even though an earlier edit of the AE session left other numbers in the cache-like fields. - assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 25600)); -} - -#[test] -fn cameras_auto_orient_and_position() { - // 256: the default two-node camera (ldta byte 38 = 0x44); 251: one-node (autoOrient off, 0x04). - let bytes = fixture!("256-camera-two-node-default.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let camera = layer_of_type(&comp, LayerType::Camera); - let h = camera.header().unwrap(); - assert_eq!((h.flag_bytes[1], h.is_auto_oriented(), h.is_three_d(), h.source_id, h.light_type()), (0x44, true, true, None, None)); - // The default Position is an "auto state" record that stores [0, 0, -2666.67]. - let pos = camera.camera_position().unwrap(); - assert!(pos.auto_state); - assert_near(&pos.stored, &[0.0, 0.0, -2666.67], 0.01); - - let bytes = fixture!("251-camera-one-node.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let camera = layer_of_type(&first_comp(&project), LayerType::Camera); - let h = camera.header().unwrap(); - assert_eq!((h.flag_bytes[1], h.is_auto_oriented(), h.is_three_d()), (0x04, false, true)); - // AE reports [0, 0, -2666.67] for the one-node camera: the stored value. - let pos = camera.camera_position().unwrap(); - assert!(pos.auto_state); - assert_near(&pos.stored, &[0.0, 0.0, -2666.67], 0.01); - - // 253: Position set to [100, 200, -1000]: stored as given, no auto state. - let bytes = fixture!("253-camera-position-100-200-m1000.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let camera = layer_of_type(&first_comp(&project), LayerType::Camera); - let pos = camera.camera_position().unwrap(); - assert!(!pos.auto_state); - assert_eq!(pos.stored, [100.0, 200.0, -1000.0]); -} - -/// Lights type and position. -#[test] -fn lights_type_and_position() { - // 254: a spot light (its Intensity 50 is checked on import). - let bytes = fixture!("254-light-spot-intensity-50.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let light = layer_of_type(&first_comp(&project), LayerType::Light); - let h = light.header().unwrap(); - assert_eq!((h.light_type(), h.light_type_code, h.source_id, h.is_auto_oriented(), h.is_three_d()), (Some(LightType::Spot), 1, None, true, true)); - assert!(light.camera_position().unwrap().auto_state); - assert_near(&light.camera_position().unwrap().stored, &[0.0, 0.0, -1333.33], 0.01); - - // 252: a point light (light type 2). - let bytes = fixture!("252-light-point.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let light = layer_of_type(&first_comp(&project), LayerType::Light); - let h = light.header().unwrap(); - assert_eq!((h.light_type(), h.light_type_code), (Some(LightType::Point), 2)); - // The solid under it is no light. - let solid = base_layer(&first_comp(&project)).header().unwrap(); - assert_eq!((solid.light_type(), solid.light_type_code), (None, 0)); -} - -#[test] -fn solid_colour_is_four_float32_argb() { - // 259: a new solid `Blue` [0, 0, 1] in the 1920x1080 composition: float32 ARGB 1.0, 0, 0, 1.0. - let bytes = fixture!("259-solid-blue-0-0-1.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let blue = layer_shown_as(&project, &comp, "Blue"); - assert_eq!(project.layer_source_size(&blue), Some((1920, 1080))); - let f = project.layer_source(&blue).unwrap().footage().unwrap(); - assert!(f.is_solid); - assert_eq!(f.solid_argb, Some([1.0, 0.0, 0.0, 1.0])); - assert_eq!(f.solid_rgb(), Some([0.0, 0.0, 1.0])); - // L is still red. - let red = project.layer_source(&base_layer(&comp)).unwrap().footage().unwrap(); - assert_eq!(red.solid_rgb(), Some([1.0, 0.0, 0.0])); - // The new layer has no name of its own (it shows its source's name). - assert_eq!(blue.name(), None); -} diff --git a/crates/aep/tests/it/container/masks.rs b/crates/aep/tests/it/container/masks.rs deleted file mode 100644 index a9c1b82c0..000000000 --- a/crates/aep/tests/it/container/masks.rs +++ /dev/null @@ -1,203 +0,0 @@ -//! Masks: mode, invert switch, feather / opacity / expansion, and the path shapes, checked against -//! the values the corpus was made with (its MANIFEST). The solid `L` is 1920x1080. - -use crate::container::helpers::{base_layer, first_comp, open}; -use effectcraft_aep::{KeyframeKind, Mask, MaskMode, PathVertex, Project, PropNode, Property, ShapePath, ValueSource}; - -const SIZE: (f64, f64) = (1920.0, 1080.0); - -fn masks(name: &str) -> Option> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - base_layer(&first_comp(&project)).masks() - }) -} - -fn assert_points(vertices: &[PathVertex], expected: &[[f64; 2]]) { - assert_eq!(vertices.len(), expected.len()); - for (v, e) in vertices.iter().zip(expected) { - for (got, want) in v.position.iter().zip(e) { - assert!((got - want).abs() < 1e-3, "{:?} != {e:?}", v.position); - } - // No tangents: both handles sit on the vertex. - assert_eq!(v.in_handle, v.position); - assert_eq!(v.out_handle, v.position); - } -} - -#[test] -fn no_masks_in_the_base() { - assert!(skip!(masks("000-base.aep")).is_empty()); -} - -#[test] -fn rectangular_mask_with_defaults() { - // 090: rect size [800,400], centre [960,540]: "Mask 1", vertices [560,340] [1360,340] [1360,740] [560,740], mode Add. - let m = skip!(masks("090-mask-rect.aep")); - assert_eq!(m.len(), 1); - let m = &m[0]; - assert_eq!(m.name.as_deref(), Some("Mask 1")); - assert_eq!((m.mode, m.inverted), (Some(MaskMode::Add), Some(false))); - // Feather, opacity and expansion are absent at their defaults. - assert_eq!((m.feather.value, m.feather.source), ([0.0, 0.0], ValueSource::Default)); - assert_eq!((m.opacity_percent.value, m.opacity_percent.source), (100.0, ValueSource::Default)); - assert_eq!((m.expansion.value, m.expansion.source), (0.0, ValueSource::Default)); - assert!(!m.path_animated); - assert!(m.path_key_seconds.is_empty()); - assert_eq!(m.shapes.len(), 1); - let s = &m.shapes[0]; - // The box is normalised to the layer size: 560/1920, 340/1080, 1360/1920, 740/1080. - let want_box = [560.0 / 1920.0, 340.0 / 1080.0, 1360.0 / 1920.0, 740.0 / 1080.0]; - for (got, want) in s.bbox.iter().zip(want_box) { - assert!((f64::from(*got) - want).abs() < 1e-6, "{:?}", s.bbox); - } - assert_eq!(s.closed_flag, 1); - assert_eq!(s.vertex_count(), 4); - // Three points per vertex, [vertex, out handle, next in handle], inside the box. - let rect: [[f32; 2]; 12] = - [[0.0, 0.0], [0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [0.0, 1.0], [0.0, 1.0], [0.0, 1.0], [0.0, 0.0]]; - assert_eq!(s.points, rect); - assert_points(&s.vertices(SIZE), &[[560.0, 340.0], [1360.0, 340.0], [1360.0, 740.0], [560.0, 740.0]]); -} - -#[test] -fn mask_properties_mode_and_invert() { - // 091: feather [0,0] -> [20,20], opacity 100 -> 50, mode Add -> Subtract, inverted, expansion 0 -> 5. - let m = skip!(masks("091-mask-rect-props.aep")); - let m = &m[0]; - assert_eq!((m.mode, m.inverted), (Some(MaskMode::Subtract), Some(true))); - assert_eq!((m.feather.value, m.feather.source), ([20.0, 20.0], ValueSource::Stored)); - assert_eq!((m.opacity_percent.value, m.opacity_percent.source), (50.0, ValueSource::Stored)); - assert_eq!((m.expansion.value, m.expansion.source), (5.0, ValueSource::Stored)); - // The path is unchanged from 090. - assert_points(&m.shapes[0].vertices(SIZE), &[[560.0, 340.0], [1360.0, 340.0], [1360.0, 740.0], [560.0, 740.0]]); -} - -#[test] -fn animated_mask_path_has_one_shape_per_key() { - // 093: path keys at t=0 (rect 400x200: [760,440] [1160,440] [1160,640] [760,640]) and t=1 (rect 800x400). - let m = skip!(masks("093-mask-path-2keys.aep")); - let m = &m[0]; - assert!(m.path_animated); - assert_eq!(m.path_key_seconds, [0.0, 1.0]); - // The path property keeps its keys in a list of 64-byte records (the shapes are in `shap`). - let bytes = fixture!("093-mask-path-2keys.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let Some(PropNode::Group(parade)) = layer.properties().unwrap().get("ADBE Mask Parade") else { panic!("mask parade") }; - let Some(PropNode::Group(atom)) = parade.get("ADBE Mask Atom") else { panic!("mask atom") }; - let Some(PropNode::Other(path)) = atom.get("ADBE Mask Shape") else { panic!("mask shape") }; - let prop = Property::from_chunk(path.child_list(b"tdbs").unwrap()).unwrap(); - let list = prop.keys().unwrap(); - assert_eq!((list.len(), list.header.record_size), (2, 64)); - assert!(list.keyframes().all(|k| k.kind() == KeyframeKind::MaskPath)); - assert_eq!(m.shapes.len(), 2); - assert_points(&m.shapes[0].vertices(SIZE), &[[760.0, 440.0], [1160.0, 440.0], [1160.0, 640.0], [760.0, 640.0]]); - assert_points(&m.shapes[1].vertices(SIZE), &[[560.0, 340.0], [1360.0, 340.0], [1360.0, 740.0], [560.0, 740.0]]); -} - -#[test] -fn shape_path_maths_with_a_pixel_box_and_tangents() { - // The documented point order [vertex i, out handle i, in handle i + 1] with a box in pixels (the - // shape-layer convention): a triangle [0,-100] [100,100] [-100,100] in the box (-100,-100,100,100), - // the first vertex with an out handle at [50,-100] and the last record the in handle of vertex 0. - let p = ShapePath { - bbox: [-100.0, -100.0, 100.0, 100.0], - closed_flag: 1, - open: false, - points: vec![ - [0.5, 0.0], - [0.75, 0.0], - [1.0, 1.0], // vertex 0, out handle 0, in handle 1 - [1.0, 1.0], - [1.0, 1.0], - [0.0, 1.0], // vertex 1, out handle 1, in handle 2 - [0.0, 1.0], - [0.0, 1.0], - [0.25, 0.0], // vertex 2, out handle 2, in handle 0 - ], - }; - let v = p.vertices((1.0, 1.0)); - assert_eq!(v.len(), 3); - assert_eq!(v[0].position, [0.0, -100.0]); - assert_eq!(v[0].out_handle, [50.0, -100.0]); - assert_eq!(v[0].in_handle, [-50.0, -100.0]); - assert_eq!(v[1].position, [100.0, 100.0]); - assert_eq!(v[1].in_handle, [100.0, 100.0]); - assert_eq!(v[2].position, [-100.0, 100.0]); - assert_eq!(v[2].out_handle, [-100.0, 100.0]); - assert!(ShapePath { bbox: [0.0; 4], closed_flag: 0, open: false, points: Vec::new() }.vertices((1.0, 1.0)).is_empty()); -} - -// ---------------------------------------------------------------------------- batch 2 - -fn near2(got: [f64; 2], want: [f64; 2], tol: f64) { - assert!((got[0] - want[0]).abs() < tol && (got[1] - want[1]).abs() < tol, "{got:?} != {want:?}"); -} - -#[test] -fn mask_mode_ids() { - // 090 Add 1, 091 Subtract 2, 234 Intersect 3, 235 Lighten 4, 236 Darken 5, 237 Difference 6. - for (name, mode, id) in [ - ("090-mask-rect.aep", MaskMode::Add, 1), - ("091-mask-rect-props.aep", MaskMode::Subtract, 2), - ("234-mask-mode-intersect.aep", MaskMode::Intersect, 3), - ("235-mask-mode-lighten.aep", MaskMode::Lighten, 4), - ("236-mask-mode-darken.aep", MaskMode::Darken, 5), - ("237-mask-mode-difference.aep", MaskMode::Difference, 6), - ] { - let m = skip!(masks(name)); - assert_eq!(m.len(), 1, "{name}"); - assert_eq!(m[0].mode, Some(mode), "{name}"); - assert_eq!(MaskMode::from_id(id), mode); - assert_eq!(m[0].name.as_deref(), Some("Mask 1")); - assert_eq!(m[0].shapes.len(), 1); - assert!(!m[0].shapes[0].open); - } - assert_eq!(MaskMode::from_id(0), MaskMode::None); - assert_eq!(MaskMode::from_id(9), MaskMode::Other(9)); -} - -#[test] -fn ellipse_has_tangents_of_0_5523_times_the_radius() { - // 232: ellipse 800x400 at [960,540]: vertices [960,340] [1360,540] [960,740] [560,540]; in tangents - // [-220.91,0] [0,-110.457] [220.91,0] [0,110.457]; out tangents the opposite ones; closed. - let m = skip!(masks("232-mask-ellipse.aep")); - let shape = &m[0].shapes[0]; - assert!(!shape.open); - assert_eq!(shape.vertex_count(), 4); - let v = shape.vertices(SIZE); - let vertices = [[960.0, 340.0], [1360.0, 540.0], [960.0, 740.0], [560.0, 540.0]]; - let in_tangents = [[-220.913_879, 0.0], [0.0, -110.456_97], [220.913_94, 0.0], [0.0, 110.456_97]]; - let out_tangents = [[220.913_94, 0.0], [0.0, 110.456_97], [-220.913_879, 0.0], [0.0, -110.456_97]]; - for i in 0..4 { - near2(v[i].position, vertices[i], 1e-3); - near2(v[i].in_tangent(), in_tangents[i], 1e-2); - near2(v[i].out_tangent(), out_tangents[i], 1e-2); - // Tangent = handle minus vertex. - near2(v[i].in_handle, [v[i].position[0] + v[i].in_tangent()[0], v[i].position[1] + v[i].in_tangent()[1]], 1e-9); - } - // The box is the vertex box 560,340,1360,740 (normalised to the 1920x1080 layer). - let [l, t, r, b] = shape.bbox.map(f64::from); - near2([l * SIZE.0, t * SIZE.1], [560.0, 340.0], 1e-2); - near2([r * SIZE.0, b * SIZE.1], [1360.0, 740.0], 1e-2); -} - -#[test] -fn open_path_has_bit_8_in_the_shph_flags() { - // 233: three vertices [500,300] [960,700] [1400,300], closed=false, no tangents. - let m = skip!(masks("233-mask-open-path.aep")); - let shape = &m[0].shapes[0]; - assert!(shape.open); - assert_eq!(shape.closed_flag, 1); - assert_eq!(shape.vertex_count(), 3); - assert_points(&shape.vertices(SIZE), &[[500.0, 300.0], [960.0, 700.0], [1400.0, 300.0]]); - assert_eq!(m[0].mode, Some(MaskMode::Add)); - // The closed paths of the same session have the bit clear. - for name in ["232-mask-ellipse.aep", "234-mask-mode-intersect.aep"] { - assert!(!skip!(masks(name))[0].shapes[0].open, "{name}"); - } -} diff --git a/crates/aep/tests/it/container/matte.rs b/crates/aep/tests/it/container/matte.rs deleted file mode 100644 index 2502954fb..000000000 --- a/crates/aep/tests/it/container/matte.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! Track mattes (cases 402-408): mode and matte layer in the layer header. - -use crate::container::helpers::{first_comp, open}; -use effectcraft_aep::{MatteMode, Project, TrackMatte}; - -/// `(name, video switch, track matte)` of every layer of comp `C`, top first. -fn layers(name: &str) -> Option, u32)>> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).expect("project"); - let comp = first_comp(&project); - comp.layers() - .map(|l| { - let h = l.header().expect("header"); - (l.name().or_else(|| project.layer_source(&l)?.display_name()).unwrap_or_default(), h.is_video_enabled(), l.track_matte(), h.id) - }) - .collect() - }) -} - -#[test] -fn the_four_matte_modes_and_the_matte_layer_id() { - for (case, mode) in [ - ("403-matte-L-alpha-M.aep", MatteMode::Alpha), - ("404-matte-L-alphainv-M.aep", MatteMode::AlphaInverted), - ("405-matte-L-luma-M.aep", MatteMode::Luma), - ("406-matte-L-lumainv-M.aep", MatteMode::LumaInverted), - ] { - let l = skip!(layers(case)); - assert_eq!(l.len(), 2, "{case}"); - let (m_name, m_video, m_matte, m_id) = &l[0]; - let (l_name, l_video, l_matte, l_id) = &l[1]; - assert_eq!((m_name.as_str(), l_name.as_str()), ("M", "L"), "{case}"); - // The matte layer M has an id of its own (0x1d in the single-case files). - assert_ne!(m_id, l_id, "{case}"); - assert_eq!(*m_matte, None, "{case}: the matte layer has no matte itself"); - assert_eq!(*l_matte, Some(TrackMatte { mode, layer: Some(*m_id) }), "{case}"); - // After Effects switches the matte layer's video off by itself. - assert!(!m_video, "{case}"); - assert!(l_video, "{case}"); - } -} - -#[test] -fn a_matte_layer_below_its_target() { - let l = skip!(layers("407-matte-M-alpha-L-below.aep")); - assert_eq!(l[0].2, Some(TrackMatte { mode: MatteMode::Alpha, layer: Some(l[1].3) })); - // The matte is L (0x1b in the single-case file). - assert_eq!(l[1].0, "L"); - assert!(l[0].1, "M stays visible"); - assert!(!l[1].1, "L, the matte, is switched off"); - assert_eq!(l[1].2, None); -} - -#[test] -fn a_matte_layer_whose_video_was_switched_back_on() { - let l = skip!(layers("408-matte-L-alpha-M-visible.aep")); - assert!(l[0].1, "M visible"); - assert_eq!(l[1].2, Some(TrackMatte { mode: MatteMode::Alpha, layer: Some(l[0].3) })); -} - -#[test] -fn no_layer_without_a_matte_reads_one() { - for name in crate::container::helpers::FIXTURES.iter().filter(|n| !n.contains("-matte-")) { - let bytes = fixture!(name); - let file = open(&bytes); - let Some(project) = Project::new(&file) else { continue }; - for item in project.all_items() { - let Some(comp) = item.comp() else { continue }; - for layer in comp.layers() { - assert_eq!(layer.track_matte(), None, "{name}"); - } - } - } -} - -#[test] -fn modes_from_codes() { - assert_eq!(MatteMode::from_code(0), None); - assert_eq!(MatteMode::from_code(9), Some(MatteMode::Other(9))); -} diff --git a/crates/aep/tests/it/container/odd_cases.rs b/crates/aep/tests/it/container/odd_cases.rs deleted file mode 100644 index eadc757cf..000000000 --- a/crates/aep/tests/it/container/odd_cases.rs +++ /dev/null @@ -1,266 +0,0 @@ -//! Hand-built containers for odd but well-formed shapes the reader must keep, and the limits against hostile -//! input. Every successfully parsed input must write back byte for byte. - -use effectcraft_aep::{AepError, Body, Chunk, Limits, parse, parse_with_limits, write}; - -/// One chunk with its pad byte (`pad` is used when the body is odd). -fn chunk(id: &[u8; 4], body: &[u8], pad: u8) -> Vec { - let mut v = id.to_vec(); - v.extend_from_slice(&(body.len() as u32).to_be_bytes()); - v.extend_from_slice(body); - if body.len() % 2 == 1 { - v.push(pad); - } - v -} - -fn list(list_type: &[u8; 4], children: &[Vec]) -> Vec { - let mut body = list_type.to_vec(); - for c in children { - body.extend_from_slice(c); - } - chunk(b"LIST", &body, 0) -} - -/// A whole file: `RIFX`, size, `Egg!`, chunks, trailer. -fn file(chunks: &[Vec], trailer: &[u8]) -> Vec { - let mut body = b"Egg!".to_vec(); - for c in chunks { - body.extend_from_slice(c); - } - let mut v = b"RIFX".to_vec(); - v.extend_from_slice(&(body.len() as u32).to_be_bytes()); - v.extend_from_slice(&body); - v.extend_from_slice(trailer); - v -} - -fn assert_round_trip(bytes: &[u8]) -> effectcraft_aep::AepFile<'_> { - let f = parse(bytes).unwrap(); - assert!(write(&f).unwrap() == bytes, "round trip differs"); - f -} - -#[test] -fn minimal_file_and_empty_container() { - let bytes = file(&[], b""); - let f = assert_round_trip(&bytes); - assert!(f.chunks.is_empty() && f.trailer.is_empty()); -} - -#[test] -fn empty_input_and_bad_headers_are_errors() { - assert_eq!(parse(b""), Err(AepError::NotRifx)); - assert_eq!(parse(b"RIFX"), Err(AepError::NotRifx)); - assert_eq!(parse(b"RIFF\0\0\0\x04Egg!"), Err(AepError::NotRifx)); - assert_eq!(parse(b"RIFX\0\0\0\x04Evil"), Err(AepError::BadFormType(*b"Evil"))); - assert!(matches!(parse(b"RIFX\0\0\0\x03Egg!"), Err(AepError::Truncated { .. }))); - // Declared size past the end of the input. - assert!(matches!(parse(b"RIFX\0\0\0\x20Egg!"), Err(AepError::Truncated { declared: 32, available: 4 }))); - assert!(matches!(parse(b"RIFX\xff\xff\xff\xffEgg!"), Err(AepError::Truncated { .. }))); -} - -#[test] -fn ids_ending_in_a_space_are_kept() { - let bytes = file(&[chunk(b"seq ", &[1, 2], 0), chunk(b"Pin ", &[], 0), chunk(b"FEE ", &[9, 9, 9, 9], 0), chunk(b"LOm ", &[1], 0)], b""); - let f = assert_round_trip(&bytes); - let ids: Vec<&[u8; 4]> = f.chunks.iter().map(|c| &c.id).collect(); - assert_eq!(ids, [b"seq ", b"Pin ", b"FEE ", b"LOm "]); - assert!(f.chunks[0].is(b"seq ")); -} - -#[test] -fn odd_sized_chunks_keep_their_pad_byte_even_when_not_zero() { - let bytes = file(&[chunk(b"abcd", &[1, 2, 3], 0xAA), chunk(b"efgh", &[4], 0)], b""); - let f = assert_round_trip(&bytes); - assert_eq!(f.chunks[0].pad, Some(0xAA)); - assert_eq!(f.chunks[1].pad, Some(0)); - assert_eq!(f.chunks[0].bytes(), Some(&[1, 2, 3][..])); -} - -#[test] -fn odd_last_chunk_without_pad_byte() { - // The container ends right after an odd body: no pad byte exists in the file. - let mut body = b"Egg!".to_vec(); - body.extend_from_slice(b"abcd\0\0\0\x03xyz"); - let mut bytes = b"RIFX".to_vec(); - bytes.extend_from_slice(&(body.len() as u32).to_be_bytes()); - bytes.extend_from_slice(&body); - let f = assert_round_trip(&bytes); - assert_eq!(f.chunks.len(), 1); - assert_eq!(f.chunks[0].pad, None); - // The same with a trailer following. - bytes.extend_from_slice(b""); - let f = assert_round_trip(&bytes); - assert_eq!(f.chunks[0].pad, None); - assert_eq!(&*f.trailer, b""); -} - -#[test] -fn list_with_raw_text_body_is_opaque() { - // Like LIST btdk: the body after the list type is text, not chunks. - let text = b"{\"a\": 1, \"b\": [1, 2, 3]} not a chunk sequence at all"; - let bytes = file(&[chunk(b"LIST", &[b"btdk".as_slice(), text].concat(), 0), chunk(b"next", &[], 0)], b""); - let f = assert_round_trip(&bytes); - assert!(matches!(f.chunks[0].body, Body::OpaqueList { .. })); - assert_eq!(f.chunks[0].list_type(), Some(*b"btdk")); - assert_eq!(f.chunks[0].bytes(), Some(&text[..])); - assert!(f.chunks[1].is(b"next")); -} - -#[test] -fn list_with_a_child_larger_than_the_list_is_opaque_not_an_error() { - let mut bad_child = b"kid1".to_vec(); - bad_child.extend_from_slice(&1000u32.to_be_bytes()); - bad_child.extend_from_slice(&[0; 4]); - let bytes = file(&[chunk(b"LIST", &[b"lsta".as_slice(), &bad_child].concat(), 0), chunk(b"tail", &[], 0)], b""); - let f = assert_round_trip(&bytes); - assert!(matches!(f.chunks[0].body, Body::OpaqueList { .. })); - assert!(f.chunks[1].is(b"tail")); -} - -#[test] -fn list_with_trailing_bytes_shorter_than_a_header_is_opaque() { - let bytes = file(&[chunk(b"LIST", &[b"lsta".as_slice(), &chunk(b"kid1", &[], 0), &[1, 2, 3]].concat(), 0)], b""); - let f = assert_round_trip(&bytes); - assert!(matches!(f.chunks[0].body, Body::OpaqueList { .. })); -} - -#[test] -fn empty_list_and_list_shorter_than_its_type() { - let bytes = file(&[list(b"Pefl", &[]), chunk(b"LIST", &[1, 2], 0), chunk(b"LIST", &[], 0)], b""); - let f = assert_round_trip(&bytes); - assert!(matches!(&f.chunks[0].body, Body::List { children, .. } if children.is_empty())); - // A LIST chunk too short to hold a type stays plain data. - assert!(matches!(f.chunks[1].body, Body::Data(_))); - assert!(matches!(f.chunks[2].body, Body::Data(_))); -} - -#[test] -fn nested_ids_hold_a_utf8_chunk() { - let name = chunk(b"Utf8", b"Hello", 0x7f); - let empty = chunk(b"Utf8", b"", 0); - let bytes = file(&[chunk(b"tdsn", &name, 0), chunk(b"pdnm", &empty, 0), chunk(b"fnam", &name, 0), chunk(b"othr", &name, 0)], b""); - let f = assert_round_trip(&bytes); - for c in &f.chunks[..3] { - assert!(matches!(c.body, Body::Chunks(_)), "{:?}", c.id); - assert_eq!(c.children().len(), 1); - let expect: &[u8] = if c.id == *b"pdnm" { b"" } else { b"Hello" }; - assert_eq!(c.children()[0].bytes(), Some(expect)); - } - assert_eq!(f.chunks[0].children()[0].pad, Some(0x7f)); - // An id outside the nested set is plain data even though its body looks like a chunk. - assert!(matches!(f.chunks[3].body, Body::Data(_))); -} - -#[test] -fn nested_id_with_a_body_that_is_not_a_chunk_stays_data() { - let bytes = file(&[chunk(b"tdsn", b"not a chunk sequence!", 0), chunk(b"tdsn", &[0; 3], 0), chunk(b"tdsn", &[], 0)], b""); - let f = assert_round_trip(&bytes); - assert!(f.chunks.iter().all(|c| matches!(c.body, Body::Data(_)))); -} - -#[test] -fn xmp_packet_follows_the_container() { - let xmp = b"\ndata\n \n"; - let mut trailer = b"junk before ".to_vec(); - trailer.extend_from_slice(xmp); - trailer.extend_from_slice(b"\n\n"); - let bytes = file(&[chunk(b"abcd", &[1, 2], 0)], &trailer); - let f = assert_round_trip(&bytes); - assert_eq!(&*f.trailer, &trailer[..]); - assert_eq!(f.xmp(), Some(&xmp[..])); - // No packet, no XMP. - let bytes = file(&[], b"nothing here"); - assert_eq!(assert_round_trip(&bytes).xmp(), None); - // An unterminated packet is not returned. - let bytes = file(&[], b" and no end"); - assert_eq!(assert_round_trip(&bytes).xmp(), None); -} - -#[test] -fn chunk_larger_than_its_parent_is_an_error_at_the_top_level() { - let mut bad = b"big!".to_vec(); - bad.extend_from_slice(&0xffff_fff0u32.to_be_bytes()); - bad.extend_from_slice(&[0; 4]); - let bytes = file(&[bad], b""); - assert!(matches!(parse(&bytes), Err(AepError::ChunkTooLarge { size: 0xffff_fff0, .. }))); - // A chunk header cut short by the container end. - let bytes = file(&[vec![b'a', b'b', b'c', b'd', 0, 0]], b""); - assert!(matches!(parse(&bytes), Err(AepError::Malformed { .. }))); -} - -#[test] -fn deep_nesting_is_kept_opaque_below_the_depth_limit() { - // 50 000 nested lists, emitted outermost first so building stays linear. - let levels: usize = 50_000; - let leaf = chunk(b"leaf", &[1, 2], 0); - let mut chunk_bytes = Vec::new(); - for _ in 0..levels { - chunk_bytes.extend_from_slice(b"LIST"); - // placeholder for the size, filled below - chunk_bytes.extend_from_slice(&[0; 4]); - chunk_bytes.extend_from_slice(b"deep"); - } - chunk_bytes.extend_from_slice(&leaf); - let mut inner_total = leaf.len(); - for level in (0..levels).rev() { - let size = 4 + inner_total; - let at = level * 12 + 4; - chunk_bytes[at..at + 4].copy_from_slice(&(size as u32).to_be_bytes()); - inner_total = 8 + size; - } - let bytes = file(&[chunk_bytes], b""); - let f = assert_round_trip(&bytes); - let depth = f.walk().map(|(d, _)| d).max().unwrap(); - assert!(depth <= Limits::default().max_depth, "depth {depth}"); - // A smaller limit parses less and still round-trips. - let f = parse_with_limits(&bytes, Limits { max_depth: 3, max_chunks: 1000 }).unwrap(); - assert!(f.walk().map(|(d, _)| d).max().unwrap() <= 3); - assert!(write(&f).unwrap() == bytes); -} - -#[test] -fn chunk_count_limit() { - let many: Vec> = (0..100).map(|_| chunk(b"abcd", &[], 0)).collect(); - let bytes = file(&many, b""); - assert_eq!(parse_with_limits(&bytes, Limits { max_depth: 8, max_chunks: 99 }), Err(AepError::TooManyChunks)); - assert!(parse_with_limits(&bytes, Limits { max_depth: 8, max_chunks: 100 }).is_ok()); -} - -#[test] -fn huge_declared_sizes_do_not_allocate() { - // A list that claims a gigantic child inside a small file: no allocation sized by the claim. - let mut c = b"LIST".to_vec(); - c.extend_from_slice(&u32::MAX.to_be_bytes()); - c.extend_from_slice(b"lsta"); - let bytes = file(&[c], b""); - assert!(matches!(parse(&bytes), Err(AepError::ChunkTooLarge { .. }))); -} - -#[test] -fn modified_trees_are_re_sized_on_write() { - let bytes = file(&[list(b"Fold", &[chunk(b"name", b"abc", 0), chunk(b"keep", &[7, 7], 0)])], b"tail"); - let mut f = parse(&bytes).unwrap(); - if let Some(Chunk { body: Body::List { children, .. }, .. }) = f.chunks.first_mut() { - children[0] = Chunk::data(*b"name", b"a longer name!".to_vec()); - } - let out = write(&f).unwrap(); - let g = parse(&out).unwrap(); - let kids = g.chunks[0].children(); - assert_eq!(kids[0].bytes(), Some(&b"a longer name!"[..])); - assert_eq!(kids[1].bytes(), Some(&[7u8, 7][..])); - assert_eq!(&*g.trailer, b"tail"); - assert!(write(&g).unwrap() == out); -} - -#[test] -fn writer_rejects_absurd_depth_instead_of_overflowing_the_stack() { - let mut c = Chunk::data(*b"leaf", vec![1u8, 2]); - for _ in 0..2000 { - c = Chunk::list(*b"deep", vec![c]); - } - let f = effectcraft_aep::AepFile { chunks: vec![c], trailer: std::borrow::Cow::Borrowed(&[]) }; - assert_eq!(write(&f), Err(AepError::TooDeep)); - // Dropping the deep tree must not overflow either (2000 levels). -} diff --git a/crates/aep/tests/it/container/robustness.rs b/crates/aep/tests/it/container/robustness.rs deleted file mode 100644 index 0a427bb88..000000000 --- a/crates/aep/tests/it/container/robustness.rs +++ /dev/null @@ -1,698 +0,0 @@ -//! Hostile and damaged input: nothing may panic; whatever parses must write back identically. - -use effectcraft_aep::{AepError, parse, write}; - -/// Parses; on success, the invariant "parse then write is the identity" must hold. -fn check(bytes: &[u8]) -> Result<(), AepError> { - let file = parse(bytes)?; - let back = write(&file).map_err(|_| AepError::TooLarge)?; - assert!(back == bytes, "round trip of an accepted input differs ({} bytes)", bytes.len()); - Ok(()) -} - -/// A small deterministic generator (xorshift64*). -struct Rng(u64); - -impl Rng { - fn next(&mut self) -> u64 { - self.0 ^= self.0 >> 12; - self.0 ^= self.0 << 25; - self.0 ^= self.0 >> 27; - self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) - } - fn below(&mut self, n: usize) -> usize { - (self.next() % n.max(1) as u64) as usize - } -} - -#[test] -fn empty_and_tiny_inputs() { - assert_eq!(check(&[]), Err(AepError::NotRifx)); - for n in 0..16 { - let bytes = fixture!("001-empty.aep"); - let _ = check(&bytes[..n]); - } -} - -#[test] -fn truncated_at_every_length() { - let bytes = fixture!("001-empty.aep"); - let declared = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize + 8; - for len in 0..=bytes.len() { - let r = check(&bytes[..len]); - if len < declared { - assert!(r.is_err(), "length {len} of {declared} must be rejected"); - } else { - assert!(r.is_ok(), "length {len} (>= declared end) must parse: {r:?}"); - } - } -} - -#[test] -fn truncated_larger_fixture_at_sampled_lengths() { - let bytes = fixture!("090-mask-rect.aep"); - let declared = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize + 8; - let mut rng = Rng(0x9e37_79b9_7f4a_7c15); - for _ in 0..400 { - let len = rng.below(bytes.len() + 1); - let r = check(&bytes[..len]); - assert_eq!(r.is_ok(), len >= declared, "len {len}"); - } -} - -#[test] -fn random_byte_flips() { - for (name, iterations) in [("001-empty.aep", 4000), ("000-base.aep", 1500), ("110-text-A.aep", 600)] { - let original = fixture!(name); - let mut rng = Rng(0x1234_5678_9abc_def1 ^ original.len() as u64); - let (mut ok, mut err) = (0, 0); - for _ in 0..iterations { - let mut b = original.clone(); - for _ in 0..=rng.below(8) { - let at = rng.below(b.len()); - b[at] = rng.next() as u8; - } - match check(&b) { - Ok(()) => ok += 1, - Err(_) => err += 1, - } - } - assert_eq!(ok + err, iterations, "{name}"); - } -} - -#[test] -fn a_whole_combined_file_survives_flips_and_truncation() { - // The cases above are cut from the combined files by our writer; this one is After Effects' - // own bytes (the smallest combined file). - let original = skip!(crate::common::try_file("aepx-pair.aep")); - let declared = u32::from_be_bytes([original[4], original[5], original[6], original[7]]) as usize + 8; - let mut rng = Rng(0x0bad_5eed_1234_5678); - for _ in 0..200 { - let len = rng.below(original.len() + 1); - assert_eq!(check(&original[..len]).is_ok(), len >= declared, "len {len}"); - let mut b = original.clone(); - for _ in 0..=rng.below(8) { - let at = rng.below(b.len()); - b[at] = rng.next() as u8; - } - let _ = check(&b); - } -} - -#[test] -fn flips_in_the_headers_and_sizes() { - // Aim at the bytes that matter most: the first 200 bytes, every value of every byte. - let original = fixture!("001-empty.aep"); - for at in 0..200 { - for v in [0u8, 1, 0x7f, 0x80, 0xff] { - let mut b = original.clone(); - b[at] = v; - let _ = check(&b); - } - } -} - -#[test] -fn oversized_chunk_sizes() { - let original = fixture!("001-empty.aep"); - // Every chunk header's size field set to huge values, one at a time, at every 4-byte aligned - // offset of the first 2 KB. - for at in (12..2048).step_by(2) { - for v in [u32::MAX, 0x8000_0000, 0x0100_0000, original.len() as u32, 1 << 20] { - let mut b = original.clone(); - b[at..at + 4].copy_from_slice(&v.to_be_bytes()); - let _ = check(&b); - } - } - // The container size itself. - for v in [0u32, 3, 4, 5, u32::MAX, original.len() as u32] { - let mut b = original.clone(); - b[4..8].copy_from_slice(&v.to_be_bytes()); - let _ = check(&b); - } -} - -#[test] -fn garbage_after_a_valid_header() { - let mut rng = Rng(42); - for _ in 0..2000 { - let n = rng.below(200); - let mut b = b"RIFX\0\0\0\0Egg!".to_vec(); - for _ in 0..n { - b.push(rng.next() as u8); - } - let size = (b.len() - 8) as u32; - b[4..8].copy_from_slice(&size.to_be_bytes()); - let _ = check(&b); - } -} - -// ----------------------------------------------------------------------------------- typed view - -use effectcraft_aep::{AepFile, Body, Chunk, Comp, Layer, Project, PropGroup, PropNode, Property}; - -/// Touches the property accessors; none may panic on a damaged property. -fn exercise_property(p: &Property<'_, '_>) { - let _ = (p.header(), p.dims(), p.is_animated(), p.static_value(), p.time_scale(), p.flags()); - let _ = (p.expression(), p.expression_flags().map(|f| f.disabled()), p.expression_enabled(), p.user_name(), p.first_key_value()); - if let Some(keys) = p.keys() { - let scale = p.time_scale().unwrap_or(0); - for k in keys.keyframes() { - let _ = (k.time_units(), k.raw().len(), k.kind(), k.seconds(scale), k.seconds(0)); - let _ = (k.interpolation_in(), k.interpolation_out(), k.flags(), k.label(), k.is_roving()); - let _ = (k.scalar_value(), k.ease(), k.spatial(), k.components(), k.value()); - let _ = k.ease_components(); - for component in [0, 1, 2, 3, 7, 255, usize::MAX] { - let _ = k.ease_component(component); - } - let _ = k.spatial().map(|s| (s.value.len(), s.in_tangent.len(), s.out_tangent.len(), s.ease)); - } - } -} - -fn exercise_group(g: &PropGroup<'_, '_>, depth: usize) { - if depth > 24 { - return; - } - let _ = (g.flags(), g.names(), g.user_name()); - for e in g.entries() { - match e.node { - PropNode::Group(g) => exercise_group(&g, depth + 1), - PropNode::Property(p) => exercise_property(&p), - PropNode::Other(c) => { - if let Some(g) = c.child_list(b"tdgp").and_then(PropGroup::from_chunk) { - exercise_group(&g, depth + 1); - } - } - } - } -} - -fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Layer<'_, '_>) { - let _ = (layer.name(), layer.is_three_d(), layer.id(), layer.track_matte()); - if let Some(h) = layer.header() { - let _ = (h.in_point(), h.out_point(), h.stretch_ratio(), h.stretch_den); - let _ = (h.is_shy(), h.is_locked(), h.is_solo(), h.is_three_d(), h.is_motion_blur(), h.is_adjustment(), h.is_guide()); - let _ = (h.is_null_object(), h.collapses_transformations(), h.quality, h.blend_mode, h.layer_type); - let _ = (h.is_enabled(), h.is_video_enabled(), h.is_audio_enabled(), h.is_effects_enabled(), h.is_auto_oriented(), h.light_type(), h.blend_mode.code()); - } - let _ = (layer.is_enabled(), layer.is_audio_enabled(), layer.is_effects_enabled()); - let _ = layer.camera_position().map(|p| (p.stored, p.auto_state)); - let _ = project.layer_anchor_px(layer); - let _ = layer - .time_remap() - .map(|t| (t.enabled, t.keys.iter().fold(0.0, |acc, k| acc + k.value_seconds + k.time_seconds.unwrap_or(0.0) + f64::from(k.time_units)))); - for g in layer.shape_groups() { - let _ = (g.name, g.position, g.details.len()); - for d in &g.details { - match d { - effectcraft_aep::ShapeDetail::Polystar { star_type, outer_radius, inner_radius, inner_roundness, item_index } => { - let _ = (star_type.value, outer_radius.value, inner_radius.value, inner_roundness.map(|r| r.value), *item_index); - } - effectcraft_aep::ShapeDetail::Gradient { gradient_type, highlight_length, highlight_angle, item_index } => { - let _ = (gradient_type.value, highlight_length.map(|t| t.value), highlight_angle.map(|t| t.value), *item_index); - } - effectcraft_aep::ShapeDetail::RectPosition { position, item_index } => { - let _ = (position.value, *item_index); - } - } - } - for item in g.items { - if let effectcraft_aep::ShapeItem::Path { paths, .. } = item { - for s in paths { - let _ = s.vertices((1.0, 1.0)).iter().fold(0.0, |acc, v| acc + v.in_tangent()[0] + v.out_tangent()[1]); - } - } - } - } - let _ = (project.layer_source(layer).map(|i| i.id()), project.layer_source(layer).and_then(|i| i.display_name()), project.layer_source_size(layer)); - if let Some(t) = layer.transform(comp_size.0, comp_size.1) { - let _ = (t.anchor_px(f64::from(comp_size.0), f64::from(comp_size.1)), t.position.value, t.opacity_percent.value); - } - if let Some(root) = layer.properties() { - exercise_group(&root, 0); - } - // One index for the layer's effects: building it walks every layer of the file. - let defs = project.effect_definition_index(); - for e in layer.effects() { - let _ = (e.match_name().len(), e.name(), e.declared_param_count(), e.has_own_definitions(), defs.source(&e)); - for p in e.params().into_iter().chain(defs.params(&e)) { - let _ = (p.index, p.kind, p.name.len(), p.items.as_ref().map(Vec::len), p.pard().len(), p.value(), p.stored_value(), p.pard_default()); - let _ = (p.is_default(), p.popup_item_count(), p.popup_selected_index(), p.popup_selected_item(), p.valid_max(), p.is_animated()); - let _ = (p.valid_min(), p.slider_range()); - if let Some(keys) = p.keys() { - for k in keys.keyframes() { - let _ = (k.value(), k.spatial(), k.time_units(), k.ease()); - } - } - for owner in [0, 1, 0x1b, u32::MAX] { - let _ = p.layer_ref(owner); - } - for size in [0.0, 1920.0, f64::NAN, f64::INFINITY, f64::MAX] { - let _ = p.point_px(size, size); - } - if let Some(s) = p.stored() { - exercise_property(&s); - } - } - } - for m in layer.masks() { - let _ = (m.name.clone(), m.mode, m.inverted, m.counter, m.feather, m.opacity_percent, m.expansion, m.path_animated, m.path_key_seconds.len()); - for s in &m.shapes { - let _ = (s.vertex_count(), s.vertices((1920.0, 1080.0)).len(), s.vertices((f64::NAN, f64::INFINITY)).len(), s.open); - } - } - if let Some(t) = layer.text_document() { - let _ = (t.fill_rgb(), t.fonts.len(), t.text.len(), t.raw_text.len(), t.font_size, t.font.clone(), t.paragraph_texts().len()); - let _ = (t.paragraphs.iter().fold(0, |acc, p| acc + p.length), t.style_runs.iter().fold(0.0, |acc, r| acc + r.tracking + r.fill_argb[0]), t.text_box); - let _ = t - .style_runs - .iter() - .fold(0.0, |acc, r| acc + r.leading.unwrap_or(0.0) + f64::from(u8::from(r.faux_bold)) + f64::from(u8::from(r.faux_italic)) + r.font_index as f64); - let _ = t.style_runs.iter().map(|r| r.caps).collect::>(); - let _ = t.paragraphs.iter().map(|p| p.justification).collect::>(); - } - for m in layer.markers() { - let _ = (m.comment.len(), m.chapter.len(), m.url.len(), m.frame_target.len(), m.cue_point_name.len(), m.duration_seconds); - let _ = (m.label, m.cue_type, m.cue_params.iter().map(|(k, v)| k.len() + v.len()).sum::()); - } -} - -fn exercise_comp(project: &Project<'_, '_>, comp: &Comp<'_, '_>) { - let tb = comp.time_base(); - let _ = tb.map(|t| (t.frame_rate(), t.seconds(i32::MIN), t.seconds(i32::MAX))); - let _ = (comp.name(), comp.renderer(), comp.markers()); - let mut size = (1920, 1080); - if let Some(h) = comp.header() { - size = (u32::from(h.width), u32::from(h.height)); - let _ = (h.frame_rate(), h.frame_rate_fixed, h.duration_seconds(), h.work_area_start_units, h.work_area_end_units); - let _ = (h.background, h.pixel_aspect.to_f64(), h.pixel_aspect.reduced(), h.shutter_angle, h.motion_blur); - let _ = (h.shutter_phase, h.display_start.map(|r| r.to_f64())); - } - for layer in comp.layers() { - exercise_layer(project, size, &layer); - } -} - -/// Touches every accessor of the typed view; none may panic on a damaged tree. -fn exercise(file: &AepFile<'_>) { - let Some(project) = Project::new(file) else { return }; - for item in project.all_items() { - let _ = (item.kind(), item.name(), item.id(), item.label(), item.footage(), item.display_name()); - let _ = item.footage().map(|f| (f.duration, f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate, f.is_sequence)); - let _ = item.id().and_then(|id| project.item_by_id(id)); - if let Some(comp) = item.comp() { - exercise_comp(&project, &comp); - } - } -} - -/// The fixtures whose typed fields are decoded, one per kind of chunk body. -const DECODED: &[&str] = &[ - "000-base.aep", - "010-layer-name.aep", - "022-layer-parent-null.aep", - "030-comp-size-1280x720.aep", - "035-comp-workarea-1-2.aep", - "039-comp-renderer-advanced3d.aep", - "044-static-anchor-10-20.aep", - "052-key-position-2key-ease.aep", - "054-key-position-2key-spatial-bezier.aep", - "056-key-position-3key-roving-key2.aep", - "058-key-opacity-2key.aep", - "060-expr-opacity-wiggle.aep", - "071-fx-slider-value77.aep", - "073-fx-color-0.2-0.6-1.aep", - "077-fx-dropdown-default.aep", - "080-fx-dropshadow-default.aep", - "091-mask-rect-props.aep", - "093-mask-path-2keys.aep", - "113-text-Hello-size60-fillorange.aep", - "122-marker-comp-1s.aep", - "123-marker-layer-1s.aep", - "124-precomp-Pre.aep", - "126-footage-png-layer.aep", - "202-key-out-hold-in-linear.aep", - "204-key-ease-asymmetric.aep", - "205-key-opacity-ease-asymmetric.aep", - "206-key-scale-2key-linear.aep", - "208-key-mask-feather-2key-linear.aep", - "210-key-fill-color-2key-linear.aep", - "211-anchor-100x100-solid-10-20.aep", - "213-expr-opacity-wiggle-disabled.aep", - "214-fx-gaussianblur-default.aep", - "215-fx-fill-default.aep", - "218-fx-point-111-222.aep", - "220-fx-layercontrol-to-layer1.aep", - "221-fx-slider-2key.aep", - "222-layer-video-off.aep", - "228-layer-blend-difference.aep", - "229-comp-fps-29.97.aep", - "232-mask-ellipse.aep", - "233-mask-open-path.aep", - "237-mask-mode-difference.aep", - "239-shape-stroke-green-w8-round.aep", - "240-shape-custom-path-tangents.aep", - "241-shape-gradient-fill-linear.aep", - "242-shape-group-position-50-50.aep", - "245-text-box-400x200-Hello.aep", - "248-text-range-fill-red-1-3.aep", - "249-marker-layer-full.aep", - "251-camera-one-node.aep", - "252-light-point.aep", - "253-camera-position-100-200-m1000.aep", - "254-light-spot-intensity-50.aep", - "259-solid-blue-0-0-1.aep", - "300-fx-gaussianblur-0-explicit.aep", - "305-key-scale-bezier-ease.aep", - "306-key-maskfeather-bezier-ease.aep", - "307-key-fillcolor-bezier.aep", - "309-solid-100x100-mask-rect.aep", - "310-solid-100x100-pointcontrol.aep", - "317-layer-stretch150.aep", - "318-layer-inpoint-0.3333.aep", - "319-precomp-timeremap.aep", - "321-fx-layercontrol-none.aep", - "324-fx-dropdown-5items-select3.aep", - "327-comp-displaystartframe-100.aep", - "328-mask-two-ellipse-rect.aep", - "329-mask-ellipse-mode-none.aep", - "331-shape-polystar-polygon-5-100.aep", - "332-shape-gradient-fill-radial.aep", - "333-shape-group-two-rects.aep", - "334-text-box-right-align.aep", - "335-text-point-fauxbold.aep", - "340-text-range-two-styles.aep", - "342-camera-dof-800-30.aep", - "343-light-spot-color-red.aep", - "349-marker-layer-event-cue-params.aep", - "351-footage-wav-as-layer.aep", - "352-footage-pngseq-imported.aep", - "354-footage-pngseq-timeremap.aep", - "364-fx-tint-white-2key.aep", - "382-fx-ramp-start-2key.aep", - "383-fx-ramp-on-100x100-start-10-20.aep", - "389-fx-exposure-default.aep", - "395-fx-exposure-individual-red-1.aep", - "397-fx-exposure-master-2key.aep", -]; - -#[test] -fn typed_view_reads_every_undamaged_fixture() { - for name in crate::container::helpers::FIXTURES { - let bytes = fixture!(name); - exercise(&parse(&bytes).unwrap()); - } -} - -#[test] -fn typed_view_survives_damaged_files() { - for (name, iterations) in [("000-base.aep", 1500), ("055-key-position-3key-inserted-t2.5.aep", 800), ("071-fx-slider-value77.aep", 800)] { - let original = fixture!(name); - let mut rng = Rng(0xfeed_beef_1234_5678 ^ original.len() as u64); - for _ in 0..iterations { - let mut b = original.clone(); - for _ in 0..=rng.below(12) { - let at = rng.below(b.len()); - b[at] = rng.next() as u8; - } - if let Ok(file) = parse(&b) { - exercise(&file); - } - } - } -} - -#[test] -fn typed_view_survives_byte_flips_in_the_decoded_fixtures() { - for name in DECODED { - let original = fixture!(name); - let mut rng = Rng(0x0dd_ba11_cafe_f00d ^ original.len() as u64); - let (mut parsed, mut total) = (0, 0); - for _ in 0..250 { - let mut b = original.clone(); - for _ in 0..=rng.below(16) { - let at = rng.below(b.len()); - b[at] = rng.next() as u8; - } - total += 1; - if let Ok(file) = parse(&b) { - parsed += 1; - exercise(&file); - } - } - // Flips that land inside bodies keep the file parseable; sizes that break the structure do not. - assert!(parsed > 0 && parsed <= total, "{name}: {parsed} of {total}"); - } -} - -#[test] -fn truncated_typed_files_never_panic() { - // A cut inside the container is an error; a cut in the trailer still parses. Either way no panic. - for name in DECODED { - let original = fixture!(name); - let declared = u32::from_be_bytes([original[4], original[5], original[6], original[7]]) as usize + 8; - let mut rng = Rng(0x7e57_7e57 ^ original.len() as u64); - for _ in 0..120 { - let len = rng.below(original.len() + 1); - if let Ok(file) = parse(&original[..len]) { - assert!(len >= declared, "{name}: {len} < {declared}"); - exercise(&file); - } - } - // Also cut right before and after the declared end. - for len in [declared - 1, declared, declared + 1] { - if let Ok(file) = parse(&original[..len.min(original.len())]) { - exercise(&file); - } - } - } -} - -/// The chunks whose bodies the typed view decodes. -const DECODED_IDS: &[&[u8; 4]] = &[ - b"ldta", b"cdta", b"prin", b"idta", b"idpi", b"tdb4", b"cdat", b"tdsb", b"lhd3", b"ldat", b"mkif", b"shph", b"parn", b"pard", b"sspc", b"opti", b"alas", - b"Utf8", b"tdmn", b"NmHd", b"btdk", b"tdpi", -]; - -/// Applies a random mutation to a body. -fn damage(body: &mut Vec, rng: &mut Rng) { - match rng.below(7) { - 0 => body.truncate(rng.below(body.len() + 1)), - 1 => body.clear(), - 2 => { - for _ in 0..=rng.below(4) { - if !body.is_empty() { - let at = rng.below(body.len()); - body[at] = rng.next() as u8; - } - } - } - 3 => { - // A 4-byte window set to an extreme value (sizes, counts, offsets). - if body.len() >= 4 { - let at = rng.below(body.len() - 3); - let v = [0xffff_ffffu32, 0x8000_0000, 0x7fff_ffff, 0, 1][rng.below(5)]; - body[at..at + 4].copy_from_slice(&v.to_be_bytes()); - } - } - 4 => body.extend((0..=rng.below(64)).map(|_| rng.next() as u8)), - 5 => { - // An 8-byte window set to NaN / infinity / a huge double. - if body.len() >= 8 { - let at = rng.below(body.len() - 7); - let v = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e308, -1e308][rng.below(5)]; - body[at..at + 8].copy_from_slice(&v.to_be_bytes()); - } - } - _ => body.iter_mut().for_each(|b| *b = 0xff), - } -} - -fn damage_tree(chunks: &mut [Chunk<'static>], rng: &mut Rng, depth: usize) { - if depth > 70 { - return; - } - for chunk in chunks { - let id = chunk.id; - match &mut chunk.body { - Body::Data(d) => { - if DECODED_IDS.contains(&&id) && rng.below(12) == 0 { - damage(d.to_mut(), rng); - } - } - Body::OpaqueList { data, .. } => { - if rng.below(3) == 0 { - damage(data.to_mut(), rng); - } - } - Body::Chunks(c) | Body::List { children: c, .. } => damage_tree(c, rng, depth + 1), - } - } -} - -#[test] -fn typed_view_survives_damaged_chunk_bodies() { - // Damage the bodies the typed view decodes (not the container framing), directly in the tree: - // wrong sizes, empty and truncated bodies, extreme counts, NaN doubles, unterminated text. - for name in DECODED { - let bytes = fixture!(name); - let original = parse(&bytes).unwrap().into_owned(); - let mut rng = Rng(0xbad_c0de_0001 ^ bytes.len() as u64); - for _ in 0..120 { - let mut file = original.clone(); - damage_tree(&mut file.chunks, &mut rng, 0); - exercise(&file); - } - } -} - -#[test] -fn extreme_values_in_the_decoded_headers() { - use effectcraft_aep::{CompHeader, LayerHeader, Rational, ShapePath}; - // Every field at its maximum: no overflow, no division by zero, no panic. - let h = LayerHeader::parse(&[0xff; 164]).unwrap(); - let _ = (h.in_point(), h.out_point(), h.start.to_f64(), h.stretch_ratio()); - let mut zero_den = [0u8; 164]; - zero_den[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); - zero_den[12..16].copy_from_slice(&i32::MIN.to_be_bytes()); - let h = LayerHeader::parse(&zero_den).unwrap(); - assert_eq!((h.in_point(), h.out_point(), h.start.to_f64()), (None, None, None)); - let mut wide = [0u8; 164]; - wide[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); - wide[12..16].copy_from_slice(&i32::MIN.to_be_bytes()); - wide[16..20].copy_from_slice(&u32::MAX.to_be_bytes()); - wide[20..24].copy_from_slice(&i32::MAX.to_be_bytes()); - wide[24..28].copy_from_slice(&u32::MAX.to_be_bytes()); - let h = LayerHeader::parse(&wide).unwrap(); - let _ = h.in_point(); - let c = CompHeader::parse(&[0xff; 204]).unwrap(); - assert_eq!((c.duration_seconds(), c.work_area_end_units), (None, None)); - let _ = (c.frame_rate(), c.pixel_aspect.to_f64()); - let zero = CompHeader::parse(&[0; 204]).unwrap(); - assert_eq!((zero.frame_rate(), zero.pixel_aspect.to_f64(), zero.duration_seconds()), (None, None, None)); - let all = LayerHeader::parse(&[0xff; 164]).unwrap(); - let _ = (all.is_enabled(), all.is_auto_oriented(), all.light_type(), all.blend_mode.code()); - assert_eq!(LayerHeader::parse(&[0u8; 164]).unwrap().light_type(), None); - assert_eq!(Rational { num: i64::MAX, den: i64::MIN }.reduced(), None); - assert_eq!(Rational { num: i64::MIN, den: i64::MIN }.reduced(), Rational::new(1, 1)); - // A path whose point count is not a multiple of three, and non-finite box and scale. - let path = ShapePath { bbox: [f32::NAN, f32::INFINITY, f32::MIN, f32::MAX], closed_flag: 9, open: true, points: vec![[f32::NAN, 0.0]; 7] }; - assert_eq!(path.vertex_count(), 2); - assert_eq!(path.vertices((f64::NAN, f64::MAX)).len(), 2); -} - -/// Calls `f` on the body of every data chunk with this id, anywhere in the tree. -fn for_each_body(chunks: &mut [Chunk<'static>], id: &[u8; 4], f: &mut dyn FnMut(&mut Vec), depth: usize) { - if depth > 70 { - return; - } - for chunk in chunks { - let this = chunk.id; - match &mut chunk.body { - Body::Data(d) if this == *id => f(d.to_mut()), - Body::Data(_) | Body::OpaqueList { .. } => {} - Body::Chunks(c) | Body::List { children: c, .. } => for_each_body(c, id, f, depth + 1), - } - } -} - -#[test] -fn hostile_keyframe_layouts_never_panic() { - // The property header selects the record template: every component count (0..=255) with the - // template flag at 0, 1 and 0xff, over keyframe lists of every record size in these fixtures. - for name in [ - "204-key-ease-asymmetric.aep", - "206-key-scale-2key-linear.aep", - "208-key-mask-feather-2key-linear.aep", - "210-key-fill-color-2key-linear.aep", - "093-mask-path-2keys.aep", - "122-marker-comp-1s.aep", - "305-key-scale-bezier-ease.aep", - "306-key-maskfeather-bezier-ease.aep", - "307-key-fillcolor-bezier.aep", - "319-precomp-timeremap.aep", - ] { - let bytes = fixture!(name); - let original = parse(&bytes).unwrap().into_owned(); - for components in 0..=255u8 { - for template in [0u8, 1, 0xff] { - let mut file = original.clone(); - for_each_body( - &mut file.chunks, - b"tdb4", - &mut |body| { - if body.len() > 7 { - body[3] = components; - body[7] = template; - } - }, - 0, - ); - exercise(&file); - } - } - } -} - -#[test] -fn hostile_text_dictionaries_and_marker_headers_never_panic() { - // Damage the marker header (NmHd), the strings and the layer reference in many ways, and the - // opaque text lists. - for name in [ - "245-text-box-400x200-Hello.aep", - "248-text-range-fill-red-1-3.aep", - "249-marker-layer-full.aep", - "220-fx-layercontrol-to-layer1.aep", - "334-text-box-right-align.aep", - "335-text-point-fauxbold.aep", - "340-text-range-two-styles.aep", - "349-marker-layer-event-cue-params.aep", - "321-fx-layercontrol-none.aep", - "324-fx-dropdown-5items-select3.aep", - "352-footage-pngseq-imported.aep", - "350-footage-wav-imported.aep", - ] { - let bytes = fixture!(name); - let original = parse(&bytes).unwrap().into_owned(); - let mut rng = Rng(0x07e4_70dd_ba11 ^ bytes.len() as u64); - for _ in 0..300 { - let mut file = original.clone(); - for id in [b"NmHd", b"Utf8", b"tdpi"] { - for_each_body(&mut file.chunks, id, &mut |body| damage(body, &mut rng), 0); - } - damage_tree(&mut file.chunks, &mut rng, 0); - exercise(&file); - } - } -} - -#[test] -fn extreme_values_in_the_batch_3_fields() { - use effectcraft_aep::{CompHeader, LayerHeader}; - // Time stretch: zero and maximal numerators and denominators (bytes 8 and 108), with extreme times. - for (num, den) in [(0u32, 0u32), (1, 0), (0, 1), (u32::MAX, 1), (1, u32::MAX), (u32::MAX, u32::MAX), (3, 2)] { - let mut ldta = [0u8; 164]; - ldta[8..12].copy_from_slice(&num.to_be_bytes()); - ldta[108..112].copy_from_slice(&den.to_be_bytes()); - ldta[12..16].copy_from_slice(&i32::MIN.to_be_bytes()); - ldta[16..20].copy_from_slice(&1u32.to_be_bytes()); - ldta[20..24].copy_from_slice(&i32::MAX.to_be_bytes()); - ldta[24..28].copy_from_slice(&u32::MAX.to_be_bytes()); - ldta[28..32].copy_from_slice(&i32::MIN.to_be_bytes()); - ldta[32..36].copy_from_slice(&1u32.to_be_bytes()); - let h = LayerHeader::parse(&ldta).unwrap(); - let _ = (h.stretch_ratio(), h.in_point(), h.out_point()); - if den == 0 { - assert_eq!((h.stretch_ratio(), h.in_point(), h.out_point()), (None, None, None)); - } - } - // Display start and shutter phase from extreme bytes; a missing tail leaves them unknown. - for fill in [0x00u8, 0x7f, 0x80, 0xff] { - let c = CompHeader::parse(&[fill; 204]).unwrap(); - let _ = (c.shutter_phase, c.display_start.map(|r| r.to_f64())); - } - // A zero denominator has no value. - assert_eq!(CompHeader::parse(&[0; 204]).unwrap().display_start.and_then(|r| r.to_f64()), None); -} diff --git a/crates/aep/tests/it/container/roundtrip.rs b/crates/aep/tests/it/container/roundtrip.rs deleted file mode 100644 index e6d7cba7a..000000000 --- a/crates/aep/tests/it/container/roundtrip.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! Byte-identical round trip over the generated test projects as After Effects wrote them (the -//! combined files, not the single-case projects cut from them), and the structural facts of the -//! container. - -use std::collections::BTreeMap; - -use effectcraft_aep::{AepFile, Body, parse, write}; - -/// The binary files of the fixture directory (the `.aepx` has its own tests). -fn files() -> Vec<&'static str> { - crate::common::FILES.iter().copied().filter(|n| n.ends_with(".aep")).collect() -} - -/// The bytes of a whole file; returns from the calling test when it is missing. -macro_rules! file { - ($name:expr) => { - skip!(crate::common::try_file($name)) - }; -} - -fn id(c: &[u8; 4]) -> String { - String::from_utf8_lossy(c).into_owned() -} - -#[test] -fn every_fixture_round_trips_byte_for_byte() { - for name in files() { - let bytes = file!(name); - let file = parse(&bytes).unwrap_or_else(|e| panic!("{name}: {e}")); - let back = write(&file).unwrap(); - assert_eq!(back.len(), bytes.len(), "{name}: length"); - assert!(back == bytes, "{name}: bytes differ"); - // Owned copy round-trips too. - let owned: AepFile<'static> = file.into_owned(); - assert!(write(&owned).unwrap() == bytes, "{name}: owned copy differs"); - } -} - -#[test] -fn header_and_trailer_facts() { - for name in files() { - let bytes = file!(name); - assert_eq!(&bytes[..4], b"RIFX"); - assert_eq!(&bytes[8..12], b"Egg!"); - let declared = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize; - let file = parse(&bytes).unwrap(); - // The declared size ends before the end of the file; the rest is the XMP packet. - assert!(declared + 8 < bytes.len(), "{name}"); - assert_eq!(file.trailer.len(), bytes.len() - declared - 8, "{name}"); - assert!(file.trailer.starts_with(b""), "{name}"); - assert!(std::str::from_utf8(xmp).is_ok(), "{name}: xmp is UTF-8"); - } -} - -#[test] -fn top_level_chunks_of_the_base_project() { - let bytes = fixture!("000-base.aep"); - let file = parse(&bytes).unwrap(); - let ids: Vec = file.chunks.iter().map(|c| if c.id == *b"LIST" { format!("LIST {}", id(&c.list_type().unwrap())) } else { id(&c.id) }).collect(); - // The first chunks, in file order (observed in every generated file). - assert_eq!(&ids[..3], ["svap", "head", "nhed"]); - assert!(ids.iter().any(|i| i == "LIST Fold"), "{ids:?}"); - // Chunk offsets are 2-byte aligned and every id is 4 printable ASCII bytes. - for (_, c) in file.walk() { - assert!(c.id.iter().all(|b| (0x20..0x7f).contains(b)), "{:?}", c.id); - } -} - -#[test] -fn nesting_depth_is_below_the_limit() { - for name in files() { - let bytes = file!(name); - let file = parse(&bytes).unwrap(); - let max = file.walk().map(|(d, _)| d).max().unwrap(); - assert!(max <= 13, "{name}: depth {max}"); - // Nothing is kept opaque because of the depth limit. - assert!(max < 64); - } -} - -#[test] -fn nested_chunk_ids_hold_one_utf8_chunk() { - let mut nested = BTreeMap::::new(); - for name in files() { - let bytes = file!(name); - let file = parse(&bytes).unwrap(); - for (_, c) in file.walk() { - if matches!(c.body, Body::Chunks(_)) { - *nested.entry(id(&c.id)).or_default() += 1; - // Each holds exactly one Utf8 chunk. - assert_eq!(c.children().len(), 1); - assert_eq!(c.children()[0].id, *b"Utf8"); - } - } - } - assert!(nested.contains_key("tdsn"), "{nested:?}"); -} - -#[test] -fn raw_text_lists_are_kept_opaque() { - // LIST btdk holds raw text, not chunks (observed once a project has a text layer). - let bytes = fixture!("110-text-A.aep"); - let file = parse(&bytes).unwrap(); - let mut found = 0; - for (_, c) in file.walk() { - if let Body::OpaqueList { list_type, data } = &c.body { - assert!(!data.is_empty()); - if list_type == b"btdk" { - found += 1; - assert!(data.iter().all(|b| b.is_ascii() || *b >= 0x80), "btdk is text"); - } - } - } - assert!(found >= 1, "expected a LIST btdk kept opaque"); -} - -#[test] -fn list_types_ending_in_a_space_are_kept() { - // `LIST Pin ` and `LIST FEE ` occur in every generated project that has an item (all but the - // empty one); the space is part of the type. - for name in files().into_iter().filter(|n| *n != "empty.aep") { - let bytes = file!(name); - let file = parse(&bytes).unwrap(); - for ty in [b"Pin ", b"FEE "] { - assert!(file.walk().any(|(_, c)| c.is_list(ty)), "{name}: no LIST {:?}", String::from_utf8_lossy(ty)); - } - } -} diff --git a/crates/aep/tests/it/container/shapes.rs b/crates/aep/tests/it/container/shapes.rs deleted file mode 100644 index cf5ff9298..000000000 --- a/crates/aep/tests/it/container/shapes.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! Shape layers: rectangle, fill, stroke, rounded corners, custom path, gradient fill and group -//! position, checked against the values the corpus was made with (its MANIFEST, batch 2). The shape -//! layer `S` is on top of the solid `L`; its group is `Group 1`. - -use crate::container::helpers::{assert_near, first_comp, layer_named, open}; -use effectcraft_aep::{LayerType, Project, ShapeGroup, ShapeItem, StrokeCap, StrokeJoin, ValueSource}; - -fn groups(name: &str) -> Option> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_named(&first_comp(&project), "S"); - let h = layer.header().unwrap(); - assert_eq!(h.layer_type, LayerType::Shape, "{name}"); - assert!(h.collapses_transformations(), "{name}: shape layers have the collapse switch from creation"); - layer.shape_groups() - }) -} - -fn only_group(name: &str) -> Option { - Some({ - let mut g = groups(name)?; - assert_eq!(g.len(), 1, "{name}"); - g.remove(0) - }) -} - -fn rect_size(item: &ShapeItem) -> [f64; 2] { - let ShapeItem::Rect { name, size } = item else { panic!("{item:?}") }; - assert_eq!(name.as_deref(), Some("Rectangle Path 1")); - let size = size.expect("rect size"); - assert_eq!(size.source, ValueSource::Stored); - size.value -} - -#[test] -fn rectangle_fill_and_rounded_corners() { - // 238: Rectangle Path 400x300, Fill [0,1,0], Round Corners radius 20 (in this order). - let g = skip!(only_group("238-shape-rect-rounded-corners.aep")); - assert_eq!(g.name.as_deref(), Some("Group 1")); - assert_eq!((g.position.value, g.position.source), ([0.0, 0.0], ValueSource::Default)); - assert_eq!(g.items.len(), 3); - assert_eq!(rect_size(&g.items[0]), [400.0, 300.0]); - let ShapeItem::Fill { name, color } = &g.items[1] else { panic!("{:?}", g.items[1]) }; - assert_eq!(name.as_deref(), Some("Fill 1")); - assert_eq!(color.unwrap().value, [1.0, 0.0, 1.0, 0.0]); - let ShapeItem::RoundCorners { name, radius } = &g.items[2] else { panic!("{:?}", g.items[2]) }; - assert_eq!(name.as_deref(), Some("Round Corners 1")); - assert_eq!(radius.unwrap().value, 20.0); -} - -#[test] -fn stroke_colour_width_cap_and_join() { - // 239: Stroke [0,1,0] width 8, Line Cap 2 (round), Line Join 2 (round); no Fill. - let g = skip!(only_group("239-shape-stroke-green-w8-round.aep")); - assert_eq!(g.items.len(), 2); - assert_eq!(rect_size(&g.items[0]), [400.0, 300.0]); - let ShapeItem::Stroke { name, stroke } = &g.items[1] else { panic!("{:?}", g.items[1]) }; - assert_eq!(name.as_deref(), Some("Stroke 1")); - assert_eq!(stroke.color.unwrap().value, [1.0, 0.0, 1.0, 0.0]); - assert_eq!(stroke.width.unwrap().value, 8.0); - assert_eq!((stroke.cap.value, stroke.cap.source), (StrokeCap::Round, ValueSource::Stored)); - assert_eq!((stroke.join.value, stroke.join.source), (StrokeJoin::Round, ValueSource::Stored)); - // Touching the join stores the miter limit in its default state (4). - assert_eq!(stroke.miter_limit.unwrap().value, 4.0); - assert!(!g.items.iter().any(|i| matches!(i, ShapeItem::Fill { .. }))); -} - -#[test] -fn custom_path_with_tangents_in_pixels() { - // 240: Path 1, closed, vertices [0,-100] [100,100] [-100,100], inTangents [-10,-20] [30,20] [-60,10], - // outTangents [40,0] [-20,30] [0,-50] (the box of vertices and handles is -160,-120,130,130), then a Fill. - let g = skip!(only_group("240-shape-custom-path-tangents.aep")); - assert_eq!(g.items.len(), 2); - let ShapeItem::Path { name, paths } = &g.items[0] else { panic!("{:?}", g.items[0]) }; - assert_eq!(name.as_deref(), Some("Path 1")); - assert_eq!(paths.len(), 1); - let p = &paths[0]; - assert!(!p.open); - assert_near(&p.bbox.map(f64::from), &[-160.0, -120.0, 130.0, 130.0], 1e-6); - let v = p.vertices((1.0, 1.0)); - let positions: Vec<[f64; 2]> = v.iter().map(|x| x.position).collect(); - let in_t: Vec<[f64; 2]> = v.iter().map(|x| x.in_tangent()).collect(); - let out_t: Vec<[f64; 2]> = v.iter().map(|x| x.out_tangent()).collect(); - for (got, want) in positions.iter().zip([[0.0, -100.0], [100.0, 100.0], [-100.0, 100.0]]) { - assert_near(got, &want, 1e-3); - } - for (got, want) in in_t.iter().zip([[-10.0, -20.0], [30.0, 20.0], [-60.0, 10.0]]) { - assert_near(got, &want, 1e-3); - } - for (got, want) in out_t.iter().zip([[40.0, 0.0], [-20.0, 30.0], [0.0, -50.0]]) { - assert_near(got, &want, 1e-3); - } - assert!(matches!(g.items[1], ShapeItem::Fill { .. })); -} - -#[test] -fn gradient_fill_start_and_end() { - // 241: Gradient Fill 1 (linear), start [-200,0], end [200,0] in pixels; type and stops are not stored. - let g = skip!(only_group("241-shape-gradient-fill-linear.aep")); - assert_eq!(g.items.len(), 2); - assert_eq!(rect_size(&g.items[0]), [400.0, 300.0]); - let ShapeItem::GradientFill { name, start, end } = &g.items[1] else { panic!("{:?}", g.items[1]) }; - assert_eq!(name.as_deref(), Some("Gradient Fill 1")); - assert_eq!(start.unwrap().value, [-200.0, 0.0]); - assert_eq!(end.unwrap().value, [200.0, 0.0]); -} - -#[test] -fn group_position() { - // 242: Group 1 / Transform / Position [0,0] -> [50,50]; the contents are unchanged. - let g = skip!(only_group("242-shape-group-position-50-50.aep")); - assert_eq!((g.position.value, g.position.source), ([50.0, 50.0], ValueSource::Stored)); - assert_eq!(g.items.len(), 2); - assert_eq!(rect_size(&g.items[0]), [400.0, 300.0]); - assert!(matches!(g.items[1], ShapeItem::Fill { .. })); -} - -#[test] -fn other_layers_have_no_shape_groups() { - let bytes = fixture!("238-shape-rect-rounded-corners.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let solid = comp.layers().find(|l| l.header().is_some_and(|h| h.layer_type == LayerType::Av)).unwrap(); - assert!(solid.shape_groups().is_empty()); -} diff --git a/crates/aep/tests/it/container/text_fields.rs b/crates/aep/tests/it/container/text_fields.rs deleted file mode 100644 index 6c08d8993..000000000 --- a/crates/aep/tests/it/container/text_fields.rs +++ /dev/null @@ -1,209 +0,0 @@ -//! Text document fields used by the importer: stroke colour, automatic leading, the font of each -//! run, the undecoded-slot check, damaged runs, the Source Text record and the text anchor rule. - -use crate::container::helpers::{first_comp, layer_named, open}; -use effectcraft_aep::{Caps, LayerType, Project, TextDocument, ValueSource}; - -/// Every synthetic text case that has a fixture, with its text. -const CASES: &[(&str, &str)] = &[ - ("110-text-A.aep", "A"), - ("113-text-Hello-size60-fillorange.aep", "Hello"), - ("114-text-animator-opacity.aep", "Hello"), - ("243-text-multiline-A-CR-B.aep", "A\rB"), - ("245-text-box-400x200-Hello.aep", "Hello"), - ("246-text-box-center-align.aep", "Hello"), - ("247-text-tracking-100.aep", "Hello"), - ("248-text-range-fill-red-1-3.aep", "Hello"), - ("334-text-box-right-align.aep", "Hello"), - ("335-text-point-fauxbold.aep", "Hello"), - ("336-text-point-fauxitalic.aep", "Hello"), - ("337-text-point-allcaps.aep", "Hello"), - ("338-text-point-smallcaps.aep", "Hello"), - ("339-text-point-leading60.aep", "Hello"), - ("340-text-range-two-styles.aep", "Hello"), - ("385-text-anchor-10-20.aep", "A"), - ("386-text-etx-A-B.aep", "A\u{3}B"), -]; - -fn doc(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - layer_named(&first_comp(&project), "T").text_document().unwrap_or_else(|| panic!("{name}: no text document")) - }) -} - -/// The raw `btdk` body of the text layer of a fixture. -fn body(name: &str) -> Option> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = layer_named(&comp, "T"); - layer.chunk().find_list(b"btdk").and_then(|c| c.bytes()).unwrap().to_vec() - }) -} - -fn replace_once(hay: &[u8], from: &[u8], to: &[u8]) -> Vec { - replace_after(hay, b"", from, to) -} - -/// Replaces the first `from` after the first `anchor` (the run style of 244 starts with -/// `/0 0 /1 100.0`; the document's style sheet before it has the same slots). -fn replace_after(hay: &[u8], anchor: &[u8], from: &[u8], to: &[u8]) -> Vec { - let start = if anchor.is_empty() { 0 } else { hay.windows(anchor.len()).position(|w| w == anchor).unwrap() }; - let at = start + hay[start..].windows(from.len()).position(|w| w == from).unwrap_or_else(|| panic!("{:?} not found", String::from_utf8_lossy(from))); - [&hay[..at], to, &hay[at + from.len()..]].concat() -} - -#[test] -fn every_sample_is_complete_and_has_only_decoded_slots_changed() { - for (name, text) in CASES { - let d = skip!(doc(name)); - assert_eq!(d.text, *text, "{name}"); - assert_eq!(d.incomplete_runs, 0, "{name}"); - assert!(d.undecoded_style_fields.is_empty(), "{name}: {:?}", d.undecoded_style_fields); - assert!(d.undecoded_paragraph_fields.is_empty(), "{name}: {:?}", d.undecoded_paragraph_fields); - assert_eq!(d.style_runs.iter().map(|r| r.length).sum::(), d.raw_text.chars().count(), "{name}"); - for run in &d.style_runs { - // No sample has automatic leading: the stored leading is used (98 by default). - assert!(!run.auto_leading, "{name}"); - // The stroke colour is white in every sample (no stroke was sampled). - assert_eq!(run.stroke_argb, Some([1.0; 4]), "{name}"); - assert_eq!(d.font_of(run), Some("TimesNewRomanPSMT"), "{name}"); - } - } -} - -#[test] -fn stored_leading_and_font_of_a_run() { - assert_eq!(skip!(doc("243-text-multiline-A-CR-B.aep")).style_runs[0].leading, Some(98.0)); - assert_eq!(skip!(doc("339-text-point-leading60.aep")).style_runs[0].leading, Some(60.0)); - // 335: faux bold moves the run to font index 1, which is still Times New Roman. - let d = skip!(doc("335-text-point-fauxbold.aep")); - assert_eq!((d.style_runs[0].font_index, d.font_of(&d.style_runs[0])), (1, Some("TimesNewRomanPSMT"))); -} - -#[test] -fn automatic_leading_is_slot_4() { - let b = replace_once(&skip!(body("110-text-A.aep")), b"/4 false /5 98.0", b"/4 true /5 98.0"); - let d = TextDocument::parse(&b).unwrap(); - assert!(d.style_runs[0].auto_leading); - assert!(d.undecoded_style_fields.is_empty()); -} - -#[test] -fn automatic_leading_as_after_effects_stores_it() { - // 400: Auto Leading switched on for 387's "A" CR "B" (size 100, explicit leading 98 before). - // Against its unedited save 399 the run style differs in `/4` (true) and `/5` (0.01) only, and - // the composed second line sits 120 px (1.2 x 100) below the first, as After Effects measures. - let d = skip!(doc("400-text-autoleading-on.aep")); - assert_eq!(d.text, "A\rB"); - assert_eq!(d.incomplete_runs, 0); - assert!(d.undecoded_style_fields.is_empty(), "{:?}", d.undecoded_style_fields); - assert!(d.undecoded_paragraph_fields.is_empty(), "{:?}", d.undecoded_paragraph_fields); - for run in &d.style_runs { - assert!(run.auto_leading); - assert_eq!((run.font_size, run.leading), (100.0, Some(0.01))); - } - let b = skip!(body("400-text-autoleading-on.aep")); - let text = String::from_utf8_lossy(&b); - assert!(text.contains("/0 << /0 [ 0.0 120.00001 ] >>"), "composed second baseline at 120 px"); -} - -#[test] -fn undecoded_slots_that_differ_are_listed() { - let src = skip!(body("110-text-A.aep")); - // Style slot 68 and paragraph slot 24 changed to values outside their neutral ones (0 and 1, - // 732, 734); a zero slot the samples lack (93) is not listed. - const RUN: &[u8] = b"/0 0 /1 100.0"; - let b = replace_after(&src, RUN, b"/68 0 ", b"/68 2 "); - let b = replace_after(&b, RUN, b"/96 true >>", b"/93 0.0 /94 0.0 /96 true >>"); - // The run's paragraph is the one with `/22 1 /23 true` (the style sheet's has `/22 0`). - let para = b"/20 6 /21 false /22 1 /23 true /24 1"; - let b = replace_once(&b, para, b"/20 6 /21 false /22 1 /23 true /24 2"); - let d = TextDocument::parse(&b).unwrap(); - assert_eq!(d.undecoded_style_fields, ["68"]); - assert_eq!(d.undecoded_paragraph_fields, ["24"]); - // A non-zero unknown slot is listed. - let d = TextDocument::parse(&replace_after(&src, RUN, b"/96 true >>", b"/97 2 /96 true >>")).unwrap(); - assert_eq!(d.undecoded_style_fields, ["97"]); - // `/nil` is the stored form of a slot without a value (244 has three): not listed. - let d = TextDocument::parse(&replace_once(&src, b"/22 1 /23 true /24 1", b"/22 1 /23 true /24 1 /48 /nil")).unwrap(); - assert!(d.undecoded_paragraph_fields.is_empty(), "{:?}", d.undecoded_paragraph_fields); -} - -#[test] -fn a_damaged_run_is_kept_and_counted() { - // 340 has three runs; the size of the third (60) is removed: the run stays and takes the size of - // the one before it. - let src = skip!(body("340-text-range-two-styles.aep")); - let at = src.windows(b"/1 60.0".len()).position(|w| w == b"/1 60.0").unwrap(); - let b = [&src[..at], &src[at + b"/1 60.0".len()..]].concat(); - let d = TextDocument::parse(&b).unwrap(); - assert_eq!(d.style_runs.len(), 3); - assert_eq!(d.incomplete_runs, 1); - assert_eq!(d.style_runs[2].font_size, 100.0); - assert_eq!(d.style_runs[2].fill_argb, [1.0, 0.0, 0.0, 1.0]); - assert_eq!(d.style_runs[2].caps, Caps::Normal); -} - -#[test] -fn source_text_record_and_text_anchor() { - for name in ["110-text-A.aep", "114-text-animator-opacity.aep", "248-text-range-fill-red-1-3.aep"] { - let bytes = fixture!(name); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let t = layer_named(&comp, "T"); - assert_eq!(t.header().unwrap().layer_type, LayerType::Text); - let st = t.source_text_property().expect("source text record"); - assert!(!st.is_animated() && st.expression().is_none(), "{name}"); - assert_eq!(t.text_document_count(), 1, "{name}"); - // The text anchor is absent: the text origin, not the centre of a source. - let tr = t.transform(1920, 1080).unwrap(); - assert_eq!(tr.anchor_fraction.source, ValueSource::Default, "{name}"); - assert_eq!(tr.text_anchor_px(), [0.0; 3], "{name}"); - assert_eq!(tr.position.value, [960.0, 540.0, 0.0], "{name}"); - } -} - -#[test] -fn a_stored_text_anchor_is_pixels() { - // 385: 110's text layer with Anchor Point [10, 20], stored as pixels (a text layer has no source). - let bytes = fixture!("385-text-anchor-10-20.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let tr = layer_named(&comp, "T").transform(1920, 1080).unwrap(); - assert_eq!(tr.anchor_fraction.source, ValueSource::Stored); - assert_eq!(tr.text_anchor_px(), [10.0, 20.0, 0.0]); - assert_eq!(tr.position.value, [960.0, 540.0, 0.0]); -} - -#[test] -fn etx_is_stored_as_it_is_and_splits_the_paragraph_runs() { - // 386: "A" U+0003 "B" is stored with the U+0003; After Effects lays it out like 243's CR (two - // lines, two paragraphs), and the paragraph runs say the same. - let etx = skip!(doc("386-text-etx-A-B.aep")); - let cr = skip!(doc("243-text-multiline-A-CR-B.aep")); - assert_eq!(etx.raw_text, "A\u{3}B\r"); - assert_eq!(etx.paragraphs.len(), cr.paragraphs.len()); - assert_eq!(etx.paragraphs.iter().map(|p| p.length).collect::>(), cr.paragraphs.iter().map(|p| p.length).collect::>()); -} - -#[test] -fn hostile_documents_never_panic() { - let src = skip!(body("340-text-range-two-styles.aep")); - // Every prefix, a run length that overflows, a string with a lone surrogate, deep nesting. - for cut in (0..src.len()).step_by(97) { - let _ = TextDocument::parse(&src[..cut]); - } - let _ = TextDocument::parse(&replace_once(&src, b"/1 3 >>", b"/1 99999999999999999999 >>")); - let lone = [b"/1 << /1 [ << /0 << /0 (".as_slice(), &[0xfe, 0xff, 0xd8, 0x00, 0x00, b'A'], b") >> >> ] >>"].concat(); - let _ = TextDocument::parse(&lone); - let deep = [b"/1 ".as_slice(), &b"<< /0 ".repeat(10_000), &b">> ".repeat(10_000)].concat(); - assert!(TextDocument::parse(&deep).is_none()); -} diff --git a/crates/aep/tests/it/container/text_markers_footage.rs b/crates/aep/tests/it/container/text_markers_footage.rs deleted file mode 100644 index 48f49297e..000000000 --- a/crates/aep/tests/it/container/text_markers_footage.rs +++ /dev/null @@ -1,273 +0,0 @@ -//! Text documents, markers and footage items, checked against the values the corpus was made -//! with (its MANIFEST). - -use crate::container::helpers::{base_layer, first_comp, open}; -use effectcraft_aep::{CueType, ItemKind, KeyframeKind, LayerType, Marker, Project, Property, TextDocument, TextValue, parse_text_dict}; - -fn text_layer_document(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = comp.layers().find(|l| l.name().as_deref() == Some("T")).expect("the text layer T"); - let h = layer.header().unwrap(); - assert_eq!(h.layer_type, LayerType::Text); - layer.text_document().expect("text document") - }) -} - -#[test] -fn text_a_with_the_defaults() { - // 110: point text "A": Times New Roman (TimesNewRomanPSMT), size 100, white fill. - let d = skip!(text_layer_document("110-text-A.aep")); - assert_eq!(d.text, "A"); - assert_eq!(d.raw_text, "A\r"); - assert_eq!(d.font_size, 100.0); - assert_eq!(d.fill_argb, [1.0, 1.0, 1.0, 1.0]); - assert_eq!(d.fill_rgb(), [1.0, 1.0, 1.0]); - assert_eq!(d.font.as_deref(), Some("TimesNewRomanPSMT")); - assert!(d.fonts.iter().any(|f| f == "TimesNewRomanPSMT")); -} - -#[test] -fn text_hello_size_60_orange() { - // 113 (chain 111-113): text "Hello", fontSize 60, fillColor [1, 0.5, 0]. - let d = skip!(text_layer_document("113-text-Hello-size60-fillorange.aep")); - assert_eq!(d.text, "Hello"); - assert_eq!(d.font_size, 60.0); - assert_eq!(d.fill_rgb(), [1.0, 0.5, 0.0]); - assert_eq!(d.font.as_deref(), Some("TimesNewRomanPSMT")); -} - -#[test] -fn a_solid_layer_has_no_text_document() { - let bytes = fixture!("000-base.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - assert!(base_layer(&first_comp(&project)).text_document().is_none()); -} - -#[test] -fn text_dictionary_parser() { - // Names, numbers, booleans, nested dictionaries and arrays, a UTF-16BE string with an escaped - // parenthesis, a string without a byte order mark. - let mut doc = Vec::new(); - doc.extend_from_slice(b"/0 << /a 1 /b -2.5 /c true /d [ 1 2.0 /x ] >>\n/1 ("); - doc.extend_from_slice(&[0xfe, 0xff, 0x00, b'H', 0x00, 0x69, 0x00, 0x5c, b')', 0x00, 0x21]); - doc.extend_from_slice(b")\n/2 (plain) /3 word"); - let top = parse_text_dict(&doc); - assert_eq!(top.get("0").unwrap().get("a"), Some(&TextValue::Int(1))); - assert_eq!(top.get("0").unwrap().get("b"), Some(&TextValue::Float(-2.5))); - assert_eq!(top.get("0").unwrap().get("c"), Some(&TextValue::Bool(true))); - let d = top.get("0").unwrap().get("d").unwrap(); - assert_eq!((d.at(0), d.at(1), d.at(2)), (Some(&TextValue::Int(1)), Some(&TextValue::Float(2.0)), Some(&TextValue::Name("x".to_string())))); - // The byte after a backslash is kept literally: the units are 0x0048 0x0069 0x0029 0x0021. - assert_eq!(top.get("1").and_then(TextValue::as_str), Some("Hi)!")); - assert_eq!(top.get("2"), Some(&TextValue::Bytes(b"plain".to_vec()))); - assert_eq!(top.get("3"), Some(&TextValue::Token("word".to_string()))); -} - -#[test] -fn text_dictionary_parser_survives_garbage() { - // Unbalanced brackets, a string that never ends, nothing, binary junk, 100 levels of nesting. - for body in [&b"<< /a"[..], b"[ 1 2", b"(abc", b"(abc\\", b"", b">>", b")", b"/a <<", &[0xff, 0xfe, 0x00, 0x80, 0x28]] { - let _ = parse_text_dict(body); - } - let deep = [b"/k ".as_slice(), &b"[".repeat(100), &b"]".repeat(100)].concat(); - let top = parse_text_dict(&deep); - // Nesting beyond the limit stops the parse; nothing was read for the key. - assert_eq!(top, TextValue::Dict(Vec::new())); - let ok = [b"/k ".as_slice(), &b"[".repeat(10), &b"]".repeat(10)].concat(); - assert!(matches!(parse_text_dict(&ok), TextValue::Dict(p) if p.len() == 1)); - // A body that is not a text document yields no document. - assert_eq!(TextDocument::parse(b"/0 1 /1 2"), None); -} - -// ------------------------------------------------------------------------------------- markers - -#[test] -fn comp_marker() { - // 122: a composition marker at 1 s with the comment "CompMarker". - let bytes = fixture!("122-marker-comp-1s.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - assert_eq!( - comp.markers(), - [Marker { - time_units: 25600, - seconds: Some(1.0), - comment: "CompMarker".to_string(), - duration_seconds: Some(0.0), - label: Some(0), - cue_type: Some(CueType::Event), - ..Marker::default() - }] - ); - // The times are 16-byte records of the property inside `mrst`. - let mrst = comp.item().chunk().child_list(b"SecL").unwrap().find_list(b"mrst").unwrap(); - let keys = Property::from_chunk(mrst.child_list(b"tdbs").unwrap()).unwrap().keys().unwrap(); - assert_eq!((keys.len(), keys.header.record_size), (1, 16)); - assert!(keys.keyframes().all(|k| k.kind() == KeyframeKind::Marker)); - // The layer has none. - assert!(base_layer(&comp).markers().is_empty()); -} - -#[test] -fn layer_marker() { - // 123: a marker on L at 1 s, comment "LayerMarker". - let bytes = fixture!("123-marker-layer-1s.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - assert_eq!( - base_layer(&comp).markers(), - [Marker { - time_units: 25600, - seconds: Some(1.0), - comment: "LayerMarker".to_string(), - duration_seconds: Some(0.0), - label: Some(0), - cue_type: Some(CueType::Event), - ..Marker::default() - }] - ); - assert!(comp.markers().is_empty()); -} - -#[test] -fn no_markers_in_the_base() { - let bytes = fixture!("000-base.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - assert!(comp.markers().is_empty()); - assert!(base_layer(&comp).markers().is_empty()); -} - -// ------------------------------------------------------------------------------------- footage - -#[test] -fn solid_footage_item() { - // The base solid L: red [1,0,0], 1920x1080 (ARGB floats 1, 1, 0, 0). - let bytes = fixture!("000-base.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let solid = project.item_by_id(0x1a).unwrap(); - assert_eq!(solid.kind(), Some(ItemKind::Footage)); - let f = solid.footage().unwrap(); - assert!(f.is_solid); - assert_eq!(f.file_type, "Soli"); - assert_eq!((f.width, f.height), (1920, 1080)); - assert_eq!(f.name.as_deref(), Some("L")); - assert_eq!(f.solid_argb, Some([1.0, 1.0, 0.0, 0.0])); - assert_eq!(f.solid_rgb(), Some([1.0, 0.0, 0.0])); - assert_eq!(f.path, None); - assert_eq!(solid.name(), None); - assert_eq!(solid.label(), Some(1)); - // A composition is not footage. - assert!(first_comp(&project).item().footage().is_none()); -} - -#[test] -fn png_footage_layer() { - // 126: the png test8x8.png (8x8) imported and used for a layer "png" (label 5). - let bytes = fixture!("126-footage-png-layer.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = comp.layers().find(|l| l.name().as_deref() == Some("png")).unwrap(); - let h = layer.header().unwrap(); - assert_eq!((h.label, h.layer_type), (5, LayerType::Av)); - let item = project.layer_source(&layer).unwrap(); - assert_eq!(item.kind(), Some(ItemKind::Footage)); - let f = item.footage().unwrap(); - assert!(!f.is_solid); - assert_eq!(f.file_type, "png!"); - assert_eq!((f.width, f.height), (8, 8)); - assert_eq!(f.name.as_deref(), Some("test8x8.png")); - assert_eq!(f.solid_argb, None); - // The path comes from the alias JSON (the fixture holds a neutral replacement of the original). - assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test8x8.png")), "{:?}", f.path); - assert_eq!(project.layer_source_size(&layer), Some((8, 8))); - // L is still there below it. - assert_eq!(comp.layers().count(), 2); -} - -// ---------------------------------------------------------------------------- batch 2 - -use effectcraft_aep::Justification; - -#[test] -fn multi_line_text_is_paragraphs_separated_by_cr() { - // 243: point text `A\rB`: stored `A\rB\r`, two paragraph runs of 2 characters, one style run of 4. - let d = skip!(text_layer_document("243-text-multiline-A-CR-B.aep")); - assert_eq!(d.raw_text, "A\rB\r"); - assert_eq!(d.text, "A\rB"); - assert_eq!(d.paragraph_texts(), ["A", "B"]); - assert_eq!(d.paragraphs.iter().map(|p| p.length).collect::>(), [2, 2]); - assert!(d.paragraphs.iter().all(|p| p.justification == Justification::Left)); - assert_eq!(d.style_runs.iter().map(|r| r.length).collect::>(), [4]); - assert_eq!(d.text_box, None); -} - -#[test] -fn paragraph_box_text_and_justification() { - // 245: paragraph (box) text `Hello` in a 400x200 box, top-left [-200,-100] in layer space, left aligned. - let d = skip!(text_layer_document("245-text-box-400x200-Hello.aep")); - assert_eq!(d.text, "Hello"); - let b = d.text_box.expect("box text has a frame"); - assert_eq!((b.x, b.y, b.width, b.height), (-200.0, -100.0, 400.0, 200.0)); - assert_eq!(d.paragraphs.iter().map(|p| (p.length, p.justification)).collect::>(), [(6, Justification::Left)]); - // 246: the same box with the justification changed from left to centre; only the justification differs. - let d = skip!(text_layer_document("246-text-box-center-align.aep")); - assert_eq!(d.paragraphs.iter().map(|p| (p.length, p.justification)).collect::>(), [(6, Justification::Center)]); - let b = d.text_box.expect("box text has a frame"); - assert_eq!((b.x, b.y, b.width, b.height), (-200.0, -100.0, 400.0, 200.0)); - // Point text has no frame. - assert_eq!(skip!(text_layer_document("247-text-tracking-100.aep")).text_box, None); -} - -#[test] -fn tracking_and_style_ranges() { - // 247: point text `Hello`, tracking 0 -> 100 for the whole document. - let d = skip!(text_layer_document("247-text-tracking-100.aep")); - assert_eq!(d.text, "Hello"); - assert_eq!(d.style_runs.iter().map(|r| (r.length, r.tracking)).collect::>(), [(6, 100.0)]); - // 243 has the default tracking 0. - assert_eq!(skip!(text_layer_document("243-text-multiline-A-CR-B.aep")).style_runs[0].tracking, 0.0); - // 248: characters [1,3) ("el") filled red [1,0,0], the rest white: the style runs split into 1, 2 and 3 characters. - let d = skip!(text_layer_document("248-text-range-fill-red-1-3.aep")); - assert_eq!(d.style_runs.iter().map(|r| r.length).collect::>(), [1, 2, 3]); - assert_eq!(d.style_runs.iter().map(|r| r.fill_argb).collect::>(), [[1.0; 4], [1.0, 1.0, 0.0, 0.0], [1.0; 4]]); - assert_eq!(d.paragraphs.iter().map(|p| p.length).collect::>(), [6]); - assert!(d.style_runs.iter().all(|r| r.font_size == 100.0 && r.tracking == 0.0)); -} - -#[test] -fn marker_with_duration_and_all_strings() { - // 249: a layer marker on L at 1 s: comment `LM`, duration 1 s, chapter `Chap`, URL `http://a.example/u`, - // frame target `_blank`, cue point `CueX`. - let bytes = fixture!("249-marker-layer-full.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let markers = base_layer(&comp).markers(); - assert_eq!( - markers, - [Marker { - time_units: 25600, - seconds: Some(1.0), - comment: "LM".to_string(), - duration_seconds: Some(1.0), - chapter: "Chap".to_string(), - url: "http://a.example/u".to_string(), - frame_target: "_blank".to_string(), - cue_point_name: "CueX".to_string(), - label: Some(0), - cue_type: Some(effectcraft_aep::CueType::Event), - cue_params: Vec::new(), - }] - ); -} diff --git a/crates/aep/tests/it/container/text_style_slots.rs b/crates/aep/tests/it/container/text_style_slots.rs deleted file mode 100644 index d2e938200..000000000 --- a/crates/aep/tests/it/container/text_style_slots.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Character and paragraph slots of the text document, each found with one scripted change -//! against the reference point text 538 (`HHHH`, Times New Roman 100 px, normal baseline). - -use crate::container::helpers::{first_comp, layer_named, open}; -use effectcraft_aep::{AutoKern, Justification, KernRun, Project, TextDocument}; - -fn text(name: &str) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - layer_named(&first_comp(&project), "T").text_document().unwrap_or_else(|| panic!("{name}: no text document")) - }) -} - -#[test] -fn the_reference_text_has_the_defaults_and_nothing_undecoded() { - let t = skip!(text("538-text-point-HHHH-normal-ref.aep")); - let r = t.style_runs[0]; - assert_eq!((r.horizontal_scale, r.vertical_scale, r.baseline_shift, r.tsume, r.stroke_width), (1.0, 1.0, 0.0, 0.0, 1.0)); - assert_eq!(r.auto_kern, AutoKern::Metrics); - assert_eq!((r.ligatures, r.no_break, r.apply_fill, r.apply_stroke, r.stroke_over_fill), (false, false, true, false, true)); - assert_eq!((r.line_join, r.baseline_direction, r.digit_set), (0, 1, 0)); - let p = t.paragraphs[0]; - assert_eq!(p.justification, Justification::Left); - assert_eq!((p.first_line_indent, p.start_indent, p.end_indent, p.space_before, p.space_after), (0.0, 0.0, 0.0, 0.0, 0.0)); - assert_eq!((p.leading_type, p.auto_hyphenate, p.hanging_roman, p.every_line_composer, p.direction), (0, true, false, false, 0)); - assert!(t.kerning.is_empty()); - assert_eq!(t.line_orientation, None); - assert!(t.undecoded_style_fields.is_empty() && t.undecoded_paragraph_fields.is_empty(), "{t:?}"); -} - -#[test] -fn character_slots_each_hold_one_setting() { - let run = |name: &str| { - Some({ - let t = text(name)?; - assert!(t.undecoded_style_fields.is_empty() && t.undecoded_paragraph_fields.is_empty(), "{name}: {:?}", t.undecoded_style_fields); - t.style_runs[0] - }) - }; - assert_eq!(skip!(run("539-text-hscale-0.9.aep")).horizontal_scale, 0.9); - assert_eq!(skip!(run("540-text-vscale-1.5.aep")).vertical_scale, 1.5); - assert_eq!(skip!(run("541-text-baselineshift-41.aep")).baseline_shift, 41.0); - assert_eq!(skip!(run("542-text-autokern-none.aep")).auto_kern, AutoKern::None); - assert_eq!(skip!(run("543-text-autokern-optical.aep")).auto_kern, AutoKern::Optical); - assert!(skip!(run("544-text-applystroke-on.aep")).apply_stroke); - assert_eq!(skip!(run("545-text-strokewidth-5.aep")).stroke_width, 5.0); - assert!(!skip!(run("546-text-applyfill-off.aep")).apply_fill); - assert_eq!(skip!(run("548-text-linejoin-round.aep")).line_join, 1); - assert!(!skip!(run("550-text-strokeoverfill-off.aep")).stroke_over_fill); - assert!(skip!(run("552-text-nobreak-on.aep")).no_break); - assert_eq!(skip!(run("553-text-tsume-0.5.aep")).tsume, 0.5); - assert!(skip!(run("555-text-ligature-on.aep")).ligatures); - assert_eq!(skip!(run("571-text-digitset-arabic.aep")).digit_set, 1); - assert_eq!(skip!(run("578-text-digitset-hindi.aep")).digit_set, 2); - assert_eq!(skip!(run("573-text-baselinedir-rotated.aep")).baseline_direction, 2); - assert_eq!(skip!(run("576-text-baselinedir-crossstream.aep")).baseline_direction, 3); -} - -#[test] -fn paragraph_slots_each_hold_one_setting() { - let para = |name: &str| { - Some({ - let t = text(name)?; - assert!(t.undecoded_style_fields.is_empty() && t.undecoded_paragraph_fields.is_empty(), "{name}: {:?}", t.undecoded_paragraph_fields); - t.paragraphs[0] - }) - }; - assert_eq!(skip!(para("560-text-firstlineindent-20.aep")).first_line_indent, 20.0); - assert_eq!(skip!(para("561-text-startindent-30.aep")).start_indent, 30.0); - assert_eq!(skip!(para("562-text-endindent-40.aep")).end_indent, 40.0); - assert_eq!(skip!(para("563-text-spacebefore-10.aep")).space_before, 10.0); - assert_eq!(skip!(para("564-text-spaceafter-12.aep")).space_after, 12.0); - assert_eq!(skip!(para("572-text-leadingtype-japanese.aep")).leading_type, 1); - assert!(!skip!(para("556-text-autohyphenate-off.aep")).auto_hyphenate); - assert!(skip!(para("558-text-hangingroman-on.aep")).hanging_roman); - assert!(skip!(para("559-text-everyline-on.aep")).every_line_composer); - assert_eq!(skip!(para("569-text-direction-rtl.aep")).direction, 1); - assert_eq!(skip!(para("565-text-justify-fullleft.aep")).justification, Justification::FullLeft); - assert_eq!(skip!(para("566-text-justify-fullcenter.aep")).justification, Justification::FullCenter); - assert_eq!(skip!(para("567-text-justify-fullright.aep")).justification, Justification::FullRight); - assert_eq!(skip!(para("568-text-justify-fullall.aep")).justification, Justification::FullAll); -} - -#[test] -fn manual_kerning_is_a_list_of_character_runs() { - // 554: kerning 50 on the whole text: automatic kerning is switched off (0) and each of the four - // characters carries 50; the closing `\r` has no amount. - let t = skip!(text("554-text-kerning-50.aep")); - assert_eq!(t.style_runs[0].auto_kern, AutoKern::None); - assert_eq!(t.kerning.iter().map(|k| k.length).sum::(), 5); - assert!(t.kerning.iter().take(4).all(|k| *k == KernRun { length: 1, amount: Some(50.0) }), "{:?}", t.kerning); - assert_eq!(t.kerning.last().and_then(|k| k.amount), None); -} - -#[test] -fn vertical_text_has_its_line_orientation() { - assert_eq!(skip!(text("575-text-vertical-rtl.aep")).line_orientation, Some(2)); -} - -#[test] -fn several_settings_in_one_document() { - // 595: stroke on, width 5, blue, horizontal 0.9, vertical 1.5, baseline shift 41; 596 the same - // with the fill over the stroke. - let a = skip!(text("595-text-stroke-scale-shift-combined.aep")).style_runs[0]; - assert_eq!((a.apply_stroke, a.stroke_width, a.horizontal_scale, a.vertical_scale, a.baseline_shift), (true, 5.0, 0.9, 1.5, 41.0)); - assert_eq!(a.stroke_argb, Some([1.0, 0.0, 0.0, 1.0])); - assert!(a.stroke_over_fill); - assert!(!skip!(text("596-text-combined-fill-over-stroke.aep")).style_runs[0].stroke_over_fill); -} - -#[test] -fn paragraph_slot_34_is_neutral_for_its_two_sampled_values() { - // 727: Reset Paragraph changes only /34 (0 -> 7); both values lay text out alike (S18). - assert_eq!(skip!(text("725-text-point-HHHH-normal-ref-S18.aep")).undecoded_paragraph_fields, Vec::::new()); - let t = skip!(text("727-text-reset-paragraph.aep")); - assert!(t.undecoded_paragraph_fields.is_empty(), "{:?}", t.undecoded_paragraph_fields); - // Another value of /34 is still listed. - let bytes = fixture!("727-text-reset-paragraph.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_named(&first_comp(&project), "T"); - let body = layer.chunk().find_list(b"btdk").and_then(|c| c.bytes()).unwrap().to_vec(); - // Every `/34 7` (the run's paragraph and the document's paragraph sheet) becomes `/34 5`. - let mut changed = Vec::with_capacity(body.len()); - let mut i = 0; - while i < body.len() { - if body[i..].starts_with(b"/34 7 ") { - changed.extend_from_slice(b"/34 5 "); - i += 6; - } else { - changed.push(body[i]); - i += 1; - } - } - assert_eq!(TextDocument::parse(&changed).unwrap().undecoded_paragraph_fields, ["34"]); -} - -#[test] -fn slots_24_35_and_68_are_neutral_for_0_and_1() { - // 732-734: 517 with paragraph /24, paragraph /35 or style /68 edited; After Effects keeps the - // value and lays the text out the same (S21). - for name in ["732-text-box-byteedit-para24-0.aep", "733-text-box-byteedit-para35-0.aep", "734-text-box-byteedit-style68-1.aep"] { - let t = skip!(text(name)); - assert!( - t.undecoded_style_fields.is_empty() && t.undecoded_paragraph_fields.is_empty(), - "{name}: {:?} {:?}", - t.undecoded_style_fields, - t.undecoded_paragraph_fields - ); - } -} diff --git a/crates/aep/tests/it/container/typed.rs b/crates/aep/tests/it/container/typed.rs deleted file mode 100644 index e85391e0f..000000000 --- a/crates/aep/tests/it/container/typed.rs +++ /dev/null @@ -1,268 +0,0 @@ -//! The typed view, checked against the values the generated corpus was made with (the synthetic -//! MANIFEST: composition `C` 1920x1080 at 25 fps with one solid layer `L`, then one change per -//! file). - -use crate::container::helpers::FIXTURES; -use effectcraft_aep::{AepFile, Body, ItemKind, KeyList, Layer, Project, PropGroup, PropNode, Property, parse}; - -fn first_layer<'f, 'a>(project: &Project<'f, 'a>) -> Layer<'f, 'a> { - let comp = project.all_items().into_iter().find_map(|i| i.comp()).expect("a composition"); - comp.layers().next().expect("a layer") -} - -fn transform<'f, 'a>(layer: &Layer<'f, 'a>) -> PropGroup<'f, 'a> { - match layer.properties().expect("layer properties").get("ADBE Transform Group") { - Some(PropNode::Group(g)) => g, - other => panic!("transform group: {other:?}"), - } -} - -fn property<'f, 'a>(group: &PropGroup<'f, 'a>, name: &str) -> Property<'f, 'a> { - match group.get(name) { - Some(PropNode::Property(p)) => p, - other => panic!("{name}: {other:?}"), - } -} - -#[test] -fn base_project_items() { - let bytes = fixture!("000-base.aep"); - let file = parse(&bytes).unwrap(); - let project = Project::new(&file).unwrap(); - // Comp C and the folder Solids at the top; the solid's footage item lives inside the folder. - let top: Vec<_> = project.items().map(|i| (i.kind(), i.name())).collect(); - assert_eq!(top, [(Some(ItemKind::Composition), Some("C".to_string())), (Some(ItemKind::Folder), Some("Solids".to_string()))]); - let all: Vec<_> = project.all_items().iter().map(|i| i.kind()).collect(); - assert_eq!(all, [Some(ItemKind::Composition), Some(ItemKind::Folder), Some(ItemKind::Footage)]); - // numItems = 3 in the manifest. - assert_eq!(all.len(), 3); - let folder = project.items().nth(1).unwrap(); - assert_eq!(folder.children().count(), 1); -} - -#[test] -fn empty_project_has_no_items_of_a_composition() { - let bytes = fixture!("001-empty.aep"); - let file = parse(&bytes).unwrap(); - let project = Project::new(&file).unwrap(); - assert!(project.all_items().iter().all(|i| i.comp().is_none())); -} - -#[test] -fn composition_time_base_gives_the_frame_rate() { - let bytes = fixture!("000-base.aep"); - let file = parse(&bytes).unwrap(); - let comp = Project::new(&file).unwrap().items().find_map(|i| i.comp()).unwrap(); - let tb = comp.time_base().unwrap(); - assert_eq!((tb.frame_duration, tb.timescale), (1024, 25600)); - assert_eq!(tb.frame_rate(), Some(25.0)); - assert_eq!(tb.seconds(25600), Some(1.0)); - // 031: frameRate 25 -> 30 changes the time base. - let bytes = fixture!("031-comp-fps30.aep"); - let file = parse(&bytes).unwrap(); - let comp = Project::new(&file).unwrap().items().find_map(|i| i.comp()).unwrap(); - assert_eq!(comp.time_base().unwrap().frame_rate(), Some(30.0)); -} - -#[test] -fn layers_and_names() { - // Base: one layer L whose name is its source's (no explicit name stored). - let bytes = fixture!("000-base.aep"); - let file = parse(&bytes).unwrap(); - let comp = Project::new(&file).unwrap().items().find_map(|i| i.comp()).unwrap(); - let layers: Vec<_> = comp.layers().collect(); - assert_eq!(layers.len(), 1); - assert_eq!(layers[0].name(), None); - assert_eq!(layers[0].is_three_d(), Some(false)); - // 110: a text layer T on top of L. - let bytes = fixture!("110-text-A.aep"); - let file = parse(&bytes).unwrap(); - let comp = Project::new(&file).unwrap().items().find_map(|i| i.comp()).unwrap(); - let names: Vec<_> = comp.layers().map(|l| l.name()).collect(); - assert_eq!(names, [Some("T".to_string()), None]); -} - -#[test] -fn three_d_switch() { - let bytes = fixture!("015-layer-3d.aep"); - let file = parse(&bytes).unwrap(); - let project = Project::new(&file).unwrap(); - let layer = first_layer(&project); - assert_eq!(layer.is_three_d(), Some(true)); - // The 3D switch adds the Z rotation to the transform group. - assert!(transform(&layer).names().iter().any(|n| n == "ADBE Rotate Z")); - let bytes = fixture!("000-base.aep"); - let file = parse(&bytes).unwrap(); - let project = Project::new(&file).unwrap(); - assert!(!transform(&first_layer(&project)).names().iter().any(|n| n == "ADBE Rotate Z")); -} - -#[test] -fn match_names_come_from_the_tdmn_chunks() { - let bytes = fixture!("000-base.aep"); - let file = parse(&bytes).unwrap(); - let layer = first_layer(&Project::new(&file).unwrap()); - let root = layer.properties().unwrap(); - let names = root.names(); - assert_eq!(&names[..2], ["ADBE Time Remapping", "ADBE Transform Group"]); - assert!(names.iter().any(|n| n == "ADBE Material Options Group")); - // The path lookup follows nested groups; "ADBE Group End" names nothing. - assert!(matches!(root.find(&["ADBE Transform Group"]), Some(PropNode::Group(_)))); - assert!(!names.iter().any(|n| n == "ADBE Group End")); - assert!(root.find(&["ADBE Transform Group", "ADBE Nonexistent"]).is_none()); - // The raw tdmn body is 40 bytes, NUL padded. - let raw = root.chunk().children().find(|c| c.is(b"tdmn")).unwrap(); - assert_eq!(raw.bytes().unwrap().len(), 40); -} - -#[test] -fn static_value_is_the_first_dims_doubles_of_cdat() { - // 040: Position [960,540,0] -> [100,200,0]; AE stores only non-default transform values. - let bytes = fixture!("040-static-position-100-200.aep"); - let file = parse(&bytes).unwrap(); - let layer = first_layer(&Project::new(&file).unwrap()); - let position = property(&transform(&layer), "ADBE Position"); - assert_eq!(position.dims(), Some(3)); - assert!(!position.is_animated()); - assert_eq!(position.header().map(|h| h.len()), Some(124)); - assert_eq!(position.header().and_then(|h| h.get(68).copied()), Some(0)); - assert_eq!(position.static_value(), Some(vec![100.0, 200.0, 0.0])); - assert!(position.keys().is_none()); - // The base file stores no Position at all. - let bytes = fixture!("000-base.aep"); - let file = parse(&bytes).unwrap(); - let layer = first_layer(&Project::new(&file).unwrap()); - assert!(transform(&layer).get("ADBE Position").is_none()); -} - -#[test] -fn effect_parameter_value() { - // 071: Slider Control effect with Slider = 77. - let bytes = fixture!("071-fx-slider-value77.aep"); - let file = parse(&bytes).unwrap(); - let layer = first_layer(&Project::new(&file).unwrap()); - let parade = match layer.properties().unwrap().get("ADBE Effect Parade") { - Some(PropNode::Group(g)) => g, - other => panic!("{other:?}"), - }; - assert_eq!(parade.names(), ["ADBE Slider Control"]); - let Some(PropNode::Other(instance)) = parade.get("ADBE Slider Control") else { panic!("effect instance") }; - assert!(instance.is_list(b"sspc")); - // The effect's name is in a nested fnam chunk. - let fnam = instance.child(b"fnam").unwrap(); - assert!(matches!(fnam.to_chunk().body, Body::Chunks(_))); - assert_eq!(fnam.children().next().unwrap().bytes(), Some(&b"Slider Control"[..])); - // The parameters are a property group inside the instance. - let params = PropGroup::from_chunk(instance.child_list(b"tdgp").unwrap()).unwrap(); - assert_eq!(params.names(), ["ADBE Slider Control-0000", "ADBE Slider Control-0001", "ADBE Effect Built In Params"]); - let slider = property(¶ms, "ADBE Slider Control-0001"); - assert_eq!(slider.dims(), Some(1)); - assert_eq!(slider.static_value(), Some(vec![77.0])); -} - -#[test] -fn position_keyframes() { - // 055: Position keys at 0 s [0,0,0], 1 s [100,0,0] and 2.5 s [200,100,0], all linear. - let bytes = fixture!("055-key-position-3key-inserted-t2.5.aep"); - let file = parse(&bytes).unwrap(); - let project = Project::new(&file).unwrap(); - let comp = project.items().find_map(|i| i.comp()).unwrap(); - let tb = comp.time_base().unwrap(); - let layer = first_layer(&project); - let position = property(&transform(&layer), "ADBE Position"); - assert!(position.is_animated()); - assert_eq!(position.header().and_then(|h| h.get(68).copied()), Some(1)); - assert_eq!(position.dims(), Some(3)); - assert_eq!(position.static_value(), None); - let keys = position.keys().unwrap(); - // lhd3: record count (word 2), record size (word 4), capacity rounded up to 4 (word 7). - assert_eq!(keys.header.magic, 0x00d0_0bee); - assert_eq!(keys.header.count, 3); - assert_eq!(keys.header.record_size, 128); - assert_eq!(keys.header.words[3], 1); - assert_eq!(keys.header.words[7], 4); - assert_eq!(keys.len(), 3); - let times: Vec = keys.keyframes().map(|k| k.time_units().unwrap()).collect(); - assert_eq!(times, [0, 25_600, 64_000]); - let seconds: Vec = times.iter().map(|t| tb.seconds(*t).unwrap()).collect(); - assert_eq!(seconds, [0.0, 1.0, 2.5]); - let values: Vec> = keys.keyframes().map(|k| k.value().unwrap()).collect(); - assert_eq!(values, [[0.0, 0.0, 0.0], [100.0, 0.0, 0.0], [200.0, 100.0, 0.0]]); -} - -#[test] -fn list_header_facts_hold_in_every_list_of_every_fixture() { - let mut lists = 0; - let mut with_records = 0; - for name in FIXTURES { - let bytes = fixture!(name); - let file = parse(&bytes).unwrap(); - for (_, c) in file.walk() { - if !c.is_list(b"list") || c.child(b"lhd3").is_none() { - continue; - } - lists += 1; - let keys = KeyList::from_chunk(c).unwrap_or_else(|| panic!("{name}: len(ldat) != count * record size")); - assert_eq!(keys.header.magic, 0x00d0_0bee, "{name}"); - assert!(keys.header.words[8..].iter().all(|w| *w == 0), "{name}"); - if !keys.is_empty() { - with_records += 1; - } - assert_eq!(keys.records().count(), keys.len()); - } - } - assert!(lists >= 9 * 10, "lists seen: {lists}"); - assert!(with_records >= 1); -} - -/// Visits every property under a group, depth-limited. -fn visit(group: &PropGroup<'_, '_>, depth: usize, f: &mut dyn FnMut(&Property<'_, '_>)) { - if depth > 24 { - return; - } - for e in group.entries() { - match e.node { - PropNode::Group(g) => visit(&g, depth + 1, f), - PropNode::Property(p) => f(&p), - PropNode::Other(c) => { - if let Some(g) = c.child_list(b"tdgp").and_then(PropGroup::from_chunk) { - visit(&g, depth + 1, f); - } - } - } - } -} - -#[test] -fn property_header_facts_hold_in_every_property_of_every_fixture() { - let (mut props, mut animated) = (0, 0); - for name in FIXTURES { - let bytes = fixture!(name); - let file: AepFile<'_> = parse(&bytes).unwrap(); - let Some(project) = Project::new(&file) else { continue }; - for item in project.all_items() { - let Some(comp) = item.comp() else { continue }; - for layer in comp.layers() { - let Some(root) = layer.properties() else { continue }; - visit(&root, 0, &mut |p| { - props += 1; - let header = p.header().unwrap_or_else(|| panic!("{name}: property without tdb4")); - assert_eq!(header.len(), 124, "{name}"); - // Constant first three bytes, and byte 68 = has keyframes. - assert_eq!(&header[..3], &[0xdb, 0x99, 0x00], "{name}"); - assert_eq!(header[68] == 1, p.is_animated(), "{name}"); - if p.is_animated() { - animated += 1; - let keys = p.keys().unwrap_or_else(|| panic!("{name}: no key list")); - let (count, w) = (keys.header.count, keys.header.words); - assert_eq!(w[3], count.div_ceil(4), "{name}: word 3"); - assert_eq!(w[7], count.div_ceil(4) * 4, "{name}: word 7"); - assert!(p.static_value().is_none(), "{name}"); - } - }); - } - } - } - assert!(props > 100, "properties seen: {props}"); - assert!(animated >= 1); -} diff --git a/crates/aep/tests/it/container/values.rs b/crates/aep/tests/it/container/values.rs deleted file mode 100644 index b7e91881d..000000000 --- a/crates/aep/tests/it/container/values.rs +++ /dev/null @@ -1,249 +0,0 @@ -//! Static transform values with their units, the "absent = default" rule, keyframe records and -//! expressions, checked against the values the corpus was made with (its MANIFEST). - -use crate::container::helpers::{base_layer, first_comp, open}; -use effectcraft_aep::{Interpolation, KeyEase, KeyframeKind, Project, PropNode, Property, Transform, ValueSource}; - -/// The transform of the solid `L` (comp-size defaults) in a fixture. -fn transform(name: &str) -> Option<(Transform, (u32, u32))> { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let comp = first_comp(&project); - let layer = base_layer(&comp); - let ch = comp.header().unwrap(); - let t = layer.transform(u32::from(ch.width), u32::from(ch.height)).unwrap(); - (t, project.layer_source_size(&layer).unwrap()) - }) -} - -fn approx(a: [f64; 3], b: [f64; 3]) { - for (x, y) in a.iter().zip(b) { - assert!((x - y).abs() < 1e-9, "{a:?} != {b:?}"); - } -} - -#[test] -fn absent_properties_are_the_defaults() { - let (t, size) = skip!(transform("000-base.aep")); - assert_eq!(size, (1920, 1080)); - // The base stores none of the five: Position is the comp centre, Anchor the layer centre. - assert_eq!(t.position.value, [960.0, 540.0, 0.0]); - assert_eq!(t.anchor_fraction.value, [0.5, 0.5, 0.0]); - assert_eq!(t.anchor_px(1920.0, 1080.0), [960.0, 540.0, 0.0]); - assert_eq!(t.scale_percent.value, [100.0, 100.0, 100.0]); - assert_eq!(t.rotation_degrees.value, 0.0); - assert_eq!(t.opacity_percent.value, 100.0); - for source in [t.position.source, t.anchor_fraction.source, t.scale_percent.source, t.rotation_degrees.source, t.opacity_percent.source] { - assert_eq!(source, ValueSource::Default); - } -} - -#[test] -fn one_static_value_per_case() { - // 040 Position [960,540,0] -> [100,200,0]. - let (t, _) = skip!(transform("040-static-position-100-200.aep")); - assert_eq!(t.position.value, [100.0, 200.0, 0.0]); - assert_eq!(t.position.source, ValueSource::Stored); - assert_eq!(t.scale_percent.value, [100.0, 100.0, 100.0]); - assert_eq!(t.scale_percent.source, ValueSource::Default); - - // 041 Scale [100,100,100] -> [50,50,100]: stored as fractions. - let (t, _) = skip!(transform("041-static-scale-50.aep")); - assert_eq!(t.scale_percent.value, [50.0, 50.0, 100.0]); - assert_eq!(t.scale_percent.source, ValueSource::Stored); - assert_eq!(t.position.value, [960.0, 540.0, 0.0]); - - // 042 Rotation 0 -> 45 degrees. - let (t, _) = skip!(transform("042-static-rotation-45.aep")); - assert_eq!(t.rotation_degrees.value, 45.0); - assert_eq!(t.rotation_degrees.source, ValueSource::Stored); - - // 043 Opacity 100 -> 25 percent. - let (t, _) = skip!(transform("043-static-opacity-25.aep")); - assert_eq!(t.opacity_percent.value, 25.0); - assert_eq!(t.opacity_percent.source, ValueSource::Stored); - - // 044 Anchor Point [960,540,0] -> [10,20,0]: a fraction of the layer size, 10/1920 and 20/1080. - let (t, (w, h)) = skip!(transform("044-static-anchor-10-20.aep")); - assert_eq!(t.anchor_fraction.source, ValueSource::Stored); - approx(t.anchor_fraction.value, [10.0 / 1920.0, 20.0 / 1080.0, 0.0]); - approx(t.anchor_px(f64::from(w), f64::from(h)), [10.0, 20.0, 0.0]); -} - -#[test] -fn a_composition_resize_materialises_the_old_centre() { - // 030: the comp becomes 1280x720 and L (1920x1080) is not moved: its Position, which was - // "absent = centre" in the base, is now stored as [960,540,0] (the new centre would be - // [640,360]); the layer size is unchanged. - let (t, size) = skip!(transform("030-comp-size-1280x720.aep")); - assert_eq!(size, (1920, 1080)); - assert_eq!(t.position.value, [960.0, 540.0, 0.0]); - assert_eq!(t.position.source, ValueSource::Stored); - assert_eq!(t.anchor_fraction.source, ValueSource::Default); -} - -// ------------------------------------------------------------------------------------ keyframes - -/// The Position property of `L` in a fixture, handed to `f`. -fn with_position(name: &str, f: impl FnOnce(Property<'_, '_>) -> R) -> Option { - with_transform_property(name, "ADBE Position", f) -} - -fn with_transform_property(name: &str, prop: &str, f: impl FnOnce(Property<'_, '_>) -> R) -> Option { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = base_layer(&first_comp(&project)); - let Some(PropNode::Property(p)) = layer.properties().unwrap().find(&["ADBE Transform Group", prop]) else { panic!("{name}: no {prop}") }; - f(p) - }) -} - -#[test] -fn linear_position_keys() { - skip!(with_position("055-key-position-3key-inserted-t2.5.aep", |p| { - assert_eq!(p.time_scale(), Some(25600)); - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 3); - // Keys added through the scripting interface are linear in and out, uncoloured, not roving. - for k in &keys { - assert_eq!(k.kind(), KeyframeKind::Spatial { components: 3 }); - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); - assert_eq!((k.label(), k.is_roving()), (Some(0), Some(false))); - } - let secs: Vec<_> = keys.iter().map(|k| k.seconds(25600).unwrap()).collect(); - assert_eq!(secs, [0.0, 1.0, 2.5]); - let values: Vec<_> = keys.iter().map(|k| k.spatial().unwrap().value).collect(); - assert_eq!(values, [[0.0, 0.0, 0.0], [100.0, 0.0, 0.0], [200.0, 100.0, 0.0]]); - assert_eq!(p.first_key_value(), Some(vec![0.0, 0.0, 0.0])); - assert!(p.is_animated()); - })); - // The transform of the layer reports the animated Position as keyframed (value at the first key). - let (t, _) = skip!(transform("055-key-position-3key-inserted-t2.5.aep")); - assert_eq!(t.position.source, ValueSource::Keyframed); - assert_eq!(t.position.value, [0.0, 0.0, 0.0]); -} - -#[test] -fn ease_preset_sets_bezier_and_influence() { - // 052: both keys use the ease preset: bezier in and out, speed 0, influence 0.33 (33 %). - skip!(with_position("052-key-position-2key-ease.aep", |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert_eq!(keys.len(), 2); - for k in &keys { - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); - let s = k.spatial().unwrap(); - // The speeds sit at slots 0 and 2, the influences at slots 1 and 3; which pair is "in" - // is not decided, so the slots are exposed as stored. - assert_eq!((s.ease[0], s.ease[2]), (0.0, 0.0)); - assert_eq!((s.ease[1], s.ease[3]), (0.33, 0.33)); - } - let secs: Vec<_> = keys.iter().map(|k| k.seconds(25600).unwrap()).collect(); - assert_eq!(secs, [0.0, 1.0]); - })); -} - -#[test] -fn hold_keyframe() { - // 053: key 1 is a hold keyframe on both sides (bytes 3, 3), key 2 stays linear; the values are unchanged. - skip!(with_position("053-key-position-2key-hold-key1.aep", |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - assert_eq!((keys[0].interpolation_in(), keys[0].interpolation_out()), (Some(Interpolation::Hold), Some(Interpolation::Hold))); - assert_eq!((keys[1].interpolation_in(), keys[1].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); - assert_eq!(keys[0].spatial().unwrap().value, [0.0, 0.0, 0.0]); - assert_eq!(keys[1].spatial().unwrap().value, [100.0, 0.0, 0.0]); - })); -} - -#[test] -fn spatial_tangents() { - // 054: key 1 spatial out tangent [30,60,0], key 2 spatial in tangent [-30,-60,0]; the - // auto-bezier / continuous switches were turned off together (the flag word becomes 0). - skip!(with_position("054-key-position-2key-spatial-bezier.aep", |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().map(|k| k.spatial().unwrap()).collect(); - assert_eq!(keys[0].out_tangent, [30.0, 60.0, 0.0]); - assert_eq!(keys[1].in_tangent, [-30.0, -60.0, 0.0]); - assert_eq!(keys[0].in_tangent, [0.0, 0.0, 0.0]); - assert_eq!(keys[1].out_tangent, [0.0, 0.0, 0.0]); - assert_eq!((keys[0].auto_bezier_flag, keys[1].auto_bezier_flag), (0, 0)); - })); -} - -#[test] -fn roving_and_label_flags() { - // 056: key 2 roving (AE moved it from 1 s to 26509/25600 s, the value is kept). - skip!(with_position("056-key-position-3key-roving-key2.aep", |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - let roving: Vec<_> = keys.iter().map(|k| k.is_roving().unwrap()).collect(); - assert_eq!(roving, [false, true, false]); - assert_eq!(keys[1].time_units(), Some(26509)); - assert_eq!(keys[1].seconds(25600), Some(1.0355078125)); - assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); - assert_eq!(keys[1].flags(), Some(0x0027)); - assert_eq!(keys[1].label(), Some(0)); - })); - // 057: key 2 gets keyframe label 9; flags 0x0007 become 0x0247. - skip!(with_position("057-key-position-3key-label9-key2.aep", |p| { - let keys: Vec<_> = p.keys().unwrap().keyframes().collect(); - let labels: Vec<_> = keys.iter().map(|k| k.label().unwrap()).collect(); - assert_eq!(labels, [0, 9, 0]); - assert_eq!(keys[1].flags(), Some(0x0247)); - assert_eq!(keys[0].flags(), Some(0x0007)); - assert_eq!(keys[1].is_roving(), Some(false)); - assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); - })); -} - -#[test] -fn scalar_opacity_keys() { - // 058: Opacity 0 % at 0 s, 100 % at 2 s, linear: 48-byte records, the value is a fraction. - skip!(with_transform_property("058-key-opacity-2key.aep", "ADBE Opacity", |p| { - assert!(p.is_animated()); - assert_eq!(p.dims(), Some(1)); - assert_eq!(p.time_scale(), Some(25600)); - let list = p.keys().unwrap(); - assert_eq!(list.header.record_size, 48); - let keys: Vec<_> = list.keyframes().collect(); - assert_eq!(keys.len(), 2); - assert!(keys.iter().all(|k| k.kind() == KeyframeKind::Plain { components: 1 })); - assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 2.0]); - assert_eq!(keys.iter().map(|k| k.scalar_value().unwrap()).collect::>(), [0.0, 1.0]); - for k in &keys { - assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); - assert_eq!(k.ease(), Some(KeyEase { in_speed: 0.0, in_influence: 0.0, out_speed: 0.0, out_influence: 0.0 })); - assert_eq!(k.flags(), Some(0)); - } - assert_eq!(keys[0].spatial(), None); - })); - let (t, _) = skip!(transform("058-key-opacity-2key.aep")); - assert_eq!(t.opacity_percent.source, ValueSource::Keyframed); - assert_eq!(t.opacity_percent.value, 0.0); -} - -// ---------------------------------------------------------------------------------- expressions - -#[test] -fn expression_text_and_flag_bytes() { - // 060: Opacity expression `wiggle(1,10)`; the static value 1.0 is kept. - skip!(with_transform_property("060-expr-opacity-wiggle.aep", "ADBE Opacity", |p| { - assert_eq!(p.expression().as_deref(), Some("wiggle(1,10)")); - let flags = p.expression_flags().unwrap(); - // Byte 120 marks the expression. Bytes 76 and 77 were 1 too in the single-case file and - // are 0 in the combined one, so they do not mark it. - assert_eq!(flags.byte_120, 1); - assert_eq!(p.static_value(), Some(vec![1.0])); - assert!(!p.is_animated()); - })); - // A property without an expression has none of the three bytes set. - skip!(with_position("040-static-position-100-200.aep", |p| { - assert_eq!(p.expression(), None); - let flags = p.expression_flags().unwrap(); - assert_eq!((flags.byte_76, flags.byte_77, flags.byte_120), (0, 0, 0)); - // A written static property: tdsb 1, byte 5 of tdb4 has bit 0 set (15 for Position). - assert_eq!(p.flags(), Some(1)); - assert_eq!(p.header().and_then(|h| h.get(5).copied()), Some(15)); - })); -} diff --git a/crates/aep/tests/it/import/effects_thirdparty.rs b/crates/aep/tests/it/import/effects_thirdparty.rs index 567d77642..5ecb0f1f5 100644 --- a/crates/aep/tests/it/import/effects_thirdparty.rs +++ b/crates/aep/tests/it/import/effects_thirdparty.rs @@ -118,7 +118,7 @@ fn extractor_channel_info_layout() { // `02 00 00 32` on Alpha, still the input's own channel. let c = ExtractorChannels::parse(&channels([(1, "R"), (1, "G"), (1, "B"), (0x3200_0002, "(copy)")])).expect("parses"); assert!(c.is_default()); - assert_eq!(c.sources(), Ok(["R", "G", "B", "(copy)"].map(String::from))); + assert_eq!(c.sources(effectcraft_effects::EXTRACTOR_COPY), Ok(["R", "G", "B", "(copy)"].map(String::from))); } #[test] diff --git a/crates/export/tests/it/movie_bytes.rs b/crates/export/tests/it/movie_bytes.rs index 00e19b396..95d67fd53 100644 --- a/crates/export/tests/it/movie_bytes.rs +++ b/crates/export/tests/it/movie_bytes.rs @@ -94,14 +94,12 @@ fn export_bytes(format: OutputFormat, name: &str) -> Vec { #[test] fn h264_movie_bytes_are_pinned() { let data = export_bytes(OutputFormat::H264, "/out/pinned.mp4"); - // FilmCraft 09aaf9b's encoder lists its settings in the first frame's user-data SEI (211 - // bytes where 0.1.1's name took 50): 161 bytes more than the FilmCraft 2c5ba7a pin. The encoder's - // version string "0.8.0" -> "0.12.0" in that SEI adds one more byte (and one to the size fields). - // craft-video's encoder (craft-libs) is that encoder at a later FilmCraft revision than the - // d5ead4b pin: it names itself "craft-h264enc 0.1.0" in the SEI (5 bytes fewer), and with these - // settings its packets match the pin's for the first ten frames and differ after (24 bytes more - // in all, with the size fields). - assert_eq!((data.len(), fnv1a(&data)), (104_366, 4_413_091_804_733_884_658), "H.264 MP4"); + // The shared encoder revision includes craft-video's later motion-search work (four-axis + // sub-pel refinement and gating 16x8/8x16 searches on the 8x8 result). The app's encoder + // configuration and input path are unchanged, but its coded decisions and output bytes differ + // from the earlier craft-video pin. craft-video pins those decisions and checks bit-exact + // decoding against its reconstruction with FFmpeg/ffprobe oracles. + assert_eq!((data.len(), fnv1a(&data)), (102_462, 9_984_203_720_367_148_918), "H.264 MP4"); } #[test] diff --git a/crates/lottie/Cargo.toml b/crates/lottie/Cargo.toml index a9f64b3ba..9a95dca13 100644 --- a/crates/lottie/Cargo.toml +++ b/crates/lottie/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-lottie = { workspace = true } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } diff --git a/crates/lottie/src/anim.rs b/crates/lottie/src/anim.rs index 40a56a7eb..62550f86f 100644 --- a/crates/lottie/src/anim.rs +++ b/crates/lottie/src/anim.rs @@ -1,23 +1,14 @@ -//! Animated properties: EffectCraft keyframes ↔ Lottie keyframes. -//! -//! A Lottie keyframe holds the start value `s` of a segment and the segment's normalised cubic -//! Bezier ease: `o` (out tangent of this key) and `i` (in tangent of the next key), each with `x` -//! (time fraction) and `y` (value progress fraction), per dimension. After Effects' temporal ease -//! is speed (units/s) and influence (fraction of the segment): for a segment of duration `d` and -//! value change `Δv`, -//! -//! ```text -//! o.x = influence_out o.y = speed_out · influence_out · d / Δv -//! i.x = 1 − influence_in i.y = 1 − speed_in · influence_in · d / Δv -//! ``` -//! -//! which is exactly the Bezier the keyframe evaluator uses. Spatial properties ease along the -//! motion path (Δv = arc length, one dimension) and carry `to`/`ti` spatial tangents. Hold keys -//! set `h: 1`. +//! Animated properties: EffectCraft keyframes ↔ Lottie keyframes, through `craft-lottie`'s +//! property encoding ([`craft_lottie::read_prop`], [`craft_lottie::write_prop`]) and its +//! conversion between a segment's normalised Bezier ease and After Effects' speed and influence +//! ([`Tangents`]). Spatial properties ease along the motion path (Δv = arc length, one +//! dimension) and carry `to`/`ti` spatial tangents. +pub(crate) use craft_lottie::nums; +use craft_lottie::{Animated, Json, KeyOut, PropValue, Tangents, read_prop, round6}; use effectcraft_keyframe::{self as kf, Ease, Interp, Keyframe, Value}; use effectcraft_project::{Expression, Property}; -use serde_json::{Value as Json, json}; +use serde_json::json; use crate::Timebase; @@ -62,15 +53,11 @@ fn secs(t: effectcraft_time::Tick) -> f64 { } fn r6(v: f64) -> f64 { - if v.is_finite() { (v * 1e6).round() / 1e6 } else { 0.0 } + round6(v) } -/// A key value as Lottie's `s` (numbers wrapped in an array, objects in a one-element array). -fn wrap(j: Json) -> Json { - match j { - Json::Array(_) => j, - other => json!([other]), - } +fn lottie_ease(e: Ease) -> craft_lottie::Ease { + craft_lottie::Ease { speed: e.speed, influence: e.influence } } fn is_spatial(p: &Property) -> bool { @@ -80,7 +67,7 @@ fn is_spatial(p: &Property) -> bool { /// Export a property as a Lottie animatable property (`{a, k}` plus `x` for expressions). /// `label` names the property in warnings. Muted keys are omitted: Lottie has no mute state, and /// the remaining keys carry the animation the renderer shows. -pub(crate) fn export_prop(ex: &mut Ex, p: &Property, conv: &dyn Fn(&Value) -> Json, label: &str) -> Json { +pub(crate) fn export_prop(ex: &mut Ex, p: &Property, conv: &dyn Fn(&Value) -> Json, label: &str) -> Animated { let muted = p.keys.iter().any(|k| k.muted); if muted { ex.warn(format!("{label}: muted keyframes are not exported")); @@ -92,146 +79,102 @@ pub(crate) fn export_prop(ex: &mut Ex, p: &Property, conv: &dyn Fn(&Value) -> Js } else { &p.keys }; - let mut out = - if keys.is_empty() { json!({"a": 0, "k": conv(&p.value)}) } else { json!({"a": 1, "k": export_keys(ex, keys, is_spatial(p), p.hold_only, conv)}) }; + let mut expression = None; if let Some(e) = p.expr.as_ref().filter(|e| e.enabled && !e.text.trim().is_empty()) { if ex.include_expressions { - out["x"] = json!(e.text); + expression = Some(e.text.as_str()); } else { ex.warn(format!("{label}: expression not exported (enable includeExpressions to export it as `x`)")); } } - out + if keys.is_empty() { + return Animated(craft_lottie::write_prop(conv(&p.value), &[], expression)); + } + Animated::keyed(&export_keys(ex, keys, is_spatial(p), p.hold_only, conv), expression) } -fn export_keys(ex: &Ex, keys: &[Keyframe], spatial: bool, hold_only: bool, conv: &dyn Fn(&Value) -> Json) -> Vec { +fn export_keys(ex: &Ex, keys: &[Keyframe], spatial: bool, hold_only: bool, conv: &dyn Fn(&Value) -> Json) -> Vec { let mut out = Vec::with_capacity(keys.len()); for (i, k) in keys.iter().enumerate() { - let mut o = json!({"t": r6(ex.tb.frame(k.time)), "s": wrap(conv(&k.value))}); - if i + 1 == keys.len() { - if k.out_interp == Interp::Hold || hold_only { - o["h"] = json!(1); + let mut o = KeyOut { t: ex.tb.frame(k.time), s: conv(&k.value), hold: false, ease: vec![], spatial: None }; + let last = i + 1 == keys.len(); + if k.out_interp == Interp::Hold || hold_only || (!last && !k.value.interpolates()) { + o.hold = true; + } else if !last { + o.ease = segment_ease(keys, i, spatial); + if spatial { + let (_, to) = kf::spatial_tangents(keys, i); + let (ti, _) = kf::spatial_tangents(keys, i + 1); + let n = if matches!(k.value, Value::Vec2(_)) { 2 } else { conv(&k.value).as_array().map(Vec::len).unwrap_or(3).min(3) }; + o.spatial = Some((to.get(..n).unwrap_or_default().to_vec(), ti.get(..n).unwrap_or_default().to_vec())); } - out.push(o); - continue; - } - if k.out_interp == Interp::Hold || hold_only || !k.value.interpolates() { - o["h"] = json!(1); - out.push(o); - continue; - } - let (ox, oy, ix, iy) = segment_ease(keys, i, spatial); - o["o"] = json!({"x": ox, "y": oy}); - o["i"] = json!({"x": ix, "y": iy}); - if spatial { - let (_, to) = kf::spatial_tangents(keys, i); - let (ti, _) = kf::spatial_tangents(keys, i + 1); - let n = if matches!(k.value, Value::Vec2(_)) { 2 } else { conv(&k.value).as_array().map(Vec::len).unwrap_or(3).min(3) }; - o["to"] = json!(to[..n].iter().map(|v| r6(*v)).collect::>()); - o["ti"] = json!(ti[..n].iter().map(|v| r6(*v)).collect::>()); } out.push(o); } out } -/// Normalised ease of segment `i → i+1`: (o.x, o.y, i.x, i.y) per dimension. -fn segment_ease(keys: &[Keyframe], i: usize, spatial: bool) -> (Vec, Vec, Vec, Vec) { - let (a, b) = (&keys[i], &keys[i + 1]); +/// Normalised ease of segment `i → i+1`, one entry per dimension. +fn segment_ease(keys: &[Keyframe], i: usize, spatial: bool) -> Vec { + let (Some(a), Some(b)) = (keys.get(i), keys.get(i + 1)) else { return vec![] }; let dur = (secs(b.time) - secs(a.time)).max(1e-12); let ca = a.value.components(); let cb = b.value.components(); let numeric = !ca.is_empty() && ca.len() == cb.len(); let dims = if spatial || !numeric { 1 } else { ca.len() }; - let (mut ox, mut oy, mut ix, mut iy) = (vec![], vec![], vec![], vec![]); - for d in 0..dims { - let (dv, eo, ei) = if spatial { - let len = kf::spatial_segment_length(keys, i); - (len, kf::side_ease(keys, i, 0, true, true), kf::side_ease(keys, i + 1, 0, true, false)) - } else if numeric { - (cb[d] - ca[d], kf::side_ease(keys, i, d, false, true), kf::side_ease(keys, i + 1, d, false, false)) - } else { - // Paths, gradients: overall progress 0 → 1. - let side = |k: &Keyframe, out: bool| { - let interp = if out { k.out_interp } else { k.in_interp }; - let list = if out { &k.out_ease } else { &k.in_ease }; - if interp == Interp::Bezier { - list.first().copied().unwrap_or_default() - } else { - Ease { speed: 1.0 / dur, influence: kf::LINEAR_SIDE_INFLUENCE } - } + (0..dims) + .map(|d| { + let (dv, eo, ei) = if spatial { + let len = kf::spatial_segment_length(keys, i); + (len, kf::side_ease(keys, i, 0, true, true), kf::side_ease(keys, i + 1, 0, true, false)) + } else if numeric { + (cb[d] - ca[d], kf::side_ease(keys, i, d, false, true), kf::side_ease(keys, i + 1, d, false, false)) + } else { + // Paths, gradients: overall progress 0 → 1. + let side = |k: &Keyframe, out: bool| { + let interp = if out { k.out_interp } else { k.in_interp }; + let list = if out { &k.out_ease } else { &k.in_ease }; + if interp == Interp::Bezier { + list.first().copied().unwrap_or_default() + } else { + Ease { speed: 1.0 / dur, influence: kf::LINEAR_SIDE_INFLUENCE } + } + }; + (1.0, Some(side(a, true)), Some(side(b, false))) }; - (1.0, Some(side(a, true)), Some(side(b, false))) - }; - let lin = Ease { speed: dv / dur, influence: kf::LINEAR_SIDE_INFLUENCE }; - let (eo, ei) = (eo.unwrap_or(lin), ei.unwrap_or(lin)); - // Crossing time handles must retain the independently specified influences. - let (i0, i1) = (eo.influence.clamp(0.0, 1.0), ei.influence.clamp(0.0, 1.0)); - let (y0, y1) = if dv.abs() > 1e-12 { (eo.speed * i0 * dur / dv, 1.0 - ei.speed * i1 * dur / dv) } else { (0.0, 1.0) }; - ox.push(r6(i0)); - oy.push(r6(y0)); - ix.push(r6(1.0 - i1)); - iy.push(r6(y1)); - } - (ox, oy, ix, iy) + let lin = Ease { speed: dv / dur, influence: kf::LINEAR_SIDE_INFLUENCE }; + // Crossing time handles keep the independently specified influences. + Tangents::from_speed(lottie_ease(eo.unwrap_or(lin)), lottie_ease(ei.unwrap_or(lin)), dv, dur) + }) + .collect() } // ---------------------------------------------------------------- import -/// Whether a Lottie property value is keyframed. -pub(crate) fn is_animated(j: &Json) -> bool { - if j.get("a").and_then(Json::as_i64) == Some(1) { - return true; - } - j.get("k").and_then(Json::as_array).and_then(|a| a.first()).is_some_and(|f| f.get("t").is_some()) -} - -/// Component `d` of an ease tangent field (`x` / `y` may be a number or an array). -fn comp(j: &Json, field: &str, d: usize) -> Option { - match j.get(field)? { - Json::Number(n) => n.as_f64(), - Json::Array(a) => a.get(d).or(a.first()).and_then(Json::as_f64), - _ => None, - } -} - -fn vec3_of(j: Option<&Json>) -> [f64; 3] { - let a = j.and_then(Json::as_array); - let g = |i: usize| a.and_then(|a| a.get(i)).and_then(Json::as_f64).unwrap_or(0.0); - [g(0), g(1), g(2)] -} - /// Import a Lottie animatable property into `p` (value, keys, expression). `conv` turns a Lottie /// value (as found in `k` or a key's `s`, possibly wrapped in a one-element array) into a value of /// the property's type. pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Json) -> Option) { - if !j.is_object() { - if let Some(v) = conv(j) { - p.value = v; - } - return; - } - if let Some(x) = j.get("x").and_then(Json::as_str).filter(|x| !x.trim().is_empty()) { + let prop = read_prop(j); + if let Some(x) = prop.expression { p.expr = Some(Expression { text: x.to_string(), enabled: true }); } - let Some(k) = j.get("k") else { return }; - if !is_animated(j) { - if let Some(v) = conv(k) { - p.value = v; + let list = match prop.value { + PropValue::None => return, + PropValue::Static(v) => { + if let Some(v) = conv(v) { + p.value = v; + } + return; } - return; - } - let Some(list) = k.as_array() else { return }; + PropValue::Keys(list) => list, + }; let spatial = is_spatial(p); let mut keys: Vec = Vec::with_capacity(list.len()); - let mut kept: Vec<&Json> = Vec::with_capacity(list.len()); - let mut prev_end: Option<&Json> = None; + let mut kept = Vec::with_capacity(list.len()); for kj in list { - let t = kj.get("t").and_then(Json::as_f64).unwrap_or(0.0); - let sv = kj.get("s").or(prev_end); - prev_end = kj.get("e"); - let Some(v) = sv.and_then(conv) else { continue }; - let mut key = Keyframe::new(im.tb.tick(t), v); + let Some(v) = kj.s.and_then(conv) else { continue }; + let mut key = Keyframe::new(im.tb.tick(kj.t), v); key.spatial_auto = false; if p.hold_only || !key.value.interpolates() { key = key.hold(); @@ -245,16 +188,14 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js let n = keys.len(); for i in 0..n.saturating_sub(1) { let Some(kj) = kept.get(i) else { break }; - if kj.get("h").and_then(Json::as_i64) == Some(1) || p.hold_only { + if kj.hold || p.hold_only { keys[i].out_interp = Interp::Hold; keys[i + 1].in_interp = Interp::Hold; continue; } if spatial { - let to = vec3_of(kj.get("to")); - let ti = vec3_of(kj.get("ti")); - keys[i].spatial_out = to; - keys[i + 1].spatial_in = ti; + keys[i].spatial_out = kj.to; + keys[i + 1].spatial_in = kj.ti; } } // Eases need the spatial tangents (arc length), so they come second. @@ -263,7 +204,7 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js if keys[i].out_interp == Interp::Hold { continue; } - let (Some(o), Some(ii)) = (kj.get("o"), kj.get("i")) else { + let (Some(o), Some(ii)) = (kj.o, kj.i) else { keys[i].out_interp = Interp::Linear; keys[i + 1].in_interp = Interp::Linear; continue; @@ -277,13 +218,8 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js let mut outs = vec![]; let mut ins = vec![]; for d in 0..dims { - let ox = comp(o, "x", d).unwrap_or(1.0 / 3.0).clamp(0.0, 1.0); - let oy = comp(o, "y", d).unwrap_or(ox); - let ix = comp(ii, "x", d).unwrap_or(2.0 / 3.0).clamp(0.0, 1.0); - let iy = comp(ii, "y", d).unwrap_or(ix); - if (ox - oy).abs() > 1e-4 || (ix - iy).abs() > 1e-4 { - linear = false; - } + let t = Tangents::read(o, ii, d); + linear &= t.is_linear(); let dv = if spatial { kf::spatial_segment_length(&keys, i) } else if numeric { @@ -291,10 +227,9 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js } else { 1.0 }; - let inf_o = ox.max(0.001); - let inf_i = (1.0 - ix).max(0.001); - outs.push(Ease { speed: oy * dv / (inf_o * dur), influence: inf_o }); - ins.push(Ease { speed: (1.0 - iy) * dv / (inf_i * dur), influence: inf_i }); + let (out, into) = t.to_speed(dv, dur); + outs.push(Ease { speed: out.speed, influence: out.influence }); + ins.push(Ease { speed: into.speed, influence: into.influence }); } if linear { keys[i].out_interp = Interp::Linear; @@ -310,6 +245,13 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js p.keys = keys; } +/// [`import_prop`] for a property of the model ([`Animated`]). +pub(crate) fn import_animated(im: &Im, a: Option<&Animated>, p: &mut Property, conv: &dyn Fn(&Json) -> Option) { + if let Some(a) = a { + import_prop(im, &a.0, p, conv); + } +} + // ---------------------------------------------------------------- value converters pub(crate) fn num(v: &Value) -> Json { @@ -335,23 +277,6 @@ pub(crate) fn arr3(v: &Value) -> Json { json!([r6(*c.first().unwrap_or(&0.0)), r6(*c.get(1).unwrap_or(&0.0)), r6(*c.get(2).unwrap_or(&0.0))]) } -/// Numbers of a Lottie value (`5`, `[5]`, `[1, 2, 3]`). -pub(crate) fn nums(j: &Json) -> Option> { - match j { - Json::Number(n) => Some(vec![n.as_f64()?]), - Json::Array(a) => { - // `[[x, y]]`-style wrapping. - if a.len() == 1 - && let Some(inner @ Json::Array(_)) = a.first() - { - return nums(inner); - } - a.iter().map(Json::as_f64).collect() - } - _ => None, - } -} - pub(crate) fn to_scalar(j: &Json) -> Option { nums(j).and_then(|v| v.first().copied()).map(Value::Scalar) } @@ -368,15 +293,8 @@ pub(crate) fn to_vec3(j: &Json, z: f64) -> Option { } pub(crate) fn to_color(j: &Json) -> Option { - let v = nums(j)?; - let mut c = [*v.first()?, *v.get(1).unwrap_or(&0.0), *v.get(2).unwrap_or(&0.0), *v.get(3).unwrap_or(&1.0)]; - // Some files use 0–255. - if c[..3].iter().any(|x| *x > 1.0) { - for x in &mut c[..3] { - *x /= 255.0; - } - } - Some(Value::Color(c)) + // Some files use 0–255: `craft_lottie::color` divides those. + craft_lottie::color(j).map(Value::Color) } pub(crate) fn to_bool(j: &Json) -> Option { diff --git a/crates/lottie/src/base64.rs b/crates/lottie/src/base64.rs deleted file mode 100644 index b45f86d4a..000000000 --- a/crates/lottie/src/base64.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Standard base64 (RFC 4648 §4) for embedded image assets. - -const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -pub fn encode(data: &[u8]) -> String { - let mut out = String::with_capacity(data.len().div_ceil(3) * 4); - for chunk in data.chunks(3) { - let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)]; - let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32; - for i in 0..4 { - if i <= chunk.len() { - out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char); - } else { - out.push('='); - } - } - } - out -} - -pub fn decode(s: &str) -> Option> { - let val = |c: u8| -> Option { - Some(match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - _ => return None, - } as u32) - }; - let clean: Vec = s.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=').collect(); - let mut out = Vec::with_capacity(clean.len() * 3 / 4); - for chunk in clean.chunks(4) { - let mut n = 0u32; - for (i, &c) in chunk.iter().enumerate() { - n |= val(c)? << (18 - 6 * i); - } - let bytes = [(n >> 16) as u8, (n >> 8) as u8, n as u8]; - match chunk.len() { - 4 => out.extend_from_slice(&bytes), - 3 => out.extend_from_slice(&bytes[..2]), - 2 => out.push(bytes[0]), - _ => return None, - } - } - Some(out) -} - -/// Split a `data:;base64,` URI into (mime, bytes). -pub fn data_uri(s: &str) -> Option<(String, Vec)> { - let rest = s.strip_prefix("data:")?; - let (head, payload) = rest.split_once(',')?; - let mime = head.strip_suffix(";base64")?; - Some((mime.to_string(), decode(payload)?)) -} - -#[cfg(test)] -mod tests { - #[test] - fn roundtrip() { - for s in ["", "f", "fo", "foo", "foob", "fooba", "foobar"] { - let e = super::encode(s.as_bytes()); - assert_eq!(super::decode(&e).unwrap(), s.as_bytes()); - } - assert_eq!(super::encode(b"foobar"), "Zm9vYmFy"); - assert_eq!(super::encode(b"fo"), "Zm8="); - } -} diff --git a/crates/lottie/src/export.rs b/crates/lottie/src/export.rs index 88dcf4ed4..99ca28e7e 100644 --- a/crates/lottie/src/export.rs +++ b/crates/lottie/src/export.rs @@ -2,11 +2,14 @@ use std::collections::BTreeSet; +use craft_lottie::model::{Asset, Effect, Font, Fonts, Layer as LottieLayer, LayerContent, Marker, Mask, PrecompLayer, SolidLayer, Transform}; +use craft_lottie::{Animated, Animation, Json}; use effectcraft_keyframe::Value; use effectcraft_project::{Comp, FootageKind, GroupKind, ItemId, ItemKind, Layer, LayerSource, MaskMode, MatteKind, Project, PropGroup}; -use serde_json::{Map, Value as Json, json}; +use serde_json::json; use crate::anim::{self, Ex, export_prop}; +use crate::shapes::fixed; use crate::{LottieError, Timebase, shapes, text}; /// Export settings. @@ -134,30 +137,15 @@ struct Doc<'a> { opts: &'a ExportOptions, read: &'a dyn Fn(&str) -> Option>, ex: Ex, - assets: Vec, + assets: Vec, done: BTreeSet, - fonts: Vec, + fonts: Vec, any_3d: bool, } -fn hex(c: [f32; 3]) -> String { - let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2])) -} - /// The image type `bytes` hold, by their signature; `None` for anything else. pub(crate) fn image_mime(bytes: &[u8]) -> Option<&'static str> { - if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { - Some("image/png") - } else if bytes.starts_with(&[0xff, 0xd8, 0xff]) { - Some("image/jpeg") - } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { - Some("image/gif") - } else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") { - Some("image/webp") - } else { - None - } + craft_lottie::image_mime(bytes) } impl Doc<'_> { @@ -165,84 +153,68 @@ impl Doc<'_> { self.ex.tb.frame(t) } - fn prop(&mut self, g: &PropGroup, m: &str, conv: &dyn Fn(&Value) -> Json, label: &str) -> Option { + fn prop(&mut self, g: &PropGroup, m: &str, conv: &dyn Fn(&Value) -> Json, label: &str) -> Option { let p = g.get(m)?; Some(export_prop(&mut self.ex, p, conv, &format!("{label} ▸ {}", p.name))) } - fn transform(&mut self, l: &Layer) -> Json { - let mut ks = Map::new(); - let Some(tr) = l.transform() else { return json!({}) }; + fn transform(&mut self, l: &Layer) -> Transform { + let mut ks = Transform::default(); + let Some(tr) = l.transform() else { return ks }; let label = format!("{} ▸ Transform", l.name); let three = l.is_3d(); - if let Some(a) = self.prop(tr, "anchor", &anim::arr3, &label) { - ks.insert("a".into(), a); - } + ks.anchor = self.prop(tr, "anchor", &anim::arr3, &label); if tr.get("positionX").is_some() { let mut p = json!({"s": true}); for (k, m) in [("x", "positionX"), ("y", "positionY"), ("z", "positionZ")] { if (k != "z" || three) && let Some(v) = self.prop(tr, m, &anim::num, &label) { - p[k] = v; + p[k] = v.0; } } - ks.insert("p".into(), p); - } else if let Some(p) = self.prop(tr, "position", &anim::arr3, &label) { - ks.insert("p".into(), p); - } - if let Some(s) = self.prop(tr, "scale", &anim::arr3, &label) { - ks.insert("s".into(), s); + ks.position = Some(Animated(p)); + } else { + ks.position = self.prop(tr, "position", &anim::arr3, &label); } + ks.scale = self.prop(tr, "scale", &anim::arr3, &label); if three { - for (k, m) in [("rx", "rotationX"), ("ry", "rotationY"), ("rz", "rotation")] { - if let Some(v) = self.prop(tr, m, &anim::num, &label) { - ks.insert(k.into(), v); - } - } - if let Some(v) = self.prop(tr, "orientation", &anim::arr3, &label) { - ks.insert("or".into(), v); - } - } else if let Some(r) = self.prop(tr, "rotation", &anim::num, &label) { - ks.insert("r".into(), r); + ks.rotation_x = self.prop(tr, "rotationX", &anim::num, &label); + ks.rotation_y = self.prop(tr, "rotationY", &anim::num, &label); + ks.rotation_z = self.prop(tr, "rotation", &anim::num, &label); + ks.orientation = self.prop(tr, "orientation", &anim::arr3, &label); + } else { + ks.rotation = self.prop(tr, "rotation", &anim::num, &label); } - if let Some(o) = self.prop(tr, "opacity", &anim::num, &label) { - ks.insert("o".into(), o); - } - Json::Object(ks) + ks.opacity = self.prop(tr, "opacity", &anim::num, &label); + ks } - fn masks(&mut self, l: &Layer) -> Vec { + fn masks(&mut self, l: &Layer) -> Vec { let Some(masks) = l.masks() else { return vec![] }; let mut out = vec![]; for m in masks.groups() { let GroupKind::Mask { mode, inverted, .. } = m.kind else { continue }; let label = format!("{} ▸ {}", l.name, m.name); - let mut o = json!({"nm": m.name, "mode": mask_mode(mode), "inv": inverted}); - if let Some(v) = self.prop(m, "path", &shapes::path_value, &label) { - o["pt"] = v; - } - if let Some(v) = self.prop(m, "opacity", &anim::num, &label) { - o["o"] = v; - } - if let Some(v) = self.prop(m, "expansion", &anim::num, &label) { - o["x"] = v; - } + let mut o = Mask { name: Some(m.name.clone()), mode: Some(mask_mode(mode).into()), inverted: Some(inverted), ..Default::default() }; + o.path = self.prop(m, "path", &shapes::path_value, &label); + o.opacity = self.prop(m, "opacity", &anim::num, &label); + o.expansion = self.prop(m, "expansion", &anim::num, &label); if let Some(f) = m.get("feather") { if f.is_animated() || f.value.components().iter().any(|v| *v != 0.0) { self.ex.warn(format!("{label}: mask feather is exported as `f` (not every Lottie player renders it)")); } - o["f"] = export_prop(&mut self.ex, f, &anim::arr2, &format!("{label} ▸ Mask Feather")); + o.extra.insert("f".into(), export_prop(&mut self.ex, f, &anim::arr2, &format!("{label} ▸ Mask Feather")).0); } if !m.enabled { - o["mode"] = json!("n"); + o.mode = Some("n".into()); } out.push(o); } out } - fn effects(&mut self, l: &Layer) -> Vec { + fn effects(&mut self, l: &Layer) -> Vec { let Some(fx) = l.effects() else { return vec![] }; let mut out = vec![]; for (i, g) in fx.groups().enumerate() { @@ -268,11 +240,27 @@ impl Doc<'_> { }; (p.name.clone(), export_prop(&mut self.ex, p, &conv, &format!("{label} ▸ {}", p.name))) } - None => (format!("Param {}", pi + 1), json!({"a": 0, "k": konst})), + None => (format!("Param {}", pi + 1), fixed(json!(konst))), }; - params.push(json!({"ty": ty, "nm": nm, "mn": m, "ix": pi + 1, "v": v})); + params.push(Effect { + kind: Some(i64::from(*ty)), + name: Some(nm), + match_name: Some((*m).into()), + index: Some(pi as i64 + 1), + value: Some(v), + ..Default::default() + }); } - out.push(json!({"ty": map.ty, "nm": g.name, "mn": effect, "ix": i + 1, "en": g.enabled as u8, "np": params.len(), "ef": params})); + out.push(Effect { + kind: Some(i64::from(map.ty)), + name: Some(g.name.clone()), + match_name: Some(effect.clone()), + index: Some(i as i64 + 1), + enabled: Some(i64::from(g.enabled)), + count: Some(params.len() as i64), + values: Some(params), + ..Default::default() + }); } out } @@ -294,8 +282,16 @@ impl Doc<'_> { self.ex.warn(format!("{}: `{}` is not a PNG, JPEG, GIF or WebP image (layer exported as a null)", l.name, f.path)); return None; }; - let uri = format!("data:{mime};base64,{}", crate::base64::encode(&bytes)); - self.assets.push(json!({"id": id, "nm": it.name, "w": f.width, "h": f.height, "u": "", "p": uri, "e": 1})); + self.assets.push(Asset { + id: Some(id.clone()), + name: Some(it.name.clone()), + width: Some(f64::from(f.width)), + height: Some(f64::from(f.height)), + dir: Some(String::new()), + path: Some(craft_lottie::base64::to_data_uri(mime, &bytes)), + embedded: Some(1), + ..Default::default() + }); self.done.insert(id.clone()); Some(id) } @@ -309,11 +305,19 @@ impl Doc<'_> { let c = it.as_comp()?; self.done.insert(id.clone()); let layers = self.layers(c); - self.assets.push(json!({"id": id, "nm": it.name, "fr": c.frame_rate.as_f64(), "w": c.width, "h": c.height, "layers": layers})); + self.assets.push(Asset { + id: Some(id.clone()), + name: Some(it.name.clone()), + frame_rate: Some(c.frame_rate.as_f64()), + width: Some(f64::from(c.width)), + height: Some(f64::from(c.height)), + layers: Some(layers), + ..Default::default() + }); Some(id) } - fn layers(&mut self, comp: &Comp) -> Vec { + fn layers(&mut self, comp: &Comp) -> Vec { let mattes: BTreeSet<_> = comp.layers.iter().filter_map(|l| l.track_matte.map(|m| m.layer)).collect(); let mut out = vec![]; for (idx, l) in comp.layers.iter().enumerate() { @@ -322,11 +326,9 @@ impl Doc<'_> { out } - fn layer(&mut self, comp: &Comp, idx: usize, l: &Layer, is_matte: bool) -> Json { + fn layer(&mut self, comp: &Comp, idx: usize, l: &Layer, is_matte: bool) -> LottieLayer { let name = l.name.clone(); - let mut o = Map::new(); - o.insert("ind".into(), json!(idx + 1)); - o.insert("nm".into(), json!(name)); + let mut o = LottieLayer { index: Some(idx as i64 + 1), name: Some(name.clone()), ..Default::default() }; let three = l.is_3d(); if three { self.any_3d = true; @@ -334,34 +336,30 @@ impl Doc<'_> { self.ex.warn(format!("{name}: 3D layer exported with ddd: 1 (most Lottie players render 2D only)")); } } - o.insert("ddd".into(), json!(three as u8)); + o.three_d = Some(i64::from(three)); let mut hidden = !l.switches.video || l.switches.guide; - let mut ty = 3; + o.content = LayerContent::Null; match &l.source { LayerSource::Shape => { - ty = 4; let items = l.props.sub("contents").map(|c| shapes::export_items(&mut self.ex, c, &name)).unwrap_or_default(); - o.insert("shapes".into(), json!(items)); + o.content = LayerContent::Shape(items); } LayerSource::Text => { if self.opts.text_as_shapes { - ty = 4; - let items = text::glyph_shapes(&mut self.ex, l); - o.insert("shapes".into(), json!(items)); + o.content = LayerContent::Shape(text::glyph_shapes(&mut self.ex, l)); } else { - ty = 5; - let t = text::export_text(&mut self.ex, l, &mut self.fonts); - o.insert("t".into(), t); + o.content = LayerContent::Text(Box::new(text::export_text(&mut self.ex, l, &mut self.fonts))); } } LayerSource::Solid { item } => { let sol = self.project.item(*item).and_then(|i| if let ItemKind::Solid(s) = &i.kind { Some(s.clone()) } else { None }); match sol { Some(s) if !l.switches.adjustment => { - ty = 1; - o.insert("sc".into(), json!(hex(s.color))); - o.insert("sw".into(), json!(s.width)); - o.insert("sh".into(), json!(s.height)); + o.content = LayerContent::Solid(SolidLayer { + color: Some(craft_lottie::to_hex(s.color)), + width: Some(f64::from(s.width)), + height: Some(f64::from(s.height)), + }); } _ => { self.ex.warn(format!("{name}: adjustment layers are not part of Lottie (exported as a null)")); @@ -371,15 +369,9 @@ impl Doc<'_> { } LayerSource::Comp { item } => { if let Some(id) = self.precomp_asset(*item) { - ty = 0; let (w, h) = self.project.comp(*item).map(|c| (c.width, c.height)).unwrap_or((comp.width, comp.height)); - o.insert("refId".into(), json!(id)); - o.insert("w".into(), json!(w)); - o.insert("h".into(), json!(h)); - if let Some(tm) = l.props.get("timeRemap") { - let v = export_prop(&mut self.ex, tm, &anim::num, &format!("{name} ▸ Time Remap")); - o.insert("tm".into(), v); - } + let time_remap = l.props.get("timeRemap").map(|tm| export_prop(&mut self.ex, tm, &anim::num, &format!("{name} ▸ Time Remap"))); + o.content = LayerContent::Precomp(PrecompLayer { ref_id: Some(id), width: Some(f64::from(w)), height: Some(f64::from(h)), time_remap }); } } LayerSource::Footage { item } => { @@ -387,8 +379,7 @@ impl Doc<'_> { match kind { Some((FootageKind::Still, true)) => { if let Some(id) = self.image_asset(*item, l) { - ty = 2; - o.insert("refId".into(), json!(id)); + o.content = LayerContent::Image(Some(id)); } else { hidden = true; } @@ -413,20 +404,16 @@ impl Doc<'_> { hidden = true; } } - o.insert("ty".into(), json!(ty)); - if let Some(p) = l.parent.and_then(|p| comp.index_of(p)) { - o.insert("parent".into(), json!(p)); - } - o.insert("sr".into(), json!(l.stretch / 100.0)); + o.parent = l.parent.and_then(|p| comp.index_of(p)).map(|p| p as i64); + o.stretch = Some(l.stretch / 100.0); if l.stretch < 0.0 { self.ex.warn(format!("{name}: reversed time stretch is not supported by most Lottie players")); } - let ks = self.transform(l); - o.insert("ks".into(), ks); - o.insert("ao".into(), json!((l.auto_orient == effectcraft_project::AutoOrient::AlongPath) as u8)); - o.insert("ip".into(), json!(self.frame(l.in_point))); - o.insert("op".into(), json!(self.frame(l.out_point))); - o.insert("st".into(), json!(self.frame(l.start_time))); + o.transform = Some(self.transform(l)); + o.auto_orient = Some(i64::from(l.auto_orient == effectcraft_project::AutoOrient::AlongPath)); + o.in_point = Some(self.frame(l.in_point)); + o.out_point = Some(self.frame(l.out_point)); + o.start_time = Some(self.frame(l.start_time)); let bm = match crate::blend_to_lottie(l.blend_mode) { Some(b) => b, None => { @@ -434,32 +421,32 @@ impl Doc<'_> { 0 } }; - o.insert("bm".into(), json!(bm)); + o.blend_mode = Some(i64::from(bm)); let masks = self.masks(l); if !masks.is_empty() { - o.insert("hasMask".into(), json!(true)); - o.insert("masksProperties".into(), json!(masks)); + o.has_mask = Some(true); + o.masks = Some(masks); } let ef = self.effects(l); if !ef.is_empty() { - o.insert("ef".into(), json!(ef)); + o.effects = Some(ef); } if let Some(tm) = l.track_matte && let Some(mi) = comp.index_of(tm.layer) { - o.insert("tt".into(), json!(matte_code(tm.kind))); - o.insert("tp".into(), json!(mi)); + o.matte_mode = Some(i64::from(matte_code(tm.kind))); + o.matte_parent = Some(mi as i64); if mi != idx { self.ex.warn(format!("{name}: track matte layer is not directly above (players without `tp` support use the layer above)")); } } if is_matte { - o.insert("td".into(), json!(1)); + o.is_matte = Some(1); if l.switches.video { self.ex.warn(format!("{name}: visible track matte layer (Lottie always hides matte layers)")); } } else if hidden { - o.insert("hd".into(), json!(true)); + o.hidden = Some(true); } if !l.markers.is_empty() { self.ex.warn(format!("{name}: layer markers are not part of Lottie (composition markers are exported)")); @@ -471,7 +458,7 @@ impl Doc<'_> { if l.preserve_transparency { self.ex.warn(format!("{name}: Preserve Underlying Transparency is not part of Lottie")); } - Json::Object(o) + o } } @@ -493,24 +480,27 @@ pub fn export_comp(project: &Project, comp: ItemId, opts: &ExportOptions, read: }; doc.done.insert(format!("comp_{}", comp.0)); let layers = doc.layers(c); - let markers: Vec = c.markers.iter().map(|m| json!({"tm": doc.frame(m.time), "cm": m.comment, "dr": doc.frame(m.duration)})).collect(); - let mut out = json!({ - "v": "5.12.0", - "fr": c.frame_rate.as_f64(), - "ip": 0, - "op": doc.frame(c.duration), - "w": c.width, - "h": c.height, - "nm": item.name, - "ddd": doc.any_3d as u8, - "assets": doc.assets, - "layers": layers, - "markers": markers, - }); - if !doc.fonts.is_empty() { - out["fonts"] = json!({"list": doc.fonts}); - } - Ok(ExportResult { json: out, warnings: doc.ex.warnings }) + let markers: Vec = c + .markers + .iter() + .map(|m| Marker { time: Some(doc.frame(m.time)), comment: Some(m.comment.clone()), duration: Some(doc.frame(m.duration)), ..Default::default() }) + .collect(); + let animation = Animation { + version: Some("5.12.0".into()), + frame_rate: Some(c.frame_rate.as_f64()), + in_point: Some(0.0), + out_point: Some(doc.frame(c.duration)), + width: Some(f64::from(c.width)), + height: Some(f64::from(c.height)), + name: Some(item.name.clone()), + three_d: Some(i64::from(doc.any_3d)), + assets: Some(doc.assets), + layers: Some(layers), + markers: Some(markers), + fonts: (!doc.fonts.is_empty()).then(|| Fonts { list: Some(doc.fonts), ..Default::default() }), + ..Default::default() + }; + Ok(ExportResult { json: animation.to_json(), warnings: doc.ex.warnings }) } /// Package an export as a dotLottie archive (`manifest.json` + `animations/.json`). diff --git a/crates/lottie/src/import.rs b/crates/lottie/src/import.rs index 1e1430e12..6534727dc 100644 --- a/crates/lottie/src/import.rs +++ b/crates/lottie/src/import.rs @@ -3,6 +3,8 @@ use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; +use craft_lottie::model::{Asset, Effect, Layer as LottieLayer, LayerContent, Mask, Transform}; +use craft_lottie::{Animated, Animation, Json}; use effectcraft_color::Label; use effectcraft_keyframe::{ShapePath, Value}; use effectcraft_project::build::{self, Ids}; @@ -11,9 +13,8 @@ use effectcraft_project::{ PropGroup, Property, Solid, TrackMatte, }; use effectcraft_time::{FrameRate, Tick}; -use serde_json::Value as Json; -use crate::anim::{self, Im, import_prop}; +use crate::anim::{self, Im, import_animated, import_prop}; use crate::export::{fx_by_id, fx_by_type, fx_params, mask_mode_from}; use crate::{LottieError, Timebase, shapes, text}; @@ -40,24 +41,15 @@ pub struct ImportResult { pub warnings: Vec, } -fn f(j: &Json, k: &str) -> Option { - j.get(k).and_then(Json::as_f64) -} - -fn s<'a>(j: &'a Json, k: &str) -> Option<&'a str> { - j.get(k).and_then(Json::as_str) -} - -fn hex_color(sc: &str) -> [f32; 3] { - let h = sc.trim_start_matches('#'); - let c = |i: usize| { - h.get(i..i + 2).filter(|x| x.bytes().all(|b| b.is_ascii_hexdigit())).and_then(|x| u8::from_str_radix(x, 16).ok()).unwrap_or(0) as f32 / 255.0 +/// The Lottie document inside raw bytes (plain JSON, or a stored dotLottie archive), read into +/// `craft-lottie`'s model within its default limits. +fn document(bytes: &[u8]) -> Result { + let read = |b: &[u8]| { + Animation::read(b).map_err(|e| match e { + craft_lottie::LottieError::Parse(m) => LottieError::Parse(m), + other => LottieError::Invalid(other.to_string()), + }) }; - [c(0), c(2), c(4)] -} - -/// The Lottie JSON inside raw bytes (plain JSON, or a stored dotLottie archive). -fn document(bytes: &[u8]) -> Result { if bytes.starts_with(b"PK") { let entries = crate::zip::read_stored(bytes); let anim = entries @@ -65,9 +57,9 @@ fn document(bytes: &[u8]) -> Result { .find(|(n, _)| n.starts_with("animations/") && n.ends_with(".json")) .or_else(|| entries.iter().find(|(n, _)| n.ends_with(".json") && n != "manifest.json")) .ok_or_else(|| LottieError::Parse("dotLottie archive without an uncompressed animation".into()))?; - return serde_json::from_slice(&anim.1).map_err(|e| LottieError::Parse(e.to_string())); + return read(&anim.1); } - serde_json::from_slice(bytes).map_err(|e| LottieError::Parse(e.to_string())) + read(bytes) } struct Ctx<'a> { @@ -121,30 +113,28 @@ pub fn import( store: &mut dyn FnMut(&ImportedImage) -> Option, ) -> Result { let doc = document(bytes)?; - let (Some(w), Some(h)) = (f(&doc, "w"), f(&doc, "h")) else { return Err(LottieError::Parse("missing `w`/`h`".into())) }; - let fr = f(&doc, "fr").filter(|v| *v > 0.0).unwrap_or(30.0); + let (Some(w), Some(h)) = (doc.width, doc.height) else { return Err(LottieError::Parse("missing `w`/`h`".into())) }; + let fr = doc.frame_rate.filter(|v| *v > 0.0).unwrap_or(30.0); let rate = FrameRate::from_f64(fr); let tb = Timebase { rate }; - let name = s(&doc, "nm").filter(|n| !n.is_empty()).unwrap_or(fallback_name).to_string(); - let ip = f(&doc, "ip").unwrap_or(0.0); - let op = f(&doc, "op").unwrap_or(ip + fr).max(ip + 1.0); + let name = doc.name.as_deref().filter(|n| !n.is_empty()).unwrap_or(fallback_name).to_string(); + let ip = doc.in_point.unwrap_or(0.0); + let op = doc.out_point.unwrap_or(ip + fr).max(ip + 1.0); let mut cx = Ctx { im: Im { tb, warnings: vec![] }, assets: BTreeMap::new(), fonts: vec![], store, base_dir, items: vec![], folder: None, name: name.clone() }; - if let Some(list) = doc.get("fonts").and_then(|f| f.get("list")).and_then(Json::as_array) { - for fo in list { - // Every text key referring to the font copies its family and style: keep them to - // a font name's length. - let short = |v: &str| v.chars().take(MAX_FONT_NAME_CHARS).collect::(); - let n = s(fo, "fName").unwrap_or("").to_string(); - let fam = short(s(fo, "fFamily").unwrap_or(&n)); - let st = short(s(fo, "fStyle").unwrap_or("Regular")); - cx.fonts.push((n, fam, st)); - } + for fo in doc.fonts.as_ref().and_then(|f| f.list.as_deref()).unwrap_or_default() { + // Every text key referring to the font copies its family and style: keep them to + // a font name's length. + let short = |v: &str| v.chars().take(MAX_FONT_NAME_CHARS).collect::(); + let n = fo.name.clone().unwrap_or_default(); + let fam = short(fo.family.as_deref().unwrap_or(&n)); + let st = short(fo.style.as_deref().unwrap_or("Regular")); + cx.fonts.push((n, fam, st)); } // Glyph outlines embedded for players without the fonts. Text is set in installed fonts. - if let Some(chars) = doc.get("chars").and_then(Json::as_array).filter(|c| !c.is_empty()) { + if let Some(chars) = doc.chars.as_deref().filter(|c| !c.is_empty()) { let mut fams: Vec<&str> = vec![]; - for fam in chars.iter().filter_map(|c| s(c, "fFamily")).filter(|f| !f.trim().is_empty()) { + for fam in chars.iter().filter_map(|c| c.family.as_deref()).filter(|f| !f.trim().is_empty()) { if !fams.contains(&fam) { fams.push(fam); } @@ -155,25 +145,27 @@ pub fn import( let (w, h) = (w.round().max(1.0) as u32, h.round().max(1.0) as u32); let duration = tb.tick(op); // Pass 1: asset items (precomps empty for now, images stored). - let assets = doc.get("assets").and_then(Json::as_array).cloned().unwrap_or_default(); - let layer_sizes = precomp_layer_sizes(&doc, &assets); - for a in &assets { - let Some(id) = s(a, "id") else { continue }; - if a.get("layers").is_some() { + let assets: &[Asset] = doc.assets.as_deref().unwrap_or_default(); + let top: &[LottieLayer] = doc.layers.as_deref().unwrap_or_default(); + let layer_sizes = precomp_layer_sizes(top, assets); + for a in assets { + let Some(id) = a.id.as_deref() else { continue }; + let size = a.width.zip(a.height).map(|(x, y)| (x as u32, y as u32)); + if a.layers.is_some() { let folder = cx.folder(project); let layer = layer_sizes.get(id).copied(); - let aw = f(a, "w").map(|v| v as u32).or(layer.map(|l| l.0)).unwrap_or(w); - let ah = f(a, "h").map(|v| v as u32).or(layer.map(|l| l.1)).unwrap_or(h); - let arate = f(a, "fr").map(FrameRate::from_f64).unwrap_or(rate); + let aw = a.width.map(|v| v as u32).or(layer.map(|l| l.0)).unwrap_or(w); + let ah = a.height.map(|v| v as u32).or(layer.map(|l| l.1)).unwrap_or(h); + let arate = a.frame_rate.map(FrameRate::from_f64).unwrap_or(rate); let c = Comp::new(aw, ah, arate, duration); - let nm = s(a, "nm").unwrap_or(id).to_string(); + let nm = a.name.as_deref().unwrap_or(id).to_string(); let item = project.add_item(&nm, Label::Sandstone, Some(folder), ItemKind::Comp(Arc::new(c))); cx.items.push(item); - cx.assets.insert(id.to_string(), (item, f(a, "w").zip(f(a, "h")).map(|(x, y)| (x as u32, y as u32)))); - } else if let Some(p) = s(a, "p") { - let (aw, ah) = (f(a, "w").unwrap_or(0.0) as u32, f(a, "h").unwrap_or(0.0) as u32); - let nm = s(a, "nm").unwrap_or(id).to_string(); - let path = if let Some((mime, data)) = crate::base64::data_uri(p) { + cx.assets.insert(id.to_string(), (item, size)); + } else if let Some(p) = a.path.as_deref() { + let (aw, ah) = (a.width.unwrap_or(0.0) as u32, a.height.unwrap_or(0.0) as u32); + let nm = a.name.as_deref().unwrap_or(id).to_string(); + let path = if let Some((mime, data)) = craft_lottie::base64::data_uri(p) { let ext = match mime.as_str() { "image/jpeg" | "image/jpg" => "jpg", "image/webp" => "webp", @@ -183,7 +175,7 @@ pub fn import( }; (cx.store)(&ImportedImage { id: id.to_string(), name: nm.clone(), bytes: data, ext: ext.into() }) } else { - let u = s(a, "u").unwrap_or(""); + let u = a.dir.as_deref().unwrap_or(""); match external_image(&format!("{u}{p}"), cx.base_dir) { Ok(path) => Some(path), Err(why) => { @@ -225,11 +217,11 @@ pub fn import( } } // Pass 2: precomp contents. - for a in &assets { - let (Some(id), Some(layers)) = (s(a, "id"), a.get("layers").and_then(Json::as_array)) else { continue }; + for a in assets { + let (Some(id), Some(layers)) = (a.id.as_deref(), a.layers.as_deref()) else { continue }; let Some((item, _)) = cx.assets.get(id).copied() else { continue }; let Some(mut c) = project.comp(item).cloned() else { continue }; - let end = layers.iter().filter_map(|l| f(l, "op")).fold(0.0f64, f64::max); + let end = layers.iter().filter_map(|l| l.out_point).fold(0.0f64, f64::max); if end > 0.0 { c.duration = tb.tick(end); c.work_area = (Tick::ZERO, c.duration); @@ -244,18 +236,15 @@ pub fn import( if ip > 0.0 { comp.work_area = (tb.tick(ip), duration); } - if let Some(ms) = doc.get("markers").and_then(Json::as_array) { - for m in ms { - comp.markers.push(Marker { - time: tb.tick(f(m, "tm").unwrap_or(0.0)), - duration: tb.tick(f(m, "dr").unwrap_or(0.0)), - comment: s(m, "cm").unwrap_or("").to_string(), - ..Default::default() - }); - } + for m in doc.markers.as_deref().unwrap_or_default() { + comp.markers.push(Marker { + time: tb.tick(m.time.unwrap_or(0.0)), + duration: tb.tick(m.duration.unwrap_or(0.0)), + comment: m.comment.clone().unwrap_or_default(), + ..Default::default() + }); } - let layers = doc.get("layers").and_then(Json::as_array).cloned().unwrap_or_default(); - build_layers(&mut cx, project, &mut comp, &layers); + build_layers(&mut cx, project, &mut comp, top); let id = project.add_item(&name, Label::Sandstone, None, ItemKind::Comp(Arc::new(comp))); cx.items.push(id); project.fix_next_id(); @@ -265,44 +254,46 @@ pub fn import( /// By asset id, the `w`/`h` of the first precomp layer, in the main comp or in any asset, that /// shows it. lottie-spec gives a precomposition asset no size: the layer's `w`/`h` are its /// clipping rect. One pass over all layers, not one per asset. -fn precomp_layer_sizes<'a>(doc: &'a Json, assets: &'a [Json]) -> HashMap<&'a str, (u32, u32)> { +fn precomp_layer_sizes<'a>(top: &'a [LottieLayer], assets: &'a [Asset]) -> HashMap<&'a str, (u32, u32)> { let mut out = HashMap::new(); - let lists = doc.get("layers").into_iter().chain(assets.iter().filter_map(|a| a.get("layers"))); - for l in lists.filter_map(Json::as_array).flatten() { - if l.get("ty").and_then(Json::as_u64) != Some(0) { - continue; - } - let (Some(id), Some((lw, lh))) = (s(l, "refId"), f(l, "w").zip(f(l, "h"))) else { continue }; + let lists = std::iter::once(top).chain(assets.iter().filter_map(|a| a.layers.as_deref())); + for l in lists.flatten() { + let LayerContent::Precomp(p) = &l.content else { continue }; + let (Some(id), Some((lw, lh))) = (p.ref_id.as_deref(), p.width.zip(p.height)) else { continue }; out.entry(id).or_insert((lw.round().max(1.0) as u32, lh.round().max(1.0) as u32)); } out } -fn transform(im: &Im, ks: &Json, tr: &mut PropGroup, next: &mut u64) { - let set = |tr: &mut PropGroup, m: &str, j: Option<&Json>, conv: &dyn Fn(&Json) -> Option| { - if let (Some(j), Some(p)) = (j, tr.get_mut(m)) { - import_prop(im, j, p, conv); +fn transform(im: &Im, ks: &Transform, tr: &mut PropGroup, next: &mut u64) { + let set = |tr: &mut PropGroup, m: &str, j: Option<&Animated>, conv: &dyn Fn(&Json) -> Option| { + if let Some(p) = tr.get_mut(m) { + import_animated(im, j, p, conv); } }; - set(tr, "anchor", ks.get("a"), &|v| anim::to_vec3(v, 0.0)); - set(tr, "scale", ks.get("s"), &|v| anim::to_vec3(v, 100.0)); - set(tr, "rotation", ks.get("r").or(ks.get("rz")), &anim::to_scalar); - set(tr, "rotationX", ks.get("rx"), &anim::to_scalar); - set(tr, "rotationY", ks.get("ry"), &anim::to_scalar); - set(tr, "orientation", ks.get("or"), &|v| anim::to_vec3(v, 0.0)); - set(tr, "opacity", ks.get("o"), &anim::to_scalar); - let Some(p) = ks.get("p") else { return }; - if p.get("s").and_then(Json::as_bool) == Some(true) { + set(tr, "anchor", ks.anchor.as_ref(), &|v| anim::to_vec3(v, 0.0)); + set(tr, "scale", ks.scale.as_ref(), &|v| anim::to_vec3(v, 100.0)); + set(tr, "rotation", ks.rotation.as_ref().or(ks.rotation_z.as_ref()), &anim::to_scalar); + set(tr, "rotationX", ks.rotation_x.as_ref(), &anim::to_scalar); + set(tr, "rotationY", ks.rotation_y.as_ref(), &anim::to_scalar); + set(tr, "orientation", ks.orientation.as_ref(), &|v| anim::to_vec3(v, 0.0)); + set(tr, "opacity", ks.opacity.as_ref(), &anim::to_scalar); + let Some(p) = &ks.position else { return }; + if let Some(dims) = p.split() { // Separated dimensions: X/Y/Z Position after Position. let at = tr.children.iter().position(|c| c.match_id() == "position").map(|i| i + 1).unwrap_or(tr.children.len()); let base = tr.get("position").map(|p| p.value.as_vec3()).unwrap_or([0.0; 3]); - for (d, (key, m, name)) in - [("x", "positionX", "X Position"), ("y", "positionY", "Y Position"), ("z", "positionZ", "Z Position")].iter().enumerate().rev() + for (d, (j, m, name)) in dims + .iter() + .zip([("positionX", "X Position"), ("positionY", "Y Position"), ("positionZ", "Z Position")]) + .map(|(j, (m, n))| (j, m, n)) + .enumerate() + .rev() { let mut pr = Property::new(*next, m, name, Value::Scalar(base[d])).with_ui(ParamUi::Number); *next += 1; pr.three_d_only = d == 2; - if let Some(j) = p.get(*key) { + if let Some(j) = j { import_prop(im, j, &mut pr, &anim::to_scalar); } tr.children.insert(at, Node::Prop(pr)); @@ -312,50 +303,50 @@ fn transform(im: &Im, ks: &Json, tr: &mut PropGroup, next: &mut u64) { } } -fn masks(im: &Im, ids: &mut Ids, list: &[Json], g: &mut PropGroup) { +fn masks(im: &Im, ids: &mut Ids, list: &[Mask], g: &mut PropGroup) { for (i, m) in list.iter().enumerate() { - let mode = mask_mode_from(s(m, "mode").unwrap_or("a")); - let name = s(m, "nm").map(str::to_string).unwrap_or(format!("Mask {}", i + 1)); + let mode = mask_mode_from(m.mode.as_deref().unwrap_or("a")); + let name = m.name.clone().unwrap_or(format!("Mask {}", i + 1)); let color = build::MASK_COLORS[i % build::MASK_COLORS.len()]; let mut mg = build::mask(ids, &name, ShapePath::default(), mode, color); if let GroupKind::Mask { inverted, .. } = &mut mg.kind { - *inverted = m.get("inv").and_then(Json::as_bool).unwrap_or(false); + *inverted = m.inverted.unwrap_or(false); } - let mut set = |k: &str, mid: &str, conv: &dyn Fn(&Json) -> Option| { - if let (Some(j), Some(p)) = (m.get(k), mg.get_mut(mid)) { + let mut set = |j: Option<&Json>, mid: &str, conv: &dyn Fn(&Json) -> Option| { + if let (Some(j), Some(p)) = (j, mg.get_mut(mid)) { import_prop(im, j, p, conv); } }; - let closed = m.get("cl").and_then(Json::as_bool).unwrap_or(false); - set("pt", "path", &|v| shapes::to_path(v, closed)); - set("o", "opacity", &anim::to_scalar); - set("x", "expansion", &anim::to_scalar); - set("f", "feather", &anim::to_vec2); + let closed = m.closed.unwrap_or(false); + set(m.path.as_ref().map(|a| &a.0), "path", &|v| shapes::to_path(v, closed)); + set(m.opacity.as_ref().map(|a| &a.0), "opacity", &anim::to_scalar); + set(m.expansion.as_ref().map(|a| &a.0), "expansion", &anim::to_scalar); + set(m.extra.get("f"), "feather", &anim::to_vec2); g.children.push(Node::Group(mg)); } } -fn effects(im: &mut Im, ids: &mut Ids, list: &[Json], g: &mut PropGroup, size: [f64; 2]) { +fn effects(im: &mut Im, ids: &mut Ids, list: &[Effect], g: &mut PropGroup, size: [f64; 2]) { for e in list { - let ty = e.get("ty").and_then(Json::as_u64).unwrap_or(0); - let params = e.get("ef").and_then(Json::as_array).cloned().unwrap_or_default(); - let inner_ty = params.first().and_then(|p| p.get("ty")).and_then(Json::as_u64); - let map = s(e, "mn").and_then(fx_by_id).or_else(|| fx_by_type(ty, inner_ty)); - let nm = s(e, "nm").unwrap_or("Effect"); + let ty = e.kind.and_then(|t| u64::try_from(t).ok()).unwrap_or(0); + let params: &[Effect] = e.values.as_deref().unwrap_or_default(); + let inner_ty = params.first().and_then(|p| p.kind).and_then(|t| u64::try_from(t).ok()); + let map = e.match_name.as_deref().and_then(fx_by_id).or_else(|| fx_by_type(ty, inner_ty)); + let nm = e.name.as_deref().unwrap_or("Effect"); let Some(map) = map else { im.warn(format!("effect `{nm}` (type {ty}) is not supported (skipped)")); continue; }; let Some(spec) = effectcraft_effects::find(map.id) else { continue }; let mut fg = effectcraft_effects::instantiate(spec, ids, nm, size); - if e.get("en").and_then(Json::as_u64) == Some(0) { + if e.enabled == Some(0) { fg.enabled = false; } for (i, (m, pty, scale, _)) in fx_params(map).iter().enumerate() { if m.is_empty() { continue; } - let Some(pj) = params.get(i).and_then(|p| p.get("v")) else { continue }; + let Some(pj) = params.get(i).and_then(|p| p.value.as_ref()) else { continue }; let Some(p) = fg.get_mut(m) else { continue }; let (pty, scale) = (*pty, *scale); let conv = move |v: &Json| -> Option { @@ -367,79 +358,84 @@ fn effects(im: &mut Im, ids: &mut Ids, list: &[Json], g: &mut PropGroup, size: [ _ => anim::to_scalar(v).map(|x| Value::Scalar(x.as_f64() / scale)), } }; - import_prop(im, pj, p, &conv); + import_prop(im, &pj.0, p, &conv); } g.children.push(Node::Group(fg)); } } -fn layer_source(cx: &mut Ctx, project: &mut Project, comp: &Comp, j: &Json) -> Option<(LayerSource, (u32, u32))> { - let ty = j.get("ty").and_then(Json::as_u64).unwrap_or(99); +fn layer_source(cx: &mut Ctx, project: &mut Project, comp: &Comp, j: &LottieLayer) -> Option<(LayerSource, (u32, u32))> { let full = (comp.width, comp.height); - let asset = |cx: &Ctx| s(j, "refId").and_then(|r| cx.assets.get(r).copied()); - Some(match ty { - 0 => { - let Some((item, _)) = asset(cx) else { - cx.im.warn(format!("{}: missing precomp asset", s(j, "nm").unwrap_or("layer"))); + let nm = j.name.as_deref(); + let asset = |cx: &Ctx, r: Option<&str>| r.and_then(|r| cx.assets.get(r).copied()); + Some(match &j.content { + LayerContent::Precomp(p) => { + let Some((item, _)) = asset(cx, p.ref_id.as_deref()) else { + cx.im.warn(format!("{}: missing precomp asset", nm.unwrap_or("layer"))); return None; }; let size = project.comp(item).map(|c| (c.width, c.height)).unwrap_or(full); (LayerSource::Comp { item }, size) } - 1 => { - let sw = f(j, "sw").unwrap_or(comp.width as f64).round().max(1.0) as u32; - let sh = f(j, "sh").unwrap_or(comp.height as f64).round().max(1.0) as u32; - let color = hex_color(s(j, "sc").unwrap_or("#000000")); - let name = s(j, "nm").unwrap_or("Solid"); + LayerContent::Solid(sl) => { + let sw = sl.width.unwrap_or(comp.width as f64).round().max(1.0) as u32; + let sh = sl.height.unwrap_or(comp.height as f64).round().max(1.0) as u32; + let color = craft_lottie::hex_color(sl.color.as_deref().unwrap_or("#000000")); + let name = nm.unwrap_or("Solid"); let folder = cx.folder(project); let item = project.add_item(name, Label::Red, Some(folder), ItemKind::Solid(Solid { color, width: sw, height: sh, pixel_aspect: 1.0 })); cx.items.push(item); (LayerSource::Solid { item }, (sw, sh)) } - 2 => { - let Some((item, size)) = asset(cx) else { - cx.im.warn(format!("{}: missing image asset", s(j, "nm").unwrap_or("layer"))); + LayerContent::Image(r) => { + let Some((item, size)) = asset(cx, r.as_deref()) else { + cx.im.warn(format!("{}: missing image asset", nm.unwrap_or("layer"))); return None; }; (LayerSource::Footage { item }, size.unwrap_or(full)) } - 3 => (LayerSource::Null, (100, 100)), - 4 => (LayerSource::Shape, full), - 5 => (LayerSource::Text, full), - 13 => { - cx.im.warn(format!("{}: camera layers are not imported", s(j, "nm").unwrap_or("camera"))); - return None; - } - other => { - cx.im.warn(format!("{}: layer type {other} is not supported (skipped)", s(j, "nm").unwrap_or("layer"))); - return None; - } + LayerContent::Null => (LayerSource::Null, (100, 100)), + LayerContent::Shape(_) => (LayerSource::Shape, full), + LayerContent::Text(_) => (LayerSource::Text, full), + LayerContent::Other(ty) => match ty.as_u64().unwrap_or(99) { + // A shape or text layer whose content is missing or unreadable is an empty one. + 4 => (LayerSource::Shape, full), + 5 => (LayerSource::Text, full), + 13 => { + cx.im.warn(format!("{}: camera layers are not imported", nm.unwrap_or("camera"))); + return None; + } + other => { + cx.im.warn(format!("{}: layer type {other} is not supported (skipped)", nm.unwrap_or("layer"))); + return None; + } + }, }) } /// Build the layers of a comp (Lottie order: first = top = layer #1). -fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[Json]) { +fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[LottieLayer]) { let tb = cx.im.tb; let mut by_ind: BTreeMap = BTreeMap::new(); // (layer id, its index in `comp.layers`, parent ind, matte: (kind, explicit tp ind), json position) let mut pending: Vec<(LayerId, usize, Option, Option<(MatteKind, Option)>, usize)> = vec![]; let mut pos_ind: Vec> = vec![]; for (ji, j) in layers.iter().enumerate() { - let ind = j.get("ind").and_then(Json::as_i64); + let ind = j.index; pos_ind.push(ind); let Some((source, size)) = layer_source(cx, project, comp, j) else { continue }; - let name = s(j, "nm").unwrap_or(source.type_name()).to_string(); + let name = j.name.clone().unwrap_or_else(|| source.type_name().to_string()); let mut l: Layer = build::layer(project, comp, &name, source.clone(), size, None); if let Some(i) = ind { by_ind.insert(i, l.id); } - let ip = f(j, "ip").unwrap_or(0.0); - let op = f(j, "op").unwrap_or(tb.frame(comp.duration)); + let ip = j.in_point.unwrap_or(0.0); + let op = j.out_point.unwrap_or(tb.frame(comp.duration)); l.in_point = tb.tick(ip); l.out_point = tb.tick(op.max(ip)); - l.start_time = tb.tick(f(j, "st").unwrap_or(0.0)); + l.start_time = tb.tick(j.start_time.unwrap_or(0.0)); // Below 1 % (or 0) the layer time divides by ~0, and layer.timeStretch refuses it too. - let sr = f(j, "sr").unwrap_or(1.0); + let sr = j.stretch.unwrap_or(1.0); l.stretch = if sr.is_finite() && sr.abs() >= 0.01 { // Past ±9900 % too (#3247): the largest stretch a layer supports, sign kept. let pct = effectcraft_project::limits::stretch(sr * 100.0); @@ -451,73 +447,70 @@ fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[ cx.im.warn(format!("{name}: a time stretch of {} % is not supported (100 % used)", sr * 100.0)); 100.0 }; - if j.get("ddd").and_then(Json::as_u64) == Some(1) { + if j.three_d == Some(1) { l.switches.three_d = true; } - if let Some(bm) = j.get("bm").and_then(Json::as_u64) { + if let Some(bm) = j.blend_mode.and_then(|b| u64::try_from(b).ok()) { l.blend_mode = crate::blend_from_lottie(bm); } - if j.get("ao").and_then(Json::as_u64) == Some(1) { + if j.auto_orient == Some(1) { l.auto_orient = AutoOrient::AlongPath; } - if j.get("hd").and_then(Json::as_bool) == Some(true) { + if j.hidden == Some(true) { l.switches.video = false; } - if j.get("td").and_then(Json::as_u64) == Some(1) { + if j.is_matte == Some(1) { l.switches.video = false; } let mut next = project.next_id; - if let (Some(ks), Some(tr)) = (j.get("ks"), l.props.sub_mut("transform")) { + if let (Some(ks), Some(tr)) = (&j.transform, l.props.sub_mut("transform")) { transform(&cx.im, ks, tr, &mut next); } let mut ids = Ids(&mut next); - match &source { - LayerSource::Shape => { - let mut items = j.get("shapes").and_then(Json::as_array).into_iter().flatten(); - let groups = shapes::import_items(&mut cx.im, &mut ids, &mut items); + match (&source, &j.content) { + (LayerSource::Shape, LayerContent::Shape(items)) => { + let groups = shapes::import_items(&mut cx.im, &mut ids, &mut items.iter()); if let Some(c) = l.props.sub_mut("contents") { c.children.extend(groups.into_iter().map(Node::Group)); } } - LayerSource::Text => { - if let (Some(t), Some(tg)) = (j.get("t"), l.props.sub_mut("text")) { + (LayerSource::Text, LayerContent::Text(t)) => { + if let Some(tg) = l.props.sub_mut("text") { text::import_text(&mut cx.im, &mut ids, t, tg, &cx.fonts); } } - LayerSource::Comp { .. } => { - if let Some(tm) = j.get("tm") { + (LayerSource::Comp { .. }, LayerContent::Precomp(p)) => { + if let Some(tm) = &p.time_remap { let mut pr = ids.prop("timeRemap", "Time Remap", Value::Scalar(0.0)).with_ui(ParamUi::Number); - import_prop(&cx.im, tm, &mut pr, &anim::to_scalar); + import_prop(&cx.im, &tm.0, &mut pr, &anim::to_scalar); l.props.children.insert(0, Node::Prop(pr)); } } _ => {} } - if let Some(list) = j.get("masksProperties").and_then(Json::as_array) + if let Some(list) = &j.masks && let Some(g) = l.props.sub_mut("masks") { masks(&cx.im, &mut ids, list, g); } - if let Some(list) = j.get("ef").and_then(Json::as_array) + if let Some(list) = &j.effects && let Some(g) = l.props.sub_mut("effects") { effects(&mut cx.im, &mut ids, list, g, [size.0 as f64, size.1 as f64]); } - if j.get("sy").and_then(Json::as_array).is_some_and(|a| !a.is_empty()) { + if j.extra.get("sy").and_then(Json::as_array).is_some_and(|a| !a.is_empty()) { cx.im.warn(format!("{name}: layer styles are not imported")); } project.next_id = next; - let parent = j.get("parent").and_then(Json::as_i64); - let tt = j.get("tt").and_then(Json::as_u64).unwrap_or(0); - let matte = match tt { + let matte = match j.matte_mode.unwrap_or(0) { 1 => Some(MatteKind::Alpha), 2 => Some(MatteKind::AlphaInverted), 3 => Some(MatteKind::Luma), 4 => Some(MatteKind::LumaInverted), _ => None, } - .map(|k| (k, j.get("tp").and_then(Json::as_i64))); - pending.push((l.id, comp.layers.len(), parent, matte, ji)); + .map(|k| (k, j.matte_parent)); + pending.push((l.id, comp.layers.len(), j.parent, matte, ji)); comp.layers.push(l); } for (id, at, parent, matte, ji) in pending { @@ -536,15 +529,3 @@ fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[ } } } - -#[cfg(test)] -mod hex_color_tests { - use super::hex_color; - - #[test] - fn hex_color_rejects_plus_sign() { - assert_eq!(hex_color("#+f0000"), [0.0, 0.0, 0.0]); - assert_eq!(hex_color("#zz0000"), [0.0, 0.0, 0.0]); - assert_eq!(hex_color("#ff0000"), [1.0, 0.0, 0.0]); - } -} diff --git a/crates/lottie/src/lib.rs b/crates/lottie/src/lib.rs index 1b12cc8be..0a1f4bc96 100644 --- a/crates/lottie/src/lib.rs +++ b/crates/lottie/src/lib.rs @@ -1,7 +1,7 @@ //! Lottie JSON import and export. //! -//! Implemented from the public Lottie format description (the lottie-spec 1.0 schema and the -//! LottieFiles format documentation); no player or exporter source was used. +//! The format itself (the document model, property and keyframe encoding, paths, gradients, +//! embedded images) is `craft-lottie`; this crate maps it onto EffectCraft's project. //! //! **Export** ([`export_comp`]) turns a composition into a Lottie document: nested compositions //! become precomp assets, still footage becomes embedded base64 image assets, and shape, solid, @@ -21,7 +21,6 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod anim; -mod base64; mod export; mod import; mod shapes; diff --git a/crates/lottie/src/shapes.rs b/crates/lottie/src/shapes.rs index 6cd1f09cc..f28e73a04 100644 --- a/crates/lottie/src/shapes.rs +++ b/crates/lottie/src/shapes.rs @@ -1,23 +1,27 @@ //! Shape layer contents ↔ Lottie shape items (`gr`, `rc`, `el`, `sr`, `sh`, `fl`, `st`, `gf`, -//! `gs`, `tm`, `rp`, `rd`, `op`, `pb`, `tw`, `zz`, `mm`, `tr`). +//! `gs`, `tm`, `rp`, `rd`, `op`, `pb`, `tw`, `zz`, `mm`, `tr`), on `craft-lottie`'s model. +use craft_lottie::model::{ + Dash, Ellipse, Fill, GradientColors, GradientFill, GradientStroke, Group, Map, Merge, OffsetPath, Path, PolyStar, PuckerBloat, Rect, Repeater, + RepeaterTransform, RoundCorners, Shape, ShapeKind, Stroke, Transform, Trim, Twist, ZigZag, +}; +use craft_lottie::{Animated, Bezier, Json}; use effectcraft_color::BlendMode; use effectcraft_keyframe::{Gradient, ShapePath, Value}; use effectcraft_project::build::{self, EXTRA_DASHES, Ids}; use effectcraft_project::{Node, ParamUi, PropGroup}; -use serde_json::{Map, Value as Json, json}; +use serde_json::json; use crate::anim::{self, Ex, Im, export_prop, import_prop}; // ---------------------------------------------------------------- shared value converters -pub(crate) fn shape_json(p: &ShapePath) -> Json { - let pts = |v: &[[f64; 2]]| v.iter().map(|q| json!([r(q[0]), r(q[1])])).collect::>(); - json!({"c": p.closed, "v": pts(&p.vertices), "i": pts(&p.in_tangents), "o": pts(&p.out_tangents)}) +pub(crate) fn bezier(p: &ShapePath) -> Bezier { + Bezier { closed: p.closed, vertices: p.vertices.clone(), in_tangents: p.in_tangents.clone(), out_tangents: p.out_tangents.clone() } } -fn r(v: f64) -> f64 { - (v * 1e6).round() / 1e6 +pub(crate) fn shape_json(p: &ShapePath) -> Json { + bezier(p).to_json() } pub(crate) fn path_value(v: &Value) -> Json { @@ -30,29 +34,8 @@ pub(crate) fn path_value(v: &Value) -> Json { /// A Lottie path. `closed` is used when the path has no `c`: Bodymovin 3.x and early 4.x keep the /// flag outside the path, as `cl` on a mask and `closed` on an `sh` item. pub(crate) fn to_path(j: &Json, closed: bool) -> Option { - let o = match j { - Json::Array(a) => a.first()?, - o => o, - }; - let pts = |k: &str| -> Vec<[f64; 2]> { - o.get(k) - .and_then(Json::as_array) - .map(|a| a.iter().map(|p| anim::nums(p).map(|v| [*v.first().unwrap_or(&0.0), *v.get(1).unwrap_or(&0.0)]).unwrap_or([0.0; 2])).collect()) - .unwrap_or_default() - }; - let vertices = pts("v"); - let n = vertices.len(); - let fit = |mut v: Vec<[f64; 2]>| { - v.resize(n, [0.0; 2]); - v - }; - Some(Value::Path(ShapePath { - in_tangents: fit(pts("i")), - out_tangents: fit(pts("o")), - vertices, - closed: o.get("c").and_then(Json::as_bool).unwrap_or(closed), - feather: Vec::new(), - })) + let b = Bezier::from_json(j, closed)?; + Some(Value::Path(ShapePath { vertices: b.vertices, in_tangents: b.in_tangents, out_tangents: b.out_tangents, closed: b.closed, feather: Vec::new() })) } /// Gradient as Lottie's flat stop list: `[pos, r, g, b]…` then `[pos, alpha]…`. @@ -61,29 +44,19 @@ pub(crate) fn gradient_flat(v: &Value) -> Json { Value::Gradient(g) => g.clone(), _ => Gradient::default(), }; - let mut out = vec![]; - for (p, c) in &g.colors { - out.extend([r(*p), r(c[0] as f64), r(c[1] as f64), r(c[2] as f64)]); + craft_lottie::Gradient { + colors: g.colors.iter().map(|(p, c)| (*p, [f64::from(c[0]), f64::from(c[1]), f64::from(c[2])])).collect(), + opacities: g.opacities.iter().map(|(p, a)| (*p, f64::from(*a))).collect(), } - let plain = g.opacities.iter().all(|(_, a)| (*a - 1.0).abs() < 1e-6); - if !plain { - for (p, a) in &g.opacities { - out.extend([r(*p), r(*a as f64)]); - } - } - json!(out) + .to_flat() } pub(crate) fn to_gradient(j: &Json, ncolors: usize) -> Option { - let v = anim::nums(j)?; - let n = ncolors.min(v.len() / 4); - let colors: Vec<(f64, [f32; 4])> = (0..n).map(|i| (v[i * 4], [v[i * 4 + 1] as f32, v[i * 4 + 2] as f32, v[i * 4 + 3] as f32, 1.0])).collect(); - let rest = &v[n * 4..]; - let mut opacities: Vec<(f64, f32)> = rest.chunks(2).filter(|c| c.len() == 2).map(|c| (c[0], c[1] as f32)).collect(); - if opacities.is_empty() { - opacities = vec![(0.0, 1.0), (1.0, 1.0)]; - } - Some(Value::Gradient(Gradient { colors, opacities })) + let g = craft_lottie::Gradient::from_flat(j, ncolors)?; + Some(Value::Gradient(Gradient { + colors: g.colors.iter().map(|(p, [r, gr, b])| (*p, [*r as f32, *gr as f32, *b as f32, 1.0])).collect(), + opacities: g.opacities.iter().map(|(p, a)| (*p, *a as f32)).collect(), + })) } fn blend_index(m: BlendMode) -> u32 { @@ -92,22 +65,18 @@ fn blend_index(m: BlendMode) -> u32 { // ---------------------------------------------------------------- export +/// A group's properties, exported with the warnings they need. struct Out<'a, 'b> { ex: &'a mut Ex, g: &'b PropGroup, - o: Map, label: String, } impl Out<'_, '_> { - fn put(&mut self, key: &str, m: &str, conv: &dyn Fn(&Value) -> Json) { - if let Some(p) = self.g.get(m) { - let v = export_prop(self.ex, p, conv, &format!("{} ▸ {}", self.label, p.name)); - self.o.insert(key.into(), v); - } - } - fn raw(&mut self, key: &str, v: Json) { - self.o.insert(key.into(), v); + /// The property `m` of the group, when it has one. + fn put(&mut self, m: &str, conv: &dyn Fn(&Value) -> Json) -> Option { + let p = self.g.get(m)?; + Some(export_prop(self.ex, p, conv, &format!("{} ▸ {}", self.label, p.name))) } fn e(&self, m: &str) -> u32 { self.g.get(m).map(|p| p.value.as_enum()).unwrap_or(0) @@ -121,34 +90,46 @@ impl Out<'_, '_> { fn animated(&self, m: &str) -> bool { self.g.get(m).is_some_and(|p| p.is_animated() || p.has_expression()) } - fn blend(&mut self) { + fn blend(&mut self) -> i64 { let i = self.e("blend"); let m = BlendMode::ALL.get(i as usize).copied().unwrap_or_default(); match crate::blend_to_lottie(m) { - Some(bm) => self.raw("bm", json!(bm)), + Some(bm) => i64::from(bm), None => { self.ex.warn(format!("{}: blend mode {m:?} has no Lottie equivalent (Normal used)", self.label)); - self.raw("bm", json!(0)); + 0 } } } - fn done(self) -> Json { - Json::Object(self.o) + fn direction(&self) -> i64 { + if self.e("direction") == 1 { 3 } else { 1 } } } -/// Stroke fields shared by `st` and `gs`. -fn stroke_fields(o: &mut Out) { - o.put("w", "width", &anim::num); - o.raw("lc", json!(o.e("cap") + 1)); - o.raw("lj", json!(o.e("join") + 1)); - o.raw("ml", json!(o.f("miter"))); +/// A static property (`{a: 0, k}`). +pub(crate) fn fixed(k: Json) -> Animated { + Animated(json!({"a": 0, "k": k})) +} + +/// Stroke fields shared by `st` and `gs`: width, cap, join, miter limit, dashes. +struct StrokeOut { + width: Option, + cap: i64, + join: i64, + miter: f64, + dashes: Option>, +} + +fn stroke_fields(o: &mut Out) -> StrokeOut { + let width = o.put("width", &anim::num); + let (cap, join, miter) = (i64::from(o.e("cap")) + 1, i64::from(o.e("join")) + 1, o.f("miter")); let used = |g: Option<&PropGroup>, m: &str| g.and_then(|g| g.get(m)).is_some_and(|p| p.is_animated() || p.value.as_f64().abs() > 1e-9); let (taper, wave) = (o.g.sub("taper"), o.g.sub("wave")); if used(taper, "startLength") || used(taper, "endLength") || used(wave, "amount") { let msg = format!("{}: stroke Taper and Wave have no Lottie equivalent (uniform width exported)", o.label); o.ex.warn(msg); } + let mut dashes = None; if let Some(d) = o.g.sub("dashes") { let dash = d.get("dash").map(|p| p.value.as_f64()).unwrap_or(0.0); if dash > 0.0 || d.any_animated() { @@ -156,202 +137,257 @@ fn stroke_fields(o: &mut Out) { for (n, m) in [("d", "dash"), ("g", "gap"), ("d", "dash2"), ("g", "gap2"), ("d", "dash3"), ("g", "gap3"), ("o", "offset")] { if let Some(p) = d.get(m) { let v = export_prop(o.ex, p, &anim::num, &format!("{} ▸ Dashes ▸ {}", o.label, p.name)); - list.push(json!({"n": n, "nm": p.name, "v": v})); + list.push(Dash { kind: Some(n.into()), name: Some(p.name.clone()), length: Some(v), ..Default::default() }); } } - o.raw("d", json!(list)); + dashes = Some(list); } } + StrokeOut { width, cap, join, miter, dashes } } -fn shape_transform(ex: &mut Ex, tr: &PropGroup, label: &str) -> Json { - let mut o = Out { ex, g: tr, o: Map::new(), label: format!("{label} ▸ Transform") }; - o.raw("ty", json!("tr")); - o.put("a", "anchor", &anim::arr2); - o.put("p", "position", &anim::arr2); - o.put("s", "scale", &anim::arr2); - o.put("r", "rotation", &anim::num); - o.put("o", "opacity", &anim::num); - o.put("sk", "skew", &anim::num); - o.put("sa", "skewAxis", &anim::num); - o.put("so", "startOpacity", &anim::num); - o.put("eo", "endOpacity", &anim::num); - o.done() +/// The `tr` of a group or a repeater: anchor, position, scale, rotation, opacity, skew, and the +/// repeater's start and end opacity, by their Lottie keys. +fn shape_transform(ex: &mut Ex, tr: &PropGroup, label: &str) -> Vec<(&'static str, Animated)> { + let mut o = Out { ex, g: tr, label: format!("{label} ▸ Transform") }; + let mut out = vec![]; + for (k, m, conv) in [ + ("a", "anchor", anim::arr2 as fn(&Value) -> Json), + ("p", "position", anim::arr2), + ("s", "scale", anim::arr2), + ("r", "rotation", anim::num), + ("o", "opacity", anim::num), + ("sk", "skew", anim::num), + ("sa", "skewAxis", anim::num), + ("so", "startOpacity", anim::num), + ("eo", "endOpacity", anim::num), + ] { + if let Some(v) = o.put(m, &conv) { + out.push((k, v)); + } + } + out +} + +/// The `tr` item that ends a group's items. +fn group_transform(keys: Vec<(&'static str, Animated)>) -> Shape { + let (mut t, mut extra) = (Transform::default(), Map::new()); + for (k, v) in keys { + match k { + "a" => t.anchor = Some(v), + "p" => t.position = Some(v), + "s" => t.scale = Some(v), + "r" => t.rotation = Some(v), + "o" => t.opacity = Some(v), + "sk" => t.skew = Some(v), + "sa" => t.skew_axis = Some(v), + _ => { + extra.insert(k.into(), v.0); + } + } + } + Shape { kind: ShapeKind::Transform(Box::new(t)), extra, ..Default::default() } +} + +/// A repeater's `tr`, which players read with `ty: "tr"` like a group's. +fn repeater_transform(keys: Vec<(&'static str, Animated)>) -> RepeaterTransform { + let mut t = RepeaterTransform::default(); + t.extra.insert("ty".into(), json!("tr")); + for (k, v) in keys { + match k { + "a" => t.anchor = Some(v), + "p" => t.position = Some(v), + "s" => t.scale = Some(v), + "r" => t.rotation = Some(v), + "so" => t.start_opacity = Some(v), + "eo" => t.end_opacity = Some(v), + "sk" => t.skew = Some(v), + "sa" => t.skew_axis = Some(v), + _ => { + t.extra.insert(k.into(), v.0); + } + } + } + t } /// Export a contents group's items (first item = top, as in the timeline). -pub(crate) fn export_items(ex: &mut Ex, contents: &PropGroup, label: &str) -> Vec { +pub(crate) fn export_items(ex: &mut Ex, contents: &PropGroup, label: &str) -> Vec { let mut out = vec![]; for node in &contents.children { let Node::Group(g) = node else { continue }; let lbl = format!("{label} ▸ {}", g.name); - let ty = match g.match_id.as_str() { - "group" => "gr", - "rect" => "rc", - "ellipse" => "el", - "star" => "sr", - "path" => "sh", - "fill" => "fl", - "stroke" => "st", - "gfill" => "gf", - "gstroke" => "gs", - "trim" => "tm", - "repeater" => "rp", - "round" => "rd", - "offset" => "op", - "pucker" => "pb", - "twist" => "tw", - "zigzag" => "zz", - "merge" => "mm", - other => { - ex.warn(format!("{lbl}: shape item `{other}` has no Lottie equivalent (skipped)")); - continue; + let mut o = Out { ex, g, label: lbl.clone() }; + let mut blend = None; + let kind = match g.match_id.as_str() { + "group" => { + let mut items = g.sub("contents").map(|c| export_items(o.ex, c, &lbl)).unwrap_or_default(); + items.push(match g.sub("transform") { + Some(t) => group_transform(shape_transform(o.ex, t, &lbl)), + None => group_transform(vec![ + ("a", fixed(json!([0, 0]))), + ("p", fixed(json!([0, 0]))), + ("s", fixed(json!([100, 100]))), + ("r", fixed(json!(0))), + ("o", fixed(json!(100))), + ]), + }); + blend = Some(o.blend()); + ShapeKind::Group(Group { count: Some(items.len() as f64), items: Some(items) }) } - }; - let mut o = Out { ex, g, o: Map::new(), label: lbl.clone() }; - o.raw("ty", json!(ty)); - o.raw("nm", json!(g.name)); - if !g.enabled { - o.raw("hd", json!(true)); - } - let dir = |o: &mut Out| { - let d = if o.e("direction") == 1 { 3 } else { 1 }; - o.raw("d", json!(d)); - }; - match ty { - "gr" => { - let items = g.sub("contents").map(|c| export_items(o.ex, c, &lbl)).unwrap_or_default(); - let mut items = items; - let tr = match g.sub("transform") { - Some(t) => shape_transform(o.ex, t, &lbl), - None => { - json!({"ty": "tr", "a": {"a": 0, "k": [0, 0]}, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]}, "r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}}) - } - }; - items.push(tr); - o.raw("np", json!(items.len())); - o.raw("it", json!(items)); - o.blend(); - } - "rc" => { - dir(&mut o); - o.put("s", "size", &anim::arr2); - o.put("p", "position", &anim::arr2); - if o.flag("perCorner") { + "rect" => { + let direction = Some(o.direction()); + let size = o.put("size", &anim::arr2); + let position = o.put("position", &anim::arr2); + let roundness = if o.flag("perCorner") { let names = ["topLeftRoundness", "topRightRoundness", "bottomRightRoundness", "bottomLeftRoundness"]; let radii = names.map(|m| o.f(m)); // Lottie `rc` has one `r`: four equal static radii export as that value. // `r` is a property (`{a, k}`) like the uniform branch writes, not a bare number. if radii.iter().all(|v| (v - radii[0]).abs() < 1e-6) && !names.iter().any(|m| o.animated(m)) && radii[0] >= 0.0 { - o.raw("r", json!({"a": 0, "k": r(radii[0])})); + Some(fixed(json!(craft_lottie::round6(radii[0])))) } else { o.ex.warn(format!("{}: per-corner roundness has no Lottie rectangle equivalent (roundness 0 exported)", o.label)); - o.raw("r", json!({"a": 0, "k": 0})); + Some(fixed(json!(0))) } } else { - o.put("r", "roundness", &anim::num); - } + o.put("roundness", &anim::num) + }; + ShapeKind::Rect(Rect { direction, position, size, roundness }) } - "el" => { - dir(&mut o); - o.put("s", "size", &anim::arr2); - o.put("p", "position", &anim::arr2); + "ellipse" => { + let direction = Some(o.direction()); + let size = o.put("size", &anim::arr2); + ShapeKind::Ellipse(Ellipse { direction, position: o.put("position", &anim::arr2), size }) } - "sr" => { - dir(&mut o); - o.raw("sy", json!(o.e("type") + 1)); - o.put("pt", "points", &anim::num); - o.put("p", "position", &anim::arr2); - o.put("r", "rotation", &anim::num); - o.put("ir", "innerRadius", &anim::num); - o.put("or", "outerRadius", &anim::num); - o.put("is", "innerRoundness", &anim::num); - o.put("os", "outerRoundness", &anim::num); + "star" => ShapeKind::PolyStar(PolyStar { + direction: Some(o.direction()), + star_type: Some(i64::from(o.e("type")) + 1), + points: o.put("points", &anim::num), + position: o.put("position", &anim::arr2), + rotation: o.put("rotation", &anim::num), + inner_radius: o.put("innerRadius", &anim::num), + outer_radius: o.put("outerRadius", &anim::num), + inner_roundness: o.put("innerRoundness", &anim::num), + outer_roundness: o.put("outerRoundness", &anim::num), + }), + "path" => ShapeKind::Path(Path { direction: Some(o.direction()), path: o.put("path", &path_value), closed: None }), + "fill" => { + let f = Fill { color: o.put("color", &anim::arr), opacity: o.put("opacity", &anim::num), rule: Some(i64::from(o.e("rule")) + 1) }; + blend = Some(o.blend()); + ShapeKind::Fill(f) } - "sh" => { - dir(&mut o); - o.put("ks", "path", &path_value); + "stroke" => { + let (color, opacity) = (o.put("color", &anim::arr), o.put("opacity", &anim::num)); + let st = stroke_fields(&mut o); + blend = Some(o.blend()); + ShapeKind::Stroke(Stroke { + color, + opacity, + width: st.width, + cap: Some(st.cap), + join: Some(st.join), + miter_limit: Some(st.miter), + miter_limit_animated: None, + dashes: st.dashes, + }) } - "fl" => { - o.put("c", "color", &anim::arr); - o.put("o", "opacity", &anim::num); - o.raw("r", json!(o.e("rule") + 1)); - o.blend(); - } - "st" => { - o.put("c", "color", &anim::arr); - o.put("o", "opacity", &anim::num); - stroke_fields(&mut o); - o.blend(); - } - "gf" | "gs" => { - o.put("o", "opacity", &anim::num); - o.put("s", "start", &anim::arr2); - o.put("e", "end", &anim::arr2); - o.raw("t", json!(o.e("type") + 1)); - o.put("h", "highlightLength", &anim::num); - o.put("a", "highlightAngle", &anim::num); + m @ ("gfill" | "gstroke") => { + let opacity = o.put("opacity", &anim::num); + let (start, end) = (o.put("start", &anim::arr2), o.put("end", &anim::arr2)); + let gradient_type = Some(i64::from(o.e("type")) + 1); + let (highlight_length, highlight_angle) = (o.put("highlightLength", &anim::num), o.put("highlightAngle", &anim::num)); let ncolors = match g.get("colors").map(|p| &p.value) { Some(Value::Gradient(gr)) => gr.colors.len(), _ => 2, }; - if let Some(p) = g.get("colors") { - let k = export_prop(o.ex, p, &gradient_flat, &format!("{lbl} ▸ Colors")); - o.raw("g", json!({"p": ncolors, "k": k})); - } - if ty == "gf" { - o.raw("r", json!(o.e("rule") + 1)); + let colors = g.get("colors").map(|p| GradientColors { + count: Some(ncolors as i64), + stops: Some(export_prop(o.ex, p, &gradient_flat, &format!("{lbl} ▸ Colors"))), + ..Default::default() + }); + let kind = if m == "gfill" { + ShapeKind::GradientFill(GradientFill { + colors, + start, + end, + gradient_type, + highlight_length, + highlight_angle, + opacity, + rule: Some(i64::from(o.e("rule")) + 1), + }) } else { - stroke_fields(&mut o); - } - o.blend(); + let st = stroke_fields(&mut o); + ShapeKind::GradientStroke(GradientStroke { + colors, + start, + end, + gradient_type, + highlight_length, + highlight_angle, + opacity, + width: st.width, + cap: Some(st.cap), + join: Some(st.join), + miter_limit: Some(st.miter), + miter_limit_animated: None, + dashes: st.dashes, + }) + }; + blend = Some(o.blend()); + kind } - "tm" => { - o.put("s", "start", &anim::num); - o.put("e", "end", &anim::num); - o.put("o", "offset", &anim::num); - o.raw("m", json!(o.e("mode") + 1)); - } - "rp" => { - o.put("c", "copies", &anim::num); - o.put("o", "offset", &anim::num); + "trim" => ShapeKind::Trim(Trim { + start: o.put("start", &anim::num), + end: o.put("end", &anim::num), + offset: o.put("offset", &anim::num), + multiple: Some(i64::from(o.e("mode")) + 1), + }), + "repeater" => { + let (copies, offset) = (o.put("copies", &anim::num), o.put("offset", &anim::num)); // Lottie: 1 = Above, 2 = Below; EffectCraft: 0 = Below, 1 = Above. - o.raw("m", json!(if o.e("composite") == 1 { 1 } else { 2 })); - if let Some(t) = g.sub("transform") { - let tr = shape_transform(o.ex, t, &lbl); - o.raw("tr", tr); - } + let composite = Some(if o.e("composite") == 1 { 1 } else { 2 }); + let transform = g.sub("transform").map(|t| repeater_transform(shape_transform(o.ex, t, &lbl))); + ShapeKind::Repeater(Repeater { copies, offset, composite, transform }) } - "rd" => o.put("r", "radius", &anim::num), - "op" => { - o.put("a", "amount", &anim::num); - o.raw("lj", json!(o.e("join") + 1)); - o.put("ml", "miter", &anim::num); + "round" => ShapeKind::RoundCorners(RoundCorners { radius: o.put("radius", &anim::num) }), + "offset" => { + let amount = o.put("amount", &anim::num); + let join = Some(i64::from(o.e("join")) + 1); + let miter_limit = o.put("miter", &anim::num); if (o.f("copies") - 1.0).abs() > 1e-9 || o.animated("copies") || o.f("copyOffset") != 0.0 { o.ex.warn(format!("{lbl}: Offset Paths copies are not part of Lottie (one copy exported)")); } + ShapeKind::OffsetPath(OffsetPath { amount, join, miter_limit }) } - "pb" => o.put("a", "amount", &anim::num), - "tw" => { - o.put("a", "angle", &anim::num); - o.put("c", "center", &anim::arr2); + "pucker" => ShapeKind::PuckerBloat(PuckerBloat { amount: o.put("amount", &anim::num) }), + "twist" => ShapeKind::Twist(Twist { angle: o.put("angle", &anim::num), center: o.put("center", &anim::arr2) }), + "zigzag" => ShapeKind::ZigZag(ZigZag { + frequency: o.put("size", &anim::num), + amount: o.put("ridges", &anim::num), + point_type: Some(fixed(json!(o.e("points") + 1))), + }), + "merge" => ShapeKind::Merge(Merge { mode: Some(i64::from(o.e("mode")) + 1) }), + other => { + o.ex.warn(format!("{lbl}: shape item `{other}` has no Lottie equivalent (skipped)")); + continue; } - "zz" => { - o.put("s", "size", &anim::num); - o.put("r", "ridges", &anim::num); - o.raw("pt", json!({"a": 0, "k": o.e("points") + 1})); - } - "mm" => o.raw("mm", json!(o.e("mode") + 1)), - _ => {} - } - out.push(o.done()); + }; + out.push(Shape { name: Some(g.name.clone()), hidden: (!g.enabled).then_some(true), blend_mode: blend, kind, ..Default::default() }); } out } // ---------------------------------------------------------------- import -fn set(im: &Im, g: &mut PropGroup, m: &str, j: Option<&Json>, conv: &dyn Fn(&Json) -> Option) { +fn set(im: &Im, g: &mut PropGroup, m: &str, j: Option<&Animated>, conv: &dyn Fn(&Json) -> Option) { + if let (Some(j), Some(p)) = (j, g.get_mut(m)) { + import_prop(im, &j.0, p, conv); + } +} + +fn set_json(im: &Im, g: &mut PropGroup, m: &str, j: Option<&Json>, conv: &dyn Fn(&Json) -> Option) { if let (Some(j), Some(p)) = (j, g.get_mut(m)) { import_prop(im, j, p, conv); } @@ -363,43 +399,60 @@ fn set_enum(g: &mut PropGroup, m: &str, v: u32) { } } -fn int(j: &Json, k: &str) -> Option { - let v = j.get(k)?; +/// A whole number however a file writes it: `2`, `2.0`, `2.4` (rounded) or a property `{k: 2}`. +fn int_json(v: Option<&Json>) -> Option { + let v = v?; v.as_i64().or_else(|| v.as_f64().map(|f| f.round() as i64)).or_else(|| v.get("k").and_then(anim::nums).and_then(|n| n.first().map(|f| f.round() as i64))) } -fn import_blend(j: &Json, g: &mut PropGroup) { - if let Some(bm) = j.get("bm").and_then(Json::as_u64) { +/// An integer key of the model, or the value the model kept in `extra` when it was written +/// another way. +fn int(field: Option, extra: &Map, key: &str) -> Option { + field.or_else(|| int_json(extra.get(key))) +} + +fn import_blend(s: &Shape, g: &mut PropGroup) { + if let Some(bm) = int(s.blend_mode, &s.extra, "bm").and_then(|b| u64::try_from(b).ok()) { set_enum(g, "blend", blend_index(crate::blend_from_lottie(bm))); } } -fn import_stroke(im: &Im, ids: &mut Ids, j: &Json, g: &mut PropGroup) { - set(im, g, "width", j.get("w"), &anim::to_scalar); - if let Some(lc) = int(j, "lc") { +/// The stroke keys of `st` and `gs`. +struct StrokeIn<'a> { + width: Option<&'a Animated>, + cap: Option, + join: Option, + miter: Option, + miter_animated: Option<&'a Animated>, + dashes: Option<&'a [Dash]>, +} + +fn import_stroke(im: &Im, ids: &mut Ids, st: StrokeIn<'_>, g: &mut PropGroup) { + set(im, g, "width", st.width, &anim::to_scalar); + if let Some(lc) = st.cap { set_enum(g, "cap", lc.saturating_sub(1).clamp(0, 2) as u32); } - if let Some(lj) = int(j, "lj") { + if let Some(lj) = st.join { set_enum(g, "join", lj.saturating_sub(1).clamp(0, 2) as u32); } if let Some(p) = g.get_mut("miter") { - if let Some(ml) = j.get("ml").and_then(Json::as_f64) { + if let Some(ml) = st.miter { p.value = Value::Scalar(ml); - } else if let Some(ml2) = j.get("ml2") { - import_prop(im, ml2, p, &anim::to_scalar); + } else if let Some(ml2) = st.miter_animated { + import_prop(im, &ml2.0, p, &anim::to_scalar); } } - if let Some(list) = j.get("d").and_then(Json::as_array) + if let Some(list) = st.dashes && let Some(d) = g.sub_mut("dashes") { // The n-th `d` and `g` are the n-th Dash/Gap pair; the extra pairs are created as the Dashes "+" does. let (mut dashes, mut gaps) = (0, 0); for e in list { - let (n, pair) = match e.get("n").and_then(Json::as_str) { + let (n, pair) = match e.kind.as_deref() { Some("d") => (&mut dashes, 0), Some("g") => (&mut gaps, 1), Some("o") => { - set(im, d, "offset", e.get("v"), &anim::to_scalar); + set(im, d, "offset", e.length.as_ref(), &anim::to_scalar); continue; } _ => continue, @@ -418,206 +471,299 @@ fn import_stroke(im: &Im, ids: &mut Ids, j: &Json, g: &mut PropGroup) { [dm, gm][pair] } }; - set(im, d, m, e.get("v"), &anim::to_scalar); + set(im, d, m, e.length.as_ref(), &anim::to_scalar); } } } -fn import_shape_transform(im: &Im, j: &Json, tr: &mut PropGroup) { - set(im, tr, "anchor", j.get("a"), &anim::to_vec2); - set(im, tr, "position", j.get("p"), &anim::to_vec2); - set(im, tr, "scale", j.get("s"), &anim::to_vec2); - set(im, tr, "rotation", j.get("r"), &anim::to_scalar); - set(im, tr, "opacity", j.get("o"), &anim::to_scalar); - set(im, tr, "skew", j.get("sk"), &anim::to_scalar); - set(im, tr, "skewAxis", j.get("sa"), &anim::to_scalar); - set(im, tr, "startOpacity", j.get("so"), &anim::to_scalar); - set(im, tr, "endOpacity", j.get("eo"), &anim::to_scalar); +/// A `tr` (of a group or a repeater), looked up by its Lottie keys. +fn import_shape_transform(im: &Im, get: &dyn Fn(&str) -> Option, tr: &mut PropGroup) { + for (k, m, conv) in [ + ("a", "anchor", anim::to_vec2 as fn(&Json) -> Option), + ("p", "position", anim::to_vec2), + ("s", "scale", anim::to_vec2), + ("r", "rotation", anim::to_scalar), + ("o", "opacity", anim::to_scalar), + ("sk", "skew", anim::to_scalar), + ("sa", "skewAxis", anim::to_scalar), + ("so", "startOpacity", anim::to_scalar), + ("eo", "endOpacity", anim::to_scalar), + ] { + set_json(im, tr, m, get(k).as_ref(), &conv); + } +} + +/// A named key of the model, or the same key kept in `extra`. +fn key(a: Option<&Animated>, extra: &Map, k: &str) -> Option { + a.map(|a| a.0.clone()).or_else(|| extra.get(k).cloned()) +} + +fn group_tr_get<'a>(t: &'a Transform, item: &'a Map) -> impl Fn(&str) -> Option + 'a { + move |k| { + let named = match k { + "a" => t.anchor.as_ref(), + "p" => t.position.as_ref(), + "s" => t.scale.as_ref(), + "r" => t.rotation.as_ref(), + "o" => t.opacity.as_ref(), + "sk" => t.skew.as_ref(), + "sa" => t.skew_axis.as_ref(), + _ => None, + }; + key(named, &t.extra, k).or_else(|| item.get(k).cloned()) + } +} + +fn repeater_tr_get(t: &RepeaterTransform) -> impl Fn(&str) -> Option + '_ { + move |k| { + let named = match k { + "a" => t.anchor.as_ref(), + "p" => t.position.as_ref(), + "s" => t.scale.as_ref(), + "r" => t.rotation.as_ref(), + "so" => t.start_opacity.as_ref(), + "eo" => t.end_opacity.as_ref(), + "sk" => t.skew.as_ref(), + "sa" => t.skew_axis.as_ref(), + _ => None, + }; + key(named, &t.extra, k) + } } /// Import Lottie shape items into shape contents groups. -pub(crate) fn import_items(im: &mut Im, ids: &mut Ids, items: &mut dyn Iterator) -> Vec { +pub(crate) fn import_items(im: &mut Im, ids: &mut Ids, items: &mut dyn Iterator) -> Vec { let mut out = vec![]; - for j in items { - let ty = j.get("ty").and_then(Json::as_str).unwrap_or(""); - let dir = |g: &mut PropGroup| { - if int(j, "d") == Some(3) { + for s in items { + let x = &s.extra; + let dir = |g: &mut PropGroup, d: Option| { + if int(d, x, "d") == Some(3) { set_enum(g, "direction", 1); } }; - let mut g = match ty { - "gr" => { + let mut g = match &s.kind { + ShapeKind::Group(gr) => { + let list = gr.items.as_deref().unwrap_or_default(); // Borrowed, not cloned: each nesting level copying its subtree costs memory // quadratic in the depth. - let list = j.get("it").and_then(Json::as_array).map(Vec::as_slice).unwrap_or_default(); - let children = import_items(im, ids, &mut list.iter().filter(|i| i.get("ty").and_then(Json::as_str) != Some("tr"))); + let children = import_items(im, ids, &mut list.iter().filter(|i| !matches!(i.kind, ShapeKind::Transform(_)))); let mut g = build::shape_group(ids, "Group 1", children); - if let Some(tr) = list.iter().find(|i| i.get("ty").and_then(Json::as_str) == Some("tr")) - && let Some(t) = g.sub_mut("transform") + if let Some(tr) = list.iter().find(|i| matches!(i.kind, ShapeKind::Transform(_))) + && let ShapeKind::Transform(t) = &tr.kind + && let Some(tg) = g.sub_mut("transform") { - import_shape_transform(im, tr, t); + import_shape_transform(im, &group_tr_get(t, &tr.extra), tg); } - import_blend(j, &mut g); + import_blend(s, &mut g); g } - "rc" => { + ShapeKind::Rect(r) => { let mut g = build::shape_rect(ids, [100.0, 100.0], [0.0, 0.0], 0.0); - dir(&mut g); - set(im, &mut g, "size", j.get("s"), &anim::to_vec2); - set(im, &mut g, "position", j.get("p"), &anim::to_vec2); - set(im, &mut g, "roundness", j.get("r"), &anim::to_scalar); + dir(&mut g, r.direction); + set(im, &mut g, "size", r.size.as_ref(), &anim::to_vec2); + set(im, &mut g, "position", r.position.as_ref(), &anim::to_vec2); + set(im, &mut g, "roundness", r.roundness.as_ref(), &anim::to_scalar); // Lottie has one roundness: keep the per-corner values in step so ticking the box // on an imported rectangle keeps the shape. for m in ["topLeftRoundness", "topRightRoundness", "bottomRightRoundness", "bottomLeftRoundness"] { - set(im, &mut g, m, j.get("r"), &anim::to_scalar); + set(im, &mut g, m, r.roundness.as_ref(), &anim::to_scalar); } g } - "el" => { + ShapeKind::Ellipse(e) => { let mut g = build::shape_ellipse(ids, [100.0, 100.0], [0.0, 0.0]); - dir(&mut g); - set(im, &mut g, "size", j.get("s"), &anim::to_vec2); - set(im, &mut g, "position", j.get("p"), &anim::to_vec2); + dir(&mut g, e.direction); + set(im, &mut g, "size", e.size.as_ref(), &anim::to_vec2); + set(im, &mut g, "position", e.position.as_ref(), &anim::to_vec2); g } - "sr" => { - let star = int(j, "sy").unwrap_or(1) != 2; + ShapeKind::PolyStar(p) => { + let star = int(p.star_type, x, "sy").unwrap_or(1) != 2; let mut g = build::shape_star(ids, star, 5.0, [0.0, 0.0], 100.0, 50.0); - dir(&mut g); - set(im, &mut g, "points", j.get("pt"), &anim::to_scalar); - set(im, &mut g, "position", j.get("p"), &anim::to_vec2); - set(im, &mut g, "rotation", j.get("r"), &anim::to_scalar); - set(im, &mut g, "innerRadius", j.get("ir"), &anim::to_scalar); - set(im, &mut g, "outerRadius", j.get("or"), &anim::to_scalar); - set(im, &mut g, "innerRoundness", j.get("is"), &anim::to_scalar); - set(im, &mut g, "outerRoundness", j.get("os"), &anim::to_scalar); + dir(&mut g, p.direction); + set(im, &mut g, "points", p.points.as_ref(), &anim::to_scalar); + set(im, &mut g, "position", p.position.as_ref(), &anim::to_vec2); + set(im, &mut g, "rotation", p.rotation.as_ref(), &anim::to_scalar); + set(im, &mut g, "innerRadius", p.inner_radius.as_ref(), &anim::to_scalar); + set(im, &mut g, "outerRadius", p.outer_radius.as_ref(), &anim::to_scalar); + set(im, &mut g, "innerRoundness", p.inner_roundness.as_ref(), &anim::to_scalar); + set(im, &mut g, "outerRoundness", p.outer_roundness.as_ref(), &anim::to_scalar); g } - "sh" => { + ShapeKind::Path(p) => { let mut g = build::shape_path(ids, ShapePath::default()); - dir(&mut g); - let closed = j.get("closed").and_then(Json::as_bool).unwrap_or(false); - set(im, &mut g, "path", j.get("ks"), &|v| to_path(v, closed)); + dir(&mut g, p.direction); + let closed = p.closed.unwrap_or(false); + set(im, &mut g, "path", p.path.as_ref(), &|v| to_path(v, closed)); g } - "fl" => { + ShapeKind::Fill(f) => { let mut g = build::shape_fill(ids, [1.0, 1.0, 1.0, 1.0]); - set(im, &mut g, "color", j.get("c"), &anim::to_color); - set(im, &mut g, "opacity", j.get("o"), &anim::to_scalar); - if int(j, "r") == Some(2) { + set(im, &mut g, "color", f.color.as_ref(), &anim::to_color); + set(im, &mut g, "opacity", f.opacity.as_ref(), &anim::to_scalar); + if int(f.rule, x, "r") == Some(2) { set_enum(&mut g, "rule", 1); } - import_blend(j, &mut g); + import_blend(s, &mut g); g } - "st" => { + ShapeKind::Stroke(st) => { let mut g = build::shape_stroke(ids, [1.0, 1.0, 1.0, 1.0], 2.0); - set(im, &mut g, "color", j.get("c"), &anim::to_color); - set(im, &mut g, "opacity", j.get("o"), &anim::to_scalar); - import_stroke(im, ids, j, &mut g); - import_blend(j, &mut g); - g - } - "gf" | "gs" => { - let radial = int(j, "t") == Some(2); - let mut g = if ty == "gf" { - build::shape_gradient_fill(ids, radial, [0.0, 0.0], [100.0, 0.0], Gradient::default()) - } else { - build::shape_gradient_stroke(ids, radial, [0.0, 0.0], [100.0, 0.0], Gradient::default(), 2.0) + set(im, &mut g, "color", st.color.as_ref(), &anim::to_color); + set(im, &mut g, "opacity", st.opacity.as_ref(), &anim::to_scalar); + let fields = StrokeIn { + width: st.width.as_ref(), + cap: int(st.cap, x, "lc"), + join: int(st.join, x, "lj"), + miter: st.miter_limit, + miter_animated: st.miter_limit_animated.as_ref(), + dashes: st.dashes.as_deref(), }; - set(im, &mut g, "opacity", j.get("o"), &anim::to_scalar); - set(im, &mut g, "start", j.get("s"), &anim::to_vec2); - set(im, &mut g, "end", j.get("e"), &anim::to_vec2); - set(im, &mut g, "highlightLength", j.get("h"), &anim::to_scalar); - set(im, &mut g, "highlightAngle", j.get("a"), &anim::to_scalar); - if let Some(gj) = j.get("g") { - let n = gj.get("p").and_then(Json::as_u64).unwrap_or(2) as usize; - if let Some(k) = gj.get("k") { - set(im, &mut g, "colors", Some(k), &move |v| to_gradient(v, n)); - } - } - if ty == "gf" { - if int(j, "r") == Some(2) { - set_enum(&mut g, "rule", 1); - } - } else { - import_stroke(im, ids, j, &mut g); - } - import_blend(j, &mut g); + import_stroke(im, ids, fields, &mut g); + import_blend(s, &mut g); g } - "tm" => { + ShapeKind::GradientFill(gf) => { + let radial = int(gf.gradient_type, x, "t") == Some(2); + let mut g = build::shape_gradient_fill(ids, radial, [0.0, 0.0], [100.0, 0.0], Gradient::default()); + gradient_common( + im, + &mut g, + gf.opacity.as_ref(), + gf.start.as_ref(), + gf.end.as_ref(), + gf.highlight_length.as_ref(), + gf.highlight_angle.as_ref(), + gf.colors.as_ref(), + ); + if int(gf.rule, x, "r") == Some(2) { + set_enum(&mut g, "rule", 1); + } + import_blend(s, &mut g); + g + } + ShapeKind::GradientStroke(gs) => { + let radial = int(gs.gradient_type, x, "t") == Some(2); + let mut g = build::shape_gradient_stroke(ids, radial, [0.0, 0.0], [100.0, 0.0], Gradient::default(), 2.0); + gradient_common( + im, + &mut g, + gs.opacity.as_ref(), + gs.start.as_ref(), + gs.end.as_ref(), + gs.highlight_length.as_ref(), + gs.highlight_angle.as_ref(), + gs.colors.as_ref(), + ); + let fields = StrokeIn { + width: gs.width.as_ref(), + cap: int(gs.cap, x, "lc"), + join: int(gs.join, x, "lj"), + miter: gs.miter_limit, + miter_animated: gs.miter_limit_animated.as_ref(), + dashes: gs.dashes.as_deref(), + }; + import_stroke(im, ids, fields, &mut g); + import_blend(s, &mut g); + g + } + ShapeKind::Trim(t) => { let mut g = build::shape_trim(ids, 0.0, 100.0, 0.0); - set(im, &mut g, "start", j.get("s"), &anim::to_scalar); - set(im, &mut g, "end", j.get("e"), &anim::to_scalar); - set(im, &mut g, "offset", j.get("o"), &anim::to_scalar); - if int(j, "m") == Some(2) { + set(im, &mut g, "start", t.start.as_ref(), &anim::to_scalar); + set(im, &mut g, "end", t.end.as_ref(), &anim::to_scalar); + set(im, &mut g, "offset", t.offset.as_ref(), &anim::to_scalar); + if int(t.multiple, x, "m") == Some(2) { set_enum(&mut g, "mode", 1); } g } - "rp" => { + ShapeKind::Repeater(r) => { let mut g = build::shape_repeater(ids, 3.0, [100.0, 0.0]); - set(im, &mut g, "copies", j.get("c"), &anim::to_scalar); - set(im, &mut g, "offset", j.get("o"), &anim::to_scalar); - set_enum(&mut g, "composite", if int(j, "m") == Some(1) { 1 } else { 0 }); - if let (Some(tr), Some(t)) = (j.get("tr"), g.sub_mut("transform")) { - import_shape_transform(im, tr, t); + set(im, &mut g, "copies", r.copies.as_ref(), &anim::to_scalar); + set(im, &mut g, "offset", r.offset.as_ref(), &anim::to_scalar); + set_enum(&mut g, "composite", if int(r.composite, x, "m") == Some(1) { 1 } else { 0 }); + if let (Some(tr), Some(t)) = (r.transform.as_ref(), g.sub_mut("transform")) { + import_shape_transform(im, &repeater_tr_get(tr), t); } g } - "rd" | "op" | "pb" | "tw" | "zz" | "mm" => { - let kind = match ty { - "rd" => "round", - "op" => "offset", - "pb" => "pucker", - "tw" => "twist", - "zz" => "zigzag", - _ => "merge", - }; - let Some(mut g) = build::shape_simple_op(ids, kind) else { continue }; - match ty { - "rd" => set(im, &mut g, "radius", j.get("r"), &anim::to_scalar), - "op" => { - set(im, &mut g, "amount", j.get("a"), &anim::to_scalar); - if let Some(lj) = int(j, "lj") { - set_enum(&mut g, "join", lj.saturating_sub(1).clamp(0, 2) as u32); - } - set(im, &mut g, "miter", j.get("ml"), &anim::to_scalar); - } - "pb" => set(im, &mut g, "amount", j.get("a"), &anim::to_scalar), - "tw" => { - set(im, &mut g, "angle", j.get("a"), &anim::to_scalar); - set(im, &mut g, "center", j.get("c"), &anim::to_vec2); - } - "zz" => { - set(im, &mut g, "size", j.get("s"), &anim::to_scalar); - set(im, &mut g, "ridges", j.get("r"), &anim::to_scalar); - if int(j, "pt") == Some(2) { - set_enum(&mut g, "points", 1); - } - } - _ => { - if let Some(m) = int(j, "mm") { - set_enum(&mut g, "mode", m.saturating_sub(1).clamp(0, 4) as u32); - } - } + ShapeKind::RoundCorners(r) => { + let Some(mut g) = build::shape_simple_op(ids, "round") else { continue }; + set(im, &mut g, "radius", r.radius.as_ref(), &anim::to_scalar); + g + } + ShapeKind::OffsetPath(op) => { + let Some(mut g) = build::shape_simple_op(ids, "offset") else { continue }; + set(im, &mut g, "amount", op.amount.as_ref(), &anim::to_scalar); + if let Some(lj) = int(op.join, x, "lj") { + set_enum(&mut g, "join", lj.saturating_sub(1).clamp(0, 2) as u32); + } + set(im, &mut g, "miter", op.miter_limit.as_ref(), &anim::to_scalar); + g + } + ShapeKind::PuckerBloat(pb) => { + let Some(mut g) = build::shape_simple_op(ids, "pucker") else { continue }; + set(im, &mut g, "amount", pb.amount.as_ref(), &anim::to_scalar); + g + } + ShapeKind::Twist(tw) => { + let Some(mut g) = build::shape_simple_op(ids, "twist") else { continue }; + set(im, &mut g, "angle", tw.angle.as_ref(), &anim::to_scalar); + set(im, &mut g, "center", tw.center.as_ref(), &anim::to_vec2); + g + } + ShapeKind::ZigZag(zz) => { + let Some(mut g) = build::shape_simple_op(ids, "zigzag") else { continue }; + set(im, &mut g, "size", zz.frequency.as_ref(), &anim::to_scalar); + set(im, &mut g, "ridges", zz.amount.as_ref(), &anim::to_scalar); + if int_json(zz.point_type.as_ref().map(|a| &a.0)) == Some(2) { + set_enum(&mut g, "points", 1); } g } - "tr" => continue, - other => { - im.warn(format!("shape item `{other}` is not supported (skipped)")); + ShapeKind::Merge(mm) => { + let Some(mut g) = build::shape_simple_op(ids, "merge") else { continue }; + if let Some(m) = int(mm.mode, x, "mm") { + set_enum(&mut g, "mode", m.saturating_sub(1).clamp(0, 4) as u32); + } + g + } + ShapeKind::Transform(_) => continue, + ShapeKind::Other(ty) => { + im.warn(format!("shape item `{}` is not supported (skipped)", ty.as_str().unwrap_or(""))); continue; } }; - if let Some(nm) = j.get("nm").and_then(Json::as_str) { - g.name = nm.to_string(); + if let Some(nm) = &s.name { + g.name = nm.clone(); } - if j.get("hd").and_then(Json::as_bool) == Some(true) { + if s.hidden == Some(true) { g.enabled = false; } out.push(g); } out } + +/// The keys `gf` and `gs` share. +#[allow(clippy::too_many_arguments)] +fn gradient_common( + im: &Im, + g: &mut PropGroup, + opacity: Option<&Animated>, + start: Option<&Animated>, + end: Option<&Animated>, + highlight_length: Option<&Animated>, + highlight_angle: Option<&Animated>, + colors: Option<&GradientColors>, +) { + set(im, g, "opacity", opacity, &anim::to_scalar); + set(im, g, "start", start, &anim::to_vec2); + set(im, g, "end", end, &anim::to_vec2); + set(im, g, "highlightLength", highlight_length, &anim::to_scalar); + set(im, g, "highlightAngle", highlight_angle, &anim::to_scalar); + if let Some(c) = colors { + let n = c.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(2); + set(im, g, "colors", c.stops.as_ref(), &move |v| to_gradient(v, n)); + } +} diff --git a/crates/lottie/src/tests.rs b/crates/lottie/src/tests.rs index 8656852de..35c52026d 100644 --- a/crates/lottie/src/tests.rs +++ b/crates/lottie/src/tests.rs @@ -381,7 +381,7 @@ fn offset_paths_miter_uses_animatable_lottie_value() { assert_eq!(shapes[0]["ml"]["k"][1]["s"], json!([9.0])); assert_eq!(shapes[1]["ml"], json!({"a": 0, "k": 6.0})); assert_eq!(shapes[2]["ty"], "st"); - assert_eq!(shapes[2]["ml"], json!(7.0)); + assert_eq!(shapes[2]["ml"].as_f64(), Some(7.0)); assert!(compare_comps(&p, cid, &q, nc) > 10); let restored = &q.comp(nc).unwrap().layers[0]; assert_eq!(restored.props.group("contents/offset").unwrap().get("miter").unwrap().keys.len(), 2); diff --git a/crates/lottie/src/text.rs b/crates/lottie/src/text.rs index 4e50b461d..39199cfb3 100644 --- a/crates/lottie/src/text.rs +++ b/crates/lottie/src/text.rs @@ -1,14 +1,18 @@ //! Text layers ↔ Lottie text data (`t`: document keys `d`, animators `a`, more options `m`), //! and text converted to glyph shapes. +use craft_lottie::model::{ + Font, Map, Path, Shape, ShapeKind, TextAlign, TextData, TextDocKey, TextDocs, TextDocument, TextFollowPath, TextRange, TextSelector, TextStyle, +}; +use craft_lottie::{Animated, Json}; use effectcraft_keyframe::{Justify, TextDoc, Value}; use effectcraft_project::build::{self, Ids}; use effectcraft_project::{Layer, Node, PropGroup}; use effectcraft_time::Tick; -use serde_json::{Map, Value as Json, json}; +use serde_json::json; use crate::anim::{self, Ex, Im, export_prop, import_prop}; -use crate::shapes; +use crate::shapes::{self, fixed}; const JUSTIFY: [Justify; 7] = [Justify::Left, Justify::Right, Justify::Center, Justify::JustifyLastLeft, Justify::JustifyLastRight, Justify::JustifyLastCenter, Justify::JustifyAll]; @@ -18,47 +22,49 @@ pub(crate) fn font_name(family: &str, style: &str) -> String { format!("{}-{}", family.replace(' ', ""), style.replace(' ', "")) } -fn rgb(c: [f32; 4]) -> Json { - json!([c[0] as f64, c[1] as f64, c[2] as f64]) +fn rgb(c: [f32; 4]) -> Vec { + vec![f64::from(c[0]), f64::from(c[1]), f64::from(c[2])] } -fn doc_json(d: &TextDoc) -> Json { - let mut o = json!({ - "t": d.text.replace("\r\n", "\r").replace('\n', "\r"), - "f": font_name(&d.font, &d.style), - "s": d.size, - "j": JUSTIFY.iter().position(|j| *j == d.justify).unwrap_or(0), - "tr": d.tracking, - "lh": d.leading.unwrap_or(d.size * 1.2), - "ls": d.baseline_shift, - "of": d.stroke_over_fill, - }); - if d.apply_fill { - o["fc"] = rgb(d.fill); +fn doc_json(d: &TextDoc) -> TextDocument { + let stroke = d.apply_stroke && d.stroke_width > 0.0; + TextDocument { + text: Some(d.text.replace("\r\n", "\r").replace('\n', "\r")), + font: Some(font_name(&d.font, &d.style)), + size: Some(d.size), + justify: Some(JUSTIFY.iter().position(|j| *j == d.justify).unwrap_or(0) as i64), + tracking: Some(d.tracking), + line_height: Some(d.leading.unwrap_or(d.size * 1.2)), + baseline_shift: Some(d.baseline_shift), + stroke_over_fill: Some(d.stroke_over_fill), + fill: d.apply_fill.then(|| rgb(d.fill)), + stroke: stroke.then(|| rgb(d.stroke)), + stroke_width: stroke.then_some(d.stroke_width), + caps: if d.all_caps { + Some(1) + } else if d.small_caps { + Some(2) + } else { + None + }, + box_size: d.box_size.map(|b| b.to_vec()), + box_position: d.box_size.map(|_| d.box_pos.to_vec()), + ..Default::default() } - if d.apply_stroke && d.stroke_width > 0.0 { - o["sc"] = rgb(d.stroke); - o["sw"] = json!(d.stroke_width); - } - if d.all_caps { - o["ca"] = json!(1); - } else if d.small_caps { - o["ca"] = json!(2); - } - if let Some(b) = d.box_size { - o["sz"] = json!(b); - o["ps"] = json!(d.box_pos); - } - o } -fn doc_from(j: &Json, fonts: &[(String, String, String)]) -> TextDoc { +/// A colour of a text document (`fc`, `sc`), 0..=1 or 0..=255. +fn doc_color(c: Option<&Vec>, extra: &Map, key: &str) -> Option<[f32; 4]> { + let j = c.filter(|c| !c.is_empty()).map(|c| json!(c)).or_else(|| extra.get(key).cloned())?; + anim::to_color(&j).map(|v| v.as_color()) +} + +fn doc_from(j: &TextDocument, fonts: &[(String, String, String)]) -> TextDoc { let mut d = TextDoc::default(); - let f = |k: &str| j.get(k).and_then(Json::as_f64); - if let Some(t) = j.get("t").and_then(Json::as_str) { + if let Some(t) = &j.text { d.text = t.replace(['\r', '\u{3}'], "\n"); } - if let Some(name) = j.get("f").and_then(Json::as_str) { + if let Some(name) = &j.font { match fonts.iter().find(|(n, _, _)| n == name) { Some((_, fam, st)) => { d.font = fam.clone(); @@ -71,40 +77,39 @@ fn doc_from(j: &Json, fonts: &[(String, String, String)]) -> TextDoc { } } } - if let Some(s) = f("s") { + if let Some(s) = j.size { d.size = s; } - let col = |k: &str| j.get(k).and_then(anim::to_color).map(|v| v.as_color()); - match col("fc") { + match doc_color(j.fill.as_ref(), &j.extra, "fc") { Some(c) => d.fill = c, None => d.apply_fill = false, } - if let Some(c) = col("sc") { + if let Some(c) = doc_color(j.stroke.as_ref(), &j.extra, "sc") { d.stroke = c; d.apply_stroke = true; - d.stroke_width = f("sw").unwrap_or(1.0); + d.stroke_width = j.stroke_width.unwrap_or(1.0); } - if let Some(of) = j.get("of").and_then(Json::as_bool) { + if let Some(of) = j.stroke_over_fill { d.stroke_over_fill = of; } - if let Some(i) = j.get("j").and_then(Json::as_u64) { - d.justify = JUSTIFY.get(i as usize).copied().unwrap_or_default(); + if let Some(i) = j.justify.and_then(|i| usize::try_from(i).ok()) { + d.justify = JUSTIFY.get(i).copied().unwrap_or_default(); } - d.tracking = f("tr").unwrap_or(0.0); - if let Some(lh) = f("lh") + d.tracking = j.tracking.unwrap_or(0.0); + if let Some(lh) = j.line_height && (lh - d.size * 1.2).abs() > 1e-6 { d.leading = Some(lh); } - d.baseline_shift = f("ls").unwrap_or(0.0); - match j.get("ca").and_then(Json::as_u64) { + d.baseline_shift = j.baseline_shift.unwrap_or(0.0); + match j.caps { Some(1) => d.all_caps = true, Some(2) => d.small_caps = true, _ => {} } - if let Some(sz) = j.get("sz").and_then(anim::nums).filter(|v| v.len() >= 2) { + if let Some(sz) = j.box_size.as_deref().filter(|v| v.len() >= 2) { d.box_size = Some([sz[0], sz[1]]); - if let Some(ps) = j.get("ps").and_then(anim::nums).filter(|v| v.len() >= 2) { + if let Some(ps) = j.box_position.as_deref().filter(|v| v.len() >= 2) { d.box_pos = [ps[0], ps[1]]; } } @@ -136,28 +141,86 @@ fn conv_for(v: &Value) -> fn(&Value) -> Json { } } +/// The field of a range animator's style for a Lottie key. +fn style_field<'a>(st: &'a mut TextStyle, key: &str) -> Option<&'a mut Option> { + Some(match key { + "p" => &mut st.position, + "a" => &mut st.anchor, + "s" => &mut st.scale, + "r" => &mut st.rotation, + "rx" => &mut st.rotation_x, + "ry" => &mut st.rotation_y, + "sk" => &mut st.skew, + "sa" => &mut st.skew_axis, + "o" => &mut st.opacity, + "fc" => &mut st.fill, + "fh" => &mut st.fill_hue, + "fs" => &mut st.fill_saturation, + "fb" => &mut st.fill_brightness, + "fo" => &mut st.fill_opacity, + "sc" => &mut st.stroke, + "sw" => &mut st.stroke_width, + "so" => &mut st.stroke_opacity, + "t" => &mut st.tracking, + "ls" => &mut st.line_spacing, + "bl" => &mut st.blur, + _ => return None, + }) +} + +fn style_set(st: &mut TextStyle, key: &str, v: Animated) { + match style_field(st, key) { + Some(f) => *f = Some(v), + None => { + st.extra.insert(key.into(), v.0); + } + } +} + +fn style_get(st: &TextStyle, key: &str) -> Option { + let named = match key { + "p" => &st.position, + "a" => &st.anchor, + "s" => &st.scale, + "r" => &st.rotation, + "sk" => &st.skew, + "sa" => &st.skew_axis, + "o" => &st.opacity, + "fc" => &st.fill, + "fh" => &st.fill_hue, + "fs" => &st.fill_saturation, + "fb" => &st.fill_brightness, + "sc" => &st.stroke, + "sw" => &st.stroke_width, + "t" => &st.tracking, + _ => &None, + }; + named.as_ref().map(|a| a.0.clone()).or_else(|| st.extra.get(key).cloned()) +} + /// Export a text layer's `t` object. Fonts used are added to `fonts`. -pub(crate) fn export_text(ex: &mut Ex, layer: &Layer, fonts: &mut Vec) -> Json { - let Some(tg) = layer.props.sub("text") else { return json!({}) }; +pub(crate) fn export_text(ex: &mut Ex, layer: &Layer, fonts: &mut Vec) -> TextData { + let Some(tg) = layer.props.sub("text") else { return TextData::default() }; let label = &layer.name; let mut docs = vec![]; let mut add_font = |d: &TextDoc| { let n = font_name(&d.font, &d.style); - if !fonts.iter().any(|f| f["fName"] == json!(n)) { - fonts.push(json!({"fName": n, "fFamily": d.font, "fStyle": d.style, "ascent": 75})); + if !fonts.iter().any(|f| f.name.as_deref() == Some(n.as_str())) { + fonts.push(Font { name: Some(n), family: Some(d.font.clone()), style: Some(d.style.clone()), ascent: Some(75.0), ..Default::default() }); } }; + let key = |t: f64, d: &TextDoc| TextDocKey { time: Some(t), document: Some(doc_json(d)), ..Default::default() }; if let Some(st) = tg.get("sourceText") { if st.keys.is_empty() { if let Value::Text(d) = &st.value { add_font(d); - docs.push(json!({"t": 0, "s": doc_json(d)})); + docs.push(key(0.0, d)); } } else { for k in &st.keys { if let Value::Text(d) = &k.value { add_font(d); - docs.push(json!({"t": ex.tb.frame(k.time), "s": doc_json(d)})); + docs.push(key(ex.tb.frame(k.time), d)); } } } @@ -184,22 +247,28 @@ pub(crate) fn export_text(ex: &mut Ex, layer: &Layer, fonts: &mut Vec) -> animators.push(export_animator(ex, a, &format!("{label} ▸ {}", a.name))); } } - let mut m = json!({"g": 1, "a": {"a": 0, "k": [0, 0]}}); + let mut m = TextAlign { grouping: Some(1), anchor: Some(fixed(json!([0, 0]))), ..Default::default() }; if let Some(more) = tg.sub("moreOptions") { - m["g"] = json!(more.get("anchorGrouping").map(|p| p.value.as_enum()).unwrap_or(0) + 1); + m.grouping = Some(i64::from(more.get("anchorGrouping").map(|p| p.value.as_enum()).unwrap_or(0)) + 1); if let Some(p) = more.get("groupingAlignment") { - m["a"] = export_prop(ex, p, &anim::arr2, &format!("{label} ▸ Grouping Alignment")); + m.anchor = Some(export_prop(ex, p, &anim::arr2, &format!("{label} ▸ Grouping Alignment"))); } } if tg.sub("pathOptions").and_then(|p| p.get("path")).is_some_and(|p| p.value.as_enum() > 0) { ex.warn(format!("{label}: text on a path is not exported")); } - json!({"d": {"k": docs}, "a": animators, "m": m, "p": {}}) + TextData { + documents: Some(TextDocs { keys: Some(docs), ..Default::default() }), + ranges: Some(animators), + alignment: Some(m), + follow_path: Some(TextFollowPath::default()), + ..Default::default() + } } /// Text animators reproducing the style runs of `d` (fill, stroke, stroke width, size, /// tracking, baseline shift) over their character ranges. -fn style_run_animators(ex: &mut Ex, d: &TextDoc, label: &str) -> Vec { +fn style_run_animators(ex: &mut Ex, d: &TextDoc, label: &str) -> Vec { let base = d.base_style(); let mut out = vec![]; let mut start = 0usize; @@ -211,63 +280,71 @@ fn style_run_animators(ex: &mut Ex, d: &TextDoc, label: &str) -> Vec { if *s == base || run.len == 0 { continue; } - let k = |v: Json| json!({"a": 0, "k": v}); - let mut props = Map::new(); + let k = fixed; + let mut props = TextStyle::default(); if s.apply_fill && s.fill != base.fill { - props.insert("fc".into(), k(json!([s.fill[0] as f64, s.fill[1] as f64, s.fill[2] as f64, 1.0]))); + props.fill = Some(k(json!([s.fill[0] as f64, s.fill[1] as f64, s.fill[2] as f64, 1.0]))); } if s.apply_stroke && s.stroke != base.stroke { - props.insert("sc".into(), k(json!([s.stroke[0] as f64, s.stroke[1] as f64, s.stroke[2] as f64, 1.0]))); + props.stroke = Some(k(json!([s.stroke[0] as f64, s.stroke[1] as f64, s.stroke[2] as f64, 1.0]))); } if (s.stroke_width - base.stroke_width).abs() > 1e-9 { - props.insert("sw".into(), k(json!(s.stroke_width - base.stroke_width))); + props.stroke_width = Some(k(json!(s.stroke_width - base.stroke_width))); } if (s.size - base.size).abs() > 1e-9 && base.size > 0.0 { let p = s.size / base.size * 100.0; - props.insert("s".into(), k(json!([p, p, 100.0]))); + props.scale = Some(k(json!([p, p, 100.0]))); } if (s.tracking - base.tracking).abs() > 1e-9 { // Lottie tracking is in 1/1000 em like the Character panel's. - props.insert("t".into(), k(json!(s.tracking - base.tracking))); + props.tracking = Some(k(json!(s.tracking - base.tracking))); } if (s.baseline_shift - base.baseline_shift).abs() > 1e-9 { - props.insert("p".into(), k(json!([0.0, -(s.baseline_shift - base.baseline_shift), 0.0]))); + props.position = Some(k(json!([0.0, -(s.baseline_shift - base.baseline_shift), 0.0]))); } let lost = s.font != base.font || s.style != base.style || s.faux_bold != base.faux_bold || s.faux_italic != base.faux_italic; if lost && !warned { ex.warn(format!("{label}: per-character fonts and faux styles are not part of Lottie text (base font used)")); warned = true; } - if props.is_empty() { + if props == TextStyle::default() { continue; } - out.push(json!({ - "nm": format!("Style {a}–{b}"), - "s": { - "t": 0, "xe": k(json!(0)), "ne": k(json!(0)), "a": k(json!(100)), "b": 1, "rn": 0, "sh": 1, - "r": 2, "m": k(json!(1)), "s": k(json!(a)), "e": k(json!(b)), "o": k(json!(0)), - }, - "a": Json::Object(props), - })); + let mut sel = TextSelector { + kind: Some(0), + ease_high: Some(k(json!(0))), + ease_low: Some(k(json!(0))), + amount: Some(k(json!(100))), + based_on: Some(1), + randomize: Some(0), + shape: Some(1), + units: Some(2), + start: Some(k(json!(a))), + end: Some(k(json!(b))), + offset: Some(k(json!(0))), + ..Default::default() + }; + sel.extra.insert("m".into(), k(json!(1)).0); + out.push(TextRange { name: Some(format!("Style {a}–{b}")), selector: Some(sel), style: Some(props), ..Default::default() }); } out } -fn export_animator(ex: &mut Ex, a: &PropGroup, label: &str) -> Json { - let mut props = Map::new(); +fn export_animator(ex: &mut Ex, a: &PropGroup, label: &str) -> TextRange { + let mut props = TextStyle::default(); if let Some(pg) = a.sub("properties") { for p in pg.props() { match ANIM_PROPS.iter().find(|(_, _, m)| *m == p.match_id) { Some((key, _, _)) => { let v = export_prop(ex, p, &conv_for(&p.value), &format!("{label} ▸ {}", p.name)); - props.insert((*key).into(), v); + style_set(&mut props, key, v); } None if matches!(p.match_id.as_str(), "trackingType") => {} None => ex.warn(format!("{label} ▸ {}: text animator property not supported by Lottie", p.name)), } } } - let mut sel = json!({"t": 0}); + let mut sel = TextSelector { kind: Some(0), ..Default::default() }; let sels: Vec<&PropGroup> = a.sub("selectors").map(|s| s.groups().collect()).unwrap_or_default(); if sels.len() > 1 { ex.warn(format!("{label}: only the first selector is exported (Lottie animators have one)")); @@ -276,36 +353,29 @@ fn export_animator(ex: &mut Ex, a: &PropGroup, label: &str) -> Json { if s.match_id != "rangeSelector" { ex.warn(format!("{label}: {} is not supported by Lottie", s.name)); } else { - for (k, m) in [("s", "start"), ("e", "end"), ("o", "offset")] { - if let Some(p) = s.get(m) { - sel[k] = export_prop(ex, p, &anim::num, &format!("{label} ▸ {}", p.name)); - } - } + let mut prop = |m: &str| s.get(m).map(|p| export_prop(ex, p, &anim::num, &format!("{label} ▸ {}", p.name))); + (sel.start, sel.end, sel.offset) = (prop("start"), prop("end"), prop("offset")); if let Some(adv) = s.sub("advanced") { - let e = |m: &str| adv.get(m).map(|p| p.value.as_enum()).unwrap_or(0) + 1; - sel["r"] = json!(e("units")); - sel["b"] = json!(e("basedOn")); - sel["m"] = json!({"a": 0, "k": e("mode")}); - sel["sh"] = json!(e("shape")); - sel["rn"] = json!(adv.get("randomize").is_some_and(|p| p.value.as_bool()) as u8); - for (k, m) in [("a", "amount"), ("sm", "smoothness"), ("xe", "easeHigh"), ("ne", "easeLow")] { - if let Some(p) = adv.get(m) { - sel[k] = export_prop(ex, p, &anim::num, &format!("{label} ▸ {}", p.name)); - } - } + let e = |m: &str| i64::from(adv.get(m).map(|p| p.value.as_enum()).unwrap_or(0)) + 1; + sel.units = Some(e("units")); + sel.based_on = Some(e("basedOn")); + sel.extra.insert("m".into(), json!({"a": 0, "k": e("mode")})); + sel.shape = Some(e("shape")); + sel.randomize = Some(i64::from(adv.get("randomize").is_some_and(|p| p.value.as_bool()))); + let mut prop = |m: &str| adv.get(m).map(|p| export_prop(ex, p, &anim::num, &format!("{label} ▸ {}", p.name))); + (sel.amount, sel.smoothness, sel.ease_high, sel.ease_low) = (prop("amount"), prop("smoothness"), prop("easeHigh"), prop("easeLow")); } } } - json!({"nm": a.name, "s": sel, "a": Json::Object(props)}) + TextRange { name: Some(a.name.clone()), selector: Some(sel), style: Some(props), ..Default::default() } } /// Import Lottie text data into a text layer's `text` group. -pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGroup, fonts: &[(String, String, String)]) { - if let Some(list) = t.get("d").and_then(|d| d.get("k")).and_then(Json::as_array) +pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &TextData, tg: &mut PropGroup, fonts: &[(String, String, String)]) { + if let Some(list) = t.documents.as_ref().and_then(|d| d.keys.as_deref()) && let Some(st) = tg.get_mut("sourceText") { - let docs: Vec<(f64, TextDoc)> = - list.iter().filter_map(|k| Some((k.get("t").and_then(Json::as_f64).unwrap_or(0.0), doc_from(k.get("s")?, fonts)))).collect(); + let docs: Vec<(f64, TextDoc)> = list.iter().filter_map(|k| Some((k.time.unwrap_or(0.0), doc_from(k.document.as_ref()?, fonts)))).collect(); if let Some((_, first)) = docs.first() { st.value = Value::Text(Box::new(first.clone())); } @@ -314,24 +384,25 @@ pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGro st.keys = docs.into_iter().map(|(f, d)| effectcraft_keyframe::Keyframe::new(im.tb.tick(f), Value::Text(Box::new(d))).hold()).collect(); } } - if let Some(m) = t.get("m") + if let Some(m) = &t.alignment && let Some(more) = tg.sub_mut("moreOptions") { - if let (Some(g), Some(p)) = (m.get("g").and_then(Json::as_u64), more.get_mut("anchorGrouping")) { + let grouping = m.grouping.or_else(|| m.extra.get("g").and_then(Json::as_i64)).and_then(|g| u64::try_from(g).ok()); + if let (Some(g), Some(p)) = (grouping, more.get_mut("anchorGrouping")) { p.value = Value::Enum((g.max(1) - 1).min(3) as u32); } - if let (Some(a), Some(p)) = (m.get("a"), more.get_mut("groupingAlignment")) { - import_prop(im, a, p, &anim::to_vec2); + if let (Some(a), Some(p)) = (&m.anchor, more.get_mut("groupingAlignment")) { + import_prop(im, &a.0, p, &anim::to_vec2); } } - let Some(list) = t.get("a").and_then(Json::as_array) else { return }; + let Some(list) = &t.ranges else { return }; let mut animators = vec![]; for (i, a) in list.iter().enumerate() { - let name = a.get("nm").and_then(Json::as_str).map(str::to_string).unwrap_or(format!("Animator {}", i + 1)); - let props_j = a.get("a").cloned().unwrap_or(json!({})); + let name = a.name.clone().unwrap_or(format!("Animator {}", i + 1)); + let style = a.style.clone().unwrap_or_default(); let mut kinds: Vec<&str> = vec![]; for (key, kind, _) in ANIM_PROPS { - if props_j.get(*key).is_some() && !kinds.contains(kind) { + if style_get(&style, key).is_some() && !kinds.contains(kind) { kinds.push(kind); } } @@ -339,7 +410,7 @@ pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGro let mut g = build::text_animator(ids, &name, props); if let Some(pg) = g.sub_mut("properties") { for (key, _, m) in ANIM_PROPS { - let (Some(j), Some(p)) = (props_j.get(*key), pg.get_mut(m)) else { continue }; + let (Some(j), Some(p)) = (style_get(&style, key), pg.get_mut(m)) else { continue }; let conv: Box Option> = match &p.value { Value::Vec3(d) => { let z = d[2]; @@ -349,34 +420,38 @@ pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGro Value::Color(_) => Box::new(anim::to_color), _ => Box::new(anim::to_scalar), }; - import_prop(im, j, p, &*conv); + import_prop(im, &j, p, &*conv); } } - if let Some(s) = a.get("s") + if let Some(s) = &a.selector && let Some(sel) = g.sub_mut("selectors").and_then(|s| s.groups_mut_first()) { - for (k, m) in [("s", "start"), ("e", "end"), ("o", "offset")] { - if let (Some(j), Some(p)) = (s.get(k), sel.get_mut(m)) { - import_prop(im, j, p, &anim::to_scalar); + for (m, j) in [("start", &s.start), ("end", &s.end), ("offset", &s.offset)] { + if let (Some(j), Some(p)) = (j, sel.get_mut(m)) { + import_prop(im, &j.0, p, &anim::to_scalar); } } if let Some(adv) = sel.sub_mut("advanced") { - let mut en = |m: &str, key: &str, max: u32| { - let v = s.get(key).and_then(|v| if v.is_object() { v.get("k") } else { Some(v) }).and_then(anim::nums).and_then(|n| n.first().copied()); + let mut en = |m: &str, field: Option, key: &str, max: u32| { + let v = field.map(|f| f as f64).or_else(|| { + let v = s.extra.get(key)?; + let v = if v.is_object() { v.get("k")? } else { v }; + anim::nums(v).and_then(|n| n.first().copied()) + }); if let (Some(v), Some(p)) = (v, adv.get_mut(m)) { p.value = Value::Enum((((v.round() as i64).saturating_sub(1)).max(0) as u32).min(max)); } }; - en("units", "r", 1); - en("basedOn", "b", 3); - en("mode", "m", 5); - en("shape", "sh", 5); - if let (Some(rn), Some(p)) = (s.get("rn").and_then(Json::as_u64), adv.get_mut("randomize")) { + en("units", s.units, "r", 1); + en("basedOn", s.based_on, "b", 3); + en("mode", None, "m", 5); + en("shape", s.shape, "sh", 5); + if let (Some(rn), Some(p)) = (s.randomize.and_then(|r| u64::try_from(r).ok()), adv.get_mut("randomize")) { p.value = Value::Bool(rn != 0); } - for (k, m) in [("a", "amount"), ("sm", "smoothness"), ("xe", "easeHigh"), ("ne", "easeLow")] { - if let (Some(j), Some(p)) = (s.get(k), adv.get_mut(m)) { - import_prop(im, j, p, &anim::to_scalar); + for (m, j) in [("amount", &s.amount), ("smoothness", &s.smoothness), ("easeHigh", &s.ease_high), ("easeLow", &s.ease_low)] { + if let (Some(j), Some(p)) = (j, adv.get_mut(m)) { + import_prop(im, &j.0, p, &anim::to_scalar); } } } @@ -400,7 +475,7 @@ impl FirstGroup for PropGroup { /// Text converted to glyph shapes: one group with every glyph outline (at layer time 0's /// Source Text), a fill and a stroke, as Lottie shape items. -pub(crate) fn glyph_shapes(ex: &mut Ex, layer: &Layer) -> Vec { +pub(crate) fn glyph_shapes(ex: &mut Ex, layer: &Layer) -> Vec { let Some(tg) = layer.props.sub("text") else { return vec![] }; let Some(st) = tg.get("sourceText") else { return vec![] }; let Value::Text(doc) = st.value_at(Tick::ZERO) else { return vec![] }; @@ -412,14 +487,29 @@ pub(crate) fn glyph_shapes(ex: &mut Ex, layer: &Layer) -> Vec { for g in &lay.glyphs { let p = kurbo::Affine::translate((g.origin.x, g.origin.y)) * g.path.clone(); for sp in effectcraft_path::from_kurbo(&p) { - items.push(json!({"ty": "sh", "nm": g.ch.to_string(), "d": 1, "ks": {"a": 0, "k": shapes::shape_json(&sp)}})); + let path = Path { direction: Some(1), path: Some(fixed(shapes::shape_json(&sp))), closed: None }; + items.push(Shape { name: Some(g.ch.to_string()), kind: ShapeKind::Path(path), ..Default::default() }); } } - let col = |c: [f32; 4]| json!({"a": 0, "k": [c[0] as f64, c[1] as f64, c[2] as f64, 1.0]}); - let stroke = (doc.apply_stroke && doc.stroke_width > 0.0).then( - || json!({"ty": "st", "nm": "Stroke", "c": col(doc.stroke), "o": {"a": 0, "k": 100}, "w": {"a": 0, "k": doc.stroke_width}, "lc": 2, "lj": 2, "ml": 4}), - ); - let fill = doc.apply_fill.then(|| json!({"ty": "fl", "nm": "Fill", "c": col(doc.fill), "o": {"a": 0, "k": 100}, "r": 1})); + let col = |c: [f32; 4]| fixed(json!([c[0] as f64, c[1] as f64, c[2] as f64, 1.0])); + let stroke = (doc.apply_stroke && doc.stroke_width > 0.0).then(|| Shape { + name: Some("Stroke".into()), + kind: ShapeKind::Stroke(craft_lottie::model::Stroke { + color: Some(col(doc.stroke)), + opacity: Some(fixed(json!(100))), + width: Some(fixed(json!(doc.stroke_width))), + cap: Some(2), + join: Some(2), + miter_limit: Some(4.0), + ..Default::default() + }), + ..Default::default() + }); + let fill = doc.apply_fill.then(|| Shape { + name: Some("Fill".into()), + kind: ShapeKind::Fill(craft_lottie::model::Fill { color: Some(col(doc.fill)), opacity: Some(fixed(json!(100))), rule: Some(1) }), + ..Default::default() + }); // Items above draw on top: stroke over fill puts the stroke first. if doc.stroke_over_fill { items.extend(stroke); @@ -429,6 +519,15 @@ pub(crate) fn glyph_shapes(ex: &mut Ex, layer: &Layer) -> Vec { items.extend(stroke); } let n = items.len() + 1; - items.push(json!({"ty": "tr", "a": {"a": 0, "k": [0, 0]}, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]}, "r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}})); - vec![json!({"ty": "gr", "nm": layer.name, "np": n, "it": items})] + let tr = craft_lottie::model::Transform { + anchor: Some(fixed(json!([0, 0]))), + position: Some(fixed(json!([0, 0]))), + scale: Some(fixed(json!([100, 100]))), + rotation: Some(fixed(json!(0))), + opacity: Some(fixed(json!(100))), + ..Default::default() + }; + items.push(Shape { kind: ShapeKind::Transform(Box::new(tr)), ..Default::default() }); + let group = craft_lottie::model::Group { count: Some(n as f64), items: Some(items) }; + vec![Shape { name: Some(layer.name.clone()), kind: ShapeKind::Group(group), ..Default::default() }] } diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 76cce90fa..f744c684c 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -22,6 +22,10 @@ effectcraft-pdf = { workspace = true } effectcraft-model = { workspace = true } filmcraft-codecs = { workspace = true } filmcraft-media = { workspace = true } +craft-dpx = { workspace = true } +craft-exr = { workspace = true } +craft-gif = { workspace = true } +craft-webp = { workspace = true } craft-audio = { workspace = true } craft-media = { workspace = true } filmcraft-mpegts = { workspace = true } @@ -29,7 +33,6 @@ filmcraft-frame = { workspace = true } filmcraft-color = { workspace = true } filmcraft-time = { workspace = true } exr = { workspace = true } -gif = { workspace = true } image = { workspace = true, features = ["gif", "webp", "tiff", "bmp", "exr", "tga", "hdr"] } rayon = { workspace = true } serde_json = { workspace = true } @@ -37,6 +40,8 @@ thiserror = { workspace = true } log = { workspace = true } [dev-dependencies] +# Writes the animated GIFs of the tests. +gif = { workspace = true } tempfile = { workspace = true } # (tests render comps that read layers through effects; already a dependency of effectcraft-render) effectcraft-effects = { workspace = true } diff --git a/crates/media/src/dpx.rs b/crates/media/src/dpx.rs index a5b2abdaf..f08f1344d 100644 --- a/crates/media/src/dpx.rs +++ b/crates/media/src/dpx.rs @@ -1,17 +1,11 @@ -//! DPX (SMPTE 268M) and Kodak Cineon stills, the film-scan interchange formats, read from the -//! public specifications. +//! DPX (SMPTE 268M) and Kodak Cineon stills, the film-scan interchange formats, read with +//! `craft-dpx`; this module maps a frame onto footage and 16-bit pixels. //! -//! Supported: luma, RGB, RGBA and ABGR (DPX) or one / three channels (Cineon), 8-, 10-, 12- and -//! 16-bit unsigned samples, 10-bit filled into 32-bit words with the pad bits low (DPX method A, -//! Cineon "32-bit left justified") or high (method B, "right justified"), 12-bit in 16-bit words, -//! big- and little-endian files, the four unrotated image orientations and the pixel aspect ratio. //! Code values are shown as stored (a log scan looks flat, as in After Effects without a Cineon -//! conversion); the codec names the transfer (`log`, `linear`, …). Anything else (run-length -//! encoding, signed or float samples, Y'CbCr, packed 10/12-bit, transposed images) is refused -//! with an error naming it. Every field is read with bounds checks. +//! conversion); the codec names the transfer (`log`, `linear`, …). Y'CbCr elements and transposed +//! images are refused with an error naming them; so is everything `craft-dpx` does not read. use effectcraft_project::{AlphaMode, Footage}; -use rayon::prelude::*; use crate::{MediaError, Result}; @@ -21,391 +15,110 @@ pub(crate) const EXTENSIONS: &[&str] = &["dpx", "cin"]; /// Largest image accepted (8192 × 8192): bigger headers are refused before allocating. const MAX_PIXELS: u64 = 1 << 26; -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Kind { - Dpx, - Cineon, +fn limits() -> craft_dpx::Limits { + let mut l = craft_dpx::Limits::default(); + l.max_pixels = MAX_PIXELS; + l } -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Layout { - Luma, - Rgb, - Rgba, - Abgr, -} - -impl Layout { - fn components(self) -> usize { - match self { - Layout::Luma => 1, - Layout::Rgb => 3, - Layout::Rgba | Layout::Abgr => 4, - } - } - fn name(self) -> &'static str { - match self { - Layout::Luma => "luma", - Layout::Rgb => "RGB", - Layout::Rgba => "RGBA", - Layout::Abgr => "ABGR", - } +fn error(path: &str, e: craft_dpx::Error) -> MediaError { + match e { + craft_dpx::Error::Unsupported(_) => MediaError::Unsupported(format!("{path}: {e}")), + _ => MediaError::Decode(format!("{path}: {e}")), } } -/// How samples are stored in a line. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Packing { - /// One byte per sample. - Bytes8, - /// One 16-bit word per sample. - Words16, - /// Three 10-bit samples per 32-bit word, first in the high bits, two pad bits low. - Filled10A, - /// Three 10-bit samples per 32-bit word, two pad bits high. - Filled10B, - /// One 12-bit sample per 16-bit word, four pad bits low. - Filled12A, - /// One 12-bit sample per 16-bit word, four pad bits high. - Filled12B, +/// The header of a DPX or Cineon file this module shows (`None` for other formats). +fn info(path: &str, bytes: &[u8]) -> Result> { + if craft_dpx::sniff(bytes).is_none() { + return Ok(None); + } + let info = craft_dpx::probe(bytes, &limits()).map_err(|e| error(path, e))?; + if info.layout.is_ycbcr() { + return Err(MediaError::Unsupported(format!("{path}: DPX with Y'CbCr samples is not supported"))); + } + if info.flips().is_none() { + return Err(MediaError::Unsupported(format!("{path}: DPX orientation {} (transposed image) is not supported", info.orientation))); + } + Ok(Some(info)) } -impl Packing { - fn max(self) -> u32 { - match self { - Packing::Bytes8 => 0xff, - Packing::Words16 => 0xffff, - Packing::Filled10A | Packing::Filled10B => 0x3ff, - Packing::Filled12A | Packing::Filled12B => 0xfff, - } - } - fn bits(self) -> u32 { - match self { - Packing::Bytes8 => 8, - Packing::Words16 => 16, - Packing::Filled10A | Packing::Filled10B => 10, - Packing::Filled12A | Packing::Filled12B => 12, - } - } - /// Bytes holding `n` samples, padded to a 32-bit word (lines start on word boundaries). - fn line_bytes(self, n: u64) -> u64 { - match self { - Packing::Bytes8 => n.div_ceil(4) * 4, - Packing::Words16 | Packing::Filled12A | Packing::Filled12B => (n * 2).div_ceil(4) * 4, - Packing::Filled10A | Packing::Filled10B => n.div_ceil(3) * 4, - } +fn layout_name(info: &craft_dpx::Info) -> &'static str { + match info.layout { + craft_dpx::Layout::Luma => "luma", + craft_dpx::Layout::Rgb => "RGB", + _ if info.descriptor == 52 => "ABGR", + _ => "RGBA", } } -/// What a header says about the picture. -#[derive(Clone, Debug)] -struct Header { - kind: Kind, - big_endian: bool, - width: u32, - height: u32, - layout: Layout, - packing: Packing, - /// Byte offset of the first line. - offset: u64, - /// Bytes from one line's start to the next. - stride: u64, - flip_x: bool, - flip_y: bool, - pixel_aspect: f64, - /// Transfer characteristic for the codec name (`log`, `linear`, …), empty when unstated. - transfer: &'static str, -} - -/// Bounds-checked reads in the file's byte order. -struct Reader<'a> { - b: &'a [u8], - big: bool, -} - -impl Reader<'_> { - fn u8(&self, o: usize) -> Option { - self.b.get(o).copied() +/// The transfer characteristic for the codec name, empty when unstated. +fn transfer(info: &craft_dpx::Info) -> &'static str { + if info.kind == craft_dpx::Kind::Cineon { + return "log"; } - fn u16(&self, o: usize) -> Option { - let s: [u8; 2] = self.b.get(o..o.checked_add(2)?)?.try_into().ok()?; - Some(if self.big { u16::from_be_bytes(s) } else { u16::from_le_bytes(s) }) - } - fn u32(&self, o: usize) -> Option { - let s: [u8; 4] = self.b.get(o..o.checked_add(4)?)?.try_into().ok()?; - Some(if self.big { u32::from_be_bytes(s) } else { u32::from_le_bytes(s) }) - } -} - -const UNDEFINED32: u32 = u32::MAX; - -/// DPX or Cineon, and the byte order, from the magic number. -fn sniff(bytes: &[u8]) -> Option<(Kind, bool)> { - match bytes.get(..4)? { - b"SDPX" => Some((Kind::Dpx, true)), - b"XPDS" => Some((Kind::Dpx, false)), - [0x80, 0x2a, 0x5f, 0xd7] => Some((Kind::Cineon, true)), - [0xd7, 0x5f, 0x2a, 0x80] => Some((Kind::Cineon, false)), - _ => None, - } -} - -fn unsupported(path: &str, what: impl std::fmt::Display) -> MediaError { - MediaError::Unsupported(format!("{path}: {what}")) -} - -fn truncated(path: &str, kind: Kind) -> MediaError { - let name = if kind == Kind::Dpx { "DPX" } else { "Cineon" }; - MediaError::Decode(format!("{path}: truncated {name} header")) -} - -fn parse(path: &str, bytes: &[u8]) -> Result> { - let Some((kind, big_endian)) = sniff(bytes) else { return Ok(None) }; - let r = Reader { b: bytes, big: big_endian }; - let h = match kind { - Kind::Dpx => parse_dpx(path, &r)?, - Kind::Cineon => parse_cineon(path, &r)?, - }; - let pixels = u64::from(h.width) * u64::from(h.height); - if h.width == 0 || h.height == 0 || pixels > MAX_PIXELS { - return Err(MediaError::Decode(format!("{path}: image size {} × {} out of range", h.width, h.height))); - } - let need = h.offset.saturating_add(h.stride.saturating_mul(u64::from(h.height))); - if (bytes.len() as u64) < need { - return Err(MediaError::Decode(format!("{path}: truncated image data ({} of {need} bytes)", bytes.len()))); - } - Ok(Some(h)) -} - -fn parse_dpx(path: &str, r: &Reader) -> Result
{ - let t = || truncated(path, Kind::Dpx); - let image_offset = r.u32(4).ok_or_else(t)?; - let orientation = r.u16(768).ok_or_else(t)?; - let elements = r.u16(770).ok_or_else(t)?; - let width = r.u32(772).ok_or_else(t)?; - let height = r.u32(776).ok_or_else(t)?; - // The first image element (the picture; further elements are alternative views). - let sign = r.u32(780).ok_or_else(t)?; - let descriptor = r.u8(800).ok_or_else(t)?; - let transfer = r.u8(801).ok_or_else(t)?; - let bits = r.u8(803).ok_or_else(t)?; - let packing = r.u16(804).ok_or_else(t)?; - let encoding = r.u16(806).ok_or_else(t)?; - let data_offset = r.u32(808).ok_or_else(t)?; - let eol_padding = r.u32(812).ok_or_else(t)?; - if elements == 0 || elements == u16::MAX { - return Err(unsupported(path, "DPX file without an image element")); - } - if sign == 1 { - return Err(unsupported(path, "DPX with signed samples is not supported")); - } - if encoding == 1 { - return Err(unsupported(path, "run-length encoded DPX is not supported")); - } - let layout = match descriptor { - 6 => Layout::Luma, - 50 => Layout::Rgb, - 51 => Layout::Rgba, - 52 => Layout::Abgr, - 100..=103 => return Err(unsupported(path, "DPX with Y'CbCr samples is not supported")), - d => return Err(unsupported(path, format!("DPX image element descriptor {d} is not supported (luma, RGB, RGBA and ABGR are)"))), - }; - let packing = match (bits, packing) { - (8, _) => Packing::Bytes8, - (16, _) => Packing::Words16, - (10, 1) => Packing::Filled10A, - (10, 2) => Packing::Filled10B, - (12, 1) => Packing::Filled12A, - (12, 2) => Packing::Filled12B, - (10 | 12, _) => return Err(unsupported(path, format!("DPX with packed {bits}-bit samples (packing {packing}) is not supported"))), - (b, _) => return Err(unsupported(path, format!("DPX with {b}-bit samples is not supported (8, 10, 12 and 16 are)"))), - }; - let (flip_x, flip_y) = match orientation { - 0 | u16::MAX => (false, false), - 1 => (true, false), - 2 => (false, true), - 3 => (true, true), - o => return Err(unsupported(path, format!("DPX orientation {o} (transposed image) is not supported"))), - }; - let offset = if data_offset == 0 || data_offset == UNDEFINED32 { image_offset } else { data_offset }; - let eol = if eol_padding == UNDEFINED32 { 0 } else { eol_padding }; - let samples = u64::from(width) * layout.components() as u64; - // Pixel aspect ratio (orientation header), when stated. - let pixel_aspect = match (r.u32(1628), r.u32(1632)) { - (Some(h), Some(v)) if h != 0 && v != 0 && h != UNDEFINED32 && v != UNDEFINED32 => { - let a = f64::from(h) / f64::from(v); - if (0.1..=10.0).contains(&a) { a } else { 1.0 } - } - _ => 1.0, - }; - let transfer = match transfer { - 1 => "log (printing density)", - 2 => "linear", - 3 => "log", - 5 | 6 => "Rec. 709", - 13 => "ADX", + match info.transfer { + Some(1) => "log (printing density)", + Some(2) => "linear", + Some(3) => "log", + Some(5 | 6) => "Rec. 709", + Some(13) => "ADX", _ => "", - }; - Ok(Header { - kind: Kind::Dpx, - big_endian: r.big, - width, - height, - layout, - packing, - offset: u64::from(offset), - stride: packing.line_bytes(samples) + u64::from(eol), - flip_x, - flip_y, - pixel_aspect, - transfer, - }) -} - -fn parse_cineon(path: &str, r: &Reader) -> Result
{ - let t = || truncated(path, Kind::Cineon); - let offset = r.u32(4).ok_or_else(t)?; - let orientation = r.u8(192).ok_or_else(t)?; - let channels = r.u8(193).ok_or_else(t)?; - // Channel 0's description; every channel must match it. - let bits = r.u8(198).ok_or_else(t)?; - let width = r.u32(200).ok_or_else(t)?; - let height = r.u32(204).ok_or_else(t)?; - let interleave = r.u8(680).ok_or_else(t)?; - let packing = r.u8(681).ok_or_else(t)?; - let signed = r.u8(682).ok_or_else(t)?; - let eol_padding = r.u32(684).ok_or_else(t)?; - let layout = match channels { - 1 => Layout::Luma, - 3 => Layout::Rgb, - c => return Err(unsupported(path, format!("Cineon with {c} channels is not supported (1 and 3 are)"))), - }; - for c in 1..usize::from(channels) { - let base = 196 + 28 * c; - if r.u8(base + 2) != Some(bits) || r.u32(base + 4) != Some(width) || r.u32(base + 8) != Some(height) { - return Err(unsupported(path, "Cineon channels of different sizes or depths are not supported")); - } } - if interleave != 0 { - return Err(unsupported(path, "Cineon with line or channel interleave is not supported")); - } - if signed == 1 { - return Err(unsupported(path, "Cineon with signed samples is not supported")); - } - let packing = match (bits, packing) { - (8, _) => Packing::Bytes8, - (16, _) => Packing::Words16, - (10, 5) => Packing::Filled10A, - (10, 6) => Packing::Filled10B, - (10, p) => return Err(unsupported(path, format!("Cineon with 10-bit packing {p} is not supported (32-bit words are)"))), - (b, _) => return Err(unsupported(path, format!("Cineon with {b}-bit samples is not supported (8, 10 and 16 are)"))), - }; - let (flip_x, flip_y) = match orientation { - 0 | u8::MAX => (false, false), - 1 => (false, true), - 2 => (true, false), - 3 => (true, true), - o => return Err(unsupported(path, format!("Cineon orientation {o} (transposed image) is not supported"))), - }; - let eol = if eol_padding == UNDEFINED32 { 0 } else { eol_padding }; - let samples = u64::from(width) * layout.components() as u64; - Ok(Header { - kind: Kind::Cineon, - big_endian: r.big, - width, - height, - layout, - packing, - offset: u64::from(offset), - stride: packing.line_bytes(samples) + u64::from(eol), - flip_x, - flip_y, - pixel_aspect: 1.0, - transfer: "log", - }) } /// Footage for a DPX or Cineon file (`None` for other formats). pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result> { - let Some(h) = parse(path, bytes)? else { return Ok(None) }; - let alpha = matches!(h.layout, Layout::Rgba | Layout::Abgr); + let Some(h) = info(path, bytes)? else { return Ok(None) }; + let alpha = h.layout.has_alpha(); let mut f = crate::probe::still_footage(path, h.width, h.height, image::ImageFormat::Png, alpha); f.alpha = if alpha { AlphaMode::Straight } else { AlphaMode::Ignore }; - f.pixel_aspect = h.pixel_aspect; - let name = if h.kind == Kind::Dpx { "DPX" } else { "Cineon" }; - f.codec = format!("{name} {}-bit {}", h.packing.bits(), h.layout.name()); - if !h.transfer.is_empty() { - f.codec = format!("{}, {}", f.codec, h.transfer); + f.pixel_aspect = + h.pixel_aspect.map(|(x, y)| f64::from(x) / f64::from(y)).filter(|a| (0.1..=10.0).contains(a) && h.kind == craft_dpx::Kind::Dpx).unwrap_or(1.0); + let name = if h.kind == craft_dpx::Kind::Dpx { "DPX" } else { "Cineon" }; + f.codec = format!("{name} {}-bit {}", h.bits, layout_name(&h)); + let t = transfer(&h); + if !t.is_empty() { + f.codec = format!("{}, {t}", f.codec); } Ok(Some(f)) } -/// The picture of a DPX or Cineon file as 16-bit samples (`None` for other formats). +/// The picture of a DPX or Cineon file as 16-bit samples, upright (`None` for other formats). pub(crate) fn decode(path: &str, bytes: &[u8]) -> Result> { - let Some(h) = parse(path, bytes)? else { return Ok(None) }; - let (w, ht) = (h.width as usize, h.height as usize); - // Output components: luma, RGB or RGBA (ABGR reordered). - let nc = h.layout.components(); - let row_len = w * nc; - let mut out = vec![0u16; row_len * ht]; - let max = h.packing.max(); - out.par_chunks_mut(row_len).enumerate().for_each(|(y, row)| { - let sy = if h.flip_y { ht - 1 - y } else { y }; - let start = h.offset.saturating_add(h.stride.saturating_mul(sy as u64)); - let line = usize::try_from(start).ok().and_then(|s| bytes.get(s..)).unwrap_or(&[]); - for x in 0..w { - let sx = if h.flip_x { w - 1 - x } else { x }; - for c in 0..nc { - // ABGR stores alpha first and colour reversed. - let sc = if h.layout == Layout::Abgr { 3 - c } else { c }; - let v = sample(line, h.packing, h.big_endian, sx * nc + sc); - if let Some(o) = row.get_mut(x * nc + c) { - *o = ((u64::from(v.min(max)) * 0xffff + u64::from(max) / 2) / u64::from(max)) as u16; + let Some(h) = info(path, bytes)? else { return Ok(None) }; + let (flip_x, flip_y) = h.flips().unwrap_or_default(); + let frame = craft_dpx::decode(bytes, &limits()).map_err(|e| error(path, e))?; + let (w, ht, nc) = (h.width as usize, h.height as usize, h.layout.components()); + let row_len = w.checked_mul(nc).ok_or_else(|| MediaError::Decode(format!("{path}: image dimensions overflow")))?; + let mut out = frame.codes; + if flip_y { + for y in 0..ht / 2 { + for x in 0..row_len { + out.swap(y * row_len + x, (ht - 1 - y) * row_len + x); + } + } + } + if flip_x { + for row in out.chunks_exact_mut(row_len) { + for x in 0..w / 2 { + let (a, b) = (x * nc, (w - 1 - x) * nc); + for c in 0..nc { + row.swap(a + c, b + c); } } } - }); + } + out.iter_mut().for_each(|c| *c = craft_dpx::widen(*c, h.bits)); let (w32, h32) = (h.width, h.height); let img = match h.layout { - Layout::Luma => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageLuma16), - Layout::Rgb => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageRgb16), - Layout::Rgba | Layout::Abgr => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageRgba16), + craft_dpx::Layout::Luma => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageLuma16), + craft_dpx::Layout::Rgb => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageRgb16), + _ => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageRgba16), }; img.map(Some).ok_or_else(|| MediaError::Decode(format!("{path}: image buffer size mismatch"))) } -/// Sample `i` of a line (0 past its end; the header check makes that unreachable for valid -/// headers). -#[inline] -fn sample(line: &[u8], packing: Packing, big: bool, i: usize) -> u32 { - let word16 = |o: usize| -> u32 { - match line.get(o..o + 2) { - Some(&[a, b]) => u32::from(if big { u16::from_be_bytes([a, b]) } else { u16::from_le_bytes([a, b]) }), - _ => 0, - } - }; - let word32 = |o: usize| -> u32 { - match line.get(o..o + 4) { - Some(&[a, b, c, d]) => { - if big { - u32::from_be_bytes([a, b, c, d]) - } else { - u32::from_le_bytes([a, b, c, d]) - } - } - _ => 0, - } - }; - match packing { - Packing::Bytes8 => line.get(i).copied().map_or(0, u32::from), - Packing::Words16 => word16(i * 2), - Packing::Filled12A => word16(i * 2) >> 4, - Packing::Filled12B => word16(i * 2) & 0xfff, - Packing::Filled10A => (word32(i / 3 * 4) >> (22 - 10 * (i % 3) as u32)) & 0x3ff, - Packing::Filled10B => (word32(i / 3 * 4) >> (20 - 10 * (i % 3) as u32)) & 0x3ff, - } -} - #[cfg(test)] mod tests { use super::*; @@ -452,7 +165,7 @@ mod tests { #[test] fn hostile_headers_never_panic() { - assert!(parse("x", b"not a dpx").expect("other").is_none()); + assert!(info("x", b"not a dpx").expect("other").is_none()); let good = { let mut a = dpx_header(4, 4, 50, 10, 1, 0); a.extend(std::iter::repeat_n(0x5a, 64)); @@ -462,14 +175,18 @@ mod tests { for n in [4, 8, 600, 790, 805, 2047, 2048, 2100] { assert!(decode("t.dpx", good.get(..n).expect("cut")).is_err(), "{n}"); } - // huge, zero, unsupported + // huge, zero, Y'CbCr, unsupported depth, transposed for (w, h, d, bits, p, o) in - [(u32::MAX, u32::MAX, 50, 10, 1, 0), (0, 4, 50, 10, 1, 0), (4, 4, 102, 10, 1, 0), (4, 4, 50, 10, 0, 0), (4, 4, 50, 32, 0, 0), (4, 4, 50, 10, 1, 5)] + [(u32::MAX, u32::MAX, 50, 10, 1, 0), (0, 4, 50, 10, 1, 0), (4, 4, 102, 10, 1, 0), (4, 4, 50, 32, 0, 0), (4, 4, 50, 10, 1, 5)] { let mut b = dpx_header(w, h, d, bits, p, o); b.extend(std::iter::repeat_n(0, 64)); - assert!(probe("h.dpx", &b).is_err() && decode("h.dpx", &b).is_err()); + assert!(probe("h.dpx", &b).is_err() && decode("h.dpx", &b).is_err(), "{w}x{h} {d} {bits} {p} {o}"); } + // 8192 × 8193 is past this module's own cap, which is below craft-dpx's default. + let mut big = dpx_header(8192, 8193, 6, 8, 0, 0); + big.extend(std::iter::repeat_n(0, 64)); + assert!(probe("big.dpx", &big).is_err()); // run-length encoding and offsets past the end are refused let mut rle = good.clone(); rle[806..808].copy_from_slice(&1u16.to_be_bytes()); diff --git a/crates/media/src/exr_channels.rs b/crates/media/src/exr_channels.rs index d0acf590f..96b0173cd 100644 --- a/crates/media/src/exr_channels.rs +++ b/crates/media/src/exr_channels.rs @@ -31,35 +31,15 @@ use crate::convert::{AlphaOp, float_to_image}; /// stop at the same size). const MAX_DISPLAY_PIXELS: usize = 1 << 28; -fn is_depth(name: &str) -> bool { - let last = name.rsplit('.').next().unwrap_or(name); - last.eq_ignore_ascii_case("z") || name.to_ascii_lowercase().contains("depth") -} - -/// Full plane name of a channel in a part: `part.channel`, except that Blender 5 writes one part -/// per pass whose channels already carry the full name (part `ViewLayer.Depth` holds -/// `ViewLayer.Depth.Z`), which is kept as is instead of doubling the prefix. -fn channel_name(part: Option<&str>, channel: &str) -> String { - match part { - Some(p) if channel.strip_prefix(p).is_some_and(|rest| rest.starts_with('.')) => channel.to_string(), - Some(p) => format!("{p}.{channel}"), - None => channel.to_string(), - } -} +// Channel naming and the Cryptomatte manifest are `craft-exr`'s. +use craft_exr::channels::{is_depth, part_channel_name as channel_name}; +pub use craft_exr::cryptomatte::parse_manifest; /// The part name channels are prefixed with (`None`: unnamed). fn part_name(header: &Header) -> Option { header.own_attributes.layer_name.as_ref().map(|t| t.to_string()).filter(|s| !s.is_empty()) } -/// Parse a Cryptomatte manifest (`{"name": "hexhash", …}`). -pub fn parse_manifest(json: &str) -> Vec<(String, u32)> { - let Ok(serde_json::Value::Object(m)) = serde_json::from_str::(json) else { return vec![] }; - let mut v: Vec<(String, u32)> = m.iter().filter_map(|(k, h)| Some((k.clone(), u32::from_str_radix(h.as_str()?.trim(), 16).ok()?))).collect(); - v.sort(); - v -} - /// Why an OpenEXR file's pixels can't be decoded when its headers name a compression this build /// can't decompress (HTJ2K, OpenEXR 3.4's High-Throughput JPEG 2000): the decoders only said /// "no non-deep rgb channels" or showed a transparent frame (#482). `None` for other files. diff --git a/crates/media/src/gif_anim.rs b/crates/media/src/gif_anim.rs index d201c8b7e..8453b50ac 100644 --- a/crates/media/src/gif_anim.rs +++ b/crates/media/src/gif_anim.rs @@ -43,18 +43,11 @@ pub(crate) fn gcd(a: u32, b: u32) -> u32 { } /// Describe an animated GIF as a movie. `None` for a GIF with fewer than two frames (a still) or -/// one whose headers can't be read. +/// one whose headers can't be read. A damaged tail keeps the frames before it. pub(crate) fn probe(path: &str, bytes: &[u8]) -> Option { - let mut dec = gif::DecodeOptions::new().read_info(Cursor::new(bytes)).ok()?; - let (width, height) = (u32::from(dec.width()), u32::from(dec.height())); - let mut delays: Vec = Vec::new(); - while delays.len() < MAX_FRAMES { - match dec.next_frame_info() { - Ok(Some(f)) => delays.push(delay_cs(u32::from(f.delay))), - // The end, or a damaged tail: keep the frames before it. - _ => break, - } - } + let info = craft_gif::scan(bytes, MAX_FRAMES)?; + let (width, height) = (u32::from(info.width), u32::from(info.height)); + let delays: Vec = info.frames.iter().map(|f| delay_cs(u32::from(f.delay_cs))).collect(); if delays.len() < 2 || width == 0 || height == 0 { return None; } diff --git a/crates/media/src/webp_anim.rs b/crates/media/src/webp_anim.rs index f0784d1e3..147fe8264 100644 --- a/crates/media/src/webp_anim.rs +++ b/crates/media/src/webp_anim.rs @@ -23,7 +23,7 @@ pub(crate) const CODEC: &str = "WebP"; /// Whether `bytes` start like a WebP file. pub(crate) fn is_webp(bytes: &[u8]) -> bool { - bytes.get(0..4) == Some(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") + craft_webp::is_webp(bytes) } /// What the chunk headers of an animated WebP say. @@ -35,46 +35,11 @@ struct Header { delays: Vec, } -fn u24(b: &[u8]) -> Option { - match b { - [a, b, c, ..] => Some(u32::from(*a) | u32::from(*b) << 8 | u32::from(*c) << 16), - _ => None, - } -} - /// Read the `VP8X` header and the `ANMF` frame headers. `None` when the file isn't an animated /// WebP. A truncated tail keeps the frames before it. fn header(bytes: &[u8]) -> Option
{ - if !is_webp(bytes) { - return None; - } - let riff = bytes.get(4..8).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; - let end = usize::try_from(riff).ok()?.saturating_add(8).min(bytes.len()); - let (mut at, mut canvas, mut delays) = (12usize, None, Vec::new()); - while delays.len() < MAX_FRAMES { - let Some(head) = bytes.get(at..at.saturating_add(8)).filter(|_| at.saturating_add(8) <= end) else { break }; - let size = head.get(4..8).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; - let size = usize::try_from(size).ok()?; - let body_end = at.saturating_add(8).saturating_add(size); - let Some(body) = bytes.get(at.saturating_add(8)..body_end).filter(|_| body_end <= end) else { break }; - match head.get(0..4) { - Some(b"VP8X") => { - let flags = *body.first()?; - if flags & 0x02 == 0 { - // No animation flag: a still. - return None; - } - let w = u24(body.get(4..)?)?.saturating_add(1); - let h = u24(body.get(7..)?)?.saturating_add(1); - canvas = Some((w, h, flags & 0x10 != 0)); - } - Some(b"ANMF") if body.len() >= 16 => delays.push(u24(body.get(12..)?)?), - _ => {} - } - at = body_end.saturating_add(size & 1); - } - let (width, height, alpha) = canvas?; - Some(Header { width, height, alpha, delays }) + let info = craft_webp::scan(bytes, MAX_FRAMES).filter(|i| i.animated)?; + Some(Header { width: info.width, height: info.height, alpha: info.alpha, delays: info.frames.iter().map(|f| f.duration_ms).collect() }) } /// The delay of a frame in milliseconds. Browsers show delays of 10 ms or less (that encoders diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index ebe7da7e8..1dfa79430 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "effectcraft-model" -description = "3D models: glTF 2.0 (.gltf/.glb), Wavefront OBJ/MTL, STL and FBX 7.x (binary and ASCII) import, PBR metallic-roughness materials, node hierarchy, skinning and animation, parametric primitives, and extruded/bevelled outline meshes" +description = "3D models: glTF 2.0 (.gltf/.glb), Wavefront OBJ/MTL, STL and FBX 6.x/7.x (binary and ASCII) import through craft-mesh, PBR metallic-roughness materials, node hierarchy, skinning and animation, parametric primitives, and extruded/bevelled outline meshes" version.workspace = true edition.workspace = true license.workspace = true @@ -10,10 +10,9 @@ rust-version.workspace = true workspace = true [dependencies] +craft-mesh = { workspace = true } effectcraft-geom = { workspace = true } serde = { workspace = true } -serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } image = { workspace = true } -miniz_oxide = "0.9" diff --git a/crates/model/src/fbx.rs b/crates/model/src/fbx.rs index 4f952847c..fead03b21 100644 --- a/crates/model/src/fbx.rs +++ b/crates/model/src/fbx.rs @@ -1,1017 +1,34 @@ -//! FBX 7.x scenes, binary and ASCII. -//! -//! Written from public descriptions of the format (the binary node-record layout, the ASCII -//! syntax, and the scene objects of the Autodesk FBX SDK documentation): no importer source was -//! read. -//! -//! - **Binary**: the `Kaydara FBX Binary` header and version, node records with 32-bit (before -//! 7.5) or 64-bit offsets, every property type (`Y C I F D L S R` and the `f d l i b` arrays, -//! zlib-compressed or not). Object names `Name\0\x01Class` become `Class::Name` as in ASCII. -//! - **ASCII**: `Key: value, value { children }` with `;` comments and `*N { a: … }` arrays. -//! - **Scene**: `Geometry` meshes (`Vertices`, `PolygonVertexIndex` polygons fan-triangulated, -//! the first `LayerElementNormal`, `LayerElementUV` and `LayerElementMaterial` with every -//! mapping and reference mode), `Model` nodes with the SDK transform (translation, rotation -//! offset and pivot, pre/post rotation, Euler rotation in its order, scaling offset and pivot, -//! scaling) and geometric transforms, `Material` (Lambert/Phong mapped onto -//! metallic-roughness), `Texture` and `Video` (embedded or relative image files), joined by -//! `Connections`. `GlobalSettings` axes turn the scene to +Y up. -//! -//! Not imported: FBX 6.x and older, animation stacks, skin deformers, blend shapes, cameras and -//! lights, NURBS and patches. Units stay the file's own (like OBJ). +//! FBX 6.x and 7.x scenes, binary and ASCII, read with `craft-mesh` (`craft_mesh::fbx`): +//! `Geometry` meshes, `Model` nodes with the SDK transform and geometric transforms, `Material` +//! (Lambert/Phong mapped onto metallic-roughness), embedded or relative `Texture` images, +//! joined by `Connections`. A root node turns the file's `GlobalSettings` axes to +Y up; units +//! stay the file's own (like OBJ). Meshes without normals get smooth ones. -use std::collections::HashMap; -use std::sync::Arc; +use crate::scene::{MissingNormals, error, limits, mat4, to_model}; +use crate::{Model, ModelError, Node, Result}; -use crate::obj::srgb_to_linear; -use crate::{AlphaMode, Mat4, Material, Mesh, Model, ModelError, Node, Primitive, Result, TexRef, Texture, perr, vec3}; +pub use craft_mesh::fbx::BINARY_MAGIC; -/// The binary file's magic (`Kaydara FBX Binary`, two spaces, NUL, 0x1A, 0x00). -pub const BINARY_MAGIC: &[u8] = b"Kaydara FBX Binary \0\x1a\0"; - -/// Deepest node nesting accepted (real files nest well under 10 levels). -const MAX_DEPTH: usize = 64; -/// Largest decoded array accepted (bytes). -const MAX_ARRAY_BYTES: usize = 1 << 30; -/// Most memory one import may keep: parsed arrays as stored (8 bytes per element, whatever the -/// wire type) plus the meshes built from them (#1234). -const MAX_IMPORT_BYTES: usize = 1 << 31; - -/// Most pixels one texture may hold (8192 × 8192) and all the textures of one import together -/// (2^29: 8 GiB as float RGBA, thirty-two 4K maps). A texture past a limit is left out and the -/// import says so. -const MAX_TEXTURE_PIXELS: u64 = 1 << 26; -const MAX_TEXTURE_IMPORT_PIXELS: u64 = 1 << 29; - -/// What is left of an import's memory budget. -struct Budget(std::cell::Cell); - -impl Budget { - fn new(bytes: usize) -> Budget { - Budget(std::cell::Cell::new(bytes)) - } - /// Take `bytes` (None: a size that overflowed) from the budget, or fail the import before - /// anything that large is allocated. - fn take(&self, bytes: Option, what: &str) -> Result<()> { - let left = self.0.get(); - match bytes.filter(|&b| b <= left) { - Some(b) => { - self.0.set(left - b); - Ok(()) - } - None => Err(perr(format!("FBX: {what} would take the import past its {} MiB memory limit", MAX_IMPORT_BYTES >> 20))), - } - } -} - -/// Bytes a mesh keeps. -fn mesh_bytes(m: &Mesh) -> Option { - m.primitives.iter().try_fold(0usize, |acc, p| { - let n = p.positions.len().checked_mul(12)?.checked_add(p.normals.len().checked_mul(12)?)?.checked_add(p.uvs.len().checked_mul(8)?)?; - let n = n.checked_add(p.tangents.len().checked_mul(16)?)?.checked_add(p.joints.len().checked_mul(8)?)?.checked_add(p.weights.len().checked_mul(16)?)?; - acc.checked_add(n)?.checked_add(p.indices.len().checked_mul(4)?) - }) -} - -/// Bytes the values under `nodes` keep. Used for ASCII files, which hold array elements as -/// one `Prop` each and are parsed before they can be counted (the text itself bounds them). -fn value_bytes(nodes: &[FbxNode]) -> Option { - nodes.iter().try_fold(0usize, |acc, n| { - let own = n.props.iter().try_fold(0usize, |a, p| { - let extra = match p { - Prop::Ints(v) => v.len().checked_mul(8)?, - Prop::Floats(v) => v.len().checked_mul(8)?, - Prop::Str(v) => v.len(), - Prop::Bytes(v) => v.len(), - Prop::Int(_) | Prop::Float(_) => 0, - }; - a.checked_add(std::mem::size_of::())?.checked_add(extra) - })?; - acc.checked_add(own)?.checked_add(value_bytes(&n.children)?) - }) -} - -/// One property value of an FBX node. -#[derive(Clone, Debug, PartialEq)] -pub enum Prop { - Int(i64), - Float(f64), - Str(String), - Bytes(Vec), - Ints(Vec), - Floats(Vec), -} - -impl Prop { - fn as_f64(&self) -> Option { - match self { - Prop::Int(i) => Some(*i as f64), - Prop::Float(f) => Some(*f), - _ => None, - } - } - fn as_i64(&self) -> Option { - match self { - Prop::Int(i) => Some(*i), - Prop::Float(f) if f.is_finite() => Some(*f as i64), - _ => None, - } - } - fn as_str(&self) -> Option<&str> { - match self { - Prop::Str(s) => Some(s), - _ => None, - } - } -} - -/// A node of the FBX document tree (the same for binary and ASCII files). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct FbxNode { - pub name: String, - pub props: Vec, - pub children: Vec, -} - -impl FbxNode { - pub fn child(&self, name: &str) -> Option<&FbxNode> { - self.children.iter().find(|c| c.name == name) - } - pub fn children_named<'a>(&'a self, name: &'a str) -> impl Iterator + 'a { - self.children.iter().filter(move |c| c.name == name) - } - fn prop(&self, i: usize) -> Option<&Prop> { - self.props.get(i) - } - fn str_at(&self, i: usize) -> Option<&str> { - self.prop(i).and_then(Prop::as_str) - } - /// The node's array as floats: a binary array property, an ASCII `a:` child, or the plain - /// value list. - pub fn floats(&self) -> Vec { - if let Some(a) = self.child("a") { - return a.floats(); - } - let mut out = vec![]; - for p in &self.props { - match p { - Prop::Floats(v) => out.extend_from_slice(v), - Prop::Ints(v) => out.extend(v.iter().map(|&i| i as f64)), - Prop::Int(i) => out.push(*i as f64), - Prop::Float(f) => out.push(*f), - _ => {} - } - } - out - } - /// The node's array as integers (see [`FbxNode::floats`]). - pub fn ints(&self) -> Vec { - if let Some(a) = self.child("a") { - return a.ints(); - } - let mut out = vec![]; - for p in &self.props { - match p { - Prop::Ints(v) => out.extend_from_slice(v), - Prop::Floats(v) => out.extend(v.iter().filter(|f| f.is_finite()).map(|&f| f as i64)), - p => out.extend(p.as_i64()), - } - } - out - } -} - -/// Read an FBX file (binary or ASCII) into its top-level nodes and the file version -/// (e.g. 7400). -pub fn read(bytes: &[u8]) -> Result<(u32, Vec)> { - read_within(bytes, &Budget::new(MAX_IMPORT_BYTES)) -} - -fn read_within(bytes: &[u8], budget: &Budget) -> Result<(u32, Vec)> { - if bytes.starts_with(BINARY_MAGIC) { - read_binary(bytes, budget) - } else { - let (version, nodes) = read_ascii(&String::from_utf8_lossy(bytes))?; - budget.take(value_bytes(&nodes), "its values")?; - Ok((version, nodes)) - } -} - -// --------------------------------------------------------------------------------------------- -// Binary - -struct Bin<'a> { - d: &'a [u8], - /// 64-bit record offsets (version 7500 and later). - wide: bool, - budget: &'a Budget, -} - -impl Bin<'_> { - fn take(&self, pos: &mut usize, n: usize) -> Result<&[u8]> { - let end = pos.checked_add(n).ok_or_else(|| perr("FBX: offset overflow"))?; - let s = self.d.get(*pos..end).ok_or_else(|| perr(format!("FBX: truncated at byte {pos}")))?; - *pos = end; - Ok(s) - } - fn arr(&self, pos: &mut usize) -> Result<[u8; N]> { - let s = self.take(pos, N)?; - let mut a = [0u8; N]; - a.copy_from_slice(s); - Ok(a) - } - fn u32(&self, pos: &mut usize) -> Result { - Ok(u32::from_le_bytes(self.arr(pos)?)) - } - fn offset(&self, pos: &mut usize) -> Result { - if self.wide { Ok(u64::from_le_bytes(self.arr(pos)?)) } else { Ok(self.u32(pos)? as u64) } - } - fn to_usize(v: u64) -> Result { - usize::try_from(v).map_err(|_| perr("FBX: offset out of range")) - } - - /// Records until `end` or a null record. - fn list(&self, pos: &mut usize, end: usize, depth: usize) -> Result> { - if depth > MAX_DEPTH { - return Err(perr("FBX: nodes nested too deeply")); - } - let mut out = vec![]; - while *pos < end { - match self.record(pos, end, depth)? { - Some(n) => out.push(n), - None => break, - } - } - Ok(out) - } - - /// One node record ending within `limit` (the enclosing record's end); `None` for the null - /// record that closes a list. - fn record(&self, pos: &mut usize, limit: usize, depth: usize) -> Result> { - let start = *pos; - let end = Self::to_usize(self.offset(pos)?)?; - let nprops = self.offset(pos)?; - let plen = Self::to_usize(self.offset(pos)?)?; - let nlen = self.arr::<1>(pos)?[0] as usize; - if end == 0 && nprops == 0 && plen == 0 && nlen == 0 { - return Ok(None); - } - // A child reaching past its parent would be parsed again once the parent's end is - // restored. - if end <= start || end > limit.min(self.d.len()) { - return Err(perr(format!("FBX: bad record end {end} at byte {start}"))); - } - let name = String::from_utf8_lossy(self.take(pos, nlen)?).into_owned(); - let pstart = *pos; - let pend = pstart.checked_add(plen).filter(|&e| e <= end).ok_or_else(|| perr(format!("FBX: `{name}`: property list past the record")))?; - // Every property is at least one byte, so a count above the list length is corrupt. - if nprops > plen as u64 { - return Err(perr(format!("FBX: `{name}`: {nprops} properties in {plen} bytes"))); - } - let mut props = Vec::with_capacity(nprops as usize); - for _ in 0..nprops { - props.push(self.prop(pos, pend)?); - } - *pos = pend; - let children = if *pos < end { self.list(pos, end, depth + 1)? } else { vec![] }; - *pos = end; - Ok(Some(FbxNode { name, props, children })) - } - - fn prop(&self, pos: &mut usize, pend: usize) -> Result { - let sub = Bin { d: self.d.get(..pend).ok_or_else(|| perr("FBX: truncated property"))?, wide: self.wide, budget: self.budget }; - let t = sub.arr::<1>(pos)?[0]; - Ok(match t { - b'Y' => Prop::Int(i16::from_le_bytes(sub.arr(pos)?) as i64), - b'C' => Prop::Int((sub.arr::<1>(pos)?[0] != 0) as i64), - b'I' => Prop::Int(i32::from_le_bytes(sub.arr(pos)?) as i64), - b'L' => Prop::Int(i64::from_le_bytes(sub.arr(pos)?)), - b'F' => Prop::Float(f32::from_le_bytes(sub.arr(pos)?) as f64), - b'D' => Prop::Float(f64::from_le_bytes(sub.arr(pos)?)), - b'S' => { - let n = sub.u32(pos)? as usize; - Prop::Str(object_name(sub.take(pos, n)?)) - } - b'R' => { - let n = sub.u32(pos)? as usize; - Prop::Bytes(sub.take(pos, n)?.to_vec()) - } - b'f' | b'd' | b'l' | b'i' | b'b' => { - let len = sub.u32(pos)? as usize; - let enc = sub.u32(pos)?; - let clen = sub.u32(pos)? as usize; - let size = match t { - b'd' | b'l' => 8, - b'f' | b'i' => 4, - _ => 1, - }; - let want = len.checked_mul(size).filter(|&n| n <= MAX_ARRAY_BYTES).ok_or_else(|| perr("FBX: array too large"))?; - // Elements are kept as f64/i64 (booleans and 32-bit values widen), so the budget - // is charged for what is kept, not for the wire bytes. - sub.budget.take(len.checked_mul(8), "an array")?; - let data = sub.take(pos, clen)?; - let raw = match enc { - 0 => data.to_vec(), - // The status only: the error's Debug form prints what was decompressed. - 1 => miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, want).map_err(|e| perr(format!("FBX: array zlib: {:?}", e.status)))?, - e => return Err(perr(format!("FBX: unknown array encoding {e}"))), - }; - let raw = raw.get(..want).ok_or_else(|| perr("FBX: array shorter than its length"))?; - match t { - b'f' => Prop::Floats(raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect()), - b'd' => Prop::Floats(raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect()), - b'l' => Prop::Ints(raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c)).collect()), - b'i' => Prop::Ints(raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as i64).collect()), - _ => Prop::Ints(raw.iter().map(|&b| (b != 0) as i64).collect()), - } - } - t => return Err(perr(format!("FBX: unknown property type 0x{t:02x}"))), - }) - } -} - -/// Binary object names are `Name\0\x01Class`; ASCII writes `Class::Name`. -fn object_name(b: &[u8]) -> String { - let s = String::from_utf8_lossy(b); - match s.split_once("\0\x01") { - Some((name, class)) => format!("{class}::{name}"), - None => s.into_owned(), - } -} - -fn read_binary(bytes: &[u8], budget: &Budget) -> Result<(u32, Vec)> { - let mut pos = BINARY_MAGIC.len(); - let version = Bin { d: bytes, wide: false, budget }.u32(&mut pos)?; - let bin = Bin { d: bytes, wide: version >= 7500, budget }; - let mut nodes = vec![]; - while pos < bytes.len() { - match bin.record(&mut pos, bytes.len(), 0) { - Ok(Some(n)) => nodes.push(n), - Ok(None) => break, - // A damaged tail (footer, padding) after complete sections is ignored. - Err(_) if nodes.iter().any(|n| n.name == "Objects") => break, - Err(e) => return Err(e), - } - } - Ok((version, nodes)) -} - -// --------------------------------------------------------------------------------------------- -// ASCII - -#[derive(Clone, Debug, PartialEq)] -enum Tok { - Key(String), - Val(Prop), - /// `*N` array length (the values follow in an `a:` child). - Count, - Comma, - Open, - Close, -} - -fn tokenize(text: &str) -> Vec { - let mut out = vec![]; - let mut it = text.char_indices().peekable(); - while let Some(&(i, c)) = it.peek() { - match c { - c if c.is_whitespace() => { - it.next(); - } - ';' => { - for (_, c) in it.by_ref() { - if c == '\n' { - break; - } - } - } - ',' => { - it.next(); - out.push(Tok::Comma); - } - '{' => { - it.next(); - out.push(Tok::Open); - } - '}' => { - it.next(); - out.push(Tok::Close); - } - '"' => { - it.next(); - let start = i + 1; - let mut end = text.len(); - for (j, c) in it.by_ref() { - if c == '"' { - end = j; - break; - } - } - out.push(Tok::Val(Prop::Str(text.get(start..end).unwrap_or("").replace(""", "\"")))); - } - _ => { - let start = i; - let mut end = text.len(); - while let Some(&(j, c)) = it.peek() { - if c.is_whitespace() || matches!(c, ',' | '{' | '}' | '"' | ';' | ':') { - end = j; - break; - } - it.next(); - } - let word = text.get(start..end).unwrap_or(""); - if it.peek().is_some_and(|&(_, c)| c == ':') { - it.next(); - out.push(Tok::Key(word.to_string())); - } else if word.starts_with('*') { - out.push(Tok::Count); - } else if let Ok(i) = word.parse::() { - out.push(Tok::Val(Prop::Int(i))); - } else if let Ok(f) = word.parse::() { - out.push(Tok::Val(Prop::Float(f))); - } else if !word.is_empty() { - out.push(Tok::Val(Prop::Str(word.to_string()))); - } else { - // A stray `:` with no key. - it.next(); - } - } - } - } - out -} - -fn ascii_list(toks: &[Tok], i: &mut usize, depth: usize) -> Result> { - if depth > MAX_DEPTH { - return Err(perr("FBX: nodes nested too deeply")); - } - let mut out = vec![]; - while let Some(t) = toks.get(*i) { - *i += 1; - match t { - Tok::Close if depth > 0 => return Ok(out), - Tok::Key(name) => { - let mut node = FbxNode { name: name.clone(), ..FbxNode::default() }; - loop { - match toks.get(*i) { - Some(Tok::Val(v)) => node.props.push(v.clone()), - Some(Tok::Count | Tok::Comma) => {} - _ => break, - } - *i += 1; - } - if toks.get(*i) == Some(&Tok::Open) { - *i += 1; - node.children = ascii_list(toks, i, depth + 1)?; - } - out.push(node); - } - _ => {} - } - } - Ok(out) -} - -fn read_ascii(text: &str) -> Result<(u32, Vec)> { - let toks = tokenize(text); - let mut i = 0; - let nodes = ascii_list(&toks, &mut i, 0)?; - let version = nodes - .iter() - .find(|n| n.name == "FBXHeaderExtension") - .and_then(|h| h.child("FBXVersion")) - .and_then(|v| v.prop(0)) - .and_then(Prop::as_i64) - .and_then(|v| u32::try_from(v).ok()) - .unwrap_or(0); - Ok((version, nodes)) -} - -// --------------------------------------------------------------------------------------------- -// Scene - -/// `Properties70` entries by name (`P: name, type, label, flags, values…`). -struct Props70<'a>(HashMap<&'a str, &'a FbxNode>); - -impl<'a> Props70<'a> { - fn of(node: &'a FbxNode) -> Props70<'a> { - let mut m = HashMap::new(); - if let Some(p) = node.child("Properties70") { - for e in p.children_named("P") { - if let Some(name) = e.str_at(0) { - m.entry(name).or_insert(e); - } - } - } - Props70(m) - } - fn values(&self, name: &str) -> Vec { - self.0.get(name).map(|e| e.props.iter().skip(4).filter_map(Prop::as_f64).collect()).unwrap_or_default() - } - fn f(&self, name: &str) -> Option { - self.values(name).first().copied().filter(|v| v.is_finite()) - } - fn v3(&self, name: &str, default: [f64; 3]) -> [f64; 3] { - match self.values(name).as_slice() { - [x, y, z, ..] if x.is_finite() && y.is_finite() && z.is_finite() => [*x, *y, *z], - _ => default, - } - } -} - -/// An Euler rotation (degrees) in FBX rotation order (`eEulerXYZ` = 0 rotates about X first). -fn euler(d: [f64; 3], order: i64) -> Mat4 { - let (x, y, z) = (Mat4::rotate_x(d[0]), Mat4::rotate_y(d[1]), Mat4::rotate_z(d[2])); - match order { - 1 => y * z * x, - 2 => x * z * y, - 3 => z * x * y, - 4 => y * x * z, - 5 => x * y * z, - _ => z * y * x, - } -} - -fn translate(t: [f64; 3]) -> Mat4 { - Mat4::translate(vec3(t[0], t[1], t[2])) -} - -/// A Model's local transform: `T · Roff · Rp · Rpre · R · Rpost⁻¹ · Rp⁻¹ · Soff · Sp · S · Sp⁻¹`. -fn model_local(p: &Props70) -> Mat4 { - let order = p.f("RotationOrder").map_or(0, |o| o as i64); - let active = p.f("RotationActive").is_some_and(|a| a != 0.0); - let (pre, post) = - if active { (euler(p.v3("PreRotation", [0.0; 3]), 0), euler(p.v3("PostRotation", [0.0; 3]), 0).transpose()) } else { (Mat4::IDENTITY, Mat4::IDENTITY) }; - let rp = p.v3("RotationPivot", [0.0; 3]); - let sp = p.v3("ScalingPivot", [0.0; 3]); - let s = p.v3("Lcl Scaling", [1.0; 3]); - translate(p.v3("Lcl Translation", [0.0; 3])) - * translate(p.v3("RotationOffset", [0.0; 3])) - * translate(rp) - * pre - * euler(p.v3("Lcl Rotation", [0.0; 3]), order) - * post - * translate([-rp[0], -rp[1], -rp[2]]) - * translate(p.v3("ScalingOffset", [0.0; 3])) - * translate(sp) - * Mat4::scale(vec3(s[0], s[1], s[2])) - * translate([-sp[0], -sp[1], -sp[2]]) -} - -/// The geometric transform of a Model (applies to its geometry, not to its children). -fn geometric(p: &Props70) -> Option { - let t = p.v3("GeometricTranslation", [0.0; 3]); - let r = p.v3("GeometricRotation", [0.0; 3]); - let s = p.v3("GeometricScaling", [1.0; 3]); - if t == [0.0; 3] && r == [0.0; 3] && s == [1.0; 3] { - return None; - } - Some(translate(t) * euler(r, 0) * Mat4::scale(vec3(s[0], s[1], s[2]))) -} - -/// The file's axis system → +Y up, +Z front, +X right. -fn axis_matrix(settings: Option<&FbxNode>) -> Mat4 { - let p = settings.map(Props70::of); - let get = |name: &str, d: f64| p.as_ref().and_then(|p| p.f(name)).unwrap_or(d); - let axis = |a: f64, s: f64| -> Option<[f64; 4]> { - let a = a as i64; - let sign = if s < 0.0 { -1.0 } else { 1.0 }; - let mut v = [0.0; 4]; - *v.get_mut(usize::try_from(a).ok().filter(|&a| a < 3)?)? = sign; - Some(v) - }; - let (Some(right), Some(up), Some(front)) = ( - axis(get("CoordAxis", 0.0), get("CoordAxisSign", 1.0)), - axis(get("UpAxis", 1.0), get("UpAxisSign", 1.0)), - axis(get("FrontAxis", 2.0), get("FrontAxisSign", 1.0)), - ) else { - return Mat4::IDENTITY; - }; - let m = Mat4([right, up, front, [0.0, 0.0, 0.0, 1.0]]); - // Two axes on the same file axis: not a rotation. - let used = |k: usize| right[k] != 0.0 || up[k] != 0.0 || front[k] != 0.0; - if (0..3).all(used) { m } else { Mat4::IDENTITY } -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum Mapping { - PolygonVertex, - Vertex, - Polygon, - AllSame, -} - -/// A geometry layer element (normals, UVs, material indices). -struct LayerData { - mapping: Mapping, - data: Vec, - index: Option>, - width: usize, -} - -impl LayerData { - fn of(geom: &FbxNode, element: &str, data: &str, index: &str, width: usize) -> Option { - let e = geom.child(element)?; - let mapping = match e.child("MappingInformationType").and_then(|m| m.str_at(0)).unwrap_or("ByPolygonVertex") { - "ByPolygonVertex" => Mapping::PolygonVertex, - "ByVertex" | "ByVertice" | "ByControlPoint" => Mapping::Vertex, - "ByPolygon" => Mapping::Polygon, - "AllSame" => Mapping::AllSame, - _ => return None, - }; - let reference = e.child("ReferenceInformationType").and_then(|m| m.str_at(0)).unwrap_or("Direct"); - let index = (reference != "Direct").then(|| e.child(index).map(FbxNode::ints)).flatten(); - Some(LayerData { mapping, data: e.child(data)?.floats(), index, width }) - } - fn get(&self, pv: usize, v: usize, poly: usize) -> Option<&[f64]> { - let i = match self.mapping { - Mapping::PolygonVertex => pv, - Mapping::Vertex => v, - Mapping::Polygon => poly, - Mapping::AllSame => 0, - }; - let j = match &self.index { - Some(ix) => usize::try_from(*ix.get(i)?).ok()?, - None => i, - }; - let a = j.checked_mul(self.width)?; - self.data.get(a..a.checked_add(self.width)?) - } -} - -fn f32s(s: &[f64]) -> [f32; N] { - let mut a = [0.0f32; N]; - for (o, v) in a.iter_mut().zip(s) { - *o = if v.is_finite() { *v as f32 } else { 0.0 }; - } - a -} - -/// A Mesh geometry with its polygons triangulated; `materials[k]` is the model-level material -/// index of the geometry's material slot `k`. -fn build_mesh(name: &str, geom: &FbxNode, materials: &[usize], with_normal_maps: &dyn Fn(usize) -> bool) -> Option { - let positions: Vec<[f32; 3]> = geom.child("Vertices")?.floats().as_chunks::<3>().0.iter().map(|c| f32s::<3>(c)).collect(); - let pvi = geom.child("PolygonVertexIndex")?.ints(); - let normals = LayerData::of(geom, "LayerElementNormal", "Normals", "NormalsIndex", 3); - let uvs = LayerData::of(geom, "LayerElementUV", "UV", "UVIndex", 2); - let mats = geom.child("LayerElementMaterial").and_then(|e| { - let mapping = e.child("MappingInformationType").and_then(|m| m.str_at(0)).unwrap_or("AllSame"); - let ids = e.child("Materials")?.ints(); - Some((mapping == "ByPolygon", ids)) - }); - - type Key = (u32, [u32; 3], [u32; 2]); - let mut prims: Vec<(Option, Primitive, HashMap, Vec)> = vec![]; - let mut prim_of: HashMap, usize> = HashMap::new(); - let mut corners: Vec<(usize, usize)> = vec![]; - let mut poly = 0usize; - for (pv, &raw) in pvi.iter().enumerate() { - // The last corner of a polygon is stored as `-index - 1`. - let (v, last) = if raw < 0 { (!raw, true) } else { (raw, false) }; - corners.push((pv, usize::try_from(v).unwrap_or(usize::MAX))); - if !last { - continue; - } - let poly_corners = std::mem::take(&mut corners); - let p_index = poly; - poly += 1; - if poly_corners.len() < 3 || poly_corners.iter().any(|&(_, v)| v >= positions.len()) { - continue; - } - let slot = mats.as_ref().and_then(|(by_poly, ids)| { - let k = if *by_poly { *ids.get(p_index)? } else { *ids.first()? }; - materials.get(usize::try_from(k).ok()?).copied() - }); - let slot = slot.or_else(|| materials.first().copied()); - let at = *prim_of.entry(slot).or_insert_with(|| { - prims.push((slot, Primitive { material: slot, ..Default::default() }, HashMap::new(), vec![])); - prims.len() - 1 - }); - let Some((_, prim, map, need)) = prims.get_mut(at) else { continue }; - let mut ids = Vec::with_capacity(poly_corners.len()); - for &(pv, v) in &poly_corners { - let n = normals.as_ref().and_then(|l| l.get(pv, v, p_index)).map(f32s::<3>); - let t = uvs.as_ref().and_then(|l| l.get(pv, v, p_index)).map(f32s::<2>); - let key: Key = (v as u32, n.unwrap_or([f32::NAN; 3]).map(f32::to_bits), t.unwrap_or([f32::NAN; 2]).map(f32::to_bits)); - let id = *map.entry(key).or_insert_with(|| { - prim.positions.push(positions.get(v).copied().unwrap_or_default()); - prim.normals.push(n.unwrap_or_default()); - prim.uvs.push(t.unwrap_or_default()); - need.push(n.is_none()); - (prim.positions.len() - 1) as u32 - }); - ids.push(id); - } - for i in 2..ids.len() { - prim.indices.extend([ids[0], ids[i - 1], ids[i]]); - } - } - let mut mesh = Mesh { name: name.to_string(), primitives: vec![] }; - for (_, mut p, _, need) in prims { - if p.indices.is_empty() { - continue; - } - if need.iter().any(|&b| b) { - let given = p.normals.clone(); - p.compute_normals(); - for ((n, g), need) in p.normals.iter_mut().zip(given).zip(&need) { - if !need { - *n = g; - } - } - } - if uvs.is_none() { - p.uvs.clear(); - } else { - // FBX's v axis points up the image; textures are stored top row first. - for uv in p.uvs.iter_mut() { - uv[1] = 1.0 - uv[1]; - } - } - if p.material.is_some_and(with_normal_maps) { - p.compute_tangents(); - } - mesh.primitives.push(p); - } - (!mesh.primitives.is_empty()).then_some(mesh) -} - -/// Lambert/Phong surface properties onto metallic-roughness. -fn material(name: &str, node: &FbxNode) -> Material { - let p = Props70::of(node); - let phong = node.child("ShadingModel").and_then(|s| s.str_at(0)).is_some_and(|s| s.eq_ignore_ascii_case("phong")); - let factor = p.f("DiffuseFactor").unwrap_or(1.0); - let d = p.v3("DiffuseColor", p.v3("Diffuse", [0.8; 3])); - let alpha = match p.f("Opacity") { - Some(o) => o, - None => { - let tc = p.v3("TransparentColor", [0.0; 3]); - 1.0 - (tc[0] + tc[1] + tc[2]) / 3.0 * p.f("TransparencyFactor").unwrap_or(0.0) - } - } - .clamp(0.0, 1.0); - let lin = |c: f64| srgb_to_linear((c * factor).clamp(0.0, 1.0) as f32); - let e = p.v3("EmissiveColor", [0.0; 3]); - let ef = p.f("EmissiveFactor").unwrap_or(1.0); - let roughness = if phong { - let ns = p.f("ShininessExponent").or_else(|| p.f("Shininess")).unwrap_or(20.0).max(0.0); - (2.0 / (ns + 2.0)).sqrt() as f32 - } else { - 1.0 - }; - Material { - name: name.to_string(), - base_color: [lin(d[0]), lin(d[1]), lin(d[2]), alpha as f32], - metallic: 0.0, - roughness, - emissive: e.map(|c| srgb_to_linear((c * ef).clamp(0.0, 1.0) as f32)), - alpha_mode: if alpha < 0.999 { AlphaMode::Blend } else { AlphaMode::Opaque }, - ..Material::default() - } -} - -/// Decode standard base64 (ASCII FBX embeds `Video` content this way); `None` on bad input. -fn base64(s: &str) -> Option> { - let mut out = Vec::with_capacity(s.len() / 4 * 3); - let (mut acc, mut bits) = (0u32, 0u32); - for c in s.bytes() { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' => 62, - b'/' => 63, - b'=' => break, - c if c.is_ascii_whitespace() => continue, - _ => return None, - }; - acc = (acc << 6) | v as u32; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((acc >> bits) as u8); - acc &= (1 << bits) - 1; - } - } - Some(out) -} - -fn short_name(full: &str) -> &str { - full.split_once("::").map_or(full, |(_, n)| n) -} - -/// Parse an FBX file into a model. `resolve(uri)` reads texture files next to it. +/// Parse an FBX file; `resolve(path)` reads texture files the file names but does not embed. pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result { - parse_within(bytes, resolve, MAX_IMPORT_BYTES) -} - -/// [`parse`] keeping at most `limit` bytes of arrays and meshes. -fn parse_within(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, limit: usize) -> Result { - let budget = Budget::new(limit); - let (version, doc) = read_within(bytes, &budget)?; - if version != 0 && version < 7000 { - return Err(ModelError::Unsupported(format!("FBX {}.{} (only FBX 7.x files are read)", version / 1000, version % 1000 / 100))); + let limits = limits(); + let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(error)?; + let mut textures = |path: &str| resolve(path); + let scene = doc.scene(&limits, &mut textures).map_err(error)?; + if scene.meshes.is_empty() { + return Err(ModelError::Parse("FBX file without meshes".into())); } - let top = |name: &str| doc.iter().find(|n| n.name == name); - let objects = top("Objects").ok_or_else(|| perr("FBX: no Objects section"))?; - let by_id: HashMap = objects.children.iter().filter_map(|o| Some((o.prop(0)?.as_i64()?, o))).collect(); - let kind = |id: i64| by_id.get(&id).map(|n| n.name.as_str()); - - // Connections: (child, parent, property) in file order. - let mut links: Vec<(i64, i64, Option<&str>)> = vec![]; - if let Some(c) = top("Connections") { - for e in c.children_named("C") { - let (Some(a), Some(b)) = (e.prop(1).and_then(Prop::as_i64), e.prop(2).and_then(Prop::as_i64)) else { continue }; - links.push((a, b, e.str_at(3))); - } + let mut m = to_model(scene, MissingNormals::Smooth, &|_| None)?; + // The axes node goes first: every node index moves up by one. + for n in &mut m.nodes { + n.children.iter_mut().for_each(|c| *c += 1); } - // The same links by parent, so each object finds its children without scanning them all. - let mut children_of: HashMap)>> = HashMap::new(); - for &(a, b, prop) in &links { - children_of.entry(b).or_default().push((a, prop)); - } - let children_of = |id: i64| children_of.get(&id).map(Vec::as_slice).unwrap_or_default().iter().copied(); - - let model_ids: Vec = objects.children.iter().filter(|o| o.name == "Model").filter_map(|o| o.prop(0)?.as_i64()).collect(); - let mut node_of: HashMap = HashMap::new(); - let mut nodes = vec![Node { name: "FBX axes".into(), matrix: Some(axis_matrix(top("GlobalSettings"))), ..Node::default() }]; - for &id in &model_ids { - if node_of.contains_key(&id) { - continue; - } - let Some(o) = by_id.get(&id) else { continue }; - let name = short_name(o.str_at(1).unwrap_or("")).to_string(); - node_of.insert(id, nodes.len()); - nodes.push(Node { name, matrix: Some(model_local(&Props70::of(o))), ..Node::default() }); - } - - // Hierarchy: the first Model→Model link is the parent; anything else hangs off the root. - let mut parent: HashMap = HashMap::new(); - for &(c, p, _) in &links { - if let (Some(&ci), Some(&pi)) = (node_of.get(&c), node_of.get(&p)) - && ci != pi - { - parent.entry(ci).or_insert(pi); - } - } - for i in 1..nodes.len() { - let p = parent.get(&i).copied().unwrap_or(0); - if let Some(n) = nodes.get_mut(p) { - n.children.push(i); - } - } - - // Materials (in first-use order) and their textures. - let mut materials: Vec = vec![]; - let mut textures: Vec> = vec![]; - let mut material_of: HashMap = HashMap::new(); - let mut texture_of: HashMap> = HashMap::new(); - // Decoded images by the source actually used (embedded Video id, else the resolved file - // name): Texture objects aliasing one image share its pixels instead of each keeping a copy. - let mut image_of: HashMap<(Option, String), Option> = HashMap::new(); - // Textures have their own allowance (pixels, as `Texture::decode_within` counts them); the - // memory budget is for the file's own records. - let mut texture_pixels_left = MAX_TEXTURE_IMPORT_PIXELS; - let mut warnings: Vec = vec![]; - // Ok(None): no usable image (the material goes untextured). Err: the memory budget ran out. - let mut load_texture = |tid: i64, textures: &mut Vec>| -> Result> { - if let Some(t) = texture_of.get(&tid) { - return Ok(*t); - } - let Some(tex) = by_id.get(&tid) else { - texture_of.insert(tid, None); - return Ok(None); - }; - let videos: Vec = children_of(tid).filter(|l| kind(l.0) == Some("Video")).map(|l| l.0).collect(); - let files: Vec = ["RelativeFilename", "FileName"].iter().filter_map(|k| Some(tex.child(k)?.str_at(0)?.replace('\\', "/"))).collect(); - let embedded = videos.iter().find_map(|&v| { - let content = by_id.get(&v)?.child("Content")?; - let bytes = match content.props.first()? { - Prop::Bytes(b) if !b.is_empty() => Some(b.clone()), - Prop::Str(_) => { - let s: String = content.props.iter().filter_map(Prop::as_str).collect(); - base64(&s).filter(|b| !b.is_empty()) - } - _ => None, - }?; - Some(((Some(v), String::new()), bytes)) - }); - let source = embedded.or_else(|| { - files.iter().find_map(|f| { - let g = resolve(f).map(|b| (f.clone(), b)).or_else(|| { - let base = f.rsplit('/').next()?; - Some((base.to_string(), resolve(base)?)) - })?; - Some(((None, g.0), g.1)) - }) - }); - let t = match source { - None => None, - Some((key, bytes)) => match image_of.get(&key) { - Some(i) => *i, - None => { - // Charge the decoded size before decoding, so a small file claiming huge - // dimensions is refused before its pixels are allocated. A texture past the - // limits is left out (the material goes untextured) and the import says so. - let loaded = Texture::dimensions(&bytes).and_then(|(w, h)| { - let pixels = u64::from(w) * u64::from(h); - if pixels > MAX_TEXTURE_PIXELS { - return Err(perr(format!("a {w}×{h} texture (at most {MAX_TEXTURE_PIXELS} pixels)"))); - } - if pixels > texture_pixels_left { - return Err(perr(format!("a {w}×{h} texture: the model's textures would hold more than {MAX_TEXTURE_IMPORT_PIXELS} pixels"))); - } - let t = Texture::decode(&bytes)?; - texture_pixels_left -= pixels; - Ok(t) - }); - let i = match loaded { - Ok(t) => { - textures.push(Arc::new(t)); - Some(textures.len() - 1) - } - Err(e) => { - log::warn!("model: FBX texture left out: {e}"); - warnings.push(format!("texture left out: {e}")); - None - } - }; - image_of.insert(key, i); - i - } - }, - }; - texture_of.insert(tid, t); - Ok(t) - }; - let mut material_index = |mid: i64, materials: &mut Vec, textures: &mut Vec>| -> Result> { - if let Some(&m) = material_of.get(&mid) { - return Ok(Some(m)); - } - let Some(node) = by_id.get(&mid) else { return Ok(None) }; - let mut m = material(short_name(node.str_at(1).unwrap_or("")), node); - for (tid, prop) in children_of(mid).filter(|l| kind(l.0) == Some("Texture")) { - let slot = match prop { - Some("DiffuseColor") => &mut m.base_color_tex, - Some("NormalMap") => &mut m.normal_tex, - Some("EmissiveColor") => &mut m.emissive_tex, - _ => continue, - }; - if slot.is_none() { - *slot = load_texture(tid, textures)?.map(|texture| TexRef { texture, uv_set: 0 }); - } - } - if m.emissive_tex.is_some() && m.emissive == [0.0; 3] { - m.emissive = [1.0; 3]; - } - materials.push(m); - material_of.insert(mid, materials.len() - 1); - Ok(Some(materials.len() - 1)) - }; - - // One mesh per Model with Mesh geometry (material slots are per Model). Models instancing the - // same geometry with the same materials share one mesh rather than each building a copy. - let mut meshes: Vec = vec![]; - let mut mesh_of: HashMap<(i64, Vec), usize> = HashMap::new(); - for &id in &model_ids { - let Some(&ni) = node_of.get(&id) else { continue }; - let Some(gid) = children_of(id).find(|l| kind(l.0) == Some("Geometry")).map(|l| l.0) else { continue }; - let Some(geom) = by_id.get(&gid) else { continue }; - let mut mats: Vec = vec![]; - for (mid, _) in children_of(id).filter(|l| kind(l.0) == Some("Material")) { - mats.extend(material_index(mid, &mut materials, &mut textures)?); - } - let name = nodes.get(ni).map(|n| n.name.clone()).unwrap_or_default(); - let mesh_index = match mesh_of.get(&(gid, mats.clone())) { - Some(&i) => i, - None => { - let normal_mapped: Vec = materials.iter().map(|m| m.normal_tex.is_some()).collect(); - let Some(mesh) = build_mesh(&name, geom, &mats, &|m| normal_mapped.get(m).copied().unwrap_or(false)) else { continue }; - budget.take(mesh_bytes(&mesh), &format!("mesh `{name}`"))?; - meshes.push(mesh); - mesh_of.insert((gid, mats), meshes.len() - 1); - meshes.len() - 1 - } - }; - let geo = by_id.get(&id).and_then(|o| geometric(&Props70::of(o))); - match geo { - Some(matrix) => { - nodes.push(Node { name: format!("{name} geometry"), matrix: Some(matrix), mesh: Some(mesh_index), ..Node::default() }); - let gi = nodes.len() - 1; - if let Some(n) = nodes.get_mut(ni) { - n.children.push(gi); - } - } - None => { - if let Some(n) = nodes.get_mut(ni) { - n.mesh = Some(mesh_index); - } - } - } - } - if meshes.is_empty() { - return Err(perr("FBX file without meshes")); - } - Ok(Model { meshes, nodes, roots: vec![0], materials, textures, warnings, ..Model::default() }) + m.skins.iter_mut().flat_map(|s| s.joints.iter_mut()).for_each(|j| *j += 1); + m.animations.iter_mut().flat_map(|a| a.channels.iter_mut()).for_each(|c| c.node += 1); + let roots = m.roots.iter().map(|r| r + 1).collect(); + m.nodes.insert(0, Node { name: "FBX axes".into(), matrix: Some(mat4(&doc.axes_to_y_up())), children: roots, ..Node::default() }); + m.roots = vec![0]; + Ok(m) } #[cfg(test)] diff --git a/crates/model/src/fbx/tests.rs b/crates/model/src/fbx/tests.rs index fcd34c4f0..399b16e2d 100644 --- a/crates/model/src/fbx/tests.rs +++ b/crates/model/src/fbx/tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::load; +use crate::{AlphaMode, load, vec3}; /// A Z-up scene: a Null parent with a mesh child (rotated, scaled, with a geometric offset) /// holding a quad and a triangle with a material each. @@ -131,116 +131,12 @@ fn check_scene(m: &Model) { assert!(close(lo, [8.0, 2.0, -2.0]) && close(hi, [10.0, 4.0, 0.0]), "{lo:?} {hi:?}"); } -/// A binary FBX of the same node tree (`a:` children become typed arrays). -fn write_binary(nodes: &[FbxNode], version: u32, compress: bool) -> Vec { - fn prop(out: &mut Vec, p: &Prop, compress: bool) { - let array = |out: &mut Vec, t: u8, len: usize, raw: Vec| { - out.push(t); - out.extend((len as u32).to_le_bytes()); - let data = if compress { miniz_oxide::deflate::compress_to_vec_zlib(&raw, 6) } else { raw }; - out.extend((compress as u32).to_le_bytes()); - out.extend((data.len() as u32).to_le_bytes()); - out.extend(data); - }; - match p { - Prop::Int(i) => match i32::try_from(*i) { - Ok(v) => { - out.push(b'I'); - out.extend(v.to_le_bytes()); - } - Err(_) => { - out.push(b'L'); - out.extend(i.to_le_bytes()); - } - }, - Prop::Float(f) => { - out.push(b'D'); - out.extend(f.to_le_bytes()); - } - Prop::Str(s) => { - let s = match s.split_once("::") { - Some((class, name)) => format!("{name}\0\x01{class}"), - None => s.clone(), - }; - out.push(b'S'); - out.extend((s.len() as u32).to_le_bytes()); - out.extend(s.as_bytes()); - } - Prop::Bytes(b) => { - out.push(b'R'); - out.extend((b.len() as u32).to_le_bytes()); - out.extend(b); - } - Prop::Ints(v) => array(out, b'i', v.len(), v.iter().flat_map(|&i| (i as i32).to_le_bytes()).collect()), - Prop::Floats(v) => array(out, b'd', v.len(), v.iter().flat_map(|f| f.to_le_bytes()).collect()), - } - } - fn record(out: &mut Vec, n: &FbxNode, wide: bool, compress: bool) { - let w = if wide { 8 } else { 4 }; - let start = out.len(); - out.extend(vec![0u8; 3 * w]); - out.push(n.name.len() as u8); - out.extend(n.name.as_bytes()); - let props = match n.child("a") { - Some(a) if a.props.iter().all(|p| matches!(p, Prop::Int(_))) => vec![Prop::Ints(a.ints())], - Some(a) => vec![Prop::Floats(a.floats())], - None => n.props.clone(), - }; - let pstart = out.len(); - for p in &props { - prop(out, p, compress); - } - let plen = out.len() - pstart; - let kids: Vec<&FbxNode> = n.children.iter().filter(|c| c.name != "a").collect(); - if !kids.is_empty() { - for k in kids { - record(out, k, wide, compress); - } - out.extend(vec![0u8; 3 * w + 1]); - } - let end = out.len(); - for (k, v) in [end, props.len(), plen].into_iter().enumerate() { - let at = start + k * w; - if wide { - out[at..at + 8].copy_from_slice(&(v as u64).to_le_bytes()); - } else { - out[at..at + 4].copy_from_slice(&(v as u32).to_le_bytes()); - } - } - } - let wide = version >= 7500; - let mut out = BINARY_MAGIC.to_vec(); - out.extend(version.to_le_bytes()); - for n in nodes { - record(&mut out, n, wide, compress); - } - out.extend(vec![0u8; if wide { 25 } else { 13 }]); - // Footer bytes after the closing null record. - out.extend([0xfa; 16]); - out -} - #[test] fn ascii_fbx_scene() { let m = load("scene.fbx", ASCII.as_bytes(), &|_| None).unwrap(); check_scene(&m); } -#[test] -fn binary_fbx_matches_ascii() { - let (_, doc) = read(ASCII.as_bytes()).unwrap(); - let ascii = parse(ASCII.as_bytes(), &|_| None).unwrap(); - for (version, compress) in [(7400, false), (7400, true), (7500, true)] { - let bin = write_binary(&doc, version, compress); - let (v, nodes) = read(&bin).unwrap(); - assert_eq!(v, version); - assert_eq!(nodes.iter().map(|n| n.name.as_str()).collect::>(), ["FBXHeaderExtension", "GlobalSettings", "Objects", "Connections"]); - // Found by its magic even without the extension. - let m = load("scene.bin", &bin, &|_| None).unwrap(); - assert_eq!(m, ascii, "version {version}, compressed {compress}"); - } -} - #[test] fn embedded_and_relative_textures() { let png = { @@ -291,91 +187,6 @@ fn b64(b: &[u8]) -> String { s } -#[test] -fn hostile_fbx_files_fail_cleanly() { - let (_, doc) = read(ASCII.as_bytes()).unwrap(); - let bin = write_binary(&doc, 7500, true); - // Every truncation and every single-byte corruption returns (no panic, no runaway). - for n in 0..bin.len() { - let _ = parse(&bin[..n], &|_| None); - } - for i in 0..bin.len() { - let mut b = bin.clone(); - b[i] ^= 0xff; - let _ = parse(&b, &|_| None); - } - // An array claiming 4 G elements. - let mut huge = BINARY_MAGIC.to_vec(); - huge.extend(7400u32.to_le_bytes()); - let body: Vec = b"d".iter().copied().chain(u32::MAX.to_le_bytes()).chain(0u32.to_le_bytes()).chain(8u32.to_le_bytes()).chain([0u8; 8]).collect(); - let start = huge.len(); - let end = start + 13 + 1 + body.len(); - huge.extend((end as u32).to_le_bytes()); - huge.extend(1u32.to_le_bytes()); - huge.extend((body.len() as u32).to_le_bytes()); - huge.push(1); - huge.push(b'V'); - huge.extend(body); - assert!(read(&huge).is_err()); - // Deep nesting, both encodings. - assert!(read("A: {".repeat(100_000).as_bytes()).is_err()); - // Not an FBX scene at all, an old FBX version, and a scene without meshes. - assert!(parse(b"\x00\x01garbage", &|_| None).is_err()); - let v6 = "FBXHeaderExtension: {\n FBXVersion: 6100\n}\nObjects: {\n}\n"; - assert!(matches!(parse(v6.as_bytes(), &|_| None), Err(ModelError::Unsupported(_)))); - assert!(parse(b"Objects: {\n Model: 1, \"Model::Empty\", \"Null\" {\n }\n}\n", &|_| None).is_err()); -} - -/// A version-7400 binary FBX holding one top-level node `A` with uncompressed arrays of type -/// `t` (`b'b'`, `b'i'`, `b'f'`, `b'd'`, `b'l'`) and `len` elements each. -fn binary_arrays(arrays: &[(u8, usize)]) -> Vec { - let mut props = vec![]; - for &(t, len) in arrays { - let size = match t { - b'd' | b'l' => 8, - b'f' | b'i' => 4, - _ => 1, - }; - props.push(t); - props.extend((len as u32).to_le_bytes()); - props.extend(0u32.to_le_bytes()); - props.extend(((len * size) as u32).to_le_bytes()); - props.extend(std::iter::repeat_n(1u8, len * size)); - } - let mut out = BINARY_MAGIC.to_vec(); - out.extend(7400u32.to_le_bytes()); - let end = out.len() + 13 + 1 + props.len(); - out.extend((end as u32).to_le_bytes()); - out.extend((arrays.len() as u32).to_le_bytes()); - out.extend((props.len() as u32).to_le_bytes()); - out.push(1); - out.push(b'A'); - out.extend(props); - out -} - -#[test] -fn fbx_arrays_are_charged_for_the_memory_they_keep() { - // A boolean array is one byte per element on the wire but eight once kept as `Prop::Ints`: - // the budget counts the eight (#1234). - let n = 10_000; - let bin = binary_arrays(&[(b'b', n)]); - assert!(read_within(&bin, &Budget::new(n * 8)).is_ok()); - let e = read_within(&bin, &Budget::new(n * 8 - 1)).unwrap_err(); - assert!(e.to_string().contains("memory limit"), "{e}"); - // 32-bit floats widen to f64 the same way. - assert!(read_within(&binary_arrays(&[(b'f', n)]), &Budget::new(n * 4)).is_err()); - // Several arrays each within the budget but not together. - let bin = binary_arrays(&[(b'i', n), (b'd', n), (b'b', n)]); - assert!(read_within(&bin, &Budget::new(n * 24)).is_ok()); - assert!(read_within(&bin, &Budget::new(n * 20)).is_err()); - // ASCII values count too. - let (_, doc) = read(ASCII.as_bytes()).unwrap(); - let values = value_bytes(&doc).unwrap(); - assert!(values > 45 * std::mem::size_of::(), "{values}"); - assert!(parse_within(ASCII.as_bytes(), &|_| None, values - 1).unwrap_err().to_string().contains("memory limit")); -} - /// [`ASCII`] with two more Models instancing its geometry: `Copy` with the same two materials, /// `Red only` with just the first. fn instanced_scene() -> String { @@ -401,27 +212,6 @@ fn fbx_models_instancing_one_geometry_share_its_mesh() { assert_eq!(mesh_of("Shape"), mesh_of("Copy"), "same geometry and materials: one mesh"); assert_ne!(mesh_of("Shape"), mesh_of("Red only"), "different materials: its own mesh"); assert_eq!(m.meshes.len(), 2); - // A budget with room for one copy of the geometry's mesh, but not three, still imports. - let one = parse(ASCII.as_bytes(), &|_| None).unwrap(); - let mesh = mesh_bytes(&one.meshes[0]).unwrap(); - let (_, doc) = read(instanced_scene().as_bytes()).unwrap(); - let values = value_bytes(&doc).unwrap(); - assert!(parse_within(instanced_scene().as_bytes(), &|_| None, values + 2 * mesh).is_ok()); - assert!(parse_within(instanced_scene().as_bytes(), &|_| None, values + mesh).is_err()); -} - -#[test] -fn binary_child_record_past_its_parent_is_an_error() { - let parent = FbxNode { name: "P".into(), props: vec![], children: vec![FbxNode { name: "C".into(), props: vec![], children: vec![] }] }; - let after = FbxNode { name: "Q".into(), props: vec![Prop::Int(1)], children: vec![] }; - let mut bin = write_binary(&[parent, after], 7400, false); - assert_eq!(read(&bin).unwrap().1.len(), 2); - // `P` starts after the magic and version; `C` after P's 12-byte header, name length and name. - let p = BINARY_MAGIC.len() + 4; - let p_end = u32::from_le_bytes(bin[p..p + 4].try_into().unwrap()); - let c = p + 14; - bin[c..c + 4].copy_from_slice(&(p_end + 1).to_le_bytes()); - assert!(read(&bin).unwrap_err().to_string().contains("bad record end")); } #[test] @@ -448,11 +238,6 @@ Connections: {"#; 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))); - // Textures have their own allowance: a tight record budget does not drop them. - let (_, nodes) = read(doc.as_bytes()).unwrap(); - let values = value_bytes(&nodes).unwrap(); - let mesh = mesh_bytes(&m.meshes[0]).unwrap(); - assert_eq!(parse_within(doc.as_bytes(), &resolve, values + mesh).unwrap().textures.len(), 1); assert!(m.warnings.is_empty()); } diff --git a/crates/model/src/gltf.rs b/crates/model/src/gltf.rs index d55c39455..68bc86764 100644 --- a/crates/model/src/gltf.rs +++ b/crates/model/src/gltf.rs @@ -1,738 +1,26 @@ -//! glTF 2.0 import, written from the Khronos glTF 2.0 specification. -//! -//! Supports `.gltf` (JSON with external `.bin`/image files or `data:` URIs) and `.glb` (binary -//! container: a JSON chunk and a BIN chunk). Imports the default scene's node hierarchy (TRS or -//! matrix), triangle primitives (`TRIANGLES`, `TRIANGLE_STRIP`, `TRIANGLE_FAN`) with POSITION, -//! NORMAL, TANGENT, TEXCOORD_0, JOINTS_0 and WEIGHTS_0, PBR metallic-roughness materials -//! (base colour, metallic-roughness, normal, occlusion and emissive textures; alpha modes; -//! double-sided; `KHR_materials_emissive_strength`, `KHR_materials_unlit`), embedded or -//! external PNG/JPEG images with sampler wrap modes, skins and animations (step, linear and -//! cubic-spline translation/rotation/scale), perspective and orthographic cameras, and -//! `KHR_lights_punctual` lights (directional, point, spot). Sparse accessors and morph targets -//! are ignored. +//! glTF 2.0 import (`.gltf` with external or embedded buffers, `.glb`), read with `craft-mesh` +//! (`craft_mesh::gltf`): meshes, PBR metallic-roughness materials, the node hierarchy, skins, +//! animations, cameras and `KHR_lights_punctual` lights. External buffers and images are read +//! through the caller's resolver by their percent-decoded URI. Primitives without normals get +//! flat normals (glTF 2.0 §3.7.2.1); normal-mapped ones get tangents from their UVs. -use std::collections::HashMap; -use std::{cell::Cell, sync::Arc}; +use crate::scene::{MissingNormals, error, limits, to_model}; +use crate::{Model, Result}; -use serde_json::Value; +pub use craft_mesh::base64_decode; +pub use craft_mesh::gltf::{split_glb, uri_decode}; -use crate::{ - AlphaMode, Animation, Channel, ChannelPath, Interp, MAX_IMPORT_TEXTURE_PIXELS, Mat4, Material, Mesh, Model, ModelError, Node, Primitive, Result, Skin, - TexRef, Texture, Wrap, perr, -}; - -const GLB_MAGIC: u32 = 0x4654_6C67; -const CHUNK_JSON: u32 = 0x4E4F_534A; -const CHUNK_BIN: u32 = 0x004E_4942; - -/// Split a GLB container into its JSON text and BIN chunk. -pub fn split_glb(b: &[u8]) -> Result<(&[u8], Option<&[u8]>)> { - let u32_at = |o: usize| -> Option { b.get(o..o + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) }; - if u32_at(0) != Some(GLB_MAGIC) { - return Err(perr("not a GLB file")); - } - if u32_at(4) != Some(2) { - return Err(ModelError::Unsupported(format!("GLB version {}", u32_at(4).unwrap_or(0)))); - } - let total = (u32_at(8).unwrap_or(0) as usize).min(b.len()); - let mut o = 12; - let mut json = None; - let mut bin = None; - while o + 8 <= total { - let len = u32_at(o).unwrap_or(0) as usize; - let ty = u32_at(o + 4).unwrap_or(0); - let past_end = || perr("GLB chunk runs past the end of the file"); - let end = (o + 8).checked_add(len).ok_or_else(past_end)?; - let data = b.get(o + 8..end).ok_or_else(past_end)?; - match ty { - CHUNK_JSON if json.is_none() => json = Some(data), - CHUNK_BIN if bin.is_none() => bin = Some(data), - _ => {} - } - o = end; - } - Ok((json.ok_or_else(|| perr("GLB without a JSON chunk"))?, bin)) -} - -/// Decode standard base64 (with or without padding; whitespace ignored). -pub fn base64_decode(s: &str) -> Option> { - let mut out = Vec::with_capacity(s.len() * 3 / 4); - let mut acc = 0u32; - let mut bits = 0; - for c in s.bytes() { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - b'=' => break, - b' ' | b'\n' | b'\r' | b'\t' => continue, - _ => return None, - } as u32; - acc = (acc << 6) | v; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((acc >> bits) as u8); - acc &= (1 << bits) - 1; - } - } - Some(out) -} - -/// Percent-decode a relative URI. -pub fn uri_decode(s: &str) -> String { - let b = s.as_bytes(); - let mut out = Vec::with_capacity(b.len()); - let mut i = 0; - while i < b.len() { - if b[i] == b'%' - && i + 2 < b.len() - && b[i + 1].is_ascii_hexdigit() - && b[i + 2].is_ascii_hexdigit() - && let Ok(v) = u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or("zz"), 16) - { - out.push(v); - i += 3; - continue; - } - out.push(b[i]); - i += 1; - } - String::from_utf8_lossy(&out).into_owned() -} - -/// Bytes of a `data:` URI or an external resource. -fn load_uri(uri: &str, resolve: &dyn Fn(&str) -> Option>) -> Result> { - if let Some(rest) = uri.strip_prefix("data:") { - let (meta, data) = rest.split_once(',').ok_or_else(|| perr("malformed data URI"))?; - return if meta.ends_with(";base64") { base64_decode(data).ok_or_else(|| perr("bad base64 in data URI")) } else { Ok(uri_decode(data).into_bytes()) }; - } - let name = uri_decode(uri); - resolve(&name).ok_or(ModelError::Missing(name)) -} - -struct Doc<'a> { - j: &'a Value, - buffers: Vec>, - /// Zero components that buffer-less accessors may still allocate, across the whole file: - /// nothing backs them, so many references to one capped accessor must not multiply (#2139). - zero_left: Cell, - /// Components every accessor read may still allocate, across the whole file: each primitive - /// that references an accessor keeps its own copy, so references must not multiply memory. - read_left: Cell, - /// The budget `read_left` started from, for the error message. - read_cap: usize, -} - -fn arr<'v>(v: &'v Value, k: &str) -> &'v [Value] { - v.get(k).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) -} -/// A non-negative integer field; one too large for `usize` counts as absent (#1235). -fn idx(v: &Value, k: &str) -> Option { - v.get(k).and_then(Value::as_u64).and_then(|x| usize::try_from(x).ok()) -} -/// Node indices in an array field (out-of-range ones are dropped). -fn indices(v: &Value, k: &str) -> Vec { - arr(v, k).iter().filter_map(Value::as_u64).filter_map(|c| usize::try_from(c).ok()).collect() -} - -/// The most components accessors without a buffer view (all zeros) may have, together: nothing -/// in the file backs their counts, so they are capped instead of checked against a buffer -/// (#1235, #2139). -const MAX_ZERO_COMPONENTS: usize = 1 << 24; - -/// The most components all accessor reads in one file may allocate together (about 1 GiB as -/// `f32`/`u32`). Each primitive keeps its own copy of what it reads, so an accessor referenced -/// N times costs N times; this bounds that by a fixed amount rather than by buffer size, because -/// real assets legitimately share one vertex buffer across many primitives. A 10M-triangle scan -/// (5M vertices with position, normal, UV and tangent, 30M indices) reads about 90M. -const MAX_READ_COMPONENTS: usize = 1 << 28; - -/// Where an accessor's elements lie in its buffer: `count` elements of `elem` bytes, `stride` -/// apart from `base`, all checked to be inside `buf`. -struct Span<'b> { - buf: &'b [u8], - base: usize, - stride: usize, -} -fn num(v: &Value, k: &str, d: f64) -> f64 { - v.get(k).and_then(Value::as_f64).unwrap_or(d) -} -fn nums(v: &Value, k: &str, d: [f64; N]) -> [f64; N] { - let mut out = d; - if let Some(a) = v.get(k).and_then(Value::as_array) { - for (i, x) in a.iter().take(N).enumerate() { - out[i] = x.as_f64().unwrap_or(d[i]); - } - } - out -} - -/// Bytes of component `c` of element `i`, with checked offsets (the span was validated, but -/// nothing derived from the file is indexed unchecked). -fn component(buf: &[u8], base: usize, stride: usize, i: usize, c: usize, csize: usize) -> Result<&[u8]> { - let o = i.checked_mul(stride).and_then(|o| o.checked_add(base)).and_then(|o| o.checked_add(c.checked_mul(csize)?)); - o.and_then(|o| buf.get(o..o.checked_add(csize)?)).ok_or_else(|| perr("accessor reads past its buffer")) -} - -impl Doc<'_> { - /// Charge `total` components to the file's read budget before allocating them. - fn charge(&self, total: usize) -> Result<()> { - let left = self.read_left.get(); - let Some(rest) = left.checked_sub(total) else { - let cap = self.read_cap; - return Err(perr(format!("accessor reads need more than {cap} components in total ({total} requested, {left} left)"))); - }; - self.read_left.set(rest); - Ok(()) - } - - /// Charge `count` items of `per` components each. - fn charge_each(&self, count: usize, per: usize) -> Result<()> { - self.charge(count.checked_mul(per).ok_or_else(|| perr("primitive is too large"))?) - } - - /// The accessor's element count and total components (`count * n`), checked; and its span in - /// the buffer, validated before anything is allocated from the count. `None` for an - /// accessor without a buffer view, whose components are all zero. - fn layout(&self, acc: &Value, n: usize, csize: usize) -> Result<(usize, usize, Option>)> { - let count = match acc.get("count") { - None => 0, - Some(c) => c.as_u64().and_then(|c| usize::try_from(c).ok()).ok_or_else(|| perr("accessor count is not a valid size"))?, - }; - let total = count.checked_mul(n).ok_or_else(|| perr("accessor count is too large"))?; - let Some(bv) = idx(acc, "bufferView") else { - let left = self.zero_left.get(); - let Some(rest) = left.checked_sub(total) else { - return Err(perr(format!("accessors without a bufferView have more than {MAX_ZERO_COMPONENTS} components ({total} requested, {left} left)"))); - }; - self.zero_left.set(rest); - self.charge(total)?; - return Ok((count, total, None)); - }; - let view = arr(self.j, "bufferViews").get(bv).ok_or_else(|| perr(format!("no bufferView {bv}")))?; - let buf = self.buffers.get(idx(view, "buffer").unwrap_or(0)).ok_or_else(|| perr("bufferView buffer out of range"))?; - let past = || perr("accessor reads past its buffer"); - let base = idx(view, "byteOffset").unwrap_or(0).checked_add(idx(acc, "byteOffset").unwrap_or(0)).ok_or_else(past)?; - let elem = csize.checked_mul(n).ok_or_else(past)?; - let stride = idx(view, "byteStride").filter(|s| *s > 0).unwrap_or(elem); - if stride < elem { - return Err(perr(format!("bufferView byteStride {stride} is smaller than its {elem}-byte elements"))); - } - if count > 0 { - let end = (count - 1).checked_mul(stride).and_then(|o| o.checked_add(base)).and_then(|o| o.checked_add(elem)).ok_or_else(past)?; - if end > buf.len() { - return Err(past()); - } - } - self.charge(total)?; - Ok((count, total, Some(Span { buf, base, stride }))) - } - - /// An accessor as `f32` rows of `n` components (normalised integers mapped to 0..1 / -1..1). - fn floats(&self, a: usize) -> Result<(Vec, usize)> { - let acc = arr(self.j, "accessors").get(a).ok_or_else(|| perr(format!("no accessor {a}")))?; - let n = match acc.get("type").and_then(Value::as_str).unwrap_or("") { - "SCALAR" => 1, - "VEC2" => 2, - "VEC3" => 3, - "VEC4" => 4, - "MAT2" => 4, - "MAT3" => 9, - "MAT4" => 16, - t => return Err(perr(format!("accessor type `{t}`"))), - }; - let ct = idx(acc, "componentType").unwrap_or(5126); - let norm = acc.get("normalized").and_then(Value::as_bool).unwrap_or(false); - let csize = match ct { - 5120 | 5121 => 1, - 5122 | 5123 => 2, - 5125 | 5126 => 4, - _ => return Err(perr(format!("componentType {ct}"))), - }; - let (count, total, span) = self.layout(acc, n, csize)?; - let mut out = vec![0.0f32; total]; - let Some(Span { buf, base, stride }) = span else { - // No buffer view: all zeros (sparse substitution is not supported). - return Ok((out, n)); - }; - // Matrices of 1/2-byte components pad columns to 4 bytes; ignored (rare). - for i in 0..count { - for c in 0..n { - let s = component(buf, base, stride, i, c, csize)?; - out[i * n + c] = match ct { - 5126 => f32::from_le_bytes([s[0], s[1], s[2], s[3]]), - 5125 => u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f32, - 5123 => { - let v = u16::from_le_bytes([s[0], s[1]]) as f32; - if norm { v / 65535.0 } else { v } - } - 5122 => { - let v = i16::from_le_bytes([s[0], s[1]]) as f32; - if norm { (v / 32767.0).max(-1.0) } else { v } - } - 5121 => { - let v = s[0] as f32; - if norm { v / 255.0 } else { v } - } - _ => { - let v = s[0] as i8 as f32; - if norm { (v / 127.0).max(-1.0) } else { v } - } - }; - } - } - Ok((out, n)) - } - - /// Integer accessor (indices, joints) read exactly. - fn ints(&self, a: usize) -> Result> { - let acc = arr(self.j, "accessors").get(a).ok_or_else(|| perr(format!("no accessor {a}")))?; - let ct = idx(acc, "componentType").unwrap_or(5125); - if ct == 5126 { - return Ok(self.floats(a)?.0.into_iter().map(|v| v as u32).collect()); - } - let n = match acc.get("type").and_then(Value::as_str).unwrap_or("SCALAR") { - "VEC4" => 4, - "VEC3" => 3, - "VEC2" => 2, - _ => 1, - }; - let csize = match ct { - 5120 | 5121 => 1, - 5122 | 5123 => 2, - _ => 4, - }; - let (count, total, span) = self.layout(acc, n, csize)?; - let Some(Span { buf, base, stride }) = span else { return Ok(vec![0; total]) }; - let mut out = Vec::with_capacity(total); - for i in 0..count { - for c in 0..n { - let s = component(buf, base, stride, i, c, csize)?; - out.push(match csize { - 1 => s[0] as u32, - 2 => u16::from_le_bytes([s[0], s[1]]) as u32, - _ => u32::from_le_bytes([s[0], s[1], s[2], s[3]]), - }); - } - } - Ok(out) - } -} - -/// Parse a `.gltf` (JSON) or `.glb` file. +/// Parse a `.gltf` (JSON) or `.glb` file; `resolve(uri)` reads external buffers and images. pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result { - parse_with_budget(bytes, resolve, MAX_READ_COMPONENTS) -} - -/// [`parse`] with a read budget of `read_budget` accessor components for the whole file. -pub(crate) fn parse_with_budget(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, read_budget: usize) -> Result { - let (json, bin) = if bytes.starts_with(b"glTF") { split_glb(bytes)? } else { (bytes, None) }; - let j: Value = serde_json::from_slice(json).map_err(|e| perr(format!("glTF JSON: {e}")))?; - let ver = j.get("asset").and_then(|a| a.get("version")).and_then(Value::as_str).unwrap_or(""); - if !ver.starts_with('2') { - return Err(ModelError::Unsupported(format!("glTF version `{ver}` (2.0 required)"))); - } - for ext in arr(&j, "extensionsRequired") { - let e = ext.as_str().unwrap_or(""); - if !matches!(e, "KHR_materials_unlit" | "KHR_materials_emissive_strength") { - return Err(ModelError::Unsupported(format!("required extension {e}"))); - } - } - let mut buffers = vec![]; - for (i, b) in arr(&j, "buffers").iter().enumerate() { - let data = match b.get("uri").and_then(Value::as_str) { - Some(u) => load_uri(u, resolve)?, - None if i == 0 => bin.map(<[u8]>::to_vec).ok_or_else(|| perr("buffer 0 has no uri and the file has no BIN chunk"))?, - None => vec![], - }; - buffers.push(data); - } - let d = Doc { j: &j, buffers, zero_left: Cell::new(MAX_ZERO_COMPONENTS), read_left: Cell::new(read_budget), read_cap: read_budget }; - - // Images → textures (decoded once per image; samplers set the wrap modes). - let mut images: Vec>> = vec![]; - // Images naming one source decode once, and all of them within one pixel budget. - let mut image_of: HashMap>> = HashMap::new(); - let mut pixels_left = MAX_IMPORT_TEXTURE_PIXELS; - let mut warnings: Vec = vec![]; - for (n, im) in arr(&j, "images").iter().enumerate() { - let (uri, view) = (im.get("uri").and_then(Value::as_str), idx(im, "bufferView")); - let key = match (uri, view) { - (Some(u), _) => format!("uri:{u}"), - (None, Some(bv)) => format!("bufferView:{bv}"), - (None, None) => { - images.push(None); - continue; - } - }; - let image = image_of.entry(key).or_insert_with(|| { - let data = if let Some(u) = uri { - load_uri(u, resolve).ok() - } else { - arr(&j, "bufferViews").get(view.unwrap_or(usize::MAX)).and_then(|v| { - let b = d.buffers.get(idx(v, "buffer").unwrap_or(0))?; - let o = idx(v, "byteOffset").unwrap_or(0); - b.get(o..o.checked_add(idx(v, "byteLength").unwrap_or(0))?).map(<[u8]>::to_vec) - }) - }; - match data.map(|b| Texture::decode_within(&b, &mut pixels_left)) { - Some(Ok(t)) => Some(Arc::new(t)), - Some(Err(e)) => { - log::warn!("model: glTF image {n} left out: {e}"); - warnings.push(format!("image {n} left out: {e}")); - None - } - None => None, - } - }); - images.push(image.clone()); - } - let wrap = |v: u64| match v { - 33071 => Wrap::Clamp, - 33648 => Wrap::Mirror, - _ => Wrap::Repeat, - }; - let mut textures: Vec> = vec![]; - let mut tex_map: Vec> = vec![]; - // One texture per decoded image and wrapping: repeated references share it instead of copying - // the pixels. The image is keyed by its allocation, so image entries naming the same file - // (which share one decode) also share their wrap variants. - let mut texture_of: HashMap<(usize, [Wrap; 2]), usize> = HashMap::new(); - for t in arr(&j, "textures") { - let Some(img) = idx(t, "source").and_then(|s| images.get(s).cloned().flatten()) else { - tex_map.push(None); - continue; - }; - let src = Arc::as_ptr(&img) as usize; - let samp = idx(t, "sampler").and_then(|s| arr(&j, "samplers").get(s)); - let ws = samp.and_then(|s| s.get("wrapS")).and_then(Value::as_u64).unwrap_or(10497); - let wt = samp.and_then(|s| s.get("wrapT")).and_then(Value::as_u64).unwrap_or(10497); - let w = [wrap(ws), wrap(wt)]; - let i = match texture_of.get(&(src, w)) { - Some(&i) => i, - None => { - let tex = if img.wrap == w { - img - } else { - // A wrap variant copies the pixels, so it is charged to the import budget too; - // one that does not fit is left out like an undecodable image. - let cost = u64::from(img.width) * u64::from(img.height); - if cost > pixels_left { - warnings.push(format!( - "a texture with another wrap mode left out: the model's textures would hold more than {MAX_IMPORT_TEXTURE_PIXELS} pixels" - )); - tex_map.push(None); - continue; - } - pixels_left -= cost; - Arc::new(Texture { wrap: w, ..(*img).clone() }) - }; - textures.push(tex); - texture_of.insert((src, w), textures.len() - 1); - textures.len() - 1 - } - }; - tex_map.push(Some(i)); - } - let tref = |v: Option<&Value>| -> Option { - let v = v?; - let t = tex_map.get(idx(v, "index")?).copied().flatten()?; - Some(TexRef { texture: t, uv_set: idx(v, "texCoord").unwrap_or(0) as u32 }) - }; - - let mut materials = vec![]; - for m in arr(&j, "materials") { - let pbr = m.get("pbrMetallicRoughness").cloned().unwrap_or(Value::Null); - let bc = nums(&pbr, "baseColorFactor", [1.0; 4]); - let ext = m.get("extensions"); - let strength = ext.and_then(|e| e.get("KHR_materials_emissive_strength")).map_or(1.0, |e| num(e, "emissiveStrength", 1.0)); - let em = nums(m, "emissiveFactor", [0.0; 3]); - materials.push(Material { - name: m.get("name").and_then(Value::as_str).unwrap_or("").to_string(), - base_color: bc.map(|v| v as f32), - base_color_tex: tref(pbr.get("baseColorTexture")), - metallic: num(&pbr, "metallicFactor", 1.0) as f32, - roughness: num(&pbr, "roughnessFactor", 1.0) as f32, - metallic_roughness_tex: tref(pbr.get("metallicRoughnessTexture")), - normal_tex: tref(m.get("normalTexture")), - normal_scale: m.get("normalTexture").map_or(1.0, |n| num(n, "scale", 1.0)) as f32, - occlusion_tex: tref(m.get("occlusionTexture")), - occlusion_strength: m.get("occlusionTexture").map_or(1.0, |n| num(n, "strength", 1.0)) as f32, - emissive: [(em[0] * strength) as f32, (em[1] * strength) as f32, (em[2] * strength) as f32], - emissive_tex: tref(m.get("emissiveTexture")), - alpha_mode: match m.get("alphaMode").and_then(Value::as_str) { - Some("MASK") => AlphaMode::Mask, - Some("BLEND") => AlphaMode::Blend, - _ => AlphaMode::Opaque, - }, - alpha_cutoff: num(m, "alphaCutoff", 0.5) as f32, - double_sided: m.get("doubleSided").and_then(Value::as_bool).unwrap_or(false), - unlit: ext.and_then(|e| e.get("KHR_materials_unlit")).is_some(), - }); - } - - let mut meshes = vec![]; - for m in arr(&j, "meshes") { - let mut mesh = Mesh { name: m.get("name").and_then(Value::as_str).unwrap_or("").to_string(), primitives: vec![] }; - for p in arr(m, "primitives") { - if let Some(prim) = primitive(&d, p, &materials)? { - mesh.primitives.push(prim); - } - } - meshes.push(mesh); - } - - let mut nodes = vec![]; - for n in arr(&j, "nodes") { - let matrix = n.get("matrix").and_then(Value::as_array).filter(|a| a.len() == 16).map(|a| { - // Column-major in the file. - let v: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); - let mut m = [[0.0; 4]; 4]; - for c in 0..4 { - for r in 0..4 { - m[r][c] = v[c * 4 + r]; - } - } - Mat4(m) - }); - nodes.push(Node { - name: n.get("name").and_then(Value::as_str).unwrap_or("").to_string(), - translation: nums(n, "translation", [0.0; 3]), - rotation: nums(n, "rotation", [0.0, 0.0, 0.0, 1.0]), - scale: nums(n, "scale", [1.0; 3]), - matrix, - mesh: idx(n, "mesh").filter(|&m| m < meshes.len()), - skin: idx(n, "skin"), - camera: idx(n, "camera"), - light: n.get("extensions").and_then(|e| e.get("KHR_lights_punctual")).and_then(|e| idx(e, "light")), - children: indices(n, "children"), - }); - } - - let scene = idx(&j, "scene").unwrap_or(0); - let roots: Vec = match arr(&j, "scenes").get(scene) { - Some(s) => indices(s, "nodes"), - None => { - // No scene: every node that is nobody's child. - let mut child = vec![false; nodes.len()]; - for n in &nodes { - for &c in &n.children { - if c < child.len() { - child[c] = true; - } - } - } - (0..nodes.len()).filter(|&i| !child[i]).collect() - } - }; - - let mut skins = vec![]; - for s in arr(&j, "skins") { - let joints: Vec = indices(s, "joints"); - let inverse_bind = match idx(s, "inverseBindMatrices") { - Some(a) => { - let (f, _) = d.floats(a)?; - f.as_chunks::<16>() - .0 - .iter() - .map(|v| { - let mut m = [[0.0; 4]; 4]; - for c in 0..4 { - for r in 0..4 { - m[r][c] = v[c * 4 + r] as f64; - } - } - Mat4(m) - }) - .collect() - } - None => vec![Mat4::IDENTITY; joints.len()], - }; - skins.push(Skin { joints, inverse_bind }); - } - - let mut animations = vec![]; - for a in arr(&j, "animations") { - let samplers = arr(a, "samplers"); - let mut anim = Animation { name: a.get("name").and_then(Value::as_str).unwrap_or("").to_string(), channels: vec![] }; - for c in arr(a, "channels") { - let Some(t) = c.get("target") else { continue }; - let Some(node) = idx(t, "node") else { continue }; - let path = match t.get("path").and_then(Value::as_str) { - Some("translation") => ChannelPath::Translation, - Some("rotation") => ChannelPath::Rotation, - Some("scale") => ChannelPath::Scale, - _ => continue, - }; - let Some(s) = idx(c, "sampler").and_then(|s| samplers.get(s)) else { continue }; - let interp = match s.get("interpolation").and_then(Value::as_str) { - Some("STEP") => Interp::Step, - Some("CUBICSPLINE") => Interp::CubicSpline, - _ => Interp::Linear, - }; - let (Some(input), Some(output)) = (idx(s, "input"), idx(s, "output")) else { continue }; - let (times, _) = d.floats(input)?; - let (values, _) = d.floats(output)?; - anim.channels.push(Channel { node, path, interp, times, values }); - } - animations.push(anim); - } - - let cameras = arr(&j, "cameras").iter().enumerate().map(|(i, c)| camera(c, i)).collect(); - let lights = j - .get("extensions") - .and_then(|e| e.get("KHR_lights_punctual")) - .map(|e| arr(e, "lights").iter().enumerate().map(|(i, l)| light(l, i)).collect()) - .unwrap_or_default(); - Ok(Model { meshes, nodes, roots, materials, textures, skins, animations, cameras, lights, warnings }) -} - -fn name_or(v: &Value, d: String) -> String { - v.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string).unwrap_or(d) -} - -/// A glTF camera (glTF 2.0 §5.12): `perspective` {yfov, aspectRatio?, znear} or -/// `orthographic` {xmag, ymag}. -fn camera(c: &Value, i: usize) -> crate::ModelCamera { - let projection = match (c.get("type").and_then(Value::as_str), c.get("orthographic")) { - (Some("orthographic"), Some(o)) => crate::CameraProjection::Orthographic { xmag: num(o, "xmag", 1.0), ymag: num(o, "ymag", 1.0) }, - _ => { - let p = c.get("perspective").cloned().unwrap_or(Value::Null); - crate::CameraProjection::Perspective { - yfov: num(&p, "yfov", 0.8).clamp(1e-3, 3.1), - aspect: p.get("aspectRatio").and_then(Value::as_f64), - znear: num(&p, "znear", 0.01), - } - } - }; - crate::ModelCamera { name: name_or(c, format!("Camera {}", i + 1)), projection } -} - -/// A `KHR_lights_punctual` light: type, color, intensity, range, spot cone angles. -fn light(l: &Value, i: usize) -> crate::ModelLight { - let kind = match l.get("type").and_then(Value::as_str) { - Some("directional") => crate::ModelLightKind::Directional, - Some("spot") => { - let s = l.get("spot").cloned().unwrap_or(Value::Null); - let outer = num(&s, "outerConeAngle", std::f64::consts::FRAC_PI_4).clamp(1e-3, std::f64::consts::FRAC_PI_2); - crate::ModelLightKind::Spot { inner: num(&s, "innerConeAngle", 0.0).clamp(0.0, outer), outer } - } - _ => crate::ModelLightKind::Point, - }; - crate::ModelLight { - name: name_or(l, format!("Light {}", i + 1)), - kind, - color: nums(l, "color", [1.0; 3]), - intensity: num(l, "intensity", 1.0).max(0.0), - range: l.get("range").and_then(Value::as_f64), - } -} - -fn primitive(d: &Doc, p: &Value, materials: &[Material]) -> Result> { - let mode = idx(p, "mode").unwrap_or(4); - if !matches!(mode, 4..=6) { - return Ok(None); - } - let attrs = p.get("attributes").ok_or_else(|| perr("primitive without attributes"))?; - let Some(pa) = idx(attrs, "POSITION") else { return Ok(None) }; - let (pos, _) = d.floats(pa)?; - let positions: Vec<[f32; 3]> = pos.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect(); - let n = positions.len(); - let vec3s = |a: Option| -> Result> { - Ok(match a { - Some(a) => d.floats(a)?.0.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect(), - None => vec![], - }) - }; - let mut normals = vec3s(idx(attrs, "NORMAL"))?; - let uvs: Vec<[f32; 2]> = match idx(attrs, "TEXCOORD_0") { - Some(a) => d.floats(a)?.0.as_chunks::<2>().0.iter().map(|c| [c[0], c[1]]).collect(), - None => vec![], - }; - let tangents: Vec<[f32; 4]> = match idx(attrs, "TANGENT") { - Some(a) => d.floats(a)?.0.as_chunks::<4>().0.iter().map(|c| [c[0], c[1], c[2], c[3]]).collect(), - None => vec![], - }; - let joints: Vec<[u16; 4]> = match idx(attrs, "JOINTS_0") { - Some(a) => d.ints(a)?.as_chunks::<4>().0.iter().map(|c| [c[0] as u16, c[1] as u16, c[2] as u16, c[3] as u16]).collect(), - None => vec![], - }; - let weights: Vec<[f32; 4]> = match idx(attrs, "WEIGHTS_0") { - Some(a) => d.floats(a)?.0.as_chunks::<4>().0.iter().map(|c| [c[0], c[1], c[2], c[3]]).collect(), - None => vec![], - }; - let raw: Vec = match idx(p, "indices") { - Some(a) => d.ints(a)?, - None => { - // Generated indices are allocated like a read, once per referencing primitive. - d.charge(n)?; - (0..n as u32).collect() - } - }; - if raw.iter().any(|&i| i as usize >= n) { - return Err(perr("index out of range")); - } - let mut indices = Vec::with_capacity(raw.len()); - match mode { - 5 => { - for i in 2..raw.len() { - let (a, b, c) = (raw[i - 2], raw[i - 1], raw[i]); - if i % 2 == 0 { indices.extend([a, b, c]) } else { indices.extend([b, a, c]) } - } - } - 6 => { - for i in 2..raw.len() { - indices.extend([raw[0], raw[i - 1], raw[i]]); - } - } - _ => indices.extend(raw.as_chunks::<3>().0.iter().flatten()), - } - // The triangle list is kept besides the raw indices (a strip or fan of k indices becomes - // 3(k-2)), so it is charged like a read. - d.charge(indices.len())?; - if normals.len() != n { - normals.clear(); - } - let material = idx(p, "material").filter(|&m| m < materials.len()); - let skinned = joints.len() == n && weights.len() == n; - if normals.is_empty() { - // Flat normals unshare every vertex: position and normal, plus UVs and joints/weights. - let per = 6 + if uvs.len() == n { 2 } else { 0 } + if skinned { 8 } else { 0 }; - d.charge_each(indices.len(), per)?; - } - let mut prim = Primitive { - positions, - normals, - uvs: if uvs.len() == n { uvs } else { vec![] }, - tangents: if tangents.len() == n { tangents } else { vec![] }, - joints: if skinned { joints } else { vec![] }, - weights: if skinned { weights } else { vec![] }, - indices, - material, - }; - if prim.normals.is_empty() { - prim.flat_normals(); - prim.tangents.clear(); - } - let needs_tangents = material.is_some_and(|m| materials[m].normal_tex.is_some()); - if needs_tangents && prim.tangents.is_empty() { - d.charge_each(prim.positions.len(), 4)?; - prim.compute_tangents(); - } - Ok(Some(prim)) -} - -#[cfg(test)] -mod tests { - use super::uri_decode; - - #[test] - fn uri_decode_rejects_signed_hex_pair() { - assert_eq!(uri_decode("a%+1b"), "a%+1b"); - assert_eq!(uri_decode("a%-1b"), "a%-1b"); - assert_eq!(uri_decode("a%41b"), "aAb"); - } + let mut buffers = |uri: &str| resolve(uri); + let scene = craft_mesh::gltf::read(bytes, &limits(), &mut buffers).map_err(error)?; + to_model(scene, MissingNormals::Flat, &|im| { + let uri = im.uri.as_deref()?; + match uri.strip_prefix("data:") { + Some(_) => None, + // craft-mesh decodes external image URIs while constructing the scene. Decode only + // once here; a second pass changes literal percent escapes in valid filenames. + None => resolve(uri), + } + }) } diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index b95a9f487..0f25570eb 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -1,12 +1,14 @@ //! 3D models for the Advanced 3D renderer. //! -//! - [`gltf`]: glTF 2.0 import (`.gltf` with external or embedded buffers, `.glb`), written from -//! the Khronos glTF 2.0 specification: meshes, PBR metallic-roughness materials (base colour, -//! metallic-roughness, normal, occlusion and emissive maps), the node hierarchy, skins and -//! animations. +//! The file formats are read with `craft-mesh` (storytold/craft-libs); this crate maps its +//! scene onto [`Model`], decodes the textures and adds the normals and tangents a file leaves out. +//! +//! - [`gltf`]: glTF 2.0 import (`.gltf` with external or embedded buffers, `.glb`): meshes, PBR +//! metallic-roughness materials (base colour, metallic-roughness, normal, occlusion and +//! emissive maps), the node hierarchy, skins, animations, cameras and lights. //! - [`obj`]: Wavefront OBJ geometry with MTL materials (mapped onto the metallic-roughness model). //! - [`stl`]: STL meshes (binary and ASCII, with the binary per-facet and part colours). -//! - [`fbx`]: FBX 7.x scenes, binary and ASCII: meshes, the Model hierarchy, Lambert/Phong +//! - [`fbx`]: FBX 6.x and 7.x scenes, binary and ASCII: meshes, the Model hierarchy, Lambert/Phong //! materials and their textures. //! - [`prim`]: parametric primitives (cube, sphere, plane, torus, cone, cylinder). //! - [`extrude`]: extruded, bevelled meshes from 2D outlines (text and shape layers), with @@ -22,6 +24,7 @@ pub mod fbx; pub mod gltf; pub mod obj; pub mod prim; +mod scene; pub mod stl; pub mod triangulate; @@ -227,6 +230,9 @@ impl Primitive { if !self.uvs.is_empty() { p.uvs.push(self.uvs[i]); } + if !self.tangents.is_empty() { + p.tangents.push(self.tangents[i]); + } if !self.joints.is_empty() { p.joints.push(self.joints[i]); p.weights.push(self.weights[i]); diff --git a/crates/model/src/obj.rs b/crates/model/src/obj.rs index c9d364fc7..c305cf23f 100644 --- a/crates/model/src/obj.rs +++ b/crates/model/src/obj.rs @@ -1,33 +1,21 @@ -//! Wavefront OBJ geometry and MTL materials. +//! Wavefront OBJ geometry and MTL materials, read with `craft-mesh` (`craft_mesh::obj`). //! -//! OBJ: `v` (optional vertex colours ignored), `vt`, `vn`, `f` with `v`, `v/vt`, `v//vn`, -//! `v/vt/vn` references (negative = relative), polygons fan-triangulated, `o`/`g` groups, `s` -//! smoothing (normals computed per smoothing state when a face has none), `usemtl`, `mtllib`. -//! -//! MTL materials map onto metallic-roughness: `Kd` → base colour, `d`/`Tr` → alpha, `Ke` → -//! emissive, `Pr`/`Pm` (the PBR extension) → roughness/metallic, otherwise roughness from the -//! Phong exponent `Ns` (`sqrt(2 / (Ns + 2))`) and metallic 0; `map_Kd`, `map_Ke`, -//! `map_Bump`/`bump`/`norm` load base colour, emissive and normal textures. +//! The material library and the textures it names are read through the caller's resolver: a +//! texture is looked up by the name as written (a name containing spaces is one name), then by +//! its file name (an absolute path from another machine, #1274), then by the final token (the +//! options convention, `-bm 1 file.png`). Faces without normals get smooth normals within a +//! smoothing group and flat ones where smoothing is off. -use std::collections::{HashMap, HashSet}; -use std::sync::Arc; +use crate::scene::{MissingNormals, error, limits, to_model}; +use crate::{Model, Result}; -use crate::{AlphaMode, MAX_IMPORT_TEXTURE_PIXELS, Material, Mesh, Model, Primitive, Result, TexRef, Texture, perr}; +pub use craft_mesh::srgb_to_linear; -/// The last component of a referenced path, treating `\` as a separator too: a path from a -/// machine of another kind (`C:\textures\checker.png`) still finds `checker.png` next to the -/// model (#1274). `None` when the name carries no path at all. -fn sibling_name(name: &str) -> Option<&str> { - let file = name.rsplit(['/', '\\']).next()?; - (!file.is_empty() && file.len() < name.len()).then_some(file) -} - -/// A material reference resolved against the model's folder: the name as written (a name -/// containing spaces is one name), then its file name (an absolute path from another machine, -/// #1274), then the final token (the options convention, `-bm 1 file.png`). +/// A material reference resolved against the model's folder: the name as written, then its file +/// name, then the final token. fn resolve_reference(resolve: &dyn Fn(&str) -> Option>, name: &str) -> Option> { let mut tried: Vec<&str> = vec![]; - for candidate in [name, sibling_name(name).unwrap_or(name), name.split_whitespace().last().unwrap_or(name)] { + for candidate in [name, craft_mesh::obj::sibling_name(name).unwrap_or(name), name.split_whitespace().last().unwrap_or(name)] { if tried.contains(&candidate) { continue; } @@ -39,289 +27,11 @@ fn resolve_reference(resolve: &dyn Fn(&str) -> Option>, name: &str) -> O None } -/// The textures an OBJ import has decoded, by reference, and the pixels it may still decode. -pub struct TextureCache { - loaded: HashMap>, - pixels_left: u64, - /// Textures left out, for the user. - pub warnings: Vec, -} - -impl Default for TextureCache { - fn default() -> Self { - TextureCache { loaded: HashMap::new(), pixels_left: MAX_IMPORT_TEXTURE_PIXELS, warnings: vec![] } - } -} - -/// Parse MTL text into named materials (textures appended to `textures`, decoded once per -/// reference through `cache`). -pub fn parse_mtl(text: &str, resolve: &dyn Fn(&str) -> Option>, textures: &mut Vec>, cache: &mut TextureCache) -> Vec { - let mut out: Vec = vec![]; - let TextureCache { loaded, pixels_left, warnings } = cache; - let mut tex = |name: &str, textures: &mut Vec>| -> Option { - let key = name.trim().to_string(); - let t = *loaded.entry(key.clone()).or_insert_with(|| { - let Some(b) = resolve_reference(resolve, &key) else { - log::warn!("model: texture `{key}` was not found next to the model"); - warnings.push(format!("texture `{key}` was not found next to the model")); - return None; - }; - match Texture::decode_within(&b, pixels_left) { - Ok(t) => { - textures.push(Arc::new(t)); - Some(textures.len() - 1) - } - Err(e) => { - log::warn!("model: cannot decode texture `{key}`: {e}"); - warnings.push(format!("texture `{key}` left out: {e}")); - None - } - } - }); - t.map(|texture| TexRef { texture, uv_set: 0 }) - }; - let mut ns_seen = false; - let mut pr_seen = false; - for line in text.lines() { - let line = line.trim(); - let (key, rest) = line.split_once(char::is_whitespace).map(|(k, r)| (k, r.trim())).unwrap_or((line, "")); - let f3 = || -> [f32; 3] { - let v: Vec = rest.split_whitespace().filter_map(|x| x.parse().ok()).collect(); - match v.len() { - 0 => [0.0; 3], - 1 | 2 => [v[0]; 3], - _ => [v[0], v[1], v[2]], - } - }; - let f1 = || rest.split_whitespace().next().and_then(|x| x.parse::().ok()); - if key == "newmtl" { - if let Some(m) = out.last_mut() { - finish(m, ns_seen, pr_seen); - } - ns_seen = false; - pr_seen = false; - out.push(Material { name: rest.to_string(), metallic: 0.0, roughness: 0.5, ..Material::default() }); - continue; - } - let Some(m) = out.last_mut() else { continue }; - match key { - "Kd" => { - let c = f3(); - m.base_color = [srgb_to_linear(c[0]), srgb_to_linear(c[1]), srgb_to_linear(c[2]), m.base_color[3]]; - } - "Ke" => m.emissive = f3().map(srgb_to_linear), - "d" => m.base_color[3] = f1().unwrap_or(1.0), - "Tr" => m.base_color[3] = 1.0 - f1().unwrap_or(0.0), - "Ns" => { - let ns = f1().unwrap_or(0.0).max(0.0); - if !pr_seen { - m.roughness = (2.0 / (ns + 2.0)).sqrt(); - } - ns_seen = true; - } - "Pr" => { - m.roughness = f1().unwrap_or(0.5).clamp(0.0, 1.0); - pr_seen = true; - } - "Pm" => m.metallic = f1().unwrap_or(0.0).clamp(0.0, 1.0), - "map_Kd" => m.base_color_tex = tex(rest, textures), - "map_Ke" => { - m.emissive_tex = tex(rest, textures); - if m.emissive == [0.0; 3] { - m.emissive = [1.0; 3]; - } - } - "map_Bump" | "map_bump" | "bump" | "norm" => m.normal_tex = tex(rest, textures), - _ => {} - } - } - if let Some(m) = out.last_mut() { - finish(m, ns_seen, pr_seen); - } - out -} - -fn finish(m: &mut Material, _ns: bool, _pr: bool) { - if m.base_color[3] < 0.999 { - m.alpha_mode = AlphaMode::Blend; - } -} - -/// sRGB-encoded component → linear (MTL colours are display colours). -pub fn srgb_to_linear(c: f32) -> f32 { - if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } -} - -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -struct Key { - v: u32, - t: u32, - n: u32, - /// Smoothing state (faces without normals get computed normals per state). - s: u32, -} - -/// Parse OBJ text (and its MTL libraries through `resolve`). +/// Parse OBJ text (and its MTL libraries and textures through `resolve`). pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result { - let text = String::from_utf8_lossy(bytes); - let mut v: Vec<[f32; 3]> = vec![]; - let mut vt: Vec<[f32; 2]> = vec![]; - let mut vn: Vec<[f32; 3]> = vec![]; - let mut materials: Vec = vec![]; - let mut material_of: HashMap = HashMap::new(); - let mut textures: Vec> = vec![]; - let mut cache = TextureCache::default(); - let mut libraries: HashSet = HashSet::new(); - // One primitive per material, in order of first use. - let mut prims: Vec<(Option, Primitive, HashMap, Vec)> = vec![]; - let mut prim_of: HashMap, usize> = HashMap::new(); - let mut current: Option = None; - let mut smooth = 0u32; - let mut flat_id = 1u32 << 31; - let mut faces = 0usize; - // Join `\` line continuations. - let joined = text.replace("\\\r\n", " ").replace("\\\n", " "); - for (ln, line) in joined.lines().enumerate() { - let line = line.split('#').next().unwrap_or("").trim(); - if line.is_empty() { - continue; - } - let mut it = line.split_whitespace(); - let key = it.next().unwrap_or(""); - let rest: Vec<&str> = it.collect(); - let fl = |i: usize| rest.get(i).and_then(|x| x.parse::().ok()); - match key { - "v" => v.push([fl(0).unwrap_or(0.0), fl(1).unwrap_or(0.0), fl(2).unwrap_or(0.0)]), - "vt" => vt.push([fl(0).unwrap_or(0.0), fl(1).unwrap_or(0.0)]), - "vn" => vn.push([fl(0).unwrap_or(0.0), fl(1).unwrap_or(0.0), fl(2).unwrap_or(1.0)]), - "s" => { - smooth = match rest.first().copied() { - None | Some("off") | Some("0") => 0, - Some(x) => x.parse().unwrap_or(1).max(1), - } - } - "mtllib" => { - let name = line["mtllib".len()..].trim(); - // A library named again is already loaded. - if !libraries.insert(name.to_string()) { - continue; - } - let mut found = false; - for file in std::iter::once(name).chain(name.split_whitespace()).chain(sibling_name(name)) { - if let Some(b) = resolve(file) { - let ms = parse_mtl(&String::from_utf8_lossy(&b), resolve, &mut textures, &mut cache); - for m in ms { - material_of.entry(m.name.clone()).or_insert(materials.len()); - materials.push(m); - } - found = true; - break; - } - } - if !found && !name.is_empty() { - log::warn!("model: material library `{name}` was not found next to the model"); - } - } - "usemtl" => { - let name = line["usemtl".len()..].trim(); - current = Some(*material_of.entry(name.to_string()).or_insert_with(|| { - // Unknown material: a named grey default. - materials.push(Material { name: name.to_string(), metallic: 0.0, roughness: 0.5, base_color: [0.8, 0.8, 0.8, 1.0], ..Material::default() }); - materials.len() - 1 - })); - } - "f" => { - if rest.len() < 3 { - continue; - } - faces += 1; - let resolve_i = |s: &str, len: usize| -> Option { - if s.is_empty() { - return None; - } - let i: i64 = s.parse().ok()?; - let k = if i < 0 { len as i64 + i } else { i - 1 }; - (k >= 0 && (k as usize) < len).then_some(k as u32) - }; - let mut refs = vec![]; - for r in &rest { - let mut parts = r.split('/'); - let vi = resolve_i(parts.next().unwrap_or(""), v.len()).ok_or_else(|| perr(format!("line {}: bad vertex index `{r}`", ln + 1)))?; - let ti = parts.next().and_then(|s| resolve_i(s, vt.len())); - let ni = parts.next().and_then(|s| resolve_i(s, vn.len())); - refs.push((vi, ti, ni)); - } - let has_n = refs.iter().all(|r| r.2.is_some()); - // Faces without normals: shared within a smoothing group, unique otherwise. - let s = if has_n { - 0 - } else if smooth == 0 { - flat_id += 1; - flat_id - } else { - smooth - }; - let slot = *prim_of.entry(current).or_insert_with(|| { - prims.push((current, Primitive { material: current, ..Default::default() }, HashMap::new(), vec![])); - prims.len() - 1 - }); - let (_, prim, map, need) = &mut prims[slot]; - let mut ids = vec![]; - for (vi, ti, ni) in refs { - let k = Key { v: vi, t: ti.unwrap_or(u32::MAX), n: ni.unwrap_or(u32::MAX), s }; - let id = *map.entry(k).or_insert_with(|| { - prim.positions.push(v[vi as usize]); - prim.uvs.push(ti.map_or([0.0, 0.0], |t| vt[t as usize])); - prim.normals.push(ni.map_or([0.0; 3], |n| vn[n as usize])); - need.push(ni.is_none()); - (prim.positions.len() - 1) as u32 - }); - ids.push(id); - } - for i in 2..ids.len() { - prim.indices.extend([ids[0], ids[i - 1], ids[i]]); - } - } - _ => {} - } - } - if faces == 0 { - return Err(perr("OBJ file without faces")); - } - let any_uv = !vt.is_empty(); - let mut mesh = Mesh { name: String::new(), primitives: vec![] }; - for (_, mut p, _, need) in prims { - if need.iter().any(|&b| b) { - // Fill missing normals from the triangles (area weighted), keep given ones. - let given = p.normals.clone(); - p.compute_normals(); - for (i, n) in p.normals.iter_mut().enumerate() { - if !need[i] { - *n = given[i]; - } - } - } - if !any_uv { - p.uvs.clear(); - } else { - // OBJ's v axis points up the image; textures are stored top row first. - for uv in p.uvs.iter_mut() { - uv[1] = 1.0 - uv[1]; - } - } - if p.material.is_some_and(|m| materials[m].normal_tex.is_some()) { - p.compute_tangents(); - } - mesh.primitives.push(p); - } - let mut model = Model::single(mesh, materials).with_textures(textures); - model.warnings = cache.warnings; - Ok(model) -} - -impl Model { - fn with_textures(mut self, t: Vec>) -> Model { - self.textures = t; - self - } + // `craft-mesh` splits `mtllib` names and tries each complete library path itself. Applying + // texture-option fallback here first can mistake the last library for the whole directive. + let mut library = |name: &str| resolve(name); + let scene = craft_mesh::obj::read(bytes, &limits(), &mut library).map_err(error)?; + to_model(scene, MissingNormals::BySmoothing, &|im| resolve_reference(resolve, im.uri.as_deref()?.trim())) } diff --git a/crates/model/src/scene.rs b/crates/model/src/scene.rs new file mode 100644 index 000000000..07fee0397 --- /dev/null +++ b/crates/model/src/scene.rs @@ -0,0 +1,459 @@ +//! A `craft-mesh` scene (glTF, OBJ, STL or FBX, read there) as a [`Model`]: one primitive per +//! part with one index per vertex, decoded textures, and the normals and tangents the renderer +//! needs where the file has none. + +use std::collections::HashMap; +use std::sync::Arc; + +use craft_mesh as cm; + +use crate::{ + 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, +/// arrays and embedded images in one import. +pub(crate) fn limits() -> cm::Limits { + cm::Limits { max_data_bytes: 2 << 30, ..cm::Limits::default() } +} + +pub(crate) fn error(e: cm::Error) -> ModelError { + match e { + cm::Error::Missing(name) => ModelError::Missing(name), + cm::Error::Unsupported(m) => ModelError::Unsupported(m), + cm::Error::Malformed(m) | cm::Error::TooLarge(m) => ModelError::Parse(m), + } +} + +/// What a primitive without normals gets. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum MissingNormals { + /// Every triangle its own vertices and face normal (glTF 2.0 §3.7.2.1). + Flat, + /// Area-weighted vertex normals (FBX). + Smooth, + /// Smooth within an OBJ smoothing group, flat where smoothing is off. + BySmoothing, +} + +/// A column-major `craft-mesh` matrix as a [`Mat4`]. +pub(crate) fn mat4(m: &cm::Mat4) -> Mat4 { + let mut out = [[0.0; 4]; 4]; + for (c, col) in m.as_chunks::<4>().0.iter().enumerate() { + for (r, v) in col.iter().enumerate() { + out[r][c] = *v; + } + } + Mat4(out) +} + +fn wrap(w: cm::Wrap) -> Wrap { + match w { + cm::Wrap::Repeat => Wrap::Repeat, + cm::Wrap::Clamp => Wrap::Clamp, + cm::Wrap::Mirror => Wrap::Mirror, + } +} + +/// 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(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() + .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)) => { + 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 => { + 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<(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 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 + .materials + .iter() + .map(|m| Material { + name: m.name.clone(), + base_color: m.base_color, + base_color_tex: tref(m.base_color_texture), + metallic: m.metallic, + roughness: m.roughness, + metallic_roughness_tex: tref(m.metallic_roughness_texture), + normal_tex: tref(m.normal_texture), + normal_scale: m.normal_scale, + occlusion_tex: tref(m.occlusion_texture), + occlusion_strength: m.occlusion_strength, + emissive: m.emissive, + emissive_tex: tref(m.emissive_texture), + alpha_mode: match m.alpha_mode { + cm::AlphaMode::Opaque => AlphaMode::Opaque, + cm::AlphaMode::Mask(_) => AlphaMode::Mask, + cm::AlphaMode::Blend => AlphaMode::Blend, + }, + alpha_cutoff: if let cm::AlphaMode::Mask(c) = m.alpha_mode { c } else { 0.5 }, + double_sided: m.double_sided, + unlit: m.unlit, + }) + .collect(); + let mut adapter_bytes = 0u64; + let meshes = scene.meshes.iter().map(|m| mesh(m, &materials, missing, &mut adapter_bytes)).collect::>>()?; + let nodes = scene + .nodes + .iter() + .map(|n| { + let (translation, rotation, scale, matrix) = match n.trs { + Some(t) => (t.translation, t.rotation, t.scale, None), + None => ([0.0; 3], [0.0, 0.0, 0.0, 1.0], [1.0; 3], Some(mat4(&n.transform))), + }; + Node { + name: n.name.clone(), + translation, + rotation, + scale, + matrix, + mesh: n.mesh.filter(|&m| m < scene.meshes.len()), + skin: n.skin, + camera: n.camera, + light: n.light, + children: n.children.clone(), + } + }) + .collect(); + let skins = scene + .skins + .iter() + .map(|s| Skin { + joints: s.joints.clone(), + inverse_bind: if s.inverse_bind.is_empty() { vec![Mat4::IDENTITY; s.joints.len()] } else { s.inverse_bind.iter().map(mat4).collect() }, + }) + .collect(); + let animations = scene + .animations + .iter() + .map(|a| Animation { + name: a.name.clone(), + channels: a + .channels + .iter() + .map(|c| Channel { + node: c.node, + path: match c.path { + cm::ChannelPath::Translation => ChannelPath::Translation, + cm::ChannelPath::Rotation => ChannelPath::Rotation, + cm::ChannelPath::Scale => ChannelPath::Scale, + }, + interp: match c.interpolation { + cm::Interpolation::Step => Interp::Step, + cm::Interpolation::Linear => Interp::Linear, + cm::Interpolation::CubicSpline => Interp::CubicSpline, + }, + times: c.times.clone(), + values: c.values.clone(), + }) + .collect(), + }) + .collect(); + let name_or = |n: &str, d: String| if n.is_empty() { d } else { n.to_string() }; + let cameras = scene + .cameras + .iter() + .enumerate() + .map(|(i, c)| ModelCamera { + name: name_or(&c.name, format!("Camera {}", i + 1)), + projection: match c.projection { + cm::Projection::Perspective { yfov, aspect, znear, .. } => CameraProjection::Perspective { yfov: yfov.clamp(1e-3, 3.1), aspect, znear }, + cm::Projection::Orthographic { xmag, ymag, .. } => CameraProjection::Orthographic { xmag, ymag }, + }, + }) + .collect(); + let lights = scene + .lights + .iter() + .enumerate() + .map(|(i, l)| ModelLight { + name: name_or(&l.name, format!("Light {}", i + 1)), + kind: match l.kind { + cm::LightKind::Directional => ModelLightKind::Directional, + cm::LightKind::Point => ModelLightKind::Point, + cm::LightKind::Spot { inner, outer } => { + let outer = outer.clamp(1e-3, std::f64::consts::FRAC_PI_2); + ModelLightKind::Spot { inner: inner.clamp(0.0, outer), outer } + } + }, + color: l.color, + intensity: l.intensity.max(0.0), + range: l.range, + }) + .collect(); + 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 +/// and UVs are kept for a part when every corner of it has them; a triangle naming a vertex +/// that is not there is left out. +fn mesh(m: &cm::Mesh, materials: &[Material], missing: MissingNormals, adapter_bytes: &mut u64) -> Result { + let skinned = !m.joints.is_empty() && m.joints.len() == m.positions.len() && m.weights.len() == m.positions.len(); + let uv_set = m.uv_sets.first(); + // Include temporary hash keys, smoothing maps and the peak duplicate produced by + // flat-normal expansion. + // Account against the whole scene before building any primitive arrays. + let projected = m + .parts + .iter() + .try_fold(0u64, |sum, part| { + let has_missing = part.corners.iter().any(|c| (c.normal as usize) >= m.normals.len()); + let flat = missing == MissingNormals::Flat || (missing == MissingNormals::BySmoothing && part.smoothing == 0); + let vertices = if flat && has_missing { (part.triangle_count() as u64).checked_mul(3)? } else { part.corners.len() as u64 }; + let bytes_per_vertex = if missing == MissingNormals::Flat { 64 } else { 128 }; + sum.checked_add(vertices.checked_mul(bytes_per_vertex)?) + }) + .ok_or_else(|| ModelError::Parse("expanded mesh size overflow".into()))?; + *adapter_bytes = adapter_bytes.checked_add(projected).ok_or_else(|| ModelError::Parse("expanded mesh size overflow".into()))?; + if *adapter_bytes > (2u64 << 30) { + return Err(ModelError::Parse("expanded mesh data exceeds the 2 GiB import limit".into())); + } + let smooth = smooth_normals(m, missing); + let mut primitives = vec![]; + for part in &m.parts { + let normals = part.corners.iter().any(|c| (c.normal as usize) < m.normals.len()); + let tangents = part.has_tangents && m.tangents.len() == m.positions.len(); + let uvs = uv_set.filter(|set| part.corners.iter().any(|c| (c.uv as usize) < set.len())); + let flat_missing = missing == MissingNormals::BySmoothing && part.smoothing == 0; + let mut authored_normals = vec![]; + let mut ids: HashMap<(cm::Corner, Option), u32> = HashMap::new(); + let mut p = Primitive { material: part.material.filter(|&i| i < materials.len()), ..Primitive::default() }; + for (face, t) in part.triangles().enumerate() { + if t.iter().any(|c| c.position as usize >= m.positions.len()) { + continue; + } + let flat_face_normal = (normals && flat_missing).then(|| face_normal(m, t)); + for c in t { + let has_normal = (c.normal as usize) < m.normals.len(); + let has_uv = uvs.is_some_and(|set| (c.uv as usize) < set.len()); + let key = ( + cm::Corner { position: c.position, normal: if has_normal { c.normal } else { cm::NONE }, uv: if has_uv { c.uv } else { cm::NONE } }, + (!has_normal && flat_face_normal.is_some()).then_some(face), + ); + let next = p.positions.len() as u32; + let id = *ids.entry(key).or_insert_with(|| { + let at = c.position as usize; + p.positions.push(m.positions.get(at).copied().unwrap_or_default().map(|x| x as f32)); + if normals { + let authored = m.normals.get(c.normal as usize).copied().map(|n| n.map(|x| x as f32)); + let fallback = flat_face_normal.or_else(|| smooth.get(&(c.position, part.material, smooth_group(part, missing))).copied()); + authored_normals.push(authored.or(fallback)); + p.normals.push(authored.or(fallback).unwrap_or([0.0, 0.0, 1.0])); + } else if let Some(n) = smooth.get(&(c.position, part.material, smooth_group(part, missing))) { + p.normals.push(*n); + } + if tangents { + p.tangents.push(m.tangents.get(at).copied().unwrap_or_default().map(|x| x as f32)); + } + if let Some(set) = uvs { + p.uvs.push(set.get(c.uv as usize).copied().unwrap_or_default()); + } + if skinned { + p.joints.push(m.joints.get(at).copied().unwrap_or_default()); + p.weights.push(m.weights.get(at).copied().unwrap_or_default()); + } + next + }); + p.indices.push(id); + } + } + if p.indices.is_empty() { + continue; + } + if normals && authored_normals.iter().any(Option::is_none) { + // Keep authored corner normals, and fill only absent ones from the surrounding + // triangles. The generated normals are smooth in a mixed-authorship part. + if authored_normals.iter().any(Option::is_none) { + p.compute_normals(); + for (n, authored) in p.normals.iter_mut().zip(authored_normals) { + if let Some(authored) = authored { + *n = authored; + } + } + } + } else if p.normals.is_empty() { + match missing { + MissingNormals::Flat => p.flat_normals(), + MissingNormals::BySmoothing if part.smoothing == 0 => p.flat_normals(), + MissingNormals::Smooth | MissingNormals::BySmoothing => p.compute_normals(), + } + } + if p.tangents.is_empty() && p.material.is_some_and(|i| materials.get(i).is_some_and(|mat| mat.normal_tex.is_some())) { + p.compute_tangents(); + } + primitives.push(p); + } + Ok(Mesh { name: m.name.clone(), primitives }) +} + +fn smooth_group(part: &cm::Part, missing: MissingNormals) -> u32 { + match missing { + MissingNormals::Smooth => 1, + MissingNormals::BySmoothing => part.smoothing, + MissingNormals::Flat => 0, + } +} + +fn face_normal(m: &cm::Mesh, tri: [cm::Corner; 3]) -> [f32; 3] { + let [a, b, c] = tri.map(|corner| m.positions.get(corner.position as usize).copied().unwrap_or_default()); + let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + if len > 0.0 { n.map(|x| (x / len) as f32) } else { [0.0, 0.0, 1.0] } +} + +/// Area weighted generated normals across parts with the same material and smoothing state. +fn smooth_normals(m: &cm::Mesh, missing: MissingNormals) -> HashMap<(u32, Option, u32), [f32; 3]> { + let mut sums: HashMap<(u32, Option, u32), [f64; 3]> = HashMap::new(); + if missing == MissingNormals::Flat { + return HashMap::new(); + } + for part in &m.parts { + let group = smooth_group(part, missing); + if group == 0 { + continue; + } + for tri in part.triangles() { + let Some(a) = m.positions.get(tri[0].position as usize) else { continue }; + let Some(b) = m.positions.get(tri[1].position as usize) else { continue }; + let Some(c) = m.positions.get(tri[2].position as usize) else { continue }; + let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + let face = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + for corner in tri { + if (corner.normal as usize) < m.normals.len() { + continue; + } + let n = sums.entry((corner.position, part.material, group)).or_default(); + for i in 0..3 { + n[i] += face[i]; + } + } + } + } + sums.into_iter() + .map(|(key, n)| { + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + let n = if len > 0.0 { n.map(|x| (x / len) as f32) } else { [0.0, 0.0, 1.0] }; + (key, n) + }) + .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/stl.rs b/crates/model/src/stl.rs index 34e9a7f06..4fb8ee084 100644 --- a/crates/model/src/stl.rs +++ b/crates/model/src/stl.rs @@ -1,201 +1,23 @@ -//! STL (stereolithography) meshes, binary and ASCII. +//! STL (stereolithography) meshes, binary and ASCII, read with `craft-mesh` +//! (`craft_mesh::stl`): every facet keeps its own three vertices and its face normal, and binary +//! colour extensions become one plain material per colour. //! -//! Written from the public description of the format (3D Systems' StereoLithography Interface -//! Specification, 1989, and its widely documented colour extensions): -//! -//! - Binary: an 80-byte header, a little-endian `u32` facet count, then 50 bytes per facet: a -//! normal and three vertices (12 `f32`) and a 16-bit attribute word. Bytes after the last -//! facet are ignored. -//! - ASCII: `solid name`, then `facet normal nx ny nz` / `outer loop` / `vertex x y z`… / -//! `endloop` / `endfacet`, closed by `endsolid`; several solids may follow each other. -//! Loops with more than three vertices are fan-triangulated. -//! - Colour (binary only): with `COLOR=r g b a` (four bytes) in the header (Materialise Magics), -//! that is the part's colour and a facet whose attribute has bit 15 clear has its own colour -//! (red in bits 0–4, green 5–9, blue 10–14); otherwise (VisCAM / SolidView) a facet with bit 15 -//! set has its own colour (blue in bits 0–4, green 5–9, red 10–14). Each colour becomes a -//! plain dielectric material; uncoloured files get none (the renderer's default material). -//! -//! STL has no units, no UVs and no shared vertices: every facet keeps its own three vertices -//! with the face normal from its counter-clockwise winding (the stored normal is only used when -//! the triangle is degenerate), which gives the faceted look of an STL part. STL files are -//! Z-up (3D printing and CAD); they are turned to the +Y-up convention of [`crate::Model`] -//! (`(x, y, z)` → `(x, z, −y)`, a proper rotation, so winding is kept). Facets with non-finite -//! coordinates are skipped. +//! STL files are Z-up (3D printing and CAD); they are turned to the +Y-up convention of +//! [`crate::Model`] (`(x, y, z)` → `(x, z, −y)`, a proper rotation, so winding is kept). -use std::collections::HashMap; - -use crate::{Material, Mesh, Model, Primitive, Result, cross, normalize, obj::srgb_to_linear, perr, sub}; - -/// Header (80) plus facet count (4). -const HEADER: usize = 84; -/// Bytes per binary facet. -const FACET: usize = 50; - -/// Parse an STL file (binary or ASCII, detected from the contents). -pub fn parse(bytes: &[u8]) -> Result { - let count = bytes.get(80..HEADER).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_le_bytes); - let needed = count.and_then(|n| (n as usize).checked_mul(FACET)).and_then(|n| n.checked_add(HEADER)); - // A binary file's size is exact; many binary headers still begin with `solid`, so the size - // decides first, then the ASCII keyword. - if needed.is_some_and(|n| n == bytes.len()) { - return binary(bytes); - } - if looks_ascii(bytes) { - return ascii(bytes); - } - if needed.is_some_and(|n| n <= bytes.len()) { - return binary(bytes); - } - Err(perr("not an STL file (truncated binary facets or no `solid` keyword)")) -} - -fn looks_ascii(bytes: &[u8]) -> bool { - let head = bytes.get(..bytes.len().min(512)).unwrap_or(&[]); - let text = String::from_utf8_lossy(head); - let t = text.trim_start(); - t.get(..5).is_some_and(|k| k.eq_ignore_ascii_case("solid")) && (t.contains("facet") || t.contains("endsolid")) -} +use crate::scene::{MissingNormals, error, limits, to_model}; +use crate::{Model, Result}; /// The Z-up → Y-up turn. -fn y_up(v: [f32; 3]) -> [f32; 3] { +fn y_up(v: [f64; 3]) -> [f64; 3] { [v[0], v[2], -v[1]] } -/// Facets grouped into primitives by colour, in order of first use. -#[derive(Default)] -struct Builder { - /// (colour key, primitive); `None` = uncoloured. - prims: Vec<(Option<[u8; 3]>, Primitive)>, - /// Colour → index into `prims` (up to 32 768 colours, so not a linear search). - slots: HashMap, usize>, - facets: usize, -} - -impl Builder { - /// Add one triangle (file coordinates); `stored` is the file's facet normal. - fn tri(&mut self, color: Option<[u8; 3]>, stored: [f32; 3], v: [[f32; 3]; 3]) { - if v.iter().flatten().any(|c| !c.is_finite()) { - return; - } - let v = v.map(y_up); - let n = normalize(cross(sub(v[1], v[0]), sub(v[2], v[0]))) - .or_else(|| stored.iter().all(|c| c.is_finite()).then(|| normalize(y_up(stored))).flatten()) - .unwrap_or([0.0, 1.0, 0.0]); - let slot = *self.slots.entry(color).or_insert_with(|| { - self.prims.push((color, Primitive::default())); - self.prims.len() - 1 - }); - let Some((_, p)) = self.prims.get_mut(slot) else { return }; - for c in v { - p.indices.push(p.positions.len() as u32); - p.positions.push(c); - p.normals.push(n); - } - self.facets += 1; - } - - fn finish(self, name: String) -> Result { - if self.facets == 0 { - return Err(perr("STL file without facets")); - } - let mut materials = vec![]; - let mut mesh = Mesh { name, primitives: vec![] }; - for (color, mut p) in self.prims { - if let Some(c) = color { - let lin = c.map(|x| srgb_to_linear(x as f32 / 255.0)); - let name = format!("#{:02X}{:02X}{:02X}", c[0], c[1], c[2]); - materials.push(Material { name, ..Material::plain([lin[0], lin[1], lin[2], 1.0], 0.0, 0.5) }); - p.material = Some(materials.len() - 1); - } - mesh.primitives.push(p); - } - // Uncoloured facets next to coloured ones: a neutral grey of their own. - if !materials.is_empty() { - for p in mesh.primitives.iter_mut().filter(|p| p.material.is_none()) { - materials.push(Material { name: "STL".into(), ..Material::plain([0.6, 0.6, 0.6, 1.0], 0.0, 0.5) }); - p.material = Some(materials.len() - 1); - } - } - Ok(Model::single(mesh, materials)) +/// Parse an STL file (binary or ASCII, detected from the contents). +pub fn parse(bytes: &[u8]) -> Result { + let mut scene = craft_mesh::stl::read(bytes, &limits()).map_err(error)?; + for m in &mut scene.meshes { + m.positions.iter_mut().chain(m.normals.iter_mut()).for_each(|v| *v = y_up(*v)); } -} - -fn f32_at(b: &[u8], at: usize) -> f32 { - b.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map_or(f32::NAN, f32::from_le_bytes) -} - -/// A 5-bit channel expanded to 8 bits. -fn five(x: u16) -> u8 { - let x = (x & 31) as u8; - (x << 3) | (x >> 2) -} - -/// The Magics `COLOR=` part colour in the header (RGB; alpha is ignored). -fn header_color(header: &[u8]) -> Option<[u8; 3]> { - let at = header.windows(6).position(|w| w == b"COLOR=")?; - let c = header.get(at + 6..at + 10)?; - Some([*c.first()?, *c.get(1)?, *c.get(2)?]) -} - -fn binary(bytes: &[u8]) -> Result { - let header = bytes.get(..80).ok_or_else(|| perr("STL header truncated"))?; - let magics = header_color(header); - let body = bytes.get(HEADER..).unwrap_or(&[]); - let count = bytes.get(80..HEADER).and_then(|b| <[u8; 4]>::try_from(b).ok()).map_or(0, u32::from_le_bytes) as usize; - let mut b = Builder::default(); - for f in body.as_chunks::().0.iter().take(count) { - let n = [f32_at(f, 0), f32_at(f, 4), f32_at(f, 8)]; - let v = [0usize, 1, 2].map(|k| [f32_at(f, 12 + 12 * k), f32_at(f, 16 + 12 * k), f32_at(f, 20 + 12 * k)]); - let attr = f.get(48..50).and_then(|a| <[u8; 2]>::try_from(a).ok()).map_or(0, u16::from_le_bytes); - let color = match magics { - Some(part) => Some(if attr & 0x8000 == 0 { [five(attr), five(attr >> 5), five(attr >> 10)] } else { part }), - None => (attr & 0x8000 != 0).then(|| [five(attr >> 10), five(attr >> 5), five(attr)]), - }; - b.tri(color, n, v); - } - let text = String::from_utf8_lossy(header); - let name = text.trim_matches(|c: char| c == '\0' || c.is_whitespace()); - b.finish(name.strip_prefix("solid").unwrap_or(name).trim().to_string()) -} - -/// Three numbers from the rest of an ASCII line. -fn three<'a>(it: &mut impl Iterator) -> Option<[f32; 3]> { - Some([it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next()?.parse().ok()?]) -} - -fn ascii(bytes: &[u8]) -> Result { - let text = String::from_utf8_lossy(bytes); - let mut b = Builder::default(); - let mut name: Option = None; - let mut normal = [0.0f32; 3]; - let mut loop_v: Vec<[f32; 3]> = vec![]; - for (ln, line) in text.lines().enumerate() { - let line = line.trim(); - let mut it = line.split_whitespace(); - let Some(key) = it.next() else { continue }; - let bad = || perr(format!("STL line {}: expected three numbers", ln + 1)); - match key.to_ascii_lowercase().as_str() { - "solid" if name.is_none() => { - name = Some(line.get(5..).unwrap_or("").trim().to_string()); - } - "facet" => { - // `facet normal nx ny nz` - normal = it.next().and_then(|_| three(&mut it)).unwrap_or([0.0; 3]); - loop_v.clear(); - } - "vertex" => loop_v.push(three(&mut it).ok_or_else(bad)?), - "endloop" | "endfacet" => { - if let Some((&first, rest)) = loop_v.split_first() { - for w in rest.windows(2) { - if let [a, c] = w { - b.tri(None, normal, [first, *a, *c]); - } - } - } - loop_v.clear(); - } - _ => {} - } - } - b.finish(name.unwrap_or_default()) + to_model(scene, MissingNormals::Flat, &|_| None) } diff --git a/crates/model/src/tests.rs b/crates/model/src/tests.rs index fd3576afe..8c6a347fb 100644 --- a/crates/model/src/tests.rs +++ b/crates/model/src/tests.rs @@ -119,6 +119,22 @@ fn obj_without_normals_gets_them() { assert!(obj::parse(b"v 0 0 0\n", &|_| None).is_err()); } +#[test] +fn obj_mixed_authored_normals_keep_flat_missing_corners() { + let src = b"v 0 0 0\nv 1 0 0\nv 0 1 0\nv 0 0 1\nvn 0 1 0\ns off\nf 1//1 2 3\nf 1 3 4\n"; + let m = obj::parse(src, &|_| None).unwrap(); + let corners: Vec<_> = m.meshes[0] + .primitives + .iter() + .flat_map(|p| p.positions.iter().zip(&p.normals)) + .filter(|(position, _)| **position == [0.0, 1.0, 0.0]) + .map(|(_, normal)| *normal) + .collect(); + assert!(corners.contains(&[0.0, 0.0, 1.0]), "{corners:?}"); + assert!(corners.contains(&[1.0, 0.0, 0.0]), "{corners:?}"); + assert!(m.meshes[0].primitives.iter().any(|p| p.normals.contains(&[0.0, 1.0, 0.0]))); +} + #[test] fn obj_textures_from_another_machine_find_the_file_next_to_the_model() { // No committed media: the material file and its textures are written by the test itself. @@ -649,9 +665,9 @@ fn gltf_accessor_counts_are_checked_against_the_buffer_before_allocating() { let view = r#"{"buffer": 0, "byteLength": 36}"#; let cases = [ // A count far beyond the 36-byte buffer. - (r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 4000000000}"#, view, "past its buffer"), + (r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 4000000000}"#, view, "limit allows"), // count * components overflows. - (r#"{"bufferView": 0, "componentType": 5126, "type": "MAT4", "count": 9223372036854775807}"#, view, "too large"), + (r#"{"bufferView": 0, "componentType": 5126, "type": "MAT4", "count": 9223372036854775807}"#, view, "limit allows"), // Offsets that overflow when added. ( r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 3, "byteOffset": 16}"#, @@ -659,11 +675,11 @@ fn gltf_accessor_counts_are_checked_against_the_buffer_before_allocating() { "past its buffer", ), // A stride that overflows with the count. - (r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 3000000000}"#, r#"{"buffer": 0, "byteStride": 252}"#, "past its buffer"), + (r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 3000000000}"#, r#"{"buffer": 0, "byteStride": 252}"#, "limit allows"), // A stride smaller than an element would re-read the same bytes for a huge count. (r#"{"bufferView": 0, "componentType": 5126, "type": "MAT4", "count": 30}"#, r#"{"buffer": 0, "byteStride": 1}"#, "smaller than"), // No buffer view: nothing backs the count, so it is capped. - (r#"{"componentType": 5126, "type": "VEC3", "count": 1000000000}"#, view, "without a bufferView"), + (r#"{"componentType": 5126, "type": "VEC3", "count": 1000000000}"#, view, "limit allows"), ]; let t0 = std::time::Instant::now(); for (acc, v, want) in cases { @@ -721,67 +737,15 @@ fn gltf_issue_2139_huge_mat4_count_is_an_error() { } #[test] -fn gltf_buffer_less_accessors_share_one_zero_budget() { - // Each buffer-less accessor is capped, but nothing backs any of them, so referencing a capped - // one from many primitives must not multiply the allocation (#2139). +fn gltf_reused_buffer_less_accessor_is_read_once() { + // The shared reader parses a repeated accessor only once, so referencing it from several + // primitives does not multiply its one bounded allocation. let acc = r#"{"componentType": 5126, "type": "VEC3", "count": 5000000}"#; let prims = [r#"{"attributes": {"POSITION": 0}}"#; 4].join(", "); let doc = gltf_doc(acc, r#"{"buffer": 0}"#, 3).replace(r#"[{"attributes": {"POSITION": 0}}]"#, &format!("[{prims}]")); assert_eq!(doc.matches(r#""POSITION": 0"#).count(), 4); - let e = crate::gltf::parse(doc.as_bytes(), &|_| None).err().unwrap_or_else(|| panic!("imported")); - assert!(e.to_string().contains("without a bufferView"), "{e}"); - // One such accessor read once still imports. - let doc = gltf_doc(acc, r#"{"buffer": 0}"#, 3); - assert!(crate::gltf::parse(doc.as_bytes(), &|_| None).is_ok()); -} - -/// `refs` primitives sharing one buffer-backed `verts`-vertex POSITION accessor, without indices. -fn gltf_shared_positions(verts: usize, refs: usize) -> String { - let acc = format!(r#"{{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": {verts}}}"#); - let prims = vec![r#"{"attributes": {"POSITION": 0}}"#; refs].join(", "); - gltf_doc(&acc, r#"{"buffer": 0}"#, verts * 12).replace(r#"[{"attributes": {"POSITION": 0}}]"#, &format!("[{prims}]")) -} - -#[test] -fn gltf_buffer_backed_reads_share_one_read_budget() { - // A buffer-backed accessor is checked against its buffer, but each primitive that references - // it reads and keeps its own copy, so a small file listing many references must not ask for - // memory set by the reference count (#2139 review). Everything a primitive keeps is charged - // to one per-file budget: 1,000 vertices without indices or normals cost 3,000 position - // components, 1,000 generated indices, a 999-index triangle list and 999 flat-shaded - // vertices of 6 components, 10,993 in all. - let one = gltf_shared_positions(1000, 1); - let m = crate::gltf::parse_with_budget(one.as_bytes(), &|_| None, 20_000).unwrap(); - assert_eq!(m.meshes[0].primitives.len(), 1); - let three = gltf_shared_positions(1000, 3); - assert_eq!(three.matches(r#""POSITION": 0"#).count(), 3); - let e = crate::gltf::parse_with_budget(three.as_bytes(), &|_| None, 20_000).err().unwrap_or_else(|| panic!("imported")); - assert!(e.to_string().contains("more than 20000 components"), "{e}"); - // The real cap leaves room for legitimate sharing: many primitives over one vertex buffer. - let m = crate::gltf::parse(gltf_shared_positions(1000, 50).as_bytes(), &|_| None).unwrap(); - assert_eq!(m.meshes[0].primitives.len(), 50); -} - -#[test] -fn gltf_missing_indices_are_charged_to_the_read_budget() { - // Without `indices` every vertex gets a generated index, allocated like a read: after the - // 3,000 position components, 999 left is one short for the 1,000 indices. - let doc = gltf_shared_positions(1000, 1); - let e = crate::gltf::parse_with_budget(doc.as_bytes(), &|_| None, 3999).err().unwrap_or_else(|| panic!("imported")); - assert!(e.to_string().contains("(1000 requested, 999 left)"), "{e}"); -} - -#[test] -fn gltf_strip_expansion_is_charged_to_the_read_budget() { - // A strip of k indices becomes 3(k-2) triangle indices and as many flat-shaded vertices, so - // the output is charged, not only the 1,009 components read. - let doc = gltf_doc(r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 3}"#, r#"{"buffer": 0}"#, 1036) - .replace(r#""count": 3}]"#, r#""count": 3}, {"bufferView": 0, "componentType": 5121, "type": "SCALAR", "count": 1000}]"#) - .replace(r#""attributes": {"POSITION": 0}"#, r#""attributes": {"POSITION": 0}, "indices": 1, "mode": 5"#); - let m = crate::gltf::parse_with_budget(doc.as_bytes(), &|_| None, 30_000).unwrap(); - assert_eq!(m.meshes[0].primitives[0].indices.len(), 2994); - let e = crate::gltf::parse_with_budget(doc.as_bytes(), &|_| None, 5000).err().unwrap_or_else(|| panic!("imported")); - assert!(e.to_string().contains("more than 5000 components"), "{e}"); + let result = crate::gltf::parse(doc.as_bytes(), &|_| None); + assert!(result.is_ok(), "{result:?}"); } #[test] diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index bf6148569..68aabfbd7 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-eps = { workspace = true } craft-pdf.workspace = true effectcraft-svg = { workspace = true } kurbo = { workspace = true } diff --git a/crates/pdf/README.md b/crates/pdf/README.md index a88adff0b..53689ba9a 100644 --- a/crates/pdf/README.md +++ b/crates/pdf/README.md @@ -144,7 +144,7 @@ ffmpeg elsewhere) to check the code tables against an independent implementation ## Shared parser setup and bounds The workspace pins `craft-pdf` to `craft-libs` Git revision -`e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4`, with `default-features = false` and only the explicit `read` +`091863e4a615f38743bfd5d6dc62a2e8f37cd5d5`, with `default-features = false` and only the explicit `read` feature. This excludes the backend's bundled fonts and Adobe CMaps and preserves EffectCraft's font and asset policies. The shared parser does not change the supported drawing operators, image codecs, continuously rasterized SVG tree, editable shapes, or EPS interpreter. diff --git a/crates/pdf/src/ps/eps.rs b/crates/pdf/src/ps/eps.rs index 8fb72698a..e89b1d276 100644 --- a/crates/pdf/src/ps/eps.rs +++ b/crates/pdf/src/ps/eps.rs @@ -1,31 +1,11 @@ use super::{HashMap, Rc, is_white}; /// The PostScript section of an EPS file (DOS EPS binary header handled) and its bounding box -/// (`%%HiResBoundingBox` preferred). +/// (`%%HiResBoundingBox` preferred), read with `craft-eps`: the header comments, and the trailer +/// for a box deferred with `(atend)`. A binary header that points outside the file is refused. pub fn eps_parts(bytes: &[u8]) -> Option<(&[u8], [f64; 4])> { - let ps = if bytes.starts_with(&[0xC5, 0xD0, 0xD3, 0xC6]) && bytes.len() >= 12 { - let off = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize; - let len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize; - bytes.get(off..off.checked_add(len)?.min(bytes.len()))? - } else { - bytes - }; - let find_box = |key: &[u8]| -> Option<[f64; 4]> { - let mut from = 0; - while let Some(p) = ps[from..].windows(key.len()).position(|w| w == key) { - let s = from + p + key.len(); - let e = ps[s..].iter().position(|c| matches!(c, b'\n' | b'\r')).map_or(ps.len(), |q| s + q); - let v: Vec = String::from_utf8_lossy(&ps[s..e]).split_whitespace().filter_map(|t| t.parse().ok()).collect(); - if v.len() == 4 && v[2] > v[0] && v[3] > v[1] { - return Some([v[0], v[1], v[2], v[3]]); - } - // A rejected comment is done with: the scan goes on past its line, not over it again. - from = e; - } - None - }; - let bbox = find_box(b"%%HiResBoundingBox:").or_else(|| find_box(b"%%BoundingBox:"))?; - Some((ps, bbox)) + let ps = craft_eps::sections(bytes).ok()?.postscript; + Some((ps, craft_eps::Comments::read(ps).page_box()?)) } pub(super) fn find_from(hay: &[u8], needle: &[u8], from: usize) -> Option { diff --git a/crates/pdf/src/tests/import.rs b/crates/pdf/src/tests/import.rs index 516ff054d..f8c6509c2 100644 --- a/crates/pdf/src/tests/import.rs +++ b/crates/pdf/src/tests/import.rs @@ -563,7 +563,8 @@ fn bounding_box_comments_are_scanned_once() { // A rejected `%%BoundingBox:` comment is not scanned again from each later marker on its // line: 20,000 markers on one line would otherwise take quadratic work. let mut src = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); - src.extend_from_slice("%%BoundingBox: x ".repeat(20_000).as_bytes()); + // Keep the valid comment inside craft-eps's bounded header window. + src.extend_from_slice("%%BoundingBox: x ".repeat(3_000).as_bytes()); src.extend_from_slice(b"\n%%BoundingBox: 0 0 50 50\n0 0 10 10 rectfill\n"); let doc = parse(&src).unwrap(); assert_eq!((doc.width, doc.height), (50.0, 50.0)); diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index b6849041b..46ad240d7 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -10,4 +10,5 @@ rust-version.workspace = true workspace = true [dependencies] +craft-psd = { workspace = true } miniz_oxide = "0.9" diff --git a/crates/psd/src/engine_data.rs b/crates/psd/src/engine_data.rs index 20fa1676d..43dec23d5 100644 --- a/crates/psd/src/engine_data.rs +++ b/crates/psd/src/engine_data.rs @@ -1,316 +1,9 @@ -//! The text engine data of type layers (`EngineData` in the `TySh` descriptor): a PostScript-like -//! tree of dictionaries (`<< /Key value >>`), arrays (`[ ]`), numbers, names, booleans and -//! strings (`(þÿ` + UTF-16BE with backslash escapes `)`). Read best-effort. +//! Engine data (the text engine document of type layers, `TySh`): `craft-psd`'s +//! `engine_data`, re-exported. [`text_style`] is its typed view of the first style run. -/// Bytes that end a bare token or a `/Name` (besides whitespace). -const DELIMITERS: &[u8] = b"[]<>/("; +pub use craft_psd::engine_data::{TextStyle, Value, minimal, parse, parse_lossy, write}; -#[derive(Clone, Debug, PartialEq)] -pub enum EValue { - Dict(Vec<(String, EValue)>), - Array(Vec), - Num(f64), - Bool(bool), - Name(String), - Str(String), -} - -impl EValue { - pub fn get(&self, key: &str) -> Option<&EValue> { - match self { - EValue::Dict(v) => v.iter().find(|(k, _)| k == key).map(|(_, v)| v), - _ => None, - } - } - pub fn idx(&self, i: usize) -> Option<&EValue> { - match self { - EValue::Array(v) => v.get(i), - _ => None, - } - } - /// Follow a `/`-separated path; numeric segments index arrays. - pub fn path(&self, p: &str) -> Option<&EValue> { - let mut cur = self; - for seg in p.split('/').filter(|s| !s.is_empty()) { - cur = match seg.parse::() { - Ok(i) => cur.idx(i)?, - Err(_) => cur.get(seg)?, - }; - } - Some(cur) - } - pub fn num(&self) -> Option { - match self { - EValue::Num(n) => Some(*n), - _ => None, - } - } - pub fn str(&self) -> Option<&str> { - match self { - EValue::Str(s) | EValue::Name(s) => Some(s), - _ => None, - } - } -} - -struct P<'a> { - b: &'a [u8], - i: usize, -} - -impl P<'_> { - fn ws(&mut self) { - while self.i < self.b.len() && (self.b[self.i].is_ascii_whitespace() || self.b[self.i] == 0) { - self.i += 1; - } - } - fn peek(&self, s: &[u8]) -> bool { - self.b[self.i..].starts_with(s) - } - fn value(&mut self, depth: usize) -> Option { - if depth > 128 { - return None; - } - self.ws(); - if self.i >= self.b.len() { - return None; - } - if self.peek(b"<<") { - self.i += 2; - let mut v = vec![]; - loop { - self.ws(); - if self.i >= self.b.len() { - return Some(EValue::Dict(v)); - } - if self.peek(b">>") { - self.i += 2; - return Some(EValue::Dict(v)); - } - if self.b[self.i] != b'/' { - // Unexpected token: skip it. - self.i += 1; - continue; - } - let key = self.name(); - let val = self.value(depth + 1)?; - v.push((key, val)); - } - } - match self.b[self.i] { - b'[' => { - self.i += 1; - let mut v = vec![]; - loop { - self.ws(); - if self.i >= self.b.len() { - return Some(EValue::Array(v)); - } - if self.b[self.i] == b']' { - self.i += 1; - return Some(EValue::Array(v)); - } - let start = self.i; - match self.value(depth + 1) { - Some(x) => v.push(x), - None => return Some(EValue::Array(v)), - } - if self.i == start { - self.i += 1; - } - } - } - b'/' => Some(EValue::Name(self.name())), - b'(' => Some(EValue::Str(self.string())), - _ => { - let start = self.i; - while self.i < self.b.len() && !self.b[self.i].is_ascii_whitespace() && !DELIMITERS.contains(&self.b[self.i]) { - self.i += 1; - } - let tok = std::str::from_utf8(&self.b[start..self.i]).unwrap_or(""); - if self.i == start { - self.i += 1; - return Some(EValue::Name(String::new())); - } - Some(match tok { - "true" => EValue::Bool(true), - "false" => EValue::Bool(false), - // "nan", "inf" and overflowing literals parse as f64 but are not numbers here. - t => match t.parse::() { - Ok(n) if n.is_finite() => EValue::Num(n), - _ => EValue::Name(t.to_string()), - }, - }) - } - } - } - fn name(&mut self) -> String { - self.i += 1; // '/' - let start = self.i; - while self.i < self.b.len() && !self.b[self.i].is_ascii_whitespace() && !DELIMITERS.contains(&self.b[self.i]) { - self.i += 1; - } - String::from_utf8_lossy(&self.b[start..self.i]).into_owned() - } - fn string(&mut self) -> String { - self.i += 1; // '(' - let mut raw = vec![]; - while self.i < self.b.len() { - let c = self.b[self.i]; - self.i += 1; - match c { - b'\\' if self.i < self.b.len() => { - let e = self.b[self.i]; - self.i += 1; - raw.push(match e { - b'n' => b'\n', - b'r' => b'\r', - b't' => b'\t', - other => other, - }); - } - b')' => break, - _ => raw.push(c), - } - } - if raw.starts_with(&[0xFE, 0xFF]) { - let u: Vec = raw[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); - String::from_utf16_lossy(&u).trim_end_matches('\0').to_string() - } else { - String::from_utf8_lossy(&raw).into_owned() - } - } -} - -/// Parse engine data (returns an empty dictionary on garbage). -pub fn parse(b: &[u8]) -> EValue { - let mut p = P { b, i: 0 }; - p.value(0).unwrap_or(EValue::Dict(vec![])) -} - -/// Encode a string the way engine data stores it (UTF-16BE with a BOM, escaped). -pub fn encode_string(s: &str) -> Vec { - let mut out = vec![b'(', 0xFE, 0xFF]; - for u in s.encode_utf16() { - for b in u.to_be_bytes() { - if matches!(b, b'(' | b')' | b'\\') { - out.push(b'\\'); - } - out.push(b); - } - } - out.push(b')'); - out -} - -/// The first style run's character attributes. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct TextStyle { - pub font: Option, - pub size: Option, - /// RGB 0..1. - pub color: Option<[f64; 3]>, - /// 0 left, 1 right, 2 centre, 3+ justified variants. - pub justification: Option, - pub tracking: Option, - pub leading: Option, - pub faux_bold: bool, - pub faux_italic: bool, - /// Paragraph (box) text rather than point text. - pub box_text: bool, -} - -/// Sane upper bound for a font size in points (Photoshop's own limit is 1296 pt). -const MAX_FONT_SIZE: f64 = 10_000.0; -/// Sane bound for tracking (1/1000 em) and leading (points). -const MAX_SPACING: f64 = 100_000.0; - -pub fn text_style(ed: &EValue) -> TextStyle { - let engine = ed.get("EngineDict").unwrap_or(ed); - let resources = ed.get("ResourceDict").or_else(|| ed.get("DocumentResources")); - let run = engine.path("StyleRun/RunArray/0/StyleSheet/StyleSheetData"); - let normal = resources.and_then(|r| r.path("StyleSheetSet/0/StyleSheetData")); - let attr = |k: &str| run.and_then(|r| r.get(k)).or_else(|| normal.and_then(|n| n.get(k))); - let font = - attr("Font").and_then(EValue::num).and_then(|i| resources?.path(&format!("FontSet/{}/Name", i as usize))).and_then(EValue::str).map(str::to_string); - let color = attr("FillColor").and_then(|c| c.get("Values")).and_then(|v| match v { - EValue::Array(a) if a.len() >= 4 => Some([a[1].num()?, a[2].num()?, a[3].num()?]), - _ => None, - }); - let para = engine.path("ParagraphRun/RunArray/0/ParagraphSheet/Properties"); - let para_normal = resources.and_then(|r| r.path("ParagraphSheetSet/0/Properties")); - let justification = - para.and_then(|p| p.get("Justification")).or_else(|| para_normal.and_then(|p| p.get("Justification"))).and_then(EValue::num).map(|n| n as u8); - let auto_leading = attr("AutoLeading").is_none_or(|v| *v != EValue::Bool(false)); - let box_text = engine.path("Rendered/Shapes/Children/0/ShapeType").and_then(EValue::num) == Some(1.0); - TextStyle { - font, - size: attr("FontSize").and_then(EValue::num).filter(|s| *s > 0.0).map(|s| s.min(MAX_FONT_SIZE)), - color, - justification, - tracking: attr("Tracking").and_then(EValue::num).map(|t| t.clamp(-MAX_SPACING, MAX_SPACING)), - leading: if auto_leading { None } else { attr("Leading").and_then(EValue::num).map(|l| l.clamp(-MAX_SPACING, MAX_SPACING)) }, - faux_bold: attr("FauxBold") == Some(&EValue::Bool(true)), - faux_italic: attr("FauxItalic") == Some(&EValue::Bool(true)), - box_text, - } -} - -/// Minimal engine data for a type layer with one style run (fixtures, and what a writer needs). -pub fn minimal(text: &str, font: &str, size: f64, color: [f64; 3], justification: u8) -> Vec { - let mut out = Vec::new(); - out.extend_from_slice(b"\n\n<<\n\t/EngineDict\n\t<<\n\t\t/Editor << /Text "); - out.extend_from_slice(&encode_string(&format!("{text}\r"))); - out.extend_from_slice(b" >>\n\t\t/ParagraphRun << /RunArray [ << /ParagraphSheet << /Properties << /Justification "); - out.extend_from_slice(justification.to_string().as_bytes()); - out.extend_from_slice(b" >> >> >> ] >>\n\t\t/StyleRun << /RunArray [ << /StyleSheet << /StyleSheetData << /Font 0 /FontSize "); - out.extend_from_slice(format!("{size:.1}").as_bytes()); - out.extend_from_slice( - format!(" /FillColor << /Type 1 /Values [ 1.0 {:.5} {:.5} {:.5} ] >> /AutoLeading true >> >> >> ] >>\n\t>>\n", color[0], color[1], color[2]).as_bytes(), - ); - out.extend_from_slice(b"\t/ResourceDict << /FontSet [ << /Name "); - out.extend_from_slice(&encode_string(font)); - out.extend_from_slice(b" /Type 0 >> ] >>\n>>"); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_minimal() { - let b = minimal("Hi (there)", "Arial-BoldMT", 36.0, [1.0, 0.5, 0.0], 2); - let v = parse(&b); - assert_eq!(v.path("EngineDict/Editor/Text").and_then(EValue::str), Some("Hi (there)\r")); - let st = text_style(&v); - assert_eq!(st.font.as_deref(), Some("Arial-BoldMT")); - assert_eq!(st.size, Some(36.0)); - assert_eq!(st.color, Some([1.0, 0.5, 0.0])); - assert_eq!(st.justification, Some(2)); - assert!(!st.box_text); - } - - #[test] - fn garbage_is_harmless() { - let _ = parse(b"<< /A [ 1 2 << /B (unterminated"); - let _ = parse(b"]]]>>>> /x"); - let _ = parse(&[0xFF; 64]); - } - - #[test] - fn non_finite_and_out_of_range_numbers_are_not_numbers() { - let b = b"<< /FontSize nan /Tracking inf /Leading -inf /Other 1e999 >>"; - let v = parse(b); - assert_eq!(v.get("FontSize").and_then(EValue::num), None); - assert_eq!(v.get("Other").and_then(EValue::num), None); - let ed = parse(b"<< /EngineDict << /StyleRun << /RunArray [ << /StyleSheet << /StyleSheetData << /FontSize nan /Tracking inf /Leading -inf /AutoLeading false >> >> >> ] >> >> >>"); - let st = text_style(&ed); - assert_eq!((st.size, st.tracking, st.leading), (None, None, None)); - let ed = parse(b"<< /EngineDict << /StyleRun << /RunArray [ << /StyleSheet << /StyleSheetData << /FontSize 1e300 /Tracking -1e300 /AutoLeading false /Leading 1e300 >> >> >> ] >> >> >>"); - let st = text_style(&ed); - assert_eq!(st.size, Some(MAX_FONT_SIZE)); - assert_eq!(st.tracking, Some(-MAX_SPACING)); - assert_eq!(st.leading, Some(MAX_SPACING)); - } +/// The first style run's character and paragraph attributes of a parsed document. +pub fn text_style(ed: &Value) -> TextStyle { + craft_psd::engine_data::first_style(ed) } diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index d221b9044..6357b0024 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -287,7 +287,7 @@ impl Psd { let d = descriptor::read_descriptor(&mut r)?; let text = d.text("Txt ").unwrap_or_default().replace("\r\n", "\n").replace('\r', "\n"); let text = text.strip_suffix('\n').map(str::to_string).unwrap_or(text); - let style = d.raw("EngineData").map(|e| engine_data::text_style(&engine_data::parse(e))).unwrap_or_default(); + let style = d.raw("EngineData").map(|e| engine_data::text_style(&engine_data::parse_lossy(e))).unwrap_or_default(); let bounds = d.obj("bounds").or_else(|| d.obj("boundingBox")).and_then(|o| Some([o.num("Left")?, o.num("Top ")?, o.num("Rght")?, o.num("Btom")?])); l.text = Some(TextInfo { text, transform: t, style, bounds }); diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index 7cd4fbe5a..9e11b781d 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-exr = { workspace = true } effectcraft-geom = { workspace = true } effectcraft-color = { workspace = true } rayon = { workspace = true } diff --git a/crates/raster/src/channels3d.rs b/crates/raster/src/channels3d.rs index ae2d38303..05473ca80 100644 --- a/crates/raster/src/channels3d.rs +++ b/crates/raster/src/channels3d.rs @@ -66,36 +66,19 @@ impl AuxChannels { /// The layers of the channels (OpenEXR layers: the name before the last `.`; `""` for the /// unnamed layer), in channel order. pub fn layers(&self) -> Vec<&str> { - let mut out: Vec<&str> = vec![]; - for (n, _) in &self.channels { - let (layer, _) = split_channel(n); - if !out.contains(&layer) { - out.push(layer); - } - } - out + craft_exr::channels::layers(self.channels.iter().map(|(n, _)| n.as_str())) } /// A layer's channels as the names to show in red, green, blue and alpha (`""` = none): /// its R, G, B, A channels (or red / green / blue / alpha, X / Y / Z, U / V); a layer of one /// channel (depth, an ID) shows it in all three colours. pub fn layer_rgba(&self, layer: &str) -> [String; 4] { - let chans: Vec<&str> = self.channels.iter().map(|(n, _)| n.as_str()).filter(|n| split_channel(n).0 == layer).collect(); - let pick = |names: &[&str]| -> String { - chans.iter().find(|c| names.iter().any(|n| split_channel(c).1.eq_ignore_ascii_case(n))).map_or(String::new(), |c| c.to_string()) - }; - if let [one] = chans.as_slice() { - return [one.to_string(), one.to_string(), one.to_string(), String::new()]; - } - [pick(&["R", "red", "X", "U"]), pick(&["G", "green", "Y", "V"]), pick(&["B", "blue", "Z"]), pick(&["A", "alpha"])] + craft_exr::channels::layer_rgba(self.channels.iter().map(|(n, _)| n.as_str()), layer) + .map(|i| i.and_then(|i| self.channels.get(i)).map_or(String::new(), |(n, _)| n.clone())) } } -/// A channel name's layer and channel: `diffuse.R` → (`diffuse`, `R`), `ViewLayer.Combined.R` -/// → (`ViewLayer.Combined`, `R`), `Z` → (`""`, `Z`). -pub fn split_channel(name: &str) -> (&str, &str) { - name.rsplit_once('.').unwrap_or(("", name)) -} +pub use craft_exr::channels::split_channel; impl AuxChannels { pub fn depth(&self) -> Option<&[f32]> { @@ -206,42 +189,7 @@ impl AuxChannels { } } -/// MurmurHash3 x86 32-bit (public-domain algorithm by Austin Appleby). -pub fn murmur3_32(data: &[u8], seed: u32) -> u32 { - const C1: u32 = 0xcc9e_2d51; - const C2: u32 = 0x1b87_3593; - let mut h = seed; - let (chunks, tail) = data.as_chunks::<4>(); - for c in chunks { - let mut k = u32::from_le_bytes([c[0], c[1], c[2], c[3]]); - k = k.wrapping_mul(C1).rotate_left(15).wrapping_mul(C2); - h ^= k; - h = h.rotate_left(13).wrapping_mul(5).wrapping_add(0xe654_6b64); - } - let mut k = 0u32; - for (i, b) in tail.iter().enumerate() { - k ^= (*b as u32) << (8 * i); - } - if !tail.is_empty() { - k = k.wrapping_mul(C1).rotate_left(15).wrapping_mul(C2); - h ^= k; - } - h ^= data.len() as u32; - h ^= h >> 16; - h = h.wrapping_mul(0x85eb_ca6b); - h ^= h >> 13; - h = h.wrapping_mul(0xc2b2_ae35); - h ^= h >> 16; - h -} - -/// Cryptomatte hash of a name (the manifest value). -pub fn crypto_hash(name: &str) -> u32 { - let h = murmur3_32(name.as_bytes(), 0); - // Keep the float finite and normal: flip the low exponent bit when it is all 0s or 1s. - let e = (h >> 23) & 0xff; - if e == 0 || e == 255 { h ^ (1 << 23) } else { h } -} +pub use craft_exr::cryptomatte::{hash as crypto_hash, murmur3_32}; /// The ID float stored in Cryptomatte channels for a hash. pub fn crypto_float(hash: u32) -> f32 { diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index 73b7ce830..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)) } } @@ -355,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/svg/Cargo.toml b/crates/svg/Cargo.toml index e542bed47..6a1e4d741 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-svg = { workspace = true } effectcraft-geom = { workspace = true } effectcraft-raster = { workspace = true } effectcraft-path = { workspace = true } diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index cba08d81b..dc41f67fd 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -35,11 +35,9 @@ impl std::fmt::Display for Error { impl std::error::Error for Error {} -/// Quick sniff: an XML document whose root looks like ` bool { - let head = &bytes[..bytes.len().min(2048)]; - let s = String::from_utf8_lossy(head); - s.contains(" usize { - let b = text.as_bytes(); - let (mut i, mut depth, mut max) = (0usize, 0usize, 0usize); - let skip_to = |from: usize, end: &[u8]| b.get(from..).and_then(|r| r.windows(end.len()).position(|w| w == end)).map_or(b.len(), |p| from + p + end.len()); - while i < b.len() { - if b[i] != b'<' { - i += 1; - continue; - } - let rest = &b[i..]; - if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else { - // A start tag: find its end outside quotes; `/>` closes it at once. - let mut j = i + 1; - let mut quote = None; - while let Some(&c) = b.get(j) { - match quote { - Some(q) if c == q => quote = None, - Some(_) => {} - None if c == b'"' || c == b'\'' => quote = Some(c), - None if c == b'>' => break, - None => {} - } - j += 1; - } - if b.get(j.wrapping_sub(1)) != Some(&b'/') { - depth += 1; - max = max.max(depth); - } - i = j + 1; - } - } - max -} - /// Nodes a document may expand to: a few kilobytes of nested internal entities /// (``) otherwise expand to millions and exhaust memory. const MAX_XML_NODES: u32 = 4_000_000; @@ -1781,7 +1732,7 @@ const MAX_XML_NODES: u32 = 4_000_000; pub fn parse(bytes: &[u8]) -> Result { let text = String::from_utf8_lossy(bytes); let text = text.trim_start_matches('\u{feff}'); - if xml_depth(text) > MAX_XML_DEPTH { + if craft_svg::guard::deeper_than(text, MAX_XML_DEPTH) { return Err(Error::Xml(format!("elements nested more than {MAX_XML_DEPTH} levels deep"))); } // DTDs stay allowed (Illustrator's SVGs declare entities), but expansion is bounded (#2129). diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index 3c7f37a88..c0c2ed55e 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -730,6 +730,8 @@ fn malformed_input() { assert_eq!(d.skipped, vec!["text".to_string()]); assert!(looks_like_svg(BASIC)); assert!(!looks_like_svg(b"\x89PNG")); + // The first element must be the `svg`: an HTML page with an inline SVG is not one. + assert!(!looks_like_svg(b"")); } #[test] @@ -767,7 +769,7 @@ fn deep_nesting_errors_instead_of_overflowing_the_stack() { "".repeat(1000), "".repeat(1000) ); - assert_eq!(crate::xml_depth(&s), 2); + assert!(!craft_svg::guard::deeper_than(&s, 3) && craft_svg::guard::deeper_than(&s, 2)); assert!(crate::parse(s.as_bytes()).is_ok()); } diff --git a/docs/testing.md b/docs/testing.md index f4bdbaf79..34682d119 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -20,6 +20,9 @@ cargo xtask aep-corpus EFFECTCRAFT_AEP_FIXTURES=corpus/aep EFFECTCRAFT_AEP_FIXTURES_REQUIRED=1 cargo test -p effectcraft-aep ``` +The container and typed-view tests are in `craft-aep` ([storytold/craft-libs](https://github.com/storytold/craft-libs)), +which reads the same corpus from `CRAFT_AEP_FIXTURES` (and `CRAFT_AEP_FIXTURES_REQUIRED`). + The `dev` profile keeps debug info to line tables (fast builds, readable backtraces). To debug interactively — local variables, parameters, column breakpoints — build with the `dev-full` profile: `cargo run --profile dev-full -p effectcraft -- --demo` (see `CONTRIBUTING.md`). diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index beb1e0cc9..a4ed9d6dd 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"; +const REV: &str = "47107f660191de2f0b425569506f4daa4faadac9"; const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("hayro-syntax", "0.7.2"), ("hayro-jbig2", "0.3.0")]; pub fn run(root: &Path) -> Result<(), String> {