Merge remote-tracking branch 'upstream/main' into docs/hardware-video-protocol

This commit is contained in:
nazar-gavrylyk committed 2026-11-24 19:41:21 +01:00
commit a0ef54fac1
102 files changed
+11502 -1281

No files matched your search

+7
View File
@@ -12,3 +12,10 @@ gpu = { max-threads = 1 }
[[profile.default.overrides]]
filter = 'package(effectcraft-gpu) | package(effectcraft-ui-egui) | package(effectcraft-sam2) | (package(effectcraft-cli) & test(/^cli::gpu_adapter_name_/))'
test-group = 'gpu'
# This sub-second test can stall indefinitely. Keep its assertions and surface the last
# flushed stage on timeout instead of waiting for the whole job to be cancelled.
[[profile.default.overrides]]
filter = 'binary_id(=effectcraft-export::it) & test(=roundtrip::prores_mov_roundtrip)'
slow-timeout = { period = "60s", terminate-after = 2, on-timeout = "fail" }
failure-output = "immediate"
+1
View File
@@ -54,3 +54,4 @@ jobs:
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+1
View File
@@ -162,3 +162,4 @@ under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Forks and
| Asset | Author | Source | Licence |
|---|---|---|---|
| `crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture` | Dylan M. Taylor | Original sine waves; reproducible recipe in `crates/media/tests/fixtures/README.md` | MIT OR Apache-2.0 |
| `crates/media/tests/fixtures/monochrome-av1.mkv` | Terra854 | Original grayscale ramps from `crates/media/tests/fixtures/generate-monochrome-av1.sh` | MIT OR Apache-2.0 |
Generated
+161 -216
View File
@@ -1182,11 +1182,11 @@ dependencies = [
[[package]]
name = "craft-aaf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)",
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-cfb",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"thiserror 2.0.21",
]
@@ -1207,45 +1207,20 @@ dependencies = [
[[package]]
name = "craft-audio"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"thiserror 2.0.21",
]
[[package]]
name = "craft-audio"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"log",
"rayon",
"symphonia 0.6.1",
"thiserror 2.0.21",
]
[[package]]
name = "craft-audio"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)",
"log",
"thiserror 2.0.21",
]
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93#7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93"
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
[[package]]
name = "craft-cms"
@@ -1264,7 +1239,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c
[[package]]
name = "craft-color"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"serde",
]
@@ -1291,7 +1266,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c
[[package]]
name = "craft-dpx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"thiserror 2.0.21",
]
@@ -1299,7 +1274,7 @@ dependencies = [
[[package]]
name = "craft-dpx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
dependencies = [
"thiserror 2.0.21",
]
@@ -1317,7 +1292,16 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae"
source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e"
[[package]]
name = "craft-exr"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"flate2",
"serde_json",
]
[[package]]
name = "craft-exr"
@@ -1339,10 +1323,10 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c
[[package]]
name = "craft-frame"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"craft-color",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"rayon",
"serde",
]
@@ -1350,12 +1334,20 @@ dependencies = [
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3"
dependencies = [
"gif",
"image",
]
[[package]]
name = "craft-hdr"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-i18n"
version = "0.1.0"
@@ -1382,7 +1374,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=937ac93c5cf3cd4b6a81e195b078fe161eb081b9#937ac93c5cf3cd4b6a81e195b078fe161eb081b9"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"thiserror 2.0.21",
]
@@ -1413,38 +1405,23 @@ source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9
[[package]]
name = "craft-media"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-media"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"chrono",
"thiserror 2.0.21",
]
[[package]]
name = "craft-media"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-media-source"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-color",
"craft-frame",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-y4m",
"serde",
"thiserror 2.0.21",
]
@@ -1482,7 +1459,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae"
source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e"
dependencies = [
"hayro-syntax",
"thiserror 2.0.21",
@@ -1491,7 +1468,7 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae"
source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e"
dependencies = [
"craft-eps",
"kurbo",
@@ -1504,7 +1481,18 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c#08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"encoding_rs",
"flate2",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189#53198114310dbc2b41e18e4eaf2fd83e69964189"
dependencies = [
"encoding_rs",
"flate2",
@@ -1526,7 +1514,7 @@ dependencies = [
[[package]]
name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"craft-tiff",
"miniz_oxide 0.9.1",
@@ -1537,6 +1525,11 @@ dependencies = [
"zune-jpeg",
]
[[package]]
name = "craft-sniff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
[[package]]
name = "craft-svg"
version = "0.1.0"
@@ -1555,7 +1548,7 @@ dependencies = [
[[package]]
name = "craft-tga"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"thiserror 2.0.21",
]
@@ -1563,7 +1556,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1581,25 +1574,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1616,22 +1591,14 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"serde",
"serde_json",
]
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d"
dependencies = [
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1694,20 +1661,9 @@ dependencies = [
[[package]]
name = "craft-video"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"rav1e",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "craft-video"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"rav1e",
"rayon",
"thiserror 2.0.21",
@@ -1722,6 +1678,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
@@ -1732,40 +1698,10 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-y4m"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=25c7a8959cf70cf8c3f076d05baadb0990710569#25c7a8959cf70cf8c3f076d05baadb0990710569"
source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d"
dependencies = [
"thiserror 2.0.21",
]
@@ -1993,7 +1929,7 @@ dependencies = [
[[package]]
name = "effectcraft"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"chrono",
"cpal",
@@ -2022,7 +1958,7 @@ dependencies = [
[[package]]
name = "effectcraft-aep"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-aep",
"craft-mime",
@@ -2039,7 +1975,7 @@ dependencies = [
[[package]]
name = "effectcraft-automation"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-jsonrpc",
"craft-mime",
@@ -2055,7 +1991,7 @@ dependencies = [
[[package]]
name = "effectcraft-cli"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"cpu-time",
"effectcraft-automation",
@@ -2074,7 +2010,7 @@ dependencies = [
[[package]]
name = "effectcraft-color"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"proptest",
"serde",
@@ -2082,7 +2018,7 @@ dependencies = [
[[package]]
name = "effectcraft-effects"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"chrono",
"craft-cms",
@@ -2101,7 +2037,7 @@ dependencies = [
[[package]]
name = "effectcraft-engine"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"chrono",
"craft-docpath",
@@ -2141,13 +2077,14 @@ dependencies = [
[[package]]
name = "effectcraft-export"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-exr",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"craft-gif",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-tga",
"craft-video",
"effectcraft-color",
"effectcraft-effects",
"effectcraft-keyframe",
@@ -2168,7 +2105,7 @@ dependencies = [
[[package]]
name = "effectcraft-expr"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"boa_engine",
"effectcraft-color",
@@ -2185,7 +2122,7 @@ dependencies = [
[[package]]
name = "effectcraft-geom"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"proptest",
"serde",
@@ -2193,7 +2130,7 @@ dependencies = [
[[package]]
name = "effectcraft-gpu"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"bytemuck",
"effectcraft-color",
@@ -2216,7 +2153,7 @@ dependencies = [
[[package]]
name = "effectcraft-helper-host"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"bytemuck",
"effectcraft-effects",
@@ -2227,7 +2164,7 @@ dependencies = [
[[package]]
name = "effectcraft-host"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-vectorcraft-format",
"effectcraft-engine",
@@ -2255,7 +2192,7 @@ dependencies = [
[[package]]
name = "effectcraft-interchange"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb)",
"effectcraft-color",
@@ -2275,7 +2212,7 @@ dependencies = [
[[package]]
name = "effectcraft-keyframe"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"effectcraft-color",
"effectcraft-geom",
@@ -2287,7 +2224,7 @@ dependencies = [
[[package]]
name = "effectcraft-lottie"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-docpath",
"craft-lottie",
@@ -2306,20 +2243,20 @@ dependencies = [
[[package]]
name = "effectcraft-media"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-color",
"craft-docpath",
"craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-exr",
"craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"craft-frame",
"craft-gif",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-media-source",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-video",
"craft-webp",
"effectcraft-color",
"effectcraft-effects",
@@ -2349,7 +2286,7 @@ dependencies = [
[[package]]
name = "effectcraft-model"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-mesh",
"effectcraft-geom",
@@ -2361,7 +2298,7 @@ dependencies = [
[[package]]
name = "effectcraft-path"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"effectcraft-geom",
"effectcraft-keyframe",
@@ -2374,7 +2311,7 @@ dependencies = [
[[package]]
name = "effectcraft-pdf"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-doc",
"craft-pdf",
@@ -2395,7 +2332,7 @@ dependencies = [
[[package]]
name = "effectcraft-plugin"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"effectcraft-effects",
"effectcraft-keyframe",
@@ -2407,7 +2344,7 @@ dependencies = [
[[package]]
name = "effectcraft-project"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-ecproj-format",
"effectcraft-color",
@@ -2421,17 +2358,18 @@ dependencies = [
[[package]]
name = "effectcraft-psd"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-psd",
"craft-codepage",
"craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189)",
"miniz_oxide 0.9.1",
]
[[package]]
name = "effectcraft-raster"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-exr",
"craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"effectcraft-color",
"effectcraft-geom",
"rayon",
@@ -2440,7 +2378,7 @@ dependencies = [
[[package]]
name = "effectcraft-render"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"effectcraft-color",
"effectcraft-effects",
@@ -2464,7 +2402,7 @@ dependencies = [
[[package]]
name = "effectcraft-sam2"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"bytemuck",
"candle-core",
@@ -2479,7 +2417,7 @@ dependencies = [
[[package]]
name = "effectcraft-script"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"boa_engine",
"effectcraft-engine",
@@ -2497,7 +2435,7 @@ dependencies = [
[[package]]
name = "effectcraft-segment"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"miniz_oxide 0.9.1",
"ndarray",
@@ -2506,7 +2444,7 @@ dependencies = [
[[package]]
name = "effectcraft-svg"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-svg",
"effectcraft-geom",
@@ -2520,7 +2458,7 @@ dependencies = [
[[package]]
name = "effectcraft-text"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"effectcraft-keyframe",
"harfrust",
@@ -2532,7 +2470,7 @@ dependencies = [
[[package]]
name = "effectcraft-time"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"proptest",
"serde",
@@ -2540,7 +2478,7 @@ dependencies = [
[[package]]
name = "effectcraft-track"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"craft-mime",
"effectcraft-raster",
@@ -2553,7 +2491,7 @@ dependencies = [
[[package]]
name = "effectcraft-ui-egui"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"bytemuck",
"chrono",
@@ -2596,7 +2534,7 @@ dependencies = [
[[package]]
name = "effectcraft-web"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"effectcraft-engine",
"effectcraft-export",
@@ -3017,28 +2955,28 @@ dependencies = [
[[package]]
name = "filmcraft-bitstream"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
]
[[package]]
name = "filmcraft-cfb"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93)",
"craft-cfb",
]
[[package]]
name = "filmcraft-codecs"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-jpeg",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-video",
"craft-y4m",
"filmcraft-bitstream",
"filmcraft-color",
@@ -3057,7 +2995,7 @@ dependencies = [
[[package]]
name = "filmcraft-color"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"serde",
]
@@ -3065,7 +3003,7 @@ dependencies = [
[[package]]
name = "filmcraft-dng"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-raw",
"craft-tiff",
@@ -3077,7 +3015,7 @@ dependencies = [
[[package]]
name = "filmcraft-frame"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"filmcraft-color",
"filmcraft-time",
@@ -3088,7 +3026,7 @@ dependencies = [
[[package]]
name = "filmcraft-geom"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"serde",
]
@@ -3096,17 +3034,18 @@ dependencies = [
[[package]]
name = "filmcraft-interchange"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-aaf",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"filmcraft-cfb",
"filmcraft-color",
"filmcraft-geom",
"filmcraft-media",
"filmcraft-project",
"filmcraft-time",
"roxmltree",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -3115,28 +3054,34 @@ dependencies = [
[[package]]
name = "filmcraft-isobmff"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
]
[[package]]
name = "filmcraft-matroska"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
]
[[package]]
name = "filmcraft-media"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-hdr",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-media-source",
"craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
"craft-sniff",
"craft-tga",
"craft-tiff",
"filmcraft-color",
"filmcraft-dng",
"filmcraft-frame",
@@ -3150,7 +3095,7 @@ dependencies = [
[[package]]
name = "filmcraft-project"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"filmcraft-color",
"filmcraft-geom",
@@ -3165,9 +3110,9 @@ dependencies = [
[[package]]
name = "filmcraft-time"
version = "0.20.1"
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b"
dependencies = [
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)",
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)",
]
[[package]]
@@ -3747,7 +3692,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae"
source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e"
dependencies = [
"hayro-ccitt",
]
@@ -3761,7 +3706,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae"
source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e"
dependencies = [
"hayro-jbig2",
"hayro-jpeg2000",
@@ -8697,7 +8642,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.24.1"
version = "0.25.1"
dependencies = [
"chrono",
"pkg-config",
+24 -22
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/*"]
[workspace.package]
version = "0.24.1"
version = "0.25.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -13,16 +13,18 @@ repository = "https://github.com/storytold/effectcraft"
[workspace.dependencies]
craft-timeline = { git = "https://github.com/storytold/craft-libs", rev = "0d6dd8bed815b8366869a800d2bf22588ca62dcb", default-features = false }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.1.0", default-features = false, features = ["read"] }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-jsonrpc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bc186ca719958fcce3b6ee24794277eabed14609" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] }
craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e", default-features = false, features = ["read"] }
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e" }
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c" }
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" }
craft-tga = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "53198114310dbc2b41e18e4eaf2fd83e69964189" }
craft-codepage = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
@@ -96,25 +98,25 @@ same-file = "1.0"
tempfile = "3.27"
# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all in sync.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", default-features = false, features = ["isobmff", "matroska"] }
craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false, features = ["isobmff", "matroska"] }
craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
# footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001).
# Only `crates/media`, `crates/export` and `crates/interchange` may depend on these.
filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" }
filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" }
filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" }
filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" }
filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" }
# timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only)
filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" }
filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" }
filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" }
# gpu (the same wgpu eframe / egui-wgpu use)
wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] }
@@ -230,8 +232,8 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.7.2" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.3.0" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e", version = "=0.7.2" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e", version = "=0.3.0" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+149 -5
View File
@@ -111,7 +111,9 @@ pub fn install_pickers(app: &mut EffectcraftApp, ctx: &egui::Context) -> Receive
let tx = Errors { tx, ctx: ctx.clone() };
let errors = tx.clone();
app.hooks.pick_files = Some(Box::new(move |exts: &[&str]| {
blocking(&errors, "Open", || rfd::FileDialog::new().add_filter("Media", exts).pick_files()).unwrap_or_default().into_iter().map(path_string).collect()
// No extensions (a script's File.openDialog without a filter): every file.
let dialog = || if exts.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter("Media", exts) };
blocking(&errors, "Open", || dialog().pick_files()).unwrap_or_default().into_iter().map(path_string).collect()
}));
let errors = tx.clone();
app.hooks.pick_save = Some(Box::new(move |name: &str| {
@@ -123,6 +125,12 @@ pub fn install_pickers(app: &mut EffectcraftApp, ctx: &egui::Context) -> Receive
}));
let errors = tx.clone();
app.hooks.pick_folder = Some(Box::new(move || blocking(&errors, "Choose Folder", || rfd::FileDialog::new().pick_folder()).map(path_string)));
let errors = tx.clone();
// Scripts' file dialogs where they block (Windows; see `install_file_dialogs` in main.rs).
app.hooks.pick_file_dialog = Some(Box::new(move |dialog: FileDialog| {
let what = title(&dialog);
blocking(&errors, what, || Some(pick_blocking(dialog))).unwrap_or_default()
}));
let errors = tx;
app.hooks.pick_save_file = Some(Box::new(move |name: &str, ext: &str| {
blocking(&errors, "Save", || {
@@ -170,9 +178,9 @@ pub fn show_asked(asked: &Receiver<Asked>, frame: &eframe::Frame, ctx: &egui::Co
/// The dialog's title, for errors.
fn title(dialog: &FileDialog) -> &'static str {
match dialog {
FileDialog::Open { .. } | FileDialog::OpenProject => "Open",
FileDialog::Folder => "Choose Folder",
FileDialog::Save { .. } => "Save",
FileDialog::Open { .. } | FileDialog::OpenProject | FileDialog::Script { .. } => "Open",
FileDialog::Folder | FileDialog::ScriptFolder { .. } => "Choose Folder",
FileDialog::Save { .. } | FileDialog::ScriptSave { .. } => "Save",
}
}
@@ -231,6 +239,101 @@ fn path(file: Option<FileHandle>) -> Vec<String> {
paths(file.map(|f| vec![f]))
}
/// The filters of a script's file dialog (#2778): its own, under the script's name for it (else
/// "Files"), then "All Files" when the script's filter offers every file. Without extensions, no
/// filter: every file. macOS takes all the filters' extensions together as the allowed types, so a
/// dialog that also offers every file gets no filter there.
macro_rules! script_filters {
($dialog:expr, $label:expr, $exts:expr, $any:expr) => {{
let (d, label, exts, any): (_, &str, &[String], bool) = ($dialog, $label, $exts, $any);
if exts.is_empty() || (any && cfg!(target_os = "macos")) {
d
} else {
let d = d.add_filter(if label.is_empty() { "Files" } else { label }, exts);
if any { d.add_filter("All Files", &["*"]) } else { d }
}
}};
}
/// The folder a script's dialog starts in: its `start` when that is a folder, else the folder
/// the file `start` names lives in; `None` when neither exists (the system's choice).
fn start_dir(start: &str) -> Option<std::path::PathBuf> {
if start.is_empty() {
return None;
}
let at = std::path::Path::new(start);
if at.is_dir() { Some(at.to_path_buf()) } else { at.parent().filter(|d| d.is_dir()).map(std::path::Path::to_path_buf) }
}
/// The filters of a script's save dialog: the script's own ([`script_filters!`]), else the
/// extension of the default name.
fn save_exts(exts: &[String], default: &str) -> Vec<String> {
if exts.is_empty() { std::path::Path::new(default).extension().map(|e| vec![e.to_string_lossy().to_string()]).unwrap_or_default() } else { exts.to_vec() }
}
/// A script's file dialog, blocking until it closes (`Hooks::pick_file_dialog`, Windows): its
/// paths, empty when cancelled. Runs inside [`guarded`] (see [`install_pickers`]).
fn pick_blocking(dialog: FileDialog) -> Vec<String> {
let all =
|files: Option<Vec<std::path::PathBuf>>| -> Vec<String> { files.unwrap_or_default().into_iter().map(|p| p.to_string_lossy().to_string()).collect() };
let one = |file: Option<std::path::PathBuf>| all(file.map(|f| vec![f]));
match dialog {
FileDialog::Script { label, exts, any, many, prompt, start } => {
let mut d = script_filters!(rfd::FileDialog::new(), &label, &exts, any);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&start) {
d = d.set_directory(dir);
}
if many { all(d.pick_files()) } else { one(d.pick_file()) }
}
FileDialog::ScriptFolder { prompt, start } => {
let mut d = rfd::FileDialog::new();
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&start) {
d = d.set_directory(dir);
}
one(d.pick_folder())
}
FileDialog::ScriptSave { default, prompt, label, exts, any } => {
let at = std::path::Path::new(&default);
let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let mut d = script_filters!(rfd::FileDialog::new(), &label, &save_exts(&exts, &default), any);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&default) {
d = d.set_directory(dir);
}
one(d.set_file_name(name).save_file())
}
FileDialog::Open { exts, many } => {
let d = if exts.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter("Media", &exts) };
if many { all(d.pick_files()) } else { one(d.pick_file()) }
}
FileDialog::OpenProject => one(rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file()),
FileDialog::Folder => one(rfd::FileDialog::new().pick_folder()),
FileDialog::Save { default, ext, project } => {
let at = std::path::Path::new(&default);
let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let mut d = if project {
rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"])
} else if ext.is_empty() {
rfd::FileDialog::new()
} else {
rfd::FileDialog::new().add_filter(&ext, &[ext.as_str()])
};
if let Some(dir) = at.parent().filter(|d| d.is_dir()) {
d = d.set_directory(dir);
}
one(d.set_file_name(name).save_file())
}
}
}
/// The dialog, as the blocking hooks show it. On macOS rfd makes the panel here, before the
/// future is returned, so a panel AppKit can't make panics here, inside [`guarded`].
///
@@ -242,7 +345,8 @@ fn path(file: Option<FileHandle>) -> Vec<String> {
fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer {
match dialog {
FileDialog::Open { exts, many } => {
let d = parented(frame).add_filter("Media", &exts);
// No extensions (a script's File.openDialog without a filter): every file.
let d = if exts.is_empty() { parented(frame) } else { parented(frame).add_filter("Media", &exts) };
if many {
let f = d.pick_files();
Box::pin(async move { paths(f.await) })
@@ -251,6 +355,46 @@ fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer {
Box::pin(async move { path(f.await) })
}
}
FileDialog::Script { label, exts, any, many, prompt, start } => {
let mut d = script_filters!(parented(frame), &label, &exts, any);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&start) {
d = d.set_directory(dir);
}
if many {
let f = d.pick_files();
Box::pin(async move { paths(f.await) })
} else {
let f = d.pick_file();
Box::pin(async move { path(f.await) })
}
}
FileDialog::ScriptFolder { prompt, start } => {
let mut d = parented(frame);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&start) {
d = d.set_directory(dir);
}
let f = d.pick_folder();
Box::pin(async move { path(f.await) })
}
FileDialog::ScriptSave { default, prompt, label, exts, any } => {
let at = std::path::Path::new(&default);
let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let mut d = script_filters!(parented(frame), &label, &save_exts(&exts, &default), any);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&default) {
d = d.set_directory(dir);
}
let f = d.set_file_name(name).save_file();
Box::pin(async move { path(f.await) })
}
FileDialog::OpenProject => {
let f = parented(frame).add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file();
Box::pin(async move { path(f.await) })
+3
View File
@@ -143,3 +143,6 @@ sync_github_name = true
real_name = "Nicola Falcier"
display_name = "Nicola Falcier"
sync_github_name = false
[people.Terra854]
display_name = "Terra854"
+2
View File
@@ -59,6 +59,8 @@ const REFUSED: &[&str] = &[
"scriptui.set",
"scriptui.mouse",
"scriptui.close",
// Hands a script the file it waits on, so its code goes on.
"scriptui.fileDialog",
"file.executeFile",
"effect.helpers.scan",
"effect.helpers.load",
+1
View File
@@ -1587,6 +1587,7 @@ fn automation_roots_refuse_running_script_code() {
("scriptui.set", json!({"window": 1, "widget": 2, "value": 1})),
("scriptui.mouse", json!({"window": 1, "widget": 2, "type": "click"})),
("scriptui.close", json!({"window": 1})),
("scriptui.fileDialog", json!({"host": 1, "paths": null})),
] {
let msg = refused(&mut s, "execute_command", json!({"command": command, "params": params}));
assert!(msg.contains("not available while file access is confined"), "`{command}`: {msg}");
+5 -5
View File
@@ -567,8 +567,8 @@ pub trait EffectHost: Sync {
}
/// Parameter `id` (a [`flatten_params`] id such as `birthRate`) of effect `effect_index` in
/// the layer's stack (the running effect's [`EffectEnv::effect_index`]) at another **layer
/// time**: Particle Emitter 3D samples its Birth Rate at every step it simulates (#1373).
/// `None` when unavailable.
/// time**: stepped particle systems sample their Birth Rate (#1373) and producer position
/// at every step they simulate. `None` when unavailable.
fn param_at(&self, _effect_index: usize, _id: &str, _layer_time: f64) -> Option<Value> {
None
}
@@ -1524,10 +1524,10 @@ pub fn is_time_dependent(id: &str) -> bool {
}
/// Does effect `id` read its own parameters at earlier times (the stepped particle systems sample
/// their Birth Rate at every step, #1373)? Caches keyed on the current values can't see what an
/// expression returned then.
/// their Birth Rate and producer position at every step, #1373)? Caches keyed on the current
/// values can't see what an expression returned then.
pub fn reads_param_history(id: &str) -> bool {
matches!(id, "ec.sim.ccparticleworld" | "ec.sim.ccparticlesystems2" | "ec.sim.ccmrmercury")
matches!(id, "ec.sim.ccparticleworld" | "ec.sim.ccparticlesystems2" | "ec.sim.ccmrmercury" | "ec.sim.particleplayground")
}
/// Run an effect on a buffer.
+34 -2
View File
@@ -13,7 +13,6 @@
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EngineDesc {
pub life: f32,
pub producer: [f32; 3],
pub radius: [f32; 3],
/// Animation (0 Explosive … 9 Fractal Uni).
pub anim: u32,
@@ -34,7 +33,6 @@ pub struct EngineDesc {
/// Particle Playground's Cannon with gravity only (see `sim3::Pg`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CannonDesc {
pub pos: [f32; 2],
pub barrel_angle: f32,
pub barrel_radius: f32,
pub dir_spread: f32,
@@ -61,6 +59,10 @@ pub struct SimRequest<'a> {
pub steps: u64,
/// Birth step of every particle id born before `steps` (ascending).
pub births: &'a [u32],
/// Producer position at the start of each simulated step, in the system's own coordinates:
/// entry `i` is the position used by particles born in step `i` and by the force centre
/// during step `i`.
pub producers: &'a [[f32; 3]],
pub system: ParticleSystem,
}
@@ -110,3 +112,33 @@ pub fn births_at(steps: u64, cap: usize, rate: impl Fn(u64) -> f64) -> Option<Ve
/// Steps per second of the stepped simulations.
pub const SPS: f64 = crate::sim::SPS;
/// Add one producer position to a rolling history fingerprint.
pub fn producer_hash_step(mut hash: u64, position: [f32; 3]) -> u64 {
for value in position {
hash = (hash ^ u64::from(value.to_bits())).wrapping_mul(0x0100_0000_01b3).rotate_left(5);
}
hash
}
/// Fingerprint of the first `steps` producer positions.
pub fn producer_hash(producers: &[[f32; 3]], steps: u64) -> u64 {
let count = usize::try_from(steps).unwrap_or(usize::MAX);
let mut hash = 0;
for position in producers.iter().take(count) {
hash = producer_hash_step(hash, *position);
}
hash
}
/// Rolling fingerprints of the producer history after each step (the empty prefix is zero).
pub fn producer_prefixes(producers: &[[f32; 3]]) -> Vec<u64> {
let mut out = Vec::with_capacity(producers.len().saturating_add(1));
out.push(0);
let mut hash = 0;
for position in producers {
hash = producer_hash_step(hash, *position);
out.push(hash);
}
out
}
+2 -2
View File
@@ -28,10 +28,10 @@ mod weather;
pub(crate) use common::{h, hs, pct, pt, spec};
pub use engine::particle_state;
#[cfg(test)]
use engine::{MERCURY, PS2, PW_EFFECT_CAMERA, Stepped, rate_history, sim_key, simulate_rates};
use engine::{MERCURY, PS2, PW, PW_EFFECT_CAMERA, Stepped, rate_history, sim_key, simulate_rates};
#[cfg(test)]
pub(crate) use engine::{PState, PW_ANIMS, Phys, simulate};
pub(crate) use engine::{SPS, steps_at};
pub(crate) use engine::{ProducerPath, SPS, steps_at};
pub(crate) use particle_fx::particle_world_textured;
pub use particle_fx::{Blob, mercury_blobs};
#[cfg(test)]
+137 -24
View File
@@ -15,6 +15,94 @@ pub(crate) fn steps_at(t: f64) -> u64 {
if t <= 0.0 { 0 } else { ((t * SPS + 1e-6).floor() as u64).min(crate::util::MAX_SIM_STEPS) }
}
/// The parameter path of a simulation producer and the coordinates its positions use.
#[derive(Clone, Copy, Debug)]
pub(crate) enum ProducerPath {
/// One point parameter. `by_height` converts layer pixels to the systems' height-relative units.
Point { id: &'static str, by_height: bool },
/// Three scalar parameters in world coordinates.
Components { x: &'static str, y: &'static str, z: &'static str },
}
impl ProducerPath {
fn raw_current(self, ctx: &EffectCtx) -> [f64; 3] {
match self {
Self::Point { id, .. } => {
let p = ctx.params.v2(id);
[p[0], p[1], 0.0]
}
Self::Components { x, y, z } => [ctx.params.f(x), ctx.params.f(y), ctx.params.f(z)],
}
}
fn convert(self, ctx: &EffectCtx, raw: [f64; 3]) -> [f32; 3] {
let unit = match self {
Self::Point { by_height: true, .. } => ctx.layer_size[1].max(1.0),
_ => 1.0,
};
let finite = |v: f64| if v.is_finite() { (v / unit) as f32 } else { 0.0 };
[finite(raw[0]), finite(raw[1]), finite(raw[2])]
}
/// The producer position at the start of every simulated step.
pub(crate) fn history(self, ctx: &EffectCtx) -> Vec<[f32; 3]> {
let steps = steps_at(ctx.time);
if steps == 0 {
return vec![];
}
let current_raw = self.raw_current(ctx).map(|v| if v.is_finite() { v } else { 0.0 });
let current = self.convert(ctx, current_raw);
let host = ctx.env.host;
let index = ctx.env.effect_index;
match self {
Self::Point { id, .. } => {
let dynamic = host.is_some_and(|h| !h.param_is_static(index, id));
if !dynamic {
return vec![current; steps as usize];
}
(0..steps)
.map(|i| {
let raw = host
.and_then(|h| h.param_at(index, id, i as f64 / SPS))
.map(|v| {
let p = v.as_vec2();
[p[0], p[1], 0.0]
})
.unwrap_or(current_raw);
self.convert(ctx, raw)
})
.collect()
}
Self::Components { x, y, z } => {
let static_x = host.is_some_and(|h| h.param_is_static(index, x));
let static_y = host.is_some_and(|h| h.param_is_static(index, y));
let static_z = host.is_some_and(|h| h.param_is_static(index, z));
(0..steps)
.map(|i| {
let time = i as f64 / SPS;
let value = |id: &str, now: f64, is_static: bool| {
if is_static {
now
} else {
host.and_then(|h| h.param_at(index, id, time)).map(|v| v.as_f64()).filter(|v| v.is_finite()).unwrap_or(now)
}
};
self.convert(ctx, [value(x, current_raw[0], static_x), value(y, current_raw[1], static_y), value(z, current_raw[2], static_z)])
})
.collect()
}
}
}
/// Parameter ids left out of the main cache key; their history is fingerprinted separately.
pub(crate) fn cache_skips(self) -> Vec<&'static str> {
match self {
Self::Point { id, .. } => vec![id],
Self::Components { x, y, z } => vec![x, y, z],
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct Particle {
pub p: [f32; 3],
@@ -34,6 +122,9 @@ pub(crate) struct PState {
/// The birth rates of the steps so far (see [`rates_hash`]): a checkpoint is only resumed
/// from with the same history.
pub hist: u64,
/// The producer positions of the steps so far: a checkpoint is only resumed from with the
/// same producer history.
pub producer_hist: u64,
}
/// `hist` after one more step at `rate` particles per second.
@@ -47,7 +138,6 @@ pub(crate) struct Phys {
/// Particles per second.
pub rate: f64,
pub life: f32,
pub producer: [f32; 3],
pub radius: [f32; 3],
pub anim: u32,
pub speed: f32,
@@ -82,14 +172,14 @@ fn rand_dir(i: u32, k: u32, seed: u32, flat: bool) -> [f32; 3] {
}
impl Phys {
fn spawn(&self, id: u32) -> Particle {
fn spawn(&self, id: u32, producer: [f32; 3]) -> Particle {
let seed = self.seed;
let mut p = [0.0f32; 3];
// Uniform in the producer ellipsoid.
let u = rand_dir(id, 1, seed, self.flat);
let rr = h(id, 3, seed).powf(if self.flat { 0.5 } else { 1.0 / 3.0 });
for k in 0..3 {
p[k] = self.producer[k] + u[k] * self.radius[k] * rr;
p[k] = producer[k] + u[k] * self.radius[k] * rr;
}
if self.flat {
p[2] = 0.0;
@@ -118,13 +208,13 @@ impl Phys {
/// One step at the constant [`Phys::rate`] (the tests' reference).
#[cfg(test)]
pub(crate) fn step(&self, st: &mut PState, step: u64) {
self.step_at_rate(st, step, self.rate);
pub(crate) fn step(&self, st: &mut PState, step: u64, producer: [f32; 3]) {
self.step_at_rate(st, step, self.rate, producer);
}
/// One step with `rate` particles per second born during it (rather than [`Phys::rate`]):
/// the rate only decides the births, particles already alive move and age as ever.
pub(crate) fn step_at_rate(&self, st: &mut PState, step: u64, rate: f64) {
pub(crate) fn step_at_rate(&self, st: &mut PState, step: u64, rate: f64, producer: [f32; 3]) {
let dt = (1.0 / SPS) as f32;
let t = step as f32 * dt;
let mut drag = self.resistance;
@@ -138,19 +228,19 @@ impl Phys {
match self.anim {
4 => {
// Twirly: swirl around the vertical axis through the producer.
let (dx, dz) = (q.p[0] - self.producer[0], q.p[2] - self.producer[2]);
let (dx, dz) = (q.p[0] - producer[0], q.p[2] - producer[2]);
let k = 4.0 * self.extra;
a[0] += -dz * k;
a[2] += dx * k;
if self.flat {
let dy = q.p[1] - self.producer[1];
let dy = q.p[1] - producer[1];
a[0] += -dy * k;
a[1] += dx * k;
}
}
5 => {
// Vortex: strong tangential + inward pull.
let (dx, dy) = (q.p[0] - self.producer[0], q.p[1] - self.producer[1]);
let (dx, dy) = (q.p[0] - producer[0], q.p[1] - producer[1]);
let k = 6.0 * self.extra;
a[0] += -dy * k - dx * 2.0;
a[1] += dx * k - dy * 2.0;
@@ -183,6 +273,7 @@ impl Phys {
});
st.parts.retain(|q| q.age < q.life);
st.hist = rates_hash(st.hist, rate);
st.producer_hist = crate::psim::producer_hash_step(st.producer_hist, producer);
st.carry += rate / SPS;
let n = st.carry.floor() as u32;
st.carry -= n as f64;
@@ -193,7 +284,7 @@ impl Phys {
let id = st.next_id;
st.next_id = st.next_id.wrapping_add(1);
// Sub-step birth offset keeps continuous streams smooth.
let mut q = self.spawn(id);
let mut q = self.spawn(id, producer);
let frac = h(id, 12, seed) * dt;
for k in 0..3 {
q.p[k] += q.v[k] * frac;
@@ -214,7 +305,6 @@ impl Phys {
let dt = (1.0 / SPS) as f32;
crate::psim::EngineDesc {
life: self.life,
producer: self.producer,
radius: self.radius,
anim: self.anim,
speed: self.speed,
@@ -232,20 +322,21 @@ impl Phys {
/// The state at layer time `ctx.time` from the host's particle backend (GPU particles), or
/// `None` (simulate on the CPU). `rates`: the birth rate of each step, when it changes over time
/// (else [`Phys::rate`]).
pub(super) fn accelerated(ctx: &EffectCtx, key: u64, phys: &Phys, rates: Option<&[f64]>) -> Option<std::sync::Arc<PState>> {
pub(super) fn accelerated(ctx: &EffectCtx, key: u64, phys: &Phys, rates: Option<&[f64]>, producers: &[[f32; 3]]) -> Option<std::sync::Arc<PState>> {
let backend = ctx.env.host?.particles()?;
let steps = steps_at(ctx.time);
let births = match rates {
Some(r) => crate::psim::births_at(steps, phys.max, |i| r.get(i as usize).copied().unwrap_or(0.0))?,
None => crate::psim::births(phys.rate, steps, phys.max)?,
};
let req = crate::psim::SimRequest { key, steps, births: &births, system: crate::psim::ParticleSystem::Engine(phys.desc()) };
let req = crate::psim::SimRequest { key, steps, births: &births, producers, system: crate::psim::ParticleSystem::Engine(phys.desc()) };
let parts = backend.simulate(&req)?;
Some(std::sync::Arc::new(PState {
parts: parts.into_iter().map(|q| Particle { p: q.p, v: q.v, age: q.age, life: q.life, rnd: q.rnd, id: q.id }).collect(),
carry: 0.0,
next_id: births.len() as u32,
hist: 0,
producer_hist: crate::psim::producer_hash(producers, steps),
}))
}
@@ -267,15 +358,23 @@ pub(super) fn rate_history(ctx: &EffectCtx, id: &str, k: f64) -> Vec<f64> {
/// Run a particle system through `rates` (one birth rate per step, see [`rate_history`]) with
/// `cache`, resuming only from checkpoints reached with the same rates.
pub(super) fn simulate_rates(cache: &SimCache<PState>, key: u64, phys: &Phys, rates: &[f64]) -> std::sync::Arc<PState> {
pub(super) fn simulate_rates(cache: &SimCache<PState>, key: u64, phys: &Phys, rates: &[f64], producers: &[[f32; 3]]) -> std::sync::Arc<PState> {
// `hist` of the state after each number of steps.
let mut prefix = Vec::with_capacity(rates.len() + 1);
prefix.push(0u64);
for r in rates {
prefix.push(rates_hash(prefix.last().copied().unwrap_or(0), *r));
}
let producer_prefix = crate::psim::producer_prefixes(producers);
let rate = |i: u64| rates.get(i as usize).copied().unwrap_or(0.0);
cache.run_where(key, rates.len() as u64, PState::default, |st, i| phys.step_at_rate(st, i, rate(i)), |s, st| prefix.get(s as usize) == Some(&st.hist))
let producer = |i: u64| producers.get(i as usize).copied().unwrap_or([0.0; 3]);
cache.run_where(
key,
rates.len() as u64,
PState::default,
|st, i| phys.step_at_rate(st, i, rate(i), producer(i)),
|s, st| prefix.get(s as usize) == Some(&st.hist) && producer_prefix.get(s as usize) == Some(&st.producer_hist),
)
}
/// A stepped particle system's particles at `ctx.time`, born at the Birth Rate of their own
@@ -286,6 +385,7 @@ pub(super) struct Stepped<'a> {
pub(super) cache: &'a SimCache<PState>,
pub(super) salt: u64,
pub(super) skip: &'a [&'a str],
pub(super) producer: ProducerPath,
pub(super) k: f64,
pub(super) gpu: bool,
}
@@ -293,20 +393,31 @@ pub(super) struct Stepped<'a> {
impl Stepped<'_> {
pub(super) fn state(&self, ctx: &EffectCtx, phys: &Phys) -> std::sync::Arc<PState> {
let rates = rate_history(ctx, "birthRate", self.k);
let producers = self.producer.history(ctx);
let mut skip = self.skip.to_vec();
skip.push("birthRate");
skip.extend(self.producer.cache_skips());
let key = params_key_except(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, self.salt, &skip);
let gpu = if self.gpu { accelerated(ctx, key, phys, Some(&rates)) } else { None };
gpu.unwrap_or_else(|| simulate_rates(self.cache, key, phys, &rates))
let gpu = if self.gpu { accelerated(ctx, key, phys, Some(&rates), &producers) } else { None };
gpu.unwrap_or_else(|| simulate_rates(self.cache, key, phys, &rates, &producers))
}
}
/// CC Particle World.
const PW: Stepped = Stepped { cache: &PW_CACHE, salt: 1, skip: &[PW_EFFECT_CAMERA], k: PW_RATE, gpu: true };
pub(super) const PW: Stepped = Stepped {
cache: &PW_CACHE,
salt: 1,
skip: &[PW_EFFECT_CAMERA],
producer: ProducerPath::Components { x: "producer/producerX", y: "producer/producerY", z: "producer/producerZ" },
k: PW_RATE,
gpu: true,
};
/// CC Particle Systems II.
pub(super) const PS2: Stepped = Stepped { cache: &PS2_CACHE, salt: 2, skip: &[], k: PS2_RATE, gpu: true };
pub(super) const PS2: Stepped =
Stepped { cache: &PS2_CACHE, salt: 2, skip: &[], producer: ProducerPath::Point { id: "producer/position", by_height: true }, k: PS2_RATE, gpu: true };
/// CC Mr. Mercury (its blobs are simulated on the CPU).
pub(super) const MERCURY: Stepped = Stepped { cache: &MERCURY_CACHE, salt: 3, skip: &[], k: MERCURY_RATE, gpu: false };
pub(super) const MERCURY: Stepped =
Stepped { cache: &MERCURY_CACHE, salt: 3, skip: &[], producer: ProducerPath::Point { id: "producer", by_height: true }, k: MERCURY_RATE, gpu: false };
/// CC Particle World's particles at `ctx.time`, born at the Birth Rate of their own time.
pub(super) fn pw_state(ctx: &EffectCtx, phys: &Phys) -> std::sync::Arc<PState> {
@@ -326,17 +437,19 @@ pub fn particle_state(id: &str, ctx: &EffectCtx) -> Option<Vec<crate::psim::SimP
}
/// The simulation cache key of a stepped particle effect at a constant Birth Rate (the tests'
/// reference): every parameter but CC Particle World's Effect Camera.
/// reference): every parameter but CC Particle World's Effect Camera, Birth Rate and producer.
#[cfg(test)]
pub(super) fn sim_key(ctx: &EffectCtx, salt: u64) -> u64 {
params_key_except(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, salt, &[PW_EFFECT_CAMERA])
let mut skip = vec![PW_EFFECT_CAMERA, "birthRate"];
skip.extend(PW.producer.cache_skips());
params_key_except(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, salt, &skip)
}
/// Run a particle system at its constant [`Phys::rate`] to layer time `t` through `cache` (the
/// tests' reference).
#[cfg(test)]
pub(crate) fn simulate(cache: &SimCache<PState>, key: u64, t: f64, phys: &Phys) -> std::sync::Arc<PState> {
cache.run(key, steps_at(t), PState::default, |st, i| phys.step(st, i))
pub(crate) fn simulate(cache: &SimCache<PState>, key: u64, t: f64, phys: &Phys, producer: [f32; 3]) -> std::sync::Arc<PState> {
cache.run(key, steps_at(t), PState::default, |st, i| phys.step(st, i, producer))
}
pub(crate) const PARTICLE_TYPES: &[&str] =
-5
View File
@@ -15,7 +15,6 @@ pub(super) fn pw_phys(ctx: &EffectCtx) -> Phys {
Phys {
rate: pr.f("birthRate").max(0.0) * PW_RATE,
life: pr.f("longevity").max(0.0) as f32,
producer: [pr.f("producer/producerX") as f32, pr.f("producer/producerY") as f32, pr.f("producer/producerZ") as f32],
radius: [pr.f("producer/radiusX").max(0.0) as f32, pr.f("producer/radiusY").max(0.0) as f32, pr.f("producer/radiusZ").max(0.0) as f32],
anim: pr.e("physics/animation"),
speed: pr.f("physics/velocity") as f32 * 0.5,
@@ -251,12 +250,10 @@ pub(super) fn ps2_phys(ctx: &EffectCtx) -> Phys {
let pr = ctx.params;
let lh = ctx.layer_size[1] as f32;
let unit = lh.max(1.0);
let pos = pr.v2("producer/position");
let dir = (pr.f("physics/direction") as f32).to_radians();
Phys {
rate: pr.f("birthRate").max(0.0) * PS2_RATE,
life: pr.f("longevity").max(0.0) as f32,
producer: [pos[0] as f32 / unit, pos[1] as f32 / unit, 0.0],
radius: [pr.f("producer/radiusX").max(0.0) as f32 / unit, pr.f("producer/radiusY").max(0.0) as f32 / unit, 0.0],
anim: [0u32, 1, 2, 3, 4, 5, 6, 7, 8, 9][pr.e("physics/animation").min(9) as usize],
speed: pr.f("physics/velocity") as f32 * 0.25,
@@ -321,12 +318,10 @@ pub struct Blob {
pub(super) fn mercury_phys(ctx: &EffectCtx) -> Phys {
let pr = ctx.params;
let unit = (ctx.layer_size[1] as f32).max(1.0);
let pos = pr.v2("producer");
let dir = (pr.f("direction") as f32).to_radians();
Phys {
rate: pr.f("birthRate").max(0.0) * MERCURY_RATE,
life: pr.f("longevity").max(0.0) as f32,
producer: [pos[0] as f32 / unit, pos[1] as f32 / unit, 0.0],
radius: [pr.f("radiusX").max(0.0) as f32 / unit, pr.f("radiusY").max(0.0) as f32 / unit, 0.0],
anim: [0u32, 1, 2, 3, 4, 5, 6, 7, 8, 9][pr.e("animation").min(9) as usize],
speed: pr.f("velocity") as f32 * 0.3,
+171 -11
View File
@@ -227,7 +227,6 @@ fn engine_resume_equals_from_scratch() {
let phys = Phys {
rate: 90.0,
life: 1.5,
producer: [0.0; 3],
radius: [0.05; 3],
anim,
speed: 0.5,
@@ -242,10 +241,10 @@ fn engine_resume_equals_from_scratch() {
};
let a: SimCache<PState> = SimCache::new(2);
let b: SimCache<PState> = SimCache::new(2);
let direct = simulate(&a, 1, 2.0, &phys);
let _ = simulate(&b, 1, 1.0, &phys);
let _ = simulate(&b, 1, 0.37, &phys);
let resumed = simulate(&b, 1, 2.0, &phys);
let direct = simulate(&a, 1, 2.0, &phys, [0.0; 3]);
let _ = simulate(&b, 1, 1.0, &phys, [0.0; 3]);
let _ = simulate(&b, 1, 0.37, &phys, [0.0; 3]);
let resumed = simulate(&b, 1, 2.0, &phys, [0.0; 3]);
assert_eq!(direct.parts.len(), resumed.parts.len(), "anim {anim}");
assert!(direct.parts.iter().zip(&resumed.parts).all(|(p, q)| p.p == q.p && p.v == q.v && p.id == q.id), "anim {anim}");
assert!(!direct.parts.is_empty());
@@ -566,6 +565,34 @@ fn half_resolution_scales_sprites() {
// ---------------------------------------------------------- Birth Rate over time (#1373)
/// A host whose producer moves from `start_x` at layer time 0 to `start_x + 60 · t`.
struct MovingProducer {
index: usize,
start_x: f64,
}
impl crate::EffectHost for MovingProducer {
fn layer(&self, _: u64, _: bool) -> Option<crate::LayerPixels> {
None
}
fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option<Vec<f32>> {
None
}
fn param_at(&self, effect_index: usize, id: &str, t: f64) -> Option<Value> {
if effect_index != self.index {
return None;
}
let x = self.start_x + 60.0 * t;
match id {
"producer/position" | "producer" => Some(Value::Vec2([x, 50.0])),
"producer/producerX" => Some(num(x)),
"producer/producerY" => Some(num(50.0)),
"producer/producerZ" => Some(num(0.0)),
_ => None,
}
}
}
/// A host that evaluates effect `index`'s Birth Rate at other layer times as `rate(t)`.
struct Rate {
index: usize,
@@ -624,8 +651,13 @@ fn pw_at(seed: f64, now: f64, t: f64, host: Option<&Rate>) -> Vec<crate::psim::S
fn pw_fresh(seed: f64, now: f64, t: f64, host: &Rate) -> Vec<crate::psim::SimParticle> {
let p = pw_params(seed, now);
let ctx = pw_ctx(&p, t, Some(host), host.index);
let key = params_key_except(&ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 1, &[PW_EFFECT_CAMERA, "birthRate"]);
let st = simulate_rates(&SimCache::new(1), key, &pw_phys(&ctx), &rate_history(&ctx, "birthRate", PW_RATE));
let rates = rate_history(&ctx, "birthRate", PW_RATE);
let producers = PW.producer.history(&ctx);
let mut skip = PW.skip.to_vec();
skip.push("birthRate");
skip.extend(PW.producer.cache_skips());
let key = params_key_except(&ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 1, &skip);
let st = simulate_rates(&SimCache::new(1), key, &pw_phys(&ctx), &rates, &producers);
st.parts.iter().map(|q| crate::psim::SimParticle { p: q.p, v: q.v, age: q.age, life: q.life, rnd: q.rnd, id: q.id }).collect()
}
@@ -699,7 +731,7 @@ fn a_constant_birth_rate_is_unchanged() {
let p = pw_params(105.0, 2.0);
let ctx = pw_ctx(&p, 1.3, None, 0);
let phys = pw_phys(&ctx);
let before = simulate(&SimCache::new(1), sim_key(&ctx, 1), 1.3, &phys);
let before = simulate(&SimCache::new(1), sim_key(&ctx, 1), 1.3, &phys, [0.0; 3]);
let now = pw_at(105.0, 2.0, 1.3, Some(&host));
assert_eq!(now.len(), before.parts.len());
assert!(now.iter().zip(&before.parts).all(|(a, b)| a.id == b.id && a.p == b.p && a.v == b.v && a.age == b.age));
@@ -714,7 +746,8 @@ fn the_birth_schedule_follows_the_rate_history() {
let p = pw_params(106.0, 0.0);
let ctx = pw_ctx(&p, 0.7, Some(&host), 0);
let rates = rate_history(&ctx, "birthRate", PW_RATE);
let st = simulate_rates(&SimCache::new(1), 9, &pw_phys(&ctx), &rates);
let producers = PW.producer.history(&ctx);
let st = simulate_rates(&SimCache::new(1), 9, &pw_phys(&ctx), &rates, &producers);
let births = crate::psim::births_at(rates.len() as u64, 40_000, |i| rates[i as usize]).unwrap();
assert_eq!(st.next_id as usize, births.len());
assert!(births.iter().all(|&b| f64::from(b) / SPS < 0.5), "nothing born once the ramp reaches 0");
@@ -762,8 +795,11 @@ fn sys_fresh(sys: &System, seed: u32, now: f64, t: f64, host: &Rate) -> Vec<(u32
let ctx = sys_ctx(&p, t, Some(host), seed);
let mut skip = sys.stepped.skip.to_vec();
skip.push("birthRate");
skip.extend(sys.stepped.producer.cache_skips());
let key = params_key_except(&ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, sys.stepped.salt, &skip);
let st = simulate_rates(&SimCache::new(1), key, &(sys.phys)(&ctx), &rate_history(&ctx, "birthRate", sys.stepped.k));
let rates = rate_history(&ctx, "birthRate", sys.stepped.k);
let producers = sys.stepped.producer.history(&ctx);
let st = simulate_rates(&SimCache::new(1), key, &(sys.phys)(&ctx), &rates, &producers);
st.parts.iter().map(|q| (q.id, q.p, q.age)).collect()
}
@@ -819,10 +855,134 @@ fn particle_systems_ii_and_mr_mercury_are_unchanged_at_a_constant_rate() {
for sys in &SYSTEMS {
let p = sys_params(sys.id, 2.0);
let ctx = sys_ctx(&p, 1.3, None, 203);
let before = simulate(&SimCache::new(1), 1, 1.3, &(sys.phys)(&ctx));
let producers = sys.stepped.producer.history(&ctx);
let producer = producers.last().copied().unwrap_or([0.0; 3]);
let before = simulate(&SimCache::new(1), 1, 1.3, &(sys.phys)(&ctx), producer);
let before: Vec<_> = before.parts.iter().map(|q| (q.id, q.p, q.age)).collect();
assert!(!before.is_empty());
assert_eq!(sys_at(sys, 203, 2.0, 1.3, Some(&host)), before, "{}: keyed to a constant", sys.id);
assert_eq!(sys_at(sys, 203, 2.0, 1.3, None), before, "{}: no host", sys.id);
}
}
/// #1955: a particle is born where its producer was during that step, not where the producer
/// is when the frame is rendered.
#[test]
fn stepped_particles_are_born_at_their_producer_positions() {
let cases: [(&str, &Stepped<'static>, fn(&EffectCtx) -> Phys); 3] =
[("ec.sim.ccparticleworld", &PW, pw_phys), ("ec.sim.ccparticlesystems2", &PS2, ps2_phys), ("ec.sim.ccmrmercury", &MERCURY, mercury_phys)];
for (id, stepped, phys_fn) in cases {
let mut p = sys_params(id, 1.0);
p.values.insert("longevity".into(), num(5.0));
for (key, value) in [
("producer/radiusX", num(0.0)),
("producer/radiusY", num(0.0)),
("producer/radiusZ", num(0.0)),
("radiusX", num(0.0)),
("radiusY", num(0.0)),
("physics/velocity", num(0.0)),
("physics/gravity", num(0.0)),
("gravity", num(0.0)),
("velocity", num(0.0)),
] {
if p.values.contains_key(key) {
p.values.insert(key.into(), value);
}
}
match id {
"ec.sim.ccparticleworld" => {
p.values.insert("producer/producerX".into(), num(80.0));
p.values.insert("producer/producerY".into(), num(50.0));
p.values.insert("producer/producerZ".into(), num(0.0));
}
"ec.sim.ccparticlesystems2" => {
p.values.insert("producer/position".into(), pt(80.0, 50.0));
}
"ec.sim.ccmrmercury" => {
p.values.insert("producer".into(), pt(80.0, 50.0));
}
_ => {}
}
let host = MovingProducer { index: 0, start_x: 20.0 };
let env = EffectEnv { host: Some(&host), effect_index: 0, ..Default::default() };
let ctx = EffectCtx { params: &p, time: 1.0, layer_size: [100.0, 100.0], seed: 301, adjustment: false, env };
let phys = phys_fn(&ctx);
let state = stepped.state(&ctx, &phys);
let births = crate::psim::births_at(steps_at(ctx.time), 40_000, |_| phys.rate).unwrap();
assert!(!state.parts.is_empty(), "{id}: particles born");
for q in &state.parts {
let birth = births[q.id as usize] as f32;
// The producer moves 60 units per second. Particle Emitter 3D uses world units;
// the 2D systems use layer-height-relative units in this 100-pixel-high layer.
let want = if id == "ec.sim.ccparticleworld" { [20.0 + birth, 50.0, 0.0] } else { [(20.0 + birth) / 100.0, 0.5, 0.0] };
let distance = (0..3).map(|k| (q.p[k] - want[k]).abs()).fold(0.0f32, f32::max);
assert!(distance < 1e-5, "{id}: particle {} born at {want:?}, not {:?}", q.id, q.p);
}
}
}
/// A producer's current position stays out of the simulation key even in production-shaped
/// parameters, where it has both a canonical id and a positional alias.
#[test]
fn current_producer_positions_do_not_change_stepped_simulation_keys() {
use effectcraft_project::build::Ids;
let cases: [(&str, &Stepped<'static>, &[(&str, &str, Value)], (&str, Value)); 3] = [
(
"ec.sim.ccparticleworld",
&PW,
&[
("producer/producerX", "#1/producerX", num(80.0)),
("producer/producerY", "#1/producerY", num(50.0)),
("producer/producerZ", "#1/producerZ", num(0.0)),
],
("longevity", num(2.0)),
),
("ec.sim.ccparticlesystems2", &PS2, &[("producer/position", "#1/position", pt(80.0, 50.0))], ("longevity", num(2.0))),
("ec.sim.ccmrmercury", &MERCURY, &[("producer", "producer", pt(80.0, 50.0))], ("radiusX", num(2.0))),
];
for (id, stepped, producers, (other, other_value)) in cases {
let spec = crate::find(id).unwrap();
let mut next = 1;
let group = crate::instantiate(spec, &mut Ids(&mut next), spec.name, [100.0, 100.0]);
let mut p = crate::flatten_params(&group, &mut |pr| pr.value.clone());
let key = |p: &crate::Params| {
let ctx = EffectCtx { params: p, time: 1.0, layer_size: [100.0, 100.0], seed: 303, adjustment: false, env: EffectEnv::default() };
let mut skip = stepped.skip.to_vec();
skip.push("birthRate");
skip.extend(stepped.producer.cache_skips());
params_key_except(&ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, stepped.salt, &skip)
};
let before = key(&p);
for (canonical, alias, value) in producers {
assert!(p.values.contains_key(*canonical), "{id}: {canonical}");
assert!(p.values.contains_key(*alias), "{id}: {alias}");
p.values.insert((*canonical).into(), (*value).clone());
p.values.insert((*alias).into(), (*value).clone());
}
assert_eq!(key(&p), before, "{id}: the current producer position changed the key");
p.values.insert(other.into(), other_value);
assert_ne!(key(&p), before, "{id}: another parameter still changes the key");
}
}
/// The producer's current value is not part of the simulation key, but an earlier producer
/// value is: a checkpoint reached with another producer history is not reused.
#[test]
fn a_changed_producer_history_drops_stale_checkpoints() {
let state = |start_x| {
let mut p = sys_params("ec.sim.ccparticlesystems2", 1.0);
p.values.insert("longevity".into(), num(5.0));
p.values.insert("producer/position".into(), pt(80.0, 50.0));
p.values.insert("producer/radiusX".into(), num(0.0));
p.values.insert("producer/radiusY".into(), num(0.0));
p.values.insert("physics/velocity".into(), num(0.0));
p.values.insert("physics/gravity".into(), num(0.0));
let host = MovingProducer { index: 0, start_x };
let env = EffectEnv { host: Some(&host), effect_index: 0, ..Default::default() };
let ctx = EffectCtx { params: &p, time: 1.0, layer_size: [100.0, 100.0], seed: 302, adjustment: false, env };
let phys = ps2_phys(&ctx);
PS2.state(&ctx, &phys).parts.first().map(|q| q.p).unwrap()
};
assert!((state(20.0)[0] - 0.2).abs() < 1e-5, "{:?}", state(20.0));
assert!((state(60.0)[0] - 0.6).abs() < 1e-5, "{:?}", state(60.0));
}
+80 -27
View File
@@ -27,8 +27,8 @@ use effectcraft_project::ParamUi;
use effectcraft_raster::{Image, Px};
use rayon::prelude::*;
use crate::sim::{Acc, Post, SPS, Shape, Sprite, SpritePlan, Tint, combine, splat, steps_at};
use crate::util::{SimCache, hash1, params_key, point_in_poly, unpremul};
use crate::sim::{Acc, Post, ProducerPath, SPS, Shape, Sprite, SpritePlan, Tint, combine, splat, steps_at};
use crate::util::{SimCache, hash1, params_key_except, point_in_poly, unpremul};
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
@@ -108,6 +108,8 @@ pub struct PgState {
pub parts: Vec<PgParticle>,
carry: f64,
next_id: u32,
/// Fingerprint of the producer positions of the steps so far.
producer_hist: u64,
}
/// A map layer sampled in layer coordinates.
@@ -346,7 +348,6 @@ impl Mapper {
struct Pg {
// Cannon
cannon: bool,
pos: [f32; 2],
barrel_angle: f32,
barrel_radius: f32,
rate: f64,
@@ -380,7 +381,8 @@ struct Pg {
}
impl Pg {
fn spawn(&self, id: u32) -> PgParticle {
/// Spawn a cannon particle at `producer` (the cannon's position during its birth step).
fn spawn_at(&self, id: u32, producer: [f32; 2]) -> PgParticle {
let s = self.seed;
let h = |k: u32| hash1(id, k, s) * 2.0 - 1.0;
// AE angles: 0° = up, clockwise.
@@ -395,7 +397,7 @@ impl Pg {
let (a, rr) = (hash1(id, 5, s) * std::f32::consts::TAU, hash1(id, 6, s).sqrt() * -r);
[a.cos() * rr, a.sin() * rr]
};
let p = [self.pos[0] + off[0], self.pos[1] + off[1]];
let p = [producer[0] + off[0], producer[1] + off[1]];
let mut q = PgParticle::new(p, [d[0] * speed, d[1] * speed], self.color, self.radius, id, SRC_CANNON);
if !self.cannon_text.is_empty() {
q.ch = self.cannon_text[id as usize % self.cannon_text.len()] as u32;
@@ -403,6 +405,12 @@ impl Pg {
q
}
/// Spawn a cannon particle at the origin (the tests' reference).
#[cfg(test)]
fn spawn(&self, id: u32) -> PgParticle {
self.spawn_at(id, [0.0; 2])
}
/// The particle as the ephemeral mapper sees it this step (unchanged without one).
fn ephemeral(&self, q: &PgParticle) -> PgParticle {
let mut e = *q;
@@ -412,7 +420,8 @@ impl Pg {
e
}
fn step(&self, st: &mut PgState) {
/// Advance the simulation one step, using `producer` for particles born in that step.
fn step_at(&self, st: &mut PgState, producer: [f32; 2]) {
let dt = (1.0 / SPS) as f32;
let s = self.seed;
// Persistent Property Mapper: the mapped values stay with the particle.
@@ -534,18 +543,36 @@ impl Pg {
}
let id = st.next_id;
st.next_id = st.next_id.wrapping_add(1);
let mut q = self.spawn(id);
let mut q = self.spawn_at(id, producer);
// Sub-step birth offset keeps streams smooth.
let frac = hash1(id, 9, s) * dt;
q.p = [q.p[0] + q.v[0] * frac, q.p[1] + q.v[1] * frac];
st.parts.push(q);
}
}
st.producer_hist = crate::psim::producer_hash_step(st.producer_hist, [producer[0], producer[1], 0.0]);
}
/// Advance one step with the origin as its producer (the tests' reference).
#[cfg(test)]
fn step(&self, st: &mut PgState) {
self.step_at(st, [0.0; 2]);
}
}
static PG_CACHE: SimCache<PgState> = SimCache::new(6);
/// The cannon's position history is sampled in layer pixels, not in the shared systems'
/// height-relative coordinates.
const PG_PRODUCER: ProducerPath = ProducerPath::Point { id: "cannon/cannonPosition", by_height: false };
/// The simulation key without the cannon's current position: its history is fingerprinted
/// separately, so moving the cannon does not make every simulation restart.
fn pg_key(ctx: &EffectCtx) -> u64 {
let skip = PG_PRODUCER.cache_skips();
params_key_except(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 0x7067, &skip)
}
fn image_key(img: &Image) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
@@ -615,7 +642,6 @@ fn pg_of(ctx: &EffectCtx) -> Pg {
let ephemeral = mapper_from(ctx, "ephemeralPropertyMapper", true);
Pg {
cannon: pr.b("cannonEnabled"),
pos: { pr.v2("cannon/cannonPosition").map(|v| v as f32) },
barrel_angle: pr.f("cannon/barrelAngle") as f32,
barrel_radius: pr.f("cannon/barrelRadius") as f32,
rate: pr.f("cannon/particlesPerSecond").max(0.0),
@@ -665,12 +691,14 @@ impl Affects {
}
/// Particle Playground cannons with gravity only, simulated by the host's particle backend.
fn pg_accelerated(ctx: &EffectCtx, key: u64, pg: &Pg) -> Option<std::sync::Arc<PgState>> {
fn pg_accelerated(ctx: &EffectCtx, key: u64, pg: &Pg, producers: &[[f32; 3]]) -> Option<std::sync::Arc<PgState>> {
let backend = ctx.env.host?.particles()?;
let steps = steps_at(ctx.time);
if producers.len() < usize::try_from(steps).ok()? {
return None;
}
let births = crate::psim::births(pg.rate, steps, 60_000)?;
let desc = crate::psim::CannonDesc {
pos: pg.pos,
barrel_angle: pg.barrel_angle,
barrel_radius: pg.barrel_radius,
dir_spread: pg.dir_spread,
@@ -681,19 +709,22 @@ fn pg_accelerated(ctx: &EffectCtx, key: u64, pg: &Pg) -> Option<std::sync::Arc<P
seed: pg.seed,
bounds: pg.bounds,
};
let req = crate::psim::SimRequest { key, steps, births: &births, system: crate::psim::ParticleSystem::Cannon(desc) };
let req = crate::psim::SimRequest { key, steps, births: &births, producers, system: crate::psim::ParticleSystem::Cannon(desc) };
let parts = backend.simulate(&req)?;
Some(std::sync::Arc::new(PgState {
parts: parts
.into_iter()
.map(|q| {
let born = pg.spawn(q.id);
PgParticle { p: [q.p[0], q.p[1]], v: [q.v[0], q.v[1]], ..born }
})
.collect(),
carry: 0.0,
next_id: births.len() as u32,
}))
let parts = parts
.into_iter()
.map(|q| {
let birth = *births.get(q.id as usize)?;
let producer = *producers.get(birth as usize)?;
// The GPU returns the particle's actual position; use its birth step for the
// particle's birth metadata (origin, colour, radius and text).
let mut born = pg.spawn_at(q.id, [producer[0], producer[1]]);
born.p = [q.p[0], q.p[1]];
born.v = [q.v[0], q.v[1]];
Some(born)
})
.collect::<Option<Vec<_>>>()?;
Some(std::sync::Arc::new(PgState { parts, carry: 0.0, next_id: births.len() as u32, producer_hist: crate::psim::producer_hash(producers, steps) }))
}
/// The live particles of a Particle Playground whose cannon is the only producer and force
@@ -707,8 +738,19 @@ pub fn playground_state(ctx: &EffectCtx) -> Option<Vec<crate::psim::SimParticle>
if !pg.cannon_only() || grid || exploder {
return None;
}
let key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 0x7067);
let st = pg_accelerated(ctx, key, &pg).unwrap_or_else(|| PG_CACHE.run(key, steps_at(ctx.time), PgState::default, |st, _| pg.step(st)));
let producers = PG_PRODUCER.history(ctx);
let producer_prefix = crate::psim::producer_prefixes(&producers);
let key = pg_key(ctx);
let producer = |i: u64| producers.get(i as usize).map(|p| [p[0], p[1]]).unwrap_or([0.0; 2]);
let st = pg_accelerated(ctx, key, &pg, &producers).unwrap_or_else(|| {
PG_CACHE.run_where(
key,
steps_at(ctx.time),
PgState::default,
|st, i| pg.step_at(st, producer(i)),
|s, st| producer_prefix.get(s as usize) == Some(&st.producer_hist),
)
});
Some(
st.parts
.iter()
@@ -748,7 +790,7 @@ pub fn playground_plan(ctx: &EffectCtx, b: &Buf) -> PgPlan {
let ex_r = pr.f("layerExploder/radiusOfNewParticles").max(0.5) as f32;
let ex_disp = pr.f("layerExploder/velocityDispersion") as f32;
let mut key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 0x7067);
let mut key = pg_key(ctx);
for m in [&pg.persistent, &pg.ephemeral].into_iter().flatten() {
key ^= image_key(&m.map.img).rotate_left(7);
}
@@ -819,8 +861,19 @@ pub fn playground_plan(ctx: &EffectCtx, b: &Buf) -> PgPlan {
};
// A cannon with gravity only: every particle moves on its own (GPU particles).
let independent = pg.cannon_only() && !(grid_on && across > 0 && down > 0) && exploder.is_none();
let gpu = if independent { pg_accelerated(ctx, key, &pg) } else { None };
let st = gpu.unwrap_or_else(|| PG_CACHE.run(key, steps_at(ctx.time), init, |st, _| pg.step(st)));
let producers = PG_PRODUCER.history(ctx);
let producer_prefix = crate::psim::producer_prefixes(&producers);
let producer = |i: u64| producers.get(i as usize).map(|p| [p[0], p[1]]).unwrap_or([0.0; 2]);
let gpu = if independent { pg_accelerated(ctx, key, &pg, &producers) } else { None };
let st = gpu.unwrap_or_else(|| {
PG_CACHE.run_where(
key,
steps_at(ctx.time),
init,
|st, i| pg.step_at(st, producer(i)),
|s, st| producer_prefix.get(s as usize) == Some(&st.producer_hist),
)
});
// Render: what the ephemeral mapper changes shows for this frame only.
let parts: Vec<PgParticle> = st.parts.iter().map(|q| pg.ephemeral(q)).collect();
let auto_orient = pr.b("options/autoOrientRotation");
+120 -2
View File
@@ -1,5 +1,5 @@
use super::*;
use crate::{EffectEnv, MaskShape, run_fx};
use crate::{EffectCtx, EffectEnv, MaskShape, Params, run_fx};
fn run(vals: &[(&str, Value)], t: f64) -> Image {
run_fx("ec.sim.particleplayground", vals, Image::filled(80, 60, [0.2, 0.2, 0.2, 1.0]), t, EffectEnv::default()).img
@@ -27,6 +27,125 @@ fn cannon_stream_is_seek_consistent() {
assert!(z.data.iter().all(|p| p[3] == 0.0));
}
/// A host whose cannon moves from `start_x` at layer time 0 to `start_x + 60 · t`.
struct MovingCannon {
index: usize,
start_x: f64,
}
impl crate::EffectHost for MovingCannon {
fn layer(&self, _: u64, _: bool) -> Option<crate::LayerPixels> {
None
}
fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option<Vec<f32>> {
None
}
fn param_at(&self, effect_index: usize, id: &str, t: f64) -> Option<Value> {
(effect_index == self.index && id == "cannon/cannonPosition").then_some(Value::Vec2([self.start_x + 60.0 * t, 50.0]))
}
}
fn pg_params(current_x: f64) -> Params {
let spec = crate::find("ec.sim.particleplayground").unwrap();
let mut p = Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), crate::default_value(ps, [80.0, 60.0]))).collect() };
for (id, value) in [
("gridEnabled", Value::Bool(false)),
("cannonEnabled", Value::Bool(true)),
("cannon/cannonPosition", Value::Vec2([current_x, 50.0])),
("cannon/barrelRadius", num(0.0)),
("cannon/particlesPerSecond", num(60.0)),
("cannon/directionRandomSpread", num(0.0)),
("cannon/velocity", num(0.0)),
("cannon/velocityRandomSpread", num(0.0)),
("gravity/gravityForce", num(0.0)),
("randomSeed", num(1.0)),
] {
p.values.insert(id.into(), value);
}
p
}
/// Production-shaped Particle Playground parameters, including the positional aliases that
/// [`crate::flatten_params`] adds for grouped controls.
fn pg_production_params(current_x: f64) -> Params {
use effectcraft_project::build::Ids;
let spec = crate::find("ec.sim.particleplayground").unwrap();
let mut next = 1;
let mut group = crate::instantiate(spec, &mut Ids(&mut next), spec.name, [80.0, 60.0]);
group.sub_mut("cannon").unwrap().prop_mut("cannonPosition").unwrap().value = Value::Vec2([current_x, 50.0]);
crate::flatten_params(&group, &mut |pr| pr.value.clone())
}
/// #1955: a Particle Playground cannon particle is born at the cannon's position during its
/// birth step, not at the cannon's position when the frame is rendered.
#[test]
fn cannon_particles_are_born_at_their_producer_positions() {
let p = pg_params(80.0);
let host = MovingCannon { index: 0, start_x: 20.0 };
let env = EffectEnv { host: Some(&host), effect_index: 0, ..Default::default() };
let ctx = EffectCtx { params: &p, time: 1.0, layer_size: [80.0, 60.0], seed: 11, adjustment: false, env };
let parts = playground_state(&ctx).unwrap();
let births = crate::psim::births(60.0, steps_at(1.0), 60_000).unwrap();
assert!(parts.len() > 20, "{} particles", parts.len());
for q in parts {
let step = births[q.id as usize] as f32;
assert!((q.p[0] - (20.0 + step)).abs() < 1e-4, "particle {} at {:?}, expected {}", q.id, q.p, 20.0 + step);
}
}
/// The current cannon position is not part of the simulation key, but an earlier one is: a
/// checkpoint reached with another producer history is not reused.
#[test]
fn a_changed_cannon_history_drops_stale_checkpoints() {
let p = pg_params(80.0);
let state = |start_x| {
let host = MovingCannon { index: 0, start_x };
let env = EffectEnv { host: Some(&host), effect_index: 0, ..Default::default() };
let ctx = EffectCtx { params: &p, time: 1.0, layer_size: [80.0, 60.0], seed: 12, adjustment: false, env };
playground_state(&ctx).unwrap().into_iter().next().unwrap().p[0]
};
assert!((state(20.0) - 20.0).abs() < 1e-4, "{}", state(20.0));
assert!((state(60.0) - 60.0).abs() < 1e-4, "{}", state(60.0));
}
/// The cannon's current position is not part of the simulation key, while its other cannon
/// parameters remain part of it.
#[test]
fn the_cannon_position_is_not_part_of_the_particle_playground_key() {
let p = pg_production_params(80.0);
fn ctx(p: &Params) -> EffectCtx<'_> {
EffectCtx { params: p, time: 1.0, layer_size: [80.0, 60.0], seed: 13, adjustment: false, env: EffectEnv::default() }
}
assert!(p.values.contains_key("#2/cannonPosition"), "production parameters have the positional alias");
let mut moved = p.clone();
moved.values.insert("cannon/cannonPosition".into(), Value::Vec2([120.0, 50.0]));
moved.values.insert("#2/cannonPosition".into(), Value::Vec2([120.0, 50.0]));
assert_eq!(pg_key(&ctx(&p)), pg_key(&ctx(&moved)));
moved.values.insert("cannon/barrelAngle".into(), num(10.0));
moved.values.insert("#2/barrelAngle".into(), num(10.0));
assert_ne!(pg_key(&ctx(&p)), pg_key(&ctx(&moved)));
}
/// Moving the cannon only changes the position of particles born after the move; particles
/// that already exist keep their world-space trajectory.
#[test]
fn moving_the_cannon_does_not_move_existing_particles() {
let pg = Pg { cannon: true, rate: 60.0, vel: 60.0, ..bare(3) };
let mut initial = PgState::default();
pg.step_at(&mut initial, [10.0, 10.0]);
let mut moved = initial.clone();
let mut unchanged = initial.clone();
pg.step_at(&mut moved, [100.0, 10.0]);
pg.step_at(&mut unchanged, [10.0, 10.0]);
assert_eq!(moved.parts.len(), 2);
assert_eq!(unchanged.parts.len(), 2);
assert_eq!(moved.parts[0].id, unchanged.parts[0].id);
assert_eq!(moved.parts[0].p, unchanged.parts[0].p);
assert_eq!(moved.parts[0].v, unchanged.parts[0].v);
assert!((moved.parts[1].p[0] - 100.0).abs() < 1e-4, "{:?}", moved.parts[1].p);
assert!((unchanged.parts[1].p[0] - 10.0).abs() < 1e-4, "{:?}", unchanged.parts[1].p);
}
#[test]
fn grid_falls_with_gravity_and_bounces_off_a_wall() {
let grid = |t: f64, env: EffectEnv| {
@@ -136,7 +255,6 @@ fn property_mapper_and_layer_map_read_layers() {
fn bare(seed: u32) -> Pg {
Pg {
cannon: false,
pos: [0.0; 2],
barrel_angle: 0.0,
barrel_radius: 0.0,
rate: 0.0,
+33 -1
View File
@@ -522,12 +522,44 @@ pub fn params_key(ctx: &crate::EffectCtx, b: &crate::Buf, salt: u64) -> u64 {
params_key_except(ctx, b, salt, &[])
}
/// Whether a flattened parameter is one of the paths in `skip`.
///
/// [`crate::flatten_params`] gives a grouped parameter both its canonical path (for example
/// `producer/position`) and a positional alias (for example `#1/position`). The aliases carry
/// the same value, so skipping only the canonical path would still let the current producer
/// position change a simulation key. Group metadata maps each alias back to its canonical path.
fn skipped_param(ctx: &crate::EffectCtx, id: &str, skip: &[&str]) -> bool {
if skip.iter().any(|s| id.starts_with(s)) {
return true;
}
if !id.contains('#') {
return false;
}
let mut canonical = String::new();
let mut prefix = String::new();
for part in id.split('/') {
let group = part.strip_prefix('#').filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())).and_then(|_| {
let metadata = format!("{prefix}{part}/@match");
match ctx.params.values.get(&metadata) {
Some(crate::Value::Str(group)) => Some(group.as_str()),
_ => None,
}
});
canonical.push_str(group.unwrap_or(part));
canonical.push('/');
prefix.push_str(part);
prefix.push('/');
}
canonical.pop();
skip.iter().any(|s| canonical.starts_with(s))
}
/// [`params_key`] without the parameters whose ids start with one of `skip` (ones that only
/// change how the simulation is viewed, so animating them doesn't restart it).
pub fn params_key_except(ctx: &crate::EffectCtx, b: &crate::Buf, salt: u64, skip: &[&str]) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
let mut keys: Vec<&String> = ctx.params.values.keys().filter(|k| !skip.iter().any(|s| k.starts_with(s))).collect();
let mut keys: Vec<&String> = ctx.params.values.keys().filter(|k| !skipped_param(ctx, k, skip)).collect();
keys.sort();
for k in keys {
k.hash(&mut h);
+255 -35
View File
@@ -9,7 +9,7 @@ use effectcraft_render::EvalCtx;
use serde_json::{Value, json};
use super::layer_menu::target_masks;
use super::{CommandSpec, b_p, bad, f_p, has_comp, has_layers, layer_mut, layer_p, merge_p, str_p};
use super::{CommandSpec, b_p, bad, comp_id, f_p, has_comp, has_layers, layer_mut, layer_p, layers_p, merge_p, str_p, unlocked};
use crate::{EngineError, Result, Session, VertexRef, cmd};
mod closed;
@@ -153,26 +153,223 @@ fn parametric_path(ctx: &EvalCtx, layer: &effectcraft_project::Layer, g: &PropGr
effectcraft_path::from_kurbo(&path).into_iter().next()
}
/// How deep [`parametric_in`] looks into nested shape groups; deeper ones are left alone.
const MAX_SHAPE_DEPTH: usize = 64;
/// The parametric paths in `g` (itself, if it is one), in drawing order.
fn parametric_in(g: &PropGroup, lid: LayerId, depth: usize, out: &mut Vec<(LayerId, Uid)>) {
if PARAMETRIC.contains(&g.match_id.as_str()) {
out.push((lid, g.uid));
return;
}
if depth >= MAX_SHAPE_DEPTH {
return;
}
for c in g.groups() {
parametric_in(c, lid, depth + 1, out);
}
}
/// Converts masks and the selected parametric shape paths (Rectangle, Ellipse, Polystar) to editable Bezier paths of the same geometry at the current time.
/// Items on locked layers are skipped, and it errors when nothing is left to convert.
fn convert_to_bezier(s: &mut Session, p: &Value) -> Result<Value> {
// On a shape layer this replaces a Rectangle, Ellipse or Polystar path with an editable
// Path 1 of the same geometry, as After Effects does (#932). The parametric properties are
// read at the current time and the path that comes out is static: a size or roundness
// animation cannot survive the conversion, in After Effects either.
let (cid, items) = selected_shape_items(s, p)?;
const LABEL: &str = "Convert To Bezier Path";
// An explicit `mask` is what converts: selected shape items (or `items`) don't take its place,
// and a `mask` that matches nothing is reported below rather than converting a shape.
// The composition is the one `comp` names (else the active one), as the mask and layer
// resolvers use; a selection made in another composition doesn't apply to it.
let cid = comp_id(s, p)?;
let mut items = if p.get("mask").is_some() {
Vec::new()
} else {
let (items_cid, items) = selected_shape_items(s, p, "path.convertToBezier")?;
if items_cid == cid { items } else { Vec::new() }
};
// `items` count as given only as a list, as `selected_shape_items` reads them; a null or other
// value leaves the selection in charge.
let explicit_items = matches!(p.get("items"), Some(Value::Array(_)));
// An explicit `layer` / `layers` limits the selected shape items to those layers.
let explicit_layers = p.get("layer").is_some_and(|v| !v.is_null()) || p.get("layers").is_some();
if explicit_layers && !explicit_items {
let (_, layers) = layers_p(s, p)?;
items.retain(|(l, _)| layers.contains(l));
}
// Items on a locked layer are left alone (an error when they all are), whether they come from
// the selection or from `items`.
if !items.is_empty() {
let mut item_layers: Vec<LayerId> = items.iter().map(|(l, _)| *l).collect();
item_layers.sort();
item_layers.dedup();
let open = unlocked(s, cid, item_layers, "path.convertToBezier")?;
items.retain(|(l, _)| open.contains(l));
}
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let shapes: Vec<(LayerId, Uid)> = items
.into_iter()
.filter(|(l, u)| {
comp.layer(*l).and_then(|l| l.props.sub("contents")).and_then(|c| c.find_group(*u)).is_some_and(|g| PARAMETRIC.contains(&g.match_id.as_str()))
})
.collect();
if shapes.is_empty() {
return edit_mask_groups(s, p, "Convert To Bezier Path", |g| {
if let GroupKind::Mask { roto_bezier, .. } = &mut g.kind {
*roto_bezier = false;
// A selected parametric path converts itself, animated or not (After Effects keeps the shape
// at the current time). A selected shape group converts the parametric paths inside it
// (#3057: selecting Rectangle 1 rather than its Rectangle Path 1 reported "no masks"), but
// leaves the animated ones alone, as converting a whole layer does.
let mut shapes: Vec<(LayerId, Uid)> = Vec::new();
let mut skipped: Vec<(LayerId, Uid)> = Vec::new();
for (lid, uid) in &items {
let Some(g) = comp.layer(*lid).and_then(|l| l.props.sub("contents")).and_then(|c| c.find_group(*uid)) else { continue };
if PARAMETRIC.contains(&g.match_id.as_str()) {
shapes.push((*lid, *uid));
continue;
}
let mut found = Vec::new();
parametric_in(g, *lid, 0, &mut found);
for (fl, fu) in found {
if g.find_group(fu).is_some_and(PropGroup::any_animated) {
skipped.push((fl, fu));
} else {
shapes.push((fl, fu));
}
Ok(())
});
}
}
shapes.sort();
shapes.dedup();
// A path both selected itself and inside a selected group converts; it is not skipped.
skipped.sort();
skipped.dedup();
skipped.retain(|x| !shapes.contains(x));
let mut skipped_animated = skipped.len();
// Masks the selection targets too (a selected mask or one of its properties, mask vertices)
// convert with the shape paths in the same step, as the command acts on every selected path:
// selecting a mask and a Rectangle path must not convert only the rectangle.
// Explicit `items` name exactly what converts: the selection adds no masks to them.
let mut sel_masks: Vec<(LayerId, Uid)> = Vec::new();
if !shapes.is_empty() && !explicit_items {
let masks_of = |l: LayerId| comp.layer(l).filter(|ly| !ly.switches.locked).and_then(|ly| ly.masks());
for (l, u) in &s.state.selected_props {
let Some(m) = masks_of(*l) else { continue };
sel_masks.extend(m.groups().filter(|g| g.uid == *u || g.find(*u).is_some()).map(|g| (*l, g.uid)));
}
for v in &s.state.selected_vertices {
if masks_of(v.layer).is_some_and(|m| m.groups().any(|g| g.uid == v.mask)) {
sel_masks.push((v.layer, v.mask));
}
}
if explicit_layers {
let (_, layers) = layers_p(s, p)?;
sel_masks.retain(|(l, _)| layers.contains(l));
}
sel_masks.sort();
sel_masks.dedup();
}
if shapes.is_empty() {
// Explicit `items` with nothing parametric in them (a Fill, a path that is already Bezier)
// convert nothing: they don't hand the conversion to a selected mask or the layer's masks.
if explicit_items && p.get("mask").is_none() {
let why = if skipped_animated > 0 {
"the parametric paths are animated: name the path itself in `items` to convert it at the current time (its animation is lost)"
} else {
"nothing to convert: the given items have no Rectangle, Ellipse or Polystar path"
};
return Err(bad(LABEL, why));
}
let (_, mut masks) = masks_for(s, p)?;
let mask_of = |l: LayerId, u: Uid| comp.layer(l).and_then(|l| l.masks()).and_then(|m| m.groups().find(|g| g.uid == u));
masks.retain(|(l, u)| mask_of(*l, *u).is_some());
// An explicit `layer` / `layers` is the scope: a mask selected on another layer is not
// converted in its place. With none of the selected masks in scope, the scoped layers'
// own masks are the targets, as for a selected layer.
let scope = if explicit_layers { Some(layers_p(s, p)?.1) } else { None };
let in_scope = |l: &LayerId| scope.as_ref().is_none_or(|v| v.contains(l));
if let Some(layers) = &scope {
masks.retain(|(l, _)| layers.contains(l));
if masks.is_empty() && p.get("mask").is_none() {
for l in layers {
if let Some(m) = comp.layer(*l).and_then(|ly| ly.masks()) {
masks.extend(m.groups().map(|g| (*l, g.uid)));
}
}
}
}
masks.sort();
masks.dedup();
// Masks on a locked layer are left alone, as shape items are. This comes after the scope
// and its fallback, so a locked selected mask doesn't hand the conversion to other masks.
let mut mask_layers: Vec<LayerId> = masks.iter().map(|(l, _)| *l).collect();
mask_layers.dedup();
masks.retain(|(l, _)| comp.layer(*l).is_some_and(|ly| !ly.switches.locked));
// Masks take priority when they are targeted (a `mask`, a selected mask or mask vertices)
// or when one of them has RotoBezier tangents to turn off. A selected layer's plain masks
// are already Bezier paths: converting them would do nothing and hide the layer's
// parametric shapes (#3057).
let mask_targeted = p.get("mask").is_some()
|| (p.get("layer").is_none() && s.state.selected_vertices.iter().any(|v| in_scope(&v.layer)))
|| s.state
.selected_props
.iter()
.any(|(l, u)| in_scope(l) && comp.layer(*l).and_then(|l| l.masks()).is_some_and(|m| m.uid != *u && m.find_group(*u).is_some()));
let any_roto = masks.iter().any(|(l, u)| mask_of(*l, *u).is_some_and(is_roto));
// Every targeted mask is on a locked layer: say so rather than convert anything else.
if mask_targeted && masks.is_empty() && !mask_layers.is_empty() {
unlocked(s, cid, mask_layers, "path.convertToBezier")?;
return Err(bad(LABEL, "the masks are on locked layers"));
}
// A selected group whose paths were all skipped as animated reports that, rather than
// turning to the layer's masks.
if !masks.is_empty() && (mask_targeted || (any_roto && skipped_animated == 0)) {
// The scoped targets are edited as resolved here, not looked up again.
let n = masks.len();
s.edit(LABEL, None, |proj, _| {
for (lid, uid) in &masks {
let l = layer_mut(proj, cid, *lid)?;
if let Some(g) = l.props.sub_mut("masks").and_then(|m| m.find_group_mut(*uid))
&& let GroupKind::Mask { roto_bezier, .. } = &mut g.kind
{
*roto_bezier = false;
}
}
Ok(())
})?;
return Ok(json!({"masks": n}));
}
if p.get("mask").is_some() {
return Err(bad(LABEL, "no mask matches `mask`"));
}
// Only layers selected (#3057): a shape layer drawn with the Rectangle, Ellipse or Polygon
// tool converts its parametric paths, as the masks of a selected layer do. A selected
// shape item with nothing parametric in it (a Fill, a Bezier path) is not widened to the
// whole layer, and an animated parametric path is left alone here: converting keeps only
// the shape at the current time, so that takes selecting the path itself.
if items.is_empty() {
let (lcid, mut layers) = layers_p(s, p)?;
// A layer named twice (`layers: [1, "Shape 1"]`) converts once: its paths would
// otherwise be replaced twice, and the second replacement finds no such item.
layers.sort();
layers.dedup();
if lcid == cid {
for lid in unlocked(s, cid, layers, "path.convertToBezier")? {
let Some(l) = comp.layer(lid).filter(|l| matches!(l.source, LayerSource::Shape)) else { continue };
let Some(contents) = l.props.sub("contents") else { continue };
let mut found = Vec::new();
parametric_in(contents, lid, 0, &mut found);
for (fl, fu) in found {
if contents.find_group(fu).is_some_and(PropGroup::any_animated) {
skipped_animated += 1;
} else {
shapes.push((fl, fu));
}
}
}
}
}
if shapes.is_empty() {
let why = if skipped_animated > 0 {
"the parametric paths are animated: select one in the Timeline to convert it at the current time (its animation is lost)"
} else if !masks.is_empty() {
"nothing to convert: the masks are already Bezier paths"
} else {
"nothing to convert: select a Rectangle, Ellipse or Polystar path, a shape layer with one, or a layer with masks"
};
return Err(bad(LABEL, why));
}
}
let t = s.time();
let n = shapes.len();
@@ -210,13 +407,22 @@ fn convert_to_bezier(s: &mut Session, p: &Value) -> Result<Value> {
made.push((lid, new_uid));
}
proj.next_id = next;
// The new paths are what is selected, so the vertices can be edited straight away.
for (lid, uid) in &sel_masks {
let l = layer_mut(proj, cid, *lid)?;
if let Some(g) = l.props.sub_mut("masks").and_then(|m| m.find_group_mut(*uid))
&& let GroupKind::Mask { roto_bezier, .. } = &mut g.kind
{
*roto_bezier = false;
}
}
// The new paths are what is selected, so the vertices can be edited straight away; the
// converted masks stay selected with them.
if !made.is_empty() {
st.selected_props = made.clone();
st.selected_props = made.iter().chain(&sel_masks).copied().collect();
}
Ok(made)
})?;
Ok(json!({"paths": made.len(), "of": n}))
Ok(json!({"paths": made.len(), "of": n, "masks": sel_masks.len(), "skippedAnimated": skipped_animated}))
}
// ---------------------------------------------------------------- mask options
@@ -389,24 +595,25 @@ const SHAPE_ITEMS: &[&str] = &[
"wiggle", "wiggler", "merge", "front", "bevel", "side", "back",
];
/// Selected shape items (contents entries) of shape layers: (layer, uid).
fn selected_shape_items(s: &Session, p: &Value) -> Result<(ItemId, Vec<(LayerId, Uid)>)> {
/// Selected shape items (contents entries) of shape layers: (layer, uid), with their composition.
/// Explicit `items` are on the layer `layer_p` resolves, in the composition it resolves (`comp`,
/// else the active one); selected items are the active composition's.
fn selected_shape_items(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, Vec<(LayerId, Uid)>)> {
if let Some(Value::Array(a)) = p.get("items") {
let (cid, lid) = layer_p(s, p, cmd)?;
return Ok((cid, a.iter().filter_map(Value::as_u64).map(|u| (lid, u)).collect()));
}
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let mut out = vec![];
if let Some(Value::Array(a)) = p.get("items") {
let (_, lid) = layer_p(s, p, "path.groupShapes")?;
out.extend(a.iter().filter_map(Value::as_u64).map(|u| (lid, u)));
} else {
for (lid, uid) in &s.state.selected_props {
let Some(l) = comp.layer(*lid).filter(|l| matches!(l.source, LayerSource::Shape)) else { continue };
if l.props
.sub("contents")
.and_then(|c| c.find_group(*uid))
.is_some_and(|g| g.uid != l.props.sub("contents").map(|c| c.uid).unwrap_or(0) && SHAPE_ITEMS.contains(&g.match_id.as_str()))
{
out.push((*lid, *uid));
}
for (lid, uid) in &s.state.selected_props {
let Some(l) = comp.layer(*lid).filter(|l| matches!(l.source, LayerSource::Shape)) else { continue };
if l.props
.sub("contents")
.and_then(|c| c.find_group(*uid))
.is_some_and(|g| g.uid != l.props.sub("contents").map(|c| c.uid).unwrap_or(0) && SHAPE_ITEMS.contains(&g.match_id.as_str()))
{
out.push((*lid, *uid));
}
}
Ok((cid, out))
@@ -421,8 +628,10 @@ fn has_shape_items(s: &Session) -> std::result::Result<(), String> {
if ok { Ok(()) } else { Err("select shape items (Contents ▸ …) in the timeline".into()) }
}
/// Wraps the selected shape items of one layer in a new group placed where the first of them was.
/// Errors when no shape items are selected or they do not share one parent group.
fn group_shapes(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, items) = selected_shape_items(s, p)?;
let (cid, items) = selected_shape_items(s, p, "path.groupShapes")?;
let Some(lid) = items.first().map(|x| x.0) else { return Err(bad("path.groupShapes", "select shape items to group")) };
let uids: Vec<Uid> = items.iter().filter(|(l, _)| *l == lid).map(|(_, u)| *u).collect();
let g = s.edit("Group Shapes", None, |proj, st| {
@@ -496,8 +705,10 @@ fn offset_items(g: &mut PropGroup, d: [f64; 2]) {
}
}
/// Replaces each selected shape group with its children, baking the group's position offset into them.
/// Errors when no group is selected or a group has a scale, rotation, skew, opacity or animated transform.
fn ungroup_shapes(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, items) = selected_shape_items(s, p)?;
let (cid, items) = selected_shape_items(s, p, "path.ungroupShapes")?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let groups: Vec<(LayerId, Uid)> = items
.into_iter()
@@ -548,11 +759,20 @@ fn ungroup_shapes(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"ungrouped": n}))
}
/// The command specs for the path commands: RotoBezier, Convert To Bezier Path, Group Shapes, Ungroup Shapes and the rest of this module.
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("path.toggleClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{}", closed::has_paths, closed::toggle_closed),
cmd!("path.rotoBezier", "RotoBezier", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?, value?}", has_layers, roto_bezier),
cmd!("path.convertToBezier", "Convert To Bezier Path", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?}", has_layers, convert_to_bezier),
cmd!(
"path.convertToBezier",
"Convert To Bezier Path",
["Layer", "Mask and Shape Path"],
None,
"{layer?, layers?, mask?, items?: [uid]}",
has_layers,
convert_to_bezier
),
cmd!("path.groupShapes", "Group Shapes", ["Layer"], Some("Cmd+G"), "{layer?, items?: [uid]}", has_shape_items, group_shapes),
cmd!("path.ungroupShapes", "Ungroup Shapes", ["Layer"], Some("Cmd+Shift+G"), "{layer?, items?: [group uid]}", has_shape_items, ungroup_shapes),
cmd!(
+21 -1
View File
@@ -430,7 +430,12 @@ fn run_startup(s: &mut Session, _: &Value) -> Result<Value> {
/// (frontends call it as the app quits, after the unsaved-changes prompt).
fn run_shutdown(s: &mut Session, _: &Value) -> Result<Value> {
s.replace_project(effectcraft_project::Project::default(), None);
Ok(run_folder(s, SHUTDOWN_DIR, true))
// The app is quitting: nothing would show a Shutdown script's file dialog (File.saveDialog…),
// so it gets null at once instead of waiting.
let answers = std::mem::replace(&mut s.script_ui.answers_file_dialogs, false);
let r = run_folder(s, SHUTDOWN_DIR, true);
s.script_ui.answers_file_dialogs = answers;
Ok(r)
}
/// Window ▸ `<ScriptUI panel>`: run the panel script (or bring its panel forward).
@@ -599,6 +604,21 @@ pub fn specs() -> Vec<CommandSpec> {
always,
scriptui::close
),
crate::query!(
"scriptui.fileDialogs",
"Script File Dialogs",
"{} → [{id, host, kind: open|save|folder, prompt, exts, label, any, many, start, shown}]: the file dialogs scripts wait on (File.openDialog, File.saveDialog, Folder.selectDialog…)",
scriptui::file_dialogs
),
cmd!(
"scriptui.fileDialog",
"Answer Script File Dialog",
[],
None,
"{id? (from scriptui.fileDialogs; default the only one), host?, paths: [path…] | null (cancelled)} → the waiting script goes on with the picked files",
always,
scriptui::file_dialog
),
]
}
+104
View File
@@ -436,6 +436,50 @@ pub struct ScriptUiEvent {
/// The ScriptUI mouse events scripts can listen for (`addEventListener`).
pub const MOUSE_EVENTS: [&str; 6] = ["mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "click"];
/// The [`ScriptUiEvent::kind`] that answers a script's file dialog ([`ScriptFileDialog`]); its
/// value is `{host, paths: [path…] | null}` and it goes to the script context `host`, not to a
/// window.
pub const FILE_DIALOG_EVENT: &str = "fileDialog";
/// What a script's file dialog picks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FileDialogKind {
/// A file (or several) to open: `File.openDialog`, `file.openDlg`.
#[default]
Open,
/// Where to save: `File.saveDialog`, `file.saveDlg`.
Save,
/// A folder: `Folder.selectDialog`, `folder.selectDlg`.
Folder,
}
/// A file dialog a script asked for and waits on (#2778). The frontend shows it and answers with
/// `scriptui.fileDialog`; agents can answer it the same way.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ScriptFileDialog {
/// Unique in the process: an answer goes to this dialog only.
pub id: u32,
/// The script context waiting for the answer.
pub host: u32,
pub kind: FileDialogKind,
/// The script's prompt.
pub prompt: String,
/// The extensions the script's filter names, lower case (empty: any file).
pub exts: Vec<String>,
/// The filter's name (`"Audio"` in `"Audio:*.mp3;*.wav"`; empty: none given).
pub label: String,
/// The filter also offers every file (`*.*`).
pub any: bool,
/// `multiSelect`: several files may be picked.
pub many: bool,
/// The file or folder the dialog starts from (`file.saveDlg`: the default name).
pub start: String,
/// A frontend has shown it (it is not shown again).
pub shown: bool,
}
/// Hands an event to the script that owns the window; returns what the handler reported
/// (`{ok, output, error}`) and updates [`Session::script_ui`].
pub type ScriptUiDispatch = fn(&mut Session, &ScriptUiEvent) -> std::result::Result<Value, String>;
@@ -491,6 +535,13 @@ pub struct ScriptUi {
/// replaced, until EffectCraft quits.
#[serde(skip)]
pub startup_hosts: Vec<u32>,
/// The file dialogs scripts wait on, until `scriptui.fileDialog` answers them.
pub file_dialogs: Vec<ScriptFileDialog>,
/// A frontend shows the scripts' file dialogs (the egui UI sets it). Without one, as in
/// headless runs, `File.openDialog` and the like return `null` at once, so a script never
/// waits on a dialog nobody shows.
#[serde(skip)]
pub answers_file_dialogs: bool,
}
impl ScriptUi {
@@ -859,10 +910,63 @@ pub(crate) fn resize(s: &mut Session, p: &Value) -> Result<Value> {
dispatch(s, ScriptUiEvent { window, widget: 0, kind: "resize".into(), value: json!([w, h]) })
}
/// `scriptui.fileDialogs`: the file dialogs scripts wait on.
pub(crate) fn file_dialogs(s: &mut Session, _: &Value) -> Result<Value> {
Ok(serde_json::to_value(&s.script_ui.file_dialogs).unwrap_or(Value::Null))
}
/// `scriptui.fileDialog`: answer a script's file dialog with the picked `paths` (`null` or
/// empty: cancelled); the script goes on with them. The dialog stays pending until its script
/// has the answer, so a refused answer leaves it to be answered again.
pub(crate) fn file_dialog(s: &mut Session, p: &Value) -> Result<Value> {
let c = "scriptui.fileDialog";
// A script answering a dialog (its own or another script's) would only be refused when the
// answer is handed over: scripts can't drive script windows.
if s.running_for_script() {
return Err(crate::commands::bad(c, "scripts can't answer file dialogs"));
}
let num = |k: &str| p.get(k).map(|v| v.as_u64().and_then(|n| u32::try_from(n).ok()));
let pending = &s.script_ui.file_dialogs;
let asked = match (num("id"), num("host")) {
(Some(id), _) => id.and_then(|id| pending.iter().find(|d| d.id == id)),
(None, Some(host)) => host.and_then(|h| pending.iter().find(|d| d.host == h)),
(None, None) if pending.len() == 1 => pending.first(),
(None, None) => None,
};
let asked = asked.cloned().ok_or_else(|| crate::commands::bad(c, "no such file dialog (give `id` from scriptui.fileDialogs)"))?;
let mut paths: Vec<String> = match p.get("paths").or_else(|| p.get("path")) {
None | Some(Value::Null) => vec![],
Some(Value::String(one)) => vec![one.clone()],
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<Vec<_>>>().ok_or_else(|| crate::commands::bad(c, "`paths` must be strings"))?
}
Some(other) => return Err(crate::commands::bad(c, format!("`paths` must be a list of paths or null, not {other}"))),
};
paths.retain(|p| !p.is_empty());
if !asked.many {
paths.truncate(1);
}
let paths = if paths.is_empty() { Value::Null } else { json!(paths) };
// The scripting engine takes the dialog off the list when its script has the answer.
let value = json!({"id": asked.id, "host": asked.host, "paths": paths});
dispatch(s, ScriptUiEvent { window: 0, widget: 0, kind: FILE_DIALOG_EVENT.into(), value })
}
/// `scriptui.close`: close a window (a dialog's `show()` returns `result`, default 2 = Cancel).
pub(crate) fn close(s: &mut Session, p: &Value) -> Result<Value> {
let window = window_p(s, p, "scriptui.close")?;
let result = p.get("result").cloned().unwrap_or(json!(2));
// A script waiting on its file dialog (one whose answer never came) can still be closed:
// the file dialog counts as cancelled first. If that is refused, the close is tried all the
// same (and refused with its own reason).
let host = s.script_ui.window(window).map(|w| w.host);
let asked = host.and_then(|h| s.script_ui.file_dialogs.iter().find(|d| d.host == h)).map(|d| d.id);
if let Some(id) = asked
&& let Ok(cancelled) = file_dialog(s, &json!({"id": id, "paths": null}))
&& s.script_ui.window(window).is_none()
{
return Ok(cancelled);
}
dispatch(s, ScriptUiEvent { window, widget: 0, kind: "close".into(), value: result })
}
+108 -2
View File
@@ -306,8 +306,8 @@ fn instance_keys_stay_out_of_a_layer_that_blends_frames() {
assert!(pr.keys.is_empty());
}
/// An override from a collapsed parent reaches the nested instance as a value only: the keys the
/// nested instance property carries itself must not be copied onto its own target.
/// A static override from a collapsed parent reaches the nested instance as a value only: the
/// keys the nested instance property carries itself must not be copied onto its own target.
#[test]
fn collapsed_parent_override_replaces_the_nested_instance_keys() {
let mut s = Session::default();
@@ -338,3 +338,109 @@ fn collapsed_parent_override_replaces_the_nested_instance_keys() {
assert!((over[0].value.as_f64() - 80.0).abs() < 1e-6, "value {:?}", over[0].value);
assert!(over[0].keys.is_empty(), "the nested instance's own keys are stale");
}
/// Top → Mid → Inner, with a keyed Essential override on the Top instance. The Inner target is
/// `target`; the Mid instance is `nested`. `time_remap` makes the nested source time differ from
/// the Mid instance's layer time.
fn collapsed_parent_scene(time_remap: bool) -> (Session, effectcraft_project::ItemId, effectcraft_project::ItemId, u64, u64, u64) {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Inner", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap();
let target = s.execute("layer.newSolid", json!({"name": "A", "color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap();
s.execute("essential.addProperty", json!({"layer": target, "path": "transform/opacity"})).unwrap();
s.execute("comp.new", json!({"name": "Mid", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap();
let mid = s.active_comp_id().unwrap();
let inner = s.project.find_by_name("Inner").unwrap().id;
let nested = s.execute("layer.addItem", json!({"item": inner.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap();
let nested_path = s.execute("essential.instance", json!({"layer": nested})).unwrap()["controls"][0]["path"].as_str().unwrap().to_string();
s.execute("prop.addKey", json!({"layer": nested, "path": nested_path, "time": 0.0, "value": 0.0})).unwrap();
s.execute("prop.addKey", json!({"layer": nested, "path": nested_path, "time": 1.0, "value": 100.0})).unwrap();
let ctl = s.execute("essential.addProperty", json!({"layer": nested, "path": nested_path})).unwrap()["controls"][0].as_u64().unwrap();
s.execute("layer.setSwitch", json!({"layers": [nested], "switch": "collapse", "value": true})).unwrap();
if time_remap {
s.execute("layer.enableTimeRemap", json!({"layers": [nested]})).unwrap();
}
s.execute("comp.new", json!({"name": "Top", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap();
let top = s.active_comp_id().unwrap();
let inst = s.execute("layer.addItem", json!({"item": mid.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setSwitch", json!({"layers": [inst], "switch": "collapse", "value": true})).unwrap();
let controls = s.execute("essential.instance", json!({"layer": inst})).unwrap()["controls"].clone();
let top_path = controls.as_array().unwrap().iter().find(|c| c["control"].as_u64() == Some(ctl)).unwrap()["path"].as_str().unwrap().to_string();
s.execute("prop.addKey", json!({"layer": inst, "path": top_path, "time": 0.0, "value": 10.0})).unwrap();
s.execute("prop.addKey", json!({"layer": inst, "path": top_path, "time": 1.0, "value": 90.0})).unwrap();
(s, top, inner, target, nested, inst)
}
/// A keyed override from a collapsed parent replaces the nested instance's own history with the
/// parent's, so the nested target can still sample the producer at its birth times.
#[test]
fn a_collapsed_parent_keeps_its_override_history_for_the_nested_instance() {
use effectcraft_project::LayerId;
let (mut s, top, inner, target, nested, inst) = collapsed_parent_scene(false);
// The Inner target starts late and is stretched: the parent's source-time keys must be moved
// into this target's own layer time.
{
let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(inner).unwrap().layer_mut(LayerId(target)).unwrap();
layer.start_time = Tick::from_seconds_f64(0.5);
layer.stretch = 125.0;
}
let r = effectcraft_render::Renderer::new(&s.project, &*s.footage, crate::render::RenderOpts::default());
let ctx = effectcraft_render::EvalCtx::new(&s.project, top, s.project.comp(top).unwrap(), Tick::from_seconds_f64(0.25));
let layer = ctx.comp.layer(LayerId(inst)).unwrap();
let collapsed = r.collapsed(&ctx, layer).expect("the instance collapses");
let (_, nctx) = r.collapse_into(&ctx, layer, &collapsed, 1.0).expect("a nested context");
let nl = nctx.comp.layer(LayerId(nested)).unwrap();
let over = effectcraft_render::essential_overrides(&nctx, nl);
assert_eq!(over.len(), 1);
assert!((over[0].value.as_f64() - 30.0).abs() < 1e-6, "value {:?}", over[0].value);
assert_eq!(over[0].keys.len(), 2, "the parent's history reaches the nested target");
assert_eq!(over[0].keys[0].value, KV::Scalar(10.0));
assert_eq!(over[0].keys[1].value, KV::Scalar(90.0));
// The flattened path puts source times 0 and 1 at -0.4 and 0.4 in the target's layer time.
let flat = essential::with_overrides(&s.project, inner, &over).unwrap();
let flat_target = flat.comp(inner).unwrap().layer(LayerId(target)).unwrap();
let flat_prop = flat_target.props.prop("transform/opacity").unwrap();
assert_eq!(flat_prop.keys[0].time, Tick::from_seconds_f64(-0.4));
assert_eq!(flat_prop.keys[1].time, Tick::from_seconds_f64(0.4));
// The collapsed path reads the same values at those exact target-layer times.
let nested_collapsed = r.collapsed(&nctx, nl).expect("the nested instance collapses");
let (_, target_ctx) = r.collapse_into(&nctx, nl, &nested_collapsed, 1.0).expect("the target context");
let target_layer = target_ctx.comp.layer(LayerId(target)).unwrap();
let target_prop = target_layer.props.prop("transform/opacity").unwrap();
assert_eq!(target_ctx.value_at_layer_time(target_layer, target_prop, Tick::from_seconds_f64(-0.4)), KV::Scalar(10.0));
assert_eq!(target_ctx.value_at_layer_time(target_layer, target_prop, Tick::from_seconds_f64(0.4)), KV::Scalar(90.0));
}
/// A remapped nested source has a different time domain, so its inherited history stays out just
/// as it does on the flattened path. Both paths use the same current value.
#[test]
fn a_remapped_nested_instance_drops_inherited_history_consistently() {
use effectcraft_project::LayerId;
let (s, top, inner, target, nested, inst) = collapsed_parent_scene(true);
let r = effectcraft_render::Renderer::new(&s.project, &*s.footage, crate::render::RenderOpts::default());
let ctx = effectcraft_render::EvalCtx::new(&s.project, top, s.project.comp(top).unwrap(), Tick::from_seconds_f64(0.25));
let layer = ctx.comp.layer(LayerId(inst)).unwrap();
let collapsed = r.collapsed(&ctx, layer).expect("the instance collapses");
let (_, nctx) = r.collapse_into(&ctx, layer, &collapsed, 1.0).expect("a nested context");
let nl = nctx.comp.layer(LayerId(nested)).unwrap();
let over = effectcraft_render::essential_overrides(&nctx, nl);
assert_eq!(over.len(), 1);
assert!(over[0].keys.is_empty(), "the remapped source has no usable inherited history");
let flat = essential::with_overrides(&s.project, inner, &over).unwrap();
let flat_target = flat.comp(inner).unwrap().layer(LayerId(target)).unwrap();
let flat_prop = flat_target.props.prop("transform/opacity").unwrap();
let flat_ctx = effectcraft_render::EvalCtx::new(&flat, inner, flat.comp(inner).unwrap(), Tick::from_seconds_f64(0.25));
let flat_value = flat_ctx.value(flat_target, flat_prop);
let nested_collapsed = r.collapsed(&nctx, nl).expect("the nested instance collapses");
let (_, target_ctx) = r.collapse_into(&nctx, nl, &nested_collapsed, 1.0).expect("the target context");
let target_layer = target_ctx.comp.layer(LayerId(target)).unwrap();
let target_prop = target_layer.props.prop("transform/opacity").unwrap();
let collapsed_value = target_ctx.value(target_layer, target_prop);
assert_eq!(collapsed_value, flat_value);
}
+426
View File
@@ -649,6 +649,432 @@ fn convert_to_bezier_evaluates_corner_expressions() {
assert_eq!(path, expected, "the expression-evaluated corner is converted");
}
/// The uid of the first shape item with `match_id` in a shape layer's Contents.
fn shape_item(s: &Session, l: u64, match_id: &str) -> u64 {
/// Depth-first search of a property group tree for the uid of the first group with the given match id.
fn walk(g: &effectcraft_project::PropGroup, id: &str) -> Option<u64> {
if g.match_id == id {
return Some(g.uid);
}
g.groups().find_map(|c| walk(c, id))
}
let ly = layer(s, l);
let contents = ly.props.sub("contents").unwrap();
contents.groups().find_map(|c| walk(c, match_id)).unwrap()
}
/// #3057: right after drawing with the Rectangle, Ellipse or Polygon tool only the layer is
/// selected; Convert To Bezier Path then converted nothing and reported "no masks". The selected
/// shape layer's parametric paths convert, as the masks of a selected layer do, and so do those in
/// a selected shape group (Rectangle 1 rather than its Rectangle Path 1).
#[test]
fn convert_to_bezier_on_a_selected_shape_layer_or_group() {
for kind in ["rect", "ellipse", "polygon"] {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": kind, "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
assert_eq!(s.state.selected_layers, vec![LayerId(l)], "the new layer is selected");
assert!(s.state.selected_props.is_empty(), "and no shape item");
let out = s.execute("path.convertToBezier", json!({})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{kind}: {out}");
let (new_uid, now) = first_shape(&s, l);
assert_eq!(now, "path", "{kind}: the layer's parametric path is a bezier path now");
assert_eq!(s.state.selected_props, vec![(LayerId(l), new_uid)], "{kind}: and selected, to edit its vertices");
}
// A selected shape group converts the parametric path inside it.
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let group = shape_item(&s, l, "group");
s.state.selected_props = vec![(LayerId(l), group)];
let out = s.execute("path.convertToBezier", json!({})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(first_shape(&s, l).1, "path");
// Nothing parametric left: the error says what to select instead of asking for masks.
s.execute("layer.select", json!({"layers": [l]})).unwrap();
let err = s.execute("path.convertToBezier", json!({})).unwrap_err().to_string();
assert!(err.contains("Rectangle, Ellipse or Polystar"), "{err}");
}
/// #3057: a selected shape item with nothing parametric in it (a Fill) does not widen the
/// conversion to the rest of the layer. A guard for the fix (it passes on the old code too).
#[test]
fn convert_to_bezier_does_not_widen_a_selected_fill() {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
let fill = shape_item(&s, l, "fill");
s.state.selected_props = vec![(LayerId(l), fill)];
assert!(s.execute("path.convertToBezier", json!({})).is_err());
assert_eq!(first_shape(&s, l).1, "rect", "the rectangle stays parametric");
}
/// #3057: a selected shape layer's plain masks are already Bezier paths, so they don't hide its
/// rectangle: the rectangle converts. A RotoBezier mask still converts first.
#[test]
fn convert_to_bezier_on_a_shape_layer_with_a_plain_mask() {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap();
s.execute("layer.select", json!({"layers": [l]})).unwrap();
s.state.selected_vertices.clear();
let out = s.execute("path.convertToBezier", json!({})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(first_shape(&s, l).1, "path");
// Nothing parametric left and the mask is plain: say so rather than succeed doing nothing.
s.execute("layer.select", json!({"layers": [l]})).unwrap();
s.state.selected_vertices.clear();
let err = s.execute("path.convertToBezier", json!({})).unwrap_err().to_string();
assert!(err.contains("already Bezier"), "{err}");
}
/// #3057: an explicit `mask` that matches no mask converts nothing, rather than every parametric
/// path of the layer.
#[test]
fn convert_to_bezier_with_an_unmatched_mask_converts_nothing() {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
assert!(s.execute("path.convertToBezier", json!({"layer": l, "mask": "No Such Mask"})).is_err());
assert_eq!(first_shape(&s, l).1, "rect", "the rectangle stays parametric");
}
/// #3057: an explicit `layer` is the layer converted, even with a path selected on another one.
#[test]
fn convert_to_bezier_follows_an_explicit_layer() {
let mut s = comp();
let a = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let b = s.execute("layer.newShape", json!({"kind": "ellipse", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let (a_rect, _) = first_shape(&s, a);
s.state.selected_props = vec![(LayerId(a), a_rect)];
let out = s.execute("path.convertToBezier", json!({"layer": b})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(first_shape(&s, b).1, "path", "the given layer converts");
assert_eq!(first_shape(&s, a).1, "rect", "the selection on another layer does not");
}
/// #3057: converting a selected layer leaves an animated parametric path alone (its animation
/// would be lost) and reports it; selecting that path converts it at the current time, as After
/// Effects does.
#[test]
fn convert_to_bezier_skips_animated_paths_of_a_selected_layer() {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let (rect, _) = first_shape(&s, l);
let size = layer(&s, l).props.sub("contents").unwrap().find_group(rect).unwrap().get("size").unwrap().uid;
for (t, v) in [(0.0, [120.0, 80.0]), (1.0, [200.0, 100.0])] {
s.execute("prop.addKey", json!({"layer": l, "path": format!("@{size}"), "time": t, "value": v})).unwrap();
}
s.execute("layer.select", json!({"layers": [l]})).unwrap();
let err = s.execute("path.convertToBezier", json!({})).unwrap_err().to_string();
assert!(err.contains("animated"), "{err}");
assert_eq!(first_shape(&s, l).1, "rect", "the animated rectangle stays parametric");
s.state.selected_props = vec![(LayerId(l), rect)];
let out = s.execute("path.convertToBezier", json!({})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(first_shape(&s, l).1, "path", "the selected path converts");
}
/// #3057 review: a layer named twice in `layers` (by id and by name) converts once, and its
/// animated paths are counted once.
#[test]
fn convert_to_bezier_with_a_layer_named_twice() {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let name = layer(&s, l).name;
let out = s.execute("path.convertToBezier", json!({"layers": [l, name, l]})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(out["of"].as_u64(), Some(1), "{out}");
assert_eq!(first_shape(&s, l).1, "path");
let mut s = comp();
let a = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let b = s.execute("layer.newShape", json!({"kind": "ellipse", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let (rect, _) = first_shape(&s, a);
let size = layer(&s, a).props.sub("contents").unwrap().find_group(rect).unwrap().get("size").unwrap().uid;
for (t, v) in [(0.0, [120.0, 80.0]), (1.0, [200.0, 100.0])] {
s.execute("prop.addKey", json!({"layer": a, "path": format!("@{size}"), "time": t, "value": v})).unwrap();
}
s.execute("layer.select", json!({"layers": [b]})).unwrap();
let out = s.execute("path.convertToBezier", json!({"layers": [a, a, b]})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(out["skippedAnimated"].as_u64(), Some(1), "{out}");
}
/// #3057 review: shape items on a locked layer don't convert, whether given as `items` or
/// selected; unlocked, they do.
#[test]
fn convert_to_bezier_leaves_a_locked_layer_alone() {
for explicit in [true, false] {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let (rect, _) = first_shape(&s, l);
let lock = |s: &mut Session, v: bool| {
s.execute("layer.setSwitch", json!({"layers": [l], "switch": "locked", "value": v})).unwrap();
};
let run = |s: &mut Session| {
if explicit {
s.execute("path.convertToBezier", json!({"layer": l, "items": [rect]}))
} else {
s.state.selected_props = vec![(LayerId(l), rect)];
s.execute("path.convertToBezier", json!({}))
}
};
lock(&mut s, true);
let err = run(&mut s).unwrap_err().to_string();
assert!(err.contains("locked"), "explicit {explicit}: {err}");
assert_eq!(first_shape(&s, l).1, "rect", "explicit {explicit}: the locked rectangle stays parametric");
lock(&mut s, false);
let out = run(&mut s).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "explicit {explicit}: {out}");
assert_eq!(first_shape(&s, l).1, "path");
}
}
/// #3057 review: a selected group leaves its animated paths alone and reports them, as
/// converting a whole layer does; the path itself, selected, still converts.
#[test]
fn convert_to_bezier_skips_animated_paths_of_a_selected_group() {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let (rect, _) = first_shape(&s, l);
let group = shape_item(&s, l, "group");
let size = layer(&s, l).props.sub("contents").unwrap().find_group(rect).unwrap().get("size").unwrap().uid;
s.execute("prop.setExpression", json!({"layer": l, "path": format!("@{size}"), "expression": "[100, 100]"})).unwrap();
s.state.selected_props = vec![(LayerId(l), group)];
let err = s.execute("path.convertToBezier", json!({})).unwrap_err().to_string();
assert!(err.contains("animated"), "{err}");
assert_eq!(first_shape(&s, l).1, "rect", "the expression-driven rectangle stays parametric");
// The group and its path both selected: the path is converted, not skipped.
s.state.selected_props = vec![(LayerId(l), group), (LayerId(l), rect)];
let out = s.execute("path.convertToBezier", json!({})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(out["skippedAnimated"].as_u64(), Some(0), "{out}");
assert_eq!(first_shape(&s, l).1, "path");
}
/// #3057 review: an explicit `mask` is what converts, even with a parametric path selected or
/// `items` given; a `mask` that matches nothing is an error and converts no shape.
#[test]
fn convert_to_bezier_gives_an_explicit_mask_priority() {
// A shape layer with a rectangle and a RotoBezier mask; the rectangle's path is selected.
let setup = || {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap();
let m = layer(&s, l).masks().unwrap().groups().next().unwrap().uid;
s.execute("path.rotoBezier", json!({"layer": l, "mask": m, "value": true})).unwrap();
let (rect, _) = first_shape(&s, l);
s.state.selected_props = vec![(LayerId(l), rect)];
(s, l, m, rect)
};
// A matching mask converts, not the selected rectangle.
let (mut s, l, m, _) = setup();
s.execute("path.convertToBezier", json!({"layer": l, "mask": m})).unwrap();
assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: false, .. }), "the mask converts");
assert_eq!(first_shape(&s, l).1, "rect", "the selected rectangle stays parametric");
// An unmatched mask is an error, and the selected rectangle is not converted in its place.
let (mut s, l, _, _) = setup();
let err = s.execute("path.convertToBezier", json!({"layer": l, "mask": "No Such Mask"})).unwrap_err().to_string();
assert!(err.contains("mask"), "{err}");
assert_eq!(first_shape(&s, l).1, "rect");
assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. }));
// `mask` and `items` together: the mask converts, the items don't.
let (mut s, l, m, rect) = setup();
s.state.selected_props.clear();
s.execute("path.convertToBezier", json!({"layer": l, "mask": m, "items": [rect]})).unwrap();
assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: false, .. }), "the mask converts");
assert_eq!(first_shape(&s, l).1, "rect", "the listed rectangle stays parametric");
}
/// #3057 review: a selected mask and a selected parametric path both convert, in one undo step;
/// neither is dropped for the other.
#[test]
fn convert_to_bezier_converts_a_selected_mask_and_path_together() {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap();
let m = layer(&s, l).masks().unwrap().groups().next().unwrap().uid;
s.execute("path.rotoBezier", json!({"layer": l, "mask": m, "value": true})).unwrap();
let (rect, _) = first_shape(&s, l);
s.state.selected_vertices.clear();
s.state.selected_props = vec![(LayerId(l), m), (LayerId(l), rect)];
let out = s.execute("path.convertToBezier", json!({})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(out["masks"].as_u64(), Some(1), "{out}");
assert_eq!(first_shape(&s, l).1, "path", "the rectangle converts");
assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: false, .. }), "and so does the mask");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(first_shape(&s, l).1, "rect", "one undo restores the rectangle");
assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. }), "and the mask");
}
/// #3057 review: explicit `items` convert only those shape paths; a RotoBezier mask that happens to
/// be selected on the same layer is not converted along with them.
#[test]
fn convert_to_bezier_with_explicit_items_leaves_a_selected_mask_alone() {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap();
let m = layer(&s, l).masks().unwrap().groups().next().unwrap().uid;
s.execute("path.rotoBezier", json!({"layer": l, "mask": m, "value": true})).unwrap();
let (rect, _) = first_shape(&s, l);
s.state.selected_vertices.clear();
s.state.selected_props = vec![(LayerId(l), m)];
let out = s.execute("path.convertToBezier", json!({"layer": l, "items": [rect]})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert!(out.get("masks").is_none_or(|v| v.as_u64().unwrap_or(0) == 0), "{out}");
assert_eq!(first_shape(&s, l).1, "path", "the listed rectangle converts");
assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. }), "the selected mask is unchanged");
}
/// #3057 review: explicit `items` with nothing parametric in them (a Fill, a path that is already
/// Bezier) are an error and change nothing: neither a selected RotoBezier mask nor, with no mask
/// selected, the layer's own RotoBezier masks are converted in their place.
#[test]
fn convert_to_bezier_with_explicit_non_parametric_items_converts_no_mask() {
for item in ["fill", "path"] {
for mask_selected in [true, false] {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap();
let m = layer(&s, l).masks().unwrap().groups().next().unwrap().uid;
s.execute("path.rotoBezier", json!({"layer": l, "mask": m, "value": true})).unwrap();
let (rect, _) = first_shape(&s, l);
s.state.selected_vertices.clear();
s.state.selected_props.clear();
// An already-Bezier path: the rectangle converted first, the mask left as it is.
if item == "path" {
s.execute("path.convertToBezier", json!({"layer": l, "items": [rect]})).unwrap();
assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. }));
}
let uid = shape_item(&s, l, item);
s.state.selected_vertices.clear();
s.state.selected_props = if mask_selected { vec![(LayerId(l), m)] } else { Vec::new() };
let before = layer(&s, l).props;
let err = s.execute("path.convertToBezier", json!({"layer": l, "items": [uid]})).unwrap_err().to_string();
assert!(err.contains("Rectangle, Ellipse or Polystar"), "{item}, mask selected {mask_selected}: {err}");
assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. }), "{item}, mask selected {mask_selected}: the mask is unchanged");
assert!(layer(&s, l).props == before, "{item}, mask selected {mask_selected}: no shape or mask changed");
}
}
}
/// #3057 review: an explicit `layer` scopes the mask conversion too: a RotoBezier mask selected
/// on another layer is left alone, and the given layer's masks convert.
#[test]
fn convert_to_bezier_keeps_masks_to_an_explicit_layer() {
let mut s = comp();
let (a, _) = masked(&mut s);
let (b, mb) = masked(&mut s);
for l in [a, b] {
s.state.selected_props.clear();
s.state.selected_vertices.clear();
s.execute("path.rotoBezier", json!({"layer": l, "value": true})).unwrap();
}
assert!(matches!(mask_kind(&s, a), GroupKind::Mask { roto_bezier: true, .. }));
assert!(matches!(mask_kind(&s, b), GroupKind::Mask { roto_bezier: true, .. }));
s.state.selected_vertices.clear();
s.state.selected_props = vec![(LayerId(b), mb)];
let out = s.execute("path.convertToBezier", json!({"layer": a})).unwrap();
assert_eq!(out["masks"].as_u64(), Some(1), "{out}");
assert!(matches!(mask_kind(&s, a), GroupKind::Mask { roto_bezier: false, .. }), "the given layer's mask converts");
assert!(matches!(mask_kind(&s, b), GroupKind::Mask { roto_bezier: true, .. }), "the mask selected on another layer does not");
}
/// #3057 review: a RotoBezier mask on a locked layer stays as it is, given as the layer or
/// selected, and removing it as a target does not hand the conversion to another layer's mask.
#[test]
fn convert_to_bezier_leaves_a_locked_layers_masks_alone() {
let mut s = comp();
let (a, ma) = masked(&mut s);
let (b, _) = masked(&mut s);
for l in [a, b] {
s.state.selected_props.clear();
s.state.selected_vertices.clear();
s.execute("path.rotoBezier", json!({"layer": l, "value": true})).unwrap();
}
s.execute("layer.setSwitch", json!({"layers": [a], "switch": "locked", "value": true})).unwrap();
let roto = |s: &Session, l: u64| matches!(mask_kind(s, l), GroupKind::Mask { roto_bezier: true, .. });
// The locked layer given explicitly.
s.state.selected_props.clear();
s.state.selected_vertices.clear();
let err = s.execute("path.convertToBezier", json!({"layer": a})).unwrap_err().to_string();
assert!(err.contains("locked"), "{err}");
assert!(roto(&s, a), "the locked layer's mask stays RotoBezier");
// Its mask selected, with the unlocked layer in scope too: B's mask is not converted instead.
s.state.selected_props = vec![(LayerId(a), ma)];
let err = s.execute("path.convertToBezier", json!({"layers": [a, b]})).unwrap_err().to_string();
assert!(err.contains("locked"), "{err}");
assert!(roto(&s, a) && roto(&s, b), "neither mask converts");
}
/// #3057 review: an explicit `comp` that is not the active composition is where `items` and
/// `mask` are looked up and converted.
#[test]
fn convert_to_bezier_in_a_composition_that_is_not_active() {
let mut s = comp();
let main = s.active_comp_id().unwrap();
let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap();
let (rect, _) = first_shape(&s, l);
let (solid, m) = masked(&mut s);
s.state.selected_props.clear();
s.state.selected_vertices.clear();
s.execute("path.rotoBezier", json!({"layer": solid, "value": true})).unwrap();
s.execute("comp.new", json!({"name": "Other", "width": 400, "height": 300, "frameRate": 30, "duration": 4})).unwrap();
assert_ne!(s.active_comp_id(), Some(main), "another composition is active");
let in_main = |s: &Session| s.project.comp(main).unwrap().clone();
let main_mask_roto = |s: &Session| {
let c = in_main(s);
matches!(c.layer(LayerId(solid)).unwrap().masks().unwrap().find_group(m).unwrap().kind, GroupKind::Mask { roto_bezier: true, .. })
};
// Explicit shape items.
let out = s.execute("path.convertToBezier", json!({"comp": main.0, "layer": l, "items": [rect]})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
let c = in_main(&s);
let contents = c.layer(LayerId(l)).unwrap().props.sub("contents").unwrap();
assert!(contents.find_group(rect).is_none(), "the rectangle is replaced in that composition");
// An explicit mask.
assert!(main_mask_roto(&s));
s.execute("path.convertToBezier", json!({"comp": main.0, "layer": solid, "mask": m})).unwrap();
assert!(!main_mask_roto(&s), "the mask converts in that composition");
}
/// #3057: parametric paths in nested groups convert from the layer and from the outer group.
#[test]
fn convert_to_bezier_finds_paths_in_nested_groups() {
for select_outer in [false, true] {
let mut s = comp();
let l = s.execute("layer.newShape", json!({"kind": "star", "size": [120, 120]})).unwrap()["layer"].as_u64().unwrap();
let inner = shape_item(&s, l, "group");
s.state.selected_props = vec![(LayerId(l), inner)];
s.execute("path.groupShapes", json!({})).unwrap();
let outer = shape_item(&s, l, "group");
assert_ne!(outer, inner, "the shape is nested one group deeper");
if select_outer {
s.state.selected_props = vec![(LayerId(l), outer)];
} else {
s.execute("layer.select", json!({"layers": [l]})).unwrap();
}
let out = s.execute("path.convertToBezier", json!({})).unwrap();
assert_eq!(out["paths"].as_u64(), Some(1), "{out}");
assert_eq!(first_shape(&s, l).1, "path");
}
}
/// #2201: a viewer drag on the free-transform box sends one `path.freeTransform` per frame with a
/// shared merge key; one undo must revert the whole drag, not the last frame.
#[test]
+1
View File
@@ -18,6 +18,7 @@ craft-video = { workspace = true }
craft-audio = { workspace = true }
craft-media = { workspace = true }
craft-gif = { workspace = true }
craft-tga = { workspace = true }
craft-exr = { workspace = true, features = ["decode"] }
image = { workspace = true, features = ["png", "jpeg", "tiff", "exr", "tga"] }
rayon = { workspace = true }
+10 -3
View File
@@ -413,9 +413,16 @@ fn write_still<W: std::io::Write + std::io::Seek>(cx: &Cx, file: &mut W, img: &I
};
match fmt {
OutputFormat::PngSequence => image::codecs::png::PngEncoder::new(file).write_image(&data, w, h, ct),
// Uncompressed (the encoder's run-length compression is off), top-left origin, the
// alpha bits in the image descriptor: 8 for RGB + Alpha, 0 otherwise.
OutputFormat::TargaSequence => image::codecs::tga::TgaEncoder::new(file).disable_rle().write_image(&data, w, h, ct),
// The shared footerless writer: uncompressed, top-left origin, the alpha bits in the
// image descriptor: 8 for RGB + Alpha, 0 otherwise.
OutputFormat::TargaSequence => {
let layout = match channels {
Channels::Rgba => craft_tga::Layout::Rgba,
Channels::Alpha => craft_tga::Layout::Gray,
Channels::Rgb => craft_tga::Layout::Rgb,
};
return craft_tga::write_top_left_raw(file, w, h, layout, &data).map_err(|e| ExportError::Encode(e.to_string()));
}
// (the TIFF encoder needs Seek)
_ => image::codecs::tiff::TiffEncoder::new(file).write_image(&data, w, h, ct),
}
+29 -10
View File
@@ -126,7 +126,19 @@ fn check_frame(img: &Image, k: u64, tol: f32) {
assert!(near([c[0], c[1], c[2]], want, tol), "frame {k} centre {c:?} want {want:?}");
}
fn decode_movie(path: &Path, frames: u64, tol: f32) -> effectcraft_project::Footage {
/// Write to the test process's stderr, not libtest's buffered per-test capture: nextest can
/// then show the last stage even when it has to terminate a stuck process.
fn prores_stage(trace: bool, stage: std::fmt::Arguments<'_>) {
use std::io::Write as _;
if trace {
let mut stderr = std::io::stderr().lock();
let _ = writeln!(stderr, "ProRes MOV roundtrip: {stage}").and_then(|()| stderr.flush());
}
}
fn decode_movie(path: &Path, frames: u64, tol: f32, trace: bool) -> effectcraft_project::Footage {
prores_stage(trace, format_args!("native probe"));
let f = effectcraft_media::probe(path).expect("probe our output");
assert_eq!((f.width, f.height), (W, H));
assert!(f.has_video);
@@ -134,6 +146,7 @@ fn decode_movie(path: &Path, frames: u64, tol: f32) -> effectcraft_project::Foot
assert_eq!(n as u64, frames, "frame count from duration {:?} @ {:?}", f.duration, f.frame_rate);
let pool = MediaPool::new();
for k in 0..frames {
prores_stage(trace, format_args!("native decode frame {k}"));
let img = pool.frame_at(&f, f.frame_rate.tick_of(k as i64)).expect("decode");
check_frame(&img, k, tol);
}
@@ -153,8 +166,9 @@ fn ffprobe(path: &Path) -> Option<String> {
}
/// Frame `k` decoded by ffmpeg (external oracle) as RGBA, or `None` without ffmpeg.
fn ffmpeg_frame(path: &Path, k: u64) -> Option<Image> {
fn ffmpeg_frame(path: &Path, k: u64, trace: bool) -> Option<Image> {
let png = path.with_extension(format!("ffmpeg-{k}.png"));
prores_stage(trace, format_args!("FFmpeg decode frame {k}"));
let st = Command::new("ffmpeg")
.args(["-hide_banner", "-loglevel", "error", "-y", "-i"])
.arg(path)
@@ -163,13 +177,14 @@ fn ffmpeg_frame(path: &Path, k: u64) -> Option<Image> {
.status()
.ok()?;
assert!(st.success(), "ffmpeg failed to decode {}", path.display());
prores_stage(trace, format_args!("read FFmpeg oracle PNG for frame {k}"));
let img = image::open(&png).expect("ffmpeg png").to_rgba8();
Some(Image::from_rgba8(img.width(), img.height(), img.as_raw()))
}
fn ffmpeg_check(path: &Path, tol: f32) {
fn ffmpeg_check(path: &Path, tol: f32, trace: bool) {
for k in [0, 4, 5, FRAMES - 1] {
match ffmpeg_frame(path, k) {
match ffmpeg_frame(path, k, trace) {
Some(img) => check_frame(&img, k, tol),
None => {
eprintln!("ffmpeg not found: skipping oracle decode");
@@ -187,8 +202,8 @@ fn h264_mp4_roundtrip() {
let path = d.join("comp.mp4");
let r = run(&p, cid, &NoFootage, &om, &path);
assert!(r.bytes > 100 && !r.audio);
decode_movie(&path, FRAMES, 0.08);
ffmpeg_check(&path, 0.08);
decode_movie(&path, FRAMES, 0.08, false);
ffmpeg_check(&path, 0.08, false);
if let Some(s) = ffprobe(&path) {
assert!(s.contains("h264|64|48|yuv420p"), "{s}");
assert!(s.lines().next().unwrap_or("").ends_with("|12"), "{s}");
@@ -223,17 +238,21 @@ fn h264_odd_size_is_cropped_even() {
#[test]
fn prores_mov_roundtrip() {
prores_stage(true, format_args!("fixture setup"));
let d = out_dir("prores");
let (p, cid) = project(None);
let om = OutputModule::for_format(OutputFormat::ProRes);
let path = d.join("comp.mov");
prores_stage(true, format_args!("native export"));
run(&p, cid, &NoFootage, &om, &path);
decode_movie(&path, FRAMES, 0.03);
ffmpeg_check(&path, 0.03);
decode_movie(&path, FRAMES, 0.03, true);
ffmpeg_check(&path, 0.03, true);
prores_stage(true, format_args!("ffprobe metadata"));
if let Some(s) = ffprobe(&path) {
assert!(s.starts_with("prores|64|48"), "{s}");
assert!(s.lines().next().unwrap_or("").ends_with("|12"), "{s}");
}
prores_stage(true, format_args!("complete"));
}
#[test]
@@ -758,12 +777,12 @@ fn webm_vp9_opus_roundtrip() {
let r = run(&p, cid, &pool, &om, &path);
assert!(r.audio && r.bytes > 200, "{r:?}");
// Decoded back through FilmCraft (Matroska demuxer, VP9 and Opus decoders).
let f = decode_movie(&path, FRAMES, 0.08);
let f = decode_movie(&path, FRAMES, 0.08, false);
assert!(f.has_audio);
let s = MediaPool::new().audio_samples(&f, Tick::from_seconds_f64(0.3), 24_000, 48_000);
let l = rms(s.iter().step_by(2).copied());
assert!((l - 0.3536).abs() < 0.06, "left RMS {l}");
ffmpeg_check(&path, 0.08);
ffmpeg_check(&path, 0.08, false);
if let Some(s) = ffprobe(&path) {
assert!(s.contains("vp9|64|48|yuv420p"), "{s}");
assert!(s.contains("opus"), "{s}");
+8 -4
View File
@@ -469,8 +469,10 @@ impl<'a> Resolver<'a> {
Req::PropInfo { comp, layer, path } => {
let (l, p) = self.prop(*comp, *layer, path)?;
let dims = prop_dims(l, p);
let times = p.keys.iter().map(|k| Resp::Num(l.comp_time(k.time).seconds())).collect();
let values = p.keys.iter().map(|k| value_resp(&k.value, dims)).collect();
let ctx = self.ctx_at(*comp, self.ctx.time.seconds())?;
let effective = ctx.effective_property(l, p);
let times = effective.keys.iter().map(|k| Resp::Num(l.comp_time(k.time).seconds())).collect();
let values = effective.keys.iter().map(|k| value_resp(&k.value, dims)).collect();
let index = path.rsplit('/').next().and_then(|last| {
let parent = path.rsplit_once('/').map(|(g, _)| g);
let g = match parent {
@@ -497,13 +499,15 @@ impl<'a> Resolver<'a> {
Req::Value { comp, layer, path, t, pre } => {
let (l, p) = self.prop(*comp, *layer, path)?;
let t = f64::from_bits(*t);
let v = if *pre { p.value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { self.ctx_at(*comp, t)?.value(l, p) };
let ctx = self.ctx_at(*comp, t)?;
let v = if *pre { ctx.effective_property(l, p).value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { ctx.value(l, p) };
value_resp(&v, prop_dims(l, p))
}
Req::Doc { comp, layer, path, t, pre } => {
let (l, p) = self.prop(*comp, *layer, path)?;
let t = f64::from_bits(*t);
let v = if *pre { p.value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { self.ctx_at(*comp, t)?.value(l, p) };
let ctx = self.ctx_at(*comp, t)?;
let v = if *pre { ctx.effective_property(l, p).value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { ctx.value(l, p) };
match v {
Value::Text(d) => Resp::Str(doc_json(&d)),
Value::Str(s) => Resp::Str(doc_json(&effectcraft_keyframe::TextDoc::plain(&s))),
+69
View File
@@ -1974,6 +1974,75 @@ fn a_layer_parameters_own_expression_reads_its_layer() {
}
}
#[test]
fn a_collapsed_essential_override_is_the_history_an_expression_reads() {
use effectcraft_project::essential::{self, EgControl, EgKind, EssentialGraphics};
use effectcraft_project::{Expression, GroupKind};
let mut p = Project::default();
let mut inner = Comp::new(64, 32, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
let mut target = solid(&mut p, &inner, "Target", [1.0, 1.0, 1.0], 64, 32);
let opacity = target.props.prop_mut(OPA).unwrap();
opacity.keys = vec![Keyframe::new(secs(0.0), Value::Scalar(0.0)), Keyframe::new(secs(1.0), Value::Scalar(100.0))];
opacity.expr = Some(Expression {
text: "thisProperty.valueAtTime(0) + thisProperty.numKeys + thisProperty.key(1).value + thisProperty.nearestKey(0.9).value".into(),
enabled: true,
});
let target_id = target.id;
let opacity_id = opacity.uid;
inner.layers = vec![target].into();
inner.essential = Some(EssentialGraphics {
controls: vec![EgControl {
id: 1,
name: "Opacity".into(),
kind: EgKind::Property { layer: target_id, prop: opacity_id, links: vec![] },
as_type: None,
}],
..Default::default()
});
let inner_id = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into()));
let mut outer = Comp::new(64, 32, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
let mut instance = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: inner_id }, (64, 32), None);
let mut next = p.next_id;
let mut ids = Ids(&mut next);
let mut control = ids.prop(&essential::match_id(1), "Opacity", Value::Scalar(20.0));
control.keys = vec![Keyframe::new(secs(0.0), Value::Scalar(20.0)), Keyframe::new(secs(1.0), Value::Scalar(80.0))];
let mut group = ids.group(essential::GROUP, "Essential Properties");
group.kind = GroupKind::Essential { overridden: vec![control.uid] };
group.children.push(control.into());
instance.props.children.push(group.into());
p.next_id = next;
instance.switches.collapse = true;
outer.layers = vec![instance].into();
let outer_id = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.into()));
// The flattened path replaces the target property's keys with the instance override's.
let ctx = EvalCtx::new(&p, outer_id, p.comp(outer_id).unwrap(), secs(0.25));
let outer_layer = &ctx.comp.layers[0];
let overrides = effectcraft_render::essential_overrides(&ctx, outer_layer);
let flat = essential::with_overrides(&p, inner_id, &overrides).unwrap();
let mut flat_ctx = EvalCtx::new(&flat, inner_id, flat.comp(inner_id).unwrap(), secs(0.25));
flat_ctx.expr = Some(&Expressions);
let flat_target = flat_ctx.comp.layer(target_id).unwrap();
let flat_value = flat_ctx.value(flat_target, flat_target.props.prop(OPA).unwrap()).as_f64();
// The collapsed path carries the same history in its override. An expression on the target
// reads that effective history, just as it does on the flattened path.
let mut r = Renderer::new(&p, &NoFootage, RenderOpts::default());
r.expr = Some(&Expressions);
let mut collapsed_ctx = EvalCtx::new(&p, outer_id, p.comp(outer_id).unwrap(), secs(0.25));
collapsed_ctx.expr = Some(&Expressions);
let outer_layer = &collapsed_ctx.comp.layers[0];
let collapsed = r.collapsed(&collapsed_ctx, outer_layer).expect("the precomp collapses");
let (_, nested_ctx) = r.collapse_into(&collapsed_ctx, outer_layer, &collapsed, 1.0).unwrap();
let nested_target = nested_ctx.comp.layer(target_id).unwrap();
let collapsed_value = nested_ctx.value(nested_target, nested_target.props.prop(OPA).unwrap()).as_f64();
assert_close!(flat_value, 122.0);
assert_close!(collapsed_value, flat_value);
}
#[test]
fn time_to_frames_rounds_durations_away_from_zero() {
let f = fx();
+60 -4
View File
@@ -37,16 +37,29 @@ pub(crate) const IDS: &[&str] = &[
/// Largest LUT the kernels take (floats in the storage buffer); bigger ones render on the CPU.
const MAX_FLOATS: usize = 1 << 24;
/// Most halvings the kernel's partition searches run (`fxl_search_steps` caps the count there).
const SHADER_MAX_STEPS: u32 = 32;
/// Halvings a partition search over `n` entries runs: `n`'s bit length, which every search
/// finishes within, plus one to spare.
const fn search_steps(n: usize) -> u32 {
usize::BITS - n.leading_zeros() + 1
}
// A program's tables fit in MAX_FLOATS floats, so none needs more halvings than the kernel runs.
const _: () = assert!(search_steps(MAX_FLOATS) <= SHADER_MAX_STEPS);
/// Run effect `id` (one of [`IDS`]); `None` = this parameter combination runs on the CPU.
pub(crate) fn apply(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
let (ops, straight) = effectcraft_effects::color_program(id, ctx)?;
if ops.is_empty() {
return Some(b);
}
let data = encode(&ops)?;
let (data, steps) = encode(&ops)?;
let buf = e.data(&data);
let mut p = Params::default();
p.u[0][0] = (straight == Straight::Divide) as u32;
p.u[0][1] = steps;
let out = e.scratch(b.img.width, b.img.height);
e.pixels("fxl_point", &p, &b.img, None, &out, Some(&buf));
Some(GBuf { img: out, ..b })
@@ -79,11 +92,13 @@ pub(crate) fn push_lut(d: &mut Vec<f32>, lut: &Lut) -> f32 {
at
}
/// Program layout: a stream of (opcode, arguments…) ending in 0, followed by LUT data.
fn encode(ops: &[ColorOp]) -> Option<Vec<f32>> {
/// Program layout: a stream of (opcode, arguments…) ending in 0, followed by LUT data; and the
/// halvings the kernel's partition searches need for this program's tables.
fn encode(ops: &[ColorOp]) -> Option<(Vec<f32>, u32)> {
if ops.len() > MAX_OPS {
return None;
}
let mut steps = 0;
let mut prog: Vec<f32> = vec![];
let mut tables: Vec<Vec<f32>> = vec![];
// LUT offsets are patched once the program's length is known.
@@ -142,6 +157,13 @@ fn encode(ops: &[ColorOp]) -> Option<Vec<f32>> {
prog.extend(lo.iter().chain(hi));
}
ColorOp::Lut { lut, shaper, interp, inverse } => {
// The kernel searches an inverted 1D table and every shaper channel.
if *inverse && lut.n3 == 0 {
steps = steps.max(search_steps(lut.n1));
}
for channel in shaper.iter().flat_map(|s| s.iter()) {
steps = steps.max(search_steps(channel.len()));
}
prog.extend([8.0, 0.0, *interp as f32, *inverse as u32 as f32, -1.0]);
let mut t = vec![];
push_lut(&mut t, lut);
@@ -179,5 +201,39 @@ fn encode(ops: &[ColorOp]) -> Option<Vec<f32>> {
for t in tables {
prog.extend(t);
}
Some(prog)
Some((prog, steps))
}
#[cfg(test)]
mod tests {
use super::*;
/// The kernel's partition search (fxl_shape, fxl_inv_1d) run for `steps` halvings over the
/// sorted table 0, 1, …, n - 1: the index of the first entry not below `x`.
fn search(n: usize, steps: u32, x: f64) -> usize {
let (mut lo, mut hi) = (0, n);
for _ in 0..steps {
if lo < hi {
let mid = lo + (hi - lo) / 2;
if (mid as f64) < x {
lo = mid + 1;
} else {
hi = mid;
}
}
}
lo
}
#[test]
fn search_steps_finish_every_partition_search() {
for n in [1, 2, 3, 4, 5, 255, 256, 257, 1 << 16, (1 << 16) + 1, MAX_FLOATS / 3, MAX_FLOATS] {
let steps = search_steps(n);
assert!(steps <= SHADER_MAX_STEPS, "{n} entries need more halvings than the kernel runs");
for x in [-1.0, 0.0, 0.5, n as f64 / 3.0 + 0.5, n as f64 - 1.5, n as f64 - 0.5, n as f64 + 1.0] {
let want = (x.ceil().max(0.0) as usize).min(n);
assert_eq!(search(n, steps, x), want, "{n} entries, target {x}");
}
}
}
}
+57 -12
View File
@@ -5,7 +5,7 @@
use std::sync::{Mutex, OnceLock};
use effectcraft_effects::psim::{ParticleSystem, SimParticle, SimRequest};
use effectcraft_effects::psim::{ParticleSystem, SimParticle, SimRequest, producer_prefixes};
use crate::context::GpuContext;
@@ -25,6 +25,8 @@ struct Checkpoint {
n: u32,
/// The birth steps of its particles (see [`born`]).
born: u64,
/// Fingerprint of the producer history that reached this checkpoint.
producer: u64,
buf: wgpu::Buffer,
used: u64,
}
@@ -74,6 +76,7 @@ fn pipes(g: &GpuContext) -> &Pipes {
buffer(1, wgpu::BufferBindingType::Storage { read_only: true }),
buffer(2, wgpu::BufferBindingType::Storage { read_only: true }),
buffer(3, wgpu::BufferBindingType::Storage { read_only: false }),
buffer(4, wgpu::BufferBindingType::Storage { read_only: true }),
],
});
let layout = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
@@ -93,6 +96,18 @@ fn pipes(g: &GpuContext) -> &Pipes {
})
}
/// Producer positions packed for the shader's `vec4<f32>` storage buffer.
fn packed_producers(producers: &[[f32; 3]]) -> Vec<u8> {
let mut out = Vec::new();
for position in producers {
out.extend_from_slice(&position[0].to_le_bytes());
out.extend_from_slice(&position[1].to_le_bytes());
out.extend_from_slice(&position[2].to_le_bytes());
out.extend_from_slice(&0.0f32.to_le_bytes());
}
out
}
/// The shader's parameter block.
fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec<u8> {
let dt = (1.0 / effectcraft_effects::psim::SPS) as f32;
@@ -103,8 +118,7 @@ fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec<u8> {
ParticleSystem::Engine(e) => {
u2 = [e.anim, e.flat as u32, e.seed, prev_n];
f[0] = [e.life, e.speed, e.extra, e.cone];
f[1] = [e.producer[0], e.producer[1], e.producer[2], 0.0];
f[2] = [e.radius[0], e.radius[1], e.radius[2], 0.0];
f[1] = [e.radius[0], e.radius[1], e.radius[2], 0.0];
f[3] = [e.gravity[0], e.gravity[1], e.gravity[2], 0.0];
f[4] = [e.axis[0], e.axis[1], e.axis[2], 0.0];
f[5] = [e.damp, dt, 0.0, 0.0];
@@ -112,9 +126,9 @@ fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec<u8> {
ParticleSystem::Cannon(c) => {
u[3] = 1;
u2 = [0, 1, c.seed, prev_n];
f[0] = [c.pos[0], c.pos[1], c.barrel_angle, c.barrel_radius];
f[1] = [c.dir_spread, c.vel, c.vel_spread, c.grav_spread];
f[2] = [c.gravity[0], c.gravity[1], dt, 0.0];
f[0] = [c.barrel_angle, c.barrel_radius, c.dir_spread, c.vel];
f[1] = [c.vel_spread, c.grav_spread, dt, 0.0];
f[2] = [c.gravity[0], c.gravity[1], 0.0, 0.0];
f[3] = c.bounds;
}
}
@@ -141,10 +155,24 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimPartic
if !g.can_readback() || req.steps > u32::MAX as u64 {
return None;
}
let n = req.births.len() as u32;
let n = u32::try_from(req.births.len()).ok()?;
if n == 0 {
return Some(vec![]);
}
let steps = usize::try_from(req.steps).ok()?;
if steps == 0 {
return None;
}
if req.producers.len() < steps {
return None;
}
// Check the storage-buffer size before allocating the history fingerprint or its bytes.
let producer_size = steps.checked_mul(16)?;
if u64::try_from(producer_size).ok()? > g.device.limits().max_storage_buffer_binding_size {
return None;
}
let producers = &req.producers[..steps];
let producer_prefix = producer_prefixes(producers);
let deferred = g.deferred.clone();
let key = deferred.as_ref().map(|_| sim_key(req));
if let (Some(d), Some(k)) = (&deferred, key) {
@@ -167,7 +195,17 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimPartic
let mut c = g.particle_states.lock().ok()?;
c.clock += 1;
let now = c.clock;
match c.list.iter_mut().filter(|k| k.key == req.key && k.steps <= req.steps && born(req.births, k.steps) == (k.n, k.born)).max_by_key(|k| k.steps) {
match c
.list
.iter_mut()
.filter(|k| {
k.key == req.key
&& k.steps <= req.steps
&& born(req.births, k.steps) == (k.n, k.born)
&& producer_prefix.get(k.steps as usize) == Some(&k.producer)
})
.max_by_key(|k| k.steps)
{
Some(k) => {
k.used = now;
(k.steps, Some(k.buf.clone()), k.n)
@@ -178,6 +216,8 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimPartic
let d = &g.device;
let births: Vec<u8> = req.births.iter().flat_map(|b| b.to_le_bytes()).collect();
let births = g.buffer_init(Some("births"), &births, wgpu::BufferUsages::STORAGE);
let producer_bytes = packed_producers(producers);
let producers = g.buffer_init(Some("particle producers"), &producer_bytes, wgpu::BufferUsages::STORAGE);
let prev = prev.unwrap_or_else(|| {
d.create_buffer(&wgpu::BufferDescriptor { label: Some("particles"), size: STATE_BYTES, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false })
});
@@ -196,6 +236,7 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimPartic
wgpu::BindGroupEntry { binding: 1, resource: births.as_entire_binding() },
wgpu::BindGroupEntry { binding: 2, resource: prev.as_entire_binding() },
wgpu::BindGroupEntry { binding: 3, resource: next.as_entire_binding() },
wgpu::BindGroupEntry { binding: 4, resource: producers.as_entire_binding() },
],
});
let read = d.create_buffer(&wgpu::BufferDescriptor {
@@ -221,14 +262,14 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimPartic
g.map_readback(&read, row, row, 1, move |r| done(r.map_err(|e| log::error!("gpu particle readback: {e}")).ok()));
#[cfg(not(target_arch = "wasm32"))]
let _ = g.poll_readbacks(wgpu::PollType::Poll);
keep_checkpoint(g, req, n, next);
keep_checkpoint(g, req, n, next, &producer_prefix);
d.miss();
return Some(vec![]);
}
let row = usize::try_from(size).ok()?;
let bytes = g.read_buffer(&read, row, row, 1).map_err(|e| log::error!("gpu particle readback: {e}")).ok()?;
let parts = parse(&bytes);
keep_checkpoint(g, req, n, next);
keep_checkpoint(g, req, n, next, &producer_prefix);
Some(parts)
}
@@ -239,6 +280,9 @@ fn sim_key(req: &SimRequest) -> u128 {
k.u64(req.steps);
k.u64(req.births.len() as u64);
k.bytes(&req.births.iter().flat_map(|b| b.to_le_bytes()).collect::<Vec<u8>>());
let producer_count = usize::try_from(req.steps).ok().and_then(|steps| req.producers.get(..steps)).map_or(0, |producers| producers.len());
k.u64(producer_count as u64);
k.bytes(&packed_producers(req.producers.get(..producer_count).unwrap_or(&[])));
k.debug(&req.system);
k.finish()
}
@@ -256,12 +300,13 @@ fn parse(bytes: &[u8]) -> Vec<SimParticle> {
}
/// Keep a simulated state on the GPU as a checkpoint (the oldest go beyond the limit).
fn keep_checkpoint(g: &GpuContext, req: &SimRequest, n: u32, next: wgpu::Buffer) {
fn keep_checkpoint(g: &GpuContext, req: &SimRequest, n: u32, next: wgpu::Buffer, producer_prefix: &[u64]) {
if let Ok(mut c) = g.particle_states.lock() {
let now = c.clock;
c.list.retain(|k| !(k.key == req.key && k.steps == req.steps));
let (_, h) = born(req.births, req.steps);
c.list.push(Checkpoint { key: req.key, steps: req.steps, n, born: h, buf: next, used: now });
let producer = producer_prefix.get(req.steps as usize).copied().unwrap_or(0);
c.list.push(Checkpoint { key: req.key, steps: req.steps, n, born: h, producer, buf: next, used: now });
while c.list.len() > CHECKPOINTS {
let Some(i) = c.list.iter().enumerate().min_by_key(|(_, k)| k.used).map(|(i, _)| i) else { break };
c.list.remove(i);
+31 -14
View File
@@ -120,6 +120,14 @@ fn mix_exact(a: vec3<f32>, b: vec3<f32>, t: f32) -> vec3<f32> {
return a + (b - a) * t;
}
// Halvings for the partition searches (fxl_shape, fxl_inv_1d): written per dispatch by fx_lut.rs
// (enough for the largest table the program searches) and capped here. Every invocation runs the
// same count, so the loops stay bounded and non-divergent, but because the count isn't known when
// the shader is compiled, a software driver doesn't unroll every search into the kernel.
fn fxl_search_steps() -> u32 {
return min(P.u[0].y, 32u);
}
// ocio::shape over `n` (x, y) points at `at` (`flip`: the curve with x and y swapped).
fn fxl_shape(at: u32, n: u32, x: f32, flip: bool) -> f32 {
if (n < 2u) {
@@ -130,8 +138,8 @@ fn fxl_shape(at: u32, n: u32, x: f32, flip: bool) -> f32 {
// partition_point(|p| p.x < x).
var lo = 0u;
var hi = n;
// Bound the partition search as for inverse 1D LUTs below.
for (var step = 0u; step < 32u; step++) {
// Bounded as for inverse 1D LUTs below.
for (var step = 0u; step < fxl_search_steps(); step++) {
if (lo < hi) {
let mid = lo + (hi - lo) / 2u;
if (data[at + mid * 2u + kx] < x) {
@@ -161,14 +169,17 @@ fn fxl_shaper_at(s: u32, k: u32) -> vec2<u32> {
// Evaluate independent shaper channels without dynamically writing vector lanes.
fn fxl_shaper_apply(sh: u32, c: vec3<f32>, flip: bool) -> vec3<f32> {
let r = fxl_shaper_at(sh, 0u);
let g = fxl_shaper_at(sh, 1u);
let b = fxl_shaper_at(sh, 2u);
return vec3<f32>(
fxl_shape(r.x, r.y, c.x, flip),
fxl_shape(g.x, g.y, c.y, flip),
fxl_shape(b.x, b.y, c.z, flip)
);
// One search per kernel instead of three: a software driver unrolls each fixed-length
// search, so every extra call multiplies compile time. Lanes are read and written with
// select(), never by a dynamic index.
var r = c;
for (var k = 0u; k < 3u; k++) {
let lane = vec3<bool>(k == 0u, k == 1u, k == 2u);
let a = fxl_shaper_at(sh, k);
let v = fxl_shape(a.x, a.y, select(select(c.z, c.y, k == 1u), c.x, k == 0u), flip);
r = select(r, vec3<f32>(v), lane);
}
return r;
}
fn fxl_file_fwd(o: u32, sh: i32, c0: vec3<f32>, interp: u32) -> vec3<f32> {
@@ -188,9 +199,10 @@ fn fxl_inv_1d(o: u32, i: u32, y: f32) -> f32 {
// partition_point over the table's values.
var lo = 0u;
var hi = n;
// A u32 interval needs at most 32 halvings. A fixed trip count avoids
// a divergent data-dependent loop on software Vulkan without changing lookup.
for (var step = 0u; step < 32u; step++) {
// fxl_search_steps() halvings cover every table this program searches. A trip count shared
// by every invocation avoids a divergent data-dependent loop on software Vulkan without
// changing lookup.
for (var step = 0u; step < fxl_search_steps(); step++) {
if (lo < hi) {
let mid = lo + (hi - lo) / 2u;
if (data[b1 + mid * 3u + i] < y) {
@@ -218,7 +230,12 @@ fn fxl_file(o: u32, sh: i32, c: vec3<f32>, interp: u32, inverse: bool) -> vec3<f
if (n3 == 0u) {
var x = c;
if (n1 > 1u) {
x = vec3<f32>(fxl_inv_1d(o, 0u, c.x), fxl_inv_1d(o, 1u, c.y), fxl_inv_1d(o, 2u, c.z));
// One search call for all three channels, as in fxl_shaper_apply.
for (var k = 0u; k < 3u; k++) {
let lane = vec3<bool>(k == 0u, k == 1u, k == 2u);
let v = fxl_inv_1d(o, k, select(select(c.z, c.y, k == 1u), c.x, k == 0u));
x = select(x, vec3<f32>(v), lane);
}
}
if (sh >= 0) {
x = fxl_shaper_apply(u32(sh), x, true);
+22 -20
View File
@@ -9,10 +9,10 @@ struct PSim {
u: vec4<u32>,
// Animation, flat, seed, particles in `prev`.
u2: vec4<u32>,
// Engine: f[0] = (life, speed, extra, cone), f[1] = producer, f[2] = radius,
// f[3] = gravity, f[4] = axis, f[5] = (damp, dt).
// Cannon: f[0] = (pos.x, pos.y, barrel angle, barrel radius), f[1] = (dir spread, vel,
// vel spread, grav spread), f[2] = (gravity.x, gravity.y, dt), f[3] = bounds.
// Engine: f[0] = (life, speed, extra, cone), f[1] = radius, f[3] = gravity,
// f[4] = axis, f[5] = (damp, dt).
// Cannon: f[0] = (barrel angle, barrel radius, dir spread, vel), f[1] = (vel spread,
// grav spread, dt), f[2] = (gravity.x, gravity.y), f[3] = bounds.
f: array<vec4<f32>, 6>,
}
@@ -29,6 +29,8 @@ struct PState {
@group(1) @binding(1) var<storage, read> births: array<u32>;
@group(1) @binding(2) var<storage, read> prev: array<PState>;
@group(1) @binding(3) var<storage, read_write> next: array<PState>;
// Producer position at each simulated step, in the system's own coordinates.
@group(1) @binding(4) var<storage, read> producers: array<vec4<f32>>;
const PS_TAU: f32 = 6.2831855;
@@ -70,11 +72,11 @@ struct Part {
}
// sim::Phys::spawn (+ the step's sub-step birth offset).
fn ps_spawn_engine(id: u32) -> Part {
fn ps_spawn_engine(id: u32, birth: u32) -> Part {
let flat = S.u2.y != 0u;
let anim = S.u2.x;
let producer = S.f[1].xyz;
let radius = S.f[2].xyz;
let producer = producers[birth].xyz;
let radius = S.f[1].xyz;
let u = ps_rand_dir(id, 1u, flat);
var e = 1.0 / 3.0;
if (flat) {
@@ -129,7 +131,7 @@ fn ps_step_engine(q: Part, j: u32) -> Part {
let seed = S.u2.z;
let dt = S.f[5].y;
let t = f32(j) * dt;
let producer = S.f[1].xyz;
let producer = producers[j].xyz;
let gravity = S.f[3].xyz;
let extra = S.f[0].z;
var a = gravity;
@@ -181,13 +183,13 @@ fn ps_step_engine(q: Part, j: u32) -> Part {
}
// sim3::Pg::spawn (+ the sub-step birth offset).
fn ps_spawn_cannon(id: u32) -> Part {
let pos = S.f[0].xy;
let angle = S.f[0].z;
let r = S.f[0].w;
let spread = S.f[1].x;
let vel = S.f[1].y;
let vel_spread = S.f[1].z;
fn ps_spawn_cannon(id: u32, birth: u32) -> Part {
let pos = producers[birth].xy;
let angle = S.f[0].x;
let r = S.f[0].y;
let spread = S.f[0].z;
let vel = S.f[0].w;
let vel_spread = S.f[1].x;
let a = radians(angle + ps_hs(id, 1u) * spread * 0.5);
let d = vec2<f32>(sin_p(a), -cos_p(a));
let speed = max(vel + ps_hs(id, 3u) * vel_spread, 0.0);
@@ -200,7 +202,7 @@ fn ps_spawn_cannon(id: u32) -> Part {
off = vec2<f32>(cos_p(aa) * rr, sin_p(aa) * rr);
}
let v = d * speed;
let dt = S.f[2].z;
let dt = S.f[1].z;
let frac = ps_h(id, 9u) * dt;
let p = pos + off + v * frac;
return Part(vec3<f32>(p, 0.0), vec3<f32>(v, 0.0), 0.0, 0.0, 0.0);
@@ -208,8 +210,8 @@ fn ps_spawn_cannon(id: u32) -> Part {
// sim3::Pg::step for one particle (gravity only); returns false when it leaves the bounds.
fn ps_step_cannon(q: ptr<function, Part>, id: u32) -> bool {
let dt = S.f[2].z;
let spread = S.f[1].w;
let dt = S.f[1].z;
let spread = S.f[1].y;
var g = 1.0;
if (spread > 0.0) {
g = 1.0 + (ps_h(id, 7u) * 2.0 - 1.0) * spread;
@@ -245,9 +247,9 @@ fn particles(@builtin(global_invocation_id) gid: vec3<u32>) {
j = s0;
} else {
if (cannon) {
q = ps_spawn_cannon(id);
q = ps_spawn_cannon(id, b);
} else {
q = ps_spawn_engine(id);
q = ps_spawn_engine(id, b);
}
j = b + 1u;
}
+41
View File
@@ -3,6 +3,7 @@
//! passes; and the job loops' pass driver (`effectcraft_render::passes`) settles natively.
use effectcraft_effects::EffectCtx;
use effectcraft_effects::psim::{EngineDesc, ParticleSim, ParticleSystem, SimRequest};
use effectcraft_project::BitDepth;
use effectcraft_render::three_d::adv;
use effectcraft_render::{Accelerator, Backend, LayerCache, NoFootage, RenderOpts, Renderer};
@@ -47,6 +48,46 @@ fn particles_resolve_in_passes() {
}
}
/// The deferred readback key includes the producer history: a request with a different history
/// starts its own readback instead of returning the previous history's particles.
#[test]
fn particle_producer_history_is_part_of_the_deferred_key() {
let Some((g, _lock)) = deferred_gpu() else { return };
let system = ParticleSystem::Engine(EngineDesc {
life: 10.0,
radius: [0.0; 3],
anim: 0,
speed: 0.0,
gravity: [0.0; 3],
axis: [0.0, -1.0, 0.0],
extra: 0.0,
cone: 0.0,
damp: 1.0,
seed: 51,
flat: true,
});
let births = [0u32];
let first_producers = [[10.0, 0.0, 0.0]];
let first = SimRequest { key: 0x1955_0def, steps: 1, births: &births, producers: &first_producers, system };
g.frame_begin();
g.pass_begin();
assert!(g.simulate(&first).unwrap().is_empty() && g.pass_missed(), "the first readback starts");
settle(g);
g.pass_begin();
let ready = g.simulate(&first).unwrap();
assert!(!ready.is_empty() && !g.pass_missed(), "the first readback is ready");
assert!((ready[0].p[0] - 10.0).abs() < 1e-4, "{:?}", ready[0].p);
let changed_producers = [[99.0, 0.0, 0.0]];
let changed = SimRequest { key: first.key, steps: 1, births: &births, producers: &changed_producers, system };
g.pass_begin();
assert!(g.simulate(&changed).unwrap().is_empty() && g.pass_missed(), "the producer history was not part of the deferred key");
settle(g);
g.pass_begin();
let changed = g.simulate(&changed).unwrap();
assert!(!changed.is_empty() && (changed[0].p[0] - 99.0).abs() < 1e-4, "{:?}", changed[0].p);
}
#[test]
fn advanced_3d_resolves_in_passes() {
let Some((g, _lock)) = deferred_gpu() else { return };
+139 -1
View File
@@ -3,7 +3,7 @@
//! ids) at positions within tolerance, from scratch and when advancing / seeking from GPU
//! checkpoints.
use effectcraft_effects::psim::{ParticleSim, SimParticle};
use effectcraft_effects::psim::{EngineDesc, ParticleSim, ParticleSystem, SimParticle, SimRequest};
use effectcraft_effects::{EffectCtx, EffectEnv, EffectHost, LayerPixels, Params};
use effectcraft_keyframe::Value;
@@ -24,6 +24,39 @@ impl EffectHost for Host {
}
}
/// A host whose producer moves from `start_x` at layer time 0 to `start_x + 60 · t`.
struct MovingProducer {
gpu: Option<&'static Gpu>,
index: usize,
start_x: f64,
}
impl EffectHost for MovingProducer {
fn layer(&self, _id: u64, _masks_and_effects: bool) -> Option<LayerPixels> {
None
}
fn audio(&self, _id: u64, _start: f64, _frames: usize, _rate: u32) -> Option<Vec<f32>> {
None
}
fn particles(&self) -> Option<&dyn ParticleSim> {
self.gpu.map(|g| g as &dyn ParticleSim)
}
fn param_at(&self, effect_index: usize, id: &str, t: f64) -> Option<Value> {
if effect_index != self.index {
return None;
}
let x = self.start_x + 60.0 * t;
match id {
"producer/position" | "producer" => Some(Value::Vec2([x, 50.0])),
"producer/producerX" => Some(n(x)),
"producer/producerY" => Some(n(50.0)),
"producer/producerZ" => Some(n(0.0)),
"cannon/cannonPosition" => Some(Value::Vec2([x, 50.0])),
_ => None,
}
}
}
pub(crate) fn params(id: &str, vals: &[(&str, Value)]) -> Params {
let spec = effectcraft_effects::find(id).unwrap();
let size = [320.0, 240.0];
@@ -179,6 +212,111 @@ fn particle_systems_ii_matches_the_cpu() {
}
}
/// #1955: a moving producer is sampled at every simulation step on both the CPU and the GPU.
#[test]
fn moving_producers_match_the_cpu_on_the_gpu() {
let Some(g) = gpu() else { return };
for id in ["ec.sim.ccparticleworld", "ec.sim.ccparticlesystems2"] {
let p = if id == "ec.sim.ccparticleworld" {
params(
id,
&[
("birthRate", n(2.0)),
("longevity", n(5.0)),
("producer/producerX", n(80.0)),
("producer/producerY", n(50.0)),
("producer/producerZ", n(0.0)),
("producer/radiusX", n(0.0)),
("producer/radiusY", n(0.0)),
("producer/radiusZ", n(0.0)),
("physics/animation", Value::Enum(4)),
("physics/velocity", n(0.0)),
("physics/gravity", n(0.0)),
],
)
} else {
params(
id,
&[
("birthRate", n(2.0)),
("longevity", n(5.0)),
("producer/position", Value::Vec2([80.0, 50.0])),
("producer/radiusX", n(0.0)),
("producer/radiusY", n(0.0)),
("physics/animation", Value::Enum(5)),
("physics/velocity", n(0.0)),
("physics/gravity", n(0.0)),
],
)
};
let cpu_host = MovingProducer { gpu: None, index: 0, start_x: 20.0 };
let gpu_host = MovingProducer { gpu: Some(g), index: 0, start_x: 20.0 };
let ctx = |env| EffectCtx { params: &p, time: 1.0, layer_size: [320.0, 240.0], seed: 31, adjustment: false, env };
let cpu = effectcraft_effects::particle_state(id, &ctx(EffectEnv { host: Some(&cpu_host), ..Default::default() })).unwrap();
let before = crate::particles::DISPATCHES.load(std::sync::atomic::Ordering::Relaxed);
let gpu = effectcraft_effects::particle_state(id, &ctx(EffectEnv { host: Some(&gpu_host), ..Default::default() })).unwrap();
assert!(crate::particles::DISPATCHES.load(std::sync::atomic::Ordering::Relaxed) > before, "{id}: simulated on the GPU");
agree(&format!("{id} moving producer"), &cpu, &gpu, 1e-4, cpu.len() / 100 + 1);
}
let p = params(
"ec.sim.particleplayground",
&[
("cannonEnabled", Value::Bool(true)),
("grid/particlesAcross", n(0.0)),
("grid/particlesDown", n(0.0)),
("cannon/barrelRadius", n(0.0)),
("cannon/particlesPerSecond", n(60.0)),
("cannon/velocity", n(0.0)),
("cannon/velocityRandomSpread", n(0.0)),
("gravity/gravityForce", n(0.0)),
],
);
let cpu_host = MovingProducer { gpu: None, index: 0, start_x: 20.0 };
let gpu_host = MovingProducer { gpu: Some(g), index: 0, start_x: 20.0 };
let ctx = |env| EffectCtx { params: &p, time: 1.0, layer_size: [320.0, 240.0], seed: 32, adjustment: false, env };
let cpu = effectcraft_effects::playground_state(&ctx(EffectEnv { host: Some(&cpu_host), ..Default::default() })).unwrap();
let before = crate::particles::DISPATCHES.load(std::sync::atomic::Ordering::Relaxed);
let gpu = effectcraft_effects::playground_state(&ctx(EffectEnv { host: Some(&gpu_host), ..Default::default() })).unwrap();
assert!(crate::particles::DISPATCHES.load(std::sync::atomic::Ordering::Relaxed) > before, "particle playground: simulated on the GPU");
agree("particle playground moving producer", &cpu, &gpu, 1e-4, cpu.len() / 100 + 1);
let births = effectcraft_effects::psim::births(60.0, 60, 60_000).unwrap();
for q in &gpu {
let birth = births[q.id as usize] as f32;
assert!((q.p[0] - (20.0 + birth)).abs() < 1e-4, "particle {} at {:?}, expected {}", q.id, q.p, 20.0 + birth);
}
}
/// A checkpoint reached with one producer history is not reused for another history, even
/// when the current producer position and the system's key are unchanged.
#[test]
fn a_changed_gpu_producer_history_drops_a_stale_checkpoint() {
let Some(g) = gpu() else { return };
let system = ParticleSystem::Engine(EngineDesc {
life: 10.0,
radius: [0.0; 3],
anim: 0,
speed: 0.0,
gravity: [0.0; 3],
axis: [0.0, -1.0, 0.0],
extra: 0.0,
cone: 0.0,
damp: 1.0,
seed: 41,
flat: true,
});
let births_one = [0u32];
let producers_one = [[10.0, 0.0, 0.0]];
let first = g.simulate(&SimRequest { key: 0x1955, steps: 1, births: &births_one, producers: &producers_one, system }).unwrap();
assert!((first[0].p[0] - 10.0).abs() < 1e-4, "{:?}", first[0].p);
let births_two = [0u32, 1u32];
let producers_two = [[99.0, 0.0, 0.0], [20.0, 0.0, 0.0]];
let second = g.simulate(&SimRequest { key: 0x1955, steps: 2, births: &births_two, producers: &producers_two, system }).unwrap();
assert!((second[0].p[0] - 99.0).abs() < 1e-4, "the old checkpoint was reused: {:?}", second[0].p);
assert!((second[1].p[0] - 20.0).abs() < 1e-4, "{:?}", second[1].p);
}
#[test]
fn playground_cannon_matches_the_cpu_and_checkpoints_reuse() {
let Some(g) = gpu() else { return };
+8 -4
View File
@@ -27,13 +27,13 @@ craft-dpx = { workspace = true }
craft-exr = { workspace = true, features = ["decode"] }
craft-gif = { workspace = true, features = ["frames"] }
craft-webp = { workspace = true, features = ["frames"] }
craft-audio = { workspace = true, features = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode"] }
craft-audio = { workspace = true, features = ["decode-native", "aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode", "flac-decode"] }
craft-color = { workspace = true }
craft-frame = { workspace = true }
craft-media = { workspace = true, features = ["mpegts"] }
craft-media-source = { workspace = true }
craft-media = { workspace = true, features = ["mpegts", "avi", "mxf"] }
craft-media-source = { workspace = true, features = ["y4m"] }
craft-time = { workspace = true }
craft-video = { workspace = true, features = ["h264-decode", "threads"] }
craft-video = { workspace = true, features = ["h264-decode", "hevc-decode", "vp9-decode", "vp8-decode", "av1-decode", "prores", "dnx", "mpeg2-decode", "ffv1", "apv-decode", "threads"] }
filmcraft-frame = { workspace = true }
filmcraft-color = { workspace = true }
filmcraft-time = { workspace = true }
@@ -52,3 +52,7 @@ gif = { workspace = true }
tempfile = { workspace = true }
# (tests render comps that read layers through effects; already a dependency of effectcraft-render)
effectcraft-effects = { workspace = true }
# Pure-Rust AAC and FLAC fixture encoding.
craft-audio = { workspace = true, features = ["aac-encode", "flac-encode"] }
# APV import parity fixtures use the existing shared encoder.
craft-video = { workspace = true, features = ["apv-encode"] }
+8 -8
View File
@@ -7,7 +7,7 @@
use std::io;
use craft_audio::aac::AudioSpecificConfig;
use filmcraft_media::ByteReader;
use craft_media::ByteSource;
/// How far into an MPEG TS / PS file the audio streams are looked for: the stream is indexed as
/// far as this, not through the whole file.
@@ -16,7 +16,7 @@ const MPEG_HEAD: u64 = 8 << 20;
/// The configuration of the audio track FilmCraft plays, if it is AAC: from an MP4 / MOV `header`
/// (its ftyp and moov, or the whole file) and `file`, or else from `file`, read as Matroska or
/// MPEG TS / PS.
pub(crate) fn config(header: Option<&[u8]>, file: Option<&dyn ByteReader>) -> Option<AudioSpecificConfig> {
pub(crate) fn config(header: Option<&[u8]>, file: Option<&dyn ByteSource>) -> Option<AudioSpecificConfig> {
let asc = match header.and_then(|h| mp4(h, file)) {
Some(asc) => asc,
None => {
@@ -32,7 +32,7 @@ pub(crate) fn config(header: Option<&[u8]>, file: Option<&dyn ByteReader>) -> Op
/// The track FilmCraft's MP4 source plays: the first audio track with samples, a sample
/// description and a timescale, read from the whole file as it is (a fragmented movie's samples
/// are in its fragments, not the `moov`).
fn mp4(header: &[u8], file: Option<&dyn ByteReader>) -> Option<Vec<u8>> {
fn mp4(header: &[u8], file: Option<&dyn ByteSource>) -> Option<Vec<u8>> {
let mp4 = match file {
Some(f) => craft_media::isobmff::open(Head(f, f.len())),
None => craft_media::isobmff::open(header),
@@ -50,7 +50,7 @@ fn mp4(header: &[u8], file: Option<&dyn ByteReader>) -> Option<Vec<u8>> {
/// The track FilmCraft's Matroska source plays: the first audio track with frames, found by
/// indexing the clusters as that source does.
fn matroska(file: &dyn ByteReader) -> Option<Vec<u8>> {
fn matroska(file: &dyn ByteSource) -> Option<Vec<u8>> {
let mkv = craft_media::matroska::open(Head(file, file.len())).ok()?;
match &mkv.tracks.iter().find(|t| t.kind == craft_media::matroska::TrackKind::Audio && !t.samples.is_empty())?.codec {
craft_media::matroska::Codec::Aac { asc } => Some(asc.clone()),
@@ -61,12 +61,12 @@ fn matroska(file: &dyn ByteReader) -> Option<Vec<u8>> {
/// The configuration of the stream FilmCraft's MPEG source plays: the first audio stream whose
/// first unit it can read. Only AAC is asked about, so the streams before that one were refused
/// whatever their codec, and an ADTS stream played has no configuration outside its frames.
fn latm(file: &dyn ByteReader) -> Option<Vec<u8>> {
fn latm(file: &dyn ByteSource) -> Option<Vec<u8>> {
use craft_media::mpegts::{self, Codec};
let head = Head(file, file.len().min(MPEG_HEAD));
let mpeg = mpegts::open(&head).ok()?;
let audio = mpeg.streams.iter().enumerate().filter(|(_, s)| s.kind() == mpegts::Kind::Audio && !s.units.is_empty());
let played = audio.take(filmcraft_media::MAX_AUDIO_STREAMS).find_map(|(i, s)| {
let played = audio.take(craft_media_source::MAX_AUDIO_STREAMS).find_map(|(i, s)| {
let first = mpeg.read_unit(&head, i, 0).ok()?;
match s.codec {
Codec::AacAdts => mpegts::frame_info(&s.codec, &first).map(|_| None),
@@ -77,8 +77,8 @@ fn latm(file: &dyn ByteReader) -> Option<Vec<u8>> {
played?
}
/// The first `.1` bytes of a file, as the byte source FilmCraft's demuxers read.
struct Head<'a>(&'a dyn ByteReader, u64);
/// The first `.1` bytes available to the AAC container scan.
struct Head<'a>(&'a dyn ByteSource, u64);
impl Head<'_> {
fn read(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+15 -19
View File
@@ -137,7 +137,7 @@ impl<'a> From<&'a crate::stream::DecodedFrame> for FrameView<'a> {
/// Convert a FilmCraft frame to an [`Image`].
#[cfg(test)]
pub(crate) fn frame_to_image(f: &VideoFrame, op: AlphaOp) -> Image {
pub(crate) fn frame_to_image<'a>(f: impl Into<FrameView<'a>>, op: AlphaOp) -> Image {
frame_to_image_in(f, op, Vec::new())
}
@@ -533,25 +533,28 @@ pub(crate) fn straight_to_image(w: u32, h: u32, px: &[[f32; 4]], op: AlphaOp) ->
#[cfg(test)]
mod tests {
use super::*;
use craft_color::ColorInfo;
use craft_frame::{Chroma, PixelData, VideoFrame};
use craft_time::Tick;
use std::sync::Arc;
fn yuv_frame(y: u8, u: u8, v: u8, color: filmcraft_color::ColorInfo) -> VideoFrame {
fn yuv_frame(y: u8, u: u8, v: u8, color: ColorInfo) -> VideoFrame {
VideoFrame {
width: 4,
height: 2,
data: PixelData::Yuv8 { planes: [Arc::new(vec![y; 8]), Arc::new(vec![u; 2]), Arc::new(vec![v; 2])], chroma: Chroma::C420, alpha: None },
color,
par: (1, 1),
pts: filmcraft_time::Tick::ZERO,
pts: Tick::ZERO,
}
}
#[test]
fn limited_range_grey_and_white() {
let op = AlphaOp::new(AlphaMode::Straight, [0.0; 3]);
let img = frame_to_image(&yuv_frame(235, 128, 128, filmcraft_color::ColorInfo::REC709), op);
let img = frame_to_image(&yuv_frame(235, 128, 128, ColorInfo::REC709), op);
assert!(img.data.iter().all(|p| (p[0] - 1.0).abs() < 1e-5 && (p[1] - 1.0).abs() < 1e-5 && p[3] == 1.0));
let img = frame_to_image(&yuv_frame(126, 128, 128, filmcraft_color::ColorInfo::REC709), op);
let img = frame_to_image(&yuv_frame(126, 128, 128, ColorInfo::REC709), op);
assert!((img.data[0][0] - 110.0 / 219.0).abs() < 1e-5);
}
@@ -568,9 +571,9 @@ mod tests {
chroma: Chroma::C420,
alpha: None,
},
color: filmcraft_color::ColorInfo::REC709,
color: ColorInfo::REC709,
par: (1, 1),
pts: filmcraft_time::Tick::ZERO,
pts: Tick::ZERO,
}
}
@@ -588,7 +591,7 @@ mod tests {
// More than half the size, odd sizes, other chroma layouts: convert the full frame.
assert!(frame_to_image_scaled(&f, 49, 32).is_none());
assert!(frame_to_image_scaled(&smooth_420(95, 64), 40, 30).is_none());
assert!(frame_to_image_scaled(&yuv_frame(100, 128, 128, filmcraft_color::ColorInfo::REC709), 2, 1).is_some());
assert!(frame_to_image_scaled(&yuv_frame(100, 128, 128, ColorInfo::REC709), 2, 1).is_some());
let mut f444 = smooth_420(96, 64);
if let PixelData::Yuv8 { chroma, .. } = &mut f444.data {
*chroma = Chroma::C444;
@@ -600,7 +603,7 @@ mod tests {
fn bt709_red() {
// 8-bit limited BT.709 red: Y 63, Cb 102, Cr 240
let op = AlphaOp::new(AlphaMode::Straight, [0.0; 3]);
let p = frame_to_image(&yuv_frame(63, 102, 240, filmcraft_color::ColorInfo::REC709), op).data[0];
let p = frame_to_image(&yuv_frame(63, 102, 240, ColorInfo::REC709), op).data[0];
assert!(p[0] > 0.98 && p[1] < 0.02 && p[2] < 0.02, "{p:?}");
}
@@ -631,14 +634,7 @@ mod tests {
fn rgba8_levels_are_the_quantised_float_frame() {
let (w, h) = (37usize, 18usize);
let noise = |n: usize, seed: usize| Arc::new((0..n).map(|i| ((i * 7919 + seed * 104_729) % 256) as u8).collect::<Vec<u8>>());
let frame = |data| VideoFrame {
width: w as u32,
height: h as u32,
data,
color: filmcraft_color::ColorInfo::REC709,
par: (1, 1),
pts: filmcraft_time::Tick::ZERO,
};
let frame = |data| VideoFrame { width: w as u32, height: h as u32, data, color: ColorInfo::REC709, par: (1, 1), pts: Tick::ZERO };
let yuv = |chroma: Chroma, alpha: bool| {
let n = w.div_ceil(1 << chroma.shifts().0) * h.div_ceil(1 << chroma.shifts().1);
frame(PixelData::Yuv8 { planes: [noise(w * h, 1), noise(n, 2), noise(n, 3)], chroma, alpha: alpha.then(|| noise(w * h, 4)) })
@@ -675,9 +671,9 @@ mod tests {
chroma: Chroma::C420,
alpha: None,
},
color: filmcraft_color::ColorInfo::REC709,
color: ColorInfo::REC709,
par: (1, 1),
pts: filmcraft_time::Tick::ZERO,
pts: Tick::ZERO,
};
let op = AlphaOp::new(AlphaMode::Straight, [0.0; 3]);
for _ in 0..3 {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,116 @@
use std::io::Cursor;
use std::sync::Arc;
use craft_audio::flac::{Encoder, EncoderConfig, STREAMINFO_OFFSET};
use craft_media::{isobmff, matroska};
use craft_media_source::MediaKind;
use crate::stream::{self, MediaSource as OpenedSource};
const RATE: u32 = 96_000;
const BLOCK: usize = 1_000;
const FRAMES: usize = 196 * BLOCK + 221;
const COLD_SEEK: usize = 2 * RATE as usize + BLOCK + 200;
struct Fixture {
private: Vec<u8>,
packets: Vec<Vec<u8>>,
samples: Vec<Vec<i32>>,
}
impl Fixture {
fn new() -> Result<Self, Box<dyn std::error::Error>> {
let left: Vec<i32> = (0..FRAMES).map(|i| (i as i32 * 307 % 65_536) - 30_000).collect();
let right: Vec<i32> = (0..FRAMES).map(|i| 28_000 - (i as i32 * 701 % 59_000)).collect();
let mut config = EncoderConfig::new(RATE, 2, 24);
config.block_size = BLOCK as u16;
let mut encoder = Encoder::new(config)?;
let mut packets = encoder.encode_frames(&[&left, &right])?;
packets.push(encoder.finish());
let mut private = encoder.header(&[]);
let offset = STREAMINFO_OFFSET as usize;
private[offset..offset + 34].copy_from_slice(&encoder.streaminfo());
Ok(Self { private, packets, samples: vec![left, right] })
}
fn mp4(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let offset = STREAMINFO_OFFSET as usize;
let mut entry = isobmff::SampleEntry::flac(self.private[offset..offset + 34].try_into()?);
entry.audio.as_mut().ok_or("FLAC sample entry needs an audio header")?.sample_rate = 48_000.0;
let mut writer = isobmff::Mp4Writer::new(Cursor::new(Vec::new()), isobmff::WriterOptions::new(isobmff::Brand::Mp4))?;
writer.add_track(isobmff::TrackConfig::new(entry, RATE))?;
for (i, packet) in self.packets.iter().enumerate() {
let duration = (FRAMES - i * BLOCK).min(BLOCK) as u32;
writer.write_sample(0, isobmff::WriteSample { data: packet, duration, composition_offset: 0, is_sync: true })?;
}
Ok(writer.finish()?.into_inner())
}
fn mkv(&self, private: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_FLAC");
track.audio = Some((f64::from(RATE), 2, Some(24)));
track.codec_private = private.to_vec();
let mut writer = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default())?;
for (i, packet) in self.packets.iter().enumerate() {
// The muxer rounds starts to its millisecond clock. A 1000-frame packet
// at 96 kHz does not start on a millisecond boundary after packet zero.
let pts = (i * BLOCK) as i64 * 1_000_000_000 / i64::from(RATE);
let duration = (FRAMES - i * BLOCK).min(BLOCK) as u64 * 1_000_000_000 / u64::from(RATE);
writer.write_frame(0, pts, true, packet, Some(duration))?;
}
Ok(writer.finish()?.into_inner())
}
}
#[test]
fn flac_in_mp4_and_matroska_uses_shared_samples_after_cold_and_backward_seeks() -> Result<(), Box<dyn std::error::Error>> {
let fixture = Fixture::new()?;
let dir = tempfile::tempdir().unwrap();
for (name, bytes) in [("audio.mp4", fixture.mp4()?), ("audio.mka", fixture.mkv(&fixture.private)?)] {
let bytes: Arc<[u8]> = bytes.into();
let path = dir.path().join(name);
std::fs::write(&path, &bytes).unwrap();
let disk = stream::open_source(&path).unwrap().0.unwrap();
let memory = stream::open_bytes(name, bytes).unwrap();
for opened in [disk, memory] {
let OpenedSource::Craft(source) = opened else { panic!("{name}: expected the shared FLAC reader") };
let info = source.info();
assert_eq!(info.kind, MediaKind::AudioOnly);
let audio = info.audio().unwrap();
assert_eq!((audio.codec.as_str(), audio.sample_rate, audio.channels, audio.bits_per_sample), ("FLAC", RATE, 2, Some(24)));
for (start, frames) in [(COLD_SEEK, 48), (991, 33), (FRAMES - 25, 50), (0, FRAMES)] {
let decoded = source.audio(start as i64, frames, RATE).unwrap();
assert_eq!((decoded.num_channels(), decoded.frames()), (2, frames));
for (actual, expected) in decoded.channels.iter().zip(&fixture.samples) {
for (i, &sample) in actual.iter().enumerate() {
let want = expected.get(start + i).copied().unwrap_or(0) as f32 / 8_388_608.0;
assert_eq!(sample, want, "{name} sample {}", start + i);
}
}
}
let whole = source.audio(451, 93, 44_100).unwrap();
let first = source.audio(451, 31, 44_100).unwrap();
let second = source.audio(482, 62, 44_100).unwrap();
for ((whole, first), second) in whole.channels.iter().zip(&first.channels).zip(&second.channels) {
assert_eq!(&whole[..31], first, "{name} first resampled segment");
assert_eq!(&whole[31..], second, "{name} second resampled segment");
}
}
}
Ok(())
}
#[test]
fn flac_without_the_expected_private_marker_keeps_matroska_fallback() -> Result<(), Box<dyn std::error::Error>> {
let fixture = Fixture::new()?;
let mut private = fixture.private.clone();
private[..4].copy_from_slice(b"test");
let OpenedSource::Film(source) = stream::open_bytes("legacy.mka", fixture.mkv(&private)?.into()).unwrap() else {
panic!("expected the legacy FLAC reader");
};
let decoded = source.audio(0, 16, RATE).unwrap();
assert!(decoded.channels[0].iter().any(|&sample| sample != 0.0));
Ok(())
}
@@ -0,0 +1,49 @@
use super::*;
use crate::stream::{self, MediaSource as OpenedSource};
#[test]
fn shared_monochrome_av1_retains_luma_on_backward_seek() -> std::result::Result<(), Box<dyn std::error::Error>> {
let bytes: Arc<[u8]> = Arc::from(include_bytes!("../../tests/fixtures/monochrome-av1.mkv").as_slice());
let OpenedSource::Craft(source) = stream::open_bytes("monochrome-av1.mkv", bytes)? else {
panic!("expected the shared AV1 reader");
};
for i in [2u8, 0, 1] {
let pts = Tick::from_units(i64::from(i), 25);
let frame = source.video_frame(FrameRequest { time: pts, scale: 1.0 })?;
assert_eq!((frame.width, frame.height, frame.pts, frame.color.range), (16, 12, pts, Range::Full));
let PixelData::Yuv8 { planes: [y, cb, cr], chroma: Chroma::C420, alpha: None } = &frame.data else {
panic!("expected 8-bit luma with neutral chroma");
};
let expected: Vec<u8> = (0..12).flat_map(|row| (0..16).map(move |col| 16 + 64 * i + col + 2 * row)).collect();
assert_eq!(y.as_slice(), expected);
assert_eq!(cb.as_slice(), [128; 48]);
assert_eq!(cr.as_slice(), cb.as_slice());
let rgba = frame.to_rgba8()?;
for (pixel, &sample) in rgba.as_chunks::<4>().0.iter().zip(&expected) {
assert_eq!(*pixel, [sample, sample, sample, 255]);
}
}
Ok(())
}
#[test]
fn monochrome_10_bit_preserves_aperture_rotation_alpha_and_layout() -> std::result::Result<(), Box<dyn std::error::Error>> {
let y = Plane::packed(5, 5, 10, Samples::U16((64..89).collect()))?;
let alpha = Plane::packed(5, 5, 10, Samples::U16((900..925).collect()))?;
let mut decoded = DecodedVideoFrame::new(5, 5, ColorFamily::Gray, Subsampling::S444, vec![y], Some(alpha))?;
decoded.sar = Some((3, 2));
let aperture = isobmff::CleanAperture { width: (3, 1), height: (3, 1), horiz_offset: (0, 1), vert_offset: (0, 1) };
let presentation = FramePresentation { container_color: Some(ColorInfo::REC709), par: (1, 1), rotation: 1, aperture: Some(aperture) };
let pts = Tick::from_units(4, 25);
let frame = to_craft_frame(decoded, presentation, pts)?;
assert_eq!((frame.width, frame.height, frame.par, frame.pts), (3, 3, (2, 3), pts));
assert_eq!(frame.color, ColorInfo::REC709);
let PixelData::Yuv16 { planes: [y, cb, cr], chroma: Chroma::C420, bits: 10, alpha: Some(alpha) } = &frame.data else {
panic!("expected 10-bit luma and alpha");
};
assert_eq!(y.as_slice(), [80, 75, 70, 81, 76, 71, 82, 77, 72]);
assert_eq!(alpha.as_slice(), [916, 911, 906, 917, 912, 907, 918, 913, 908]);
assert_eq!(cb.as_slice(), [512; 4]);
assert_eq!(cr.as_slice(), cb.as_slice());
Ok(())
}
+96
View File
@@ -0,0 +1,96 @@
use std::sync::Arc;
use craft_color::ColorInfo;
use craft_frame::VideoFrame;
use craft_media::{ByteSource, avi};
use craft_media_source::{MediaError, Result, VideoStreamInfo};
use craft_time::{FrameRate, Tick};
use craft_video::raw_video::{self, RawFormat, RawPixels};
pub(super) struct RawAvi {
format: RawFormat,
width: u32,
height: u32,
bottom_up: bool,
payload_bytes: usize,
rate: FrameRate,
cached: Option<(usize, Arc<VideoFrame>)>,
}
impl RawAvi {
pub(super) fn new(stream: &avi::Stream) -> Option<Self> {
let bitmap = stream.video.as_ref()?;
let format = raw_video::RawFormat::from_avi(bitmap.compression, bitmap.bit_count)?;
if !matches!(format, RawFormat::Bgr24 | RawFormat::Bgrx32) || stream.start != 0 {
return None;
}
let width = u32::try_from(bitmap.width).ok()?;
let height = bitmap.height.unsigned_abs();
if !(1..=16_384).contains(&width) || !(1..=16_384).contains(&height) {
return None;
}
let stride = (u64::from(width) * u64::from(bitmap.bit_count / 8)).next_multiple_of(4);
let payload_bytes = stride * u64::from(height);
let decoded_bytes = u64::from(width) * u64::from(height) * 4;
// A request can hold its input and new picture while the old picture is cached.
if payload_bytes + 2 * decoded_bytes > craft_video::budget::DECODE_MEMORY_BUDGET {
return None;
}
// Empty AVI slots and partial chunks need the legacy reader's recovery policy.
if stream.chunks.iter().any(|chunk| u64::from(chunk.size) < payload_bytes) {
return None;
}
Some(Self {
format,
width,
height,
bottom_up: bitmap.height > 0,
payload_bytes: usize::try_from(payload_bytes).ok()?,
rate: FrameRate::new(i64::from(stream.rate), i64::from(stream.scale)),
cached: None,
})
}
pub(super) fn duration(&self, slots: usize) -> Tick {
self.rate.tick_of(i64::try_from(slots).unwrap_or(i64::MAX))
}
pub(super) fn info(&self, stream: &avi::Stream) -> VideoStreamInfo {
let bytes: u128 = stream.chunks.iter().map(|chunk| u128::from(chunk.size)).sum();
let bytes_per_slot = bytes as f64 / stream.chunks.len() as f64;
VideoStreamInfo {
width: self.width,
height: self.height,
frame_rate: self.rate,
par: (1, 1),
codec: self.format.label().to_string(),
pixel_format: String::new(),
color: ColorInfo::SRGB_FULL,
has_alpha: false,
bitrate: Some((bytes_per_slot * 8.0 * self.rate.as_f64()) as u64),
hdr: None,
}
}
pub(super) fn frame(&mut self, file: &avi::AviFile, source: &dyn ByteSource, stream: usize, index: usize) -> Result<Arc<VideoFrame>> {
if let Some((cached_index, frame)) = &self.cached
&& *cached_index == index
{
return Ok(frame.clone());
}
if filmcraft_media::cancel::cancelled() {
return Err(MediaError::Cancelled);
}
let packet = file.read_chunk_range(source, stream, index, 0, self.payload_bytes).map_err(|e| MediaError::Io(e.to_string()))?;
let pixels = raw_video::decode(self.format, self.width, self.height, self.bottom_up, &packet)
.map_err(|e| MediaError::Decode(format!("uncompressed AVI picture: {e:?}")))?;
let RawPixels::Rgba(pixels) = pixels else {
return Err(MediaError::Unsupported("unexpected uncompressed AVI pixel layout".into()));
};
let mut frame = VideoFrame::rgba8(self.width, self.height, pixels).map_err(|e| MediaError::Decode(e.to_string()))?;
frame.pts = self.rate.tick_of(i64::try_from(index).unwrap_or(i64::MAX));
let frame = Arc::new(frame);
self.cached = Some((index, frame.clone()));
Ok(frame)
}
}
@@ -0,0 +1,173 @@
use std::io::Cursor;
use std::sync::Arc;
use craft_color::ColorInfo;
use craft_frame::PixelData;
use craft_media::avi;
use craft_media_source::FrameRequest;
use craft_time::Tick;
use crate::stream::{self, MediaSource};
const WIDTH: u32 = 3;
const HEIGHT: u32 = 2;
const FPS: u32 = 25;
const AUDIO_RATE: u32 = 8_000;
const AUDIO_PER_FRAME: usize = (AUDIO_RATE / FPS) as usize;
fn rgba(frame: u8, x: u8, y: u8) -> [u8; 4] {
[16 + 30 * frame, 21 + 71 * y, 5 + 17 * x, 255]
}
fn bitmap(frame: u8, depth: u16, bottom_up: bool) -> Vec<u8> {
let stride = (WIDTH as usize * usize::from(depth / 8)).next_multiple_of(4);
let mut bytes = Vec::new();
for row in 0..HEIGHT as u8 {
let y = if bottom_up { HEIGHT as u8 - 1 - row } else { row };
for x in 0..WIDTH as u8 {
let [r, g, b, _] = rgba(frame, x, y);
bytes.extend([b, g, r]);
if depth == 32 {
bytes.push(43);
}
}
bytes.resize((usize::from(row) + 1) * stride, 111);
}
bytes
}
// Original in-memory fixture. The shared AVI muxer writes deterministic test pixels and PCM.
fn fixture(depth: u16, bottom_up: bool, sparse: bool) -> Result<Vec<u8>, avi::Error> {
let mut video = avi::VideoSpec::new([0; 4], WIDTH, HEIGHT, FPS, 1);
if !bottom_up {
video.format.height = -(HEIGHT as i32);
}
video.format.bit_count = depth;
video.format.size_image = bitmap(0, depth, bottom_up).len() as u32;
let audio = avi::AudioSpec::pcm(AUDIO_RATE, 1, 16);
let mut writer =
avi::AviWriter::new(Cursor::new(Vec::new()), vec![avi::StreamSpec::Video(video), avi::StreamSpec::Audio(audio)], avi::MuxOptions::default())?;
for i in 0..3u8 {
let picture = if sparse && i == 1 { Vec::new() } else { bitmap(i, depth, bottom_up) };
let sound = (1000 * (i16::from(i) + 1)).to_le_bytes().repeat(AUDIO_PER_FRAME);
writer.write_chunk(0, &picture, true)?;
writer.write_chunk(1, &sound, true)?;
}
Ok(writer.finish()?.into_inner())
}
#[test]
fn raw_rgb_avi_preserves_pixels_and_pcm_across_indexed_seeks() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempfile::tempdir()?;
for (name, depth, bottom_up) in [("bottom-up.avi", 24, true), ("top-down.avi", 32, false)] {
let bytes: Arc<[u8]> = fixture(depth, bottom_up, false)?.into();
let path = dir.path().join(name);
std::fs::write(&path, &bytes)?;
let disk = stream::open_source(&path).ok_or("unrecognized AVI")?.0?;
let memory = stream::open_bytes(name, bytes)?;
for opened in [disk, memory] {
let MediaSource::Craft(source) = opened else { panic!("{name}: expected shared raw AVI route") };
let info = source.info();
let video = info.video.as_ref().ok_or("missing video")?;
assert_eq!((video.width, video.height, video.has_alpha), (WIDTH, HEIGHT, false));
assert_eq!(video.codec, format!("Uncompressed RGB {depth}-bit"));
assert_eq!(info.duration, Tick::from_units(3, i64::from(FPS)));
for i in [2u8, 0, 1] {
let time = Tick::from_units(2 * i64::from(i) + 1, 2 * i64::from(FPS));
let frame = source.video_frame(FrameRequest { time, scale: 1.0 })?;
assert_eq!(frame.pts, Tick::from_units(i64::from(i), i64::from(FPS)));
assert_eq!((frame.par, frame.color), ((1, 1), ColorInfo::SRGB_FULL));
let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected 8-bit RGBA") };
let expected: Vec<u8> = (0..HEIGHT as u8).flat_map(|y| (0..WIDTH as u8).flat_map(move |x| rgba(i, x, y))).collect();
assert_eq!(pixels.as_slice(), expected);
}
let audio = source.audio(AUDIO_PER_FRAME as i64 - 2, 4, AUDIO_RATE)?;
assert_eq!(audio.channels, [vec![1000.0 / 32768.0, 1000.0 / 32768.0, 2000.0 / 32768.0, 2000.0 / 32768.0]]);
}
}
Ok(())
}
#[test]
fn raw_rgb_avi_with_dropped_slot_keeps_legacy_playback() -> Result<(), Box<dyn std::error::Error>> {
let opened = stream::open_bytes("sparse.avi", fixture(24, true, true)?.into())?;
let MediaSource::Film(source) = opened else { panic!("expected legacy AVI slot handling") };
let time = filmcraft_time::Tick::from_units(1, i64::from(FPS));
let frame = source.video_frame(filmcraft_media::FrameRequest { time, scale: 1.0 })?;
assert_eq!((frame.width, frame.height), (WIDTH, HEIGHT));
Ok(())
}
fn audio_header(bytes: &[u8]) -> Result<usize, &'static str> {
bytes.windows(12).position(|window| &window[..4] == b"strh" && &window[8..] == b"auds").map(|offset| offset + 8).ok_or("AVI audio stream header")
}
#[test]
fn delayed_avi_pcm_keeps_raw_rgb_and_reports_the_later_audio_end() -> Result<(), Box<dyn std::error::Error>> {
let mut bytes = fixture(24, true, false)?;
let at = audio_header(&bytes)?;
let delay = AUDIO_PER_FRAME as u32 + 13;
bytes[at + 28..at + 32].copy_from_slice(&delay.to_le_bytes()); // dwStart
bytes[at + 32..at + 36].copy_from_slice(&1u32.to_le_bytes()); // stale dwLength
let bytes: Arc<[u8]> = bytes.into();
let dir = tempfile::tempdir()?;
let path = dir.path().join("delayed-rgb.avi");
std::fs::write(&path, &bytes)?;
let end = Tick::from_units(i64::from(delay) + 3 * AUDIO_PER_FRAME as i64, i64::from(AUDIO_RATE));
for info in [crate::probe::probe(&path)?, crate::probe::probe_bytes("delayed-rgb.avi", bytes.clone())?] {
assert_eq!(info.duration.0, end.0);
assert!(info.has_audio && info.has_video);
}
let disk = stream::open_source(&path).ok_or("unrecognized AVI")?.0?;
let memory = stream::open_bytes("delayed-rgb.avi", bytes)?;
for opened in [disk, memory] {
let MediaSource::Craft(source) = opened else { panic!("delayed fixed-size PCM should stay on the shared RGB route") };
let frame = source.video_frame(FrameRequest { time: Tick::from_units(1, i64::from(FPS)), scale: 1.0 })?;
let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected RGBA picture") };
assert_eq!(&pixels[..4], &rgba(1, 0, 0));
let delay = i64::from(delay);
let after = source.audio(delay + AUDIO_PER_FRAME as i64, 2, AUDIO_RATE)?;
assert_eq!(after.channels[0], [2000.0 / 32768.0; 2]);
let first = source.audio(delay - 2, 4, AUDIO_RATE)?;
assert_eq!(first.channels[0], [0.0, 0.0, 1000.0 / 32768.0, 1000.0 / 32768.0]);
}
Ok(())
}
#[test]
fn delayed_avi_pcm_audio_only_uses_the_stream_clock_and_indexed_samples() -> Result<(), Box<dyn std::error::Error>> {
let audio = avi::StreamSpec::Audio(avi::AudioSpec::pcm(AUDIO_RATE, 1, 16));
let mut writer = avi::AviWriter::new(Cursor::new(Vec::new()), vec![audio], avi::MuxOptions::default())?;
writer.write_chunk(0, &8192i16.to_le_bytes().repeat(5), true)?;
writer.write_chunk(0, &16384i16.to_le_bytes().repeat(9), true)?;
let mut bytes = writer.finish()?.into_inner();
let at = audio_header(&bytes)?;
// This stream clock places dwStart at 4.8 native samples, truncated to 4.
bytes[at + 20..at + 24].copy_from_slice(&1u32.to_le_bytes());
bytes[at + 24..at + 28].copy_from_slice(&5000u32.to_le_bytes());
bytes[at + 28..at + 32].copy_from_slice(&3u32.to_le_bytes());
bytes[at + 32..at + 36].copy_from_slice(&200u32.to_le_bytes());
let bytes: Arc<[u8]> = bytes.into();
let opened = stream::open_bytes("delayed-pcm.avi", bytes.clone())?;
let MediaSource::Craft(source) = opened else { panic!("expected shared PCM reader") };
assert_eq!(source.audio(0, 6, AUDIO_RATE)?.channels[0], [0.0, 0.0, 0.0, 0.0, 0.25, 0.25]);
assert_eq!(source.audio(17, 2, AUDIO_RATE)?.channels[0], [0.5, 0.0]);
let info = crate::probe::probe_bytes("delayed-pcm.avi", bytes)?;
assert_eq!(info.duration.0, Tick::from_units(18, i64::from(AUDIO_RATE)).0);
Ok(())
}
#[test]
fn delayed_avi_pcm_with_conflicting_block_size_keeps_legacy_rgb_route() -> Result<(), Box<dyn std::error::Error>> {
let mut bytes = fixture(24, true, false)?;
let at = audio_header(&bytes)?;
bytes[at + 28..at + 32].copy_from_slice(&16u32.to_le_bytes());
bytes[at + 44..at + 48].copy_from_slice(&1u32.to_le_bytes()); // dwSampleSize
let opened = stream::open_bytes("delayed-pcm-block.avi", bytes.into())?;
let MediaSource::Film(source) = opened else { panic!("expected legacy PCM block alignment") };
assert_eq!(source.audio(15, 2, AUDIO_RATE)?.channels[0], [0.0, 1000.0 / 32768.0]);
Ok(())
}
@@ -0,0 +1,83 @@
use std::io::Cursor;
use craft_video::ffv1::{self, Colorspace, Encoder, EncoderConfig};
use super::*;
use crate::stream::{self, MediaSource as OpenedSource};
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
const WIDTH: u32 = 5;
const HEIGHT: u32 = 3;
fn rgba(frame: u8, x: u8, y: u8) -> [u8; 4] {
[15 + 55 * frame + x, 59 + 3 * y, 191 + x + y, 255]
}
#[test]
fn shared_ffv1_rgb8_keeps_opaque_pixels_across_backward_seek() -> TestResult {
let mut raw = ffv1::Frame { width: WIDTH, height: HEIGHT, colorspace: Colorspace::Rgb, bit_depth: 8, chroma_shift: (0, 0), planes: vec![Vec::new(); 3] };
let encoder = Encoder::new(&raw, EncoderConfig::default())?;
let mut track = matroska::TrackSpec::new(matroska::TrackKind::Video, "V_FFV1");
track.codec_private = encoder.config_record();
track.video_size = Some((WIDTH, HEIGHT));
track.default_duration_ns = Some(40_000_000);
let mut writer = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default())?;
// Original per-channel ramps, encoded and muxed in memory.
let mut expected = Vec::new();
for n in 0u8..3 {
let pixels: Vec<[u8; 4]> = (0..HEIGHT as u8).flat_map(|y| (0..WIDTH as u8).map(move |x| rgba(n, x, y))).collect();
for (c, plane) in raw.planes.iter_mut().enumerate() {
*plane = pixels.iter().map(|pixel| u16::from(pixel[c])).collect();
}
writer.write_frame(0, i64::from(n) * 40_000_000, true, &encoder.encode(&raw)?, Some(40_000_000))?;
expected.push(pixels.into_flattened());
}
let bytes = writer.finish()?.into_inner();
let OpenedSource::Craft(source) = stream::open_bytes("rgb-ffv1.mkv", bytes.into())? else {
panic!("expected the shared FFV1 reader");
};
for n in [2, 0, 1] {
let pts = Tick::from_units(n as i64, 25);
let frame = source.video_frame(FrameRequest { time: pts, scale: 1.0 })?;
assert_eq!((frame.width, frame.height, frame.pts, frame.color.range), (WIDTH, HEIGHT, pts, Range::Full));
let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected packed RGBA8") };
assert_eq!(pixels.as_slice(), expected[n]);
}
Ok(())
}
fn presentation() -> FramePresentation {
FramePresentation { container_color: Some(ColorInfo::SRGB_FULL), par: (1, 1), rotation: 0, aperture: None }
}
#[test]
fn packed_rgb_keeps_stride_aperture_rotation_and_straight_alpha() -> TestResult {
let make_plane = |base: u8| {
let samples: Vec<u8> = (0u8..3).flat_map(|y| [base + y * 4, base + y * 4 + 1, base + y * 4 + 2, 250]).collect();
Plane::new(3, 3, 4, 8, Samples::U8(samples))
};
let mut decoded =
DecodedVideoFrame::new(3, 3, ColorFamily::Rgb, Subsampling::S444, vec![make_plane(10)?, make_plane(30)?, make_plane(50)?], Some(make_plane(0)?))?;
decoded.sar = Some((3, 2));
let aperture = isobmff::CleanAperture { width: (1, 1), height: (3, 1), horiz_offset: (0, 1), vert_offset: (0, 1) };
let presentation = FramePresentation { aperture: Some(aperture), rotation: 1, ..presentation() };
let pts = Tick::from_units(4, 25);
let frame = to_craft_frame(decoded, presentation, pts)?;
assert_eq!((frame.width, frame.height, frame.par, frame.pts), (3, 1, (2, 3), pts));
assert_eq!(frame.color, ColorInfo::SRGB_FULL);
let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected packed RGBA8") };
assert_eq!(pixels.as_slice(), [19, 39, 59, 9, 15, 35, 55, 5, 11, 31, 51, 1]);
Ok(())
}
#[test]
fn limited_range_high_depth_rgb_remains_unsupported() -> TestResult {
let channel = Plane::packed(1, 1, 10, Samples::U16(vec![900]))?;
let decoded = DecodedVideoFrame::new(1, 1, ColorFamily::Rgb, Subsampling::S444, vec![channel; 3], None)?;
let color = ColorInfo { range: Range::Limited, ..ColorInfo::SRGB_FULL };
let presentation = FramePresentation { container_color: Some(color), ..presentation() };
assert!(matches!(to_craft_frame(decoded, presentation, Tick::ZERO), Err(MediaError::Unsupported(_))));
Ok(())
}
@@ -0,0 +1,225 @@
//! Standalone FLAC through the pinned shared decoder. The source retains bounded decoded PCM.
use std::sync::Arc;
use craft_audio::{AudioBuffer, flac};
use craft_frame::VideoFrame;
use craft_media_source::{AudioStreamInfo, DEFAULT_MAX_MEDIA_BYTES, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedSource};
#[cfg(any(unix, windows))]
use craft_media_source::{SharedBytes, read_range};
use craft_time::Tick;
use super::{resample_audio_with_phase, resampling_origin};
/// Preserve the previous reader's ceiling for an individual PCM request.
const MAX_AUDIO_REQUEST_BYTES: usize = 512 << 20;
fn looks_like_flac(name: &str, head: &[u8]) -> bool {
head.starts_with(b"fLaC")
|| head.starts_with(b"ID3") && std::path::Path::new(name).extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("flac"))
}
#[cfg(any(unix, windows))]
pub(super) fn open_reader(name: &str, head: &[u8], source: &SharedBytes) -> Option<SharedSource> {
if !looks_like_flac(name, head) {
return None;
}
let bytes = read_range(&**source, 0, usize::try_from(source.len()).ok()?).ok()?;
open_bytes(name, &bytes)
}
pub(super) fn open_bytes(name: &str, bytes: &[u8]) -> Option<SharedSource> {
if !looks_like_flac(name, bytes) || bytes.len() > DEFAULT_MAX_MEDIA_BYTES {
return None;
}
// Keep both the compressed and decoded inputs within the shared media buffer budget.
// Declining the file leaves the prior reader available, including its broader recovery.
let max_values = (DEFAULT_MAX_MEDIA_BYTES / std::mem::size_of::<i32>()) as u64;
let decoded = flac::decode_with_limit(bytes, max_values).ok()?;
let rate = decoded.info.sample_rate;
let frames = decoded.channels.first()?.len();
if frames == 0 || rate == 0 {
return None;
}
let scale = 2.0_f32.powi(1 - i32::from(decoded.info.bits_per_sample));
let samples = decoded.channels.into_iter().map(|plane| plane.into_iter().map(|sample| sample as f32 * scale).collect()).collect();
let info = MediaInfo {
name: name.into(),
kind: MediaKind::AudioOnly,
duration: Tick::from_units(i64::try_from(frames).ok()?, i64::from(rate)),
video: None,
audio_streams: vec![AudioStreamInfo {
sample_rate: rate,
channels: u32::from(decoded.info.channels),
codec: "FLAC".into(),
bits_per_sample: Some(u32::from(decoded.info.bits_per_sample)),
}],
container: "FLAC".into(),
start_timecode: None,
file_size: Some(bytes.len() as u64),
};
Some(Arc::new(FlacSource { info, rate, samples }))
}
struct FlacSource {
info: MediaInfo,
rate: u32,
samples: Vec<Vec<f32>>,
}
impl MediaSource for FlacSource {
fn info(&self) -> &MediaInfo {
&self.info
}
fn video_frame(&self, _req: FrameRequest) -> Result<Arc<VideoFrame>> {
Err(MediaError::NoStream("video"))
}
fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
if sample_rate == 0 {
return Err(MediaError::Decode("audio sample rate must be nonzero".into()));
}
if frames.checked_mul(self.samples.len()).and_then(|n| n.checked_mul(std::mem::size_of::<f32>())).is_none_or(|n| n > MAX_AUDIO_REQUEST_BYTES) {
return Err(MediaError::Decode("FLAC audio request exceeds the PCM buffer limit".into()));
}
let prefix = if start < 0 { usize::try_from(start.unsigned_abs()).unwrap_or(frames).min(frames) } else { 0 };
let Some((origin, phase)) = resampling_origin(start.max(0), self.rate, sample_rate) else {
return Ok(AudioBuffer::new(sample_rate, self.samples.len() as u16, frames));
};
let origin = usize::try_from(origin).unwrap_or(usize::MAX);
let tail: Vec<&[f32]> = self.samples.iter().map(|plane| plane.get(origin..).unwrap_or_default()).collect();
// Keep the true end of the PCM tail so interpolation holds the final sample until
// the clip ends. Padding this input tail would fade the final sample into silence.
let mut channels = resample_audio_with_phase(&tail, self.rate, sample_rate, frames - prefix, phase, 0);
if prefix != 0 {
for channel in &mut channels {
channel.resize(frames, 0.0);
channel.rotate_right(prefix);
}
}
Ok(AudioBuffer { sample_rate, channels })
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions};
use craft_media_source::{MediaError, MediaKind, SharedSource};
use craft_time::Tick;
use crate::stream::{self, MediaSource as OpenedSource};
const RATE: u32 = 48_000;
const FRAMES: usize = 4_501;
fn fixture() -> (Vec<u8>, AudioBuffer) {
let left = (0..FRAMES).map(|i| ((i * 23 % 350) as f32 - 170.0) / 512.0).collect();
let right = (0..FRAMES).map(|i| (220.0 - (i * 37 % 470) as f32) / 512.0).collect();
let pcm = AudioBuffer { sample_rate: RATE, channels: vec![left, right] };
let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int24);
(craft_audio::encode(&pcm, &opts).unwrap(), pcm)
}
fn require_shared(opened: OpenedSource) -> SharedSource {
let OpenedSource::Craft(source) = opened else { panic!("FLAC should use the shared reader") };
source
}
#[test]
#[cfg(any(unix, windows))]
fn standalone_flac_uses_shared_source_for_disk_and_memory() {
let (bytes, pcm) = fixture();
let bytes: Arc<[u8]> = bytes.into();
let memory = require_shared(stream::open_bytes("music.flac", bytes.clone()).unwrap());
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("music.flac");
std::fs::write(&path, &bytes).unwrap();
let disk = require_shared(stream::open_source(&path).unwrap().0.unwrap());
let legacy = filmcraft_codecs::open_bytes("music.flac", bytes.clone()).unwrap();
for source in [memory, disk] {
let info = source.info();
let stream = info.audio().unwrap();
assert_eq!(info.kind, MediaKind::AudioOnly);
assert_eq!(info.duration, Tick::from_units(FRAMES as i64, i64::from(RATE)));
assert_eq!(info.file_size, Some(bytes.len() as u64));
assert_eq!(info.container, legacy.info().container);
assert_eq!(stream.codec, legacy.info().audio().unwrap().codec);
assert_eq!((stream.sample_rate, stream.channels, stream.bits_per_sample), (RATE, 2, Some(24)));
let decoded = source.audio(0, FRAMES, RATE).unwrap();
assert_eq!((decoded.sample_rate, decoded.num_channels(), decoded.frames()), (RATE, 2, FRAMES));
for (got, want) in decoded.channels.iter().flatten().zip(pcm.channels.iter().flatten()) {
assert_eq!(got, want);
}
// Seek backwards, across the encoder's block boundary, and around both clip edges.
for (rate, start, frames) in [(RATE, 4091, 20), (RATE, -3, 8), (96_000, 8998, 10), (44_100, 251, 39), (44_100, 61, 39)] {
let got = source.audio(start, frames, rate).unwrap();
let want = legacy.audio(start, frames, rate).unwrap();
assert_eq!(got.channels[0].len(), frames);
for (got, want) in got.channels.iter().zip(&want.channels) {
for (got, want) in got.iter().zip(want) {
assert!((got - want).abs() <= 1e-6, "output rate {rate}, start {start}: {got} vs {want}");
}
}
}
let full = source.audio(61, 63, 44_100).unwrap();
let left = source.audio(61, 23, 44_100).unwrap();
let right = source.audio(84, 40, 44_100).unwrap();
for ((whole, left), right) in full.channels.iter().zip(&left.channels).zip(&right.channels) {
assert_eq!(&whole[..23], left);
assert_eq!(&whole[23..], right);
}
assert!(matches!(source.audio(0, usize::MAX, RATE), Err(MediaError::Decode(_))));
assert!(matches!(source.audio(0, 1, 0), Err(MediaError::Decode(_))));
}
}
#[test]
#[cfg(any(unix, windows))]
fn standalone_flac_keeps_legacy_trailer_compatibility() {
let (mut bytes, pcm) = fixture();
bytes.extend_from_slice(b"trailing bytes");
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("trailer.flac");
std::fs::write(&path, &bytes).unwrap();
let disk = stream::open_source(&path).unwrap().0.unwrap();
let memory = stream::open_bytes("trailer.flac", bytes.into()).unwrap();
for opened in [disk, memory] {
let OpenedSource::Film(source) = opened else { panic!("the existing reader should accept the trailer") };
let prefix = source.audio(0, 32, RATE).unwrap();
assert_eq!((prefix.channels[0].as_slice(), prefix.channels[1].as_slice()), (&pcm.channels[0][..32], &pcm.channels[1][..32]));
}
}
#[test]
#[cfg(any(unix, windows))]
fn native_flac_opener_declines_an_oversized_file_without_reading_it() {
use std::sync::atomic::{AtomicBool, Ordering};
use craft_media::ByteSource;
use craft_media_source::{DEFAULT_MAX_MEDIA_BYTES, SharedBytes};
struct OversizedFile(AtomicBool);
impl ByteSource for OversizedFile {
fn len(&self) -> u64 {
DEFAULT_MAX_MEDIA_BYTES as u64 + 1
}
fn read_at(&self, _: u64, _: &mut [u8]) -> std::io::Result<()> {
self.0.store(true, Ordering::Relaxed);
Err(std::io::Error::other("oversized input was read"))
}
}
let file = Arc::new(OversizedFile(AtomicBool::new(false)));
let source: SharedBytes = file.clone();
assert!(super::open_reader("oversized.flac", b"fLaC", &source).is_none());
assert!(!file.0.load(Ordering::Relaxed));
}
}
@@ -0,0 +1,82 @@
use std::io::Cursor;
use craft_video::ffv1::{self, Colorspace, Encoder, EncoderConfig};
use super::*;
use crate::stream::{self, MediaSource as OpenedSource};
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
fn assert_samples(actual: &[f32], expected: &[f32]) {
assert_eq!(actual.len(), expected.len());
for (i, (&got, &want)) in actual.iter().zip(expected).enumerate() {
assert!((got - want).abs() < 1e-6, "sample {i}: expected {want}, got {got}");
}
}
#[test]
fn full_range_rgb_ffv1_keeps_wide_samples_across_backward_seek() -> TestResult {
const WIDTH: u32 = 5;
const HEIGHT: u32 = 3;
let mut raw = ffv1::Frame { width: WIDTH, height: HEIGHT, colorspace: Colorspace::Rgb, bit_depth: 10, chroma_shift: (0, 0), planes: vec![Vec::new(); 3] };
let encoder = Encoder::new(&raw, EncoderConfig::default())?;
let mut track = matroska::TrackSpec::new(matroska::TrackKind::Video, "V_FFV1");
track.codec_private = encoder.config_record();
track.video_size = Some((WIDTH, HEIGHT));
track.default_duration_ns = Some(40_000_000);
let mut writer = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default())?;
let mut expected = Vec::new();
for n in 0u16..3 {
let codes: Vec<[u16; 3]> = (0..WIDTH as u16 * HEIGHT as u16).map(|p| [256 + 96 * n + p, 500 + p, 910 - p]).collect();
for (c, plane) in raw.planes.iter_mut().enumerate() {
*plane = codes.iter().map(|pixel| pixel[c]).collect();
}
writer.write_frame(0, i64::from(n) * 40_000_000, true, &encoder.encode(&raw)?, Some(40_000_000))?;
// The existing Rec.709 fallback uses the sRGB preview curve. All fixture codes are
// above its linear segment, and adjacent codes must survive the full conversion.
expected.push(
codes
.into_iter()
.flat_map(|pixel| {
let [r, g, b] = pixel.map(|c| ((f32::from(c) / 1023.0 + 0.055) / 1.055).powf(2.4));
[r, g, b, 1.0]
})
.collect::<Vec<_>>(),
);
}
let bytes = writer.finish()?.into_inner();
let OpenedSource::Craft(source) = stream::open_bytes("wide-rgb-ffv1.mkv", bytes.into())? else {
panic!("expected the shared FFV1 reader");
};
for n in [2, 0, 1] {
let pts = Tick::from_units(n as i64, 25);
let frame = source.video_frame(FrameRequest { time: pts, scale: 1.0 })?;
assert_eq!((frame.width, frame.height, frame.pts), (WIDTH, HEIGHT, pts));
assert_eq!((frame.color.range, frame.color.transfer), (Range::Full, Transfer::Linear));
let PixelData::RgbaF32(pixels) = &frame.data else { panic!("expected linear floating-point RGBA") };
assert_samples(pixels, &expected[n]);
}
Ok(())
}
#[test]
fn full_range_wide_rgb_crops_rotates_and_premultiplies() -> TestResult {
let plane = |rows| Plane::new(3, 2, 4, 10, Samples::U16(rows));
let red = plane(vec![8, 1023, 11, 999, 12, 1023, 13, 999])?;
let green = plane(vec![20, 512, 21, 999, 22, 256, 23, 999])?;
let blue = plane(vec![24, 1, 25, 999, 26, 1023, 27, 999])?;
let alpha = plane(vec![0, 512, 0, 999, 0, 0, 0, 999])?;
let mut decoded = DecodedVideoFrame::new(3, 2, ColorFamily::Rgb, Subsampling::S444, vec![red, green, blue], Some(alpha))?;
decoded.sar = Some((5, 4));
let aperture = isobmff::CleanAperture { width: (1, 1), height: (2, 1), horiz_offset: (0, 1), vert_offset: (0, 1) };
let color = ColorInfo { transfer: Transfer::Linear, ..ColorInfo::SRGB_FULL };
let presentation = FramePresentation { container_color: Some(color), par: (1, 1), rotation: 1, aperture: Some(aperture) };
let pts = Tick::from_units(4, 25);
let frame = to_craft_frame(decoded, presentation, pts)?;
assert_eq!((frame.width, frame.height, frame.par, frame.pts, frame.color), (2, 1, (4, 5), pts, color));
let PixelData::RgbaF32(pixels) = &frame.data else { panic!("expected linear floating-point RGBA") };
let half = 512.0 / 1023.0;
assert_samples(pixels, &[0.0, 0.0, 0.0, 0.0, half, half * half, half / 1023.0, half]);
Ok(())
}
+26
View File
@@ -223,6 +223,32 @@ mod tests {
assert!(e.to_lowercase().contains("memory"), "{e}");
}
#[test]
fn gif_probe_and_playback_respect_text_control_scope() {
let mut bytes = Vec::new();
{
let mut encoder = gif::Encoder::new(&mut bytes, 2, 2, &[255, 0, 0, 0, 0, 255]).unwrap();
for (index, delay, transparent) in [(0, 23, Some(0)), (1, 7, None)] {
let frame = gif::Frame { width: 2, height: 2, delay, transparent, buffer: vec![index; 4].into(), ..gif::Frame::default() };
encoder.write_frame(&frame).unwrap();
}
}
let offset = craft_gif::scan(&bytes, 1).unwrap().frames[0].offset;
// A text grid consumes the first Graphic Control Extension. The first
// image then uses the app's default display delay of 100 ms.
let text = [0x21, 0x01, 12, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 1, b'X', 0];
bytes.splice(offset..offset, text);
let bytes: std::sync::Arc<[u8]> = bytes.into();
let footage = probe_bytes("text-control.gif", bytes.clone()).unwrap();
let pool = MediaPool::new();
pool.add_bytes("text-control.gif", bytes);
assert_eq!(
(footage.duration, colour_at(&pool, &footage, 0.09), colour_at(&pool, &footage, 0.11)),
(Tick::from_units(17, 100), [1.0, 0.0, 0.0], [0.0, 0.0, 1.0])
);
}
#[test]
fn a_zero_delay_is_ten_hundredths_like_in_browsers() {
let f = probe_bytes("a.gif", gif(&[(RED, 0), (GREEN, 1)]).into()).unwrap();
+2 -2
View File
@@ -17,6 +17,7 @@
mod aac;
mod convert;
mod craft_source;
pub mod downmix;
mod dpx;
pub mod exr_channels;
@@ -26,7 +27,6 @@ mod exr_read;
mod gif_anim;
mod layered;
mod localize;
mod mp4_h264;
pub use layered::vector_doc;
mod pool;
mod probe;
@@ -84,7 +84,7 @@ impl From<craft_media_source::MediaError> for MediaError {
pub const STILL_EXTENSIONS: &[&str] =
&["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps", "vectorcraft"];
/// File extensions recognised as audio-only files.
pub const AUDIO_EXTENSIONS: &[&str] = filmcraft_media::AUDIO_EXTENSIONS;
pub const AUDIO_EXTENSIONS: &[&str] = craft_media_source::AUDIO_EXTENSIONS;
pub use effectcraft_project::VIDEO_EXTENSIONS;
/// File extensions recognised as 3D models (Advanced 3D model layers).
-597
View File
@@ -1,597 +0,0 @@
//! Software MP4/MOV H.264 route backed by `craft-media`, `craft-video`, `craft-audio`, and
//! `craft-media-source`.
//!
//! Preserves sync-sample backward seek, B-frame reordering, cooperative cancellation, VUI +
//! container colour resolution, draft mode for reduced-resolution playback, and bounded worker
//! threads.
use std::sync::{Arc, Mutex};
use craft_audio::{AudioBuffer, TrackDecoder as AudioTrackDecoder};
use craft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};
use craft_frame::{Chroma, PixelData, VideoFrame};
use craft_media::isobmff::{self, Mp4File, Track, TrackKind};
use craft_media::{ByteSource, CodecId};
use craft_media_source::{
AudioStreamInfo, FrameRequest, MAX_AUDIO_STREAMS, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, SharedSource, VideoStreamInfo,
};
use craft_time::{FrameRate, Tick};
use craft_video::frame::{ColorFamily, ColorTags, Plane, Samples, Subsampling, VideoFrame as DecodedVideoFrame};
use craft_video::{TrackDecoder, TrackDecoderOptions};
/// Maximum worker threads per `TrackDecoder` instance.
const MAX_WORKERS: usize = 8;
/// Maximum decoded frames retained in the per-source GOP window cache.
const MAX_CACHED_FRAMES: usize = 32;
/// Maximum audio lookahead packets inspected when initializing `craft_audio::TrackDecoder`.
const AUDIO_LOOKAHEAD: usize = 8;
fn worker_cap() -> usize {
std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS)
}
/// True when `head` begins with a plausible ISO-BMFF top-level box.
fn looks_like_isobmff(head: &[u8]) -> bool {
if head.len() < 8 {
return false;
}
matches!(&head[4..8], b"ftyp" | b"moov" | b"mdat" | b"free" | b"skip" | b"wide" | b"pnot" | b"uuid")
}
/// Open an in-place MP4/MOV H.264 source via `craft-media` / `craft-video`.
/// Returns `None` when the file is not ISO-BMFF, has no H.264 video track, or has an audio track
/// whose codec is not yet handled by `craft-audio`.
pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Option<Result<SharedSource>> {
if !looks_like_isobmff(head) {
return None;
}
open_byte_source(name, reader.clone())
}
/// Open an in-memory MP4/MOV H.264 source via `craft-media` / `craft-video`.
pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource>> {
if !looks_like_isobmff(&bytes) {
return None;
}
open_byte_source(name, Arc::new(bytes))
}
fn open_byte_source(name: &str, source: SharedBytes) -> Option<Result<SharedSource>> {
let file = isobmff::open(source.clone()).ok()?;
let video_idx = file.tracks.iter().position(|t| t.kind == TrackKind::Video && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0)?;
let video_track = &file.tracks[video_idx];
let video_params = video_track.codec_params();
if video_params.codec != CodecId::H264 {
return None;
}
// Collect playable audio tracks and ensure `craft-audio` can decode every one of them.
let mut audio_tracks = Vec::new();
let mut audio_infos = Vec::new();
for (idx, track) in file.tracks.iter().enumerate() {
if audio_tracks.len() >= MAX_AUDIO_STREAMS {
break;
}
if track.kind != TrackKind::Audio || track.samples.is_empty() || track.entries.is_empty() || track.timescale == 0 {
continue;
}
let params = track.codec_params();
let mut lookahead = Vec::with_capacity(AUDIO_LOOKAHEAD.min(track.samples.len()));
for s_idx in 0..AUDIO_LOOKAHEAD.min(track.samples.len()) {
let Ok(pkt) = file.read_sample(&*source, idx, s_idx) else {
return None;
};
lookahead.push(pkt);
}
let refs: Vec<&[u8]> = lookahead.iter().map(Vec::as_slice).collect();
let Ok(dec) = AudioTrackDecoder::new(&params, &refs) else {
return None;
};
let native_rate = dec.sample_rate().max(1);
let channels = u32::from(dec.layout().channels()).max(1);
audio_infos.push(AudioStreamInfo {
sample_rate: native_rate,
channels,
codec: params.codec.name().to_string(),
bits_per_sample: params.pcm.map(|p| u32::from(p.bits)),
});
audio_tracks.push(AudioTrackEntry {
track_idx: idx,
native_rate,
state: Mutex::new(AudioTrackState { decoder: dec, next_sample: 0, decoded_pos: 0, buf: Vec::new() }),
});
}
let video_decoder = match TrackDecoder::with_options(&video_params, TrackDecoderOptions { threads: Some(worker_cap()), draft: false }) {
Ok(d) => d,
Err(e) => return Some(Err(MediaError::Decode(e.to_string()))),
};
let container_color = video_track.video().and_then(|v| v.color.as_ref()).map(color_from_isobmff);
let color = container_color.unwrap_or(ColorInfo::REC709);
let (width, height) = video_track
.video()
.map(|v| (u32::from(v.width), u32::from(v.height)))
.filter(|&(w, h)| w > 0 && h > 0)
.unwrap_or((video_track.width, video_track.height));
let par = video_track.video().and_then(|v| v.pixel_aspect).filter(|&(n, d)| n > 0 && d > 0).unwrap_or((1, 1));
let frame_rate = estimate_frame_rate(video_track);
let duration = Tick::from_units(i64::try_from(video_track.duration).unwrap_or(i64::MAX), i64::from(video_track.timescale));
let bitrate = video_track.entries.first().and_then(|e| e.bitrate).map(|b| u64::from(b.avg_bitrate)).filter(|&b| b > 0);
let info = MediaInfo {
name: name.to_string(),
kind: MediaKind::Movie,
duration,
video: Some(VideoStreamInfo {
width,
height,
frame_rate,
par,
codec: "H.264".to_string(),
pixel_format: "yuv420p".to_string(),
color,
has_alpha: false,
bitrate,
hdr: None,
}),
audio_streams: audio_infos,
container: "mp4".to_string(),
start_timecode: None,
file_size: Some(source.len()),
};
Some(Ok(Arc::new(Mp4H264Source {
info,
source,
file,
video_track_idx: video_idx,
container_color,
par,
video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }),
audio_tracks,
})))
}
struct CachedFrame {
pts: i64,
frame: Arc<VideoFrame>,
}
struct VideoState {
decoder: TrackDecoder,
next_decode_idx: usize,
gop_start_idx: usize,
flushed: bool,
decoded: Vec<CachedFrame>,
}
struct AudioTrackState {
decoder: AudioTrackDecoder,
next_sample: usize,
/// Sample index (in native-rate frames) of `buf[0]` relative to track start (0).
decoded_pos: i64,
/// Interleaved or planar? Planar: one `Vec<f32>` per channel.
buf: Vec<Vec<f32>>,
}
struct AudioTrackEntry {
track_idx: usize,
native_rate: u32,
state: Mutex<AudioTrackState>,
}
struct Mp4H264Source {
info: MediaInfo,
source: SharedBytes,
file: Mp4File,
video_track_idx: usize,
container_color: Option<ColorInfo>,
par: (u32, u32),
video: Mutex<VideoState>,
audio_tracks: Vec<AudioTrackEntry>,
}
impl MediaSource for Mp4H264Source {
fn info(&self) -> &MediaInfo {
&self.info
}
fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>> {
let track = &self.file.tracks[self.video_track_idx];
let t_track = tick_to_units(req.time, track.timescale);
let target_idx = track.sample_at_presentation_time(t_track).ok_or_else(|| MediaError::Decode("no video samples".into()))?;
let target_pts = track.samples[target_idx].pts;
let mut state = self.video.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(hit) = state.decoded.iter().find(|c| c.pts == target_pts) {
return Ok(hit.frame.clone());
}
let sync_idx = track.sync_sample_before(target_idx);
// Backward seek or jump to a later GOP: reset the decoder to the target sync sample.
if target_idx < state.next_decode_idx || sync_idx > state.gop_start_idx {
state.decoder.reset().map_err(|e| MediaError::Decode(e.to_string()))?;
state.decoded.clear();
state.next_decode_idx = sync_idx;
state.gop_start_idx = sync_idx;
state.flushed = false;
}
let want_draft = req.scale < 0.99;
if state.decoder.draft() != want_draft {
state.decoder.set_draft(want_draft);
}
while !state.decoded.iter().any(|c| c.pts >= target_pts) {
if filmcraft_media::cancel::cancelled() {
return Err(MediaError::Cancelled);
}
if state.next_decode_idx < track.samples.len() {
let idx = state.next_decode_idx;
let sample = track.samples[idx];
let pkt = self.file.read_sample(&*self.source, self.video_track_idx, idx).map_err(|e| MediaError::Io(e.to_string()))?;
let frames = state.decoder.decode(&pkt, sample.pts).map_err(|e| MediaError::Decode(e.to_string()))?;
state.next_decode_idx = idx + 1;
push_decoded(&mut state.decoded, frames, self.container_color, self.par, track.timescale, track.edit_offset)?;
} else if !state.flushed {
let frames = state.decoder.flush().map_err(|e| MediaError::Decode(e.to_string()))?;
state.flushed = true;
push_decoded(&mut state.decoded, frames, self.container_color, self.par, track.timescale, track.edit_offset)?;
break;
} else {
break;
}
}
if let Some(exact) = state.decoded.iter().find(|c| c.pts == target_pts) {
return Ok(exact.frame.clone());
}
// Fallback: latest decoded frame at or before target_pts, or earliest available.
let best = state
.decoded
.iter()
.filter(|c| c.pts <= target_pts)
.max_by_key(|c| c.pts)
.or_else(|| state.decoded.first())
.ok_or_else(|| MediaError::Decode("H.264 decoder produced no frame".into()))?;
Ok(best.frame.clone())
}
fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
self.audio_stream(0, start, frames, sample_rate)
}
fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
let entry = self.audio_tracks.get(stream).ok_or(MediaError::NoStream("audio"))?;
if sample_rate == 0 {
return Err(MediaError::Decode("invalid audio sample rate 0".into()));
}
let channels_count = self.info.audio_streams.get(stream).map_or(2, |s| s.channels as usize);
if frames == 0 {
return Ok(AudioBuffer::new(sample_rate, channels_count as u16, 0));
}
let native_rate = entry.native_rate;
let (native_start, native_frames) = if sample_rate == native_rate {
(start, frames)
} else {
let s0 = (i128::from(start) * i128::from(native_rate)) / i128::from(sample_rate);
let len = ((frames as u128 * u128::from(native_rate)).div_ceil(u128::from(sample_rate)) + 2) as usize;
(i64::try_from(s0).unwrap_or(0), len)
};
let track = &self.file.tracks[entry.track_idx];
let mut state = entry.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let decoded =
decode_audio_range(&self.file, &*self.source, entry.track_idx, track, native_rate, channels_count, &mut state, native_start, native_frames)?;
if sample_rate == native_rate {
return Ok(AudioBuffer { sample_rate, channels: decoded });
}
let mut resampled = vec![vec![0.0f32; frames]; channels_count];
let ratio = f64::from(native_rate) / f64::from(sample_rate);
for (c, out_ch) in resampled.iter_mut().enumerate() {
let in_ch = &decoded[c];
if in_ch.is_empty() {
continue;
}
for (i, dst) in out_ch.iter_mut().enumerate() {
let pos = i as f64 * ratio;
let idx = pos.floor() as usize;
let frac = (pos - idx as f64) as f32;
let s0 = in_ch.get(idx).copied().unwrap_or(0.0);
let s1 = in_ch.get(idx + 1).copied().unwrap_or(s0);
*dst = s0 + (s1 - s0) * frac;
}
}
Ok(AudioBuffer { sample_rate, channels: resampled })
}
}
#[allow(clippy::too_many_arguments)]
fn decode_audio_range(
file: &Mp4File,
source: &dyn ByteSource,
track_idx: usize,
track: &Track,
native_rate: u32,
channels_count: usize,
state: &mut AudioTrackState,
start: i64,
frames: usize,
) -> Result<Vec<Vec<f32>>> {
let mut out = vec![vec![0.0f32; frames]; channels_count];
let end = start.saturating_add(frames as i64);
if end <= 0 {
return Ok(out);
}
let buf_len = state.buf.first().map_or(0, Vec::len) as i64;
let buf_end = state.decoded_pos.saturating_add(buf_len);
if start < state.decoded_pos || start > buf_end + i64::from(native_rate) * 2 {
// Seek to the sample at or before `start` in track timescale.
let t_track = (i128::from(start.max(0)) * i128::from(track.timescale)) / i128::from(native_rate);
let sample_idx = track.sample_at_presentation_time(i64::try_from(t_track).unwrap_or(0)).unwrap_or(0);
// Back up a few packets for AAC/Opus overlap/preroll.
let seek_idx = sample_idx.saturating_sub(2);
state.decoder.reset();
state.next_sample = seek_idx;
let sample_pts = track.presentation_pts(seek_idx).unwrap_or(0);
state.decoded_pos = i64::try_from((i128::from(sample_pts) * i128::from(native_rate)) / i128::from(track.timescale.max(1))).unwrap_or(0);
for ch in &mut state.buf {
ch.clear();
}
}
if state.buf.len() != channels_count {
state.buf = vec![Vec::new(); channels_count];
}
while state.decoded_pos + state.buf.first().map_or(0, Vec::len) as i64 <= end && state.next_sample < track.samples.len() {
if filmcraft_media::cancel::cancelled() {
return Err(MediaError::Cancelled);
}
let idx = state.next_sample;
let pkt = file.read_sample(source, track_idx, idx).map_err(|e| MediaError::Io(e.to_string()))?;
state.next_sample = idx + 1;
let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?;
for (c, ch) in state.buf.iter_mut().enumerate() {
if let Some(src_ch) = block.channels.get(c) {
ch.extend_from_slice(src_ch);
}
}
}
let avail = state.buf.first().map_or(0, Vec::len);
for i in 0..frames {
let pos = start.saturating_add(i as i64);
if pos >= state.decoded_pos {
let off = (pos - state.decoded_pos) as usize;
if off < avail {
for (c, out_ch) in out.iter_mut().enumerate() {
out_ch[i] = state.buf[c][off];
}
}
}
}
// Trim already-consumed audio older than `end` minus a small safety margin.
let drop_to = (end - state.decoded_pos).max(0) as usize;
let trim = drop_to.min(avail);
if trim > 0 {
for ch in &mut state.buf {
ch.drain(..trim);
}
state.decoded_pos = state.decoded_pos.saturating_add(trim as i64);
}
Ok(out)
}
fn push_decoded(
cache: &mut Vec<CachedFrame>,
frames: Vec<DecodedVideoFrame>,
container_color: Option<ColorInfo>,
par: (u32, u32),
timescale: u32,
edit_offset: i64,
) -> Result<()> {
for vf in frames {
let pts = vf.pts.unwrap_or(0);
let frame = Arc::new(to_craft_frame(vf, container_color, par, timescale, edit_offset)?);
cache.push(CachedFrame { pts, frame });
}
if cache.len() > MAX_CACHED_FRAMES {
let excess = cache.len() - MAX_CACHED_FRAMES;
cache.drain(..excess);
}
Ok(())
}
fn to_craft_frame(vf: DecodedVideoFrame, container_color: Option<ColorInfo>, default_par: (u32, u32), timescale: u32, edit_offset: i64) -> Result<VideoFrame> {
let width = vf.width();
let height = vf.height();
let subsampling = vf.subsampling();
let family = vf.family();
let tags = vf.color;
let pts_units = vf.pts.unwrap_or(0).saturating_add(edit_offset);
let pts = Tick::from_units(pts_units, i64::from(timescale.max(1)));
let par = vf.sar.filter(|&(n, d)| n > 0 && d > 0).unwrap_or(default_par);
let color = resolve_color(tags, container_color);
let bit_depth = vf.bit_depth();
let (planes, alpha) = vf.into_planes();
let data = match family {
ColorFamily::YCbCr => {
let chroma = match subsampling {
Subsampling::S420 => Chroma::C420,
Subsampling::S422 => Chroma::C422,
Subsampling::S444 => Chroma::C444,
_ => return Err(MediaError::Unsupported("unsupported YCbCr subsampling".into())),
};
let mut iter = planes.into_iter();
let (Some(y), Some(cb), Some(cr)) = (iter.next(), iter.next(), iter.next()) else {
return Err(MediaError::Decode("missing YUV planes".into()));
};
if bit_depth <= 8 {
let y = Arc::new(plane_u8(y)?);
let cb = Arc::new(plane_u8(cb)?);
let cr = Arc::new(plane_u8(cr)?);
let a = alpha.map(plane_u8).transpose()?.map(Arc::new);
PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha: a }
} else {
let y = Arc::new(plane_u16(y)?);
let cb = Arc::new(plane_u16(cb)?);
let cr = Arc::new(plane_u16(cr)?);
let a = alpha.map(plane_u16).transpose()?.map(Arc::new);
PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: u32::from(bit_depth), alpha: a }
}
}
ColorFamily::Rgb | ColorFamily::Gray => return Err(MediaError::Unsupported("non-YCbCr H.264 pixel format".into())),
};
Ok(VideoFrame { width, height, data, color, par, pts })
}
fn plane_u8(p: Plane) -> Result<Vec<u8>> {
let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride());
match p.into_samples() {
Samples::U8(mut v) => {
if stride == w {
v.truncate(w * h);
return Ok(v);
}
let mut out = Vec::with_capacity(w * h);
for y in 0..h {
let row = y * stride;
out.extend_from_slice(&v[row..row + w]);
}
Ok(out)
}
Samples::U16(_) => Err(MediaError::Decode("expected 8-bit plane".into())),
}
}
fn plane_u16(p: Plane) -> Result<Vec<u16>> {
let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride());
match p.into_samples() {
Samples::U16(mut v) => {
if stride == w {
v.truncate(w * h);
return Ok(v);
}
let mut out = Vec::with_capacity(w * h);
for y in 0..h {
let row = y * stride;
out.extend_from_slice(&v[row..row + w]);
}
Ok(out)
}
Samples::U8(_) => Err(MediaError::Decode("expected 16-bit plane".into())),
}
}
fn resolve_color(vui: ColorTags, container: Option<ColorInfo>) -> ColorInfo {
let base = container.unwrap_or(ColorInfo::REC709);
let matrix = Matrix::from_code(vui.matrix).unwrap_or(base.matrix);
let transfer = Transfer::from_code(vui.transfer).unwrap_or(base.transfer);
let primaries = primaries_from_code(vui.primaries).unwrap_or(base.primaries);
let range = if vui.full_range { Range::Full } else { base.range };
ColorInfo { matrix, transfer, primaries, range }
}
fn color_from_isobmff(c: &isobmff::ColorInfo) -> ColorInfo {
match c {
isobmff::ColorInfo::Nclx { primaries, transfer, matrix, full_range } => ColorInfo {
matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709),
transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709),
primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709),
range: if *full_range { Range::Full } else { Range::Limited },
},
isobmff::ColorInfo::Nclc { primaries, transfer, matrix } => ColorInfo {
matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709),
transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709),
primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709),
range: Range::Limited,
},
isobmff::ColorInfo::Icc { .. } => ColorInfo::REC709,
}
}
fn primaries_from_code(c: u8) -> Option<Primaries> {
match c {
1 => Some(Primaries::Bt709),
5 => Some(Primaries::Bt601_625),
6 => Some(Primaries::Bt601_525),
9 => Some(Primaries::Bt2020),
11 | 12 => Some(Primaries::P3D65),
_ => None,
}
}
fn tick_to_units(t: Tick, timescale: u32) -> i64 {
let v = (i128::from(t.0) * i128::from(timescale)) / i128::from(craft_time::TICKS_PER_SECOND);
i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX })
}
fn estimate_frame_rate(track: &Track) -> FrameRate {
let ts = i128::from(track.timescale);
if ts <= 0 || track.samples.is_empty() {
return FrameRate::FPS_30;
}
let mut durs: Vec<u32> = track.samples.iter().map(|s| s.duration).filter(|&d| d > 0).collect();
if durs.is_empty() {
return FrameRate::FPS_30;
}
durs.sort_unstable();
let median = durs[durs.len() / 2];
for r in FrameRate::COMMON {
if ts * i128::from(r.den) == i128::from(median) * i128::from(r.num) {
return r;
}
}
let fps = track.timescale as f64 / f64::from(median);
FrameRate::COMMON
.into_iter()
.map(|r| (r, (fps / r.as_f64() - 1.0).abs()))
.filter(|&(_, off)| off <= 0.005)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(r, _)| r)
.unwrap_or_else(|| FrameRate::new(i64::from(track.timescale), i64::from(median)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn worker_cap_is_bounded() {
let cap = worker_cap();
assert!((1..=MAX_WORKERS).contains(&cap), "cap={cap}");
}
#[test]
fn vui_overrides_container_color_and_falls_back_when_unspecified() {
let container = color_from_isobmff(&isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: false });
assert_eq!(container.primaries, Primaries::Bt2020);
assert_eq!(container.transfer, Transfer::Pq);
assert_eq!(container.matrix, Matrix::Bt2020Ncl);
assert_eq!(container.range, Range::Limited);
// Unspecified VUI (2) falls back to container color.
let resolved = resolve_color(ColorTags::UNSPECIFIED, Some(container));
assert_eq!(resolved, container);
// Explicit VUI overrides container color.
let vui = ColorTags { primaries: 1, transfer: 1, matrix: 1, full_range: true };
let resolved = resolve_color(vui, Some(container));
assert_eq!(resolved.primaries, Primaries::Bt709);
assert_eq!(resolved.transfer, Transfer::Bt709);
assert_eq!(resolved.matrix, Matrix::Bt709);
assert_eq!(resolved.range, Range::Full);
}
}
+156 -13
View File
@@ -554,7 +554,68 @@ impl Sources {
/// A movie/audio source by path ([`Opened`]), opened by the first caller while the others wait
/// for it (`None`: failed to open; not retried until `forget`), with the file's identity as
/// opened.
type SourceSlot = Arc<OnceLock<(Option<Opened>, ReadFile)>>;
type SourceSlot = Arc<Source>;
#[derive(Default)]
struct Source {
opened: OnceLock<(Option<Opened>, ReadFile)>,
#[cfg(not(target_arch = "wasm32"))]
dispatch: Mutex<Dispatch>,
}
#[cfg(not(target_arch = "wasm32"))]
type DecodeJob = Box<dyn FnOnce() + Send>;
#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
struct Dispatch {
active: bool,
pending: VecDeque<DecodeJob>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Source {
fn enqueue(self: &Arc<Self>, workers: &'static rayon::ThreadPool, job: DecodeJob) {
let mut dispatch = lock(&self.dispatch);
if dispatch.active {
dispatch.pending.push_back(job);
return;
}
dispatch.active = true;
drop(dispatch);
self.start(workers, job);
}
fn start(self: &Arc<Self>, workers: &'static rayon::ThreadPool, job: DecodeJob) {
let source = self.clone();
workers.spawn_fifo(move || {
// Release on errors and unwinding too. Never hold the dispatch lock during a decode.
let _permit = DecodePermit { source, workers };
job();
});
}
}
#[cfg(not(target_arch = "wasm32"))]
struct DecodePermit {
source: SourceSlot,
workers: &'static rayon::ThreadPool,
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for DecodePermit {
fn drop(&mut self) {
let mut dispatch = lock(&self.source.dispatch);
let next = dispatch.pending.pop_front();
if next.is_none() {
dispatch.active = false;
}
drop(dispatch);
if let Some(job) = next {
self.source.start(self.workers, job);
}
}
}
/// An opened movie/audio source, the turn its picture is shown with and the order its decoded
/// audio channels arrive in.
@@ -568,7 +629,7 @@ struct Opened {
impl Opened {
/// `src` with what its container says: `header` is an MP4/MOV's ftyp and moov (or the whole
/// file), `file` the file for other containers' AAC configuration.
fn new(src: MediaSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Opened {
fn new(src: MediaSource, header: Option<&[u8]>, file: Option<&dyn craft_media::ByteSource>) -> Opened {
let turn = header.map_or(Orientation::NoTransforms, crate::probe::video_turn);
Opened { order: channel_order(&src, header, file), src, turn }
}
@@ -576,7 +637,7 @@ impl Opened {
/// The order `src`'s audio channels decode in; multichannel AAC's by its configuration, where
/// the container's header shows it ([`crate::aac::config`]).
fn channel_order(src: &MediaSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Order {
fn channel_order(src: &MediaSource, header: Option<&[u8]>, file: Option<&dyn craft_media::ByteSource>) -> Order {
match src.primary_audio() {
Some((_, channels, codec)) if codec.contains("AAC") && channels > 2 => {
crate::aac::config(header, file).map_or(Order::Aac, |asc| crate::downmix::aac_order(&asc))
@@ -1198,7 +1259,11 @@ impl Inner {
/// Each call notes the file as read (see [`crate::reads`]), with its identity as opened.
fn opened(&self, path: &Arc<str>) -> Option<Opened> {
let slot = lock(&self.sources).slot(path);
let (opened, file) = slot.get_or_init(|| self.open(path));
self.opened_in(path, &slot)
}
fn opened_in(&self, path: &Arc<str>, slot: &SourceSlot) -> Option<Opened> {
let (opened, file) = slot.opened.get_or_init(|| self.open(path));
reads::note(file.clone());
opened.clone()
}
@@ -1220,7 +1285,7 @@ impl Inner {
let opened = bytes.and_then(|bytes| {
let name = std::path::Path::new(&**path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let src = crate::stream::open_bytes(&name, bytes.clone())?;
Ok(Opened::new(src, Some(&bytes), Some(&filmcraft_media::reader::MemReader(bytes.clone()))))
Ok(Opened::new(src, Some(&bytes), Some(&bytes)))
});
(opened, read)
});
@@ -1634,6 +1699,10 @@ impl Inner {
/// (wasm32) or this is one of them. With the files the decode read (see [`crate::reads`]):
/// collected on the thread that decodes, not noted anywhere (the caller notes them).
fn run_decode(self: &Arc<Self>, loc: &Loc, footage: &Footage) -> (Result<Pixels>, ReadFiles) {
// A codec can yield to Rayon while holding its source's decoder mutex. Keep later
// roots for that source OUT of the work-stealing pool until this root finishes (#4074).
// Carry the slot too: forget/reopen must not pair an old permit with a new decoder.
let source = loc.media_t.map(|_| lock(&self.sources).slot(&loc.key.path));
#[cfg(not(target_arch = "wasm32"))]
if let Some(threads) = decode_threads()
&& threads.current_thread_index().is_none()
@@ -1642,14 +1711,20 @@ impl Inner {
let (me, at, f) = (self.clone(), loc.clone(), footage.clone());
// The request's cancel flag and decoding hints go with it (#329).
let hints = filmcraft_media::cancel::Context::current();
threads.spawn(move || {
let slot = source.clone();
let job = Box::new(move || {
#[cfg(not(test))]
let decoded = reads::captured(|| hints.run(|| me.decode_source(&at, &f)));
let decoded = reads::captured(|| hints.run(|| me.decode_source(&at, &f, slot.as_ref())));
// (the decodes counted on that thread are this thread's)
#[cfg(test)]
let decoded = crate::exr_channels::counting(|| reads::captured(|| hints.run(|| me.decode_source(&at, &f))));
let decoded = crate::exr_channels::counting(|| reads::captured(|| hints.run(|| me.decode_source(&at, &f, slot.as_ref()))));
let _ = tx.send(decoded);
});
if let Some(source) = &source {
source.enqueue(threads, job);
} else {
threads.spawn(job);
}
// A plain block: this thread runs nothing else meanwhile.
return match rx.recv() {
#[cfg(not(test))]
@@ -1668,11 +1743,14 @@ impl Inner {
};
}
let _decoding = Decoding::new();
reads::captured(|| self.decode_source(loc, footage))
reads::captured(|| self.decode_source(loc, footage, source.as_ref()))
}
/// Decode the picture `loc` names: a still whole, a movie frame at its size.
fn decode_source(&self, loc: &Loc, footage: &Footage) -> Result<Pixels> {
fn decode_source(&self, loc: &Loc, footage: &Footage, source: Option<&SourceSlot>) -> Result<Pixels> {
if filmcraft_media::cancel::cancelled() {
return Err(MediaError::Cancelled);
}
self.decodes.fetch_add(1, Ordering::Relaxed);
#[cfg(test)]
{
@@ -1684,7 +1762,7 @@ impl Inner {
}
match loc.media_t {
None => self.decode_still(loc, footage).map(|img| Pixels::F32(Arc::new(img))),
Some(_) => self.decode_media(loc, footage),
Some(_) => self.decode_media(loc, footage, source),
}
}
@@ -1748,7 +1826,7 @@ impl Inner {
}
}
fn decode_media(&self, loc: &Loc, footage: &Footage) -> Result<Pixels> {
fn decode_media(&self, loc: &Loc, footage: &Footage, source: Option<&SourceSlot>) -> Result<Pixels> {
let op = AlphaOp::of(footage, loc.float);
let path = &loc.key.path;
let f32 = |img| Pixels::F32(Arc::new(img));
@@ -1760,7 +1838,8 @@ impl Inner {
Ok(f32(dynamic_to_image(frame, op)))
}
Some(mt) => {
let Opened { src, turn, .. } = self.opened(path).ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?;
let opened = source.map_or_else(|| self.opened(path), |slot| self.opened_in(path, slot));
let Opened { src, turn, .. } = opened.ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?;
// A movie shown turned a quarter (a phone held upright): the footage's size and
// the render's are the turned picture's, the decoded frame's are the file's.
let side = |(w, h): (u32, u32)| if crate::probe::swaps_sides(turn) { (h, w) } else { (w, h) };
@@ -2489,6 +2568,70 @@ mod tests {
.collect()
}
/// #4074: nested codec work may steal another root. A queued same-source root must not
/// re-enter its locked decoder, and an independent source must still make progress.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn movie_dispatch_does_not_reenter_a_locked_source() {
let workers: &'static _ = Box::leak(Box::new(rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap()));
let codec = Arc::new(rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap());
let source = SourceSlot::default();
let decoder = Arc::new(Mutex::new(()));
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let (done_tx, done_rx) = std::sync::mpsc::channel();
let first_decoder = decoder.clone();
source.enqueue(
workers,
Box::new(move || {
let _decoder = lock(&first_decoder);
codec.install(move || {
entered_tx.send(()).unwrap();
release_rx.recv().unwrap();
});
}),
);
entered_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap();
source.enqueue(
workers,
Box::new(move || {
let _decoder = lock(&decoder);
done_tx.send(()).unwrap();
}),
);
let other = SourceSlot::default();
let (other_tx, other_rx) = std::sync::mpsc::channel();
other.enqueue(workers, Box::new(move || other_tx.send(()).unwrap()));
let independent = other_rx.recv_timeout(std::time::Duration::from_secs(2));
// Always release the codec, including on regression failure. The timeout bounds a
// deadlock; no decode duration or throughput is being asserted.
release_tx.send(()).unwrap();
assert!(independent.is_ok(), "another source must finish while this codec is parked");
done_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap();
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn movie_dispatch_releases_queued_work_after_a_panic() {
let workers: &'static _ = Box::leak(Box::new(rayon::ThreadPoolBuilder::new().num_threads(1).panic_handler(|_| {}).build().unwrap()));
let source = SourceSlot::default();
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
source.enqueue(
workers,
Box::new(move || {
entered_tx.send(()).unwrap();
release_rx.recv().unwrap();
panic!("a codec failed");
}),
);
entered_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap();
let (done_tx, done_rx) = std::sync::mpsc::channel();
source.enqueue(workers, Box::new(move || done_tx.send(()).unwrap()));
release_tx.send(()).unwrap();
done_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap();
}
/// #3269: requests for a frame being decoded wait for that decode and take its picture, also
/// on rayon workers (the viewer's frame workers), which each decoded a private copy before.
#[test]
+6 -1
View File
@@ -28,6 +28,11 @@ pub fn probe(path: impl AsRef<Path>) -> Result<Footage> {
// A movie is read in place (its index), not loaded whole.
if let Some(src) = crate::stream::probe_source(path) {
let mut f = footage_from_source(&path.to_string_lossy(), &src?);
if ext_of(path) == "wav"
&& let Ok(bytes) = crate::read_regular_file(path)
{
f.markers = crate::wav_markers::read(&bytes);
}
let header = crate::stream::movie_header(path);
let turn = header.as_deref().map_or(Orientation::NoTransforms, video_turn);
turn_footage(&mut f, turn);
@@ -235,7 +240,7 @@ pub(crate) fn footage_from_craft_info(path: &str, info: &craft_media_source::Med
}
}
fn profile_of_craft(c: &craft_color::ColorInfo) -> Option<effectcraft_project::ColorSpace> {
pub(crate) fn profile_of_craft(c: &craft_color::ColorInfo) -> Option<effectcraft_project::ColorSpace> {
use craft_color::{Primaries, Transfer};
use effectcraft_project::ColorSpace;
match (c.primaries, c.transfer) {
+99 -10
View File
@@ -38,7 +38,7 @@ impl DecodedFrame {
}
/// An opened movie/audio source, routed through `craft-media-source` for migrated formats
/// (currently software MP4/H.264) and `filmcraft-media` for remaining formats.
/// (the route matrix in `craft_source`) and `filmcraft-media` for remaining formats.
#[derive(Clone)]
pub(crate) enum MediaSource {
Craft(craft_media_source::SharedSource),
@@ -74,7 +74,7 @@ impl MediaSource {
/// Open an in-memory movie/audio source, trying migrated `craft-media-source` routes first.
pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Result<MediaSource> {
if let Some(res) = crate::mp4_h264::open_bytes(name, bytes.clone()) {
if let Some(res) = crate::craft_source::open_bytes(name, bytes.clone()) {
return res.map(MediaSource::Craft).map_err(MediaError::from);
}
filmcraft_codecs::open_bytes(name, bytes).map(MediaSource::Film).map_err(MediaError::from)
@@ -173,8 +173,8 @@ pub(crate) fn open_source(path: &Path) -> Option<(Result<MediaSource>, FileStamp
let stamp = reader.stamp;
let name = name_of(path);
let craft_reader: craft_media_source::SharedBytes = reader.clone();
if let Ok(head) = craft_media_source::read_range(&*craft_reader, 0, craft_media_source::HEAD_LEN)
&& let Some(res) = crate::mp4_h264::open_reader(&name, &head, &craft_reader)
if let Ok(head) = craft_media_source::read_range(&*craft_reader, 0, crate::craft_source::NATIVE_SNIFF_HEAD_LEN)
&& let Some(res) = crate::craft_source::open_reader(&name, &head, &craft_reader)
{
return Some((res.map(MediaSource::Craft).map_err(MediaError::from), stamp));
}
@@ -191,12 +191,12 @@ pub(crate) fn open_source(_path: &Path) -> Option<(Result<MediaSource>, FileStam
/// `path` read in place (`None` when it can't be opened, or without a native file system).
#[cfg(any(unix, windows))]
pub(crate) fn file_reader(path: &Path) -> Option<Box<dyn filmcraft_media::ByteReader>> {
pub(crate) fn file_reader(path: &Path) -> Option<Box<dyn craft_media::ByteSource>> {
Some(Box::new(FileReader::open(path).ok()?))
}
#[cfg(not(any(unix, windows)))]
pub(crate) fn file_reader(_path: &Path) -> Option<Box<dyn filmcraft_media::ByteReader>> {
pub(crate) fn file_reader(_path: &Path) -> Option<Box<dyn craft_media::ByteSource>> {
None
}
@@ -261,21 +261,110 @@ pub(crate) fn probe_source(path: &Path) -> Option<Result<MediaSource>> {
return None;
}
let reader = Arc::new(FileReader::open(path).ok()?);
let head = filmcraft_media::reader::read_range(&*reader, 0, filmcraft_media::reader::HEAD_LEN).ok()?;
let head = filmcraft_media::reader::read_range(&*reader, 0, crate::craft_source::NATIVE_SNIFF_HEAD_LEN).ok()?;
let legacy_head = &head[..head.len().min(filmcraft_media::reader::HEAD_LEN)];
let name = path.to_string_lossy();
if crate::layered::sniff(&name, &head) || image::guess_format(&head).is_ok() {
if crate::layered::sniff(&name, legacy_head) || image::guess_format(legacy_head).is_ok() {
return None;
}
let name = name_of(path);
let craft_reader: craft_media_source::SharedBytes = reader.clone();
if let Some(res) = crate::mp4_h264::open_reader(&name, &head, &craft_reader) {
if let Some(res) = crate::craft_source::open_reader(&name, &head, &craft_reader) {
return Some(res.map(MediaSource::Craft).map_err(MediaError::from));
}
let fc_reader: filmcraft_media::SharedReader = reader;
filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, &head, &fc_reader)).map(|r| r.map(MediaSource::Film).map_err(Into::into))
filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, legacy_head, &fc_reader)).map(|r| r.map(MediaSource::Film).map_err(Into::into))
}
#[cfg(not(any(unix, windows)))]
pub(crate) fn probe_source(_path: &Path) -> Option<Result<MediaSource>> {
None
}
#[cfg(all(test, any(unix, windows)))]
mod tests {
use super::*;
use craft_media::isobmff::{self, Brand, CodecConfig, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use filmcraft_frame::PixelData;
use image::ExtendedColorType;
use image::codecs::jpeg::JpegEncoder;
type TestResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
const WIDTH: u16 = 16;
const HEIGHT: u16 = 16;
fn generated_mjpeg_mov() -> TestResult<Arc<[u8]>> {
// Original synthetic fixture: encode two authored solid RGB tiles, not external media.
let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov))?;
let video = writer.add_track(TrackConfig::new(SampleEntry::jpeg(WIDTH, HEIGHT), 1_000))?;
for rgb in [[220, 32, 24], [19, 36, 224]] {
let rgb = rgb.repeat(usize::from(WIDTH) * usize::from(HEIGHT));
let mut jpeg = Vec::new();
JpegEncoder::new_with_quality(&mut jpeg, 90).encode(&rgb, u32::from(WIDTH), u32::from(HEIGHT), ExtendedColorType::Rgb8)?;
writer.write_sample(video, WriteSample { data: &jpeg, duration: 40, composition_offset: 0, is_sync: true })?;
}
Ok(writer.finish()?.into_inner().into())
}
fn legacy_mjpeg_pixels(source: &MediaSource, time: Tick) -> TestResult<Arc<Vec<u8>>> {
let frame = match source.video_frame(time, 1.0)? {
DecodedFrame::Film(frame) => Some(frame),
DecodedFrame::Craft(_) => None,
}
.ok_or("the MJPEG baseline must use FilmCraft")?;
assert_eq!((frame.width, frame.height), (u32::from(WIDTH), u32::from(HEIGHT)));
let rgba = match &frame.data {
PixelData::Rgba8(rgba) => Some(rgba),
_ => None,
}
.ok_or("legacy MJPEG decodes to RGBA8")?;
assert_eq!(rgba.len(), usize::from(WIDTH) * usize::from(HEIGHT) * 4);
Ok(rgba.clone())
}
#[test]
fn generated_mjpeg_mov_preserves_legacy_probe_and_seek() -> TestResult<()> {
let bytes = generated_mjpeg_mov()?;
let mov = isobmff::open(bytes.as_ref())?;
assert!(mov.is_quicktime);
assert_eq!(mov.tracks.len(), 1);
let track = &mov.tracks[0];
assert!(matches!(track.codec(), Some(CodecConfig::Jpeg { .. })));
assert_eq!(track.timescale, 1_000);
assert_eq!(track.samples.len(), 2);
assert_eq!((track.samples[0].pts, track.samples[1].pts), (0, 40));
let dir = tempfile::tempdir()?;
let name = "generated-mjpeg.mov";
let path = dir.path().join(name);
std::fs::write(&path, bytes.as_ref())?;
let native_probe = crate::probe(&path)?;
let memory_probe = crate::probe_bytes(name, bytes.clone())?;
let direct = filmcraft_codecs::open_bytes(name, bytes.clone())?;
let legacy_probe = crate::probe::footage_from_info(name, direct.info());
let step = Tick::from_units(1, 25);
for probe in [native_probe, memory_probe] {
assert!(probe.has_video && !probe.has_audio);
assert_eq!((probe.width, probe.height), (u32::from(WIDTH), u32::from(HEIGHT)));
assert_eq!((probe.frame_rate.num, probe.frame_rate.den), (25, 1));
assert_eq!(probe.duration, Tick::from_units(2, 25));
assert_eq!(probe.codec, legacy_probe.codec);
assert_eq!(probe.color_profile, legacy_probe.color_profile);
}
let native = open_source(&path).ok_or("native source")?.0?;
let memory = open_bytes(name, bytes)?;
assert!(matches!(&native, MediaSource::Film(_)));
assert!(matches!(&memory, MediaSource::Film(_)));
let legacy = MediaSource::Film(direct);
for (time, dominant) in [(Tick::ZERO, 0), (step, 2), (Tick::ZERO, 0)] {
let expected = legacy_mjpeg_pixels(&legacy, time)?;
// Independent colour check: a repeated first frame or blank decode cannot pass parity.
assert!(expected.as_chunks::<4>().0.iter().all(|p| p[dominant] > 180 && p[2 - dominant] < 80 && p[3] == 255));
assert_eq!(legacy_mjpeg_pixels(&native, time)?, expected);
assert_eq!(legacy_mjpeg_pixels(&memory, time)?, expected);
}
Ok(())
}
}
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env sh
set -eu
cd "$(dirname "$0")"
ffmpeg -hide_banner -loglevel error \
-f lavfi -i "nullsrc=s=16x12:r=25,format=gray,geq=lum='16+64*N+X+2*Y'" \
-frames:v 3 -c:v libaom-av1 -pix_fmt gray -color_range pc \
-color_primaries bt709 -color_trc bt709 -colorspace bt709 \
-g 1 -crf 0 -b:v 0 -aom-params lossless=1 -cpu-used 6 -threads 16 \
-fflags +bitexact -flags:v +bitexact -f matroska -y monochrome-av1.mkv
Binary file not shown.
@@ -0,0 +1,7 @@
asset: monochrome-av1.mkv
title: Synthetic monochrome AV1 seek fixture
author: Terra854
source: crates/media/tests/fixtures/generate-monochrome-av1.sh
license: MIT OR Apache-2.0
added: 2026-11-22
notes: Original 16x12 grayscale ramps generated with FFmpeg 7.1 and libaom-av1. SHA-256 0837f2039cad2324e7c7e3d4d11bbcf09b02bc9ee6acf84814c5a06e514c52d5.
+7
View File
@@ -300,6 +300,13 @@ fn mpeg_aac_mixes_by_the_stream_played() {
}
let p = write(&format!("latm-first-{latm_first}.ts"), &ts.out);
check(label, case.content, &mix(&MediaPool::new(), &probe(&p).expect("probe")));
let path = format!("/mem/latm-first-{latm_first}.ts");
let bytes: Arc<[u8]> = ts.out.into();
let pool = MediaPool::new();
pool.add_bytes(&path, bytes.clone());
let footage = probe_bytes(&path, bytes).expect("probe registered MPEG bytes");
check(&format!("{label} in memory"), case.content, &mix(&pool, &footage));
}
}
+67
View File
@@ -0,0 +1,67 @@
use std::io::Cursor;
use std::sync::Arc;
use craft_media::avi::{AudioSpec, AviWriter, MuxOptions, StreamSpec, VideoSpec};
use effectcraft_media::{MediaPool, probe, probe_bytes};
use effectcraft_project::FootageKind;
use effectcraft_time::{FrameRate, Tick};
use image::{ExtendedColorType, codecs::jpeg::JpegEncoder};
const SIDE: u32 = 16;
const FPS: u32 = 25;
const SAMPLE_RATE: u32 = 48_000;
fn mjpeg_with_pcm() -> Arc<[u8]> {
let video = StreamSpec::Video(VideoSpec::new(*b"MJPG", SIDE, SIDE, FPS, 1));
let audio = StreamSpec::Audio(AudioSpec::pcm(SAMPLE_RATE, 1, 16));
let mut writer = AviWriter::new(Cursor::new(Vec::new()), vec![video, audio], MuxOptions::default()).expect("AVI writer");
let samples_per_frame = (SAMPLE_RATE / FPS) as usize;
for (color, sample) in [([220_u8, 40, 30], 8_192_i16), ([30, 40, 220], -8_192)] {
let pixels = color.repeat((SIDE * SIDE) as usize);
let mut jpeg = Vec::new();
JpegEncoder::new_with_quality(&mut jpeg, 90).encode(&pixels, SIDE, SIDE, ExtendedColorType::Rgb8).expect("JPEG picture");
writer.write_chunk(0, &jpeg, true).expect("video chunk");
let pcm = sample.to_le_bytes().repeat(samples_per_frame);
writer.write_chunk(1, &pcm, true).expect("matching audio chunk");
}
writer.finish().expect("finish AVI").into_inner().into()
}
#[test]
fn generated_mjpeg_avi_preserves_video_seek_and_pcm_alignment() {
let bytes = mjpeg_with_pcm();
let directory = tempfile::tempdir().expect("temporary directory");
let path = directory.path().join("native-mjpeg.avi");
std::fs::write(&path, &bytes).expect("write AVI");
let native = probe(&path).expect("native AVI probe");
let name = "in-memory-mjpeg.avi";
let memory = probe_bytes(name, bytes.clone()).expect("in-memory AVI probe");
for footage in [&native, &memory] {
assert_eq!(footage.kind, FootageKind::Video);
assert_eq!((footage.width, footage.height), (SIDE, SIDE));
assert_eq!(footage.frame_rate, FrameRate::FPS_25);
assert_eq!(footage.duration, Tick::from_units(2, i64::from(FPS)));
assert_eq!(footage.codec, "Motion JPEG");
assert!(footage.has_video && footage.has_audio);
}
let native_pool = MediaPool::new();
let memory_pool = MediaPool::new();
memory_pool.add_bytes(name, bytes);
for (frame, dominant, other, sign) in [(0, 0, 2, 1.0), (1, 2, 0, -1.0), (0, 0, 2, 1.0)] {
let at = Tick::from_units(frame, i64::from(FPS));
let native_frame = native_pool.frame_at(&native, at).expect("native picture");
let memory_frame = memory_pool.frame_at(&memory, at).expect("in-memory picture");
let pixel = native_frame.get(i64::from(SIDE / 2), i64::from(SIDE / 2));
assert_eq!(pixel, memory_frame.get(i64::from(SIDE / 2), i64::from(SIDE / 2)));
assert!(pixel[dominant] > pixel[other] + 0.4, "picture at frame {frame}: {pixel:?}");
let native_pcm = native_pool.audio_samples(&native, at, 16, SAMPLE_RATE);
let memory_pcm = memory_pool.audio_samples(&memory, at, 16, SAMPLE_RATE);
assert_eq!(native_pcm, memory_pcm);
assert_eq!(native_pcm.len(), 32);
assert!(native_pcm.iter().all(|sample| sign * sample > 0.05), "PCM at frame {frame}: {native_pcm:?}");
}
}
+129 -7
View File
@@ -5,18 +5,16 @@ use std::io::Cursor;
use craft_media::isobmff::{Brand, Mp4Writer, SampleEntry, TimecodeConfig, TrackConfig, WriteSample, WriterOptions};
use effectcraft_project::FootageKind;
/// A two-frame 24 fps Motion JPEG MOV, with a timecode track from `start_frame` when given.
fn mov(start_frame: Option<u32>) -> Vec<u8> {
let mut jpeg = Vec::new();
image::RgbImage::from_pixel(16, 16, image::Rgb([200, 40, 90])).write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).expect("jpeg");
/// A two-frame 24 fps MOV, with a timecode track from `start_frame` when given.
fn mov(entry: SampleEntry, packet: &[u8], start_frame: Option<u32>) -> Vec<u8> {
let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).expect("writer");
let v = w.add_track(TrackConfig::new(SampleEntry::jpeg(16, 16), 24)).expect("video track");
let v = w.add_track(TrackConfig::new(entry, 24)).expect("video track");
if let Some(start) = start_frame {
let tc = TimecodeConfig { timescale: 24, frame_duration: 1, frames_per_second: 24, ..Default::default() };
w.add_timecode_track(v, tc, start).expect("timecode track");
}
for _ in 0..2 {
w.write_sample(v, WriteSample { data: &jpeg, duration: 1, composition_offset: 0, is_sync: true }).expect("frame");
w.write_sample(v, WriteSample { data: packet, duration: 1, composition_offset: 0, is_sync: true }).expect("frame");
}
w.finish().expect("finish").into_inner()
}
@@ -25,10 +23,12 @@ fn mov(start_frame: Option<u32>) -> Vec<u8> {
fn a_movies_start_timecode_is_read() {
let dir = std::env::temp_dir().join(format!("effectcraft-file-timecode-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("mkdir");
let mut jpeg = Vec::new();
image::RgbImage::from_pixel(16, 16, image::Rgb([200, 40, 90])).write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).expect("jpeg");
// 10:00:00:00 at 24 fps, and a movie with no timecode
for (name, start) in [("tc.mov", Some(10 * 3600 * 24)), ("none.mov", None)] {
let p = dir.join(name);
std::fs::write(&p, mov(start)).expect("write");
std::fs::write(&p, mov(SampleEntry::jpeg(16, 16), &jpeg, start)).expect("write");
let f = effectcraft_media::probe(&p).expect("probe");
assert_eq!(f.kind, FootageKind::Video, "{name}");
assert_eq!(f.file_timecode, start.map(i64::from), "{name}");
@@ -36,3 +36,125 @@ fn a_movies_start_timecode_is_read() {
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn shared_mov_preserves_recorded_start_timecode() {
use craft_media::isobmff::FourCc;
use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile};
let dir = tempfile::tempdir().expect("temp dir");
let profile = Profile::P4444;
let frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, false).expect("ProRes frame");
let packet = Encoder::new(profile, 16, 16).encode(&frame).expect("encode ProRes");
for (name, start) in [("tc.mov", Some(10 * 3600 * 24)), ("none.mov", None)] {
let entry = SampleEntry::prores(FourCc(profile.fourcc()), 16, 16);
let bytes = mov(entry, &packet, start);
let path = dir.path().join(name);
std::fs::write(&path, &bytes).expect("write MOV");
let from_file = effectcraft_media::probe(&path).expect("probe file");
let from_bytes = effectcraft_media::probe_bytes(name, bytes.into()).expect("probe bytes");
for footage in [from_file, from_bytes] {
assert_eq!(footage.kind, FootageKind::Video, "{name}");
// FilmCraft labels the same sample entry "Apple ProRes 4444".
assert_eq!(footage.codec, "ProRes", "{name}: must use the shared reader");
assert_eq!(footage.file_timecode, start.map(i64::from), "{name}");
assert_eq!(footage.start_timecode, None, "{name}: no Interpret Footage override");
}
}
}
#[test]
fn shared_mov_timecode_rebases_edl_labels_on_its_own_presentation_clock() {
use craft_media::isobmff::{self, CodecConfig, Edit, FourCc, TrackKind};
use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile};
use effectcraft_media::{MediaPool, probe_bytes};
use effectcraft_time::{FrameRate, Tick};
const START: u32 = 10 * 3600 * 24;
const MOVIE_CLOCK: u32 = 24;
const VIDEO_CLOCK: u32 = 48;
const TC_CLOCK: u32 = 96;
const UNIT_RATE: i32 = 0x0001_0000;
let edit = |segment_duration, media_time| Edit { segment_duration, media_time, media_rate: UNIT_RATE };
let profile = Profile::P4444;
let mut encoder = Encoder::new(profile, 16, 16);
let mut frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, false).expect("ProRes frame");
let packets = [40, 120, 200].map(|luma| {
frame.y.fill(luma << 8);
encoder.encode(&frame).expect("encode ProRes")
});
// The timecode track is written independently to vary its real media edit,
// rather than accidentally using the video's edit as a timecode adjustment.
let make_mov = |video_edits: Vec<Edit>, tc_edits: Vec<Edit>, counter: u32, movie_clock: u32| {
let mut opts = WriterOptions::new(Brand::Mov);
opts.movie_timescale = movie_clock;
let mut w = Mp4Writer::new(Cursor::new(Vec::new()), opts).expect("writer");
let mut video_cfg = TrackConfig::new(SampleEntry::prores(FourCc(profile.fourcc()), 16, 16), VIDEO_CLOCK);
video_cfg.edits = video_edits;
let video = w.add_track(video_cfg).expect("video track");
let tc = TimecodeConfig { timescale: TC_CLOCK, frame_duration: 4, frames_per_second: 24, ..Default::default() };
let entry =
SampleEntry { format: FourCc(*b"tmcd"), data_reference_index: 1, codec: CodecConfig::Timecode(tc), video: None, audio: None, bitrate: None };
let mut tc_cfg = TrackConfig::new(entry, TC_CLOCK);
tc_cfg.edits = tc_edits;
let tc = w.add_track(tc_cfg).expect("timecode track");
for packet in &packets {
w.write_sample(video, WriteSample { data: packet, duration: 2, composition_offset: 0, is_sync: true }).expect("write ProRes");
}
w.write_sample(tc, WriteSample { data: &counter.to_be_bytes(), duration: 12, composition_offset: 0, is_sync: true }).expect("write timecode");
w.finish().expect("finish").into_inner()
};
let pool = MediaPool::new();
let plain: std::sync::Arc<[u8]> = make_mov(vec![], vec![], START, MOVIE_CLOCK).into();
let unedited = probe_bytes("plain.mov", plain.clone()).expect("probe unedited MOV");
assert_eq!(unedited.file_timecode, Some(i64::from(START)));
pool.add_bytes("plain.mov", plain);
let at = |presentation_frame| Tick::from_units(presentation_frame, i64::from(MOVIE_CLOCK));
let pixels = [0, 1, 2].map(|n| pool.frame_at(&unedited, at(n)).expect("decode unedited reference").data[0]);
assert!(pixels[0][0] < pixels[1][0] && pixels[1][0] < pixels[2][0], "reference pictures must be distinct");
let cases = [
("matched-trim.mov", vec![edit(2, 2)], vec![edit(2, 4)], START, -4, START + 1, [(START + 1, 0, 1), (START + 2, 1, 2)]),
("video-only-trim.mov", vec![edit(2, 2)], vec![], START + 1, 0, START + 1, [(START + 1, 0, 1), (START + 2, 1, 2)]),
("matched-delay.mov", vec![edit(1, -1), edit(3, 0)], vec![edit(1, -1), edit(3, 0)], START, 4, START - 1, [(START, 1, 0), (START + 1, 2, 1)]),
];
for (name, video_edits, tc_edits, counter, tc_pts, expected_origin, points) in cases {
let bytes: std::sync::Arc<[u8]> = make_mov(video_edits, tc_edits, counter, MOVIE_CLOCK).into();
let parsed = isobmff::open(bytes.as_ref()).expect("parse generated MOV");
let tc = parsed.tracks.iter().find(|track| track.kind == TrackKind::Timecode).expect("timecode track");
assert_eq!(tc.presentation_pts(0), Some(tc_pts), "{name}: fixture timecode edit");
let footage = probe_bytes(name, bytes.clone()).expect("probe edited MOV");
assert_eq!(footage.codec, "ProRes", "{name}: must use the shared reader");
assert_eq!(footage.native_rate.unwrap_or(footage.frame_rate), FrameRate::FPS_24);
let origin = footage.file_timecode.expect("usable presentation timecode");
assert_eq!(origin, i64::from(expected_origin), "{name}");
pool.add_bytes(name, bytes);
for (edl_label, presentation_frame, picture) in points {
// The EDL importer subtracts this origin at the native video rate.
let rebased = i64::from(edl_label) - origin;
assert_eq!(rebased, presentation_frame, "{name}: EDL in-point");
let image = pool.frame_at(&footage, at(rebased)).expect("decode rebased in-point");
assert_eq!(image.data[0], pixels[picture], "{name}: decoded source picture");
}
}
let disjoint = make_mov(vec![edit(1, 0), edit(1, 4)], vec![], START, MOVIE_CLOCK);
let footage = probe_bytes("disjoint.mov", disjoint.into()).expect("probe disjoint MOV");
assert_eq!(footage.codec, "ProRes", "ambiguous timecode alone must not force a decoder fallback");
assert_eq!(footage.file_timecode, None, "a single EDL origin cannot describe disjoint edits");
// One millisecond cannot be represented in the 96 Hz timecode track.
// The demuxer reports zero after conversion, but the EDL origin is ambiguous.
let fractional = make_mov(vec![], vec![edit(1, -1), edit(125, 0)], START, 1000);
let parsed = isobmff::open(fractional.as_slice()).expect("parse fractional delay MOV");
let tc = parsed.tracks.iter().find(|track| track.kind == TrackKind::Timecode).expect("timecode track");
assert_eq!(tc.presentation_pts(0), Some(0), "demux rounded the empty edit");
let footage = probe_bytes("fractional.mov", fractional.into()).expect("probe fractional delay MOV");
assert_eq!(footage.file_timecode, None, "do not turn a fractional delay into a fabricated origin");
}
+747 -3
View File
@@ -1,7 +1,7 @@
//! Footage import against ffmpeg as an external oracle.
//!
//! Fixtures are generated with ffmpeg into `target/fixtures/media` (never committed); every test
//! skips (passes with a note) when ffmpeg is not installed. Decoded frames are compared with
//! Oracle fixtures are generated with ffmpeg into `target/fixtures/media` (never committed);
//! tests using them skip when ffmpeg is not installed. Decoded frames are compared with
//! frames ffmpeg extracts to PNG (PSNR, premultiplied RGBA).
use std::path::{Path, PathBuf};
@@ -385,7 +385,10 @@ fn resampled_audio_read_in_frame_pieces_matches_ffmpeg() {
/// The H.264 fixture with the rotation part of its video track header's matrix (`[a b; c d]`,
/// 16.16 fixed point) replaced: what a phone writes for a movie shot with the camera turned.
fn turned_mp4(p: &Path, abcd: [i32; 4]) -> Arc<[u8]> {
let mut bytes = std::fs::read(p).expect("read");
turn_mp4_bytes(std::fs::read(p).expect("read"), abcd)
}
fn turn_mp4_bytes(mut bytes: Vec<u8>, abcd: [i32; 4]) -> Arc<[u8]> {
// (The video track comes first; a version 0 `tkhd` has its matrix 44 bytes after the type.)
let at = bytes.windows(4).position(|w| w == b"tkhd").expect("tkhd");
assert_eq!(bytes[at + 4], 0, "a version 0 tkhd");
@@ -461,6 +464,158 @@ fn prores_4444_with_alpha() {
assert!(pool.frame_at(&g, Tick::ZERO).expect("frame").data.iter().all(|p| p[3] == 1.0));
}
/// The alpha mode follows the coded frame, even when a MOV writer signals an inconsistent depth.
#[test]
fn prores_alpha_uses_coded_frame_not_mov_depth() {
use craft_media::isobmff::{self, Brand, FourCc, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile};
let profile = Profile::P4444;
let mut encoder = Encoder::new(profile, 16, 16);
let mut frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, true).unwrap();
for row in frame.alpha.as_mut().unwrap().as_chunks_mut::<16>().0 {
row[..8].fill(0);
}
for (depth, mode) in [(24, AlphaMode::Straight), (32, AlphaMode::Ignore)] {
if mode == AlphaMode::Ignore {
frame.alpha = None;
}
let packet = encoder.encode(&frame).unwrap();
let mut entry = SampleEntry::prores(FourCc(profile.fourcc()), 16, 16);
entry.video.as_mut().unwrap().depth = depth;
let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap();
let output_track = writer.add_track(TrackConfig::new(entry, 24)).unwrap();
writer.write_sample(output_track, WriteSample { data: &packet, duration: 1, composition_offset: 0, is_sync: true }).unwrap();
let bytes: Arc<[u8]> = writer.finish().unwrap().into_inner().into();
let mov = isobmff::open(bytes.as_ref()).unwrap();
assert_eq!(mov.tracks[0].video().unwrap().depth, depth);
let name = format!("prores4444_depth{depth}.mov");
let footage = probe_bytes(&name, bytes.clone()).expect("probe ProRes 4444");
assert_eq!(footage.codec, "ProRes", "must exercise the shared reader, not legacy fallback");
assert_eq!(footage.alpha, mode, "MOV depth {depth}");
let pool = MediaPool::new();
pool.add_bytes(&name, bytes);
let image = pool.frame_at(&footage, Tick::ZERO).expect("decode ProRes 4444");
assert_eq!((image.width, image.height), (16, 16));
let left_alpha = if mode == AlphaMode::Straight { 0.0 } else { 1.0 };
assert!((image.data[0][3] - left_alpha).abs() < 0.02);
assert!(image.data[15][3] > 0.97);
}
}
/// Generated PCM ramps expose edit-list timing without an external encoder or oracle.
#[test]
fn mov_pcm_edit_lists_preserve_first_read_and_seek_timing() {
use craft_media::isobmff::{self, Brand, Edit, FourCc, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile};
const RATE: u32 = 48_000;
const AUDIO_FRAMES: usize = 12_000;
let samples: Vec<[i16; 2]> = (0..AUDIO_FRAMES).map(|i| [1000 + (i % 257) as i16 * 32, -2000 - (i % 193) as i16 * 16]).collect();
let profile = Profile::Hq;
let mut encoder = Encoder::new(profile, 16, 16);
let packet = encoder.encode(&Frame::new(16, 16, ChromaFormat::Yuv422, 10, false).unwrap()).unwrap();
// The extreme edits also guard signed buffer arithmetic on the first audio request.
for offset in [0i64, 480, -480, -i64::MAX, i64::MAX - i64::MAX % 48] {
let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap();
let video = writer.add_track(TrackConfig::new(SampleEntry::prores(FourCc(profile.fourcc()), 16, 16), 24)).unwrap();
let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: f64::from(RATE) };
let mut audio_config = TrackConfig::new(SampleEntry::pcm(pcm), RATE);
if offset > 0 {
audio_config.edits.push(Edit { segment_duration: (offset / 48) as u64, media_time: -1, media_rate: 0x0001_0000 });
}
if offset != 0 {
audio_config.edits.push(Edit { segment_duration: 240, media_time: (-offset).max(0), media_rate: 0x0001_0000 });
}
let audio = writer.add_track(audio_config).unwrap();
writer.write_sample(video, WriteSample { data: &packet, duration: 24, composition_offset: 0, is_sync: true }).unwrap();
for chunk in samples.chunks(256) {
let data: Vec<u8> = chunk.iter().flat_map(|frame| frame.iter().flat_map(|s| s.to_le_bytes())).collect();
writer.write_sample(audio, WriteSample { data: &data, duration: chunk.len() as u32, composition_offset: 0, is_sync: true }).unwrap();
}
let bytes: Arc<[u8]> = writer.finish().unwrap().into_inner().into();
let mov = isobmff::open(bytes.as_ref()).unwrap();
let track = mov.tracks.iter().find(|t| t.kind == isobmff::TrackKind::Audio).unwrap();
assert_eq!(track.edit_offset, offset, "fixture must carry the requested audio edit");
assert_eq!(track.presentation_pts(0), Some(offset));
let name = format!("pcm-edit-{offset}.mov");
let footage = probe_bytes(&name, bytes.clone()).expect("probe generated MOV");
assert_eq!(footage.codec, "ProRes", "must exercise the shared importer");
assert!(footage.has_audio);
let pool = MediaPool::new();
pool.add_bytes(&name, bytes);
let check = |start: usize, count: usize| {
let got = pool.audio_samples(&footage, Tick::from_units(start as i64, i64::from(RATE)), count, RATE);
assert_eq!(got.len(), count * 2);
for (i, frame) in got.as_chunks::<2>().0.iter().enumerate() {
let source = i64::try_from(start + i).unwrap().saturating_sub(offset);
let expected = usize::try_from(source).ok().and_then(|p| samples.get(p)).copied().unwrap_or([0, 0]);
for c in 0..2 {
assert_eq!(frame[c], f32::from(expected[c]) / 32768.0, "edit {offset}, request {start}, frame {i}, channel {c}");
}
}
got
};
let first = check(0, 2048);
let mut sequential = Vec::new();
let mut start = 0;
while start < 2048 {
let count = 127.min(2048 - start);
sequential.extend(check(start, count));
start += count;
}
assert_eq!(sequential, first, "edit {offset}: chunking must preserve samples");
for start in [3000, 100, 6000, 0, 480, 700] {
check(start, 600);
}
assert_eq!(check(0, 2048), first, "edit {offset}: reopening the decode window must preserve samples");
}
}
/// A synthetic asymmetrical aperture and rotation must determine what the shared importer shows.
#[test]
fn mov_renders_clean_aperture_before_display_rotation() {
use craft_media::isobmff::{self, Brand, CleanAperture, FourCc, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile};
let profile = Profile::P4444;
let mut frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, true).unwrap();
// Our generated alpha value uniquely labels each source coordinate.
for (i, p) in frame.alpha.as_mut().unwrap().iter_mut().enumerate() {
*p = i as u16 * 257;
}
let packet = Encoder::new(profile, 16, 16).encode(&frame).unwrap();
let mut entry = SampleEntry::prores(FourCc(profile.fourcc()), 16, 16);
let clean_aperture = CleanAperture { width: (8, 1), height: (12, 1), horiz_offset: (2, 1), vert_offset: (-1, 1) };
entry.video.as_mut().unwrap().clean_aperture = Some(clean_aperture);
let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap();
let track = writer.add_track(TrackConfig::new(entry, 24)).unwrap();
writer.write_sample(track, WriteSample { data: &packet, duration: 1, composition_offset: 0, is_sync: true }).unwrap();
let bytes = turn_mp4_bytes(writer.finish().unwrap().into_inner(), [0, 0x1_0000, -0x1_0000, 0]);
let mov = isobmff::open(bytes.as_ref()).unwrap();
assert_eq!(mov.tracks[0].video().unwrap().clean_aperture, Some(clean_aperture));
assert_eq!(mov.tracks[0].display_rotation(), Some(1));
let name = "turned_clean_aperture.mov";
let footage = probe_bytes(name, bytes.clone()).expect("probe the cropped MOV");
assert_eq!(footage.codec, "ProRes", "must exercise the shared reader, not legacy fallback");
assert_eq!((footage.width, footage.height), (12, 8));
let pool = MediaPool::new();
pool.add_bytes(name, bytes);
let image = pool.frame_at(&footage, Tick::ZERO).expect("render the cropped MOV");
assert_eq!((image.width, image.height), (12, 8));
for (x, y) in [(0, 0), (11, 0), (0, 7), (11, 7), (4, 3)] {
// Rotate 90° after cropping the source box (6, 1, 8, 12).
let source = (6 + y, 12 - x);
let expected = (source.0 + 16 * source.1) as f32 / 255.0;
assert!((image.data[y * 12 + x][3] - expected).abs() < 0.002, "pixel {x},{y} must come from {source:?}");
}
}
#[test]
fn vp9_webm_frames() {
let Some(p) = vp9_webm() else { return };
@@ -1361,3 +1516,592 @@ fn h264_bframe_route_backward_seek_cancel_color_and_draft() {
pool.cancellable(&on, &mut || resumed = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20)));
assert_eq!(resumed.map(|i| (i.width, i.height)), Some((320, 180)));
}
fn assert_seek_draft_cancel_parity(p: &Path, expected_size: (u32, u32), expected_color: Option<effectcraft_project::ColorSpace>) {
use std::sync::atomic::AtomicBool;
let f = probe(p).expect("probe");
assert_eq!((f.width, f.height), expected_size);
if let Some(c) = expected_color {
assert_eq!(f.color_profile, Some(c));
}
let pool = MediaPool::new();
let f18 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 18)).expect("frame 18");
let f13 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 13)).expect("frame 13");
let f7 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 7)).expect("frame 7");
let f0 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 0)).expect("frame 0");
for img in [&f18, &f13, &f7, &f0] {
assert_eq!((img.width, img.height), expected_size);
}
let fresh_f7 = MediaPool::new().frame(ItemId(1), &f, t_of(f.frame_rate, 7)).expect("fresh frame 7");
assert!(psnr(&f7, &fresh_f7) > 55.0, "backward seek frame 7 must match fresh decode");
let (dw, dh) = (expected_size.0 / 2, expected_size.1 / 2);
let draft = pool.frame_at_size(ItemId(1), &f, t_of(f.frame_rate, 5), dw, dh).expect("draft frame");
let full = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 5)).expect("full frame");
assert_eq!((draft.width, draft.height), (dw, dh));
assert!(psnr(&draft, &effectcraft_raster::resample(&full, dw, dh)) > 40.0, "draft frame matches resampled full frame");
let off = Arc::new(AtomicBool::new(true));
let mut cancelled = Some(Arc::clone(&f0));
pool.cancellable(&off, &mut || cancelled = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20)));
assert!(cancelled.is_none(), "cancelled read must not decode");
let on = Arc::new(AtomicBool::new(false));
let mut resumed = None;
pool.cancellable(&on, &mut || resumed = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20)));
assert_eq!(resumed.map(|i| (i.width, i.height)), Some(expected_size));
}
#[test]
fn hevc_bframe_route_backward_seek_cancel_color_and_draft() {
let Some(p) = try_ffmpeg_fixture(
"hevc_bframes_bt709.mp4",
&[
"-f",
"lavfi",
"-i",
"testsrc2=size=320x180:rate=24:duration=1",
"-c:v",
"libx265",
"-preset",
"fast",
"-x265-params",
"keyint=12:bframes=2:log-level=error",
"-pix_fmt",
"yuv420p",
"-colorspace",
"bt709",
"-color_primaries",
"bt709",
"-color_trc",
"bt709",
"-color_range",
"tv",
],
) else {
return;
};
assert_seek_draft_cancel_parity(&p, (320, 180), Some(effectcraft_project::ColorSpace::Rec709));
}
#[test]
fn vp9_webm_route_backward_seek_cancel_and_draft() {
let Some(p) = vp9_webm() else { return };
assert_seek_draft_cancel_parity(&p, (640, 360), None);
}
#[test]
fn draft_and_full_quality_cache_do_not_bleed() {
if h264_encoder() != Some("libx264") {
return;
}
let Some(p) = try_ffmpeg_fixture(
"h264_draft_full_cache.mp4",
&["-f", "lavfi", "-i", "testsrc2=size=320x180:rate=24:duration=1", "-c:v", "libx264", "-preset", "fast", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p"],
) else {
return;
};
let f = probe(&p).expect("probe");
let pool = MediaPool::new();
let t = t_of(f.frame_rate, 7);
// Request draft at `t` first, then full quality at the exact same `t` and a neighbour in the same GOP.
let draft = pool.frame_at_size(ItemId(1), &f, t, 160, 90).expect("draft frame");
assert_eq!((draft.width, draft.height), (160, 90));
let full = pool.frame_at(&f, t).expect("full frame after draft");
let full_next = pool.frame_at(&f, t_of(f.frame_rate, 8)).expect("full neighbour after draft");
let fresh = MediaPool::new().frame_at(&f, t).expect("fresh full frame");
let fresh_next = MediaPool::new().frame_at(&f, t_of(f.frame_rate, 8)).expect("fresh full neighbour");
assert!(psnr(&full, &fresh) > 55.0, "full frame after draft must match fresh full decode");
assert!(psnr(&full_next, &fresh_next) > 55.0, "full GOP neighbour after draft must not reuse draft references");
}
#[test]
fn rotated_mp4_matches_reference_orientation() {
if h264_encoder() != Some("libx264") {
return;
}
let Some(p) = try_ffmpeg_fixture(
"h264_rotate_90.mp4",
&["-f", "lavfi", "-i", "testsrc2=size=320x180:rate=24:duration=0.5", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-metadata:s:v:0", "rotate=90"],
) else {
return;
};
let f = probe(&p).expect("probe rotated mp4");
assert_eq!((f.width, f.height), (180, 320), "90-degree rotated mp4 swaps width and height");
let pool = MediaPool::new();
let img = pool.frame_at(&f, Tick::ZERO).expect("rotated frame");
assert_eq!((img.width, img.height), (180, 320));
assert!(psnr(&img, &reference_frame(&p, 0)) > 35.0, "rotated frame pixels match ffmpeg auto-rotated reference");
}
#[test]
fn webm_alpha_falls_back_to_filmcraft_preserving_alpha() {
let Some(p) = try_ffmpeg_fixture(
"vp9_alpha_fallback.webm",
&["-f", "lavfi", "-i", "format=rgba,geq=r='255':g='0':b='0':a='255*X/W':s=128x64:r=24", "-t", "0.25", "-c:v", "libvpx-vp9", "-pix_fmt", "yuva420p"],
) else {
return;
};
let f = probe(&p).expect("probe webm alpha");
assert_eq!(f.alpha, AlphaMode::Straight, "WebM alpha_mode=1 must preserve Straight alpha");
let pool = MediaPool::new();
let img = pool.frame_at(&f, Tick::ZERO).expect("webm alpha frame");
assert!(img.data[0][3] < 0.05 && img.data[127][3] > 0.95, "alpha ramp preserved via fallback");
}
#[test]
fn filmcraft_fallback_handles_mjpeg_mov() {
let Some(p) = try_ffmpeg_fixture("mjpeg_fallback.mov", &["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=24:duration=0.25", "-c:v", "mjpeg", "-q:v", "3"])
else {
return;
};
let f = probe(&p).expect("probe mjpeg fallback");
assert_eq!((f.width, f.height), (160, 120));
let pool = MediaPool::new();
let img = pool.frame_at(&f, Tick::ZERO).expect("mjpeg fallback frame");
assert_eq!((img.width, img.height), (160, 120));
}
/// A cold seek and uninterrupted playback must cross the same audible boundary. The PCM is
/// contiguous, so the test isolates reset positioning from separately handled timestamp gaps.
#[test]
fn matroska_cold_seek_applies_codec_delay_once() {
assert_matroska_cold_seek_codec_delay(8_250_000); // Exactly 396 samples, but 8 indexed ticks.
}
#[test]
fn matroska_cold_seek_matches_fractional_codec_delay_rounding() {
assert_matroska_cold_seek_codec_delay(8_260_000); // 396.48 samples, also 8 indexed ticks.
}
fn assert_matroska_cold_seek_codec_delay(delay_ns: i64) {
use craft_media::matroska::{self, MkvWriter, MuxOptions, TrackKind, TrackSpec};
use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile};
const RATE: u32 = 48_000;
const PACKET_FRAMES: usize = 4_800;
const PACKET_NS: i64 = 100_000_000;
const CHANGE_PACKET: i64 = 32;
const HALF_WINDOW: usize = 192;
let profile = Profile::P4444;
let black = Frame::new(16, 16, ChromaFormat::Yuv444, 10, false).unwrap();
let picture = Encoder::new(profile, 16, 16).encode(&black).unwrap();
let mut video = TrackSpec::new(TrackKind::Video, "V_PRORES");
video.video_size = Some((16, 16));
video.codec_private = profile.fourcc().to_vec();
video.default_duration_ns = Some(4_000_000_000);
let mut audio = TrackSpec::new(TrackKind::Audio, "A_PCM/INT/LIT");
audio.audio = Some((f64::from(RATE), 1, Some(16)));
audio.codec_delay_ns = delay_ns as u64;
audio.default_duration_ns = Some(PACKET_NS as u64);
let mut mux = MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![video, audio], MuxOptions::default()).unwrap();
mux.write_frame(0, 0, true, &picture, None).unwrap();
let silent = vec![0; PACKET_FRAMES * 2];
let signal = 16_384i16.to_le_bytes().repeat(PACKET_FRAMES);
for n in 0..40 {
let pcm = if n < CHANGE_PACKET { &silent } else { &signal };
mux.write_frame(1, n * PACKET_NS - delay_ns, true, pcm, None).unwrap();
}
let bytes = mux.finish().unwrap().into_inner();
let mkv = matroska::open(bytes.as_slice()).unwrap();
assert_eq!(mkv.tracks[1].samples[0].pts, -8);
// Distinct files and pools keep the two decoder states independent.
let dir = tempfile::tempdir().unwrap();
let warm_path = dir.path().join("sequential.mkv");
let cold_path = dir.path().join("cold.mkv");
std::fs::write(&warm_path, &bytes).unwrap();
std::fs::write(&cold_path, &bytes).unwrap();
let warm = probe(&warm_path).unwrap();
let cold = probe(&cold_path).unwrap();
for f in [&warm, &cold] {
assert!(f.has_audio);
assert_eq!(f.codec, "ProRes", "exercise the shared Matroska route, not legacy fallback");
}
let warm_pool = MediaPool::new();
for n in 0..CHANGE_PACKET - 1 {
let t = Tick::from_units(n * PACKET_FRAMES as i64, i64::from(RATE));
let _ = warm_pool.audio_samples(&warm, t, PACKET_FRAMES, RATE);
}
let boundary = CHANGE_PACKET * PACKET_FRAMES as i64 - delay_ns * i64::from(RATE) / 1_000_000_000;
let t = Tick::from_units(boundary - HALF_WINDOW as i64, i64::from(RATE));
let sequential = warm_pool.audio_samples(&warm, t, 2 * HALF_WINDOW, RATE);
assert_eq!(sequential.len(), 4 * HALF_WINDOW);
assert!(sequential[..2 * HALF_WINDOW].iter().all(|s| s.abs() < 1e-6));
assert!(sequential[2 * HALF_WINDOW..].iter().all(|s| s.abs() > 0.1));
let seek = MediaPool::new().audio_samples(&cold, t, 2 * HALF_WINDOW, RATE);
assert_eq!(seek, sequential, "cold seek must not shift the signal boundary");
}
#[test]
fn matroska_opus_audio_timing_and_seek() {
let Some(p) = try_ffmpeg_fixture(
"vp9_opus_timing.webm",
&[
"-f",
"lavfi",
"-i",
"testsrc2=size=160x120:rate=24:duration=1",
"-f",
"lavfi",
"-i",
"sine=frequency=440:sample_rate=48000:duration=1",
"-c:v",
"libvpx-vp9",
"-c:a",
"libopus",
],
) else {
return;
};
let f = probe(&p).expect("probe webm with opus");
assert!(f.has_audio, "opus audio stream detected");
let pool = MediaPool::new();
let start_audio = pool.audio_samples(&f, Tick::ZERO, 4800, 48_000);
assert_eq!(start_audio.len(), 9600);
let rms_start = (start_audio.iter().map(|v| v * v).sum::<f32>() / start_audio.len() as f32).sqrt();
assert!((rms_start - 0.0625).abs() < 0.02, "opus audio at t=0 rms {rms_start}");
let seek_audio = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000);
assert_eq!(seek_audio.len(), 9600);
let rms_seek = (seek_audio.iter().map(|v| v * v).sum::<f32>() / seek_audio.len() as f32).sqrt();
assert!((rms_seek - 0.0625).abs() < 0.02, "opus audio after seek rms {rms_seek}");
}
#[test]
fn audio_only_isobmff_and_matroska_route_through_craft_audio() {
for (file, codec, args) in [
("audio_only_aac.m4a", "aac", &["-c:a", "aac"][..]),
("audio_only_alac.m4a", "alac", &["-c:a", "alac"][..]),
("audio_only_opus.webm", "libopus", &["-c:a", "libopus"][..]),
] {
let mut ffmpeg_args = vec!["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=1"];
ffmpeg_args.extend_from_slice(args);
let Some(p) = try_ffmpeg_fixture(file, &ffmpeg_args) else {
continue;
};
let f = probe(&p).expect(codec);
assert_eq!(f.kind, FootageKind::Audio, "{file} must probe as Audio");
assert!(!f.has_video, "{file} has no video");
assert!(f.has_audio, "{file} has audio");
assert!(f.duration >= Tick(TICKS_PER_SECOND * 9 / 10), "{file} duration {:?}", f.duration);
let pool = MediaPool::new();
let start = pool.audio_samples(&f, Tick::ZERO, 4800, 48_000);
let seek = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000);
assert_eq!(start.len(), 9600);
assert_eq!(seek.len(), 9600);
let rms_seek = (seek.iter().map(|v| v * v).sum::<f32>() / seek.len() as f32).sqrt();
assert!((rms_seek - 0.0625).abs() < 0.02, "{file} seek rms {rms_seek}");
}
}
#[test]
fn mxf_route_backward_seek_cancel_and_pcm_audio() {
use std::sync::atomic::AtomicBool;
let Some(p) = mpeg2_mxf() else { return };
let f = probe(&p).expect("probe mxf");
assert_eq!(f.codec, "MPEG-2", "MXF MPEG-2 must route through shared craft-media::mxf");
let pool = MediaPool::new();
let f20 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20)).expect("frame 20");
let f5 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 5)).expect("backward seek frame 5");
assert_eq!((f20.width, f20.height), (1280, 720));
assert_eq!((f5.width, f5.height), (1280, 720));
let fresh_f5 = MediaPool::new().frame(ItemId(1), &f, t_of(f.frame_rate, 5)).expect("fresh frame 5");
assert!(psnr(&f5, &fresh_f5) > 55.0, "MXF backward seek frame 5 matches fresh decode");
let off = Arc::new(AtomicBool::new(true));
let mut cancelled = Some(Arc::clone(&f5));
pool.cancellable(&off, &mut || cancelled = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 30)));
assert!(cancelled.is_none(), "cancelled MXF read must not decode");
let pcm_start = pool.audio_samples(&f, Tick::ZERO, 4800, 48_000);
let pcm_seek = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000);
assert_eq!(pcm_start.len(), 9600);
assert_eq!(pcm_seek.len(), 9600);
let rms_seek = (pcm_seek.iter().map(|v| v * v).sum::<f32>() / pcm_seek.len() as f32).sqrt();
assert!((rms_seek - 0.0625).abs() < 0.02, "MXF PCM seek rms {rms_seek}");
}
#[test]
fn standalone_audio_formats_route_through_craft_audio() {
for (file, args) in [
("standalone_tone.wav", &["-c:a", "pcm_s16le"][..]),
("standalone_tone.aiff", &["-c:a", "pcm_s16be"][..]),
("standalone_tone.mp3", &["-c:a", "libmp3lame", "-b:a", "128k"][..]),
("standalone_tone.aac", &["-c:a", "aac", "-b:a", "128k"][..]),
("standalone_tone.ac3", &["-c:a", "ac3", "-b:a", "192k"][..]),
("standalone_tone.ogg", &["-c:a", "libopus"][..]),
] {
let mut ffmpeg_args = vec!["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=1"];
ffmpeg_args.extend_from_slice(args);
let Some(p) = try_ffmpeg_fixture(file, &ffmpeg_args) else {
continue;
};
let f = probe(&p).expect(file);
assert_eq!(f.kind, FootageKind::Audio, "{file} must probe as Audio");
assert!(!f.has_video, "{file} has no video");
assert!(f.has_audio, "{file} has audio");
assert!(f.duration >= Tick(TICKS_PER_SECOND * 8 / 10), "{file} duration {:?}", f.duration);
let pool = MediaPool::new();
let start = pool.audio_samples(&f, Tick::ZERO, 4800, 48_000);
let seek = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000);
assert_eq!(start.len(), 9600, "{file} start len");
assert_eq!(seek.len(), 9600, "{file} seek len");
let rms_seek = (seek.iter().map(|v| v * v).sum::<f32>() / seek.len() as f32).sqrt();
assert!((rms_seek - 0.0625).abs() < 0.03, "{file} seek rms {rms_seek}");
}
}
fn read_audio_sequential(pool: &MediaPool, f: &Footage, total_frames: usize, chunk_frames: usize, rate: u32) -> Vec<f32> {
let mut out = Vec::with_capacity(total_frames * 2);
let mut pos = 0usize;
while pos < total_frames {
let len = chunk_frames.min(total_frames - pos);
let t = Tick::from_units(pos as i64, i64::from(rate));
out.extend_from_slice(&pool.audio_samples(f, t, len, rate));
pos += len;
}
out
}
fn slice_rms(samples: &[f32]) -> f32 {
if samples.is_empty() {
return 0.0;
}
(samples.iter().map(|v| v * v).sum::<f32>() / samples.len() as f32).sqrt()
}
fn assert_samples_close(a: &[f32], b: &[f32], tol: f32, ctx: &str) {
assert_eq!(a.len(), b.len(), "{ctx}: length mismatch");
let max_diff = a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);
assert!(max_diff <= tol, "{ctx}: max_diff {max_diff} > {tol}");
}
fn pure_rust_aac_packets(duration_secs: usize) -> (Vec<u8>, Vec<Vec<u8>>) {
let mut enc = craft_audio::aac::Encoder::new(craft_audio::aac::EncoderConfig::cbr(48_000, 2, 128_000)).expect("aac encoder");
let asc = enc.audio_specific_config();
let samples: Vec<f32> = (0..48_000 * duration_secs).map(|i| (2.0 * std::f32::consts::PI * 440.0 * i as f32 / 48_000.0).sin() * 0.25).collect();
let mut pkts = enc.encode(&[&samples, &samples]);
pkts.extend(enc.flush());
(asc, pkts)
}
#[test]
fn mkv_and_mp4_aac_play_continuously_without_crackle_and_seek_matches_sequential() {
let dir = tempfile::tempdir().expect("tempdir");
let mp4_path = dir.path().join("aac_1546_pair.mp4");
let mkv_path = dir.path().join("aac_1546_pair.mkv");
let (asc, pkts) = pure_rust_aac_packets(2);
let entry = craft_media::isobmff::SampleEntry {
format: craft_media::isobmff::FourCc(*b"mp4a"),
data_reference_index: 1,
codec: craft_media::isobmff::CodecConfig::Aac(craft_media::isobmff::AacConfig::from_asc(asc.clone())),
video: None,
audio: Some(craft_media::isobmff::AudioParams { channels: 2, sample_size: 16, sample_rate: 48_000.0, ..Default::default() }),
bitrate: None,
};
let mut mp4_writer =
craft_media::isobmff::Mp4Writer::new(std::io::Cursor::new(Vec::new()), craft_media::isobmff::WriterOptions::new(craft_media::isobmff::Brand::Mp4))
.expect("mp4 writer");
mp4_writer.add_track(craft_media::isobmff::TrackConfig::new(entry, 48_000)).expect("add track");
for pkt in &pkts {
mp4_writer
.write_sample(0, craft_media::isobmff::WriteSample { data: pkt, duration: 1024, composition_offset: 0, is_sync: true })
.expect("write mp4 sample");
}
std::fs::write(&mp4_path, mp4_writer.finish().expect("finish mp4").into_inner()).expect("write mp4");
let mut spec = craft_media::matroska::TrackSpec::new(craft_media::matroska::TrackKind::Audio, "A_AAC");
spec.codec_private = asc;
spec.audio = Some((48_000.0, 2, None));
let mut mkv_writer =
craft_media::matroska::MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![spec], craft_media::matroska::MuxOptions::default()).expect("mkv writer");
for (i, pkt) in pkts.iter().enumerate() {
let pts_ns = (i as i64 * 1024 * 1_000_000_000) / 48_000;
mkv_writer.write_frame(0, pts_ns, true, pkt, None).expect("write mkv frame");
}
std::fs::write(&mkv_path, mkv_writer.finish().expect("finish mkv").into_inner()).expect("write mkv");
let mp4 = probe(&mp4_path).expect("probe mp4");
let mkv = probe(&mkv_path).expect("probe mkv");
let rate = 48_000u32;
let total_frames = 80_000usize;
let mp4_seq = read_audio_sequential(&MediaPool::new(), &mp4, total_frames, 4096, rate);
let mkv_seq = read_audio_sequential(&MediaPool::new(), &mkv, total_frames, 4096, rate);
// After the initial priming window (0.1s), MKV and MP4 must match without crackle.
let skip = 4800 * 2;
assert_samples_close(&mp4_seq[skip..], &mkv_seq[skip..], 0.01, "mkv vs mp4 sequential");
// Cold seeks on fresh MediaPools at t=0.5s and t=1.0s must match sequential playback.
for seek_frame in [24_000usize, 48_000usize] {
let t = Tick::from_units(seek_frame as i64, i64::from(rate));
let cold = MediaPool::new().audio_samples(&mkv, t, 4800, rate);
let start = seek_frame * 2;
assert_samples_close(&cold, &mkv_seq[start..start + 4800 * 2], 1e-4, "mkv cold seek vs sequential");
}
// Backward seek after reading near the end must also match sequential playback.
let back_pool = MediaPool::new();
let _ = back_pool.audio_samples(&mkv, Tick::from_units(60_000, i64::from(rate)), 4800, rate);
let backward = back_pool.audio_samples(&mkv, Tick::from_units(24_000, i64::from(rate)), 4800, rate);
assert_samples_close(&backward, &mkv_seq[24_000 * 2..24_000 * 2 + 4800 * 2], 1e-4, "mkv backward seek vs sequential");
}
fn build_gapped_aac_mkv(out_path: &Path, gap_at_pkt: usize, gap_ns: i64, start_offset_ns: i64) {
let (asc, pkts) = pure_rust_aac_packets(2);
let mut spec = craft_media::matroska::TrackSpec::new(craft_media::matroska::TrackKind::Audio, "A_AAC");
spec.codec_private = asc;
spec.audio = Some((48_000.0, 2, None));
let mut writer =
craft_media::matroska::MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![spec], craft_media::matroska::MuxOptions::default()).expect("mkv writer");
for (i, pkt) in pkts.iter().take(60).enumerate() {
let base_ns = (i as i64 * 1024 * 1_000_000_000) / 48_000;
let extra = if i >= gap_at_pkt { gap_ns } else { 0 };
writer.write_frame(0, start_offset_ns + base_ns + extra, true, pkt, None).expect("write mkv frame");
}
let mkv_bytes = writer.finish().expect("finish mkv").into_inner();
std::fs::write(out_path, mkv_bytes).expect("write mkv");
}
#[test]
fn audio_real_silence_gap_honored_on_sequential_and_seek() {
let dir = tempfile::tempdir().expect("tempdir");
let mkv_path = dir.path().join("real_gap.mkv");
// 24 packets (~0.512s) at 0, then a 500 ms silence gap before packet 24.
build_gapped_aac_mkv(&mkv_path, 24, 500_000_000, 0);
let f = probe(&mkv_path).expect("probe gapped mkv");
let rate = 48_000u32;
let total_frames = 72_000usize;
let seq = read_audio_sequential(&MediaPool::new(), &f, total_frames, 4096, rate);
// Pre-gap tone (0.1s..0.4s), silence gap (0.55s..0.95s), post-gap tone (1.1s..1.4s).
assert!(slice_rms(&seq[4800 * 2..19_200 * 2]) > 0.04, "pre-gap tone expected");
assert!(slice_rms(&seq[26_400 * 2..45_600 * 2]) < 1e-4, "silence gap expected");
assert!(slice_rms(&seq[52_800 * 2..67_200 * 2]) > 0.04, "post-gap tone expected");
for seek_frame in [9_600usize, 30_000usize, 54_000usize] {
let t = Tick::from_units(seek_frame as i64, i64::from(rate));
let cold = MediaPool::new().audio_samples(&f, t, 4800, rate);
let start = seek_frame * 2;
assert_samples_close(&cold, &seq[start..start + 4800 * 2], 1e-4, "gap cold seek vs sequential");
}
let back_pool = MediaPool::new();
let _ = back_pool.audio_samples(&f, Tick::from_units(54_000, i64::from(rate)), 4800, rate);
for seek_frame in [30_000usize, 9_600usize] {
let backward = back_pool.audio_samples(&f, Tick::from_units(seek_frame as i64, i64::from(rate)), 4800, rate);
let start = seek_frame * 2;
assert_samples_close(&backward, &seq[start..start + 4800 * 2], 1e-4, "gap backward seek vs sequential");
}
}
#[test]
fn audio_delayed_first_packet_honored_on_sequential_and_seek() {
let dir = tempfile::tempdir().expect("tempdir");
let mkv_path = dir.path().join("delayed_first.mkv");
// First packet delayed by 500 ms.
build_gapped_aac_mkv(&mkv_path, usize::MAX, 0, 500_000_000);
let f = probe(&mkv_path).expect("probe delayed mkv");
let rate = 48_000u32;
let total_frames = 57_600usize;
let seq = read_audio_sequential(&MediaPool::new(), &f, total_frames, 4096, rate);
// Leading silence (0..0.45s) and delayed tone (0.6s..1.0s).
assert!(slice_rms(&seq[..21_600 * 2]) < 1e-4, "leading silence expected");
assert!(slice_rms(&seq[28_800 * 2..48_000 * 2]) > 0.04, "delayed tone expected");
for seek_frame in [4_800usize, 30_000usize] {
let t = Tick::from_units(seek_frame as i64, i64::from(rate));
let cold = MediaPool::new().audio_samples(&f, t, 4800, rate);
let start = seek_frame * 2;
assert_samples_close(&cold, &seq[start..start + 4800 * 2], 1e-4, "delayed cold seek vs sequential");
}
let back_pool = MediaPool::new();
let _ = back_pool.audio_samples(&f, Tick::from_units(36_000, i64::from(rate)), 4800, rate);
for seek_frame in [30_000usize, 4_800usize] {
let backward = back_pool.audio_samples(&f, Tick::from_units(seek_frame as i64, i64::from(rate)), 4800, rate);
let start = seek_frame * 2;
assert_samples_close(&backward, &seq[start..start + 4800 * 2], 1e-4, "delayed backward seek vs sequential");
}
}
#[test]
fn avi_and_mpegts_route_through_craft_media_with_seek_and_cancel() {
use std::sync::atomic::AtomicBool;
for (file, args) in [
(
"route_h264.avi",
&[
"-f",
"lavfi",
"-i",
"testsrc2=size=160x120:rate=24:duration=1",
"-f",
"lavfi",
"-i",
"sine=frequency=440:sample_rate=48000:duration=1",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-g",
"12",
"-c:a",
"mp3",
][..],
),
(
"route_h264.ts",
&[
"-f",
"lavfi",
"-i",
"testsrc2=size=160x120:rate=24:duration=1",
"-f",
"lavfi",
"-i",
"sine=frequency=440:sample_rate=48000:duration=1",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-g",
"12",
"-c:a",
"aac",
][..],
),
] {
let Some(p) = try_ffmpeg_fixture(file, args) else {
continue;
};
let f = probe(&p).expect(file);
assert!(f.has_video && f.has_audio, "{file} must have video+audio");
let pool = MediaPool::new();
let f15 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 15)).expect("frame 15");
let f3 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 3)).expect("backward seek frame 3");
assert_eq!((f15.width, f15.height), (160, 120));
let fresh_f3 = MediaPool::new().frame(ItemId(1), &f, t_of(f.frame_rate, 3)).expect("fresh frame 3");
assert!(psnr(&f3, &fresh_f3) > 50.0, "{file} backward seek frame 3 matches fresh");
let off = Arc::new(AtomicBool::new(true));
let mut cancelled = Some(Arc::clone(&f3));
pool.cancellable(&off, &mut || cancelled = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20)));
assert!(cancelled.is_none(), "{file} cancelled read must not decode");
let pcm_seek = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000);
assert_eq!(pcm_seek.len(), 9600);
let rms = (pcm_seek.iter().map(|v| v * v).sum::<f32>() / pcm_seek.len() as f32).sqrt();
assert!((rms - 0.0625).abs() < 0.03, "{file} audio seek rms {rms}");
}
}
+1
View File
@@ -1,6 +1,7 @@
//! The crate's integration tests, one binary (each module is a former `tests/<name>.rs`).
mod aac_layout;
mod avi_mjpeg;
mod downmix;
mod exif_orientation;
mod exr_golden;
+33 -4
View File
@@ -53,10 +53,7 @@ impl Cs {
match self {
Cs::Gray => [g(0); 3],
Cs::Rgb | Cs::Pattern => [g(0), g(1), g(2)],
Cs::Cmyk => {
let k = g(3);
[(1.0 - g(0)) * (1.0 - k), (1.0 - g(1)) * (1.0 - k), (1.0 - g(2)) * (1.0 - k)]
}
Cs::Cmyk => cmyk_to_rgb(g(0), g(1), g(2), g(3)),
Cs::Lab => lab_to_rgb(c.first().copied().unwrap_or(0.0), c.get(1).copied().unwrap_or(0.0), c.get(2).copied().unwrap_or(0.0)),
Cs::Indexed { base, hival, lookup } => {
let i = (c.first().copied().unwrap_or(0.0).round().max(0.0) as usize).min(*hival);
@@ -69,6 +66,38 @@ impl Cs {
}
}
/// The screen colour of each solid overprint of cyan, magenta and yellow, indexed by
/// `c * 4 + m * 2 + y`. Paper is white.
const INK_SOLIDS: [[f64; 3]; 8] = [
[1.0, 1.0, 1.0],
[0.9422, 0.9861, 0.1296],
[0.9734, 0.1382, 0.5601],
[1.0, 0.1424, 0.0305],
[0.0754, 0.6765, 0.8047],
[0.0, 0.5965, 0.2797],
[0.2292, 0.0166, 0.5538],
[0.0251, 0.002, 0.0],
];
/// How each ink's value (C, M, Y, K) becomes the area it covers.
const INK_COVERAGE: [f64; 4] = [1.0774, 1.0434, 1.0474, 1.1823];
/// DeviceCMYK (each 0 to 1) to RGB, as the Neugebauer equations model halftone printing: the
/// solid colour of every combination of the inks, weighted by the area that combination
/// covers. The solids and the coverage curves are fitted to what After Effects shows for a
/// chart of 1,296 CMYK patches. `(1 - c)(1 - k)` makes every pale pink a bright magenta.
pub(crate) fn cmyk_to_rgb(c: f64, m: f64, y: f64, k: f64) -> [f64; 3] {
let area = |i: usize, v: f64| v.clamp(0.0, 1.0).powf(INK_COVERAGE[i]);
let (ac, am, ay, ak) = (area(0, c), area(1, m), area(2, y), area(3, k));
let mut out = [0.0; 3];
for (i, solid) in INK_SOLIDS.iter().enumerate() {
let w = (if i & 4 != 0 { ac } else { 1.0 - ac }) * (if i & 2 != 0 { am } else { 1.0 - am }) * (if i & 1 != 0 { ay } else { 1.0 - ay });
for (o, s) in out.iter_mut().zip(solid) {
*o += w * s;
}
}
out.map(|v| v * (1.0 - ak))
}
fn lab_to_rgb(l: f64, a: f64, b: f64) -> [f64; 3] {
let fy = (l + 16.0) / 116.0;
let fx = fy + a / 500.0;
+3 -3
View File
@@ -253,11 +253,11 @@ fn eps_fallback_font(name: &[u8]) -> Option<&'static [u8]> {
}
fn parse_eps(bytes: &[u8]) -> Result<Doc, Error> {
let steps = (bytes.len() as u64).saturating_mul(4).clamp(8_000_000, 256_000_000);
let limits = craft_ps::read::Limits {
// Preserve EffectCraft's established 8,000,000-unit PostScript execution budget.
steps: 8_000_000,
steps,
stack_overflow_noop: true,
skip_images: true,
skip_images: false,
keep_unpainted: true,
zero_division_zero: true,
fallback_font: Some(eps_fallback_font),
+1 -1
View File
@@ -129,7 +129,7 @@ fn pdf_forms_rotation_cmyk_and_alpha() {
// The form (CMYK red, clipped to its 10×10 box, scaled ×2) covers PDF (0..20, 0..20); the
// half-transparent black square covers PDF (0..10, 0..10). /Rotate 90: PDF (x, y) → (y, x).
let red = img.get(15, 15);
assert!(red[0] > 0.99 && red[1] < 0.01 && red[3] > 0.99, "{red:?}");
assert!(red[0] > 0.99 && (red[1] - 0.1424).abs() < 0.01 && (red[2] - 0.0305).abs() < 0.01, "CMYK 0 1 1 0, as After Effects shows it: {red:?}");
let dark = img.get(5, 5);
assert!((dark[0] - 0.5).abs() < 0.02 && dark[3] > 0.99, "{dark:?}");
assert_eq!(img.get(30, 30)[3], 0.0, "form clipped to its bounding box");
+55 -3
View File
@@ -49,9 +49,7 @@ fn eps_with_aliased_operators_device_queries_and_embedded_data_draws() {
fn eps_filter_on_a_string_source_does_not_skip_the_program() {
let square = "1 0 0 setrgbcolor 50 25 moveto 150 25 lineto 150 75 lineto 50 75 lineto closepath fill\n";
let img = "gsave 1 1 8 [1 0 0 1 0 0] (FF) /ASCIIHexDecode filter image grestore\n";
// Images aren't drawn yet, so this parses without `eps`'s nothing-skipped check.
let doc = parse(format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n{img}{square}").as_bytes()).unwrap();
assert_eq!(doc.skipped, ["image"]);
let doc = eps(format!("{img}{square}").as_bytes());
assert!(coverage(&render(&doc), 50, 25, 150, 75) > 4900.0, "drawing after an image read from a string");
}
@@ -643,3 +641,57 @@ fn eps_unembedded_reencoded_accent_uses_bundled_glyph() {
assert!(ia > 50.0 && (ia - ib).abs() < 1.0, "EPS accent {ia} vs PDF accent {ib}");
assert_eq!(ink_x(&a), ink_x(&b));
}
#[test]
fn eps_images_are_drawn() {
// Hexadecimal data read by a procedure; the program goes on after it.
let doc = eps(b"gsave 100 50 scale 2 1 8 [2 0 0 -1 0 1] { currentfile 6 string readhexstring pop } false 3 colorimage\nFF0000 00FF00\ngrestore 0 0 1 setrgbcolor 150 0 10 10 rectfill\n");
let img = render(&doc);
let (red, green) = (img.get(25, 75), img.get(75, 75));
assert!(red[0] > 0.9 && red[1] < 0.1 && red[3] > 0.99, "{red:?}");
assert!(green[1] > 0.9 && green[0] < 0.1 && green[3] > 0.99, "{green:?}");
assert!(img.get(155, 95)[2] > 0.99, "drawing continues after the image data");
// A stencil paints the current colour where its sample is 0.
let doc = eps(b"1 0 0 setrgbcolor 100 50 scale 2 1 false [2 0 0 -1 0 1] {<40>} imagemask\n");
let img = render(&doc);
assert!(img.get(25, 75)[0] > 0.9 && img.get(25, 75)[3] > 0.9, "{:?}", img.get(25, 75));
assert_eq!(img.get(75, 75)[3], 0.0);
}
#[test]
fn cmyk_converts_as_the_measured_chart_does() {
// Measured from After Effects' rendering of a CMYK chart, within 3 of 255.
for (cmyk, want) in [
([0.0, 0.0, 0.0, 0.0], [255.0, 255.0, 255.0]),
([0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0]),
([0.0, 0.25, 0.0, 0.0], [255.0, 205.0, 229.0]),
([0.0, 0.1, 0.0, 0.0], [255.0, 235.0, 244.0]),
] {
let got = crate::color::cmyk_to_rgb(cmyk[0], cmyk[1], cmyk[2], cmyk[3]).map(|v| v * 255.0);
for (g, w) in got.iter().zip(want) {
assert!((g - w).abs() < 3.0, "{cmyk:?}: {got:?} vs {want:?}");
}
}
}
#[test]
fn a_prolog_keeps_the_built_in_cmyk_conversion() {
// The idiom of Illustrator's EPS prolog: define the operator only when it does not exist.
let doc = eps(b"/setcmykcolor where { pop } { /setcmykcolor { pop pop pop pop 0 1 0 setrgbcolor } def } ifelse 0 1 1 0 setcmykcolor 0 0 10 10 rectfill\n");
let c = render(&doc).get(5, 95);
assert!(c[0] > 0.9 && c[1] < 0.3, "{c:?}");
let doc = eps(b"0.1 0.2 0.3 0.4 setcmykcolor currentcmykcolor 0.4 eq exch 0.3 eq and exch 0.2 eq and exch 0.1 eq and { 0 0 10 10 rectfill } if\n");
assert_eq!(shape_names(&doc).len(), 1);
}
#[test]
fn eps_restore_undoes_dictionary_changes() {
// Illustrator's prolog counts graphics states in a dictionary and relies on `restore` to
// take the count back down.
let doc = eps(b"/w 10 def /d 1 dict def d /v 1 put save /w 40 def d /v 2 put restore 0 0 w 10 rectfill d /v get 1 eq { 100 0 10 10 rectfill } if\n");
let img = render(&doc);
assert_eq!(img.get(20, 95)[3], 0.0, "w is 10 again");
assert!(img.get(5, 95)[3] > 0.99);
assert!(img.get(105, 95)[3] > 0.99, "d's entry is 1 again");
}
+1 -1
View File
@@ -650,7 +650,7 @@ pub fn sync_project(before: &Project, after: &mut Project) {
/// Keys given in comp time, in the time of a layer that starts at `start` and is stretched to
/// `stretch` percent. Empty when the stretch is not a usable factor.
fn keys_in_layer_time(keys: &[Keyframe], start: Tick, stretch: f64) -> Vec<Keyframe> {
pub fn keys_in_layer_time(keys: &[Keyframe], start: Tick, stretch: f64) -> Vec<Keyframe> {
if stretch.is_finite() && stretch > 0.0 { keys.iter().map(|k| key_in_layer_time(k, start, stretch)).collect() } else { vec![] }
}
+2 -1
View File
@@ -11,7 +11,8 @@ workspace = true
[dependencies]
craft-psd = { workspace = true }
miniz_oxide = "0.9"
craft-codepage = { workspace = true }
[dev-dependencies]
craft-psd = { workspace = true, features = ["testgen"] }
miniz_oxide = "0.9"
-5
View File
@@ -105,11 +105,6 @@ impl Budget {
}
}
/// Inflate a zlib stream to at most `limit` bytes.
pub(crate) fn inflate(src: &[u8], limit: usize) -> Result<Vec<u8>> {
miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(src, limit).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))
}
/// Give back what a channel buffer from `Psd::channel_bytes` / `Psd::decode_plane` was charged:
/// a borrowed one (uncompressed data, or a plane of an inflated stream charged as a whole) was not.
pub(crate) fn release_bytes(budget: &mut Budget, raw: Cow<'_, [u8]>) {
+1 -6
View File
@@ -102,7 +102,7 @@ impl Psd {
hidden: rec.flags.hidden(),
protect_transparency: rec.flags.transparency_protected(),
channels,
name: mac_roman_string(&rec.name),
name: crate::read::decode_mac_roman(&rec.name),
..Default::default()
};
if let craft_psd::MaskData::Mask(m) = &rec.mask {
@@ -489,11 +489,6 @@ fn error(e: &craft_psd::PsdError) -> Error {
}
}
/// A Pascal string's bytes in the system (Mac Roman) encoding; ASCII covers the common case.
fn mac_roman_string(b: &[u8]) -> String {
b.iter().map(|&b| if b < 0x80 { b as char } else { super::read::mac_roman(b) }).collect()
}
/// App representation only; binary field framing belongs to craft-psd.
fn from_shared_adjustment(value: craft_psd::adjust::Adjustment) -> Adjustment {
use craft_psd::adjust::Adjustment as Shared;
+47 -52
View File
@@ -1,8 +1,9 @@
#[cfg(test)]
use super::counters;
use super::limits::{Budget, DECODE_BUDGET, Error, Result, decode_pixels, finite_sample, inflate, release_bytes, too_large};
use super::limits::{Budget, DECODE_BUDGET, Error, Result, decode_pixels, finite_sample, release_bytes, too_large};
use super::model::{ColorMode, Layer, Pixels, Rect};
use super::{Psd, Reader};
use craft_psd::compression::PlaneStream;
use std::borrow::Cow;
impl Psd {
@@ -32,13 +33,15 @@ impl Psd {
pub(crate) fn plane_bytes<'a>(&self, comp: u16, r: &mut Reader<'a>, w: usize, h: usize, budget: &mut Budget) -> Result<Cow<'a, [u8]>> {
let rowb = self.row_bytes(w);
let size = rowb.checked_mul(h).ok_or_else(|| too_large(w, h))?;
Ok(match self.open_planes(comp, r, 1, 1, (w, h), budget)? {
PlaneStream::Raw => Cow::Borrowed(r.bytes(size)?),
PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(&counts, 0, r, rowb, h, budget)?),
PlaneStream::Zip(mut v) => {
v.resize(size, 0);
self.zip_plane(comp, &mut v, 0, w, h, budget)?;
Cow::Owned(v)
let mut stream = self.open_planes(comp, r, 1, 1, (w, h), budget)?;
Ok(match &mut stream {
PlaneStream::Raw { .. } => Cow::Borrowed(stream.next_raw_plane(size).map_err(compression_err)?),
PlaneStream::Rle { .. } => Cow::Owned(Self::unpack_plane(&mut stream, 0, rowb, h, budget)?),
PlaneStream::Zip { data } => {
// Single-channel recovery: zero-pad short ZIP streams before un-predicting.
data.resize(size, 0);
self.zip_plane(comp, data, 0, w, h, budget)?;
Cow::Owned(std::mem::take(data))
}
})
}
@@ -47,39 +50,31 @@ impl Psd {
/// `w`×`h` samples, of which the first `want` are decoded: the RLE row sizes of every plane,
/// or the inflated ZIP data, which holds all planes one after another (charged to `budget`
/// before it is inflated).
fn open_planes(&self, comp: u16, r: &mut Reader, total: usize, want: usize, size: (usize, usize), budget: &mut Budget) -> Result<PlaneStream> {
fn open_planes<'a>(&self, comp: u16, r: &mut Reader<'a>, total: usize, want: usize, size: (usize, usize), budget: &mut Budget) -> Result<PlaneStream<'a>> {
let (w, h) = size;
let size = self.row_bytes(w).checked_mul(h).ok_or_else(|| too_large(w, h))?;
Ok(match comp {
0 => PlaneStream::Raw,
1 => {
let n = total.saturating_mul(h);
let mut counts = Vec::with_capacity(n.min(r.remaining() / 2));
for _ in 0..n {
counts.push(if self.psb { r.u32()? as usize } else { r.u16()? as usize });
}
PlaneStream::Rle(counts)
}
2 | 3 => {
let rest = r.bytes(r.remaining())?;
// One stream holds every plane: what it may decode to is what they need.
let all = size.checked_mul(want).ok_or_else(|| too_large(w, h))?;
budget.charge(all as u64)?;
PlaneStream::Zip(inflate(rest, all)?)
}
c => return Err(Error::Unsupported(format!("compression {c}"))),
})
let plane_size = self.row_bytes(w).checked_mul(h).ok_or_else(|| too_large(w, h))?;
let zip_limit = if matches!(comp, 2 | 3) { plane_size.checked_mul(want).ok_or_else(|| too_large(w, h))? } else { 0 };
let rest = r.bytes(r.remaining())?;
PlaneStream::open(
craft_psd::Compression::from_u16(comp),
rest,
total,
h,
if self.psb { craft_psd::Version::Psb } else { craft_psd::Version::Psd },
zip_limit,
|bytes| budget.charge(bytes as u64).map_err(|e| craft_psd::PsdError::Unsupported(e.to_string())),
)
.map_err(compression_err)
}
/// The raw bytes (`row_bytes(w)` × `h`, ZIP prediction undone) of plane `c`: raw and RLE
/// planes are read from `r` in order, raw ones borrowed from the file data, ZIP ones from the
/// inflated buffer (un-predicted in place; already charged by `open_planes`), RLE ones charged
/// to `budget`.
/// planes are read from `stream` in order, raw ones borrowed from the file data, ZIP ones from
/// the inflated buffer (un-predicted in place; already charged by `open_planes`), RLE ones
/// charged to `budget`.
fn decode_plane<'x, 'a: 'x>(
&self,
comp: u16,
planes: &'x mut PlaneStream,
r: &mut Reader<'a>,
planes: &'x mut PlaneStream<'a>,
c: usize,
size: (usize, usize),
budget: &mut Budget,
@@ -88,20 +83,20 @@ impl Psd {
let rowb = self.row_bytes(w);
let size = rowb.checked_mul(h).ok_or_else(|| too_large(w, h))?;
Ok(match planes {
PlaneStream::Raw => Cow::Borrowed(r.bytes(size)?),
PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(counts, c, r, rowb, h, budget)?),
PlaneStream::Zip(v) => Cow::Borrowed(self.zip_plane(comp, v, c, w, h, budget)?),
PlaneStream::Raw { .. } => Cow::Borrowed(planes.next_raw_plane(size).map_err(compression_err)?),
PlaneStream::Rle { .. } => Cow::Owned(Self::unpack_plane(planes, c, rowb, h, budget)?),
PlaneStream::Zip { data } => Cow::Borrowed(self.zip_plane(comp, data, c, w, h, budget)?),
})
}
/// Unpack the `h` RLE rows of plane `c` (row byte counts `counts`, plane after plane) into a
/// buffer charged to `budget`.
fn unpack_plane(counts: &[usize], c: usize, r: &mut Reader, rowb: usize, h: usize, budget: &mut Budget) -> Result<Vec<u8>> {
/// Unpack the `h` RLE rows of plane `c` into a buffer charged to `budget`, using padded
/// PackBits recovery.
fn unpack_plane(planes: &mut PlaneStream<'_>, c: usize, rowb: usize, h: usize, budget: &mut Budget) -> Result<Vec<u8>> {
let mut out = budget.vec::<u8>(rowb.checked_mul(h).ok_or(Error::Truncated)?)?;
for row in 0..h {
let n = *counts.get(c * h + row).ok_or(Error::Truncated)?;
unpack_bits(r.bytes(n)?, rowb, &mut out)?;
}
planes.next_rle_plane_into(c, rowb, h, true, &mut out).map_err(|e| match e {
craft_psd::PsdError::UnexpectedEof { .. } | craft_psd::PsdError::Decompress(_) => Error::Truncated,
other => Error::Invalid(other.to_string()),
})?;
Ok(out)
}
@@ -263,7 +258,7 @@ impl Psd {
let mut black = if self.mode == ColorMode::Cmyk && want > 3 { Some(budget.filled(n, 0.0f32)?) } else { None };
let mut stream = self.open_planes(comp, &mut r, nch, want, (w, h), &mut budget)?;
for c in 0..want {
let raw = self.decode_plane(comp, &mut stream, &mut r, c, (w, h), &mut budget)?;
let raw = self.decode_plane(comp, &mut stream, c, (w, h), &mut budget)?;
self.store_merged_channel(c, &raw, &mut data, &mut black);
release_bytes(&mut budget, raw);
}
@@ -461,16 +456,16 @@ impl Psd {
}
}
/// The pixel data of a run of planes, as prepared by `Psd::open_planes`.
enum PlaneStream {
Raw,
/// RLE row byte counts of every plane, plane after plane.
Rle(Vec<usize>),
/// The inflated ZIP data of all planes.
Zip(Vec<u8>),
fn compression_err(e: craft_psd::PsdError) -> Error {
match e {
craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated,
craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s),
other => Error::Invalid(other.to_string()),
}
}
/// PackBits decoding of one row (appends exactly `row` bytes, zero-padded).
#[cfg(test)]
pub(crate) fn unpack_bits(src: &[u8], row: usize, out: &mut Vec<u8>) -> Result<()> {
// The production caller already charges/reserves the complete plane in Budget.
// Keep the shared recovery API bounded to this row; never relax the app budget.
+10 -5
View File
@@ -80,12 +80,17 @@ impl<'a> Reader<'a> {
let padded = total.div_ceil(pad) * pad;
self.skip(padded - total)?;
// Pascal strings are in the system (Mac Roman) encoding; ASCII covers the common case.
Ok(s.iter().map(|&b| if b < 0x80 { b as char } else { mac_roman(b) }).collect())
Ok(decode_mac_roman(s))
}
}
/// Mac OS Roman upper half (0x80..=0xFF), as published by the Unicode Consortium mapping table.
pub(crate) fn mac_roman(b: u8) -> char {
const T: &str = "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ\u{F8FF}ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ";
T.chars().nth((b - 0x80) as usize).unwrap_or('?')
/// Decode the legacy Pascal names in PSD and PSB.
pub(crate) fn decode_mac_roman(bytes: &[u8]) -> String {
bytes
.iter()
.map(|&byte| {
// Keep the ordinary space EffectCraft used for this byte in legacy Pascal names.
if byte == 0xca { ' ' } else { craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, byte) }
})
.collect()
}
+2 -1
View File
@@ -7,6 +7,7 @@ mod fixed_adjustments;
mod fixed_writers;
mod integration;
mod opt;
mod parity;
mod scalar_blocks;
mod section_divider;
mod shared_corpus;
@@ -527,7 +528,7 @@ fn a_failed_inflate_reports_its_status_not_its_output() {
let mut z = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 1 << 20], 6);
let n = z.len();
z[n - 1] ^= 0xff;
let Err(Error::Invalid(msg)) = crate::limits::inflate(&z, 1 << 21) else { panic!("the checksum fails") };
let Err(craft_psd::PsdError::Decompress(msg)) = craft_psd::compression::zip_decompress_up_to(&z, 1 << 21) else { panic!("the checksum fails") };
assert!(msg.len() < 100, "{} bytes", msg.len());
}
+2 -3
View File
@@ -69,7 +69,7 @@ fn ref_decode_channel(p: &Psd, offset: usize, len: usize, w: usize, h: usize) ->
}
2 | 3 => {
let rest = r.bytes(r.remaining())?;
let mut v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, rowb * h).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))?;
let mut v = craft_psd::compression::zip_decompress_up_to(rest, rowb * h).map_err(|e| Error::Invalid(e.to_string()))?;
v.resize(rowb * h, 0);
if comp == 3 {
ref_unpredict(p.depth, &mut v, w, h);
@@ -112,8 +112,7 @@ fn ref_composite(p: &Psd) -> Result<Pixels> {
}
2 | 3 => {
let rest = r.bytes(r.remaining())?;
let v =
miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, want * rowb * h).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))?;
let v = craft_psd::compression::zip_decompress_up_to(rest, want * rowb * h).map_err(|e| Error::Invalid(e.to_string()))?;
for (c, pl) in planes.iter_mut().enumerate().take(want) {
let mut plane = v.get(c * rowb * h..(c + 1) * rowb * h).ok_or(Error::Truncated)?.to_vec();
if comp == 3 {
+136
View File
@@ -0,0 +1,136 @@
//! Parity and recovery tests for PSD/PSB composite alpha, malformed resources,
//! RLE/ZIP plane framing, and save/reopen round-trips.
use crate::write::*;
use crate::*;
use craft_psd::{Compression, ImageResource, Version};
/// Convert an encoded PSD into a PSB (or vice versa) with the specified compression
/// for both layers and the merged image, using `craft_psd::PsdFile`.
fn reencode_with(bytes: &[u8], version: Version, comp: Compression, merged_alpha: bool) -> Vec<u8> {
let mut file = craft_psd::PsdFile::from_bytes(bytes).expect("parse");
let depth = file.header.depth;
let old_ver = file.header.version;
file.header.version = version;
file.write_as_psb = version.is_psb();
if let Some(info) = file.layer_info.as_mut() {
info.merged_alpha = merged_alpha;
for rec in &mut info.layers {
let rects: Vec<(usize, usize)> = rec.channels.iter().map(|ch| rec.channel_rect(ch.id).size().expect("channel rect")).collect();
for (ch, (w, h)) in rec.channels.iter_mut().zip(rects) {
if w > 0 && h > 0 {
let decoded = ch.decode(w, h, depth, old_ver).expect("decode channel");
*ch = craft_psd::ChannelData::encode(ch.id, comp, &decoded, w, h, depth, version).expect("encode channel");
}
}
}
}
let decoded_merged = file.image_data.decode(&craft_psd::Header { version: old_ver, ..file.header.clone() }).expect("decode merged");
file.image_data = craft_psd::ImageData::encode(comp, &decoded_merged, &file.header).expect("encode merged");
file.to_bytes().expect("write")
}
#[test]
fn psd_and_psb_composite_alpha_flag_controls_alpha_channel() {
let mut doc = WDoc::new(4, 3);
doc.layers = vec![WLayer::solid("Semi", Rect::new(0, 0, 4, 3), [0.8, 0.4, 0.2, 0.5])];
let base = write(&doc);
for version in [Version::Psd, Version::Psb] {
let with_alpha = reencode_with(&base, version, Compression::Rle, true);
let p_alpha = Psd::parse(with_alpha).expect("parse with alpha");
assert_eq!(p_alpha.psb, version.is_psb());
assert!(p_alpha.merged_alpha);
let comp_alpha = p_alpha.composite().expect("composite with alpha");
assert!((comp_alpha.data[0][3] - 0.5).abs() < 0.02, "{version:?}: {:?}", comp_alpha.data[0]);
let without_alpha = reencode_with(&base, version, Compression::Rle, false);
let p_opaque = Psd::parse(without_alpha).expect("parse without alpha");
assert_eq!(p_opaque.psb, version.is_psb());
assert!(!p_opaque.merged_alpha);
let comp_opaque = p_opaque.composite().expect("composite without alpha");
assert_eq!(comp_opaque.data[0][3], 1.0, "{version:?}: {:?}", comp_opaque.data[0]);
}
}
#[test]
fn malformed_resources_recover_in_both_psd_and_psb() {
let mut doc = WDoc::new(6, 4);
doc.layers = vec![WLayer::solid("L", Rect::new(1, 1, 3, 2), [0.2, 0.6, 0.9, 0.75])];
let base = write(&doc);
for version in [Version::Psd, Version::Psb] {
let mut file = craft_psd::PsdFile::from_bytes(&reencode_with(&base, version, Compression::Rle, true)).expect("parse");
file.resources.push(ImageResource::new(1005, vec![0; 16]));
let intact = file.to_bytes().expect("write");
let want = Psd::parse(intact.clone()).expect("intact parse");
// Corrupt the first resource's declared length so it overruns the resource section.
let mut damaged = intact;
let res_at = 30 + u32::from_be_bytes(damaged[26..30].try_into().expect("cmd len")) as usize;
let name_len = 1 + usize::from(damaged[res_at + 4 + 6]);
let len_at = res_at + 4 + 6 + name_len + name_len % 2;
damaged[len_at..len_at + 4].copy_from_slice(&0x7fff_fff0u32.to_be_bytes());
let recovered = Psd::parse(damaged).expect("recovered parse");
assert!(recovered.warnings.is_empty(), "{version:?}: {:?}", recovered.warnings);
assert_eq!(recovered.psb, version.is_psb());
assert_eq!(recovered.merged_alpha, want.merged_alpha);
assert_eq!(recovered.layers.len(), want.layers.len());
assert_eq!(recovered.composite().expect("comp").data, want.composite().expect("want comp").data);
assert_eq!(recovered.layer_pixels(0, false).expect("layer").data, want.layer_pixels(0, false).expect("want layer").data);
}
}
#[test]
fn rle_and_zip_planes_decode_across_psd_and_psb() {
let mut doc = WDoc::new(8, 6);
doc.layers =
vec![WLayer::solid("Base", Rect::new(0, 0, 8, 6), [0.25, 0.5, 0.75, 1.0]), WLayer::solid("Overlay", Rect::new(2, 1, 4, 4), [1.0, 0.25, 0.0, 0.6])];
let base = write(&doc);
let reference = Psd::parse(base.clone()).expect("base parse");
let ref_comp = reference.composite().expect("ref comp").data;
let ref_l0 = reference.layer_pixels(0, false).expect("ref l0").data;
let ref_l1 = reference.layer_pixels(1, true).expect("ref l1").data;
for version in [Version::Psd, Version::Psb] {
for comp in [Compression::Raw, Compression::Rle, Compression::Zip, Compression::ZipPrediction] {
let bytes = reencode_with(&base, version, comp, true);
let p = Psd::parse(bytes).expect("parse");
assert_eq!(p.psb, version.is_psb());
assert_eq!(p.composite().expect("comp").data, ref_comp, "{version:?} {comp:?} composite");
assert_eq!(p.layer_pixels(0, false).expect("l0").data, ref_l0, "{version:?} {comp:?} l0");
assert_eq!(p.layer_pixels(1, true).expect("l1").data, ref_l1, "{version:?} {comp:?} l1");
}
}
}
#[test]
fn save_and_reopen_parity_preserves_psd_and_psb_documents() {
let mut doc = WDoc::new(10, 8);
doc.layers = vec![
WLayer::group_end(),
WLayer::solid("Child", Rect::new(1, 2, 5, 4), [0.4, 0.8, 0.2, 0.9]).with_blend(b"mul ").with_opacity(200),
WLayer::group("Folder", true, *b"pass"),
];
let initial = write(&doc);
for version in [Version::Psd, Version::Psb] {
for comp in [Compression::Rle, Compression::ZipPrediction] {
let saved = reencode_with(&initial, version, comp, true);
let reopened_bytes = craft_psd::PsdFile::from_bytes(&saved).expect("parse saved").to_bytes().expect("resave");
assert_eq!(reopened_bytes, saved, "{version:?} {comp:?} round-trip bytes");
let a = Psd::parse(saved).expect("parse first");
let b = Psd::parse(reopened_bytes).expect("parse reopened");
assert_eq!(a.psb, b.psb);
assert_eq!(a.merged_alpha, b.merged_alpha);
assert_eq!(a.layers.len(), b.layers.len());
for (la, lb) in a.layers.iter().zip(&b.layers) {
assert_eq!((&la.name, la.blend, la.opacity, la.section), (&lb.name, lb.blend, lb.opacity, lb.section));
}
assert_eq!(a.composite().expect("comp a").data, b.composite().expect("comp b").data);
assert_eq!(a.layer_pixels(1, true).expect("l1 a").data, b.layer_pixels(1, true).expect("l1 b").data);
}
}
}
+26
View File
@@ -84,3 +84,29 @@ fn missing_empty_or_malformed_unicode_name_keeps_pascal_name() {
assert_eq!(Psd::parse(file.to_bytes().unwrap()).unwrap().layers[0].name, "Pascal");
}
}
#[test]
fn pascal_layer_name_keeps_legacy_mac_roman_and_unicode_precedence() {
let mut doc = WDoc::new(1, 1);
doc.rle = false; // The raw pixels have the same layout in PSD and PSB.
doc.layers = vec![WLayer::empty("Fallback", vec![])];
let bytes = write(&doc);
for version in [craft_psd::Version::Psd, craft_psd::Version::Psb] {
let mut file = craft_psd::PsdFile::from_bytes(&bytes).unwrap();
file.header.version = version;
file.layer_info.as_mut().unwrap().layers[0].name = b"Caf\x8e\xca\xdb".to_vec();
for (unicode, expected) in
[(None, "Caf\u{e9} \u{20ac}"), (Some(vec![0, 0, 0, 1, 0]), "Caf\u{e9} \u{20ac}"), (Some(record(&[0x0041, 0x00a0, 0x0042])), "A\u{a0}B")]
{
let layer = &mut file.layer_info.as_mut().unwrap().layers[0];
layer.blocks.retain(|b| b.key != *b"luni");
if let Some(data) = unicode {
layer.blocks.push(craft_psd::tagged::TaggedBlock::new(*b"luni", data));
}
let parsed = Psd::parse(file.to_bytes().unwrap()).unwrap();
assert_eq!(parsed.psb, version.is_psb());
assert_eq!(parsed.layers[0].name, expected);
}
}
}
+16 -9
View File
@@ -723,15 +723,22 @@ fn hash_blend_spans(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer) {
/// Feed every property of `g` that can change over time (keyframes or expression) as its value
/// at the context time. The static structure is hashed separately.
/// Mix the collapsed-instance overrides that target `id` into a cache key. They replace values
/// Mix the collapsed-instance overrides that target `layer` into a cache key. They replace values
/// without editing the layer, so a key without them would reuse another instance's buffer.
fn hash_overrides(h: &mut KeyHasher, ctx: &EvalCtx, id: effectcraft_project::LayerId) {
for o in ctx.property_overrides.iter().filter(|o| o.layer == id) {
fn hash_overrides(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer) {
for o in ctx.property_overrides.iter().filter(|o| o.layer == layer.id) {
o.prop.hash(h);
o.font.hash(h);
hash_debug(h, &o.value);
hash_debug(h, &o.keys);
// The stored value belongs to the outer context. The nested layer can be compared with
// its previous frame while that value stays fixed, so hash the effective value at the
// target layer's exact time as well.
if let Some(prop) = layer.props.find(o.prop) {
hash_debug(h, &o.value_at_layer_time(prop, layer.layer_time(ctx.time)));
}
}
for m in ctx.media_overrides.iter().filter(|m| m.layer == id) {
for m in ctx.media_overrides.iter().filter(|m| m.layer == layer.id) {
m.item.hash(h);
}
}
@@ -754,8 +761,8 @@ fn hash_values(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer, g: &PropGroup) {
/// time, or `None` when the layer must not be cached (movie footage, precomps, cameras, adjustment
/// layers…).
pub fn layer_key(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool) -> Option<u64> {
// Time effects (and CC Particle World's Birth Rate history) see property values at other
// times. Keyframes are part of the hashed structure (and the layer time is folded in), but
// Time effects (and stepped particle systems' Birth Rate and producer history) see property
// values at other times. Keyframes are part of the hashed structure (and the layer time is folded in), but
// expressions may read other layers at those times, which the key cannot see: such layers
// are not cached.
if history_unkeyable(layer, None) {
@@ -778,8 +785,8 @@ pub fn input_key(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bo
}
/// Does the layer run (among its first `effects` effects, all when `None`) an effect that reads
/// the layer at other times (Echo, Timewarp…) or its own parameters' history (CC Particle
/// World's Birth Rate, #1373)?
/// the layer at other times (Echo, Timewarp…) or its own parameters' history (stepped particle
/// systems' Birth Rate and producer position, #1373)?
fn reads_other_times(layer: &Layer, effects: Option<usize>) -> bool {
layer.switches.effects
&& layer.effects().is_some_and(|fx| {
@@ -930,7 +937,7 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo
// Collapsed-instance overrides replace values without editing the nested layer, so mix them
// into the key: a Font override, effect parameter or any other source-affecting override
// must not reuse another instance's processed buffer.
hash_overrides(&mut h, ctx, layer.id);
hash_overrides(&mut h, ctx, layer);
hash_debug(&mut h, &layer.source);
// (Audio, Lock and Shy don't change pixels.)
hash_debug(&mut h, &layer.switches.pixels());
+2 -2
View File
@@ -87,7 +87,7 @@ impl Dependencies<'_> {
hash_debug(self.h, layer);
// An overridden clip plays on the layer clock and a keyed one from its key: the same
// selection at the same time can pose differently.
super::hash_overrides(self.h, ctx, layer.id);
super::hash_overrides(self.h, ctx, layer);
hash_values(self.h, ctx, layer, &layer.props);
hash_debug(self.h, &ctx.world_matrix(layer));
if let Some(item) = layer.source.item() {
@@ -148,7 +148,7 @@ impl Dependencies<'_> {
hash_debug(self.h, layer);
// A referenced layer's static values can be overridden by the collapsed instance without
// editing it (`hash_values` only sees animated ones), so the owner's key needs them too.
super::hash_overrides(self.h, ctx, layer.id);
super::hash_overrides(self.h, ctx, layer);
hash_values(self.h, ctx, layer, &layer.props);
hash_debug(self.h, &ctx.world_matrix(layer));
// A cached owner never runs this layer's effects, so the comp camera and lights its
+50 -9
View File
@@ -3,8 +3,10 @@
//! Keyframe times are stored in **layer time** (they move with the layer), so evaluating a
//! property at comp time `t` first maps `t` through the layer's start time and stretch.
use std::borrow::Cow;
use effectcraft_geom::{Mat3, Mat4, Vec3, vec2, vec3};
use effectcraft_keyframe::Value;
use effectcraft_keyframe::{Value, evaluate, evaluate_orientation};
use effectcraft_project::{Comp, ItemId, Layer, LayerId, LayerSource, Project, PropGroup, Property};
use effectcraft_time::Tick;
@@ -57,12 +59,21 @@ impl<'a> EvalCtx<'a> {
pub fn at(&self, time: Tick) -> EvalCtx<'a> {
EvalCtx { time, ..*self }
}
/// The property as this context evaluates it: a collapsed Essential Property override
/// replaces its value and keyframes, while a Font override merges only the font. The
/// expression stays on the property and is not evaluated here.
pub fn effective_property<'p>(&self, layer: &Layer, prop: &'p Property) -> Cow<'p, Property> {
let Some(o) = self.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == prop.uid) else {
return Cow::Borrowed(prop);
};
Cow::Owned(o.effective_property(prop))
}
/// Value of a property at the context time (keyframes, then expression).
pub fn value(&self, layer: &Layer, prop: &Property) -> Value {
// A collapsed precomp instance's Essential Property override replaces the base value;
// its expression (if any) still runs, and sees the overrides of this context.
if let Some(o) = self.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == prop.uid) {
let v = o.value(layer, prop, self.time);
let v = o.value_at_layer_time(prop, layer.layer_time(self.time));
if prop.has_expression()
&& let Some(h) = self.expr
{
@@ -87,7 +98,12 @@ impl<'a> EvalCtx<'a> {
/// fractional stretch: a Hold key at `lt` could read its previous value). An expression
/// still runs at the context time.
pub fn value_at_layer_time(&self, layer: &Layer, prop: &Property, lt: Tick) -> Value {
let v = prop.value_at(lt);
let v = self
.property_overrides
.iter()
.rev()
.find(|o| o.layer == layer.id && o.prop == prop.uid)
.map_or_else(|| prop.value_at(lt), |o| o.value_at_layer_time(prop, lt));
if prop.has_expression()
&& let Some(h) = self.expr
{
@@ -283,16 +299,41 @@ impl<'a> EvalCtx<'a> {
}
impl crate::PropertyOverride {
pub(crate) fn value(&self, layer: &Layer, prop: &Property, time: Tick) -> Value {
/// The target property with this override applied, without evaluating its expression.
fn effective_property(&self, prop: &Property) -> Property {
let mut property = prop.clone();
if self.font {
// A Font control merges only the font into the target text, as
// `essential::with_overrides` does.
let mut value = prop.value_at(layer.layer_time(time));
effectcraft_project::essential::merge_font(&mut value, &self.value);
value
// `essential::with_overrides` does. The target's own text and keyframes stay.
effectcraft_project::essential::merge_font(&mut property.value, &self.value);
for key in &mut property.keys {
effectcraft_project::essential::merge_font(&mut key.value, &self.value);
}
} else {
self.value.clone()
property.keys = self.keys.clone();
property.value = self.value.clone();
}
property
}
/// The overridden value at the target layer's exact `layer_time`.
pub(crate) fn value_at_layer_time(&self, prop: &Property, layer_time: Tick) -> Value {
if self.font {
// A Font override leaves the target's history in place and merges its font into the
// value that history selects. The same font is merged into every key, so merging
// after evaluation is equivalent and avoids cloning all the target's keys.
let mut value = prop.value_at(layer_time);
effectcraft_project::essential::merge_font(&mut value, &self.value);
return value;
}
if self.keys.is_empty() {
return self.value.clone();
}
// Match `Property::value_at` for the replacement history, including orientation's
// shortest-arc interpolation and spatial position paths.
if prop.match_id == "orientation" && matches!(self.value, Value::Vec3(_)) {
return evaluate_orientation(&self.keys, layer_time).unwrap_or_else(|| self.value.clone());
}
evaluate(&self.keys, layer_time, prop.spatial).unwrap_or_else(|| self.value.clone())
}
}
+26 -5
View File
@@ -139,7 +139,13 @@ impl EffectHost for FxHost<'_, '_, '_> {
}
fn param_is_static(&self, effect_index: usize, id: &str) -> bool {
effect_param(self.layer, effect_index, id).is_some_and(|p| p.keys.is_empty() && !p.has_expression())
let Some(p) = effect_param(self.layer, effect_index, id) else { return false };
let Some(o) = self.ctx.property_overrides.iter().rev().find(|o| o.layer == self.layer.id && o.prop == p.uid) else {
return p.keys.is_empty() && !p.has_expression();
};
// A whole-value override replaces the target property's keys. A Font override leaves them
// in place, so those keys still make the value vary over time.
o.keys.is_empty() && !p.has_expression() && (!o.font || p.keys.is_empty())
}
fn comp_scene(&self) -> Option<effectcraft_effects::CompScene> {
@@ -210,10 +216,25 @@ pub fn essential_overrides(ctx: &EvalCtx, layer: &Layer) -> Vec<effectcraft_proj
if over.contains(&p.uid)
&& let Some(control) = essential::control_of(&p.match_id)
{
// An expression on the instance property replaces its keys, and so does an override
// from a collapsed parent (only its value reaches here, the keys are the stale own ones).
let from_parent = ctx.property_overrides.iter().any(|o| o.layer == layer.id && o.prop == p.uid);
let keys = if same_time && !from_parent && !p.has_expression() { p.keys.clone() } else { vec![] };
// An expression on the instance property replaces its keys. A whole-value override
// from a collapsed parent replaces the instance's own keys with the parent's; a Font
// override leaves them in place, so the font merges into their history.
let parent = ctx.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == p.uid);
let keys = if !same_time || p.has_expression() {
vec![]
} else if let Some(parent) = parent {
if parent.font {
let mut keys = p.keys.clone();
for key in &mut keys {
effectcraft_project::essential::merge_font(&mut key.value, &parent.value);
}
keys
} else {
parent.keys.clone()
}
} else {
p.keys.clone()
};
out.push(essential::Override { control, value: ctx.value(layer, p), keys });
}
});
+23 -15
View File
@@ -9,7 +9,7 @@ use super::{
ItemId, ItemKind, Layer, LayerCache, LayerSource, Params, Project, Quality, Region, Renderer, Tick, cache, color, masks, shapes, styles, text, three_d,
vec2,
};
use effectcraft_keyframe::Value;
use effectcraft_keyframe::{Keyframe, Value};
use effectcraft_project::LayerId;
/// Coordinate space and stack range shared by CPU and accelerated effect evaluation.
@@ -44,6 +44,8 @@ pub struct PropertyOverride {
pub(crate) layer: LayerId,
pub(crate) prop: u64,
pub(crate) value: Value,
/// The override's keyframes, in the target layer's time.
pub(crate) keys: Vec<Keyframe>,
/// A Font control changes only the font of the target text, not its text.
pub(crate) font: bool,
}
@@ -122,28 +124,29 @@ fn collapsed_instance(ctx: &EvalCtx, layer: &Layer, item: ItemId) -> Option<(Vec
if over.is_empty() {
return Some((vec![], vec![]));
}
let g = essential::group(layer)?;
let eg = ctx.project.comp(item)?.essential.as_ref()?;
essential::group(layer)?;
let nc = ctx.project.comp(item)?;
let eg = nc.essential.as_ref()?;
let mut property = vec![];
let mut fonts: Vec<PropertyOverride> = vec![];
let mut media = vec![];
g.walk("", &mut |_, p| {
if !over.contains(&p.uid) {
return;
}
let Some(control) = essential::control_of(&p.match_id) else { return };
let Some(ctl) = eg.resolve(control) else { return };
let value = ctx.value(layer, p);
for over in essential_overrides(ctx, layer) {
let Some(ctl) = eg.resolve(over.control) else { continue };
match &ctl.kind {
EgKind::Property { .. } => {
let font = ctl.as_type == Some(ControlType::Font);
for (layer, prop) in ctl.kind.targets() {
let o = PropertyOverride { layer, prop, value: value.clone(), font };
for (target_layer, prop) in ctl.kind.targets() {
let keys = if font {
vec![]
} else {
nc.layer(target_layer).map(|target| essential::keys_in_layer_time(&over.keys, target.start_time, target.stretch)).unwrap_or_default()
};
let o = PropertyOverride { layer: target_layer, prop, value: over.value.clone(), keys, font };
if font { fonts.push(o) } else { property.push(o) }
}
}
EgKind::Media { layer: target } => {
let Value::Scalar(id) = value else { return };
let Value::Scalar(id) = over.value else { continue };
let item = ItemId(id.max(0.0) as u64);
if matches!(ctx.project.item(item).map(|i| &i.kind), Some(ItemKind::Footage(_))) {
media.push(MediaOverride { layer: *target, item });
@@ -151,12 +154,17 @@ fn collapsed_instance(ctx: &EvalCtx, layer: &Layer, item: ItemId) -> Option<(Vec
}
_ => {}
}
});
}
// A Font control merges into the text its instance shows, after a whole-value (Text) override
// of the same property, as `essential::with_overrides` does: keep one entry per property.
for f in fonts {
match property.iter_mut().rev().find(|o| o.layer == f.layer && o.prop == f.prop) {
Some(o) => effectcraft_project::essential::merge_font(&mut o.value, &f.value),
Some(o) => {
effectcraft_project::essential::merge_font(&mut o.value, &f.value);
for key in &mut o.keys {
effectcraft_project::essential::merge_font(&mut key.value, &f.value);
}
}
None => property.push(f),
}
}
+28
View File
@@ -697,6 +697,34 @@ fn particle_systems_ii_and_mr_mercury_keep_a_burst_after_birth_rate_drops_to_zer
}
}
/// A Particle Playground cannon-position expression reads the cannon's position at earlier
/// times, so its layer cannot be served from a cache keyed only by the current value.
#[test]
fn particle_playground_with_a_cannon_position_expression_is_not_layer_cached() {
let (mut p, cid, comp) = setup();
let mut l = solid(&mut p, &comp, [0.0, 0.0, 0.0], 200, 100);
add_effect(
&mut p,
&mut l,
"ec.sim.particleplayground",
[200.0, 100.0],
&[("grid/particlesAcross", Value::Scalar(0.0)), ("grid/particlesDown", Value::Scalar(0.0)), ("cannon/particlesPerSecond", Value::Scalar(60.0))],
);
p.comp_mut(cid).unwrap().layers.push(l);
let c = p.comp(cid).unwrap();
let key = crate::cache::layer_key(&crate::eval::EvalCtx::new(&p, cid, c, Tick::from_seconds_f64(0.9)), &c.layers[0], 1.0, false, false);
assert!(key.is_some(), "a static cannon position is cacheable");
let fx = p.comp_mut(cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.iter_mut().find_map(|c| match c {
effectcraft_project::Node::Group(g) => Some(g),
_ => None,
});
fx.unwrap().prop_mut("cannon/cannonPosition").unwrap().expr = Some(effectcraft_project::Expression { text: "time * 10".into(), enabled: true });
let c = p.comp(cid).unwrap();
let key = crate::cache::layer_key(&crate::eval::EvalCtx::new(&p, cid, c, Tick::from_seconds_f64(0.9)), &c.layers[0], 1.0, false, false);
assert!(key.is_none(), "the cannon's parameter history is not cacheable");
}
/// A Birth Rate expression on any of the stepped particle systems keeps the layer out of the
/// layer cache (its key can't see what the expression returned at earlier times); without one
/// the layer is cached.
+148 -6
View File
@@ -1,9 +1,9 @@
//! Collapse Transformations, Continuously Rasterize and the Quality switch.
use effectcraft_color::{BlendMode, Label};
use effectcraft_keyframe::{TextDoc, Value};
use effectcraft_keyframe::{Keyframe, TextDoc, Value};
use effectcraft_project::build::{self, Ids};
use effectcraft_project::{BitDepth, Comp, FrameBlend, ItemId, ItemKind, Layer, LayerSource, Project, Quality, Solid};
use effectcraft_project::{BitDepth, Comp, FrameBlend, GroupKind, ItemId, ItemKind, Layer, LayerSource, Project, Quality, Solid};
use effectcraft_time::{FrameRate, Tick};
use crate::{EvalCtx, Image, NoFootage, RenderOpts, Renderer, render_frame};
@@ -90,6 +90,145 @@ fn collapsed_precomp_equals_manual_flattening() {
assert!((half.get(x, y)[0] - (bg + (full - bg) * 0.5)).abs() < 0.03, "{:?} vs {full}", half.get(x, y));
}
/// A Particle Emitter 2D producer in a nested comp, overridden by a keyframed Essential
/// Property on the collapsed precomp instance. The particles born earlier follow the instance
/// override's history, just as they do on the flattened path.
#[test]
fn a_collapsed_particle_producer_follows_the_instance_override_history() {
use effectcraft_project::essential::{self, EgControl, EgKind, EssentialGraphics};
fn scene(collapse: bool) -> (Project, ItemId) {
let mut p = project();
let mut outer = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
let mut inner = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
let mut layer = solid(&mut p, &inner, [0.0, 0.0, 0.0], (200, 100), [100.0, 50.0, 0.0]);
let spec = effectcraft_effects::find("ec.sim.ccparticlesystems2").unwrap();
let mut next = p.next_id;
let mut effect = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [200.0, 100.0]);
p.next_id = next;
effect.prop_mut("birthRate").unwrap().value = Value::Scalar(60.0);
effect.prop_mut("longevity").unwrap().value = Value::Scalar(5.0);
let producer = effect.sub_mut("producer").unwrap().prop_mut("position").unwrap();
producer.value = Value::Vec2([140.0, 50.0]);
producer.keys = vec![Keyframe::new(Tick::ZERO, Value::Vec2([140.0, 50.0])), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Vec2([160.0, 50.0]))];
let producer_uid = producer.uid;
for (group, name) in [("producer", "radiusX"), ("producer", "radiusY"), ("physics", "velocity"), ("physics", "gravity")] {
effect.sub_mut(group).unwrap().prop_mut(name).unwrap().value = Value::Scalar(0.0);
}
layer.props.sub_mut("effects").unwrap().children.push(effect.into());
let layer_id = layer.id;
inner.layers = vec![layer].into();
let inner_id = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into()));
p.comp_mut(inner_id).unwrap().essential = Some(EssentialGraphics {
controls: vec![EgControl {
id: 1,
name: "Producer".into(),
kind: EgKind::Property { layer: layer_id, prop: producer_uid, links: vec![] },
as_type: None,
}],
..Default::default()
});
let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: inner_id }, (200, 100), None);
let mut next = p.next_id;
let mut ids = Ids(&mut next);
let mut control = ids.prop(&essential::match_id(1), "Producer", Value::Vec2([20.0, 50.0]));
control.keys = vec![Keyframe::new(Tick::ZERO, Value::Vec2([20.0, 50.0])), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Vec2([120.0, 50.0]))];
let mut group = ids.group(essential::GROUP, "Essential Properties");
group.kind = GroupKind::Essential { overridden: vec![control.uid] };
group.children.push(control.into());
pre.props.children.push(group.into());
p.next_id = next;
pre.switches.collapse = collapse;
outer.layers = vec![pre].into();
let outer_id = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.into()));
(p, outer_id)
}
fn particle_span(img: &Image) -> (f32, f32) {
let (mut first, mut last, mut mass) = (f32::INFINITY, f32::NEG_INFINITY, 0.0);
for y in 0..img.height {
for x in 0..img.width {
let red = img.get(x as i64, y as i64)[0];
if red > 0.001 {
first = first.min(x as f32);
last = last.max(x as f32);
mass += red;
}
}
}
assert!(mass > 1.0, "particles drawn");
(first, last)
}
let (p, cid) = scene(false);
let flattened = particle_span(&render_frame(&p, cid, Tick::from_seconds_f64(1.0), 1.0));
let (p, cid) = scene(true);
let comp = p.comp(cid).unwrap();
let ctx = EvalCtx::new(&p, cid, comp, Tick::from_seconds_f64(1.0));
assert!(Renderer::new(&p, &NoFootage, RenderOpts::default()).collapsed(&ctx, &comp.layers[0]).is_some(), "the precomp stays collapsed");
let collapsed = particle_span(&render_frame(&p, cid, Tick::from_seconds_f64(1.0), 1.0));
// The override moves the producer from x=20 to x=120. The trail must reach both ends,
// independently of whether the flattened and collapsed paths agree.
assert!(collapsed.0 < 30.0 && collapsed.1 > 110.0, "collapsed producer trail {collapsed:?}");
assert!(
(flattened.0 - collapsed.0).abs() < 2.0 && (flattened.1 - collapsed.1).abs() < 2.0,
"collapsed producer history: {collapsed:?} vs flattened {flattened:?}"
);
}
/// A keyframed Source Text override on a collapsed precomp changes the nested text layer at
/// its exact layer times. Its processed-layer key must change too, or the previous nested frame
/// is reused and the old text stays on screen.
#[test]
fn an_animated_collapsed_text_override_changes_the_nested_layer_cache_key() {
use effectcraft_project::essential::{self, EgControl, EgKind, EssentialGraphics};
fn text(value: &str) -> Value {
Value::Text(Box::new(TextDoc { text: value.into(), size: 60.0, ..Default::default() }))
}
let mut p = project();
let mut outer = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
let mut inner = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
let mut layer = build::layer(&mut p, &inner, "Text", LayerSource::Text, (200, 100), None);
layer.props.prop_mut("text/sourceText").unwrap().value = text("BASE");
let layer_id = layer.id;
let source_uid = layer.props.prop("text/sourceText").unwrap().uid;
inner.layers = vec![layer].into();
inner.essential = Some(EssentialGraphics {
controls: vec![EgControl { id: 1, name: "Text".into(), kind: EgKind::Property { layer: layer_id, prop: source_uid, links: vec![] }, as_type: None }],
..Default::default()
});
let inner_id = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into()));
let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: inner_id }, (200, 100), None);
let mut next = p.next_id;
let mut ids = Ids(&mut next);
let mut control = ids.prop(&essential::match_id(1), "Text", text("A"));
control.keys = vec![Keyframe::new(Tick::ZERO, text("A")), Keyframe::new(Tick::from_seconds_f64(1.0), text("B"))];
let mut group = ids.group(essential::GROUP, "Essential Properties");
group.kind = GroupKind::Essential { overridden: vec![control.uid] };
group.children.push(control.into());
pre.props.children.push(group.into());
p.next_id = next;
pre.switches.collapse = true;
outer.layers = vec![pre].into();
let outer_id = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.into()));
let outer = p.comp(outer_id).unwrap();
let pre = &outer.layers[0];
let renderer = Renderer::new(&p, &NoFootage, RenderOpts::default());
let ctx = EvalCtx::new(&p, outer_id, outer, Tick::from_seconds_f64(1.0));
let collapsed = renderer.collapsed(&ctx, pre).unwrap();
let (_, nested) = renderer.collapse_into(&ctx, pre, &collapsed, 1.0).unwrap();
let layer = &nested.comp.layers[0];
let before = nested.time - nested.comp.frame_rate.frame_duration();
let now_key = crate::cache::layer_key(&nested, layer, 1.0, false, false).unwrap();
let before_key = crate::cache::layer_key(&nested.at(before), layer, 1.0, false, false).unwrap();
assert_ne!(now_key, before_key, "the animated Source Text override changes the nested layer's pixels");
}
#[test]
fn masks_on_a_collapsed_layer_force_a_flattened_render() {
let (mut p, cid) = scene(true, false);
@@ -159,8 +298,7 @@ fn referenced_layer_overrides_change_the_owner_cache_key() {
let comp = p.comp(cid).unwrap();
let b = comp.layer(bid).unwrap();
let opacity = comp.layer(aid).unwrap().props.prop("transform/opacity").unwrap().uid;
let key = |value: f64| {
let overrides = [crate::PropertyOverride { layer: aid, prop: opacity, value: Value::Scalar(value), font: false }];
let key = |overrides: &[crate::PropertyOverride]| {
let ctx = EvalCtx {
project: &p,
comp_id: cid,
@@ -168,15 +306,19 @@ fn referenced_layer_overrides_change_the_owner_cache_key() {
time: Tick::ZERO,
expr: None,
footage: None,
property_overrides: &overrides,
property_overrides: overrides,
media_overrides: &[],
reads: None,
};
crate::cache::layer_key(&ctx, b, 1.0, false, false)
};
let (opaque, half) = (key(100.0), key(50.0));
let override_at = |value: f64, keys: Vec<Keyframe>| [crate::PropertyOverride { layer: aid, prop: opacity, value: Value::Scalar(value), keys, font: false }];
let (opaque, half) = (key(&override_at(100.0, vec![])), key(&override_at(50.0, vec![])));
assert!(opaque.is_some(), "the owner is cacheable");
assert_ne!(opaque, half, "A's static override changes B's key");
let early = override_at(100.0, vec![Keyframe::new(Tick::ZERO, Value::Scalar(25.0))]);
let late = override_at(100.0, vec![Keyframe::new(Tick::ZERO, Value::Scalar(75.0))]);
assert_ne!(key(&early), key(&late), "A's override history changes B's key");
}
#[test]
+1 -1
View File
@@ -284,7 +284,7 @@ pub fn animator_selection_within(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup,
let stat = if prop.has_expression() {
// The expression is not run here, but an Essential Property override still wins over the base value.
match ctx.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == prop.uid) {
Some(o) => o.value(layer, prop, ctx.time),
Some(o) => o.value_at_layer_time(prop, layer.layer_time(ctx.time)),
None => prop.value_at(layer.layer_time(ctx.time)),
}
} else {
+18 -6
View File
@@ -287,11 +287,23 @@ File.prototype = {
copy: function (to) { return JSON.parse(__file("copy", this.__path, __str(to))); },
rename: function () { throw __err("File.rename is not supported"); },
execute: function () { return JSON.parse(__file("execute", this.__path)); },
openDlg: function () { return null; },
saveDlg: function () { return null; },
openDlg: function (prompt, filter, multiSelect) { return __pickFile("open", prompt, filter, multiSelect, this.__path); },
saveDlg: function (prompt, filter) { return __pickFile("save", prompt, filter, false, this.__path); },
};
File.openDialog = function () { return null; };
File.saveDialog = function () { return null; };
// The app's file dialog (#2778): a File (an array of them with multiSelect), a Folder for
// "folder", or null when cancelled, and where no dialog can be shown (the Script Console, the
// web, headless runs). Filters are strings ("*.jsx", "Audio:*.mp3;*.wav"); a function (macOS)
// offers every file.
function __pickFile(kind, prompt, filter, multiSelect, start) {
var opt = function (v) { return v === undefined || v === null ? null : __str(v); };
var r = JSON.parse(__fileDialog(kind, opt(prompt), typeof filter === "string" ? filter : null, !!multiSelect, opt(start)));
if (!r || !r.length) return null;
if (kind === "folder") return new Folder(r[0]);
if (kind === "open" && multiSelect) return r.map(function (p) { return new File(p); });
return new File(r[0]);
}
File.openDialog = function (prompt, filter, multiSelect) { return __pickFile("open", prompt, filter, multiSelect); };
File.saveDialog = function (prompt, filter) { return __pickFile("save", prompt, filter, false); };
File.decode = function (s) { return decodeURIComponent(s); };
File.encode = function (s) { return encodeURIComponent(s); };
File.fs = "EffectCraft";
@@ -354,9 +366,9 @@ Folder.prototype = {
}
return out;
},
selectDlg: function () { return null; },
selectDlg: function (prompt) { return __pickFile("folder", prompt, null, false, this.__path); },
};
Folder.selectDialog = function () { return null; };
Folder.selectDialog = function (prompt) { return __pickFile("folder", prompt, null, false); };
Object.defineProperty(Folder, "current", { get: function () { var d = __get("app").projectDir; return d ? new Folder(d) : null; } });
Object.defineProperty(Folder, "temp", { get: function () { return null; } });
Object.defineProperty(Folder, "desktop", { get: function () { return null; } });
+2 -1
View File
@@ -562,7 +562,7 @@ pub(crate) fn new_context() -> Result<Context, String> {
let limits = ctx.runtime_limits_mut();
limits.set_loop_iteration_limit(200_000_000);
limits.set_recursion_limit(2000);
let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>); 11] = [
let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>); 12] = [
(js_string!("__exec"), 2, native_exec),
(js_string!("__query"), 2, native_query),
(js_string!("__print"), 1, native_print),
@@ -574,6 +574,7 @@ pub(crate) fn new_context() -> Result<Context, String> {
(js_string!("__uiNewId"), 0, crate::ui::native_new_id),
(js_string!("__uiModal"), 1, crate::ui::native_modal),
(js_string!("__uiLayoutNative"), 1, crate::ui::native_layout),
(js_string!("__fileDialog"), 5, crate::ui::native_file_dialog),
];
for (name, len, f) in natives {
ctx.register_global_callable(name, len, NativeFunction::from_fn_ptr(f)).map_err(|e| e.to_string())?;
+15
View File
@@ -288,3 +288,18 @@ fn empty_or_missing_folders_run_nothing() {
crate::install(&mut s);
assert_eq!(s.execute("file.runShutdownScripts", json!({})).unwrap(), none);
}
/// #2778: the app is quitting, so nothing would show a Shutdown script's file dialog: it gets null
/// at once instead of waiting for good.
#[test]
fn a_shutdown_script_file_dialog_does_not_wait() {
let store = Arc::new(MemoryConfig::default());
let probe = r#"var f = File.saveDialog("Save the log", "*.txt"); app.settings.saveSetting("Startup Test", "log", f === null ? "none" : "asked");"#;
store.write(&format!("{SHUTDOWN_DIR}/Save Log.jsx"), probe).unwrap();
let mut s = session(&store);
s.script_ui.answers_file_dialogs = true;
let r = s.execute("file.runShutdownScripts", json!({})).unwrap();
assert_eq!(r, json!({"ran": ["Save Log.jsx"], "waiting": [], "failed": []}));
assert_eq!(setting(&mut s, "log"), "none");
assert!(s.script_ui.file_dialogs.is_empty());
}
+122
View File
@@ -297,3 +297,125 @@ fn sample_scripts_and_installing() {
let _ = std::fs::remove_dir_all(&dir);
let _: Value = json!(null);
}
const PICK_AUDIO: &str = r#"
var d = new Window("dialog", "Pick Audio");
var song = d.add("edittext", undefined, "", { name: "song" });
var browse = d.add("button", undefined, "Browse...", { name: "browse" });
browse.onClick = function () {
var f = File.openDialog("Select a song", "Audio:*.MP3;*.wav,All files:*.*");
song.text = f ? f.fsName : "(cancelled)";
};
var where = d.add("button", undefined, "Folder...", { name: "where" });
where.onClick = function () {
var f = Folder.selectDialog("Output folder");
song.text = f instanceof Folder ? "folder " + f.fsName : "(cancelled)";
};
d.add("button", undefined, "OK", { name: "ok" });
var r = d.show();
r + " " + song.text
"#;
/// #2778: File.openDialog, Folder.selectDialog… in a dialog's Browse… handler. With a frontend
/// that shows scripts' file dialogs, the script waits for `scriptui.fileDialog`'s answer (the
/// picked files, or null when cancelled); headless runs get null at once.
#[test]
fn file_dialogs_wait_for_their_answer() {
let mut s = session();
// Headless: nothing shows a dialog, so the script never waits on one.
let o = run_code(&mut s, r#"var f = File.openDialog("Pick"); f === null ? "none" : "picked""#, "headless.jsx");
assert!(!o.waiting && o.error.is_none(), "{o:?}");
assert_eq!(o.result, json!("none"));
assert!(s.script_ui.file_dialogs.is_empty());
s.script_ui.answers_file_dialogs = true;
// At the top of a script, with multiSelect: an array of Files.
let o = run_code(&mut s, r#"var fs = File.openDialog("Pick scripts", "*.jsx", true); fs ? fs.length + " " + fs[1].name : "none""#, "top.jsx");
assert!(o.waiting, "{o:?}");
let asked = s.execute("scriptui.fileDialogs", json!({})).unwrap();
assert_eq!(asked[0]["kind"], "open", "{asked}");
assert_eq!((asked[0]["prompt"].clone(), asked[0]["exts"].clone(), asked[0]["many"].clone()), (json!("Pick scripts"), json!(["jsx"]), json!(true)));
let r = s.execute("scriptui.fileDialog", json!({"paths": ["/a/x.jsx", "/b/y.jsx"]})).unwrap();
assert_eq!(r["result"], "2 y.jsx", "{r}");
assert!(s.script_ui.file_dialogs.is_empty());
// In a modal dialog's Browse… handler.
let o = run_code(&mut s, PICK_AUDIO, "pick.jsx");
assert!(o.waiting, "{o:?}");
let r = s.execute("scriptui.click", json!({"widget": "browse"})).unwrap();
assert_eq!(r["waiting"], true, "{r}");
let asked = s.script_ui.file_dialogs.clone();
assert_eq!(asked.len(), 1);
assert_eq!(asked[0].exts, ["mp3", "wav"], "the filter's extensions, `*.*` adds none");
assert_eq!((asked[0].label.as_str(), asked[0].any, asked[0].many), ("Audio", true, false));
// An answer for another dialog (a stale one) is refused; this one still waits.
let e = s.execute("scriptui.fileDialog", json!({"id": asked[0].id + 1000, "paths": null})).unwrap_err().to_string();
assert!(e.contains("no such file dialog"), "{e}");
assert_eq!(s.script_ui.file_dialogs.len(), 1);
// The dialog's controls wait for the answer.
let e = s.execute("scriptui.click", json!({"widget": "ok"})).unwrap_err().to_string();
assert!(e.contains("waiting for its file dialog"), "{e}");
// Cancelled: null.
s.execute("scriptui.fileDialog", json!({"paths": null})).unwrap();
let song = |s: &Session| s.script_ui.windows[0].root.lookup(&json!("song")).map(|w| w.text.clone()).unwrap_or_default();
assert_eq!(song(&s), "(cancelled)");
s.execute("scriptui.click", json!({"widget": "browse"})).unwrap();
// Only one file without multiSelect.
s.execute("scriptui.fileDialog", json!({"paths": ["/media/song.wav", "/media/other.wav"]})).unwrap();
assert_eq!(song(&s), "/media/song.wav");
s.execute("scriptui.click", json!({"widget": "where"})).unwrap();
assert_eq!(s.script_ui.file_dialogs[0].kind, effectcraft_engine::scriptui::FileDialogKind::Folder);
s.execute("scriptui.fileDialog", json!({"paths": ["/media/out"]})).unwrap();
assert_eq!(song(&s), "folder /media/out");
let r = s.execute("scriptui.click", json!({"widget": "ok"})).unwrap();
assert_eq!(r["result"], "1 folder /media/out", "{r}");
// Nothing waits any more.
assert!(s.execute("scriptui.fileDialog", json!({"paths": null})).is_err());
// A file dialog whose answer never comes doesn't trap its script window: closing it cancels
// the file dialog, then closes the window.
let o = run_code(&mut s, PICK_AUDIO, "pick.jsx");
assert!(o.waiting, "{o:?}");
s.execute("scriptui.click", json!({"widget": "browse"})).unwrap();
assert_eq!(s.script_ui.file_dialogs.len(), 1);
let r = s.execute("scriptui.close", json!({})).unwrap();
assert_eq!(r["result"], "2 (cancelled)", "{r}");
assert!(s.script_ui.windows.is_empty() && s.script_ui.file_dialogs.is_empty());
}
/// A script can't answer or close another script's waiting file dialog (it would take the dialog
/// off the list and leave its script waiting for good): refused, and the window still closes.
#[test]
fn scripts_cannot_strand_a_waiting_file_dialog() {
let mut s = session();
s.script_ui.answers_file_dialogs = true;
let o = run_code(&mut s, PICK_AUDIO, "pick.jsx");
assert!(o.waiting, "{o:?}");
s.execute("scriptui.click", json!({"widget": "browse"})).unwrap();
let (window, id) = (s.script_ui.windows[0].id, s.script_ui.file_dialogs[0].id);
// From the Script Console.
for (command, params) in [("scriptui.close", json!({"window": window})), ("scriptui.fileDialog", json!({"id": id, "paths": ["/x.wav"]}))] {
let code = format!("try {{ __exec({command:?}, {:?}); \"ran\" }} catch (e) {{ \"refused\" }}", params.to_string());
let o = crate::run(&mut s, &effectcraft_engine::ScriptRequest { code: &code, name: "console", console: true });
assert_eq!(o.result, json!("refused"), "{command}: {o:?}");
assert_eq!(s.script_ui.file_dialogs.len(), 1, "{command}: the dialog still waits");
}
let r = s.execute("scriptui.close", json!({"window": window})).unwrap();
assert_eq!(r["result"], "2 (cancelled)", "{r}");
assert!(s.script_ui.windows.is_empty() && s.script_ui.file_dialogs.is_empty());
}
#[test]
fn file_dialog_filters_name_their_extensions() {
use crate::ui::filter_exts;
assert_eq!(filter_exts("*.jsx"), ["jsx"]);
assert_eq!(filter_exts("Audio:*.MP3;*.wav,All files:*.*"), ["mp3", "wav"]);
assert_eq!(filter_exts("Images (*.png, *.jpg)|*.png;*.jpg"), ["png", "jpg"]);
assert!(filter_exts("*.*").is_empty() && filter_exts("").is_empty() && filter_exts("*.").is_empty());
use crate::ui::{filter_any, filter_label};
assert_eq!(filter_label("Audio:*.mp3;*.wav,All files:*.*"), "Audio");
assert_eq!(filter_label("Images (*.png, *.jpg)|*.png;*.jpg"), "Images");
assert_eq!(filter_label("*.jsx"), "");
assert!(filter_any("Audio:*.mp3,All files:*.*") && filter_any("Any|*"));
assert!(!filter_any("*.jsx") && !filter_any(""));
}
+150 -18
View File
@@ -18,7 +18,7 @@ use std::sync::atomic::{AtomicU32, Ordering};
use boa_engine::{Context, JsResult, JsValue, js_string};
use effectcraft_engine::Session;
use effectcraft_engine::scriptui::{ScriptUiEvent, ScriptWindow, layout};
use effectcraft_engine::scriptui::{FILE_DIALOG_EVENT, FileDialogKind, ScriptFileDialog, ScriptUiEvent, ScriptWindow, layout};
use serde_json::{Value as J, json};
use web_time::Instant;
@@ -126,6 +126,116 @@ pub(crate) fn native_modal(_: &JsValue, args: &[JsValue], ctx: &mut Context) ->
}
}
/// The extensions a ScriptUI file filter names, lower case: `"*.wav"`, `"Audio:*.mp3;*.wav,All
/// files:*.*"` (Windows), `"Audio (*.mp3, *.wav)|*.mp3;*.wav"`… Wildcard-only patterns (`*.*`)
/// name none; a filter without extensions (or a macOS filter function) offers every file.
pub(crate) fn filter_exts(filter: &str) -> Vec<String> {
const MAX_EXTS: usize = 64;
const MAX_LEN: usize = 16;
let mut out: Vec<String> = vec![];
for part in filter.split("*.").skip(1) {
let ext: String = part.chars().take_while(char::is_ascii_alphanumeric).collect();
if ext.is_empty() || ext.len() > MAX_LEN {
continue;
}
let ext = ext.to_ascii_lowercase();
if !out.contains(&ext) {
out.push(ext);
}
if out.len() >= MAX_EXTS {
break;
}
}
out
}
/// The name a ScriptUI file filter gives its first entry (`"Audio"` in `"Audio:*.mp3;*.wav"`,
/// `"Audio (*.mp3)|*.mp3"`); empty when it gives none.
pub(crate) fn filter_label(filter: &str) -> String {
const MAX_LEN: usize = 64;
let Some(end) = filter.find([':', '|']) else { return String::new() };
// "Audio (*.mp3, *.wav)": the name without its list of patterns.
let label = filter.get(..end).unwrap_or_default();
let label = label.split('(').next().unwrap_or_default().trim();
if label.contains('*') { String::new() } else { label.chars().take(MAX_LEN).collect() }
}
/// Whether a ScriptUI file filter also offers every file (`*.*`, or a bare `*` pattern).
pub(crate) fn filter_any(filter: &str) -> bool {
filter.contains("*.*") || filter.split([':', '|', ';', ',']).any(|p| p.trim() == "*")
}
static NEXT_FILE_DIALOG: AtomicU32 = AtomicU32::new(1);
/// Argument `i` as text; empty when null or missing.
fn text_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<String> {
match args.get(i) {
None => Ok(String::new()),
Some(v) if v.is_null() || v.is_undefined() => Ok(String::new()),
Some(v) => Ok(v.to_string(ctx)?.to_std_string_escaped()),
}
}
/// `__fileDialog(kind, prompt, filter, multiSelect, start)` → `[path…]` JSON or `null`:
/// `File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the instance `openDlg` /
/// `saveDlg` / `selectDlg` (#2778). On a script-host thread, with a frontend that shows the
/// scripts' file dialogs ([`effectcraft_engine::scriptui::ScriptUi::answers_file_dialogs`]), it
/// asks for the dialog ([`ScriptFileDialog`]), hands the session back to the caller like a modal
/// dialog does and waits for `scriptui.fileDialog`'s answer. Elsewhere (the Script Console, the
/// web, headless runs) there is no dialog to wait on: `null`, as a cancelled dialog.
pub(crate) fn native_file_dialog(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let kind = match arg_string(args, 0, ctx)?.as_str() {
"save" => FileDialogKind::Save,
"folder" => FileDialogKind::Folder,
_ => FileDialogKind::Open,
};
let prompt = text_arg(args, 1, ctx)?;
let filter = text_arg(args, 2, ctx)?;
let start = text_arg(args, 4, ctx)?;
let many = kind == FileDialogKind::Open && args.get(3).is_some_and(JsValue::to_boolean);
let id = NEXT_FILE_DIALOG.fetch_add(1, Ordering::Relaxed);
let asked = with_active(|a| {
if a.link.is_none() || !a.session.script_ui.answers_file_dialogs {
return Ok(false);
}
// One dialog at a time per script.
a.session.script_ui.file_dialogs.retain(|d| d.host != a.host);
let folder = kind == FileDialogKind::Folder;
let (exts, label, any) = if folder { (vec![], String::new(), false) } else { (filter_exts(&filter), filter_label(&filter), filter_any(&filter)) };
a.session.script_ui.file_dialogs.push(ScriptFileDialog { id, host: a.host, kind, prompt, exts, label, any, many, start, shown: false });
Ok(true)
})
.unwrap_or(false);
if !asked {
return Ok(JsValue::null());
}
let forget = || {
let _ = with_active(|a| {
a.session.script_ui.file_dialogs.retain(|d| d.id != id);
Ok(())
});
};
loop {
let windows = snapshot(ctx);
let out = crate::Outcome { output: settle(), waiting: true, ..Default::default() };
// The caller went away: as cancelled.
let Some(ev) = yield_wait(out, windows, false) else { return Ok(JsValue::null()) };
if ev.kind == FILE_DIALOG_EVENT {
// An answer to an earlier dialog of this script is not this one's.
if ev.value.get("id").and_then(J::as_u64) == Some(u64::from(id)) {
forget();
let paths = ev.value.get("paths").cloned().unwrap_or(J::Null);
return Ok(js_str(&paths.to_string()));
}
} else if ev.kind == "close" {
// `dispatch_ui` refuses the script's window events while it waits; a close that got
// here all the same ends the wait as cancelled, so the window can be closed.
forget();
return Ok(JsValue::null());
}
}
}
// ---------------------------------------------------------------- script-host threads
pub(crate) enum ToHost {
@@ -320,8 +430,7 @@ fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome {
}
publish(session, host, &name, windows);
if done {
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
forget_host(session, host);
} else if let Ok(mut h) = hosts().lock() {
h.insert(host, HostEnd { next_due, epoch: session.script_ui.project_epoch, ..end });
}
@@ -331,6 +440,13 @@ fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome {
}
}
/// A script host has ended: its windows close and nothing waits on its file dialogs.
fn forget_host(session: &mut Session, host: u32) {
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.file_dialogs.retain(|d| d.host != host);
session.script_ui.revision += 1;
}
/// Run a script file on a new script-host thread (see the module docs). Not on the web, where
/// scripts run inline.
#[cfg(not(target_arch = "wasm32"))]
@@ -434,22 +550,33 @@ pub fn dispatch_ui(session: &mut Session, ev: &ScriptUiEvent) -> Result<J, Strin
if ACTIVE.with(|a| a.try_borrow().map(|g| g.is_some()).unwrap_or(true)) {
return Err("scripts can't drive script windows".into());
}
let w = session.script_ui.window(ev.window).ok_or_else(|| format!("no script window {}", ev.window))?;
let (host, name) = (w.host, w.script.clone());
let inline = host == CONSOLE_HOST || INLINE.with(|m| m.borrow().contains_key(&host));
if inline {
return Ok(dispatch_inline(session, host, &name, ev).to_json());
}
let host = if ev.kind == FILE_DIALOG_EVENT {
// The answer to a file dialog goes to the script waiting on it (only script-host
// threads wait on one, see [`native_file_dialog`]).
let id = ev.value.get("id").and_then(J::as_u64);
let asked = session.script_ui.file_dialogs.iter().find(|d| Some(u64::from(d.id)) == id);
asked.map(|d| d.host).ok_or("no such file dialog")?
} else {
let w = session.script_ui.window(ev.window).ok_or_else(|| format!("no script window {}", ev.window))?;
let (host, name) = (w.host, w.script.clone());
// The script is inside its file dialog's call: its windows wait for the answer.
if session.script_ui.file_dialogs.iter().any(|d| d.host == host) {
return Err("the script is waiting for its file dialog".into());
}
let inline = host == CONSOLE_HOST || INLINE.with(|m| m.borrow().contains_key(&host));
if inline {
return Ok(dispatch_inline(session, host, &name, ev).to_json());
}
host
};
let end = hosts().lock().ok().and_then(|mut h| h.remove(&host));
let Some(end) = end else {
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
forget_host(session, host);
return Err("the script that made this window has ended".into());
};
if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::Event(std::mem::take(session), ev.clone())) {
*session = msg.into_session();
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
forget_host(session, host);
return Err("the script that made this window has ended".into());
}
Ok(receive(session, host, end).to_json())
@@ -487,7 +614,10 @@ fn dispatch_inline(session: &mut Session, host: u32, name: &str, ev: &ScriptUiEv
/// Whether `host`'s tasks stop now that the project it ran with was closed: it has no window
/// open and is not a Startup script's.
fn ends_with_project(session: &Session, host: u32) -> bool {
!session.script_ui.windows.iter().any(|w| w.host == host) && !session.script_ui.startup_hosts.contains(&host)
// A script waiting on its file dialog goes on when it is answered.
!session.script_ui.windows.iter().any(|w| w.host == host)
&& !session.script_ui.startup_hosts.contains(&host)
&& !session.script_ui.file_dialogs.iter().any(|d| d.host == host)
}
/// Run the due tasks of the script-host threads; hosts without windows whose project was closed
@@ -501,13 +631,16 @@ pub(crate) fn tick_threaded(session: &mut Session, now: Instant, report: &mut cr
let Some(end) = h.get(&host) else { continue };
if end.epoch != epoch && ends_with_project(session, host) {
// Dropping its end lets the host thread finish.
stale.extend(h.remove(&host));
stale.extend(h.remove(&host).map(|end| (host, end)));
} else if end.next_due.is_some_and(|d| d <= now) {
due.push(host);
}
}
}
drop(stale);
for end in stale {
forget_host(session, end.0);
drop(end.1);
}
for host in due {
if session.script_ui.render_host.is_some() {
break;
@@ -515,8 +648,7 @@ pub(crate) fn tick_threaded(session: &mut Session, now: Instant, report: &mut cr
let Some(end) = hosts().lock().ok().and_then(|mut h| h.remove(&host)) else { continue };
if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::Tick(std::mem::take(session), now)) {
*session = msg.into_session();
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
forget_host(session, host);
continue;
}
report.add(receive(session, host, end));
+3 -1
View File
@@ -31,7 +31,9 @@ impl EffectcraftApp {
/// Loads and applies the workspaces saved in the session's config directory (a failed load is reported in
/// `ui.status`), initializes the default UI, playback and render state, and registers the frontend's commands as
/// shortcutable `UiCommand`s on the session.
pub fn new(session: Session) -> Self {
pub fn new(mut session: Session) -> Self {
// Scripts' file dialogs (File.openDialog…) show here ([`panels::scriptui_view::serve_file_dialogs`]).
session.script_ui.answers_file_dialogs = true;
let mut ui = UiState::default();
let workspace_store = workspace_state::WorkspaceStore::load(session.config.as_deref(), &mut ui);
EffectcraftApp {
+12
View File
@@ -326,12 +326,21 @@ impl EffectcraftApp {
|| !self.synthetic.is_empty()
|| !self.input_waiters.is_empty()
|| self.pending_screenshots.iter().any(|s| s.slot.is_none())
|| self.script_file_dialog_waits()
|| (self.playback.playing && child_viewports);
if paint {
self.request_hidden_paint(ctx);
}
}
/// A script waits for a file dialog nobody has shown yet: dialogs are served in a UI pass
/// (`serve_file_dialogs`), so a minimized window must paint for it (#3253 review). Not while
/// a non-blocking dialog is up: the next one waits for it.
fn script_file_dialog_waits(&self) -> bool {
let one_at_a_time = self.hooks.file_dialog_async.is_some() && self.file_dialogs.any();
!one_at_a_time && self.session.script_ui.file_dialogs.iter().any(|d| !d.shown)
}
/// Ask the host for a UI pass even when the window is minimized or occluded.
///
/// Native eframe honours `RequestPaintWhileHidden`; the shared web backend does not carry it
@@ -529,6 +538,9 @@ impl EffectcraftApp {
updates_ui::show(self, &ctx);
panels::scriptui_view::sync_panels(self);
panels::scriptui_view::show_windows(self, &ctx);
// After the windows' events and the menus' commands: a script that asked for a file
// dialog in this pass gets it now.
panels::scriptui_view::serve_file_dialogs(self);
panels::learn::coach(self, &ctx);
let lift = panels::media_panels::import_card(self, ui, full);
self.draw_toast(ui, full, lift);
+10
View File
@@ -144,6 +144,16 @@ impl EffectcraftApp {
pub(crate) fn run_dialog_answers(&mut self) {
while let Ok(answer) = self.dialog_answers.1.try_recv() {
self.file_dialogs.answered();
// A script's file dialog: answered even when cancelled (the script waits on it).
if answer.command == panels::scriptui_view::FILE_DIALOG_COMMAND {
// A dialog that couldn't open says why in the status line and counts as cancelled.
let paths = answer.paths.unwrap_or_else(|e| {
self.ui.status = e;
Vec::new()
});
panels::scriptui_view::answer_file_dialog(self, &answer.params, paths);
continue;
}
menus::dialog_answered(self, answer);
}
}
+17
View File
@@ -13,6 +13,19 @@ pub enum FileDialog {
OpenProject,
/// A folder.
Folder,
/// A file (several when `many`) a script asks for (`File.openDialog`, #2778): the script's
/// filter named `label` with these extensions (none: every file), and `any`: every file
/// besides (the filter's `*.*`).
/// `prompt` is the dialog's title (empty: the system's) and `start` the file or folder it
/// opens at (empty: the system's).
Script { label: String, exts: Vec<String>, any: bool, many: bool, prompt: String, start: String },
/// A folder a script asks for (`Folder.selectDialog`, `folder.selectDlg`) with its `prompt`
/// (the dialog's title) and the folder it starts in (`start`); both empty when not given.
ScriptFolder { prompt: String, start: String },
/// Where a script wants to save (`File.saveDialog`, `file.saveDlg`): `default` (a file name
/// or path) with the script's filter (`label`, `exts`, `any` as in [`FileDialog::Script`]; no
/// extensions: the default's extension) and the script's `prompt` as the title.
ScriptSave { default: String, prompt: String, label: String, exts: Vec<String>, any: bool },
/// Where to save `default` (a file name or path) with extension `ext` (empty: no filter);
/// `project`: the project save dialog, given the file name.
Save { default: String, ext: String, project: bool },
@@ -62,6 +75,10 @@ pub struct Hooks {
/// a drag over the window (#511), and on Linux a blocking desktop-portal dialog never pumps
/// events, so the compositor marks the window as not responding (#1275).
pub file_dialog_async: Option<Box<dyn Fn(FileDialog, DialogDone)>>,
/// Shows a [`FileDialog`] and blocks until it closes: the picked paths (empty: cancelled).
/// Scripts' file dialogs use it where [`Hooks::file_dialog_async`] isn't set (Windows); without
/// it they fall back to the pickers above.
pub pick_file_dialog: Option<Box<dyn Fn(FileDialog) -> Vec<String>>>,
/// Tells the user the graphics device was lost and the window is closing, once. `saved` is
/// the auto-save of unsaved changes (`None`: nothing was unsaved), its path or why it failed.
pub device_lost: Option<Box<dyn Fn(Option<Result<String, String>>)>>,
+5
View File
@@ -538,6 +538,11 @@ impl FileDialogsUp {
self.count = self.count.saturating_add(1);
}
/// Whether one is up.
pub(crate) fn any(&self) -> bool {
self.count > 0
}
pub(crate) fn answered(&mut self) {
self.count = self.count.saturating_sub(1);
}
+33
View File
@@ -356,6 +356,39 @@ fn image(width: usize, height: usize) -> Arc<egui::ColorImage> {
Arc::new(egui::ColorImage::new([width, height], vec![egui::Color32::from_rgb(10, 20, 30); width.checked_mul(height).unwrap()]))
}
/// #3253 review: a script waits on a file dialog while the window is hidden. File dialogs are
/// served in a UI pass, so the app asks for one until the dialog is shown; a hidden window with
/// nothing waiting stays quiet.
#[test]
fn a_script_file_dialog_asks_for_a_pass_while_the_window_is_hidden() {
use effectcraft_engine::scriptui::{FileDialogKind, ScriptFileDialog};
let ctx = egui::Context::default();
let frame = eframe::Frame::_new_kittest();
let mut app = app_with_comp();
ready(&mut app, &ctx, &frame);
let asks =
|out: &egui::LogicOutput| out.viewport_commands.values().flatten().filter(|c| matches!(c, egui::ViewportCommand::RequestPaintWhileHidden)).count();
let size = egui::vec2(800.0, 480.0);
assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 0, "nothing waits: a hidden window stays quiet");
app.session.script_ui.file_dialogs.push(ScriptFileDialog {
id: 1,
host: 1,
kind: FileDialogKind::Open,
prompt: String::new(),
exts: vec![],
label: String::new(),
any: true,
many: false,
start: String::new(),
shown: false,
});
assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 1, "a script waits for its dialog: the hidden window paints");
if let Some(d) = app.session.script_ui.file_dialogs.first_mut() {
d.shown = true;
}
assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 0, "the dialog is shown: no more passes asked for");
}
#[test]
fn a_screenshot_is_issued_only_after_settled_passes_and_writes_from_the_tick() {
let ctx = egui::Context::default();
+101 -21
View File
@@ -354,36 +354,116 @@ pub fn audio(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
p.text(pos2(sx + 2.0, y), Align2::LEFT_CENTER, format!("{db:.1}"), Tokens::ui(10.0), t.text_faint);
}
p.text(pos2(sx + 30.0, top - 9.0), Align2::LEFT_CENTER, "dB", Tokens::ui(10.0), t.text_dim);
// Selected layer's Audio Levels.
// Selected layer's Audio Levels: "Left" / "Right" and the editable "-12.0 dB" fields need
// about 110 px; narrower, "L" / "R" (down to 80 px, below which the section is left out).
let lx = rect.min.x + 120.0;
if rect.max.x - lx < 80.0 {
return;
}
let sel = app.session.state.selected_layers.first().copied();
let levels = sel.and_then(|id| {
let c = app.session.active_comp()?;
let l = c.layer(id)?;
let pr = l.props.sub("audio")?.get("levels")?;
Some((l.name.clone(), pr.value.as_vec2()))
});
match levels {
Some((name, [a, b])) => {
p.text(pos2(lx, top - 9.0), Align2::LEFT_CENTER, &name, Tokens::ui(11.0), t.text_dim);
for (i, (k, v)) in [("Left", a), ("Right", b)].into_iter().enumerate() {
let y = top + 12.0 + i as f32 * 20.0;
p.text(pos2(lx, y), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim);
p.text(pos2(lx + 44.0, y), Align2::LEFT_CENTER, format!("{v:+.1} dB"), Tokens::ui(12.0), t.hot_text);
}
}
None => {
p.text(pos2(lx, top + 12.0), Align2::LEFT_CENTER, tr("No audio layer selected"), Tokens::ui(11.0), t.text_faint);
}
}
audio_levels(app, ui, &p, pos2(lx, top), rect.max.x - lx < 110.0);
if app.meter.active() || app.audio.is_some() {
ui.ctx().request_repaint();
}
}
/// The Audio panel's level fields at `at` (left, top of the meters): the selected layer's Audio
/// Levels at the current time, keyframes (read at layer time) and expression included, as the
/// Timeline and Effect Controls show them (#3227). An edit runs the Timeline's `prop.set`: on a
/// keyframed property it keys the current time; a scrub is one undo step; with the Timeline's
/// Link Channels on, the other channel moves by the same dB (#2485). `compact` labels the channels
/// "L" / "R" to fit a narrow panel.
fn audio_levels(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, at: egui::Pos2, compact: bool) {
let t = app.tokens;
let (lx, top) = (at.x, at.y);
let comp = app.session.active_comp_arc();
let selected = app.session.state.selected_layers.first().copied();
let levels = match (comp.as_deref(), app.session.active_comp_id()) {
(Some(comp), Some(cid)) => selected.and_then(|id| comp.layer(id)).and_then(|layer| {
let pr = layer.props.sub("audio")?.get("levels")?;
let project = app.session.project.clone();
let expr = app.session.expr.clone();
// The session's footage source, as the render and `prop.get` use it, so an expression
// that samples footage (`sampleImage`) shows what it evaluates to (#3234).
let footage = app.session.footage.clone();
let ectx = effectcraft_engine::render::EvalCtx {
project: &project,
comp_id: cid,
comp,
time: app.session.time(),
expr: expr.as_deref(),
footage: Some(footage.as_ref()),
property_overrides: &[],
media_overrides: &[],
reads: None,
};
// The keyframed value before the expression: what `prop.set` writes and scrubs from.
let raw = pr.value_at(layer.layer_time(ectx.time)).as_vec2();
Some((layer.id.0, pr.uid, pr.has_expression(), layer.name.as_str(), ectx.value(layer, pr).as_vec2(), raw))
}),
_ => None,
};
let Some((lid, uid, driven, name, values, raw)) = levels else {
p.text(pos2(lx, top + 12.0), Align2::LEFT_CENTER, tr("No audio layer selected"), Tokens::ui(11.0), t.text_faint);
return;
};
p.text(pos2(lx, top - 9.0), Align2::LEFT_CENTER, name, Tokens::ui(11.0), t.text_dim);
// The values themselves: red while an expression drives the property (#1306).
let vt = t.for_value(driven);
// As in the Timeline, a scrub moves every selected layer by the same change and a typed value
// sets the typed channel.
let scrub = ui.ctx().dragged_id().is_some() && ui.input(|i| i.pointer.is_decidedly_dragging());
// Proportional Scrubbing (Ctrl+Alt / Cmd+Opt): the change spreads over the selected layers by
// selection order, as in the Timeline.
let proportional = scrub && ui.input(|i| widgets::proportional_scrub(i.modifiers));
// Linked channels move together; Alt edits one alone (Ctrl+Alt is a proportional scrub).
let linked = app.ui.timeline.is_linked(uid, false) && !ui.input(|i| i.modifiers.alt && !widgets::proportional_scrub(i.modifiers));
let mut actions: Vec<serde_json::Value> = vec![];
// A scrub ended this frame: the edits below still join its undo step, the next scrub starts
// another (#3234 review).
let mut released = false;
let (channels, field_x) = if compact { (["L", "R"], 14.0) } else { (["Left", "Right"], 44.0) };
for (d, (k, v)) in channels.into_iter().zip(values).enumerate() {
let y = top + 12.0 + d as f32 * 20.0;
p.text(pos2(lx, y), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim);
let spec = widgets::HotSpec { speed: 1.0, range: (-1e9, 1e9), decimals: 1, suffix: " dB" };
let (r, nv, done) = widgets::hot_number_at(ui, pos2(lx + field_x, y - 9.0), egui::Id::unique(("audio-level", uid, d)), v, &spec, &vt);
released |= done;
app.auto.add(if d == 0 { "audio.levelLeft" } else { "audio.levelRight" }, r, &format!("{v:.1} dB"));
if let Some(nv) = nv {
let merge = format!("audio-levels-{uid}");
let mut params = json!({"layer": lid, "prop": uid, "merge": merge, "selected": true, "offset": scrub, "proportional": proportional, "dims": [d]});
let value = if linked {
// The other channel follows by each layer's own change, keeping its balance.
params["follow"] = json!([usize::from(d == 0)]);
widgets::shifted(&values, d, nv)
} else {
let mut value = values.to_vec();
if let Some(slot) = value.get_mut(d) {
*slot = nv;
}
value
};
// The fields show the value after the expression; `prop.set` writes (and a scrub takes
// its change from) the keyframed value under it. So each channel is that value moved
// by the change the edit makes to what is shown (every selected layer then moves by
// it), except a typed channel, which is set as typed.
let value: Vec<f64> =
value.iter().zip(values.iter().zip(raw)).enumerate().map(|(e, (n, (shown, r)))| if e == d && !scrub { *n } else { r + (n - shown) }).collect();
params["value"] = json!(value);
actions.push(params);
}
}
let ctx = ui.ctx().clone();
for params in actions {
if let Err(e) = crate::menus::invoke(app, &ctx, "prop.set", params) {
app.ui.status = e;
}
}
if released {
app.session.history.merge_key = None;
}
}
/// The History panel: every state of the session's branching history, indented under the state it
/// grew from, with the current state highlighted and future/abandoned branches dimmed. Only the
/// rows in view are drawn; the current state is scrolled into view when it changes. Clicking a
+109
View File
@@ -540,6 +540,115 @@ fn perform(app: &mut EffectcraftApp, ctx: &egui::Context, acts: Vec<Act>) {
}
}
/// The command that answers a script's file dialog.
pub(crate) const FILE_DIALOG_COMMAND: &str = "scriptui.fileDialog";
/// The answer to a script's file dialog shown without blocking. Dropped unanswered (a dialog that
/// ended without its completion handler, a dialog thread that didn't start) it answers
/// "cancelled", so the script never waits for an answer that can't come.
struct PendingAnswer {
tx: std::sync::mpsc::Sender<crate::DialogAnswer>,
answer: Option<crate::DialogAnswer>,
}
impl PendingAnswer {
fn send(mut self, paths: Result<Vec<String>, String>) {
if let Some(a) = self.answer.take() {
let _ = self.tx.send(crate::DialogAnswer { paths, ..a });
}
}
}
impl Drop for PendingAnswer {
fn drop(&mut self) {
if let Some(a) = self.answer.take() {
let _ = self.tx.send(a);
}
}
}
/// Show the file dialog a script waits on (`File.openDialog`, `File.saveDialog`,
/// `Folder.selectDialog`… from a ScriptUI Browse… button, #2778) and hand the answer back
/// through `scriptui.fileDialog`. Where blocking the frame is unsafe the dialog shows without
/// blocking ([`crate::Hooks::file_dialog_async`]), one at a time, and answers when it closes; a
/// host without a dialog answers "cancelled" at once, so the script never waits for nothing.
pub fn serve_file_dialogs(app: &mut EffectcraftApp) {
use effectcraft_engine::scriptui::FileDialogKind;
let spawn = app.hooks.file_dialog_async.is_some();
// A non-blocking dialog already up: the next one shows after it.
if spawn && app.file_dialogs.any() {
return;
}
let Some(asked) = app.session.script_ui.file_dialogs.iter_mut().find(|d| !d.shown) else { return };
asked.shown = true;
let asked = asked.clone();
let params = json!({"id": asked.id});
// The save dialog's default: the script's file, else a name with the filter's extension.
let default = match (asked.start.is_empty(), asked.exts.first()) {
(false, _) => asked.start.clone(),
(true, Some(ext)) => format!("Untitled.{ext}"),
(true, None) => "Untitled".to_string(),
};
let request = match asked.kind {
FileDialogKind::Open => crate::FileDialog::Script {
label: asked.label.clone(),
exts: asked.exts.clone(),
any: asked.any,
many: asked.many,
prompt: asked.prompt.clone(),
start: asked.start.clone(),
},
FileDialogKind::Save => crate::FileDialog::ScriptSave {
default: default.clone(),
prompt: asked.prompt.clone(),
label: asked.label.clone(),
exts: asked.exts.clone(),
any: asked.any,
},
FileDialogKind::Folder => crate::FileDialog::ScriptFolder { prompt: asked.prompt.clone(), start: asked.start.clone() },
};
if let Some(spawn) = app.hooks.file_dialog_async.as_ref() {
let answer = crate::DialogAnswer { command: FILE_DIALOG_COMMAND.to_string(), key: "paths", params, paths: Ok(Vec::new()) };
let pending = PendingAnswer { tx: app.dialog_answers.0.clone(), answer: Some(answer) };
app.file_dialogs.opened();
spawn(request, Box::new(move |paths| pending.send(paths)));
return;
}
let paths: Vec<String> = match (&app.hooks.pick_file_dialog, asked.kind) {
(Some(pick), _) => pick(request),
(_, FileDialogKind::Open) => {
let exts: Vec<&str> = asked.exts.iter().map(String::as_str).collect();
app.hooks.pick_files.as_ref().map(|pick| pick(&exts)).unwrap_or_default()
}
(_, FileDialogKind::Save) => app.hooks.save_dialog(&default).flatten().into_iter().collect(),
(_, FileDialogKind::Folder) => app.hooks.pick_folder.as_ref().and_then(|pick| pick()).into_iter().collect(),
};
let paths = if asked.many { paths } else { paths.into_iter().take(1).collect() };
answer_file_dialog(app, &params, paths);
}
/// Answer a script's file dialog (`params`: `{id}`) with the picked `paths` (empty: cancelled);
/// what the script then reports shows as [`perform`] shows a handler's. An answer that comes
/// after the dialog was dropped (its script window closed meanwhile) is let go.
pub(crate) fn answer_file_dialog(app: &mut EffectcraftApp, params: &Value, paths: Vec<String>) {
let id = params.get("id").and_then(Value::as_u64);
if !app.session.script_ui.file_dialogs.iter().any(|d| Some(u64::from(d.id)) == id) {
return;
}
let paths = if paths.is_empty() { Value::Null } else { json!(paths) };
match app.session.execute(FILE_DIALOG_COMMAND, json!({"id": id, "paths": paths})) {
Ok(r) => {
if let Some(e) = r.get("error").filter(|e| !e.is_null()) {
let msg = e["message"].as_str().unwrap_or("script error").to_string();
app.toast = Some((msg, app.now()));
} else if let Some(o) = r["output"].as_str().filter(|o| !o.is_empty()) {
app.ui.status = o.lines().last().unwrap_or_default().to_string();
}
}
Err(e) => app.ui.status = e.to_string(),
}
}
/// The floating script windows (dialogs, palettes, windows), drawn over the app.
pub fn show_windows(app: &mut EffectcraftApp, ctx: &egui::Context) {
let windows: Vec<ScriptWindow> = app.session.script_ui.windows.iter().filter(|w| w.kind != WindowKind::Panel).cloned().collect();
+1
View File
@@ -11,6 +11,7 @@ mod ui_accessibility_audit;
mod ui_agent_audit;
mod ui_alt_drag_duplicate;
mod ui_angles;
mod ui_audio_panel_levels;
mod ui_audio_scrub;
mod ui_azerty_shortcuts;
mod ui_batch_links;
@@ -0,0 +1,405 @@
//! The Audio panel's level fields (#3227): they show the selected layer's Audio Levels at the
//! current time, keyframes and expression included, as the Timeline does; typing into one on a
//! keyframed property sets a key at the current time and leaves the static value alone, and with
//! the Timeline's Link Channels on the other channel follows (#2485).
use effectcraft_engine::Session;
use effectcraft_engine::project::LayerId;
use effectcraft_ui_egui::EffectcraftApp;
use effectcraft_ui_egui::dock::PanelKind;
use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
const LEFT: &str = "audio.levelLeft";
const RIGHT: &str = "audio.levelRight";
fn center(h: &Harness<'_, EffectcraftApp>, id: &str) -> Pos2 {
let e = h.state().auto.find(id).unwrap_or_else(|| panic!("the Audio panel shows no {id}"));
pos2(e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0)
}
fn label(h: &Harness<'_, EffectcraftApp>, id: &str) -> String {
h.state().auto.find(id).unwrap_or_else(|| panic!("the Audio panel shows no {id}")).label.clone()
}
fn click(h: &mut Harness<'_, EffectcraftApp>, id: &str) {
let p = center(h, id);
h.input_mut().events.push(Event::PointerMoved(p));
h.step();
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
}
fn type_value(h: &mut Harness<'_, EffectcraftApp>, id: &str, v: &str) {
click(h, id);
h.input_mut().events.push(Event::Text(v.into()));
h.step();
h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(3);
}
/// Comps Sound and Main, and a precomp layer of Sound (which has Audio Levels) in Main at
/// `levels`; its layer id.
fn sound_layer(s: &mut Session, levels: [f64; 2]) -> u64 {
s.execute("comp.new", json!({"name": "Sound", "width": 64, "height": 36, "duration": 4})).unwrap();
s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "duration": 4})).unwrap();
let l = s.execute("layer.addItem", json!({"item": "Sound"})).unwrap()["layer"].as_u64().unwrap();
s.execute("prop.set", json!({"layer": l, "path": "audio/levels", "value": levels})).unwrap();
l
}
/// The harness with layer `l` selected and the Audio panel up.
fn harness(mut s: Session, l: u64) -> Harness<'static, EffectcraftApp> {
s.execute("layer.select", json!({"layers": [l]})).unwrap();
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.state_mut().show_panel(PanelKind::Audio);
h.run_steps(4);
h
}
fn levels(h: &Harness<'_, EffectcraftApp>, l: u64) -> effectcraft_engine::project::Property {
h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().props.prop("audio/levels").unwrap().clone()
}
/// `prop.get`'s `key` (`value`: keyframed, `evaluated`: after the expression) at the current time.
fn engine_value(h: &mut Harness<'_, EffectcraftApp>, l: u64, key: &str) -> Vec<f64> {
let r = h.state_mut().session.execute("prop.get", json!({"layer": l, "path": "audio/levels"})).unwrap();
r[key].as_array().unwrap_or_else(|| panic!("no {key} in {r}")).iter().map(|v| v.as_f64().unwrap()).collect()
}
fn db(v: f64) -> String {
format!("{v:.1} dB")
}
/// Keyframed Audio Levels on a layer that starts 1 s into the comp, with the current time between
/// the keys: the panel shows the value interpolated at layer time, not the static one (nor the one
/// at comp time, past the last key); typing sets a key at the current time.
#[test]
fn keyframed_levels_show_the_value_at_the_current_time_and_typing_keys_it() {
let mut s = Session::default();
let l = sound_layer(&mut s, [-20.0, -20.0]);
// Keys at layer time 0 s and 1 s (the layer still starts at 0 s, so comp time = layer time).
s.execute("prop.addKey", json!({"layer": l, "path": "audio/levels", "time": 0.0, "value": [-6.0, -12.0]})).unwrap();
s.execute("prop.addKey", json!({"layer": l, "path": "audio/levels", "time": 1.0, "value": [0.0, 0.0]})).unwrap();
// The layer moves 1 s later: its keys sit at comp 1 s and 2 s.
let cid = s.active_comp_id().unwrap();
let one = effectcraft_engine::time::Tick::from_seconds_f64(1.0);
let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(l)).unwrap();
layer.start_time += one;
layer.in_point += one;
layer.out_point += one;
s.execute("time.set", json!({"time": 1.5})).unwrap();
let mut h = harness(s, l);
let now = engine_value(&mut h, l, "value");
assert!(now[0] > -6.0 && now[0] < 0.0 && now[1] > -12.0 && now[1] < 0.0, "between the keys: {now:?}");
assert_eq!(label(&h, LEFT), db(now[0]), "Left at the current time");
assert_eq!(label(&h, RIGHT), db(now[1]), "Right at the current time");
assert_ne!(label(&h, LEFT), db(-20.0), "not the static value");
type_value(&mut h, LEFT, "-1");
let pr = levels(&h, l);
assert_eq!(pr.value.components(), vec![-20.0, -20.0], "the static value stays");
let keys: Vec<(f64, Vec<f64>)> = pr.keys.iter().map(|k| (k.time.seconds(), k.value.components())).collect();
assert_eq!(keys.len(), 3, "a key at the current time: {keys:?}");
assert_eq!(keys[0].1, vec![-6.0, -12.0], "{keys:?}");
let lt = h.state().session.time().seconds() - 1.0;
assert!((keys[1].0 - lt).abs() < 1e-6, "the new key is at the current layer time {lt}: {keys:?}");
assert_eq!(keys[1].1[0], -1.0, "the typed Left: {keys:?}");
assert!((keys[1].1[1] - now[1]).abs() < 1e-9, "Right keeps its value at that time: {keys:?}");
assert_eq!(keys[2].1, vec![0.0, 0.0], "{keys:?}");
assert_eq!(label(&h, LEFT), db(-1.0), "the panel shows the new key");
}
/// An expression drives Audio Levels: the panel shows what it evaluates to.
#[test]
fn expression_driven_levels_show_the_evaluated_value() {
let mut s = effectcraft_host::session();
let l = sound_layer(&mut s, [-6.0, -12.0]);
s.execute("prop.setExpression", json!({"layer": l, "path": "audio/levels", "expression": "[-1, -2]"})).unwrap();
let mut h = harness(s, l);
assert_eq!(engine_value(&mut h, l, "evaluated"), vec![-1.0, -2.0], "the expression runs");
assert_eq!(label(&h, LEFT), db(-1.0));
assert_eq!(label(&h, RIGHT), db(-2.0));
}
/// Static Audio Levels: typing sets the value and adds no key.
#[test]
fn static_levels_take_a_typed_value_without_a_key() {
let mut s = Session::default();
let l = sound_layer(&mut s, [-6.0, -12.0]);
let mut h = harness(s, l);
assert_eq!(label(&h, LEFT), db(-6.0));
assert_eq!(label(&h, RIGHT), db(-12.0));
type_value(&mut h, RIGHT, "-3");
let pr = levels(&h, l);
assert_eq!(pr.value.components(), vec![-6.0, -3.0]);
assert!(pr.keys.is_empty(), "no key on a static property");
}
/// With the Timeline's Link Channels on (#2485), typing into one channel moves the other by the
/// same dB, as in the Timeline.
#[test]
fn linked_levels_move_both_channels_by_the_same_db() {
let mut s = Session::default();
let l = sound_layer(&mut s, [-6.0, -12.0]);
let mut h = harness(s, l);
let uid = levels(&h, l).uid;
h.state_mut().ui.timeline.toggle_link(uid, false);
h.run_steps(2);
assert!(h.state().ui.timeline.is_linked(uid, false));
type_value(&mut h, LEFT, "-3");
assert_eq!(levels(&h, l).value.components(), vec![-3.0, -9.0], "both rise 3 dB and keep their 6 dB balance");
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
h.run_steps(2);
assert_eq!(levels(&h, l).value.components(), vec![-6.0, -12.0], "one Undo takes back both channels");
}
/// Proportional Scrubbing (After Effects 26.2): with three layers selected, a Ctrl+Alt scrub of
/// Left in the Audio panel (which shows the first selected layer) leaves that layer as it is,
/// moves the last selected by the whole change and the middle one by half, as in the Timeline.
#[test]
fn ctrl_alt_scrub_is_proportional_over_the_selected_layers() {
let mut s = Session::default();
let first = sound_layer(&mut s, [-20.0, -20.0]);
let mut ids = vec![first];
for _ in 0..2 {
let l = s.execute("layer.addItem", json!({"item": "Sound"})).unwrap()["layer"].as_u64().unwrap();
s.execute("prop.set", json!({"layer": l, "path": "audio/levels", "value": [-20.0, -20.0]})).unwrap();
ids.push(l);
}
// Selection order: the first created (the one the panel shows), then the second, then the third.
let mut h = harness(s, first);
for l in &ids[1..] {
h.state_mut().session.execute("layer.select", json!({"layers": [l], "add": true})).unwrap();
}
h.run_steps(2);
assert_eq!(h.state().session.state.selected_layers.first().map(|l| l.0), Some(first), "the panel shows the first selected layer");
let from = center(&h, LEFT);
let ctrl_alt = Modifiers { alt: true, ctrl: true, command: true, ..Default::default() };
h.input_mut().events.push(Event::PointerMoved(from));
h.step();
h.input_mut().events.push(Event::ModifiersChanged(ctrl_alt));
h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: ctrl_alt });
h.step();
let to = from + vec2(40.0, 0.0);
for k in 1..=24 {
h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (k as f32 / 24.0)));
h.step();
}
h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: ctrl_alt });
h.step();
h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(2);
let moved: Vec<f64> = ids.iter().map(|l| levels(&h, *l).value.components()[0] + 20.0).collect();
assert!(moved[2] > 1.0, "the last selected layer moved: {moved:?}");
assert!(moved[0].abs() < 1e-9, "the first selected layer stays: {moved:?}");
assert!((moved[1] - moved[2] / 2.0).abs() < 1e-6, "the middle one moves by half: {moved:?}");
}
/// Scrub Left in the Audio panel 40 px to the right with `modifiers`.
fn scrub_left(h: &mut Harness<'_, EffectcraftApp>, modifiers: Modifiers) {
let from = center(h, LEFT);
let to = from + vec2(40.0, 0.0);
h.input_mut().events.push(Event::PointerMoved(from));
h.step();
h.input_mut().events.push(Event::ModifiersChanged(modifiers));
h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers });
h.step();
for k in 1..=24 {
h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (k as f32 / 24.0)));
h.step();
}
h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers });
h.step();
h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(2);
}
/// An expression shifts the shown levels: a scrub moves the keyframed value under it (of the
/// shown layer and of every other selected layer) by the scrub's change, the same as without the
/// expression, not by the change plus the expression's offset; Ctrl+Alt spreads that change.
#[test]
fn a_scrub_of_expression_driven_levels_moves_every_selected_layer_by_the_scrub() {
let mut s = effectcraft_host::session();
let first = sound_layer(&mut s, [-20.0, -20.0]);
let mut ids = vec![first];
for _ in 0..2 {
let l = s.execute("layer.addItem", json!({"item": "Sound"})).unwrap()["layer"].as_u64().unwrap();
s.execute("prop.set", json!({"layer": l, "path": "audio/levels", "value": [-30.0, -30.0]})).unwrap();
ids.push(l);
}
let mut h = harness(s, first);
for l in &ids[1..] {
h.state_mut().session.execute("layer.select", json!({"layers": [l], "add": true})).unwrap();
}
h.run_steps(2);
let left = |h: &Harness<'_, EffectcraftApp>| -> Vec<f64> { ids.iter().map(|l| levels(h, *l).value.components()[0]).collect() };
let undo = |h: &mut Harness<'_, EffectcraftApp>| {
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
h.run_steps(2);
};
let before = left(&h);
// Without an expression: the change a 40 px scrub makes.
scrub_left(&mut h, Modifiers::NONE);
let change = left(&h)[0] - before[0];
assert!(change > 1.0, "the scrub raised Left: {before:?} -> {:?}", left(&h));
undo(&mut h);
assert_eq!(left(&h), before);
for l in &ids {
h.state_mut().session.execute("prop.setExpression", json!({"layer": l, "path": "audio/levels", "expression": "value + [10, 10]"})).unwrap();
}
h.run_steps(2);
assert_eq!(label(&h, LEFT), db(-10.0), "the panel shows the expression's value");
scrub_left(&mut h, Modifiers::NONE);
let after = left(&h);
for (i, (a, b)) in after.iter().zip(&before).enumerate() {
assert!((a - b - change).abs() < 1e-6, "layer {i} moved by the scrub ({change}), not by the expression's offset too: {before:?} -> {after:?}");
}
assert_eq!(label(&h, LEFT), db(after[0] + 10.0), "the panel shows the moved value through the expression");
undo(&mut h);
// Proportional: the first selected stays, the middle takes half, the last all of it.
let ctrl_alt = Modifiers { alt: true, ctrl: true, command: true, ..Default::default() };
scrub_left(&mut h, ctrl_alt);
let moved: Vec<f64> = left(&h).iter().zip(&before).map(|(a, b)| a - b).collect();
assert!(moved[0].abs() < 1e-9, "the first selected layer stays: {moved:?}");
assert!((moved[2] - change).abs() < 1e-6, "the last selected moves by the scrub's change ({change}): {moved:?}");
assert!((moved[1] - change / 2.0).abs() < 1e-6, "the middle one moves by half: {moved:?}");
}
/// #3234 review: each scrub is its own undo step. A second scrub with nothing between it and
/// the first must not fold into it (one Undo would take both back).
#[test]
fn two_scrubs_are_two_undo_steps() {
let mut s = effectcraft_host::session();
let l = sound_layer(&mut s, [-20.0, -20.0]);
let mut h = harness(s, l);
let left = |h: &Harness<'_, EffectcraftApp>| levels(h, l).value.components()[0];
let start = left(&h);
scrub_left(&mut h, Modifiers::NONE);
let first = left(&h);
assert!(first > start + 1.0, "the first scrub raised Left: {start} -> {first}");
scrub_left(&mut h, Modifiers::NONE);
let second = left(&h);
assert!(second > first + 1.0, "the second scrub raised it again: {first} -> {second}");
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
h.run_steps(2);
assert!((left(&h) - first).abs() < 1e-9, "one Undo takes back the second scrub only: {start} / {first} / {second} -> {}", left(&h));
}
/// With Link Channels on, a scrub of Left moves Right by the same dB; Alt scrubs Left alone.
#[test]
fn a_linked_scrub_moves_both_channels_and_alt_moves_one() {
let mut s = Session::default();
let l = sound_layer(&mut s, [-6.0, -12.0]);
let mut h = harness(s, l);
let uid = levels(&h, l).uid;
h.state_mut().ui.timeline.toggle_link(uid, false);
h.run_steps(2);
scrub_left(&mut h, Modifiers::NONE);
let c = levels(&h, l).value.components();
assert!(c[0] > -6.0, "the scrub raised Left: {c:?}");
assert!((c[0] - c[1] - 6.0).abs() < 1e-9, "Right moved by the same dB: {c:?}");
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
h.run_steps(2);
assert_eq!(levels(&h, l).value.components(), vec![-6.0, -12.0], "one Undo takes back the scrub");
scrub_left(&mut h, Modifiers { alt: true, ..Default::default() });
let c = levels(&h, l).value.components();
assert!(c[0] > -6.0, "the Alt scrub raised Left: {c:?}");
assert_eq!(c[1], -12.0, "Alt leaves Right alone: {c:?}");
}
/// Typed into an expression-driven field, the value is the keyframed value under the expression
/// (what the expression reads as `value`), as in the Timeline.
#[test]
fn typing_into_expression_driven_levels_sets_the_value_under_the_expression() {
let mut s = effectcraft_host::session();
let l = sound_layer(&mut s, [-6.0, -12.0]);
s.execute("prop.setExpression", json!({"layer": l, "path": "audio/levels", "expression": "value + [10, 10]"})).unwrap();
let mut h = harness(s, l);
assert_eq!(label(&h, LEFT), db(4.0));
type_value(&mut h, LEFT, "-5");
assert_eq!(levels(&h, l).value.components(), vec![-5.0, -12.0], "Left as typed, Right's own value under the expression kept");
assert_eq!(label(&h, LEFT), db(5.0), "shown through the expression");
assert_eq!(label(&h, RIGHT), db(-2.0));
}
/// A narrow Audio panel (200-230 px) still shows the level fields, labelled "L" / "R", and keeps
/// them inside the panel.
#[test]
fn a_narrow_audio_panel_keeps_the_level_fields_inside_it() {
for width in [200.0, 215.0, 230.0, 320.0] {
let mut s = Session::default();
let l = sound_layer(&mut s, [-20.0, -20.0]);
s.execute("layer.select", json!({"layers": [l]})).unwrap();
let panel = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(width, 400.0));
let mut h = Harness::builder().with_size(vec2(width + 100.0, 400.0)).build_ui_state(
move |ui, app: &mut EffectcraftApp| {
app.auto.begin_frame();
effectcraft_ui_egui::panels::misc::audio(app, ui, panel);
},
EffectcraftApp::new(s),
);
h.run_steps(3);
for id in [LEFT, RIGHT] {
let e = h.state().auto.find(id).unwrap_or_else(|| panic!("{width} px: the Audio panel shows no {id}")).clone();
assert!(e.rect[0] + e.rect[2] <= width, "{width} px: {id} ends at {} px, past the panel", e.rect[0] + e.rect[2]);
assert_eq!(e.label, db(-20.0), "{width} px");
}
}
}
/// Stands in for `sampleImage()` on footage (this harness has no expression language): both
/// channels come from the first frame's pixel through the context's footage source, red and green
/// as minus dB x 100. Fails without the source, as the real one samples transparent.
struct SampleFootage;
impl effectcraft_engine::render::ExprHost for SampleFootage {
fn eval(
&self,
ctx: &effectcraft_engine::render::EvalCtx,
_: &effectcraft_engine::project::Layer,
_: &effectcraft_engine::project::Property,
_: &effectcraft_engine::keyframe::Value,
) -> Result<effectcraft_engine::keyframe::Value, String> {
let src = ctx.footage.ok_or("sampleImage: no footage source")?;
let item = effectcraft_engine::project::ItemId(0);
let img = src.frame(item, &effectcraft_engine::project::Footage::default(), ctx.time).ok_or("no frame")?;
let px = img.get(0, 0);
Ok(effectcraft_engine::keyframe::Value::Vec2([-f64::from(px[0]) * 100.0, -f64::from(px[1]) * 100.0]))
}
}
/// One frame of nonzero footage for every request.
struct Grey;
impl effectcraft_engine::render::FootageSource for Grey {
fn frame(
&self,
_: effectcraft_engine::project::ItemId,
_: &effectcraft_engine::project::Footage,
_: effectcraft_engine::time::Tick,
) -> Option<std::sync::Arc<effectcraft_engine::raster::Image>> {
Some(std::sync::Arc::new(effectcraft_engine::raster::Image::filled(4, 4, [0.25, 0.5, 0.0, 1.0])))
}
}
/// Audio Levels driven by an expression that samples footage pixels (#3234): the panel evaluates
/// with the session's footage source, as the render does, so it shows the sampled
/// values (-25 dB, -50 dB) rather than a failed evaluation's keyframed ones.
#[test]
fn levels_driven_by_footage_sampling_show_the_sampled_value() {
let mut s = Session::default();
let l = sound_layer(&mut s, [-6.0, -12.0]);
s.expr = Some(std::sync::Arc::new(SampleFootage));
s.footage = std::sync::Arc::new(Grey);
s.execute("prop.setExpression", json!({"layer": l, "path": "audio/levels", "expression": "sampleImage([0, 0])"})).unwrap();
let h = harness(s, l);
assert_eq!(label(&h, LEFT), db(-25.0));
assert_eq!(label(&h, RIGHT), db(-50.0));
}
+5 -2
View File
@@ -273,13 +273,16 @@ fn playback_prefetches_past_the_cached_frames_ahead() {
for f in 0..120 {
h.state().request_frame(cid, f, scale);
}
for _ in 0..4000 {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
while std::time::Instant::now() < deadline {
if h.state().frames.cached_frames(&series).len() >= 120 && h.state().frames.inflight() == 0 {
break;
}
h.step();
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert_eq!(h.state().frames.cached_frames(&series), (0..120).collect::<Vec<_>>());
let cached = h.state().frames.cached_frames(&series);
assert_eq!(cached, (0..120).collect::<Vec<_>>(), "setup cached {} frames before playback: {cached:?}", cached.len());
// Rendering/instrumentation time must not move the playhead near the end of the
// cached run. Exercise real prefetch workers while holding playback in its first second.
h.state_mut().use_manual_clock();
+162
View File
@@ -398,3 +398,165 @@ fn scheduled_import_reveals_its_composition_without_manual_clicks() {
assert!(!h.state().ui.start_screen, "Home must not hide a composition opened by the scheduled import");
h.state_mut().session.execute("scriptui.close", json!({"window":"Automatic import"})).unwrap();
}
/// #2778: a script dialog's Browse… button calls `File.openDialog` / `Folder.selectDialog`; the
/// app shows its file dialog (with the script's filter) and the script goes on with the picked
/// file, or with null when cancelled. Blocking dialogs (Windows) answer in the same pass; the
/// non-blocking ones (macOS, Linux) when they close.
#[test]
fn script_browse_buttons_open_the_file_dialog() {
use std::sync::{Arc, Mutex};
let mut h = harness();
let picked = std::env::temp_dir().join("Song.wav").to_string_lossy().to_string();
let asked: Arc<Mutex<Vec<Vec<String>>>> = Arc::default();
let (log, file) = (asked.clone(), picked.clone());
h.state_mut().hooks.pick_files = Some(Box::new(move |exts: &[&str]| {
log.lock().unwrap().push(exts.iter().map(|e| e.to_string()).collect());
vec![file.clone()]
}));
// Cancelled.
h.state_mut().hooks.pick_folder = Some(Box::new(|| None::<String>));
let code = r#"
var d = new Window("dialog", "Pick Audio");
var row = d.add("group");
var song = row.add("edittext", undefined, "", { name: "song" });
song.characters = 30;
var browse = row.add("button", undefined, "Browse...", { name: "browse" });
browse.onClick = function () {
var f = File.openDialog("Select a song", "Audio:*.mp3;*.wav,All files:*.*");
song.text = f ? f.fsName : "(cancelled)";
};
var out = d.add("edittext", undefined, "", { name: "out" });
var where = d.add("button", undefined, "Folder...", { name: "where" });
where.onClick = function () {
var f = Folder.selectDialog("Output folder");
out.text = f ? f.fsName : "(cancelled)";
};
d.add("button", undefined, "OK", { name: "ok" });
if (d.show() === 1) app.project.activeItem.layers.addNull().name = song.text + " | " + out.text;
"#;
let r = h.state_mut().session.execute("script.run", json!({"code": code, "name": "pick.jsx"})).unwrap();
assert_eq!(r["waiting"], true, "{r}");
h.run_steps(3);
let d = h.state().session.script_ui.windows.iter().find(|w| w.modal).unwrap().id;
let text = |h: &Harness<'_, EffectcraftApp>, name: &str| {
h.state().session.script_ui.window(d).and_then(|w| w.root.lookup(&json!(name))).map(|w| w.text.clone()).unwrap_or_default()
};
click(&mut h, &format!("scriptui.{d}.browse"));
assert_eq!(*asked.lock().unwrap(), [vec!["mp3".to_string(), "wav".to_string()]], "Browse… opens the file dialog with the script's filter");
assert_eq!(text(&h, "song"), picked, "the script gets the picked file");
click(&mut h, &format!("scriptui.{d}.where"));
assert_eq!(text(&h, "out"), "(cancelled)", "a cancelled dialog gives the script null");
// A dialog that doesn't block the frame answers when it closes.
let done: Arc<Mutex<Vec<(effectcraft_ui_egui::FileDialog, effectcraft_ui_egui::DialogDone)>>> = Arc::default();
let queue = done.clone();
h.state_mut().hooks.file_dialog_async = Some(Box::new(move |dialog, answer| queue.lock().unwrap().push((dialog, answer))));
click(&mut h, &format!("scriptui.{d}.where"));
let (dialog, answer) = done.lock().unwrap().pop().expect("the folder dialog is asked for");
assert_eq!(dialog, effectcraft_ui_egui::FileDialog::ScriptFolder { prompt: "Output folder".into(), start: String::new() });
let folder = std::env::temp_dir().to_string_lossy().to_string();
answer(Ok(vec![folder.clone()]));
h.run_steps(3);
assert_eq!(text(&h, "out"), folder);
// A dialog that ends without answering (its completion handler never runs) counts as
// cancelled: the script doesn't wait for good.
h.state_mut().hooks.file_dialog_async = Some(Box::new(|_: effectcraft_ui_egui::FileDialog, answer: effectcraft_ui_egui::DialogDone| drop(answer)));
click(&mut h, &format!("scriptui.{d}.where"));
h.run_steps(3);
assert_eq!(text(&h, "out"), "(cancelled)");
// The dialog still works: OK closes it and the script runs on.
click(&mut h, &format!("scriptui.{d}.ok"));
assert_eq!(layer_names(&h), [format!("{picked} | (cancelled)")]);
assert!(h.state().session.script_ui.windows.is_empty());
}
/// #2778 review: the prompt, the start location and the full filter of a script's instance
/// `openDlg` / `saveDlg` / `selectDlg` reach the host's dialog, not just the filter's extensions.
#[test]
fn script_file_dialog_options_reach_the_host_dialog() {
use effectcraft_ui_egui::FileDialog;
use std::sync::{Arc, Mutex};
let mut h = harness();
let asked: Arc<Mutex<Vec<FileDialog>>> = Arc::default();
let log = asked.clone();
h.state_mut().hooks.pick_file_dialog = Some(Box::new(move |dialog| {
log.lock().unwrap().push(dialog);
Vec::new()
}));
let dir = std::env::temp_dir().to_string_lossy().to_string();
let code = format!(
r#"
var d = new Window("dialog", "Options");
d.add("button", undefined, "Open", {{ name: "open" }}).onClick = function () {{ new File({dir:?}).openDlg("Pick a song", "Audio:*.mp3;*.wav,All files:*.*", false); }};
d.add("button", undefined, "Save", {{ name: "save" }}).onClick = function () {{ new File({dir:?} + "/Mix.wav").saveDlg("Save the mix", "Audio:*.wav;*.aif"); }};
d.add("button", undefined, "Folder", {{ name: "folder" }}).onClick = function () {{ new Folder({dir:?}).selectDlg("Output folder"); }};
d.add("button", undefined, "OK", {{ name: "ok" }});
d.show();
"#
);
let r = h.state_mut().session.execute("script.run", json!({"code": code, "name": "opts.jsx"})).unwrap();
assert_eq!(r["waiting"], true, "{r}");
h.run_steps(3);
let d = h.state().session.script_ui.windows.iter().find(|w| w.modal).unwrap().id;
for name in ["open", "save", "folder"] {
click(&mut h, &format!("scriptui.{d}.{name}"));
}
let got = asked.lock().unwrap().clone();
let exts = |e: &[&str]| e.iter().map(|e| e.to_string()).collect::<Vec<_>>();
assert_eq!(
got,
[
FileDialog::Script { label: "Audio".into(), exts: exts(&["mp3", "wav"]), any: true, many: false, prompt: "Pick a song".into(), start: dir.clone() },
FileDialog::ScriptSave {
default: format!("{dir}/Mix.wav"),
prompt: "Save the mix".into(),
label: "Audio".into(),
exts: exts(&["wav", "aif"]),
any: false
},
FileDialog::ScriptFolder { prompt: "Output folder".into(), start: dir.clone() },
],
"the dialogs carry the script's prompt, start location and whole filter"
);
}
/// #2894: the same from a dockable ScriptUI panel (Window ▸ <panel>): its button's
/// `File.openDialog` opens the file dialog and the panel's handler goes on with the file.
#[test]
fn a_docked_panel_button_opens_the_file_dialog() {
use effectcraft_engine::config::{ConfigStore, MemoryConfig};
use std::sync::{Arc, Mutex};
let store = Arc::new(MemoryConfig::default());
let panel = r#"
var p = this;
var status = p.add("statictext", undefined, "No file selected", { name: "status" });
status.characters = 40;
var pick = p.add("button", undefined, "Select SRT File", { name: "pick" });
pick.onClick = function () {
var f = File.openDialog("Select an SRT file", "Subtitles:*.srt;All Files:*.*");
status.text = f ? f.name : "No file selected";
};
p.layout.layout(true);
"#;
store.write("Scripts/ScriptUI Panels/Subtitles Panel.jsx", panel).unwrap();
let mut s = effectcraft_host::session();
s.config = Some(store.clone());
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
let asked: Arc<Mutex<Vec<Vec<String>>>> = Arc::default();
let log = asked.clone();
let file = std::env::temp_dir().join("Episode 1.srt").to_string_lossy().to_string();
h.state_mut().hooks.pick_files = Some(Box::new(move |exts: &[&str]| {
log.lock().unwrap().push(exts.iter().map(|e| e.to_string()).collect());
vec![file.clone()]
}));
h.state_mut().session.execute("window.scriptPanel", json!({"name": "Subtitles Panel.jsx"})).unwrap();
h.run_steps(3);
let panel = h.state().session.script_ui.windows.iter().find(|w| w.script == "Subtitles Panel.jsx").expect("the panel's window").id;
assert!(h.state().ui.dock.is_docked(PanelKind::ScriptPanel(panel)), "the panel docks");
click(&mut h, &format!("scriptui.{panel}.pick"));
assert_eq!(*asked.lock().unwrap(), [vec!["srt".to_string()]], "the panel's button opens the file dialog");
let status = h.state().session.script_ui.window(panel).and_then(|w| w.root.lookup(&json!("status"))).map(|w| w.text.clone()).unwrap_or_default();
assert_eq!(status, "Episode 1.srt");
}
+9 -1
View File
@@ -688,7 +688,15 @@ Scripts that build ScriptUI windows publish them to the session; agents drive th
A dialog's `show()` waits for the user: the `script.run` / `file.runScript` reply carries
`"waiting": true`, and the script continues (its final output arrives in the reply of the click
that closes the dialog). File ▸ Scripts: `file.scripts.list`, `file.runScript {"name": …}`,
that closes the dialog). A script's file dialog (`File.openDialog`, `File.saveDialog`,
`Folder.selectDialog`, `openDlg` / `saveDlg` / `selectDlg`, as a Browse… button calls them) waits
the same way in the app, which shows it. `scriptui.fileDialogs` lists the dialogs scripts wait on
(`{id, host, kind: open|save|folder, prompt, exts, label, any, many, start, shown}`; `shown`: the
app has shown it) and `scriptui.fileDialog {"id": …, "paths": […]}` (or `null`: cancelled) answers
one. On Windows the system dialog blocks the app's window until a person closes it, so an agent
can't answer it there; on macOS and Linux it doesn't block. The script's windows refuse events
meanwhile, except `scriptui.close`, which cancels the file dialog first. Without the app (headless
runs), in the Script Console and in Shutdown scripts these return `null` at once. File ▸ Scripts: `file.scripts.list`, `file.runScript {"name": …}`,
`file.installScript` / `file.installScriptUIPanel {"path": …}`, `window.scriptPanel {"name": …}`,
`window.restoreScriptPanels` (the panels open when the app last quit), `file.runStartupScripts` and
`file.runShutdownScripts` (the scripts in `Scripts/Startup` and `Scripts/Shutdown`; the second closes
+7 -5
View File
@@ -481,12 +481,14 @@ Playground cannons without interacting forces evolve every particle independentl
backend (reached through `EffectHost::particles` when the GPU compositor is active) simulates one
particle per invocation from the CPU's birth schedule and keeps per-key state checkpoints on the
GPU, like `SimCache`; the CPU simulation stays the oracle (tests compare ids and positions).
Particle Emitter 3D, Particle Emitter 2D and Liquid Particles sample their Birth Rate at every
step (`EffectHost::param_at`, #1373), so a keyed rate only decides the births of its own time;
the rate is left out of the simulation key, and a checkpoint is resumed only with the same rate history (the CPU state's `hist`, the GPU
checkpoint's births). The rate's keyframes are read at the step's exact layer time
Particle Emitter 3D, Particle Emitter 2D and Liquid Particles sample their Birth Rate and producer
position at every step (`EffectHost::param_at`, #1373), so a keyed rate only decides the births of
its own time and a particle is born where its producer was during that step. The rate and producer
are left out of the simulation key; a checkpoint is resumed only with the same rate and producer
histories (the CPU state's `hist` and `producer_hist`, the GPU checkpoint's births and producer
fingerprint). The values are read at the step's exact layer time
(`EvalCtx::value_at_layer_time`; mapping it to comp time and back rounds under a fractional
stretch), a rate without keyframes or an expression isn't sampled, and a layer of one of them with
stretch), a value without keyframes or an expression isn't sampled, and a layer of one of them with
expressions isn't layer cached (its key can't see what an expression returned at earlier times).
`effectcraft-cli bench --gpu` reports CPU vs GPU ms/frame, speed-up, Auto's ms/frame, pixel
agreement and the steady-state upload / readback MB per frame for every comp plus an
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more