diff --git a/.config/nextest.toml b/.config/nextest.toml index 38f939c31..54ea528cf 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -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" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ffbe49afb..b38c3d2b8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 }} diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7043e6128..74dbce1fa 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -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 | diff --git a/Cargo.lock b/Cargo.lock index 360c25794..b967eb41d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index 3301c483e..8a9a9d097 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/apps/effectcraft/src/file_dialogs.rs b/apps/effectcraft/src/file_dialogs.rs index 9f3114367..c8cf5181a 100644 --- a/apps/effectcraft/src/file_dialogs.rs +++ b/apps/effectcraft/src/file_dialogs.rs @@ -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, 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) -> Vec { 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 { + 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 { + 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 { + let all = + |files: Option>| -> Vec { files.unwrap_or_default().into_iter().map(|p| p.to_string_lossy().to_string()).collect() }; + let one = |file: Option| 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) -> Vec { 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) }) diff --git a/contributors/people.toml b/contributors/people.toml index 4f77ce8d1..eb363be5d 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -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" diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index 70586b798..803317795 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -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", diff --git a/crates/automation/src/tests.rs b/crates/automation/src/tests.rs index afee15936..a21248cb5 100644 --- a/crates/automation/src/tests.rs +++ b/crates/automation/src/tests.rs @@ -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}"); diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs index 2f1e1051b..00c38c502 100644 --- a/crates/engine/src/cmd/paths.rs +++ b/crates/engine/src/cmd/paths.rs @@ -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 { // 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 = 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 = 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 { 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 { - 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 = 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 { - 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 { 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 { 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!( diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 8c14e03ec..510efd12c 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -430,7 +430,12 @@ fn run_startup(s: &mut Session, _: &Value) -> Result { /// (frontends call it as the app quits, after the unsaved-changes prompt). fn run_shutdown(s: &mut Session, _: &Value) -> Result { 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 ▸ ``: run the panel script (or bring its panel forward). @@ -599,6 +604,21 @@ pub fn specs() -> Vec { 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 + ), ] } diff --git a/crates/engine/src/scriptui.rs b/crates/engine/src/scriptui.rs index 69e572ec2..250ca86bc 100644 --- a/crates/engine/src/scriptui.rs +++ b/crates/engine/src/scriptui.rs @@ -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, + /// 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; @@ -491,6 +535,13 @@ pub struct ScriptUi { /// replaced, until EffectCraft quits. #[serde(skip)] pub startup_hosts: Vec, + /// The file dialogs scripts wait on, until `scriptui.fileDialog` answers them. + pub file_dialogs: Vec, + /// 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 { 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 { + 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 { + 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 = 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::>>().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 { 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 }) } diff --git a/crates/engine/src/tests/stubs.rs b/crates/engine/src/tests/stubs.rs index 6f89f4f62..58fb21777 100644 --- a/crates/engine/src/tests/stubs.rs +++ b/crates/engine/src/tests/stubs.rs @@ -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 { + 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] diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index 6b93a8a7c..a810d21c2 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -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 } diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 16d65fabe..b89acbbab 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -413,9 +413,16 @@ fn write_still(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), } diff --git a/crates/export/tests/it/roundtrip.rs b/crates/export/tests/it/roundtrip.rs index 65644f071..fbde6ab1b 100644 --- a/crates/export/tests/it/roundtrip.rs +++ b/crates/export/tests/it/roundtrip.rs @@ -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 { } /// Frame `k` decoded by ffmpeg (external oracle) as RGBA, or `None` without ffmpeg. -fn ffmpeg_frame(path: &Path, k: u64) -> Option { +fn ffmpeg_frame(path: &Path, k: u64, trace: bool) -> Option { 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 { .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}"); diff --git a/crates/gpu/src/fx_lut.rs b/crates/gpu/src/fx_lut.rs index cf8df08d6..532679c0e 100644 --- a/crates/gpu/src/fx_lut.rs +++ b/crates/gpu/src/fx_lut.rs @@ -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 { 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, lut: &Lut) -> f32 { at } -/// Program layout: a stream of (opcode, arguments…) ending in 0, followed by LUT data. -fn encode(ops: &[ColorOp]) -> Option> { +/// 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, u32)> { if ops.len() > MAX_OPS { return None; } + let mut steps = 0; let mut prog: Vec = vec![]; let mut tables: Vec> = vec![]; // LUT offsets are patched once the program's length is known. @@ -142,6 +157,13 @@ fn encode(ops: &[ColorOp]) -> Option> { 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> { 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}"); + } + } + } } diff --git a/crates/gpu/src/shaders/fx_lut.wgsl b/crates/gpu/src/shaders/fx_lut.wgsl index f9081f834..b4d51a0ad 100644 --- a/crates/gpu/src/shaders/fx_lut.wgsl +++ b/crates/gpu/src/shaders/fx_lut.wgsl @@ -120,6 +120,14 @@ fn mix_exact(a: vec3, b: vec3, t: f32) -> vec3 { 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 { // Evaluate independent shaper channels without dynamically writing vector lanes. fn fxl_shaper_apply(sh: u32, c: vec3, flip: bool) -> vec3 { - let r = fxl_shaper_at(sh, 0u); - let g = fxl_shaper_at(sh, 1u); - let b = fxl_shaper_at(sh, 2u); - return vec3( - 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(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(v), lane); + } + return r; } fn fxl_file_fwd(o: u32, sh: i32, c0: vec3, interp: u32) -> vec3 { @@ -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, interp: u32, inverse: bool) -> vec3 1u) { - x = vec3(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(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(v), lane); + } } if (sh >= 0) { x = fxl_shaper_apply(u32(sh), x, true); diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 39ad32f14..c23ceeb05 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -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"] } diff --git a/crates/media/src/aac.rs b/crates/media/src/aac.rs index 356a8dff5..0aa987bf0 100644 --- a/crates/media/src/aac.rs +++ b/crates/media/src/aac.rs @@ -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 { +pub(crate) fn config(header: Option<&[u8]>, file: Option<&dyn ByteSource>) -> Option { 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> { +fn mp4(header: &[u8], file: Option<&dyn ByteSource>) -> Option> { 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> { /// 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> { +fn matroska(file: &dyn ByteSource) -> Option> { 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> { /// 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> { +fn latm(file: &dyn ByteSource) -> Option> { 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> { 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<()> { diff --git a/crates/media/src/convert.rs b/crates/media/src/convert.rs index bf83a9650..dd3a46801 100644 --- a/crates/media/src/convert.rs +++ b/crates/media/src/convert.rs @@ -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>, 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::>()); - 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 { diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs new file mode 100644 index 000000000..4459ac129 --- /dev/null +++ b/crates/media/src/craft_source.rs @@ -0,0 +1,5278 @@ +//! ISO-BMFF (MP4/MOV/M4A), Matroska/WebM (MKV/MKA/WebM), MXF, AVI, MPEG-TS/PS, YUV4MPEG2 and +//! standalone audio media-reader routes 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, while falling back to `filmcraft-codecs` for unsupported codecs or audio streams. +//! +//! ## Route Matrix (`crates/media`) +//! Video codecs admitted by [`supports_video_codec`] in every container: `H264`, `Hevc`, `Av1`, +//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video` and `Ffv1`. Audio goes through +//! `craft_audio::TrackDecoder` whenever it accepts the track (including `Pcm`); a track it declines +//! sends the whole file to `filmcraft-codecs`. +//! - **ISO-BMFF (`MP4`/`MOV`/`M4A`)**: shared, plus strictly admitted video-only `Apv` MP4. +//! Fallback: `Mjpeg`, `Mpeg4Video`, other `Apv`, or declined audio. +//! - **Matroska / WebM (`MKV`/`MKA`/`WebM`)**: shared, with `CodecDelay` + `SeekPreRoll` timing. +//! Fallback: `alpha_mode == 1` (`BlockAdditional` alpha), unreadable or compressed frame +//! encodings, `V_FFV1` without `CodecPrivate`, `Mjpeg`/`Theora`/`Apv`, or declined audio +//! (for example `Vorbis`). +//! - **MXF (OP1a/OP-Atom)**: shared, with sound `Pcm` and `Aes3` (D-10) read by +//! `MxfFile::read_pcm`. Fallback: compressed sound, video that needs reordering, or other codecs. +//! - **AVI / MPEG-TS / MPEG-PS**: shared; AVI also accepts complete 24/32-bit `BI_RGB` streams. +//! Fallback: other codecs (`Mjpeg`, `Mpeg4Video`, `Theora`, `Apv`), other raw AVI layouts, or +//! declined audio. +//! - **YUV4MPEG2 (`Y4M`)**: `craft_media_source::y4m`. Fallback: files it reports as unsupported +//! (for example a frame above the shared media buffer limit). +//! - **Standalone audio**: `craft_audio::Decoder` with `decode-native` for `WAV`, `AIFF`, +//! `MP3`/`MP2`/`MP1`, `AAC` (ADTS), `AC-3` and `Ogg` (`Opus`); bounded FLAC uses the shared +//! native FLAC decoder. Fallback: `Ogg Vorbis`, `CAF`, or FLAC and WAV/AIFF input the shared +//! readers decline. + +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, Region, VideoFrame}; +use craft_media::avi::{self, AviFile}; +use craft_media::bitstream::unescape_rbsp; +use craft_media::isobmff::{self, Mp4File}; +use craft_media::matroska::{self, MkvFile}; +use craft_media::mpegts; +use craft_media::mxf::{self, MxfFile, SoundFormat}; +use craft_media::{ByteSource, CodecId, CodecParams}; +use craft_media_source::cancel::cancelled; +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, VideoError, prores}; + +mod raw_avi; +use raw_avi::RawAvi; + +mod standalone_flac; + +/// 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; +const AUDIO_SEEK_BACKUP_PACKETS: usize = 2; + +/// Complete first-sample read cap for the ProRes alpha probe; larger samples use the legacy route. +const MAX_PRORES_ALPHA_SAMPLE_BYTES: u32 = 32 * 1024 * 1024; +/// Complete first-presented sample cap for the MXF ProRes colour probe. Larger samples retain the +/// existing colour policy; the ProRes header parser requires the complete declared frame. +const MAX_MXF_PRORES_COLOR_SAMPLE_BYTES: u32 = 4 * 1024 * 1024; + +/// Only migrate APV MP4 files with bounded complete access-unit reads. +const MAX_SHARED_APV_SAMPLE_BYTES: u32 = 32 * 1024 * 1024; +// Match the Film GOP cache's per-source decoded-plane ceiling. +const MAX_SHARED_APV_CACHE_BYTES: usize = 384 << 20; +const ISOBMFF_IDENTITY_MATRIX: [i32; 9] = [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x4000_0000]; + +fn worker_cap() -> usize { + std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS) +} + +fn prores_has_alpha(packet_size: u32, read: impl FnOnce() -> Option>) -> Option { + if packet_size > MAX_PRORES_ALPHA_SAMPLE_BYTES { + return None; + } + let packet = read()?; + Some(craft_video::prores::probe(&packet).ok()?.alpha != craft_video::prores::AlphaType::None) +} + +fn supports_video_codec(codec: CodecId) -> bool { + matches!( + codec, + CodecId::H264 | CodecId::Hevc | CodecId::Av1 | CodecId::Vp9 | CodecId::Vp8 | CodecId::ProRes | CodecId::Dnxhd | CodecId::Mpeg2Video | CodecId::Ffv1 + ) +} + +/// 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") +} + +/// True when `head` begins with an EBML header (Matroska / WebM). +fn looks_like_matroska(head: &[u8]) -> bool { + head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) +} + +/// The MXF sniffer needs the 16-byte partition key after the bounded 64 KiB run-in. +#[cfg(any(unix, windows))] +pub(crate) const NATIVE_SNIFF_HEAD_LEN: usize = 64 * 1024 + 16; + +/// Open an in-place ISO-BMFF, Matroska/WebM, MXF, AVI, MPEG-TS/PS, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. +/// Returns `None` when the container/codec/audio combination should fall back to `filmcraft-codecs`. +#[cfg(any(unix, windows))] +pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Option> { + let usual_head = &head[..head.len().min(craft_media_source::HEAD_LEN)]; + if looks_like_isobmff(usual_head) { + return open_isobmff(name, reader.clone()); + } + if looks_like_matroska(usual_head) { + return open_matroska(name, reader.clone()); + } + if mxf::sniff(head) { + return open_mxf(name, reader.clone()); + } + if avi::sniff(usual_head) { + return open_avi(name, reader.clone()); + } + if let Some(fmt) = mpegts::sniff(usual_head) { + return open_mpeg(name, fmt, reader.clone()); + } + if craft_media_source::y4m::sniff(usual_head) { + return open_y4m(name, reader.clone()); + } + if let Some(source) = standalone_flac::open_reader(name, usual_head, reader) { + return Some(Ok(source)); + } + open_standalone_audio(name, usual_head, reader.clone()) +} + +/// Open an in-memory ISO-BMFF, Matroska/WebM, MXF, AVI, MPEG-TS/PS, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. +pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option> { + if looks_like_isobmff(&bytes) { + return open_isobmff(name, Arc::new(bytes)); + } + if looks_like_matroska(&bytes) { + return open_matroska(name, Arc::new(bytes)); + } + if mxf::sniff(&bytes) { + return open_mxf(name, Arc::new(bytes)); + } + if avi::sniff(&bytes) { + return open_avi(name, Arc::new(bytes)); + } + if let Some(fmt) = mpegts::sniff(&bytes) { + return open_mpeg(name, fmt, Arc::new(bytes)); + } + if craft_media_source::y4m::sniff(&bytes) { + return open_y4m(name, Arc::new(bytes)); + } + if let Some(source) = standalone_flac::open_bytes(name, &bytes) { + return Some(Ok(source)); + } + #[cfg(any(unix, windows))] + { + let head_len = <[u8]>::len(&bytes).min(64); + let head = bytes[..head_len].to_vec(); + open_standalone_audio(name, &head, Arc::new(bytes)) + } + #[cfg(not(any(unix, windows)))] + { + None + } +} + +/// Open a YUV4MPEG2 stream through the shared indexed source. A stream the shared source reports +/// as unsupported keeps the FilmCraft route, so a file that opened before still opens. +fn open_y4m(name: &str, source: SharedBytes) -> Option> { + match craft_media_source::y4m::Y4mSource::open(name, source) { + Ok(y4m) => Some(Ok(Arc::new(y4m))), + Err(MediaError::Unsupported(_)) => None, + Err(e) => Some(Err(e)), + } +} + +enum ContainerFile { + Isobmff(Mp4File), + Matroska(Box), + Avi(Box), + Mpeg { file: Box, origin_pts: i64 }, + Mxf(Box), +} + +impl ContainerFile { + fn sample_count(&self, track_idx: usize) -> usize { + match self { + ContainerFile::Isobmff(f) => f.tracks.get(track_idx).map_or(0, |t| t.samples.len()), + ContainerFile::Matroska(f) => f.tracks.get(track_idx).map_or(0, |t| t.samples.len()), + ContainerFile::Avi(f) => f.streams.get(track_idx).map_or(0, |s| s.chunks.len()), + ContainerFile::Mpeg { file, .. } => file.streams.get(track_idx).map_or(0, |s| s.units.len()), + ContainerFile::Mxf(f) => f.tracks.get(track_idx).map_or(0, |t| t.samples.len()), + } + } + + fn read_sample(&self, src: &dyn ByteSource, track_idx: usize, sample_idx: usize) -> Result> { + match self { + ContainerFile::Isobmff(f) => f.read_sample(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), + ContainerFile::Matroska(f) => f.read_sample(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), + ContainerFile::Avi(f) => f.read_chunk(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), + ContainerFile::Mpeg { file, .. } => file.read_unit(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), + ContainerFile::Mxf(f) => f.read_sample(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), + } + } + + fn target_sample(&self, track_idx: usize, time: Tick) -> Option<(usize, i64)> { + match self { + ContainerFile::Isobmff(f) => { + let track = f.tracks.get(track_idx)?; + let t_track = tick_to_units(time, track.timescale); + let idx = track.sample_at_presentation_time(t_track)?; + Some((idx, track.samples[idx].pts)) + } + ContainerFile::Matroska(f) => { + let track = f.tracks.get(track_idx)?; + let t_track = tick_to_matroska_units(time, track.timebase); + let idx = track.sample_at_pts(t_track)?; + Some((idx, track.samples[idx].pts)) + } + ContainerFile::Avi(f) => { + let s = f.streams.get(track_idx)?; + if s.chunks.is_empty() || s.rate == 0 || s.scale == 0 { + return None; + } + let max_idx = i64::try_from(s.chunks.len() - 1).unwrap_or(0); + let d = tick_to_rational_units(time, i64::from(s.rate), i64::from(s.scale)).clamp(0, max_idx); + let idx = usize::try_from(d).ok()?; + Some((idx, d)) + } + ContainerFile::Mpeg { file, origin_pts } => { + let s = file.streams.get(track_idx)?; + let t_90k = tick_to_units(time, 90_000).saturating_add(*origin_pts); + let (idx, pts) = s + .units + .iter() + .enumerate() + .filter_map(|(i, u)| u.pts.map(|p| (i, p))) + .filter(|&(_, p)| p <= t_90k) + .max_by_key(|&(_, p)| p) + .or_else(|| s.units.iter().enumerate().find_map(|(i, u)| u.pts.map(|p| (i, p))))?; + Some((idx, pts)) + } + ContainerFile::Mxf(f) => { + let track = f.tracks.get(track_idx)?; + let (offset, presented_len) = mxf_picture_window(track); + if presented_len == 0 { + return None; + } + let d = tick_to_rational_units(time, i64::from(track.edit_rate.num), i64::from(track.edit_rate.den)); + let pos = offset.saturating_add(d.clamp(0, presented_len - 1)); + let idx = track.sample_at(pos)?; + Some((idx, track.samples[idx].pts)) + } + } + } + + fn sync_sample_before(&self, track_idx: usize, target_idx: usize) -> usize { + match self { + ContainerFile::Isobmff(f) => f.tracks[track_idx].sync_sample_before(target_idx), + ContainerFile::Matroska(f) => f.tracks[track_idx].sync_sample_before(target_idx), + ContainerFile::Avi(f) => { + let s = &f.streams[track_idx]; + let i = target_idx.min(s.chunks.len().saturating_sub(1)); + if s.keyframes_known { (0..=i).rev().find(|&k| s.chunks[k].key).unwrap_or(0) } else { 0 } + } + ContainerFile::Mpeg { file, .. } => { + let s = &file.streams[track_idx]; + let i = target_idx.min(s.units.len().saturating_sub(1)); + (0..=i).rev().find(|&k| s.units[k].key).unwrap_or(0) + } + ContainerFile::Mxf(f) => f.tracks[track_idx].sync_before(target_idx), + } + } + + fn scanned_avi_has_picture(&self, track_idx: usize, sample_idx: usize) -> bool { + let Self::Avi(file) = self else { return false }; + file.streams.get(track_idx).is_some_and(|s| !s.keyframes_known && s.chunks.get(sample_idx).is_some_and(|c| c.size != 0)) + } + + fn sample_pts(&self, track_idx: usize, sample_idx: usize) -> i64 { + match self { + ContainerFile::Isobmff(f) => f.tracks[track_idx].samples[sample_idx].pts, + ContainerFile::Matroska(f) => f.tracks[track_idx].samples[sample_idx].pts, + ContainerFile::Avi(_) => i64::try_from(sample_idx).unwrap_or(0), + ContainerFile::Mpeg { file, .. } => file.streams[track_idx].units[sample_idx].pts.unwrap_or(0), + ContainerFile::Mxf(f) => f.tracks[track_idx].samples[sample_idx].pts, + } + } + + fn pts_to_tick(&self, track_idx: usize, raw_pts: i64) -> Tick { + match self { + ContainerFile::Isobmff(f) => { + let track = &f.tracks[track_idx]; + let pts_units = raw_pts.saturating_add(track.edit_offset); + Tick::from_units(pts_units, i64::from(track.timescale.max(1))) + } + ContainerFile::Matroska(f) => { + let track = &f.tracks[track_idx]; + let ns = track.ticks_to_ns(raw_pts); + Tick::from_units(ns, 1_000_000_000) + } + ContainerFile::Avi(f) => { + let s = &f.streams[track_idx]; + Tick::from_units(raw_pts.saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) + } + ContainerFile::Mpeg { origin_pts, .. } => Tick::from_units(raw_pts.saturating_sub(*origin_pts), 90_000), + ContainerFile::Mxf(f) => { + let track = &f.tracks[track_idx]; + let rel_pts = raw_pts.saturating_sub(track.first_edit_unit()); + Tick::from_units(rel_pts.saturating_mul(i64::from(track.edit_rate.den)), i64::from(track.edit_rate.num.max(1))) + } + } + } + + fn audio_packet_is_stamped(&self, track_idx: usize, sample_idx: usize) -> bool { + match self { + Self::Isobmff(_) | Self::Avi(_) | Self::Mpeg { .. } | Self::Mxf(_) => true, + Self::Matroska(f) => f.tracks[track_idx].samples.get(sample_idx).is_some_and(|s| s.lace == 0 || s.duration > 0), + } + } + + fn audio_seek_info(&self, track_idx: usize, audio_starts: &[i64], seek_preroll_samples: i64, start: i64) -> (usize, i64) { + let target = start.saturating_sub(seek_preroll_samples).max(0); + let sample_idx = audio_starts.partition_point(|&s| s <= target).saturating_sub(1); + let mut seek_idx = sample_idx.saturating_sub(AUDIO_SEEK_BACKUP_PACKETS); + while seek_idx > 0 && !self.audio_packet_is_stamped(track_idx, seek_idx) { + seek_idx -= 1; + } + let decoded_pos = audio_starts.get(seek_idx).copied().unwrap_or(0); + (seek_idx, decoded_pos) + } + + fn audio_edit_range(&self, track_idx: usize, start: i64, frames: usize, sample_rate: u32) -> std::ops::Range { + let Self::Isobmff(file) = self else { return 0..frames }; + let Some((leading_duration, media)) = file.tracks.get(track_idx).and_then(|track| unit_rate_media_edit(&track.edits)) else { + return 0..frames; + }; + if file.timescale == 0 { + return 0..frames; + } + + // Packet positions include preroll. The edit's movie-clock boundaries + // determine which samples are presented, with the end excluded. + let offset = |ticks: u128| { + let frame = (ticks * u128::from(sample_rate)).div_ceil(u128::from(file.timescale)) as i128; + usize::try_from((frame - i128::from(start)).max(0)).unwrap_or(usize::MAX).min(frames) + }; + let leading = u128::from(leading_duration); + offset(leading)..offset(leading + u128::from(media.segment_duration)) + } + + /// Exclusive native packet position of the PCM edit's end. Unlike audio_edit_range, + /// this follows the demuxer's truncated packet placement, not the movie output clock. + fn pcm_edit_packet_end(&self, track_idx: usize, native_rate: u32) -> Option { + let Self::Isobmff(file) = self else { return None }; + let track = file.tracks.get(track_idx)?; + // pcm_chunked alone describes how the sample table was indexed from entry one. + // With several descriptions the decoder may have selected a different entry. + let [entry] = track.entries.as_slice() else { return None }; + if !matches!(entry.codec, isobmff::CodecConfig::Pcm(_)) + || !track.pcm_chunked + || native_rate == 0 + || track.timescale != native_rate + || file.timescale == 0 + { + return None; + } + let (leading, media) = unit_rate_media_edit(&track.edits)?; + let movie_clock = u128::from(file.timescale); + let native_clock = u128::from(native_rate); + let packet_start = i128::from(track.edit_offset).checked_add(i128::from(media.media_time))?; + let expected_start = i128::try_from(u128::from(leading) * native_clock / movie_clock).ok()?; + if packet_start != expected_start { + return None; + } + let duration = i128::try_from((u128::from(media.segment_duration) * native_clock).div_ceil(movie_clock)).ok()?; + i64::try_from(packet_start.checked_add(duration)?).ok() + } +} + +/// Where the container puts one audio packet, for [`contiguous_starts`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PacketTime { + /// Its timestamp, in output samples. + stamp: i64, + /// Whether `stamp` is the packet's own. A Matroska frame after the first in a laced block + /// without a duration repeats the block's timestamp. + stamped: bool, + /// Samples it decodes to, when known. + samples: Option, +} + +/// Packet start positions in output samples: each packet starts where the previous one ends, +/// unless its own timestamp is more than `tolerance` samples from there (a real gap or overlap in +/// the recording) or the previous packet's length is unknown; then it starts at its timestamp. +/// +/// Container timestamps are coarser than a sample. Matroska stores milliseconds, and a remux to MP4 +/// (OBS's) turns that rounding into uneven sample durations: a 1024-sample AAC frame at 48 kHz +/// lasts 21.33 ms, so frames are stamped at 0, 1008, 2064, 3072… Placing each decoded packet at its +/// stamp overwrote the end of one packet and left a hole of silence after another, a click every +/// few packets: crackling throughout playback and export (`storytold/effectcraft#1546`, +/// `storytold/filmcraft#359`). +fn contiguous_starts(packets: impl IntoIterator, tolerance: i64) -> Vec { + let tolerance = tolerance.max(0).unsigned_abs(); + let mut next = None; + packets.into_iter().map(|p| place_packet(p, &mut next, tolerance)).collect() +} + +fn packet_start(packet: PacketTime, next: Option, tolerance: u64) -> i64 { + match next { + Some(n) if !packet.stamped || n.abs_diff(packet.stamp) <= tolerance => n, + _ => packet.stamp, + } +} + +fn place_packet(packet: PacketTime, next: &mut Option, tolerance: u64) -> i64 { + let start = packet_start(packet, *next, tolerance); + *next = packet.samples.and_then(|n| start.checked_add(n)); + start +} + +struct PacketTimingPrefix { + len: usize, + next: Option, + tolerance: u64, + min_pending_stamp: i64, +} + +struct AudioStarts { + // Unvisited entries still hold raw container stamps. Resolve in place + // as packets arrive, reusing this table for the finished timeline. + positions: Vec, + pending: Option, +} + +impl AudioStarts { + fn complete(positions: Vec) -> Self { + Self { positions, pending: None } + } + + fn from_packet_timing(positions: Vec, tolerance: i64) -> Self { + // Open resolves exactly the bounded lookahead before anyone can seek. + let min_pending_stamp = positions.iter().skip(AUDIO_LOOKAHEAD).copied().min().unwrap_or(i64::MIN); + let pending = + (!positions.is_empty()).then_some(PacketTimingPrefix { len: 0, next: None, tolerance: tolerance.max(0).unsigned_abs(), min_pending_stamp }); + Self { positions, pending } + } + + fn start(&self, file: &ContainerFile, track: usize, idx: usize) -> Option { + let stamp = *self.positions.get(idx)?; + let Some(prefix) = &self.pending else { return Some(stamp) }; + if idx < prefix.len { + return Some(stamp); + } + debug_assert_eq!(idx, prefix.len); + (idx == prefix.len).then(|| { + let packet = PacketTime { stamp, stamped: file.audio_packet_is_stamped(track, idx), samples: None }; + packet_start(packet, prefix.next, prefix.tolerance) + }) + } + + fn observe(&mut self, file: &ContainerFile, track: usize, idx: usize, packet: &[u8], decoder: &AudioTrackDecoder) { + let Some(prefix) = &mut self.pending else { return }; + if idx != prefix.len { + return; + } + let samples = match decoder.codec() { + CodecId::Opus => opus_packet_samples(packet).map(i64::from), + CodecId::Flac => decoder.flac_packet_frames(packet).and_then(|n| i64::try_from(n).ok()), + _ => None, + }; + let timing = PacketTime { stamp: self.positions[idx], stamped: file.audio_packet_is_stamped(track, idx), samples }; + self.positions[idx] = place_packet(timing, &mut prefix.next, prefix.tolerance); + prefix.len += 1; + if prefix.len == self.positions.len() { + self.pending = None; + } + } + + fn seek_proves_first_packet(&self, target: i64) -> bool { + let Some(prefix) = &self.pending else { return false }; + // A normal read that starts before the very first packet looks like a + // backward seek. It need not read the suffix if the ordinary seek + // would back up to packet 0 anyway. Stamped starts can only move by the + // timing tolerance; unstamped continuation moves forward from next. + prefix.min_pending_stamp > target + && prefix.min_pending_stamp.abs_diff(target) > prefix.tolerance + && prefix.next.is_none_or(|next| next > target) + && self.positions.get(AUDIO_SEEK_BACKUP_PACKETS + 1..prefix.len).is_some_and(|p| p.iter().all(|&start| start > target)) + } + + fn finish_for_seek(&mut self, file: &ContainerFile, source: &dyn ByteSource, track: usize, decoder: &AudioTrackDecoder) -> Result<()> { + // The exact recurrence can carry a timing phase across arbitrarily many + // rounded or laced packets. A first discontinuous seek may still have to + // index the unread suffix; normal open and sequential decode never do this. + while let Some(idx) = self.pending.as_ref().map(|prefix| prefix.len) { + if cancelled() { + return Err(MediaError::Cancelled); + } + // Do not commit a guessed duration after an I/O error; the next + // request can retry this packet without re-reading the valid prefix. + let packet = file.read_sample(source, track, idx)?; + self.observe(file, track, idx, &packet, decoder); + } + Ok(()) + } +} + +fn fixed_packet_samples(dec: &mut AudioTrackDecoder, codec: CodecId, lookahead: &[Vec]) -> Option { + if !matches!(codec, CodecId::Aac | CodecId::HeAac | CodecId::Mp1 | CodecId::Mp2 | CodecId::Mp3 | CodecId::Ac3 | CodecId::Eac3) { + return None; + } + let mut frame_len: Option = None; + for pkt in lookahead { + let Ok(block) = dec.decode(pkt) else { + dec.reset(); + return None; + }; + let n = block.channels.first().map_or(0, Vec::len); + if n == 0 { + dec.reset(); + return None; + } + match frame_len { + None => frame_len = Some(n), + Some(prev) if prev != n => { + dec.reset(); + return None; + } + Some(_) => {} + } + } + dec.reset(); + frame_len.and_then(|n| i64::try_from(n).ok()) +} + +/// Duration of an Opus packet in 48 kHz samples from its TOC (RFC 6716 §3.1); `None` if invalid. +fn opus_packet_samples(pkt: &[u8]) -> Option { + let &toc = pkt.first()?; + let config = toc >> 3; + let frame = match config { + 0..=11 => [480, 960, 1920, 2880][(config & 3) as usize], + 12..=15 => [480, 960][(config & 1) as usize], + _ => [120, 240, 480, 960][(config & 3) as usize], + }; + let frames = match toc & 3 { + 0 => 1, + 1 | 2 => 2, + _ => (*pkt.get(1)? & 0x3F) as u32, + }; + let n = frame * frames; + (n > 0 && n <= 5760).then_some(n) +} + +fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: CodecId, native_rate: u32, fixed_samples: Option) -> AudioStarts { + let rate = i128::from(native_rate); + match container { + ContainerFile::Isobmff(f) => { + let Some(track) = f.tracks.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; + let ts = i128::from(track.timescale.max(1)); + let stamps: Vec = (0..track.samples.len()).map(|i| isobmff_audio_position(track, i, native_rate)).collect(); + let unit = i64::try_from((rate + ts - 1) / ts).unwrap_or(i64::MAX); + if matches!(codec, CodecId::Opus | CodecId::Flac) { + return AudioStarts::from_packet_timing(stamps, unit.saturating_mul(2).saturating_add(1)); + } + let Some(frame) = fixed_samples else { + return AudioStarts::complete(stamps); + }; + let tolerance = (frame / 2).max(unit.saturating_mul(2).saturating_add(1)); + let packets = stamps.into_iter().map(|stamp| PacketTime { stamp, stamped: true, samples: Some(frame) }); + AudioStarts::complete(contiguous_starts(packets, tolerance)) + } + ContainerFile::Matroska(f) => { + let Some(track) = f.tracks.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; + // Indexed PTS already subtracts CodecDelay rounded to the container clock. + // Translate between that clock and the warm path's whole-frame delay. + let tick_ns = i128::from(f.info.timestamp_scale.max(1)); + let delay_ns = i128::from(track.codec_delay_ns); + let indexed_delay_ns = ((delay_ns + tick_ns / 2) / tick_ns) * tick_ns; + let delay_frames = audio_frames_from_ns(delay_ns, native_rate); + let stamp_for = |pts: i64| -> i64 { + let ns = i128::from(track.ticks_to_ns(pts)) + indexed_delay_ns; + i64::try_from(audio_frames_from_ns(ns, native_rate) - delay_frames).unwrap_or(0) + }; + let tick_samples = i64::try_from(i128::from(track.ticks_to_ns(2)) * rate / 1_000_000_000).unwrap_or(i64::MAX).saturating_add(1); + if matches!(codec, CodecId::Opus | CodecId::Flac) { + return AudioStarts::from_packet_timing(track.samples.iter().map(|s| stamp_for(s.pts)).collect(), tick_samples); + } + let Some(frame) = fixed_samples else { + return AudioStarts::complete(track.samples.iter().map(|s| stamp_for(s.pts)).collect()); + }; + let packets = track.samples.iter().map(|s| PacketTime { stamp: stamp_for(s.pts), stamped: s.lace == 0 || s.duration > 0, samples: Some(frame) }); + AudioStarts::complete(contiguous_starts(packets, (frame / 2).max(tick_samples))) + } + ContainerFile::Avi(f) => { + let Some(s) = f.streams.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; + let den = i128::from(s.rate.max(1)); + let scale = i128::from(s.scale.max(1)); + if s.sample_size > 0 { + let mut acc = delayed_avi_pcm_start(s).map_or(0, |(start, _)| start); + return AudioStarts::complete( + s.chunks + .iter() + .map(|c| { + let start = acc; + acc = acc.saturating_add(i64::from(c.size / s.sample_size.max(1))); + start + }) + .collect(), + ); + } + let stamps: Vec = (0..s.chunks.len()).map(|i| i64::try_from(i128::from(i as i64) * scale * rate / den).unwrap_or(0)).collect(); + let Some(frame) = fixed_samples else { + return AudioStarts::complete(stamps); + }; + AudioStarts::complete(contiguous_starts(stamps.into_iter().map(|stamp| PacketTime { stamp, stamped: true, samples: Some(frame) }), frame / 2)) + } + ContainerFile::Mpeg { file, origin_pts } => { + let Some(s) = file.streams.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; + let mut last_stamp = 0i64; + let stamps: Vec = s + .units + .iter() + .map(|u| { + if let Some(p) = u.pts { + last_stamp = i64::try_from(i128::from(p.saturating_sub(*origin_pts)) * rate / 90_000).unwrap_or(0); + } + last_stamp + }) + .collect(); + let Some(frame) = fixed_samples else { + return AudioStarts::complete(stamps); + }; + AudioStarts::complete(contiguous_starts( + s.units.iter().zip(stamps).map(|(u, stamp)| PacketTime { stamp, stamped: u.pts.is_some(), samples: Some(frame) }), + frame / 2, + )) + } + ContainerFile::Mxf(_) => AudioStarts::complete(Vec::new()), + } +} + +fn audio_frames_from_ns(ns: i128, rate: u32) -> i128 { + (ns * i128::from(rate)) / 1_000_000_000 +} + +/// The decoded buffer starts on the presentation timeline, including negative trimmed samples. +/// Using the same signed position on open and seek preserves edit-list trim and leading silence. +fn isobmff_audio_position(track: &isobmff::Track, sample_idx: usize, native_rate: u32) -> i64 { + let pts = track.presentation_pts(sample_idx).unwrap_or(0); + let scaled = (i128::from(pts) * i128::from(native_rate)) / i128::from(track.timescale.max(1)); + i64::try_from(scaled).unwrap_or(if scaled < 0 { i64::MIN } else { i64::MAX }) +} + +fn open_audio_tracks(container: &ContainerFile, source: &dyn ByteSource, candidates: I) -> Option<(Vec, Vec)> +where + I: IntoIterator, +{ + let mut audio_tracks = Vec::new(); + let mut audio_infos = Vec::new(); + for (idx, sample_count, params, _codec_delay_ns) in candidates { + if audio_tracks.len() >= MAX_AUDIO_STREAMS { + break; + } + let n = AUDIO_LOOKAHEAD.min(sample_count); + let mut lookahead = Vec::with_capacity(n); + for s_idx in 0..n { + let pkt = container.read_sample(source, idx, s_idx).ok()?; + lookahead.push(pkt); + } + let refs: Vec<&[u8]> = lookahead.iter().map(Vec::as_slice).collect(); + let mut dec = AudioTrackDecoder::new(¶ms, &refs).ok()?; + let native_rate = dec.sample_rate().max(1); + let channels = u32::from(dec.layout().channels()).max(1); + let codec = dec.codec(); + let fixed_samples = fixed_packet_samples(&mut dec, codec, &lookahead); + let mut audio_starts = compute_audio_starts(container, idx, codec, native_rate, fixed_samples); + if audio_starts.pending.is_some() { + for (s_idx, pkt) in lookahead.iter().enumerate() { + audio_starts.observe(container, idx, s_idx, pkt, &dec); + } + } + let seek_preroll_samples = match container { + ContainerFile::Matroska(f) if codec == CodecId::Opus => { + let preroll_ns = i128::from(f.tracks[idx].seek_pre_roll_ns.max(80_000_000)); + i64::try_from(preroll_ns * i128::from(native_rate) / 1_000_000_000).unwrap_or(0) + } + _ => 0, + }; + let initial_pos = audio_starts.start(container, idx, 0).unwrap_or(0); + audio_infos.push(AudioStreamInfo { + sample_rate: native_rate, + channels, + codec: params.codec.name().to_string(), + bits_per_sample: dec.flac_stream_info().map(|info| u32::from(info.bits_per_sample)).or_else(|| params.pcm.map(|p| u32::from(p.bits))), + }); + audio_tracks.push(AudioTrackEntry { + track_idx: idx, + native_rate, + fixed_packet_samples: fixed_samples, + backend: AudioBackend::Decoder { + seek_preroll_samples, + state: Mutex::new(AudioTrackState { decoder: dec, audio_starts, next_sample: 0, decoded_pos: initial_pos, buf: Vec::new() }), + }, + }); + } + Some((audio_tracks, audio_infos)) +} + +/// A probe hint only: a single configured SPS can signal a visible size different from the +/// sample entry. Multiple or in-band parameter sets leave the initial hint to the container. +fn nal_visible_size_hint(config: &isobmff::CodecConfig) -> Option<(u32, u32)> { + let (_, _, width, height) = match config { + isobmff::CodecConfig::Avc(avc) => { + if avc.pps.is_empty() { + return None; + } + let mut sets = avc.sps.iter().filter(|n| n.first().is_some_and(|h| h & 0x1f == 7)); + let sps = sets.next()?; + if sets.next().is_some() { + return None; + } + craft_video::h264::decode::params::Sps::parse(&unescape_rbsp(sps.get(1..)?)).ok()?.crop_rect() + } + isobmff::CodecConfig::Hevc(hevc) => { + let (mut vps, mut sps, mut pps) = (false, None, false); + for nal in hevc.arrays.iter().filter(|a| (32..=34).contains(&a.nal_type)).flat_map(|a| &a.nalus) { + match nal.first().map(|h| (h >> 1) & 0x3f) { + Some(32) => vps = true, + Some(33) if sps.is_some() => return None, + Some(33) => sps = Some(nal), + Some(34) => pps = true, + _ => {} + } + } + if !vps || !pps { + return None; + } + craft_video::hevc::decode::params::Sps::parse(&unescape_rbsp(sps?.get(2..)?)).ok()?.crop_rect() + } + _ => return None, + }; + (width != 0 && height != 0).then_some((width, height)) +} + +/// Apply a valid container clean aperture in decoded-picture coordinates, before rotation. +fn clean_aperture_region(aperture: isobmff::CleanAperture, (width, height): (u32, u32)) -> Option { + let ratio = |(n, d): (u32, u32)| (d != 0).then(|| f64::from(n) / f64::from(d)); + let offset = |(n, d): (i32, u32)| (d != 0).then(|| f64::from(n) / f64::from(d)); + let w = ratio(aperture.width)?.round(); + let h = ratio(aperture.height)?.round(); + let dx = offset(aperture.horiz_offset)?; + let dy = offset(aperture.vert_offset)?; + let (frame_width, frame_height) = (f64::from(width), f64::from(height)); + if w < 1.0 || h < 1.0 || w > frame_width || h > frame_height { + return None; + } + let x = ((frame_width - w) / 2.0 + dx).round(); + let y = ((frame_height - h) / 2.0 + dy).round(); + if x < 0.0 || y < 0.0 || x + w > frame_width || y + h > frame_height { + return None; + } + let r = Region { x: x as usize, y: y as usize, w: w as usize, h: h as usize }; + (!r.is_full(width as usize, height as usize)).then_some(r) +} + +/// A single unit-rate media span, optionally preceded by one empty span. +fn unit_rate_media_edit(edits: &[isobmff::Edit]) -> Option<(u64, &isobmff::Edit)> { + const UNIT_RATE: i32 = 0x0001_0000; + let (leading_duration, media) = match edits { + [media] => (0, media), + [empty, media] if empty.media_time == -1 && empty.segment_duration > 0 && empty.media_rate == UNIT_RATE => (empty.segment_duration, media), + _ => return None, + }; + (media.media_time >= 0 && media.segment_duration != 0 && media.media_rate == UNIT_RATE).then_some((leading_duration, media)) +} + +/// A scalar EDL origin cannot describe dwell, disjoint edits or respeeding. +fn continuous_edit_mapping(track: &isobmff::Track, movie_timescale: u32) -> Option<(i64, i64)> { + if track.edits.is_empty() { + return (track.edit_offset == 0).then_some((0, 0)); + } + let (leading_duration, media) = unit_rate_media_edit(&track.edits)?; + if movie_timescale == 0 || track.timescale == 0 { + return None; + } + // Check the raw movie-to-media conversion before the demuxer's rounded + // offset can make a fractional delay look like an integral frame. + let lead = i128::from(leading_duration) * i128::from(track.timescale); + let movie_clock = i128::from(movie_timescale); + if lead % movie_clock != 0 { + return None; + } + let offset = i64::try_from(lead / movie_clock - i128::from(media.media_time)).ok()?; + (offset == track.edit_offset).then_some((media.media_time, offset)) +} + +/// The EDL origin is the timecode at presentation time zero, not the raw +/// counter at the start of the timecode sample. Its own track's edit and media +/// clock determine that sample's position; the video may have a different edit. +fn isobmff_timecode_origin(file: &Mp4File, video_idx: usize, video_rate: FrameRate) -> Option { + let video = file.tracks.get(video_idx)?; + continuous_edit_mapping(video, file.timescale)?; + let mut links = video.references.iter().filter(|(kind, _)| kind.0 == *b"tmcd").flat_map(|(_, ids)| ids); + let linked = links.next(); + if links.next().is_some() { + return None; + } + + let mut tracks = file.tracks.iter().filter(|track| track.kind == isobmff::TrackKind::Timecode && linked.is_none_or(|id| track.id == *id)); + let track = tracks.next()?; + if tracks.next().is_some() { + return None; + } + let [entry] = track.entries.as_slice() else { return None }; + let isobmff::CodecConfig::Timecode(tc) = &entry.codec else { return None }; + let [sample] = track.samples.as_slice() else { return None }; + let (media_start, timecode_offset) = continuous_edit_mapping(track, file.timescale)?; + if track.timescale == 0 || tc.timescale == 0 || tc.frame_duration == 0 || video_rate.num <= 0 || video_rate.den <= 0 { + return None; + } + if !track.edits.is_empty() && !(sample.pts..sample.pts.checked_add(i64::from(sample.duration))?).contains(&media_start) { + return None; + } + + // EDL subtracts the origin in native video frames; do not invent a + // rounding or clock-conversion policy for nonmatching or fractional origins. + let num = i128::from(tc.timescale); + let den = i128::from(tc.frame_duration); + if num * i128::from(video_rate.den) != den * i128::from(video_rate.num) + || video.samples.iter().any(|sample| i128::from(sample.duration) * num != i128::from(video.timescale) * den) + { + return None; + } + let delta = (i128::from(sample.pts) + i128::from(timecode_offset)) * num; + let divisor = i128::from(track.timescale) * den; + if delta % divisor != 0 { + return None; + } + i64::try_from(i128::from(tc.start_frame?) - delta / divisor).ok().filter(|&origin| origin >= 0) +} + +/// Admit only the APV MP4 shape whose timing and explicit color do not need the legacy +/// edit-list, snap/rebase or inferred-color policies. Inspect the existing index only; +/// APV's auxiliary alpha is per access unit and must still be decoded from each frame. +fn simple_mp4_apv_profile(file: &Mp4File, track: &isobmff::Track) -> Option { + use craft_video::apv::Profile; + if file.major_brand.0 != *b"isom" || file.fragmented || file.tracks.len() != 1 || !track.edits.is_empty() || track.edit_offset != 0 { + return None; + } + let [entry] = track.entries.as_slice() else { return None }; + let isobmff::CodecConfig::Apv(cfg) = &entry.codec else { return None }; + let video = entry.video.as_ref()?; + let profile = Profile::from_idc(cfg.profile_idc)?; + // The parser also accepts omitted/incomplete configuration fields. A simple complete + // version-1 record has a single primary-frame descriptor, optionally with four color bytes. + let record_size = if cfg.color_description_present { 22 } else { 18 }; + if !matches!(profile, Profile::P422_10 | Profile::P4444_10) + || cfg.raw_record.len() != record_size + || !cfg.raw_record.starts_with(&[1, 1, 1, 1]) + || cfg.bit_depth_minus8 != 2 + || cfg.chroma_format_idc != profile.default_chroma().idc() + || cfg.frame_width == 0 + || cfg.frame_height == 0 + || (cfg.frame_width, cfg.frame_height) != (u32::from(video.width), u32::from(video.height)) + || (track.width, track.height) != (cfg.frame_width, cfg.frame_height) + || video.clean_aperture.is_some() + || video.mastering_display.is_some() + || video.content_light.is_some() + || video.pixel_aspect.is_some_and(|par| par != (1, 1)) + || track.matrix != ISOBMFF_IDENTITY_MATRIX + || !matches!(video.color.as_ref(), Some(isobmff::ColorInfo::Nclx { primaries: 1, transfer: 1, matrix: 1, full_range: false })) + { + return None; + } + let step = track.samples.first()?.duration; + if step == 0 { + return None; + } + let rate = FrameRate::COMMON.into_iter().find(|r| i128::from(track.timescale) * i128::from(r.den) == i128::from(step) * i128::from(r.num))?; + // Coarse timing needs the legacy nominal-grid snap policy before rounding. Admit only + // tracks the Film reader itself would treat as fine, using the same tick quantization. + let den = i64::from(track.timescale); + let unit = filmcraft_time::Tick::from_rational(1, 1, den); + let rate = filmcraft_time::FrameRate::new(rate.num, rate.den); + if unit.0.saturating_mul(2) >= rate.frame_duration().0 { + return None; + } + let mut pos = 0i64; + for sample in &track.samples { + if sample.description_index != 1 + || !sample.is_sync + || sample.size == 0 + || sample.size > MAX_SHARED_APV_SAMPLE_BYTES + || sample.duration != step + || sample.pts != pos + || sample.dts != pos + { + return None; + } + pos = pos.checked_add(i64::from(step))?; + } + (u64::try_from(pos).ok()? == track.duration).then_some(profile) +} + +fn open_isobmff(name: &str, source: SharedBytes) -> Option> { + let file = isobmff::open(source.clone()).ok()?; + let video_idx = file.tracks.iter().position(|t| t.kind == isobmff::TrackKind::Video && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0); + let audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file + .tracks + .iter() + .enumerate() + .filter(|(_, t)| t.kind == isobmff::TrackKind::Audio && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0) + .map(|(idx, t)| (idx, t.samples.len(), t.codec_params(), 0)) + .collect(); + + if video_idx.is_none() && audio_candidates.is_empty() { + return None; + } + + let (video_info, video_state, presentation, duration) = if let Some(v_idx) = video_idx { + let video_track = &file.tracks[v_idx]; + let video_params = video_track.codec_params(); + let apv_profile = if video_params.codec == CodecId::Apv { + Some(simple_mp4_apv_profile(&file, video_track)?) + } else { + if !supports_video_codec(video_params.codec) { + return None; + } + None + }; + 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 (mut width, mut 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)); + // Probe needs dimensions before decoding. Retain the original rational aperture separately + // so frame conversion can use the actual visible size, even with in-band parameter sets. + let aperture = video_track.video().and_then(|v| v.clean_aperture); + if let Some(clap) = aperture { + (width, height) = nal_visible_size_hint(&video_track.entries[0].codec).unwrap_or((width, height)); + if let Some(region) = clean_aperture_region(clap, (width, height)) { + (width, height) = (region.w as u32, region.h as u32); + } + } + let mut par = video_track.video().and_then(|v| v.pixel_aspect).filter(|&(n, d)| n > 0 && d > 0).unwrap_or((1, 1)); + let rotation = video_track.display_rotation().unwrap_or(0) % 4; + if rotation % 2 == 1 { + std::mem::swap(&mut width, &mut height); + par = (par.1, par.0); + } + let has_alpha = if video_params.codec == CodecId::ProRes { + // The coded alpha plane is authoritative for ProRes, not the MOV sample-entry depth. + let sample = video_track.samples.first()?; + prores_has_alpha(sample.size, || file.read_sample(&*source, v_idx, 0).ok())? + } else if let Some(profile) = apv_profile { + profile.default_chroma().has_alpha() + } else { + video_track.video().is_some_and(|v| v.depth == 32) + }; + let frame_rate = estimate_isobmff_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 (codec_name, pixel_format, bitrate) = if let Some(profile) = apv_profile { + let format = if has_alpha { "YUVA 4:4:4:4 10-bit" } else { "YUV 4:2:2 10-bit" }; + let bytes: u128 = video_track.samples.iter().map(|sample| u128::from(sample.size)).sum(); + let bitrate = (bytes * 8 * u128::from(video_track.timescale)).checked_div(u128::from(video_track.duration)).and_then(|b| u64::try_from(b).ok()); + (profile.name().into(), format.into(), bitrate) + } else { + let bitrate = video_track.entries.first().and_then(|e| e.bitrate).map(|b| u64::from(b.avg_bitrate)).filter(|&b| b > 0); + (video_params.codec.name().to_string(), String::new(), bitrate) + }; + 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 v_info = VideoStreamInfo { width, height, frame_rate, par, codec: codec_name, pixel_format, color, has_alpha, bitrate, hdr: None }; + let v_state = VideoState::packet(video_decoder); + (Some(v_info), Some(v_state), FramePresentation { container_color, par, rotation, aperture }, duration) + } else { + let duration = audio_candidates + .iter() + .map(|&(idx, _, _, _)| { + let t = &file.tracks[idx]; + Tick::from_units(i64::try_from(t.duration).unwrap_or(i64::MAX), i64::from(t.timescale)) + }) + .max() + .unwrap_or(Tick::ZERO); + (None, None, FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, duration) + }; + + let start_timecode = video_idx.zip(video_info.as_ref()).and_then(|(idx, info)| isobmff_timecode_origin(&file, idx, info.frame_rate)); + let apv_cache = video_idx.is_some_and(|idx| matches!(file.tracks[idx].codec(), Some(isobmff::CodecConfig::Apv(_)))).then(ApvFrameCache::default); + let container = ContainerFile::Isobmff(file); + let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + if video_info.is_none() && audio_tracks.is_empty() { + return None; + } + + let kind = if video_info.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; + let info = MediaInfo { + name: name.to_string(), + kind, + duration, + video: video_info, + audio_streams: audio_infos, + container: "mp4".to_string(), + start_timecode, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: container, + video_track_idx: video_idx, + presentation, + video: video_state, + audio_tracks, + apv_cache, + }))) +} + +fn open_matroska(name: &str, source: SharedBytes) -> Option> { + let file = matroska::open(source.clone()).ok()?; + let video_idx = file.tracks.iter().position(|t| t.kind == matroska::TrackKind::Video && !t.samples.is_empty() && t.timebase.0 > 0 && t.timebase.1 > 0); + let audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file + .tracks + .iter() + .enumerate() + .filter(|(_, t)| t.kind == matroska::TrackKind::Audio && !t.samples.is_empty() && t.timebase.0 > 0 && t.timebase.1 > 0 && t.frames_readable()) + .map(|(idx, t)| (idx, t.samples.len(), t.codec_params(), t.codec_delay_ns)) + .collect(); + + if video_idx.is_none() && audio_candidates.is_empty() { + return None; + } + + let container_name = if file.doc_type == "webm" { "webm" } else { "mkv" }.to_string(); + let (video_info, video_state, container_color, par, rotation, duration) = if let Some(v_idx) = video_idx { + let video_track = &file.tracks[v_idx]; + if !video_track.frames_readable() { + return None; + } + // Native FFV1 without CodecPrivate cannot initialize the shared v3 decoder. + // Keep FilmCraft's metadata at open; an unsupported read stays a playback error. + if video_track.codec_private.is_empty() && matches!(&video_track.codec, matroska::Codec::Other(id) if id == "V_FFV1") { + return None; + } + let video_params = video_track.codec_params(); + if !supports_video_codec(video_params.codec) { + return None; + } + let v_meta = video_track.video.as_ref(); + // WebM/Matroska alpha_mode == 1 stores alpha in BlockAdditional; fall back to FilmCraft. + if v_meta.is_some_and(|v| v.alpha_mode == 1) { + return None; + } + let container_color = v_meta.and_then(|v| v.color.as_ref()).map(color_from_matroska); + let color = container_color.unwrap_or(ColorInfo::REC709); + let (mut width, mut height) = v_meta.map_or((0, 0), |v| (v.pixel_width, v.pixel_height)); + let mut par = matroska_par(v_meta, width, height); + let rotation = v_meta.and_then(|v| v.display_rotation()).unwrap_or(0) % 4; + if rotation % 2 == 1 { + std::mem::swap(&mut width, &mut height); + par = (par.1, par.0); + } + let frame_rate = estimate_matroska_frame_rate(video_track); + let duration = matroska_duration(&file, video_track); + let codec_name = video_params.codec.name().to_string(); + let coded_alpha = if video_params.codec == CodecId::ProRes { + // Bound the reconstructed packet, including the prefix restored by Matroska. + // Unknown alpha must not disable the shared reader for later pictures. + video_track + .sample_size(0) + .and_then(|size| u32::try_from(size).ok()) + .and_then(|size| prores_has_alpha(size, || file.read_sample(&*source, v_idx, 0).ok())) + .unwrap_or(false) + } else { + false + }; + 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 v_info = VideoStreamInfo { + width, + height, + frame_rate, + par, + codec: codec_name, + pixel_format: String::new(), + color, + has_alpha: coded_alpha, + bitrate: None, + hdr: None, + }; + let v_state = VideoState::packet(video_decoder); + (Some(v_info), Some(v_state), container_color, par, rotation, duration) + } else { + let duration = audio_candidates.iter().map(|&(idx, _, _, _)| matroska_duration(&file, &file.tracks[idx])).max().unwrap_or(Tick::ZERO); + (None, None, None, (1, 1), 0, duration) + }; + + let container = ContainerFile::Matroska(Box::new(file)); + let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + if video_info.is_none() && audio_tracks.is_empty() { + return None; + } + + let kind = if video_info.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; + let info = MediaInfo { + name: name.to_string(), + kind, + duration, + video: video_info, + audio_streams: audio_infos, + container: container_name, + start_timecode: None, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: container, + video_track_idx: video_idx, + presentation: FramePresentation { container_color, par, rotation, aperture: None }, + video: video_state, + audio_tracks, + apv_cache: None, + }))) +} + +struct ContainerVideoPart { + track_idx: usize, + info: VideoStreamInfo, + state: Mutex, +} + +fn finish_container_source( + name: &str, + container_name: &str, + source: SharedBytes, + container: ContainerFile, + video: Option, + duration: Tick, + audio_candidates: Vec<(usize, usize, CodecParams, u64)>, +) -> Option> { + let (mut audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + if video.is_none() && audio_tracks.is_empty() { + return None; + } + let duration = if video.is_none() + && let ContainerFile::Mpeg { file, .. } = &container + && matches!(file.format, mpegts::Format::Ts { .. }) + { + audio_tracks.iter_mut().filter_map(|entry| adts_track_end(file, entry)).fold(duration, |end, track_end| end.max(track_end)) + } else { + duration + }; + let kind = if video.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; + let (video_track_idx, video_info, video_state) = match video { + Some(v) => (Some(v.track_idx), Some(v.info), Some(v.state)), + None => (None, None, None), + }; + let info = MediaInfo { + name: name.to_string(), + kind, + duration, + video: video_info, + audio_streams: audio_infos, + container: container_name.to_string(), + start_timecode: None, + file_size: Some(source.len()), + }; + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: container, + video_track_idx, + presentation: FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, + video: video_state, + audio_tracks, + apv_cache: None, + }))) +} + +/// Use the same packet starts and sample count as playback to include the final ADTS packet. +fn adts_track_end(file: &mpegts::File, entry: &mut AudioTrackEntry) -> Option { + if file.streams.get(entry.track_idx)?.codec != mpegts::Codec::AacAdts { + return None; + } + let samples = entry.fixed_packet_samples?; + let AudioBackend::Decoder { state, .. } = &mut entry.backend else { return None }; + let last_start = *state.get_mut().ok()?.audio_starts.positions.iter().max()?; + Some(Tick::from_units(last_start.saturating_add(samples), i64::from(entry.native_rate))) +} + +fn mxf_sound_window(track: &mxf::EssenceTrack) -> (u64, u64) { + let (sp_num, sp_den) = track.samples_per_edit_unit(); + let sp_den = i128::from(sp_den.max(1)); + let sp_num = i128::from(sp_num); + let offset_units = track.first_edit_unit(); + let presented_start = u64::try_from((i128::from(offset_units) * sp_num) / sp_den).unwrap_or(0); + let stored = track.stored_sample_frames(); + let presented_len = match track.duration { + Some(dur_units) => u64::try_from((i128::from(dur_units.max(0)) * sp_num) / sp_den).unwrap_or(u64::MAX).min(stored.saturating_sub(presented_start)), + None => stored.saturating_sub(presented_start), + }; + (presented_start, presented_len) +} + +fn mxf_start_timecode(tc: mxf::Timecode, rate: Option) -> i64 { + let Some(rate) = rate else { + return tc.start; + }; + if tc.rounded_base == 0 || rate.num <= 0 || rate.den <= 0 { + return tc.start; + } + let rounded_media = (rate.num as f64 / rate.den as f64).round().clamp(1.0, f64::from(u16::MAX)) as u16; + if rounded_media == tc.rounded_base { + return tc.start; + } + let (tc_num, tc_den) = if tc.drop_frame { (i128::from(tc.rounded_base) * 1000, 1001i128) } else { (i128::from(tc.rounded_base), 1i128) }; + let Some(numerator) = (i128::from(tc.start) * tc_den).checked_mul(i128::from(rate.num)) else { + return tc.start; + }; + let denominator = tc_num * i128::from(rate.den); + // Match FilmCraft's nearest-frame rounding for recorded nonnegative labels. + // Keep the shared reader's existing truncation for negative counts. + let round_up = numerator >= 0 && numerator % denominator >= denominator - denominator / 2; + let converted = numerator / denominator + i128::from(round_up); + i64::try_from(converted).unwrap_or(tc.start) +} + +/// Material-package picture span, limited to indexed display pictures after the origin. +fn mxf_picture_window(track: &mxf::EssenceTrack) -> (i64, i64) { + let start = track.first_edit_unit(); + let available = i64::try_from(track.display_order.len()).unwrap_or(i64::MAX).saturating_sub(start).max(0); + (start, track.duration.unwrap_or(available).clamp(0, available)) +} + +/// Pixel aspect is the descriptor's display aspect divided by the frame's raster aspect. +fn mxf_picture_par(dar: mxf::Rational, width: u32, height: u32) -> (u32, u32) { + const SQUARE: (u32, u32) = (1, 1); + if !dar.is_valid() || width == 0 || height == 0 { + return SQUARE; + } + // Positive i32 by u32 fits u64; reduce before narrowing to the frame's u32 pair. + let num = u64::from(dar.num as u32) * u64::from(height); + let den = u64::from(dar.den as u32) * u64::from(width); + let (mut a, mut b) = (num, den); + while b != 0 { + (a, b) = (b, a % b); + } + match (u32::try_from(num / a), u32::try_from(den / a)) { + (Ok(num), Ok(den)) => (num, den), + _ => SQUARE, + } +} + +fn open_mxf(name: &str, source: SharedBytes) -> Option> { + let file = mxf::open(&*source).ok()?; + open_parsed_mxf(name, source, file) +} + +fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Option> { + let video_idx = file.tracks.iter().position(|t| t.kind == mxf::TrackKind::Picture && !t.samples.is_empty() && t.edit_rate.is_valid()); + let sound_indices: Vec = + file.tracks.iter().enumerate().filter(|(_, t)| t.kind == mxf::TrackKind::Sound && !t.chunks.is_empty()).map(|(idx, _)| idx).collect(); + + if video_idx.is_none() && sound_indices.is_empty() { + return None; + } + + // Fall back to FilmCraft for compressed MXF sound until MXF compressed audio is wired. + let mut audio_tracks = Vec::new(); + let mut audio_infos = Vec::new(); + for &idx in &sound_indices { + if audio_tracks.len() >= MAX_AUDIO_STREAMS { + break; + } + let t = &file.tracks[idx]; + if !matches!(t.sound_format, SoundFormat::Pcm | SoundFormat::Aes3Element) { + return None; + } + let sound = t.sound.as_ref()?; + let rate = if sound.sample_rate.is_valid() { sound.sample_rate.as_f64().round().clamp(1.0, f64::from(u32::MAX)) as u32 } else { 48_000 }; + let channels = sound.channels.max(1); + let (presented_start, presented_len) = mxf_sound_window(t); + audio_infos.push(AudioStreamInfo { sample_rate: rate, channels, codec: t.codec.codec_id().name().to_string(), bits_per_sample: Some(sound.bits) }); + audio_tracks.push(AudioTrackEntry { + track_idx: idx, + native_rate: rate, + fixed_packet_samples: None, + backend: AudioBackend::MxfPcm { presented_start, presented_len }, + }); + } + + let (video_info, video_state, presentation, duration) = if let Some(v_idx) = video_idx { + let video_track = &file.tracks[v_idx]; + let video_params = video_track.codec_params(); + if !supports_video_codec(video_params.codec) || video_track.needs_reorder { + return None; + } + let (width, height) = video_track.picture.as_ref().map_or((0, 0), |p| (p.frame_width(), p.frame_height())); + let par = video_track.picture.as_ref().map_or((1, 1), |p| mxf_picture_par(p.aspect_ratio, width, height)); + let er = video_track.edit_rate; + let fps = f64::from(er.num) / f64::from(er.den.max(1)); + let frame_rate = snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(er.num), i64::from(er.den))); + let (_, dur_units) = mxf_picture_window(video_track); + let duration = Tick::from_units(dur_units.saturating_mul(i64::from(er.den)), i64::from(er.num.max(1))); + let has_alpha = video_track.picture.as_ref().is_some_and(|p| p.alpha_depth > 0); + 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 (color, container_color) = + mxf_prores_color(&file, &*source, v_idx).map_or((ColorInfo::REC709, None), |(probe, descriptor)| (probe, Some(descriptor))); + let v_info = VideoStreamInfo { + width, + height, + frame_rate, + par, + codec: video_params.codec.name().to_string(), + pixel_format: String::new(), + color, + has_alpha, + bitrate: None, + hdr: None, + }; + let v_state = VideoState::packet(video_decoder); + (Some(v_info), Some(v_state), FramePresentation { container_color, par, rotation: 0, aperture: None }, duration) + } else { + let duration = audio_tracks + .iter() + .map(|entry| { + let presented_len = match entry.backend { + AudioBackend::MxfPcm { presented_len, .. } => i64::try_from(presented_len).unwrap_or(i64::MAX), + AudioBackend::Decoder { .. } => 0, + }; + Tick::from_units(presented_len, i64::from(entry.native_rate)) + }) + .max() + .unwrap_or(Tick::ZERO); + (None, None, FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, duration) + }; + + let kind = if video_info.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; + let start_timecode = file.timecode.map(|tc| mxf_start_timecode(tc, video_info.as_ref().map(|v| v.frame_rate))); + let info = MediaInfo { + name: name.to_string(), + kind, + duration, + video: video_info, + audio_streams: audio_infos, + container: "mxf".to_string(), + start_timecode, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: ContainerFile::Mxf(Box::new(file)), + video_track_idx: video_idx, + presentation, + video: video_state, + audio_tracks, + apv_cache: None, + }))) +} + +fn default_video_info(width: u32, height: u32, frame_rate: FrameRate, codec: &CodecParams) -> VideoStreamInfo { + VideoStreamInfo { + width, + height, + frame_rate, + par: (1, 1), + codec: codec.codec.name().to_string(), + pixel_format: String::new(), + color: ColorInfo::REC709, + has_alpha: false, + bitrate: None, + hdr: None, + } +} + +/// A byte-timed PCM stream uses one indexed unit per interleaved sample frame. +/// Convert its stream-clock start to native samples before counting those units. +fn delayed_avi_pcm_start(stream: &avi::Stream) -> Option<(i64, u32)> { + if stream.start == 0 || stream.scale == 0 || stream.rate == 0 { + return None; + } + let wave = stream.audio.as_ref()?; + if !matches!((wave.format_tag, wave.bits_per_sample), (1, 8 | 16 | 24 | 32) | (3, 32 | 64)) { + return None; + } + let (sample_rate, channels) = filmcraft_media::bounded_audio_dimensions(wave.sample_rate, u32::from(wave.channels)).ok()?; + let packed = u32::from(wave.bits_per_sample.div_ceil(8)) * channels; + // The shared decoder consumes packed PCM. Keep the prior route when the + // indexed sample size or block padding implies a different packet clock. + if stream.sample_size != packed || u32::from(wave.block_align) > packed { + return None; + } + let start = i128::from(stream.start) * i128::from(stream.scale) * i128::from(sample_rate) / i128::from(stream.rate); + Some((i64::try_from(start).ok()?, sample_rate)) +} + +fn delayed_avi_pcm_end(stream: &avi::Stream) -> Option { + let (start, sample_rate) = delayed_avi_pcm_start(stream)?; + let end = stream.chunks.iter().fold(start, |frames, chunk| frames.saturating_add(i64::from(chunk.size / stream.sample_size))); + Some(Tick::from_units(end, i64::from(sample_rate))) +} + +fn open_avi(name: &str, source: SharedBytes) -> Option> { + let file = avi::open(&*source).ok()?; + let video_idx = file.streams.iter().position(|s| s.kind == avi::StreamKind::Video && !s.chunks.is_empty() && s.rate > 0 && s.scale > 0); + let audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file + .streams + .iter() + .enumerate() + .filter(|(_, s)| s.kind == avi::StreamKind::Audio && !s.chunks.is_empty()) + .map(|(idx, s)| (idx, s.chunks.len(), s.codec_params(), 0)) + .collect(); + + if video_idx.is_none() && audio_candidates.is_empty() { + return None; + } + let delayed_audio_end = audio_candidates.iter().filter_map(|&(idx, _, _, _)| delayed_avi_pcm_end(&file.streams[idx])).max().unwrap_or(Tick::ZERO); + + if let Some(idx) = video_idx + && let Some(raw) = RawAvi::new(&file.streams[idx]) + { + if audio_candidates.iter().any(|&(audio, _, _, _)| { + let stream = &file.streams[audio]; + stream.start != 0 && delayed_avi_pcm_start(stream).is_none() + }) { + return None; + } + let duration = audio_candidates + .iter() + .filter(|&&(audio, _, _, _)| file.streams[audio].start == 0) + .map(|&(audio, _, _, _)| { + let s = &file.streams[audio]; + Tick::from_units(i64::from(s.length).saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) + }) + .fold(raw.duration(file.streams[idx].chunks.len()).max(delayed_audio_end), Tick::max); + let video = ContainerVideoPart { track_idx: idx, info: raw.info(&file.streams[idx]), state: Mutex::new(VideoState::RawAvi(raw)) }; + return finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), Some(video), duration, audio_candidates); + } + + let (video, duration) = if let Some(v_idx) = video_idx { + let video_stream = &file.streams[v_idx]; + let video_params = video_stream.codec_params(); + if !supports_video_codec(video_params.codec) { + return None; + } + let (width, height) = video_stream.video.as_ref().map_or((0, 0), |v| (v.width.unsigned_abs(), v.height.unsigned_abs())); + let fps = f64::from(video_stream.rate) / f64::from(video_stream.scale.max(1)); + let frame_rate = snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(video_stream.rate), i64::from(video_stream.scale))); + // Seeking treats each indexed video chunk as one frame. A stale header + // length can describe pictures beyond the end of the index. + let frames = i64::try_from(video_stream.chunks.len()).unwrap_or(i64::MAX); + let duration = Tick::from_rational(frames, i64::from(video_stream.scale), i64::from(video_stream.rate)); + 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 mut info = default_video_info(width, height, frame_rate, &video_params); + if video_params.codec == CodecId::ProRes { + // The coded alpha plane is authoritative when it can be probed. Otherwise, + // keep the old AVI default without dropping an otherwise readable stream. + let alpha = video_stream.chunks.first().and_then(|chunk| prores_has_alpha(chunk.size, || file.read_chunk(&*source, v_idx, 0).ok())); + info.has_alpha = alpha.unwrap_or(false); + } + let state = VideoState::packet(video_decoder); + (Some(ContainerVideoPart { track_idx: v_idx, info, state }), duration) + } else { + let duration = audio_candidates + .iter() + .filter(|&&(idx, _, _, _)| delayed_avi_pcm_start(&file.streams[idx]).is_none()) + .map(|(idx, _, params, _)| { + let s = &file.streams[*idx]; + let units = if params.codec == CodecId::Pcm && s.sample_size > 0 { + // Playback counts complete blocks within each indexed chunk. + s.chunks.iter().fold(0i64, |units, chunk| units.saturating_add(i64::from(chunk.size / s.sample_size))) + } else { + i64::from(s.length) + }; + Tick::from_units(units.saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) + }) + .max() + .unwrap_or(Tick::ZERO); + (None, duration) + }; + + finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), video, duration.max(delayed_audio_end), audio_candidates) +} + +fn estimate_mpeg_frame_rate_pts(pts: impl IntoIterator) -> FrameRate { + let mut pts: Vec = pts.into_iter().take(64).collect(); + pts.sort_unstable(); + let mut deltas: Vec = pts.windows(2).map(|w| w[1] - w[0]).filter(|&d| d > 0).collect(); + if deltas.is_empty() { + return FrameRate::FPS_30; + } + deltas.sort_unstable(); + let median = deltas[deltas.len() / 2]; + snap_common_fps(90_000.0 / median as f64).unwrap_or(FrameRate::FPS_30) +} + +fn estimate_mpeg_frame_rate(units: &[mpegts::Unit]) -> FrameRate { + estimate_mpeg_frame_rate_pts(units.iter().filter_map(|u| u.pts)) +} + +/// A timestamp is the start of a picture, not the end of its display interval. +fn regular_ts_picture_end(units: &[mpegts::Unit], origin_pts: i64, rate: FrameRate) -> Option { + let [first, second, rest @ ..] = units else { return None }; + let first_pts = first.pts?; + // A complete index can still contain a unit the public reader refuses to allocate. + let readable = |unit: &mpegts::Unit| unit.size > 0 && unit.size <= mpegts::MAX_UNIT_BYTES; + if !first.key || first_pts != origin_pts || rate.num <= 0 || rate.den <= 0 || !readable(first) || !readable(second) { + return None; + } + let mut last = second.pts?; + let step = last.checked_sub(first_pts)?; + // Do not infer a tail from a snapped rate or extrapolate an irregular track. + if step <= 0 || i128::from(step) * i128::from(rate.num) != 90_000 * i128::from(rate.den) { + return None; + } + for unit in rest { + let pts = unit.pts?; + if pts.checked_sub(last)? != step || !readable(unit) { + return None; + } + last = pts; + } + let end = last.checked_add(step)?.checked_sub(origin_pts)?; + let ticks = i128::from(end) * i128::from(craft_time::TICKS_PER_SECOND) / 90_000; + Some(Tick(i64::try_from(ticks).ok()?)) +} + +fn clean_ts_packet_index(file: &mpegts::File, source: &S) -> bool { + let mpegts::Format::Ts { packet_size, sync_offset } = file.format else { return false }; + if !file.warnings.is_empty() || !matches!(packet_size, 188 | 192 | 204) || sync_offset >= packet_size || !source.len().is_multiple_of(packet_size as u64) { + return false; + } + // Unlike the scanner's recovery path, require the five sync bytes it uses to + // identify a TS to align from byte zero, with no ignored partial packet at EOF. + let mut head = [0u8; 5 * 204]; + let Some(prefix) = head.get_mut(..5 * packet_size) else { return false }; + source.read_at(0, prefix).is_ok() && (0..5).all(|i| prefix.get(i * packet_size + sync_offset) == Some(&0x47)) +} + +fn open_mpeg(name: &str, fmt: mpegts::Format, source: SharedBytes) -> Option> { + let file = mpegts::open(&*source).ok()?; + let origin_pts = file.streams.iter().filter_map(|s| s.pts_range().map(|(lo, _)| lo)).min().unwrap_or(0); + let video_idx = file.streams.iter().position(|s| s.kind() == mpegts::Kind::Video && !s.units.is_empty()); + let audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file + .streams + .iter() + .enumerate() + .filter(|(_, s)| s.kind() == mpegts::Kind::Audio && !s.units.is_empty()) + .map(|(idx, s)| (idx, s.units.len(), s.codec_params(), 0)) + .collect(); + + if video_idx.is_none() && audio_candidates.is_empty() { + return None; + } + + let (video, duration) = if let Some(v_idx) = video_idx { + let video_stream = &file.streams[v_idx]; + let video_params = video_stream.codec_params(); + if !supports_video_codec(video_params.codec) { + return None; + } + let mut 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 mut decoded_dims = (video_params.width.unwrap_or(0), video_params.height.unwrap_or(0)); + if decoded_dims.0 == 0 || decoded_dims.1 == 0 { + let start_u = video_stream.units.iter().position(|u| u.key).unwrap_or(0); + for u_idx in start_u..video_stream.units.len().min(start_u + 16) { + if let Ok(pkt) = file.read_unit(&*source, v_idx, u_idx) + && let Ok(frames) = video_decoder.decode(&pkt, video_stream.units[u_idx].pts.unwrap_or(0)) + && let Some(vf) = frames.first() + { + decoded_dims = (vf.width(), vf.height()); + break; + } + } + let _ = video_decoder.reset(); + } + let frame_rate = estimate_mpeg_frame_rate(&video_stream.units); + let indexed_span = || video_stream.pts_range().map_or(Tick::ZERO, |(_, hi)| Tick::from_units(hi.saturating_sub(origin_pts), 90_000)); + let duration = + if file.streams.len() == 1 && video_params.codec == CodecId::H264 && video_stream.skipped_bytes == 0 && clean_ts_packet_index(&file, &*source) { + regular_ts_picture_end(&video_stream.units, origin_pts, frame_rate).unwrap_or_else(indexed_span) + } else { + indexed_span() + }; + let info = default_video_info(decoded_dims.0, decoded_dims.1, frame_rate, &video_params); + let state = VideoState::packet(video_decoder); + (Some(ContainerVideoPart { track_idx: v_idx, info, state }), duration) + } else { + let duration = audio_candidates + .iter() + .filter_map(|&(idx, _, _, _)| file.streams[idx].pts_range().map(|(_, hi)| Tick::from_units(hi.saturating_sub(origin_pts), 90_000))) + .max() + .unwrap_or(Tick::ZERO); + (None, duration) + }; + + finish_container_source(name, fmt.name(), source, ContainerFile::Mpeg { file: Box::new(file), origin_pts }, video, duration, audio_candidates) +} +struct CachedFrame { + pts: i64, + draft: bool, + frame: Arc, +} + +enum VideoState { + Packet(PacketVideoState), + RawAvi(RawAvi), +} + +impl VideoState { + fn packet(decoder: TrackDecoder) -> Mutex { + Mutex::new(Self::Packet(PacketVideoState { decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() })) + } +} + +struct PacketVideoState { + decoder: TrackDecoder, + next_decode_idx: usize, + gop_start_idx: usize, + flushed: bool, + decoded: Vec, +} + +fn decode_track_packet( + decoder: &mut TrackDecoder, + is_isobmff: bool, + packet: &[u8], + pts: i64, + decode_prores: impl FnOnce(&[u8], &prores::DecodeOptions) -> prores::Result, +) -> std::result::Result, VideoError> { + if !is_isobmff || decoder.codec() != CodecId::ProRes { + return decoder.decode(packet, pts); + } + // The caller holds this source's VideoState lock. Do not let a ProRes band + // job yield to another request for the same source on the decode Rayon pool. + // ProRes packets carry a complete picture: TrackDecoder's ProRes arm adds + // the PTS to this same conversion and has no draft, reset or reorder work. + let options = prores::DecodeOptions { threads: false, ..Default::default() }; + let mut frame = DecodedVideoFrame::try_from(decode_prores(packet, &options)?)?; + frame.pts = Some(pts); + Ok(vec![frame]) +} + +struct AudioTrackState { + decoder: AudioTrackDecoder, + audio_starts: AudioStarts, + next_sample: usize, + /// Sample index (in native-rate frames) of `buf[0]` relative to track start (0). + decoded_pos: i64, + /// Planar: one `Vec` per channel. + buf: Vec>, +} + +enum AudioBackend { + Decoder { seek_preroll_samples: i64, state: Mutex }, + MxfPcm { presented_start: u64, presented_len: u64 }, +} + +struct AudioTrackEntry { + track_idx: usize, + native_rate: u32, + fixed_packet_samples: Option, + backend: AudioBackend, +} + +#[cfg(test)] +impl AudioTrackEntry { + fn decoder_parts(&mut self) -> (i64, &mut AudioTrackState) { + match &mut self.backend { + AudioBackend::Decoder { seek_preroll_samples, state } => (*seek_preroll_samples, state.get_mut().unwrap()), + AudioBackend::MxfPcm { .. } => panic!("expected decoder audio backend"), + } + } +} + +#[derive(Clone, Copy)] +struct FramePresentation { + container_color: Option, + par: (u32, u32), + rotation: u8, + aperture: Option, +} + +struct CraftMediaSource { + info: MediaInfo, + source: SharedBytes, + file: ContainerFile, + video_track_idx: Option, + presentation: FramePresentation, + video: Option>, + audio_tracks: Vec, + apv_cache: Option, +} + +#[derive(Default)] +struct ApvFrameCache { + entries: Mutex>, + decode_gate: Mutex<()>, +} + +fn apv_cache_fits_pair(a: usize, b: usize) -> bool { + a.saturating_add(b) <= MAX_SHARED_APV_CACHE_BYTES +} + +impl ApvFrameCache { + fn get(&self, pts: i64) -> Option> { + let entries = self.entries.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + entries.iter().find(|entry| entry.pts == pts).map(|entry| entry.frame.clone()) + } + + fn get_or_decode(&self, pts: i64, decode: impl FnOnce() -> Result) -> Result> { + if let Some(frame) = self.get(pts) { + return Ok(frame); + } + // The short cache lock is not held while waiting or decoding. The decoder and + // pixel adapter must be strictly serial here: Rayon could reenter the same source. + let _gate = self.decode_gate.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(frame) = self.get(pts) { + return Ok(frame); + } + let frame = Arc::new(decode()?); + let mut entries = self.entries.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if entries.len() == 2 { + entries.remove(0); + } + if entries.first().is_some_and(|other| !apv_cache_fits_pair(other.frame.byte_size(), frame.byte_size())) { + entries.clear(); + } + // Like Film, keep the current frame even if it alone exceeds the cache ceiling. + entries.push(CachedFrame { pts, draft: false, frame: frame.clone() }); + Ok(frame) + } +} + +impl CraftMediaSource { + fn apv_frame(&self, track: &isobmff::Track, video_idx: usize, cache: &ApvFrameCache, time: Tick) -> Result> { + // The admitted fine timebase uses Film's nearest-unit lookup, not the floor used + // by other shared routes. Track selection timing is distinct from the frame's pts. + let lookup = filmcraft_time::Tick(time.0.max(0)).to_rational_round(1, i64::from(track.timescale)); + let target = track.sample_at_presentation_time(lookup).ok_or_else(|| MediaError::Decode("no video samples".into()))?; + let pts = track.samples[target].pts; + cache.get_or_decode(pts, || { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + // This is an in-memory copy or positional file read, then a serial decode + // and in-thread plane conversion; none can schedule a nested render. + let packet = self.file.read_sample(&*self.source, video_idx, target)?; + let options = craft_video::apv::DecodeOptions { threads: false, ..Default::default() }; + let mut decoded = craft_video::apv::decode_frame_with(&packet, &options).map_err(|e| MediaError::Decode(e.to_string()))?; + if decoded.chroma == craft_video::apv::ChromaFormat::Monochrome { + // A primary AU with an unexpected monochrome profile is still playable in Film: + // its adapter expands it to neutral 4:4:4 without dropping any auxiliary alpha. + let neutral = 1u16 << decoded.bit_depth.saturating_sub(1); + decoded.chroma = craft_video::apv::ChromaFormat::Yuv444; + decoded.cb = vec![neutral; decoded.y.len()]; + decoded.cr = vec![neutral; decoded.y.len()]; + } + let decoded = DecodedVideoFrame::try_from(decoded).map_err(|e| MediaError::Decode(e.to_string()))?; + let mut frame = to_craft_frame(decoded, self.presentation, Tick::ZERO)?; + // Film's explicit nclx wins for APV YUV, even when the AU says full range. + // The shared converter preserves both coded and per-AU auxiliary alpha. + if let Some(color) = self.presentation.container_color { + frame.color = color; + } + Ok(frame) + }) + } +} + +impl MediaSource for CraftMediaSource { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, req: FrameRequest) -> Result> { + let (Some(video_idx), Some(video_mutex)) = (self.video_track_idx, &self.video) else { + return Err(MediaError::NoStream("video")); + }; + if let Some(cache) = &self.apv_cache + && let ContainerFile::Isobmff(file) = &self.file + && let Some(track) = file.tracks.get(video_idx) + { + return self.apv_frame(track, video_idx, cache, req.time); + } + let (target_idx, target_pts) = self.file.target_sample(video_idx, req.time).ok_or_else(|| MediaError::Decode("no video samples".into()))?; + let want_draft = req.scale < 0.99; + + let mut state = video_mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let state = match &mut *state { + VideoState::Packet(state) => state, + VideoState::RawAvi(raw) => { + let ContainerFile::Avi(file) = &self.file else { return Err(MediaError::NoStream("AVI video")) }; + return raw.frame(file, &*self.source, video_idx, target_idx); + } + }; + if let Some(hit) = state.decoded.iter().find(|c| c.pts == target_pts && c.draft == want_draft) { + return Ok(hit.frame.clone()); + } + + // A scan cannot identify AVI keyframes, but each nonempty ProRes chunk is + // an independent picture. Do not read an earlier, possibly damaged chunk. + let direct_avi_prores = state.decoder.codec() == CodecId::ProRes && self.file.scanned_avi_has_picture(video_idx, target_idx); + let sync_idx = if direct_avi_prores { target_idx } else { self.file.sync_sample_before(video_idx, target_idx) }; + let draft_changed = state.decoder.draft() != want_draft; + if draft_changed { + state.decoder.set_draft(want_draft); + } + // Backward seek, jump to a later GOP, or draft/full-quality mode switch: reset decoder to + // the target sync sample so full-quality frames never reuse draft-decoded references. + if draft_changed || 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 sample_count = self.file.sample_count(video_idx); + let is_isobmff = matches!(&self.file, ContainerFile::Isobmff(_)); + while !state.decoded.iter().any(|c| c.pts >= target_pts && c.draft == want_draft) { + if cancelled() { + return Err(MediaError::Cancelled); + } + if state.next_decode_idx < sample_count { + let idx = state.next_decode_idx; + let pts = self.file.sample_pts(video_idx, idx); + let pkt = self.file.read_sample(&*self.source, video_idx, idx)?; + let frames = + decode_track_packet(&mut state.decoder, is_isobmff, &pkt, pts, prores::decode_frame_with).map_err(|e| MediaError::Decode(e.to_string()))?; + state.next_decode_idx = idx + 1; + push_decoded(&mut state.decoded, frames, want_draft, self.presentation, &self.file, video_idx)?; + } 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, want_draft, self.presentation, &self.file, video_idx)?; + break; + } else { + break; + } + } + + if let Some(exact) = state.decoded.iter().find(|c| c.pts == target_pts && c.draft == want_draft) { + 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.draft == want_draft && c.pts <= target_pts) + .max_by_key(|c| c.pts) + .or_else(|| state.decoded.iter().find(|c| c.draft == want_draft)) + .ok_or_else(|| MediaError::Decode("video decoder produced no frame".into()))?; + Ok(best.frame.clone()) + } + + fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result { + self.audio_stream(0, start, frames, sample_rate) + } + + fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result { + 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); + let edit_range = self.file.audio_edit_range(entry.track_idx, start, frames, sample_rate); + let audible_frames = edit_range.len(); + if audible_frames == 0 { + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); + } + + let audible_start = i64::try_from(i128::from(start) + edit_range.start as i128).unwrap_or(i64::MAX); + let native_rate = entry.native_rate; + let Some((native_start, mut native_frames, phase)) = resampling_window(audible_start, audible_frames, native_rate, sample_rate) else { + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); + }; + if native_rate != sample_rate { + // The resampler asks for lookahead. Do not interpolate with samples + // that are stored in the track but lie beyond the edit. + native_frames = self.file.audio_edit_range(entry.track_idx, native_start, native_frames, native_rate).end; + } + + let decoded = match &entry.backend { + AudioBackend::Decoder { seek_preroll_samples, state: state_mutex } => { + let packet_frames = self + .file + .pcm_edit_packet_end(entry.track_idx, native_rate) + .map_or(native_frames, |end| usize::try_from((i128::from(end) - i128::from(native_start)).max(0)).unwrap_or(usize::MAX).min(native_frames)); + let mut channels = if packet_frames == 0 && native_frames != 0 { + vec![Vec::new(); channels_count] + } else { + let mut state = state_mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + decode_audio_range( + &self.file, + &*self.source, + entry.track_idx, + native_rate, + channels_count, + *seek_preroll_samples, + &mut state, + native_start, + packet_frames, + )? + }; + // A direct read still owes the full output window. For a resampled read, keep + // the clipped buffer short so its last valid sample remains the one-sided guard. + if sample_rate == native_rate && packet_frames < native_frames { + for channel in &mut channels { + channel.resize(native_frames, 0.0); + } + } + channels + } + AudioBackend::MxfPcm { presented_start, presented_len } => { + if cancelled() { + return Err(MediaError::Cancelled); + } + let ContainerFile::Mxf(mxf_file) = &self.file else { + return Err(MediaError::NoStream("audio")); + }; + let req_end = native_start.saturating_add(native_frames as i64); + let win_len = i64::try_from(*presented_len).unwrap_or(i64::MAX); + if *presented_start == 0 && native_start >= 0 && req_end <= win_len { + mxf_file.read_pcm(&*self.source, entry.track_idx, native_start as u64, native_frames).map_err(|e| MediaError::Io(e.to_string()))? + } else { + let mut out = vec![vec![0.0f32; native_frames]; channels_count]; + let clamped_start = native_start.max(0).min(win_len); + let clamped_end = req_end.max(0).min(win_len); + let read_len = usize::try_from(clamped_end.saturating_sub(clamped_start)).unwrap_or(0); + if read_len > 0 { + let dst_off = usize::try_from(clamped_start - native_start).unwrap_or(0); + let stored_start = presented_start.saturating_add(clamped_start as u64); + let read = mxf_file.read_pcm(&*self.source, entry.track_idx, stored_start, read_len).map_err(|e| MediaError::Io(e.to_string()))?; + for (dst, src) in out.iter_mut().zip(&read) { + let n = src.len().min(read_len); + dst[dst_off..dst_off + n].copy_from_slice(&src[..n]); + } + } + out + } + } + }; + + let mut channels = if sample_rate == native_rate { + decoded + } else { + let first_output = if audible_start < 0 { usize::try_from(audible_start.unsigned_abs()).unwrap_or(audible_frames).min(audible_frames) } else { 0 }; + resample_audio_with_phase(&decoded, native_rate, sample_rate, audible_frames, phase, first_output) + }; + if audible_frames < frames { + for channel in &mut channels { + channel.resize(frames, 0.0); + channel.rotate_right(edit_range.start); + } + } + Ok(AudioBuffer { sample_rate, channels }) + } +} + +#[cfg(any(unix, windows))] +struct SharedBytesSource(SharedBytes); + +#[cfg(any(unix, windows))] +impl ByteSource for SharedBytesSource { + fn len(&self) -> u64 { + self.0.len() + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.0.read_at(offset, buf) + } +} + +#[cfg(any(unix, windows))] +struct StandaloneAudioState { + decoder: craft_audio::Decoder<'static>, + decoded_pos: i64, + buf: Vec>, +} + +#[cfg(any(unix, windows))] +struct StandaloneAudioSource { + info: MediaInfo, + native_rate: u32, + state: Mutex, +} + +#[cfg(any(unix, windows))] +impl MediaSource for StandaloneAudioSource { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, _req: FrameRequest) -> Result> { + Err(MediaError::NoStream("video")) + } + + fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result { + self.audio_stream(0, start, frames, sample_rate) + } + + fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result { + if stream != 0 { + return Err(MediaError::NoStream("audio")); + } + let channels_count = self.info.audio_streams.first().map_or(2, |s| s.channels as usize); + if frames == 0 || sample_rate == 0 { + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); + } + let native_rate = self.native_rate; + let Some((native_start, native_frames, phase)) = resampling_window(start, frames, native_rate, sample_rate) else { + // An unrepresentable source position cannot address this stream. + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); + }; + + let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let decoded = decode_standalone_range(native_rate, channels_count, &mut state, native_start, native_frames)?; + if sample_rate == native_rate { + return Ok(AudioBuffer { sample_rate, channels: decoded }); + } + // Negative output positions are silence, not interpolation into frame zero. + let first_output = if start < 0 { usize::try_from(start.unsigned_abs()).unwrap_or(frames).min(frames) } else { 0 }; + Ok(AudioBuffer { sample_rate, channels: resample_audio_with_phase(&decoded, native_rate, sample_rate, frames, phase, first_output) }) + } +} + +/// Step the fractional input position as an exact integer quotient and remainder; +/// rounding happens only when interpolating a sample, independent of the window. +fn resample_audio_with_phase( + decoded: &[impl AsRef<[f32]>], + native_rate: u32, + sample_rate: u32, + frames: usize, + phase: u64, + first_output: usize, +) -> Vec> { + let mut out = vec![vec![0.0; frames]; decoded.len()]; + let divisor = u64::from(sample_rate); + let first = first_output as u128 * u128::from(native_rate) + u128::from(phase); + let Ok(first_index) = usize::try_from(first / u128::from(divisor)) else { return out }; + let first_remainder = (first % u128::from(divisor)) as u64; + let whole_step = (native_rate / sample_rate) as usize; + let remainder_step = u64::from(native_rate % sample_rate); + let inverse_rate = f64::from(sample_rate).recip(); + for (samples, dst) in decoded.iter().zip(&mut out) { + let samples = samples.as_ref(); + let (mut index, mut remainder) = (first_index, first_remainder); + for sample in dst.iter_mut().skip(first_output) { + let Some(&a) = samples.get(index) else { break }; + let b = samples.get(index + 1).copied().unwrap_or(a); + let t = (remainder as f64 * inverse_rate) as f32; + *sample = a + (b - a) * t; + remainder += remainder_step; + let carry = remainder >= divisor; + if carry { + remainder -= divisor; + } + let Some(next) = index.checked_add(whole_step + carry as usize) else { break }; + index = next; + } + } + out +} + +#[cfg(any(unix, windows))] +fn decode_standalone_range(native_rate: u32, channels_count: usize, state: &mut StandaloneAudioState, start: i64, frames: usize) -> Result>> { + let end = start.saturating_add(frames as i64); + if end <= 0 { + return Ok(vec![vec![0.0f32; frames]; channels_count]); + } + + 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 { + let target = u64::try_from(start.max(0)).unwrap_or(0); + let actual = state.decoder.seek(target).map_err(|e| MediaError::Decode(e.to_string()))?; + state.decoded_pos = i64::try_from(actual).unwrap_or(i64::MAX); + 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 { + if cancelled() { + return Err(MediaError::Cancelled); + } + let Some(block) = state.decoder.next_block().map_err(|e| MediaError::Decode(e.to_string()))? else { + break; + }; + for (c, ch) in state.buf.iter_mut().enumerate() { + if let Some(src_ch) = block.channels.get(c) { + ch.extend_from_slice(src_ch); + } + } + } + + Ok(drain_audio_window(&mut state.buf, &mut state.decoded_pos, channels_count, start, frames)) +} + +fn resampling_window(start: i64, frames: usize, native_rate: u32, sample_rate: u32) -> Option<(i64, usize, u64)> { + if sample_rate == native_rate { + return Some((start, frames, 0)); + } + let (origin, phase) = resampling_origin(start, native_rate, sample_rate)?; + let len = ((frames as u128 * u128::from(native_rate)).div_ceil(u128::from(sample_rate)) + 2) as usize; + Some((origin, len, phase)) +} + +fn resampling_origin(start: i64, native_rate: u32, sample_rate: u32) -> Option<(i64, u64)> { + let scaled = i128::from(start) * i128::from(native_rate); + let divisor = i128::from(sample_rate); + let origin = i64::try_from(scaled.div_euclid(divisor)).ok()?; + Some((origin, scaled.rem_euclid(divisor) as u64)) +} + +fn drain_audio_window(buf: &mut [Vec], decoded_pos: &mut i64, channels_count: usize, start: i64, frames: usize) -> Vec> { + let mut out = vec![vec![0.0f32; frames]; channels_count]; + let avail = buf.first().map_or(0, Vec::len); + for i in 0..frames { + let pos = start.saturating_add(i as i64); + if pos >= *decoded_pos { + let off = usize::try_from(pos.saturating_sub(*decoded_pos)).unwrap_or(usize::MAX); + if off < avail { + for (c, out_ch) in out.iter_mut().enumerate() { + out_ch[i] = buf[c][off]; + } + } + } + } + let end = start.saturating_add(frames as i64); + let drop_to = usize::try_from(end.saturating_sub(*decoded_pos).max(0)).unwrap_or(usize::MAX); + let trim = drop_to.min(avail); + if trim > 0 { + for ch in buf { + ch.drain(..trim); + } + *decoded_pos = decoded_pos.saturating_add(trim as i64); + } + out +} + +#[cfg(any(unix, windows))] +fn open_standalone_audio(name: &str, head: &[u8], source: SharedBytes) -> Option> { + let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()); + let container = craft_audio::detect_container(head, ext)?; + let container_name = match container { + craft_audio::Container::Wav => "wav", + craft_audio::Container::Aiff => "aiff", + craft_audio::Container::MpegAudio => "mp3", + craft_audio::Container::Adts => "aac", + craft_audio::Container::Ac3 => "ac3", + craft_audio::Container::Ogg => "ogg", + _ => return None, + }; + + let dec = craft_audio::Decoder::open(SharedBytesSource(source.clone()), ext, &craft_audio::DecodeOptions::default()).ok()?; + let audio_info = if dec.length_known() { + dec.info().clone() + } else { + craft_audio::Decoder::open(SharedBytesSource(source.clone()), ext, &craft_audio::DecodeOptions::default()).ok()?.probe().ok()? + }; + + let native_rate = audio_info.sample_rate.max(1); + let channels = u32::from(audio_info.channels).max(1); + let duration = Tick::from_units(i64::try_from(audio_info.frames).unwrap_or(i64::MAX), i64::from(native_rate)); + let bits_per_sample = match audio_info.sample_format { + craft_audio::SampleFormat::Int8 => Some(8), + craft_audio::SampleFormat::Int16 => Some(16), + craft_audio::SampleFormat::Int24 => Some(24), + craft_audio::SampleFormat::Int32 | craft_audio::SampleFormat::Float32 => Some(32), + craft_audio::SampleFormat::Float64 => Some(64), + craft_audio::SampleFormat::Compressed | _ => None, + }; + let info = MediaInfo { + name: name.to_string(), + kind: MediaKind::AudioOnly, + duration, + video: None, + audio_streams: vec![AudioStreamInfo { sample_rate: native_rate, channels, codec: audio_info.codec.name().to_string(), bits_per_sample }], + container: container_name.to_string(), + start_timecode: None, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(StandaloneAudioSource { info, native_rate, state: Mutex::new(StandaloneAudioState { decoder: dec, decoded_pos: 0, buf: Vec::new() }) }))) +} + +#[allow(clippy::too_many_arguments)] +fn decode_audio_range( + file: &ContainerFile, + source: &dyn ByteSource, + track_idx: usize, + native_rate: u32, + channels_count: usize, + seek_preroll_samples: i64, + state: &mut AudioTrackState, + start: i64, + frames: usize, +) -> Result>> { + let end = start.saturating_add(frames as i64); + if end <= 0 { + return Ok(vec![vec![0.0f32; frames]; channels_count]); + } + + let buf_len = state.buf.first().map_or(0, Vec::len) as i64; + let buf_end = state.decoded_pos.saturating_add(buf_len); + let moves_backward = start < state.decoded_pos; + if moves_backward || start > buf_end.saturating_add(i64::from(native_rate) * 2) { + let target = start.saturating_sub(seek_preroll_samples).max(0); + let (seek_idx, decoded_pos) = if moves_backward && state.next_sample == 0 && state.audio_starts.seek_proves_first_packet(target) { + (0, state.decoded_pos) + } else { + state.audio_starts.finish_for_seek(file, source, track_idx, &state.decoder)?; + file.audio_seek_info(track_idx, &state.audio_starts.positions, seek_preroll_samples, start) + }; + state.decoder.reset(); + state.next_sample = seek_idx; + state.decoded_pos = decoded_pos; + for ch in &mut state.buf { + ch.clear(); + } + } + + if state.buf.len() != channels_count { + state.buf = vec![Vec::new(); channels_count]; + } + + let sample_count = file.sample_count(track_idx); + while state.next_sample < sample_count { + if cancelled() { + return Err(MediaError::Cancelled); + } + let idx = state.next_sample; + let buf_len = state.buf.first().map_or(0, Vec::len) as i64; + let buf_end = state.decoded_pos.saturating_add(buf_len); + let pk_start = if buf_len > 0 && !file.audio_packet_is_stamped(track_idx, idx) { + buf_end + } else { + state.audio_starts.start(file, track_idx, idx).unwrap_or(buf_end) + }; + if pk_start >= end { + break; + } + let pkt = file.read_sample(source, track_idx, idx)?; + state.audio_starts.observe(file, track_idx, idx, &pkt, &state.decoder); + state.next_sample = idx + 1; + let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?; + let buf_len = state.buf.first().map_or(0, Vec::len) as i64; + if buf_len == 0 { + state.decoded_pos = pk_start; + } else { + let buf_end = state.decoded_pos.saturating_add(buf_len); + if pk_start > buf_end { + let gap = usize::try_from(pk_start - buf_end).unwrap_or(0); + for ch in &mut state.buf { + ch.resize(ch.len() + gap, 0.0); + } + } else if pk_start < buf_end { + if pk_start <= state.decoded_pos { + for ch in &mut state.buf { + ch.clear(); + } + state.decoded_pos = pk_start; + } else { + let overlap = usize::try_from(buf_end - pk_start).unwrap_or(0); + for ch in &mut state.buf { + let keep = ch.len().saturating_sub(overlap); + ch.truncate(keep); + } + } + } + } + for (c, ch) in state.buf.iter_mut().enumerate() { + if let Some(src_ch) = block.channels.get(c) { + ch.extend_from_slice(src_ch); + } + } + } + + Ok(drain_audio_window(&mut state.buf, &mut state.decoded_pos, channels_count, start, frames)) +} + +fn push_decoded( + cache: &mut Vec, + frames: Vec, + draft: bool, + presentation: FramePresentation, + file: &ContainerFile, + track_idx: usize, +) -> Result<()> { + for vf in frames { + let pts = vf.pts.unwrap_or(0); + let pts_tick = file.pts_to_tick(track_idx, pts); + let frame = Arc::new(to_craft_frame(vf, presentation, pts_tick)?); + cache.push(CachedFrame { pts, draft, frame }); + } + if cache.len() > MAX_CACHED_FRAMES { + let excess = cache.len() - MAX_CACHED_FRAMES; + cache.drain(..excess); + } + Ok(()) +} + +#[cfg(test)] +mod rgb8_tests; + +#[cfg(test)] +mod wide_rgb_tests; + +fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: Tick) -> Result { + let FramePresentation { container_color, par: default_par, rotation, aperture } = presentation; + let (mut width, mut height) = (vf.width(), vf.height()); + let subsampling = vf.subsampling(); + let family = vf.family(); + let tags = vf.color; + let par = match vf.sar.filter(|&(n, d)| n > 0 && d > 0) { + Some((n, d)) if rotation % 2 == 1 => (d, n), + Some(sar) => sar, + None => default_par, + }; + let mut color = resolve_color(tags, container_color); + let bit_depth = vf.bit_depth(); + let (planes, alpha) = vf.into_planes(); + + let data = match family { + ColorFamily::Rgb if color.range == Range::Full && planes.iter().chain(alpha.iter()).all(|p| p.bit_depth() == 8) => { + let luma = aperture.and_then(|clap| clean_aperture_region(clap, (width, height))); + if let Some(r) = luma { + (width, height) = (r.w as u32, r.h as u32); + } + let bytes = (width as usize) + .checked_mul(height as usize) + .and_then(|n| n.checked_mul(4)) + .filter(|&n| n <= craft_frame::DEFAULT_MAX_FRAME_BYTES) + .ok_or_else(|| MediaError::Decode("RGB picture exceeds the frame buffer limit".into()))?; + let [r, g, b]: [Plane; 3] = planes.try_into().map_err(|_| MediaError::Decode("expected three RGB planes".into()))?; + let r = plane_u8(r, luma)?; + let g = plane_u8(g, luma)?; + let b = plane_u8(b, luma)?; + let alpha = alpha.map(|a| plane_u8(a, luma)).transpose()?.into_iter().flatten().chain(std::iter::repeat(255)); + let mut rgba = Vec::new(); + rgba.try_reserve_exact(bytes).map_err(|_| MediaError::Decode("could not allocate the RGB picture".into()))?; + for (((r, g), b), a) in r.into_iter().zip(g).zip(b).zip(alpha) { + rgba.extend_from_slice(&[r, g, b, a]); + } + PixelData::Rgba8(Arc::new(rgba)) + } + ColorFamily::Rgb if color.range == Range::Full && (9..=16).contains(&bit_depth) && planes.iter().all(|p| p.bit_depth() == bit_depth) => { + let luma = aperture.and_then(|clap| clean_aperture_region(clap, (width, height))); + if let Some(r) = luma { + (width, height) = (r.w as u32, r.h as u32); + } + let samples = (width as usize) + .checked_mul(height as usize) + .and_then(|n| n.checked_mul(4)) + .filter(|&n| n <= craft_frame::DEFAULT_MAX_FRAME_BYTES / size_of::()) + .ok_or_else(|| MediaError::Decode("RGB picture exceeds the frame buffer limit".into()))?; + let [r, g, b]: [Plane; 3] = planes.try_into().map_err(|_| MediaError::Decode("expected three RGB planes".into()))?; + let r = plane_u16(r, luma)?; + let g = plane_u16(g, luma)?; + let b = plane_u16(b, luma)?; + let alpha_max = alpha.as_ref().map_or(1, |a| ((1u32 << a.bit_depth()) - 1) as u16); + let alpha = alpha.map(|a| plane_u16(a, luma)).transpose()?.into_iter().flatten().chain(std::iter::repeat(alpha_max)); + // One transfer lookup per code avoids evaluating the curve per pixel and keeps + // every decoded code distinct, including at 16 bits. + let max_code = (1usize << bit_depth) - 1; + let mut transfer = Vec::new(); + transfer.try_reserve_exact(max_code + 1).map_err(|_| MediaError::Decode("could not allocate the RGB transfer table".into()))?; + transfer.extend((0..=max_code).map(|code| craft_color::to_linear(code as f32 / max_code as f32, color.transfer))); + let linear = |value: u16| transfer[usize::from(value).min(max_code)]; + let mut rgba = Vec::new(); + rgba.try_reserve_exact(samples).map_err(|_| MediaError::Decode("could not allocate the RGB picture".into()))?; + for (((r, g), b), a) in r.into_iter().zip(g).zip(b).zip(alpha) { + let a = (f32::from(a) / f32::from(alpha_max)).min(1.0); + rgba.extend_from_slice(&[linear(r) * a, linear(g) * a, linear(b) * a, a]); + } + color.transfer = Transfer::Linear; + PixelData::RgbaF32(Arc::new(rgba)) + } + 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())); + }; + let (luma, chroma_region) = aperture + .and_then(|clap| clean_aperture_region(clap, (width, height))) + .and_then(|r| aligned_aperture(r, width as usize, height as usize, chroma)) + .unzip(); + if let Some(r) = luma { + (width, height) = (r.w as u32, r.h as u32); + } + if bit_depth <= 8 { + let y = Arc::new(plane_u8(y, luma)?); + let cb = Arc::new(plane_u8(cb, chroma_region)?); + let cr = Arc::new(plane_u8(cr, chroma_region)?); + let a = alpha.map(|p| plane_u8(p, luma)).transpose()?.map(Arc::new); + PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha: a } + } else { + let y = Arc::new(plane_u16(y, luma)?); + let cb = Arc::new(plane_u16(cb, chroma_region)?); + let cr = Arc::new(plane_u16(cr, chroma_region)?); + let a = alpha.map(|p| plane_u16(p, luma)).transpose()?.map(Arc::new); + PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: u32::from(bit_depth), alpha: a } + } + } + ColorFamily::Gray => { + let y = planes.into_iter().next().ok_or_else(|| MediaError::Decode("missing grayscale plane".into()))?; + let luma = aperture.and_then(|clap| clean_aperture_region(clap, (width, height))); + if let Some(r) = luma { + (width, height) = (r.w as u32, r.h as u32); + } + // Chroma is constant, so subsampling does not change the visible grayscale picture. + let chroma = Chroma::C420; + let chroma_len = (width as usize) + .div_ceil(2) + .checked_mul((height as usize).div_ceil(2)) + .ok_or_else(|| MediaError::Decode("monochrome chroma size overflows".into()))?; + match bit_depth { + 8 => { + let y = Arc::new(plane_u8(y, luma)?); + let alpha = alpha.map(|p| plane_u8(p, luma)).transpose()?.map(Arc::new); + let neutral = Arc::new(vec![128; chroma_len]); + PixelData::Yuv8 { planes: [y, neutral.clone(), neutral], chroma, alpha } + } + 9..=16 => { + let y = Arc::new(plane_u16(y, luma)?); + let alpha = alpha.map(|p| plane_u16(p, luma)).transpose()?.map(Arc::new); + let neutral = Arc::new(vec![1u16 << (bit_depth - 1); chroma_len]); + PixelData::Yuv16 { planes: [y, neutral.clone(), neutral], chroma, bits: u32::from(bit_depth), alpha } + } + _ => return Err(MediaError::Unsupported("monochrome bit depth below 8".into())), + } + } + ColorFamily::Rgb => return Err(MediaError::Unsupported("non-YCbCr pixel format".into())), + }; + + let frame = VideoFrame { width, height, data, color, par, pts }; + Ok(rotate_frame(frame, rotation)) +} + +/// Move the origin onto the chroma grid before clipping, keeping the size when it fits. +fn aligned_aperture(region: Region, width: usize, height: usize, chroma: Chroma) -> Option<(Region, Region)> { + let (sx, sy) = chroma.shifts(); + let (xs, ys) = (1usize << sx, 1usize << sy); + let x = region.x.min(width) & !(xs - 1); + let y = region.y.min(height) & !(ys - 1); + let luma = Region { x, y, ..region }.clip(width, height); + if luma.is_empty() || luma.is_full(width, height) { + return None; + } + let chroma = Region { x: luma.x / xs, y: luma.y / ys, w: luma.w.div_ceil(xs), h: luma.h.div_ceil(ys) }; + Some((luma, chroma)) +} + +fn rotate_plane(src: &[T], w: usize, h: usize, turns: u8) -> Vec { + if w == 0 || h == 0 || src.len() < w * h { + return src.to_vec(); + } + let mut dst = vec![T::default(); w * h]; + match turns % 4 { + 1 => { + for y in 0..h { + for x in 0..w { + dst[x * h + (h - 1 - y)] = src[y * w + x]; + } + } + } + 2 => { + for y in 0..h { + for x in 0..w { + dst[(h - 1 - y) * w + (w - 1 - x)] = src[y * w + x]; + } + } + } + 3 => { + for y in 0..h { + for x in 0..w { + dst[(w - 1 - x) * h + y] = src[y * w + x]; + } + } + } + _ => return src.to_vec(), + } + dst +} + +fn upsample_horiz(src: &[T], cw: usize, ch: usize, full_w: usize) -> Vec { + let mut out = Vec::with_capacity(full_w * ch); + for y in 0..ch { + let row = &src[y * cw..(y + 1) * cw]; + for x in 0..full_w { + out.push(row[(x / 2).min(cw.saturating_sub(1))]); + } + } + out +} + +fn rotate_frame(mut frame: VideoFrame, turns: u8) -> VideoFrame { + let turns = turns % 4; + if turns == 0 { + return frame; + } + let (w, h) = (frame.width as usize, frame.height as usize); + let (nw, nh) = if turns % 2 == 1 { (frame.height, frame.width) } else { (frame.width, frame.height) }; + let data = match frame.data { + PixelData::Rgba8(pixels) => { + let rotated = rotate_plane(pixels.as_chunks::<4>().0, w, h, turns); + PixelData::Rgba8(Arc::new(rotated.into_flattened())) + } + PixelData::RgbaF32(pixels) => { + let rotated = rotate_plane(pixels.as_chunks::<4>().0, w, h, turns); + PixelData::RgbaF32(Arc::new(rotated.into_flattened())) + } + PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha } => { + let (cw, ch, out_chroma) = match chroma { + Chroma::C420 => (w.div_ceil(2), h.div_ceil(2), Chroma::C420), + Chroma::C422 if turns % 2 == 1 => (w, h, Chroma::C444), + Chroma::C422 => (w.div_ceil(2), h, Chroma::C422), + Chroma::C444 => (w, h, Chroma::C444), + }; + let (cb_r, cr_r) = if chroma == Chroma::C422 && turns % 2 == 1 { + let src_cw = w.div_ceil(2); + (rotate_plane(&upsample_horiz(&cb, src_cw, h, w), w, h, turns), rotate_plane(&upsample_horiz(&cr, src_cw, h, w), w, h, turns)) + } else { + (rotate_plane(&cb, cw, ch, turns), rotate_plane(&cr, cw, ch, turns)) + }; + PixelData::Yuv8 { + planes: [Arc::new(rotate_plane(&y, w, h, turns)), Arc::new(cb_r), Arc::new(cr_r)], + chroma: out_chroma, + alpha: alpha.map(|a| Arc::new(rotate_plane(&a, w, h, turns))), + } + } + PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits, alpha } => { + let (cw, ch, out_chroma) = match chroma { + Chroma::C420 => (w.div_ceil(2), h.div_ceil(2), Chroma::C420), + Chroma::C422 if turns % 2 == 1 => (w, h, Chroma::C444), + Chroma::C422 => (w.div_ceil(2), h, Chroma::C422), + Chroma::C444 => (w, h, Chroma::C444), + }; + let (cb_r, cr_r) = if chroma == Chroma::C422 && turns % 2 == 1 { + let src_cw = w.div_ceil(2); + (rotate_plane(&upsample_horiz(&cb, src_cw, h, w), w, h, turns), rotate_plane(&upsample_horiz(&cr, src_cw, h, w), w, h, turns)) + } else { + (rotate_plane(&cb, cw, ch, turns), rotate_plane(&cr, cw, ch, turns)) + }; + PixelData::Yuv16 { + planes: [Arc::new(rotate_plane(&y, w, h, turns)), Arc::new(cb_r), Arc::new(cr_r)], + chroma: out_chroma, + bits, + alpha: alpha.map(|a| Arc::new(rotate_plane(&a, w, h, turns))), + } + } + }; + frame.width = nw; + frame.height = nh; + frame.data = data; + frame +} + +fn plane_region(aperture: Option, width: usize, height: usize) -> Result { + let r = aperture.unwrap_or(Region { x: 0, y: 0, w: width, h: height }); + if r.clip(width, height) != r { + return Err(MediaError::Decode("clean aperture exceeds a decoded plane".into())); + } + Ok(r) +} + +fn plane_u8(p: Plane, aperture: Option) -> Result> { + let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); + let r = plane_region(aperture, w, h)?; + match p.into_samples() { + Samples::U8(mut v) => { + if stride == w && r.is_full(w, h) { + v.truncate(w * h); + return Ok(v); + } + let mut out = Vec::with_capacity(r.w * r.h); + for y in r.y..r.y + r.h { + let row = y * stride + r.x; + out.extend_from_slice(&v[row..row + r.w]); + } + Ok(out) + } + Samples::U16(v) => { + let mut out = Vec::with_capacity(r.w * r.h); + for y in r.y..r.y + r.h { + let row = y * stride + r.x; + out.extend(v[row..row + r.w].iter().map(|&s| s.min(255) as u8)); + } + Ok(out) + } + } +} + +fn plane_u16(p: Plane, aperture: Option) -> Result> { + let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); + let r = plane_region(aperture, w, h)?; + match p.into_samples() { + Samples::U16(mut v) => { + if stride == w && r.is_full(w, h) { + v.truncate(w * h); + return Ok(v); + } + let mut out = Vec::with_capacity(r.w * r.h); + for y in r.y..r.y + r.h { + let row = y * stride + r.x; + out.extend_from_slice(&v[row..row + r.w]); + } + Ok(out) + } + Samples::U8(v) => { + let mut out = Vec::with_capacity(r.w * r.h); + for y in r.y..r.y + r.h { + let row = y * stride + r.x; + out.extend(v[row..row + r.w].iter().map(|&s| u16::from(s))); + } + Ok(out) + } + } +} + +fn resolve_color(vui: ColorTags, container: Option) -> 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 } +} + +/// Resolve the clip's initial probe colour from the first presented ProRes frame, without +/// changing decoder state or a project's saved interpretation. Later frames still resolve their +/// own decoder fields against the descriptor; this is not a variable-profile clip probe. +fn mxf_prores_color(file: &MxfFile, source: &dyn ByteSource, track_idx: usize) -> Option<(ColorInfo, ColorInfo)> { + use effectcraft_project::ColorSpace; + + let track = file.tracks.get(track_idx)?; + if !matches!(track.codec, mxf::Codec::ProRes { .. }) { + return None; + } + let descriptor = color_from_mxf(track.picture.as_ref()?)?; + let (start, len) = mxf_picture_window(track); + if len == 0 { + return None; + } + let index = track.sample_at(start)?; + let sample = track.samples.get(index)?; + if !(28..=MAX_MXF_PRORES_COLOR_SAMPLE_BYTES).contains(&sample.size) { + return None; + } + let packet = file.read_sample(source, track_idx, index).ok()?; + let tags = craft_video::prores::probe(&packet).ok()?.color; + let tags = ColorTags { primaries: tags.primaries, transfer: tags.transfer, matrix: tags.matrix, full_range: false }; + let color = resolve_color(tags, Some(descriptor)); + // Only opt in when the managed compositor can represent the resolved primaries/transfer. + // The general profile mapper also approximates some other pairs for existing routes. + match crate::probe::profile_of_craft(&color) { + Some(ColorSpace::Rec2100Pq | ColorSpace::Rec2100Hlg) => Some((color, descriptor)), + Some(ColorSpace::Rec709) if color.primaries == Primaries::Bt709 => Some((color, descriptor)), + _ => None, + } +} + +fn color_from_mxf(picture: &mxf::PictureInfo) -> Option { + let (primaries, transfer, matrix) = picture.color_codes(); + if (primaries, transfer, matrix) == (None, None, None) { + return None; + } + // Use the existing H.273 defaults without changing MXF quantisation range policy. + Some(resolve_color(ColorTags { primaries: primaries.unwrap_or(2), transfer: transfer.unwrap_or(2), matrix: matrix.unwrap_or(2), full_range: false }, None)) +} + +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 color_from_matroska(c: &matroska::Color) -> ColorInfo { + ColorInfo { + matrix: c.matrix_coefficients.and_then(|m| u8::try_from(m).ok()).and_then(Matrix::from_code).unwrap_or(Matrix::Bt709), + transfer: c.transfer_characteristics.and_then(|t| u8::try_from(t).ok()).and_then(Transfer::from_code).unwrap_or(Transfer::Bt709), + primaries: c.primaries.and_then(|p| u8::try_from(p).ok()).and_then(primaries_from_code).unwrap_or(Primaries::Bt709), + range: if c.full_range() { Range::Full } else { Range::Limited }, + } +} + +fn primaries_from_code(c: u8) -> Option { + 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 matroska_par(video: Option<&matroska::VideoInfo>, width: u32, height: u32) -> (u32, u32) { + let Some(v) = video else { return (1, 1) }; + // RFC 9559 §5.1.4.1.28.14 defines 0 as pixels and 3 as a display ratio. + // Use the coded raster because this reader presents frames without Matroska cropping. + if matches!(v.display_unit, 0 | 3) + && let (Some(dw), Some(dh)) = (v.display_width, v.display_height) + && dw > 0 + && dh > 0 + && width > 0 + && height > 0 + && (dw != width || dh != height) + { + return dw.checked_mul(height).zip(dh.checked_mul(width)).unwrap_or((1, 1)); + } + (1, 1) +} + +fn matroska_duration(file: &MkvFile, track: &matroska::Track) -> Tick { + if let Some(d) = file.info.duration + && d.is_finite() + && d > 0.0 + { + let ns = (d * file.info.timestamp_scale as f64).round() as i64; + return Tick::from_units(ns, 1_000_000_000); + } + // Blocks are indexed in coding order, so a future reference can precede a B-picture. + let presentation_end = track.samples.iter().map(|s| s.pts.saturating_add(i64::try_from(s.duration).unwrap_or(0))).max().unwrap_or(0); + Tick::from_units(track.ticks_to_ns(presentation_end), 1_000_000_000) +} + +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 tick_to_matroska_units(t: Tick, timebase: (u64, u64)) -> i64 { + let denom = i128::from(craft_time::TICKS_PER_SECOND) * i128::from(timebase.0.max(1)); + let v = (i128::from(t.0) * i128::from(timebase.1)) / denom; + i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX }) +} + +fn tick_to_rational_units(t: Tick, num: i64, den: i64) -> i64 { + let denom = i128::from(craft_time::TICKS_PER_SECOND) * i128::from(den.max(1)); + let v = (i128::from(t.0) * i128::from(num.max(1))) / denom; + i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX }) +} + +fn snap_common_fps(fps: f64) -> Option { + if !fps.is_finite() || fps <= 0.0 { + return None; + } + 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) +} + +fn estimate_isobmff_frame_rate(track: &isobmff::Track) -> FrameRate { + let ts = i128::from(track.timescale); + if ts <= 0 || track.samples.is_empty() { + return FrameRate::FPS_30; + } + let mut durs: Vec = 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); + snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(track.timescale), i64::from(median))) +} + +fn estimate_matroska_frame_rate(track: &matroska::Track) -> FrameRate { + if let Some(ns) = track.default_duration_ns + && ns > 0 + { + let fps = 1_000_000_000.0 / ns as f64; + return snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(1_000_000_000, i64::try_from(ns).unwrap_or(i64::MAX))); + } + if track.samples.len() >= 2 { + let mut pts: Vec = track.samples.iter().map(|s| s.pts).collect(); + pts.sort_unstable(); + let mut deltas: Vec = pts.windows(2).map(|w| w[1] - w[0]).filter(|&d| d > 0).collect(); + if !deltas.is_empty() { + deltas.sort_unstable(); + let median_ticks = deltas[deltas.len() / 2]; + let median_ns = track.ticks_to_ns(median_ticks); + if median_ns > 0 { + let fps = 1_000_000_000.0 / median_ns as f64; + return snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(1_000_000_000, median_ns)); + } + } + } + FrameRate::FPS_30 +} + +#[cfg(all(test, any(unix, windows)))] +mod flac_tracks_tests; +#[cfg(all(test, any(unix, windows)))] +mod raw_avi_tests; + +#[cfg(test)] +mod tests { + use super::*; + + // One 20 ms mono packet from craft-audio's generated tone.opus test fixture. + // Re-mux it into ordinary small audio-only files without an external encoder. + const OPUS_TONE: &[u8] = b"\x78\x82\x01\xB7\x6C\x7E\x40\xE6\x00\x00\x0A\xBE\x9A\xA7\xBE\xFF\xB6\x85\xD7\x0A\x71\xE0\xDD\ + \x6B\xA0\xE3\xC6\xC5\xC3\x32\xC6\x64\x1E\x6E\x63\x52\x3A\x45\x0C\x8A\x53\x8F\x44\x18\xB0\x8C\ + \x64\xAB\xEC\x98\x96\x79\x6C\x54\x53\x30\x55\x4E\x82\xE4\x16\xCA\x59\x49\xD8\xC7\x09\x5D\x59"; + + struct OpusPayloadReads { + bytes: Vec, + offsets: Vec, + packets: Mutex>, + fail_once_at: Mutex>, + } + + impl ByteSource for OpusPayloadReads { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + if buf.len() == OPUS_TONE.len() + && let Ok(index) = self.offsets.binary_search(&offset) + { + self.packets.lock().unwrap().push(index); + let mut failure = self.fail_once_at.lock().unwrap(); + if *failure == Some(index) { + *failure = None; + return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "test transient packet read")); + } + } + self.bytes.as_slice().read_at(offset, buf) + } + } + + const OPUS_RATE: u32 = 48_000; + const OPUS_FRAME: usize = 960; + const OPUS_PACKETS: usize = 192; + const OPUS_GAP_AT: usize = 96; + const OPUS_GAP: usize = 9_600; + const OPUS_LEAD: usize = 4_800; + const OPUS_CODEC_DELAY_NS: i64 = 6_500_000; + const OPUS_CODEC_DELAY_FRAMES: i64 = 312; + + struct OpusFixture { + bytes: Vec, + file: ContainerFile, + offsets: Vec, + params: CodecParams, + delay: u64, + } + + fn opus_test_config() -> isobmff::OpusConfig { + isobmff::OpusConfig { output_channels: 1, pre_skip: OPUS_CODEC_DELAY_FRAMES as u16, input_sample_rate: OPUS_RATE, ..Default::default() } + } + + fn generated_opus_matroska(lead: usize, laced: bool) -> OpusFixture { + use std::io::Cursor; + + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_OPUS"); + track.audio = Some((f64::from(OPUS_RATE), 1, None)); + track.codec_private = opus_test_config().opus_head(); + track.codec_delay_ns = OPUS_CODEC_DELAY_NS as u64; + track.seek_pre_roll_ns = 80_000_000; + track.default_duration_ns = Some(20_000_000); + let options = if laced { + matroska::MuxOptions { lacing: matroska::LacingMode::FixedOrEbml, max_lace_frames: 6, cluster_duration_ns: 10_000_000_000, ..Default::default() } + } else { + matroska::MuxOptions::default() + }; + let mut mux = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], options).unwrap(); + let lead_ns = lead as i64 * 1_000_000_000 / i64::from(OPUS_RATE); + for idx in 0..OPUS_PACKETS { + let gap_ns = if idx >= OPUS_GAP_AT { 200_000_000 } else { 0 }; + let jitter = if laced || idx % 2 == 0 { 0 } else { 1_000_000 }; + mux.write_frame(0, idx as i64 * 20_000_000 + lead_ns + gap_ns + jitter - OPUS_CODEC_DELAY_NS, true, OPUS_TONE, None).unwrap(); + } + let bytes = mux.finish().unwrap().into_inner(); + let mut file = matroska::open(bytes.as_slice()).unwrap(); + let track = &mut file.tracks[0]; + if laced { + // The writer needs a duration to group real laces. Exercise the + // durationless index representation by clearing it after demuxing. + assert_eq!(track.samples[AUDIO_LOOKAHEAD].lace, 2); + assert_eq!(track.samples[145].lace, 1); + let mut anchor = 0; + for packet in &mut track.samples { + if packet.lace == 0 { + anchor = packet.pts; + } else { + packet.pts = anchor; + } + packet.duration = 0; + } + } + let offsets = track.samples.iter().map(|s| s.offset).collect::>(); + let params = track.codec_params(); + OpusFixture { bytes, file: ContainerFile::Matroska(Box::new(file)), offsets, params, delay: OPUS_CODEC_DELAY_NS as u64 } + } + + #[test] + fn apv_cache_counts_both_frames_without_allocating_8k_planes() { + let yuva_8k = 7_680usize * 4_320 * 4 * 2; + assert!(apv_cache_fits_pair(yuva_8k, MAX_SHARED_APV_CACHE_BYTES - yuva_8k)); + assert!(!apv_cache_fits_pair(yuva_8k, yuva_8k)); + assert!(!apv_cache_fits_pair(usize::MAX, 1)); + } + + #[test] + fn apv_cache_releases_entry_lock_and_does_not_cache_errors_or_duplicate_a_hit() { + let cache = ApvFrameCache::default(); + let failed = cache.get_or_decode(1, || { + assert!(cache.entries.try_lock().is_ok()); + assert!(matches!(cache.decode_gate.try_lock(), Err(std::sync::TryLockError::WouldBlock))); + Err(MediaError::Cancelled) + }); + assert!(matches!(failed, Err(MediaError::Cancelled))); + let frame = cache + .get_or_decode(1, || { + assert!(cache.entries.try_lock().is_ok()); + Ok(VideoFrame { + width: 1, + height: 1, + data: PixelData::Yuv16 { + planes: [Arc::new(vec![200]), Arc::new(vec![512]), Arc::new(vec![512])], + chroma: Chroma::C444, + bits: 10, + alpha: None, + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }) + }) + .unwrap(); + let hit = cache.get_or_decode(1, || panic!("a cache hit must not decode again")).unwrap(); + assert!(Arc::ptr_eq(&frame, &hit)); + } + + struct ApvFixture { + bytes: Arc<[u8]>, + y: Vec>, + alpha: Vec>>, + } + + fn generated_apv_mp4(brand: isobmff::Brand, coded_alpha: bool, incomplete_config: bool, coarse_timebase: bool, rec709: bool) -> ApvFixture { + use std::io::Cursor; + + use craft_video::apv::{Encoder, EncoderConfig, Frame, Profile, decode_frame}; + use isobmff::{ApvConfig, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + let profile = if coded_alpha { Profile::P4444_10 } else { Profile::P422_10 }; + let mut config = EncoderConfig::new(profile, 16, 16); + config.qp = Some(16); + // The APV header and apvC both disagree with the authoritative explicit nclx. + config.color_description_present = true; + config.color.primaries = 9; + config.color.transfer = 16; + config.color.matrix = 9; + config.color.full_range = true; + let mut encoder = Encoder::with_config(config).unwrap(); + let mut record = encoder.decoder_config_record(); + if incomplete_config { + // The legacy decoder takes its dimensions from the AU rather than this record. + record[8..12].fill(0); + } + let mut entry = SampleEntry::apv(ApvConfig::from_record(record).unwrap(), 16, 16); + entry.video.as_mut().unwrap().color = Some(if rec709 { + isobmff::ColorInfo::Nclx { primaries: 1, transfer: 1, matrix: 1, full_range: false } + } else { + isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: true } + }); + let mut writer = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(brand)).unwrap(); + let (timescale, duration) = if coarse_timebase { (25, 1) } else { (25_000, 1_000) }; + let idx = writer.add_track(TrackConfig::new(entry, timescale)).unwrap(); + + let mut expected_y = Vec::new(); + let mut expected_alpha = Vec::new(); + for (i, y) in [160, 720].into_iter().enumerate() { + let mut frame = Frame::new(16, 16, profile.default_chroma(), 10, coded_alpha); + frame.y.fill(y); + if let Some(alpha) = frame.alpha.as_mut() { + alpha.fill(if i == 0 { 256 } else { 768 }); + } + let mut au = encoder.encode(&frame).unwrap(); + let mut alpha = if coded_alpha { decode_frame(&au).unwrap().alpha } else { None }; + if i == 1 && !coded_alpha { + let mono_profile = Profile::P400_10; + let mut mono_encoder = Encoder::new(mono_profile, 16, 16).unwrap(); + let mut mono = Frame::new(16, 16, mono_profile.default_chroma(), 10, false); + mono.y.fill(480); + let alpha_au = mono_encoder.encode(&mono).unwrap(); + alpha = Some(decode_frame(&alpha_au).unwrap().y); + // The first generated monochrome PBU becomes the matching auxiliary alpha. + let len = u32::from_be_bytes(alpha_au[4..8].try_into().unwrap()); + au.extend_from_slice(&len.to_be_bytes()); + au.push(27); + au.extend_from_slice(&alpha_au[9..8 + len as usize]); + } + expected_y.push(decode_frame(&au).unwrap().y); + expected_alpha.push(alpha); + writer.write_sample(idx, WriteSample { data: &au, duration, composition_offset: 0, is_sync: true }).unwrap(); + } + ApvFixture { bytes: writer.finish().unwrap().into_inner().into(), y: expected_y, alpha: expected_alpha } + } + + fn assert_apv_seek_parity(shared: &crate::stream::MediaSource, film: &crate::stream::MediaSource, step: i64, y: &[Vec], alpha: &[Option>]) { + use crate::stream::DecodedFrame; + + let boundary = step - craft_time::TICKS_PER_SECOND / 50_000; + for (at, i) in [(step, 1), (0, 0), (boundary - 1, 0), (boundary, 1), (step - 1, 1), (0, 0)] { + let time = effectcraft_time::Tick(at); + let DecodedFrame::Craft(new) = shared.video_frame(time, 1.0).unwrap() else { panic!("shared frame") }; + let DecodedFrame::Film(old) = film.video_frame(time, 1.0).unwrap() else { panic!("legacy frame") }; + assert_eq!(new.color, ColorInfo::REC709); + assert_eq!(old.color, filmcraft_color::ColorInfo::REC709); + // Film carries the presentation position in its cache key, not its APV pixel payload. + assert_eq!(old.pts.0, 0); + assert_eq!(new.pts.0, old.pts.0); + let PixelData::Yuv16 { planes: new_planes, bits, alpha: new_alpha, .. } = &new.data else { panic!("APV 10-bit YUV frame") }; + let filmcraft_frame::PixelData::Yuv16 { planes: old_planes, bits: old_bits, alpha: old_alpha, .. } = &old.data else { + panic!("legacy APV 10-bit YUV frame") + }; + assert_eq!(*bits, 10); + assert_eq!(bits, old_bits); + assert_eq!(new_planes[0].as_ref(), &y[i]); + for (new, old) in new_planes.iter().zip(old_planes) { + assert_eq!(new.as_ref(), old.as_ref()); + } + assert_eq!(new_alpha.as_deref(), alpha[i].as_ref()); + assert_eq!(new_alpha.as_deref(), old_alpha.as_deref()); + } + } + + /// Two distinct self-generated pictures of `colour` (`W4 H2`), 16-bit little-endian above 8 bits. + fn generated_y4m(colour: &str, bits: u8, planes: usize, chroma_len: usize) -> Arc<[u8]> { + let mut out = format!("YUV4MPEG2 W4 H2 F25:1 Ip A2:1 C{colour} XCOLORRANGE=FULL\n").into_bytes(); + for frame in 0..2u16 { + out.extend_from_slice(b"FRAME\n"); + for plane in 0..planes { + let len = if plane == 0 || plane == 3 { 8 } else { chroma_len }; + for i in 0..len as u16 { + let v = (frame * 97 + plane as u16 * 31 + i * 13) % (1 << bits.min(10)); + if bits > 8 { + out.extend_from_slice(&v.to_le_bytes()); + } else { + out.push(v as u8); + } + } + } + } + out.into() + } + + #[test] + fn y4m_import_uses_the_shared_source_with_film_parity() { + use crate::stream::{DecodedFrame, MediaSource as Opened}; + + fn planes(frame: DecodedFrame) -> (Vec>, Option>, u32) { + let wide = |p: &[u8]| p.iter().map(|&v| u16::from(v)).collect::>(); + match frame { + DecodedFrame::Craft(f) => match &f.data { + PixelData::Yuv8 { planes, alpha, .. } => (planes.iter().map(|p| wide(p)).collect(), alpha.as_ref().map(|a| wide(a)), 8u32), + PixelData::Yuv16 { planes, alpha, bits, .. } => (planes.iter().map(|p| p.to_vec()).collect(), alpha.as_ref().map(|a| a.to_vec()), *bits), + _ => panic!("shared Y4M frame is planar YUV"), + }, + DecodedFrame::Film(f) => match &f.data { + filmcraft_frame::PixelData::Yuv8 { planes, alpha, .. } => (planes.iter().map(|p| wide(p)).collect(), alpha.as_ref().map(|a| wide(a)), 8u32), + filmcraft_frame::PixelData::Yuv16 { planes, alpha, bits, .. } => { + (planes.iter().map(|p| p.to_vec()).collect(), alpha.as_ref().map(|a| a.to_vec()), *bits) + } + _ => panic!("legacy Y4M frame is planar YUV"), + }, + } + } + + let step = craft_time::TICKS_PER_SECOND / 25; + for (colour, bits, plane_count, chroma_len) in + [("420jpeg", 8, 3, 2), ("444alpha", 8, 4, 8), ("mono", 8, 1, 0), ("420p10", 10, 3, 2), ("422p12", 12, 3, 4)] + { + let bytes = generated_y4m(colour, bits, plane_count, chroma_len); + let path = "generated.y4m"; + let shared = crate::stream::open_bytes(path, bytes.clone()).unwrap(); + assert!(matches!(shared, Opened::Craft(_)), "{colour}: Y4M must use the shared source"); + let direct = filmcraft_codecs::open_bytes(path, bytes.clone()).unwrap(); + let old = crate::probe::footage_from_info(path, direct.info()); + let film = Opened::Film(direct); + let footage = crate::probe_bytes(path, bytes.clone()).unwrap(); + assert_eq!((footage.width, footage.height), (4, 2), "{colour}"); + assert_eq!(footage.frame_rate, old.frame_rate, "{colour}"); + assert_eq!(footage.duration, old.duration, "{colour}"); + assert_eq!(footage.duration.0, step * 2, "{colour}"); + assert_eq!(footage.pixel_aspect, old.pixel_aspect, "{colour}"); + assert_eq!(footage.alpha, old.alpha, "{colour}"); + assert_eq!(footage.color_profile, old.color_profile, "{colour}"); + assert_eq!(footage.codec, old.codec, "{colour}"); + let mut seen = Vec::new(); + for at in [step, 0, step - 1, step, 0] { + let time = effectcraft_time::Tick(at); + let new = planes(shared.video_frame(time, 1.0).unwrap()); + let legacy = planes(film.video_frame(time, 1.0).unwrap()); + assert_eq!(new, legacy, "{colour} at {at}"); + assert_eq!(new.2, u32::from(bits), "{colour}"); + assert_eq!(new.1.is_some(), colour == "444alpha", "{colour}"); + seen.push(new.0); + } + assert_ne!(seen[0], seen[1], "{colour}: the two pictures differ"); + } + } + + #[test] + fn simple_apv_mp4_import_preserves_film_color_alpha_and_backward_seek() { + use crate::stream::MediaSource as Opened; + use effectcraft_project::{AlphaMode, ColorSpace}; + + let step = craft_time::TICKS_PER_SECOND / 25; + for coded_alpha in [false, true] { + let ApvFixture { bytes, y, alpha } = generated_apv_mp4(isobmff::Brand::Mp4, coded_alpha, false, false, true); + let path = "paired-apv.mp4"; + assert_ne!(y[0], y[1], "regression requires visibly different frames"); + assert_eq!(alpha[0].is_some(), coded_alpha); + assert!(alpha[1].is_some(), "late auxiliary/coded alpha fixture must be live"); + let direct_film = filmcraft_codecs::open_bytes(path, bytes.clone()).unwrap(); + let old_footage = crate::probe::footage_from_info(path, direct_film.info()); + let shared = crate::stream::open_bytes(path, bytes.clone()).unwrap(); + let Opened::Craft(source) = &shared else { panic!("admitted APV must use shared decoding") }; + let footage = crate::probe_bytes(path, bytes).unwrap(); + assert_eq!((footage.width, footage.height), (16, 16)); + assert_eq!(footage.frame_rate, old_footage.frame_rate); + assert_eq!(footage.native_rate.unwrap_or(footage.frame_rate), old_footage.native_rate.unwrap_or(old_footage.frame_rate)); + assert_eq!(footage.duration, old_footage.duration); + assert_eq!(footage.duration.0, step * 2); + assert_eq!(footage.pixel_aspect, old_footage.pixel_aspect); + assert_eq!(footage.file_timecode, None); + assert_eq!(footage.file_timecode, old_footage.file_timecode); + assert_eq!(footage.alpha, if coded_alpha { AlphaMode::Straight } else { AlphaMode::Ignore }); + assert_eq!(footage.alpha, old_footage.alpha); + assert_eq!(footage.color_profile, Some(ColorSpace::Rec709)); + assert_eq!(footage.color_profile, old_footage.color_profile); + assert_eq!(footage.codec, old_footage.codec); + let shared_video = source.info().video.as_ref().unwrap(); + let film_video = direct_film.info().video.as_ref().unwrap(); + assert_eq!(shared_video.pixel_format, film_video.pixel_format); + assert_eq!(shared_video.bitrate, film_video.bitrate); + + let film = Opened::Film(direct_film); + assert_apv_seek_parity(&shared, &film, step, &y, &alpha); + } + } + + #[test] + fn apv_mov_incomplete_apvc_and_coarse_timebase_keep_the_playable_film_route() { + use crate::stream::MediaSource as Opened; + for (brand, incomplete, coarse) in [(isobmff::Brand::Mov, false, false), (isobmff::Brand::Mp4, true, false), (isobmff::Brand::Mp4, false, true)] { + let bytes = generated_apv_mp4(brand, false, incomplete, coarse, true).bytes; + let parsed = isobmff::open(bytes.as_ref()).unwrap(); + assert_eq!(parsed.is_quicktime, brand == isobmff::Brand::Mov); + // Byte routing, independent of the apparent extension. + let opened = crate::stream::open_bytes("unadmitted-apv.mp4", bytes).unwrap(); + assert!(matches!(opened, Opened::Film(_))); + assert_eq!(opened.video_frame(effectcraft_time::Tick::ZERO, 1.0).unwrap().width(), 16); + } + } + + #[test] + fn clean_pq_apv_mp4_keeps_the_playable_film_route() { + use crate::stream::MediaSource as Opened; + use effectcraft_project::ColorSpace; + + // Same fine-timebase isom encode as the admitted test, differing only in nclx. + let bytes = generated_apv_mp4(isobmff::Brand::Mp4, false, false, false, false).bytes; + let parsed = isobmff::open(bytes.as_ref()).unwrap(); + assert_eq!(parsed.major_brand.0, *b"isom"); + assert_eq!(parsed.tracks[0].timescale, 25_000); + assert!(matches!( + parsed.tracks[0].video().and_then(|video| video.color.as_ref()), + Some(isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: true }) + )); + let path = "pq-apv.mp4"; + let opened = crate::stream::open_bytes(path, bytes.clone()).unwrap(); + assert!(matches!(opened, Opened::Film(_))); + assert_eq!(opened.video_frame(effectcraft_time::Tick::ZERO, 1.0).unwrap().width(), 16); + assert_eq!(crate::probe_bytes(path, bytes).unwrap().color_profile, Some(ColorSpace::Rec2100Pq)); + } + + fn generated_opus_mp4(lead: usize) -> OpusFixture { + use std::io::Cursor; + + let entry = isobmff::SampleEntry { + format: isobmff::FourCc(*b"Opus"), + data_reference_index: 1, + codec: isobmff::CodecConfig::Opus(opus_test_config()), + video: None, + audio: Some(isobmff::AudioParams { channels: 1, sample_size: 16, sample_rate: f64::from(OPUS_RATE), ..Default::default() }), + bitrate: None, + }; + let mut mux = isobmff::Mp4Writer::new(Cursor::new(Vec::new()), isobmff::WriterOptions::new(isobmff::Brand::Mp4)).unwrap(); + mux.add_track(isobmff::TrackConfig::new(entry, OPUS_RATE)).unwrap(); + for idx in 0..OPUS_PACKETS { + let duration = (if idx + 1 == OPUS_GAP_AT { OPUS_FRAME + OPUS_GAP } else { OPUS_FRAME }) as u32; + mux.write_sample(0, isobmff::WriteSample { data: OPUS_TONE, duration, composition_offset: lead as i32, is_sync: true }).unwrap(); + } + let bytes = mux.finish().unwrap().into_inner(); + let file = isobmff::open(bytes.as_slice()).unwrap(); + let track = &file.tracks[0]; + let offsets = track.samples.iter().map(|s| s.offset).collect::>(); + let params = track.codec_params(); + OpusFixture { bytes, file: ContainerFile::Isobmff(file), offsets, params, delay: 0 } + } + + fn assert_opus_early_and_backward( + file: &ContainerFile, + source: &OpusPayloadReads, + params: &CodecParams, + delay: u64, + expected_positions: &[i64], + lead: usize, + ) -> Vec> { + let (mut tracks, _) = open_audio_tracks(file, source, [(0, OPUS_PACKETS, params.clone(), delay)]).unwrap(); + assert_eq!(*source.packets.lock().unwrap(), (0..AUDIO_LOOKAHEAD).collect::>()); + + let first = expected_positions[0]; + assert_eq!(tracks[0].decoder_parts().1.decoded_pos, first); + let (mut reference, _) = open_audio_tracks(file, &source.bytes, [(0, OPUS_PACKETS, params.clone(), delay)]).unwrap(); + reference[0].decoder_parts().1.audio_starts = AudioStarts::complete(expected_positions.to_vec()); + + let decode = |track: &mut AudioTrackEntry, src: &dyn ByteSource, start, frames| { + let (preroll, state) = track.decoder_parts(); + decode_audio_range(file, src, 0, OPUS_RATE, 1, preroll, state, start, frames).unwrap() + }; + // A first read before the initial packet can be ordinary leading silence + // or negative pre-roll. Neither should trigger the cold suffix scan. + let early_start = if lead == 0 { first - 128 } else { 0 }; + let silent_frames = (first - early_start) as usize; + let silent = decode(&mut tracks[0], source, early_start, silent_frames); + assert!(silent[0].iter().all(|&s| s == 0.0)); + assert_eq!(*source.packets.lock().unwrap(), (0..AUDIO_LOOKAHEAD).collect::>()); + assert_eq!(silent, decode(&mut reference[0], &source.bytes, early_start, silent_frames)); + let early_frames = silent_frames + 12 * OPUS_FRAME; + let early = decode(&mut tracks[0], source, early_start, early_frames); + assert_eq!(early, decode(&mut reference[0], &source.bytes, early_start, early_frames)); + assert!(early[0].iter().all(|s| s.is_finite())); + assert!(early[0].iter().any(|s| s.abs() > 1e-5), "real Opus decoding, not a silent fallback"); + { + let reads = source.packets.lock().unwrap(); + assert!(reads.iter().any(|&i| i >= AUDIO_LOOKAHEAD), "exercise the incremental frontier"); + assert!(reads.iter().all(|&i| i < 14) && reads.len() <= AUDIO_LOOKAHEAD + 14, "{reads:?}"); + } + + // A backward read after real decode must still use the exact seek index. + let backward_start = first + 2 * OPUS_FRAME as i64; + let backward = decode(&mut tracks[0], source, backward_start, OPUS_FRAME); + assert_eq!(backward, decode(&mut reference[0], &source.bytes, backward_start, OPUS_FRAME)); + let (_, state) = tracks[0].decoder_parts(); + assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); + assert!(state.audio_starts.pending.is_none()); + early + } + + fn assert_opus_first_cold_seek_and_retry( + file: &ContainerFile, + source: &OpusPayloadReads, + params: CodecParams, + delay: u64, + expected_positions: &[i64], + laced: bool, + start: i64, + ) { + let first = expected_positions[0]; + let decode = |track: &mut AudioTrackEntry, src: &dyn ByteSource, start, frames| { + let (preroll, state) = track.decoder_parts(); + decode_audio_range(file, src, 0, OPUS_RATE, 1, preroll, state, start, frames).unwrap() + }; + // A genuinely random first request is not the leading-silence shortcut. + let (mut fresh, _) = open_audio_tracks(file, source, [(0, OPUS_PACKETS, params.clone(), delay)]).unwrap(); + let (mut eager, _) = open_audio_tracks(file, &source.bytes, [(0, OPUS_PACKETS, params, delay)]).unwrap(); + eager[0].decoder_parts().1.audio_starts = AudioStarts::complete(expected_positions.to_vec()); + if laced { + assert_eq!(file.audio_seek_info(0, expected_positions, fresh[0].decoder_parts().0, start).0, 144); + } + let transient_packet = 64; + *source.fail_once_at.lock().unwrap() = Some(transient_packet); + { + let (preroll, state) = fresh[0].decoder_parts(); + let error = decode_audio_range(file, source, 0, OPUS_RATE, 1, preroll, state, start, 3 * OPUS_FRAME).unwrap_err(); + assert!(matches!(error, MediaError::Io(_))); + assert_eq!(state.audio_starts.pending.as_ref().unwrap().len, transient_packet); + assert_eq!((state.next_sample, state.decoded_pos), (0, first)); + } + let cold = decode(&mut fresh[0], source, start, 3 * OPUS_FRAME); + assert_eq!(cold, decode(&mut eager[0], &source.bytes, start, 3 * OPUS_FRAME)); + assert!(cold[0].iter().any(|s| s.abs() > 1e-5)); + let (_, state) = fresh[0].decoder_parts(); + assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); + assert!(state.audio_starts.pending.is_none()); + } + + #[test] + fn opus_open_and_first_sequential_read_do_not_scan_tail_packets() { + assert_eq!(opus_packet_samples(OPUS_TONE), Some(OPUS_FRAME as u32)); + let mut unlaced_matroska_audio = None; + let cases = [(false, 0, false), (true, 0, false), (false, OPUS_LEAD, false), (true, OPUS_LEAD, false), (true, OPUS_LEAD, true)]; + for (matroska_file, lead, laced) in cases { + let fixture = if matroska_file { generated_opus_matroska(lead, laced) } else { generated_opus_mp4(lead) }; + let OpusFixture { bytes, file, offsets, params, delay } = fixture; + assert_eq!(offsets.len(), OPUS_PACKETS); + assert!(offsets.windows(2).all(|w| w[0] < w[1])); + // Start counting after container metadata indexing. This isolates payload reads by the app + // opener, independent of how the demuxer peeks at block headers or buffers the file. + let source = OpusPayloadReads { bytes, offsets, packets: Mutex::new(Vec::new()), fail_once_at: Mutex::new(None) }; + // Independent eager placement oracle: fixed 20 ms packets, an explicit 200 ms gap, + // no drift from alternating Matroska stamp jitter, and delay applied once. + let delay_frames = if matroska_file { OPUS_CODEC_DELAY_FRAMES } else { 0 }; + let expected_positions: Vec<_> = (0..OPUS_PACKETS) + .map(|i| { + let gap = if i >= OPUS_GAP_AT { OPUS_GAP } else { 0 }; + (lead + i * OPUS_FRAME + gap) as i64 - delay_frames + }) + .collect(); + let early = assert_opus_early_and_backward(&file, &source, ¶ms, delay, &expected_positions, lead); + if laced { + assert_eq!(&early, unlaced_matroska_audio.as_ref().unwrap(), "durationless laces must place the same real audio as stamped packets"); + } else if matroska_file && lead == OPUS_LEAD { + unlaced_matroska_audio = Some(early); + } + let start = (lead + 151 * OPUS_FRAME + OPUS_GAP) as i64 - delay_frames; + assert_opus_first_cold_seek_and_retry(&file, &source, params, delay, &expected_positions, laced, start); + } + } + + #[test] + fn worker_cap_is_bounded() { + let cap = worker_cap(); + assert!((1..=MAX_WORKERS).contains(&cap), "cap={cap}"); + } + + /// Generated AAC permits unequal track/sample clocks, unlike the MOV writer's PCM tracks. + #[test] + fn mov_aac_edit_positions_saturate_with_unequal_clocks() { + use craft_audio::aac::{Encoder, EncoderConfig}; + use isobmff::{Brand, Edit, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + const RATE: u32 = 48_000; + let mut encoder = Encoder::new(EncoderConfig::cbr(RATE, 1, 64_000)).unwrap(); + let tone: Vec = (0..2048).map(|i| (i as f32 * 0.13).sin() * 0.25).collect(); + let mut packets = encoder.encode(&[&tone]); + packets.extend(encoder.flush()); + assert!(!packets.is_empty()); + for (offset, expected) in [(10i64, 480i64), (-10, -480), (i64::MAX / 2, i64::MAX), (-i64::MAX / 2, i64::MIN)] { + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let mut config = TrackConfig::new(SampleEntry::aac(encoder.audio_specific_config(), 1, RATE), 1_000); + if offset > 0 { + config.edits.push(Edit { segment_duration: offset as u64, media_time: -1, media_rate: 0x0001_0000 }); + } + config.edits.push(Edit { segment_duration: 100, media_time: (-offset).max(0), media_rate: 0x0001_0000 }); + let track_idx = writer.add_track(config).expect("AAC accepts unequal media and sample clocks"); + for packet in &packets { + writer.write_sample(track_idx, WriteSample { data: packet, duration: 21, composition_offset: 0, is_sync: true }).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let mov = isobmff::open(bytes.as_slice()).unwrap(); + let track = &mov.tracks[0]; + assert_eq!((track.timescale, track.edit_offset, track.presentation_pts(0)), (1_000, offset, Some(offset))); + let params = track.codec_params(); + assert_eq!((params.codec, params.sample_rate), (CodecId::Aac, Some(RATE))); + // Check the conversion itself: a decode error substituted with silence cannot pass. + assert_eq!(isobmff_audio_position(track, 0, RATE), expected); + let file = ContainerFile::Isobmff(mov); + let (mut tracks, infos) = open_audio_tracks(&file, &bytes, [(0, packets.len(), params, 0)]).expect("shared AAC source"); + assert_eq!(infos[0].sample_rate, RATE); + let (preroll, state) = tracks[0].decoder_parts(); + assert_eq!(state.audio_starts.start(&file, 0, 0), Some(expected)); + for start in [0, 6_000, 0] { + let decoded = decode_audio_range(&file, &bytes, 0, RATE, 1, preroll, state, start, 64).expect("the result-returning shared read must succeed"); + assert_eq!(decoded[0].len(), 64); + if expected == i64::MAX || expected == i64::MIN { + assert!(decoded[0].iter().all(|&v| v == 0.0), "out-of-range edits have no audible samples at {start}"); + } + } + } + } + + /// Original PCM generated in memory at the MOV writer's default movie timescale. + fn edited_pcm_mov(rate: u32, samples: &[i16], edits: Vec) -> Vec { + use isobmff::{Brand, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 1, sample_rate: f64::from(rate) }; + let mut config = TrackConfig::new(SampleEntry::pcm(pcm), rate); + config.edits = edits; + let track = writer.add_track(config).unwrap(); + for chunk in samples.chunks(256) { + let data: Vec = chunk.iter().flat_map(|sample| sample.to_le_bytes()).collect(); + writer.write_sample(track, WriteSample { data: &data, duration: chunk.len() as u32, composition_offset: 0, is_sync: true }).unwrap(); + } + writer.finish().unwrap().into_inner() + } + + #[test] + fn mov_pcm_trim_after_empty_edit_preserves_leading_silence() { + const RATE: u32 = 48_000; + const DELAY_MS: u64 = 100; + const DELAY: i64 = 4_800; + let samples: Vec = (0..12_000).map(|i| 1_000 + (i % 257) as i16 * 32).collect(); + for trim in [2_400i64, 4_800, 9_600] { + let bytes = edited_pcm_mov( + RATE, + &samples, + vec![ + isobmff::Edit { segment_duration: DELAY_MS, media_time: -1, media_rate: 0x0001_0000 }, + isobmff::Edit { segment_duration: 40, media_time: trim, media_rate: 0x0001_0000 }, + ], + ); + let file = isobmff::open(bytes.as_slice()).unwrap(); + assert_eq!(file.timescale, 1_000); + assert_eq!(file.tracks[0].edit_offset, DELAY - trim); + + let source = open_bytes("edited-pcm.mov", bytes.into()).expect("shared MOV route").unwrap(); + let sample = |index: i64| f32::from(samples[index as usize]) / 32_768.0; + let expected = [0.0, 0.0, sample(trim), sample(trim + 1)]; + let read = |start, frames, rate| source.audio(start, frames, rate).expect("direct shared PCM read").channels.remove(0); + assert_eq!(read(DELAY - 2, 4, RATE), expected, "first read, trim {trim}"); + assert_eq!(read(0, DELAY as usize, RATE), vec![0.0; DELAY as usize], "backward seek, trim {trim}"); + assert_eq!(read(DELAY, 2, RATE), expected[2..], "read from first presented sample, trim {trim}"); + assert_eq!(read(DELAY * 2 - 4, 5, RATE * 2), [0.0, 0.0, 0.0, 0.0, sample(trim)], "resampled read, trim {trim}"); + assert_eq!(read(4_408, 3, 44_100), [0.0, 0.0, sample(trim)], "nonintegral resampling ratio, trim {trim}"); + } + } + + #[test] + fn mov_pcm_audio_is_silent_after_the_edit_span() { + const RATE: u32 = 48_000; + const EDIT_MS: u64 = 41; + const TRIM: i64 = 9_600; + const EDIT_FRAMES: usize = 1_968; + let samples: Vec = (0..12_000).map(|i| 1_000 + (i % 257) as i16 * 32).collect(); + let last = f32::from(samples[TRIM as usize + EDIT_FRAMES - 1]) / 32_768.0; + let previous = f32::from(samples[TRIM as usize + EDIT_FRAMES - 2]) / 32_768.0; + for delay_ms in [0, 100] { + let mut edits = Vec::new(); + if delay_ms > 0 { + edits.push(isobmff::Edit { segment_duration: delay_ms, media_time: -1, media_rate: 0x0001_0000 }); + } + edits.push(isobmff::Edit { segment_duration: EDIT_MS, media_time: TRIM, media_rate: 0x0001_0000 }); + let bytes = edited_pcm_mov(RATE, &samples, edits); + let source = open_bytes("edited-pcm.mov", bytes.into()).expect("shared MOV route").unwrap(); + let read = |start, frames, rate| source.audio(start, frames, rate).expect("direct shared PCM read").channels.remove(0); + + let end = ((delay_ms + EDIT_MS) * 48) as i64; + assert_eq!(read(end - 2, 4, RATE), [previous, last, 0.0, 0.0], "crossing the boundary, delay {delay_ms}"); + assert_eq!(read(end, 2, RATE), [0.0, 0.0], "read after the end"); + assert_eq!(read(end - 2, 2, RATE), [previous, last], "backward seek"); + assert_eq!(read(end * 2 - 4, 6, RATE * 2), [previous, (previous + last) / 2.0, last, last, 0.0, 0.0]); + + let first_silent = ((delay_ms + EDIT_MS) * 44_100).div_ceil(1_000) as i64; + let boundary = read(first_silent - 1, 2, 44_100); + assert!(boundary[0] > 0.0, "sample before the fractional boundary"); + assert_eq!(boundary[1], 0.0, "sample after the fractional boundary"); + } + } + + #[test] + fn mov_pcm_fractional_empty_edit_excludes_packet_tail() { + const RATE: u32 = 44_100; + let mut samples = vec![0i16; 1_024]; + samples[600] = 16_384; + samples[601] = -8_192; + let mux = |leading_ms| { + edited_pcm_mov( + RATE, + &samples, + vec![ + isobmff::Edit { segment_duration: leading_ms, media_time: -1, media_rate: 0x0001_0000 }, + isobmff::Edit { segment_duration: 2, media_time: 512, media_rate: 0x0001_0000 }, + ], + ) + }; + let bytes: Arc<[u8]> = mux(9).into(); + let demuxed = isobmff::open(bytes.as_ref()).expect("generated PCM MOV"); + assert_eq!(demuxed.timescale, 1_000); + assert_eq!(demuxed.tracks[0].timescale, RATE); + assert!(demuxed.tracks[0].pcm_chunked); + assert_eq!(demuxed.tracks[0].edit_offset, -116); + let source = open_bytes("fractional-edit.mov", bytes).expect("shared MOV route").expect("open mapped PCM"); + let read = |start, frames, rate| source.audio(start, frames, rate).expect("direct shared PCM read").channels.remove(0); + + // The output range still includes native position 485. The source edit ends + // before raw frame 601 (position 485), but includes raw frame 600 (position 484). + assert_eq!(read(484, 3, RATE), [0.5, 0.0, 0.0]); + assert_eq!(read(485, 2, RATE), [0.0, 0.0], "packet-content-only tail"); + assert_eq!(read(484, 1, RATE), [0.5], "backward seek retains the last visible source sample"); + assert_eq!(read(968, 4, RATE * 2), [0.5, 0.5, 0.0, 0.0], "do not interpolate with the excluded sample"); + + let aligned = open_bytes("aligned-edit.mov", mux(10).into()).expect("shared MOV").expect("aligned clocks"); + assert_eq!(aligned.audio(529, 3, RATE).expect("aligned PCM").channels[0], [0.5, 0.0, 0.0]); + let unedited = open_bytes("no-edit.mov", edited_pcm_mov(RATE, &samples, Vec::new()).into()).expect("shared MOV").expect("no edit"); + assert_eq!(unedited.audio(600, 2, RATE).expect("unedited PCM").channels[0], [0.5, -0.25]); + + let mut mixed = demuxed.clone(); + let track = &mut mixed.tracks[0]; + let mut non_pcm = track.entries[0].clone(); + non_pcm.codec = isobmff::CodecConfig::Mp3; + track.entries.push(non_pcm.clone()); + track.samples[0].description_index = 2; + assert_ne!(track.codec_params().codec, CodecId::Pcm, "first sample selects the other description"); + assert_eq!(ContainerFile::Isobmff(mixed.clone()).pcm_edit_packet_end(0, RATE), None, "mixed descriptions"); + let track = &mut mixed.tracks[0]; + track.entries = vec![non_pcm]; + track.samples[0].description_index = 1; + assert_eq!(ContainerFile::Isobmff(mixed).pcm_edit_packet_end(0, RATE), None, "sole non-PCM description"); + + let file = ContainerFile::Isobmff(demuxed.clone()); + assert_eq!(file.pcm_edit_packet_end(0, RATE), Some(485)); + assert_eq!(file.pcm_edit_packet_end(0, 48_000), None, "different track and native clocks"); + let mut parsed = demuxed; + parsed.tracks[0].edits[1].segment_duration = u64::MAX; + assert_eq!(ContainerFile::Isobmff(parsed).pcm_edit_packet_end(0, RATE), None, "unrepresentable native end"); + } + + #[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); + } + + #[test] + fn matroska_color_and_sniffer_preserve_policies() { + assert!(looks_like_matroska(&[0x1A, 0x45, 0xDF, 0xA3, 0x01, 0x00])); + assert!(!looks_like_matroska(&[0x00, 0x00, 0x00, 0x18, b'f', b't', b'y', b'p'])); + assert!(looks_like_isobmff(&[0x00, 0x00, 0x00, 0x18, b'f', b't', b'y', b'p'])); + + let mkv_hdr = + matroska::Color { matrix_coefficients: Some(9), transfer_characteristics: Some(16), primaries: Some(9), range: Some(1), ..Default::default() }; + let c = color_from_matroska(&mkv_hdr); + assert_eq!(c.primaries, Primaries::Bt2020); + assert_eq!(c.transfer, Transfer::Pq); + assert_eq!(c.matrix, Matrix::Bt2020Ncl); + assert_eq!(c.range, Range::Limited); + } + + #[test] + #[cfg(any(unix, windows))] + fn matroska_ffv1_missing_config_keeps_legacy_probe() { + use crate::stream::{DecodedFrame, MediaSource as Opened}; + use craft_video::ffv1::{Colorspace, Encoder, EncoderConfig, Frame}; + + let mut frame = Frame { + width: 16, + height: 16, + colorspace: Colorspace::YCbCr, + bit_depth: 8, + chroma_shift: (1, 1), + planes: vec![vec![48; 256], vec![96; 64], vec![160; 64]], + }; + let encoder = Encoder::new(&frame, EncoderConfig::default()).expect("FFV1 encoder"); + let first = encoder.encode(&frame).expect("first FFV1 keyframe"); + frame.planes[0].fill(192); + let second = encoder.encode(&frame).expect("second FFV1 keyframe"); + + // The control changes only the container configuration, not the two coded keyframes. + let mux = |configuration| -> Arc<[u8]> { + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Video, "V_FFV1"); + track.video_size = Some((16, 16)); + track.default_duration_ns = Some(40_000_000); + track.codec_private = configuration; + let mut mux = matroska::MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default()).expect("MKV writer"); + mux.write_frame(0, 0, true, &first, None).expect("write first keyframe"); + mux.write_frame(0, 40_000_000, true, &second, None).expect("write second keyframe"); + mux.finish().expect("finish MKV").into_inner().into() + }; + let configured = mux(encoder.config_record()); + let missing = mux(Vec::new()); + let directory = tempfile::tempdir().expect("FFV1 fixture directory"); + let configured_path = directory.path().join("configured.mkv"); + let missing_path = directory.path().join("no-config.mkv"); + std::fs::write(&configured_path, &configured).expect("write configured fixture"); + std::fs::write(&missing_path, &missing).expect("write no-config fixture"); + + let configured_probe = crate::probe(&configured_path).expect("public probe of configured FFV1"); + assert!(configured_probe.has_video); + assert_eq!((configured_probe.width, configured_probe.height), (16, 16)); + assert_eq!((configured_probe.frame_rate.num, configured_probe.frame_rate.den), (25, 1)); + let opened = crate::stream::open_source(&configured_path).expect("open in place").0.expect("open configured FFV1"); + assert!(matches!(&opened, Opened::Craft(_))); + let zero = effectcraft_time::Tick::ZERO; + let later = effectcraft_time::Tick(craft_time::TICKS_PER_SECOND / 25); + for (pts, luma) in [(zero, 48), (later, 192), (zero, 48)] { + let frame = match opened.video_frame(pts, 1.0).expect("decode configured FFV1") { + DecodedFrame::Craft(frame) => Some(frame), + DecodedFrame::Film(_) => None, + } + .expect("decoded through the shared FFV1 reader"); + assert_eq!(frame.pts.0, pts.0); + assert!(matches!(&frame.data, PixelData::Yuv8 { planes, chroma: Chroma::C420, alpha: None } + if planes[0].as_slice() == [luma; 256] && planes[1].as_slice() == [96; 64] && planes[2].as_slice() == [160; 64])); + } + + let name = "no-config.mkv"; + let legacy = filmcraft_codecs::open_bytes(name, missing.clone()).expect("legacy FFV1 metadata opens without config"); + let legacy_probe = crate::probe::footage_from_info(name, legacy.info()); + let legacy_error = legacy + .video_frame(filmcraft_media::FrameRequest { time: filmcraft_time::Tick::ZERO, scale: 1.0 }) + .err() + .map(crate::MediaError::from) + .expect("FilmCraft does not play FFV1"); + assert!(matches!(&legacy_error, crate::MediaError::Unsupported(message) if message.contains("no decoder"))); + + let missing_probe = crate::probe(&missing_path).expect("public probe preserves metadata without config"); + let memory_probe = crate::probe_bytes(name, missing).expect("public memory probe preserves metadata without config"); + for probe in [missing_probe, memory_probe] { + assert!(probe.has_video); + assert_eq!((probe.width, probe.height), (legacy_probe.width, legacy_probe.height)); + assert_eq!(probe.frame_rate, legacy_probe.frame_rate); + assert_eq!(probe.duration, legacy_probe.duration); + assert_eq!(probe.codec, legacy_probe.codec); + } + let opened = crate::stream::open_source(&missing_path).expect("open in place").0.expect("open FFV1 metadata without config"); + assert!(matches!(&opened, Opened::Film(_))); + let err = opened.video_frame(zero, 1.0).err().expect("unsupported is deferred to playback"); + assert_eq!(err.to_string(), legacy_error.to_string()); + } + + #[test] + fn rotate_frame_swaps_dimensions_and_orients_planes() { + let frame = VideoFrame { + width: 4, + height: 2, + data: PixelData::Yuv8 { + planes: [Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8]), Arc::new(vec![10, 20]), Arc::new(vec![30, 40])], + chroma: Chroma::C420, + alpha: Some(Arc::new(vec![11, 12, 13, 14, 15, 16, 17, 18])), + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }; + let rot90 = rotate_frame(frame.clone(), 1); + assert_eq!((rot90.width, rot90.height), (2, 4)); + assert!(matches!(rot90.data, PixelData::Yuv8 { alpha: Some(_), .. })); + if let PixelData::Yuv8 { planes: [y, ..], alpha: Some(a), .. } = &rot90.data { + assert_eq!(&**y, &[5, 1, 6, 2, 7, 3, 8, 4]); + assert_eq!(&**a, &[15, 11, 16, 12, 17, 13, 18, 14]); + } + let rot360 = rotate_frame(rot90, 3); + assert_eq!((rot360.width, rot360.height), (4, 2)); + if let PixelData::Yuv8 { planes: [y, ..], .. } = &rot360.data { + assert_eq!(&**y, &[1, 2, 3, 4, 5, 6, 7, 8]); + } + } + + #[test] + fn plane_u8_handles_8bit_u16_storage_as_av1_produces() { + let out = Plane::packed(2, 2, 8, Samples::U16(vec![10, 20, 30, 255])).ok().and_then(|p| plane_u8(p, None).ok()); + assert_eq!(out.as_deref(), Some(&[10, 20, 30, 255][..])); + } + + #[test] + fn rotate_frame_covers_180_270_c422_and_yuv16() { + let f16 = VideoFrame { + width: 4, + height: 2, + data: PixelData::Yuv16 { + planes: [Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8]), Arc::new(vec![10, 20, 30, 40]), Arc::new(vec![50, 60, 70, 80])], + chroma: Chroma::C422, + bits: 10, + alpha: Some(Arc::new(vec![100; 8])), + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }; + let r180 = rotate_frame(f16.clone(), 2); + assert_eq!((r180.width, r180.height), (4, 2)); + if let PixelData::Yuv16 { planes: [y, ..], chroma, .. } = &r180.data { + assert_eq!(*chroma, Chroma::C422); + assert_eq!(&**y, &[8, 7, 6, 5, 4, 3, 2, 1]); + } + let r270 = rotate_frame(f16, 1); + assert_eq!((r270.width, r270.height), (2, 4)); + if let PixelData::Yuv16 { chroma, .. } = &r270.data { + assert_eq!(*chroma, Chroma::C444); + } + } + + #[test] + fn adts_transport_duration_includes_the_final_packet() { + use craft_audio::aac::{Encoder, EncoderConfig}; + use mpegts::mux::{Codec, Config, Frame, Muxer, Stream}; + + const RATE: u32 = 48_000; + const SAMPLES: i64 = 1024; + const PTS_PER_PACKET: i64 = 1_920; + const ORIGIN_PTS: i64 = 90_000; + let mut encoder = Encoder::new(EncoderConfig::cbr(RATE, 1, 96_000).with_adts(true)).expect("ADTS encoder"); + let samples: Vec = (0..8192).map(|i| (f64::from(i) * 0.13).sin() as f32 * 0.4).collect(); + let mut packets = encoder.encode(&[&samples]); + packets.extend(encoder.flush()); + let three_packets = packets.get(..3).expect("three encoded packets"); + + for last_slot in [2, 3] { + let mut mux = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::AacAdts)]).expect("TS muxer"); + for (data, slot) in three_packets.iter().zip([0, 1, last_slot]) { + let pts = ORIGIN_PTS + slot * PTS_PER_PACKET; + mux.write_frame(0, &Frame { data, pts, dts: None, key: true }).expect("write ADTS packet"); + } + let bytes: Arc<[u8]> = mux.finish().expect("finish TS").into(); + let source = open_bytes("audio.ts", bytes.clone()).expect("recognized TS").expect("shared TS audio"); + let final_packet = source.audio(last_slot * SAMPLES, SAMPLES as usize, RATE).expect("read final packet"); + assert!(final_packet.channels[0].iter().any(|sample| sample.abs() > 0.02), "the final packet carries audible samples"); + + let footage = crate::probe::probe_bytes("audio.ts", bytes).expect("public TS probe"); + assert!(footage.has_audio && !footage.has_video); + assert_eq!(footage.codec, "AAC"); + let end = Tick::from_units((last_slot + 1) * SAMPLES, i64::from(RATE)); + assert_eq!(footage.duration.0, end.0, "final packet at slot {last_slot}"); + } + } + + #[test] + fn plane_stride_and_container_helpers_cover_variants() { + if let Ok(p8) = Plane::new(2, 2, 4, 8, Samples::U8(vec![1, 2, 9, 9, 3, 4])) { + assert_eq!(plane_u8(p8, None).ok().as_deref(), Some(&[1, 2, 3, 4][..])); + } + if let Ok(p16) = Plane::new(2, 2, 4, 10, Samples::U16(vec![10, 20, 99, 99, 30, 40])) { + assert_eq!(plane_u16(p16, None).ok().as_deref(), Some(&[10, 20, 30, 40][..])); + } + if let Ok(p8_as_16) = Plane::packed(2, 1, 8, Samples::U8(vec![7, 8])) { + assert_eq!(plane_u16(p8_as_16, None).ok().as_deref(), Some(&[7, 8][..])); + } + + let nclc = color_from_isobmff(&isobmff::ColorInfo::Nclc { primaries: 1, transfer: 1, matrix: 1 }); + assert_eq!(nclc, ColorInfo::REC709); + let icc = color_from_isobmff(&isobmff::ColorInfo::Icc { kind: isobmff::FourCc(*b"prof"), profile: Vec::new() }); + assert_eq!(icc, ColorInfo::REC709); + + let v = matroska::VideoInfo { display_width: Some(1280), display_height: Some(720), display_unit: 0, ..Default::default() }; + assert_eq!(matroska_par(Some(&v), 640, 720), (1280 * 720, 720 * 640)); + assert_eq!(matroska_par(None, 640, 360), (1, 1)); + assert_eq!(snap_common_fps(23.976), Some(FrameRate::FPS_23_976)); + assert_eq!(snap_common_fps(f64::NAN), None); + assert_eq!(tick_to_matroska_units(Tick(craft_time::TICKS_PER_SECOND), (1, 1000)), 1000); + assert_eq!(tick_to_units(Tick(craft_time::TICKS_PER_SECOND), 90000), 90000); + } + + fn prores_matroska(packets: &[&[u8]]) -> Arc<[u8]> { + use craft_media::matroska::{MkvWriter, MuxOptions, TrackKind, TrackSpec}; + use craft_video::prores::Profile; + use std::io::Cursor; + + let mut track = TrackSpec::new(TrackKind::Video, "V_PRORES"); + track.video_size = Some((16, 16)); + track.codec_private = Profile::P4444.fourcc().to_vec(); + track.default_duration_ns = Some(40_000_000); + let mut mux = MkvWriter::new(Cursor::new(Vec::new()), vec![track], MuxOptions::default()).expect("Matroska writer"); + for (index, packet) in packets.iter().enumerate() { + mux.write_frame(0, index as i64 * 40_000_000, true, packet, None).expect("write ProRes"); + } + mux.finish().expect("finish Matroska").into_inner().into() + } + + #[test] + fn matroska_prores_coded_alpha_reaches_the_public_probe() { + use craft_video::prores::{ChromaFormat, Encoder, EncoderConfig, Frame, Profile}; + use effectcraft_project::AlphaMode; + + for with_alpha in [true, false] { + let mut config = EncoderConfig::new(Profile::P4444, 16, 16); + config.encode_alpha = with_alpha; + config.threads = false; + let mut picture = Frame::new(16, 16, ChromaFormat::Yuv444, 10, with_alpha).expect("allocate picture"); + if let Some(alpha) = &mut picture.alpha { + alpha.fill(512); + } + let packet = Encoder::with_config(config).encode(&picture).expect("encode ProRes"); + let bytes = prores_matroska(&[&packet]); + + let source = open_bytes("alpha.mkv", bytes.clone()).expect("recognized Matroska").expect("shared Matroska"); + let frame = source.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode ProRes"); + assert_eq!(matches!(frame.data, PixelData::Yuv16 { alpha: Some(_), .. }), with_alpha); + + let footage = crate::probe::probe_bytes("alpha.mkv", bytes).expect("public Matroska probe"); + assert_eq!(footage.codec, "ProRes"); + assert_eq!(footage.alpha, if with_alpha { AlphaMode::Straight } else { AlphaMode::Ignore }); + } + } + + #[test] + fn matroska_prores_unreadable_alpha_probe_keeps_the_shared_route() { + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + let picture = Frame::new(16, 16, ChromaFormat::Yuv444, 10, false).expect("allocate picture"); + let packet = Encoder::new(Profile::P4444, 16, 16).encode(&picture).expect("encode ProRes"); + let bytes = prores_matroska(&[&[0; 3], &packet]); + let source = open_bytes("later-frame.mkv", bytes).expect("recognized Matroska").expect("shared Matroska"); + assert!(!source.info().video.as_ref().expect("video info").has_alpha); + let time = Tick::from_units(40, 1_000); + let later = source.video_frame(FrameRequest { time, scale: 1.0 }).expect("read intact second picture"); + assert_eq!(later.pts, time); + } + + #[test] + fn clean_aperture_rounds_signed_offsets_and_ignores_invalid_regions() { + let aperture = isobmff::CleanAperture { width: (17, 2), height: (15, 2), horiz_offset: (1, 2), vert_offset: (-1, 2) }; + assert_eq!(clean_aperture_region(aperture, (16, 16)), Some(Region { x: 4, y: 4, w: 9, h: 8 })); + assert_eq!(clean_aperture_region(isobmff::CleanAperture { width: (17, 0), ..aperture }, (16, 16)), None); + assert_eq!(clean_aperture_region(isobmff::CleanAperture { horiz_offset: (10, 1), ..aperture }, (16, 16)), None); + let full = isobmff::CleanAperture { width: (16, 1), height: (16, 1), horiz_offset: (0, 1), vert_offset: (0, 1) }; + assert_eq!(clean_aperture_region(full, (16, 16)), None); + } + + #[test] + fn odd_clean_aperture_crops_luma_chroma_and_alpha_together() { + let luma = Plane::packed(6, 6, 8, Samples::U8((0..36).collect())).unwrap(); + let chroma = Plane::packed(3, 3, 8, Samples::U8((0..9).collect())).unwrap(); + let alpha = Plane::packed(6, 6, 8, Samples::U8((64..100).collect())).unwrap(); + let frame = DecodedVideoFrame::new(6, 6, ColorFamily::YCbCr, Subsampling::S420, vec![luma, chroma.clone(), chroma], Some(alpha)).unwrap(); + let aperture = Some(isobmff::CleanAperture { width: (3, 1), height: (3, 1), horiz_offset: (3, 2), vert_offset: (3, 2) }); + let presentation = FramePresentation { container_color: None, par: (3, 2), rotation: 0, aperture }; + let cropped = to_craft_frame(frame, presentation, Tick::ZERO).unwrap(); + assert_eq!((cropped.width, cropped.height, cropped.par), (3, 3, (3, 2))); + let PixelData::Yuv8 { planes: [y, cb, cr], chroma: Chroma::C420, alpha: Some(a) } = cropped.data else { + panic!("expected cropped 4:2:0 with alpha"); + }; + assert_eq!(y.as_slice(), &[14, 15, 16, 20, 21, 22, 26, 27, 28]); + assert_eq!(cb.as_slice(), &[4, 5, 7, 8]); + assert_eq!(cr.as_slice(), cb.as_slice()); + assert_eq!(a.as_slice(), &[78, 79, 80, 84, 85, 86, 90, 91, 92]); + } + + #[test] + fn clean_aperture_uses_the_decoded_picture_not_a_coded_size_hint() { + let luma = Plane::packed(8, 6, 8, Samples::U8((0..48).collect())).unwrap(); + let chroma = Plane::packed(8, 6, 8, Samples::U8(vec![128; 48])).unwrap(); + let frame = DecodedVideoFrame::new(8, 6, ColorFamily::YCbCr, Subsampling::S444, vec![luma, chroma.clone(), chroma], None).unwrap(); + let aperture = isobmff::CleanAperture { width: (4, 1), height: (4, 1), horiz_offset: (0, 1), vert_offset: (0, 1) }; + // A coded/sample-entry size of 8×8 would put the crop one row too low on the decoded + // 8×6 picture. The aperture remains in rational form until this picture is available. + assert_eq!(clean_aperture_region(aperture, (8, 8)).unwrap().y, 2); + let presentation = FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: Some(aperture) }; + let cropped = to_craft_frame(frame, presentation, Tick::ZERO).unwrap(); + assert_eq!((cropped.width, cropped.height), (4, 4)); + let y = match &cropped.data { + PixelData::Yuv8 { planes, .. } => &planes[0], + _ => panic!("expected cropped luma"), + }; + assert_eq!(y.as_slice(), &[10, 11, 12, 13, 18, 19, 20, 21, 26, 27, 28, 29, 34, 35, 36, 37]); + } + + #[test] + fn rotated_frame_preserves_container_par_without_double_inversion() { + let make_vf = |sar: Option<(u32, u32)>| { + let y = Plane::packed(2, 2, 8, Samples::U8(vec![1, 2, 3, 4])).ok()?; + let cb = Plane::packed(1, 1, 8, Samples::U8(vec![128])).ok()?; + let cr = Plane::packed(1, 1, 8, Samples::U8(vec![128])).ok()?; + let mut vf = DecodedVideoFrame::new(2, 2, ColorFamily::YCbCr, Subsampling::S420, vec![y, cb, cr], None).ok()?; + vf.sar = sar; + Some(vf) + }; + // `default_par` is already rotated by the container opener (e.g. (4, 3) -> (3, 4) for 90°). + let container_rotated_par = (3, 4); + let presentation = FramePresentation { container_color: None, par: container_rotated_par, rotation: 1, aperture: None }; + if let Some(vf_no_sar) = make_vf(None) { + let out = to_craft_frame(vf_no_sar, presentation, Tick::ZERO).ok(); + assert_eq!(out.map(|f| f.par), Some((3, 4))); + } + // Decoder-supplied SAR is in coded coordinates and must be inverted once under 90° rotation. + if let Some(vf_with_sar) = make_vf(Some((4, 3))) { + let out = to_craft_frame(vf_with_sar, presentation, Tick::ZERO).ok(); + assert_eq!(out.map(|f| f.par), Some((3, 4))); + } + } + + fn mxf_prores_color_packet(codes: (u8, u8, u8)) -> Vec { + use craft_video::prores::{self, ChromaFormat, Encoder, EncoderConfig, Frame, Profile}; + + let mut frame = Frame::new(16, 12, ChromaFormat::Yuv422, 10, false).expect("ProRes frame"); + frame.y.fill(512); + frame.cb.fill(512); + frame.cr.fill(512); + let (primaries, transfer, matrix) = codes; + let mut encoder = EncoderConfig::new(Profile::Hq, 16, 12); + encoder.color = prores::ColorInfo { primaries, transfer, matrix }; + let packet = Encoder::with_config(encoder).encode(&frame).expect("encode ProRes"); + let bits = prores::probe(&packet).expect("ProRes header").color; + assert_eq!((bits.primaries, bits.transfer, bits.matrix), codes); + packet + } + + fn mxf_prores_color_fixture(color: mxf::write::ColorSpace, packets: &[&[u8]]) -> Arc<[u8]> { + let ids = mxf::write::PackageIds::from_seed("eff-mxf-color", "op1a"); + let mut cfg = mxf::write::WriterConfig::new(mxf::write::Pattern::Op1a, mxf::Rational::new(25, 1), ids); + let mut picture = mxf::write::PictureDesc::new(mxf::write::PictureCoding::ProRes { profile: 4 }, 16, 12); + picture.color = color; + cfg.picture = Some(picture); + let mut writer = mxf::write::MxfWriter::new(std::io::Cursor::new(Vec::new()), cfg).expect("writer"); + for packet in packets { + writer.push_picture(packet, mxf::write::FrameInfo::intra()).expect("picture"); + } + writer.finish().expect("finish").into_inner().into() + } + + #[test] + fn mxf_descriptor_color_fills_unspecified_shared_prores_fields() { + use effectcraft_project::ColorSpace; + + let pq = ColorInfo { primaries: Primaries::Bt2020, transfer: Transfer::Pq, matrix: Matrix::Bt2020Ncl, range: Range::Limited }; + let mixed = ColorInfo { matrix: Matrix::Bt709, ..pq }; + for (descriptor, descriptor_codes, packet_codes, profile, expected) in [ + (mxf::write::ColorSpace::Rec2020Pq, (9, 16, 9), (2, 2, 2), Some(ColorSpace::Rec2100Pq), pq), + (mxf::write::ColorSpace::Rec2020Pq, (9, 16, 9), (1, 1, 1), Some(ColorSpace::Rec709), ColorInfo::REC709), + (mxf::write::ColorSpace::Rec2020Pq, (9, 16, 9), (2, 2, 1), Some(ColorSpace::Rec2100Pq), mixed), + (mxf::write::ColorSpace::Rec2020Pq, (9, 16, 9), (1, 2, 1), Some(ColorSpace::Rec709), ColorInfo::REC709), + (mxf::write::ColorSpace::Rec709, (1, 1, 1), (2, 2, 2), Some(ColorSpace::Rec709), ColorInfo::REC709), + ] { + let bytes = mxf_prores_color_fixture(descriptor, &[&mxf_prores_color_packet(packet_codes)]); + let file = mxf::open(bytes.as_ref()).expect("demux fixture"); + let picture = file.tracks[0].picture.as_ref().expect("picture descriptor"); + let (p, t, m) = descriptor_codes; + assert_eq!(picture.color_codes(), (Some(p), Some(t), Some(m))); + let footage = crate::probe::probe_bytes("color.mxf", bytes.clone()).expect("public probe"); + assert_eq!(footage.codec, "ProRes", "must use the shared MXF route"); + assert_eq!(footage.color_profile, profile); + + let source = open_bytes("color.mxf", bytes).expect("recognized MXF").expect("shared MXF"); + let info = source.info().video.as_ref().expect("video"); + assert_eq!(info.color, expected); + assert!(info.hdr.is_none(), "color labels alone are not HDR static metadata"); + let decoded = source.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode frame"); + assert_eq!(decoded.color, expected); + } + } + + #[test] + fn mxf_prores_explicit_rec709_keeps_managed_pixels_and_saved_interpretation() { + use effectcraft_color::{ColorSpace, Label}; + use effectcraft_project::{BitDepth, Comp, ItemKind, LayerSource, Project, build}; + use effectcraft_render::{RenderOpts, Renderer}; + + let packet = mxf_prores_color_packet((1, 1, 1)); + let render = |descriptor, saved_override| { + let bytes = mxf_prores_color_fixture(descriptor, &[&packet]); + let path = "managed-color.mxf"; + let mut footage = crate::probe::probe_bytes(path, bytes.clone()).expect("public probe"); + assert_eq!(footage.codec, "ProRes", "must use the shared MXF route"); + assert_eq!(footage.color_profile, Some(ColorSpace::Rec709)); + if saved_override { + footage.color_profile = Some(ColorSpace::Rec2100Pq); + } + let pool = crate::MediaPool::new(); + pool.add_bytes(path, bytes); + + let mut project = Project::default(); + project.settings.bit_depth = BitDepth::Bpc32; + project.settings.working_space = Some(ColorSpace::Srgb); + let rate = effectcraft_time::FrameRate::new(25, 1); + let mut comp = Comp::new(16, 12, rate, rate.tick_of(1)); + let item = project.add_item("Footage", Label::Aqua, None, ItemKind::Footage(footage)); + let layer = build::layer(&mut project, &comp, "Footage", LayerSource::Footage { item }, (16, 12), Some(comp.duration)); + comp.layers.push(layer); + let comp_id = project.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.into())); + Renderer::new(&project, &pool, RenderOpts::default()).comp_frame(comp_id, effectcraft_time::Tick::ZERO).get(8, 6) + }; + + let rec709 = render(mxf::write::ColorSpace::Rec709, false); + let conflicting = render(mxf::write::ColorSpace::Rec2020Pq, false); + let overridden = render(mxf::write::ColorSpace::Rec2020Pq, true); + assert!(rec709[0] > 0.1 && rec709[0] < 0.9 && rec709[3] > 0.99, "not an opaque midtone: {rec709:?}"); + assert!(rec709.iter().zip(conflicting).all(|(a, b)| (a - b).abs() < 1e-4), "{rec709:?} vs {conflicting:?}"); + assert!((overridden[0] - conflicting[0]).abs() > 0.02, "saved interpretation did not change the pixel: {overridden:?} vs {conflicting:?}"); + } + + #[test] + fn mxf_prores_color_reads_one_bounded_presented_packet() { + struct Reads<'a> { + bytes: &'a [u8], + log: Mutex>, + fail: bool, + } + impl ByteSource for Reads<'_> { + fn len(&self) -> u64 { + if self.fail { u64::MAX } else { self.bytes.len() as u64 } + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.log.lock().unwrap().push((offset, buf.len())); + if self.fail { + return Err(std::io::Error::other("unreadable fixture packet")); + } + self.bytes.read_at(offset, buf) + } + } + + let unspecified = mxf_prores_color_packet((2, 2, 2)); + let rec709 = mxf_prores_color_packet((1, 1, 1)); + let bytes = mxf_prores_color_fixture(mxf::write::ColorSpace::Rec2020Pq, &[&unspecified, &rec709]); + let mut file = mxf::open(bytes.as_ref()).expect("demux fixture"); + // Exercise a material edit on parsed metadata: stored packet zero is hidden. + file.tracks[0].start_position = 1; + let sample = file.tracks[0].samples[1]; + let mut reads = Reads { bytes: &bytes, log: Mutex::new(Vec::new()), fail: false }; + let (probe, descriptor) = mxf_prores_color(&file, &reads, 0).expect("first presented ProRes header"); + assert_eq!(probe, ColorInfo::REC709); + assert_eq!(descriptor.transfer, Transfer::Pq); + assert_eq!(std::mem::take(reads.log.get_mut().unwrap()), [(sample.offset, sample.size as usize)]); + + reads.fail = true; + assert_eq!(mxf_prores_color(&file, &reads, 0), None); + assert_eq!(std::mem::take(reads.log.get_mut().unwrap()), [(sample.offset, sample.size as usize)]); + // The source reports ample backing so only the cap can explain the skipped read. + file.tracks[0].samples[1].size = MAX_MXF_PRORES_COLOR_SAMPLE_BYTES + 1; + assert_eq!(mxf_prores_color(&file, &reads, 0), None); + assert!(reads.log.get_mut().unwrap().is_empty()); + + file.tracks[0].samples[1] = sample; + file.tracks[0].codec = mxf::Codec::Vc3; + assert_eq!(mxf_prores_color(&file, &reads, 0), None); + assert!(reads.log.get_mut().unwrap().is_empty()); + } + + #[test] + fn mxf_absent_color_labels_keep_defaults_and_range_policy() { + let picture = mxf::PictureInfo { component_depth: 10, black_ref_level: Some(0), white_ref_level: Some(1023), ..Default::default() }; + assert!(picture.full_range()); + assert_eq!(picture.color_codes(), (None, None, None)); + assert_eq!(color_from_mxf(&picture), None); + assert_eq!(resolve_color(ColorTags::UNSPECIFIED, color_from_mxf(&picture)), ColorInfo::REC709); + } + + #[test] + fn shared_prores_mov_uses_serial_packets_with_edited_frame_and_alpha_parity() { + use isobmff::{Brand, Edit, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + let mut encoder = prores::Encoder::new(prores::Profile::P4444, 64, 48); + let mut input = prores::Frame::new(64, 48, prores::ChromaFormat::Yuv444, 12, true).expect("ProRes frame"); + let mut entry = SampleEntry::prores(isobmff::FourCc(*b"ap4h"), 64, 48); + entry.video.as_mut().expect("visual entry").pixel_aspect = Some((4, 3)); + let mut config = TrackConfig::new(entry, 1_000); + config.edits = vec![ + Edit { segment_duration: 20, media_time: -1, media_rate: 0x0001_0000 }, + Edit { segment_duration: 120, media_time: 0, media_rate: 0x0001_0000 }, + ]; + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).expect("MOV writer"); + let track = writer.add_track(config).expect("picture track"); + let mut packets = Vec::new(); + for (luma, alpha) in [(512, 1_024), (1_536, 2_048), (3_072, 3_072)] { + input.y.fill(luma); + input.alpha.as_mut().expect("alpha input").fill(alpha); + let packet = encoder.encode(&input).expect("ProRes packet"); + writer.write_sample(track, WriteSample { data: &packet, duration: 40, composition_offset: 0, is_sync: true }).expect("MOV sample"); + packets.push(packet); + } + let bytes = writer.finish().expect("MOV finish").into_inner(); + let demuxed = isobmff::open(bytes.as_slice()).expect("MOV demux"); + assert_eq!(demuxed.tracks[track].edit_offset, 20); + let params = demuxed.tracks[track].codec_params(); + let crate::stream::MediaSource::Craft(source) = crate::stream::open_bytes("serial.mov", bytes.into()).expect("MOV opener") else { + panic!("generated ProRes cannot fall back to FilmCraft"); + }; + assert!(source.info().video.as_ref().expect("video").has_alpha); + + let mut decoder = TrackDecoder::new(¶ms).expect("ProRes decoder"); + let mut passed_serial_options = false; + let selected = decode_track_packet(&mut decoder, true, &packets[1], 40, |packet, options| { + assert!(!options.threads); + assert!(options.bit_depth.is_none()); + passed_serial_options = true; + prores::decode_frame_with(packet, options) + }) + .expect("serial packet"); + assert!(passed_serial_options, "the ISO-BMFF helper must select explicit serial decoding"); + assert_eq!(selected[0].pts, Some(40)); + + // Seek late, then backwards, then forwards. The original parallel TrackDecoder is an + // independent oracle for every plane, including alpha, of each chosen compressed frame. + let presentation = FramePresentation { container_color: None, par: (4, 3), rotation: 0, aperture: None }; + for (index, raw_pts, presented) in [(2, 80, 100), (0, 0, 20), (1, 40, 60)] { + let pts = Tick::from_units(presented, 1_000); + let actual = source.video_frame(FrameRequest::full(pts)).expect("shared MOV frame"); + let packet = &packets[index]; + let mut parallel = + decode_track_packet(&mut decoder, false, packet, raw_pts, |_, _| panic!("expected TrackDecoder")).expect("normal parallel packet"); + let expected = to_craft_frame(parallel.pop().expect("one frame"), presentation, pts).expect("parallel frame"); + assert!(parallel.is_empty()); + assert_eq!((actual.width, actual.height, actual.pts, actual.par, actual.color), (64, 48, pts, (4, 3), expected.color)); + let PixelData::Yuv16 { planes, bits, alpha: Some(alpha), .. } = &actual.data else { panic!("expected 12-bit ProRes with alpha") }; + let PixelData::Yuv16 { planes: expected_planes, bits: expected_bits, alpha: Some(expected_alpha), .. } = &expected.data else { + panic!("expected parallel ProRes with alpha"); + }; + assert_eq!((*bits, *expected_bits), (12, 12)); + assert_eq!(planes, expected_planes); + assert_eq!(alpha, expected_alpha); + assert!(alpha[0] > 0 && alpha[0] < 4_095); + } + + let regular_error = decoder.decode(&[], 0).expect_err("empty ProRes packet").to_string(); + let locked_error = decode_track_packet(&mut decoder, true, &[], 0, prores::decode_frame_with).expect_err("empty ProRes packet").to_string(); + assert_eq!(locked_error, regular_error); + } + + #[test] + fn matroska_display_aspect_reaches_shared_probe_and_frame() { + use craft_media::matroska::{ebml, element_ids::*}; + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + let element = |id, payload: &[u8]| { + let mut bytes = Vec::new(); + ebml::write_id(&mut bytes, id); + ebml::write_size(&mut bytes, payload.len() as u64, 1); + bytes.extend_from_slice(payload); + bytes + }; + + // Generate a single ProRes frame and wrap it using the public Matroska element IDs. + let profile = Profile::Hq; + let frame = Frame::new(16, 12, ChromaFormat::Yuv422, 10, false).expect("ProRes frame"); + let packet = Encoder::new(profile, 16, 12).encode(&frame).expect("encode ProRes"); + let mut block = vec![0x81, 0, 0, 0x80]; // Track 1, timestamp 0, keyframe. + // Matroska omits the eight-byte ProRes size and 'icpf' prefix. + block.extend_from_slice(&packet[8..]); + let cluster = element(CLUSTER, &[element(TIMESTAMP, &[0]), element(SIMPLE_BLOCK, &block)].concat()); + let header = element(EBML, &element(DOC_TYPE, b"matroska")); + + let cases = [(3, (16_u32, 9_u32), (4, 3)), (0, (32, 18), (4, 3)), (4, (16, 9), (1, 1)), (3, (u32::MAX, 1), (1, 1))]; + for (unit, display_size, expected) in cases { + let video = [ + element(PIXEL_WIDTH, &[16]), + element(PIXEL_HEIGHT, &[12]), + element(DISPLAY_UNIT, &[unit]), + element(DISPLAY_WIDTH, &display_size.0.to_be_bytes()), + element(DISPLAY_HEIGHT, &display_size.1.to_be_bytes()), + ] + .concat(); + let track = [ + element(TRACK_NUMBER, &[1]), + element(TRACK_UID, &[1]), + element(TRACK_TYPE, &[1]), + element(CODEC_ID, b"V_PRORES"), + element(CODEC_PRIVATE, &profile.fourcc()), + element(VIDEO, &video), + ] + .concat(); + let tracks = element(TRACKS, &element(TRACK_ENTRY, &track)); + let segment = element(SEGMENT, &[tracks, cluster.clone()].concat()); + let bytes: Arc<[u8]> = [header.clone(), segment].concat().into(); + + let footage = crate::probe::probe_bytes("aspect.mkv", bytes.clone()).expect("public Matroska probe"); + assert_eq!(footage.codec, "ProRes", "must use the shared Matroska route"); + assert_eq!((footage.width, footage.height), (16, 12)); + assert_eq!(footage.pixel_aspect, f64::from(expected.0) / f64::from(expected.1), "display unit {unit}"); + + let source = open_bytes("aspect.mkv", bytes).expect("recognized Matroska").expect("shared Matroska"); + let decoded = source.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode frame"); + assert_eq!(decoded.par.0 * expected.1, decoded.par.1 * expected.0, "display unit {unit}"); + } + } + + #[test] + fn mxf_descriptor_aspect_reaches_shared_probe_and_frame() { + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + let frame = Frame::new(16, 12, ChromaFormat::Yuv422, 10, false).expect("ProRes frame"); + let packet = Encoder::new(Profile::Hq, 16, 12).encode(&frame).expect("encode ProRes"); + for (dar, expected) in [(mxf::Rational::new(16, 9), (4, 3)), (mxf::Rational::new(0, 0), (1, 1))] { + let ids = mxf::write::PackageIds::from_seed("eff-mxf-par", "op1a"); + let mut cfg = mxf::write::WriterConfig::new(mxf::write::Pattern::Op1a, mxf::Rational::new(25, 1), ids); + let mut picture = mxf::write::PictureDesc::new(mxf::write::PictureCoding::ProRes { profile: 4 }, 16, 12); + picture.aspect = dar; + cfg.picture = Some(picture); + let mut writer = mxf::write::MxfWriter::new(std::io::Cursor::new(Vec::new()), cfg).expect("writer"); + writer.push_picture(&packet, mxf::write::FrameInfo::intra()).expect("picture"); + let bytes: Arc<[u8]> = writer.finish().expect("finish").into_inner().into(); + + let file = mxf::open(bytes.as_ref()).expect("demux fixture"); + assert_eq!(file.tracks[0].picture.as_ref().expect("picture descriptor").aspect_ratio, dar); + let footage = crate::probe::probe_bytes("aspect.mxf", bytes.clone()).expect("public probe"); + // The FilmCraft backend labels the same essence "Apple ProRes 422 HQ". + assert_eq!(footage.codec, "ProRes", "must use the shared MXF route"); + assert_eq!(footage.pixel_aspect, f64::from(expected.0) / f64::from(expected.1)); + + let source = open_bytes("aspect.mxf", bytes).expect("recognized MXF").expect("shared MXF"); + assert_eq!(source.info().video.as_ref().expect("video").par, expected); + let decoded = source.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode frame"); + assert_eq!(decoded.par, expected); + } + } + + #[test] + fn mxf_descriptor_aspect_is_bounded_and_yields_to_decoder_sar() { + let wide = mxf::Rational::new(i32::MAX, i32::MAX); + assert_eq!(mxf_picture_par(wide, u32::MAX, u32::MAX), (1, 1)); + assert_eq!(mxf_picture_par(wide, 12, 16), (4, 3)); + assert_eq!(mxf_picture_par(mxf::Rational::new(i32::MAX, 1), 1, u32::MAX), (1, 1)); + assert_eq!(mxf_picture_par(mxf::Rational::new(16, 9), 0, 12), (1, 1)); + + let par = mxf_picture_par(mxf::Rational::new(16, 9), 16, 12); + let presentation = FramePresentation { container_color: None, par, rotation: 0, aperture: None }; + for (sar, expected) in [(None, (4, 3)), (Some((0, 2)), (4, 3)), (Some((2, 1)), (2, 1))] { + let y = Plane::packed(2, 2, 8, Samples::U8(vec![1, 2, 3, 4])).expect("luma"); + let cb = Plane::packed(1, 1, 8, Samples::U8(vec![128])).expect("chroma"); + let cr = Plane::packed(1, 1, 8, Samples::U8(vec![128])).expect("chroma"); + let mut frame = DecodedVideoFrame::new(2, 2, ColorFamily::YCbCr, Subsampling::S420, vec![y, cb, cr], None).expect("decoded frame"); + frame.sar = sar; + assert_eq!(to_craft_frame(frame, presentation, Tick::ZERO).expect("converted").par, expected); + } + } + + #[test] + fn mxf_rational_units() { + assert_eq!(tick_to_rational_units(Tick(craft_time::TICKS_PER_SECOND), 25, 1), 25); + assert_eq!(tick_to_rational_units(Tick(craft_time::TICKS_PER_SECOND), 30000, 1001), 29); + } + + #[test] + fn mxf_routing_leaves_avi_payload_partition_markers_in_avi() { + // Partitions might occur as arbitrary sample bytes in another container. + let mut detected = Vec::new(); + for (padding, kind) in [(0, 3), (66_000, 2)] { + let key = [0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, kind, 0x04, 0x00]; + let mut pcm = vec![0; padding]; + pcm.extend(key); + let mut writer = avi::AviWriter::new( + std::io::Cursor::new(Vec::new()), + vec![avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 1, 16))], + avi::MuxOptions::default(), + ) + .expect("AVI writer"); + writer.write_chunk(0, &pcm, true).expect("PCM chunk"); + let bytes = writer.finish().expect("finish AVI").into_inner(); + detected.push(open_bytes("audio.avi", bytes.into()).and_then(Result::ok).map(|src| src.info().container.clone())); + } + assert_eq!(detected, [Some("avi".to_string()), Some("avi".to_string())]); + } + + #[cfg(any(unix, windows))] + #[test] + fn mxf_routing_opens_a_header_at_the_native_run_in_boundary() { + use crate::stream::{MediaSource, open_source, probe_source}; + + let options = mxf::write::OpAtomPcm { + sample_rate: 48_000, + bits: 16, + channels: 1, + edit_rate: None, + ids: mxf::write::PackageIds::from_seed("mxf-run-in", "pcm"), + timecode: None, + }; + let mut bytes = vec![0xab; 65_535]; + bytes.extend(mxf::write::write_opatom_pcm(&options, &[8192; 480]).expect("write OpAtom PCM")); + let dir = tempfile::tempdir().expect("temporary directory"); + let path = dir.path().join("run-in.mxf"); + std::fs::write(&path, &bytes).expect("write MXF fixture"); + + let memory = open_bytes("run-in.mxf", bytes.into()).expect("recognize in memory").expect("open in memory"); + let expected = memory.audio(0, 16, 48_000).expect("read memory PCM").channels; + assert_eq!(expected[0], vec![0.25; 16]); + + let (disk, _) = open_source(&path).expect("open file"); + let MediaSource::Craft(disk) = disk.expect("open disk MXF") else { panic!("use shared MXF reader on disk") }; + assert_eq!(disk.audio(0, 16, 48_000).expect("read disk PCM").channels, expected); + let probe = probe_source(&path).expect("recognize disk probe").expect("open disk probe"); + assert!(matches!(probe, MediaSource::Craft(src) if src.info().container == "mxf")); + } + + #[test] + fn mxf_start_timecode_converts_mismatched_rates_and_preserves_matching() { + let tc = mxf::Timecode { start: 100, rounded_base: 24, drop_frame: false }; + assert_eq!(mxf_start_timecode(tc, Some(FrameRate::FPS_23_976)), 100); + assert_eq!(mxf_start_timecode(tc, Some(FrameRate::FPS_24)), 100); + assert_eq!(mxf_start_timecode(tc, Some(FrameRate::new(48, 1))), 200); + let df = mxf::Timecode { start: 3000, rounded_base: 30, drop_frame: true }; + assert_eq!(mxf_start_timecode(df, Some(FrameRate::FPS_29_97)), 3000); + assert_eq!(mxf_start_timecode(df, Some(FrameRate::new(60_000, 1001))), 6000); + assert_eq!(mxf_start_timecode(df, None), 3000); + } + + #[test] + fn mxf_start_timecode_rounds_fractional_recorded_frames() { + // Three frames at 25 fps fall at 3.6 frames on a 30 fps track. + let tc = mxf::Timecode { start: 3, rounded_base: 25, drop_frame: false }; + assert_eq!(mxf_start_timecode(tc, Some(FrameRate::FPS_30)), 4); + // Two frames at 24 fps fall exactly halfway between frames 2 and 3. + let half = mxf::Timecode { start: 2, rounded_base: 24, ..tc }; + assert_eq!(mxf_start_timecode(half, Some(FrameRate::FPS_30)), 3); + let integral = mxf::Timecode { start: 5, ..tc }; + assert_eq!(mxf_start_timecode(integral, Some(FrameRate::FPS_30)), 6); + + let negative = mxf::Timecode { start: -100, ..tc }; + assert_eq!(mxf_start_timecode(negative, Some(FrameRate::FPS_30)), -120); + let negative_fraction = mxf::Timecode { start: -3, ..tc }; + assert_eq!(mxf_start_timecode(negative_fraction, Some(FrameRate::FPS_30)), -3); + let fallback = mxf::Timecode { start: i64::MAX - 1, ..tc }; + assert_eq!(mxf_start_timecode(fallback, Some(FrameRate::FPS_50)), i64::MAX - 1); + let too_large = mxf::Timecode { start: i64::MAX, ..tc }; + assert_eq!(mxf_start_timecode(too_large, Some(FrameRate::FPS_50)), i64::MAX); + let extreme = mxf::Timecode { drop_frame: true, ..too_large }; + assert_eq!(mxf_start_timecode(extreme, Some(FrameRate::new(i64::MAX, 1))), i64::MAX); + } + + #[test] + fn mxf_opatom_pcm_reads_windowed_and_resampled_audio() { + let opts = mxf::write::OpAtomPcm { + sample_rate: 48_000, + bits: 16, + channels: 2, + edit_rate: None, + ids: mxf::write::PackageIds::from_seed("eff-mxf-test", "pcm"), + timecode: Some(mxf::write::StartTimecode { frames: 240, rate: mxf::Rational::new(24, 1), drop_frame: false }), + }; + let samples: Vec = (0..4800 * 2).map(|i| ((i * 137) % 16000) - 8000).collect(); + let bytes = mxf::write::write_opatom_pcm(&opts, &samples).expect("write opatom pcm"); + let src = open_bytes("test.mxf", Arc::from(bytes)).expect("recognized").expect("opened"); + let info = src.info(); + assert_eq!(info.container, "mxf"); + assert_eq!(info.kind, MediaKind::AudioOnly); + assert_eq!(info.audio_streams.len(), 1); + assert_eq!(info.audio_streams[0].sample_rate, 48_000); + assert_eq!(info.audio_streams[0].channels, 2); + + // Direct read at t=0 + let buf = src.audio(0, 1024, 48_000).expect("direct read"); + assert_eq!(buf.channels.len(), 2); + assert_eq!(buf.channels[0].len(), 1024); + assert!(buf.channels[0].iter().any(|&v| v.abs() > 0.01)); + + // Negative start and past-end read zero-fill cleanly + let neg = src.audio(-100, 200, 48_000).expect("negative start"); + assert!(neg.channels[0][..100].iter().all(|&v| v == 0.0)); + assert!(neg.channels[0][100..].iter().any(|&v| v.abs() > 0.01)); + let past = src.audio(4700, 200, 48_000).expect("past end"); + assert!(past.channels[0][..100].iter().any(|&v| v.abs() > 0.01)); + assert!(past.channels[0][100..].iter().all(|&v| v == 0.0)); + + // Resampled read + let resampled = src.audio(0, 512, 44_100).expect("resampled"); + assert_eq!(resampled.sample_rate, 44_100); + assert_eq!(resampled.channels[0].len(), 512); + } + + #[test] + fn mxf_video_window_and_sound_trim_helpers() { + let mut cfg = + mxf::write::WriterConfig::new(mxf::write::Pattern::Op1a, mxf::Rational::new(25, 1), mxf::write::PackageIds::from_seed("eff-mxf-vid", "op1a")); + cfg.picture = Some(mxf::write::PictureDesc::new(mxf::write::PictureCoding::Avc { profile_idc: 66, intra: false }, 16, 16)); + cfg.sound = vec![mxf::write::SoundDesc { sample_rate: 48_000, channels: 1, bits: 16 }]; + let mut w = mxf::write::MxfWriter::new(std::io::Cursor::new(Vec::new()), cfg).expect("writer"); + let pcm = mxf::write::encode_pcm(&[vec![0.1f32; 1920]], 16); + w.push_picture(&[0x00, 0x00, 0x00, 0x01, 0x65], mxf::write::FrameInfo::intra()).expect("pic0"); + w.push_sound(0, &pcm).expect("snd0"); + w.push_picture(&[0x00, 0x00, 0x00, 0x01, 0x41], mxf::write::FrameInfo::intra()).expect("pic1"); + w.push_sound(0, &pcm).expect("snd1"); + let raw_bytes = w.finish().expect("finish").into_inner(); + let arc_bytes: Arc<[u8]> = Arc::from(raw_bytes.clone()); + let mxf_bytes: SharedBytes = Arc::new(arc_bytes); + let mut file = mxf::open(&*mxf_bytes).expect("open mxf"); + + // Exercise ContainerFile::Mxf video helpers and trimmed sound window. + file.tracks[0].origin = 1; + file.tracks[0].duration = Some(1); + file.tracks[1].origin = 1; + file.tracks[1].duration = Some(1); + let (win_start, win_len) = mxf_sound_window(&file.tracks[1]); + assert_eq!((win_start, win_len), (1920, 1920)); + + // Reuse the demuxed writer fixture and vary just its material-picture metadata. + // The writer itself authors neither an overclaimed nor an absent duration here. + assert_eq!(file.tracks[0].display_order, [0, 1]); + let one_frame = Tick::from_units(40, 1_000); + let beyond = Tick::from_units(80, 1_000); + for (origin, declared, expected_duration, expected_target) in + [(1, Some(2), one_frame, Some((1, 1))), (1, None, one_frame, Some((1, 1))), (1, Some(0), Tick::ZERO, None), (2, Some(2), Tick::ZERO, None)] + { + let mut edited = file.clone(); + edited.tracks[0].origin = origin; + edited.tracks[0].duration = declared; + assert_eq!(edited.tracks[0].first_edit_unit(), origin); + let source = open_parsed_mxf("op1a.mxf", mxf_bytes.clone(), edited.clone()).expect("shared MXF").expect("open parsed"); + assert_eq!(source.info().duration, expected_duration, "origin {origin}, duration {declared:?}"); + let container = ContainerFile::Mxf(Box::new(edited)); + assert_eq!(container.target_sample(0, Tick::ZERO), expected_target); + assert_eq!(container.target_sample(0, beyond), expected_target); + } + + let container = ContainerFile::Mxf(Box::new(file)); + assert_eq!(container.sample_count(0), 2); + assert_eq!(container.target_sample(0, Tick::ZERO), Some((1, 1))); + assert_eq!(container.sync_sample_before(0, 1), 1); + assert_eq!(container.sample_pts(0, 1), 1); + assert_eq!(container.pts_to_tick(0, 1), Tick::ZERO); + + // Exercise open_mxf video+sound path on valid Op1a Avc+PCM. + let src = open_bytes("op1a.mxf", Arc::from(raw_bytes)).expect("recognized").expect("opened"); + assert_eq!(src.info().container, "mxf"); + assert_eq!(src.info().audio_streams.len(), 1); + assert!(open_bytes("op1a.mxf", Arc::from(vec![0u8; 4])).is_none()); + } + + #[test] + fn standalone_wav_opens_seeks_and_resamples_via_craft_audio() { + // Minimal 48 kHz stereo 16-bit PCM WAV with 4800 frames (0.1s). + let frames = 4800u32; + let data_bytes = frames * 4; + let mut wav = Vec::with_capacity(44 + data_bytes as usize); + wav.extend_from_slice(b"RIFF"); + wav.extend_from_slice(&(36 + data_bytes).to_le_bytes()); + wav.extend_from_slice(b"WAVEfmt "); + wav.extend_from_slice(&16u32.to_le_bytes()); + wav.extend_from_slice(&1u16.to_le_bytes()); + wav.extend_from_slice(&2u16.to_le_bytes()); + wav.extend_from_slice(&48_000u32.to_le_bytes()); + wav.extend_from_slice(&(48_000u32 * 4).to_le_bytes()); + wav.extend_from_slice(&4u16.to_le_bytes()); + wav.extend_from_slice(&16u16.to_le_bytes()); + wav.extend_from_slice(b"data"); + wav.extend_from_slice(&data_bytes.to_le_bytes()); + for i in 0..frames * 2 { + let s = (((i as i32 * 257) % 16000) - 8000) as i16; + wav.extend_from_slice(&s.to_le_bytes()); + } + + let wav = Arc::<[u8]>::from(wav); + let src = open_bytes("tone.wav", wav.clone()).expect("recognized").expect("opened"); + let info = src.info(); + assert_eq!(info.container, "wav"); + assert_eq!(info.kind, MediaKind::AudioOnly); + assert_eq!(info.audio_streams[0].sample_rate, 48_000); + assert_eq!(info.audio_streams[0].bits_per_sample, Some(16)); + + let head = src.audio(0, 512, 48_000).expect("head"); + assert_eq!(head.channels[0].len(), 512); + let tail = src.audio(4000, 512, 48_000).expect("forward seek"); + assert!(tail.channels[0].iter().any(|&v| v.abs() > 0.01)); + let back = src.audio(0, 512, 48_000).expect("backward seek"); + assert_eq!(head.channels[0], back.channels[0]); + let neg = src.audio(-50, 100, 48_000).expect("negative start"); + assert!(neg.channels[0][..50].iter().all(|&v| v == 0.0)); + let resampled = src.audio(0, 256, 44_100).expect("resampled"); + assert_eq!(resampled.sample_rate, 44_100); + assert_eq!(resampled.channels[0].len(), 256); + + let cold = open_bytes("tone.wav", wav).expect("recognized").expect("opened"); + let alone = cold.audio(1, 1, 44_100).expect("single output frame"); + // Output frame 1 is at input frame 160/147. The left channel's + // input frames 1 and 2 contain -7486 and -6972 in signed 16-bit PCM. + let expected = (-7486.0 + (13.0 / 147.0) * 514.0) / 32768.0; + assert!((alone.channels[0][0] - expected).abs() < 1e-7, "absolute fractional phase"); + for (single, block) in alone.channels.iter().zip(&resampled.channels) { + assert_eq!(single[0], block[1], "reading a frame alone must match a longer block"); + } + let pre_roll = cold.audio(-1, 3, 44_100).expect("negative output window"); + for (shifted, block) in pre_roll.channels.iter().zip(&resampled.channels) { + assert_eq!(shifted[0], 0.0, "silence before frame zero"); + assert_eq!(&shifted[1..], &block[..2], "crossing frame zero must preserve phase"); + } + // Frame 3675 is exactly native frame 4000, where the left ramp is zero. + let crossing = cold.audio(3670, 6, 44_100).expect("cross a zero sample"); + let zero = cold.audio(3675, 1, 44_100).expect("read the zero sample alone"); + assert_eq!(crossing.channels[0][5], 0.0, "a fractional start must not leak into an integral sample"); + assert_eq!(crossing.channels[0][5], zero.channels[0][0]); + + let after_end = cold.audio(4410, 2, 44_100).expect("after EOF"); + assert!(after_end.channels.iter().flatten().all(|&sample| sample == 0.0)); + let out_of_range = cold.audio(i64::MAX / 2, 1, 1).expect("unrepresentable source origin"); + assert!(out_of_range.channels.iter().flatten().all(|&sample| sample == 0.0), "an unreachable origin must not replay frame zero"); + } + + /// 1024-sample frames at 48 kHz stamped to the nearest millisecond, then back in samples. + fn ms_stamps(count: i64) -> Vec { + (0..count).map(|k| (k * 1024 * 1000 + 24_000) / 48_000 * 48).collect() + } + + fn timed(stamps: &[i64], samples: Option) -> Vec { + stamps.iter().map(|&stamp| PacketTime { stamp, stamped: true, samples }).collect() + } + + #[test] + fn rounded_stamps_give_back_to_back_packets() { + let stamps = ms_stamps(200); + assert_eq!(&stamps[..4], [0, 1008, 2064, 3072]); + let starts = contiguous_starts(timed(&stamps, Some(1024)), 512); + assert_eq!(starts, (0..200).map(|k| k * 1024).collect::>()); + } + + #[test] + fn real_gaps_and_overlaps_resynchronise() { + // A 100 ms gap after packet 3, then a packet stamped 600 samples early. + let mut stamps: Vec = (0..8).map(|k| k * 1024).collect(); + for s in &mut stamps[4..] { + *s += 4800; + } + stamps[7] -= 600; + let starts = contiguous_starts(timed(&stamps, Some(1024)), 512); + assert_eq!(starts, [0, 1024, 2048, 3072, 8896, 9920, 10944, 11368]); + // Within the tolerance: runs on. + stamps[7] += 200; + assert_eq!(contiguous_starts(timed(&stamps, Some(1024)), 512)[7], 11968); + } + + #[test] + fn unstamped_packets_follow_on_and_unknown_lengths_resynchronise() { + let packets = [0, 1024, 1024, 1024, 4096].map(|stamp| PacketTime { stamp, stamped: true, samples: Some(1024) }); + let mut laced = packets; + laced[2].stamped = false; + laced[3].stamped = false; + assert_eq!(contiguous_starts(laced, 512), [0, 1024, 2048, 3072, 4096]); + let mut unknown = timed(&[0, 1024, 2100, 3124], Some(1024)); + unknown[1].samples = None; + assert_eq!(contiguous_starts(unknown, 512), [0, 1024, 2100, 3124]); + } + + #[test] + fn hostile_values_stay_finite() { + let packets = [ + PacketTime { stamp: i64::MAX, stamped: true, samples: Some(i64::MAX) }, + PacketTime { stamp: i64::MIN, stamped: false, samples: Some(-5) }, + PacketTime { stamp: 0, stamped: true, samples: Some(i64::MIN) }, + PacketTime { stamp: 7, stamped: true, samples: None }, + ]; + assert_eq!(contiguous_starts(packets, i64::MIN).len(), 4); + assert_eq!(contiguous_starts(packets, i64::MAX).len(), 4); + assert!(contiguous_starts([], 512).is_empty()); + } + + #[test] + fn avi_video_duration_uses_indexed_frames() { + use craft_video::prores::{ChromaFormat, ColorInfo as ProResColor, Encoder, EncoderConfig, Frame as ProResFrame, Interlace, Profile}; + + let mut config = EncoderConfig::new(Profile::P4444, 16, 16); + config.encode_alpha = false; + config.threads = false; + let mut encoder = Encoder::with_config(config); + let stream = avi::StreamSpec::Video(avi::VideoSpec::new(*b"ap4h", 16, 16, 30_000, 1_001)); + let mut writer = avi::AviWriter::new(std::io::Cursor::new(Vec::new()), vec![stream], avi::MuxOptions::default()).expect("AVI writer"); + for luma in [256, 768] { + let frame = ProResFrame { + width: 16, + height: 16, + chroma: ChromaFormat::Yuv444, + bit_depth: 10, + y: vec![luma; 256], + cb: vec![512; 256], + cr: vec![512; 256], + alpha: None, + interlace: Interlace::Progressive, + color: ProResColor::default(), + aspect_ratio: 0, + frame_rate_code: 0, + }; + writer.write_chunk(0, &encoder.encode(&frame).expect("encode ProRes"), true).expect("write picture"); + } + let mut bytes = writer.finish().expect("finish AVI").into_inner(); + // dwLength is 32 bytes into the strh payload, after the 8-byte chunk header. + let length_offset = bytes.windows(4).position(|tag| tag == b"strh").expect("stream header") + 8 + 32; + let frame_period = Tick::from_rational(1, 1_001, 30_000); + for declared_length in [1u32, 2, 100] { + bytes[length_offset..length_offset + 4].copy_from_slice(&declared_length.to_le_bytes()); + let stream = &avi::open(bytes.as_slice()).expect("demux fixture").streams[0]; + assert_eq!(stream.length, declared_length); + assert_eq!(stream.chunks.len(), 2); + let input: Arc<[u8]> = Arc::from(bytes.as_slice()); + let footage = crate::probe::probe_bytes("indexed.avi", input.clone()).expect("public probe"); + assert_eq!(footage.codec, "ProRes"); + assert_eq!(footage.duration, effectcraft_time::Tick::from_rational(2, 1_001, 30_000), "declared length {declared_length}"); + + let source = open_bytes("indexed.avi", input).expect("recognized AVI").expect("shared AVI"); + let last = source.video_frame(FrameRequest { time: frame_period, scale: 1.0 }).expect("seek to last picture"); + let PixelData::Yuv16 { planes: [y, ..], .. } = &last.data else { + panic!("expected the decoded ProRes luma plane"); + }; + assert!(y[0] > 512, "expected the brighter second picture"); + } + } + + #[test] + fn avi_and_mpeg_helpers_and_in_memory_route() { + assert_eq!(tick_to_rational_units(Tick(craft_time::TICKS_PER_SECOND), 24, 1), 24); + assert_eq!(tick_to_rational_units(Tick(-1), 24, 1), 0); + assert_eq!(estimate_mpeg_frame_rate_pts([0, 3000, 6000]), FrameRate::FPS_30); + assert_eq!(estimate_mpeg_frame_rate(&[]), FrameRate::FPS_30); + + let streams = vec![avi::StreamSpec::Video(avi::VideoSpec::new(*b"H264", 16, 16, 24, 1)), avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 2, 16))]; + let mut w = avi::AviWriter::new(std::io::Cursor::new(Vec::new()), streams, avi::MuxOptions::default()).expect("avi writer"); + let pcm = vec![0x10u8; 2000 * 4]; + w.write_chunk(0, &[0x00, 0x00, 0x00, 0x01, 0x65], true).expect("v0"); + w.write_chunk(1, &pcm, true).expect("a0"); + w.write_chunk(0, &[0x00, 0x00, 0x00, 0x01, 0x41], false).expect("v1"); + w.write_chunk(1, &pcm, true).expect("a1"); + let raw = w.finish().expect("finish").into_inner(); + let avi_file = avi::open(raw.as_slice()).expect("open avi"); + let avi_container = ContainerFile::Avi(Box::new(avi_file)); + assert_eq!(avi_container.sample_count(0), 2); + assert_eq!(avi_container.target_sample(0, Tick::ZERO), Some((0, 0))); + assert_eq!(avi_container.sync_sample_before(0, 1), 0); + assert_eq!(avi_container.sample_pts(0, 1), 1); + assert!(avi_container.pts_to_tick(0, 1) > Tick::ZERO); + + let src = open_bytes("test.avi", Arc::from(raw)).expect("recognized").expect("opened"); + assert_eq!(src.info().container, "avi"); + assert_eq!(src.info().audio_streams[0].sample_rate, 48_000); + let audio = src.audio(0, 512, 48_000).expect("avi audio"); + assert_eq!(audio.channels[0].len(), 512); + + // Audio-only AVI route. + let mut wa = + avi::AviWriter::new(std::io::Cursor::new(Vec::new()), vec![avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 1, 16))], avi::MuxOptions::default()) + .expect("audio avi writer"); + wa.write_chunk(0, &pcm_s16le_bytes(4_000, 1024), true).expect("a0"); + let audio_avi = + open_bytes("audio.avi", Arc::from(wa.finish().expect("finish audio avi").into_inner())).expect("recognized audio avi").expect("opened audio avi"); + assert_eq!(audio_avi.info().kind, MediaKind::AudioOnly); + assert_eq!(audio_avi.audio(0, 256, 48_000).expect("audio avi read").channels[0].len(), 256); + + // MPEG-TS route and ContainerFile::Mpeg helpers. + let mut ts = mpegts::mux::Muxer::new(Vec::new(), mpegts::mux::Config::default(), &[mpegts::mux::Stream::new(0x100, mpegts::mux::Codec::H264)]) + .expect("ts muxer"); + ts.write_frame(0, &mpegts::mux::Frame { data: &[0x00, 0x00, 0x00, 0x01, 0x65, 0x88], pts: 90_000, dts: None, key: true }).expect("ts f0"); + ts.write_frame(0, &mpegts::mux::Frame { data: &[0x00, 0x00, 0x00, 0x01, 0x41, 0x9A], pts: 93_000, dts: None, key: false }).expect("ts f1"); + ts.write_frame(0, &mpegts::mux::Frame { data: &[0x00, 0x00, 0x00, 0x01, 0x41, 0x9A], pts: 96_000, dts: None, key: false }).expect("ts f2"); + ts.write_frame(0, &mpegts::mux::Frame { data: &[0x00, 0x00, 0x00, 0x01, 0x41, 0x9A], pts: 99_000, dts: None, key: false }).expect("ts f3"); + let ts_bytes = ts.finish().expect("finish ts"); + let ts_file = mpegts::open(ts_bytes.as_slice()).expect("open ts"); + let ts_container = ContainerFile::Mpeg { file: Box::new(ts_file), origin_pts: 90_000 }; + assert!(ts_container.target_sample(0, Tick::ZERO).is_some()); + let _ = ts_container.sync_sample_before(0, 1); + assert_eq!(ts_container.sample_pts(0, 0), 90_000); + assert_eq!(ts_container.pts_to_tick(0, 90_000), Tick::ZERO); + let ts_src = open_bytes("test.ts", Arc::from(ts_bytes)).expect("recognized ts").expect("opened ts"); + assert_eq!(ts_src.info().container, "MPEG-2 TS"); + } + + fn generated_two_frame_ts() -> Vec { + use craft_video::h264::{Encoder, EncoderConfig, YuvFrame}; + use mpegts::mux::{Codec, Config, Frame, Muxer, Stream}; + + let mut config = EncoderConfig::new(16, 16, 25, 1); + config.intra_only = true; + config.threads = 1; + let mut encoder = Encoder::new(config).unwrap(); + let mut packets = Vec::new(); + let uv = [128; 8 * 8]; + for (pts, level) in [(90_000, 48), (93_600, 192)] { + let y = [level; 16 * 16]; + packets.extend(encoder.encode(&YuvFrame { y: &y, u: &uv, v: &uv, y_stride: 16, uv_stride: 8 }, pts).unwrap()); + } + packets.extend(encoder.flush()); + assert_eq!(packets.len(), 2); + let mut mux = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + for packet in packets { + assert!(packet.keyframe); + mux.write_frame(0, &Frame { data: &packet.data, pts: packet.pts, dts: Some(packet.dts), key: true }).unwrap(); + } + mux.finish().unwrap() + } + + #[test] + fn shared_video_read_observes_filmcraft_request_cancellation() { + use std::sync::atomic::AtomicBool; + + let source = crate::stream::open_bytes("cancelled.ts", generated_two_frame_ts().into()).unwrap(); + assert!(matches!(source, crate::stream::MediaSource::Craft(_))); + let cancel = Arc::new(AtomicBool::new(true)); + let request = || source.video_frame(effectcraft_time::Tick::ZERO, 1.0); + let interrupted = filmcraft_media::cancel::with_cancel(&cancel, request); + assert!(matches!(interrupted, Err(crate::MediaError::Cancelled))); + + let interrupted = craft_media_source::cancel::with_cancel(&cancel, request); + assert!(matches!(interrupted, Err(crate::MediaError::Cancelled))); + assert!(request().is_ok()); + } + + #[test] + fn regular_video_only_h264_ts_duration_keeps_the_last_picture_playable() { + let bytes = generated_two_frame_ts(); + let parsed = mpegts::open(bytes.as_slice()).unwrap(); + assert_eq!(parsed.streams.len(), 1); + assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings); + assert_eq!(parsed.streams[0].skipped_bytes, 0); + assert!(clean_ts_packet_index(&parsed, bytes.as_slice())); + let units = &parsed.streams[0].units; + assert_eq!(units.iter().map(|unit| unit.pts).collect::>(), [Some(90_000), Some(93_600)]); + + let bytes: Arc<[u8]> = bytes.into(); + let opened = crate::stream::open_bytes("final-picture.ts", bytes.clone()).unwrap(); + assert!(matches!(opened, crate::stream::MediaSource::Craft(_))); + let film = filmcraft_codecs::open_bytes("final-picture.ts", bytes.clone()).unwrap(); + let rate = effectcraft_time::FrameRate::FPS_25; + assert_eq!(film.info().duration.0, rate.tick_of(2).0); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("final-picture.ts"); + std::fs::write(&path, bytes.as_ref()).unwrap(); + let footage = crate::probe(&path).unwrap(); + let pool = crate::MediaPool::new(); + let first = pool.frame_at(&footage, effectcraft_time::Tick::ZERO).unwrap(); + let last = pool.frame_at(&footage, rate.tick_of(1)).unwrap(); + assert!(last.get(8, 8)[0] > first.get(8, 8)[0] + 0.25, "the earlier duration clamped the last request to the first picture"); + assert_eq!(footage.frame_rate, rate); + assert!(!footage.has_audio); + assert_eq!(footage.duration, rate.tick_of(2)); + } + + #[test] + fn ts_damaged_or_partial_tail_keeps_the_earlier_indexed_duration() { + let mut transport_error = [0xff; 188]; + // A dropped error-marked packet does not alter the two indexed pictures. + transport_error[..4].copy_from_slice(&[0x47, 0x9f, 0xff, 0x10]); + for (tail, warned) in [(&transport_error[..], true), (&[0x47][..], false)] { + let mut bytes = generated_two_frame_ts(); + bytes.extend_from_slice(tail); + let parsed = mpegts::open(bytes.as_slice()).unwrap(); + assert_eq!(parsed.warnings.iter().any(|warning| warning.contains("transport error indicator")), warned); + assert_eq!(parsed.streams[0].units.len(), 2); + assert_eq!(regular_ts_picture_end(&parsed.streams[0].units, 90_000, FrameRate::FPS_25), Some(Tick(craft_time::TICKS_PER_SECOND * 2 / 25))); + assert!(!clean_ts_packet_index(&parsed, bytes.as_slice())); + // The same shared route still opens and retains its prior duration. + let source = crate::stream::open_bytes("damaged-tail.ts", bytes.into()).unwrap(); + let crate::stream::MediaSource::Craft(source) = source else { panic!("existing shared route") }; + assert_eq!(source.info().duration, Tick(craft_time::TICKS_PER_SECOND / 25)); + } + } + + #[test] + fn ts_picture_end_requires_complete_exact_regular_stamps() { + let bytes = generated_two_frame_ts(); + let parsed = mpegts::open(bytes.as_slice()).unwrap(); + let units = &parsed.streams[0].units; + let rate = FrameRate::FPS_25; + assert_eq!(regular_ts_picture_end(units, 90_000, rate), Some(Tick(craft_time::TICKS_PER_SECOND * 2 / 25))); + assert_eq!(regular_ts_picture_end(&units[..1], 90_000, rate), None); + assert_eq!(regular_ts_picture_end(units, 89_999, rate), None); + assert_eq!(regular_ts_picture_end(units, 90_000, FrameRate::FPS_30), None); + + let mut nonkey = units.clone(); + nonkey[0].key = false; + assert_eq!(regular_ts_picture_end(&nonkey, 90_000, rate), None); + let mut missing = units.clone(); + missing[1].pts = None; + assert_eq!(regular_ts_picture_end(&missing, 90_000, rate), None); + let mut irregular = units.clone(); + let mut third = units[1]; + third.pts = Some(97_201); + irregular.push(third); + assert_eq!(regular_ts_picture_end(&irregular, 90_000, rate), None); + + let mut oversized = units.clone(); + oversized[1].size = mpegts::MAX_UNIT_BYTES + 1; + assert_eq!(regular_ts_picture_end(&oversized, 90_000, rate), None); + oversized[1].size = mpegts::MAX_UNIT_BYTES; + assert!(regular_ts_picture_end(&oversized, 90_000, rate).is_some()); + oversized[1].size = 0; + assert_eq!(regular_ts_picture_end(&oversized, 90_000, rate), None); + + let mut overflow = units.clone(); + overflow[0].pts = Some(i64::MAX - 3_600); + overflow[1].pts = Some(i64::MAX); + assert_eq!(regular_ts_picture_end(&overflow, i64::MAX - 3_600, rate), None); + } + + fn pcm_s16le_bytes(sample: i16, count: usize) -> Vec { + std::iter::repeat_n(sample.to_le_bytes(), count).flatten().collect() + } + + #[test] + fn audio_only_avi_counts_complete_indexed_pcm_blocks() { + let stream = avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 1, 16)); + let mut writer = avi::AviWriter::new(std::io::Cursor::new(Vec::new()), vec![stream], avi::MuxOptions::default()).expect("AVI writer"); + writer.write_chunk(0, &pcm_s16le_bytes(8_192, 7), true).expect("first chunk"); + writer.write_chunk(0, &pcm_s16le_bytes(16_384, 13), true).expect("second chunk"); + let mut bytes = writer.finish().expect("finish AVI").into_inner(); + // dwLength follows the AVI stream header's first 32 payload bytes. + let length_offset = bytes.windows(4).position(|tag| tag == b"strh").expect("stream header") + 8 + 32; + let mut durations = Vec::new(); + for declared_length in [1u32, 20, 200] { + bytes[length_offset..length_offset + 4].copy_from_slice(&declared_length.to_le_bytes()); + let stream = &avi::open(bytes.as_slice()).expect("demux fixture").streams[0]; + assert_eq!(stream.length, declared_length); + assert_eq!(stream.chunks.len(), 2); + let input: Arc<[u8]> = Arc::from(bytes.as_slice()); + let footage = crate::probe::probe_bytes("indexed-pcm.avi", input.clone()).expect("public probe"); + assert!(footage.has_audio && !footage.has_video); + durations.push(footage.duration); + + let source = open_bytes("indexed-pcm.avi", input).expect("recognized AVI").expect("shared AVI"); + let tail = source.audio(19, 2, 48_000).expect("read final sample and EOF"); + assert_eq!(tail.channels[0], [0.5, 0.0]); + } + assert_eq!(durations, [effectcraft_time::Tick::from_units(20, 48_000); 3]); + } + + #[test] + fn matroska_duration_follows_presentation_order() { + use craft_media::matroska::{MkvWriter, MuxOptions, TrackKind, TrackSpec, ebml, element_ids}; + use craft_video::h264::{Encoder, EncoderConfig, PacketFormat, Profile, YuvFrame}; + use std::io::Cursor; + + fn child(data: &[u8], id: u32) -> ebml::Elem<'_> { + ebml::Children::new(data).find(|element| element.id == id).expect("Matroska element") + } + + // Generate three distinct pictures, with the B-picture coded after its future reference. + const PERIOD_NS: i64 = 40_000_000; + let mut cfg = EncoderConfig::new(16, 16, 25, 1); + cfg.profile = Profile::High; + cfg.bframes = 1; + cfg.format = PacketFormat::LengthPrefixed; + let mut encoder = Encoder::new(cfg).expect("H.264 encoder"); + let mut track = TrackSpec::new(TrackKind::Video, "V_MPEG4/ISO/AVC"); + track.codec_private = encoder.avcc(); + track.video_size = Some((16, 16)); + track.default_duration_ns = Some(PERIOD_NS as u64); + let mut mux = MkvWriter::new(Cursor::new(Vec::new()), vec![track], MuxOptions::default()).expect("Matroska writer"); + let mut packets = Vec::new(); + for (pts, luma) in [32, 96, 160].into_iter().enumerate() { + let pic = YuvFrame { y: &[luma; 256], u: &[128; 64], v: &[128; 64], y_stride: 16, uv_stride: 8 }; + packets.extend(encoder.encode(&pic, pts as i64).expect("encode picture")); + } + packets.extend(encoder.flush()); + for packet in packets { + mux.write_frame(0, packet.pts * PERIOD_NS, packet.keyframe, &packet.data, None).expect("write picture"); + } + let mut bytes = mux.finish().expect("finish Matroska").into_inner(); + + let (offset, header_len, payload_len) = { + let segment = child(&bytes, element_ids::SEGMENT); + let info = child(segment.data, element_ids::INFO); + let duration = child(info.data, element_ids::DURATION); + let offset = segment.offset + segment.header_len + info.offset + info.header_len + duration.offset; + (offset, duration.header_len, duration.data.len()) + }; + let end = offset + header_len + payload_len; + // Give the declaration a distinct value to check that it takes precedence. + bytes[offset + header_len..end].copy_from_slice(&160.0_f64.to_be_bytes()); + let declared = crate::probe::probe_bytes("duration.mkv", Arc::from(bytes.clone())).expect("probe declared duration"); + assert_eq!(declared.duration.0, Tick::from_units(160, 1_000).0); + + // Replace Duration with equally sized padding to keep all indexed file offsets. + let mut padding = Vec::new(); + ebml::write_id(&mut padding, element_ids::VOID); + let size_len = header_len - padding.len(); + ebml::write_size(&mut padding, payload_len as u64, size_len); + padding.resize(end - offset, 0); + bytes[offset..end].copy_from_slice(&padding); + let file = matroska::open(bytes.as_slice()).expect("demux Matroska"); + assert_eq!(file.info.duration, None); + assert_eq!(file.tracks[0].samples.iter().map(|sample| sample.pts).collect::>(), [0, 80, 40]); + + let bytes: Arc<[u8]> = bytes.into(); + let footage = crate::probe::probe_bytes("duration.mkv", bytes.clone()).expect("probe inferred duration"); + assert_eq!(footage.codec, "H.264", "must use the shared route"); + assert_eq!(footage.duration.0, Tick::from_units(120, 1_000).0); + let source = open_bytes("duration.mkv", bytes).expect("recognized Matroska").expect("shared Matroska"); + let time = Tick::from_units(80, 1_000); + let picture = source.video_frame(FrameRequest { time, scale: 1.0 }).expect("read final presented picture"); + assert_eq!(picture.pts, time); + } + + #[test] + fn matroska_durationless_lace_variable_pcm_preserves_all_blocks() { + use std::io::Cursor; + + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_PCM/INT/LIT"); + track.audio = Some((48_000.0, 1, Some(16))); + let mut mux = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default()).unwrap(); + let blocks = [(8_000i16, 120usize), (-16_000i16, 200usize), (24_000i16, 80usize), (4_000i16, 100usize)]; + let pts_ns = [0i64, 2_000_000, 4_000_000, 8_333_333]; + for ((val, len), pts) in blocks.iter().zip(pts_ns) { + mux.write_frame(0, pts, true, &pcm_s16le_bytes(*val, *len), None).unwrap(); + } + let bytes = mux.finish().unwrap().into_inner(); + let mut mkv = matroska::open(bytes.as_slice()).unwrap(); + // Simulate a durationless lace for blocks 0..3 sharing block 0's timestamp. + let base_pts = mkv.tracks[0].samples[0].pts; + for (lace, s) in mkv.tracks[0].samples[..3].iter_mut().enumerate() { + s.pts = base_pts; + s.duration = 0; + s.lace = lace as u16; + } + let params = mkv.tracks[0].codec_params(); + let file = ContainerFile::Matroska(Box::new(mkv)); + let (mut tracks, _) = open_audio_tracks(&file, &bytes, [(0, 4, params.clone(), 0)]).unwrap(); + + let decode = |track: &mut AudioTrackEntry, start: i64, frames: usize| { + let (preroll, state) = track.decoder_parts(); + decode_audio_range(&file, &bytes, 0, 48_000, 1, preroll, state, start, frames).unwrap() + }; + + let full = decode(&mut tracks[0], 0, 500); + assert_eq!(full[0].len(), 500); + // Each block's samples remain intact at their cumulative offsets (0..120, 120..320, 320..400, 400..500). + assert!((full[0][0] - (8_000.0 / 32_768.0)).abs() < 1e-4); + assert!((full[0][120] - (-16_000.0 / 32_768.0)).abs() < 1e-4); + assert!((full[0][320] - (24_000.0 / 32_768.0)).abs() < 1e-4); + assert!((full[0][400] - (4_000.0 / 32_768.0)).abs() < 1e-4); + + // Chunked sequential reads and a backward seek into the lace must match the full read. + let (mut chunked_tracks, _) = open_audio_tracks(&file, &bytes, [(0, 4, params, 0)]).unwrap(); + let mut chunked = Vec::new(); + for (start, frames) in [(0, 150), (150, 200), (350, 150)] { + chunked.extend_from_slice(&decode(&mut chunked_tracks[0], start, frames)[0]); + } + assert_eq!(chunked, full[0]); + + let rewound = decode(&mut tracks[0], 200, 250); + assert_eq!(rewound[0], full[0][200..450]); + } + + #[test] + fn narrow_read_includes_overlapping_packet_like_wider_read() { + use std::io::Cursor; + + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_PCM/INT/LIT"); + track.audio = Some((48_000.0, 1, Some(16))); + let mut mux = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default()).unwrap(); + mux.write_frame(0, 0, true, &pcm_s16le_bytes(8_000, 1024), None).unwrap(); + mux.write_frame(0, 10_666_667, true, &pcm_s16le_bytes(-16_000, 1024), None).unwrap(); + let bytes = mux.finish().unwrap().into_inner(); + let mkv = matroska::open(bytes.as_slice()).unwrap(); + let params = mkv.tracks[0].codec_params(); + let file = ContainerFile::Matroska(Box::new(mkv)); + + let open_with_overlap = || { + let (mut tracks, _) = open_audio_tracks(&file, &bytes, [(0, 2, params.clone(), 0)]).unwrap(); + tracks[0].decoder_parts().1.audio_starts = AudioStarts::complete(vec![0, 512]); + tracks + }; + let decode = |track: &mut AudioTrackEntry, start: i64, frames: usize| { + let (preroll, state) = track.decoder_parts(); + decode_audio_range(&file, &bytes, 0, 48_000, 1, preroll, state, start, frames).unwrap() + }; + + let mut wide_tracks = open_with_overlap(); + let wide = decode(&mut wide_tracks[0], 0, 1536); + + // Narrow read [0, 600) ends before packet 0's 1024-sample tail, yet must include packet 1 at 512. + let mut narrow_tracks = open_with_overlap(); + let narrow = decode(&mut narrow_tracks[0], 0, 600); + assert_eq!(narrow[0], wide[0][..600]); + assert!((narrow[0][0] - (8_000.0 / 32_768.0)).abs() < 1e-4); + assert!((narrow[0][512] - (-16_000.0 / 32_768.0)).abs() < 1e-4); + + // Chunked reads and a backward seek over the same interval must also match. + let mut chunked_tracks = open_with_overlap(); + let mut chunked = Vec::new(); + for (start, frames) in [(0, 300), (300, 300)] { + chunked.extend_from_slice(&decode(&mut chunked_tracks[0], start, frames)[0]); + } + assert_eq!(chunked, wide[0][..600]); + + let rewound = decode(&mut wide_tracks[0], 0, 600); + assert_eq!(rewound[0], wide[0][..600]); + } + + #[test] + fn container_audio_preserves_fractional_resampling_phase_across_seeks() { + let mut mux = + avi::AviWriter::new(std::io::Cursor::new(Vec::new()), vec![avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 1, 16))], avi::MuxOptions::default()) + .unwrap(); + let mut pcm = Vec::with_capacity(4800 * 2); + for i in 0..4800i32 { + // Frame 4000 is exactly 0 so output frame 3675 (at 44.1 kHz) lands on 0.0. + let sample = ((i - 4000) * 5).clamp(-32767, 32767) as i16; + pcm.extend_from_slice(&sample.to_le_bytes()); + } + mux.write_chunk(0, &pcm, true).unwrap(); + let bytes: Arc<[u8]> = Arc::from(mux.finish().unwrap().into_inner()); + + let src = open_bytes("ramp.avi", bytes.clone()).expect("recognized").expect("opened"); + let resampled = src.audio(0, 256, 44_100).expect("resampled"); + + let cold = open_bytes("ramp.avi", bytes).expect("recognized").expect("opened"); + let alone = cold.audio(1, 1, 44_100).expect("single output frame"); + // Output frame 1 at 44.1 kHz is native frame 160/147 (between native 1 and 2: -19995 and -19990). + let expected = (-19995.0 + (13.0 / 147.0) * 5.0) / 32768.0; + assert!((alone.channels[0][0] - expected).abs() < 1e-7, "absolute fractional phase"); + assert_eq!(alone.channels[0][0], resampled.channels[0][1], "single-frame seek matches block"); + + let pre_roll = cold.audio(-1, 3, 44_100).expect("negative output window"); + assert_eq!(pre_roll.channels[0][0], 0.0, "silence before frame zero"); + assert_eq!(&pre_roll.channels[0][1..], &resampled.channels[0][..2], "crossing frame zero preserves phase"); + + let crossing = cold.audio(3670, 6, 44_100).expect("cross zero sample"); + let zero = cold.audio(3675, 1, 44_100).expect("zero sample alone"); + assert_eq!(crossing.channels[0][5], 0.0); + assert_eq!(crossing.channels[0][5], zero.channels[0][0]); + + let after_end = cold.audio(4410, 2, 44_100).expect("after EOF"); + assert!(after_end.channels.iter().flatten().all(|&s| s == 0.0)); + let out_of_range = cold.audio(i64::MAX / 2, 1, 1).expect("unreachable origin"); + assert!(out_of_range.channels.iter().flatten().all(|&s| s == 0.0)); + + // 48->44.1 kHz MOV edit boundary: full read, split read, and fresh seek must all agree, + // sample 6,218 must not blend in the stored tail past the edit, and sample 6,219 must be silent. + const MOV_TRIM: usize = 9_600; + const MOV_EDIT_FRAMES: usize = 1_968; + let mov_samples: Vec = (0..12_000).map(|i| 1_000 + (i % 257) as i16 * 32).collect(); + let last_in_edit = f32::from(mov_samples[MOV_TRIM + MOV_EDIT_FRAMES - 1]) / 32_768.0; + let mov_bytes: Arc<[u8]> = edited_pcm_mov( + 48_000, + &mov_samples, + vec![ + isobmff::Edit { segment_duration: 100, media_time: -1, media_rate: 0x0001_0000 }, + isobmff::Edit { segment_duration: 41, media_time: MOV_TRIM as i64, media_rate: 0x0001_0000 }, + ], + ) + .into(); + let full_mov = open_bytes("edited-pcm.mov", mov_bytes.clone()).expect("recognized").expect("opened"); + let full_window = full_mov.audio(6_200, 25, 44_100).expect("full mov read").channels.remove(0); + assert_eq!(full_window[18], last_in_edit, "sample 6,218 must not blend in the tail past the edit"); + assert_eq!(full_window[19], 0.0, "sample 6,219 must be silent"); + + let split_mov = open_bytes("edited-pcm.mov", mov_bytes.clone()).expect("recognized").expect("opened"); + let mut split_window = split_mov.audio(6_200, 18, 44_100).expect("split part 1").channels.remove(0); + split_window.extend_from_slice(&split_mov.audio(6_218, 7, 44_100).expect("split part 2").channels[0]); + assert_eq!(split_window, full_window, "split read must match full read"); + + let seek_mov = open_bytes("edited-pcm.mov", mov_bytes).expect("recognized").expect("opened"); + let seek_window = seek_mov.audio(6_218, 2, 44_100).expect("fresh seek").channels.remove(0); + assert_eq!(seek_window, full_window[18..20], "fresh seek must match full read"); + } + + #[test] + fn ffv1_and_apv_video_codecs_route_through_craft_video() { + assert!(supports_video_codec(CodecId::Ffv1)); + assert!(!supports_video_codec(CodecId::Apv), "APV requires the guarded ISO-BMFF admission path"); + + let template = craft_video::ffv1::Frame { + width: 16, + height: 16, + colorspace: craft_video::ffv1::Colorspace::YCbCr, + bit_depth: 8, + chroma_shift: (1, 1), + planes: vec![vec![128; 256], vec![128; 64], vec![128; 64]], + }; + let ffv1_enc = craft_video::ffv1::Encoder::new(&template, craft_video::ffv1::EncoderConfig::default()).expect("ffv1 encoder"); + let mut ffv1_params = CodecParams::new(CodecId::Ffv1); + ffv1_params.width = Some(16); + ffv1_params.height = Some(16); + ffv1_params.extradata = ffv1_enc.config_record(); + assert!(TrackDecoder::with_options(&ffv1_params, TrackDecoderOptions { threads: Some(1), draft: false }).is_ok(), "Ffv1 decoder"); + + let mut apv_params = CodecParams::new(CodecId::Apv); + apv_params.width = Some(16); + apv_params.height = Some(16); + assert!(TrackDecoder::with_options(&apv_params, TrackDecoderOptions { threads: Some(1), draft: false }).is_ok(), "Apv decoder"); + } + + fn generated_avi_prores(with_alpha: bool, invalid_first: bool) -> Vec { + generated_avi_prores_pictures(with_alpha, invalid_first, &[512]) + } + + fn generated_avi_prores_pictures(with_alpha: bool, invalid_first: bool, luma: &[u16]) -> Vec { + use craft_video::prores::{ChromaFormat, ColorInfo as ProResColor, Encoder, EncoderConfig, Frame as ProResFrame, Interlace, Profile}; + + let mut cfg = EncoderConfig::new(Profile::P4444, 16, 16); + cfg.encode_alpha = with_alpha; + cfg.threads = false; + let mut enc = Encoder::with_config(cfg); + let mut frame = ProResFrame { + width: 16, + height: 16, + chroma: ChromaFormat::Yuv444, + bit_depth: 10, + y: vec![512; 256], + cb: vec![512; 256], + cr: vec![512; 256], + alpha: with_alpha.then(|| vec![512; 256]), + interlace: Interlace::Progressive, + color: ProResColor::default(), + aspect_ratio: 0, + frame_rate_code: 0, + }; + let mut w = avi::AviWriter::new( + std::io::Cursor::new(Vec::new()), + vec![avi::StreamSpec::Video(avi::VideoSpec::new(*b"ap4h", 16, 16, 24, 1))], + avi::MuxOptions::default(), + ) + .expect("avi writer"); + if invalid_first { + w.write_chunk(0, &[0], true).expect("write nonempty invalid first chunk"); + } + for &y in luma { + frame.y.fill(y); + let pkt = enc.encode(&frame).expect("encode prores"); + w.write_chunk(0, &pkt, true).expect("write prores chunk"); + } + w.finish().expect("finish avi").into_inner() + } + + #[test] + fn avi_prores_coded_alpha_parity() { + let alpha_src = open_bytes("alpha.avi", Arc::from(generated_avi_prores(true, false))).expect("recognized").expect("opened"); + assert!(alpha_src.info().video.as_ref().unwrap().has_alpha); + let frame = alpha_src.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode alpha frame"); + assert!(matches!(frame.data, PixelData::Yuv16 { alpha: Some(_), .. })); + + let opaque_src = open_bytes("opaque.avi", Arc::from(generated_avi_prores(false, false))).expect("recognized").expect("opened"); + assert!(!opaque_src.info().video.as_ref().unwrap().has_alpha); + let frame = opaque_src.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode opaque frame"); + assert!(matches!(frame.data, PixelData::Yuv16 { alpha: None, .. })); + } + + #[test] + fn avi_prores_unreadable_first_alpha_header_keeps_shared_playback() { + use crate::stream::{DecodedFrame, MediaSource as Opened}; + use effectcraft_project::AlphaMode; + + let bytes: Arc<[u8]> = generated_avi_prores(true, true).into(); + let demuxed = avi::open(bytes.as_ref()).expect("generated AVI"); + let video = &demuxed.streams[0]; + assert_eq!(video.codec_params().codec, CodecId::ProRes); + assert_eq!((video.rate, video.scale), (24, 1)); + assert_eq!(video.chunks.len(), 2); + assert_eq!(video.chunks[0].size, 1); + assert!(video.keyframes_known && video.chunks[1].key); + + let path = "invalid-first-prores.avi"; + let opened = crate::stream::open_bytes(path, bytes.clone()).expect("first unreadable header does not reject AVI"); + let Opened::Craft(shared) = &opened else { panic!("AVI remains on the shared reader") }; + assert!(!shared.info().video.as_ref().unwrap().has_alpha); + assert_eq!(crate::probe_bytes(path, bytes).unwrap().alpha, AlphaMode::Ignore); + + let later = effectcraft_time::Tick(craft_time::TICKS_PER_SECOND / 24); + let DecodedFrame::Craft(frame) = opened.video_frame(later, 1.0).expect("indexed second keyframe remains playable") else { + panic!("expected a shared frame"); + }; + assert_eq!((frame.width, frame.height, frame.pts.0), (16, 16, later.0)); + assert!(matches!(frame.data, PixelData::Yuv16 { alpha: Some(_), .. })); + } + + // The fixture is a tiny AVI generated by this test. Neutralize only RIFF index + // records (not coincidental FourCC strings inside compressed pictures). + fn make_generated_avi_indexless(mut bytes: &mut [u8]) { + while !bytes.is_empty() { + let size = u32::from_le_bytes(bytes[4..8].try_into().expect("generated RIFF length")) as usize; + let (chunk, rest) = bytes.split_at_mut(8 + size + size % 2); + match &chunk[..4] { + b"RIFF" | b"LIST" => make_generated_avi_indexless(&mut chunk[12..8 + size]), + b"indx" | b"idx1" | b"ix00" => chunk[..4].copy_from_slice(b"JUNK"), + b"avih" => chunk[20] &= !0x10, // Clear AVIF_HASINDEX in dwFlags. + _ => {} + } + bytes = rest; + } + } + + fn avi_prores_test_picture(source: &crate::stream::MediaSource, time: effectcraft_time::Tick) -> Arc { + let crate::stream::DecodedFrame::Craft(frame) = source.video_frame(time, 1.0).expect("read shared ProRes picture") else { + panic!("expected the shared AVI reader"); + }; + assert_eq!(frame.pts.0, time.0); + frame + } + + fn avi_prores_test_pixels(frame: &VideoFrame) -> (&[u16], &[u16]) { + let PixelData::Yuv16 { planes, alpha: Some(alpha), .. } = &frame.data else { panic!("expected a YUV picture with coded alpha") }; + (&planes[0], alpha) + } + + #[test] + fn indexless_avi_prores_seeks_independent_pictures_past_a_bad_first_chunk() { + const SLOT: i64 = craft_time::TICKS_PER_SECOND / 24; + let mut bytes = generated_avi_prores_pictures(true, true, &[512, 768]); + let indexed = crate::stream::open_bytes("indexed-prores.avi", Arc::from(bytes.clone())).expect("open indexed control"); + let first = effectcraft_time::Tick(SLOT); + let second = effectcraft_time::Tick(2 * SLOT); + let expected_first = avi_prores_test_picture(&indexed, first); + let expected_second = avi_prores_test_picture(&indexed, second); + assert_ne!(avi_prores_test_pixels(&expected_first).0, avi_prores_test_pixels(&expected_second).0); + + make_generated_avi_indexless(&mut bytes); + let demuxed = avi::open(bytes.as_slice()).expect("open scanned AVI"); + assert_eq!(demuxed.index, avi::IndexSource::Scan); + let video = &demuxed.streams[0]; + assert!(!video.keyframes_known); + assert_eq!((video.chunks.len(), video.chunks[0].size), (3, 1)); + + let opened = crate::stream::open_bytes("scanned-prores.avi", Arc::from(bytes)).expect("open indexless AVI"); + let cold = avi_prores_test_picture(&opened, second); + assert_eq!(avi_prores_test_pixels(&cold), avi_prores_test_pixels(&expected_second)); + assert!(opened.video_frame(effectcraft_time::Tick(0), 1.0).is_err(), "the requested corrupt picture remains an error"); + + let after_error = avi_prores_test_picture(&opened, second); + assert_eq!(avi_prores_test_pixels(&after_error), avi_prores_test_pixels(&expected_second)); + let backward = avi_prores_test_picture(&opened, first); + assert_eq!(avi_prores_test_pixels(&backward), avi_prores_test_pixels(&expected_first)); + } + + #[test] + fn oversized_prores_alpha_probe_refuses_without_reading() { + let mut read_count = 0; + let alpha = prores_has_alpha(MAX_PRORES_ALPHA_SAMPLE_BYTES + 1, || { + read_count += 1; + None + }); + assert_eq!(alpha, None); + assert_eq!(read_count, 0); + } +} + +#[cfg(test)] +mod monochrome_tests; diff --git a/crates/media/src/craft_source/flac_tracks_tests.rs b/crates/media/src/craft_source/flac_tracks_tests.rs new file mode 100644 index 000000000..8395c81d1 --- /dev/null +++ b/crates/media/src/craft_source/flac_tracks_tests.rs @@ -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, + packets: Vec>, + samples: Vec>, +} + +impl Fixture { + fn new() -> Result> { + let left: Vec = (0..FRAMES).map(|i| (i as i32 * 307 % 65_536) - 30_000).collect(); + let right: Vec = (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, Box> { + 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, Box> { + 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> { + 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> { + 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(()) +} diff --git a/crates/media/src/craft_source/monochrome_tests.rs b/crates/media/src/craft_source/monochrome_tests.rs new file mode 100644 index 000000000..e3251550d --- /dev/null +++ b/crates/media/src/craft_source/monochrome_tests.rs @@ -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> { + 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 = (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> { + 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(()) +} diff --git a/crates/media/src/craft_source/raw_avi.rs b/crates/media/src/craft_source/raw_avi.rs new file mode 100644 index 000000000..76dd8f517 --- /dev/null +++ b/crates/media/src/craft_source/raw_avi.rs @@ -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)>, +} + +impl RawAvi { + pub(super) fn new(stream: &avi::Stream) -> Option { + 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> { + 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) + } +} diff --git a/crates/media/src/craft_source/raw_avi_tests.rs b/crates/media/src/craft_source/raw_avi_tests.rs new file mode 100644 index 000000000..1dc67aead --- /dev/null +++ b/crates/media/src/craft_source/raw_avi_tests.rs @@ -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 { + 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, 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> { + 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 = (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> { + 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 { + 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> { + 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> { + 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> { + 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(()) +} diff --git a/crates/media/src/craft_source/rgb8_tests.rs b/crates/media/src/craft_source/rgb8_tests.rs new file mode 100644 index 000000000..8650f0a75 --- /dev/null +++ b/crates/media/src/craft_source/rgb8_tests.rs @@ -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>; + +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 = (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(()) +} diff --git a/crates/media/src/craft_source/standalone_flac.rs b/crates/media/src/craft_source/standalone_flac.rs new file mode 100644 index 000000000..e4b94d6e0 --- /dev/null +++ b/crates/media/src/craft_source/standalone_flac.rs @@ -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 { + 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 { + 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::()) 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>, +} + +impl MediaSource for FlacSource { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, _req: FrameRequest) -> Result> { + Err(MediaError::NoStream("video")) + } + + fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result { + 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::())).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, 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)); + } +} diff --git a/crates/media/src/craft_source/wide_rgb_tests.rs b/crates/media/src/craft_source/wide_rgb_tests.rs new file mode 100644 index 000000000..ceb963750 --- /dev/null +++ b/crates/media/src/craft_source/wide_rgb_tests.rs @@ -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>; + +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::>(), + ); + } + 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(()) +} diff --git a/crates/media/src/gif_anim.rs b/crates/media/src/gif_anim.rs index dc5f55e27..146f18932 100644 --- a/crates/media/src/gif_anim.rs +++ b/crates/media/src/gif_anim.rs @@ -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(); diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 4f337c0bf..5d3f376d0 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -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 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). diff --git a/crates/media/src/mp4_h264.rs b/crates/media/src/mp4_h264.rs deleted file mode 100644 index 456fcd92b..000000000 --- a/crates/media/src/mp4_h264.rs +++ /dev/null @@ -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> { - 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> { - if !looks_like_isobmff(&bytes) { - return None; - } - open_byte_source(name, Arc::new(bytes)) -} - -fn open_byte_source(name: &str, source: SharedBytes) -> Option> { - 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(¶ms, &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, -} - -struct VideoState { - decoder: TrackDecoder, - next_decode_idx: usize, - gop_start_idx: usize, - flushed: bool, - decoded: Vec, -} - -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` per channel. - buf: Vec>, -} - -struct AudioTrackEntry { - track_idx: usize, - native_rate: u32, - state: Mutex, -} - -struct Mp4H264Source { - info: MediaInfo, - source: SharedBytes, - file: Mp4File, - video_track_idx: usize, - container_color: Option, - par: (u32, u32), - video: Mutex, - audio_tracks: Vec, -} - -impl MediaSource for Mp4H264Source { - fn info(&self) -> &MediaInfo { - &self.info - } - - fn video_frame(&self, req: FrameRequest) -> Result> { - 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 { - self.audio_stream(0, start, frames, sample_rate) - } - - fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result { - 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>> { - 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, - frames: Vec, - container_color: Option, - 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, default_par: (u32, u32), timescale: u32, edit_offset: i64) -> Result { - 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> { - 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> { - 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 { - 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 { - 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 = 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); - } -} diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 7bb4ae78b..f8c596189 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -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, ReadFile)>>; +type SourceSlot = Arc; + +#[derive(Default)] +struct Source { + opened: OnceLock<(Option, ReadFile)>, + #[cfg(not(target_arch = "wasm32"))] + dispatch: Mutex, +} + +#[cfg(not(target_arch = "wasm32"))] +type DecodeJob = Box; + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Dispatch { + active: bool, + pending: VecDeque, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Source { + fn enqueue(self: &Arc, 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, 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) -> Option { 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, slot: &SourceSlot) -> Option { + 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, loc: &Loc, footage: &Footage) -> (Result, 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 { + fn decode_source(&self, loc: &Loc, footage: &Footage, source: Option<&SourceSlot>) -> Result { + 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 { + fn decode_media(&self, loc: &Loc, footage: &Footage, source: Option<&SourceSlot>) -> Result { 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] diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 52a29a363..954036fc4 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -28,6 +28,11 @@ pub fn probe(path: impl AsRef) -> Result { // 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 { +pub(crate) fn profile_of_craft(c: &craft_color::ColorInfo) -> Option { use craft_color::{Primaries, Transfer}; use effectcraft_project::ColorSpace; match (c.primaries, c.transfer) { diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index 5f81239f3..0de9b427b 100644 --- a/crates/media/src/stream.rs +++ b/crates/media/src/stream.rs @@ -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 { - 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, 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, 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> { +pub(crate) fn file_reader(path: &Path) -> Option> { Some(Box::new(FileReader::open(path).ok()?)) } #[cfg(not(any(unix, windows)))] -pub(crate) fn file_reader(_path: &Path) -> Option> { +pub(crate) fn file_reader(_path: &Path) -> Option> { None } @@ -261,21 +261,110 @@ pub(crate) fn probe_source(path: &Path) -> Option> { 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> { 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 = std::result::Result>; + + const WIDTH: u16 = 16; + const HEIGHT: u16 = 16; + + fn generated_mjpeg_mov() -> TestResult> { + // 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>> { + 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(()) + } +} diff --git a/crates/media/tests/fixtures/generate-monochrome-av1.sh b/crates/media/tests/fixtures/generate-monochrome-av1.sh new file mode 100755 index 000000000..ecfdfc830 --- /dev/null +++ b/crates/media/tests/fixtures/generate-monochrome-av1.sh @@ -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 diff --git a/crates/media/tests/fixtures/monochrome-av1.mkv b/crates/media/tests/fixtures/monochrome-av1.mkv new file mode 100644 index 000000000..37749f35e Binary files /dev/null and b/crates/media/tests/fixtures/monochrome-av1.mkv differ diff --git a/crates/media/tests/fixtures/monochrome-av1.mkv.attribution b/crates/media/tests/fixtures/monochrome-av1.mkv.attribution new file mode 100644 index 000000000..9d6ab96df --- /dev/null +++ b/crates/media/tests/fixtures/monochrome-av1.mkv.attribution @@ -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. diff --git a/crates/media/tests/it/aac_layout.rs b/crates/media/tests/it/aac_layout.rs index 5adf762b2..014655a40 100644 --- a/crates/media/tests/it/aac_layout.rs +++ b/crates/media/tests/it/aac_layout.rs @@ -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)); } } diff --git a/crates/media/tests/it/avi_mjpeg.rs b/crates/media/tests/it/avi_mjpeg.rs new file mode 100644 index 000000000..aa25fa454 --- /dev/null +++ b/crates/media/tests/it/avi_mjpeg.rs @@ -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:?}"); + } +} diff --git a/crates/media/tests/it/file_timecode.rs b/crates/media/tests/it/file_timecode.rs index dae3335ba..7a91640fc 100644 --- a/crates/media/tests/it/file_timecode.rs +++ b/crates/media/tests/it/file_timecode.rs @@ -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) -> Vec { - 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) -> Vec { 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) -> Vec { 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, tc_edits: Vec, 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"); +} diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 944a88721..1b03817ab 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -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, 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 = 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) { + 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::() / 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::() / 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::() / 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::() / 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::() / 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 { + 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::() / 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, Vec>) { + 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 = (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::() / pcm_seek.len() as f32).sqrt(); + assert!((rms - 0.0625).abs() < 0.03, "{file} audio seek rms {rms}"); + } +} diff --git a/crates/media/tests/it/main.rs b/crates/media/tests/it/main.rs index efa69b5a6..afeda890e 100644 --- a/crates/media/tests/it/main.rs +++ b/crates/media/tests/it/main.rs @@ -1,6 +1,7 @@ //! The crate's integration tests, one binary (each module is a former `tests/.rs`). mod aac_layout; +mod avi_mjpeg; mod downmix; mod exif_orientation; mod exr_golden; diff --git a/crates/pdf/src/color.rs b/crates/pdf/src/color.rs index 8b150f907..ff141990e 100644 --- a/crates/pdf/src/color.rs +++ b/crates/pdf/src/color.rs @@ -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; diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 4fd5d701c..884ffc1f8 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -253,11 +253,11 @@ fn eps_fallback_font(name: &[u8]) -> Option<&'static [u8]> { } fn parse_eps(bytes: &[u8]) -> Result { + 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), diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index c1f519595..9ac6bb6b1 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -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"); diff --git a/crates/pdf/src/tests/import.rs b/crates/pdf/src/tests/import.rs index 80be350f6..68d6487c0 100644 --- a/crates/pdf/src/tests/import.rs +++ b/crates/pdf/src/tests/import.rs @@ -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"); +} diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index 818331cce..3bf2e0aff 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -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" diff --git a/crates/psd/src/limits.rs b/crates/psd/src/limits.rs index 6db366c00..5c301be7d 100644 --- a/crates/psd/src/limits.rs +++ b/crates/psd/src/limits.rs @@ -105,11 +105,6 @@ impl Budget { } } -/// Inflate a zlib stream to at most `limit` bytes. -pub(crate) fn inflate(src: &[u8], limit: usize) -> Result> { - 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]>) { diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 2f1ccd2b3..b5a69bb4f 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -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; diff --git a/crates/psd/src/pixels.rs b/crates/psd/src/pixels.rs index 8ce6f2d63..aabd7c2ce 100644 --- a/crates/psd/src/pixels.rs +++ b/crates/psd/src/pixels.rs @@ -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> { 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 { + fn open_planes<'a>(&self, comp: u16, r: &mut Reader<'a>, total: usize, want: usize, size: (usize, usize), budget: &mut Budget) -> Result> { 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> { + /// 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> { let mut out = budget.vec::(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), - /// The inflated ZIP data of all planes. - Zip(Vec), +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) -> 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. diff --git a/crates/psd/src/read.rs b/crates/psd/src/read.rs index 307998066..158675d89 100644 --- a/crates/psd/src/read.rs +++ b/crates/psd/src/read.rs @@ -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() } diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 51e875416..3d18841db 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -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()); } diff --git a/crates/psd/src/tests/opt.rs b/crates/psd/src/tests/opt.rs index c4fdefcfe..a14287427 100644 --- a/crates/psd/src/tests/opt.rs +++ b/crates/psd/src/tests/opt.rs @@ -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 { } 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 { diff --git a/crates/psd/src/tests/parity.rs b/crates/psd/src/tests/parity.rs new file mode 100644 index 000000000..c3b5b945a --- /dev/null +++ b/crates/psd/src/tests/parity.rs @@ -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 { + 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); + } + } +} diff --git a/crates/psd/src/tests/unicode_name.rs b/crates/psd/src/tests/unicode_name.rs index 8785b1a49..a5616099c 100644 --- a/crates/psd/src/tests/unicode_name.rs +++ b/crates/psd/src/tests/unicode_name.rs @@ -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); + } + } +} diff --git a/crates/script/src/prelude.js b/crates/script/src/prelude.js index f33da7091..6f31ec37c 100644 --- a/crates/script/src/prelude.js +++ b/crates/script/src/prelude.js @@ -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; } }); diff --git a/crates/script/src/runtime.rs b/crates/script/src/runtime.rs index 28e490158..ab7e511e5 100644 --- a/crates/script/src/runtime.rs +++ b/crates/script/src/runtime.rs @@ -562,7 +562,7 @@ pub(crate) fn new_context() -> Result { 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); 11] = [ + let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult); 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 { (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())?; diff --git a/crates/script/src/tests/startup.rs b/crates/script/src/tests/startup.rs index 67da833c5..079bed416 100644 --- a/crates/script/src/tests/startup.rs +++ b/crates/script/src/tests/startup.rs @@ -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()); +} diff --git a/crates/script/src/tests/ui.rs b/crates/script/src/tests/ui.rs index 460376ac5..52bc0b922 100644 --- a/crates/script/src/tests/ui.rs +++ b/crates/script/src/tests/ui.rs @@ -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("")); +} diff --git a/crates/script/src/ui.rs b/crates/script/src/ui.rs index ecf4cd28b..6030ae71e 100644 --- a/crates/script/src/ui.rs +++ b/crates/script/src/ui.rs @@ -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 { + const MAX_EXTS: usize = 64; + const MAX_LEN: usize = 16; + let mut out: Vec = 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 { + 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 { + 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 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)); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index f1373607d..ae0fbf38d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -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 { diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 8eef34d4b..59c12267c 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -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); diff --git a/crates/ui-egui/src/app/gpu.rs b/crates/ui-egui/src/app/gpu.rs index 92ea7665c..96a24c5e0 100644 --- a/crates/ui-egui/src/app/gpu.rs +++ b/crates/ui-egui/src/app/gpu.rs @@ -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); } } diff --git a/crates/ui-egui/src/hooks.rs b/crates/ui-egui/src/hooks.rs index 7a87eeb6c..177084a46 100644 --- a/crates/ui-egui/src/hooks.rs +++ b/crates/ui-egui/src/hooks.rs @@ -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, 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, 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>, + /// 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 Vec>>, /// 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>)>>, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5d49d397b..1d39857df 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -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); } diff --git a/crates/ui-egui/src/lifecycle_tests.rs b/crates/ui-egui/src/lifecycle_tests.rs index 5b97b1961..fe9041987 100644 --- a/crates/ui-egui/src/lifecycle_tests.rs +++ b/crates/ui-egui/src/lifecycle_tests.rs @@ -356,6 +356,39 @@ fn image(width: usize, height: usize) -> Arc { 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(); diff --git a/crates/ui-egui/src/panels/misc.rs b/crates/ui-egui/src/panels/misc.rs index 0c87721db..a34e0d483 100644 --- a/crates/ui-egui/src/panels/misc.rs +++ b/crates/ui-egui/src/panels/misc.rs @@ -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 = 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 = + 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 diff --git a/crates/ui-egui/src/panels/scriptui_view.rs b/crates/ui-egui/src/panels/scriptui_view.rs index 2e34757bf..4b365afdf 100644 --- a/crates/ui-egui/src/panels/scriptui_view.rs +++ b/crates/ui-egui/src/panels/scriptui_view.rs @@ -540,6 +540,115 @@ fn perform(app: &mut EffectcraftApp, ctx: &egui::Context, acts: Vec) { } } +/// 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, + answer: Option, +} + +impl PendingAnswer { + fn send(mut self, paths: Result, 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 = 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, ¶ms, 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) { + 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 = app.session.script_ui.windows.iter().filter(|w| w.kind != WindowKind::Panel).cloned().collect(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index f80611a9b..4444fcc5e 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -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; diff --git a/crates/ui-egui/tests/it/ui_audio_panel_levels.rs b/crates/ui-egui/tests/it/ui_audio_panel_levels.rs new file mode 100644 index 000000000..9f7121c0b --- /dev/null +++ b/crates/ui-egui/tests/it/ui_audio_panel_levels.rs @@ -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 { + 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)> = 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 = 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 { 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 = 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 { + 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> { + 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)); +} diff --git a/crates/ui-egui/tests/it/ui_preview_align.rs b/crates/ui-egui/tests/it/ui_preview_align.rs index afafa8a45..a41723d61 100644 --- a/crates/ui-egui/tests/it/ui_preview_align.rs +++ b/crates/ui-egui/tests/it/ui_preview_align.rs @@ -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::>()); + let cached = h.state().frames.cached_frames(&series); + assert_eq!(cached, (0..120).collect::>(), "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(); diff --git a/crates/ui-egui/tests/it/ui_scriptui.rs b/crates/ui-egui/tests/it/ui_scriptui.rs index a905ebc5a..6c46e71cf 100644 --- a/crates/ui-egui/tests/it/ui_scriptui.rs +++ b/crates/ui-egui/tests/it/ui_scriptui.rs @@ -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>>> = 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::)); + 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>> = 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>> = 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::>(); + 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 ▸ ): 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>>> = 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"); +} diff --git a/docs/agents.md b/docs/agents.md index a83432f04..e09a94957 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -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 diff --git a/docs/scripting-parity.md b/docs/scripting-parity.md index 9aa6ca626..662472c96 100644 --- a/docs/scripting-parity.md +++ b/docs/scripting-parity.md @@ -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)) | diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index e3aab07a7..15da0dac7 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "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> {