Merge branch 'main' into fix/1955-producer-history

This commit is contained in:
FredApps committed 2026-11-25 00:00:45 +07:00
commit 786e9b033f
76 files changed
+10174 -1110

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}");
+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 })
}
+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}");
+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}");
}
}
}
}
+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);
+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");
}
+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);
}
}
}
+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
+1 -1
View File
@@ -20,7 +20,7 @@ our own scripts; no real-world script library has been run against both apps.
| Expression performance | Cached, multi-frame | Per-thread boa contexts | unknown | No benchmark |
| Scripting object model | `app`, `Project`, items, layers, properties, keys, eases, render queue, `TextDocument`, `Shape`, markers, `File`/`Folder`, `Socket`, `app.settings` | Same classes, edits run through undoable engine commands; match names table, the properties of Offset Paths and Zig Zag included; layers, groups and properties are callable (`layer("Effects")(1)` is `.property(...)`) | good | `crates/script` tests (≈ 10 test files) |
| `$.evalFile`, `BridgeTalk` | Evaluate another script file; identify the host application and message other Adobe applications | `$.evalFile` evaluates a file relative to the calling file (nested at most 32 deep, under the scripts' file gate) and returns its last value; `BridgeTalk` names the host honestly (`appName` `effectcraft`, its version); messaging other applications throws "not supported" | partial | `tests_evalfile.rs` (#760); no inter-application messaging |
| ScriptUI | Dialogs, palettes, dockable panels, resource strings, `onDraw` / ScriptUIGraphics, mouse events | Same, dockable panels reopen at launch; a docked panel gets its dock's size and `onResize` (`scriptui.resize`, #2585); a drag keeps reaching the control it started on past the window edge, and `MouseEvent.buttons` reports the held buttons (#2584) | good | `ui_scriptui`, `tests_ui*` |
| ScriptUI | Dialogs, palettes, dockable panels, resource strings, `onDraw` / ScriptUIGraphics, mouse events | Same, dockable panels reopen at launch; a docked panel gets its dock's size and `onResize` (`scriptui.resize`, #2585); a drag keeps reaching the control it started on past the window edge, and `MouseEvent.buttons` reports the held buttons (#2584); `File.openDialog`, `File.saveDialog` and `Folder.selectDialog` (a Browse… button) show the app's file dialog and the script waits for it (#2778) | good | `ui_scriptui`, `tests_ui*` |
| `app.scheduleTask` / `cancelTask` | One-shot and repeating tasks (polling, panel refresh) until `cancelTask` | Same: repeating tasks run every `delay` ms (at least 50 ms, at most 64 pending per script) until `cancelTask`, until they throw (reported once, then cancelled), or until their owner goes: a script's last window closing, or the project closing for scripts without windows (a Startup script's tasks go on until EffectCraft quits); frontends tick them every frame, agents with `script.runTasks` | good | `tests_tasks.rs` (#773); one-shot tasks of a script file still run right after it, not after their delay |
| Scripts menu, ScriptUI Panels folder | yes | yes; a subfolder (one level) of either folder is a submenu named after it | same | [plugins.md](plugins.md) |
| Startup / Shutdown folders | yes | `Scripts/Startup` runs at launch and `Scripts/Shutdown` runs as the desktop app quits, after the project is closed, each in alphabetical order | partial | `crates/script/src/tests/startup.rs`; each script has its own global scope, so a Startup script's variables and functions are not available to later scripts ([plugins.md](plugins.md)) |
+1 -1
View File
@@ -5,7 +5,7 @@ use std::process::Command;
use serde_json::Value;
const REV: &str = "808730f49b9637b7909fe2ae56f9d63fdb100cae";
const REV: &str = "068e079c7be4b100a8a6b305b31ac881e069727e";
const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("craft-ps", "0.1.0"), ("hayro-syntax", "0.7.2"), ("hayro-jbig2", "0.3.0")];
pub fn run(root: &Path) -> Result<(), String> {