diff --git a/Cargo.lock b/Cargo.lock index 5f3a3cfb212b0b2f40d7b5853f6ce472f4060ff0..545c02186a88a4387ca5129d38f7a65f1f471879 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -75,8 +75,8 @@ dependencies = [ "accesskit_consumer", "hashbrown 0.17.2", "static_assertions", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -134,6 +134,28 @@ version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" +[[package]] +name = "alsa" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43" +dependencies = [ + "alsa-sys", + "bitflags 2.13.2", + "cfg-if", + "libc", +] + +[[package]] +name = "alsa-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527" +dependencies = [ + "libc", + "pkg-config", +] + [[package]] name = "android-activity" version = "0.6.1" @@ -143,12 +165,12 @@ dependencies = [ "android-properties", "bitflags 2.13.2", "cc", - "jni", + "jni 0.22.4", "libc", "log", - "ndk", + "ndk 0.9.0", "ndk-context", - "ndk-sys", + "ndk-sys 0.6.0+11769913", "num_enum", "thiserror 2.0.21", ] @@ -362,6 +384,24 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -527,7 +567,22 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", ] [[package]] @@ -542,6 +597,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -633,6 +699,55 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "coreaudio-rs" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "321077172d79c662f64f5071a03120748d5bb652f5231570141be24cfcd2bace" +dependencies = [ + "bitflags 1.3.2", + "core-foundation-sys", + "coreaudio-sys", +] + +[[package]] +name = "coreaudio-sys" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9b4739a805a62757a83e5654fa3faabec0442666b263bb2287d5a8185bfd953" +dependencies = [ + "bindgen", +] + +[[package]] +name = "cpal" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "873dab07c8f743075e57f524c583985fbaf745602acbe916a01539364369a779" +dependencies = [ + "alsa", + "core-foundation-sys", + "coreaudio-rs", + "dasp_sample", + "jni 0.21.1", + "js-sys", + "libc", + "mach2", + "ndk 0.8.0", + "ndk-context", + "oboe", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows 0.54.0", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -700,6 +815,12 @@ dependencies = [ "serde", ] +[[package]] +name = "dasp_sample" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" + [[package]] name = "data-url" version = "0.3.2" @@ -828,6 +949,20 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -839,11 +974,14 @@ name = "engine" version = "0.1.0" dependencies = [ "bytemuck", + "cc", + "cpal", "exr", "image", "model", "png", "pollster", + "symphonia", "text", "theme", "wgpu", @@ -955,6 +1093,12 @@ dependencies = [ "zune-inflate", ] +[[package]] +name = "extended" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" + [[package]] name = "fastrand" version = "2.5.0" @@ -1174,6 +1318,12 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "glow" version = "0.17.0" @@ -1206,7 +1356,7 @@ dependencies = [ "log", "presser", "thiserror 2.0.21", - "windows", + "windows 0.62.2", ] [[package]] @@ -1371,12 +1521,37 @@ dependencies = [ "hashbrown 0.17.2", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + [[package]] name = "jni" version = "0.22.4" @@ -1504,6 +1679,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "lebe" version = "0.5.3" @@ -1596,6 +1777,15 @@ dependencies = [ "which", ] +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + [[package]] name = "memchr" version = "2.8.3" @@ -1620,6 +1810,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -1707,6 +1903,12 @@ dependencies = [ "target-features", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.2" @@ -1745,6 +1947,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "ndk" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys 0.5.0+25.2.9519653", + "num_enum", + "thiserror 1.0.69", +] + [[package]] name = "ndk" version = "0.9.0" @@ -1754,7 +1970,7 @@ dependencies = [ "bitflags 2.13.2", "jni-sys 0.3.1", "log", - "ndk-sys", + "ndk-sys 0.6.0+11769913", "num_enum", "raw-window-handle", "thiserror 1.0.69", @@ -1766,6 +1982,15 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" +[[package]] +name = "ndk-sys" +version = "0.5.0+25.2.9519653" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691" +dependencies = [ + "jni-sys 0.3.1", +] + [[package]] name = "ndk-sys" version = "0.6.0+11769913" @@ -1775,6 +2000,16 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -1800,6 +2035,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2158,6 +2404,29 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oboe" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8b61bebd49e5d43f5f8cc7ee2891c16e0f41ec7954d36bcb6c14c5e0de867fb" +dependencies = [ + "jni 0.21.1", + "ndk 0.8.0", + "ndk-context", + "num-derive", + "num-traits", + "oboe-sys", +] + +[[package]] +name = "oboe-sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c8bb09a4a2b1d668170cfe0a7d5bc103f8999fb316c98099b6a9939c9f2e79d" +dependencies = [ + "cc", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2768,6 +3037,12 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -3003,6 +3278,141 @@ dependencies = [ "siphasher", ] +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac", + "symphonia-bundle-mp3", + "symphonia-codec-aac", + "symphonia-codec-pcm", + "symphonia-core", + "symphonia-format-isomp4", + "symphonia-format-ogg", + "symphonia-format-riff", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-flac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-aac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", +] + +[[package]] +name = "symphonia-format-isomp4" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5" +dependencies = [ + "encoding_rs", + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f" +dependencies = [ + "extended", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + [[package]] name = "syn" version = "2.0.119" @@ -3534,7 +3944,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -4028,7 +4438,7 @@ dependencies = [ "log", "naga", "naga-types", - "ndk-sys", + "ndk-sys 0.6.0+11769913", "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", @@ -4053,9 +4463,9 @@ dependencies = [ "web-sys", "wgpu-naga-bridge", "wgpu-types", - "windows", - "windows-core", - "windows-result", + "windows 0.62.2", + "windows-core 0.62.2", + "windows-result 0.4.1", ] [[package]] @@ -4105,6 +4515,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "windows" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49" +dependencies = [ + "windows-core 0.54.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows" version = "0.62.2" @@ -4112,7 +4532,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ "windows-collections", - "windows-core", + "windows-core 0.62.2", "windows-future", "windows-numerics", ] @@ -4123,7 +4543,17 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" dependencies = [ - "windows-core", + "windows-core 0.62.2", +] + +[[package]] +name = "windows-core" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65" +dependencies = [ + "windows-result 0.1.2", + "windows-targets 0.52.6", ] [[package]] @@ -4135,7 +4565,7 @@ dependencies = [ "windows-implement", "windows-interface", "windows-link", - "windows-result", + "windows-result 0.4.1", "windows-strings", ] @@ -4145,7 +4575,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "windows-core", + "windows-core 0.62.2", "windows-link", "windows-threading", ] @@ -4184,10 +4614,19 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ - "windows-core", + "windows-core 0.62.2", "windows-link", ] +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -4206,13 +4645,22 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -4221,7 +4669,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -4233,20 +4681,35 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -4258,18 +4721,36 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -4282,24 +4763,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -4328,7 +4833,7 @@ dependencies = [ "js-sys", "libc", "memmap2", - "ndk", + "ndk 0.9.0", "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", diff --git a/KNOWN_GAPS.md b/KNOWN_GAPS.md deleted file mode 100644 index de56ab6215d7091866d1958a9a85dfbe1219a85d..0000000000000000000000000000000000000000 --- a/KNOWN_GAPS.md +++ /dev/null @@ -1,42 +0,0 @@ -# Known Gaps & Roadmap - -Tracked rendering and architecture gaps compared to Blackmagic Fusion Studio 21.1. -Items listed here are **tracked bugs / missing subsystems**, never permanent exclusions. - ---- - -## 1. Cryptomatte (`Fuse.Cryptomatte` — e.g. `01_intro.comp` human character matte) -- **Status:** Tracked known gap (not an intentional exclusion). -- **Symptom:** In `01_intro.comp` (e.g. `f0600`), the human character's orange rim/matte driven by a Cryptomatte pass over multi-channel EXR (`CryptoObject00..02` MurmurHash3 ID/coverage pairs + manifest metadata) is not yet decoded, so the character's Cryptomatte glow/isolation differs from Fusion. -- **Planned fix:** Add multi-channel EXR Cryptomatte layer decoding (`exr` crate already in workspace), parse `cryptomatte//manifest` JSON from EXR header attributes, hash selected `MatteList` names via MurmurHash3-32 (`f32` bit-cast), and accumulate matching ID/coverage rank pairs into the alpha matte. - -## 2. 3D Particle System (`pEmitter`, `pRender`, `pPointForce`) -- **Status:** Tracked missing subsystem (currently reported in `unsupported` on `01_intro.comp`). -- **Symptom:** Particle layers driven by `pEmitter` / `pPointForce` / `pRender` are skipped. -- **Planned fix:** Deterministic frame-stepped particle simulator (seeded per-frame/cached state) feeding into `Scene3D` billboard/point-sprite instancing inside `Renderer3D` / `pRender`. - -## 3. Optical Flow & Retime Vectors (`Dimension.OpticalFlow`, `OpticalFlow`) -- **Status:** Tracked missing subsystem (reported in `unsupported` on `01_intro.comp`). -- **Symptom:** Motion-vector-interpolated retiming falls back to nearest/frame-blended source frames. -- **Planned fix:** GPU dense optical-flow pass (hierarchical Lucas-Kanade / TV-L1 compute shader) writing forward/backward motion vectors for downstream `TimeStretcher` / `VectorMotionBlur`. - -## 4. Project-Defined Bit Depth (`DepthFull` / `DepthInteractive` / `ChangeDepth`) -- **Status:** Implemented (verified `0.00/255` across `int8`/`int16`/`float16`/`float32` + `0.4%` HDR float16 blur on `scripts/fusion_probes.py tier1_d`). -- **Behavior:** - - **`HiQ` mode:** Honors `Comp.Prefs.Comp.FrameFormat.DepthFull`, generator `Depth`, and `ChangeDepth` (`int8` -> `Rgba8Unorm`, `int16` -> clamped `Rgba16Float`, `float16` -> unclamped HDR `Rgba16Float`, `float32` -> unclamped HDR `Rgba32Float` when `FLOAT32_FILTERABLE` is supported, else `Rgba16Float`). Non-8-bit shader pipelines compile lazily on first use. - - **`Fast` mode:** Collapses working render targets to `Rgba8Unorm` (with downsampled blurs / capped `XGlow` octaves) for maximum interactive throughput. - - **Remaining minor gap:** `Loader` uploads 8-bit decoded frames and promotes them to float when requested; direct 16/32-bit float EXR upload without intermediate 8-bit quantization is a follow-up media-layer upgrade. - -## 5. Video Decode Backend (`AVFoundation` / `VideoToolbox` + `ffmpeg` fallback) -- **Status:** Planned media layer upgrade. -- **Current behavior:** Video clips decode via `ffmpeg` subprocesses with LRU frame caching. -- **Target design:** Introduce a `VideoDecoder` trait with a native macOS `AVAssetReader` + `VideoToolbox` hardware backend for zero-copy ProRes / H.264 / HEVC scrubbing, keeping the existing `ffmpeg` CLI backend as a clean cross-platform fallback for Linux/Windows and uncommon codecs. - -## 6. Procedural `FastNoise` Internal Permutation Seed -- **Status:** Known inherent difference vs closed-source Fusion noise table (upgraded to C2 quintic 3D Perlin gradient noise with Fusion isotropic frame-width scaling, `LockXY`, `Angle`, `Detail = 0..10`, and `Discontinuous = 1`). -- **Behavior:** Scale, `Detail`, `Contrast`, `Brightness`, `Seethe`, `SeetheRate`, `XScale`/`YScale`, `Discontinuous`, and `Gradient` / `TwoColor` coloring match Fusion's visual distribution and round C2 blob shape; individual hash peaks (e.g. random star positions on the 3D cylinder in `60_moon_guide_u.comp`) sit at different pseudo-random coordinates because Fusion's internal `FastNoise` lattice/permutation table is proprietary (verified not public Perlin 2002, Perlin 1985, or Simplex 3D). 3D camera projection itself (`Camera3D`, `Transform3D`, `Shape3D` Cylinder, all `RotOrder` permutations, `AoV`/`FLength`/`ResolutionGateFit`) is verified to `0.1%–0.4% MAE` against Fusion 21.1 via `scripts/fusion_probes.py cam3d_fov`. - -## 7. Minor Tool Edge Cases Remaining -- `TextPlus` `ElementShape` `BorderFill` (`ElementShape2 = 2`) and custom font rendering on Linux render node (note: on Snow Globe, mounting `\(site.cloverRoot)/Asset/Font` read-only to `/usr/local/share/fonts/clover` in `~/dev/home-infra/service/fusion/service.pkl` exposes Clover's font library to `FusionRenderNode` without committing font files). -- `Displace` `Type = 0` (`Radial`) `LightPower` specular/bump lighting exact angle & color model (`0.7% MAE` vs `0.1%` without `LightPower`). -- `Glow` tool (`Glow = 0.583, GlowSize = 12`) slight Gaussian tail roll-off (`1.3% MAE`; `SoftGlow` is `0.0%–0.8%`). diff --git a/compatibility.md b/compatibility.md new file mode 100644 index 0000000000000000000000000000000000000000..832452afe64a8aa631bb5e59bbbf564e960b2a44 --- /dev/null +++ b/compatibility.md @@ -0,0 +1,174 @@ +# Fusion 21.1 Compatibility Matrix + +Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/engine/src/scene3d.rs`, `crates/model/src/comp.rs`) and real Fusion `.comp` corpora via `python3 scripts/gen_compatibility.py`. + +- **Tracked Gaps & Issues:** [shale.paperclover.net/fission/issues](https://shale.paperclover.net/fission/issues) +- **Conformance Probes:** [`scripts/fusion_probes.py`](scripts/fusion_probes.py) + +## Summary + +| Metric | Value | +| --- | --- | +| **Supported Flow Tools** | **66** (57 2D/Fuse/utility in `eval.rs`, 7 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | +| **Modifiers & Animation** | **7** systems (8 Fusion modifier classes + Lua expressions) | +| **Active Corpus (`trees/fusion`) Coverage** | **99.1%** (1,975 / 1,993 nodes across 16 `.comp` files) | +| **Archive Corpus (`private/samples`) Coverage** | **95.8%** (52,653 / 54,955 nodes across 324 `.comp` files) | +| **HiQ vs Fast Mode** | **`HiQ`**: honors `DepthFull` / generator `Depth` / `ChangeDepth` (`Rgba8Unorm`, clamped `Rgba16Float`, unclamped HDR `Rgba16Float`/`Rgba32Float`), full-res blurs & `XGlow`. **`Fast`**: collapses working targets to `Rgba8Unorm`, downsamples blurs, caps `XGlow` octaves for interactive scrubbing. | + +## Generators + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `Background` | `tier1_d` | 0.0% | 103 / 1949 | Solid, Horizontal/Vertical/4-Corner, Linear/Radial gradients; honors generator `Depth` in `HiQ`. | +| `FastNoise` | `noise_text` | Visual* | 18 / 201 | C2 quintic 3D Perlin fBm (`Detail`, `Contrast`, `Brightness`, `Seethe`, `LockXY`, `Angle`, `Discontinuous`, `Gradient`/`TwoColor`). *Proprietary Fusion lattice table differs ([#6](https://shale.paperclover.net/fission/issues/6)). | +| `Plasma` | `tier1_c` | 0.1%–0.2% | 0 / 39 | 4-circle linear/sine interference pattern with phase/scale animation. | +| `TextPlus` | `text`, `noise_text` | 0.1%–0.6% | 53 / 2770 | CoreText rasterizer, alignment, tracking, Euclidean subpixel SDF outline, `StyledTextCLS`. `BorderFill` tracked in [#6](https://shale.paperclover.net/fission/issues/6). | +| `Loader` | All suites | 0.0% | 106 / 1274 | PNG/JPG/TIFF/EXR stills & sequences; native macOS `AVFoundation`/`VideoToolbox` + `ffmpeg` video; `.wav`/`.mp3` audio. Direct 16/32-bit float EXR upload tracked in [#5](https://shale.paperclover.net/fission/issues/5). | + +## Compositing & Blending + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `Merge` | `merge` | 0.0%–0.3% | 293 / 6358 | All ApplyModes (`Normal`, `Screen`, `Multiply`, `Difference`, `DarkerColor`, `Overlay`, `Hard/Soft/Linear/VividLight`, `LinearDodge`, etc.), `Operator=Over/Under`, `Gain`, `BurnIn`, `SubtractiveAdditive`, `Blend`, effect mask. | +| `Dissolve` | `tier1_b` | 0.0%–0.1% | 0 / 4 | Mix (`Mix = 0..1`) between `Background` and `Foreground` with effect mask support. | +| `Shadow` | `tier1_b` | 0.1%–0.4% | 0 / 38 | Drop shadow offset, softness blur, tint color/alpha, and `ShadowOnly` output. | + +## Color & Depth + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `BrightnessContrast` | `color_ops`, `tier1_d` | 0.0%–0.1% | 29 / 231 | Gain, Lift, Gamma, Contrast, Brightness, Saturation, channel toggles, `PreDividePostMultiply`, `ClipBlack`/`ClipWhite`. | +| `ColorCorrector` | Suite comps | 0.1%–0.5% | 86 / 1357 | Master/Shadow/Midtone/Highlight wheel tint, Lift/Gamma/Gain/Brightness/Contrast/Saturation, `PreDividePostMultiply`. | +| `ColorGain` | `color_ops`, `noise_text` | 0.0%–0.1% | 2 / 4 | Per-channel Gain, Lift, Gamma, Hue, Saturation, `PreDividePostMultiply`. | +| `ColorCurves` | Suite comps | 0.1%–0.4% | 5 / 109 | Per-channel RGBA `LUTBezier` spline lookup tables with `PreDividePostMultiply`. | +| `HueCurves` | `tier1_a` | 0.1%–0.5% | 6 / 28 | 9 nested `LUTBezier` splines (Hue/Sat/Lum vs Hue, Suppression, etc.) baked to GPU LUT. | +| `GamutConvert` | Suite comps | 0.0%–0.2% | 2 / 32 | Color space & gamma curve transforms (`sRGB`, `Rec.709`, `Linear`, `SLog2`, etc.). | +| `InvertColor` | Suite comps | 0.0% | 0 / 0 | Per-channel RGBA color inversion (`R`/`G`/`B`/`A` toggles). | +| `ChannelBoolean` | `color_ops` | 0.0%–0.1% | 2 / 29 | Channel routing (`ToRed`/`ToGreen`/`ToBlue`/`ToAlpha`) and arithmetic/logic ops (`Copy`, `Add`, `Subtract`, `Multiply`, `Divide`, `Min`, `Max`, `Clear`, `Solid`, etc.). | +| `ChangeDepth` | `tier1_d` | 0.0% | 0 / 24 | Bit-depth conversion (`int8`, `int16`, `float16`, `float32`) honored in `HiQ` mode; collapsed to `Rgba8Unorm` in `Fast` mode. | +| `Fuse.Colorize` | Suite comps | 0.1%–0.5% | 13 / 386 | Gradient/tint colorization driven by luminance. | + +## Keying + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `LumaKeyer` | Suite comps | 0.1%–0.4% | 4 / 95 | Luminance/channel threshold keying with low/high feathering and matte inversion. | +| `UltraKeyer` | `tier1_a` | 0.1%–0.6% | 16 / 66 | Chroma keying with background color pick, matte threshold/gamma, spill suppression, and post-multiply. | + +## Blur, Sharpen & Glow + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `Blur` | `blur`, `tier1_d` | 0.0%–0.4% | 52 / 401 | `Fast Gaussian`, `Gaussian`, and `Box` filters; X/Y lock; `ClippingMode`; HDR float16 survival in `HiQ`; downsampled in `Fast`. | +| `Sharpen` | `tier1_a` | 0.1%–0.4% | 1 / 7 | Separable unsharp mask with X/Y amount & lock. | +| `Filter` | `tier1_a` | 0.1%–0.5% | 0 / 93 | Convolution filter types 0–4 (`Relief`, `Emboss`, `Smooth`, `Sobel`, `Laplacian`) with power & angle. | +| `VariBlur` | Suite comps | 0.2%–0.8% | 1 / 1 | Per-pixel variable-radius blur driven by `BlurImage` matte. | +| `DirectionalBlur` | `blur` | 0.1%–0.5% | 21 / 816 | `Linear`, `Centered`, `Radial`, and `Zoom` modes plus `Glow` accumulation. | +| `Glow` | `glow` | 0.2%–1.3% | 11 / 549 | Additive bloom (`Glow`, `GlowSize`, `Blend`, color scale). Minor Gaussian tail roll-off tracked in [#6](https://shale.paperclover.net/fission/issues/6). | +| `SoftGlow` | `glow` | 0.0%–0.8% | 3 / 30 | Thresholded soft glow (`Gain`, `XGlowSize`/`YGlowSize`, `Threshold`, `ClippingMode`, `ColorScale`). | +| `Fuse.XGlow` | Suite comps | 0.2%–0.8% | 4 / 34 | Multi-octave exponential glow (`Threshold`, `Gain`, `XGlowSize`, `Falloff`, `Iterations`); octave-capped in `Fast` mode. | +| `ErodeDilate` | `blur` | 0.0%–0.3% | 18 / 202 | Positive/negative morphological erode/dilate with `Box` and `Circle` kernels. | +| `FilmGrain` | `tier1_c` | Visual* | 0 / 18 | Monochrome log-space correlated film grain (`Size`, `Strength`, `Softness`). *Stochastic per-frame seed. | +| `Fuse.Outline` | Suite comps | 0.1%–0.5% | 2 / 278 | Alpha-derived silhouette outline with thickness, softness, and color tint. | +| `Fuse.XfChroma` | Suite comps | 0.1%–0.5% | 2 / 17 | Chromatic aberration / RGB channel radial & positional dispersion. | + +## Transform, Warp & Framing + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `Transform` | `xf` | 0.0%–0.3% | 47 / 1211 | `Center`, `Pivot`, `Size`/`XSize`/`YSize`, `Aspect`, `Angle`, `FlipHoriz`/`FlipVert`, `FilterMethod` (`Nearest`/`Box`/`Linear`/`Catmull-Rom`), `Edges` (`Canvas`/`Wrap`/`Duplicate`/`Mirror`). | +| `CameraShake` | `tier1_c` | 0.1%–0.5% | 0 / 12 | Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`. | +| `CornerPositioner` | `tier1_b` | 0.1%–0.4% | 0 / 29 | 4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`). | +| `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). | +| `Displace` | `displace` | 0.1%–0.7% | 11 / 109 | `XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower` angle/color minor parity tracked in [#6](https://shale.paperclover.net/fission/issues/6)). | +| `Scale` | Suite comps | 0.0%–0.2% | 12 / 98 | Proportional/non-proportional image scaling with resampling filter. | +| `BetterResize` | Suite comps | 0.0%–0.2% | 0 / 93 | Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`). | +| `Crop` | Suite comps | 0.0%–0.1% | 3 / 168 | Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`). | +| `SetDomain` | `tier1_d` | 0.0%–0.1% | 0 / 8 | Domain-of-Definition (`Adjust` shrink/expand and `Set` modes). | + +## Masks + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `EllipseMask` | `mask` | 0.0%–0.2% | 33 / 109 | Center, Width, Height, Angle, `SoftEdge`, `BorderWidth`, `Solid`, `Invert`, `PaintMode` chaining. | +| `RectangleMask` | `mask` | 0.0%–0.2% | 53 / 885 | Center, Width, Height, `CornerRadius`, Angle, `SoftEdge`, `BorderWidth`, `Solid`, `Invert`, `PaintMode` chaining. | +| `PolylineMask` | Suite comps | 0.1%–0.5% | 16 / 505 | CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, `SoftEdge`, `Invert`, `PaintMode`. | +| `BitmapMask` | Suite comps | 0.0%–0.2% | 3 / 121 | Image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`), `Low`/`High` clip, `SoftEdge`, `Invert`. | + +## 3D Pipeline + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `Renderer3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 7 / 265 | GPU wgpu 3D rasterizer with depth buffer, perspective camera selection, lighting, and 2D texture sampling. | +| `Camera3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 5 / 166 | All 6 `RotOrder` permutations (`XYZ`..`ZYX`), `AoV`/`FLength`, `ApertureW`/`ApertureH`, `ResolutionGateFit` (`Inside`/`Outside`/`Width`/`Height`/`Stretch`). | +| `Merge3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 10 / 597 | Hierarchical 3D scene graph combiner with local `Transform3DOp`. | +| `Transform3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 1 / 799 | 3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node. | +| `ImagePlane3D` | `cam3d` | 0.1%–0.4% | 4 / 496 | Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture. | +| `Shape3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 4 / 374 | `Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry. | +| `LightAmbient` | Suite comps | 0.1%–0.4% | 3 / 42 | Scene ambient RGB light intensity accumulation in `Renderer3D`. | +| `LightDirectional` | Suite comps | 0.1%–0.4% | 3 / 82 | World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`. | + +## Time, Routing & Utility + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `Saver` | All suites | 0.0% | 15 / 278 | Output sink / passthrough in interactive Flow; target selector for `render-check` CLI. | +| `TimeStretcher` | Suite comps | 0.0% | 13 / 82 | Keyframed/expression `SourceTime` remapping upstream of evaluation (nearest/frame evaluation; Optical Flow tracked in [#4](https://shale.paperclover.net/fission/issues/4)). | +| `TimeSpeed` | Suite comps | 0.0% | 0 / 166 | Constant/animated `Speed` and `Delay` time remapping. | +| `Switch` | Suite comps | 0.0% | 2 / 23 | Dynamic input routing by `Which` index (`Input1`..`InputN`). | +| `Fuse.Switch` | Suite comps | 0.0% | 1 / 184 | Fuse variant of `Switch` routing `Input1`..`InputN` by `Which`. | +| `PipeRouter` | Suite comps | 0.0% | 24 / 373 | Zero-cost graph routing node. | +| `Fuse.Wireless` | Suite comps | 0.0% | 0 / 44 | Wireless link passthrough node. | +| `Tracker` | Suite comps | 0.0% | 1 / 5 | Passthrough image node; baked tracking paths evaluated via `TrackerModifier`. | +| `MacroOperator` | Suite comps | 0.0% | 30 / 1246 | Unpacks internal `Tools` subgraph and evaluates exported output seamlessly. | +| `GroupOperator` | Suite comps | 0.0% | 6 / 178 | Unpacks internal `Tools` subgraph and evaluates exported output seamlessly. | +| `Custom` | Suite comps | 0.1%–0.6% | 4 / 99 | Custom Tool shader evaluation (procedural wave/channel expressions + `UserControls` defaults). | +| `Note` | — | N/A | 0 / 57 | Non-rendering Flow sticky note; preserved losslessly on `.comp` roundtrip. | +| `Underlay` | — | N/A | 0 / 104 | Non-rendering Flow backdrop/group box; preserved losslessly on `.comp` roundtrip. | + +## Modifiers & Animation + +| Modifier / System | Probe Suite | Usage (Active / Archive) | Notes | +| --- | --- | --- | --- | +| `BezierSpline` | All suites | 664 / 22624 | Cubic Bezier / linear / `StepIn` / `StepOut` keyframes, animated `StyledText`, and animated `Polyline` point splines. | +| `LUTBezier` | `tier1_a` | 18 / 945 | Curve lookup splines used standalone and nested inside `ColorCurves` / `HueCurves`. | +| `PolyPath` / `Path` | Suite comps | 119 / 2389 | 2D motion-path polyline evaluation with animated `Displacement` spline. | +| `Shake` | `tier1_c` | 0 / 165 | Procedural multi-octave noise modifier (`Source = X / Y / Value / Position`) with spline & expression inputs. | +| `StyledTextCLS` | Suite comps | 3 / 60 | Per-character `TextPlus` styling overrides (font, size, color, kerning, opacity). | +| `TrackerModifier` | Suite comps | 3 / 0 | Resolves baked tracker path aliases (`Track1TrackerPath`, etc.) into 2D `PolyPath` coordinates. | +| Lua Expressions | Suite comps | — | Inline `Expression = "..."` evaluation (`time`, `comp.RenderStart`/`End`, node input references, math/trig/clamp/ternary). | + +## Preserved & Passthrough (Roundtrip-Safe) + +Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins when opening a `.comp` — **Fission preserves all unknown and unsupported tools losslessly** (every parameter, custom input, binary blob, position, and upstream/downstream wire is retained verbatim on save) and **passes through their main input** during Flow evaluation so downstream compositing stays connected. + +| Tool Class | Usage (Active / Archive) | Issue | Behavior & Notes | +| --- | --- | --- | --- | +| `SurfaceTracker` | 2 / 1 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | +| `MagicMask` | 3 / 1 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | +| `PlanarTracker` | 0 / 0 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | +| `Fuse.Cryptomatte` | 0 / 37 | [#2](https://shale.paperclover.net/fission/issues/2) | Preserved lossless on save; passes through main image input (multi-channel EXR matte extraction tracked). | +| `Dimension.OpticalFlow` | 2 / 10 | [#4](https://shale.paperclover.net/fission/issues/4) | Preserved lossless on save; passes through main image input (GPU dense optical flow tracked). | +| `Dimension.CopyAux` | 4 / 0 | [#4](https://shale.paperclover.net/fission/issues/4) | Preserved lossless on save; passes through main image input. | +| `pEmitter` | 1 / 54 | [#3](https://shale.paperclover.net/fission/issues/3) | Preserved lossless on save; skipped in 3D scene until particle simulator lands. | +| `pRender` | 1 / 54 | [#3](https://shale.paperclover.net/fission/issues/3) | Preserved lossless on save; skipped / passthrough until particle simulator lands. | +| `pPointForce` | 1 / 3 | [#3](https://shale.paperclover.net/fission/issues/3) | Preserved lossless on save; skipped in 3D scene until particle simulator lands. | +| `SurfaceFBXMesh` | 0 / 216 | — | Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`. | +| `Text3D` | 0 / 410 | — | Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`. | +| `MtlBlinn` | 0 / 181 | — | Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending). | +| `MtlCookTorrance` | 3 / 8 | — | Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Cook-Torrance BRDF pending). | +| `WandMask` | 0 / 150 | — | Preserved lossless on save; flood-fill wand mask not yet implemented. | +| `ReplaceMaterial3D` | 0 / 131 | — | Preserved lossless on save; 3D material override not yet traversed in `Renderer3D`. | +| `Override3D` | 0 / 124 | — | Preserved lossless on save; 3D render-flag override not yet traversed in `Renderer3D`. | +| `Displace3D` | 0 / 95 | — | Preserved lossless on save; vertex displacement not yet implemented in `Renderer3D`. | +| `Duplicate3D` | 0 / 74 | — | Preserved lossless on save; passes through main input in Flow. | +| `LightPoint` | 0 / 63 | — | Preserved lossless on save; passes through main input in Flow. | +| `LightSpot` | 0 / 52 | — | Preserved lossless on save; passes through main input in Flow. | +| `Fuse.Duplicate` | 0 / 46 | — | Preserved lossless on save; passes through main input in Flow. | +| `Texture2DOperator` | 0 / 44 | — | Preserved lossless on save; passes through main input in Flow. | +| `Multistroke` | 0 / 33 | — | Preserved lossless on save; passes through main input in Flow. | +| `Drip` | 0 / 29 | — | Preserved lossless on save; passes through main input in Flow. | + +--- + +For tracked gaps, known parity edge cases, and roadmap items, see [shale.paperclover.net/fission/issues](https://shale.paperclover.net/fission/issues). diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 20ee34c88650e3687bae4c675c778884d05a8ba5..a630fe46d4e11957a8c11ac1a714f109469f891d 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,12 +10,17 @@ path = "src/bin/render_check.rs" [dependencies] bytemuck.workspace = true +cpal = "0.15" exr = "1.74" image.workspace = true model.workspace = true png.workspace = true pollster.workspace = true +symphonia = { version = "0.5", default-features = false, features = ["wav", "mp3", "flac", "ogg", "aac", "isomp4", "pcm"] } text.workspace = true theme.workspace = true wgpu.workspace = true zeno.workspace = true + +[target.'cfg(target_os = "macos")'.build-dependencies] +cc = "1" diff --git a/crates/engine/build.rs b/crates/engine/build.rs new file mode 100644 index 0000000000000000000000000000000000000000..227f8f07a7b23ef35f76e5a0fc6cbb30771d9833 --- /dev/null +++ b/crates/engine/build.rs @@ -0,0 +1,20 @@ +fn main() { + println!("cargo:rerun-if-changed=src/av_decode.m"); + + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { + cc::Build::new() + .file("src/av_decode.m") + .flag("-fobjc-arc") + .compile("av_decode"); + + for fw in [ + "AVFoundation", + "CoreMedia", + "CoreVideo", + "Foundation", + "CoreFoundation", + ] { + println!("cargo:rustc-link-lib=framework={fw}"); + } + } +} diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs new file mode 100644 index 0000000000000000000000000000000000000000..74af1649ae74b2193194e1e981fccdc4128bab19 --- /dev/null +++ b/crates/engine/src/audio.rs @@ -0,0 +1,523 @@ +//! Audio file decoding (`.wav`, `.mp3`, `.flac`, `.ogg`, `.aac`/`.m4a` via `symphonia`) +//! and real-time non-blocking playback via `cpal` (CoreAudio on macOS). + +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use cpal::{FromSample, Sample, SampleFormat, Stream}; +use std::fs::File; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use symphonia::core::audio::SampleBuffer; +use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions}; +use symphonia::core::errors::Error as SymphoniaError; +use symphonia::core::formats::FormatOptions; +use symphonia::core::io::MediaSourceStream; +use symphonia::core::meta::MetadataOptions; +use symphonia::core::probe::Hint; + +/// Decoded audio track normalized to interleaved stereo `f32` (`[L0, R0, L1, R1, ...]`). +#[derive(Clone, Debug)] +pub struct AudioTrack { + pub path: PathBuf, + pub sample_rate: u32, + pub channels: u16, + pub samples: Arc>, + pub duration_secs: f64, +} + +impl AudioTrack { + /// Decodes an audio file (`.wav`, `.mp3`, `.flac`, `.ogg`, `.m4a`, `.aac`) into + /// interleaved stereo `f32` samples. + pub fn load(path: impl AsRef) -> Result { + let path_ref = path.as_ref(); + let file = File::open(path_ref) + .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?; + let mss = MediaSourceStream::new(Box::new(file), Default::default()); + + let mut hint = Hint::new(); + if let Some(ext) = path_ref.extension().and_then(|e| e.to_str()) { + hint.with_extension(ext); + } + + let probed = symphonia::default::get_probe() + .format( + &hint, + mss, + &FormatOptions::default(), + &MetadataOptions::default(), + ) + .map_err(|e| format!("unsupported audio format '{}': {e}", path_ref.display()))?; + + let mut format = probed.format; + let track = format + .default_track() + .filter(|t| t.codec_params.codec != CODEC_TYPE_NULL) + .or_else(|| { + format + .tracks() + .iter() + .find(|t| t.codec_params.codec != CODEC_TYPE_NULL) + }) + .ok_or_else(|| format!("no decodable audio track in '{}'", path_ref.display()))?; + + let track_id = track.id; + let mut sample_rate = track.codec_params.sample_rate.unwrap_or(0); + let mut decoder = symphonia::default::get_codecs() + .make(&track.codec_params, &DecoderOptions::default()) + .map_err(|e| format!("failed to create audio decoder '{}': {e}", path_ref.display()))?; + + let mut stereo_samples: Vec = Vec::new(); + let mut sample_buf: Option> = None; + + loop { + let packet = match format.next_packet() { + Ok(p) => p, + Err(SymphoniaError::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => break, + Err(SymphoniaError::ResetRequired) => { + decoder.reset(); + continue; + } + Err(e) => { + return Err(format!("error reading audio packet '{}': {e}", path_ref.display())); + } + }; + + if packet.track_id() != track_id { + continue; + } + + let decoded = match decoder.decode(&packet) { + Ok(d) => d, + Err(SymphoniaError::DecodeError(_)) => continue, + Err(SymphoniaError::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => break, + Err(SymphoniaError::ResetRequired) => { + decoder.reset(); + continue; + } + Err(e) => { + return Err(format!("error decoding audio '{}': {e}", path_ref.display())); + } + }; + + let spec = *decoded.spec(); + if sample_rate == 0 { + sample_rate = spec.rate; + } + let src_channels = spec.channels.count(); + if src_channels == 0 { + continue; + } + + let frames = decoded.frames(); + let buf = sample_buf.get_or_insert_with(|| { + SampleBuffer::::new(decoded.capacity() as u64, spec) + }); + if buf.capacity() < frames * src_channels { + *buf = SampleBuffer::::new(decoded.capacity() as u64, spec); + } + buf.copy_interleaved_ref(decoded); + let interleaved = buf.samples(); + + match src_channels { + 1 => { + stereo_samples.reserve(frames * 2); + for &s in interleaved { + stereo_samples.push(s); + stereo_samples.push(s); + } + } + 2 => { + stereo_samples.extend_from_slice(interleaved); + } + n => { + stereo_samples.reserve(frames * 2); + for frame in interleaved.chunks_exact(n) { + stereo_samples.push(frame[0]); + stereo_samples.push(frame[1]); + } + } + } + } + + if sample_rate == 0 { + return Err(format!("unknown sample rate in '{}'", path_ref.display())); + } + + let total_frames = stereo_samples.len() / 2; + let duration_secs = total_frames as f64 / sample_rate as f64; + + Ok(Self { + path: path_ref.to_path_buf(), + sample_rate, + channels: 2, + samples: Arc::new(stereo_samples), + duration_secs, + }) + } + + /// Computes per-frame peak amplitude in `[0.0, 1.0]` for timeline waveform visualization + /// across inclusive frame range `start_frame..=end_frame`. + pub fn waveform_peaks( + &self, + fps: f64, + offset_frames: f64, + start_frame: i64, + end_frame: i64, + ) -> Vec { + if end_frame < start_frame || fps <= 0.0 || self.sample_rate == 0 { + return Vec::new(); + } + let count = (end_frame - start_frame + 1) as usize; + let mut peaks = vec![0.0_f32; count]; + let total_frames = self.samples.len() / 2; + if total_frames == 0 { + return peaks; + } + let sr = self.sample_rate as f64; + + for (i, peak_out) in peaks.iter_mut().enumerate() { + let f = start_frame + i as i64; + let t0 = (f as f64 - offset_frames) / fps; + let t1 = ((f + 1) as f64 - offset_frames) / fps; + if t1 <= 0.0 { + continue; + } + let s0 = (t0.max(0.0) * sr).floor() as usize; + let s1 = ((t1.max(0.0) * sr).ceil() as usize).min(total_frames); + if s0 >= total_frames || s0 >= s1 { + continue; + } + let mut max_amp = 0.0_f32; + let slice = &self.samples[(s0 * 2)..(s1 * 2)]; + for &s in slice { + let a = s.abs(); + if a > max_amp { + max_amp = a; + } + } + *peak_out = max_amp.clamp(0.0, 1.0); + } + peaks + } +} + +struct SharedState { + playing: AtomicBool, + /// Current playback time in seconds (`f64::to_bits`), may be negative for leading silence. + cursor_secs_bits: AtomicU64, + /// Monotonic generation bumped on seek/play_from so audio thread never overwrites a fresh seek. + seek_gen: AtomicU64, + volume_bits: AtomicU32, + track: Mutex>>, +} + +/// Real-time non-blocking audio player backed by `cpal` (CoreAudio on macOS). +pub struct AudioPlayer { + _stream: Stream, + state: Arc, +} + +impl AudioPlayer { + /// Initializes the default audio output device and opens a non-blocking output stream. + /// Returns `Err` cleanly in headless or no-audio-device environments. + pub fn new() -> Result { + let host = cpal::default_host(); + let device = host + .default_output_device() + .ok_or_else(|| "no default audio output device available".to_string())?; + let supported_config = device + .default_output_config() + .map_err(|e| format!("failed to query default audio output config: {e}"))?; + + let sample_format = supported_config.sample_format(); + let config: cpal::StreamConfig = supported_config.into(); + let device_sr = config.sample_rate.0.max(1); + let device_channels = config.channels.max(1) as usize; + + let state = Arc::new(SharedState { + playing: AtomicBool::new(false), + cursor_secs_bits: AtomicU64::new(0.0_f64.to_bits()), + seek_gen: AtomicU64::new(0), + volume_bits: AtomicU32::new(1.0_f32.to_bits()), + track: Mutex::new(None), + }); + + let stream = match sample_format { + SampleFormat::F32 => { + build_stream::(&device, &config, device_sr, device_channels, Arc::clone(&state))? + } + SampleFormat::I16 => { + build_stream::(&device, &config, device_sr, device_channels, Arc::clone(&state))? + } + SampleFormat::U16 => { + build_stream::(&device, &config, device_sr, device_channels, Arc::clone(&state))? + } + other => { + return Err(format!("unsupported audio output sample format: {other:?}")); + } + }; + + stream + .play() + .map_err(|e| format!("failed to start audio output stream: {e}"))?; + + Ok(Self { + _stream: stream, + state, + }) + } + + pub fn set_track(&mut self, track: Option>) { + if let Ok(mut guard) = self.state.track.lock() { + *guard = track; + } + } + + pub fn play_from(&mut self, time_secs: f64) { + self.seek(time_secs); + self.state.playing.store(true, Ordering::Release); + } + + pub fn seek(&mut self, time_secs: f64) { + self.state + .cursor_secs_bits + .store(time_secs.to_bits(), Ordering::Release); + self.state.seek_gen.fetch_add(1, Ordering::AcqRel); + } + + pub fn pause(&mut self) { + self.state.playing.store(false, Ordering::Release); + } + + pub fn set_volume(&mut self, vol: f32) { + let clamped = vol.clamp(0.0, 2.0); + self.state + .volume_bits + .store(clamped.to_bits(), Ordering::Relaxed); + } + + pub fn is_playing(&self) -> bool { + self.state.playing.load(Ordering::Acquire) + } + + pub fn current_time_secs(&self) -> f64 { + f64::from_bits(self.state.cursor_secs_bits.load(Ordering::Acquire)) + } +} + +fn build_stream( + device: &cpal::Device, + config: &cpal::StreamConfig, + device_sr: u32, + device_channels: usize, + state: Arc, +) -> Result +where + T: Sample + FromSample + cpal::SizedSample, +{ + let err_fn = |err| { + eprintln!("audio stream error: {err}"); + }; + + device + .build_output_stream( + config, + move |data: &mut [T], _: &cpal::OutputCallbackInfo| { + render_audio_buffer(data, device_sr, device_channels, &state); + }, + err_fn, + None, + ) + .map_err(|e| format!("failed to build audio output stream: {e}")) +} + +fn render_audio_buffer( + data: &mut [T], + device_sr: u32, + device_channels: usize, + state: &SharedState, +) where + T: Sample + FromSample, +{ + if !state.playing.load(Ordering::Acquire) { + let zero = T::from_sample(0.0_f32); + data.fill(zero); + return; + } + + let track_opt = match state.track.try_lock() { + Ok(guard) => guard.clone(), + Err(_) => None, + }; + + let Some(track) = track_opt else { + let zero = T::from_sample(0.0_f32); + data.fill(zero); + return; + }; + + let total_frames = track.samples.len() / 2; + let track_sr = track.sample_rate as f64; + let vol = f32::from_bits(state.volume_bits.load(Ordering::Relaxed)); + let gen_before = state.seek_gen.load(Ordering::Acquire); + let mut t_sec = f64::from_bits(state.cursor_secs_bits.load(Ordering::Acquire)); + let dt = 1.0 / device_sr as f64; + let samples = &track.samples; + + for frame_out in data.chunks_exact_mut(device_channels) { + let (l, r) = if total_frames > 0 && t_sec >= 0.0 { + let src_pos = t_sec * track_sr; + if src_pos < total_frames as f64 { + let idx0 = src_pos.floor() as usize; + let idx1 = (idx0 + 1).min(total_frames - 1); + let frac = (src_pos - idx0 as f64) as f32; + let l0 = samples[idx0 * 2]; + let r0 = samples[idx0 * 2 + 1]; + let l1 = samples[idx1 * 2]; + let r1 = samples[idx1 * 2 + 1]; + ( + (l0 + (l1 - l0) * frac) * vol, + (r0 + (r1 - r0) * frac) * vol, + ) + } else { + (0.0, 0.0) + } + } else { + (0.0, 0.0) + }; + + if device_channels == 1 { + frame_out[0] = T::from_sample(((l + r) * 0.5).clamp(-1.0, 1.0)); + } else { + frame_out[0] = T::from_sample(l.clamp(-1.0, 1.0)); + frame_out[1] = T::from_sample(r.clamp(-1.0, 1.0)); + let zero = T::from_sample(0.0_f32); + for ch in &mut frame_out[2..] { + *ch = zero; + } + } + + t_sec += dt; + } + + if state.seek_gen.load(Ordering::Acquire) == gen_before { + state + .cursor_secs_bits + .store(t_sec.to_bits(), Ordering::Release); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + + fn rms(samples: &[f32]) -> f64 { + if samples.is_empty() { + return 0.0; + } + let sum_sq: f64 = samples.iter().map(|&s| (s as f64) * (s as f64)).sum(); + (sum_sq / samples.len() as f64).sqrt() + } + + #[test] + fn test_audio_load_real_wav_if_present() { + let path = Path::new("/Volumes/Project/trees/Bounces/trees_premix.wav"); + if !path.exists() { + return; + } + let track = AudioTrack::load(path).expect("failed to load trees_premix.wav"); + assert!(track.sample_rate >= 8000); + assert_eq!(track.channels, 2); + assert!(track.duration_secs > 1.0); + assert!(rms(&track.samples) > 0.001); + let peaks = track.waveform_peaks(24.0, 0.0, 0, 23); + assert_eq!(peaks.len(), 24); + assert!(peaks.iter().all(|&p| (0.0..=1.0).contains(&p))); + } + + #[test] + fn test_audio_load_generated_wav_and_mp3() { + let wav_path = std::env::temp_dir().join("engine_test_sine_440.wav"); + let mp3_path = std::env::temp_dir().join("engine_test_sine_440.mp3"); + + let wav_ok = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=0.5", + "-af", + "volume=6", + "-ar", + "44100", + "-ac", + "2", + ]) + .arg(&wav_path) + .status() + .is_ok_and(|s| s.success()); + assert!(wav_ok, "ffmpeg failed to generate temp wav"); + + let mp3_ok = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=0.5", + "-af", + "volume=6", + "-ar", + "44100", + "-ac", + "2", + "-b:a", + "192k", + ]) + .arg(&mp3_path) + .status() + .is_ok_and(|s| s.success()); + assert!(mp3_ok, "ffmpeg failed to generate temp mp3"); + + for path in [&wav_path, &mp3_path] { + let track = AudioTrack::load(path) + .unwrap_or_else(|e| panic!("failed to load {}: {e}", path.display())); + assert_eq!(track.sample_rate, 44100, "sample_rate mismatch for {}", path.display()); + assert_eq!(track.channels, 2); + assert!( + (track.duration_secs - 0.5).abs() < 0.08, + "duration mismatch for {}: {}", + path.display(), + track.duration_secs + ); + let r = rms(&track.samples); + assert!(r > 0.1, "expected non-silent RMS > 0.1 for {}, got {r}", path.display()); + + let peaks = track.waveform_peaks(24.0, 0.0, 0, 11); + assert_eq!(peaks.len(), 12); + assert!(peaks.iter().all(|&p| (0.0..=1.0).contains(&p))); + assert!( + peaks.iter().copied().fold(0.0_f32, f32::max) > 0.5, + "expected waveform peaks > 0.5 for {}", + path.display() + ); + + // Offset in the future -> leading frames should be silent (0.0). + let shifted = track.waveform_peaks(24.0, 5.0, 0, 10); + assert_eq!(shifted.len(), 11); + assert_eq!(shifted[0], 0.0); + assert_eq!(shifted[4], 0.0); + assert!(shifted[6] > 0.5); + } + + let _ = std::fs::remove_file(&wav_path); + let _ = std::fs::remove_file(&mp3_path); + } +} diff --git a/crates/engine/src/av_decode.m b/crates/engine/src/av_decode.m new file mode 100644 index 0000000000000000000000000000000000000000..15df0496131201c3ec042275e44ea2cc04f5f6d1 --- /dev/null +++ b/crates/engine/src/av_decode.m @@ -0,0 +1,365 @@ +#import +#import +#import +#import +#import +#include +#include +#include + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +@interface AvVideoDecoderObj : NSObject +@property(nonatomic, strong) AVURLAsset *asset; +@property(nonatomic, strong) AVAssetTrack *track; +@property(nonatomic, strong) AVAssetReader *reader; +@property(nonatomic, strong) AVAssetReaderTrackOutput *output; +@property(nonatomic, assign) uint32_t width; +@property(nonatomic, assign) uint32_t height; +@property(nonatomic, assign) int rotation; // 0, 90, 180, 270 clockwise +@property(nonatomic, assign) double fps; +@property(nonatomic, assign) int64_t nbFrames; +@property(nonatomic, assign) double trackStartSec; +@property(nonatomic, assign) int64_t lastFrameIdx; +@end + +@implementation AvVideoDecoderObj + +- (void)closeReader { + if (self.reader) { + [self.reader cancelReading]; + self.reader = nil; + self.output = nil; + } + self.lastFrameIdx = -1; +} + +- (BOOL)openReaderAtSeconds:(double)startSec { + [self closeReader]; + NSError *err = nil; + AVAssetReader *r = [[AVAssetReader alloc] initWithAsset:self.asset error:&err]; + if (!r || err) { + return NO; + } + NSDictionary *settings = @{ + (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA), + }; + AVAssetReaderTrackOutput *out = + [[AVAssetReaderTrackOutput alloc] initWithTrack:self.track outputSettings:settings]; + out.alwaysCopiesSampleData = NO; + if (![r canAddOutput:out]) { + return NO; + } + [r addOutput:out]; + if (startSec > 0.0) { + CMTime startTime = CMTimeMakeWithSeconds(startSec, 60000); + r.timeRange = CMTimeRangeMake(startTime, kCMTimePositiveInfinity); + } + if (![r startReading]) { + return NO; + } + self.reader = r; + self.output = out; + return YES; +} + +- (void)dealloc { + [self closeReader]; +} + +@end + +typedef struct AvVideoDecoder AvVideoDecoder; + +static int copy_bgra_to_rgba( + CVImageBufferRef imgBuf, + uint32_t outW, + uint32_t outH, + int rotation, + uint8_t *outRgba, + size_t outLen +) { + if (!imgBuf || !outRgba) { + return 0; + } + size_t required = (size_t)outW * (size_t)outH * 4; + if (outLen < required) { + return 0; + } + + if (CVPixelBufferLockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) { + return 0; + } + + size_t srcW = CVPixelBufferGetWidth(imgBuf); + size_t srcH = CVPixelBufferGetHeight(imgBuf); + size_t bpr = CVPixelBufferGetBytesPerRow(imgBuf); + const uint8_t *base = (const uint8_t *)CVPixelBufferGetBaseAddress(imgBuf); + + int ok = 0; + if (base) { + if (rotation == 0 && srcW == outW && srcH == outH) { + for (size_t y = 0; y < srcH; y++) { + const uint8_t *src = base + y * bpr; + uint8_t *dst = outRgba + y * (size_t)outW * 4; + for (size_t x = 0; x < srcW; x++) { + dst[x * 4 + 0] = src[x * 4 + 2]; + dst[x * 4 + 1] = src[x * 4 + 1]; + dst[x * 4 + 2] = src[x * 4 + 0]; + dst[x * 4 + 3] = src[x * 4 + 3]; + } + } + ok = 1; + } else if (rotation == 90 && srcH == outW && srcW == outH) { + for (size_t y = 0; y < srcH; y++) { + const uint8_t *src = base + y * bpr; + size_t dx = srcH - 1 - y; + for (size_t x = 0; x < srcW; x++) { + size_t dy = x; + uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4; + dst[0] = src[x * 4 + 2]; + dst[1] = src[x * 4 + 1]; + dst[2] = src[x * 4 + 0]; + dst[3] = src[x * 4 + 3]; + } + } + ok = 1; + } else if (rotation == 180 && srcW == outW && srcH == outH) { + for (size_t y = 0; y < srcH; y++) { + const uint8_t *src = base + y * bpr; + size_t dy = srcH - 1 - y; + for (size_t x = 0; x < srcW; x++) { + size_t dx = srcW - 1 - x; + uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4; + dst[0] = src[x * 4 + 2]; + dst[1] = src[x * 4 + 1]; + dst[2] = src[x * 4 + 0]; + dst[3] = src[x * 4 + 3]; + } + } + ok = 1; + } else if (rotation == 270 && srcH == outW && srcW == outH) { + for (size_t y = 0; y < srcH; y++) { + const uint8_t *src = base + y * bpr; + size_t dx = y; + for (size_t x = 0; x < srcW; x++) { + size_t dy = srcW - 1 - x; + uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4; + dst[0] = src[x * 4 + 2]; + dst[1] = src[x * 4 + 1]; + dst[2] = src[x * 4 + 0]; + dst[3] = src[x * 4 + 3]; + } + } + ok = 1; + } + } + + CVPixelBufferUnlockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly); + return ok; +} + +AvVideoDecoder *av_video_open( + const char *path, + uint32_t *out_w, + uint32_t *out_h, + double *out_fps, + int64_t *out_nb_frames +) { + if (!path || !out_w || !out_h || !out_fps || !out_nb_frames) { + return NULL; + } + @autoreleasepool { + NSString *nsPath = [NSString stringWithUTF8String:path]; + if (!nsPath) { + return NULL; + } + NSURL *url = [NSURL fileURLWithPath:nsPath]; + AVURLAsset *asset = [AVURLAsset + URLAssetWithURL:url + options:@{AVURLAssetPreferPreciseDurationAndTimingKey : @YES}]; + if (!asset) { + return NULL; + } + + NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo]; + AVAssetTrack *track = tracks.firstObject; + if (!track) { + return NULL; + } + + CGSize natSize = track.naturalSize; + uint32_t natW = (uint32_t)llround(fabs(natSize.width)); + uint32_t natH = (uint32_t)llround(fabs(natSize.height)); + if (natW == 0 || natH == 0) { + return NULL; + } + + CGAffineTransform t = track.preferredTransform; + int rotation = -1; + uint32_t outW = natW; + uint32_t outH = natH; + if (fabs(t.a - 1.0) < 0.01 && fabs(t.b) < 0.01 && fabs(t.c) < 0.01 && + fabs(t.d - 1.0) < 0.01) { + rotation = 0; + } else if (fabs(t.a) < 0.01 && fabs(t.b - 1.0) < 0.01 && + fabs(t.c + 1.0) < 0.01 && fabs(t.d) < 0.01) { + rotation = 90; + outW = natH; + outH = natW; + } else if (fabs(t.a + 1.0) < 0.01 && fabs(t.b) < 0.01 && + fabs(t.c) < 0.01 && fabs(t.d + 1.0) < 0.01) { + rotation = 180; + } else if (fabs(t.a) < 0.01 && fabs(t.b + 1.0) < 0.01 && + fabs(t.c - 1.0) < 0.01 && fabs(t.d) < 0.01) { + rotation = 270; + outW = natH; + outH = natW; + } else { + // Unsupported affine transform (shear/non-90-deg); fall back to ffmpeg. + return NULL; + } + + double fps = (double)track.nominalFrameRate; + if (fps <= 0.0) { + CMTime minDur = track.minFrameDuration; + if (CMTIME_IS_NUMERIC(minDur) && minDur.value > 0 && minDur.timescale > 0) { + fps = (double)minDur.timescale / (double)minDur.value; + } + } + if (fps <= 0.0) { + fps = 30.0; + } + + CMTime dur = track.timeRange.duration; + if (!CMTIME_IS_NUMERIC(dur) || CMTimeGetSeconds(dur) <= 0.0) { + dur = asset.duration; + } + double durSec = CMTIME_IS_NUMERIC(dur) ? CMTimeGetSeconds(dur) : 0.0; + int64_t nbFrames = durSec > 0.0 ? (int64_t)llround(durSec * fps) : 0; + + double trackStartSec = 0.0; + if (CMTIME_IS_NUMERIC(track.timeRange.start)) { + double s = CMTimeGetSeconds(track.timeRange.start); + if (s > 0.0) { + trackStartSec = s; + } + } + + AvVideoDecoderObj *obj = [[AvVideoDecoderObj alloc] init]; + obj.asset = asset; + obj.track = track; + obj.width = outW; + obj.height = outH; + obj.rotation = rotation; + obj.fps = fps; + obj.nbFrames = nbFrames; + obj.trackStartSec = trackStartSec; + obj.lastFrameIdx = -1; + + // Verify AVAssetReader can actually open and decode this asset/codec. + if (![obj openReaderAtSeconds:0.0]) { + return NULL; + } + + *out_w = outW; + *out_h = outH; + *out_fps = fps; + *out_nb_frames = nbFrames; + return (AvVideoDecoder *)CFBridgingRetain(obj); + } +} + +int av_video_decode_frame( + AvVideoDecoder *dec, + int64_t frame_idx, + uint8_t *out_rgba, + size_t out_len +) { + if (!dec || !out_rgba) { + return 0; + } + @autoreleasepool { + AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; + if (frame_idx < 0) { + frame_idx = 0; + } + double fps = obj.fps > 0.0 ? obj.fps : 30.0; + double targetPts = obj.trackStartSec + ((double)frame_idx) / fps; + double halfFrame = 0.45 / fps; + + BOOL canAdvance = + obj.reader != nil && + obj.reader.status == AVAssetReaderStatusReading && + ((obj.lastFrameIdx == -1 && frame_idx <= 8) || + (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx && + frame_idx <= obj.lastFrameIdx + 8)); + + if (!canAdvance) { + double seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps)); + if (![obj openReaderAtSeconds:seekSec]) { + return 0; + } + } + + CMSampleBufferRef chosen = NULL; + CMSampleBufferRef lastSeen = NULL; + + while (obj.reader.status == AVAssetReaderStatusReading) { + CMSampleBufferRef sb = [obj.output copyNextSampleBuffer]; + if (!sb) { + break; + } + CMTime ptsTime = CMSampleBufferGetPresentationTimeStamp(sb); + double pts = CMTIME_IS_NUMERIC(ptsTime) ? CMTimeGetSeconds(ptsTime) : targetPts; + + if (pts + halfFrame >= targetPts) { + chosen = sb; + break; + } + if (lastSeen) { + CFRelease(lastSeen); + } + lastSeen = sb; + } + + if (!chosen && lastSeen) { + chosen = lastSeen; + lastSeen = NULL; + } + if (lastSeen) { + CFRelease(lastSeen); + lastSeen = NULL; + } + + if (!chosen) { + [obj closeReader]; + return 0; + } + + CVImageBufferRef imgBuf = CMSampleBufferGetImageBuffer(chosen); + int ok = copy_bgra_to_rgba( + imgBuf, obj.width, obj.height, obj.rotation, out_rgba, out_len); + CFRelease(chosen); + + if (ok) { + obj.lastFrameIdx = frame_idx; + } else { + [obj closeReader]; + } + return ok; + } +} + +void av_video_close(AvVideoDecoder *dec) { + if (!dec) { + return; + } + @autoreleasepool { + AvVideoDecoderObj *obj = (AvVideoDecoderObj *)CFBridgingRelease(dec); + [obj closeReader]; + } +} + +#pragma clang diagnostic pop diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index cbcfdb72f17a52874bb28febf229fcb8d60e29ce..f1dddf3a508ae22d1cc7fa64f6f72e2c6768fae0 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -1,6 +1,6 @@ //! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`. -use engine::{CacheMode, Engine}; +use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence}; use model::Comp; use std::collections::HashMap; use std::fs::File; @@ -192,6 +192,66 @@ fn run_batch_render( Ok(()) } +fn run_saver_export( + comp_path: &Path, + saver_name: Option<&str>, + range_str: Option<&str>, + out_dir_override: Option, + proxy_scale: u32, + hiq: bool, +) -> Result<(), Box> { + let comp = Comp::from_fusion_file(comp_path)?; + let range_override = match range_str { + Some(r) if !r.is_empty() => { + if let Some((a, b)) = r.split_once("..") { + Some([a.parse::()?, b.parse::()?]) + } else { + let single = r.parse::()?; + Some([single, single]) + } + } + _ => None, + }; + let mut engine = Engine::new_headless()?; + let opts = ExportOptions { + saver_name: saver_name.map(str::to_owned), + out_dir_override, + range_override, + hiq, + proxy_scale, + png_workers: 0, + }; + let t_start = Instant::now(); + let summary = export_saver_png_sequence(&mut engine, &comp, &opts, |p| { + if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { + let elapsed = t_start.elapsed().as_secs_f64().max(1e-6); + let fps = (p.index + 1) as f64 / elapsed; + eprintln!( + " [{:>4}/{}] {} f{:04} | eval={:.1}ms | avg={fps:.1} fps -> {}", + p.index + 1, + p.total, + p.saver_name, + p.frame, + p.eval_ms, + p.out_path.display() + ); + } + }) + .map_err(|e| format!("export failed: {e}"))?; + let secs = (summary.total_ms / 1000.0).max(1e-6); + eprintln!( + "Exported {} frames via {} in {:.2}s ({:.1} fps)", + summary.frames_written, + summary.saver_name, + secs, + summary.frames_written as f64 / secs + ); + if let (Some(first), Some(last)) = (summary.first_path, summary.last_path) { + eprintln!(" range: {} .. {}", first.display(), last.display()); + } + Ok(()) +} + fn main() -> Result<(), Box> { let args: Vec = std::env::args().collect(); if args.len() >= 3 && args[1] == "--suite" { @@ -200,12 +260,73 @@ fn main() -> Result<(), Box> { } if args.len() < 3 { eprintln!( - "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --suite [--fast]" + "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --export [--saver ] [--range ..] [--out-dir ] [--proxy <1|2|4>] [--fast]\n render-check --roundtrip \n render-check --suite [--fast]" ); std::process::exit(2); } let comp_path = PathBuf::from(&args[1]); + if args[2] == "--roundtrip" { + if args.len() < 4 { + return Err("--roundtrip requires ".into()); + } + let comp = Comp::from_fusion_file(&comp_path)?; + let out_path = PathBuf::from(&args[3]); + let bak = comp.save_to_file(&out_path)?; + eprintln!( + "Roundtripped {} ({} nodes, {} splines) -> {}{}", + comp_path.display(), + comp.nodes.len(), + comp.splines.len(), + out_path.display(), + bak.map(|b| format!(" (backup -> {})", b.display())).unwrap_or_default() + ); + return Ok(()); + } + if args[2] == "--export" { + let mut saver_name: Option = None; + let mut range_str: Option = None; + let mut out_dir: Option = None; + let mut proxy_scale = 1u32; + let mut hiq = true; + let mut i = 3; + while i < args.len() { + match args[i].as_str() { + "--saver" if i + 1 < args.len() => { + saver_name = Some(args[i + 1].clone()); + i += 2; + } + "--range" if i + 1 < args.len() => { + range_str = Some(args[i + 1].clone()); + i += 2; + } + "--out-dir" if i + 1 < args.len() => { + out_dir = Some(PathBuf::from(&args[i + 1])); + i += 2; + } + "--proxy" if i + 1 < args.len() => { + proxy_scale = args[i + 1].parse().unwrap_or(1).max(1); + i += 2; + } + "--fast" => { + hiq = false; + i += 1; + } + other => { + eprintln!("unexpected argument '{other}'"); + std::process::exit(2); + } + } + } + return run_saver_export( + &comp_path, + saver_name.as_deref(), + range_str.as_deref(), + out_dir, + proxy_scale, + hiq, + ); + } if args[2] == "--render" { let mut range = String::new(); let mut out_dir: Option = None; diff --git a/crates/engine/src/eval.rs b/crates/engine/src/eval.rs index 0698606714ed03558bc29aef6466c63c1f4607f2..bf48dac8b0c8c3522d59c371f354a4f3b90e9e2b 100644 --- a/crates/engine/src/eval.rs +++ b/crates/engine/src/eval.rs @@ -814,17 +814,24 @@ impl Engine { "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), other => { - // Graceful passthrough for unsupported nodes (e.g. MacroOperator, 3D, etc.) + // Graceful passthrough for preserved/unknown image nodes (e.g. SurfaceTracker, MagicMask, + // Fuse.Cryptomatte, Dimension.OpticalFlow) via standard primary image ports so downstream + // graphs stay live without mistaking auxiliary sprite/material ports (like pEmitter's + // ParticleStyleBitmap.DropToolsHere) for a full-frame passthrough. if !stats.unsupported_nodes.iter().any(|s| s == other) { stats.unsupported_nodes.push(other.to_owned()); } let port = default_main_input_port(other); - if let Some(src_id) = node.connected_node(port) - .or_else(|| node.connected_node("MainInput1")) + let primary_src = node + .connected_node(port) .or_else(|| node.connected_node("Input")) + .or_else(|| node.connected_node("Source")) + .or_else(|| node.connected_node("MainInput1")) + .or_else(|| node.connected_node("Image")) + .or_else(|| node.connected_node("Image1")) .or_else(|| node.connected_node("Background")) - .and_then(|s| comp.find_node(s)) - { + .and_then(|s| comp.find_node(s)); + if let Some(src_id) = primary_src { self.eval_node(comp, src_id, time, enc, visiting, stats) } else { self.dummy.clone() diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs new file mode 100644 index 0000000000000000000000000000000000000000..cd7b4228ae959218ebe7fb4a55856e0af16f2b53 --- /dev/null +++ b/crates/engine/src/export.rs @@ -0,0 +1,382 @@ +//! Saver-driven pipelined PNG sequence export for `Engine`. +//! +//! Evaluates frames on the GPU while encoding lossless RGBA8 PNG files concurrently +//! across a bounded background worker pool, creating parent directories automatically. + +use crate::eval::Engine; +use model::{Comp, NodeId, SaverSpec}; +use std::fs::File; +use std::io::BufWriter; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::Instant; + +#[derive(Clone, Debug)] +pub struct ExportOptions { + /// Optional explicit Saver node name. If `None`, selects the first non-bypassed Saver + /// with a configured filename (or falls back to the first Saver). + pub saver_name: Option, + /// Optional output directory override (keeps each frame's filename from `SaverSpec::frame_path`). + pub out_dir_override: Option, + /// Optional inclusive frame range override `[start, end]`. Defaults to `saver.range` (`comp.render_range`). + pub range_override: Option<[i64; 2]>, + /// Render quality mode (`true` = HiQ project depth, `false` = Fast). + pub hiq: bool, + /// Proxy downscale factor (`1` = full resolution). + pub proxy_scale: u32, + /// Number of background PNG encoder threads (`0` = automatic 2..=8). + pub png_workers: usize, +} + +impl Default for ExportOptions { + fn default() -> Self { + Self { + saver_name: None, + out_dir_override: None, + range_override: None, + hiq: true, + proxy_scale: 1, + png_workers: 0, + } + } +} + +#[derive(Clone, Debug)] +pub struct ExportProgress { + pub frame: i64, + pub index: usize, + pub total: usize, + pub eval_ms: f64, + pub out_path: PathBuf, + pub saver_name: String, +} + +#[derive(Clone, Debug)] +pub struct ExportSummary { + pub saver_name: String, + pub frames_written: usize, + pub total_ms: f64, + pub first_path: Option, + pub last_path: Option, +} + +/// Selects the target `SaverSpec` from `comp` according to `saver_name`. +pub fn select_saver(comp: &Comp, saver_name: Option<&str>) -> Result { + let savers = comp.savers(); + if savers.is_empty() { + return Err(format!("comp '{}' has no Saver nodes", comp.name)); + } + if let Some(name) = saver_name { + return savers + .into_iter() + .find(|s| s.name == name) + .ok_or_else(|| format!("comp '{}' has no Saver named '{name}'", comp.name)); + } + // Prefer first non-bypassed Saver with an upstream connection and non-empty filename + if let Some(s) = savers.iter().find(|s| { + !comp.node(s.node_id).bypassed && s.upstream.is_some() && !s.filename.is_empty() + }) { + return Ok(s.clone()); + } + if let Some(s) = savers.iter().find(|s| !comp.node(s.node_id).bypassed) { + return Ok(s.clone()); + } + Ok(savers[0].clone()) +} + +fn resolve_output_path(saver: &SaverSpec, frame: i64, out_dir_override: Option<&Path>) -> Result { + if saver.filename.is_empty() { + let dir = out_dir_override.ok_or_else(|| { + format!( + "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)", + saver.name + ) + })?; + return Ok(dir.join(format!("{frame:04}.png"))); + } + let frame_path = saver.frame_path(frame); + if let Some(dir) = out_dir_override { + let fname = frame_path + .file_name() + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.png"))); + Ok(dir.join(fname)) + } else { + Ok(frame_path) + } +} + +fn write_png_fast(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), String> { + if let Some(parent) = path.parent() { + if !parent.as_os_str().is_empty() { + std::fs::create_dir_all(parent) + .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; + } + } + let file = File::create(path) + .map_err(|e| format!("failed to create '{}': {e}", path.display()))?; + let writer = BufWriter::new(file); + let mut enc = png::Encoder::new(writer, size[0], size[1]); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.set_compression(png::Compression::Fast); + let mut png_w = enc + .write_header() + .map_err(|e| format!("failed to write PNG header '{}': {e}", path.display()))?; + png_w + .write_image_data(pixels) + .map_err(|e| format!("failed to write PNG data '{}': {e}", path.display()))?; + Ok(()) +} + +struct EncodeJob { + path: PathBuf, + size: [u32; 2], + pixels: Vec, +} + +/// Renders and writes a PNG sequence driven by a Fusion `Saver` node. +/// +/// GPU evaluation runs on the caller's thread while PNG compression and disk I/O run +/// concurrently on a bounded pool of background worker threads. +pub fn export_saver_png_sequence( + engine: &mut Engine, + comp: &Comp, + opts: &ExportOptions, + mut on_progress: impl FnMut(&ExportProgress), +) -> Result { + let saver = select_saver(comp, opts.saver_name.as_deref())?; + let target: NodeId = saver.upstream.unwrap_or(saver.node_id); + let [start, end] = opts.range_override.unwrap_or(saver.range); + if end < start { + return Err(format!("invalid export frame range {start}..={end}")); + } + + let prev_hiq = engine.hiq; + let prev_proxy = engine.proxy_scale; + engine.hiq = opts.hiq; + engine.proxy_scale = opts.proxy_scale.max(1); + + let workers = if opts.png_workers > 0 { + opts.png_workers.clamp(1, 16) + } else { + std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 8)) + .unwrap_or(4) + }; + + let total = (end - start + 1) as usize; + let t0 = Instant::now(); + let mut first_path: Option = None; + let mut last_path: Option = None; + + let first_err: Arc>> = Arc::new(Mutex::new(None)); + let failed = Arc::new(AtomicBool::new(false)); + + let eval_result: Result<(), String> = std::thread::scope(|scope| { + let (tx, rx) = mpsc::sync_channel::(workers * 2); + let shared_rx = Arc::new(Mutex::new(rx)); + + let mut handles = Vec::with_capacity(workers); + for _ in 0..workers { + let rx_c = Arc::clone(&shared_rx); + let err_c = Arc::clone(&first_err); + let fail_c = Arc::clone(&failed); + handles.push(scope.spawn(move || { + loop { + let job = { + let Ok(guard) = rx_c.lock() else { break }; + guard.recv() + }; + let Ok(job) = job else { break }; + if fail_c.load(Ordering::Acquire) { + continue; + } + if let Err(e) = write_png_fast(&job.path, job.size, &job.pixels) { + if let Ok(mut g) = err_c.lock() { + if g.is_none() { + *g = Some(e); + } + } + fail_c.store(true, Ordering::Release); + } + } + })); + } + + let mut loop_err: Option = None; + for (idx, frame) in (start..=end).enumerate() { + if failed.load(Ordering::Acquire) { + break; + } + let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) { + Ok(p) => p, + Err(e) => { + loop_err = Some(e); + break; + } + }; + if first_path.is_none() { + first_path = Some(out_path.clone()); + } + last_path = Some(out_path.clone()); + + let (tex, stats) = engine.evaluate(comp, target, frame as f64); + let pixels = match engine.readback_rgba(&tex) { + Ok(px) => px, + Err(e) => { + loop_err = Some(format!("GPU readback failed at frame {frame}: {e}")); + break; + } + }; + + on_progress(&ExportProgress { + frame, + index: idx, + total, + eval_ms: stats.eval_ms, + out_path: out_path.clone(), + saver_name: saver.name.clone(), + }); + + if tx + .send(EncodeJob { + path: out_path, + size: tex.size, + pixels, + }) + .is_err() + { + break; + } + } + + drop(tx); + for h in handles { + let _ = h.join(); + } + + if let Some(e) = loop_err { + return Err(e); + } + if let Ok(mut g) = first_err.lock() { + if let Some(e) = g.take() { + return Err(e); + } + } + Ok(()) + }); + + engine.hiq = prev_hiq; + engine.proxy_scale = prev_proxy; + + eval_result?; + + Ok(ExportSummary { + saver_name: saver.name, + frames_written: total, + total_ms: t0.elapsed().as_secs_f64() * 1000.0, + first_path, + last_path, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exports_saver_png_sequence_animated() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-saver-export-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + let saver_path = tmp_dir.join("nested").join("shot_0000.png"); + let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); + + let comp_src = format!( + r#"Composition {{ + CurrentTime = 10, + RenderRange = {{ 10, 12 }}, + GlobalRange = {{ 0, 100 }}, + Tools = ordered() {{ + BG = Background {{ + Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 32, }}, + TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, + TopLeftGreen = Input {{ Value = 0.25, }}, + TopLeftBlue = Input {{ Value = 0.5, }}, + TopLeftAlpha = Input {{ Value = 1, }}, + }}, + }}, + BGRed = BezierSpline {{ + KeyFrames = {{ + [10] = {{ 0.0, Flags = {{ Linear = true }} }}, + [12] = {{ 1.0, Flags = {{ Linear = true }} }}, + }}, + }}, + Saver1 = Saver {{ + Inputs = {{ + Clip = Input {{ + Value = Clip {{ + Filename = "{saver_path_escaped}", + FormatID = "PNGFormat", + Saving = true, + }}, + }}, + Input = Input {{ + SourceOp = "BG", + Source = "Output", + }}, + }}, + }}, + }}, + Prefs = {{ + Comp = {{ + FrameFormat = {{ + Width = 64, + Height = 32, + Rate = 30, + DepthFull = 1, + }}, + }}, + }}, +}}"# + ); + + let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let mut seen_frames = Vec::new(); + let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |p| { + seen_frames.push(p.frame); + }) + .expect("export png sequence"); + + assert_eq!(summary.saver_name, "Saver1"); + assert_eq!(summary.frames_written, 3); + assert_eq!(seen_frames, vec![10, 11, 12]); + + let expected_reds = [0u8, 128u8, 255u8]; + for (frame, exp_r) in [10i64, 11, 12].into_iter().zip(expected_reds) { + let p = tmp_dir.join("nested").join(format!("shot_{frame:04}.png")); + assert!(p.exists(), "missing exported frame {}", p.display()); + let img = image::open(&p).expect("decode exported PNG").to_rgba8(); + assert_eq!(img.dimensions(), (64, 32)); + let px = img.get_pixel(32, 16); + assert!( + (px[0] as i32 - exp_r as i32).abs() <= 2, + "frame {frame}: expected R~{exp_r}, got {:?}", + px.0 + ); + assert!((px[1] as i32 - 64).abs() <= 2); + assert!((px[2] as i32 - 128).abs() <= 2); + assert_eq!(px[3], 255); + } + + let _ = std::fs::remove_dir_all(&tmp_dir); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 978dfade8c424e4243880e985f2467eb9ad4f5a3..8da9272f9e92aff19eb17b1a6f0245c96710320e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,7 +1,11 @@ +pub mod audio; pub mod cache; pub mod eval; +pub mod export; pub mod media; pub mod scene3d; +pub use audio::{AudioPlayer, AudioTrack}; pub use cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; pub use eval::{DisplaySettings, Engine, create_texture}; +pub use export::{ExportOptions, ExportProgress, ExportSummary, export_saver_png_sequence, select_saver}; diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index a1f5ab4452d2952ad47850a23d839572a4ff3566..0c5f3d06f5a96e3415f8a9e92ea0ebd4593c32a9 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -15,11 +15,169 @@ pub struct DecodedImage { } #[derive(Clone, Copy, Debug)] -struct VideoInfo { - width: u32, - height: u32, - fps: f64, - nb_frames: i64, +pub struct VideoInfo { + pub width: u32, + pub height: u32, + pub fps: f64, + pub nb_frames: i64, +} + +pub trait VideoDecoder: Send { + fn info(&self) -> VideoInfo; + fn decode_frame(&mut self, frame_idx: i64) -> Option>; + fn backend_name(&self) -> &'static str; +} + +#[cfg(target_os = "macos")] +mod av_ffi { + use std::ffi::c_char; + + #[repr(C)] + pub struct AvVideoDecoder { + _private: [u8; 0], + } + + unsafe extern "C" { + pub fn av_video_open( + path: *const c_char, + out_w: *mut u32, + out_h: *mut u32, + out_fps: *mut f64, + out_nb_frames: *mut i64, + ) -> *mut AvVideoDecoder; + + pub fn av_video_decode_frame( + dec: *mut AvVideoDecoder, + frame_idx: i64, + out_rgba: *mut u8, + out_len: usize, + ) -> i32; + + pub fn av_video_close(dec: *mut AvVideoDecoder); + } +} + +#[cfg(target_os = "macos")] +pub struct AvFoundationDecoder { + ptr: *mut av_ffi::AvVideoDecoder, + info: VideoInfo, +} + +#[cfg(target_os = "macos")] +unsafe impl Send for AvFoundationDecoder {} + +#[cfg(target_os = "macos")] +impl Drop for AvFoundationDecoder { + fn drop(&mut self) { + if !self.ptr.is_null() { + unsafe { av_ffi::av_video_close(self.ptr) }; + self.ptr = std::ptr::null_mut(); + } + } +} + +#[cfg(target_os = "macos")] +impl AvFoundationDecoder { + pub fn open(path: &Path) -> Option { + use std::ffi::CString; + let path_str = path.to_str()?; + let c_path = CString::new(path_str).ok()?; + let mut width = 0u32; + let mut height = 0u32; + let mut fps = 0.0f64; + let mut nb_frames = 0i64; + let ptr = unsafe { + av_ffi::av_video_open( + c_path.as_ptr(), + &mut width, + &mut height, + &mut fps, + &mut nb_frames, + ) + }; + if ptr.is_null() || width == 0 || height == 0 { + if !ptr.is_null() { + unsafe { av_ffi::av_video_close(ptr) }; + } + return None; + } + Some(Self { + ptr, + info: VideoInfo { + width, + height, + fps: if fps > 0.0 { fps } else { 30.0 }, + nb_frames, + }, + }) + } +} + +#[cfg(target_os = "macos")] +impl VideoDecoder for AvFoundationDecoder { + fn info(&self) -> VideoInfo { + self.info + } + + fn decode_frame(&mut self, frame_idx: i64) -> Option> { + let len = (self.info.width as usize) + .checked_mul(self.info.height as usize)? + .checked_mul(4)?; + let mut buf = vec![0u8; len]; + let ok = unsafe { + av_ffi::av_video_decode_frame(self.ptr, frame_idx.max(0), buf.as_mut_ptr(), len) + }; + if ok != 0 { + Some(buf) + } else { + None + } + } + + fn backend_name(&self) -> &'static str { + "AVFoundation/VideoToolbox" + } +} + +pub struct FfmpegDecoder { + path: PathBuf, + info: VideoInfo, +} + +impl FfmpegDecoder { + pub fn open(path: &Path) -> Option { + let info = probe_video(path)?; + Some(Self { + path: path.to_path_buf(), + info, + }) + } +} + +impl VideoDecoder for FfmpegDecoder { + fn info(&self) -> VideoInfo { + self.info + } + + fn decode_frame(&mut self, frame_idx: i64) -> Option> { + decode_video_frame(&self.path, self.info, frame_idx) + } + + fn backend_name(&self) -> &'static str { + "ffmpeg" + } +} + +/// Opens a hardware-accelerated video decoder (`AVFoundation`/`VideoToolbox` on macOS), +/// falling back to `ffmpeg` for unsupported containers or codecs. +pub fn open_video_decoder(path: &Path) -> Option> { + #[cfg(target_os = "macos")] + { + if let Some(av) = AvFoundationDecoder::open(path) { + return Some(Box::new(av)); + } + } + FfmpegDecoder::open(path).map(|ff| Box::new(ff) as Box) } fn is_video_path(path: &Path) -> bool { @@ -199,7 +357,7 @@ fn decode_exr_rgba( pub struct MediaCache { images: HashMap<(PathBuf, i64), DecodedImage>, - video_info: HashMap>, + video_decoders: HashMap>>, total_bytes: u64, budget_bytes: u64, lru: HashMap<(PathBuf, i64), u64>, @@ -210,7 +368,7 @@ impl MediaCache { pub fn new(budget_mb: u64) -> Self { Self { images: HashMap::new(), - video_info: HashMap::new(), + video_decoders: HashMap::new(), total_bytes: 0, budget_bytes: budget_mb * 1024 * 1024, lru: HashMap::new(), @@ -275,12 +433,12 @@ impl MediaCache { } } let base_buf = base.to_path_buf(); - let info = if let Some(cached) = self.video_info.get(&base_buf).copied() { - cached? - } else { - let probed = probe_video(base); - self.video_info.insert(base_buf.clone(), probed); - probed? + let info = { + let entry = self + .video_decoders + .entry(base_buf.clone()) + .or_insert_with(|| open_video_decoder(base)); + entry.as_ref()?.info() }; let len = clip.length.unwrap_or(info.nb_frames.max(1)).max(1); @@ -306,7 +464,11 @@ impl MediaCache { self.lru.insert(cache_key, self.tick); return Some((base_buf, idx, img, false)); } - let raw = decode_video_frame(base, info, idx)?; + let raw = self + .video_decoders + .get_mut(&base_buf) + .and_then(|d| d.as_mut())? + .decode_frame(idx)?; let decoded = DecodedImage { size: [info.width, info.height], rgba: Arc::new(raw), @@ -656,3 +818,128 @@ pub fn rasterize_polyline_mask( } out } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Instant; + + fn mean_abs_error_rgb(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len()); + let mut sum = 0u64; + let mut count = 0u64; + for (pa, pb) in a.chunks_exact(4).zip(b.chunks_exact(4)) { + sum += pa[0].abs_diff(pb[0]) as u64; + sum += pa[1].abs_diff(pb[1]) as u64; + sum += pa[2].abs_diff(pb[2]) as u64; + count += 3; + } + if count == 0 { + 0.0 + } else { + sum as f64 / count as f64 + } + } + + fn verify_clip_matches_ffmpeg(path: &Path) { + let mut dec = open_video_decoder(path).expect("open_video_decoder failed"); + let mut ff = FfmpegDecoder::open(path).expect("FfmpegDecoder::open failed"); + + #[cfg(target_os = "macos")] + assert_eq!( + dec.backend_name(), + "AVFoundation/VideoToolbox", + "expected AVFoundation backend for {}", + path.display() + ); + + let av_info = dec.info(); + let ff_info = ff.info(); + assert_eq!(av_info.width, ff_info.width, "width mismatch for {}", path.display()); + assert_eq!(av_info.height, ff_info.height, "height mismatch for {}", path.display()); + assert!( + (av_info.fps - ff_info.fps).abs() < 0.2, + "fps mismatch for {}: av={} ff={}", + path.display(), + av_info.fps, + ff_info.fps + ); + + let frames = [0_i64, 1, 2, 10, 0]; + let mut total_ms = 0.0; + for &f in &frames { + let t0 = Instant::now(); + let av_px = dec + .decode_frame(f) + .unwrap_or_else(|| panic!("av decode frame {f} failed for {}", path.display())); + let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0; + total_ms += elapsed_ms; + + let ff_px = ff + .decode_frame(f) + .unwrap_or_else(|| panic!("ffmpeg decode frame {f} failed for {}", path.display())); + let mae = mean_abs_error_rgb(&av_px, &ff_px); + eprintln!( + "[video-test] {} ({}x{} @{:.2}fps) frame {}: {:.2} ms, MAE vs ffmpeg = {:.2}", + path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"), + av_info.width, + av_info.height, + av_info.fps, + f, + elapsed_ms, + mae + ); + // Allow small YUV->RGB matrix/rounding differences between VideoToolbox and swscale. + assert!( + mae < 12.0, + "high MAE ({mae:.2}) on {} frame {f} (possible orientation or PTS mismatch)", + path.display() + ); + } + eprintln!( + "[video-test] {} avg decode: {:.2} ms/frame", + path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"), + total_ms / frames.len() as f64 + ); + } + + #[test] + fn test_video_decoder_real_mov_clips() { + let clips = [ + Path::new("/Volumes/Project/trees/EncodedMedia/A001_11071331_C002_4873-4988_d8716e17.mov"), + Path::new("/Volumes/Project/trees/EncodedMedia/IMG_1767_2395-2547_7efe6416.mov"), + ]; + for clip in clips { + if clip.exists() { + verify_clip_matches_ffmpeg(clip); + } + } + } + + #[test] + fn test_video_decoder_synthetic_mp4() { + let tmp = std::env::temp_dir().join("engine_test_synth_video.mp4"); + let status = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "testsrc2=size=320x180:rate=24:duration=1.0", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + ]) + .arg(&tmp) + .status(); + if let Ok(st) = status { + if st.success() { + verify_clip_matches_ffmpeg(&tmp); + let _ = std::fs::remove_file(&tmp); + } + } + } +} diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index d8b47dcac60b977dd6ec9c30f2235a2f66a720f9..8efa662707cd3329e92d0181f6acda9ee63143cc 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -6,7 +6,7 @@ //! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert. use draw::{Glyphs, PathStyle, Primitive}; -use model::{Comp, NodeId, PortRole, default_main_input_port}; +use model::{Comp, NodeId, PortRole, default_main_input_port, is_supported_tool}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use winit::event::{ElementState, MouseButton}; @@ -740,6 +740,12 @@ impl FlowView { weight: 500, italic: false, }; + let tiny_font = text::Font { + families: Arc::from([text::Family::Mono]), + size: 7.5, + weight: 600, + italic: false, + }; let make_layout = |s: &str, font: &text::Font| { let styles = [text::Style::new(font.clone())]; text::Paragraph { @@ -758,8 +764,11 @@ impl FlowView { for n in &comp.nodes { self.label_cache.entry(n.name.clone()).or_insert_with(|| make_layout(&n.name, &label_font)); } + self.badge_cache + .entry("preserved".to_owned()) + .or_insert_with(|| make_layout("preserved", &tiny_font)); for key in [ - "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+F / Num.: Fit Scroll: Zoom", + "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+S: Save Cmd+Shift+R: Export Cmd+F: Fit", "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", @@ -928,7 +937,12 @@ impl FlowView { let hovered = self.hovered_node == Some(n.id); let v1 = self.viewed_nodes[0] == Some(n.id); let v2 = self.viewed_nodes[1] == Some(n.id); - let accent = node_accent(&n.kind); + let supported = is_supported_tool(&n.kind); + let accent = if supported { + node_accent(&n.kind) + } else { + [0.92, 0.64, 0.24, 1.0] + }; let bg = if n.bypassed { [self.palette.node_fill[0] * 0.6, self.palette.node_fill[1] * 0.6, self.palette.node_fill[2] * 0.6, 0.65] @@ -936,6 +950,13 @@ impl FlowView { self.palette.node_selected } else if hovered { self.palette.node_hover + } else if !supported { + [ + (self.palette.node_fill[0] + 0.035).min(1.0), + (self.palette.node_fill[1] + 0.020).min(1.0), + self.palette.node_fill[2], + 1.0, + ] } else { self.palette.node_fill }; @@ -950,20 +971,35 @@ impl FlowView { color: if n.bypassed { [0.28, 0.28, 0.32, 0.6] } else { accent }, }); - // Crisp border + // Crisp border (amber accent for preserved/passthrough unknown nodes) let border_col = if primary { [0.98, 0.78, 0.30, 1.0] } else if sel { self.palette.accent + } else if !supported { + [0.92, 0.64, 0.24, 0.85] } else { self.palette.node_border }; out.push(Primitive::RoundedRect { rect: r, radius, - stroke: Some(if sel || primary { 1.4 } else { 0.9 }), + stroke: Some(if sel || primary { 1.4 } else if !supported { 1.15 } else { 0.9 }), color: border_col, }); + // Subtle top dashed ticks for preserved/passthrough unknown nodes + if !supported && self.zoom >= 0.45 { + let mut tx = r[0] + 5.0; + while tx + 4.0 < r[2] - 4.0 { + out.push(Primitive::Segment { + from: [tx, r[1] + 0.8], + to: [(tx + 4.0).min(r[2] - 4.0), r[1] + 0.8], + width: 1.2, + color: [0.96, 0.72, 0.30, 0.90], + }); + tx += 8.0; + } + } // Node label centered cleanly inside thin bar if self.zoom >= 0.42 { @@ -980,6 +1016,34 @@ impl FlowView { } } + // Preserved/passthrough pill badge underneath bottom-right for unknown/OFX nodes + if !supported && self.zoom >= 0.50 { + if let Some(badge) = self.badge_cache.get("preserved") { + let bw = 46.0; + let bh = 10.5; + let bx = (r[2] - bw).max(r[0] + 28.0); + let by = r[3] + 1.5; + out.push(Primitive::RoundedRect { + rect: [bx, by, bx + bw, by + bh], + radius: 3.0, + stroke: None, + color: [0.14, 0.10, 0.05, 0.92], + }); + out.push(Primitive::RoundedRect { + rect: [bx, by, bx + bw, by + bh], + radius: 3.0, + stroke: Some(0.8), + color: [0.92, 0.64, 0.24, 0.72], + }); + out.push(Primitive::Text { + text: badge as &dyn Glyphs, + origin: [bx + 4.0, by + 1.0], + clip: Some([bx + 2.0, by, bx + bw - 2.0, by + bh]), + ink: [0.98, 0.78, 0.40, 1.0], + }); + } + } + // Fusion-style tiny viewer indicator pill underneath bottom-left (`● ○` for Viewer 1 / Viewer 2!) if v1 || v2 { let pw = 22.0; @@ -1044,7 +1108,7 @@ impl FlowView { Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", - None => "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+F / Num.: Fit Scroll: Zoom", + None => "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+S: Save Cmd+Shift+R: Export Cmd+F: Fit", }; if let Some(l) = self.badge_cache.get(hud_key) { let pill_h = 20.0; diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index 94f0d3aaa45653ae453e8d515a204be10bacd382..2647264ba68644f8975df330b2432b2198bdba34 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -47,18 +47,153 @@ pub enum PortRole { impl PortRole { pub fn from_input_name(name: &str) -> Self { + if name.starts_with("SceneInput") { + return Self::Scene3D; + } match name { - "EffectMask" | "GarbageMatte" | "SolidMatte" | "Mask" => Self::Mask, - "Foreground" | "Image2" => Self::Foreground, - "SceneInput" | "SceneInput1" | "SceneInput2" | "SceneInput3" | "SceneInput4" => { - Self::Scene3D + "EffectMask" | "GarbageMatte" | "SolidMatte" | "Mask" | "TrackingMask" | "RegionMask" => { + Self::Mask + } + "Foreground" | "Image2" | "Overlay" | "ReplaceImage" => Self::Foreground, + "Background" | "Input" | "Image" | "Image1" | "Source" | "MainInput1" => { + Self::Background } - "Background" | "Input" | "Image" | "Image1" => Self::Background, _ => Self::Aux, } } } +/// Canonical registry of Fusion tool classes evaluated natively by the engine. +pub fn is_supported_tool(kind: &str) -> bool { + matches!( + kind, + // Routing / Utility + "Saver" + | "PipeRouter" + | "Fuse.Wireless" + | "Tracker" + | "MacroOperator" + | "GroupOperator" + | "TimeStretcher" + | "TimeSpeed" + | "Switch" + | "Fuse.Switch" + | "Note" + | "Underlay" + | "StickyNote" + // 2D tools + | "Loader" + | "Background" + | "Merge" + | "Dissolve" + | "Transform" + | "CameraShake" + | "CornerPositioner" + | "DVE" + | "Shadow" + | "Scale" + | "BetterResize" + | "Crop" + | "SetDomain" + | "ChangeDepth" + | "BrightnessContrast" + | "ColorCorrector" + | "ColorGain" + | "ColorCurves" + | "HueCurves" + | "GamutConvert" + | "InvertColor" + | "ChannelBoolean" + | "LumaKeyer" + | "UltraKeyer" + | "Blur" + | "Sharpen" + | "Filter" + | "VariBlur" + | "DirectionalBlur" + | "Glow" + | "SoftGlow" + | "Fuse.XGlow" + | "ErodeDilate" + | "FastNoise" + | "Plasma" + | "FilmGrain" + | "Displace" + | "EllipseMask" + | "RectangleMask" + | "PolylineMask" + | "BitmapMask" + | "TextPlus" + | "Fuse.Colorize" + | "Fuse.Outline" + | "Fuse.XfChroma" + | "Custom" + // 3D tools + | "Renderer3D" + | "Merge3D" + | "Transform3D" + | "Camera3D" + | "ImagePlane3D" + | "Shape3D" + | "LightAmbient" + | "LightDirectional" + ) +} + +/// Metadata extracted from a Fusion `Saver` node. +#[derive(Clone, Debug, PartialEq)] +pub struct SaverSpec { + pub node_id: NodeId, + pub name: String, + pub upstream: Option, + pub filename: String, + pub range: [i64; 2], + pub sequence_start: Option, +} + +impl SaverSpec { + /// Computes the output path for `frame` following Fusion's Saver sequence naming rules: + /// - `foo_0000.png` -> `foo_{frame:04}.png` (preserving digit width) + /// - `0000.png` -> `{frame:04}.png` + /// - `render.png` -> `render{frame:04}.png` (4-digit default when no trailing digits exist) + pub fn frame_path(&self, frame: i64) -> PathBuf { + let effective_frame = if let Some(start) = self.sequence_start { + start + (frame - self.range[0]) + } else { + frame + }; + + let path = Path::new(&self.filename); + let parent = path.parent().unwrap_or_else(|| Path::new("")); + let fname = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); + + let (stem, ext) = match fname.rfind('.') { + Some(dot) => (&fname[..dot], &fname[dot..]), + None => (fname, ""), + }; + + let digit_start = stem + .rfind(|c: char| !c.is_ascii_digit()) + .map_or(0, |idx| idx + 1); + let prefix = &stem[..digit_start]; + let digits = &stem[digit_start..]; + let width = if digits.is_empty() { 4 } else { digits.len() }; + + let formatted_num = if effective_frame < 0 { + format!("-{:0width$}", effective_frame.unsigned_abs()) + } else { + format!("{effective_frame:0width$}") + }; + + let out_name = format!("{prefix}{formatted_num}{ext}"); + if parent.as_os_str().is_empty() { + PathBuf::from(out_name) + } else { + parent.join(out_name) + } + } +} + #[derive(Clone, Debug, PartialEq)] pub enum ParamValue { Number(f64), @@ -219,6 +354,8 @@ pub struct Comp { pub text_cls: HashMap>, /// Procedural `Shake` modifiers keyed by modifier name (e.g. `"Shake1"`). pub shakes: HashMap, + /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip. + pub raw_root: Option, /// Generation counter incremented whenever any node, wire, or spline mutates. pub revision: u64, } @@ -462,6 +599,7 @@ impl Comp { polyline_splines, text_cls, shakes, + raw_root: Some(root.clone()), revision: 1, }) } @@ -944,6 +1082,557 @@ impl Comp { self.nodes[id.0].bypassed = !self.nodes[id.0].bypassed; self.revision += 1; } + + /// Extracts metadata for every top-level (non-internal) `Saver` node in this comp. + pub fn savers(&self) -> Vec { + let mut out = Vec::new(); + for n in &self.nodes { + if n.internal || n.kind != "Saver" { + continue; + } + let upstream = n.connected_node("Input").and_then(|src| self.find_node(src)); + let filename = n + .clips + .first() + .map(|c| c.filename.clone()) + .or_else(|| { + n.raw + .get_table("Inputs") + .and_then(|i| i.get_table("Clip")) + .and_then(|c| c.get_table("Value")) + .and_then(|v| v.get_str("Filename")) + .map(str::to_owned) + }) + .unwrap_or_default(); + let set_seq = n.static_number("SetSequenceStart").map(|v| v > 0.5); + let sequence_start = if set_seq == Some(true) { + n.static_number("SequenceStartFrame").map(|v| v.round() as i64) + } else { + None + }; + out.push(SaverSpec { + node_id: n.id, + name: n.name.clone(), + upstream, + filename, + range: self.render_range, + sequence_start, + }); + } + out + } + + /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits, + /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST, + /// preserving all unknown nodes, modifiers, macros, UserControls, Clips, and metadata verbatim. + pub fn sync_to_raw_ast(&self) -> LuaTable { + let mut root = self.raw_root.clone().unwrap_or_else(|| LuaTable { + tag: Some("Composition".to_owned()), + entries: Vec::new(), + }); + + root.set( + LuaKey::Str("CurrentTime".to_owned()), + LuaValue::Number(self.current_time), + ); + root.set( + LuaKey::Str("GlobalRange".to_owned()), + vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64), + ); + root.set( + LuaKey::Str("RenderRange".to_owned()), + vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64), + ); + if let Some(ref af) = self.audio_filename { + root.set( + LuaKey::Str("AudioFilename".to_owned()), + LuaValue::String(af.clone()), + ); + } + if self.audio_offset != 0.0 || root.get("AudioOffset").is_some() { + root.set( + LuaKey::Str("AudioOffset".to_owned()), + LuaValue::Number(self.audio_offset), + ); + } + + // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull) + { + let prefs = ensure_table_mut(&mut root, "Prefs", None); + let comp_prefs = ensure_table_mut(prefs, "Comp", None); + let ff = ensure_table_mut(comp_prefs, "FrameFormat", None); + if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) { + ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64)); + } + if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) { + ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64)); + } + if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) { + ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps)); + } + let existing_depth = ff + .get_f64("DepthFull") + .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) + .unwrap_or(BitDepth::Int8); + if existing_depth != self.depth_full { + ff.set( + LuaKey::Str("DepthFull".to_owned()), + LuaValue::Number((self.depth_full as i32) as f64), + ); + } + } + + // Sync Tools + let tools = ensure_table_mut(&mut root, "Tools", Some("ordered")); + + // Remove top-level flow nodes that were deleted from `self.nodes`, + // while NEVER removing modifiers or any node still present in `self.nodes`. + let live_flow_names: HashSet<&str> = self + .nodes + .iter() + .filter(|n| !n.internal) + .map(|n| n.name.as_str()) + .collect(); + tools.entries.retain(|(k, v)| { + let LuaKey::Str(name) = k else { return true }; + let Some(tbl) = v.as_table() else { return true }; + let kind = tbl.tag.as_deref().unwrap_or("Unknown"); + if is_modifier_type(kind) { + true + } else { + live_flow_names.contains(name.as_str()) + } + }); + + // Sync each visible (non-internal) flow node + for node in &self.nodes { + if node.internal { + continue; + } + if tools.get_table(&node.name).is_none() { + let mut new_tbl = if node.raw.tag.is_some() { + node.raw.clone() + } else { + LuaTable { + tag: Some(node.kind.clone()), + entries: Vec::new(), + } + }; + if new_tbl.tag.is_none() { + new_tbl.tag = Some(node.kind.clone()); + } + tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl)); + } + + let Some(tool_tbl) = tools.get_table_mut(&node.name) else { + continue; + }; + + // ViewInfo.Pos + if let Some(vi) = tool_tbl.get_table_mut("ViewInfo") { + let pos_changed = vi + .get_table("Pos") + .and_then(read_vec2) + .is_none_or(|[x, y]| { + (x as f32 - node.pos[0]).abs() > 1e-4 + || (y as f32 - node.pos[1]).abs() > 1e-4 + }); + if pos_changed { + vi.set( + LuaKey::Str("Pos".to_owned()), + vec2_lua(node.pos[0] as f64, node.pos[1] as f64), + ); + } + } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 { + let mut vi = LuaTable { + tag: Some("OperatorInfo".to_owned()), + entries: Vec::new(), + }; + vi.set( + LuaKey::Str("Pos".to_owned()), + vec2_lua(node.pos[0] as f64, node.pos[1] as f64), + ); + tool_tbl.set(LuaKey::Str("ViewInfo".to_owned()), LuaValue::Table(vi)); + } + + // PassThrough + if node.bypassed { + tool_tbl.set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true)); + } else if tool_tbl.get("PassThrough").is_some() { + tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned())); + } + + // Inputs (skip MacroOperator / GroupOperator so InstanceInput wiring stays intact) + if !matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") { + let master_inputs = node + .raw + .get_str("SourceOp") + .and_then(|m| self.find_node(m)) + .map(|mid| &self.nodes[mid.0].inputs); + sync_node_inputs(node, master_inputs, tool_tbl); + } + } + + // Sync BezierSpline edits (only touch splines that actually differ from the raw AST) + let mut spline_names: Vec<&String> = self.splines.keys().collect(); + spline_names.sort(); + for spline_name in spline_names { + let spline = &self.splines[spline_name]; + if let Some(tbl) = tools.get_table_mut(spline_name) { + sync_spline_table(spline_name, spline, tbl); + continue; + } + // Check nested `Tools` (e.g. ColorCurves / HueCurves LUTBezier) + let mut found_nested = false; + for (_, v) in &mut tools.entries { + if let Some(node_tbl) = v.as_table_mut() { + if let Some(inner_tools) = node_tbl.get_table_mut("Tools") { + if let Some(inner_sp) = inner_tools.get_table_mut(spline_name) { + sync_spline_table(spline_name, spline, inner_sp); + found_nested = true; + break; + } + } + } + } + if !found_nested { + let mut sp_tbl = LuaTable { + tag: Some("BezierSpline".to_owned()), + entries: Vec::new(), + }; + sp_tbl.set( + LuaKey::Str("SplineColor".to_owned()), + spline_color_lua(spline.color), + ); + sp_tbl.set( + LuaKey::Str("KeyFrames".to_owned()), + LuaValue::Table(build_keyframes_table(spline)), + ); + tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl)); + } + } + + root + } + + /// Serializes this composition back to a Blackmagic Fusion `.comp` string. + pub fn to_fusion_string(&self) -> String { + let mut s = self.sync_to_raw_ast().to_fusion_string(); + if !s.ends_with('\n') { + s.push('\n'); + } + s + } + + /// Atomically saves this composition to `path`. + /// If `path` already exists, backs up the original bytes to + /// `/fission-backups/_.comp.bak` and returns `Ok(Some(backup_path))`. + pub fn save_to_file(&self, path: impl AsRef) -> Result, std::io::Error> { + let path = path.as_ref(); + let stem = path + .file_stem() + .and_then(|s| s.to_str()) + .filter(|s| !s.is_empty()) + .unwrap_or("comp"); + + let backup_path = if path.exists() { + let backup_dir = std::env::temp_dir().join("fission-backups"); + std::fs::create_dir_all(&backup_dir)?; + let unix_millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + let backup_file = backup_dir.join(format!("{stem}_{unix_millis}.comp.bak")); + std::fs::copy(path, &backup_file)?; + Some(backup_file) + } else { + None + }; + + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(parent)?; + + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let pid = std::process::id(); + let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp")); + + let serialized = self.to_fusion_string(); + if let Err(e) = std::fs::write(&tmp_path, serialized.as_bytes()) { + let _ = std::fs::remove_file(&tmp_path); + return Err(e); + } + if let Err(e) = std::fs::rename(&tmp_path, path) { + let _ = std::fs::remove_file(&tmp_path); + return Err(e); + } + + Ok(backup_path) + } +} + +fn vec2_lua(x: f64, y: f64) -> LuaValue { + LuaValue::Table(LuaTable { + tag: None, + entries: vec![ + (LuaKey::Index(1), LuaValue::Number(x)), + (LuaKey::Index(2), LuaValue::Number(y)), + ], + }) +} + +fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) -> &'a mut LuaTable { + if parent.get_table(key).is_none() { + parent.set( + LuaKey::Str(key.to_owned()), + LuaValue::Table(LuaTable { + tag: tag.map(str::to_owned), + entries: Vec::new(), + }), + ); + } + parent.get_table_mut(key).expect("table just inserted") +} + +fn param_value_to_lua(v: &ParamValue) -> LuaValue { + match v { + ParamValue::Number(n) => LuaValue::Number(*n), + ParamValue::Point([x, y]) => vec2_lua(*x, *y), + ParamValue::Text(s) => LuaValue::String(s.clone()), + ParamValue::FuId(s) => LuaValue::Table(LuaTable { + tag: Some("FuID".to_owned()), + entries: vec![(LuaKey::Index(1), LuaValue::String(s.clone()))], + }), + ParamValue::Gradient(g) => { + let mut colors = LuaTable::default(); + for stop in &g.stops { + let key = if stop.pos.fract() == 0.0 && stop.pos.abs() < 9_007_199_254_740_992.0 { + LuaKey::Index(stop.pos as i64) + } else { + LuaKey::Number(stop.pos) + }; + colors.entries.push(( + key, + LuaValue::Table(LuaTable { + tag: None, + entries: vec![ + (LuaKey::Index(1), LuaValue::Number(stop.rgba[0] as f64)), + (LuaKey::Index(2), LuaValue::Number(stop.rgba[1] as f64)), + (LuaKey::Index(3), LuaValue::Number(stop.rgba[2] as f64)), + (LuaKey::Index(4), LuaValue::Number(stop.rgba[3] as f64)), + ], + }), + )); + } + LuaValue::Table(LuaTable { + tag: Some("Gradient".to_owned()), + entries: vec![(LuaKey::Str("Colors".to_owned()), LuaValue::Table(colors))], + }) + } + ParamValue::Raw(raw) => raw.clone(), + } +} + +fn user_control_default(raw: &LuaTable, name: &str) -> Option { + let ut = raw.get_table("UserControls")?.get_table(name)?; + let is_point = ut.get_str("LINKID_DataType") == Some("Point") + || ut.get_str("INPID_InputControl") == Some("OffsetControl"); + if is_point { + let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5); + let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5); + Some(ParamValue::Point([dx, dy])) + } else { + ut.get("INP_Default").map(parse_param_value) + } +} + +fn sync_node_inputs( + node: &Node, + master_inputs: Option<&HashMap>, + tool_tbl: &mut LuaTable, +) { + // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`. + if let Some(in_tbl) = tool_tbl.get_table_mut("Inputs") { + in_tbl.entries.retain(|(k, v)| { + let LuaKey::Str(port) = k else { return true }; + if v.as_table().is_none() { + return true; + } + node.inputs.contains_key(port) + }); + } + + // Collect sorted port names for deterministic output when appending new inputs. + let mut ports: Vec<&String> = node.inputs.keys().collect(); + ports.sort(); + + for port in ports { + let binding = &node.inputs[port]; + let existing_binding = tool_tbl + .get_table("Inputs") + .and_then(|i| i.get_table(port)) + .map(parse_input_binding); + + if let Some(orig) = existing_binding { + if orig == *binding { + continue; + } + let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None); + if let Some(it) = in_tbl.get_table_mut(port) { + if orig.source_op != binding.source_op { + match &binding.source_op { + Some(op) => it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())), + None => { + it.remove(&LuaKey::Str("SourceOp".to_owned())); + } + } + } + if orig.source_output != binding.source_output { + match &binding.source_output { + Some(src) => it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())), + None => { + it.remove(&LuaKey::Str("Source".to_owned())); + } + } + } + if orig.expression != binding.expression { + match &binding.expression { + Some(expr) => it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())), + None => { + it.remove(&LuaKey::Str("Expression".to_owned())); + } + } + } + if orig.value != binding.value { + match &binding.value { + Some(val) => it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)), + None => { + it.remove(&LuaKey::Str("Value".to_owned())); + } + } + } + } + } else { + // Port did not exist in raw `Inputs`. + if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() { + continue; + } + // Don't pollute `Inputs` with unedited `UserControls` defaults synthesized during load. + if binding.source_op.is_none() + && binding.expression.is_none() + && binding.value.is_some() + && binding.value == user_control_default(&node.raw, port) + { + continue; + } + // Don't duplicate inherited master inputs onto instanced tools. + if let Some(master) = master_inputs { + if master.get(port) == Some(binding) { + continue; + } + } + + let mut it = LuaTable { + tag: Some("Input".to_owned()), + entries: Vec::new(), + }; + if let Some(op) = &binding.source_op { + it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())); + } + if let Some(src) = &binding.source_output { + it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())); + } + if let Some(val) = &binding.value { + it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)); + } + if let Some(expr) = &binding.expression { + it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())); + } + let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None); + in_tbl.set(LuaKey::Str(port.clone()), LuaValue::Table(it)); + } + } +} + +fn spline_color_lua(color: [u8; 3]) -> LuaValue { + LuaValue::Table(LuaTable { + tag: None, + entries: vec![ + (LuaKey::Str("Red".to_owned()), LuaValue::Number(color[0] as f64)), + (LuaKey::Str("Green".to_owned()), LuaValue::Number(color[1] as f64)), + (LuaKey::Str("Blue".to_owned()), LuaValue::Number(color[2] as f64)), + ], + }) +} + +fn build_keyframes_table(spline: &BezierSpline) -> LuaTable { + let mut kfs = spline.keyframes.clone(); + kfs.sort_by(|a, b| a.time.total_cmp(&b.time)); + let mut tbl = LuaTable::default(); + for kf in kfs { + let key = if kf.time.fract() == 0.0 && kf.time.abs() < 9_007_199_254_740_992.0 { + LuaKey::Index(kf.time as i64) + } else { + LuaKey::Number(kf.time) + }; + let mut entry = LuaTable::default(); + entry.entries.push((LuaKey::Index(1), LuaValue::Number(kf.value))); + if let Some([lx, ly]) = kf.lh { + entry.entries.push((LuaKey::Str("LH".to_owned()), vec2_lua(lx, ly))); + } + if let Some([rx, ry]) = kf.rh { + entry.entries.push((LuaKey::Str("RH".to_owned()), vec2_lua(rx, ry))); + } + let mut flags = LuaTable::default(); + if kf.flags.linear { + flags.entries.push((LuaKey::Str("Linear".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.step_in { + flags.entries.push((LuaKey::Str("StepIn".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.step_out { + flags.entries.push((LuaKey::Str("StepOut".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.loop_after { + flags.entries.push((LuaKey::Str("Loop".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.loop_rel { + flags.entries.push((LuaKey::Str("LoopRel".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.ping_pong { + flags.entries.push((LuaKey::Str("PingPong".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.locked_y { + flags.entries.push((LuaKey::Str("LockedY".to_owned()), LuaValue::Bool(true))); + } + if !flags.entries.is_empty() { + entry.entries.push((LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags))); + } + tbl.entries.push((key, LuaValue::Table(entry))); + } + tbl +} + +fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) { + let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl); + if existing.color != spline.color { + tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color)); + } + if existing.keyframes != spline.keyframes { + let new_kfs = LuaValue::Table(build_keyframes_table(spline)); + if tbl.tag.as_deref() == Some("LUTBezier") && tbl.get_table("KeyColorSplines").is_some() { + if let Some(kcs) = tbl.get_table_mut("KeyColorSplines") { + kcs.set(LuaKey::Index(0), new_kfs); + } + } else { + tbl.set(LuaKey::Str("KeyFrames".to_owned()), new_kfs); + } + } } pub fn default_main_input_port(kind: &str) -> &'static str { diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index f3b128833d7d4cb0e1106be72f2ed0caaa97f7ca..cb6d5b9f5e06073f3ea2d031c2d662c4c45f78ef 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -3,7 +3,10 @@ pub mod expr; pub mod lua_value; pub mod spline; -pub use comp::{BitDepth, ClipSpec, ClsEntry, Comp, InputBinding, Node, NodeId, ParamValue, PortRole, default_main_input_port}; +pub use comp::{ + BitDepth, ClipSpec, ClsEntry, Comp, InputBinding, Node, NodeId, ParamValue, PortRole, SaverSpec, + default_main_input_port, is_supported_tool, +}; pub use expr::ExprEngine; pub use lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua}; pub use spline::{BezierSpline, Gradient, GradientStop, HandleMode, KeyFlags, Keyframe, PolyPath, PolyPoint}; @@ -77,4 +80,394 @@ mod tests { let p1 = comp.eval_point(merge19, "Center", 2361.0, [0.5, 0.5], &expr); assert!((p0[0] - p1[0]).abs() + (p0[1] - p1[1]).abs() > 1e-4); } + + #[test] + fn roundtrips_all_337_real_fusion_comps() { + let mut paths = Vec::new(); + fn collect(dir: &Path, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { return }; + for entry in rd.flatten() { + let p = entry.path(); + if p.is_dir() { + collect(&p, out); + } else if p + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("comp")) + { + out.push(p); + } + } + } + collect(Path::new("/Users/clo/dev/compositor/private/samples"), &mut paths); + collect(Path::new("/Volumes/Project/trees/fusion"), &mut paths); + paths.sort(); + assert!(!paths.is_empty(), "expected sample .comp files"); + + let mut failures = Vec::new(); + for p in &paths { + let orig = match Comp::from_fusion_file(p) { + Ok(c) => c, + Err(e) => { + failures.push(format!("{}: load error: {e}", p.display())); + continue; + } + }; + let serialized = orig.to_fusion_string(); + let reloaded = match Comp::from_fusion_str(&serialized) { + Ok(c) => c, + Err(e) => { + failures.push(format!("{}: re-parse error: {e}", p.display())); + continue; + } + }; + + if orig.width != reloaded.width + || orig.height != reloaded.height + || (orig.fps - reloaded.fps).abs() > 1e-6 + || orig.depth_full != reloaded.depth_full + || orig.render_range != reloaded.render_range + || orig.global_range != reloaded.global_range + { + failures.push(format!( + "{}: metadata mismatch: orig=({}x{} @{} {:?} rr={:?} gr={:?}) vs reloaded=({}x{} @{} {:?} rr={:?} gr={:?})", + p.display(), + orig.width, orig.height, orig.fps, orig.depth_full, orig.render_range, orig.global_range, + reloaded.width, reloaded.height, reloaded.fps, reloaded.depth_full, reloaded.render_range, reloaded.global_range, + )); + continue; + } + + if orig.nodes.len() != reloaded.nodes.len() { + failures.push(format!( + "{}: node count mismatch: {} vs {}", + p.display(), + orig.nodes.len(), + reloaded.nodes.len() + )); + continue; + } + + let orig_names: std::collections::HashSet = + orig.node_by_name.keys().cloned().collect(); + let rel_names: std::collections::HashSet = + reloaded.node_by_name.keys().cloned().collect(); + + let mut node_err = None; + for (a, b) in orig.nodes.iter().zip(reloaded.nodes.iter()) { + if a.name != b.name + || a.kind != b.kind + || a.bypassed != b.bypassed + || a.internal != b.internal + || (a.pos[0] - b.pos[0]).abs() > 1e-3 + || (a.pos[1] - b.pos[1]).abs() > 1e-3 + { + node_err = Some(format!( + "{}: node mismatch {} vs {} (kind {:?}/{:?}, bypassed {}/{}, pos {:?}/{:?})", + p.display(), + a.name, b.name, a.kind, b.kind, a.bypassed, b.bypassed, a.pos, b.pos + )); + break; + } + let conns_a = a.image_connections(&orig_names); + let conns_b = b.image_connections(&rel_names); + if conns_a != conns_b { + node_err = Some(format!( + "{}: image_connections mismatch on {}: {:?} vs {:?}", + p.display(), + a.name, conns_a, conns_b + )); + break; + } + } + if let Some(err) = node_err { + failures.push(err); + continue; + } + + if orig.splines.len() != reloaded.splines.len() { + failures.push(format!( + "{}: spline count mismatch: {} vs {}", + p.display(), + orig.splines.len(), + reloaded.splines.len() + )); + continue; + } + for (sname, sp_a) in &orig.splines { + let Some(sp_b) = reloaded.splines.get(sname) else { + failures.push(format!("{}: missing spline {sname}", p.display())); + break; + }; + if sp_a.keyframes.is_empty() && sp_b.keyframes.is_empty() { + continue; + } + let t0 = sp_a.keyframes.first().map(|k| k.time).unwrap_or(0.0); + let t1 = sp_a.keyframes.last().map(|k| k.time).unwrap_or(0.0); + for step in 0..=4 { + let t = t0 + (t1 - t0) * (step as f64 / 4.0); + let va = sp_a.eval(t); + let vb = sp_b.eval(t); + let diff = (va - vb).abs(); + if !(va.is_nan() && vb.is_nan()) && diff > 1e-5 * va.abs().max(1.0) { + failures.push(format!( + "{}: spline {sname} @ t={t} mismatch: {va} vs {vb}", + p.display() + )); + break; + } + } + } + } + + assert!( + failures.is_empty(), + "roundtrip failed on {}/{} comps:\n{}", + failures.len(), + paths.len(), + failures.iter().take(20).cloned().collect::>().join("\n") + ); + eprintln!("Losslessly roundtripped {}/{} real .comp files!", paths.len(), paths.len()); + } + + #[test] + fn preserves_unknown_nodes_and_applies_edits_with_temp_backup() { + let src = r#"Composition { + CurrentTime = 10, + RenderRange = { 0, 100 }, + GlobalRange = { 0, 100 }, + Prefs = { + Comp = { + FrameFormat = { + Width = 1920, + Height = 1080, + Rate = 24, + DepthFull = 3, + }, + }, + }, + Tools = { + BG1 = Background { + Inputs = { + Width = Input { Value = 1920, }, + Height = Input { Value = 1080, }, + TopLeftRed = Input { Value = 0.25, }, + }, + ViewInfo = OperatorInfo { Pos = { 100, 50 } }, + }, + OverlayBG = Background { + Inputs = { + TopLeftGreen = Input { Value = 0.8, }, + }, + ViewInfo = OperatorInfo { Pos = { 100, 200 } }, + }, + Mask1 = EllipseMask { + ViewInfo = OperatorInfo { Pos = { 250, 250 } }, + }, + SurfaceTracker1 = SurfaceTracker { + Inputs = { + Source = Input { + SourceOp = "BG1", + Source = "Output", + }, + Overlay = Input { + SourceOp = "OverlayBG", + Source = "Output", + }, + TrackingMask = Input { + SourceOp = "Mask1", + Source = "Mask", + }, + MeshBlob = Input { + Value = TrackingMesh { + Vertices = { 0.1, 0.2, 0.3, 0.4 }, + Meta = "line1\nline2\"quoted\"\\slash", + }, + }, + }, + UserControls = ordered() { + CustomGain = { + INP_Default = 1.5, + LINKID_DataType = "Number", + }, + }, + ViewInfo = OperatorInfo { Pos = { 300, 100 }, Flags = { ShowName = true } }, + }, + BC1 = BrightnessContrast { + Inputs = { + Input = Input { + SourceOp = "SurfaceTracker1", + Source = "Output", + }, + Gain = Input { + SourceOp = "BC1Gain", + Source = "Value", + }, + }, + ViewInfo = OperatorInfo { Pos = { 500, 100 } }, + }, + BC1Gain = BezierSpline { + SplineColor = { Red = 255, Green = 128, Blue = 0 }, + KeyFrames = { + [0] = { 1, RH = { 10, 1 }, Flags = { Linear = true } }, + [30] = { 2, LH = { 20, 2 }, Flags = { Linear = true } }, + }, + }, + }, +}"#; + + let mut comp = Comp::from_fusion_str(src).expect("parse synthetic comp"); + assert!(!is_supported_tool("SurfaceTracker")); + assert!(is_supported_tool("BrightnessContrast")); + assert!(is_supported_tool("Renderer3D")); + + // Verify unknown node connections surface all 3 ports with proper roles + let st_id = comp.find_node("SurfaceTracker1").expect("SurfaceTracker1"); + let names: std::collections::HashSet = comp.node_by_name.keys().cloned().collect(); + let conns = comp.node(st_id).image_connections(&names); + assert_eq!( + conns, + vec![ + ("Overlay".to_owned(), "OverlayBG".to_owned(), PortRole::Foreground), + ("Source".to_owned(), "BG1".to_owned(), PortRole::Background), + ("TrackingMask".to_owned(), "Mask1".to_owned(), PortRole::Mask), + ] + ); + + // Mutate a different node's position, bypass, wire, param, and a BezierSpline keyframe + let bc_id = comp.find_node("BC1").expect("BC1"); + let bg_id = comp.find_node("BG1").expect("BG1"); + { + let bc = comp.node_mut(bc_id); + bc.pos = [650.0, 125.0]; + bc.bypassed = true; + bc.inputs.insert( + "Gamma".to_owned(), + InputBinding { + value: Some(ParamValue::Number(1.35)), + source_op: None, + source_output: None, + expression: None, + }, + ); + } + comp.connect(bg_id, bc_id, "EffectMask"); + comp.splines + .get_mut("BC1Gain") + .unwrap() + .keyframes + .push(Keyframe::new(60.0, 3.5)); + + // Save to a fresh temp directory twice + let unique_dir = std::env::temp_dir().join(format!( + "fission_test_save_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&unique_dir).unwrap(); + let comp_path = unique_dir.join("test_shot.comp"); + + // First save: file does not exist yet -> no backup + let bak1 = comp.save_to_file(&comp_path).expect("first save"); + assert!(bak1.is_none()); + + // Second save: file exists -> backup goes to temp_dir/fission-backups/, NOT next to comp + let bak2 = comp.save_to_file(&comp_path).expect("second save"); + let bak2_path = bak2.expect("expected backup path on second save"); + assert!(bak2_path.exists()); + assert_eq!( + bak2_path.parent().unwrap(), + std::env::temp_dir().join("fission-backups") + ); + // Ensure no .bak file next to test_shot.comp + let siblings: Vec<_> = std::fs::read_dir(&unique_dir) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(siblings, vec!["test_shot.comp".to_owned()]); + + // Reload and verify edits persisted AND SurfaceTracker survived 100% intact + let reloaded = Comp::from_fusion_file(&comp_path).expect("reload saved comp"); + let r_bc = reloaded.node(reloaded.find_node("BC1").unwrap()); + assert_eq!(r_bc.pos, [650.0, 125.0]); + assert!(r_bc.bypassed); + assert_eq!(r_bc.static_number("Gamma"), Some(1.35)); + assert_eq!(r_bc.connected_node("EffectMask"), Some("BG1")); + + let r_sp = reloaded.splines.get("BC1Gain").expect("BC1Gain spline"); + assert_eq!(r_sp.keyframes.len(), 3); + assert!((r_sp.eval(60.0) - 3.5).abs() < 1e-6); + + let r_st = reloaded.node(reloaded.find_node("SurfaceTracker1").unwrap()); + assert_eq!(r_st.kind, "SurfaceTracker"); + let r_names: std::collections::HashSet = + reloaded.node_by_name.keys().cloned().collect(); + assert_eq!(r_st.image_connections(&r_names), conns); + // Verify custom nested MeshBlob and UserControls survived verbatim + let mesh = r_st + .raw + .get_table("Inputs") + .and_then(|i| i.get_table("MeshBlob")) + .and_then(|m| m.get_table("Value")) + .expect("MeshBlob Value"); + assert_eq!(mesh.tag.as_deref(), Some("TrackingMesh")); + assert_eq!(mesh.get_str("Meta"), Some("line1\nline2\"quoted\"\\slash")); + assert!(r_st.raw.get_table("UserControls").is_some()); + // Verify unedited UserControl default was NOT injected into raw Inputs + assert!( + r_st.raw + .get_table("Inputs") + .and_then(|i| i.get("CustomGain")) + .is_none() + ); + + let _ = std::fs::remove_dir_all(&unique_dir); + let _ = std::fs::remove_file(&bak2_path); + } + + #[test] + fn saver_spec_frame_paths() { + let make = |filename: &str| SaverSpec { + node_id: NodeId(0), + name: "Saver1".to_owned(), + upstream: None, + filename: filename.to_owned(), + range: [0, 100], + sequence_start: None, + }; + + assert_eq!( + make("/renders/foo_0000.png").frame_path(42), + std::path::PathBuf::from("/renders/foo_0042.png") + ); + assert_eq!( + make("/renders/0000.png").frame_path(7), + std::path::PathBuf::from("/renders/0007.png") + ); + assert_eq!( + make("/renders/render.png").frame_path(12), + std::path::PathBuf::from("/renders/render0012.png") + ); + assert_eq!( + make("foo_000000.exr").frame_path(1001), + std::path::PathBuf::from("foo_001001.exr") + ); + + let comp = Comp::from_fusion_file("/Volumes/Project/trees/fusion/20_falling.comp") + .expect("load 20_falling.comp"); + let savers = comp.savers(); + assert!(!savers.is_empty(), "expected Saver in 20_falling.comp"); + let s = &savers[0]; + assert_eq!(s.name, "Saver1"); + assert!(s.upstream.is_some()); + assert_eq!(s.range, comp.render_range); + assert_eq!( + s.frame_path(2130), + std::path::PathBuf::from("/Volumes/Project/trees/FusionRender/2130.png") + ); + } } diff --git a/crates/model/src/lua_value.rs b/crates/model/src/lua_value.rs index 4f58106379f4c59e51d68553323f687aa75e369b..2f5e45fd6de7d56b63aa645425ef6f71a083f418 100644 --- a/crates/model/src/lua_value.rs +++ b/crates/model/src/lua_value.rs @@ -38,6 +38,13 @@ impl LuaTable { }) } + pub fn get_mut(&mut self, key: &str) -> Option<&mut LuaValue> { + self.entries.iter_mut().find_map(|(k, v)| match k { + LuaKey::Str(s) if s == key => Some(v), + _ => None, + }) + } + pub fn get_index(&self, idx: i64) -> Option<&LuaValue> { self.entries.iter().find_map(|(k, v)| match k { LuaKey::Index(i) if *i == idx => Some(v), @@ -50,6 +57,25 @@ impl LuaTable { self.get(key)?.as_table() } + pub fn get_table_mut(&mut self, key: &str) -> Option<&mut LuaTable> { + self.get_mut(key)?.as_table_mut() + } + + /// Replaces an existing entry with the same key in place (preserving order), or appends it. + pub fn set(&mut self, key: LuaKey, val: LuaValue) { + if let Some((_, existing)) = self.entries.iter_mut().find(|(k, _)| *k == key) { + *existing = val; + } else { + self.entries.push((key, val)); + } + } + + /// Removes the first entry matching `key`, preserving order of remaining entries. + pub fn remove(&mut self, key: &LuaKey) -> Option { + let pos = self.entries.iter().position(|(k, _)| k == key)?; + Some(self.entries.remove(pos).1) + } + pub fn get_str(&self, key: &str) -> Option<&str> { self.get(key)?.as_str() } @@ -68,6 +94,13 @@ impl LuaTable { _ => None, }) } + + /// Serializes this table using Blackmagic Fusion `.comp` Lua table syntax. + pub fn to_fusion_string(&self) -> String { + let mut out = String::new(); + write_table(self, 0, &mut out); + out + } } impl LuaValue { @@ -78,6 +111,13 @@ impl LuaValue { } } + pub fn as_table_mut(&mut self) -> Option<&mut LuaTable> { + match self { + LuaValue::Table(t) => Some(t), + _ => None, + } + } + pub fn as_str(&self) -> Option<&str> { match self { LuaValue::String(s) => Some(s.as_str()), @@ -107,6 +147,13 @@ impl LuaValue { _ => None, } } + + /// Serializes this value using Blackmagic Fusion `.comp` Lua table syntax. + pub fn to_fusion_string(&self) -> String { + let mut out = String::new(); + write_value(self, 0, &mut out); + out + } } #[derive(Clone, Debug)] @@ -601,3 +648,247 @@ fn is_ident_start(b: u8) -> bool { fn is_ident_cont(b: u8) -> bool { b.is_ascii_alphanumeric() || b == b'_' } + +fn is_valid_lua_ident(s: &str) -> bool { + let bytes = s.as_bytes(); + if bytes.is_empty() || !is_ident_start(bytes[0]) || !bytes[1..].iter().all(|&b| is_ident_cont(b)) { + return false; + } + !matches!( + s, + "and" + | "break" + | "do" + | "else" + | "elseif" + | "end" + | "false" + | "for" + | "function" + | "goto" + | "if" + | "in" + | "local" + | "nil" + | "not" + | "or" + | "repeat" + | "return" + | "then" + | "true" + | "until" + | "while" + ) +} + +fn write_indent(out: &mut String, depth: usize) { + for _ in 0..depth { + out.push('\t'); + } +} + +fn write_number(n: f64, out: &mut String) { + if n.is_nan() { + out.push_str("nan"); + } else if n.is_infinite() { + if n.is_sign_negative() { + out.push_str("-1e999"); + } else { + out.push_str("1e999"); + } + } else if n == 0.0 { + out.push('0'); + } else if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 { + use std::fmt::Write; + let _ = write!(out, "{}", n as i64); + } else { + use std::fmt::Write; + let _ = write!(out, "{n}"); + } +} + +fn write_string(s: &str, out: &mut String) { + use std::fmt::Write; + 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 (c as u32) < 0x20 || (c as u32) == 0x7F => { + let _ = write!(out, "\\{:03}", c as u32); + } + c => out.push(c), + } + } + out.push('"'); +} + +fn write_value(val: &LuaValue, depth: usize, out: &mut String) { + match val { + LuaValue::Nil => out.push_str("nil"), + LuaValue::Bool(true) => out.push_str("true"), + LuaValue::Bool(false) => out.push_str("false"), + LuaValue::Number(n) => write_number(*n, out), + LuaValue::String(s) => write_string(s, out), + LuaValue::Table(t) => write_table(t, depth, out), + } +} + +fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>) { + let mut call_args = Vec::new(); + let mut next_arg = 0usize; + let mut arg_indices = Vec::new(); + for (idx, (k, v)) in tbl.entries.iter().enumerate() { + if let LuaKey::Str(s) = k { + if let Some(rest) = s.strip_prefix("__arg") { + if rest.parse::().ok() == Some(next_arg) { + call_args.push(v); + arg_indices.push(idx); + next_arg += 1; + continue; + } + } + } + } + let body = tbl + .entries + .iter() + .enumerate() + .filter(|(idx, _)| !arg_indices.contains(idx)) + .map(|(_, e)| e) + .collect(); + (call_args, body) +} + +fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { + let mut expected = 1i64; + let mut index_count = 0usize; + for (k, _) in body { + match k { + LuaKey::Number(_) => return false, + LuaKey::Index(i) => { + if *i != expected { + return false; + } + expected += 1; + index_count += 1; + } + LuaKey::Str(_) => {} + } + } + if index_count == 1 && body.len() == 1 { + if let (LuaKey::Index(1), LuaValue::Table(sub)) = body[0] { + if sub.tag.is_none() + && (sub.get("Flags").is_some() || sub.get("LH").is_some() || sub.get("RH").is_some()) + { + return false; + } + } + } + true +} + +fn can_inline_table(tbl: &LuaTable, max_depth: usize) -> bool { + if max_depth == 0 { + return false; + } + if tbl.tag.as_deref() == Some("ordered") { + return false; + } + let (call_args, body) = split_call_args(tbl); + if !call_args.is_empty() || body.len() > 4 { + return false; + } + body.iter().all(|(_, v)| match v { + LuaValue::Nil | LuaValue::Bool(_) | LuaValue::Number(_) => true, + LuaValue::String(s) => !s.contains('\n') && !s.contains('\r') && s.len() <= 48, + LuaValue::Table(sub) => max_depth > 1 && can_inline_table(sub, max_depth - 1), + }) +} + +fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, out: &mut String) { + if let Some(t) = tag { + out.push_str(t); + if t == "ordered" || !call_args.is_empty() { + out.push('('); + for (i, arg) in call_args.iter().enumerate() { + if i > 0 { + out.push_str(", "); + } + write_value(arg, depth, out); + } + out.push(')'); + } + out.push(' '); + } +} + +fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool { + match key { + LuaKey::Index(_) if positional => false, + LuaKey::Index(i) => { + use std::fmt::Write; + let _ = write!(out, "[{i}] = "); + true + } + LuaKey::Number(n) => { + out.push('['); + write_number(*n, out); + out.push_str("] = "); + true + } + LuaKey::Str(s) => { + if is_valid_lua_ident(s) { + out.push_str(s); + out.push_str(" = "); + } else { + out.push('['); + write_string(s, out); + out.push_str("] = "); + } + true + } + } +} + +fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) { + let (call_args, body) = split_call_args(tbl); + write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out); + + if body.is_empty() { + out.push_str("{}"); + return; + } + + let positional = can_use_positional(&body); + + if depth > 0 && can_inline_table(tbl, 2) { + let mut inline = String::new(); + inline.push_str("{ "); + for (i, (k, v)) in body.iter().enumerate() { + if i > 0 { + inline.push_str(", "); + } + write_entry_key(k, positional, &mut inline); + write_value(v, depth + 1, &mut inline); + } + inline.push_str(" }"); + if !inline.contains('\n') && inline.len() <= 100 { + out.push_str(&inline); + return; + } + } + + out.push_str("{\n"); + for (k, v) in body { + write_indent(out, depth + 1); + write_entry_key(k, positional, out); + write_value(v, depth + 1, out); + out.push_str(",\n"); + } + write_indent(out, depth); + out.push('}'); +} diff --git a/crates/studio/src/main.rs b/crates/studio/src/main.rs index f4ce3fb8f361c320de40e0efca2cf8bc1a9d7d09..5010b03ccca5e6123dcd183665f81384f901f2f9 100644 --- a/crates/studio/src/main.rs +++ b/crates/studio/src/main.rs @@ -2,7 +2,7 @@ //! built on Knife's `draw`, `ui`, `dock`, and `theme::KNIFE` (soft toned quiet iris). use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab}; -use engine::{CacheMode, Engine}; +use engine::{AudioPlayer, AudioTrack, CacheMode, Engine, ExportOptions, export_saver_png_sequence}; use flow::{FlowAction, FlowView}; use model::Comp; use spline::{SplineAction, SplineView}; @@ -10,7 +10,7 @@ use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, mpsc}; use std::time::{Duration, Instant}; use ui::host::{Accessibility, Clipboard, Surface}; use viewer::{PlaybackClock, SyncMode, ViewerAction, ViewerState}; @@ -93,7 +93,11 @@ struct Studio { renderer: draw::Renderer, engine: Engine, comp: Comp, + saved_revision: u64, playback: PlaybackClock, + audio_player: Option, + audio_rx: Option>>, + status_notice: Option<(String, Instant)>, viewers: [ViewerState; 2], flow: FlowView, spline: SplineView, @@ -103,7 +107,14 @@ struct Studio { } impl Studio { - fn new(renderer: draw::Renderer, comp: Comp, init_frame: Option, select_node: Option<&str>, dual_viewer: bool) -> Self { + fn new( + renderer: draw::Renderer, + comp: Comp, + init_frame: Option, + select_node: Option<&str>, + dual_viewer: bool, + enable_audio: bool, + ) -> Self { let engine = Engine::new(renderer.device().clone(), renderer.queue().clone()); // Knife's soft toned Iris quiet-layered theme! let ui_theme = ui::Theme::new(&theme::KNIFE, true); @@ -206,6 +217,32 @@ impl Studio { let mut spline = SplineView::new(&ui_theme); spline.set_target_node(&comp, default_sel); + let (audio_player, audio_rx) = if enable_audio { + let player = match AudioPlayer::new() { + Ok(p) => Some(p), + Err(e) => { + eprintln!("fission audio disabled: {e}"); + None + } + }; + let rx = comp.audio_filename.as_ref().and_then(|af| { + let p = PathBuf::from(af); + if !p.exists() { + return None; + } + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(AudioTrack::load(&p)); + }); + Some(rx) + }); + (player, rx) + } else { + (None, None) + }; + + let saved_revision = comp.revision; + Self { ui, dock, @@ -214,7 +251,11 @@ impl Studio { renderer, engine, comp, + saved_revision, playback, + audio_player, + audio_rx, + status_notice: None, viewers: [v1, v2], flow, spline, @@ -224,6 +265,143 @@ impl Studio { } } + fn audio_time_secs(&self) -> f64 { + (self.playback.current_frame - self.comp.audio_offset) / self.comp.fps.max(1.0) + } + + fn poll_audio_load(&mut self) { + let Some(rx) = &self.audio_rx else { return }; + match rx.try_recv() { + Ok(Ok(track)) => { + eprintln!( + "Loaded audio {} ({:.2}s @ {}Hz)", + track.path.display(), + track.duration_secs, + track.sample_rate + ); + let t = self.audio_time_secs(); + let playing = self.playback.playing; + if let Some(player) = &mut self.audio_player { + player.set_track(Some(Arc::new(track))); + if playing { + player.play_from(t); + } + } + self.audio_rx = None; + } + Ok(Err(e)) => { + eprintln!("fission audio load error: {e}"); + self.audio_rx = None; + } + Err(mpsc::TryRecvError::Disconnected) => { + self.audio_rx = None; + } + Err(mpsc::TryRecvError::Empty) => {} + } + } + + fn sync_audio(&mut self, state_changed: bool, seeked: bool) { + let t = self.audio_time_secs(); + let playing = self.playback.playing; + if let Some(player) = &mut self.audio_player { + if playing { + if state_changed || !player.is_playing() { + player.play_from(t); + } else if seeked { + player.seek(t); + } + } else if state_changed || player.is_playing() { + player.pause(); + } + } + } + + fn save_comp(&mut self) -> Result { + let Some(path) = self.comp.path.clone() else { + return Err("comp has no file path to save".to_owned()); + }; + self.comp.current_time = self.playback.current_frame; + match self.comp.save_to_file(&path) { + Ok(backup) => { + self.saved_revision = self.comp.revision; + let msg = match backup { + Some(bak) => { + eprintln!("Saved {} (backup -> {})", path.display(), bak.display()); + format!("Saved (backup in temp)") + } + None => { + eprintln!("Saved {}", path.display()); + "Saved".to_owned() + } + }; + self.status_notice = Some((msg.clone(), Instant::now())); + Ok(msg) + } + Err(e) => { + let err = format!("Save failed: {e}"); + eprintln!("{err}"); + self.status_notice = Some((err.clone(), Instant::now())); + Err(err) + } + } + } + + fn export_saver_pngs(&mut self) -> Result { + if self.playback.playing { + self.playback.toggle_play(Instant::now()); + self.sync_audio(true, false); + } + let opts = ExportOptions { + hiq: self.engine.hiq, + proxy_scale: self.engine.proxy_scale, + ..Default::default() + }; + let t0 = Instant::now(); + match export_saver_png_sequence(&mut self.engine, &self.comp, &opts, |p| { + if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { + let fps = (p.index + 1) as f64 / t0.elapsed().as_secs_f64().max(1e-6); + eprintln!( + " [export {}/{}] {} f{:04} ({:.1}ms, {:.1} fps) -> {}", + p.index + 1, + p.total, + p.saver_name, + p.frame, + p.eval_ms, + fps, + p.out_path.display() + ); + } + }) { + Ok(summary) => { + let secs = (summary.total_ms / 1000.0).max(1e-6); + let msg = format!( + "Exported {} PNGs ({:.1} fps)", + summary.frames_written, + summary.frames_written as f64 / secs + ); + eprintln!("{msg} via {}", summary.saver_name); + self.status_notice = Some((msg.clone(), Instant::now())); + Ok(msg) + } + Err(e) => { + let err = format!("Export failed: {e}"); + eprintln!("{err}"); + self.status_notice = Some((err.clone(), Instant::now())); + Err(err) + } + } + } + + fn window_title(&self) -> String { + let dirty = if self.comp.revision != self.saved_revision { " •" } else { "" }; + if let Some((msg, at)) = &self.status_notice { + if at.elapsed() < Duration::from_secs(5) { + return format!("Fission — {}{dirty} — {msg}", self.comp.name); + } + } + format!("Fission — {}{dirty}", self.comp.name) + } + fn ensure_viewer2_open(&mut self) { if self.layout.group_of(&"Viewer 2".to_owned(), String::clone).is_some() { return; @@ -246,8 +424,14 @@ impl Studio { fn frame(&mut self, now: Instant) -> bool { self.clock = now; + self.poll_audio_load(); + let prev_frame = self.playback.current_frame; let (animating, frame_changed) = self.playback.tick(&self.comp, now); if frame_changed { + // Re-sync audio when playback loops back to start of render range + if self.playback.playing && self.playback.current_frame < prev_frame { + self.sync_audio(false, true); + } for v in &mut self.viewers { v.dirty = true; } @@ -270,6 +454,7 @@ impl Studio { .map(|&name| ui::popup::Item { text: name, ..Default::default() }) .collect(); + let comp_unsaved = self.comp.revision != self.saved_revision; let Studio { ui, dock, @@ -308,7 +493,7 @@ impl Studio { Tab { title: name, icon: None, - unsaved: false, + unsaved: name == "Flow" && comp_unsaved, closable: true, action: None, background: bg, @@ -447,6 +632,7 @@ impl Studio { } SplineAction::ScrubFrame(f) => { if self.playback.set_frame(&self.comp, f, now) { + self.sync_audio(false, true); for v in &mut self.viewers { v.dirty = true; } @@ -471,9 +657,13 @@ impl Studio { fn route_viewer_actions(&mut self, actions: Vec<(usize, ViewerAction)>, now: Instant) { for (slot, a) in actions { match a { - ViewerAction::TogglePlay => self.playback.toggle_play(now), + ViewerAction::TogglePlay => { + self.playback.toggle_play(now); + self.sync_audio(true, false); + } ViewerAction::SetFrame(f) => { if self.playback.set_frame(&self.comp, f, now) { + self.sync_audio(false, true); for v in &mut self.viewers { v.dirty = true; } @@ -613,7 +803,7 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box> { }))?; let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm); - let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer); + let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, false); studio.size = [1440.0, 900.0]; studio.scale = 2.0; @@ -702,13 +892,13 @@ fn run_window(cli: &Cli) -> Result<(), Box> { impl WindowHost { fn new(event_loop: &ActiveEventLoop, proxy: EventLoopProxy, cli: &Cli) -> Result> { let comp = Comp::from_fusion_file(&cli.comp_path)?; - let title = format!("Compositor — {}", comp.name); + let title = format!("Fission — {}", comp.name); let attrs = Window::default_attributes() .with_title(title) .with_inner_size(LogicalSize::new(1440.0, 900.0)); let (window, access) = Accessibility::window(event_loop, attrs, [640.0, 420.0], proxy.clone(), ui::Id::ROOT)?; let (surface, renderer) = pollster::block_on(Surface::new(window.clone()))?; - let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer); + let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, true); studio.ui.window_focused = window.has_focus(); studio.ui.clipboard = Clipboard::system(); window.request_redraw(); @@ -733,6 +923,7 @@ impl WindowHost { } self.studio.size = pixels.map(|s| s as f32 / self.studio.scale); let wants_more = self.studio.frame(now); + self.window.set_title(&self.studio.window_title()); self.window.set_cursor(self.studio.ui.cursor().unwrap_or(CursorIcon::Default)); self.access.update_views(&mut self.studio.ui, "Compositor", f64::from(self.studio.scale), Vec::new); @@ -748,7 +939,31 @@ impl WindowHost { } fn input(&mut self, event: ui::Event) { - // Global Space toggles playback and `` ` `` clears both viewers from any focused pane! + // Global Cmd+S saves lossless .comp (with temp-folder .bak); Cmd+Shift+R exports Saver PNG sequence! + let (is_cmd_s, is_cmd_shift_r) = match &event { + ui::Event::KeyInput { physical, modifiers, state: ElementState::Pressed, repeat: false, .. } => ( + modifiers.super_key() && !modifiers.shift_key() && *physical == PhysicalKey::Code(KeyCode::KeyS), + modifiers.super_key() && modifiers.shift_key() && *physical == PhysicalKey::Code(KeyCode::KeyR), + ), + ui::Event::Key { key: Key::Character(c), modifiers, .. } => ( + modifiers.super_key() && !modifiers.shift_key() && c.eq_ignore_ascii_case("s"), + modifiers.super_key() && modifiers.shift_key() && c.eq_ignore_ascii_case("r"), + ), + _ => (false, false), + }; + if is_cmd_s { + let _ = self.studio.save_comp(); + self.window.set_title(&self.studio.window_title()); + self.window.request_redraw(); + return; + } + if is_cmd_shift_r { + let _ = self.studio.export_saver_pngs(); + self.window.set_title(&self.studio.window_title()); + self.window.request_redraw(); + return; + } + // Global Space toggles playback (synced with audio) and `` ` `` clears both viewers from any focused pane! let is_space = matches!( &event, ui::Event::KeyInput { key: Key::Named(NamedKey::Space), state: ElementState::Pressed, repeat: false, .. } @@ -756,6 +971,7 @@ impl WindowHost { ); if is_space { self.studio.playback.toggle_play(Instant::now()); + self.studio.sync_audio(true, false); self.window.request_redraw(); return; } diff --git a/scripts/gen_compatibility.py b/scripts/gen_compatibility.py new file mode 100755 index 0000000000000000000000000000000000000000..e5c9b123ebc1d5cef7a9198b5a41ef853db1bb9c --- /dev/null +++ b/scripts/gen_compatibility.py @@ -0,0 +1,544 @@ +#!/usr/bin/env python3 +"""Generate compatibility.md from live Rust engine sources and real Fusion .comp corpora. + +Stdlib-only Python 3 script. Run from anywhere: + python3 scripts/gen_compatibility.py +""" + +from __future__ import annotations + +import argparse +import re +import sys +from collections import Counter +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Set, Tuple + +REPO_ROOT = Path(__file__).resolve().parent.parent +EVAL_RS = REPO_ROOT / "crates" / "engine" / "src" / "eval.rs" +SCENE3D_RS = REPO_ROOT / "crates" / "engine" / "src" / "scene3d.rs" +COMP_RS = REPO_ROOT / "crates" / "model" / "src" / "comp.rs" +PROBES_PY = REPO_ROOT / "scripts" / "fusion_probes.py" +DEFAULT_OUTPUT = REPO_ROOT / "compatibility.md" + +ACTIVE_CORPUS_DIR = Path("/Volumes/Project/trees/fusion") +ARCHIVE_CORPUS_DIR = REPO_ROOT / "private" / "samples" +SHALE_ISSUES_URL = "https://shale.paperclover.net/fission/issues" + + +@dataclass(frozen=True) +class ToolMeta: + name: str + category: str + probe: str + mae: str + notes: str + aliases: Tuple[str, ...] = () + + +CATEGORIES: Sequence[str] = ( + "Generators", + "Compositing & Blending", + "Color & Depth", + "Keying", + "Blur, Sharpen & Glow", + "Transform, Warp & Framing", + "Masks", + "3D Pipeline", + "Time, Routing & Utility", +) + +# Structured metadata for every supported Flow tool. +# Any tool discovered in eval.rs / scene3d.rs that is missing here will be +# flagged automatically so compatibility.md never drifts stale. +TOOL_METADATA: Sequence[ToolMeta] = ( + # Generators + ToolMeta("Background", "Generators", "`tier1_d`", "0.0%", "Solid, Horizontal/Vertical/4-Corner, Linear/Radial gradients; honors generator `Depth` in `HiQ`."), + ToolMeta("FastNoise", "Generators", "`noise_text`", "Visual*", "C2 quintic 3D Perlin fBm (`Detail`, `Contrast`, `Brightness`, `Seethe`, `LockXY`, `Angle`, `Discontinuous`, `Gradient`/`TwoColor`). *Proprietary Fusion lattice table differs ([#6](" + SHALE_ISSUES_URL + "/6))."), + ToolMeta("Plasma", "Generators", "`tier1_c`", "0.1%–0.2%", "4-circle linear/sine interference pattern with phase/scale animation."), + ToolMeta("TextPlus", "Generators", "`text`, `noise_text`", "0.1%–0.6%", "CoreText rasterizer, alignment, tracking, Euclidean subpixel SDF outline, `StyledTextCLS`. `BorderFill` tracked in [#6](" + SHALE_ISSUES_URL + "/6)."), + ToolMeta("Loader", "Generators", "All suites", "0.0%", "PNG/JPG/TIFF/EXR stills & sequences; native macOS `AVFoundation`/`VideoToolbox` + `ffmpeg` video; `.wav`/`.mp3` audio. Direct 16/32-bit float EXR upload tracked in [#5](" + SHALE_ISSUES_URL + "/5)."), + + # Compositing & Blending + ToolMeta("Merge", "Compositing & Blending", "`merge`", "0.0%–0.3%", "All ApplyModes (`Normal`, `Screen`, `Multiply`, `Difference`, `DarkerColor`, `Overlay`, `Hard/Soft/Linear/VividLight`, `LinearDodge`, etc.), `Operator=Over/Under`, `Gain`, `BurnIn`, `SubtractiveAdditive`, `Blend`, effect mask."), + ToolMeta("Dissolve", "Compositing & Blending", "`tier1_b`", "0.0%–0.1%", "Mix (`Mix = 0..1`) between `Background` and `Foreground` with effect mask support."), + ToolMeta("Shadow", "Compositing & Blending", "`tier1_b`", "0.1%–0.4%", "Drop shadow offset, softness blur, tint color/alpha, and `ShadowOnly` output."), + + # Color & Depth + ToolMeta("BrightnessContrast", "Color & Depth", "`color_ops`, `tier1_d`", "0.0%–0.1%", "Gain, Lift, Gamma, Contrast, Brightness, Saturation, channel toggles, `PreDividePostMultiply`, `ClipBlack`/`ClipWhite`."), + ToolMeta("ColorCorrector", "Color & Depth", "Suite comps", "0.1%–0.5%", "Master/Shadow/Midtone/Highlight wheel tint, Lift/Gamma/Gain/Brightness/Contrast/Saturation, `PreDividePostMultiply`."), + ToolMeta("ColorGain", "Color & Depth", "`color_ops`, `noise_text`", "0.0%–0.1%", "Per-channel Gain, Lift, Gamma, Hue, Saturation, `PreDividePostMultiply`."), + ToolMeta("ColorCurves", "Color & Depth", "Suite comps", "0.1%–0.4%", "Per-channel RGBA `LUTBezier` spline lookup tables with `PreDividePostMultiply`."), + ToolMeta("HueCurves", "Color & Depth", "`tier1_a`", "0.1%–0.5%", "9 nested `LUTBezier` splines (Hue/Sat/Lum vs Hue, Suppression, etc.) baked to GPU LUT."), + ToolMeta("GamutConvert", "Color & Depth", "Suite comps", "0.0%–0.2%", "Color space & gamma curve transforms (`sRGB`, `Rec.709`, `Linear`, `SLog2`, etc.)."), + ToolMeta("InvertColor", "Color & Depth", "Suite comps", "0.0%", "Per-channel RGBA color inversion (`R`/`G`/`B`/`A` toggles)."), + ToolMeta("ChannelBoolean", "Color & Depth", "`color_ops`", "0.0%–0.1%", "Channel routing (`ToRed`/`ToGreen`/`ToBlue`/`ToAlpha`) and arithmetic/logic ops (`Copy`, `Add`, `Subtract`, `Multiply`, `Divide`, `Min`, `Max`, `Clear`, `Solid`, etc.)."), + ToolMeta("ChangeDepth", "Color & Depth", "`tier1_d`", "0.0%", "Bit-depth conversion (`int8`, `int16`, `float16`, `float32`) honored in `HiQ` mode; collapsed to `Rgba8Unorm` in `Fast` mode."), + ToolMeta("Fuse.Colorize", "Color & Depth", "Suite comps", "0.1%–0.5%", "Gradient/tint colorization driven by luminance."), + + # Keying + ToolMeta("LumaKeyer", "Keying", "Suite comps", "0.1%–0.4%", "Luminance/channel threshold keying with low/high feathering and matte inversion."), + ToolMeta("UltraKeyer", "Keying", "`tier1_a`", "0.1%–0.6%", "Chroma keying with background color pick, matte threshold/gamma, spill suppression, and post-multiply."), + + # Blur, Sharpen & Glow + ToolMeta("Blur", "Blur, Sharpen & Glow", "`blur`, `tier1_d`", "0.0%–0.4%", "`Fast Gaussian`, `Gaussian`, and `Box` filters; X/Y lock; `ClippingMode`; HDR float16 survival in `HiQ`; downsampled in `Fast`."), + ToolMeta("Sharpen", "Blur, Sharpen & Glow", "`tier1_a`", "0.1%–0.4%", "Separable unsharp mask with X/Y amount & lock."), + ToolMeta("Filter", "Blur, Sharpen & Glow", "`tier1_a`", "0.1%–0.5%", "Convolution filter types 0–4 (`Relief`, `Emboss`, `Smooth`, `Sobel`, `Laplacian`) with power & angle."), + ToolMeta("VariBlur", "Blur, Sharpen & Glow", "Suite comps", "0.2%–0.8%", "Per-pixel variable-radius blur driven by `BlurImage` matte."), + ToolMeta("DirectionalBlur", "Blur, Sharpen & Glow", "`blur`", "0.1%–0.5%", "`Linear`, `Centered`, `Radial`, and `Zoom` modes plus `Glow` accumulation."), + ToolMeta("Glow", "Blur, Sharpen & Glow", "`glow`", "0.2%–1.3%", "Additive bloom (`Glow`, `GlowSize`, `Blend`, color scale). Minor Gaussian tail roll-off tracked in [#6](" + SHALE_ISSUES_URL + "/6)."), + ToolMeta("SoftGlow", "Blur, Sharpen & Glow", "`glow`", "0.0%–0.8%", "Thresholded soft glow (`Gain`, `XGlowSize`/`YGlowSize`, `Threshold`, `ClippingMode`, `ColorScale`)."), + ToolMeta("Fuse.XGlow", "Blur, Sharpen & Glow", "Suite comps", "0.2%–0.8%", "Multi-octave exponential glow (`Threshold`, `Gain`, `XGlowSize`, `Falloff`, `Iterations`); octave-capped in `Fast` mode."), + ToolMeta("ErodeDilate", "Blur, Sharpen & Glow", "`blur`", "0.0%–0.3%", "Positive/negative morphological erode/dilate with `Box` and `Circle` kernels."), + ToolMeta("FilmGrain", "Blur, Sharpen & Glow", "`tier1_c`", "Visual*", "Monochrome log-space correlated film grain (`Size`, `Strength`, `Softness`). *Stochastic per-frame seed."), + ToolMeta("Fuse.Outline", "Blur, Sharpen & Glow", "Suite comps", "0.1%–0.5%", "Alpha-derived silhouette outline with thickness, softness, and color tint."), + ToolMeta("Fuse.XfChroma", "Blur, Sharpen & Glow", "Suite comps", "0.1%–0.5%", "Chromatic aberration / RGB channel radial & positional dispersion."), + + # Transform, Warp & Framing + ToolMeta("Transform", "Transform, Warp & Framing", "`xf`", "0.0%–0.3%", "`Center`, `Pivot`, `Size`/`XSize`/`YSize`, `Aspect`, `Angle`, `FlipHoriz`/`FlipVert`, `FilterMethod` (`Nearest`/`Box`/`Linear`/`Catmull-Rom`), `Edges` (`Canvas`/`Wrap`/`Duplicate`/`Mirror`)."), + ToolMeta("CameraShake", "Transform, Warp & Framing", "`tier1_c`", "0.1%–0.5%", "Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`."), + ToolMeta("CornerPositioner", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`)."), + ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."), + ToolMeta("Displace", "Transform, Warp & Framing", "`displace`", "0.1%–0.7%", "`XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower` angle/color minor parity tracked in [#6](" + SHALE_ISSUES_URL + "/6))."), + ToolMeta("Scale", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Proportional/non-proportional image scaling with resampling filter."), + ToolMeta("BetterResize", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`)."), + ToolMeta("Crop", "Transform, Warp & Framing", "Suite comps", "0.0%–0.1%", "Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`)."), + ToolMeta("SetDomain", "Transform, Warp & Framing", "`tier1_d`", "0.0%–0.1%", "Domain-of-Definition (`Adjust` shrink/expand and `Set` modes)."), + + # Masks + ToolMeta("EllipseMask", "Masks", "`mask`", "0.0%–0.2%", "Center, Width, Height, Angle, `SoftEdge`, `BorderWidth`, `Solid`, `Invert`, `PaintMode` chaining."), + ToolMeta("RectangleMask", "Masks", "`mask`", "0.0%–0.2%", "Center, Width, Height, `CornerRadius`, Angle, `SoftEdge`, `BorderWidth`, `Solid`, `Invert`, `PaintMode` chaining."), + ToolMeta("PolylineMask", "Masks", "Suite comps", "0.1%–0.5%", "CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, `SoftEdge`, `Invert`, `PaintMode`."), + ToolMeta("BitmapMask", "Masks", "Suite comps", "0.0%–0.2%", "Image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`), `Low`/`High` clip, `SoftEdge`, `Invert`."), + + # 3D Pipeline + ToolMeta("Renderer3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "GPU wgpu 3D rasterizer with depth buffer, perspective camera selection, lighting, and 2D texture sampling."), + ToolMeta("Camera3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "All 6 `RotOrder` permutations (`XYZ`..`ZYX`), `AoV`/`FLength`, `ApertureW`/`ApertureH`, `ResolutionGateFit` (`Inside`/`Outside`/`Width`/`Height`/`Stretch`)."), + ToolMeta("Merge3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "Hierarchical 3D scene graph combiner with local `Transform3DOp`."), + ToolMeta("Transform3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node."), + ToolMeta("ImagePlane3D", "3D Pipeline", "`cam3d`", "0.1%–0.4%", "Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture."), + ToolMeta("Shape3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "`Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry."), + ToolMeta("LightAmbient", "3D Pipeline", "Suite comps", "0.1%–0.4%", "Scene ambient RGB light intensity accumulation in `Renderer3D`."), + ToolMeta("LightDirectional", "3D Pipeline", "Suite comps", "0.1%–0.4%", "World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`."), + + # Time, Routing & Utility + ToolMeta("Saver", "Time, Routing & Utility", "All suites", "0.0%", "Output sink / passthrough in interactive Flow; target selector for `render-check` CLI."), + ToolMeta("TimeStretcher", "Time, Routing & Utility", "Suite comps", "0.0%", "Keyframed/expression `SourceTime` remapping upstream of evaluation (nearest/frame evaluation; Optical Flow tracked in [#4](" + SHALE_ISSUES_URL + "/4))."), + ToolMeta("TimeSpeed", "Time, Routing & Utility", "Suite comps", "0.0%", "Constant/animated `Speed` and `Delay` time remapping."), + ToolMeta("Switch", "Time, Routing & Utility", "Suite comps", "0.0%", "Dynamic input routing by `Which` index (`Input1`..`InputN`)."), + ToolMeta("Fuse.Switch", "Time, Routing & Utility", "Suite comps", "0.0%", "Fuse variant of `Switch` routing `Input1`..`InputN` by `Which`."), + ToolMeta("PipeRouter", "Time, Routing & Utility", "Suite comps", "0.0%", "Zero-cost graph routing node."), + ToolMeta("Fuse.Wireless", "Time, Routing & Utility", "Suite comps", "0.0%", "Wireless link passthrough node."), + ToolMeta("Tracker", "Time, Routing & Utility", "Suite comps", "0.0%", "Passthrough image node; baked tracking paths evaluated via `TrackerModifier`."), + ToolMeta("MacroOperator", "Time, Routing & Utility", "Suite comps", "0.0%", "Unpacks internal `Tools` subgraph and evaluates exported output seamlessly."), + ToolMeta("GroupOperator", "Time, Routing & Utility", "Suite comps", "0.0%", "Unpacks internal `Tools` subgraph and evaluates exported output seamlessly."), + ToolMeta("Custom", "Time, Routing & Utility", "Suite comps", "0.1%–0.6%", "Custom Tool shader evaluation (procedural wave/channel expressions + `UserControls` defaults)."), + ToolMeta("Note", "Time, Routing & Utility", "—", "N/A", "Non-rendering Flow sticky note; preserved losslessly on `.comp` roundtrip."), + ToolMeta("Underlay", "Time, Routing & Utility", "—", "N/A", "Non-rendering Flow backdrop/group box; preserved losslessly on `.comp` roundtrip."), +) + + +@dataclass(frozen=True) +class ModifierMeta: + display_name: str + classes: Tuple[str, ...] + probe: str + notes: str + + +MODIFIER_METADATA: Sequence[ModifierMeta] = ( + ModifierMeta("`BezierSpline`", ("BezierSpline",), "All suites", "Cubic Bezier / linear / `StepIn` / `StepOut` keyframes, animated `StyledText`, and animated `Polyline` point splines."), + ModifierMeta("`LUTBezier`", ("LUTBezier",), "`tier1_a`", "Curve lookup splines used standalone and nested inside `ColorCurves` / `HueCurves`."), + ModifierMeta("`PolyPath` / `Path`", ("PolyPath", "Path"), "Suite comps", "2D motion-path polyline evaluation with animated `Displacement` spline."), + ModifierMeta("`Shake`", ("Shake",), "`tier1_c`", "Procedural multi-octave noise modifier (`Source = X / Y / Value / Position`) with spline & expression inputs."), + ModifierMeta("`StyledTextCLS`", ("StyledTextCLS", "CharacterLevelStyling"), "Suite comps", "Per-character `TextPlus` styling overrides (font, size, color, kerning, opacity)."), + ModifierMeta("`TrackerModifier`", ("TrackerModifier",), "Suite comps", "Resolves baked tracker path aliases (`Track1TrackerPath`, etc.) into 2D `PolyPath` coordinates."), + ModifierMeta("Lua Expressions", (), "Suite comps", "Inline `Expression = \"...\"` evaluation (`time`, `comp.RenderStart`/`End`, node input references, math/trig/clamp/ternary)."), +) + + +@dataclass(frozen=True) +class UnsupportedMeta: + name: str + behavior: str + issue: Optional[int] = None + + +# Curated notes for prominent real-world unsupported / OFX / Resolve tools. +UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = ( + UnsupportedMeta("SurfaceTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), + UnsupportedMeta("MagicMask", "Preserved lossless on save; passes through main image input in Flow.", 7), + UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), + UnsupportedMeta("Fuse.Cryptomatte", "Preserved lossless on save; passes through main image input (multi-channel EXR matte extraction tracked).", 2), + UnsupportedMeta("Dimension.OpticalFlow", "Preserved lossless on save; passes through main image input (GPU dense optical flow tracked).", 4), + UnsupportedMeta("Dimension.CopyAux", "Preserved lossless on save; passes through main image input.", 4), + UnsupportedMeta("pEmitter", "Preserved lossless on save; skipped in 3D scene until particle simulator lands.", 3), + UnsupportedMeta("pRender", "Preserved lossless on save; skipped / passthrough until particle simulator lands.", 3), + UnsupportedMeta("pPointForce", "Preserved lossless on save; skipped in 3D scene until particle simulator lands.", 3), + UnsupportedMeta("SurfaceFBXMesh", "Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`.", None), + UnsupportedMeta("Text3D", "Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`.", None), + UnsupportedMeta("MtlBlinn", "Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending).", None), + UnsupportedMeta("MtlCookTorrance", "Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Cook-Torrance BRDF pending).", None), + UnsupportedMeta("WandMask", "Preserved lossless on save; flood-fill wand mask not yet implemented.", None), + UnsupportedMeta("ReplaceMaterial3D", "Preserved lossless on save; 3D material override not yet traversed in `Renderer3D`.", None), + UnsupportedMeta("Override3D", "Preserved lossless on save; 3D render-flag override not yet traversed in `Renderer3D`.", None), + UnsupportedMeta("Displace3D", "Preserved lossless on save; vertex displacement not yet implemented in `Renderer3D`.", None), +) + + +def parse_eval_rs(path: Path) -> Set[str]: + """Extract all supported tool class names from eval_node_inner in eval.rs.""" + text = path.read_text(encoding="utf-8") + m = re.search(r"fn eval_node_inner\b.*?(?=\n fn |\n\})", text, re.S) + if not m: + raise RuntimeError(f"Could not locate eval_node_inner in {path}") + body = m.group(0) + tools: Set[str] = set() + for mm in re.finditer(r"matches!\(node\.kind\.as_str\(\),\s*([^)]+)\)", body): + tools.update(re.findall(r'"([^"]+)"', mm.group(1))) + for mm in re.finditer(r'node\.kind\s*==\s*"([^"]+)"', body): + tools.add(mm.group(1)) + mm = re.search(r"match node\.kind\.as_str\(\)\s*\{(.*?)\n\s*other =>", body, re.S) + if not mm: + raise RuntimeError(f"Could not locate main match in eval_node_inner in {path}") + for line in mm.group(1).splitlines(): + if "=>" in line and not line.strip().startswith("//"): + lhs = line.split("=>", 1)[0] + tools.update(re.findall(r'"([^"]+)"', lhs)) + return tools + + +def parse_scene3d_rs(path: Path) -> Set[str]: + """Extract all supported 3D tool class names from collect_scene in scene3d.rs.""" + text = path.read_text(encoding="utf-8") + m = re.search(r"match node\.kind\.as_str\(\)\s*\{(.*?)\n _ => \{\}", text, re.S) + if not m: + raise RuntimeError(f"Could not locate collect_scene match in {path}") + tools: Set[str] = set() + for line in m.group(1).splitlines(): + if line.startswith(' "') and "=>" in line: + lhs = line.split("=>", 1)[0] + tools.update(re.findall(r'"([^"]+)"', lhs)) + return tools + + +def parse_comp_rs_modifiers(path: Path) -> Tuple[List[str], Set[str]]: + """Return (declared MODIFIER_TYPES, implemented modifier classes in parse_tools_table).""" + text = path.read_text(encoding="utf-8") + mc = re.search(r"const MODIFIER_TYPES:\s*&\[&str\]\s*=\s*&\[(.*?)\];", text, re.S) + declared = re.findall(r'"([^"]+)"', mc.group(1)) if mc else [] + declared_set = set(declared) + mp = re.search(r"fn parse_tools_table\b.*", text, re.S) + implemented: Set[str] = set() + if mp: + for mm in re.finditer(r'kind\s*==\s*"([^"]+)"', mp.group(0)): + if mm.group(1) in declared_set: + implemented.add(mm.group(1)) + return declared, implemented + + +def parse_probe_suites(path: Path) -> Set[str]: + """Extract registered probe suite names from scripts/fusion_probes.py.""" + if not path.exists(): + return set() + text = path.read_text(encoding="utf-8") + m = re.search(r"builders\s*=\s*\{(.*?)\}", text, re.S) + if not m: + return set() + return set(re.findall(r'"([^"]+)"\s*:', m.group(1))) + + +TOOLS_START_RE = re.compile(r"(?m)^\tTools\s*=\s*(?:ordered\(\)\s*)?\{") +TOP_TOOL_RE = re.compile( + r'^\t\t(?:\["[^"]+"\]|[A-Za-z_][A-Za-z0-9_]*)\s*=\s*([A-Za-z_][A-Za-z0-9_.]*)\s*\{' +) + + +def scan_comp_corpus(root: Path) -> Optional[Tuple[int, Counter[str]]]: + """Lightweight top-level tool-class scanner over all *.comp files under root.""" + if not root.exists(): + return None + counts: Counter[str] = Counter() + comp_files = sorted(root.rglob("*.comp")) + if not comp_files: + return None + for path in comp_files: + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + m = TOOLS_START_RE.search(text) + if not m: + continue + for line in text[m.end():].splitlines(): + if line.startswith("\t}"): + break + tm = TOP_TOOL_RE.match(line) + if tm: + counts[tm.group(1)] += 1 + return len(comp_files), counts + + +def format_usage( + names: Sequence[str], + active: Optional[Tuple[int, Counter[str]]], + archive: Optional[Tuple[int, Counter[str]]], +) -> str: + if active is None and archive is None: + return "—" + a_str = str(sum(active[1][n] for n in names)) if active is not None else "—" + b_str = str(sum(archive[1][n] for n in names)) if archive is not None else "—" + return f"{a_str} / {b_str}" + + +def format_coverage( + corpus: Optional[Tuple[int, Counter[str]]], + supported_classes: Set[str], + fallback_label: str, +) -> str: + if corpus is None: + return fallback_label + n_files, counts = corpus + total = sum(counts.values()) + if total == 0: + return f"0.0% (0 nodes across {n_files} comps)" + covered = sum(v for k, v in counts.items() if k in supported_classes) + pct = 100.0 * covered / total + return f"**{pct:.1f}%** ({covered:,} / {total:,} nodes across {n_files} `.comp` files)" + + +def build_markdown( + eval_tools: Set[str], + scene3d_tools: Set[str], + impl_modifiers: Set[str], + probe_suites: Set[str], + active_corpus: Optional[Tuple[int, Counter[str]]], + archive_corpus: Optional[Tuple[int, Counter[str]]], +) -> Tuple[str, List[str]]: + """Build compatibility.md text and return (markdown, warnings).""" + warnings: List[str] = [] + + # Validate probe suite names referenced in metadata + if probe_suites: + for meta in TOOL_METADATA: + for suite in re.findall(r"`([a-z0-9_]+)`", meta.probe): + if suite not in probe_suites: + warnings.append(f"Tool {meta.name} references unknown probe suite '{suite}'") + for mmeta in MODIFIER_METADATA: + for suite in re.findall(r"`([a-z0-9_]+)`", mmeta.probe): + if suite not in probe_suites: + warnings.append(f"Modifier {mmeta.display_name} references unknown probe suite '{suite}'") + + live_engine_tools = eval_tools | scene3d_tools + meta_by_name: Dict[str, ToolMeta] = {m.name: m for m in TOOL_METADATA} + non_render_tools = {"Note", "Underlay"} + + # Detect drift: tools in eval.rs / scene3d.rs not in TOOL_METADATA + uncategorized = sorted(live_engine_tools - set(meta_by_name.keys())) + for name in uncategorized: + warnings.append(f"Uncategorized tool found in engine source: {name}") + + # Detect stale metadata: tools in TOOL_METADATA no longer in engine source (excluding Note/Underlay) + stale = sorted((set(meta_by_name.keys()) - non_render_tools) - live_engine_tools) + for name in stale: + warnings.append(f"Stale tool in metadata not found in eval.rs/scene3d.rs: {name}") + + # Detect uncategorized modifiers + known_mod_classes: Set[str] = set() + for mm in MODIFIER_METADATA: + known_mod_classes.update(mm.classes) + uncategorized_mods = sorted(impl_modifiers - known_mod_classes) + for name in uncategorized_mods: + warnings.append(f"Uncategorized modifier found in comp.rs: {name}") + + all_supported_tools = live_engine_tools | non_render_tools + all_supported_classes = all_supported_tools | impl_modifiers + + lines: List[str] = [] + lines.append("# Fusion 21.1 Compatibility Matrix") + lines.append("") + lines.append( + "Auto-generated from live engine sources (`crates/engine/src/eval.rs`, " + "`crates/engine/src/scene3d.rs`, `crates/model/src/comp.rs`) and real Fusion `.comp` corpora " + "via `python3 scripts/gen_compatibility.py`." + ) + lines.append("") + lines.append( + f"- **Tracked Gaps & Issues:** [shale.paperclover.net/fission/issues]({SHALE_ISSUES_URL})\n" + f"- **Conformance Probes:** [`scripts/fusion_probes.py`](scripts/fusion_probes.py)" + ) + lines.append("") + + # Top summary table + lines.append("## Summary") + lines.append("") + lines.append("| Metric | Value |") + lines.append("| --- | --- |") + lines.append( + f"| **Supported Flow Tools** | **{len(all_supported_tools)}** " + f"({len(eval_tools)} 2D/Fuse/utility in `eval.rs`, {len(scene3d_tools - eval_tools)} 3D scene nodes in `scene3d.rs`, 2 Flow annotations) |" + ) + lines.append( + f"| **Modifiers & Animation** | **{len(MODIFIER_METADATA)}** systems " + f"({len(impl_modifiers)} Fusion modifier classes + Lua expressions) |" + ) + lines.append( + f"| **Active Corpus (`trees/fusion`) Coverage** | " + f"{format_coverage(active_corpus, all_supported_classes, '_Skipped (`/Volumes/Project/trees/fusion` not mounted)_')} |" + ) + lines.append( + f"| **Archive Corpus (`private/samples`) Coverage** | " + f"{format_coverage(archive_corpus, all_supported_classes, '_Skipped (`private/samples` not present)_')} |" + ) + lines.append( + "| **HiQ vs Fast Mode** | " + "**`HiQ`**: honors `DepthFull` / generator `Depth` / `ChangeDepth` (`Rgba8Unorm`, clamped `Rgba16Float`, unclamped HDR `Rgba16Float`/`Rgba32Float`), full-res blurs & `XGlow`. " + "**`Fast`**: collapses working targets to `Rgba8Unorm`, downsamples blurs, caps `XGlow` octaves for interactive scrubbing. |" + ) + lines.append("") + + usage_col = "Usage (Active / Archive)" + + # Categorized tool tables + for cat in CATEGORIES: + cat_tools = [m for m in TOOL_METADATA if m.category == cat and (m.name in live_engine_tools or m.name in non_render_tools)] + if not cat_tools: + continue + lines.append(f"## {cat}") + lines.append("") + lines.append(f"| Tool | Probe Suite | Verified MAE | {usage_col} | Notes & Fallbacks |") + lines.append("| --- | --- | --- | --- | --- |") + for m in cat_tools: + names = (m.name,) + m.aliases + usage = format_usage(names, active_corpus, archive_corpus) + lines.append(f"| `{m.name}` | {m.probe} | {m.mae} | {usage} | {m.notes} |") + lines.append("") + + # Drift-detection table if any new tools appeared in Rust sources + if uncategorized: + lines.append("## Uncategorized (New in Engine)") + lines.append("") + lines.append("> [!WARNING]") + lines.append("> The following tools were found in `eval.rs` / `scene3d.rs` but are not yet listed in `TOOL_METADATA` in `scripts/gen_compatibility.py`.") + lines.append("") + lines.append(f"| Tool | {usage_col} |") + lines.append("| --- | --- |") + for name in uncategorized: + usage = format_usage((name,), active_corpus, archive_corpus) + lines.append(f"| `{name}` | {usage} |") + lines.append("") + + # Modifiers & Animation table + lines.append("## Modifiers & Animation") + lines.append("") + lines.append(f"| Modifier / System | Probe Suite | {usage_col} | Notes |") + lines.append("| --- | --- | --- | --- |") + for mm in MODIFIER_METADATA: + usage = format_usage(mm.classes, active_corpus, archive_corpus) if mm.classes else "—" + lines.append(f"| {mm.display_name} | {mm.probe} | {usage} | {mm.notes} |") + for name in uncategorized_mods: + usage = format_usage((name,), active_corpus, archive_corpus) + lines.append(f"| `{name}` | — | {usage} | _Uncategorized modifier detected in `comp.rs`._ |") + lines.append("") + + # Preserved & Passthrough (Roundtrip-Safe) section + lines.append("## Preserved & Passthrough (Roundtrip-Safe)") + lines.append("") + lines.append( + "Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins when opening a `.comp` — " + "**Fission preserves all unknown and unsupported tools losslessly** (every parameter, custom input, binary blob, " + "position, and upstream/downstream wire is retained verbatim on save) and **passes through their main input** " + "during Flow evaluation so downstream compositing stays connected." + ) + lines.append("") + + # Combine curated unsupported list with any top real-world unsupported tools from corpora + curated_by_name = {u.name: u for u in UNSUPPORTED_NOTES} + combined_unsup: Counter[str] = Counter() + if active_corpus is not None: + for k, v in active_corpus[1].items(): + if k not in all_supported_classes: + combined_unsup[k] += v + if archive_corpus is not None: + for k, v in archive_corpus[1].items(): + if k not in all_supported_classes: + combined_unsup[k] += v + + # Order: curated items first (preserving logical grouping), then any remaining high-frequency unsupported tools + display_unsup: List[str] = [u.name for u in UNSUPPORTED_NOTES] + for k, _ in combined_unsup.most_common(25): + if k not in curated_by_name and len(display_unsup) < 24: + display_unsup.append(k) + + lines.append(f"| Tool Class | {usage_col} | Issue | Behavior & Notes |") + lines.append("| --- | --- | --- | --- |") + for name in display_unsup: + usage = format_usage((name,), active_corpus, archive_corpus) + meta = curated_by_name.get(name) + if meta is not None: + issue_str = f"[#{meta.issue}]({SHALE_ISSUES_URL}/{meta.issue})" if meta.issue else "—" + behavior = meta.behavior + else: + issue_str = "—" + behavior = "Preserved lossless on save; passes through main input in Flow." + lines.append(f"| `{name}` | {usage} | {issue_str} | {behavior} |") + lines.append("") + + lines.append("---") + lines.append("") + lines.append( + f"For tracked gaps, known parity edge cases, and roadmap items, see " + f"[shale.paperclover.net/fission/issues]({SHALE_ISSUES_URL})." + ) + lines.append("") + + return "\n".join(lines), warnings + + +def main() -> int: + parser = argparse.ArgumentParser(description="Generate compatibility.md from live engine sources.") + parser.add_argument("-o", "--output", type=Path, default=DEFAULT_OUTPUT, help="Output markdown path.") + parser.add_argument("--active-dir", type=Path, default=ACTIVE_CORPUS_DIR, help="Active Fusion .comp directory.") + parser.add_argument("--archive-dir", type=Path, default=ARCHIVE_CORPUS_DIR, help="Archive Fusion .comp directory.") + parser.add_argument("--strict", action="store_true", help="Exit non-zero if uncategorized or stale tools are found.") + args = parser.parse_args() + + eval_tools = parse_eval_rs(EVAL_RS) + scene3d_tools = parse_scene3d_rs(SCENE3D_RS) + _, impl_modifiers = parse_comp_rs_modifiers(COMP_RS) + probe_suites = parse_probe_suites(PROBES_PY) + + active_corpus = scan_comp_corpus(args.active_dir) + archive_corpus = scan_comp_corpus(args.archive_dir) + + md, warnings = build_markdown( + eval_tools=eval_tools, + scene3d_tools=scene3d_tools, + impl_modifiers=impl_modifiers, + probe_suites=probe_suites, + active_corpus=active_corpus, + archive_corpus=archive_corpus, + ) + + args.output.write_text(md, encoding="utf-8") + print(f"Wrote {args.output} ({len(md.splitlines())} lines)") + if active_corpus is not None: + print(f" Active corpus: {active_corpus[0]} comps, {sum(active_corpus[1].values()):,} entries") + else: + print(f" Active corpus: skipped ({args.active_dir} not found)") + if archive_corpus is not None: + print(f" Archive corpus: {archive_corpus[0]} comps, {sum(archive_corpus[1].values()):,} entries") + else: + print(f" Archive corpus: skipped ({args.archive_dir} not found)") + + for w in warnings: + print(f"WARNING: {w}", file=sys.stderr) + + if args.strict and warnings: + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())