diff --git a/.coderabbit.yaml b/.coderabbit.yaml
new file mode 100644
index 000000000..2408084cf
--- /dev/null
+++ b/.coderabbit.yaml
@@ -0,0 +1,6 @@
+# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
+reviews:
+ auto_review:
+ # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
+ ignore_usernames:
+ - "dependabot[bot]"
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 000000000..2c4b8cb1a
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,30 @@
+version: 2
+updates:
+ # Maintain Rust / Cargo dependencies
+ - package-ecosystem: "cargo"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ time: "06:00"
+ timezone: "America/New_York"
+ # Consolidate updates into a single PR rather than one PR per crate
+ groups:
+ cargo-dependencies:
+ patterns:
+ - "*"
+ commit-message:
+ prefix: "chore(deps)"
+
+ # Maintain GitHub Actions workflows
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ time: "06:00"
+ timezone: "America/New_York"
+ groups:
+ actions:
+ patterns:
+ - "*"
+ commit-message:
+ prefix: "ci(deps)"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 000000000..2095acad7
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,27 @@
+name: CI
+
+# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
+# suite's shared gate workflow in craft-common-actions.
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+# A newer push to a PR branch cancels its older run; every push to main runs to the end.
+concurrency:
+ group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ gate:
+ # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
+ uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
+ with:
+ packages: >-
+ pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
+ libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
+ libgl1-mesa-dev libasound2-dev
diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml
index f8ac8a300..8967f9431 100644
--- a/.github/workflows/freebsd.yml
+++ b/.github/workflows/freebsd.yml
@@ -2,12 +2,10 @@
# (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter.
name: FreeBSD
-# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every push
-# or dependency change: a drifted dependency still shows up within a day, and always before a
-# release ships. PRs that change the FreeBSD packaging itself still run it.
+# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every pull
+# request: a drifted dependency still shows up within a day, and always before a release ships.
+# PRs that change the FreeBSD workflow or packaging itself still run it.
on:
- schedule:
- - cron: "47 2 * * *"
push:
branches: [release]
pull_request:
@@ -15,6 +13,8 @@ on:
- .github/workflows/freebsd.yml
- packaging/freebsd/**
- packaging/env.sh
+ schedule:
+ - cron: "47 2 * * *"
workflow_dispatch:
concurrency:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 808e1628d..3cfbdc8b0 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -10,15 +10,14 @@ on:
type: string
default: ""
-permissions:
- contents: write
-
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
jobs:
release:
+ permissions:
+ contents: write
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml
new file mode 100644
index 000000000..e78fe1ea3
--- /dev/null
+++ b/.github/workflows/sonarcloud.yml
@@ -0,0 +1,21 @@
+name: SonarCloud
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ types: [opened, synchronize, reopened]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: sonarcloud-${{ github.ref }}
+ # A push to main is the run that publishes coverage; superseded runs there would never finish.
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+
+jobs:
+ sonarcloud:
+ # Tracked at @main so org-wide CI improvements propagate without PR churn.
+ uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
+ secrets: inherit
diff --git a/AGENTS.md b/AGENTS.md
index aad29c94a..24abee6a1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -105,6 +105,8 @@ reproduce an image (for example, point lists traced from someone else's icon).
See `CLAUDE.md`: pure Rust, dependency layering (`cargo xtask layers`), exact `Tick` time, everything is
a command, everything is agent-drivable, and the quality gates (`cargo xtask ci`) before every commit.
+- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
+
Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in
[`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in
[craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md).
diff --git a/CLAUDE.md b/CLAUDE.md
index a7c47fe3f..e52386942 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,6 +16,7 @@ EffectCraft is a clean-room, open-source, pure-Rust motion graphics and visual e
- **Pure Rust.** Media codecs come from FilmCraft crates (git deps behind `crates/media`, see `plan/adr/0001`).
- **Layering** (`cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd/cpal; L0–L4 build for wasm32.
- **Exact time:** `effectcraft_time::Tick` (254 016 000 000/s). Keyframe times are **layer time**.
+- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Property tree:** everything animatable is a `Property` in the layer's `PropGroup` tree, addressed by paths (`transform/position`, `effects/#1/blurriness`, `@uid`).
- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP dispatch by id.
- **Everything is agent-drivable:** every interactive widget registers an automation id; UI state is serde.
diff --git a/Cargo.lock b/Cargo.lock
index 8c354978a..325893ce2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -803,6 +803,15 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "chrono"
+version = "0.4.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -976,7 +985,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09
[[package]]
name = "craft-pdf"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d#ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d"
+source = "git+https://github.com/storytold/craft-libs?rev=9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef#9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"
dependencies = [
"hayro-syntax",
"thiserror 2.0.21",
@@ -1174,7 +1183,7 @@ dependencies = [
[[package]]
name = "effectcraft"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"cpal",
"effectcraft-engine",
@@ -1199,7 +1208,7 @@ dependencies = [
[[package]]
name = "effectcraft-automation"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-engine",
"effectcraft-host",
@@ -1211,14 +1220,14 @@ dependencies = [
[[package]]
name = "effectcraft-av1enc"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"filmcraft-av1",
]
[[package]]
name = "effectcraft-cli"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"cpu-time",
"effectcraft-automation",
@@ -1234,7 +1243,7 @@ dependencies = [
[[package]]
name = "effectcraft-color"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"proptest",
"serde",
@@ -1242,8 +1251,9 @@ dependencies = [
[[package]]
name = "effectcraft-effects"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
+ "chrono",
"effectcraft-color",
"effectcraft-geom",
"effectcraft-keyframe",
@@ -1259,8 +1269,9 @@ dependencies = [
[[package]]
name = "effectcraft-engine"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
+ "chrono",
"craft-docpath",
"effectcraft-color",
"effectcraft-effects",
@@ -1293,7 +1304,7 @@ dependencies = [
[[package]]
name = "effectcraft-export"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-av1enc",
"effectcraft-color",
@@ -1323,7 +1334,7 @@ dependencies = [
[[package]]
name = "effectcraft-expr"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"boa_engine",
"effectcraft-color",
@@ -1340,7 +1351,7 @@ dependencies = [
[[package]]
name = "effectcraft-geom"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"proptest",
"serde",
@@ -1348,7 +1359,7 @@ dependencies = [
[[package]]
name = "effectcraft-gpu"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"bytemuck",
"effectcraft-color",
@@ -1370,14 +1381,14 @@ dependencies = [
[[package]]
name = "effectcraft-hevcenc"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"filmcraft-hevc",
]
[[package]]
name = "effectcraft-host"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-engine",
"effectcraft-export",
@@ -1402,7 +1413,7 @@ dependencies = [
[[package]]
name = "effectcraft-interchange"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-color",
"effectcraft-keyframe",
@@ -1421,7 +1432,7 @@ dependencies = [
[[package]]
name = "effectcraft-keyframe"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-color",
"effectcraft-geom",
@@ -1433,7 +1444,7 @@ dependencies = [
[[package]]
name = "effectcraft-lottie"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"craft-docpath",
"effectcraft-color",
@@ -1451,7 +1462,7 @@ dependencies = [
[[package]]
name = "effectcraft-media"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"craft-docpath",
"effectcraft-model",
@@ -1480,7 +1491,7 @@ dependencies = [
[[package]]
name = "effectcraft-model"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-geom",
"image",
@@ -1492,14 +1503,14 @@ dependencies = [
[[package]]
name = "effectcraft-opusenc"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"filmcraft-opus",
]
[[package]]
name = "effectcraft-path"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-geom",
"effectcraft-keyframe",
@@ -1511,7 +1522,7 @@ dependencies = [
[[package]]
name = "effectcraft-pdf"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"craft-pdf",
"effectcraft-raster",
@@ -1527,7 +1538,7 @@ dependencies = [
[[package]]
name = "effectcraft-plugin"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-effects",
"effectcraft-keyframe",
@@ -1539,7 +1550,7 @@ dependencies = [
[[package]]
name = "effectcraft-project"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-color",
"effectcraft-geom",
@@ -1552,14 +1563,14 @@ dependencies = [
[[package]]
name = "effectcraft-psd"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"miniz_oxide 0.8.9",
]
[[package]]
name = "effectcraft-raster"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-color",
"effectcraft-geom",
@@ -1568,7 +1579,7 @@ dependencies = [
[[package]]
name = "effectcraft-render"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-color",
"effectcraft-effects",
@@ -1590,7 +1601,7 @@ dependencies = [
[[package]]
name = "effectcraft-script"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"boa_engine",
"effectcraft-engine",
@@ -1602,12 +1613,13 @@ dependencies = [
"effectcraft-render",
"effectcraft-time",
"serde_json",
+ "socket2",
"web-time",
]
[[package]]
name = "effectcraft-segment"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"miniz_oxide 0.8.9",
"ndarray",
@@ -1616,7 +1628,7 @@ dependencies = [
[[package]]
name = "effectcraft-svg"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-geom",
"effectcraft-path",
@@ -1628,7 +1640,7 @@ dependencies = [
[[package]]
name = "effectcraft-text"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-keyframe",
"harfrust",
@@ -1640,7 +1652,7 @@ dependencies = [
[[package]]
name = "effectcraft-time"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"proptest",
"serde",
@@ -1648,7 +1660,7 @@ dependencies = [
[[package]]
name = "effectcraft-track"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-raster",
"effectcraft-segment",
@@ -1660,8 +1672,9 @@ dependencies = [
[[package]]
name = "effectcraft-ui-egui"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
+ "chrono",
"craft-quit",
"craft-ui",
"effectcraft-color",
@@ -1693,11 +1706,11 @@ dependencies = [
[[package]]
name = "effectcraft-vp9enc"
-version = "0.11.0"
+version = "0.16.0"
[[package]]
name = "effectcraft-web"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
"effectcraft-engine",
"effectcraft-export",
@@ -2725,8 +2738,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"
+source = "git+https://github.com/storytold/craft-libs?rev=9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef#9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"
dependencies = [
"hayro-ccitt",
]
@@ -2740,7 +2752,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
-source = "git+https://github.com/storytold/craft-libs?rev=ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d#ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d"
+source = "git+https://github.com/storytold/craft-libs?rev=9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef#9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"
dependencies = [
"hayro-jbig2",
"hayro-jpeg2000",
@@ -4827,6 +4839,16 @@ dependencies = [
"serde",
]
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "spin"
version = "0.9.9"
@@ -6637,9 +6659,11 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
-version = "0.11.0"
+version = "0.16.0"
dependencies = [
+ "chrono",
"serde_json",
+ "tempfile",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 60e97e13c..b26720cf9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,14 +4,14 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/*"]
[workspace.package]
-version = "0.11.0"
+version = "0.16.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/effectcraft"
[workspace.dependencies]
-craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d", version = "=0.1.0", default-features = false, features = ["read"] }
+craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
# internal
@@ -53,6 +53,8 @@ thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
+# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
+chrono = { version = "0.4.45", default-features = false, features = ["std"] }
rayon = "1"
# std::time::Instant/SystemTime on native; the browser clock on wasm32 (std's panic there).
web-time = "1"
@@ -138,9 +140,12 @@ type_complexity = "allow"
[profile.dev.package."*"]
opt-level = 2
+debug = false
[profile.dev]
opt-level = 1
+# Panics and backtraces keep file and line; full debug info only made the many test binaries large.
+debug = "line-tables-only"
# Pixel hot loops: keep debug builds interactive.
[profile.dev.package.effectcraft-raster]
@@ -212,4 +217,5 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
-hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d", version = "=0.7.2" }
+hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef", version = "=0.7.2" }
+hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef", version = "=0.3.0" }
diff --git a/README.md b/README.md
index 914a40907..5fa28f0bb 100644
--- a/README.md
+++ b/README.md
@@ -8,14 +8,18 @@
+
+
+
+
EffectCraft
- Motion graphics and visual effects; an open-source, clean-room reimplementation of Adobe After Effects, rebuilt in pure Rust.
+ Motion graphics and visual effects; an open-source, professional motion graphics and visual effects studio, built in pure Rust.
- A free, open-source compositor in the spirit of After Effects: compositions, layers,
+ A free, open-source compositor: compositions, layers,
keyframes, 306 effects, layer styles, expressions, 3D cameras and lights, and a render queue, native on macOS,
Windows and Linux, and in the browser. Young, moving fast, and already usable.
@@ -24,6 +28,9 @@
+
+
+
@@ -64,13 +71,14 @@
## What EffectCraft is
EffectCraft is for animated titles, motion graphics and compositing work: the kind of thing
-people reach for After Effects to do. You build a composition out of layers (solids, shapes,
+motion designers and VFX artists need. You build a composition out of layers (solids, shapes,
text, footage, other compositions), animate their properties with keyframes, stack effects on
them and render the result.
-The aim is to feel familiar to anyone who has used After Effects, with the same panels (Project,
-Composition, Timeline, Effect Controls, Effects & Presets) and the same keyframe behaviour, and
-then to go further in a few places where it matters to us:
+The interface feels natural and responsive, with dedicated panels (Project, Composition, Timeline,
+Layer, Footage, Effect Controls, Tools, Preview, Effects & Presets, Audio, Info, Paragraph,
+Character, Align, Progress, Render Queue) and standard motion graphics shortcuts, going further in
+a few places where it matters to us:
- **Lottie import and export built in**, so animations can go straight to the web and apps
without a plugin.
@@ -84,7 +92,7 @@ then to go further in a few places where it matters to us:
## Animate
-The panels, menus and shortcuts follow After Effects, so your muscle memory carries over:
+The panels, menus and shortcuts follow standard motion design conventions:
Project, Composition, Timeline, Effect Controls, Properties, Effects & Presets, Character,
Paragraph, Align, Info, Preview, Audio and the Render Queue, docked the way you expect. Drag
footage, comps and effects between them: onto the comp viewer, where they land under the pointer,
@@ -102,7 +110,7 @@ or into the Timeline, between layers and at the time you point to.
feather, expansion and vertex editing in the viewer.
- **Text:** point and paragraph text with real shaping in any font installed on your machine, the
Character and Paragraph panels, and text animators with range selectors.
-- **Expressions:** JavaScript with the After Effects object model (`wiggle`, `loopOut`,
+- **Expressions:** JavaScript with the standard motion expressions model (`wiggle`, `loopOut`,
`thisComp.layer("…")`, vector maths on arrays), an inline editor and the pick-whip.
- **Timeline like you know it:** twirl layers open to Transform, masks, effects and the rest; drag
rows to reorder layers; rename with Enter or a double-click; the property shortcuts (A, P, S,
@@ -118,9 +126,9 @@ or into the Timeline, between layers and at the time you point to.
## Effects
-306 effects (every one of After Effects' 298, and more) across its categories, each with its parameter names, order and
-defaults: blur and sharpen, channel, color correction (Curves, Levels, Hue/Saturation, Lumetri
-Color…), distort (Warp, Bulge, Turbulent Displace, CC Power Pin…), generate (Fractal Noise,
+306 built-in effects across its categories, each with its parameter names, order and
+defaults: blur and sharpen, channel, color correction (Curves, Levels, Hue/Saturation, a full
+color-grading panel…), distort (Warp, Bulge, Turbulent Displace, CC Power Pin…), generate (Fractal Noise,
Gradient Ramp, Stroke, Write-on, Audio Spectrum…), keying, matte, noise and grain, perspective,
**simulation** (CC Particle World, CC Rainfall, Shatter, Card Dance, Caustics, Wave World…),
stylize (Glow, CC Glass…), **time** (Echo, Posterize Time, Timewarp, Time Displacement…),
@@ -134,7 +142,7 @@ overlays, Stroke) with Global Light. Preview plays audio in sync, with meters an
## 3D
-Classic 3D the way After Effects does it: 3D layers with orientation and material options,
+Classic 3D compositing: 3D layers with orientation and material options,
one- and two-node **cameras** with depth of field, **lights** (parallel, spot, point, ambient)
with soft ray-traced shadows, layers that intersect correctly, orbit, pan and dolly camera
tools, and Front, Top, Left and Custom views.
@@ -145,7 +153,7 @@ tools, and Front, Top, Left and Custom views.
## Export
-A Render Queue like After Effects', with Render Settings and Output Modules: **H.264** MP4 and
+A dedicated Render Queue, with Render Settings and Output Modules: **H.264** MP4 and
**ProRes** MOV (Proxy to 4444 XQ with alpha) with audio, **HEVC** (Main / Main 10) and **AV1**
MP4, **WebM** (VP9 with inter frames and alpha, or AV1; Opus audio), PNG, JPEG, TIFF and 32-bit EXR sequences, animated GIF and WAV/AIFF. Field
rendering with 3:2 pulldown, effect/solo/guide/depth overrides, crop, region of interest and
@@ -219,25 +227,26 @@ tests, layering, asset attribution and the WebAssembly build). See [CONTRIBUTING
## Where it stands
-EffectCraft is young: its first commit was on 1 October 2026. Nearly every After Effects feature
-exists, including all of its effects, but existing is not the same as behaving exactly like After
-Effects, and we haven't measured that yet. Today it's a good place to try things and to tell us
-what breaks. It isn't yet a replacement for After Effects on client work. In particular:
+EffectCraft is young: its first commit was on 1 October 2026. A comprehensive feature set
+exists, including 306 effects, but breadth is not the same as full maturity across every edge
+case. Today it's a good place to try things and to tell us what breaks. It isn't yet recommended
+for production client work. In particular:
-- **After Effects projects can't be opened.** Projects are saved as `.ecproj`, readable versioned
- JSON, but EffectCraft can't open `.aep` / `.aepx` files, and After Effects plug-ins don't run.
-- **Behaviour still differs from After Effects in places.** Nothing yet compares our renders with
- After Effects automatically, so please report differences.
+- **Native project format.** Projects are saved as `.ecproj`, readable versioned JSON. Proprietary
+ project formats and After Effects SDK plug-ins are not supported.
+- **Fidelity is still being refined.** Automated rendering tests currently focus on small
+ compositions, so please report visual discrepancies or unexpected behaviour.
- **macOS is the most tested platform.** Linux and Windows users have hit basic interaction
bugs, which we're fixing first.
- **The trained models are new.** Roto Brush can use MobileSAM (an optional 40 MB download in
Settings ▸ Roto Brush) and face tracking can use Google's MediaPipe Face Landmarker (an optional
- 3.8 MB download in Settings ▸ Face Tracking). Neither is compared with After Effects yet.
+ 3.8 MB download in Settings ▸ Face Tracking). Both are actively undergoing evaluation and tuning.
-EffectCraft is in **alpha**: about 91% of After Effects' features exist, and we estimate it is
-about 45% of the way to replacing After Effects for professional work. The [ROADMAP](ROADMAP.md)
-has the plan, [docs/target-app-parity.md](docs/target-app-parity.md) the measurement and
-[docs/gaps.md](docs/gaps.md) every known shortfall. The web build ([docs/web.md](docs/web.md)) runs the full app in the browser.
+EffectCraft is in **alpha**: about 91% of the features tracked in
+[docs/target-app-parity.md](docs/target-app-parity.md) exist, and we estimate it is about 45% of the
+way to being ready for full professional production work. The [ROADMAP](ROADMAP.md) has the plan,
+[docs/target-app-parity.md](docs/target-app-parity.md) the measurement and [docs/gaps.md](docs/gaps.md)
+every known shortfall. The web build ([docs/web.md](docs/web.md)) runs the full app in the browser.
[Bug reports](https://github.com/storytold/effectcraft/issues) are the most useful thing you can
send us right now.
@@ -245,8 +254,8 @@ send us right now.
- **Engine first.** A stack of small crates with strict layering. The interface (egui) sits on
top and nothing underneath depends on it.
-- **Clean room.** We work from After Effects' public documentation and how it behaves, never
- from Adobe's files, icons, presets or code. No code is copied from GPL projects. The full rules
+- **Clean room.** We work from public documentation and observable behavior, never
+ from proprietary files, icons, presets or code. No code is copied from GPL projects. The full rules
are in [AGENTS.md](AGENTS.md).
- **Private by default.** No telemetry, and no network access unless you ask for it.
- **One family.** EffectCraft shares its time model and text engine design with FilmCraft, and
@@ -368,8 +377,6 @@ ArtCraft Team and are not covered by this license. They may be used only unmodif
part of this repository and EffectCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
-Adobe, Photoshop, Illustrator, Premiere Pro, Lightroom, Acrobat, After Effects and InDesign are trademarks or registered trademarks of Adobe Inc. in the United States and/or other countries. EffectCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Adobe Inc.; these names are used only to describe the workflows it is compatible with.
-
Made by the ArtCraft team and community.
diff --git a/ROADMAP.md b/ROADMAP.md
index e21039c02..f4c99d61f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -97,7 +97,7 @@ UI strings translated out of ≈ 3,900 (detail: [localization-parity.md](docs/lo
| Korean | none | 0% |
| Vietnamese | none | 0% |
-Also shipped: Traditional Chinese (partial, 29%), Ukrainian (partial, 29%), Czech (partial, 29%) and Russian (menus only, 16%). No language has had
+Also shipped: Traditional Chinese (partial, 29%), Ukrainian (partial, 29%), Czech (partial, 29%), Georgian (partial, 38%; native-speaker reviewed) and Russian (menus only, 16%). No other language has had
native-speaker review.
## Upcoming
@@ -117,6 +117,10 @@ Come tell us what matters most to you on [Discord](https://discord.gg/artcraft).
## Progress log
+- 2026-10-16: Convert To Bezier Path turns a shape layer's Rectangle, Ellipse or Polystar
+ path into an editable Path 1 with the same geometry, as After Effects does; it used to
+ apply to mask RotoBezier only, so a parametric shape path could not be converted at all
+ and its vertices could not be edited or animated (#932).
- 2026-10-12: Roto Brush span edits report strokes outside a trimmed layer without panicking;
strokes and undo history are preserved so restoring the timing allows the span edit again.
- 2026-10-11: Ukrainian panels caught up with the Chinese catalogs. The 95 rows the panel
@@ -131,6 +135,7 @@ Come tell us what matters most to you on [Discord](https://discord.gg/artcraft).
follow the shared standard: `docs/parity.md` became `docs/target-app-parity.md`; new
`docs/roadmap.md`, `localization-parity.md`, `file-format-parity.md`, `hardware-parity.md`,
`ui-parity.md`, `effects-parity.md` and `scripting-parity.md`.
+- 2026-10-14: Georgian (`ka`): every menu row, every panel-catalog row the Chinese catalogs have plus 195 Georgian-only ones, and the effect names and categories; Match System for `ka` / `ka-GE` / `ka_GE.UTF-8` locales. Reviewed by a native speaker.
- 2026-10-10: Spanish (#460) and Brazilian Portuguese (#217) menu translations.
- 2026-10-10: Japanese now translates the interface below the menu bar too: `crates/ui-egui/src/i18n/ui.rs` has a Japanese table with the same 396 rows as the Chinese ones (panels, dialogs, buttons and tooltips; the shape test keeps the three catalogs listing the same source strings). Menus were already Japanese.
- 2026-10-09: Ukrainian now covers all 396 current panel-catalog strings, including dialogs, buttons and tooltips, alongside its menu translation. The catalog keeps the same source keys and placeholder counts as the Chinese catalogs; missing or engine-generated text still falls back to English.
diff --git a/apps/effectcraft-cli/src/main.rs b/apps/effectcraft-cli/src/main.rs
index 43e514048..6e5b8d6cc 100644
--- a/apps/effectcraft-cli/src/main.rs
+++ b/apps/effectcraft-cli/src/main.rs
@@ -6,6 +6,7 @@
//! effectcraft-cli exec [--params JSON] run one command
//! effectcraft-cli exec --list [--filter TEXT] [--schemas] list engine commands (as `commands`)
//! effectcraft-cli run [ …] run several commands in order
+//! effectcraft-cli run --args-file F the same, one argument per line of F
//! effectcraft-cli props [--flat] [--time S] a layer's property tree (with paths)
//! effectcraft-cli get [--time S] read a property
//! effectcraft-cli set [--time S] [--expression E]
@@ -16,6 +17,8 @@
//! [--profile main|main10] [--level auto|4.1] [--rate-control bitrate|quality] [--video-quality 1-100]
//! [--keyint FRAMES] [--webm-codec vp9|av1] [--audio-bitrate KBPS] [--opus-app audio|voice]
//! (a relative --out is relative to the working directory; --queue outputs follow the project's own settings)
+//! [--progress] report progress on stderr when it is not a terminal, up to four lines a second:
+//! `progress `
//! effectcraft-cli render --template T.ectemplate [--values V.json] --out FILE
//! effectcraft-cli render-frame --template T.ectemplate [--values V.json] [--time S] [--out F.png]
//! effectcraft-cli render F.ecproj --queue render the project's Render Queue
@@ -94,6 +97,7 @@ const USAGE: &str = "usage: effectcraft-cli [--params JSON] run one engine command (exec --list: list them, as `commands`)
run [ ...] run several commands in order
+ run --args-file F the same, one argument per line of F (no command-line length limit)
props [--flat] [--time S] a layer's property tree with paths
get [--time S] read a property
set [--time S] [--expression E]
@@ -106,6 +110,8 @@ const USAGE: &str = "usage: effectcraft-cli )
render/render-frame --template T.ectemplate [--values V.json] render one template instance
bench [--comp C] [--time S] [--scale K] [--n N] [--play N] [--gpu [--adv3d]] per-layer/effect render timings;
--play N renders N consecutive frames with/without the layer cache;
@@ -144,6 +150,7 @@ const VALUED: &[&str] = &[
"--expression",
"--depth",
"--eval",
+ "--args-file",
// render
"--template",
"--values",
@@ -189,6 +196,7 @@ const FLAGS: &[&str] = &[
"--small",
"--adv3d",
"--autosave",
+ "--progress",
];
struct Args {
@@ -510,10 +518,15 @@ fn run(cmd: &str, args: &Args, json_out: bool) -> Result<(), Failure> {
emit(&with_saved(r, saved), json_out);
}
"run" => {
- if args.pos.is_empty() {
+ let mut pairs = args.pos.clone();
+ // Windows caps a command line at 32 767 characters: long batches come from a file.
+ if let Some(f) = args.opt("--args-file") {
+ let text = std::fs::read_to_string(f).map_err(|e| Failure::Usage(format!("--args-file {f}: {e}")))?;
+ pairs.extend(text.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from));
+ }
+ if pairs.is_empty() {
return usage_err("run needs [] pairs");
}
- let pairs = args.pos.clone();
let mut b = backend(args, true)?;
let mut results = vec![];
let mut i = 0;
@@ -772,8 +785,21 @@ fn render(args: &Args, json_out: bool) -> Result<(), Failure> {
}
s.execute("renderQueue.render", json!({"wait": false})).map_err(err)?;
let tty = std::io::IsTerminal::is_terminal(&std::io::stderr());
+ // `--progress`: one line per update for a program reading stderr (a terminal gets the live line).
+ let lines = args.flag("--progress") && !tty;
+ let (mut last_line, mut last_done) = (std::time::Instant::now(), u64::MAX);
while s.is_rendering() {
std::thread::sleep(std::time::Duration::from_millis(100));
+ if lines
+ && last_line.elapsed() >= std::time::Duration::from_millis(250)
+ && let Some(p) = s.render_progress()
+ && p.done != last_done
+ {
+ last_line = std::time::Instant::now();
+ last_done = p.done;
+ let left = p.remaining.map_or_else(|| "-".to_string(), |r| format!("{r:.1}"));
+ note!("progress {} {} {:.1} {left}", p.done, p.total, p.item_elapsed);
+ }
if tty && let Some(p) = s.render_progress() {
let left = p.remaining.map(|r| format!(", ~{r:.1}s left")).unwrap_or_default();
let _ = write!(
diff --git a/apps/effectcraft-cli/src/template.rs b/apps/effectcraft-cli/src/template.rs
index f84303dd0..8cf5c124f 100644
--- a/apps/effectcraft-cli/src/template.rs
+++ b/apps/effectcraft-cli/src/template.rs
@@ -4,7 +4,7 @@ use std::io::Read;
use effectcraft_engine::{
EngineError, Session,
- project::{ItemId, LayerId},
+ project::{ItemId, LayerId, essential::EgKind},
};
use serde_json::{Map, Value, json};
@@ -92,7 +92,7 @@ fn preflight(s: &Session, path: &str, values: &Map) -> Result<(),
project.fix_next_id();
let mut check = Session::new();
check.project = project.into();
- Ok(instantiate(&mut check, source, values))
+ Ok(instantiate(&mut check, source, values, false))
})
.map_err(|e| Failure::Error(e.to_string()))?
}
@@ -105,10 +105,27 @@ pub(super) fn prepare(s: &mut Session, args: &Args) -> Result<(), Failure> {
}
let imported = execute(s, "essential.importTemplate", json!({"path": path, "addToComp": false}))?;
let source = imported.get("comp").and_then(Value::as_u64).ok_or_else(|| Failure::Error("template import did not return a composition".into()))?;
- instantiate(s, source, &values)
+ instantiate(s, source, &values, true)
}
-fn instantiate(s: &mut Session, source: u64, values: &Map) -> Result<(), Failure> {
+/// The file a Media Replacement control is given: a path, or `{path|file|media: path}`.
+fn media_path(value: &Value) -> Option<&str> {
+ match value {
+ Value::String(path) => Some(path.as_str()),
+ Value::Object(m) => ["path", "file", "media"].iter().find_map(|k| m.get(*k)).and_then(Value::as_str),
+ _ => None,
+ }
+}
+
+/// Whether the template's control of that name (looked up as `essential.set` does) is a Media Replacement.
+fn is_media_control(s: &Session, source: u64, name: &str) -> bool {
+ let Some(eg) = s.project.comp(ItemId(source)).and_then(|c| c.essential.as_ref()) else { return false };
+ let all = eg.flat();
+ let control = all.iter().find(|c| c.name == name).or_else(|| all.iter().find(|c| c.name.eq_ignore_ascii_case(name)));
+ control.is_some_and(|c| matches!(c.kind, EgKind::Media { .. }))
+}
+
+fn instantiate(s: &mut Session, source: u64, values: &Map, import_media: bool) -> Result<(), Failure> {
// Duplicate and empty the source with commands: this preserves exact rational frame rate,
// Tick duration, background, work area and renderer settings without round-tripping floats.
let duplicate = execute(s, "project.duplicate", json!({"items": [source]}))?;
@@ -133,8 +150,11 @@ fn instantiate(s: &mut Session, source: u64, values: &Map) -> Res
}
let added = execute(s, "layer.addItem", json!({"comp": parent, "item": source, "time": 0}))?;
let instance = added.get("layer").and_then(Value::as_u64).ok_or_else(|| Failure::Error("cannot create template instance".into()))?;
- // Keep a partial final frame: layer.addItem snaps its default end to the frame grid.
+ // Keep a partial final frame: layer.addItem snaps its default end to the frame grid. Give the
+ // wrapper the source's exact name, not Duplicate's numbered one, for `[compName]` outputs.
s.edit("Template Duration", None, |project, _| {
+ let name = project.item(ItemId(source)).ok_or_else(|| EngineError::Other("template composition is missing".into()))?.name.clone();
+ project.item_mut(ItemId(parent)).ok_or_else(|| EngineError::Other("template render composition is missing".into()))?.name = name;
let comp = project.comp_mut(ItemId(parent)).ok_or(EngineError::NoComp)?;
let duration = comp.duration;
let layer = comp.layer_mut(LayerId(instance)).ok_or_else(|| EngineError::Other("template instance is missing".into()))?;
@@ -145,6 +165,25 @@ fn instantiate(s: &mut Session, source: u64, values: &Map) -> Res
// Let the wrapper carry the source composition's authored motion blur.
execute(s, "layer.setSwitch", json!({"comp": parent, "layers": [instance], "switch": "motionBlur", "value": true}))?;
for (control, value) in values {
+ if is_media_control(s, source, control) {
+ let path = media_path(value).ok_or_else(|| Failure::Error(format!("control `{control}` is a media control: give it a file path")))?;
+ // The preflight session cannot import files; the real run reports a bad path.
+ if !import_media {
+ continue;
+ }
+ let imported = execute(s, "file.import", json!({"paths": [path]}))?;
+ if let Some(err) = imported.get("errors").and_then(Value::as_array).and_then(|e| e.first()) {
+ return Err(Failure::Error(format!("control `{control}`: cannot import {path}: {err}")));
+ }
+ let item = imported
+ .get("items")
+ .and_then(Value::as_array)
+ .and_then(|items| items.first())
+ .and_then(Value::as_u64)
+ .ok_or_else(|| Failure::Error(format!("control `{control}`: {path} did not import as footage")))?;
+ execute(s, "essential.set", json!({"comp": parent, "layer": instance, "control": control, "item": item}))?;
+ continue;
+ }
execute(s, "essential.set", json!({"comp": parent, "layer": instance, "control": control, "value": value}))?;
}
Ok(())
diff --git a/apps/effectcraft-cli/tests/cli.rs b/apps/effectcraft-cli/tests/it/cli.rs
similarity index 85%
rename from apps/effectcraft-cli/tests/cli.rs
rename to apps/effectcraft-cli/tests/it/cli.rs
index 30a0271b6..538887d9b 100644
--- a/apps/effectcraft-cli/tests/cli.rs
+++ b/apps/effectcraft-cli/tests/it/cli.rs
@@ -110,6 +110,29 @@ fn exec_set_get_with_saved_project() {
assert_eq!(v[1]["result"]["time"], v[0]["result"]["time"], "{v}");
}
+/// `run --args-file` reads its command / params pairs from a file, one per line: a batch longer
+/// than a Windows command line (32 767 characters, os error 206) still runs.
+#[test]
+fn run_reads_arguments_from_a_file() {
+ let proj = tmp("args-file.ecproj");
+ let p = proj.to_str().unwrap();
+ let mut lines = vec!["comp.new".to_string(), json!({"name": "A", "width": 64, "height": 64}).to_string()];
+ for i in 0..400 {
+ lines.push("layer.newSolid".into());
+ lines.push(json!({"width": 8, "height": 8, "name": format!("Solid with a long name to pass the limit {i:04}")}).to_string());
+ lines.push(String::new());
+ }
+ let text = lines.join("\n");
+ assert!(text.len() > 32_767);
+ let file = tmp("args-file.txt");
+ std::fs::write(&file, text).unwrap();
+ let v = ok_json(&["run", "--args-file", file.to_str().unwrap(), "--empty", "--save-as", p]);
+ assert_eq!(v["result"].as_array().map(Vec::len), Some(401), "{v}");
+ let out = bin().args(["run", "--args-file", "no/such/file.txt", "--empty"]).output().unwrap();
+ assert_eq!(out.status.code(), Some(2));
+ assert!(String::from_utf8_lossy(&out.stderr).contains("--args-file no/such/file.txt"));
+}
+
#[test]
fn render_frame_writes_png() {
let out = tmp("f.png");
@@ -593,3 +616,77 @@ solid.property("ADBE Transform Group").property("ADBE Opacity").addToMotionGraph
assert_eq!(reply["error"], "command `renderQueue.add` is not available right now: select or open a composition", "{reply}");
let _ = std::fs::remove_dir_all(&root);
}
+
+/// `WGPU_ADAPTER_NAME` that matches nothing is a clean `--gpu` error listing the adapters
+/// found (wgpu's own helper panics). Read once per process, hence a subprocess.
+#[test]
+fn gpu_adapter_name_mismatch_is_a_clean_error() {
+ let out = bin()
+ .args(["render-frame", "--gpu", "--max-side", "64", "--out", tmp("nomatch.png").to_str().unwrap(), "--json"])
+ .env("WGPU_ADAPTER_NAME", "NoSuchAdapter-xyz")
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ assert_eq!(out.status.code(), Some(1), "stdout: {stdout}\nstderr: {}", String::from_utf8_lossy(&out.stderr));
+ let v: Value = serde_json::from_str(stdout.trim()).unwrap();
+ let e = v["error"].as_str().unwrap();
+ assert!(e.contains("WGPU_ADAPTER_NAME=\"NoSuchAdapter-xyz\""), "{e}");
+ assert!(e.contains("available: [") || e.contains("no adapters on the enabled backends"), "{e}");
+}
+
+/// An exported-but-empty `WGPU_ADAPTER_NAME` behaves like unset: it never produces the
+/// adapter-name error (whether a GPU exists on this machine is not asserted).
+#[test]
+fn gpu_adapter_name_empty_is_unset() {
+ let out = bin()
+ .args(["render-frame", "--gpu", "--max-side", "64", "--out", tmp("emptyname.png").to_str().unwrap(), "--json"])
+ .env("WGPU_ADAPTER_NAME", " ")
+ .output()
+ .unwrap();
+ let all = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
+ assert!(!all.contains("WGPU_ADAPTER_NAME"), "{all}");
+}
+
+/// Renders two seconds of the demo at quarter resolution (long enough for several progress
+/// updates) and returns stderr, which `output()` reads through a pipe: not a terminal.
+fn render_demo_stderr(name: &str, extra: &[&str]) -> String {
+ let out = tmp(name);
+ let mut args = vec!["render", "--demo", "--format", "gif", "--start", "0", "--end", "2", "--resolution", "quarter", "--out", out.to_str().unwrap()];
+ args.extend_from_slice(extra);
+ let o = bin().args(&args).output().unwrap();
+ let stderr = String::from_utf8_lossy(&o.stderr).to_string();
+ assert!(o.status.success(), "{args:?}: {stderr}");
+ let _ = std::fs::remove_file(out);
+ stderr
+}
+
+/// `render --progress` with a piped stderr reports the render's frames as
+/// `progress ` lines, one per
+/// change (#1778).
+#[test]
+fn render_progress_reports_frames_on_a_piped_stderr() {
+ let stderr = render_demo_stderr("progress.gif", &["--progress"]);
+ let mut last_done = None;
+ let mut totals = vec![];
+ for line in stderr.lines().filter(|l| l.starts_with("progress")) {
+ let fields: Vec<&str> = line.split(' ').collect();
+ assert_eq!(fields.len(), 5, "{line}");
+ let done: u64 = fields[1].parse().unwrap_or_else(|e| panic!("{line}: frames done: {e}"));
+ let total: u64 = fields[2].parse().unwrap_or_else(|e| panic!("{line}: frames total: {e}"));
+ let elapsed: f64 = fields[3].parse().unwrap_or_else(|e| panic!("{line}: seconds elapsed: {e}"));
+ assert!(fields[4] == "-" || fields[4].parse::().is_ok_and(|left| left >= 0.0), "{line}: seconds left");
+ assert!(done <= total && total > 0 && elapsed >= 0.0, "{line}");
+ assert!(last_done.is_none_or(|last| done > last), "one line per change, and frames only go up: {stderr}");
+ last_done = Some(done);
+ totals.push(total);
+ }
+ assert!(!totals.is_empty(), "no progress line on a piped stderr: {stderr}");
+ assert!(totals.iter().all(|&t| t == totals[0]), "one render, one total: {stderr}");
+}
+
+/// Without `--progress`, the same render writes no progress lines to a piped stderr (#1778).
+#[test]
+fn render_without_progress_writes_no_progress_lines() {
+ let stderr = render_demo_stderr("no-progress.gif", &[]);
+ assert!(!stderr.lines().any(|l| l.starts_with("progress")), "{stderr}");
+}
diff --git a/apps/effectcraft-cli/tests/it/main.rs b/apps/effectcraft-cli/tests/it/main.rs
new file mode 100644
index 000000000..17149f545
--- /dev/null
+++ b/apps/effectcraft-cli/tests/it/main.rs
@@ -0,0 +1,4 @@
+//! The crate's integration tests, one binary (each module is a former `tests/.rs`).
+
+mod cli;
+mod qa_template;
diff --git a/apps/effectcraft-cli/tests/qa_template.rs b/apps/effectcraft-cli/tests/it/qa_template.rs
similarity index 85%
rename from apps/effectcraft-cli/tests/qa_template.rs
rename to apps/effectcraft-cli/tests/it/qa_template.rs
index 2765b163e..0618c0d63 100644
--- a/apps/effectcraft-cli/tests/qa_template.rs
+++ b/apps/effectcraft-cli/tests/it/qa_template.rs
@@ -689,3 +689,123 @@ fn template_frame_output_cannot_alias_its_values_through_a_hard_link() {
assert_eq!(reply["error"], "--out hard-linked-values.png would overwrite --values values.json", "{reply}");
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// A template whose `Clip` control is a Media Replacement showing `source.png` (blue), with
+/// `other.png` (red) beside it to replace it with, exported as `lt.ectemplate` in a fresh `dir`.
+fn media_template(case: &str) -> PathBuf {
+ let temp_root = std::env::temp_dir().canonicalize().unwrap();
+ let dir = temp_root.join(format!("ec-qa-template-{case}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("build.jsx"), BUILD).unwrap();
+ ok(&dir, &["script", "build.jsx", "--save-as", "t.ecproj"]);
+ image::RgbaImage::from_pixel(2, 2, image::Rgba([30, 60, 90, 255])).save(dir.join("source.png")).unwrap();
+ image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 20, 40, 255])).save(dir.join("other.png")).unwrap();
+ let imported = ok(&dir, &["exec", "file.import", r#"{"paths":["source.png"]}"#, "t.ecproj", "--save"]);
+ let item = imported["result"]["items"][0].as_u64().unwrap();
+ let params = serde_json::json!({"comp": "Lower Third", "item": item, "position": [8, 8], "time": 0}).to_string();
+ let added = ok(&dir, &["exec", "layer.addItem", ¶ms, "t.ecproj", "--save"]);
+ let layer = added["result"]["layer"].as_u64().unwrap();
+ let params = serde_json::json!({"comp": "Lower Third", "layer": layer, "name": "Clip"}).to_string();
+ ok(&dir, &["exec", "essential.addMedia", ¶ms, "t.ecproj", "--save"]);
+ ok(&dir, &["exec", "essential.exportTemplate", r#"{"comp":"Lower Third","path":"lt.ectemplate"}"#, "t.ecproj"]);
+ dir
+}
+
+/// Renders the template's frame with `values` and checks that the control shows `other.png`.
+fn assert_renders_the_replacement(dir: &PathBuf, values: &str) {
+ std::fs::write(dir.join("values.json"), values).unwrap();
+ ok(dir, &["render-frame", "--template", "lt.ectemplate", "--values", "values.json", "--time", "1", "--out", "out.png"]);
+ let px = image::open(dir.join("out.png")).unwrap().to_rgba8().get_pixel(8, 8).0;
+ assert!(
+ (px[0] as i32 - 200).abs() <= 2 && (px[1] as i32 - 20).abs() <= 2 && (px[2] as i32 - 40).abs() <= 2,
+ "{values}: replacement media rendered: {px:?}"
+ );
+}
+
+#[test]
+fn template_values_fill_a_media_replacement_control_with_a_file_path() {
+ let dir = media_template("media-control");
+ assert_renders_the_replacement(&dir, r#"{"Clip":"other.png"}"#);
+
+ // A control that is not given a path is rejected with a clear message.
+ std::fs::write(dir.join("bad.json"), r#"{"Clip":5}"#).unwrap();
+ let (code, reply) = cli(&dir, &["render-frame", "--template", "lt.ectemplate", "--values", "bad.json", "--time", "1", "--out", "bad.png"]);
+ assert_eq!(code, 1, "{reply}");
+ assert!(reply["error"].as_str().unwrap().contains("media control"), "{reply}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// The object forms `{"path"|"file"|"media": …}` take a file path too, and the control is found
+/// by name the way `essential.set` finds it: exactly, then ignoring case (#1787).
+#[test]
+fn template_media_control_takes_a_path_object_and_a_name_in_any_case() {
+ let dir = media_template("media-forms");
+ for values in [
+ r#"{"Clip":{"path":"other.png"}}"#,
+ r#"{"Clip":{"file":"other.png"}}"#,
+ r#"{"Clip":{"media":"other.png"}}"#,
+ r#"{"clip":"other.png"}"#,
+ r#"{"CLIP":{"path":"other.png"}}"#,
+ ] {
+ let _ = std::fs::remove_file(dir.join("out.png"));
+ assert_renders_the_replacement(&dir, values);
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// A media path that cannot be imported fails the render with an error naming the control and
+/// the path, and writes no frame (#1787).
+#[test]
+fn template_media_control_reports_a_path_that_cannot_be_imported() {
+ let dir = media_template("media-missing");
+ std::fs::write(dir.join("missing.json"), r#"{"Clip":"missing.png"}"#).unwrap();
+ let (code, reply) = cli(&dir, &["render-frame", "--template", "lt.ectemplate", "--values", "missing.json", "--time", "1", "--out", "missing-out.png"]);
+ assert_eq!(code, 1, "{reply}");
+ let error = reply["error"].as_str().unwrap();
+ assert!(error.contains("control `Clip`: cannot import missing.png"), "{reply}");
+ assert!(!dir.join("missing-out.png").exists(), "{reply}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// Renders with `--template` name their outputs after the template's composition (#1937), not
+/// the numbered name a duplicate would get. The name ends in a number and differs from the
+/// archive's file name; an expression that looks the composition up by that name still finds it.
+#[test]
+fn template_render_outputs_keep_the_template_composition_name() {
+ let dir = std::env::temp_dir().join(format!("ec-qa-template-comp-name-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let build = BUILD.replace(r#"addComp("Lower Third""#, r#"addComp("Title Card 2""#).replace(
+ "var fill =",
+ "bar.property(\"ADBE Transform Group\").property(\"ADBE Position\").expression = '[comp(\"Title Card 2\").numLayers * 80, 65]';\nvar fill =",
+ );
+ std::fs::write(dir.join("build.jsx"), build).unwrap();
+ let built = ok(&dir, &["script", "build.jsx", "--save-as", "t.ecproj"]);
+ assert_eq!(built["output"], "controls: 3", "{built}");
+ ok(&dir, &["exec", "essential.exportTemplate", r#"{"comp":"Title Card 2","path":"card.ectemplate"}"#, "t.ecproj"]);
+ let template_before = std::fs::read(dir.join("card.ectemplate")).unwrap();
+ std::fs::write(dir.join("values.json"), r#"{"Title":"John Smith"}"#).unwrap();
+
+ for (case, values) in [("defaults", None), ("values", Some("values.json"))] {
+ let out = dir.join(case).join("[compName]_[#####].png");
+ let mut args =
+ vec!["render", "--template", "card.ectemplate", "--out", out.to_str().unwrap(), "--format", "png", "--start", "1", "--end", "1.0833333333333333"];
+ if let Some(values) = values {
+ args.extend(["--values", values]);
+ }
+ let rendered = ok(&dir, &args);
+ let rendered = rendered["rendered"].as_array().unwrap();
+ assert_eq!(rendered.len(), 1, "{case}: {rendered:?}");
+ assert_eq!(rendered[0]["comp"], "Title Card 2", "{case}: {rendered:?}");
+ let frames: Vec<_> = std::fs::read_dir(dir.join(case)).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
+ assert_eq!(frames.len(), 1, "{case}: {frames:?}");
+ assert!(frames[0].starts_with("Title Card 2_") && frames[0].ends_with(".png"), "{case}: {frames:?}");
+ // The template's own two layers place the bar; the one-layer wrapper would move it left.
+ let frame = image::open(dir.join(case).join(&frames[0])).unwrap().to_rgba8();
+ let bar = frame.get_pixel(300, 75).0;
+ assert!(bar[0] > 240 && bar[1] < 15, "{case}: comp(\"Title Card 2\") is the template's composition: {bar:?}");
+ }
+ assert_eq!(std::fs::read(dir.join("card.ectemplate")).unwrap(), template_before);
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/apps/effectcraft-web/Cargo.toml b/apps/effectcraft-web/Cargo.toml
index 6c30f9a56..28ea2f369 100644
--- a/apps/effectcraft-web/Cargo.toml
+++ b/apps/effectcraft-web/Cargo.toml
@@ -50,6 +50,7 @@ web-sys = { version = "0.3", features = [
"HtmlElement",
"HtmlInputElement",
"Location",
+ "Navigator",
"Url",
"UrlSearchParams",
"Window",
diff --git a/apps/effectcraft-web/js/host.js b/apps/effectcraft-web/js/host.js
index 3db6ad35c..12cb90bfa 100644
--- a/apps/effectcraft-web/js/host.js
+++ b/apps/effectcraft-web/js/host.js
@@ -57,6 +57,26 @@ function req(r) {
return new Promise((res, rej) => { r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); });
}
+// Run `op` on `store` in a readwrite transaction of its own; resolves once the transaction has
+// committed. A request's success doesn't mean the write is stored: the transaction can still
+// abort afterwards (quota at commit, the browser closing), rolling it back, and a write
+// reported as saved then is never retried (#1242). A failed request aborts the transaction
+// with its error; an explicit abort leaves no error, hence the AbortError.
+function write(db, store, op) {
+ return new Promise((res, rej) => {
+ let tx = null;
+ try {
+ tx = db.transaction(store, "readwrite");
+ tx.oncomplete = () => res();
+ tx.onabort = () => rej(tx.error ?? new DOMException("the storage transaction was aborted", "AbortError"));
+ op(tx.objectStore(store));
+ } catch (e) {
+ try { tx?.abort(); } catch {}
+ rej(e);
+ }
+ });
+}
+
async function idb() {
if (!self.indexedDB) throw new Error("no IndexedDB");
const open = indexedDB.open(DB, 1);
@@ -70,10 +90,10 @@ async function idb() {
return all.map((r) => ({ key: r.key, data: new Uint8Array(r.data), modified: r.modified }));
},
async put(key, data, modified) {
- await req(tx("readwrite").put({ key, data: data.slice().buffer, modified }));
+ await write(db, STORE, (s) => s.put({ key, data: data.slice().buffer, modified }));
},
async del(key) {
- await req(tx("readwrite").delete(key));
+ await write(db, STORE, (s) => s.delete(key));
},
};
}
@@ -315,7 +335,15 @@ function spawn(base) {
/// path, bytes)` receives "reply" (json), "file" (path, bytes: a rendered file to download),
/// "store" (path, bytes: a file to keep in browser storage) and "error" (json = message).
export function workerRun(id, json, files, base, onMessage) {
- const w = idle.pop() ?? spawn(base);
+ let w;
+ try {
+ w = idle.pop() ?? spawn(base);
+ } catch (e) {
+ // `new Worker` throws at once when the page's origin is opaque (a sandboxed iframe): the job
+ // fails like one whose worker didn't start.
+ setTimeout(() => onMessage("error", String((e && e.message) || e), null, null));
+ return;
+ }
running.set(id, w);
w.ready.then(() => {
w.worker.onmessage = (e) => {
@@ -380,7 +408,17 @@ const frameWorkers = [];
/// GPU effects on it.
export function frameWorkerStart(base, onMessage, gpu) {
const index = frameWorkers.length;
- const worker = new Worker(new URL("worker.js", base), { type: "module", name: `effectcraft-frames-${index}` });
+ let worker;
+ try {
+ worker = new Worker(new URL("worker.js", base), { type: "module", name: `effectcraft-frames-${index}` });
+ } catch (e) {
+ // The constructor throws at once when the page's origin is opaque (a sandboxed iframe). The
+ // slot stays, and the failure is reported like a worker that died, after the caller has
+ // recorded the index: frames then render on the page's thread (as with `?noworkers`).
+ frameWorkers.push(null);
+ setTimeout(() => onMessage(index, undefined, undefined, String((e && e.message) || e || "frame worker failed")));
+ return index;
+ }
worker.onmessage = (e) => {
const m = e.data;
if (m && m.type === "frameReply") onMessage(index, m.json, m.bytes ? new Uint8Array(m.bytes) : null, undefined);
@@ -456,8 +494,12 @@ export async function cacheRead(name) {
/// resolves with its size.
export async function cacheWrite(fullName, bytes) {
const [dir, name] = await entryDir(fullName);
- const canMove = typeof FileSystemHandle !== "undefined" && "move" in FileSystemHandle.prototype;
- const tmp = canMove ? `${name}.tmp.${Math.random().toString(36).slice(2)}` : name;
+ const canMove =
+ typeof FileSystemHandle !== "undefined" &&
+ "move" in FileSystemHandle.prototype &&
+ typeof crypto !== "undefined" &&
+ typeof crypto.randomUUID === "function";
+ const tmp = canMove ? `${name}.tmp.${crypto.randomUUID()}` : name;
const fh = await dir.getFileHandle(tmp, { create: true });
if (fh.createSyncAccessHandle) {
const h = await fh.createSyncAccessHandle();
@@ -550,7 +592,7 @@ async function openFolder(handle, remember) {
if (remember) {
try {
const db = await handlesDb();
- await req(db.transaction("folders", "readwrite").objectStore("folders").put({ name, handle }));
+ await write(db, "folders", (s) => s.put({ name, handle }));
} catch (e) { console.info("media browser: cannot remember the folder", e); }
}
return { name, entries };
@@ -602,7 +644,7 @@ export async function browseForget(name) {
folders.delete(name);
try {
const db = await handlesDb();
- await req(db.transaction("folders", "readwrite").objectStore("folders").delete(name));
+ await write(db, "folders", (s) => s.delete(name));
} catch {}
}
diff --git a/apps/effectcraft-web/src/app.rs b/apps/effectcraft-web/src/app.rs
index 1a6952408..3f462bd2a 100644
--- a/apps/effectcraft-web/src/app.rs
+++ b/apps/effectcraft-web/src/app.rs
@@ -184,6 +184,11 @@ fn install_hooks(app: &mut EffectcraftApp) {
#[wasm_bindgen]
pub async fn start(canvas_id: String) -> Result<(), JsValue> {
eframe::WebLogger::init(log::LevelFilter::Info).ok();
+ // Match System follows `?lang=` in the address, then the browser's languages; a language
+ // chosen in Settings still wins.
+ let navigator = web_sys::window().map(|w| w.navigator());
+ let browser = navigator.iter().flat_map(|n| n.languages().iter().filter_map(|v| v.as_string()).collect::>());
+ effectcraft_ui_egui::i18n::set_system_locales(query_value("lang"), browser.collect());
let doc = web_sys::window().and_then(|w| w.document()).ok_or("no document")?;
let canvas: web_sys::HtmlCanvasElement = doc.get_element_by_id(&canvas_id).ok_or("no canvas")?.dyn_into()?;
let empty = query_flag("empty");
@@ -257,6 +262,7 @@ pub async fn start(canvas_id: String) -> Result<(), JsValue> {
if n > 0 {
app.frames.set_remote(Some(Arc::new(frames::WebFrames::start(n, !query_flag("nogpuworkers")))));
}
+ app.frames.set_virtual_media(files::STORE.media_epoch(), Arc::new(|path| files::STORE.file_identity(path)));
let (tx, rx) = std::sync::mpsc::channel();
api::set_sender(tx);
app = app.with_control(rx);
diff --git a/apps/effectcraft-web/src/frames.rs b/apps/effectcraft-web/src/frames.rs
index 523fd03c8..c7f350526 100644
--- a/apps/effectcraft-web/src/frames.rs
+++ b/apps/effectcraft-web/src/frames.rs
@@ -416,6 +416,7 @@ fn post_reply(r: &FrameReply, px: Option<&[u8]>) {
fn new_server() -> FrameServer {
let mut s = FrameServer::new(crate::worker::pool(), Some(Arc::new(effectcraft_expr::Expressions)));
s.set_layer_store(Some(Arc::new(effectcraft_engine::render::PrefetchStore::default())));
+ s.set_virtual_id(Some(Arc::new(|path| crate::files::STORE.file_identity(path))));
s
}
diff --git a/apps/effectcraft-web/src/store.rs b/apps/effectcraft-web/src/store.rs
index b3a858def..a44a2eac7 100644
--- a/apps/effectcraft-web/src/store.rs
+++ b/apps/effectcraft-web/src/store.rs
@@ -20,6 +20,7 @@
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use effectcraft_engine::config::{ConfigStore, FileOps};
@@ -45,6 +46,8 @@ pub struct Entry {
/// Which write this is: new with every write of the key, so a file replaced by another of
/// the same size still reads as changed (workers are sent it again, #218).
pub version: u64,
+ /// FNV-1a of `data`, filled the first time a disk-cache key asks for it.
+ hash: Option,
}
/// A queued write for the browser storage: `data` = `None` deletes the key.
@@ -69,13 +72,13 @@ impl Mirror {
/// An entry read from the browser's storage at startup (nothing to flush).
pub fn load(&mut self, key: &str, data: Arc<[u8]>, modified: f64) {
let version = self.next_version();
- self.entries.insert(key.to_string(), Entry { data, modified, persist: true, version });
+ self.entries.insert(key.to_string(), Entry { data, modified, persist: true, version, hash: None });
}
pub fn put(&mut self, key: &str, data: Arc<[u8]>, modified: f64, persist: bool) {
let was_persisted = self.entries.get(key).is_some_and(|e| e.persist);
let version = self.next_version();
- self.entries.insert(key.to_string(), Entry { data, modified, persist, version });
+ self.entries.insert(key.to_string(), Entry { data, modified, persist, version, hash: None });
if persist || was_persisted {
self.touch(key);
}
@@ -149,14 +152,31 @@ pub fn key_path(key: &str) -> Option<&str> {
key.strip_prefix(FILES).filter(|p| p.starts_with('/'))
}
+/// FNV-1a 64. Computed when a disk-cache key first needs the file, not on every write.
+fn content_hash(data: &[u8]) -> u64 {
+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
+ for &b in data {
+ h ^= u64::from(b);
+ h = h.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ h
+}
+
/// The persistent store: a [`Mirror`] and a hook that wakes the flusher after changes.
-#[derive(Default)]
pub struct Store {
pub mirror: Mutex,
/// Called after every change that needs flushing (the web host schedules a flush).
pub on_change: OnceLock,
/// Clock in milliseconds since the Unix epoch (tests pin it).
pub clock: OnceLock f64>,
+ /// Bumped when a virtual file is written. Preview cache lookups key on it; they do not hash.
+ media_epoch: Arc,
+}
+
+impl Default for Store {
+ fn default() -> Self {
+ Self { mirror: Mutex::default(), on_change: OnceLock::new(), clock: OnceLock::new(), media_epoch: Arc::new(AtomicU64::new(0)) }
+ }
}
impl Store {
@@ -179,12 +199,40 @@ impl Store {
/// Store a file under `path` (persisted unless `persist` is false: render outputs).
pub fn put_file(&self, path: &str, data: Arc<[u8]>, persist: bool) {
let now = self.now();
- self.lock().put(&file_key(path), data, now, persist);
+ let key = file_key(path);
+ let replaced = self.lock().get(&key).is_none_or(|e| !Arc::ptr_eq(&e.data, &data));
+ self.lock().put(&key, data, now, persist);
+ if replaced {
+ self.media_epoch.fetch_add(1, Ordering::Relaxed);
+ }
if persist {
self.changed();
}
}
+ /// The generation preview cache lookups key on. It changes when [`Self::put_file`] writes
+ /// a different blob, and it is not a content hash.
+ pub fn media_epoch(&self) -> Arc {
+ self.media_epoch.clone()
+ }
+
+ /// Size and content hash of the file under `path`. The hash is stored on the entry so a
+ /// later key does not walk the bytes again.
+ pub fn file_identity(&self, path: &str) -> Option<(u64, u64)> {
+ let key = file_key(path);
+ let mut mirror = self.lock();
+ let entry = mirror.entries.get(&key)?;
+ if let Some(hash) = entry.hash {
+ return Some((entry.data.len() as u64, hash));
+ }
+ let hash = content_hash(&entry.data);
+ let len = entry.data.len() as u64;
+ if let Some(entry) = mirror.entries.get_mut(&key) {
+ entry.hash = Some(hash);
+ }
+ Some((len, hash))
+ }
+
pub fn file(&self, path: &str) -> Option> {
self.lock().get(&file_key(path)).map(|e| e.data.clone())
}
@@ -446,6 +494,11 @@ mod tests {
assert_ne!(a, b);
assert_eq!(&data[..], b"blue");
assert_eq!(s.file_versioned("/collision.png").map(|f| f.1), Some(b), "reading doesn't change it");
+ let epoch = s.media_epoch().load(Ordering::Relaxed);
+ let id = s.file_identity("/collision.png").expect("identity");
+ assert_eq!(id, (4, content_hash(b"blue")));
+ assert_eq!(s.file_identity("/collision.png"), Some(id), "the hash is kept on the entry");
+ assert!(epoch >= 2, "each new blob bumps the generation the preview keys on");
}
/// A write that failed is flushed again with the key's latest state (#215).
diff --git a/apps/effectcraft-web/tests/storage.mjs b/apps/effectcraft-web/tests/storage.mjs
new file mode 100644
index 000000000..0855c1674
--- /dev/null
+++ b/apps/effectcraft-web/tests/storage.mjs
@@ -0,0 +1,180 @@
+// The IndexedDB storage backend of the web app (js/host.js) under Node with a fake IndexedDB, no
+// browser or Wasm build needed:
+//
+// node apps/effectcraft-web/tests/storage.mjs
+//
+// A write is acknowledged only once its transaction has committed, not when its request
+// succeeded: a transaction that aborts afterwards rolls the write back, and the write must be
+// reported as failed so the flush keeps it for a retry (#1242). Exits non-zero on failure.
+import assert from "node:assert/strict";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const tick = () => new Promise((r) => setTimeout(r, 0));
+globalThis.self = globalThis;
+
+// A small IndexedDB: requests succeed (or fail) one task after they're made, and a readwrite
+// transaction commits once its requests are done, unless it was aborted (which rolls back its
+// writes). `fault` makes the next request do something else.
+let fault = null; // "abortAfterSuccess" | "requestError" | "throw"
+const databases = new Map();
+
+class Request {
+ constructor(tx) {
+ this.transaction = tx;
+ this.result = undefined;
+ this.error = null;
+ }
+}
+
+class Store {
+ constructor(tx, rows) {
+ this.tx = tx;
+ this.rows = rows;
+ }
+ request(apply) {
+ const tx = this.tx;
+ if (tx.finished) throw new DOMException("the transaction has finished", "TransactionInactiveError");
+ const f = fault;
+ fault = null;
+ if (f === "throw") throw new DOMException("the value can't be cloned", "DataCloneError");
+ const r = new Request(tx);
+ tx.pending++;
+ setTimeout(() => {
+ tx.pending--;
+ if (tx.finished) return;
+ if (f === "requestError") {
+ r.error = new DOMException("the key already exists", "ConstraintError");
+ const e = { target: r, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; } };
+ r.onerror?.(e);
+ tx.onerror?.(e);
+ if (!e.defaultPrevented) tx.fail(r.error);
+ return;
+ }
+ r.result = apply(tx.staged);
+ r.onsuccess?.({ target: r });
+ if (f === "abortAfterSuccess") tx.abort();
+ tx.maybeCommit();
+ }, 0);
+ return r;
+ }
+ put(v) {
+ return this.request((rows) => { rows.set(v[this.keyPath], structuredClone(v)); return v[this.keyPath]; });
+ }
+ delete(k) {
+ return this.request((rows) => { rows.delete(k); });
+ }
+ get(k) {
+ return this.request((rows) => rows.get(k));
+ }
+ getAll() {
+ return this.request((rows) => [...rows.values()]);
+ }
+}
+
+class Transaction {
+ constructor(db, name) {
+ this.db = db;
+ this.name = name;
+ this.staged = new Map(db.stores.get(name));
+ this.pending = 0;
+ this.finished = false;
+ this.error = null;
+ setTimeout(() => this.maybeCommit(), 0);
+ }
+ objectStore(name) {
+ const s = new Store(this, this.staged);
+ s.keyPath = this.db.keyPaths.get(name);
+ return s;
+ }
+ maybeCommit() {
+ if (this.finished || this.pending > 0) return;
+ this.finished = true;
+ this.db.stores.set(this.name, this.staged);
+ setTimeout(() => this.oncomplete?.(), 0);
+ }
+ fail(error) {
+ this.error = error;
+ this.abort();
+ }
+ abort() {
+ if (this.finished) throw new DOMException("the transaction has finished", "InvalidStateError");
+ this.finished = true;
+ setTimeout(() => this.onabort?.(), 0);
+ }
+}
+
+class Database {
+ constructor() {
+ this.stores = new Map();
+ this.keyPaths = new Map();
+ }
+ createObjectStore(name, { keyPath }) {
+ this.stores.set(name, new Map());
+ this.keyPaths.set(name, keyPath);
+ }
+ transaction(name) {
+ if (!this.stores.has(name)) throw new DOMException(`no store ${name}`, "NotFoundError");
+ return new Transaction(this, name);
+ }
+}
+
+globalThis.indexedDB = {
+ open(name) {
+ const r = new Request(null);
+ setTimeout(() => {
+ let db = databases.get(name);
+ if (!db) {
+ db = new Database();
+ databases.set(name, db);
+ r.result = db;
+ r.onupgradeneeded?.();
+ }
+ r.result = db;
+ r.onsuccess?.({ target: r });
+ }, 0);
+ return r;
+ },
+};
+
+const host = await import(pathToFileURL(join(here, "../js/host.js")));
+assert.equal(await host.storeOpen("indexeddb"), "indexeddb");
+const stored = (key) => databases.get("effectcraft").stores.get("entries").get(key);
+const bytes = (s) => new TextEncoder().encode(s);
+const text = (row) => row && new TextDecoder().decode(new Uint8Array(row.data));
+
+// A healthy write resolves once committed, and the store has it then.
+await host.storePut("project.json", bytes("v1"), 1);
+assert.equal(text(stored("project.json")), "v1", "a resolved put is committed");
+
+// The put's request succeeds, then the transaction aborts: the put fails, the old value stays.
+fault = "abortAfterSuccess";
+await assert.rejects(host.storePut("project.json", bytes("v2"), 2), { name: "AbortError" }, "an aborted put is reported");
+assert.equal(text(stored("project.json")), "v1", "the aborted put was rolled back");
+
+// The same for a delete: it fails and the entry stays.
+fault = "abortAfterSuccess";
+await assert.rejects(host.storeDelete("project.json"), { name: "AbortError" }, "an aborted delete is reported");
+assert.equal(text(stored("project.json")), "v1", "the aborted delete was rolled back");
+
+// A failed request aborts its transaction with the request's error.
+fault = "requestError";
+await assert.rejects(host.storePut("project.json", bytes("v3"), 3), { name: "ConstraintError" });
+assert.equal(text(stored("project.json")), "v1");
+
+// A request that throws at once (a value that can't be stored) fails the write.
+fault = "throw";
+await assert.rejects(host.storePut("project.json", bytes("v4"), 4), { name: "DataCloneError" });
+assert.equal(text(stored("project.json")), "v1");
+
+// The retry after a failure commits the latest value, and a later delete removes it.
+await host.storePut("project.json", bytes("v5"), 5);
+assert.equal(text(stored("project.json")), "v5");
+await host.storeDelete("project.json");
+assert.equal(stored("project.json"), undefined, "a resolved delete is committed");
+const all = await host.storeLoadAll();
+assert.deepEqual(all, [], "nothing else was written");
+
+await tick();
+console.log("storage: ok");
diff --git a/apps/effectcraft-web/tests/workers.mjs b/apps/effectcraft-web/tests/workers.mjs
index 15a77f1d5..58901885f 100644
--- a/apps/effectcraft-web/tests/workers.mjs
+++ b/apps/effectcraft-web/tests/workers.mjs
@@ -7,6 +7,8 @@
// (#218), and not when it is unchanged.
// - A worker whose start fails fails its job and is terminated, instead of the job waiting for
// "ready" forever (#216): host.js on the worker's error, worker.js re-raising the failed start.
+// - A `new Worker` that throws (a sandboxed iframe's opaque origin, #1586) fails the job, and a
+// frame worker is reported dead, instead of the exception escaping into startup.
// Exits non-zero on failure.
import assert from "node:assert/strict";
import { copyFileSync, mkdtempSync, writeFileSync } from "node:fs";
@@ -67,6 +69,35 @@ assert.equal(failed.kind, "error");
assert.ok(workers[1].terminated, "the failed worker is terminated");
assert.equal(host.workerStats().running, 0);
+// A `new Worker` that throws (a sandboxed iframe's opaque origin): the job fails, and a frame
+// worker is reported dead, instead of the exception escaping into startup.
+failStart = false;
+const RealWorker = globalThis.Worker;
+globalThis.Worker = class {
+ constructor() {
+ throw new Error("SecurityError: cannot be accessed from origin 'null'");
+ }
+};
+// (Take the idle workers out of play first, so that a new one has to be built.)
+for (let n = host.workerStats().idle, id = 100; n > 0; n--, id++) {
+ host.workerRun(id, "{}", [], "http://localhost/", () => {});
+ host.workerCancel(id);
+}
+assert.equal(host.workerStats().idle, 0);
+const threw = await run(6, []);
+assert.equal(threw.kind, "error");
+assert.match(threw.json, /SecurityError/);
+assert.equal(host.workerStats().running, 0);
+let frameCall = null;
+const frameDone = new Promise((resolve) => {
+ frameCall = host.frameWorkerStart("http://localhost/", (index, json, bytes, error) => resolve({ index, error }), false);
+});
+const dead = await frameDone;
+assert.equal(dead.index, frameCall, "the dead worker keeps its index");
+assert.match(dead.error, /SecurityError/);
+host.frameWorkerPost(frameCall, { type: "frame" }); // no worker behind it: ignored
+globalThis.Worker = RealWorker;
+
// #216, worker side: a rejected start is re-raised where the page's `onerror` sees it.
const dir = mkdtempSync(join(tmpdir(), "ec-worker-"));
copyFileSync(join(here, "../web/worker.js"), join(dir, "worker.js"));
diff --git a/apps/effectcraft-web/web/index.html b/apps/effectcraft-web/web/index.html
index 70ab93ff5..85049007f 100644
--- a/apps/effectcraft-web/web/index.html
+++ b/apps/effectcraft-web/web/index.html
@@ -71,7 +71,13 @@
...ec.info(),
crossOriginIsolated: self.crossOriginIsolated,
webgpu: !!navigator.gpu,
- serviceWorker: !!(navigator.serviceWorker && navigator.serviceWorker.controller),
+ serviceWorker: (() => {
+ try {
+ return !!(navigator.serviceWorker && navigator.serviceWorker.controller);
+ } catch {
+ return false;
+ }
+ })(),
load: window.effectcraftLoad,
}),
// Browser storage (OPFS / IndexedDB): save without downloading, list, remove, wait for writes.
@@ -83,8 +89,14 @@
workerFrameCheck: (params) => ec.workerFrameCheck(params ?? {}).then(JSON.parse),
};
// Offline start and install (PWA): the service worker caches the app's files.
- if ("serviceWorker" in navigator && !new URLSearchParams(location.search).has("nosw")) {
- navigator.serviceWorker.register("sw.js").catch((e) => console.warn("service worker:", e));
+ if (!new URLSearchParams(location.search).has("nosw")) {
+ try {
+ if ("serviceWorker" in navigator && navigator.serviceWorker) {
+ navigator.serviceWorker.register("sw.js").catch((e) => console.warn("service worker:", e));
+ }
+ } catch (e) {
+ console.warn("service worker:", e);
+ }
}
try {
// Compile once: the page and its render workers instantiate the same module.
diff --git a/apps/effectcraft-web/web/sw.js b/apps/effectcraft-web/web/sw.js
index 8c7efc2e5..4acbeeeeb 100644
--- a/apps/effectcraft-web/web/sw.js
+++ b/apps/effectcraft-web/web/sw.js
@@ -32,13 +32,15 @@ self.addEventListener("fetch", (event) => {
if (req.method !== "GET" || url.origin !== self.location.origin) return;
event.respondWith(
(async () => {
- const cache = await caches.open(CACHE);
- // The page itself regardless of its query (?empty, ?demo…).
- const key = req.mode === "navigate" ? new URL("./", self.registration.scope).href : req;
- const hit = await cache.match(key, { ignoreSearch: req.mode === "navigate" });
- if (hit) return hit;
+ const cache = await caches.open(CACHE).catch(() => null);
+ if (cache) {
+ // The page itself regardless of its query (?empty, ?demo…).
+ const key = req.mode === "navigate" ? new URL("./", self.registration.scope).href : req;
+ const hit = await cache.match(key, { ignoreSearch: req.mode === "navigate" }).catch(() => null);
+ if (hit) return hit;
+ }
const res = await fetch(req);
- if (res.ok && res.type === "basic") cache.put(req, res.clone());
+ if (cache && res.ok && res.type === "basic") void cache.put(req, res.clone()).catch(() => {});
return res;
})(),
);
diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs
index 4a8d5332a..51117b3ec 100644
--- a/apps/effectcraft/src/main.rs
+++ b/apps/effectcraft/src/main.rs
@@ -23,8 +23,8 @@ mod control_server;
mod launch_guard;
#[cfg(target_os = "macos")]
mod native_menu;
-// Built everywhere so it stays checked; only the macOS app uses it.
-#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
+// Built everywhere so it stays checked; the macOS and Linux apps use it.
+#[cfg_attr(not(any(target_os = "macos", target_os = "linux")), allow(dead_code))]
mod sheet_dialogs;
mod window;
@@ -122,6 +122,22 @@ fn control_port(name: &str, value: Option<&str>) -> Result {
}
}
+/// The commands' file dialogs open without blocking the frame where the host's backend would:
+/// on macOS as sheets instead of nested modal loops (#511), on Linux through the desktop
+/// portal from a worker thread — a blocking portal dialog leaves the main thread waiting on its
+/// answer without pumping events, so the window stops answering the compositor and the desktop
+/// offers to force-quit it while the Open dialog is up (#1275). Windows' blocking dialog pumps
+/// its own messages, so it keeps [`effectcraft_ui_egui::Hooks::pick_files`] and friends.
+fn install_file_dialogs(app: &mut EffectcraftApp, ctx: &egui::Context) {
+ #[cfg(any(target_os = "macos", target_os = "linux"))]
+ {
+ let ctx = ctx.clone();
+ app.hooks.file_dialog_async = Some(Box::new(move |dialog, done| sheet_dialogs::show(dialog, done, ctx.clone())));
+ }
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
+ let _ = (app, ctx);
+}
+
fn main() -> eframe::Result {
// First, so the panic hook and every start-up warning are recorded. Records go to stderr
// and the session log; Help ▸ Enable Logging writes through this logger too, and warnings
@@ -301,11 +317,11 @@ fn main() -> eframe::Result {
let file = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
d.set_file_name(file).save_file().map(|p| p.to_string_lossy().to_string())
}));
+ // The commands' file dialogs don't block the frame where the platform's backend
+ // would (#511, #1275); see [`install_file_dialogs`].
+ install_file_dialogs(&mut app, &cc.egui_ctx);
#[cfg(target_os = "macos")]
{
- // The commands' file dialogs open as sheets instead of nested modal loops (#511).
- let ctx = cc.egui_ctx.clone();
- app.hooks.file_dialog_async = Some(Box::new(move |dialog, done| sheet_dialogs::show(dialog, done, ctx.clone())));
app.hooks.app_action = Some(Box::new(native_menu::app_action));
app.hooks.clipboard_text = Some(Box::new(native_menu::clipboard_text));
}
@@ -352,15 +368,22 @@ fn wgpu_options(backends: Option) -> eframe::WgpuConfigu
// Iris Pro: the device is lost and the window never opens.
// `WGPU_VALIDATION_INDIRECT_CALL=1` turns the check back on.
setup.instance_descriptor.flags = setup.instance_descriptor.flags.difference(eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
- setup.device_descriptor = std::sync::Arc::new(|adapter| eframe::wgpu::DeviceDescriptor {
- label: Some("EffectCraft device"),
- required_limits: device_limits(adapter.limits()),
- ..Default::default()
- });
+ setup.device_descriptor = std::sync::Arc::new(|adapter| device_descriptor(adapter.limits()));
}
config
}
+/// The window device's descriptor: the adapter's limits ([`device_limits`]) and `MemoryUsage`,
+/// so memory the compositor frees on the shared device goes back to the driver.
+fn device_descriptor(adapter: eframe::wgpu::Limits) -> eframe::wgpu::DeviceDescriptor<'static> {
+ eframe::wgpu::DeviceDescriptor {
+ label: Some("EffectCraft device"),
+ required_limits: device_limits(adapter),
+ memory_hints: eframe::wgpu::MemoryHints::MemoryUsage,
+ ..Default::default()
+ }
+}
+
/// The limits to request from an adapter that offers `adapter`: all of them, with textures
/// capped at 16384 px like the headless renderer's device.
fn device_limits(adapter: eframe::wgpu::Limits) -> eframe::wgpu::Limits {
@@ -523,6 +546,17 @@ mod tests {
assert_eq!(super::device_limits(big).max_texture_dimension_2d, 16384);
}
+ /// The window device asks for `MemoryUsage`: the adapter's limits, unchanged.
+ #[test]
+ fn the_window_device_favours_memory_usage() {
+ use eframe::wgpu::Limits;
+ let big = Limits { max_texture_dimension_2d: 32768, ..Limits::default() };
+ let d = super::device_descriptor(big);
+ assert!(matches!(d.memory_hints, eframe::wgpu::MemoryHints::MemoryUsage));
+ assert_eq!(d.required_limits.max_texture_dimension_2d, 16384);
+ assert_eq!(d.label, Some("EffectCraft device"));
+ }
+
/// A positional .ecprojx is a project file, not an unsupported media import (#528).
#[test]
fn launch_classifies_xml_and_json_projects_as_projects() {
@@ -597,4 +631,17 @@ mod tests {
assert_eq!(parse_env(&[], Err(not_utf8)).unwrap_err(), format!("{need}, not `9\u{fffd}`"));
}
}
+
+ /// #1275: a blocking desktop-portal dialog on Linux leaves the window not answering the
+ /// compositor while it is open, so the commands' file dialogs go through the non-blocking
+ /// host hook there (as they do on macOS, #511). Windows' dialog pumps its own messages.
+ #[test]
+ fn commands_file_dialogs_do_not_block_the_frame() {
+ let mut app = effectcraft_ui_egui::EffectcraftApp::new(effectcraft_engine::Session::default());
+ super::install_file_dialogs(&mut app, &egui::Context::default());
+ #[cfg(any(target_os = "macos", target_os = "linux"))]
+ assert!(app.hooks.file_dialog_async.is_some(), "the commands' file dialogs must not block the frame");
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
+ assert!(app.hooks.file_dialog_async.is_none(), "the blocking dialog pumps its own messages here");
+ }
}
diff --git a/apps/effectcraft/src/sheet_dialogs.rs b/apps/effectcraft/src/sheet_dialogs.rs
index 577eb0b64..7a75ef2a7 100644
--- a/apps/effectcraft/src/sheet_dialogs.rs
+++ b/apps/effectcraft/src/sheet_dialogs.rs
@@ -1,10 +1,14 @@
-//! File dialogs that don't block the frame (macOS), for `Hooks::file_dialog_async`.
+//! File dialogs that don't block the frame (macOS and Linux), for `Hooks::file_dialog_async`.
//!
//! A blocking `rfd::FileDialog` runs a nested modal event loop inside eframe's frame, that is
//! inside winit's event handler. On macOS a file dragged over the window while that loop ran
//! re-entered winit's handler, which panics across the Objective-C boundary and aborts the app
-//! (#511). `rfd::AsyncFileDialog` shows the dialog as a sheet on the window and returns at once;
-//! the answer arrives when the sheet closes, outside the frame, and the app runs the command then.
+//! (#511). On Linux the blocking dialog is worse than slow: rfd uses the XDG desktop portal, so
+//! the main thread sits waiting on the portal's answer and never pumps winit's events — the
+//! window stops answering the compositor and the desktop offers to force-quit the app while the
+//! Open dialog is up (#1275). `rfd::AsyncFileDialog` shows the dialog as a sheet on the window
+//! (macOS) or through the portal from a worker thread (Linux) and returns at once; the answer
+//! arrives when the dialog closes, outside the frame, and the app runs the command then.
use effectcraft_ui_egui::{DialogDone, FileDialog};
use rfd::{AsyncFileDialog, FileHandle};
diff --git a/contributors/people.toml b/contributors/people.toml
index 2fa1927ce..1012a37bd 100644
--- a/contributors/people.toml
+++ b/contributors/people.toml
@@ -66,7 +66,7 @@ sync_github_name = true
display_name = "Jason Brashear"
[people.nanox333]
-display_name = "nanox333"
+display_name = "nnaannoo"
[people.Nael-Nathanael]
sync_github_name = true
@@ -87,3 +87,14 @@ sync_github_name = false
real_name = "Marco Arnulfo"
display_name = "Marco Arnulfo"
sync_github_name = false
+
+[people.krinry]
+display_name = "krinry"
+sync_github_name = true
+
+[people.Silvertree2010]
+display_name = "Netter"
+sync_github_name = false
+
+[people.ki2pixel]
+display_name = "ki2pixel"
diff --git a/crates/av1enc/README.md b/crates/av1enc/README.md
index 6ced20ba1..c922c95eb 100644
--- a/crates/av1enc/README.md
+++ b/crates/av1enc/README.md
@@ -4,8 +4,8 @@ Clean-room, pure-Rust AV1 encoder for EffectCraft's MP4 / WebM export (layer L0,
no `unsafe`, builds for `wasm32-unknown-unknown`).
Output is decoded **bit-exactly** by libdav1d (`ffmpeg -c:v libdav1d`, checked in
-`tests/ffmpeg_oracle.rs` when ffmpeg is installed) and by FilmCraft's spec-derived
-`filmcraft-av1` decoder (`tests/roundtrip.rs`): every decoded frame equals the encoder's own
+`tests/it/ffmpeg_oracle.rs` when ffmpeg is installed) and by FilmCraft's spec-derived
+`filmcraft-av1` decoder (`tests/it/roundtrip.rs`): every decoded frame equals the encoder's own
reconstruction, so prediction never drifts.
## What is implemented
diff --git a/crates/av1enc/tests/bench.rs b/crates/av1enc/tests/it/bench.rs
similarity index 97%
rename from crates/av1enc/tests/bench.rs
rename to crates/av1enc/tests/it/bench.rs
index 6577f8f9f..b29817e1a 100644
--- a/crates/av1enc/tests/bench.rs
+++ b/crates/av1enc/tests/it/bench.rs
@@ -1,7 +1,7 @@
//! Speed / efficiency measurements on ffmpeg-generated test sources (ignored by default):
-//! `cargo test -p effectcraft-av1enc --test bench -- --ignored --nocapture`.
+//! `cargo test -p effectcraft-av1enc --test it bench:: -- --ignored --nocapture`.
-mod common;
+use crate::common;
use std::process::Command;
use std::time::Instant;
diff --git a/crates/av1enc/tests/common/mod.rs b/crates/av1enc/tests/it/common/mod.rs
similarity index 100%
rename from crates/av1enc/tests/common/mod.rs
rename to crates/av1enc/tests/it/common/mod.rs
diff --git a/crates/av1enc/tests/ffmpeg_oracle.rs b/crates/av1enc/tests/it/ffmpeg_oracle.rs
similarity index 99%
rename from crates/av1enc/tests/ffmpeg_oracle.rs
rename to crates/av1enc/tests/it/ffmpeg_oracle.rs
index 66f380ac2..b35cbf496 100644
--- a/crates/av1enc/tests/ffmpeg_oracle.rs
+++ b/crates/av1enc/tests/it/ffmpeg_oracle.rs
@@ -2,7 +2,7 @@
//! bit for bit. Skipped when `ffmpeg` (with libdav1d) is not installed. ffmpeg's native `av1`
//! decoder only drives hardware decoders, so it is not used.
-mod common;
+use crate::common;
use std::process::Command;
diff --git a/crates/av1enc/tests/it/main.rs b/crates/av1enc/tests/it/main.rs
new file mode 100644
index 000000000..c66bacde5
--- /dev/null
+++ b/crates/av1enc/tests/it/main.rs
@@ -0,0 +1,6 @@
+//! The crate's integration tests, one binary (each module is a former `tests/.rs`).
+
+mod bench;
+mod common;
+mod ffmpeg_oracle;
+mod roundtrip;
diff --git a/crates/av1enc/tests/roundtrip.rs b/crates/av1enc/tests/it/roundtrip.rs
similarity index 99%
rename from crates/av1enc/tests/roundtrip.rs
rename to crates/av1enc/tests/it/roundtrip.rs
index 1e777e509..282880e08 100644
--- a/crates/av1enc/tests/roundtrip.rs
+++ b/crates/av1enc/tests/it/roundtrip.rs
@@ -1,7 +1,7 @@
//! Round trips through FilmCraft's spec-derived AV1 decoder: decoded frames must equal the
//! encoder's own reconstruction bit for bit.
-mod common;
+use crate::common;
use common::*;
use effectcraft_av1enc::{EncoderConfig, RateControl};
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index 1fae0ea90..2a0dfc50e 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -39,7 +39,13 @@ impl Rgba {
/// `#rrggbb` or `#rrggbbaa`.
pub fn from_hex(s: &str) -> Option {
let s = s.trim().trim_start_matches('#');
- let p = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok();
+ let p = |i: usize| {
+ let pair = s.get(i..i + 2)?;
+ if !pair.bytes().all(|b| b.is_ascii_hexdigit()) {
+ return None;
+ }
+ u8::from_str_radix(pair, 16).ok()
+ };
match s.len() {
6 => Some(Rgba::from_u8(p(0)?, p(2)?, p(4)?)),
8 => Some(Rgba { a: p(6)? as f32 / 255.0, ..Rgba::from_u8(p(0)?, p(2)?, p(4)?) }),
@@ -93,7 +99,7 @@ pub fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
let d = max - min;
let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
let h = if max == r {
- ((g - b) / d + if g < b { 6.0 } else { 0.0 }) / 6.0
+ (((g - b) / d + if g < b { 6.0 } else { 0.0 }) / 6.0).rem_euclid(1.0)
} else if max == g {
((b - r) / d + 2.0) / 6.0
} else {
@@ -130,7 +136,7 @@ pub fn rgb_to_hsv(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
let h = if d < 1e-7 {
0.0
} else if max == r {
- ((g - b) / d).rem_euclid(6.0) / 6.0
+ (((g - b) / d).rem_euclid(6.0) / 6.0).rem_euclid(1.0)
} else if max == g {
((b - r) / d + 2.0) / 6.0
} else {
@@ -141,7 +147,11 @@ pub fn rgb_to_hsv(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
}
pub fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) {
- let h6 = h.rem_euclid(1.0) * 6.0;
+ let mut h6 = h.rem_euclid(1.0) * 6.0;
+ // In f32, a tiny negative hue wraps to exactly 1.0; treat it as 0.
+ if h6 >= 6.0 {
+ h6 = 0.0;
+ }
let i = h6.floor();
let f = h6 - i;
let p = v * (1.0 - s);
@@ -252,6 +262,28 @@ impl Label {
mod tests {
use super::*;
+ #[test]
+ fn hsv_to_rgb_tiny_negative_hue_is_red() {
+ let (r, g, b) = hsv_to_rgb(-1e-9, 1.0, 1.0);
+ assert!(r > 0.99 && g < 0.01 && b < 0.01, "{r} {g} {b}");
+ }
+
+ #[test]
+ fn hue_stays_below_one_for_tiny_blue() {
+ let (h, _, _) = rgb_to_hsv(1.0, 0.0, 1e-9);
+ assert!((0.0..1.0).contains(&h), "rgb_to_hsv hue {h} not in 0..1");
+ let (h, _, _) = rgb_to_hsl(1.0, 0.0, 1e-9);
+ assert!((0.0..1.0).contains(&h), "rgb_to_hsl hue {h} not in 0..1");
+ }
+
+ #[test]
+ fn rejects_signed_hex_pairs() {
+ assert!(Rgba::from_hex("#+1+2+3").is_none());
+ assert!(Rgba::from_hex("#1+2+3+").is_none());
+ assert!(Rgba::from_hex("#ff00+0ff").is_none());
+ assert!(Rgba::from_hex("#a1B2c3").is_some());
+ }
+
#[test]
fn srgb_roundtrip() {
for i in 0..=100 {
diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml
index c37d09949..bb26d3127 100644
--- a/crates/effects/Cargo.toml
+++ b/crates/effects/Cargo.toml
@@ -21,4 +21,5 @@ rayon = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
+chrono = { workspace = true }
diff --git a/crates/effects/src/blur2.rs b/crates/effects/src/blur2.rs
index e4f2b0348..929f41553 100644
--- a/crates/effects/src/blur2.rs
+++ b/crates/effects/src/blur2.rs
@@ -509,11 +509,24 @@ fn camera_lens_blur(ctx: &EffectCtx, mut b: Buf) -> Buf {
// ---------------------------------------------------------------------------------------------
// CC Radial Fast Blur
+/// Transparent pixels CC Radial Fast Blur adds on every side of a `w` × `h` buffer with Center
+/// at `c` (buffer pixels) and smear `s`: content `r` from Center streaks out to `r / (1 − s)`,
+/// so the farthest corner reaches `d · s / (1 − s)` past itself (at most 4096, as the other
+/// growing effects). Shared with the GPU path so both grow the same way.
+pub fn radial_fast_pad(c: (f64, f64), w: u32, h: u32, s: f64) -> u32 {
+ let (w, h) = (f64::from(w), f64::from(h));
+ let far = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)].iter().map(|&(x, y)| (x - c.0).hypot(y - c.1)).fold(0.0, f64::max);
+ ((far * s / (1.0 - s)).ceil() + 1.0).min(4096.0) as u32
+}
+
fn radial_fast_blur(ctx: &EffectCtx, mut b: Buf) -> Buf {
let s = (ctx.params.f("amount") / 100.0).clamp(0.0, 1.0) * 0.5;
if s <= 0.0 {
return b;
}
+ if !ctx.adjustment {
+ b.pad(radial_fast_pad(b.to_px(ctx.params.v2("center")), b.img.width, b.img.height, s));
+ }
let c = b.to_px(ctx.params.v2("center"));
let mode = ctx.params.e("zoom");
let src = b.img.clone();
@@ -906,6 +919,23 @@ mod tests {
assert_eq!(circle.len(), 21);
}
+ #[test]
+ fn radial_fast_blur_streaks_past_the_layer_edge() {
+ // Center left of an opaque square: the streaks run right, beyond the layer rectangle (#2095).
+ let img = Image::filled(20, 20, [1.0, 1.0, 1.0, 1.0]);
+ let out = run("ec.blur.ccradialfast", &img, &[("center", Value::Vec2([-20.0, 10.0])), ("amount", num(80.0))]);
+ assert!(out.img.width > 20 && out.img.height > 20, "{}x{}", out.img.width, out.img.height);
+ let (o, d) = (out.offset[0] as i64, out.offset[1] as i64);
+ assert!(out.img.get(30 + o, 10 + d)[3] > 0.1, "{:?}", out.img.get(30 + o, 10 + d));
+ // Its streak samples only the square: still opaque, so the content keeps its place.
+ assert!((out.img.get(19 + o, 10 + d)[3] - 1.0).abs() < 1e-5, "{:?}", out.img.get(19 + o, 10 + d));
+ // An adjustment layer is comp-sized already; its buffer is not grown.
+ let s = find("ec.blur.ccradialfast").unwrap();
+ let params = Params { values: [("center".into(), Value::Vec2([-20.0, 10.0])), ("amount".into(), num(80.0))].into_iter().collect() };
+ let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [20.0, 20.0], seed: 1, adjustment: true, env: Default::default() };
+ assert_eq!((s.render)(&ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 }).img.width, 20);
+ }
+
#[test]
fn reduce_flicker_blurs_vertically_only() {
let mut img = Image::filled(8, 8, [0.0, 0.0, 0.0, 1.0]);
diff --git a/crates/effects/src/channel.rs b/crates/effects/src/channel.rs
index b763ac21f..44e9dd89a 100644
--- a/crates/effects/src/channel.rs
+++ b/crates/effects/src/channel.rs
@@ -49,12 +49,15 @@ fn set_channels(ctx: &EffectCtx, mut b: Buf) -> Buf {
b
}
+/// Shift Channels' Take … From menu. After Effects' ten options come first, in its order, so a
+/// project or script that sets 10 ("Full Off" there) turns the channel off here too; "Half On" is
+/// an EffectCraft extra and sits last.
const SHIFT_ORDER: [Src; 11] =
- [Src::Alpha, Src::Red, Src::Green, Src::Blue, Src::Luminance, Src::Hue, Src::Lightness, Src::Saturation, Src::Full, Src::Half, Src::Off];
-const SHIFT_NAMES: [&str; 11] = ["Alpha", "Red", "Green", "Blue", "Luminance", "Hue", "Lightness", "Saturation", "Full On", "Half On", "Full Off"];
+ [Src::Alpha, Src::Red, Src::Green, Src::Blue, Src::Luminance, Src::Hue, Src::Lightness, Src::Saturation, Src::Full, Src::Off, Src::Half];
+const SHIFT_NAMES: [&str; 11] = ["Alpha", "Red", "Green", "Blue", "Luminance", "Hue", "Lightness", "Saturation", "Full On", "Full Off", "Half On"];
fn shift_channels(ctx: &EffectCtx, mut b: Buf) -> Buf {
- let s = ["takeRedFrom", "takeGreenFrom", "takeBlueFrom", "takeAlphaFrom"].map(|id| SHIFT_ORDER[(ctx.params.e(id) as usize).min(10)]);
+ let s = ["takeRedFrom", "takeGreenFrom", "takeBlueFrom", "takeAlphaFrom"].map(|id| SHIFT_ORDER[(ctx.params.e(id) as usize).min(SHIFT_ORDER.len() - 1)]);
route(&mut b, s);
b
}
@@ -548,6 +551,24 @@ mod tests {
assert!(close(out.get(7, 0), [0.25, 0.25, 0.45, 0.5]));
}
+ /// #1797: the Take … From menu keeps After Effects' order, where the tenth option (`Enum(9)`
+ /// here, 10 to a script) is Full Off, not Half On.
+ #[test]
+ fn shift_channels_menu_follows_after_effects_order() {
+ assert_eq!(SHIFT_NAMES[8..], ["Full On", "Full Off", "Half On"]);
+ // The sample's right-hand pixels are half transparent, so a straight 0.0 and 0.5 are
+ // stored as 0.0 and 0.25.
+ let off = run("ec.channel.shiftchannels", &[("takeGreenFrom", Value::Enum(9))], sample());
+ assert!(close(off.get(0, 0), [0.2, 0.0, 0.9, 1.0]), "{:?}", off.get(0, 0));
+ assert!(close(off.get(7, 0), [0.1, 0.0, 0.45, 0.5]), "{:?}", off.get(7, 0));
+ let half = run("ec.channel.shiftchannels", &[("takeGreenFrom", Value::Enum(10))], sample());
+ assert!(close(half.get(0, 0), [0.2, 0.5, 0.9, 1.0]), "{:?}", half.get(0, 0));
+ assert!(close(half.get(7, 0), [0.1, 0.25, 0.45, 0.5]), "{:?}", half.get(7, 0));
+ // A value past the last option stays on the last one instead of panicking.
+ let past = run("ec.channel.shiftchannels", &[("takeGreenFrom", Value::Enum(99))], sample());
+ assert_eq!(past.get(0, 0), half.get(0, 0));
+ }
+
#[test]
fn channel_combiner_hls_round_trip() {
let img = sample();
diff --git a/crates/effects/src/channel3d.rs b/crates/effects/src/channel3d.rs
index 7884e8084..39a1c49b1 100644
--- a/crates/effects/src/channel3d.rs
+++ b/crates/effects/src/channel3d.rs
@@ -37,16 +37,24 @@ fn index_map(b: &Buf, a: &AuxChannels) -> Vec